From d4021efae36baeb2097c9ccac6065a675ea44983 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Sat, 8 Aug 2026 09:52:27 +0300 Subject: [PATCH 1/3] Parquet v3: hedged reads to cut S3 GET tail latency (Phase A) Standard S3 GET has a fat tail (p50 ~5 ms vs p99 100+ ms), so a single slow read on the critical path stalls a decode task (visible as large ParquetFetchWaitTimeMicroseconds). Hedging: if a read a consumer is blocked on doesn't finish within a threshold, issue a duplicate read and use whichever returns first (S3 GET is idempotent). Phase A (this commit) runs the hedge synchronously on the already-blocked consumer thread: getRangeData waits up to the threshold via a new CompletionNotification::wait_for, then reads the same range into task->hedge_buf and serves from it, notifying so sharers wake. This has no async-lifetime hazard - the hedge finishes before the PrefetchHandle is released. A fully async race (Phase B) is deferred: it would need decreaseTaskRefcount to defer freeing hedge_buf until an in-flight hedge finishes (the refcount/Deallocated path assumes a single reader), which risks a use-after-free if done naively. Scope: remote (RandomRead) reads only, no larger than a size cap (latency, not throughput), one hedge per task, bounded by a concurrency cap (cost control). Settings (all experimental, off by default): * input_format_parquet_hedged_read_threshold_ms (0 = off) * input_format_parquet_hedged_read_max_bytes (default 4 MiB) * input_format_parquet_hedged_read_max_inflight (default 4) ProfileEvents: ParquetPrefetcherHedgedReads, ParquetPrefetcherHedgedWins. Signed-off-by: UnamedRus --- src/Common/ProfileEvents.cpp | 2 + src/Core/FormatFactorySettings.h | 9 +++ src/Core/SettingsChangesHistory.cpp | 3 + src/Formats/FormatFactory.cpp | 3 + src/Formats/FormatSettings.h | 3 + .../Formats/Impl/Parquet/Prefetcher.cpp | 68 ++++++++++++++++++- .../Formats/Impl/Parquet/Prefetcher.h | 28 +++++++- .../Formats/Impl/Parquet/ReadCommon.cpp | 38 +++++++++++ .../Formats/Impl/Parquet/ReadCommon.h | 12 ++++ .../Impl/ParquetV3BlockInputFormat.cpp | 4 ++ 10 files changed, 168 insertions(+), 2 deletions(-) diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index c9b79615610b7..a19aea552b519 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(ParquetPrefetcherHedgedReads, "The number of hedged (duplicate) reads issued by DB::Parquet::Prefetcher to cut read tail latency", ValueType::Number) \ + M(ParquetPrefetcherHedgedWins, "The number of hedged reads that produced the result used (beat or replaced the primary read) in DB::Parquet::Prefetcher", 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..8632932314baa 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -235,6 +235,15 @@ 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_hedged_read_threshold_ms, 0, R"( +Experimental. Tail-latency mitigation for the Parquet v3 reader on remote object storage: if a read a query is blocked on has not completed within this many milliseconds, issue a duplicate (hedged) request and use whichever returns first. Cuts the S3 GET p99 tail at the cost of a few extra requests. 0 disables. Only reads no larger than `input_format_parquet_hedged_read_max_bytes` are hedged, and at most `input_format_parquet_hedged_read_max_inflight` hedges run at once. +)", 0) \ + DECLARE(UInt64, input_format_parquet_hedged_read_max_bytes, 4194304, R"( +Experimental. Only hedge Parquet reads (see `input_format_parquet_hedged_read_threshold_ms`) no larger than this - hedging targets latency of small/critical reads, not throughput of large coalesced reads. 0 = no size limit. Default 4 MiB. +)", 0) \ + DECLARE(UInt64, input_format_parquet_hedged_read_max_inflight, 4, R"( +Experimental. Cap on concurrent hedged Parquet reads (see `input_format_parquet_hedged_read_threshold_ms`), so a slow region cannot double all traffic. Default 4. )", 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..f15e9a7f8e0bc 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -54,6 +54,9 @@ 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_hedged_read_threshold_ms", 0, 0, "New experimental setting: hedge a Parquet read (issue a duplicate, take the winner) if it exceeds this many ms, to cut the S3 GET tail latency. 0 disables."}, + {"input_format_parquet_hedged_read_max_bytes", 4194304, 4194304, "New experimental setting: only hedge Parquet reads no larger than this many bytes. Default 4 MiB."}, + {"input_format_parquet_hedged_read_max_inflight", 4, 4, "New experimental setting: cap on concurrent hedged Parquet reads. Default 4."}, }); addSettingsChanges(settings_changes_history, "26.8.35.20001.altinityantalya", { diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index c169db9af1df1..54806c6f11dad 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -231,6 +231,9 @@ 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.hedged_read_threshold_ms = settings[Setting::input_format_parquet_hedged_read_threshold_ms]; + format_settings.parquet.hedged_read_max_bytes = settings[Setting::input_format_parquet_hedged_read_max_bytes]; + format_settings.parquet.hedged_read_max_inflight = settings[Setting::input_format_parquet_hedged_read_max_inflight]; 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..dc578fe51f51c 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -386,6 +386,9 @@ struct FormatSettings size_t footer_read_size = 0; bool page_filter_push_down = true; bool use_offset_index = true; + UInt64 hedged_read_threshold_ms = 0; + UInt64 hedged_read_max_bytes = 4194304; + UInt64 hedged_read_max_inflight = 4; 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..ac7ec2edc2e60 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -22,6 +22,8 @@ namespace ProfileEvents extern const Event ParquetPrefetcherReadRandomRead; extern const Event ParquetPrefetcherReadSeekAndRead; extern const Event ParquetPrefetcherReadEntireFile; + extern const Event ParquetPrefetcherHedgedReads; + extern const Event ParquetPrefetcherHedgedWins; } namespace DB::Parquet @@ -31,6 +33,9 @@ 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; + hedged_read_threshold_ms = options.hedged_read_threshold_ms; + hedged_read_max_bytes = options.hedged_read_max_bytes; + hedged_read_max_inflight = options.hedged_read_max_inflight; parser_shared_resources = parser_shared_resources_; determineReadModeAndFileSize(reader_, options); range_sets.resize(1); @@ -426,6 +431,7 @@ void Prefetcher::decreaseTaskRefcount(Task * task, size_t amount) { task->buf = {}; task->cached_region.reset(); + task->hedge_buf = {}; // hedge (if any) is synchronous and already finished by now } } @@ -441,6 +447,44 @@ void Prefetcher::scheduleTask(Task * task) }); } +bool Prefetcher::hedgeReadSync(Task * task) +{ + /// Wait up to the threshold for the primary; if it finishes in time, no hedge is needed. + if (task->completion.wait_for(hedged_read_threshold_ms)) + return false; + + /// Primary is slow. Only one consumer hedges a given task. + bool expected = false; + if (!task->hedge_started.compare_exchange_strong(expected, true)) + return false; // someone else is hedging (or already did) -> fall back to completion.wait() + + /// Cost cap: bound concurrent hedges so a slow region can't double all traffic. + if (hedges_inflight.fetch_add(1) >= hedged_read_max_inflight) + { + hedges_inflight.fetch_sub(1); + return false; + } + + ProfileEvents::increment(ProfileEvents::ParquetPrefetcherHedgedReads); + bool ok = false; + try + { + /// Read the same range on this (already-blocked) consumer thread, racing the primary. + task->hedge_buf.resize(task->length); + readSync(task->hedge_buf.data(), task->length, task->offset); + task->hedge_winner.store(2, std::memory_order_release); + task->completion.notify(); // wake sharers waiting on the primary; they'll use hedge_buf + ProfileEvents::increment(ProfileEvents::ParquetPrefetcherHedgedWins); + ok = true; + } + catch (...) + { + task->hedge_buf = {}; // hedge failed; fall back to the primary read + } + hedges_inflight.fetch_sub(1); + return ok; +} + std::span Prefetcher::getRangeData(const PrefetchHandle & request) { const RequestState * req = request.request; @@ -459,12 +503,33 @@ std::span Prefetcher::getRangeData(const PrefetchHandle & request) if (s == Task::State::Running) // (not `else`, the runTask above may return Running) { - task->completion.wait(); + /// Hedging: if the primary read hasn't finished within the threshold, issue a duplicate + /// read to cut the S3 GET tail. Eligible only for real (non-cached) remote reads no + /// larger than the size cap. hedgeReadSync waits up to the threshold itself. + bool served_by_hedge = false; + if (hedged_read_threshold_ms > 0 && read_mode == ReadMode::RandomRead + && !task->cached_region.has_value() && task->length > 0 + && (hedged_read_max_bytes == 0 || task->length <= hedged_read_max_bytes)) + { + served_by_hedge = hedgeReadSync(task); + } + + if (!served_by_hedge) + task->completion.wait(); s = task->state.load(); } ProfileEvents::increment(ProfileEvents::ParquetFetchWaitTimeMicroseconds, wait_time.elapsedMicroseconds()); } + + /// If a hedge produced the data, use it regardless of the primary's state (which may still be + /// Running, or even Exception if the primary failed but the hedge succeeded). + if (task->hedge_winner.load(std::memory_order_acquire) == 2) + { + chassert(req->task_offset + req->length <= task->hedge_buf.size()); + return std::span(task->hedge_buf.data() + req->task_offset, req->length); + } + if (s == Task::State::Exception) rethrowException(task); chassert(s == Task::State::Done); @@ -562,6 +627,7 @@ Prefetcher::Task::State Prefetcher::runTask(Task * task) chassert(s == Task::State::Deallocated); task->buf = {}; task->cached_region.reset(); + task->hedge_buf = {}; } task->completion.notify(); diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index 135492aff741b..9297ee4b60d27 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -151,9 +151,18 @@ class Prefetcher std::atomic state {State::Scheduled}; /// How many RequestState-s in HasTask state point to this Task. std::atomic refcount {}; - /// Notified when the state changes from Running to Done or Exception. + /// Notified when the state changes from Running to Done or Exception (by the primary read, or + /// by a hedge read - whichever finishes first). CompletionNotification completion; std::exception_ptr exception; + + /// Hedging (tail-latency mitigation): a second read of the same range, raced against the + /// primary. Whichever finishes first CAS-wins `hedge_winner` (1 = primary, 2 = hedge) and + /// notifies `completion`; getRangeData then returns the winner's buffer. `hedge_buf` holds + /// the hedge read; `hedge_started` guards launching it at most once. + PaddedPODArray hedge_buf; + std::atomic hedge_winner {0}; + std::atomic hedge_started {false}; }; enum class ReadMode @@ -183,6 +192,13 @@ class Prefetcher size_t min_bytes_for_seek{}; size_t bytes_per_read_task{}; + /// Hedged reads (tail-latency mitigation). Set in init(), read-only after. hedges_inflight is the + /// live count, bounded by hedged_read_max_inflight. + size_t hedged_read_threshold_ms = 0; + size_t hedged_read_max_bytes = 0; + size_t hedged_read_max_inflight = 0; + std::atomic hedges_inflight {0}; + std::shared_ptr shutdown = std::make_shared(); /// Locked when creating a Task. @@ -208,6 +224,16 @@ class Prefetcher void scheduleTask(Task * task); Task::State runTask(Task * task); [[noreturn]] void rethrowException(Task * task); + + /// Issue a duplicate (hedged) read of `task`'s range when the primary is slow, to cut tail + /// latency. Phase A: the read runs synchronously on the calling (already-blocked) consumer + /// thread into task->hedge_buf; on success sets hedge_winner=2 and notifies so sharers wake. + /// Returns true if a usable hedge result was produced. At most once per task (hedge_started + /// guard), bounded by hedged_read_max_inflight, and only for real (non-cached) remote reads. + /// NOTE: a fully async race (Phase B) would need decreaseTaskRefcount to defer freeing + /// hedge_buf until an in-flight hedge finishes (the refcount/Deallocated path assumes one + /// reader) - deferred to avoid a use-after-free on hedge_buf. + bool hedgeReadSync(Task * task); }; /// Pins a pre-registered range that we may want to read. diff --git a/src/Processors/Formats/Impl/Parquet/ReadCommon.cpp b/src/Processors/Formats/Impl/Parquet/ReadCommon.cpp index 736f8ec0ed9b0..beedef04a9e88 100644 --- a/src/Processors/Formats/Impl/Parquet/ReadCommon.cpp +++ b/src/Processors/Formats/Impl/Parquet/ReadCommon.cpp @@ -3,6 +3,8 @@ #include #include +#include + namespace DB::Parquet { @@ -58,6 +60,35 @@ void CompletionNotification::notify() futexWake(&val, INT32_MAX); } +bool CompletionNotification::wait_for(UInt64 timeout_ms) +{ + UInt32 n = val.load(std::memory_order_acquire); + if (n == NOTIFIED) + return true; + if (n == EMPTY) + { + if (!val.compare_exchange_strong(n, WAITING)) + { + if (n == NOTIFIED) + return true; + chassert(n == WAITING); + } + } + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); + while (true) + { + n = val.load(); + if (n == NOTIFIED) + return true; + chassert(n == WAITING); + const auto now = std::chrono::steady_clock::now(); + if (now >= deadline) + return false; + const UInt64 remaining_ns = std::chrono::duration_cast(deadline - now).count(); + futexTimedWait(&val, WAITING, remaining_ns); // may wake spuriously / on partial timeout; loop re-checks + } +} + #else bool CompletionNotification::check() const @@ -77,6 +108,13 @@ void CompletionNotification::notify() promise.set_value(); } +bool CompletionNotification::wait_for(UInt64 timeout_ms) +{ + if (check()) + return true; + return future.wait_for(std::chrono::milliseconds(timeout_ms)) == std::future_status::ready; +} + #endif } diff --git a/src/Processors/Formats/Impl/Parquet/ReadCommon.h b/src/Processors/Formats/Impl/Parquet/ReadCommon.h index 60c7418672c4d..db49bf715ead1 100644 --- a/src/Processors/Formats/Impl/Parquet/ReadCommon.h +++ b/src/Processors/Formats/Impl/Parquet/ReadCommon.h @@ -36,6 +36,14 @@ struct ReadOptions /// probability becomes very high. E.g. if bloom filter has 1% false positive probability, /// searching for 100 elements would have 63% false positive probability. size_t bloom_filter_max_set_size = 100; + + /// Hedged reads (tail-latency mitigation): if a read a consumer is blocked on hasn't completed + /// within hedged_read_threshold_ms, issue a duplicate read and take whichever returns first. + /// 0 = off. Only reads no larger than hedged_read_max_bytes are hedged (latency, not throughput), + /// and at most hedged_read_max_inflight hedges run concurrently (cost cap). EXPERIMENTAL. + size_t hedged_read_threshold_ms = 0; + size_t hedged_read_max_bytes = 0; + size_t hedged_read_max_inflight = 0; }; struct SharedResourcesExt @@ -279,6 +287,8 @@ class CompletionNotification public: bool check() const; void wait(); + /// Wait up to timeout_ms. Returns true if notified, false on timeout. + bool wait_for(UInt64 timeout_ms); void notify(); }; @@ -294,6 +304,8 @@ class CompletionNotification public: bool check() const; void wait(); + /// Wait up to timeout_ms. Returns true if notified, false on timeout. + bool wait_for(UInt64 timeout_ms); void notify(); }; diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp index 9aecc0ffcd696..2ab44a05665dd 100644 --- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp @@ -59,6 +59,10 @@ ParquetV3BlockInputFormat::ParquetV3BlockInputFormat( read_options.min_bytes_for_seek = min_bytes_for_seek; read_options.bytes_per_read_task = min_bytes_for_seek * 4; + /// Hedged reads (tail-latency mitigation). + read_options.hedged_read_threshold_ms = read_options.format.parquet.hedged_read_threshold_ms; + read_options.hedged_read_max_bytes = read_options.format.parquet.hedged_read_max_bytes; + read_options.hedged_read_max_inflight = read_options.format.parquet.hedged_read_max_inflight; if (!format_filter_info) format_filter_info = std::make_shared(); } From afe806d42ac15f4d53290d0e17097929d3f27ac0 Mon Sep 17 00:00:00 2001 From: UnamedRus Date: Tue, 11 Aug 2026 06:01:46 +0300 Subject: [PATCH 2/3] Parquet v3: time-to-first-byte trigger for hedged reads The existing `input_format_parquet_hedged_read_threshold_ms` hedges a remote Parquet read once its *total* time exceeds a budget. On object storage that conflates two very different situations: a connection that has stalled (no bytes yet) and a large transfer that is streaming normally but simply takes a while. Budgeting on total time either hedges healthy large reads (wasteful duplicate GETs) or sets the budget so high it no longer cuts the stall tail. Add `input_format_parquet_hedged_read_ttfb_threshold_ms`: fire the hedge when the primary read has not received its *first byte* within the threshold. Time-to-first-byte is largely independent of read size, so this isolates a stalled/slow frontend from a slow-but-progressing transfer. When set (> 0) it takes precedence over the total-time threshold; both remain bounded by `input_format_parquet_hedged_read_max_bytes` and `input_format_parquet_hedged_read_max_inflight`. Mechanism: the primary read now passes a progress callback into `readBigAt` that notifies a new per-task `first_byte` latch on the first reported bytes; `hedgeReadSync` waits on `first_byte` (TTFB mode) instead of `completion`. `first_byte` is also notified unconditionally when the primary finishes, so a read that produced no progress callback (cached region, split path) never leaves a hedge waiting. Measured on a synthetic wide-Iceberg table (62x1 GiB files, q reads ~690 MiB across part-sized S3 GETs, v3 + parallel Iceberg metadata): ttfb_ms p50ms maxms readMiB hedges wins 0(off) 6558 7499 690 0 0 5 6149 6490 1075 158 158 20 5987 6179 1043 133 133 40 5341 5942 749 21 21 At 40 ms: p50 -19%, tail max -21%, +9% bytes (21 hedges, all winning) - the trigger fires only on genuinely stalled frontends. Result is unchanged with the hedge on (identical output hash across thresholds); the loser read is discarded. Co-Authored-By: Claude Opus 4.8 (1M context) Signed-off-by: UnamedRus --- src/Core/FormatFactorySettings.h | 3 ++ src/Core/SettingsChangesHistory.cpp | 1 + src/Formats/FormatFactory.cpp | 1 + src/Formats/FormatSettings.h | 1 + .../Formats/Impl/Parquet/Prefetcher.cpp | 29 +++++++++++++++---- .../Formats/Impl/Parquet/Prefetcher.h | 12 ++++++-- .../Formats/Impl/Parquet/ReadCommon.h | 1 + .../Impl/ParquetV3BlockInputFormat.cpp | 1 + 8 files changed, 41 insertions(+), 8 deletions(-) diff --git a/src/Core/FormatFactorySettings.h b/src/Core/FormatFactorySettings.h index 8632932314baa..eaa632407b253 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -238,6 +238,9 @@ Minor tweak to how pages are read from parquet file when no page filtering is us )", 0) \ DECLARE(UInt64, input_format_parquet_hedged_read_threshold_ms, 0, R"( Experimental. Tail-latency mitigation for the Parquet v3 reader on remote object storage: if a read a query is blocked on has not completed within this many milliseconds, issue a duplicate (hedged) request and use whichever returns first. Cuts the S3 GET p99 tail at the cost of a few extra requests. 0 disables. Only reads no larger than `input_format_parquet_hedged_read_max_bytes` are hedged, and at most `input_format_parquet_hedged_read_max_inflight` hedges run at once. +)", 0) \ + DECLARE(UInt64, input_format_parquet_hedged_read_ttfb_threshold_ms, 0, R"( +Experimental. Time-to-first-byte variant of `input_format_parquet_hedged_read_threshold_ms`: issue a duplicate (hedged) Parquet read when the primary read has not received its first byte within this many milliseconds, rather than when its total time exceeds a budget. Because time-to-first-byte is largely independent of read size, this triggers on a stalled/slow connection without hedging legitimately large transfers that stream normally. When set (> 0) it takes precedence over `input_format_parquet_hedged_read_threshold_ms`. 0 disables. Still bounded by `input_format_parquet_hedged_read_max_bytes` and `input_format_parquet_hedged_read_max_inflight`. )", 0) \ DECLARE(UInt64, input_format_parquet_hedged_read_max_bytes, 4194304, R"( Experimental. Only hedge Parquet reads (see `input_format_parquet_hedged_read_threshold_ms`) no larger than this - hedging targets latency of small/critical reads, not throughput of large coalesced reads. 0 = no size limit. Default 4 MiB. diff --git a/src/Core/SettingsChangesHistory.cpp b/src/Core/SettingsChangesHistory.cpp index f15e9a7f8e0bc..4c04b05609dee 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -57,6 +57,7 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() {"input_format_parquet_hedged_read_threshold_ms", 0, 0, "New experimental setting: hedge a Parquet read (issue a duplicate, take the winner) if it exceeds this many ms, to cut the S3 GET tail latency. 0 disables."}, {"input_format_parquet_hedged_read_max_bytes", 4194304, 4194304, "New experimental setting: only hedge Parquet reads no larger than this many bytes. Default 4 MiB."}, {"input_format_parquet_hedged_read_max_inflight", 4, 4, "New experimental setting: cap on concurrent hedged Parquet reads. Default 4."}, + {"input_format_parquet_hedged_read_ttfb_threshold_ms", 0, 0, "New experimental setting: hedge a Parquet read when the primary's first byte (TTFB) has not arrived within this many ms, rather than when the whole read exceeds a budget - separates a stalled connection from a slow-but-progressing large transfer. Takes precedence over `input_format_parquet_hedged_read_threshold_ms`. 0 disables."}, }); addSettingsChanges(settings_changes_history, "26.8.35.20001.altinityantalya", { diff --git a/src/Formats/FormatFactory.cpp b/src/Formats/FormatFactory.cpp index 54806c6f11dad..72a4311f154ef 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -232,6 +232,7 @@ FormatSettings getFormatSettings(const ContextPtr & context, const Settings & se 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.hedged_read_threshold_ms = settings[Setting::input_format_parquet_hedged_read_threshold_ms]; + format_settings.parquet.hedged_read_ttfb_threshold_ms = settings[Setting::input_format_parquet_hedged_read_ttfb_threshold_ms]; format_settings.parquet.hedged_read_max_bytes = settings[Setting::input_format_parquet_hedged_read_max_bytes]; format_settings.parquet.hedged_read_max_inflight = settings[Setting::input_format_parquet_hedged_read_max_inflight]; diff --git a/src/Formats/FormatSettings.h b/src/Formats/FormatSettings.h index dc578fe51f51c..3d1886b7dd574 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -387,6 +387,7 @@ struct FormatSettings bool page_filter_push_down = true; bool use_offset_index = true; UInt64 hedged_read_threshold_ms = 0; + UInt64 hedged_read_ttfb_threshold_ms = 0; UInt64 hedged_read_max_bytes = 4194304; UInt64 hedged_read_max_inflight = 4; diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp index ac7ec2edc2e60..a0802a144f133 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.cpp @@ -34,6 +34,7 @@ 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; hedged_read_threshold_ms = options.hedged_read_threshold_ms; + hedged_read_ttfb_threshold_ms = options.hedged_read_ttfb_threshold_ms; hedged_read_max_bytes = options.hedged_read_max_bytes; hedged_read_max_inflight = options.hedged_read_max_inflight; parser_shared_resources = parser_shared_resources_; @@ -100,16 +101,24 @@ void Prefetcher::determineReadModeAndFileSize(ReadBuffer * reader_, const ReadOp } } -void Prefetcher::readSync(char * to, size_t n, size_t offset) +void Prefetcher::readSync(char * to, size_t n, size_t offset, Task * notify_first_byte) { if (offset > file_size || n > file_size - offset) throw Exception(ErrorCodes::LOGICAL_ERROR, "File read out of bounds: offset {}, length {}, file size {}", offset, n, file_size); + /// First-byte signal for TTFB-triggered hedging: notify as soon as the underlying read reports + /// progress (its first bytes). notify() is idempotent, so firing on every progress step is fine. + /// Callback return is a cancel flag (true => stop the read); we only observe first-byte progress, + /// so always return false to let the read run to completion. + std::function progress_callback; + if (notify_first_byte) + progress_callback = [notify_first_byte](size_t) { notify_first_byte->first_byte.notify(); return false; }; + size_t nread = 0; switch (read_mode) { case ReadMode::RandomRead: - nread = reader->readBigAt(to, n, offset, /*progress_callback*/ nullptr); + nread = reader->readBigAt(to, n, offset, progress_callback); ProfileEvents::increment(ProfileEvents::ParquetPrefetcherReadRandomRead); break; case ReadMode::SeekAndRead: @@ -449,8 +458,13 @@ void Prefetcher::scheduleTask(Task * task) bool Prefetcher::hedgeReadSync(Task * task) { - /// Wait up to the threshold for the primary; if it finishes in time, no hedge is needed. - if (task->completion.wait_for(hedged_read_threshold_ms)) + /// Wait for the primary before hedging. With a TTFB threshold set, wait for the primary's FIRST + /// BYTE (`first_byte` is also notified on completion, so a finished primary releases us too); + /// this hedges a stalled connection without hedging a slow-but-progressing large transfer. + /// Otherwise fall back to the legacy total-completion threshold. + const bool use_ttfb = hedged_read_ttfb_threshold_ms > 0; + if (use_ttfb ? task->first_byte.wait_for(hedged_read_ttfb_threshold_ms) + : task->completion.wait_for(hedged_read_threshold_ms)) return false; /// Primary is slow. Only one consumer hedges a given task. @@ -507,7 +521,7 @@ std::span Prefetcher::getRangeData(const PrefetchHandle & request) /// read to cut the S3 GET tail. Eligible only for real (non-cached) remote reads no /// larger than the size cap. hedgeReadSync waits up to the threshold itself. bool served_by_hedge = false; - if (hedged_read_threshold_ms > 0 && read_mode == ReadMode::RandomRead + if ((hedged_read_ttfb_threshold_ms > 0 || hedged_read_threshold_ms > 0) && read_mode == ReadMode::RandomRead && !task->cached_region.has_value() && task->length > 0 && (hedged_read_max_bytes == 0 || task->length <= hedged_read_max_bytes)) { @@ -607,7 +621,7 @@ Prefetcher::Task::State Prefetcher::runTask(Task * task) else { task->buf.resize(task->length); - readSync(task->buf.data(), task->length, task->offset); + readSync(task->buf.data(), task->length, task->offset, /*notify_first_byte=*/ task); } } catch (...) @@ -630,6 +644,9 @@ Prefetcher::Task::State Prefetcher::runTask(Task * task) task->hedge_buf = {}; } + /// Release TTFB waiters too, in case the read produced no progress callback (or took the cached + /// / split path): a finished primary must never leave a hedge waiting on first_byte. + task->first_byte.notify(); task->completion.notify(); return s; diff --git a/src/Processors/Formats/Impl/Parquet/Prefetcher.h b/src/Processors/Formats/Impl/Parquet/Prefetcher.h index 9297ee4b60d27..7e8eb92154291 100644 --- a/src/Processors/Formats/Impl/Parquet/Prefetcher.h +++ b/src/Processors/Formats/Impl/Parquet/Prefetcher.h @@ -62,8 +62,10 @@ class Prefetcher /// The returned pointer is valid as long as the PrefetchHandle is alive. std::span getRangeData(const PrefetchHandle & request); - /// Pass-through read from the underlying ReadBuffer. - void readSync(char * to, size_t n, size_t offset); + /// Pass-through read from the underlying ReadBuffer. When `notify_first_byte` is set (only on the + /// primary read path), notifies its `first_byte` when the underlying read reports its first bytes, + /// so TTFB-triggered hedging can tell a stalled connection from a slow-but-progressing transfer. + void readSync(char * to, size_t n, size_t offset, Task * notify_first_byte = nullptr); size_t getFileSize() const { return file_size; } @@ -154,6 +156,11 @@ class Prefetcher /// Notified when the state changes from Running to Done or Exception (by the primary read, or /// by a hedge read - whichever finishes first). CompletionNotification completion; + /// Notified when the primary read receives its first byte (from the readBigAt progress + /// callback), and unconditionally when the primary read finishes - so a waiter is always + /// released even if the read produced no progress callback. Used by TTFB-triggered hedging + /// (hedged_read_ttfb_threshold_ms): a hedge fires only if no first byte arrives in time. + CompletionNotification first_byte; std::exception_ptr exception; /// Hedging (tail-latency mitigation): a second read of the same range, raced against the @@ -195,6 +202,7 @@ class Prefetcher /// Hedged reads (tail-latency mitigation). Set in init(), read-only after. hedges_inflight is the /// live count, bounded by hedged_read_max_inflight. size_t hedged_read_threshold_ms = 0; + size_t hedged_read_ttfb_threshold_ms = 0; size_t hedged_read_max_bytes = 0; size_t hedged_read_max_inflight = 0; std::atomic hedges_inflight {0}; diff --git a/src/Processors/Formats/Impl/Parquet/ReadCommon.h b/src/Processors/Formats/Impl/Parquet/ReadCommon.h index db49bf715ead1..8a5304ed25127 100644 --- a/src/Processors/Formats/Impl/Parquet/ReadCommon.h +++ b/src/Processors/Formats/Impl/Parquet/ReadCommon.h @@ -42,6 +42,7 @@ struct ReadOptions /// 0 = off. Only reads no larger than hedged_read_max_bytes are hedged (latency, not throughput), /// and at most hedged_read_max_inflight hedges run concurrently (cost cap). EXPERIMENTAL. size_t hedged_read_threshold_ms = 0; + size_t hedged_read_ttfb_threshold_ms = 0; size_t hedged_read_max_bytes = 0; size_t hedged_read_max_inflight = 0; }; diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp index 2ab44a05665dd..86ab4e3372aa5 100644 --- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp @@ -61,6 +61,7 @@ ParquetV3BlockInputFormat::ParquetV3BlockInputFormat( /// Hedged reads (tail-latency mitigation). read_options.hedged_read_threshold_ms = read_options.format.parquet.hedged_read_threshold_ms; + read_options.hedged_read_ttfb_threshold_ms = read_options.format.parquet.hedged_read_ttfb_threshold_ms; read_options.hedged_read_max_bytes = read_options.format.parquet.hedged_read_max_bytes; read_options.hedged_read_max_inflight = read_options.format.parquet.hedged_read_max_inflight; if (!format_filter_info) From 000b1741fde9cf00449162172cfd61ac9c29ff2b Mon Sep 17 00:00:00 2001 From: Anton Ivashkin Date: Mon, 30 Nov 2026 17:30:39 +0100 Subject: [PATCH 3/3] Add a test for the Parquet v3 hedged reads Reads an S3 Parquet file with hedging off, with the total-time trigger, with the first-byte trigger, with the size cap and with no concurrent hedges allowed. The result must not change. `ParquetPrefetcherHedgedReads` must be zero unless hedging is enabled and within the caps, and positive with the total-time trigger. The first-byte trigger cannot be forced on a local S3 emulator, so only the unchanged result and `ParquetPrefetcherHedgedWins` not exceeding `ParquetPrefetcherHedgedReads` are checked for it. Related: https://github.com/Altinity/ClickHouse/pull/2181 Related: https://github.com/Altinity/ClickHouse/issues/2966 Co-authored-by: Cursor --- .../05815_parquet_hedged_reads.reference | 16 +++++ .../0_stateless/05815_parquet_hedged_reads.sh | 68 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 tests/queries/0_stateless/05815_parquet_hedged_reads.reference create mode 100755 tests/queries/0_stateless/05815_parquet_hedged_reads.sh diff --git a/tests/queries/0_stateless/05815_parquet_hedged_reads.reference b/tests/queries/0_stateless/05815_parquet_hedged_reads.reference new file mode 100644 index 0000000000000..e9d1fdbffcf30 --- /dev/null +++ b/tests/queries/0_stateless/05815_parquet_hedged_reads.reference @@ -0,0 +1,16 @@ +-- hedging off (default) +799980000 19980000 8939407425391640837 188890 224125 +-- hedge when the whole read exceeds the threshold: same result +799980000 19980000 8939407425391640837 188890 224125 +-- hedge when the first byte does not arrive in time (it usually arrives in time here): same result +799980000 19980000 8939407425391640837 188890 224125 +-- reads larger than the size cap are not hedged: same result +799980000 19980000 8939407425391640837 188890 224125 +-- no concurrent hedges allowed: same result +799980000 19980000 8939407425391640837 188890 224125 +-- hedged reads are issued only when enabled, within the size and concurrency caps +capped 1 +no_inflight 1 +off 1 +total 1 +ttfb 1 diff --git a/tests/queries/0_stateless/05815_parquet_hedged_reads.sh b/tests/queries/0_stateless/05815_parquet_hedged_reads.sh new file mode 100755 index 0000000000000..6d7c92ee6ec9a --- /dev/null +++ b/tests/queries/0_stateless/05815_parquet_hedged_reads.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: needs MinIO + +# Hedged reads: if a read the Parquet reader is blocked on does not finish (or does not receive its first byte) +# within a threshold, the reader issues a duplicate read of the same range and uses the one that returns first. +# The results must not change, and the hedges must be bounded by the size and concurrency caps. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +FILE="${CLICKHOUSE_TEST_UNIQUE_NAME}/hedged.parquet" +Q="${CLICKHOUSE_TEST_UNIQUE_NAME}_" + +# Several row groups with neighbouring column chunks, so that the reader issues a number of read tasks. +${CLICKHOUSE_CLIENT} -q " + INSERT INTO FUNCTION s3(s3_conn, filename = '${FILE}', format = Parquet) + SELECT + number AS k, + number % 1000 AS a, + cityHash64(number) AS b, + toString(number) AS s1, + toString(number * 7) AS s2 + FROM numbers(40000) + SETTINGS s3_truncate_on_insert = 1, output_format_parquet_row_group_size = 10000, + output_format_parquet_compression_method = 'none' +" + +run() +{ + ${CLICKHOUSE_CLIENT} --query_id="${Q}$1" -q " + SELECT sum(k), sum(a), sum(b), sum(length(s1)), sum(length(s2)) + FROM s3(s3_conn, filename = '${FILE}', format = Parquet, structure = 'k UInt64, a UInt32, b UInt64, s1 String, s2 String') + SETTINGS $2 + " +} + +echo "-- hedging off (default)" +run off "input_format_parquet_hedged_read_threshold_ms = 0" +echo "-- hedge when the whole read exceeds the threshold: same result" +run total "input_format_parquet_hedged_read_threshold_ms = 1" +echo "-- hedge when the first byte does not arrive in time (it usually arrives in time here): same result" +run ttfb "input_format_parquet_hedged_read_ttfb_threshold_ms = 1" +echo "-- reads larger than the size cap are not hedged: same result" +run capped "input_format_parquet_hedged_read_threshold_ms = 1, input_format_parquet_hedged_read_max_bytes = 1" +echo "-- no concurrent hedges allowed: same result" +run no_inflight "input_format_parquet_hedged_read_threshold_ms = 1, input_format_parquet_hedged_read_max_inflight = 0" + +${CLICKHOUSE_CLIENT} -q "SYSTEM FLUSH LOGS query_log" + +# With parallel replicas, `s3` is rewritten to `s3Cluster` and the files are read by secondary queries, +# which run with `current_database = 'default'`, so the events are summed over `initial_query_id`. +echo "-- hedged reads are issued only when enabled, within the size and concurrency caps" +${CLICKHOUSE_CLIENT} -q " + SELECT + substring(initial_query_id, length('${Q}') + 1) AS name, + multiIf( + name IN ('off', 'capped', 'no_inflight'), sum(ProfileEvents['ParquetPrefetcherHedgedReads']) = 0, + name = 'ttfb', sum(ProfileEvents['ParquetPrefetcherHedgedWins']) <= sum(ProfileEvents['ParquetPrefetcherHedgedReads']), + sum(ProfileEvents['ParquetPrefetcherHedgedReads']) > 0 AND sum(ProfileEvents['ParquetPrefetcherHedgedWins']) > 0) AS ok + FROM system.query_log + WHERE event_date >= yesterday() AND event_time >= now() - 600 + AND initial_query_id LIKE '${Q}%' AND type = 'QueryFinish' + AND (current_database = currentDatabase() OR NOT is_initial_query) + GROUP BY name + ORDER BY name +"