diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index e3f0c10d8c13..ef6e8d78bc37 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -1853,6 +1853,9 @@ 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(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) \ 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 c04a65b5613e..d32fb4e0a68a 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. 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. )", 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 0137eb8e8b0f..1752027b178a 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -55,6 +55,8 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() {"allow_aggregate_function_states_in_open_formats", false, false, "New setting allowing aggregate function states in Parquet files and Iceberg tables. With it disabled, the ClickHouse types recorded in them are not applied, a state column reads as `String`, and writing a state throws `SUPPORT_IS_DISABLED`."}, {"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 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/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index f657a7b86d0c..e44bc076bc83 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -243,6 +243,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 fbb0478bb314..e076ca03ec12 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 4b17ca058090..6f2e20097932 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -8,7 +8,9 @@ #include #include #include +#include +#include #include namespace DB::ErrorCodes @@ -23,6 +25,9 @@ namespace ProfileEvents extern const Event ParquetPrefetcherReadRandomRead; extern const Event ParquetPrefetcherReadSeekAndRead; extern const Event ParquetPrefetcherReadEntireFile; + extern const Event ParquetPrefetcherPartAlignedTasks; + extern const Event ParquetPrefetcherAlignmentSkippedSmall; + extern const Event ParquetPrefetcherAlignmentWalkLimited; } namespace DB::Parquet @@ -32,6 +37,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); @@ -298,6 +305,185 @@ 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); +} + +/// 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 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 (joint_start / stride == last_window) + return std::nullopt; + return last_window * stride; +} + +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, AlignmentWalkBudget & budget) const +{ + chassert(read_alignment_stride > 0); + + 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; + + /// 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 + /// 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); + + /// 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 = 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, budget); + if (budget.exhausted) + return false; + small = std::min(read_alignment_stride, part_end - 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, const AlignmentInitialRange & initial, size_t idx, size_t start, size_t end, size_t lower_bound, + 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 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 + /// 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. + /// + /// 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; + size_t later_idx = idx; + while (piece_start > lower_bound) + { + size_t earlier_idx = later_idx; + RequestState::State s; + size_t earlier_start = 0; + size_t earlier_end = 0; + do + { + if (earlier_idx == 0) + return piece_start; + --earlier_idx; + if (budget.steps_left == 0) + { + budget.exhausted = true; + return piece_start; + } + --budget.steps_left; + + /// 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; + + /// 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 auto crossed_boundary = lastCrossedBoundary(read_alignment_stride, earlier_start, earlier_end, later_start, later_end); + + bool cut = false; + if (crossed_boundary) + { + const AlignmentDecisionKey key{earlier_idx, later_start, later_end}; + 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, budget); + --budget.depth; + if (budget.exhausted) + return piece_start; + decisions.emplace(key, cut); + } + else + cut = it->second; + } + if (cut) + 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()); @@ -331,6 +517,70 @@ 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: 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. 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 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; + /// 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}; + + 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; + /// 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) + { + walk_limited = true; + return false; + } + if (!cut) + return false; + part_boundary_constrained = true; + return true; + }; + + /// 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; for (size_t idx = range_idx; idx > 0; --idx) @@ -344,6 +594,13 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, const auto s = r.request->state.load(std::memory_order_relaxed); if (s == RequestState::State::HasRange) { + /// 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(idx - 1, r.start, r.end, left_edge_start, left_edge_end)) + break; + left_edge_start = r.start; + left_edge_end = r.end; + /// Include this range in the task. start_idx = idx - 1; total_length_of_covered_ranges += r.length(); @@ -370,7 +627,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)) @@ -379,6 +636,12 @@ 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_idx, right_edge_start, right_edge_end, r.start, r.end)) + break; + right_edge_idx = idx; + right_edge_start = r.start; + right_edge_end = r.end; + end_idx = idx + 1; total_length_of_covered_ranges += r.length(); end_offset = std::max(end_offset, r.end); @@ -390,8 +653,16 @@ 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) + 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(); task.offset = start_offset; @@ -420,6 +691,9 @@ void Prefetcher::pickRangesAndCreateTaskIfNotExists(RequestState * initial_req, lock.unlock(); + 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 3c31a6d42027..8921663ce157 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -1,10 +1,13 @@ #pragma once +#include #include #include +#include #include #include +#include namespace DB { @@ -185,6 +188,16 @@ class Prefetcher size_t min_bytes_for_seek{}; 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 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; + + /// 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. @@ -206,6 +219,49 @@ 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. + /// + /// 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, because the range that starts a splitting + /// 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; + }; + /// 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 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 + { + static constexpr size_t steps_per_range = 16; + static constexpr size_t max_depth = 64; + + explicit AlignmentWalkBudget(size_t ranges_count) : steps_left(steps_per_range * ranges_count) {} + + size_t steps_left; + 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, 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, 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 new file mode 100644 index 000000000000..6d875535bb24 --- /dev/null +++ b/src/Processors/Formats/Impl/Parquet/tests/gtest_prefetcher_cancelled_range_coalescing.cpp @@ -0,0 +1,380 @@ +#include +#include +#if USE_PARQUET + +#include + +#include +#include +#include + +#include +#include +#include +#include + +namespace ProfileEvents +{ + extern const Event ParquetPrefetcherAlignmentWalkLimited; +} + +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})); +} + +/// 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})); +} + +/// 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. 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; + 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})); + 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 +/// 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); +} + +/// 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})); +} + +/// 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 +/// 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 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..ea4476a99971 --- /dev/null +++ b/tests/queries/0_stateless/05819_parquet_read_alignment.reference @@ -0,0 +1,21 @@ +-- 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 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 +-- 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 new file mode 100755 index 000000000000..212c33923ea4 --- /dev/null +++ b/tests/queries/0_stateless/05819_parquet_read_alignment.sh @@ -0,0 +1,131 @@ +#!/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" + +# `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 " + 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 +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" + +run() +{ + ${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}. (The third number is for the checks of the guard, see count_fragments.) +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" +} + +# 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)" +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" + +echo "-- read alignment engages only when enabled, and the minimum 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, + 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 + AND query_id LIKE '${CLICKHOUSE_TEST_UNIQUE_NAME}_%' AND type = 'QueryFinish' AND current_database = currentDatabase() + 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" + +# 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 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/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("&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}" 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}"