From 189feba74b39eb706dd72139bef4101e7289db77 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Thu, 6 Aug 2026 13:33:32 +0300 Subject: [PATCH 1/5] Parquet v3: add read back-pressure for the compressed prefetch stage Add `input_format_parquet_prefetch_bandwidth_hide_seconds`. When it is greater than zero, the scheduler stops admitting further `ColumnDataPrefetch` tasks once the compressed bytes already in flight exceed that many seconds of the measured read throughput. Beyond that point the storage link is already fed, so extra compressed buffering only costs memory without improving throughput. The `Prefetcher` now counts the bytes of completed read tasks and exposes `averageThroughputBytesPerSec` (bytes since `init` divided by elapsed time). The estimate is reported as unknown (0) until at least 1 MiB has been read and 50 ms have elapsed, and an unknown estimate does not throttle. The `ColumnDataPrefetch` stage memory usage is the in-flight compressed bytes, so `ReadManager::scheduleTasksIfNeeded` compares it, plus the bytes already queued in the current scheduling pass, against `throughput * hide_seconds`. The existing privileged-task escape still applies, and with nothing in flight the check always passes, so the back-pressure cannot deadlock the reader. The setting defaults to 0, which keeps the previous behavior: compressed prefetch is bounded only by its memory budget. Co-authored-by: Cursor --- src/Core/FormatFactorySettings.h | 3 +++ src/Core/SettingsChangesHistory.cpp | 1 + src/Formats/FormatFactory.cpp | 1 + src/Formats/FormatSettings.h | 1 + .../Formats/Impl/Parquet/Prefetcher.cpp | 13 +++++++++++ .../Formats/Impl/Parquet/Prefetcher.h | 10 +++++++++ .../Formats/Impl/Parquet/ReadManager.cpp | 22 +++++++++++++++++++ 7 files changed, 51 insertions(+) diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 4951eda47549b..1d9729e317c54 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -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 in-flight compressed bytes exceed this many seconds' worth of the measured read throughput (i.e. once the storage link is kept busy). 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). )", 0) \ DECLARE(Bool, input_format_parquet_verify_checksums, true, R"( Verify page checksums when reading parquet files. diff --git a/src/Core/SettingsChangesHistory.cpp b/src/Core/SettingsChangesHistory.cpp index f93c54df707b1..8b7c31acdb445 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -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", { diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index c169db9af1df1..9fd549de0108e 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -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]; diff --git a/src/Formats/FormatSettings.h b/src/Formats/FormatSettings.h index 315bf7ab8cf05..f8d5aa7be19d1 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -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; diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index c673a467b7279..35a7e65950fe4 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -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(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(bytes) / seconds; } void Prefetcher::shutdownTasks() @@ -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 (...) { diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index 135492aff741b..b8aa3d0a51148 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -3,6 +3,8 @@ #include #include +#include +#include #include #include @@ -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; @@ -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 total_bytes_read{0}; + std::chrono::steady_clock::time_point read_start_time{}; + std::shared_ptr shutdown = std::make_shared(); /// Locked when creating a Task. diff --git a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp index b85c225850081..6bb2b8e1a2629 100644 --- a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp +++ b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp @@ -615,6 +615,20 @@ 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 in flight 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 compressed in-flight bytes are exactly this stage's memory usage. + /// 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; + } + 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); @@ -648,6 +662,14 @@ 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. + if (can_schedule && prefetch_ahead_bytes_limit > 0) + { + double compressed_in_flight = static_cast(memory_usage) + + static_cast(std::max(0, diff.by_stage[size_t(stage_idx)])); + if (compressed_in_flight >= prefetch_ahead_bytes_limit) + can_schedule = false; + } 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); From 92921ad1d2dee7a6cb1889b2c5375b9fa1b8920d Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Mon, 30 Nov 2026 15:26:47 +0100 Subject: [PATCH 2/5] Parquet v3: count back-pressure stalls and test the prefetch back-pressure Add the `ParquetPrefetchBackPressureStalls` profile event, incremented each time `input_format_parquet_prefetch_bandwidth_hide_seconds` holds back a prefetch task that the memory and thread limits would have allowed. It makes the back-pressure observable. Add `05818_parquet_prefetch_bandwidth_back_pressure`: a file with 100 row groups is read with the back-pressure disabled and with a tiny target. Both reads return the same result without hanging, and only the second one records stalls. A small memory watermark and a slow consumer make the scheduler run again after the throughput estimate is available. Co-authored-by: Cursor --- src/Common/ProfileEvents.cpp | 1 + .../Formats/Impl/Parquet/ReadManager.cpp | 4 ++ ...prefetch_bandwidth_back_pressure.reference | 7 +++ ...arquet_prefetch_bandwidth_back_pressure.sh | 56 +++++++++++++++++++ 4 files changed, 68 insertions(+) create mode 100644 tests/queries/0_stateless/05818_parquet_prefetch_bandwidth_back_pressure.reference create mode 100755 tests/queries/0_stateless/05818_parquet_prefetch_bandwidth_back_pressure.sh diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index c9b79615610b7..4cd48b6eed39a 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -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 declined to prefetch more compressed data because the in-flight compressed bytes 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) \ diff --git a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp index 6bb2b8e1a2629..d672042b43a8e 100644 --- a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp +++ b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp @@ -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 @@ -668,7 +669,10 @@ void ReadManager::scheduleTasksIfNeeded(ReadStage stage_idx) double compressed_in_flight = static_cast(memory_usage) + static_cast(std::max(0, diff.by_stage[size_t(stage_idx)])); if (compressed_in_flight >= prefetch_ahead_bytes_limit) + { can_schedule = false; + ProfileEvents::increment(ProfileEvents::ParquetPrefetchBackPressureStalls); + } } bool is_privileged = is_privileged_task(row_group_idx); LOG_TEST(getLogger("ParquetReadManager"), "scheduleTasksIfNeeded: stage={} rg={} can_schedule={} is_privileged={}", diff --git a/tests/queries/0_stateless/05818_parquet_prefetch_bandwidth_back_pressure.reference b/tests/queries/0_stateless/05818_parquet_prefetch_bandwidth_back_pressure.reference new file mode 100644 index 0000000000000..ada62dfe9ce5a --- /dev/null +++ b/tests/queries/0_stateless/05818_parquet_prefetch_bandwidth_back_pressure.reference @@ -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 diff --git a/tests/queries/0_stateless/05818_parquet_prefetch_bandwidth_back_pressure.sh b/tests/queries/0_stateless/05818_parquet_prefetch_bandwidth_back_pressure.sh new file mode 100755 index 0000000000000..b1f7ecb31644c --- /dev/null +++ b/tests/queries/0_stateless/05818_parquet_prefetch_bandwidth_back_pressure.sh @@ -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}" From 129d26681044fa0dd60c4f555ac85fac499fd849 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Tue, 1 Dec 2026 17:28:31 +0100 Subject: [PATCH 3/5] Parquet v3: count back-pressure stalls only when a row group is actually held back The `ParquetPrefetchBackPressureStalls` event was incremented before the privileged-task check, so it also counted row groups that the privileged escape scheduled anyway. Related: https://github.com/Altinity/ClickHouse/pull/2977 Co-authored-by: Cursor --- src/Processors/Formats/Impl/Parquet/ReadManager.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp index d672042b43a8e..b98bf864622f3 100644 --- a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp +++ b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp @@ -664,6 +664,7 @@ void ReadManager::scheduleTasksIfNeeded(ReadStage stage_idx) 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(memory_usage) @@ -671,7 +672,7 @@ void ReadManager::scheduleTasksIfNeeded(ReadStage stage_idx) if (compressed_in_flight >= prefetch_ahead_bytes_limit) { can_schedule = false; - ProfileEvents::increment(ProfileEvents::ParquetPrefetchBackPressureStalls); + held_by_back_pressure = true; } } bool is_privileged = is_privileged_task(row_group_idx); @@ -679,7 +680,13 @@ void ReadManager::scheduleTasksIfNeeded(ReadStage stage_idx) 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)) { From 1b54da3ce0d00e568a6cfa03478fb067ffedc0e7 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Tue, 1 Dec 2026 17:28:49 +0100 Subject: [PATCH 4/5] Parquet v3: describe the back-pressure measure as the bytes buffered by the prefetch stage The compared quantity is the memory usage of the `ColumnDataPrefetch` stage. It is charged when a read is queued and released after decoding, so it also covers downloaded data waiting to be decoded and the dictionary pages held until the row group is read. It is not the bytes still in flight. Related: https://github.com/Altinity/ClickHouse/pull/2977 Co-authored-by: Cursor --- src/Common/ProfileEvents.cpp | 2 +- src/Core/FormatFactorySettings.h | 3 +-- src/Processors/Formats/Impl/Parquet/ReadManager.cpp | 6 ++++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index 4cd48b6eed39a..54e7deaf23572 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -1852,7 +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 declined to prefetch more compressed data because the in-flight compressed bytes already covered input_format_parquet_prefetch_bandwidth_hide_seconds of the measured read throughput", 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) \ diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 1d9729e317c54..838d430a45aba 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -237,8 +237,7 @@ When reading GeoParquet files, skip whole row groups and, together with `input_f 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 in-flight compressed bytes exceed this many seconds' worth of the measured read throughput (i.e. once the storage link is kept busy). 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). -)", 0) \ +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).)", 0) \ DECLARE(Bool, input_format_parquet_verify_checksums, true, R"( Verify page checksums when reading parquet files. )", 0) \ diff --git a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp index b98bf864622f3..2de7e68445561 100644 --- a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp +++ b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp @@ -616,10 +616,12 @@ 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 in flight covers more than + /// 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 compressed in-flight bytes are exactly this stage's memory usage. + /// 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 From facf6704c6d6da98aa249bfb20521ba01f818ec7 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Tue, 1 Dec 2026 17:42:41 +0100 Subject: [PATCH 5/5] Parquet v3: reject a negative `input_format_parquet_prefetch_bandwidth_hide_seconds` A negative value silently disabled the back-pressure, while the sibling Parquet v3 settings `input_format_parquet_prefetch_memory_fraction` and `input_format_parquet_decode_thread_fraction` throw `BAD_ARGUMENTS` for an out-of-range value. Do the same here. Non-finite values are already rejected when the setting is parsed. Related: https://github.com/Altinity/ClickHouse/pull/2977 Co-authored-by: Cursor --- src/Core/FormatFactorySettings.h | 3 +- .../Formats/Impl/Parquet/ReadManager.cpp | 5 +++ ...andwidth_hide_seconds_validation.reference | 5 +++ ...fetch_bandwidth_hide_seconds_validation.sh | 35 +++++++++++++++++++ 4 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 tests/queries/0_stateless/05819_parquet_prefetch_bandwidth_hide_seconds_validation.reference create mode 100755 tests/queries/0_stateless/05819_parquet_prefetch_bandwidth_hide_seconds_validation.sh diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 838d430a45aba..6e85ad657d6ee 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -237,7 +237,8 @@ When reading GeoParquet files, skip whole row groups and, together with `input_f 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).)", 0) \ +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. )", 0) \ diff --git a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp index 2de7e68445561..1330deaff6e8c 100644 --- a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp +++ b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp @@ -91,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; diff --git a/tests/queries/0_stateless/05819_parquet_prefetch_bandwidth_hide_seconds_validation.reference b/tests/queries/0_stateless/05819_parquet_prefetch_bandwidth_hide_seconds_validation.reference new file mode 100644 index 0000000000000..948a207800521 --- /dev/null +++ b/tests/queries/0_stateless/05819_parquet_prefetch_bandwidth_hide_seconds_validation.reference @@ -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 diff --git a/tests/queries/0_stateless/05819_parquet_prefetch_bandwidth_hide_seconds_validation.sh b/tests/queries/0_stateless/05819_parquet_prefetch_bandwidth_hide_seconds_validation.sh new file mode 100755 index 0000000000000..96e8e7a9d147a --- /dev/null +++ b/tests/queries/0_stateless/05819_parquet_prefetch_bandwidth_hide_seconds_validation.sh @@ -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}"