diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index c9b79615610b7..54e7deaf23572 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 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 4951eda47549b..6e85ad657d6ee 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 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. 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..1330deaff6e8c 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 @@ -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; @@ -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; + } + 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,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(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; + 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)) { 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}" 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}"