Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Common/ProfileEvents.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1852,6 +1852,7 @@ The server successfully detected this situation and will download merged part fr
M(ParquetPrefetcherReadRandomRead, "The total number of reads with ReadMode::RandomRead by DB::Parquet::Prefetcher", ValueType::Number) \
M(ParquetPrefetcherReadSeekAndRead, "The total number of reads with ReadMode::SeekAndRead by DB::Parquet::Prefetcher", ValueType::Number) \
M(ParquetPrefetcherReadEntireFile, "The total number of read with ReadMode::EntireFileIsInMemory by DB::Parquet::Prefetcher", ValueType::Number) \
M(ParquetPrefetchBackPressureStalls, "The number of times the parquet reader held back prefetching of a row group because the compressed bytes buffered by the prefetch stage already covered input_format_parquet_prefetch_bandwidth_hide_seconds of the measured read throughput", ValueType::Number) \
M(ParquetRowsFilterExpression, "The total number of rows that were passed through filter", ValueType::Number) \
M(ParquetColumnsFilterExpression, "The total number of columns that were passed through filter", ValueType::Number) \
M(FilterTransformPassedRows, "Number of rows that passed the filter in the query", ValueType::Number) \
Expand Down
3 changes: 3 additions & 0 deletions src/Core/FormatFactorySettings.h
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,9 @@ When reading GeoParquet files, skip whole row groups and, together with `input_f
)", 0) \
DECLARE(Bool, input_format_parquet_use_offset_index, true, R"(
Minor tweak to how pages are read from parquet file when no page filtering is used.
)", 0) \
DECLARE(Double, input_format_parquet_prefetch_bandwidth_hide_seconds, 0, R"(
Read back-pressure for the Parquet v3 reader. When greater than zero, stop prefetching more compressed data pages ahead of decoding once the compressed bytes buffered by the prefetch stage (queued or downloaded reads that have not been released after decoding yet) exceed this many seconds' worth of the measured read throughput (i.e. once the storage link is kept busy). The first row group that has to be read next is always allowed. Prevents buffering compressed data far beyond what bandwidth can consume. 0 disables the back-pressure (compressed prefetch is then bounded only by its memory budget). Must be non-negative.
)", 0) \
DECLARE(Bool, input_format_parquet_verify_checksums, true, R"(
Verify page checksums when reading parquet files.
Expand Down
1 change: 1 addition & 0 deletions src/Core/SettingsChangesHistory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory()
{
{"export_merge_tree_part_check_destination_schema_staleness_ms", 0, 5000, "New setting: how stale the latest Iceberg destination metadata version may be when each part export task checks that the destination schema and partition spec did not change since the export was scheduled."},
{"export_merge_tree_part_allow_lossy_cast", false, false, "The setting is obsolete. `EXPORT PART` and `EXPORT PARTITION` cast values the way `INSERT ... SELECT` does."},
{"input_format_parquet_prefetch_bandwidth_hide_seconds", 0., 0., "New setting: read back-pressure for the Parquet v3 reader; stop prefetching compressed data pages ahead of decoding once in-flight compressed bytes exceed this many seconds of measured throughput. 0 (default) disables it."},
});
addSettingsChanges(settings_changes_history, "26.8.35.20001.altinityantalya",
{
Expand Down
1 change: 1 addition & 0 deletions src/Formats/FormatFactory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ FormatSettings getFormatSettings(const ContextPtr & context, const Settings & se
format_settings.parquet.page_filter_push_down = settings[Setting::input_format_parquet_page_filter_push_down];
format_settings.parquet.spatial_filter_push_down = settings[Setting::input_format_parquet_spatial_filter_push_down];
format_settings.parquet.use_offset_index = settings[Setting::input_format_parquet_use_offset_index];
format_settings.parquet.prefetch_bandwidth_hide_seconds = settings[Setting::input_format_parquet_prefetch_bandwidth_hide_seconds];

format_settings.parquet.enable_json_parsing = settings[Setting::input_format_parquet_enable_json_parsing];
format_settings.parquet.memory_low_watermark = settings[Setting::input_format_parquet_memory_low_watermark];
Expand Down
1 change: 1 addition & 0 deletions src/Formats/FormatSettings.h
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,7 @@ struct FormatSettings
size_t footer_read_size = 0;
bool page_filter_push_down = true;
bool use_offset_index = true;
double prefetch_bandwidth_hide_seconds = 0;

bool enable_json_parsing = true;
bool preserve_order = false;
Expand Down
13 changes: 13 additions & 0 deletions src/Processors/Formats/Impl/Parquet/Prefetcher.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@ void Prefetcher::init(ReadBuffer * reader_, const ReadOptions & options, FormatP
parser_shared_resources = parser_shared_resources_;
determineReadModeAndFileSize(reader_, options);
range_sets.resize(1);
read_start_time = std::chrono::steady_clock::now();
}

double Prefetcher::averageThroughputBytesPerSec() const
{
double seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - read_start_time).count();
size_t bytes = total_bytes_read.load(std::memory_order_relaxed);
/// Too little read / too little time elapsed to estimate: report "unknown" so back-pressure
/// fails open (does not throttle).
if (seconds < 0.05 || bytes < (1u << 20))
return 0;
return static_cast<double>(bytes) / seconds;
}

void Prefetcher::shutdownTasks()
Expand Down Expand Up @@ -544,6 +556,7 @@ Prefetcher::Task::State Prefetcher::runTask(Task * task)
task->buf.resize(task->length);
readSync(task->buf.data(), task->length, task->offset);
}
total_bytes_read.fetch_add(task->length, std::memory_order_relaxed);
}
catch (...)
{
Expand Down
10 changes: 10 additions & 0 deletions src/Processors/Formats/Impl/Parquet/Prefetcher.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
#include <Common/PODArray.h>
#include <Processors/Formats/Impl/Parquet/ReadCommon.h>

#include <atomic>
#include <chrono>
#include <optional>
#include <span>

Expand Down Expand Up @@ -67,6 +69,10 @@ class Prefetcher

size_t getFileSize() const { return file_size; }

/// Average completed-read throughput (bytes/sec) since init, or 0 if not enough has been read to
/// estimate. Used for read back-pressure (input_format_parquet_prefetch_bandwidth_hide_seconds).
double averageThroughputBytesPerSec() const;

private:
friend class PrefetchHandle;

Expand Down Expand Up @@ -183,6 +189,10 @@ class Prefetcher
size_t min_bytes_for_seek{};
size_t bytes_per_read_task{};

/// Total bytes read by completed tasks, and when reading started, for throughput estimation.
std::atomic<size_t> total_bytes_read{0};
std::chrono::steady_clock::time_point read_start_time{};

std::shared_ptr<ShutdownHelper> shutdown = std::make_shared<ShutdownHelper>();

/// Locked when creating a Task.
Expand Down
40 changes: 40 additions & 0 deletions src/Processors/Formats/Impl/Parquet/ReadManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ namespace ProfileEvents
extern const Event ParquetDecodingTaskBatches;
extern const Event ParquetReadRowGroups;
extern const Event ParquetPrunedRowGroups;
extern const Event ParquetPrefetchBackPressureStalls;
}

namespace DB::Parquet
Expand Down Expand Up @@ -90,6 +91,11 @@ void ReadManager::init(FormatParserSharedResourcesPtr parser_shared_resources_,
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"input_format_parquet_decode_thread_fraction must be in [0, 1], got {}", decode_thread_fraction);

const double bandwidth_hide_seconds = reader.options.format.parquet.prefetch_bandwidth_hide_seconds;
if (!(bandwidth_hide_seconds >= 0))
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"input_format_parquet_prefetch_bandwidth_hide_seconds must be non-negative, got {}", bandwidth_hide_seconds);

auto set_fractions = [&](ReadStage s, double memory_fraction, double thread_fraction)
{
stages[size_t(s)].memory_target_fraction = memory_fraction;
Expand Down Expand Up @@ -615,6 +621,22 @@ void ReadManager::scheduleTasksIfNeeded(ReadStage stage_idx)
size_t memory_usage = stage.memory_usage.load(std::memory_order_relaxed);
size_t batches_in_progress = stage.batches_in_progress.load(std::memory_order_relaxed);

/// Read back-pressure: once the compressed data already buffered by this stage covers more than
/// `prefetch_bandwidth_hide_seconds` of the measured read throughput, the storage link is fed, so
/// stop prefetching further ahead - extra compressed buffering would only waste memory without
/// improving throughput. The buffered bytes are this stage's memory usage: it is charged when a
/// read is queued (not when it completes) and released only after decoding (dictionary pages: after
/// the whole row group is read), so it also covers downloaded data waiting to be decoded.
/// Fail-open: 0 (disabled), or unknown throughput, means no throttle. The privileged-task escape
/// below still applies, so this can never deadlock.
double prefetch_ahead_bytes_limit = 0; // 0 = no back-pressure
if (stage_idx == ReadStage::ColumnDataPrefetch && reader.options.format.parquet.prefetch_bandwidth_hide_seconds > 0)
{
double throughput = reader.prefetcher.averageThroughputBytesPerSec();
if (throughput > 0)
prefetch_ahead_bytes_limit = throughput * reader.options.format.parquet.prefetch_bandwidth_hide_seconds;
Comment on lines +633 to +637

ghost Dec 1, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Throttle the initial prefetch batch

For a plain scan without earlier bloom/index tasks, the first ColumnDataPrefetch scheduling pass always sees unknown throughput: readFileMetaData calls Prefetcher::readSync directly, while total_bytes_read is updated only by runTask. Since the limit is then computed once before the scheduling loop, that pass admits row groups up to the existing memory allowance—about 1.8 GiB with the default 4 GiB budget for one reader—even if reads complete while the loop runs. Files fitting in that initial allowance therefore receive no back-pressure at all, and larger files retain the full initial burst; the test hides this by reducing the watermark to 4 MiB and forcing a later scheduling pass. Add a bounded bootstrap policy or recompute the estimate while admitting the initial batch.

Useful? React with 👍 / 👎.

}

LOG_TEST(getLogger("ParquetReadManager"), "scheduleTasksIfNeeded: stage={} memory_usage={} batches_in_progress={} limits: mem_low={} mem_high={} threads={}",
magic_enum::enum_name(stage_idx), memory_usage, batches_in_progress,
limits.memory_low_watermark, limits.memory_high_watermark, limits.parsing_threads);
Expand Down Expand Up @@ -648,12 +670,30 @@ void ReadManager::scheduleTasksIfNeeded(ReadStage stage_idx)
bool can_schedule = checkTaskSchedulingLimits(
memory_usage, size_t(diff.by_stage[size_t(stage_idx)]),
batches_in_progress, tasks.size(), limits);
/// Bandwidth back-pressure: hold off further prefetch when the link is already fed.
bool held_by_back_pressure = false;
if (can_schedule && prefetch_ahead_bytes_limit > 0)
{
double compressed_in_flight = static_cast<double>(memory_usage)
+ static_cast<double>(std::max<ssize_t>(0, diff.by_stage[size_t(stage_idx)]));
if (compressed_in_flight >= prefetch_ahead_bytes_limit)
{
can_schedule = false;
held_by_back_pressure = true;
}
}
bool is_privileged = is_privileged_task(row_group_idx);
LOG_TEST(getLogger("ParquetReadManager"), "scheduleTasksIfNeeded: stage={} rg={} can_schedule={} is_privileged={}",
magic_enum::enum_name(stage_idx), row_group_idx, can_schedule, is_privileged);

if (!can_schedule && !is_privileged)
{
/// Count only the row groups the back-pressure actually held back, not the ones that the
/// privileged escape lets through anyway.
if (held_by_back_pressure)
ProfileEvents::increment(ProfileEvents::ParquetPrefetchBackPressureStalls);
break;
}

if (!stage.schedulable_row_groups.unset(row_group_idx, std::memory_order_acquire))
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
-- back-pressure disabled (default)
124999750000 10434925257862044929 500000
-- back-pressure with a tiny target: same result, no hang
124999750000 10434925257862044929 500000
-- back-pressure engages only when enabled
1
1
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#!/usr/bin/env bash
# Tags: no-fasttest

CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=../shell_config.sh
. "$CUR_DIR"/../shell_config.sh

USER_FILES_PATH=$($CLICKHOUSE_CLIENT_BINARY --query "select _path,_file from file('nonexist.txt', 'CSV', 'val1 char')" 2>&1 | grep Exception | awk '{gsub("/nonexist.txt","",$9); print $9}')
WORKING_DIR="${USER_FILES_PATH}/${CLICKHOUSE_TEST_UNIQUE_NAME}"
mkdir -p "${WORKING_DIR}"
DATA_FILE="${WORKING_DIR}/back_pressure.parquet"

# 500000 rows, 5000 rows per row group => 100 row groups, so that many row groups are waiting to be
# prefetched while a few are decoded.
${CLICKHOUSE_CLIENT} -q "
INSERT INTO FUNCTION file('${DATA_FILE}', Parquet)
SELECT number AS k, toString(cityHash64(number)) AS s
FROM numbers(500000)
SETTINGS engine_file_truncate_on_insert = 1, output_format_parquet_row_group_size = 5000,
output_format_parquet_compression_method = 'none'
"

STRUCTURE="k UInt64, s String"
# A small memory budget keeps most row groups unscheduled at first. The sleep slows the consumer down, so
# that the scheduler runs again after the read throughput estimate has become available.
COMMON="input_format_parquet_use_native_reader_v3 = 1, max_threads = 4, input_format_parquet_memory_high_watermark = 4194304"

run()
{
${CLICKHOUSE_CLIENT} --query_id="${CLICKHOUSE_TEST_UNIQUE_NAME}_$1" -q "
SELECT sum(k), sum(cityHash64(s)), count()
FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}')
WHERE sleepEachRow(0.000003) = 0
SETTINGS ${COMMON}, input_format_parquet_prefetch_bandwidth_hide_seconds = $2
"
}

echo "-- back-pressure disabled (default)"
run off 0
echo "-- back-pressure with a tiny target: same result, no hang"
run tiny 0.000001

echo "-- back-pressure engages only when enabled"
${CLICKHOUSE_CLIENT} -q "
SYSTEM FLUSH LOGS query_log;
SELECT ProfileEvents['ParquetPrefetchBackPressureStalls'] = 0
FROM system.query_log
WHERE event_date >= yesterday() AND event_time >= now() - 600
AND query_id = '${CLICKHOUSE_TEST_UNIQUE_NAME}_off' AND type = 'QueryFinish' AND current_database = currentDatabase();
SELECT ProfileEvents['ParquetPrefetchBackPressureStalls'] > 0
FROM system.query_log
WHERE event_date >= yesterday() AND event_time >= now() - 600
AND query_id = '${CLICKHOUSE_TEST_UNIQUE_NAME}_tiny' AND type = 'QueryFinish' AND current_database = currentDatabase();
"

rm -rf "${WORKING_DIR}"
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- valid values
499500 1000
499500 1000
-- negative value is rejected
input_format_parquet_prefetch_bandwidth_hide_seconds must be non-negative
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
# Tags: no-fasttest

CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=../shell_config.sh
. "$CUR_DIR"/../shell_config.sh

USER_FILES_PATH=$($CLICKHOUSE_CLIENT_BINARY --query "select _path,_file from file('nonexist.txt', 'CSV', 'val1 char')" 2>&1 | grep Exception | awk '{gsub("/nonexist.txt","",$9); print $9}')
WORKING_DIR="${USER_FILES_PATH}/${CLICKHOUSE_TEST_UNIQUE_NAME}"
mkdir -p "${WORKING_DIR}"
DATA_FILE="${WORKING_DIR}/validation.parquet"

${CLICKHOUSE_CLIENT} -q "
INSERT INTO FUNCTION file('${DATA_FILE}', Parquet)
SELECT number AS k FROM numbers(1000)
SETTINGS engine_file_truncate_on_insert = 1
"

run()
{
${CLICKHOUSE_CLIENT} -q "
SELECT sum(k), count()
FROM file('${DATA_FILE}', Parquet, 'k UInt64')
SETTINGS input_format_parquet_use_native_reader_v3 = 1, input_format_parquet_prefetch_bandwidth_hide_seconds = $1
" 2>&1 | grep -o -m1 "input_format_parquet_prefetch_bandwidth_hide_seconds must be non-negative\|[0-9]* [0-9]*"
}

echo "-- valid values"
run 0
run 0.5

echo "-- negative value is rejected"
run -1

rm -rf "${WORKING_DIR}"