From ce9c58dd63c096df1eefd24f73ca3c95ea07c833 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Mon, 30 Nov 2026 16:29:17 +0100 Subject: [PATCH 01/30] Parquet v3: align coalesced reads to a fixed byte grid Add the experimental settings `input_format_parquet_read_alignment_bytes` and `input_format_parquet_read_alignment_min_bytes`. When the first one is greater than zero, the `Prefetcher` keeps each coalesced read task inside one window of a fixed grid of that size, so no read straddles a multiple of it. With the grid set to the writer's multipart part size (10 MiB for delta-rs, 64 MiB for Spark/S3A), no read straddles two parts of a multipart-uploaded object, which is an AWS byte-range best practice. This needs no per-file layout and no object-storage identity cache. Only coalescing is limited: a single requested range larger than a window is left as is. The window is the one containing the start of the initial requested range. `input_format_parquet_read_alignment_min_bytes` (default 1 MiB) is an anti-fragmentation guard: when the aligned segment ahead of the initial range would be smaller than this, the read is allowed to straddle the boundary instead of emitting a tiny extra request. New profile events: `ParquetPrefetcherPartAlignedTasks` counts tasks whose coalescing was cut at a boundary, and `ParquetPrefetcherAlignmentSkippedSmall` counts the skips by the guard. Both settings default to the previous behavior, and the settings are read straight from `FormatSettings` in `Prefetcher::init`. Based on 8afd7bdca735 and b2df5594d07b from https://github.com/Altinity/ClickHouse/pull/2181, without the part that takes the real part offsets of an object from the object-storage identity cache. Co-authored-by: Cursor --- src/Common/ProfileEvents.cpp | 2 + src/Core/FormatFactorySettings.h | 6 ++ src/Core/SettingsChangesHistory.cpp | 2 + src/Formats/FormatFactory.cpp | 2 + src/Formats/FormatSettings.h | 2 + .../Formats/Impl/Parquet/Prefetcher.cpp | 45 +++++++++++++ .../Formats/Impl/Parquet/Prefetcher.h | 5 ++ .../05819_parquet_read_alignment.reference | 10 +++ .../05819_parquet_read_alignment.sh | 65 +++++++++++++++++++ 9 files changed, 139 insertions(+) create mode 100644 tests/queries/0_stateless/05819_parquet_read_alignment.reference create mode 100755 tests/queries/0_stateless/05819_parquet_read_alignment.sh diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index c9b79615610b..1e39c346dd2b 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -1852,6 +1852,8 @@ 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(ParquetPrefetcherPartAlignedTasks, "The number of read tasks whose coalescing was cut at a read alignment boundary (input_format_parquet_read_alignment_bytes) by DB::Parquet::Prefetcher", ValueType::Number) \ + M(ParquetPrefetcherAlignmentSkippedSmall, "The number of times DB::Parquet::Prefetcher skipped read alignment because the aligned segment would be smaller than input_format_parquet_read_alignment_min_bytes (anti-fragmentation)", 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 4951eda47549..1f9a8b02ebf6 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -235,6 +235,12 @@ 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(UInt64, input_format_parquet_read_alignment_bytes, 0, R"( +Experimental. Align coalesced Parquet read requests to a fixed byte grid of this size, so no read straddles a multiple of it. Set it to the writer's multipart part size (for example 10Mi for delta-rs, 64Mi for Spark/S3A) to keep reads within single parts of a multipart-uploaded object. 0 disables. Applies to the Parquet v3 reader. +)", 0) \ + DECLARE(UInt64, input_format_parquet_read_alignment_min_bytes, 1048576, R"( +Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a read at a boundary when the resulting aligned segment would be smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. Default 1 MiB. )", 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 f93c54df707b..0c5ebfddd1f7 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -54,6 +54,8 @@ 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_read_alignment_bytes", 0, 0, "New experimental setting: align coalesced Parquet reads to a fixed byte grid (for example the writer's multipart part size) so no read straddles a multiple of it. 0 disables."}, + {"input_format_parquet_read_alignment_min_bytes", 1048576, 1048576, "New experimental setting: anti-fragmentation guard for Parquet read alignment - do not cut a read at a boundary when the aligned segment would be smaller than this. Default 1 MiB."}, }); addSettingsChanges(settings_changes_history, "26.8.35.20001.altinityantalya", { diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index c169db9af1df..b785ddedfa94 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -231,6 +231,8 @@ 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.read_alignment_bytes = settings[Setting::input_format_parquet_read_alignment_bytes]; + format_settings.parquet.read_alignment_min_bytes = settings[Setting::input_format_parquet_read_alignment_min_bytes]; 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 315bf7ab8cf0..201b07e623c9 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -386,6 +386,8 @@ struct FormatSettings size_t footer_read_size = 0; bool page_filter_push_down = true; bool use_offset_index = true; + UInt64 read_alignment_bytes = 0; + UInt64 read_alignment_min_bytes = 1048576; 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 c673a467b727..3d88762584dd 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -8,6 +8,7 @@ #include #include +#include #include namespace DB::ErrorCodes @@ -22,6 +23,8 @@ namespace ProfileEvents extern const Event ParquetPrefetcherReadRandomRead; extern const Event ParquetPrefetcherReadSeekAndRead; extern const Event ParquetPrefetcherReadEntireFile; + extern const Event ParquetPrefetcherPartAlignedTasks; + extern const Event ParquetPrefetcherAlignmentSkippedSmall; } namespace DB::Parquet @@ -31,6 +34,8 @@ void Prefetcher::init(ReadBuffer * reader_, const ReadOptions & options, FormatP { min_bytes_for_seek = options.min_bytes_for_seek; bytes_per_read_task = options.bytes_per_read_task; + read_alignment_stride = options.format.parquet.read_alignment_bytes; + read_alignment_min_bytes = options.format.parquet.read_alignment_min_bytes; parser_shared_resources = parser_shared_resources_; determineReadModeAndFileSize(reader_, options); range_sets.resize(1); @@ -323,6 +328,31 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, size_t end_idx = range_idx + 1; size_t total_length_of_covered_ranges = end_offset - start_offset; + /// EXPERIMENTAL read alignment: keep this coalesced task within a single window [part_lo, part_hi) + /// of a fixed grid (read_alignment_stride) - the window containing the initial requested range's + /// start - so one read never straddles a multiple of the stride. With the stride set to the writer's + /// multipart part size, no read straddles two parts (an AWS best practice for multipart-uploaded + /// objects). This only limits *coalescing* across a boundary; a single requested range larger than a + /// window is left as is (it would require splitting). + size_t part_lo = 0; + size_t part_hi = std::numeric_limits::max(); + bool alignment_active = false; + if (read_alignment_stride > 0) + { + part_lo = start_offset / read_alignment_stride * read_alignment_stride; + part_hi = part_lo + read_alignment_stride; + alignment_active = true; + } + + /// Anti-fragmentation: if the aligned segment ahead of the initial range would be smaller than + /// read_alignment_min_bytes, cutting here would emit a tiny read - allow the straddle instead. + if (alignment_active && read_alignment_min_bytes > 0 && part_hi - start_offset < read_alignment_min_bytes) + { + alignment_active = false; + ProfileEvents::increment(ProfileEvents::ParquetPrefetcherAlignmentSkippedSmall); + } + bool part_boundary_constrained = false; + /// Go left. size_t initial_offset = start_offset; for (size_t idx = range_idx; idx > 0; --idx) @@ -333,6 +363,12 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, !r.request->allow_incidental_read.load(std::memory_order_relaxed)) // range wants to be coalesced break; + if (alignment_active && r.start < part_lo) // would cross below this boundary window + { + part_boundary_constrained = true; + break; + } + const auto s = r.request->state.load(std::memory_order_relaxed); if (s == RequestState::State::HasRange) { @@ -368,6 +404,12 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, !r.request->allow_incidental_read.load(std::memory_order_relaxed)) break; + if (alignment_active && r.end > part_hi) // would cross above this boundary window + { + part_boundary_constrained = true; + break; + } + const auto s = r.request->state.load(std::memory_order_relaxed); if (s == RequestState::State::HasRange) { @@ -384,6 +426,9 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, } } + if (part_boundary_constrained) + ProfileEvents::increment(ProfileEvents::ParquetPrefetcherPartAlignedTasks); + /// Create task. Task & task = tasks.emplace_back(); task.offset = start_offset; diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index 135492aff741..aa37cae3d601 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -183,6 +183,11 @@ class Prefetcher size_t min_bytes_for_seek{}; size_t bytes_per_read_task{}; + /// Fixed boundary grid (bytes) for read alignment: no coalesced read task straddles a multiple of it. + /// 0 = off. And the anti-fragmentation min aligned-segment size. Set in init(), read-only after. + size_t read_alignment_stride = 0; + size_t read_alignment_min_bytes = 0; + std::shared_ptr shutdown = std::make_shared(); /// Locked when creating a Task. diff --git a/tests/queries/0_stateless/05819_parquet_read_alignment.reference b/tests/queries/0_stateless/05819_parquet_read_alignment.reference new file mode 100644 index 000000000000..c675ead95d56 --- /dev/null +++ b/tests/queries/0_stateless/05819_parquet_read_alignment.reference @@ -0,0 +1,10 @@ +-- read alignment off (default) +19999900000 99900000 17371400341328084350 1088890 1241267 6666566667 3879894 2666646666700000 +-- aligned to a fixed grid: same result +19999900000 99900000 17371400341328084350 1088890 1241267 6666566667 3879894 2666646666700000 +-- aligned, but the aligned segments are smaller than the minimum: same result +19999900000 99900000 17371400341328084350 1088890 1241267 6666566667 3879894 2666646666700000 +-- read alignment engages only when enabled, and the minimum segment size guard skips it +aligned 1 +off 1 +small 1 diff --git a/tests/queries/0_stateless/05819_parquet_read_alignment.sh b/tests/queries/0_stateless/05819_parquet_read_alignment.sh new file mode 100755 index 000000000000..f60e11d035a7 --- /dev/null +++ b/tests/queries/0_stateless/05819_parquet_read_alignment.sh @@ -0,0 +1,65 @@ +#!/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}/alignment.parquet" + +# 200000 rows, 20000 rows per row group => 10 row groups with 8 neighbouring column chunks each, so that the +# prefetcher coalesces the chunks of a row group into shared read tasks. +${CLICKHOUSE_CLIENT} -q " + INSERT INTO FUNCTION file('${DATA_FILE}', Parquet) + SELECT + number AS k, + number % 1000 AS a, + cityHash64(number) AS b, + toString(number) AS s1, + toString(number * 7) AS s2, + number / 3 AS d, + toString(cityHash64(number)) AS e, + number * number AS f + FROM numbers(200000) + SETTINGS engine_file_truncate_on_insert = 1, output_format_parquet_row_group_size = 20000, + output_format_parquet_compression_method = 'none' +" + +STRUCTURE="k UInt64, a UInt32, b UInt64, s1 String, s2 String, d Float64, e String, f UInt64" +COMMON="input_format_parquet_use_native_reader_v3 = 1" + +run() +{ + ${CLICKHOUSE_CLIENT} --query_id="${CLICKHOUSE_TEST_UNIQUE_NAME}_$1" -q " + SELECT sum(k), sum(a), sum(b), sum(length(s1)), sum(length(s2)), sum(toUInt64(d)), sum(length(e)), sum(f) + FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') + SETTINGS ${COMMON}, $2 + " +} + +echo "-- read alignment off (default)" +run off "input_format_parquet_read_alignment_bytes = 0" +echo "-- aligned to a fixed grid: same result" +run aligned "input_format_parquet_read_alignment_bytes = 100000, input_format_parquet_read_alignment_min_bytes = 1" +echo "-- aligned, but the aligned segments are smaller than the minimum: same result" +run small "input_format_parquet_read_alignment_bytes = 100000, input_format_parquet_read_alignment_min_bytes = 1048576" + +echo "-- read alignment engages only when enabled, and the minimum segment size guard skips it" +${CLICKHOUSE_CLIENT} -q " + SYSTEM FLUSH LOGS query_log; + SELECT + substring(query_id, length('${CLICKHOUSE_TEST_UNIQUE_NAME}_') + 1) AS name, + multiIf( + name = 'off', ProfileEvents['ParquetPrefetcherPartAlignedTasks'] = 0 AND ProfileEvents['ParquetPrefetcherAlignmentSkippedSmall'] = 0, + name = 'aligned', ProfileEvents['ParquetPrefetcherPartAlignedTasks'] > 0 AND ProfileEvents['ParquetPrefetcherAlignmentSkippedSmall'] = 0, + ProfileEvents['ParquetPrefetcherPartAlignedTasks'] = 0 AND ProfileEvents['ParquetPrefetcherAlignmentSkippedSmall'] > 0) AS ok + FROM system.query_log + WHERE event_date >= yesterday() AND event_time >= now() - 600 + AND query_id LIKE '${CLICKHOUSE_TEST_UNIQUE_NAME}_%' AND type = 'QueryFinish' AND current_database = currentDatabase() + ORDER BY name +" + +rm -rf "${WORKING_DIR}" From 44e2c3d806ee9e1f8fafcfc7522ac80491a9a7a5 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Wed, 2 Dec 2026 11:16:46 +0100 Subject: [PATCH 02/30] Parquet v3 read alignment: decide cuts per adjacent pair of ranges Make the coalescing of read tasks respect the `input_format_parquet_read_alignment_bytes` grid in both scan directions: - the left scan also stops at a range that would extend the task above the upper boundary (a range with the same start offset as the initial range, or an overlapping one), not only at a range that starts below the lower boundary; - the right scan also stops when the initial range itself already crosses the boundary; - the `input_format_parquet_read_alignment_min_bytes` guard is applied per cut in both directions instead of once, from the side of the initial range only. Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 48 ++++++++++++++----- 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 3d88762584dd..f8ebe8d5fdaf 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -344,14 +344,23 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, alignment_active = true; } - /// Anti-fragmentation: if the aligned segment ahead of the initial range would be smaller than - /// read_alignment_min_bytes, cutting here would emit a tiny read - allow the straddle instead. - if (alignment_active && read_alignment_min_bytes > 0 && part_hi - start_offset < read_alignment_min_bytes) - { - alignment_active = false; - ProfileEvents::increment(ProfileEvents::ParquetPrefetcherAlignmentSkippedSmall); - } bool part_boundary_constrained = false; + bool skipped_small = false; + + /// Anti-fragmentation, applied per cut and symmetrically for both scan directions: cutting at a + /// boundary leaves the part of the task on the near side of it as a separate read, `segment` bytes + /// long. If that would be smaller than read_alignment_min_bytes, don't cut, allow the straddle + /// instead. Measuring the near-side segment (not "the side of the initial range") makes the result + /// the same whichever of two neighbouring ranges is the one that starts the task. + auto shouldCutAtBoundary = [&](size_t segment) + { + if (read_alignment_min_bytes > 0 && segment < read_alignment_min_bytes) + { + skipped_small = true; + return false; + } + return true; + }; /// Go left. size_t initial_offset = start_offset; @@ -363,10 +372,23 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, !r.request->allow_incidental_read.load(std::memory_order_relaxed)) // range wants to be coalesced break; - if (alignment_active && r.start < part_lo) // would cross below this boundary window + if (alignment_active) { - part_boundary_constrained = true; - break; + const size_t new_start = std::min(start_offset, r.start); + const size_t new_end = std::max(end_offset, r.end); + /// Including this range would make the task cross the lower boundary of the window; if we + /// cut, [r.start, part_lo) stays on the near side. + bool cut = new_start < part_lo && shouldCutAtBoundary(part_lo - new_start); + /// Or the upper one (a range that starts inside the window but ends above it, e.g. with the + /// same start offset as the initial range or overlapping it); if we cut, [new_start, part_hi) + /// stays on the near side. + if (!cut && new_end > part_hi) + cut = shouldCutAtBoundary(part_hi - new_start); + if (cut) + { + part_boundary_constrained = true; + break; + } } const auto s = r.request->state.load(std::memory_order_relaxed); @@ -404,7 +426,9 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, !r.request->allow_incidental_read.load(std::memory_order_relaxed)) break; - if (alignment_active && r.end > part_hi) // would cross above this boundary window + /// Including this range would make the task cross the upper boundary of the window (also when + /// the initial range already does). If we cut, [start_offset, part_hi) stays on the near side. + if (alignment_active && std::max(end_offset, r.end) > part_hi && shouldCutAtBoundary(part_hi - start_offset)) { part_boundary_constrained = true; break; @@ -428,6 +452,8 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, if (part_boundary_constrained) ProfileEvents::increment(ProfileEvents::ParquetPrefetcherPartAlignedTasks); + if (skipped_small) + ProfileEvents::increment(ProfileEvents::ParquetPrefetcherAlignmentSkippedSmall); /// Create task. Task & task = tasks.emplace_back(); From f63af37d200ce39ea050067cc6b9885738671270 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Wed, 2 Dec 2026 11:16:53 +0100 Subject: [PATCH 03/30] Parquet v3 read alignment: test that coalesced tasks do not straddle the grid `Prefetcher` writes a test-level log line for every read task, with its offset, length and the number of requested ranges it covers. The new test `05820_parquet_read_alignment_no_straddle` reads the lines with `send_logs_level=test` and checks that, with `input_format_parquet_read_alignment_bytes` set, no task covering more than one requested range crosses a multiple of the stride, while without it such tasks exist. Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 4 ++ ...rquet_read_alignment_no_straddle.reference | 4 ++ ...5820_parquet_read_alignment_no_straddle.sh | 72 +++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.reference create mode 100755 tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.sh diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index f8ebe8d5fdaf..78e3ac6c2d0b 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -483,6 +484,9 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, lock.unlock(); + LOG_TEST(getLogger("ParquetPrefetcher"), "Read task: offset={} length={} ranges={} alignment_bytes={}", + task.offset, task.length, actual_refcount, read_alignment_stride); + scheduleTask(&task); } diff --git a/tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.reference b/tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.reference new file mode 100644 index 000000000000..a47f036f6b1c --- /dev/null +++ b/tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.reference @@ -0,0 +1,4 @@ +-- off: coalescing happens and crosses the grid +ok +-- aligned: coalescing still happens, no coalesced task crosses the grid +ok diff --git a/tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.sh b/tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.sh new file mode 100755 index 000000000000..e53693584a85 --- /dev/null +++ b/tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# Tags: no-fasttest + +# `input_format_parquet_read_alignment_bytes` must keep every coalesced read task (a task that covers more than one +# requested range) inside one window of the fixed grid. A task made of a single requested range larger than the +# window may still cross a boundary, it is not coalescing. +# The check reads the `Read task` test-level log lines of the Parquet v3 prefetcher. + +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}/alignment.parquet" + +# 10 row groups with 8 neighbouring column chunks each, so that the prefetcher coalesces the chunks of a row group. +${CLICKHOUSE_CLIENT} -q " + INSERT INTO FUNCTION file('${DATA_FILE}', Parquet) + SELECT + number AS k, + number % 1000 AS a, + cityHash64(number) AS b, + toString(number) AS s1, + toString(number * 7) AS s2, + number / 3 AS d, + toString(cityHash64(number)) AS e, + number * number AS f + FROM numbers(200000) + SETTINGS engine_file_truncate_on_insert = 1, output_format_parquet_row_group_size = 20000, + output_format_parquet_compression_method = 'none' +" + +STRUCTURE="k UInt64, a UInt32, b UInt64, s1 String, s2 String, d Float64, e String, f UInt64" +STRIDE=262144 + +# Prints: the number of tasks that cover more than one requested range, and how many of them cross a multiple +# of ${STRIDE}. +run() +{ + ${CLICKHOUSE_CLIENT} --send_logs_level=test -q " + SELECT sum(k), sum(a), sum(b), sum(length(s1)), sum(length(s2)), sum(toUInt64(d)), sum(length(e)), sum(f) + FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') + SETTINGS input_format_parquet_use_native_reader_v3 = 1, max_threads = 4, + input_format_parquet_local_file_min_bytes_for_seek = 1048576, $1 + FORMAT Null + " 2>&1 | awk -v stride=${STRIDE} ' + /ParquetPrefetcher.*Read task: / { + match($0, /offset=[0-9]+/); offset = substr($0, RSTART + 7, RLENGTH - 7) + 0; + match($0, /length=[0-9]+/); length_ = substr($0, RSTART + 7, RLENGTH - 7) + 0; + match($0, /ranges=[0-9]+/); ranges = substr($0, RSTART + 7, RLENGTH - 7) + 0; + if (ranges > 1) + { + multi += 1; + if (int(offset / stride) != int((offset + length_ - 1) / stride)) + crossing += 1; + } + } + END { print multi + 0, crossing + 0 }' +} + +# The control: without alignment, coalesced tasks do cross the multiples of the stride, so the check below can fail. +read -r multi crossing < <(run "input_format_parquet_read_alignment_bytes = 0") +echo "-- off: coalescing happens and crosses the grid" +[ "$multi" -gt 0 ] && [ "$crossing" -gt 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing" + +read -r multi crossing < <(run "input_format_parquet_read_alignment_bytes = ${STRIDE}, input_format_parquet_read_alignment_min_bytes = 1") +echo "-- aligned: coalescing still happens, no coalesced task crosses the grid" +[ "$multi" -gt 0 ] && [ "$crossing" -eq 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing" + +rm -rf "${WORKING_DIR}" From 6620e5dfcf16e133fd00cc288da8c910c439f1ae Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Wed, 2 Dec 2026 11:20:15 +0100 Subject: [PATCH 04/30] Parquet v3 read alignment: check the boundary only for ranges that would be included The alignment check ran before the state check of the neighbouring range, so a cancelled range or a range that already has a task counted as a cut: it incremented `ParquetPrefetcherPartAlignedTasks` and `ParquetPrefetcherAlignmentSkippedSmall` and stopped the scan past a cancelled range. Do the check only for a range in the `HasRange` state, which would actually be included in the task. The test `05819_parquet_read_alignment` relied on that overcounting: its coalescing was off with the default local-file seek threshold, and the cuts it saw came from ranges that already had tasks. Raise `input_format_parquet_local_file_min_bytes_for_seek` there so that the chunks are really coalesced. Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 54 ++++++++++--------- .../05819_parquet_read_alignment.sh | 3 +- 2 files changed, 30 insertions(+), 27 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 78e3ac6c2d0b..3c3b3345d124 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -373,28 +373,30 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, !r.request->allow_incidental_read.load(std::memory_order_relaxed)) // range wants to be coalesced break; - if (alignment_active) + const auto s = r.request->state.load(std::memory_order_relaxed); + if (s == RequestState::State::HasRange) { - const size_t new_start = std::min(start_offset, r.start); - const size_t new_end = std::max(end_offset, r.end); - /// Including this range would make the task cross the lower boundary of the window; if we - /// cut, [r.start, part_lo) stays on the near side. - bool cut = new_start < part_lo && shouldCutAtBoundary(part_lo - new_start); - /// Or the upper one (a range that starts inside the window but ends above it, e.g. with the - /// same start offset as the initial range or overlapping it); if we cut, [new_start, part_hi) - /// stays on the near side. - if (!cut && new_end > part_hi) - cut = shouldCutAtBoundary(part_hi - new_start); - if (cut) + /// The alignment is checked only for a range that would actually be included: a cancelled + /// range, or one that already has a task, must not stop the scan or count as a cut. + if (alignment_active) { - part_boundary_constrained = true; - break; + const size_t new_start = std::min(start_offset, r.start); + const size_t new_end = std::max(end_offset, r.end); + /// Including this range would make the task cross the lower boundary of the window; if we + /// cut, [r.start, part_lo) stays on the near side. + bool cut = new_start < part_lo && shouldCutAtBoundary(part_lo - new_start); + /// Or the upper one (a range that starts inside the window but ends above it, e.g. with the + /// same start offset as the initial range or overlapping it); if we cut, [new_start, part_hi) + /// stays on the near side. + if (!cut && new_end > part_hi) + cut = shouldCutAtBoundary(part_hi - new_start); + if (cut) + { + part_boundary_constrained = true; + break; + } } - } - const auto s = r.request->state.load(std::memory_order_relaxed); - if (s == RequestState::State::HasRange) - { /// Include this range in the task. start_idx = idx - 1; total_length_of_covered_ranges += r.length(); @@ -427,17 +429,17 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, !r.request->allow_incidental_read.load(std::memory_order_relaxed)) break; - /// Including this range would make the task cross the upper boundary of the window (also when - /// the initial range already does). If we cut, [start_offset, part_hi) stays on the near side. - if (alignment_active && std::max(end_offset, r.end) > part_hi && shouldCutAtBoundary(part_hi - start_offset)) - { - part_boundary_constrained = true; - break; - } - const auto s = r.request->state.load(std::memory_order_relaxed); if (s == RequestState::State::HasRange) { + /// Including this range would make the task cross the upper boundary of the window (also when + /// the initial range already does). If we cut, [start_offset, part_hi) stays on the near side. + if (alignment_active && std::max(end_offset, r.end) > part_hi && shouldCutAtBoundary(part_hi - start_offset)) + { + part_boundary_constrained = true; + break; + } + end_idx = idx + 1; total_length_of_covered_ranges += r.length(); end_offset = std::max(end_offset, r.end); diff --git a/tests/queries/0_stateless/05819_parquet_read_alignment.sh b/tests/queries/0_stateless/05819_parquet_read_alignment.sh index f60e11d035a7..2622907523c9 100755 --- a/tests/queries/0_stateless/05819_parquet_read_alignment.sh +++ b/tests/queries/0_stateless/05819_parquet_read_alignment.sh @@ -29,7 +29,8 @@ ${CLICKHOUSE_CLIENT} -q " " STRUCTURE="k UInt64, a UInt32, b UInt64, s1 String, s2 String, d Float64, e String, f UInt64" -COMMON="input_format_parquet_use_native_reader_v3 = 1" +# The large local-file seek threshold lets the prefetcher coalesce neighbouring column chunks. +COMMON="input_format_parquet_use_native_reader_v3 = 1, input_format_parquet_local_file_min_bytes_for_seek = 1048576" run() { From 08498eb4e7cbcbb986faebced0257aebfd9186c6 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Wed, 2 Dec 2026 11:22:16 +0100 Subject: [PATCH 05/30] Parquet v3 read alignment: make the cut decision independent of the range that starts the task The anti-fragmentation guard measured the segment before a boundary from the current start of the task. With three or more neighbouring ranges around a boundary, the layout of the tasks depended on which range started the task: for `X`, `Y` and `C`, where `C` crosses the boundary, `{Y, C}` plus `{X}` was produced when `C` started, and `{X, Y}` plus `{C}` otherwise. Decide the cut for each pair of neighbouring ranges that would be joined: the pair is cut when the first multiple of the stride after the start of the earlier range lies strictly inside the joint span of the pair, and the guard compares the distance from that start to the boundary with `input_format_parquet_read_alignment_min_bytes`. The decision depends only on the pair, so it is the same for both scan directions and for every starting range. This also replaces the window of the initial range. Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 83 ++++++++----------- 1 file changed, 35 insertions(+), 48 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 3c3b3345d124..ff4f413256f6 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -9,7 +9,6 @@ #include #include -#include #include namespace DB::ErrorCodes @@ -329,40 +328,46 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, size_t end_idx = range_idx + 1; size_t total_length_of_covered_ranges = end_offset - start_offset; - /// EXPERIMENTAL read alignment: keep this coalesced task within a single window [part_lo, part_hi) - /// of a fixed grid (read_alignment_stride) - the window containing the initial requested range's - /// start - so one read never straddles a multiple of the stride. With the stride set to the writer's - /// multipart part size, no read straddles two parts (an AWS best practice for multipart-uploaded - /// objects). This only limits *coalescing* across a boundary; a single requested range larger than a - /// window is left as is (it would require splitting). - size_t part_lo = 0; - size_t part_hi = std::numeric_limits::max(); - bool alignment_active = false; - if (read_alignment_stride > 0) - { - part_lo = start_offset / read_alignment_stride * read_alignment_stride; - part_hi = part_lo + read_alignment_stride; - alignment_active = true; - } - + /// EXPERIMENTAL read alignment: when coalescing, don't make a task cross a multiple of a fixed grid + /// (read_alignment_stride). With the stride set to the writer's multipart part size, no read straddles + /// two parts (an AWS best practice for multipart-uploaded objects). This only limits *coalescing* + /// across a boundary; a single requested range that crosses a boundary is left as is (it would require + /// splitting). + /// + /// The decision is made for each pair of neighbouring ranges (in the order of their start offsets) + /// that would be joined in the task, and depends only on the pair, so the resulting tasks don't depend + /// on which range of a chain starts the task. The pair is cut when the first multiple of the stride + /// after the start of the earlier range lies strictly inside the pair's joint span. + /// + /// Anti-fragmentation: cutting leaves the earlier range's part before the boundary as a separate + /// read. If that part is smaller than read_alignment_min_bytes, don't cut, allow the straddle instead. + const bool alignment_active = read_alignment_stride > 0; bool part_boundary_constrained = false; bool skipped_small = false; - /// Anti-fragmentation, applied per cut and symmetrically for both scan directions: cutting at a - /// boundary leaves the part of the task on the near side of it as a separate read, `segment` bytes - /// long. If that would be smaller than read_alignment_min_bytes, don't cut, allow the straddle - /// instead. Measuring the near-side segment (not "the side of the initial range") makes the result - /// the same whichever of two neighbouring ranges is the one that starts the task. - auto shouldCutAtBoundary = [&](size_t segment) + auto shouldCutBetween = [&](size_t earlier_start, size_t joint_end) { - if (read_alignment_min_bytes > 0 && segment < read_alignment_min_bytes) + if (!alignment_active) + return false; + const size_t boundary = (earlier_start / read_alignment_stride + 1) * read_alignment_stride; + if (boundary >= joint_end) + return false; + if (read_alignment_min_bytes > 0 && boundary - earlier_start < read_alignment_min_bytes) { skipped_small = true; return false; } + part_boundary_constrained = true; return true; }; + /// The ranges at the current edges of the task, for shouldCutBetween. + const size_t initial_start = start_offset; + const size_t initial_end = end_offset; + size_t left_edge_end = initial_end; + size_t right_edge_start = initial_start; + size_t right_edge_end = initial_end; + /// Go left. size_t initial_offset = start_offset; for (size_t idx = range_idx; idx > 0; --idx) @@ -378,24 +383,9 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, { /// The alignment is checked only for a range that would actually be included: a cancelled /// range, or one that already has a task, must not stop the scan or count as a cut. - if (alignment_active) - { - const size_t new_start = std::min(start_offset, r.start); - const size_t new_end = std::max(end_offset, r.end); - /// Including this range would make the task cross the lower boundary of the window; if we - /// cut, [r.start, part_lo) stays on the near side. - bool cut = new_start < part_lo && shouldCutAtBoundary(part_lo - new_start); - /// Or the upper one (a range that starts inside the window but ends above it, e.g. with the - /// same start offset as the initial range or overlapping it); if we cut, [new_start, part_hi) - /// stays on the near side. - if (!cut && new_end > part_hi) - cut = shouldCutAtBoundary(part_hi - new_start); - if (cut) - { - part_boundary_constrained = true; - break; - } - } + if (shouldCutBetween(r.start, std::max(r.end, left_edge_end))) + break; + left_edge_end = r.end; /// Include this range in the task. start_idx = idx - 1; @@ -432,13 +422,10 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, const auto s = r.request->state.load(std::memory_order_relaxed); if (s == RequestState::State::HasRange) { - /// Including this range would make the task cross the upper boundary of the window (also when - /// the initial range already does). If we cut, [start_offset, part_hi) stays on the near side. - if (alignment_active && std::max(end_offset, r.end) > part_hi && shouldCutAtBoundary(part_hi - start_offset)) - { - part_boundary_constrained = true; + if (shouldCutBetween(right_edge_start, std::max(right_edge_end, r.end))) break; - } + right_edge_start = r.start; + right_edge_end = r.end; end_idx = idx + 1; total_length_of_covered_ranges += r.length(); From 246d75125561bf63dfe5e90452bd8f96006dc8da Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Wed, 2 Dec 2026 11:30:10 +0100 Subject: [PATCH 06/30] Parquet v3 read alignment: describe the minimum segment guard accurately The descriptions of `input_format_parquet_read_alignment_min_bytes` and of the profile event `ParquetPrefetcherAlignmentSkippedSmall` still talked about "the aligned segment ahead of the initial range". The guard compares the distance from the start of the range before a cut to the boundary with the minimum, and the event counts the tasks in which at least one cut was skipped. Co-authored-by: Cursor --- src/Common/ProfileEvents.cpp | 2 +- src/Core/FormatFactorySettings.h | 2 +- src/Core/SettingsChangesHistory.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index 1e39c346dd2b..8c4325afe3c7 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -1853,7 +1853,7 @@ The server successfully detected this situation and will download merged part fr 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(ParquetPrefetcherPartAlignedTasks, "The number of read tasks whose coalescing was cut at a read alignment boundary (input_format_parquet_read_alignment_bytes) by DB::Parquet::Prefetcher", ValueType::Number) \ - M(ParquetPrefetcherAlignmentSkippedSmall, "The number of times DB::Parquet::Prefetcher skipped read alignment because the aligned segment would be smaller than input_format_parquet_read_alignment_min_bytes (anti-fragmentation)", ValueType::Number) \ + M(ParquetPrefetcherAlignmentSkippedSmall, "The number of read tasks in which DB::Parquet::Prefetcher did not cut at a read alignment boundary because the part of the read before it would be smaller than input_format_parquet_read_alignment_min_bytes (anti-fragmentation)", 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 1f9a8b02ebf6..b2ff34a06363 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -240,7 +240,7 @@ Minor tweak to how pages are read from parquet file when no page filtering is us Experimental. Align coalesced Parquet read requests to a fixed byte grid of this size, so no read straddles a multiple of it. Set it to the writer's multipart part size (for example 10Mi for delta-rs, 64Mi for Spark/S3A) to keep reads within single parts of a multipart-uploaded object. 0 disables. Applies to the Parquet v3 reader. )", 0) \ DECLARE(UInt64, input_format_parquet_read_alignment_min_bytes, 1048576, R"( -Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a read at a boundary when the resulting aligned segment would be smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. Default 1 MiB. +Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a read at a boundary when the distance from the start of the range before the cut to the boundary is smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. Default 1 MiB. )", 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 0c5ebfddd1f7..c342c68d68af 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -55,7 +55,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_read_alignment_bytes", 0, 0, "New experimental setting: align coalesced Parquet reads to a fixed byte grid (for example the writer's multipart part size) so no read straddles a multiple of it. 0 disables."}, - {"input_format_parquet_read_alignment_min_bytes", 1048576, 1048576, "New experimental setting: anti-fragmentation guard for Parquet read alignment - do not cut a read at a boundary when the aligned segment would be smaller than this. Default 1 MiB."}, + {"input_format_parquet_read_alignment_min_bytes", 1048576, 1048576, "New experimental setting: anti-fragmentation guard for Parquet read alignment - do not cut a read at a boundary when the distance from the start of the range before the cut to the boundary is smaller than this. Default 1 MiB."}, }); addSettingsChanges(settings_changes_history, "26.8.35.20001.altinityantalya", { From ca7be26064ee3693d5dc9bc6f2b81dc875b75064 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Wed, 2 Dec 2026 11:39:53 +0100 Subject: [PATCH 07/30] Parquet v3 read alignment: do not let a zero-length range hide a boundary The pair rule looks at the joint span of two neighbouring ranges. A zero-length range at a multiple of the stride has no extent, so the boundary was not strictly inside the span of the pair before it, and for the pair after it the next multiple was taken. The ranges on both sides of it could be joined into a task that crosses the boundary, with every pair passing the check. Give a zero-length range an extent of one byte when deciding the cut. The empty range then belongs to the side after the boundary, whichever range starts the task. Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index ff4f413256f6..8809ab49d811 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -361,9 +361,13 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, return true; }; - /// The ranges at the current edges of the task, for shouldCutBetween. + /// The ranges at the current edges of the task, for shouldCutBetween. A zero-length range has no + /// extent to carry a crossing, so for this purpose it takes one byte: otherwise an empty range at a + /// multiple of the stride would hide the boundary from both of the pairs it belongs to, and the + /// ranges on its sides would be joined across the boundary. + auto extentEnd = [](size_t start, size_t end) { return std::max(end, start + 1); }; const size_t initial_start = start_offset; - const size_t initial_end = end_offset; + const size_t initial_end = extentEnd(start_offset, end_offset); size_t left_edge_end = initial_end; size_t right_edge_start = initial_start; size_t right_edge_end = initial_end; @@ -383,9 +387,10 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, { /// The alignment is checked only for a range that would actually be included: a cancelled /// range, or one that already has a task, must not stop the scan or count as a cut. - if (shouldCutBetween(r.start, std::max(r.end, left_edge_end))) + const size_t r_extent_end = extentEnd(r.start, r.end); + if (shouldCutBetween(r.start, std::max(r_extent_end, left_edge_end))) break; - left_edge_end = r.end; + left_edge_end = r_extent_end; /// Include this range in the task. start_idx = idx - 1; @@ -422,10 +427,11 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, const auto s = r.request->state.load(std::memory_order_relaxed); if (s == RequestState::State::HasRange) { - if (shouldCutBetween(right_edge_start, std::max(right_edge_end, r.end))) + const size_t r_extent_end = extentEnd(r.start, r.end); + if (shouldCutBetween(right_edge_start, std::max(right_edge_end, r_extent_end))) break; right_edge_start = r.start; - right_edge_end = r.end; + right_edge_end = r_extent_end; end_idx = idx + 1; total_length_of_covered_ranges += r.length(); From 0def54cefdd67a62e8bcd8c1f51440fc19430fec Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Wed, 2 Dec 2026 11:52:22 +0100 Subject: [PATCH 08/30] Parquet v3 read alignment: compare window indexes instead of computing the boundary A joint span of two ranges crosses a multiple of the stride exactly when its first and last bytes are in different windows of the grid, and the distance from the start of the earlier range to the next multiple is the stride minus the remainder. This replaces the explicit boundary computation in the cut decision. Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 8 ++- ...rquet_read_alignment_no_straddle.reference | 4 -- ...5820_parquet_read_alignment_no_straddle.sh | 72 ------------------- 3 files changed, 5 insertions(+), 79 deletions(-) delete mode 100644 tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.reference delete mode 100755 tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.sh diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 8809ab49d811..8038eeacd217 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -349,10 +349,12 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, { if (!alignment_active) return false; - const size_t boundary = (earlier_start / read_alignment_stride + 1) * read_alignment_stride; - if (boundary >= joint_end) + /// The joint span [earlier_start, joint_end) crosses a multiple of the stride iff its first and + /// last bytes are in different windows of the grid. + if (earlier_start / read_alignment_stride == (joint_end - 1) / read_alignment_stride) return false; - if (read_alignment_min_bytes > 0 && boundary - earlier_start < read_alignment_min_bytes) + /// Distance from the start of the earlier range to the first multiple of the stride after it. + if (read_alignment_min_bytes > 0 && read_alignment_stride - earlier_start % read_alignment_stride < read_alignment_min_bytes) { skipped_small = true; return false; diff --git a/tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.reference b/tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.reference deleted file mode 100644 index a47f036f6b1c..000000000000 --- a/tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.reference +++ /dev/null @@ -1,4 +0,0 @@ --- off: coalescing happens and crosses the grid -ok --- aligned: coalescing still happens, no coalesced task crosses the grid -ok diff --git a/tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.sh b/tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.sh deleted file mode 100755 index e53693584a85..000000000000 --- a/tests/queries/0_stateless/05820_parquet_read_alignment_no_straddle.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env bash -# Tags: no-fasttest - -# `input_format_parquet_read_alignment_bytes` must keep every coalesced read task (a task that covers more than one -# requested range) inside one window of the fixed grid. A task made of a single requested range larger than the -# window may still cross a boundary, it is not coalescing. -# The check reads the `Read task` test-level log lines of the Parquet v3 prefetcher. - -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}/alignment.parquet" - -# 10 row groups with 8 neighbouring column chunks each, so that the prefetcher coalesces the chunks of a row group. -${CLICKHOUSE_CLIENT} -q " - INSERT INTO FUNCTION file('${DATA_FILE}', Parquet) - SELECT - number AS k, - number % 1000 AS a, - cityHash64(number) AS b, - toString(number) AS s1, - toString(number * 7) AS s2, - number / 3 AS d, - toString(cityHash64(number)) AS e, - number * number AS f - FROM numbers(200000) - SETTINGS engine_file_truncate_on_insert = 1, output_format_parquet_row_group_size = 20000, - output_format_parquet_compression_method = 'none' -" - -STRUCTURE="k UInt64, a UInt32, b UInt64, s1 String, s2 String, d Float64, e String, f UInt64" -STRIDE=262144 - -# Prints: the number of tasks that cover more than one requested range, and how many of them cross a multiple -# of ${STRIDE}. -run() -{ - ${CLICKHOUSE_CLIENT} --send_logs_level=test -q " - SELECT sum(k), sum(a), sum(b), sum(length(s1)), sum(length(s2)), sum(toUInt64(d)), sum(length(e)), sum(f) - FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') - SETTINGS input_format_parquet_use_native_reader_v3 = 1, max_threads = 4, - input_format_parquet_local_file_min_bytes_for_seek = 1048576, $1 - FORMAT Null - " 2>&1 | awk -v stride=${STRIDE} ' - /ParquetPrefetcher.*Read task: / { - match($0, /offset=[0-9]+/); offset = substr($0, RSTART + 7, RLENGTH - 7) + 0; - match($0, /length=[0-9]+/); length_ = substr($0, RSTART + 7, RLENGTH - 7) + 0; - match($0, /ranges=[0-9]+/); ranges = substr($0, RSTART + 7, RLENGTH - 7) + 0; - if (ranges > 1) - { - multi += 1; - if (int(offset / stride) != int((offset + length_ - 1) / stride)) - crossing += 1; - } - } - END { print multi + 0, crossing + 0 }' -} - -# The control: without alignment, coalesced tasks do cross the multiples of the stride, so the check below can fail. -read -r multi crossing < <(run "input_format_parquet_read_alignment_bytes = 0") -echo "-- off: coalescing happens and crosses the grid" -[ "$multi" -gt 0 ] && [ "$crossing" -gt 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing" - -read -r multi crossing < <(run "input_format_parquet_read_alignment_bytes = ${STRIDE}, input_format_parquet_read_alignment_min_bytes = 1") -echo "-- aligned: coalescing still happens, no coalesced task crosses the grid" -[ "$multi" -gt 0 ] && [ "$crossing" -eq 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing" - -rm -rf "${WORKING_DIR}" From b816d0c7a4c213348c36241330ddb76053c344ca Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Wed, 2 Dec 2026 11:52:23 +0100 Subject: [PATCH 09/30] Parquet v3 read alignment: merge the straddle test into 05819_parquet_read_alignment `05820_parquet_read_alignment_no_straddle` generated the same file and ran the same queries as `05819_parquet_read_alignment`. Keep one test that checks the result, the profile events and, from the `Read task` log lines, that no coalesced task crosses the grid. Co-authored-by: Cursor --- .../05819_parquet_read_alignment.reference | 8 +++- .../05819_parquet_read_alignment.sh | 48 ++++++++++++++++--- 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/tests/queries/0_stateless/05819_parquet_read_alignment.reference b/tests/queries/0_stateless/05819_parquet_read_alignment.reference index c675ead95d56..2bb19c3e577b 100644 --- a/tests/queries/0_stateless/05819_parquet_read_alignment.reference +++ b/tests/queries/0_stateless/05819_parquet_read_alignment.reference @@ -2,9 +2,13 @@ 19999900000 99900000 17371400341328084350 1088890 1241267 6666566667 3879894 2666646666700000 -- aligned to a fixed grid: same result 19999900000 99900000 17371400341328084350 1088890 1241267 6666566667 3879894 2666646666700000 --- aligned, but the aligned segments are smaller than the minimum: same result +-- aligned, but the part before the boundary is smaller than the minimum: same result 19999900000 99900000 17371400341328084350 1088890 1241267 6666566667 3879894 2666646666700000 --- read alignment engages only when enabled, and the minimum segment size guard skips it +-- read alignment engages only when enabled, and the minimum size guard skips it aligned 1 off 1 small 1 +-- off: coalescing happens and crosses the grid +ok +-- aligned: coalescing still happens, no coalesced task crosses the grid +ok diff --git a/tests/queries/0_stateless/05819_parquet_read_alignment.sh b/tests/queries/0_stateless/05819_parquet_read_alignment.sh index 2622907523c9..7a766b64de40 100755 --- a/tests/queries/0_stateless/05819_parquet_read_alignment.sh +++ b/tests/queries/0_stateless/05819_parquet_read_alignment.sh @@ -10,6 +10,11 @@ WORKING_DIR="${USER_FILES_PATH}/${CLICKHOUSE_TEST_UNIQUE_NAME}" mkdir -p "${WORKING_DIR}" DATA_FILE="${WORKING_DIR}/alignment.parquet" +# `input_format_parquet_read_alignment_bytes` must keep every coalesced read task (a task that covers more than one +# requested range) inside one window of the fixed grid, and must not change the result. A task made of a single +# requested range larger than the window may still cross a boundary, it is not coalescing. +# The tasks are read from the `Read task` test-level log lines of the Parquet v3 prefetcher. + # 200000 rows, 20000 rows per row group => 10 row groups with 8 neighbouring column chunks each, so that the # prefetcher coalesces the chunks of a row group into shared read tasks. ${CLICKHOUSE_CLIENT} -q " @@ -29,26 +34,46 @@ ${CLICKHOUSE_CLIENT} -q " " STRUCTURE="k UInt64, a UInt32, b UInt64, s1 String, s2 String, d Float64, e String, f UInt64" +STRIDE=262144 # The large local-file seek threshold lets the prefetcher coalesce neighbouring column chunks. -COMMON="input_format_parquet_use_native_reader_v3 = 1, input_format_parquet_local_file_min_bytes_for_seek = 1048576" +COMMON="input_format_parquet_use_native_reader_v3 = 1, input_format_parquet_local_file_min_bytes_for_seek = 1048576, max_threads = 4" run() { - ${CLICKHOUSE_CLIENT} --query_id="${CLICKHOUSE_TEST_UNIQUE_NAME}_$1" -q " + ${CLICKHOUSE_CLIENT} --query_id="${CLICKHOUSE_TEST_UNIQUE_NAME}_$1" --send_logs_level=test -q " SELECT sum(k), sum(a), sum(b), sum(length(s1)), sum(length(s2)), sum(toUInt64(d)), sum(length(e)), sum(f) FROM file('${DATA_FILE}', Parquet, '${STRUCTURE}') SETTINGS ${COMMON}, $2 - " + " 2> "${WORKING_DIR}/$1.log" +} + +# Prints: the number of tasks that cover more than one requested range, and how many of them cross a multiple +# of ${STRIDE}. +count_tasks() +{ + awk -v stride=${STRIDE} ' + /ParquetPrefetcher.*Read task: / { + match($0, /offset=[0-9]+/); offset = substr($0, RSTART + 7, RLENGTH - 7) + 0; + match($0, /length=[0-9]+/); length_ = substr($0, RSTART + 7, RLENGTH - 7) + 0; + match($0, /ranges=[0-9]+/); ranges = substr($0, RSTART + 7, RLENGTH - 7) + 0; + if (ranges > 1) + { + multi += 1; + if (int(offset / stride) != int((offset + length_ - 1) / stride)) + crossing += 1; + } + } + END { print multi + 0, crossing + 0 }' "${WORKING_DIR}/$1.log" } echo "-- read alignment off (default)" run off "input_format_parquet_read_alignment_bytes = 0" echo "-- aligned to a fixed grid: same result" -run aligned "input_format_parquet_read_alignment_bytes = 100000, input_format_parquet_read_alignment_min_bytes = 1" -echo "-- aligned, but the aligned segments are smaller than the minimum: same result" -run small "input_format_parquet_read_alignment_bytes = 100000, input_format_parquet_read_alignment_min_bytes = 1048576" +run aligned "input_format_parquet_read_alignment_bytes = ${STRIDE}, input_format_parquet_read_alignment_min_bytes = 1" +echo "-- aligned, but the part before the boundary is smaller than the minimum: same result" +run small "input_format_parquet_read_alignment_bytes = ${STRIDE}, input_format_parquet_read_alignment_min_bytes = 1048576" -echo "-- read alignment engages only when enabled, and the minimum segment size guard skips it" +echo "-- read alignment engages only when enabled, and the minimum size guard skips it" ${CLICKHOUSE_CLIENT} -q " SYSTEM FLUSH LOGS query_log; SELECT @@ -63,4 +88,13 @@ ${CLICKHOUSE_CLIENT} -q " ORDER BY name " +# The control: without alignment, coalesced tasks do cross the multiples of the stride, so the check can fail. +read -r multi crossing < <(count_tasks off) +echo "-- off: coalescing happens and crosses the grid" +[ "$multi" -gt 0 ] && [ "$crossing" -gt 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing" + +read -r multi crossing < <(count_tasks aligned) +echo "-- aligned: coalescing still happens, no coalesced task crosses the grid" +[ "$multi" -gt 0 ] && [ "$crossing" -eq 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing" + rm -rf "${WORKING_DIR}" From 6d08994490ba80e2178b52cdf7b159ebb69ed661 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Wed, 2 Dec 2026 11:57:40 +0100 Subject: [PATCH 10/30] Parquet v3 read alignment: say that only the merging of ranges is limited The description of `input_format_parquet_read_alignment_bytes` and the comment in `Prefetcher.h` said that no read straddles a multiple of the stride. The setting only stops separate requested ranges from being merged into one read across a multiple. A single requested range that crosses a multiple is still read as one request, and `input_format_parquet_read_alignment_min_bytes` can let a merged read cross it. Describe that, and drop the stale "min aligned-segment size" wording. Co-authored-by: Cursor --- src/Core/FormatFactorySettings.h | 2 +- src/Core/SettingsChangesHistory.cpp | 2 +- src/Processors/Formats/Impl/Parquet/Prefetcher.h | 6 ++++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index b2ff34a06363..594c86c64a9b 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -237,7 +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(UInt64, input_format_parquet_read_alignment_bytes, 0, R"( -Experimental. Align coalesced Parquet read requests to a fixed byte grid of this size, so no read straddles a multiple of it. Set it to the writer's multipart part size (for example 10Mi for delta-rs, 64Mi for Spark/S3A) to keep reads within single parts of a multipart-uploaded object. 0 disables. Applies to the Parquet v3 reader. +Experimental. When the Parquet v3 reader merges neighbouring requested ranges (for example column chunks) into one read, do not merge across a multiple of this size. Set it to the writer's multipart part size (for example 10Mi for delta-rs, 64Mi for Spark/S3A) to avoid merged reads that span two parts of a multipart-uploaded object. Only the merging is limited: a single requested range that crosses a multiple of this size is still read as one request, and `input_format_parquet_read_alignment_min_bytes` can allow a merged read to cross it too. 0 disables. )", 0) \ DECLARE(UInt64, input_format_parquet_read_alignment_min_bytes, 1048576, R"( Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a read at a boundary when the distance from the start of the range before the cut to the boundary is smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. Default 1 MiB. diff --git a/src/Core/SettingsChangesHistory.cpp b/src/Core/SettingsChangesHistory.cpp index c342c68d68af..8735f4125105 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -54,7 +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_read_alignment_bytes", 0, 0, "New experimental setting: align coalesced Parquet reads to a fixed byte grid (for example the writer's multipart part size) so no read straddles a multiple of it. 0 disables."}, + {"input_format_parquet_read_alignment_bytes", 0, 0, "New experimental setting: do not merge neighbouring Parquet read ranges across a multiple of this size (for example the writer's multipart part size). 0 disables."}, {"input_format_parquet_read_alignment_min_bytes", 1048576, 1048576, "New experimental setting: anti-fragmentation guard for Parquet read alignment - do not cut a read at a boundary when the distance from the start of the range before the cut to the boundary is smaller than this. Default 1 MiB."}, }); addSettingsChanges(settings_changes_history, "26.8.35.20001.altinityantalya", diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index aa37cae3d601..cee07790fb74 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -183,8 +183,10 @@ class Prefetcher size_t min_bytes_for_seek{}; size_t bytes_per_read_task{}; - /// Fixed boundary grid (bytes) for read alignment: no coalesced read task straddles a multiple of it. - /// 0 = off. And the anti-fragmentation min aligned-segment size. Set in init(), read-only after. + /// Read alignment: ranges are not merged into one task across a multiple of read_alignment_stride + /// (0 = off), unless the part of the merged read before the boundary, measured from the start of the + /// earlier range, is smaller than read_alignment_min_bytes. A single requested range that crosses a + /// multiple is still read as one task. Set in init(), read-only after. size_t read_alignment_stride = 0; size_t read_alignment_min_bytes = 0; From 5bfe61839bbcd729e6e7eb41d085d8d01b6f62cd Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Thu, 3 Dec 2026 10:41:14 +0100 Subject: [PATCH 11/30] Check the anti-fragmentation guard at every boundary the merge newly crosses The `input_format_parquet_read_alignment_min_bytes` guard measured the part before the first grid boundary after the start of the earlier range. When the earlier range already crosses a boundary on its own, that boundary is unavoidable, so the guard measured to it and could allow a merge across additional boundaries that the merge newly crosses. Now a pair of neighbouring ranges is cut when the joined read newly crosses a boundary (the last multiple of the stride not after the later range's start, if the earlier range ends before it), unless the largest part of the joined read before such a boundary is smaller than the minimum. The decision still depends only on the pair, so the resulting tasks do not depend on which range starts the task. Update the setting, the settings history, the ProfileEvents description and the comment in `Prefetcher.h` to match. Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- src/Common/ProfileEvents.cpp | 2 +- src/Core/FormatFactorySettings.h | 2 +- src/Core/SettingsChangesHistory.cpp | 2 +- .../Formats/Impl/Parquet/Prefetcher.cpp | 51 ++++++++++--------- .../Formats/Impl/Parquet/Prefetcher.h | 4 +- 5 files changed, 31 insertions(+), 30 deletions(-) diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index 8c4325afe3c7..3ae12d54249f 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -1853,7 +1853,7 @@ The server successfully detected this situation and will download merged part fr 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(ParquetPrefetcherPartAlignedTasks, "The number of read tasks whose coalescing was cut at a read alignment boundary (input_format_parquet_read_alignment_bytes) by DB::Parquet::Prefetcher", ValueType::Number) \ - M(ParquetPrefetcherAlignmentSkippedSmall, "The number of read tasks in which DB::Parquet::Prefetcher did not cut at a read alignment boundary because the part of the read before it would be smaller than input_format_parquet_read_alignment_min_bytes (anti-fragmentation)", ValueType::Number) \ + M(ParquetPrefetcherAlignmentSkippedSmall, "The number of read tasks in which DB::Parquet::Prefetcher did not cut at a read alignment boundary because the largest part of the read before a boundary it newly crosses would be smaller than input_format_parquet_read_alignment_min_bytes (anti-fragmentation)", 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 594c86c64a9b..1e652b30d838 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -240,7 +240,7 @@ Minor tweak to how pages are read from parquet file when no page filtering is us Experimental. When the Parquet v3 reader merges neighbouring requested ranges (for example column chunks) into one read, do not merge across a multiple of this size. Set it to the writer's multipart part size (for example 10Mi for delta-rs, 64Mi for Spark/S3A) to avoid merged reads that span two parts of a multipart-uploaded object. Only the merging is limited: a single requested range that crosses a multiple of this size is still read as one request, and `input_format_parquet_read_alignment_min_bytes` can allow a merged read to cross it too. 0 disables. )", 0) \ DECLARE(UInt64, input_format_parquet_read_alignment_min_bytes, 1048576, R"( -Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a read at a boundary when the distance from the start of the range before the cut to the boundary is smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. Default 1 MiB. +Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a merge at a boundary that the merge newly crosses when the largest part of the merged read before such a boundary is smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. Default 1 MiB. )", 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 8735f4125105..d95922cf0347 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -55,7 +55,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_read_alignment_bytes", 0, 0, "New experimental setting: do not merge neighbouring Parquet read ranges across a multiple of this size (for example the writer's multipart part size). 0 disables."}, - {"input_format_parquet_read_alignment_min_bytes", 1048576, 1048576, "New experimental setting: anti-fragmentation guard for Parquet read alignment - do not cut a read at a boundary when the distance from the start of the range before the cut to the boundary is smaller than this. Default 1 MiB."}, + {"input_format_parquet_read_alignment_min_bytes", 1048576, 1048576, "New experimental setting: anti-fragmentation guard for Parquet read alignment - do not cut a merge at a boundary that the merge newly crosses when the largest part of the merged read before such a boundary is smaller than this. Default 1 MiB."}, }); addSettingsChanges(settings_changes_history, "26.8.35.20001.altinityantalya", { diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 8038eeacd217..9193e3fc9547 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -336,25 +336,30 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, /// /// The decision is made for each pair of neighbouring ranges (in the order of their start offsets) /// that would be joined in the task, and depends only on the pair, so the resulting tasks don't depend - /// on which range of a chain starts the task. The pair is cut when the first multiple of the stride - /// after the start of the earlier range lies strictly inside the pair's joint span. + /// on which range of a chain starts the task. /// - /// Anti-fragmentation: cutting leaves the earlier range's part before the boundary as a separate - /// read. If that part is smaller than read_alignment_min_bytes, don't cut, allow the straddle instead. + /// Anti-fragmentation: cutting a pair leaves the part of the joined read before each boundary that the + /// pair newly introduces as a separate read. If the largest such part is smaller than + /// read_alignment_min_bytes, don't cut, allow the straddle instead. const bool alignment_active = read_alignment_stride > 0; bool part_boundary_constrained = false; bool skipped_small = false; - auto shouldCutBetween = [&](size_t earlier_start, size_t joint_end) + /// `earlier_start`, `earlier_end` and `later_start` describe two ranges with earlier_start <= later_start. + /// The joined read newly crosses a multiple b of the stride iff neither range crosses b on its own and the + /// joined read contains bytes on both sides of b, i.e. earlier_end <= b <= later_start. The last such + /// boundary is the largest multiple of the stride not after later_start. The part of the joined read + /// before a boundary b is b - max(earlier_start, b - stride), which does not decrease in b, so the last + /// boundary leaves the largest part. + auto shouldCutBetween = [&](size_t earlier_start, size_t earlier_end, size_t later_start) { if (!alignment_active) return false; - /// The joint span [earlier_start, joint_end) crosses a multiple of the stride iff its first and - /// last bytes are in different windows of the grid. - if (earlier_start / read_alignment_stride == (joint_end - 1) / read_alignment_stride) + const size_t last_boundary = later_start / read_alignment_stride * read_alignment_stride; + if (last_boundary < earlier_end) return false; - /// Distance from the start of the earlier range to the first multiple of the stride after it. - if (read_alignment_min_bytes > 0 && read_alignment_stride - earlier_start % read_alignment_stride < read_alignment_min_bytes) + const size_t largest_part = std::min(read_alignment_stride, last_boundary - earlier_start); + if (read_alignment_min_bytes > 0 && largest_part < read_alignment_min_bytes) { skipped_small = true; return false; @@ -363,16 +368,14 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, return true; }; - /// The ranges at the current edges of the task, for shouldCutBetween. A zero-length range has no - /// extent to carry a crossing, so for this purpose it takes one byte: otherwise an empty range at a - /// multiple of the stride would hide the boundary from both of the pairs it belongs to, and the - /// ranges on its sides would be joined across the boundary. + /// The ranges adjacent to the scans, for shouldCutBetween. A zero-length range has no extent to carry a + /// crossing, so for this purpose it takes one byte: otherwise an empty range at a multiple of the stride + /// would hide the boundary from both of the pairs it belongs to, and the ranges on its sides would be + /// joined across the boundary. auto extentEnd = [](size_t start, size_t end) { return std::max(end, start + 1); }; - const size_t initial_start = start_offset; - const size_t initial_end = extentEnd(start_offset, end_offset); - size_t left_edge_end = initial_end; - size_t right_edge_start = initial_start; - size_t right_edge_end = initial_end; + size_t left_edge_start = start_offset; + size_t right_edge_start = start_offset; + size_t right_edge_end = extentEnd(start_offset, end_offset); /// Go left. size_t initial_offset = start_offset; @@ -389,10 +392,9 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, { /// The alignment is checked only for a range that would actually be included: a cancelled /// range, or one that already has a task, must not stop the scan or count as a cut. - const size_t r_extent_end = extentEnd(r.start, r.end); - if (shouldCutBetween(r.start, std::max(r_extent_end, left_edge_end))) + if (shouldCutBetween(r.start, extentEnd(r.start, r.end), left_edge_start)) break; - left_edge_end = r_extent_end; + left_edge_start = r.start; /// Include this range in the task. start_idx = idx - 1; @@ -429,11 +431,10 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, const auto s = r.request->state.load(std::memory_order_relaxed); if (s == RequestState::State::HasRange) { - const size_t r_extent_end = extentEnd(r.start, r.end); - if (shouldCutBetween(right_edge_start, std::max(right_edge_end, r_extent_end))) + if (shouldCutBetween(right_edge_start, right_edge_end, r.start)) break; right_edge_start = r.start; - right_edge_end = r_extent_end; + right_edge_end = extentEnd(r.start, r.end); end_idx = idx + 1; total_length_of_covered_ranges += r.length(); diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index cee07790fb74..d977b57d1286 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -184,8 +184,8 @@ class Prefetcher size_t bytes_per_read_task{}; /// Read alignment: ranges are not merged into one task across a multiple of read_alignment_stride - /// (0 = off), unless the part of the merged read before the boundary, measured from the start of the - /// earlier range, is smaller than read_alignment_min_bytes. A single requested range that crosses a + /// (0 = off), unless the largest part of the merged read before a boundary that the merge newly crosses + /// is smaller than read_alignment_min_bytes. A single requested range that crosses a /// multiple is still read as one task. Set in init(), read-only after. size_t read_alignment_stride = 0; size_t read_alignment_min_bytes = 0; From 9e79207fa6e2343037e0d896e279f22ca1ece023 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Thu, 3 Dec 2026 10:49:25 +0100 Subject: [PATCH 12/30] Parquet v3 read alignment: keep cutting where a range crosses the boundary by itself The previous change looked only at the multiples of the stride that lie in the gap between two ranges. The column chunks of a file are usually contiguous, so every multiple lies inside some chunk and no pair was ever cut: the alignment did nothing, and coalesced tasks grew up to `bytes_per_read_task` across many multiples. Restore the cut condition (the joint span of the pair crosses a multiple of the stride, including when one of the ranges crosses it on its own). Fix the anti-fragmentation guard of `input_format_parquet_read_alignment_min_bytes` instead: measure the part of the joint span before the last multiple inside it, which is the largest one, and not before the first multiple after the start of the earlier range. When the earlier range ends close after the first multiple, the first-multiple check allowed a merge across further multiples. Update the setting, the settings history, the `ProfileEvents` description and the comment in `Prefetcher.h` to match. Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- src/Common/ProfileEvents.cpp | 2 +- src/Core/FormatFactorySettings.h | 2 +- src/Core/SettingsChangesHistory.cpp | 2 +- .../Formats/Impl/Parquet/Prefetcher.cpp | 58 +++++++++++-------- .../Formats/Impl/Parquet/Prefetcher.h | 4 +- 5 files changed, 38 insertions(+), 30 deletions(-) diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index 3ae12d54249f..1395d337de6b 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -1853,7 +1853,7 @@ The server successfully detected this situation and will download merged part fr 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(ParquetPrefetcherPartAlignedTasks, "The number of read tasks whose coalescing was cut at a read alignment boundary (input_format_parquet_read_alignment_bytes) by DB::Parquet::Prefetcher", ValueType::Number) \ - M(ParquetPrefetcherAlignmentSkippedSmall, "The number of read tasks in which DB::Parquet::Prefetcher did not cut at a read alignment boundary because the largest part of the read before a boundary it newly crosses would be smaller than input_format_parquet_read_alignment_min_bytes (anti-fragmentation)", ValueType::Number) \ + M(ParquetPrefetcherAlignmentSkippedSmall, "The number of read tasks in which DB::Parquet::Prefetcher did not cut at a read alignment boundary because the largest part of the read before a boundary would be smaller than input_format_parquet_read_alignment_min_bytes (anti-fragmentation)", 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 1e652b30d838..7e897cc6e0b5 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -240,7 +240,7 @@ Minor tweak to how pages are read from parquet file when no page filtering is us Experimental. When the Parquet v3 reader merges neighbouring requested ranges (for example column chunks) into one read, do not merge across a multiple of this size. Set it to the writer's multipart part size (for example 10Mi for delta-rs, 64Mi for Spark/S3A) to avoid merged reads that span two parts of a multipart-uploaded object. Only the merging is limited: a single requested range that crosses a multiple of this size is still read as one request, and `input_format_parquet_read_alignment_min_bytes` can allow a merged read to cross it too. 0 disables. )", 0) \ DECLARE(UInt64, input_format_parquet_read_alignment_min_bytes, 1048576, R"( -Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a merge at a boundary that the merge newly crosses when the largest part of the merged read before such a boundary is smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. Default 1 MiB. +Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a merge at a boundary when the largest part of the merged read before a boundary (within one multiple of the size) is smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. Default 1 MiB. )", 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 d95922cf0347..2aa2aaaed3e3 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -55,7 +55,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_read_alignment_bytes", 0, 0, "New experimental setting: do not merge neighbouring Parquet read ranges across a multiple of this size (for example the writer's multipart part size). 0 disables."}, - {"input_format_parquet_read_alignment_min_bytes", 1048576, 1048576, "New experimental setting: anti-fragmentation guard for Parquet read alignment - do not cut a merge at a boundary that the merge newly crosses when the largest part of the merged read before such a boundary is smaller than this. Default 1 MiB."}, + {"input_format_parquet_read_alignment_min_bytes", 1048576, 1048576, "New experimental setting: anti-fragmentation guard for Parquet read alignment - do not cut a merge at a boundary when the largest part of the merged read before a boundary is smaller than this. Default 1 MiB."}, }); addSettingsChanges(settings_changes_history, "26.8.35.20001.altinityantalya", { diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 9193e3fc9547..31bf2360c9cb 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -336,30 +336,34 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, /// /// The decision is made for each pair of neighbouring ranges (in the order of their start offsets) /// that would be joined in the task, and depends only on the pair, so the resulting tasks don't depend - /// on which range of a chain starts the task. + /// on which range of a chain starts the task. The pair is cut when a multiple of the stride lies + /// strictly inside the pair's joint span, including when one of the ranges crosses it on its own: + /// the ranges of a file are usually contiguous, so then every multiple of the stride lies inside some + /// range, and a rule that looks only at boundaries between the ranges would never cut. /// - /// Anti-fragmentation: cutting a pair leaves the part of the joined read before each boundary that the - /// pair newly introduces as a separate read. If the largest such part is smaller than + /// Anti-fragmentation: cutting leaves the part of the joint span before a boundary as a separate read. + /// If the largest such part (that of the last boundary inside the joint span) is smaller than /// read_alignment_min_bytes, don't cut, allow the straddle instead. const bool alignment_active = read_alignment_stride > 0; bool part_boundary_constrained = false; bool skipped_small = false; - /// `earlier_start`, `earlier_end` and `later_start` describe two ranges with earlier_start <= later_start. - /// The joined read newly crosses a multiple b of the stride iff neither range crosses b on its own and the - /// joined read contains bytes on both sides of b, i.e. earlier_end <= b <= later_start. The last such - /// boundary is the largest multiple of the stride not after later_start. The part of the joined read - /// before a boundary b is b - max(earlier_start, b - stride), which does not decrease in b, so the last - /// boundary leaves the largest part. - auto shouldCutBetween = [&](size_t earlier_start, size_t earlier_end, size_t later_start) + auto shouldCutBetween = [&](size_t earlier_start, size_t joint_end) { if (!alignment_active) return false; - const size_t last_boundary = later_start / read_alignment_stride * read_alignment_stride; - if (last_boundary < earlier_end) + /// The joint span [earlier_start, joint_end) crosses a multiple of the stride iff its first and + /// last bytes are in different windows of the grid. + const size_t last_window = (joint_end - 1) / read_alignment_stride; + if (earlier_start / read_alignment_stride == last_window) return false; - const size_t largest_part = std::min(read_alignment_stride, last_boundary - earlier_start); - if (read_alignment_min_bytes > 0 && largest_part < read_alignment_min_bytes) + /// The last multiple of the stride inside the joint span; it is after earlier_start. The part of the + /// joint span before a multiple b of the stride is measured within one window, as + /// b - max(earlier_start, b - stride). It does not decrease in b, so the last multiple leaves the + /// largest part. Measuring only the first multiple after earlier_start would allow a merge across + /// further multiples when the earlier range ends close after the first one. + const size_t last_boundary = last_window * read_alignment_stride; + if (read_alignment_min_bytes > 0 && std::min(read_alignment_stride, last_boundary - earlier_start) < read_alignment_min_bytes) { skipped_small = true; return false; @@ -368,14 +372,16 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, return true; }; - /// The ranges adjacent to the scans, for shouldCutBetween. A zero-length range has no extent to carry a - /// crossing, so for this purpose it takes one byte: otherwise an empty range at a multiple of the stride - /// would hide the boundary from both of the pairs it belongs to, and the ranges on its sides would be - /// joined across the boundary. + /// The ranges at the current edges of the task, for shouldCutBetween. A zero-length range has no + /// extent to carry a crossing, so for this purpose it takes one byte: otherwise an empty range at a + /// multiple of the stride would hide the boundary from both of the pairs it belongs to, and the + /// ranges on its sides would be joined across the boundary. auto extentEnd = [](size_t start, size_t end) { return std::max(end, start + 1); }; - size_t left_edge_start = start_offset; - size_t right_edge_start = start_offset; - size_t right_edge_end = extentEnd(start_offset, end_offset); + const size_t initial_start = start_offset; + const size_t initial_end = extentEnd(start_offset, end_offset); + size_t left_edge_end = initial_end; + size_t right_edge_start = initial_start; + size_t right_edge_end = initial_end; /// Go left. size_t initial_offset = start_offset; @@ -392,9 +398,10 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, { /// The alignment is checked only for a range that would actually be included: a cancelled /// range, or one that already has a task, must not stop the scan or count as a cut. - if (shouldCutBetween(r.start, extentEnd(r.start, r.end), left_edge_start)) + const size_t r_extent_end = extentEnd(r.start, r.end); + if (shouldCutBetween(r.start, std::max(r_extent_end, left_edge_end))) break; - left_edge_start = r.start; + left_edge_end = r_extent_end; /// Include this range in the task. start_idx = idx - 1; @@ -431,10 +438,11 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, const auto s = r.request->state.load(std::memory_order_relaxed); if (s == RequestState::State::HasRange) { - if (shouldCutBetween(right_edge_start, right_edge_end, r.start)) + const size_t r_extent_end = extentEnd(r.start, r.end); + if (shouldCutBetween(right_edge_start, std::max(right_edge_end, r_extent_end))) break; right_edge_start = r.start; - right_edge_end = extentEnd(r.start, r.end); + right_edge_end = r_extent_end; end_idx = idx + 1; total_length_of_covered_ranges += r.length(); diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index d977b57d1286..bc3ff2288bbf 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -184,8 +184,8 @@ class Prefetcher size_t bytes_per_read_task{}; /// Read alignment: ranges are not merged into one task across a multiple of read_alignment_stride - /// (0 = off), unless the largest part of the merged read before a boundary that the merge newly crosses - /// is smaller than read_alignment_min_bytes. A single requested range that crosses a + /// (0 = off), unless the largest part of the merged read before a boundary (that of the last multiple + /// inside it) is smaller than read_alignment_min_bytes. A single requested range that crosses a /// multiple is still read as one task. Set in init(), read-only after. size_t read_alignment_stride = 0; size_t read_alignment_min_bytes = 0; From 605b98b88e7e3ef552e4b64e14268863c5020f4e Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Thu, 3 Dec 2026 11:31:41 +0100 Subject: [PATCH 13/30] Parquet v3 read alignment: measure the anti-fragmentation guard on the whole piece that a cut leaves The `input_format_parquet_read_alignment_min_bytes` guard measured the part before the boundary from the start of the earlier range of the pair. When the earlier range is a small chunk that follows other chunks, the cut leaves all of them as one piece, so the part was underestimated, the guard skipped the cut, and the task kept a boundary with a long part of the task before it. On a file with 8 column chunks per row group, with a stride of 262144 and a minimum of 65536, 6 of 23 coalesced tasks kept such a boundary. Measure the part from the start of the piece of neighbouring ranges that ends with the earlier range. The start is found by walking to the left with the same checks as the scan (cancelled ranges are skipped, a range that already has a task and a gap of `min_bytes_for_seek` stop the walk, and a pair that is cut stops it). It depends only on the ranges and not on the range that starts the task, so the scan going left and the scan going right decide a pair in the same way. The walk stops as soon as the piece reaches `read_alignment_min_bytes` before the boundary. Add a run of `05819_parquet_read_alignment` with a minimum that lets a short part straddle, and check that no coalesced task contains a multiple of the stride with at least the minimum before it. The check fails (7 of 29 tasks) with the previous guard. Update the setting, the settings history and the `ProfileEvents` description. Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- src/Common/ProfileEvents.cpp | 2 +- src/Core/FormatFactorySettings.h | 2 +- src/Core/SettingsChangesHistory.cpp | 2 +- .../Formats/Impl/Parquet/Prefetcher.cpp | 141 +++++++++++++----- .../Formats/Impl/Parquet/Prefetcher.h | 12 +- .../05819_parquet_read_alignment.reference | 5 + .../05819_parquet_read_alignment.sh | 38 ++++- 7 files changed, 154 insertions(+), 48 deletions(-) diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index 1395d337de6b..23c381787612 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -1853,7 +1853,7 @@ The server successfully detected this situation and will download merged part fr 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(ParquetPrefetcherPartAlignedTasks, "The number of read tasks whose coalescing was cut at a read alignment boundary (input_format_parquet_read_alignment_bytes) by DB::Parquet::Prefetcher", ValueType::Number) \ - M(ParquetPrefetcherAlignmentSkippedSmall, "The number of read tasks in which DB::Parquet::Prefetcher did not cut at a read alignment boundary because the largest part of the read before a boundary would be smaller than input_format_parquet_read_alignment_min_bytes (anti-fragmentation)", ValueType::Number) \ + M(ParquetPrefetcherAlignmentSkippedSmall, "The number of read tasks in which DB::Parquet::Prefetcher did not cut at a read alignment boundary because the part before the boundary of the run of neighbouring ranges that the cut would leave would be smaller than input_format_parquet_read_alignment_min_bytes (anti-fragmentation)", 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 7e897cc6e0b5..e3856b06a0df 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -240,7 +240,7 @@ Minor tweak to how pages are read from parquet file when no page filtering is us Experimental. When the Parquet v3 reader merges neighbouring requested ranges (for example column chunks) into one read, do not merge across a multiple of this size. Set it to the writer's multipart part size (for example 10Mi for delta-rs, 64Mi for Spark/S3A) to avoid merged reads that span two parts of a multipart-uploaded object. Only the merging is limited: a single requested range that crosses a multiple of this size is still read as one request, and `input_format_parquet_read_alignment_min_bytes` can allow a merged read to cross it too. 0 disables. )", 0) \ DECLARE(UInt64, input_format_parquet_read_alignment_min_bytes, 1048576, R"( -Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a merge at a boundary when the largest part of the merged read before a boundary (within one multiple of the size) is smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. Default 1 MiB. +Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a merge at a boundary when the part before the boundary of the run of neighbouring ranges that the cut would leave (within one multiple of the size) is smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. Default 1 MiB. )", 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 2aa2aaaed3e3..7b0aff41d3bd 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -55,7 +55,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_read_alignment_bytes", 0, 0, "New experimental setting: do not merge neighbouring Parquet read ranges across a multiple of this size (for example the writer's multipart part size). 0 disables."}, - {"input_format_parquet_read_alignment_min_bytes", 1048576, 1048576, "New experimental setting: anti-fragmentation guard for Parquet read alignment - do not cut a merge at a boundary when the largest part of the merged read before a boundary is smaller than this. Default 1 MiB."}, + {"input_format_parquet_read_alignment_min_bytes", 1048576, 1048576, "New experimental setting: anti-fragmentation guard for Parquet read alignment - do not cut a merge at a boundary when the part before the boundary of the run of neighbouring ranges that the cut would leave is smaller than this. Default 1 MiB."}, }); addSettingsChanges(settings_changes_history, "26.8.35.20001.altinityantalya", { diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 31bf2360c9cb..235e2258f75b 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -295,6 +295,94 @@ std::vector Prefetcher::splitRange( return out_handles; } +/// A zero-length range has no extent to carry a crossing, so for the read alignment it takes one byte: +/// otherwise an empty range at a multiple of the stride would hide the boundary from both of the pairs +/// it belongs to, and the ranges on its sides would be joined across the boundary. +static size_t extentEnd(size_t start, size_t end) +{ + return std::max(end, start + 1); +} + +bool Prefetcher::shouldCutForAlignment( + const std::vector & ranges, size_t earlier_idx, size_t earlier_start, size_t earlier_end, + size_t later_start, size_t later_end, bool * skipped_small) const +{ + chassert(read_alignment_stride > 0); + + /// The joint span [earlier_start, joint_end) crosses a multiple of the stride iff its first and last + /// bytes are in different windows of the grid. This includes the case when one of the ranges crosses + /// the multiple on its own. + const size_t joint_end = std::max(extentEnd(earlier_start, earlier_end), extentEnd(later_start, later_end)); + const size_t last_window = (joint_end - 1) / read_alignment_stride; + if (earlier_start / read_alignment_stride == last_window) + return false; + + if (read_alignment_min_bytes == 0) + return true; + + /// The last multiple of the stride inside the joint span; it is after earlier_start. The part of a read + /// before a multiple b of the stride is measured within one window of the grid, as b - max(start, b - stride). + /// It does not decrease in b, so the last multiple leaves the largest part. + const size_t last_boundary = last_window * read_alignment_stride; + + /// Cutting leaves the piece of neighbouring ranges that ends with the earlier range. The piece may be + /// longer than the earlier range, so measure it from its start: the part is at least read_alignment_min_bytes + /// iff the piece starts at or before last_boundary - read_alignment_min_bytes. + bool small = true; + if (read_alignment_min_bytes <= read_alignment_stride) + { + const size_t lower_bound = last_boundary >= read_alignment_min_bytes ? last_boundary - read_alignment_min_bytes : 0; + const size_t piece_start = alignmentPieceStart(ranges, earlier_idx, earlier_start, earlier_end, lower_bound); + small = std::min(read_alignment_stride, last_boundary - piece_start) < read_alignment_min_bytes; + } + if (small) + { + if (skipped_small) + *skipped_small = true; + return false; + } + return true; +} + +size_t Prefetcher::alignmentPieceStart(const std::vector & ranges, size_t idx, size_t start, size_t end, size_t lower_bound) const +{ + /// Walk to the left over the ranges that the scan in pickRangesAndCreateTaskIfNotExists would join into one + /// task with this one, with the same checks: skip the cancelled ranges, stop at a range that already has a + /// task, at a gap of min_bytes_for_seek, and at a pair that is cut. The result depends only on the ranges + /// and not on the range that starts the task, so the decision for a pair is the same for the scan going + /// left and the scan going right. (The limit on the size of the task is not applied, because it depends on + /// the range that starts the task.) + size_t piece_start = start; + size_t later_start = start; + size_t later_end = end; + size_t later_idx = idx; + while (piece_start > lower_bound) + { + size_t earlier_idx = later_idx; + RequestState::State s; + do + { + if (earlier_idx == 0) + return piece_start; + --earlier_idx; + s = ranges[earlier_idx].request->state.load(std::memory_order_relaxed); + } while (s == RequestState::State::Cancelled); + if (s != RequestState::State::HasRange) + return piece_start; + + const RangeState & earlier = ranges[earlier_idx]; + if (earlier.end + min_bytes_for_seek <= piece_start + || shouldCutForAlignment(ranges, earlier_idx, earlier.start, earlier.end, later_start, later_end, /*skipped_small=*/ nullptr)) + return piece_start; + + piece_start = std::min(piece_start, earlier.start); + later_idx = earlier_idx; + later_start = earlier.start; + later_end = earlier.end; + } + return piece_start; +} + void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, const PrefetchHandle &, bool splitting, size_t start_offset, size_t end_offset, std::unique_lock lock) { chassert(lock.owns_lock()); @@ -341,47 +429,30 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, /// the ranges of a file are usually contiguous, so then every multiple of the stride lies inside some /// range, and a rule that looks only at boundaries between the ranges would never cut. /// - /// Anti-fragmentation: cutting leaves the part of the joint span before a boundary as a separate read. - /// If the largest such part (that of the last boundary inside the joint span) is smaller than - /// read_alignment_min_bytes, don't cut, allow the straddle instead. + /// Anti-fragmentation: cutting leaves the piece of neighbouring ranges before a boundary as a separate + /// read. If the part of that piece before the last boundary inside the joint span is smaller than + /// read_alignment_min_bytes, don't cut, allow the straddle instead. See shouldCutForAlignment. const bool alignment_active = read_alignment_stride > 0; bool part_boundary_constrained = false; bool skipped_small = false; - auto shouldCutBetween = [&](size_t earlier_start, size_t joint_end) + auto shouldCutBetween = [&](size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end) { if (!alignment_active) return false; - /// The joint span [earlier_start, joint_end) crosses a multiple of the stride iff its first and - /// last bytes are in different windows of the grid. - const size_t last_window = (joint_end - 1) / read_alignment_stride; - if (earlier_start / read_alignment_stride == last_window) + if (!shouldCutForAlignment(ranges, earlier_idx, earlier_start, earlier_end, later_start, later_end, &skipped_small)) return false; - /// The last multiple of the stride inside the joint span; it is after earlier_start. The part of the - /// joint span before a multiple b of the stride is measured within one window, as - /// b - max(earlier_start, b - stride). It does not decrease in b, so the last multiple leaves the - /// largest part. Measuring only the first multiple after earlier_start would allow a merge across - /// further multiples when the earlier range ends close after the first one. - const size_t last_boundary = last_window * read_alignment_stride; - if (read_alignment_min_bytes > 0 && std::min(read_alignment_stride, last_boundary - earlier_start) < read_alignment_min_bytes) - { - skipped_small = true; - return false; - } part_boundary_constrained = true; return true; }; - /// The ranges at the current edges of the task, for shouldCutBetween. A zero-length range has no - /// extent to carry a crossing, so for this purpose it takes one byte: otherwise an empty range at a - /// multiple of the stride would hide the boundary from both of the pairs it belongs to, and the - /// ranges on its sides would be joined across the boundary. - auto extentEnd = [](size_t start, size_t end) { return std::max(end, start + 1); }; - const size_t initial_start = start_offset; - const size_t initial_end = extentEnd(start_offset, end_offset); - size_t left_edge_end = initial_end; - size_t right_edge_start = initial_start; - size_t right_edge_end = initial_end; + /// The range at the edge of the task on each side, for shouldCutBetween. They are the initial range, and + /// later the ranges included by the scans. In the splitting mode the initial range is only the subrange. + size_t left_edge_start = start_offset; + size_t left_edge_end = end_offset; + size_t right_edge_idx = range_idx; + size_t right_edge_start = start_offset; + size_t right_edge_end = end_offset; /// Go left. size_t initial_offset = start_offset; @@ -398,10 +469,10 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, { /// The alignment is checked only for a range that would actually be included: a cancelled /// range, or one that already has a task, must not stop the scan or count as a cut. - const size_t r_extent_end = extentEnd(r.start, r.end); - if (shouldCutBetween(r.start, std::max(r_extent_end, left_edge_end))) + if (shouldCutBetween(idx - 1, r.start, r.end, left_edge_start, left_edge_end)) break; - left_edge_end = r_extent_end; + left_edge_start = r.start; + left_edge_end = r.end; /// Include this range in the task. start_idx = idx - 1; @@ -438,11 +509,11 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, const auto s = r.request->state.load(std::memory_order_relaxed); if (s == RequestState::State::HasRange) { - const size_t r_extent_end = extentEnd(r.start, r.end); - if (shouldCutBetween(right_edge_start, std::max(right_edge_end, r_extent_end))) + if (shouldCutBetween(right_edge_idx, right_edge_start, right_edge_end, r.start, r.end)) break; + right_edge_idx = end_idx; right_edge_start = r.start; - right_edge_end = r_extent_end; + right_edge_end = r.end; end_idx = idx + 1; total_length_of_covered_ranges += r.length(); diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index bc3ff2288bbf..8ea045c99dfe 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -184,8 +184,8 @@ class Prefetcher size_t bytes_per_read_task{}; /// Read alignment: ranges are not merged into one task across a multiple of read_alignment_stride - /// (0 = off), unless the largest part of the merged read before a boundary (that of the last multiple - /// inside it) is smaller than read_alignment_min_bytes. A single requested range that crosses a + /// (0 = off), unless the piece of neighbouring ranges that the cut would leave before the last + /// multiple inside the merge is smaller than read_alignment_min_bytes. A single requested range that crosses a /// multiple is still read as one task. Set in init(), read-only after. size_t read_alignment_stride = 0; size_t read_alignment_min_bytes = 0; @@ -211,6 +211,14 @@ class Prefetcher /// If splitting, the request is being cancelled and replaced by a smaller range /// (splitAndPrefetchRange), and only subrange [subrange_start, subrange_end) needs to be read. void pickRangesAndCreateTaskIfNotExists(RequestState *, const PrefetchHandle &, bool splitting, size_t start_offset, size_t end_offset, std::unique_lock lock); + /// Read alignment, called with the mutex held. `ranges` is the sorted range set, `earlier_idx` is the index of + /// the earlier range of a pair of neighbouring ranges. The extents of the pair are passed explicitly, + /// because the range that starts a splitting task is smaller than its RangeState. + /// Whether the task has to be cut between the pair, see pickRangesAndCreateTaskIfNotExists. + bool shouldCutForAlignment(const std::vector & ranges, size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end, bool * skipped_small) const; + /// The start of the piece of neighbouring ranges that ends with the range `idx` and that would be one read + /// if the pair after it was cut. The walk stops as soon as the start is at or before `lower_bound`. + size_t alignmentPieceStart(const std::vector & ranges, size_t idx, size_t start, size_t end, size_t lower_bound) const; static void decreaseTaskRefcount(Task * task, size_t amount); void scheduleTask(Task * task); Task::State runTask(Task * task); diff --git a/tests/queries/0_stateless/05819_parquet_read_alignment.reference b/tests/queries/0_stateless/05819_parquet_read_alignment.reference index 2bb19c3e577b..11436d2187ab 100644 --- a/tests/queries/0_stateless/05819_parquet_read_alignment.reference +++ b/tests/queries/0_stateless/05819_parquet_read_alignment.reference @@ -2,13 +2,18 @@ 19999900000 99900000 17371400341328084350 1088890 1241267 6666566667 3879894 2666646666700000 -- aligned to a fixed grid: same result 19999900000 99900000 17371400341328084350 1088890 1241267 6666566667 3879894 2666646666700000 +-- aligned with a minimum that lets a short part straddle: same result +19999900000 99900000 17371400341328084350 1088890 1241267 6666566667 3879894 2666646666700000 -- aligned, but the part before the boundary is smaller than the minimum: same result 19999900000 99900000 17371400341328084350 1088890 1241267 6666566667 3879894 2666646666700000 -- read alignment engages only when enabled, and the minimum size guard skips it aligned 1 +guarded 1 off 1 small 1 -- off: coalescing happens and crosses the grid ok -- aligned: coalescing still happens, no coalesced task crosses the grid ok +-- guarded: no coalesced task contains a multiple of the stride with a part of at least the minimum before it +ok diff --git a/tests/queries/0_stateless/05819_parquet_read_alignment.sh b/tests/queries/0_stateless/05819_parquet_read_alignment.sh index 7a766b64de40..bbf4d3a8efdf 100755 --- a/tests/queries/0_stateless/05819_parquet_read_alignment.sh +++ b/tests/queries/0_stateless/05819_parquet_read_alignment.sh @@ -35,6 +35,7 @@ ${CLICKHOUSE_CLIENT} -q " STRUCTURE="k UInt64, a UInt32, b UInt64, s1 String, s2 String, d Float64, e String, f UInt64" STRIDE=262144 +GUARD_MIN=65536 # The large local-file seek threshold lets the prefetcher coalesce neighbouring column chunks. COMMON="input_format_parquet_use_native_reader_v3 = 1, input_format_parquet_local_file_min_bytes_for_seek = 1048576, max_threads = 4" @@ -47,11 +48,13 @@ run() " 2> "${WORKING_DIR}/$1.log" } -# Prints: the number of tasks that cover more than one requested range, and how many of them cross a multiple -# of ${STRIDE}. +# Prints: the number of tasks that cover more than one requested range, how many of them cross a multiple of +# ${STRIDE}, and how many of them contain a multiple of ${STRIDE} (not at the start of the task) with at least $2 +# bytes of the task before it, measured within one window of the grid (the part that the anti-fragmentation +# guard has to keep from being left as a separate read). count_tasks() { - awk -v stride=${STRIDE} ' + awk -v stride=${STRIDE} -v min_part="${2:-1}" ' /ParquetPrefetcher.*Read task: / { match($0, /offset=[0-9]+/); offset = substr($0, RSTART + 7, RLENGTH - 7) + 0; match($0, /length=[0-9]+/); length_ = substr($0, RSTART + 7, RLENGTH - 7) + 0; @@ -61,15 +64,27 @@ count_tasks() multi += 1; if (int(offset / stride) != int((offset + length_ - 1) / stride)) crossing += 1; + bad = 0; + for (b = (int(offset / stride) + 1) * stride; b < offset + length_; b += stride) + { + lo = b - stride; + if (offset > lo) + lo = offset; + if (b - lo >= min_part) + bad = 1; + } + violating += bad; } } - END { print multi + 0, crossing + 0 }' "${WORKING_DIR}/$1.log" + END { print multi + 0, crossing + 0, violating + 0 }' "${WORKING_DIR}/$1.log" } echo "-- read alignment off (default)" run off "input_format_parquet_read_alignment_bytes = 0" echo "-- aligned to a fixed grid: same result" run aligned "input_format_parquet_read_alignment_bytes = ${STRIDE}, input_format_parquet_read_alignment_min_bytes = 1" +echo "-- aligned with a minimum that lets a short part straddle: same result" +run guarded "input_format_parquet_read_alignment_bytes = ${STRIDE}, input_format_parquet_read_alignment_min_bytes = ${GUARD_MIN}" echo "-- aligned, but the part before the boundary is smaller than the minimum: same result" run small "input_format_parquet_read_alignment_bytes = ${STRIDE}, input_format_parquet_read_alignment_min_bytes = 1048576" @@ -81,6 +96,7 @@ ${CLICKHOUSE_CLIENT} -q " multiIf( name = 'off', ProfileEvents['ParquetPrefetcherPartAlignedTasks'] = 0 AND ProfileEvents['ParquetPrefetcherAlignmentSkippedSmall'] = 0, name = 'aligned', ProfileEvents['ParquetPrefetcherPartAlignedTasks'] > 0 AND ProfileEvents['ParquetPrefetcherAlignmentSkippedSmall'] = 0, + name = 'guarded', ProfileEvents['ParquetPrefetcherPartAlignedTasks'] > 0, ProfileEvents['ParquetPrefetcherPartAlignedTasks'] = 0 AND ProfileEvents['ParquetPrefetcherAlignmentSkippedSmall'] > 0) AS ok FROM system.query_log WHERE event_date >= yesterday() AND event_time >= now() - 600 @@ -89,12 +105,18 @@ ${CLICKHOUSE_CLIENT} -q " " # The control: without alignment, coalesced tasks do cross the multiples of the stride, so the check can fail. -read -r multi crossing < <(count_tasks off) +read -r multi crossing violating < <(count_tasks off ${GUARD_MIN}) echo "-- off: coalescing happens and crosses the grid" -[ "$multi" -gt 0 ] && [ "$crossing" -gt 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing" +[ "$multi" -gt 0 ] && [ "$crossing" -gt 0 ] && [ "$violating" -gt 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing violating=$violating" -read -r multi crossing < <(count_tasks aligned) +read -r multi crossing violating < <(count_tasks aligned 1) echo "-- aligned: coalescing still happens, no coalesced task crosses the grid" -[ "$multi" -gt 0 ] && [ "$crossing" -eq 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing" +[ "$multi" -gt 0 ] && [ "$crossing" -eq 0 ] && [ "$violating" -eq 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing violating=$violating" + +# A pair of neighbouring ranges can be a small part of a longer run of ranges that the cut would leave before the +# boundary: the guard has to measure the whole run, not only the range before the cut. +read -r multi crossing violating < <(count_tasks guarded ${GUARD_MIN}) +echo "-- guarded: no coalesced task contains a multiple of the stride with a part of at least the minimum before it" +[ "$multi" -gt 0 ] && [ "$violating" -eq 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing violating=$violating" rm -rf "${WORKING_DIR}" From 92401447de5e4080022d4c0340e7e948a0eac810 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Thu, 3 Dec 2026 11:32:42 +0100 Subject: [PATCH 14/30] Parquet v3 read alignment: say which limits of a task depend on the range that starts it The comment on the alignment decision said that the resulting tasks do not depend on which range of a chain starts the task. That is true for where the alignment cuts a pair, which now depends only on the ranges, but not for the other limits of a task: the gap of `min_bytes_for_seek`, the size of `bytes_per_read_task` and `allow_incidental_read` are checked against the range that starts the task, so the tasks can differ with the order in which the ranges are requested, with or without the alignment. Say so. In a simulation of the scan on 3000 random sets of up to 5 ranges, with every order of the starting ranges, the tasks depend on the order in 382 sets without the alignment, in 20 sets with the alignment, and in 3 sets only with the alignment. Those 3 depend on the gap or size limit as well. Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 235e2258f75b..84db6eb5625d 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -423,11 +423,16 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, /// splitting). /// /// The decision is made for each pair of neighbouring ranges (in the order of their start offsets) - /// that would be joined in the task, and depends only on the pair, so the resulting tasks don't depend - /// on which range of a chain starts the task. The pair is cut when a multiple of the stride lies - /// strictly inside the pair's joint span, including when one of the ranges crosses it on its own: - /// the ranges of a file are usually contiguous, so then every multiple of the stride lies inside some - /// range, and a rule that looks only at boundaries between the ranges would never cut. + /// that would be joined in the task. It depends on the pair and on the ranges before it, but not on which + /// range starts the task, so the scan going left and the scan going right cut at the same places. The + /// other limits of a task still depend on the range that starts it (the gap of min_bytes_for_seek, the + /// size of bytes_per_read_task, allow_incidental_read), so the tasks can differ with the order in which + /// the ranges are requested, with or without the alignment. + /// + /// The pair is cut when a multiple of the stride lies strictly inside the pair's joint span, including + /// when one of the ranges crosses it on its own: the ranges of a file are usually contiguous, so then + /// every multiple of the stride lies inside some range, and a rule that looks only at boundaries + /// between the ranges would never cut. /// /// Anti-fragmentation: cutting leaves the piece of neighbouring ranges before a boundary as a separate /// read. If the part of that piece before the last boundary inside the joint span is smaller than From 2bf4dee94d4078d8ee569a843de35c5eb6172751 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Thu, 3 Dec 2026 11:53:49 +0100 Subject: [PATCH 15/30] Parquet v3: stop the alignment piece walk at ranges that are not read incidentally `Prefetcher::alignmentPieceStart` ignored `allow_incidental_read`, which the scans in `pickRangesAndCreateTaskIfNotExists` honour. A non-incidental range was counted into the piece, so the guard overestimated the length of the task left before the boundary and a cut could leave a part smaller than `input_format_parquet_read_alignment_min_bytes`. Stop the walk at such a range, like the left scan does. Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 84db6eb5625d..d6c5324a63ab 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -348,10 +348,10 @@ size_t Prefetcher::alignmentPieceStart(const std::vector & ranges, s { /// Walk to the left over the ranges that the scan in pickRangesAndCreateTaskIfNotExists would join into one /// task with this one, with the same checks: skip the cancelled ranges, stop at a range that already has a - /// task, at a gap of min_bytes_for_seek, and at a pair that is cut. The result depends only on the ranges - /// and not on the range that starts the task, so the decision for a pair is the same for the scan going - /// left and the scan going right. (The limit on the size of the task is not applied, because it depends on - /// the range that starts the task.) + /// task, at a range that does not want to be read incidentally, at a gap of min_bytes_for_seek, and at a + /// pair that is cut. The result depends only on the ranges and not on the range that starts the task, so + /// the decision for a pair is the same for the scan going left and the scan going right. (The limit on the + /// size of the task is not applied, because it depends on the range that starts the task.) size_t piece_start = start; size_t later_start = start; size_t later_end = end; @@ -370,8 +370,13 @@ size_t Prefetcher::alignmentPieceStart(const std::vector & ranges, s if (s != RequestState::State::HasRange) return piece_start; + /// The scans never include such a range into the task of another range, and a range that starts a task + /// always allows it (see startPrefetch), so a task never continues over it. Counting it into the piece + /// would make the piece longer than the task that is left before the boundary, and the guard would let + /// a cut leave a part smaller than read_alignment_min_bytes. const RangeState & earlier = ranges[earlier_idx]; - if (earlier.end + min_bytes_for_seek <= piece_start + if (!earlier.request->allow_incidental_read.load(std::memory_order_relaxed) + || earlier.end + min_bytes_for_seek <= piece_start || shouldCutForAlignment(ranges, earlier_idx, earlier.start, earlier.end, later_start, later_end, /*skipped_small=*/ nullptr)) return piece_start; From 9fdb9511ff27418006ef39350432da7688b7c543 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Thu, 3 Dec 2026 11:56:41 +0100 Subject: [PATCH 16/30] Parquet v3: document that a minimum larger than the alignment stride disables the cut With `input_format_parquet_read_alignment_min_bytes` larger than `input_format_parquet_read_alignment_bytes` the part before the boundary is measured within one stride and is always smaller than the minimum, so no merge is ever cut. State this in the setting description, together with the meaning of 0. Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- src/Core/FormatFactorySettings.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index e3856b06a0df..1957a011b202 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -240,7 +240,7 @@ Minor tweak to how pages are read from parquet file when no page filtering is us Experimental. When the Parquet v3 reader merges neighbouring requested ranges (for example column chunks) into one read, do not merge across a multiple of this size. Set it to the writer's multipart part size (for example 10Mi for delta-rs, 64Mi for Spark/S3A) to avoid merged reads that span two parts of a multipart-uploaded object. Only the merging is limited: a single requested range that crosses a multiple of this size is still read as one request, and `input_format_parquet_read_alignment_min_bytes` can allow a merged read to cross it too. 0 disables. )", 0) \ DECLARE(UInt64, input_format_parquet_read_alignment_min_bytes, 1048576, R"( -Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a merge at a boundary when the part before the boundary of the run of neighbouring ranges that the cut would leave (within one multiple of the size) is smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. Default 1 MiB. +Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a merge at a boundary when the part before the boundary of the run of neighbouring ranges that the cut would leave (within one multiple of the size) is smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. The part is measured within one multiple of `input_format_parquet_read_alignment_bytes`, so if this value is larger than `input_format_parquet_read_alignment_bytes`, no merge is ever cut and the alignment is effectively off. 0 disables the guard. Default 1 MiB. )", 0) \ DECLARE(Bool, input_format_parquet_verify_checksums, true, R"( Verify page checksums when reading parquet files. From 4706cf66cd00f2d24c22a04bb73fad67dfe2e32c Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Thu, 3 Dec 2026 12:24:22 +0100 Subject: [PATCH 17/30] Parquet v3 read alignment: do not recurse exponentially over ranges that cross the same boundary `Prefetcher::alignmentPieceStart` calls `shouldCutForAlignment` for every pair on its walk, and that calls `alignmentPieceStart` again. For ranges that overlap and cross the same multiple of `input_format_parquet_read_alignment_bytes` closer to it than `input_format_parquet_read_alignment_min_bytes`, every pair starts the walk over all the pairs before it, so the work doubles with each range: 48 columns whose chunks are the same bytes would hold `Prefetcher::mutex` for longer than any query timeout. A pair on the walk that crosses the same boundary as the pair being decided already decides it: cut or skipped, the part before the boundary is too small. Stop the walk there. It gives the same decisions (checked on 60000 random layouts with a port of the logic) and the work is linear in the number of ranges. The test reads a file whose columns all point to the same chunk. Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 47 +++++-- .../Formats/Impl/Parquet/Prefetcher.h | 5 +- ...ead_alignment_overlapping_ranges.reference | 6 + ...rquet_read_alignment_overlapping_ranges.sh | 123 ++++++++++++++++++ 4 files changed, 167 insertions(+), 14 deletions(-) create mode 100644 tests/queries/0_stateless/05821_parquet_read_alignment_overlapping_ranges.reference create mode 100755 tests/queries/0_stateless/05821_parquet_read_alignment_overlapping_ranges.sh diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index d6c5324a63ab..6fb682641bc1 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -9,6 +9,7 @@ #include #include +#include #include namespace DB::ErrorCodes @@ -303,27 +304,37 @@ static size_t extentEnd(size_t start, size_t end) return std::max(end, start + 1); } +/// The joint span [earlier_start, joint_end) of a pair crosses a multiple of the stride iff its first and last +/// bytes are in different windows of the grid. This includes the case when one of the ranges crosses the multiple +/// on its own. Returns the last multiple of the stride inside the joint span (it is after earlier_start), or +/// nullopt if the span does not cross any. +static std::optional lastCrossedBoundary( + size_t stride, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end) +{ + const size_t joint_end = std::max(extentEnd(earlier_start, earlier_end), extentEnd(later_start, later_end)); + const size_t last_window = (joint_end - 1) / stride; + if (earlier_start / stride == last_window) + return std::nullopt; + return last_window * stride; +} + bool Prefetcher::shouldCutForAlignment( const std::vector & ranges, size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end, bool * skipped_small) const { chassert(read_alignment_stride > 0); - /// The joint span [earlier_start, joint_end) crosses a multiple of the stride iff its first and last - /// bytes are in different windows of the grid. This includes the case when one of the ranges crosses - /// the multiple on its own. - const size_t joint_end = std::max(extentEnd(earlier_start, earlier_end), extentEnd(later_start, later_end)); - const size_t last_window = (joint_end - 1) / read_alignment_stride; - if (earlier_start / read_alignment_stride == last_window) + const auto crossed_boundary = lastCrossedBoundary(read_alignment_stride, earlier_start, earlier_end, later_start, later_end); + if (!crossed_boundary) return false; if (read_alignment_min_bytes == 0) return true; - /// The last multiple of the stride inside the joint span; it is after earlier_start. The part of a read - /// before a multiple b of the stride is measured within one window of the grid, as b - max(start, b - stride). - /// It does not decrease in b, so the last multiple leaves the largest part. - const size_t last_boundary = last_window * read_alignment_stride; + /// The part of a read before a multiple b of the stride is measured within one window of the grid, as + /// b - max(start, b - stride). It does not decrease in b, so the last multiple inside the joint span leaves + /// the largest part. + const size_t last_boundary = *crossed_boundary; /// Cutting leaves the piece of neighbouring ranges that ends with the earlier range. The piece may be /// longer than the earlier range, so measure it from its start: the part is at least read_alignment_min_bytes @@ -332,7 +343,7 @@ bool Prefetcher::shouldCutForAlignment( if (read_alignment_min_bytes <= read_alignment_stride) { const size_t lower_bound = last_boundary >= read_alignment_min_bytes ? last_boundary - read_alignment_min_bytes : 0; - const size_t piece_start = alignmentPieceStart(ranges, earlier_idx, earlier_start, earlier_end, lower_bound); + const size_t piece_start = alignmentPieceStart(ranges, earlier_idx, earlier_start, earlier_end, last_boundary, lower_bound); small = std::min(read_alignment_stride, last_boundary - piece_start) < read_alignment_min_bytes; } if (small) @@ -344,7 +355,8 @@ bool Prefetcher::shouldCutForAlignment( return true; } -size_t Prefetcher::alignmentPieceStart(const std::vector & ranges, size_t idx, size_t start, size_t end, size_t lower_bound) const +size_t Prefetcher::alignmentPieceStart( + const std::vector & ranges, size_t idx, size_t start, size_t end, size_t last_boundary, size_t lower_bound) const { /// Walk to the left over the ranges that the scan in pickRangesAndCreateTaskIfNotExists would join into one /// task with this one, with the same checks: skip the cancelled ranges, stop at a range that already has a @@ -352,6 +364,16 @@ size_t Prefetcher::alignmentPieceStart(const std::vector & ranges, s /// pair that is cut. The result depends only on the ranges and not on the range that starts the task, so /// the decision for a pair is the same for the scan going left and the scan going right. (The limit on the /// size of the task is not applied, because it depends on the range that starts the task.) + /// + /// The pair that is cut or skipped on the way is decided by the recursion into shouldCutForAlignment. When + /// that pair crosses the same boundary as the pair being decided, the answer is known without it: if it is + /// cut, the piece starts after it, at piece_start, which is still after lower_bound; if it is skipped, its + /// own piece is the one that this walk would find, and it is also after lower_bound, because the lower bound + /// is the same for the same boundary. In both cases the part is too small, so the walk stops here. Without + /// this, ranges that overlap and cross the same boundary (a malformed file) make the recursion exponential + /// in their number. A pair that crosses an earlier boundary, at least one stride before last_boundary, + /// ends the walk after this recursion: if it is skipped, the piece starts before that boundary, which is at or + /// before lower_bound. size_t piece_start = start; size_t later_start = start; size_t later_end = end; @@ -377,6 +399,7 @@ size_t Prefetcher::alignmentPieceStart(const std::vector & ranges, s const RangeState & earlier = ranges[earlier_idx]; if (!earlier.request->allow_incidental_read.load(std::memory_order_relaxed) || earlier.end + min_bytes_for_seek <= piece_start + || lastCrossedBoundary(read_alignment_stride, earlier.start, earlier.end, later_start, later_end) == last_boundary || shouldCutForAlignment(ranges, earlier_idx, earlier.start, earlier.end, later_start, later_end, /*skipped_small=*/ nullptr)) return piece_start; diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index 8ea045c99dfe..c6385cf588f7 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -217,8 +217,9 @@ class Prefetcher /// Whether the task has to be cut between the pair, see pickRangesAndCreateTaskIfNotExists. bool shouldCutForAlignment(const std::vector & ranges, size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end, bool * skipped_small) const; /// The start of the piece of neighbouring ranges that ends with the range `idx` and that would be one read - /// if the pair after it was cut. The walk stops as soon as the start is at or before `lower_bound`. - size_t alignmentPieceStart(const std::vector & ranges, size_t idx, size_t start, size_t end, size_t lower_bound) const; + /// if the pair after it was cut. The walk stops as soon as the start is at or before `lower_bound`, or when it + /// meets a pair that crosses `last_boundary`, the boundary of the pair that is being decided. + size_t alignmentPieceStart(const std::vector & ranges, size_t idx, size_t start, size_t end, size_t last_boundary, size_t lower_bound) const; static void decreaseTaskRefcount(Task * task, size_t amount); void scheduleTask(Task * task); Task::State runTask(Task * task); diff --git a/tests/queries/0_stateless/05821_parquet_read_alignment_overlapping_ranges.reference b/tests/queries/0_stateless/05821_parquet_read_alignment_overlapping_ranges.reference new file mode 100644 index 000000000000..594400c339f9 --- /dev/null +++ b/tests/queries/0_stateless/05821_parquet_read_alignment_overlapping_ranges.reference @@ -0,0 +1,6 @@ +-- read alignment off +11592660891735614522 +-- aligned, the minimum is equal to the stride +11592660891735614522 +-- aligned, the minimum is 1 +11592660891735614522 diff --git a/tests/queries/0_stateless/05821_parquet_read_alignment_overlapping_ranges.sh b/tests/queries/0_stateless/05821_parquet_read_alignment_overlapping_ranges.sh new file mode 100755 index 000000000000..92cb65c6f795 --- /dev/null +++ b/tests/queries/0_stateless/05821_parquet_read_alignment_overlapping_ranges.sh @@ -0,0 +1,123 @@ +#!/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}/overlapping.parquet" + +# The column chunks of a Parquet file are not supposed to overlap, but the reader does not check it. Many columns +# whose chunks are the same bytes give many identical ranges that all cross a multiple of +# `input_format_parquet_read_alignment_bytes` and start less than `input_format_parquet_read_alignment_min_bytes` +# before it. The decision to cut the coalescing must stay fast for them: its cost must not grow exponentially with +# the number of such ranges. +python3 - "${DATA_FILE}" <<'EOF' +import struct +import sys + +COLUMNS = 48 +ROWS = 40000 # 320000 bytes: the chunk starts at offset 4 and crosses the multiple 262144 + +def varint(n): + out = bytearray() + while True: + b = n & 0x7F + n >>= 7 + if n: + out.append(b | 0x80) + else: + out.append(b) + return bytes(out) + +def zigzag(n): + return varint((n << 1) ^ (n >> 63)) + +# Thrift compact protocol: a struct is a list of (field id, type, encoded value) in the order of ids. +I32, I64, BINARY, LIST, STRUCT = 5, 6, 8, 9, 12 + +def struct_(fields): + out = bytearray() + last = 0 + for fid, ftype, value in sorted(fields, key=lambda f: f[0]): + out.append(((fid - last) << 4) | ftype) # all ids here are consecutive or within 15 + out += value + last = fid + out.append(0) + return bytes(out) + +def i32(n): return zigzag(n) +def i64(n): return zigzag(n) +def string(s): return varint(len(s)) + s.encode() +def list_(elem_type, items): + assert len(items) >= 15 + return bytes([0xF0 | elem_type]) + varint(len(items)) + b"".join(items) +def small_list(elem_type, items): + assert len(items) < 15 + return bytes([(len(items) << 4) | elem_type]) + b"".join(items) + +values = struct.pack("<%dq" % ROWS, *range(ROWS)) +page_header = struct_([ + (1, I32, i32(0)), # DATA_PAGE + (2, I32, i32(len(values))), # uncompressed_page_size + (3, I32, i32(len(values))), # compressed_page_size + (5, STRUCT, struct_([ + (1, I32, i32(ROWS)), # num_values + (2, I32, i32(0)), # PLAIN + (3, I32, i32(3)), # RLE + (4, I32, i32(3)), # RLE + ])), +]) +chunk = page_header + values +chunk_offset = 4 + +names = ["c%d" % i for i in range(COLUMNS)] +schema = [struct_([(4, BINARY, string("schema")), (5, I32, i32(COLUMNS))])] +for name in names: + schema.append(struct_([(1, I32, i32(2)), (3, I32, i32(0)), (4, BINARY, string(name))])) # INT64, REQUIRED + +def column_chunk(name): + meta = struct_([ + (1, I32, i32(2)), # INT64 + (2, LIST, small_list(I32, [i32(0)])), # encodings: PLAIN + (3, LIST, small_list(BINARY, [string(name)])), # path_in_schema + (4, I32, i32(0)), # UNCOMPRESSED + (5, I64, i64(ROWS)), # num_values + (6, I64, i64(len(chunk))), # total_uncompressed_size + (7, I64, i64(len(chunk))), # total_compressed_size + (9, I64, i64(chunk_offset)), # data_page_offset: the same for all columns + ]) + return struct_([(2, I64, i64(chunk_offset)), (3, STRUCT, meta)]) + +row_group = struct_([ + (1, LIST, list_(STRUCT, [column_chunk(name) for name in names])), + (2, I64, i64(len(chunk))), + (3, I64, i64(ROWS)), +]) +file_metadata = struct_([ + (1, I32, i32(1)), + (2, LIST, list_(STRUCT, schema)), + (3, I64, i64(ROWS)), + (4, LIST, small_list(STRUCT, [row_group])), + (6, BINARY, string("test")), +]) + +with open(sys.argv[1], "wb") as f: + f.write(b"PAR1" + chunk + file_metadata + struct.pack(" Date: Thu, 3 Dec 2026 12:31:36 +0100 Subject: [PATCH 18/30] Parquet v3: keep the logger of `Prefetcher` in a member `LOG_TEST(getLogger("ParquetPrefetcher"), ...)` in `pickRangesAndCreateTaskIfNotExists` looked the logger up by name, which takes a global lock, for every task even when nothing is logged. Look it up once. Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- src/Processors/Formats/Impl/Parquet/Prefetcher.cpp | 2 +- src/Processors/Formats/Impl/Parquet/Prefetcher.h | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 6fb682641bc1..d75c506aaa04 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -594,7 +594,7 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, lock.unlock(); - LOG_TEST(getLogger("ParquetPrefetcher"), "Read task: offset={} length={} ranges={} alignment_bytes={}", + LOG_TEST(log, "Read task: offset={} length={} ranges={} alignment_bytes={}", task.offset, task.length, actual_refcount, read_alignment_stride); scheduleTask(&task); diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index c6385cf588f7..09e387a94fbd 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include @@ -190,6 +191,9 @@ class Prefetcher size_t read_alignment_stride = 0; size_t read_alignment_min_bytes = 0; + /// Looking a logger up by name takes a global lock, so it is done once, not for each task. + LoggerPtr log = getLogger("ParquetPrefetcher"); + std::shared_ptr shutdown = std::make_shared(); /// Locked when creating a Task. From 97974a2ca570c3d5e6453db88666c1911cb5e47a Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Thu, 3 Dec 2026 14:46:08 +0100 Subject: [PATCH 19/30] Parquet v3: measure the fragment actually left by the alignment cut The anti-fragmentation guard of `input_format_parquet_read_alignment_bytes` measured the part before the last multiple of the stride inside the joint span of a pair. When the later range spans several windows of the grid, that multiple can be far after the end of the earlier range, so the guard counted bytes of the later range, which the cut does not leave in the piece before it. A short range followed by a long one was cut anyway, and the short range was read as a tiny separate request. Measure the part up to the end of the earlier range when it is before the boundary. The same-boundary shortcut of the walk over the neighbouring ranges now needs the earlier range to reach that boundary, and the decisions of the walk are remembered for the scan, so that the cost stays polynomial for overlapping ranges. The check of the guard in `05819_parquet_read_alignment` now looks at the fragments that the cuts leave, instead of the bytes of a task before a multiple of the stride, which include the bytes of the later range. A new test `05825_parquet_read_alignment_short_range_before_long` covers the layout from the review. Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 81 ++++++---- .../Formats/Impl/Parquet/Prefetcher.h | 14 +- .../05819_parquet_read_alignment.reference | 4 +- .../05819_parquet_read_alignment.sh | 59 ++++--- ...lignment_short_range_before_long.reference | 6 + ..._read_alignment_short_range_before_long.sh | 151 ++++++++++++++++++ 6 files changed, 259 insertions(+), 56 deletions(-) create mode 100644 tests/queries/0_stateless/05825_parquet_read_alignment_short_range_before_long.reference create mode 100755 tests/queries/0_stateless/05825_parquet_read_alignment_short_range_before_long.sh diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index d75c506aaa04..31edbefd5343 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -320,7 +320,7 @@ static std::optional lastCrossedBoundary( bool Prefetcher::shouldCutForAlignment( const std::vector & ranges, size_t earlier_idx, size_t earlier_start, size_t earlier_end, - size_t later_start, size_t later_end, bool * skipped_small) const + size_t later_start, size_t later_end, bool * skipped_small, AlignmentDecisions & decisions) const { chassert(read_alignment_stride > 0); @@ -331,20 +331,25 @@ bool Prefetcher::shouldCutForAlignment( if (read_alignment_min_bytes == 0) return true; - /// The part of a read before a multiple b of the stride is measured within one window of the grid, as - /// b - max(start, b - stride). It does not decrease in b, so the last multiple inside the joint span leaves - /// the largest part. + /// Cutting leaves the piece of neighbouring ranges that ends with the earlier range as a separate read. + /// The part of the piece that the guard measures is the part inside one window of the grid, up to the + /// boundary or up to the end of the earlier range, whichever comes first: the later range, which may + /// span many windows, is not left in the piece, so the bytes after the earlier range do not count. (The + /// piece can end after the earlier range if some range before it overlaps it. This is not counted, + /// which makes the guard skip the cut more often, never less.) Among the boundaries inside the joint span + /// the last one leaves the largest part, because the part does not decrease in the boundary. const size_t last_boundary = *crossed_boundary; + const size_t part_end = std::min(last_boundary, earlier_end); - /// Cutting leaves the piece of neighbouring ranges that ends with the earlier range. The piece may be - /// longer than the earlier range, so measure it from its start: the part is at least read_alignment_min_bytes - /// iff the piece starts at or before last_boundary - read_alignment_min_bytes. + /// The piece may be longer than the earlier range, so measure it from its start: the part is at least + /// read_alignment_min_bytes iff the piece starts at or before part_end - read_alignment_min_bytes. bool small = true; if (read_alignment_min_bytes <= read_alignment_stride) { - const size_t lower_bound = last_boundary >= read_alignment_min_bytes ? last_boundary - read_alignment_min_bytes : 0; - const size_t piece_start = alignmentPieceStart(ranges, earlier_idx, earlier_start, earlier_end, last_boundary, lower_bound); - small = std::min(read_alignment_stride, last_boundary - piece_start) < read_alignment_min_bytes; + const size_t lower_bound = part_end >= read_alignment_min_bytes ? part_end - read_alignment_min_bytes : 0; + const size_t piece_start = alignmentPieceStart( + ranges, earlier_idx, earlier_start, earlier_end, last_boundary, lower_bound, decisions); + small = std::min(read_alignment_stride, part_end - piece_start) < read_alignment_min_bytes; } if (small) { @@ -356,7 +361,8 @@ bool Prefetcher::shouldCutForAlignment( } size_t Prefetcher::alignmentPieceStart( - const std::vector & ranges, size_t idx, size_t start, size_t end, size_t last_boundary, size_t lower_bound) const + const std::vector & ranges, size_t idx, size_t start, size_t end, size_t last_boundary, size_t lower_bound, + AlignmentDecisions & decisions) const { /// Walk to the left over the ranges that the scan in pickRangesAndCreateTaskIfNotExists would join into one /// task with this one, with the same checks: skip the cancelled ranges, stop at a range that already has a @@ -365,15 +371,15 @@ size_t Prefetcher::alignmentPieceStart( /// the decision for a pair is the same for the scan going left and the scan going right. (The limit on the /// size of the task is not applied, because it depends on the range that starts the task.) /// - /// The pair that is cut or skipped on the way is decided by the recursion into shouldCutForAlignment. When - /// that pair crosses the same boundary as the pair being decided, the answer is known without it: if it is - /// cut, the piece starts after it, at piece_start, which is still after lower_bound; if it is skipped, its - /// own piece is the one that this walk would find, and it is also after lower_bound, because the lower bound - /// is the same for the same boundary. In both cases the part is too small, so the walk stops here. Without - /// this, ranges that overlap and cross the same boundary (a malformed file) make the recursion exponential - /// in their number. A pair that crosses an earlier boundary, at least one stride before last_boundary, - /// ends the walk after this recursion: if it is skipped, the piece starts before that boundary, which is at or - /// before lower_bound. + /// Whether the pair on the way is cut is decided by the recursion into shouldCutForAlignment. Its result + /// depends only on the pair, so it is remembered in `decisions` for the whole scan: otherwise ranges that + /// overlap (a malformed file) make the recursion exponential in their number. + /// + /// When that pair crosses the same boundary as the pair being decided, and the earlier range reaches that + /// boundary, the answer is known without the recursion: if the pair is cut, the piece starts after it, at + /// piece_start; if it is skipped, its own piece is the one that this walk would find, and it measures up to + /// the boundary, which is not less than the part measured here. In both cases the part is too small, so + /// the walk stops here, with a start that is after lower_bound. size_t piece_start = start; size_t later_start = start; size_t later_end = end; @@ -398,9 +404,28 @@ size_t Prefetcher::alignmentPieceStart( /// a cut leave a part smaller than read_alignment_min_bytes. const RangeState & earlier = ranges[earlier_idx]; if (!earlier.request->allow_incidental_read.load(std::memory_order_relaxed) - || earlier.end + min_bytes_for_seek <= piece_start - || lastCrossedBoundary(read_alignment_stride, earlier.start, earlier.end, later_start, later_end) == last_boundary - || shouldCutForAlignment(ranges, earlier_idx, earlier.start, earlier.end, later_start, later_end, /*skipped_small=*/ nullptr)) + || earlier.end + min_bytes_for_seek <= piece_start) + return piece_start; + + const auto crossed_boundary = lastCrossedBoundary(read_alignment_stride, earlier.start, earlier.end, later_start, later_end); + if (crossed_boundary == last_boundary && earlier.end >= last_boundary) + return piece_start; + + bool cut = false; + if (crossed_boundary) + { + const AlignmentDecisionKey key{earlier_idx, later_start, later_end}; + auto it = decisions.find(key); + if (it == decisions.end()) + { + cut = shouldCutForAlignment( + ranges, earlier_idx, earlier.start, earlier.end, later_start, later_end, /*skipped_small=*/ nullptr, decisions); + decisions.emplace(key, cut); + } + else + cut = it->second; + } + if (cut) return piece_start; piece_start = std::min(piece_start, earlier.start); @@ -462,18 +487,20 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, /// every multiple of the stride lies inside some range, and a rule that looks only at boundaries /// between the ranges would never cut. /// - /// Anti-fragmentation: cutting leaves the piece of neighbouring ranges before a boundary as a separate - /// read. If the part of that piece before the last boundary inside the joint span is smaller than - /// read_alignment_min_bytes, don't cut, allow the straddle instead. See shouldCutForAlignment. + /// Anti-fragmentation: cutting leaves the piece of neighbouring ranges that ends with the earlier range + /// as a separate read. If the part of that piece before the last boundary inside the joint span (and before + /// the end of the earlier range) is smaller than read_alignment_min_bytes, don't cut, allow the straddle + /// instead. See shouldCutForAlignment. const bool alignment_active = read_alignment_stride > 0; bool part_boundary_constrained = false; bool skipped_small = false; + AlignmentDecisions alignment_decisions; auto shouldCutBetween = [&](size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end) { if (!alignment_active) return false; - if (!shouldCutForAlignment(ranges, earlier_idx, earlier_start, earlier_end, later_start, later_end, &skipped_small)) + if (!shouldCutForAlignment(ranges, earlier_idx, earlier_start, earlier_end, later_start, later_end, &skipped_small, alignment_decisions)) return false; part_boundary_constrained = true; return true; diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index 09e387a94fbd..2a248d985e90 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -4,8 +4,10 @@ #include #include +#include #include #include +#include namespace DB { @@ -219,11 +221,17 @@ class Prefetcher /// the earlier range of a pair of neighbouring ranges. The extents of the pair are passed explicitly, /// because the range that starts a splitting task is smaller than its RangeState. /// Whether the task has to be cut between the pair, see pickRangesAndCreateTaskIfNotExists. - bool shouldCutForAlignment(const std::vector & ranges, size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end, bool * skipped_small) const; + /// The results of shouldCutForAlignment for the pairs met by the walks in alignmentPieceStart, during one + /// pickRangesAndCreateTaskIfNotExists. The key is the earlier range and the extent of the later one + /// (the extent of the later one is not always its RangeState, see above). + using AlignmentDecisionKey = std::tuple; + using AlignmentDecisions = std::map; + bool shouldCutForAlignment(const std::vector & ranges, size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end, bool * skipped_small, AlignmentDecisions & decisions) const; /// The start of the piece of neighbouring ranges that ends with the range `idx` and that would be one read /// if the pair after it was cut. The walk stops as soon as the start is at or before `lower_bound`, or when it - /// meets a pair that crosses `last_boundary`, the boundary of the pair that is being decided. - size_t alignmentPieceStart(const std::vector & ranges, size_t idx, size_t start, size_t end, size_t last_boundary, size_t lower_bound) const; + /// meets a pair that is cut, or that crosses `last_boundary`, the boundary of the pair that is being decided, + /// with its earlier range reaching it. + size_t alignmentPieceStart(const std::vector & ranges, size_t idx, size_t start, size_t end, size_t last_boundary, size_t lower_bound, AlignmentDecisions & decisions) const; static void decreaseTaskRefcount(Task * task, size_t amount); void scheduleTask(Task * task); Task::State runTask(Task * task); diff --git a/tests/queries/0_stateless/05819_parquet_read_alignment.reference b/tests/queries/0_stateless/05819_parquet_read_alignment.reference index 11436d2187ab..ea4476a99971 100644 --- a/tests/queries/0_stateless/05819_parquet_read_alignment.reference +++ b/tests/queries/0_stateless/05819_parquet_read_alignment.reference @@ -15,5 +15,7 @@ small 1 ok -- aligned: coalescing still happens, no coalesced task crosses the grid ok --- guarded: no coalesced task contains a multiple of the stride with a part of at least the minimum before it +-- aligned: the cuts leave fragments shorter than the minimum +ok +-- guarded: no cut leaves a fragment shorter than the minimum ok diff --git a/tests/queries/0_stateless/05819_parquet_read_alignment.sh b/tests/queries/0_stateless/05819_parquet_read_alignment.sh index bbf4d3a8efdf..212c33923ea4 100755 --- a/tests/queries/0_stateless/05819_parquet_read_alignment.sh +++ b/tests/queries/0_stateless/05819_parquet_read_alignment.sh @@ -48,13 +48,11 @@ run() " 2> "${WORKING_DIR}/$1.log" } -# Prints: the number of tasks that cover more than one requested range, how many of them cross a multiple of -# ${STRIDE}, and how many of them contain a multiple of ${STRIDE} (not at the start of the task) with at least $2 -# bytes of the task before it, measured within one window of the grid (the part that the anti-fragmentation -# guard has to keep from being left as a separate read). +# Prints: the number of tasks that cover more than one requested range, and how many of them cross a multiple of +# ${STRIDE}. (The third number is for the checks of the guard, see count_fragments.) count_tasks() { - awk -v stride=${STRIDE} -v min_part="${2:-1}" ' + awk -v stride=${STRIDE} ' /ParquetPrefetcher.*Read task: / { match($0, /offset=[0-9]+/); offset = substr($0, RSTART + 7, RLENGTH - 7) + 0; match($0, /length=[0-9]+/); length_ = substr($0, RSTART + 7, RLENGTH - 7) + 0; @@ -64,19 +62,25 @@ count_tasks() multi += 1; if (int(offset / stride) != int((offset + length_ - 1) / stride)) crossing += 1; - bad = 0; - for (b = (int(offset / stride) + 1) * stride; b < offset + length_; b += stride) - { - lo = b - stride; - if (offset > lo) - lo = offset; - if (b - lo >= min_part) - bad = 1; - } - violating += bad; } } - END { print multi + 0, crossing + 0, violating + 0 }' "${WORKING_DIR}/$1.log" + END { print multi + 0, crossing + 0 }' "${WORKING_DIR}/$1.log" +} + +# Prints the number of tasks that are shorter than $2 bytes and are followed by another task closer than +# the seek threshold: the fragment that a cut leaves before the next task. (The task that ends the data is +# followed by the tasks of the metadata far after it.) The anti-fragmentation guard must not leave such a +# fragment: the cut that does is skipped. +count_fragments() +{ + awk ' + /ParquetPrefetcher.*Read task: / { + match($0, /offset=[0-9]+/); offset = substr($0, RSTART + 7, RLENGTH - 7) + 0; + match($0, /length=[0-9]+/); length_ = substr($0, RSTART + 7, RLENGTH - 7) + 0; + print offset, length_ + }' "${WORKING_DIR}/$1.log" \ + | sort -n \ + | awk -v min_part="$2" 'NR > 1 && $1 >= prev_end && $1 - prev_end < 1048576 && prev_length < min_part { n += 1 } { prev_end = $1 + $2; prev_length = $2 } END { print n + 0 }' } echo "-- read alignment off (default)" @@ -105,18 +109,23 @@ ${CLICKHOUSE_CLIENT} -q " " # The control: without alignment, coalesced tasks do cross the multiples of the stride, so the check can fail. -read -r multi crossing violating < <(count_tasks off ${GUARD_MIN}) +read -r multi crossing < <(count_tasks off) echo "-- off: coalescing happens and crosses the grid" -[ "$multi" -gt 0 ] && [ "$crossing" -gt 0 ] && [ "$violating" -gt 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing violating=$violating" +[ "$multi" -gt 0 ] && [ "$crossing" -gt 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing" -read -r multi crossing violating < <(count_tasks aligned 1) +read -r multi crossing < <(count_tasks aligned) echo "-- aligned: coalescing still happens, no coalesced task crosses the grid" -[ "$multi" -gt 0 ] && [ "$crossing" -eq 0 ] && [ "$violating" -eq 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing violating=$violating" +[ "$multi" -gt 0 ] && [ "$crossing" -eq 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing" + +# The control: when every pair is cut, the fragments before the cuts are short. +echo "-- aligned: the cuts leave fragments shorter than the minimum" +fragments=$(count_fragments aligned ${GUARD_MIN}) +[ "$fragments" -gt 0 ] && echo "ok" || echo "fail: fragments=$fragments" -# A pair of neighbouring ranges can be a small part of a longer run of ranges that the cut would leave before the -# boundary: the guard has to measure the whole run, not only the range before the cut. -read -r multi crossing violating < <(count_tasks guarded ${GUARD_MIN}) -echo "-- guarded: no coalesced task contains a multiple of the stride with a part of at least the minimum before it" -[ "$multi" -gt 0 ] && [ "$violating" -eq 0 ] && echo "ok" || echo "fail: multi=$multi crossing=$crossing violating=$violating" +# A fragment that a cut leaves may be a run of several neighbouring ranges: the guard has to measure the whole run, +# not only the range before the cut. +echo "-- guarded: no cut leaves a fragment shorter than the minimum" +fragments=$(count_fragments guarded ${GUARD_MIN}) +[ "$fragments" -eq 0 ] && echo "ok" || echo "fail: fragments=$fragments" rm -rf "${WORKING_DIR}" diff --git a/tests/queries/0_stateless/05825_parquet_read_alignment_short_range_before_long.reference b/tests/queries/0_stateless/05825_parquet_read_alignment_short_range_before_long.reference new file mode 100644 index 000000000000..231972ebcbd4 --- /dev/null +++ b/tests/queries/0_stateless/05825_parquet_read_alignment_short_range_before_long.reference @@ -0,0 +1,6 @@ +-- the minimum is 1: the pair is cut, the short chunk is a separate task +20000 799980000 +ok +-- the minimum is 32768: the cut would leave only the short chunk, it is skipped +20000 799980000 +ok diff --git a/tests/queries/0_stateless/05825_parquet_read_alignment_short_range_before_long.sh b/tests/queries/0_stateless/05825_parquet_read_alignment_short_range_before_long.sh new file mode 100755 index 000000000000..b870b26d29b7 --- /dev/null +++ b/tests/queries/0_stateless/05825_parquet_read_alignment_short_range_before_long.sh @@ -0,0 +1,151 @@ +#!/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}/short_before_long.parquet" + +# The anti-fragmentation guard of `input_format_parquet_read_alignment_bytes` must measure the fragment that the +# cut actually leaves. Here a short column chunk (5015 bytes) is followed by a long one (320015 bytes) that spans +# several multiples of the stride 65536. The last multiple inside the pair is far after the end of the short +# chunk, but the cut leaves only the short chunk before the long one, so with `input_format_parquet_read_alignment_min_bytes` +# of 32768 the cut must be skipped: otherwise the short chunk is read as a separate tiny request. +python3 - "${DATA_FILE}" <<'EOF' +import struct +import sys + +ROWS = 40000 +SHORT_OFFSET = 58000 # the short chunk is [58000, 63015), before the multiple 65536 +GAP = 100 # the long chunk starts after the short one, 100 bytes later + +def varint(n): + out = bytearray() + while True: + b = n & 0x7F + n >>= 7 + if n: + out.append(b | 0x80) + else: + out.append(b) + return bytes(out) + +def zigzag(n): + return varint((n << 1) ^ (n >> 63)) + +# Thrift compact protocol: a struct is a list of (field id, type, encoded value) in the order of ids. +I32, I64, BINARY, LIST, STRUCT = 5, 6, 8, 9, 12 + +def struct_(fields): + out = bytearray() + last = 0 + for fid, ftype, value in sorted(fields, key=lambda f: f[0]): + out.append(((fid - last) << 4) | ftype) # all ids here are consecutive or within 15 + out += value + last = fid + out.append(0) + return bytes(out) + +def i32(n): return zigzag(n) +def i64(n): return zigzag(n) +def string(s): return varint(len(s)) + s.encode() +def small_list(elem_type, items): + assert len(items) < 15 + return bytes([(len(items) << 4) | elem_type]) + b"".join(items) + +def make_chunk(values): + header = struct_([ + (1, I32, i32(0)), # DATA_PAGE + (2, I32, i32(len(values))), # uncompressed_page_size + (3, I32, i32(len(values))), # compressed_page_size + (5, STRUCT, struct_([ + (1, I32, i32(ROWS)), # num_values + (2, I32, i32(0)), # PLAIN + (3, I32, i32(3)), # RLE + (4, I32, i32(3)), # RLE + ])), + ]) + return header + values + +short_chunk = make_chunk(b"\x55" * (ROWS // 8)) # BOOLEAN, bit-packed: 20000 values are true +long_chunk = make_chunk(struct.pack("<%dq" % ROWS, *range(ROWS))) +long_offset = SHORT_OFFSET + len(short_chunk) + GAP + +schema = [ + struct_([(4, BINARY, string("schema")), (5, I32, i32(2))]), + struct_([(1, I32, i32(0)), (3, I32, i32(0)), (4, BINARY, string("s"))]), # BOOLEAN, REQUIRED + struct_([(1, I32, i32(2)), (3, I32, i32(0)), (4, BINARY, string("l"))]), # INT64, REQUIRED +] + +def column_chunk(ptype, name, chunk, offset): + meta = struct_([ + (1, I32, i32(ptype)), + (2, LIST, small_list(I32, [i32(0)])), # encodings: PLAIN + (3, LIST, small_list(BINARY, [string(name)])), # path_in_schema + (4, I32, i32(0)), # UNCOMPRESSED + (5, I64, i64(ROWS)), # num_values + (6, I64, i64(len(chunk))), # total_uncompressed_size + (7, I64, i64(len(chunk))), # total_compressed_size + (9, I64, i64(offset)), # data_page_offset + ]) + return struct_([(2, I64, i64(offset)), (3, STRUCT, meta)]) + +row_group = struct_([ + (1, LIST, bytes([0x20 | STRUCT]) + column_chunk(0, "s", short_chunk, SHORT_OFFSET) + column_chunk(2, "l", long_chunk, long_offset)), + (2, I64, i64(len(short_chunk) + len(long_chunk))), + (3, I64, i64(ROWS)), +]) +file_metadata = struct_([ + (1, I32, i32(1)), + (2, LIST, bytes([0x30 | STRUCT]) + b"".join(schema)), + (3, I64, i64(ROWS)), + (4, LIST, small_list(STRUCT, [row_group])), + (6, BINARY, string("test")), +]) + +with open(sys.argv[1], "wb") as f: + f.write(b"PAR1") + f.write(b"\0" * (SHORT_OFFSET - 4)) + f.write(short_chunk) + f.write(b"\0" * GAP) + f.write(long_chunk) + f.write(file_metadata + struct.pack(" "${WORKING_DIR}/log" +} + +# The number of read tasks that are made of a single range and are shorter than $1 bytes. +count_short_tasks() +{ + awk -v limit="$1" ' + /ParquetPrefetcher.*Read task: / { + match($0, /length=[0-9]+/); length_ = substr($0, RSTART + 7, RLENGTH - 7) + 0; + match($0, /ranges=[0-9]+/); ranges = substr($0, RSTART + 7, RLENGTH - 7) + 0; + if (ranges == 1 && length_ < limit) + short_ += 1; + } + END { print short_ + 0 }' "${WORKING_DIR}/log" +} + +echo "-- the minimum is 1: the pair is cut, the short chunk is a separate task" +run "input_format_parquet_read_alignment_min_bytes = 1" +[ "$(count_short_tasks 32768)" -gt 0 ] && echo "ok" || echo "fail" + +echo "-- the minimum is 32768: the cut would leave only the short chunk, it is skipped" +run "input_format_parquet_read_alignment_min_bytes = 32768" +[ "$(count_short_tasks 32768)" -eq 0 ] && echo "ok" || echo "fail" + +rm -rf "${WORKING_DIR}" From 76d3c40eae12e566f54119ed4e3e5f62ef048fb7 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Thu, 3 Dec 2026 14:59:59 +0100 Subject: [PATCH 20/30] Parquet v3 read alignment: keep the comment of `shouldCutForAlignment` next to it The comment of `shouldCutForAlignment` was left above the aliases of the decisions map that were added in front of it, so it described the wrong declaration. Put the aliases first and the comment right before the function. Comment only. Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- src/Processors/Formats/Impl/Parquet/Prefetcher.h | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index 2a248d985e90..db61ef91dc8f 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -217,15 +217,18 @@ class Prefetcher /// If splitting, the request is being cancelled and replaced by a smaller range /// (splitAndPrefetchRange), and only subrange [subrange_start, subrange_end) needs to be read. void pickRangesAndCreateTaskIfNotExists(RequestState *, const PrefetchHandle &, bool splitting, size_t start_offset, size_t end_offset, std::unique_lock lock); - /// Read alignment, called with the mutex held. `ranges` is the sorted range set, `earlier_idx` is the index of - /// the earlier range of a pair of neighbouring ranges. The extents of the pair are passed explicitly, - /// because the range that starts a splitting task is smaller than its RangeState. - /// Whether the task has to be cut between the pair, see pickRangesAndCreateTaskIfNotExists. + /// Read alignment, called with the mutex held. + /// /// The results of shouldCutForAlignment for the pairs met by the walks in alignmentPieceStart, during one /// pickRangesAndCreateTaskIfNotExists. The key is the earlier range and the extent of the later one - /// (the extent of the later one is not always its RangeState, see above). + /// (the extent of the later one is not always its RangeState, because the range that starts a splitting + /// task is smaller than its RangeState). using AlignmentDecisionKey = std::tuple; using AlignmentDecisions = std::map; + /// Whether the task has to be cut between a pair of neighbouring ranges, see + /// pickRangesAndCreateTaskIfNotExists. `ranges` is the sorted range set, `earlier_idx` is the index of the + /// earlier range of the pair. The extents of the pair are passed explicitly, because the range that starts + /// a splitting task is smaller than its RangeState. bool shouldCutForAlignment(const std::vector & ranges, size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end, bool * skipped_small, AlignmentDecisions & decisions) const; /// The start of the piece of neighbouring ranges that ends with the range `idx` and that would be one read /// if the pair after it was cut. The walk stops as soon as the start is at or before `lower_bound`, or when it From dcffe2755bd8f5a73ae9098ae46a2d2b87323700 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Thu, 3 Dec 2026 17:11:30 +0100 Subject: [PATCH 21/30] Parquet v3 read alignment: apply the size limit of a read task in the anti-fragmentation walk The guard of `input_format_parquet_read_alignment_min_bytes` walked back over the neighbouring ranges without the limit on the size of a read task. A scan takes only the ranges that start within `bytes_per_read_task` of the range that starts the task, which is 4 times `input_format_parquet_local_file_min_bytes_for_seek` for a local file. When the minimum is larger than that limit, the walk measured a longer piece than the scan leaves before the cut, and the cut left a read task shorter than the minimum. The walk now stops at a range that starts at or before the earlier range of the pair minus `bytes_per_read_task`. A scan that starts the task at a range before it takes at least these ranges, so the measured piece is a lower bound of the part that the cut leaves. The same-boundary shortcut in the walk is removed. It relied on the piece measured from the same start for both pairs, which no longer holds. The memo of the decisions for the scan keeps the cost of the walk bounded for overlapping ranges. The new test `05826_parquet_read_alignment_fragment_below_minimum` reproduces the case on a layout where the reader requests the range that crosses the boundary first. Related: https://github.com/Altinity/ClickHouse/pull/2978 Related: https://github.com/Altinity/ClickHouse/pull/2978/files#r4786374976 Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 27 ++- .../Formats/Impl/Parquet/Prefetcher.h | 5 +- ...alignment_fragment_below_minimum.reference | 8 + ...t_read_alignment_fragment_below_minimum.sh | 172 ++++++++++++++++++ 4 files changed, 193 insertions(+), 19 deletions(-) create mode 100644 tests/queries/0_stateless/05826_parquet_read_alignment_fragment_below_minimum.reference create mode 100755 tests/queries/0_stateless/05826_parquet_read_alignment_fragment_below_minimum.sh diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 4100968d9701..51f0bd68a555 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -355,8 +355,7 @@ bool Prefetcher::shouldCutForAlignment( if (read_alignment_min_bytes <= read_alignment_stride) { const size_t lower_bound = part_end >= read_alignment_min_bytes ? part_end - read_alignment_min_bytes : 0; - const size_t piece_start = alignmentPieceStart( - ranges, earlier_idx, earlier_start, earlier_end, last_boundary, lower_bound, decisions); + const size_t piece_start = alignmentPieceStart(ranges, earlier_idx, earlier_start, earlier_end, lower_bound, decisions); small = std::min(read_alignment_stride, part_end - piece_start) < read_alignment_min_bytes; } if (small) @@ -369,25 +368,22 @@ bool Prefetcher::shouldCutForAlignment( } size_t Prefetcher::alignmentPieceStart( - const std::vector & ranges, size_t idx, size_t start, size_t end, size_t last_boundary, size_t lower_bound, + const std::vector & ranges, size_t idx, size_t start, size_t end, size_t lower_bound, AlignmentDecisions & decisions) const { /// Walk to the left over the ranges that the scan in pickRangesAndCreateTaskIfNotExists would join into one - /// task with this one, with the same checks: skip the cancelled ranges, stop at a range that already has a - /// task, at a range that does not want to be read incidentally, at a gap of min_bytes_for_seek, and at a - /// pair that is cut. The result depends only on the ranges and not on the range that starts the task, so - /// the decision for a pair is the same for the scan going left and the scan going right. (The limit on the - /// size of the task is not applied, because it depends on the range that starts the task.) + /// task with the range `start`, with the same checks: skip the cancelled ranges, stop at a range that already + /// has a task, at a range that does not want to be read incidentally, at a gap of min_bytes_for_seek, and at a + /// pair that is cut. The scan also stops at the limit on the size of a task, measured from the range that + /// starts the task: it does not take a range that starts at or before that range minus bytes_per_read_task. + /// The walk applies the same limit measured from `start`. A scan that starts the task at a range before `start` + /// takes at least the ranges that the walk takes, so the piece found here is never longer than the part that + /// the cut leaves, whichever range starts the task. /// /// Whether the pair on the way is cut is decided by the recursion into shouldCutForAlignment. Its result /// depends only on the pair, so it is remembered in `decisions` for the whole scan: otherwise ranges that /// overlap (a malformed file) make the recursion exponential in their number. /// - /// When that pair crosses the same boundary as the pair being decided, and the earlier range reaches that - /// boundary, the answer is known without the recursion: if the pair is cut, the piece starts after it, at - /// piece_start; if it is skipped, its own piece is the one that this walk would find, and it measures up to - /// the boundary, which is not less than the part measured here. In both cases the part is too small, so - /// the walk stops here, with a start that is after lower_bound. size_t piece_start = start; size_t later_start = start; size_t later_end = end; @@ -412,12 +408,11 @@ size_t Prefetcher::alignmentPieceStart( /// a cut leave a part smaller than read_alignment_min_bytes. const RangeState & earlier = ranges[earlier_idx]; if (!earlier.request->allow_incidental_read.load(std::memory_order_relaxed) - || earlier.end + min_bytes_for_seek <= piece_start) + || earlier.end + min_bytes_for_seek <= piece_start + || earlier.start + bytes_per_read_task <= start) return piece_start; const auto crossed_boundary = lastCrossedBoundary(read_alignment_stride, earlier.start, earlier.end, later_start, later_end); - if (crossed_boundary == last_boundary && earlier.end >= last_boundary) - return piece_start; bool cut = false; if (crossed_boundary) diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index 76cc3db59a7a..cc297c09e30f 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -234,9 +234,8 @@ class Prefetcher bool shouldCutForAlignment(const std::vector & ranges, size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end, bool * skipped_small, AlignmentDecisions & decisions) const; /// The start of the piece of neighbouring ranges that ends with the range `idx` and that would be one read /// if the pair after it was cut. The walk stops as soon as the start is at or before `lower_bound`, or when it - /// meets a pair that is cut, or that crosses `last_boundary`, the boundary of the pair that is being decided, - /// with its earlier range reaching it. - size_t alignmentPieceStart(const std::vector & ranges, size_t idx, size_t start, size_t end, size_t last_boundary, size_t lower_bound, AlignmentDecisions & decisions) const; + /// meets a pair that is cut, or a range beyond the limit on the size of a task (see alignmentPieceStart in the .cpp). + size_t alignmentPieceStart(const std::vector & ranges, size_t idx, size_t start, size_t end, size_t lower_bound, AlignmentDecisions & decisions) const; static void decreaseTaskRefcount(Task * task, size_t amount); void scheduleTask(Task * task); Task::State runTask(Task * task); diff --git a/tests/queries/0_stateless/05826_parquet_read_alignment_fragment_below_minimum.reference b/tests/queries/0_stateless/05826_parquet_read_alignment_fragment_below_minimum.reference new file mode 100644 index 000000000000..9fa4538677f5 --- /dev/null +++ b/tests/queries/0_stateless/05826_parquet_read_alignment_fragment_below_minimum.reference @@ -0,0 +1,8 @@ +-- read alignment off +5092685448548174848 +-- aligned, the minimum is 1: the cut is made and leaves a fragment +5092685448548174848 +ok +-- aligned, the minimum is 512 KiB: no cut leaves a fragment shorter than the minimum +5092685448548174848 +ok diff --git a/tests/queries/0_stateless/05826_parquet_read_alignment_fragment_below_minimum.sh b/tests/queries/0_stateless/05826_parquet_read_alignment_fragment_below_minimum.sh new file mode 100755 index 000000000000..59a03359ee80 --- /dev/null +++ b/tests/queries/0_stateless/05826_parquet_read_alignment_fragment_below_minimum.sh @@ -0,0 +1,172 @@ +#!/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}/fragment_below_minimum.parquet" + +# The anti-fragmentation guard of `input_format_parquet_read_alignment_bytes` must not let a cut leave a read task +# that is smaller than `input_format_parquet_read_alignment_min_bytes`. The guard measures the bytes before the cut, +# but a read task can take only the ranges within `4 * input_format_parquet_local_file_min_bytes_for_seek` bytes of the +# range that starts it. Here the seek threshold is 64 KiB, so such a task takes about 5 column chunks (about 300 KiB), +# while the guard, walking back from the cut, measures more than the minimum of 512 KiB. +# +# The stride is 1 MiB. The file has 12 column chunks of about 60 KB each, contiguous, and the last of them crosses the +# boundary. The columns are stored in the reverse order of the file, so the reader requests the chunk that crosses the +# boundary first, and the ranges before it are not read yet when the cut is decided. +python3 - "${DATA_FILE}" <<'EOF' +import struct +import sys + +ROWS = 512 +COLUMNS = 12 +CHUNK_SIZE = 60 * 1024 +STRIDE = 1024 * 1024 +START = STRIDE - 680 * 1024 # the file before the first chunk is zeros + +def varint(n): + out = bytearray() + while True: + b = n & 0x7F + n >>= 7 + if n: + out.append(b | 0x80) + else: + out.append(b) + return bytes(out) + +def zigzag(n): + return varint((n << 1) ^ (n >> 63)) + +# Thrift compact protocol: a struct is a list of (field id, type, encoded value) in the order of ids. +I32, I64, BINARY, LIST, STRUCT = 5, 6, 8, 9, 12 +BYTE_ARRAY = 6 + +def struct_(fields): + out = bytearray() + last = 0 + for fid, ftype, value in sorted(fields, key=lambda f: f[0]): + out.append(((fid - last) << 4) | ftype) # all ids here are consecutive or within 15 + out += value + last = fid + out.append(0) + return bytes(out) + +def i32(n): return zigzag(n) +def i64(n): return zigzag(n) +def string(s): return varint(len(s)) + s.encode() +def small_list(elem_type, items): + assert len(items) < 15 + return bytes([(len(items) << 4) | elem_type]) + b"".join(items) + +def make_chunk(): + # PLAIN BYTE_ARRAY: each value is a 4-byte length and the bytes. The chunk is about CHUNK_SIZE bytes. + value_len = (CHUNK_SIZE - 30) // ROWS - 4 + values = b"".join(struct.pack(" "${WORKING_DIR}/$1.log" +} + +# Prints the number of read tasks that end in the last 64 KiB before the boundary and are shorter than MIN. +count_fragments() +{ + awk -v stride="${STRIDE}" -v min_part="${MIN}" ' + /ParquetPrefetcher.*Read task: / { + match($0, /offset=[0-9]+/); offset = substr($0, RSTART + 7, RLENGTH - 7) + 0; + match($0, /length=[0-9]+/); length_ = substr($0, RSTART + 7, RLENGTH - 7) + 0; + end = offset + length_; + if (end > stride - 65536 && end <= stride && length_ < min_part) + fragments += 1; + } + END { print fragments + 0 }' "${WORKING_DIR}/$1.log" +} + +echo "-- read alignment off" +run off "input_format_parquet_read_alignment_bytes = 0" + +echo "-- aligned, the minimum is 1: the cut is made and leaves a fragment" +run control "input_format_parquet_read_alignment_bytes = ${STRIDE}, input_format_parquet_read_alignment_min_bytes = 1" +[ "$(count_fragments control)" -gt 0 ] && echo "ok" || echo "fail: the layout does not produce a fragment" + +echo "-- aligned, the minimum is 512 KiB: no cut leaves a fragment shorter than the minimum" +run guarded "input_format_parquet_read_alignment_bytes = ${STRIDE}, input_format_parquet_read_alignment_min_bytes = ${MIN}" +[ "$(count_fragments guarded)" -eq 0 ] && echo "ok" || echo "fail: fragments=$(count_fragments guarded)" + +rm -rf "${WORKING_DIR}" From 680af41e3d930370f2e8da05bfaf7d4d6d550de3 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Thu, 3 Dec 2026 17:33:08 +0100 Subject: [PATCH 22/30] Parquet v3 read alignment: scan right past cancelled ranges correctly and document the task size cap The right scan in `Prefetcher::pickRangesAndCreateTaskIfNotExists` read `ranges[end_idx]` instead of `ranges[idx]`, so it kept examining the last range it had already coalesced, and it stored `end_idx` as the right edge index. Both are now `idx`, so the scan examines each neighbour once, as the left scan does, and it skips cancelled ranges instead of stopping on them. Also document in `input_format_parquet_read_alignment_min_bytes` that the measured part is capped by the length of the range before the boundary plus four times the minimum seek distance, which is the size limit of a read task. Co-authored-by: Cursor --- src/Core/FormatFactorySettings.h | 2 +- src/Processors/Formats/Impl/Parquet/Prefetcher.cpp | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 4ede0443eff1..558720f7ae8b 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -240,7 +240,7 @@ Minor tweak to how pages are read from parquet file when no page filtering is us Experimental. When the Parquet v3 reader merges neighbouring requested ranges (for example column chunks) into one read, do not merge across a multiple of this size. Set it to the writer's multipart part size (for example 10Mi for delta-rs, 64Mi for Spark/S3A) to avoid merged reads that span two parts of a multipart-uploaded object. Only the merging is limited: a single requested range that crosses a multiple of this size is still read as one request, and `input_format_parquet_read_alignment_min_bytes` can allow a merged read to cross it too. 0 disables. )", 0) \ DECLARE(UInt64, input_format_parquet_read_alignment_min_bytes, 1048576, R"( -Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a merge at a boundary when the part before the boundary of the run of neighbouring ranges that the cut would leave (within one multiple of the size) is smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. The part is measured within one multiple of `input_format_parquet_read_alignment_bytes`, so if this value is larger than `input_format_parquet_read_alignment_bytes`, no merge is ever cut and the alignment is effectively off. 0 disables the guard. Default 1 MiB. +Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a merge at a boundary when the part before the boundary of the run of neighbouring ranges that the cut would leave is smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. The part is measured within one multiple of `input_format_parquet_read_alignment_bytes`, and it cannot be longer than the length of the range before the boundary plus four times the minimum seek distance of the reader (`input_format_parquet_local_file_min_bytes_for_seek` for local files, `remote_read_min_bytes_for_seek` for remote reads), because a read task takes only the ranges that start within that distance of the range that starts it. So if this value is larger than `input_format_parquet_read_alignment_bytes`, or than that bound for a boundary, no merge is cut at that boundary. 0 disables the guard. Default 1 MiB. )", 0) \ DECLARE(Bool, input_format_parquet_verify_checksums, true, R"( Verify page checksums when reading parquet files. diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 51f0bd68a555..3ba62628763c 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -563,7 +563,7 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, initial_offset = end_offset; for (size_t idx = range_idx + 1; idx < ranges.size(); ++idx) { - const RangeState & r = ranges[end_idx]; + const RangeState & r = ranges[idx]; if (end_offset + min_bytes_for_seek <= r.start || initial_offset + bytes_per_read_task <= r.end || !r.request->allow_incidental_read.load(std::memory_order_relaxed)) @@ -574,7 +574,7 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, { if (shouldCutBetween(right_edge_idx, right_edge_start, right_edge_end, r.start, r.end)) break; - right_edge_idx = end_idx; + right_edge_idx = idx; right_edge_start = r.start; right_edge_end = r.end; @@ -589,6 +589,7 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, chassert(s == RequestState::State::HasTask); break; } + /// A cancelled range is skipped, as in the scan to the left, and the scan goes on past it. } if (part_boundary_constrained) From 4dbf8f60c7f6c65f8845b0358b00593cd3687c1d Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Thu, 3 Dec 2026 17:56:25 +0100 Subject: [PATCH 23/30] Parquet v3 read alignment: test that the scan to the right goes past a cancelled range The fix of the right scan in `Prefetcher::pickRangesAndCreateTaskIfNotExists` also changes the default read layout, with the alignment off: a cancelled range (for example the parent of a split range) no longer stops the coalescing to the right. There was no test for it. Add a unit test with a recording file. The range after a cancelled range, within the gap of `min_bytes_for_seek`, is read together with the first one in a single read, and a range beyond the gap is not. The first test fails (two reads instead of one) with the old `ranges[end_idx]`, the second one passes with both. It is a unit test because a `.sql` test cannot make a cancelled range appear to the right of the requested one: the `Prefetcher` requests the ranges in schema order, and the cancelled ranges are the parents of split ranges. Co-authored-by: Cursor --- ..._prefetcher_cancelled_range_coalescing.cpp | 107 ++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp diff --git a/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp new file mode 100644 index 000000000000..421191104aa4 --- /dev/null +++ b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp @@ -0,0 +1,107 @@ +#include +#include +#if USE_PARQUET + +#include + +#include +#include + +#include +#include +#include +#include + +using namespace DB; +using namespace DB::Parquet; + +namespace +{ + +/// A remote-like file that remembers the reads made through it. +class RecordingFile : public SeekableReadBuffer, public WithFileSize +{ +public: + explicit RecordingFile(size_t size_) : SeekableReadBuffer(nullptr, 0), size(size_) {} + + bool nextImpl() override { return false; } + off_t seek(off_t off, int) override { return off; } + off_t getPosition() override { return 0; } + std::optional tryGetFileSize() override { return size; } + bool supportsReadAt() override { return true; } + + size_t readBigAt(char * to, size_t n, size_t offset, const std::function & /*progress_callback*/) const override + { + memset(to, 'x', n); + std::lock_guard lock(mutex); + reads.emplace_back(offset, n); + return n; + } + + std::vector> getReads() const + { + std::lock_guard lock(mutex); + return reads; + } + +private: + const size_t size; + mutable std::mutex mutex; + mutable std::vector> reads; +}; + +/// Registers three ranges: `[0, 100)`, `[150, 250)` and `[second_start, second_start + 100)`. The middle range is +/// cancelled, as the range that has been split into smaller ones is. Then the first range is read, and the last one. +/// Returns the reads made through the file. +std::vector> readAroundCancelledRange(size_t file_size, size_t last_start) +{ + ReadOptions options; + options.min_bytes_for_seek = 1000; + options.bytes_per_read_task = 4000; + + RecordingFile file(file_size); + MemoryUsageDiff diff(ReadStage::ColumnData); + { + Prefetcher prefetcher; + prefetcher.init(&file, options, /*parser_shared_resources_=*/ nullptr); + + PrefetchHandle first = prefetcher.registerRange(0, 100, /*likely_to_be_used=*/ true); + PrefetchHandle middle = prefetcher.registerRange(150, 100, /*likely_to_be_used=*/ true); + PrefetchHandle last = prefetcher.registerRange(last_start, 100, /*likely_to_be_used=*/ true); + prefetcher.finalizeRanges(); + + middle.reset(&diff); + + prefetcher.startPrefetch({&first}, &diff); + EXPECT_EQ(prefetcher.getRangeData(first).size(), 100u); + prefetcher.startPrefetch({&last}, &diff); + EXPECT_EQ(prefetcher.getRangeData(last).size(), 100u); + + first.reset(&diff); + last.reset(&diff); + } + diff.finalized = true; + return file.getReads(); +} + +} + +/// The scan for the ranges to read together with the requested one goes on past a cancelled range, as it does to +/// the left: the last range is within the gap that is worth reading through, and it is read with the first one. +TEST(ParquetPrefetcher, ScanToTheRightGoesPastCancelledRange) +{ + const auto reads = readAroundCancelledRange(/*file_size=*/ 1000, /*last_start=*/ 300); + ASSERT_EQ(reads.size(), 1u); + EXPECT_EQ(reads[0], (std::pair{0, 400})); +} + +/// The cancelled range does not hide the gap: when the range after it is too far, it is not read together. +TEST(ParquetPrefetcher, ScanToTheRightStopsAtGapAfterCancelledRange) +{ + const auto reads = readAroundCancelledRange(/*file_size=*/ 10000, /*last_start=*/ 2000); + ASSERT_EQ(reads.size(), 2u); + EXPECT_EQ(reads[0], (std::pair{0, 100})); + EXPECT_EQ(reads[1], (std::pair{2000, 100})); +} + +#endif From 495f31bc25a9d0b3db7b5070faa013478afca4fb Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Thu, 3 Dec 2026 19:02:16 +0100 Subject: [PATCH 24/30] Parquet v3 read alignment: measure the initial range of a split read with its subrange When `Prefetcher::splitRange` gives a parent shorter than `min_bytes_for_seek` to `pickRangesAndCreateTaskIfNotExists` in splitting mode, the task covers only the subrange of the parent. The top-level cut decision used the subrange, but `alignmentPieceStart` walked left and read `ranges[earlier_idx]`, which for the initial range is the whole parent. The piece before the boundary was then measured from the start of the parent, so it looked longer than the part the task really reads, and the anti-fragmentation guard let a cut through that left a fragment below `input_format_parquet_read_alignment_min_bytes`. Pass the initial range with the extents it is read with (`AlignmentInitialRange`) to `shouldCutForAlignment` and `alignmentPieceStart`, and use them for the initial range in the walk. The memo is unchanged: its key is the index and the later extents, which are fixed for one call. The new gtest reproduces it: a parent `[6656, 7424)` KiB split to `[7300, 7424)`, with ranges `[7800, 8704)` and `[8704, 9216)` after it and the stride at 8192 KiB. The read must be one 1916 KiB read, as it is when the subrange is requested as a plain range. Without the fix, it is a 1404 KiB read. Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 28 ++++++++------ .../Formats/Impl/Parquet/Prefetcher.h | 12 +++++- ..._prefetcher_cancelled_range_coalescing.cpp | 38 +++++++++++++++++++ 3 files changed, 65 insertions(+), 13 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 3ba62628763c..b99791b7a134 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -327,7 +327,7 @@ static std::optional lastCrossedBoundary( } bool Prefetcher::shouldCutForAlignment( - const std::vector & ranges, size_t earlier_idx, size_t earlier_start, size_t earlier_end, + const std::vector & ranges, const AlignmentInitialRange & initial, size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end, bool * skipped_small, AlignmentDecisions & decisions) const { chassert(read_alignment_stride > 0); @@ -355,7 +355,7 @@ bool Prefetcher::shouldCutForAlignment( if (read_alignment_min_bytes <= read_alignment_stride) { const size_t lower_bound = part_end >= read_alignment_min_bytes ? part_end - read_alignment_min_bytes : 0; - const size_t piece_start = alignmentPieceStart(ranges, earlier_idx, earlier_start, earlier_end, lower_bound, decisions); + const size_t piece_start = alignmentPieceStart(ranges, initial, earlier_idx, earlier_start, earlier_end, lower_bound, decisions); small = std::min(read_alignment_stride, part_end - piece_start) < read_alignment_min_bytes; } if (small) @@ -368,7 +368,7 @@ bool Prefetcher::shouldCutForAlignment( } size_t Prefetcher::alignmentPieceStart( - const std::vector & ranges, size_t idx, size_t start, size_t end, size_t lower_bound, + const std::vector & ranges, const AlignmentInitialRange & initial, size_t idx, size_t start, size_t end, size_t lower_bound, AlignmentDecisions & decisions) const { /// Walk to the left over the ranges that the scan in pickRangesAndCreateTaskIfNotExists would join into one @@ -407,12 +407,16 @@ size_t Prefetcher::alignmentPieceStart( /// would make the piece longer than the task that is left before the boundary, and the guard would let /// a cut leave a part smaller than read_alignment_min_bytes. const RangeState & earlier = ranges[earlier_idx]; + /// The initial range is read with its subrange, see AlignmentInitialRange. + const bool is_initial = earlier_idx == initial.idx; + const size_t earlier_start = is_initial ? initial.start : earlier.start; + const size_t earlier_end = is_initial ? initial.end : earlier.end; if (!earlier.request->allow_incidental_read.load(std::memory_order_relaxed) - || earlier.end + min_bytes_for_seek <= piece_start - || earlier.start + bytes_per_read_task <= start) + || earlier_end + min_bytes_for_seek <= piece_start + || earlier_start + bytes_per_read_task <= start) return piece_start; - const auto crossed_boundary = lastCrossedBoundary(read_alignment_stride, earlier.start, earlier.end, later_start, later_end); + const auto crossed_boundary = lastCrossedBoundary(read_alignment_stride, earlier_start, earlier_end, later_start, later_end); bool cut = false; if (crossed_boundary) @@ -422,7 +426,7 @@ size_t Prefetcher::alignmentPieceStart( if (it == decisions.end()) { cut = shouldCutForAlignment( - ranges, earlier_idx, earlier.start, earlier.end, later_start, later_end, /*skipped_small=*/ nullptr, decisions); + ranges, initial, earlier_idx, earlier_start, earlier_end, later_start, later_end, /*skipped_small=*/ nullptr, decisions); decisions.emplace(key, cut); } else @@ -431,10 +435,10 @@ size_t Prefetcher::alignmentPieceStart( if (cut) return piece_start; - piece_start = std::min(piece_start, earlier.start); + piece_start = std::min(piece_start, earlier_start); later_idx = earlier_idx; - later_start = earlier.start; - later_end = earlier.end; + later_start = earlier_start; + later_end = earlier_end; } return piece_start; } @@ -498,12 +502,14 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, bool part_boundary_constrained = false; bool skipped_small = false; AlignmentDecisions alignment_decisions; + /// Taken before the scans change start_offset and end_offset. + const AlignmentInitialRange alignment_initial{range_idx, start_offset, end_offset}; auto shouldCutBetween = [&](size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end) { if (!alignment_active) return false; - if (!shouldCutForAlignment(ranges, earlier_idx, earlier_start, earlier_end, later_start, later_end, &skipped_small, alignment_decisions)) + if (!shouldCutForAlignment(ranges, alignment_initial, earlier_idx, earlier_start, earlier_end, later_start, later_end, &skipped_small, alignment_decisions)) return false; part_boundary_constrained = true; return true; diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index cc297c09e30f..662cb4f1e751 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -227,15 +227,23 @@ class Prefetcher /// task is smaller than its RangeState). using AlignmentDecisionKey = std::tuple; using AlignmentDecisions = std::map; + /// The range that starts the task, with the extents it is read with: the subrange when splitting, which is + /// smaller than its RangeState. The read alignment has to measure the initial range with these extents. + struct AlignmentInitialRange + { + size_t idx; + size_t start; + size_t end; + }; /// Whether the task has to be cut between a pair of neighbouring ranges, see /// pickRangesAndCreateTaskIfNotExists. `ranges` is the sorted range set, `earlier_idx` is the index of the /// earlier range of the pair. The extents of the pair are passed explicitly, because the range that starts /// a splitting task is smaller than its RangeState. - bool shouldCutForAlignment(const std::vector & ranges, size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end, bool * skipped_small, AlignmentDecisions & decisions) const; + bool shouldCutForAlignment(const std::vector & ranges, const AlignmentInitialRange & initial, size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end, bool * skipped_small, AlignmentDecisions & decisions) const; /// The start of the piece of neighbouring ranges that ends with the range `idx` and that would be one read /// if the pair after it was cut. The walk stops as soon as the start is at or before `lower_bound`, or when it /// meets a pair that is cut, or a range beyond the limit on the size of a task (see alignmentPieceStart in the .cpp). - size_t alignmentPieceStart(const std::vector & ranges, size_t idx, size_t start, size_t end, size_t lower_bound, AlignmentDecisions & decisions) const; + size_t alignmentPieceStart(const std::vector & ranges, const AlignmentInitialRange & initial, size_t idx, size_t start, size_t end, size_t lower_bound, AlignmentDecisions & decisions) const; static void decreaseTaskRefcount(Task * task, size_t amount); void scheduleTask(Task * task); Task::State runTask(Task * task); diff --git a/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp index 421191104aa4..b9b5daf2f225 100644 --- a/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp +++ b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp @@ -104,4 +104,42 @@ TEST(ParquetPrefetcher, ScanToTheRightStopsAtGapAfterCancelledRange) EXPECT_EQ(reads[1], (std::pair{2000, 100})); } +/// A read of a split range is measured from the subrange it reads, not from the whole range it was split from. The +/// parent is shorter than `min_bytes_for_seek`, so it is split without being cut. The subrange is the last 124 KiB of it, +/// so the 892 KiB before the boundary at 8192 KiB are below the minimum of the anti-fragmentation guard, and the ranges +/// after the parent must be read together with it, as they are when the same subrange is requested as a plain range. +TEST(ParquetPrefetcher, SplitParentIsMeasuredFromSubrange) +{ + ReadOptions options; + options.min_bytes_for_seek = 4096 * KiB; + options.bytes_per_read_task = 16384 * KiB; + options.format.parquet.read_alignment_bytes = 8192 * KiB; + options.format.parquet.read_alignment_min_bytes = 1024 * KiB; + + RecordingFile file(16384 * KiB); + MemoryUsageDiff diff(ReadStage::ColumnData); + { + Prefetcher prefetcher; + prefetcher.init(&file, options, /*parser_shared_resources_=*/ nullptr); + + PrefetchHandle parent = prefetcher.registerRange(6656 * KiB, 768 * KiB, /*likely_to_be_used=*/ true); + PrefetchHandle first = prefetcher.registerRange(7800 * KiB, 904 * KiB, /*likely_to_be_used=*/ true); + PrefetchHandle second = prefetcher.registerRange(8704 * KiB, 512 * KiB, /*likely_to_be_used=*/ true); + prefetcher.finalizeRanges(); + + auto children = prefetcher.splitRange(std::move(parent), {{7300 * KiB, 124 * KiB}}, /*likely_to_be_used=*/ false); + ASSERT_EQ(children.size(), 1u); + EXPECT_EQ(prefetcher.getRangeData(children[0]).size(), 124 * KiB); + + children[0].reset(&diff); + first.reset(&diff); + second.reset(&diff); + } + diff.finalized = true; + + const auto reads = file.getReads(); + ASSERT_EQ(reads.size(), 1u); + EXPECT_EQ(reads[0], (std::pair{7300 * KiB, 1916 * KiB})); +} + #endif From 7694a69d03018d5bc7147d372c93607e153e2f71 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Fri, 4 Dec 2026 11:07:51 +0100 Subject: [PATCH 25/30] Parquet v3 read alignment: bound the walk to the left for the cut decision The walk to the left in `Prefetcher::alignmentPieceStart` and the decisions it needs in `Prefetcher::shouldCutForAlignment` call each other. With many overlapping ranges, the recursion depth and the total walk length grow with the number of ranges. For 200000 identical overlapping ranges this crashed the server with a stack overflow, and 20000 ranges took several seconds. Each top-level decision now has an `AlignmentWalkBudget` that limits the nesting depth (64) and the number of walk steps (4096). When a limit is reached, the decision is abandoned and the task is not cut at that boundary, so the read stays merged. This is fail-closed: the read is never split on an incomplete decision. The new profile event `ParquetPrefetcherAlignmentWalkLimited` counts these cases. Add the gtest `ManyOverlappingRangesDoNotExhaustTheStack`. Closes the review comment: https://github.com/Altinity/ClickHouse/pull/2978#discussion_r4789930026 Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- src/Common/ProfileEvents.cpp | 1 + .../Formats/Impl/Parquet/Prefetcher.cpp | 42 ++++++++++++++++--- .../Formats/Impl/Parquet/Prefetcher.h | 18 +++++++- ..._prefetcher_cancelled_range_coalescing.cpp | 38 +++++++++++++++++ 4 files changed, 92 insertions(+), 7 deletions(-) diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index 256827ec58d9..0911d262e5d2 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -1854,6 +1854,7 @@ The server successfully detected this situation and will download merged part fr 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(ParquetPrefetcherPartAlignedTasks, "The number of read tasks whose coalescing was cut at a read alignment boundary (input_format_parquet_read_alignment_bytes) by DB::Parquet::Prefetcher", ValueType::Number) \ + M(ParquetPrefetcherAlignmentWalkLimited, "The number of read tasks in which DB::Parquet::Prefetcher did not decide a cut at a read alignment boundary, and so did not cut there, because the walk over the neighbouring ranges reached its limit on the number of steps or on the depth of the nested decisions (ranges that overlap a lot)", ValueType::Number) \ M(ParquetPrefetcherAlignmentSkippedSmall, "The number of read tasks in which DB::Parquet::Prefetcher did not cut at a read alignment boundary because the part before the boundary of the run of neighbouring ranges that the cut would leave would be smaller than input_format_parquet_read_alignment_min_bytes (anti-fragmentation)", 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) \ diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index b99791b7a134..9d174f9c1819 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -27,6 +27,7 @@ namespace ProfileEvents extern const Event ParquetPrefetcherReadEntireFile; extern const Event ParquetPrefetcherPartAlignedTasks; extern const Event ParquetPrefetcherAlignmentSkippedSmall; + extern const Event ParquetPrefetcherAlignmentWalkLimited; } namespace DB::Parquet @@ -328,7 +329,7 @@ static std::optional lastCrossedBoundary( bool Prefetcher::shouldCutForAlignment( const std::vector & ranges, const AlignmentInitialRange & initial, size_t earlier_idx, size_t earlier_start, size_t earlier_end, - size_t later_start, size_t later_end, bool * skipped_small, AlignmentDecisions & decisions) const + size_t later_start, size_t later_end, bool * skipped_small, AlignmentDecisions & decisions, AlignmentWalkBudget & budget) const { chassert(read_alignment_stride > 0); @@ -355,7 +356,9 @@ bool Prefetcher::shouldCutForAlignment( if (read_alignment_min_bytes <= read_alignment_stride) { const size_t lower_bound = part_end >= read_alignment_min_bytes ? part_end - read_alignment_min_bytes : 0; - const size_t piece_start = alignmentPieceStart(ranges, initial, earlier_idx, earlier_start, earlier_end, lower_bound, decisions); + const size_t piece_start = alignmentPieceStart(ranges, initial, earlier_idx, earlier_start, earlier_end, lower_bound, decisions, budget); + if (budget.exhausted) + return false; small = std::min(read_alignment_stride, part_end - piece_start) < read_alignment_min_bytes; } if (small) @@ -369,7 +372,7 @@ bool Prefetcher::shouldCutForAlignment( size_t Prefetcher::alignmentPieceStart( const std::vector & ranges, const AlignmentInitialRange & initial, size_t idx, size_t start, size_t end, size_t lower_bound, - AlignmentDecisions & decisions) const + AlignmentDecisions & decisions, AlignmentWalkBudget & budget) const { /// Walk to the left over the ranges that the scan in pickRangesAndCreateTaskIfNotExists would join into one /// task with the range `start`, with the same checks: skip the cancelled ranges, stop at a range that already @@ -384,6 +387,9 @@ size_t Prefetcher::alignmentPieceStart( /// depends only on the pair, so it is remembered in `decisions` for the whole scan: otherwise ranges that /// overlap (a malformed file) make the recursion exponential in their number. /// + /// The steps of the walk and the depth of the nested decisions are limited by `budget`. When a limit is reached, + /// the walk returns with `budget.exhausted` set, and the callers return without a decision. + /// size_t piece_start = start; size_t later_start = start; size_t later_end = end; @@ -397,6 +403,12 @@ size_t Prefetcher::alignmentPieceStart( if (earlier_idx == 0) return piece_start; --earlier_idx; + if (budget.steps_left == 0) + { + budget.exhausted = true; + return piece_start; + } + --budget.steps_left; s = ranges[earlier_idx].request->state.load(std::memory_order_relaxed); } while (s == RequestState::State::Cancelled); if (s != RequestState::State::HasRange) @@ -425,8 +437,17 @@ size_t Prefetcher::alignmentPieceStart( auto it = decisions.find(key); if (it == decisions.end()) { + if (budget.depth == AlignmentWalkBudget::max_depth) + { + budget.exhausted = true; + return piece_start; + } + ++budget.depth; cut = shouldCutForAlignment( - ranges, initial, earlier_idx, earlier_start, earlier_end, later_start, later_end, /*skipped_small=*/ nullptr, decisions); + ranges, initial, earlier_idx, earlier_start, earlier_end, later_start, later_end, /*skipped_small=*/ nullptr, decisions, budget); + --budget.depth; + if (budget.exhausted) + return piece_start; decisions.emplace(key, cut); } else @@ -502,6 +523,7 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, bool part_boundary_constrained = false; bool skipped_small = false; AlignmentDecisions alignment_decisions; + AlignmentWalkBudget alignment_budget; /// Taken before the scans change start_offset and end_offset. const AlignmentInitialRange alignment_initial{range_idx, start_offset, end_offset}; @@ -509,7 +531,17 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, { if (!alignment_active) return false; - if (!shouldCutForAlignment(ranges, alignment_initial, earlier_idx, earlier_start, earlier_end, later_start, later_end, &skipped_small, alignment_decisions)) + /// Each decision has its own limits. An abandoned decision does not cut, as when the guard holds. + alignment_budget = AlignmentWalkBudget{}; + const bool cut = shouldCutForAlignment( + ranges, alignment_initial, earlier_idx, earlier_start, earlier_end, later_start, later_end, + &skipped_small, alignment_decisions, alignment_budget); + if (alignment_budget.exhausted) + { + ProfileEvents::increment(ProfileEvents::ParquetPrefetcherAlignmentWalkLimited); + return false; + } + if (!cut) return false; part_boundary_constrained = true; return true; diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index 662cb4f1e751..5330fe713395 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -235,15 +235,29 @@ class Prefetcher size_t start; size_t end; }; + /// Limits of one top-level decision of the read alignment (see pickRangesAndCreateTaskIfNotExists). The walks and + /// the decisions they need call each other, so the nesting is bounded by `max_depth`, and the number of steps of + /// all the walks of one decision by `max_steps`. When a limit is reached, the decision is abandoned and the task is + /// not cut at that boundary, so the read stays merged, as when the guard holds a merge. Without the limits, ranges + /// that overlap a lot make the recursion as deep as their number, and the walks as long. + struct AlignmentWalkBudget + { + static constexpr size_t max_steps = 4096; + static constexpr size_t max_depth = 64; + + size_t steps_left = max_steps; + size_t depth = 0; + bool exhausted = false; + }; /// Whether the task has to be cut between a pair of neighbouring ranges, see /// pickRangesAndCreateTaskIfNotExists. `ranges` is the sorted range set, `earlier_idx` is the index of the /// earlier range of the pair. The extents of the pair are passed explicitly, because the range that starts /// a splitting task is smaller than its RangeState. - bool shouldCutForAlignment(const std::vector & ranges, const AlignmentInitialRange & initial, size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end, bool * skipped_small, AlignmentDecisions & decisions) const; + bool shouldCutForAlignment(const std::vector & ranges, const AlignmentInitialRange & initial, size_t earlier_idx, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end, bool * skipped_small, AlignmentDecisions & decisions, AlignmentWalkBudget & budget) const; /// The start of the piece of neighbouring ranges that ends with the range `idx` and that would be one read /// if the pair after it was cut. The walk stops as soon as the start is at or before `lower_bound`, or when it /// meets a pair that is cut, or a range beyond the limit on the size of a task (see alignmentPieceStart in the .cpp). - size_t alignmentPieceStart(const std::vector & ranges, const AlignmentInitialRange & initial, size_t idx, size_t start, size_t end, size_t lower_bound, AlignmentDecisions & decisions) const; + size_t alignmentPieceStart(const std::vector & ranges, const AlignmentInitialRange & initial, size_t idx, size_t start, size_t end, size_t lower_bound, AlignmentDecisions & decisions, AlignmentWalkBudget & budget) const; static void decreaseTaskRefcount(Task * task, size_t amount); void scheduleTask(Task * task); Task::State runTask(Task * task); diff --git a/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp index b9b5daf2f225..afb1f606911e 100644 --- a/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp +++ b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp @@ -142,4 +142,42 @@ TEST(ParquetPrefetcher, SplitParentIsMeasuredFromSubrange) EXPECT_EQ(reads[0], (std::pair{7300 * KiB, 1916 * KiB})); } +/// Many ranges that all overlap make the walk over the neighbouring ranges as long as their number, and the nested +/// decisions as deep. Both are limited, so this must neither overflow the stack nor take long. The walk gives up +/// without a cut, so the requested range is read in one piece. +TEST(ParquetPrefetcher, ManyOverlappingRangesDoNotExhaustTheStack) +{ + const size_t n = 200000; + + ReadOptions options; + options.min_bytes_for_seek = 64 * KiB; + options.bytes_per_read_task = 4 * MiB; + options.format.parquet.read_alignment_bytes = 10 * MiB; + options.format.parquet.read_alignment_min_bytes = 1 * MiB; + + RecordingFile file(20 * MiB); + MemoryUsageDiff diff(ReadStage::ColumnData); + { + Prefetcher prefetcher; + prefetcher.init(&file, options, /*parser_shared_resources_=*/ nullptr); + + std::vector handles; + handles.reserve(n); + for (size_t i = 0; i < n; ++i) + handles.push_back(prefetcher.registerRange(9 * MiB + MiB / 2, MiB, /*likely_to_be_used=*/ true)); + prefetcher.finalizeRanges(); + + prefetcher.startPrefetch({&handles.back()}, &diff); + EXPECT_EQ(prefetcher.getRangeData(handles.back()).size(), MiB); + + for (auto & handle : handles) + handle.reset(&diff); + } + diff.finalized = true; + + const auto reads = file.getReads(); + ASSERT_EQ(reads.size(), 1u); + EXPECT_EQ(reads[0], (std::pair{9 * MiB + MiB / 2, MiB})); +} + #endif From df8cc9df497026083688a1dfe6f48c02325feea0 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Fri, 4 Dec 2026 11:34:25 +0100 Subject: [PATCH 26/30] Parquet v3 read alignment: do not stop cutting on a fixed count of walk steps The step budget added with the bounded walk counted every step of the walk to the left, with a fixed limit of 4096. A walk over a guard window of small ranges takes a step per range, so for about 4200 contiguous ranges of 250 bytes inside 1 MiB before a multiple of the stride, the budget ran out and the read straddled the boundary, although the same layout with larger ranges was cut. The budget is now shared by the decisions of one pick and scales with the number of ranges of the file: 16 steps per range. The depth limit of the nested decisions is unchanged, so the recursion is still bounded. When the budget runs out, the pick stops cutting, as before. The event `ParquetPrefetcherAlignmentWalkLimited` is counted once per pick, not per abandoned decision. With 200000 identical overlapping ranges the pick takes under 1 ms, against 14 ms before this change for the same gtest. Add the gtest `ManyTinyContiguousRangesAreCutAtBoundary`, which failed on the previous commit: the read ended at 10510760 instead of 10 MiB. Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 16 ++++++-- .../Formats/Impl/Parquet/Prefetcher.h | 17 ++++---- ..._prefetcher_cancelled_range_coalescing.cpp | 40 +++++++++++++++++++ 3 files changed, 62 insertions(+), 11 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 9d174f9c1819..077683106e9d 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -523,7 +523,9 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, bool part_boundary_constrained = false; bool skipped_small = false; AlignmentDecisions alignment_decisions; - AlignmentWalkBudget alignment_budget; + /// Shared by the decisions of this pick, see AlignmentWalkBudget. + AlignmentWalkBudget alignment_budget(ranges.size()); + bool walk_limited = false; /// Taken before the scans change start_offset and end_offset. const AlignmentInitialRange alignment_initial{range_idx, start_offset, end_offset}; @@ -531,14 +533,18 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, { if (!alignment_active) return false; - /// Each decision has its own limits. An abandoned decision does not cut, as when the guard holds. - alignment_budget = AlignmentWalkBudget{}; + /// Once the budget is exhausted, the pick does not cut any more, as when the guard holds. + if (alignment_budget.exhausted) + { + walk_limited = true; + return false; + } const bool cut = shouldCutForAlignment( ranges, alignment_initial, earlier_idx, earlier_start, earlier_end, later_start, later_end, &skipped_small, alignment_decisions, alignment_budget); if (alignment_budget.exhausted) { - ProfileEvents::increment(ProfileEvents::ParquetPrefetcherAlignmentWalkLimited); + walk_limited = true; return false; } if (!cut) @@ -634,6 +640,8 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, ProfileEvents::increment(ProfileEvents::ParquetPrefetcherPartAlignedTasks); if (skipped_small) ProfileEvents::increment(ProfileEvents::ParquetPrefetcherAlignmentSkippedSmall); + if (walk_limited) + ProfileEvents::increment(ProfileEvents::ParquetPrefetcherAlignmentWalkLimited); /// Create task. Task & task = tasks.emplace_back(); diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index 5330fe713395..fc99f9d6670d 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -235,17 +235,20 @@ class Prefetcher size_t start; size_t end; }; - /// Limits of one top-level decision of the read alignment (see pickRangesAndCreateTaskIfNotExists). The walks and - /// the decisions they need call each other, so the nesting is bounded by `max_depth`, and the number of steps of - /// all the walks of one decision by `max_steps`. When a limit is reached, the decision is abandoned and the task is - /// not cut at that boundary, so the read stays merged, as when the guard holds a merge. Without the limits, ranges - /// that overlap a lot make the recursion as deep as their number, and the walks as long. + /// Limits of the read alignment decisions of one pickRangesAndCreateTaskIfNotExists. The walks and the decisions + /// they need call each other, so the nesting is bounded by `max_depth`. The steps of all the walks of the pick are + /// bounded by `steps_per_range` times the number of ranges of the file: a walk over a guard window of small ranges + /// takes a step per range, so this is not a fixed count of steps. When a limit is reached, the pick stops making + /// cuts, so the read stays merged, as when the guard holds a merge. Without the limits, ranges that overlap a lot + /// make the recursion as deep as their number, and the walks as long. struct AlignmentWalkBudget { - static constexpr size_t max_steps = 4096; + static constexpr size_t steps_per_range = 16; static constexpr size_t max_depth = 64; - size_t steps_left = max_steps; + explicit AlignmentWalkBudget(size_t ranges_count) : steps_left(steps_per_range * ranges_count) {} + + size_t steps_left; size_t depth = 0; bool exhausted = false; }; diff --git a/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp index afb1f606911e..bcca701e58aa 100644 --- a/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp +++ b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp @@ -180,4 +180,44 @@ TEST(ParquetPrefetcher, ManyOverlappingRangesDoNotExhaustTheStack) EXPECT_EQ(reads[0], (std::pair{9 * MiB + MiB / 2, MiB})); } +/// Many small contiguous ranges inside one guard window: the walk over them to the left is as long as the number of +/// them, and it is not a nested decision, so it must not turn the cut off. The task is cut at the boundary. +TEST(ParquetPrefetcher, ManyTinyContiguousRangesAreCutAtBoundary) +{ + const size_t chunk = 250; + const size_t before_count = (MiB + chunk - 1) / chunk + 2; + const size_t after_count = 100; + + ReadOptions options; + options.min_bytes_for_seek = 4 * MiB; + options.bytes_per_read_task = 16 * MiB; + options.format.parquet.read_alignment_bytes = 10 * MiB; + options.format.parquet.read_alignment_min_bytes = 1 * MiB; + + RecordingFile file(20 * MiB); + MemoryUsageDiff diff(ReadStage::ColumnData); + const size_t start = 10 * MiB - before_count * chunk; + { + Prefetcher prefetcher; + prefetcher.init(&file, options, /*parser_shared_resources_=*/ nullptr); + + std::vector handles; + for (size_t i = 0; i < before_count + after_count; ++i) + handles.push_back(prefetcher.registerRange(start + i * chunk, chunk, /*likely_to_be_used=*/ true)); + prefetcher.finalizeRanges(); + + prefetcher.startPrefetch({&handles[0]}, &diff); + EXPECT_EQ(prefetcher.getRangeData(handles[0]).size(), chunk); + + for (auto & handle : handles) + handle.reset(&diff); + } + diff.finalized = true; + + const auto reads = file.getReads(); + ASSERT_EQ(reads.size(), 1u); + EXPECT_EQ(reads[0].first, start); + EXPECT_EQ(reads[0].first + reads[0].second, 10 * MiB); +} + #endif From e03b1ac73947ff97f3b2c3d056482188a1aedbb8 Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Fri, 4 Dec 2026 11:44:02 +0100 Subject: [PATCH 27/30] Parquet v3 read alignment: describe `ParquetPrefetcherAlignmentWalkLimited` as counted once per task The event is incremented once for each read task in which the walk limits were reached, not once for each abandoned decision, and after the limit the task stops cutting at all the following boundaries. Say so in the description, and check in `ManyOverlappingRangesDoNotExhaustTheStack` that 200000 overlapping ranges add one to the event. Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- src/Common/ProfileEvents.cpp | 2 +- .../gtest_prefetcher_cancelled_range_coalescing.cpp | 11 ++++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index 0911d262e5d2..ef6e8d78bc37 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -1854,7 +1854,7 @@ The server successfully detected this situation and will download merged part fr 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(ParquetPrefetcherPartAlignedTasks, "The number of read tasks whose coalescing was cut at a read alignment boundary (input_format_parquet_read_alignment_bytes) by DB::Parquet::Prefetcher", ValueType::Number) \ - M(ParquetPrefetcherAlignmentWalkLimited, "The number of read tasks in which DB::Parquet::Prefetcher did not decide a cut at a read alignment boundary, and so did not cut there, because the walk over the neighbouring ranges reached its limit on the number of steps or on the depth of the nested decisions (ranges that overlap a lot)", ValueType::Number) \ + M(ParquetPrefetcherAlignmentWalkLimited, "The number of read tasks in which DB::Parquet::Prefetcher stopped cutting at read alignment boundaries, because the walk over the neighbouring ranges reached its limit on the number of steps or on the depth of the nested decisions (ranges that overlap a lot). It is counted once per task", ValueType::Number) \ M(ParquetPrefetcherAlignmentSkippedSmall, "The number of read tasks in which DB::Parquet::Prefetcher did not cut at a read alignment boundary because the part before the boundary of the run of neighbouring ranges that the cut would leave would be smaller than input_format_parquet_read_alignment_min_bytes (anti-fragmentation)", 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) \ diff --git a/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp index bcca701e58aa..398ce019adc2 100644 --- a/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp +++ b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp @@ -4,6 +4,7 @@ #include +#include #include #include @@ -12,6 +13,11 @@ #include #include +namespace ProfileEvents +{ + extern const Event ParquetPrefetcherAlignmentWalkLimited; +} + using namespace DB; using namespace DB::Parquet; @@ -144,10 +150,12 @@ TEST(ParquetPrefetcher, SplitParentIsMeasuredFromSubrange) /// Many ranges that all overlap make the walk over the neighbouring ranges as long as their number, and the nested /// decisions as deep. Both are limited, so this must neither overflow the stack nor take long. The walk gives up -/// without a cut, so the requested range is read in one piece. +/// without a cut, so the requested range is read in one piece. The limit is reported once for the task, not once for +/// each of the decisions that were abandoned. TEST(ParquetPrefetcher, ManyOverlappingRangesDoNotExhaustTheStack) { const size_t n = 200000; + const auto walk_limited_before = ProfileEvents::global_counters[ProfileEvents::ParquetPrefetcherAlignmentWalkLimited]; ReadOptions options; options.min_bytes_for_seek = 64 * KiB; @@ -178,6 +186,7 @@ TEST(ParquetPrefetcher, ManyOverlappingRangesDoNotExhaustTheStack) const auto reads = file.getReads(); ASSERT_EQ(reads.size(), 1u); EXPECT_EQ(reads[0], (std::pair{9 * MiB + MiB / 2, MiB})); + EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::ParquetPrefetcherAlignmentWalkLimited] - walk_limited_before, 1u); } /// Many small contiguous ranges inside one guard window: the walk over them to the left is as long as the number of From f25124752d0997ba8373cf6487e52dad4c95cc6e Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Fri, 4 Dec 2026 12:08:50 +0100 Subject: [PATCH 28/30] Parquet v3 read alignment: document the work limit of the cut decisions The comment of `AlignmentWalkBudget` said that the steps scale with the ranges of the file, but the budget is taken from the range set of the pick, which is the subranges of one split for a split range. Say so. Document in `input_format_parquet_read_alignment_bytes` that in a file whose ranges overlap so much that deciding the cuts would take more than a bounded amount of work, the reads of the task are left merged, and that the profile event `ParquetPrefetcherAlignmentWalkLimited` counts such tasks. Related: https://github.com/Altinity/ClickHouse/pull/2978 Co-authored-by: Cursor --- src/Core/FormatFactorySettings.h | 2 +- src/Processors/Formats/Impl/Parquet/Prefetcher.h | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 558720f7ae8b..d32fb4e0a68a 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -237,7 +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(UInt64, input_format_parquet_read_alignment_bytes, 0, R"( -Experimental. When the Parquet v3 reader merges neighbouring requested ranges (for example column chunks) into one read, do not merge across a multiple of this size. Set it to the writer's multipart part size (for example 10Mi for delta-rs, 64Mi for Spark/S3A) to avoid merged reads that span two parts of a multipart-uploaded object. Only the merging is limited: a single requested range that crosses a multiple of this size is still read as one request, and `input_format_parquet_read_alignment_min_bytes` can allow a merged read to cross it too. 0 disables. +Experimental. When the Parquet v3 reader merges neighbouring requested ranges (for example column chunks) into one read, do not merge across a multiple of this size. Set it to the writer's multipart part size (for example 10Mi for delta-rs, 64Mi for Spark/S3A) to avoid merged reads that span two parts of a multipart-uploaded object. Only the merging is limited: a single requested range that crosses a multiple of this size is still read as one request, and `input_format_parquet_read_alignment_min_bytes` can allow a merged read to cross it too. In a file whose ranges overlap so much that deciding the cuts would take more than a bounded amount of work, the reads of the task are left merged, and the profile event `ParquetPrefetcherAlignmentWalkLimited` counts such tasks. 0 disables. )", 0) \ DECLARE(UInt64, input_format_parquet_read_alignment_min_bytes, 1048576, R"( Experimental. Anti-fragmentation guard for `input_format_parquet_read_alignment_bytes`: do not cut a merge at a boundary when the part before the boundary of the run of neighbouring ranges that the cut would leave is smaller than this many bytes. The read then straddles the boundary instead of emitting a tiny extra request. The part is measured within one multiple of `input_format_parquet_read_alignment_bytes`, and it cannot be longer than the length of the range before the boundary plus four times the minimum seek distance of the reader (`input_format_parquet_local_file_min_bytes_for_seek` for local files, `remote_read_min_bytes_for_seek` for remote reads), because a read task takes only the ranges that start within that distance of the range that starts it. So if this value is larger than `input_format_parquet_read_alignment_bytes`, or than that bound for a boundary, no merge is cut at that boundary. 0 disables the guard. Default 1 MiB. diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index fc99f9d6670d..8921663ce157 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -237,8 +237,9 @@ class Prefetcher }; /// Limits of the read alignment decisions of one pickRangesAndCreateTaskIfNotExists. The walks and the decisions /// they need call each other, so the nesting is bounded by `max_depth`. The steps of all the walks of the pick are - /// bounded by `steps_per_range` times the number of ranges of the file: a walk over a guard window of small ranges - /// takes a step per range, so this is not a fixed count of steps. When a limit is reached, the pick stops making + /// bounded by `steps_per_range` times the number of ranges of the range set that the pick works on (all the + /// ranges of the file, or the subranges of one split): a walk over a guard window of small ranges takes a step per + /// range, so this is not a fixed count of steps. When a limit is reached, the pick stops making /// cuts, so the read stays merged, as when the guard holds a merge. Without the limits, ranges that overlap a lot /// make the recursion as deep as their number, and the walks as long. struct AlignmentWalkBudget From 67498bdc9bf4e824df4b9e47aeaddec7f4cd725e Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Fri, 4 Dec 2026 13:43:12 +0100 Subject: [PATCH 29/30] Parquet v3 read alignment: stop the walk at a cancelled range that the scan stops at The scans check `allow_incidental_read`, the gap of `min_bytes_for_seek` and the size limit of a task before they look at the state of a range. The alignment walk skipped cancelled ranges first, so it could go past a cancelled range that does not allow incidental reads, where the scan stops, and count bytes that the task does not read. The guard could then allow a cut that leaves a part below `read_alignment_min_bytes`. The walk now checks the same barriers in the same order for every range, cancelled ones included. For ranges that are not cancelled the outcome does not change. Example in bytes (MiB scaled by 1000: stride 10000, minimum 1000, gap 500, task limit 2000): `[9400, 9600)` is requested, `[8800, 9400)` is cancelled and does not allow incidental reads, and `[9700, 10100)` follows across the boundary at 10000. The read was 200 bytes; now `[9400, 10100)` is read as one range, 700 bytes. Codex review comment: https://github.com/Altinity/ClickHouse/pull/2978#discussion_r4799583447 Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 36 ++++++--- ..._prefetcher_cancelled_range_coalescing.cpp | 81 +++++++++++++++++++ 2 files changed, 104 insertions(+), 13 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 077683106e9d..2007d031ba7f 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -375,9 +375,10 @@ size_t Prefetcher::alignmentPieceStart( AlignmentDecisions & decisions, AlignmentWalkBudget & budget) const { /// Walk to the left over the ranges that the scan in pickRangesAndCreateTaskIfNotExists would join into one - /// task with the range `start`, with the same checks: skip the cancelled ranges, stop at a range that already - /// has a task, at a range that does not want to be read incidentally, at a gap of min_bytes_for_seek, and at a - /// pair that is cut. The scan also stops at the limit on the size of a task, measured from the range that + /// task with the range `start`, with the same checks in the same order: stop at a range that does not want to be + /// read incidentally, at a gap of min_bytes_for_seek, and at the size limit of a task, also when the range is + /// cancelled; skip a cancelled range that passes these; stop at a range that already has a task, and at a pair + /// that is cut. The scan also stops at the limit on the size of a task, measured from the range that /// starts the task: it does not take a range that starts at or before that range minus bytes_per_read_task. /// The walk applies the same limit measured from `start`. A scan that starts the task at a range before `start` /// takes at least the ranges that the walk takes, so the piece found here is never longer than the part that @@ -398,6 +399,8 @@ size_t Prefetcher::alignmentPieceStart( { size_t earlier_idx = later_idx; RequestState::State s; + size_t earlier_start = 0; + size_t earlier_end = 0; do { if (earlier_idx == 0) @@ -409,7 +412,23 @@ size_t Prefetcher::alignmentPieceStart( return piece_start; } --budget.steps_left; - s = ranges[earlier_idx].request->state.load(std::memory_order_relaxed); + + /// The initial range is read with its subrange, see AlignmentInitialRange. + const RangeState & earlier = ranges[earlier_idx]; + const bool is_initial = earlier_idx == initial.idx; + earlier_start = is_initial ? initial.start : earlier.start; + earlier_end = is_initial ? initial.end : earlier.end; + + /// The scans check these barriers before they look at the state of a range, so a cancelled range stops them + /// as well when it does not allow incidental reads or is too far. The walk checks them in the same order: if it + /// skipped a cancelled range first, it would go past a range that the scan stops at, and count bytes that the + /// task does not read. + if (!earlier.request->allow_incidental_read.load(std::memory_order_relaxed) + || earlier_end + min_bytes_for_seek <= piece_start + || earlier_start + bytes_per_read_task <= start) + return piece_start; + + s = earlier.request->state.load(std::memory_order_relaxed); } while (s == RequestState::State::Cancelled); if (s != RequestState::State::HasRange) return piece_start; @@ -418,15 +437,6 @@ size_t Prefetcher::alignmentPieceStart( /// always allows it (see startPrefetch), so a task never continues over it. Counting it into the piece /// would make the piece longer than the task that is left before the boundary, and the guard would let /// a cut leave a part smaller than read_alignment_min_bytes. - const RangeState & earlier = ranges[earlier_idx]; - /// The initial range is read with its subrange, see AlignmentInitialRange. - const bool is_initial = earlier_idx == initial.idx; - const size_t earlier_start = is_initial ? initial.start : earlier.start; - const size_t earlier_end = is_initial ? initial.end : earlier.end; - if (!earlier.request->allow_incidental_read.load(std::memory_order_relaxed) - || earlier_end + min_bytes_for_seek <= piece_start - || earlier_start + bytes_per_read_task <= start) - return piece_start; const auto crossed_boundary = lastCrossedBoundary(read_alignment_stride, earlier_start, earlier_end, later_start, later_end); diff --git a/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp index 398ce019adc2..d45581cb4697 100644 --- a/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp +++ b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp @@ -229,4 +229,85 @@ TEST(ParquetPrefetcher, ManyTinyContiguousRangesAreCutAtBoundary) EXPECT_EQ(reads[0].first + reads[0].second, 10 * MiB); } +/// Ranges in bytes, the same layout as in MiB with the stride 10, the minimum 1, the gap 0.5 and the task limit 2 (scaled by 1000): +/// `A = [8500, 9000)` and `C = [9400, 9600)` are requested with `B = [8800, 9400)` cancelled between them, and `D = [9700, 10100)` +/// follows `C` across the boundary at 10000. The scan to the left stops at `B`, because `B` does not allow incidental reads, +/// so the cut between `C` and `D` leaves 200 bytes before the boundary, below the minimum. The alignment walk must stop at `B` +/// as the scan does, and must not count `A` into the piece: then the guard does not cut, and `C` is read together with `D`. +TEST(ParquetPrefetcher, CancelledNonIncidentalRangeStopsAlignmentWalk) +{ + ReadOptions options; + options.min_bytes_for_seek = 500; + options.bytes_per_read_task = 2000; + options.format.parquet.read_alignment_bytes = 10000; + options.format.parquet.read_alignment_min_bytes = 1000; + + RecordingFile file(20000); + MemoryUsageDiff diff(ReadStage::ColumnData); + { + Prefetcher prefetcher; + prefetcher.init(&file, options, /*parser_shared_resources_=*/ nullptr); + + PrefetchHandle a = prefetcher.registerRange(8500, 500, /*likely_to_be_used=*/ true); + PrefetchHandle b = prefetcher.registerRange(8800, 600, /*likely_to_be_used=*/ false); + PrefetchHandle c = prefetcher.registerRange(9400, 200, /*likely_to_be_used=*/ true); + PrefetchHandle d = prefetcher.registerRange(9700, 400, /*likely_to_be_used=*/ true); + prefetcher.finalizeRanges(); + b.reset(&diff); + + prefetcher.startPrefetch({&c}, &diff); + /// Waits for the task, which makes the read. The size is the requested range; the task is checked by the reads. + EXPECT_EQ(prefetcher.getRangeData(c).size(), 200u); + + c.reset(&diff); + d.reset(&diff); + a.reset(&diff); + } + diff.finalized = true; + + const auto reads = file.getReads(); + ASSERT_EQ(reads.size(), 1u); + EXPECT_EQ(reads[0], (std::pair{9400, 700})); +} + +/// The same layout, but `B` allows incidental reads. The scan skips the cancelled `B` and includes `A`. The piece that +/// the cut would leave is `[8500, 9600)`, 1100 bytes before the boundary, which is at least the minimum, so the cut is +/// made and the task is `A`, `C`. The walk must skip `B` here as well. This checks that the barriers of a cancelled +/// range do not stop the walk when they do not apply. +TEST(ParquetPrefetcher, CancelledIncidentalRangeIsSkippedByAlignmentWalk) +{ + ReadOptions options; + options.min_bytes_for_seek = 500; + options.bytes_per_read_task = 2000; + options.format.parquet.read_alignment_bytes = 10000; + options.format.parquet.read_alignment_min_bytes = 1000; + + RecordingFile file(20000); + MemoryUsageDiff diff(ReadStage::ColumnData); + { + Prefetcher prefetcher; + prefetcher.init(&file, options, /*parser_shared_resources_=*/ nullptr); + + PrefetchHandle a = prefetcher.registerRange(8500, 500, /*likely_to_be_used=*/ true); + PrefetchHandle b = prefetcher.registerRange(8800, 600, /*likely_to_be_used=*/ true); + PrefetchHandle c = prefetcher.registerRange(9400, 200, /*likely_to_be_used=*/ true); + PrefetchHandle d = prefetcher.registerRange(9700, 400, /*likely_to_be_used=*/ true); + prefetcher.finalizeRanges(); + b.reset(&diff); + + prefetcher.startPrefetch({&c}, &diff); + /// Waits for the task, which makes the read. The size is the requested range; the task is checked by the reads. + EXPECT_EQ(prefetcher.getRangeData(c).size(), 200u); + + c.reset(&diff); + d.reset(&diff); + a.reset(&diff); + } + diff.finalized = true; + + const auto reads = file.getReads(); + ASSERT_EQ(reads.size(), 1u); + EXPECT_EQ(reads[0], (std::pair{8500, 1100})); +} + #endif From 00eb94916bda10b440c9d1648d2edbd60db2f08a Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Fri, 4 Dec 2026 14:29:53 +0100 Subject: [PATCH 30/30] Parquet v3 read alignment: find the crossing of a split subrange that starts after its neighbour A short range that is split reads its subrange, which can start after a neighbour that sorts after it by its stored start. The right scan then passes the neighbour as the later range with a smaller start than the earlier range, and `lastCrossedBoundary` took the earlier start as the first byte of the joint span. The joint span `[8000, 13000)` of the neighbour `[8000, 9000)` and the subrange `[12000, 13000)` crossed the multiple 10000, but the check reported no crossing, and the read straddled the boundary although neither requested range did. The joint span now starts at the smaller of the two starts. When the later range starts before the earlier one, the guard cannot measure the part before the boundary, because the piece is walked from the earlier range and the neighbour is not in it. With a minimum of zero the cut is made, as for any crossing. With a positive minimum the read stays merged, as it did before, so a cut never leaves a fragment below the minimum. Codex review comment: https://github.com/Altinity/ClickHouse/pull/2978#discussion_r4800262034 Co-authored-by: Cursor --- .../Formats/Impl/Parquet/Prefetcher.cpp | 14 +++- ..._prefetcher_cancelled_range_coalescing.cpp | 67 +++++++++++++++++++ 2 files changed, 79 insertions(+), 2 deletions(-) diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index 2007d031ba7f..6f2e20097932 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -315,14 +315,17 @@ static size_t extentEnd(size_t start, size_t end) /// The joint span [earlier_start, joint_end) of a pair crosses a multiple of the stride iff its first and last /// bytes are in different windows of the grid. This includes the case when one of the ranges crosses the multiple -/// on its own. Returns the last multiple of the stride inside the joint span (it is after earlier_start), or +/// on its own. Returns the last multiple of the stride inside the joint span (it is after the start of the joint span), or /// nullopt if the span does not cross any. static std::optional lastCrossedBoundary( size_t stride, size_t earlier_start, size_t earlier_end, size_t later_start, size_t later_end) { + /// The later range can start before the earlier one, when the earlier one is a split subrange that starts after + /// the neighbour (see AlignmentInitialRange), so the joint span starts at the smaller of the two starts. + const size_t joint_start = std::min(earlier_start, later_start); const size_t joint_end = std::max(extentEnd(earlier_start, earlier_end), extentEnd(later_start, later_end)); const size_t last_window = (joint_end - 1) / stride; - if (earlier_start / stride == last_window) + if (joint_start / stride == last_window) return std::nullopt; return last_window * stride; } @@ -340,6 +343,13 @@ bool Prefetcher::shouldCutForAlignment( if (read_alignment_min_bytes == 0) return true; + /// When the later range starts before the earlier one, the earlier one is a split subrange that starts after the + /// neighbour. The piece below is measured from the earlier range, and the neighbour is not in it, so the guard + /// cannot measure the part before the boundary here. The read is kept merged: the guard skips the cut, as it does + /// when the part is small, so a cut never leaves a fragment below the minimum. + if (later_start < earlier_start) + return false; + /// Cutting leaves the piece of neighbouring ranges that ends with the earlier range as a separate read. /// The part of the piece that the guard measures is the part inside one window of the grid, up to the /// boundary or up to the end of the earlier range, whichever comes first: the later range, which may diff --git a/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp index d45581cb4697..6d875535bb24 100644 --- a/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp +++ b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp @@ -270,6 +270,73 @@ TEST(ParquetPrefetcher, CancelledNonIncidentalRangeStopsAlignmentWalk) EXPECT_EQ(reads[0], (std::pair{9400, 700})); } +/// A split short range whose subrange starts after the neighbour that sorts after it: the neighbour `[8000, 9000)` starts +/// before the subrange `[12000, 13000)`. The joint span `[8000, 13000)` crosses the multiple 10000, although neither +/// requested range does. With no minimum the cut is made, so the subrange is read alone. +TEST(ParquetPrefetcher, SplitSubrangeAfterNeighbourCutsAtBoundary) +{ + ReadOptions options; + options.min_bytes_for_seek = 20000; + options.bytes_per_read_task = 100000; + options.format.parquet.read_alignment_bytes = 10000; + options.format.parquet.read_alignment_min_bytes = 0; + + RecordingFile file(20000); + MemoryUsageDiff diff(ReadStage::ColumnData); + { + Prefetcher prefetcher; + prefetcher.init(&file, options, /*parser_shared_resources_=*/ nullptr); + PrefetchHandle parent = prefetcher.registerRange(5000, 10000, /*likely_to_be_used=*/ true); + PrefetchHandle neighbour = prefetcher.registerRange(8000, 1000, /*likely_to_be_used=*/ true); + prefetcher.finalizeRanges(); + + auto children = prefetcher.splitRange(std::move(parent), {{12000, 1000}}, /*likely_to_be_used=*/ false); + ASSERT_EQ(children.size(), 1u); + EXPECT_EQ(prefetcher.getRangeData(children[0]).size(), 1000u); + + children[0].reset(&diff); + neighbour.reset(&diff); + } + diff.finalized = true; + + const auto reads = file.getReads(); + ASSERT_EQ(reads.size(), 1u); + EXPECT_EQ(reads[0], (std::pair{12000, 1000})); +} + +/// The same layout with a minimum of 1000. The guard cannot measure the part before the boundary for this pair, so it does +/// not cut, and the read stays merged across the boundary. This keeps the guard from leaving a fragment below the minimum. +TEST(ParquetPrefetcher, SplitSubrangeAfterNeighbourStaysMergedWithMinimum) +{ + ReadOptions options; + options.min_bytes_for_seek = 20000; + options.bytes_per_read_task = 100000; + options.format.parquet.read_alignment_bytes = 10000; + options.format.parquet.read_alignment_min_bytes = 1000; + + RecordingFile file(20000); + MemoryUsageDiff diff(ReadStage::ColumnData); + { + Prefetcher prefetcher; + prefetcher.init(&file, options, /*parser_shared_resources_=*/ nullptr); + PrefetchHandle parent = prefetcher.registerRange(5000, 10000, /*likely_to_be_used=*/ true); + PrefetchHandle neighbour = prefetcher.registerRange(8000, 1000, /*likely_to_be_used=*/ true); + prefetcher.finalizeRanges(); + + auto children = prefetcher.splitRange(std::move(parent), {{12000, 1000}}, /*likely_to_be_used=*/ false); + ASSERT_EQ(children.size(), 1u); + EXPECT_EQ(prefetcher.getRangeData(children[0]).size(), 1000u); + + children[0].reset(&diff); + neighbour.reset(&diff); + } + diff.finalized = true; + + const auto reads = file.getReads(); + ASSERT_EQ(reads.size(), 1u); + EXPECT_EQ(reads[0], (std::pair{8000, 5000})); +} + /// The same layout, but `B` allows incidental reads. The scan skips the cancelled `B` and includes `A`. The piece that /// the cut would leave is `[8500, 9600)`, 1100 bytes before the boundary, which is at least the minimum, so the cut is /// made and the task is `A`, `C`. The walk must skip `B` here as well. This checks that the barriers of a cancelled