diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index c9b79615610b7..1e39c346dd2b1 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 4951eda47549b..1f9a8b02ebf6c 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 f93c54df707b1..0c5ebfddd1f7f 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 c169db9af1df1..b785ddedfa94f 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 315bf7ab8cf05..201b07e623c96 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 c673a467b7279..3d88762584dd6 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 135492aff741b..aa37cae3d6015 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 0000000000000..c675ead95d564 --- /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 0000000000000..f60e11d035a7f --- /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}"