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..eaa632407b253 100644 --- a/src/Core/FormatFactorySettings.h +++ b/src/Core/FormatFactorySettings.h @@ -235,6 +235,18 @@ 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_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. +)", 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..4c04b05609dee 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -54,6 +54,10 @@ 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."}, + {"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 c169db9af1df1..72a4311f154ef 100644 --- a/src/Formats/FormatFactory.cpp +++ b/src/Formats/FormatFactory.cpp @@ -231,6 +231,10 @@ 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_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]; 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..3d1886b7dd574 100644 --- a/src/Formats/FormatSettings.h +++ b/src/Formats/FormatSettings.h @@ -386,6 +386,10 @@ 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_ttfb_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..a0802a144f133 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,10 @@ 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_; determineReadModeAndFileSize(reader_, options); range_sets.resize(1); @@ -95,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: @@ -426,6 +440,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 +456,49 @@ void Prefetcher::scheduleTask(Task * task) }); } +bool Prefetcher::hedgeReadSync(Task * task) +{ + /// 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. + 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 +517,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_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)) + { + 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); @@ -542,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 (...) @@ -562,8 +641,12 @@ Prefetcher::Task::State Prefetcher::runTask(Task * task) chassert(s == Task::State::Deallocated); task->buf = {}; task->cached_region.reset(); + 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 135492aff741b..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; } @@ -151,9 +153,23 @@ 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; + /// 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 + /// 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 +199,14 @@ 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_ttfb_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 +232,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..8a5304ed25127 100644 --- a/src/Processors/Formats/Impl/Parquet/ReadCommon.h +++ b/src/Processors/Formats/Impl/Parquet/ReadCommon.h @@ -36,6 +36,15 @@ 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_ttfb_threshold_ms = 0; + size_t hedged_read_max_bytes = 0; + size_t hedged_read_max_inflight = 0; }; struct SharedResourcesExt @@ -279,6 +288,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 +305,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..86ab4e3372aa5 100644 --- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp @@ -59,6 +59,11 @@ 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_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) format_filter_info = std::make_shared(); } 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 +"