Skip to content

Parquet hedged reads - #2979

Open
ianton-ru wants to merge 54 commits into
antalya-26.8from
feature/antalya-26.8/parquet-hedged-reads
Open

ianton-ru wants to merge 54 commits into
antalya-26.8from
feature/antalya-26.8/parquet-hedged-reads

Conversation

@ianton-ru

Copy link
Copy Markdown

Part of #2181 (Parquet v3 reader): hedged reads. This part works on its own.

A single slow S3 GET on the critical path stalls a decode task. Typical S3 latency has a long tail (p50 around 5 ms, p99 above 100 ms), which shows up as a large ParquetFetchWaitTimeMicroseconds. With hedging, when a read that a consumer is blocked on does not finish within a threshold, the reader issues a duplicate read of the same range and uses the one that finishes first. A GET of a byte range is idempotent, so the duplicate is safe. The slower read is discarded.

The hedge runs synchronously on the consumer thread that is already blocked, so it finishes before the task buffer is released. A fully asynchronous race is not part of this PR: it would need the task refcount path to defer freeing the hedge buffer until an in-flight hedge finishes.

Hedging applies only to remote (random-access) reads, to reads no larger than a size cap (it targets latency, not throughput), at most once per read task, and with a cap on concurrent hedges to bound the extra traffic. New experimental settings, all off by default:

  • input_format_parquet_hedged_read_threshold_ms (default 0, off): hedge a read that has not finished within this many milliseconds.
  • input_format_parquet_hedged_read_ttfb_threshold_ms (default 0, off): hedge a read whose first byte has not arrived within this many milliseconds, which tells a stalled connection from a large transfer that streams normally. When set, it takes precedence over the total-time threshold.
  • input_format_parquet_hedged_read_max_bytes (default 4 MiB): do not hedge reads larger than this. 0 means no limit.
  • input_format_parquet_hedged_read_max_inflight (default 4): the maximum number of hedges running at once.

New profile events: ParquetPrefetcherHedgedReads counts the duplicate reads, and ParquetPrefetcherHedgedWins counts the hedges whose result was used.

The code comes from two commits of #2181 by UnamedRus: the hedged reads and the time-to-first-byte trigger. Measurements in the second commit, on a synthetic wide Iceberg table (62 files of 1 GiB, a query reading about 690 MiB in part-sized GETs): with the first-byte threshold at 40 ms, the median query time fell by 19% and the maximum by 21%, with 9% more bytes read (21 hedges, all of them used). I did not repeat those measurements here. The test checks that results are unchanged with hedging on, that hedges are issued only when enabled, and that the size and concurrency caps hold. It cannot force the first-byte trigger to fire, because on a local S3 emulator the first byte usually arrives in time, so that trigger is checked only for unchanged results.

Related: #2181

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

Added the experimental settings input_format_parquet_hedged_read_threshold_ms, input_format_parquet_hedged_read_ttfb_threshold_ms, input_format_parquet_hedged_read_max_bytes and input_format_parquet_hedged_read_max_inflight for the Parquet v3 reader. A remote read that is slow, or whose first byte is late, is duplicated and the first result is used, which cuts the tail latency of object-storage reads. They are off by default. Added the profile events ParquetPrefetcherHedgedReads and ParquetPrefetcherHedgedWins.

Documentation entry for user-facing changes

The settings are documented in their declarations (input_format_parquet_hedged_read_*), and the profile events in their descriptions in ProfileEvents.cpp.

CI/CD Options

Exclude tests:

  • Fast test
  • Integration Tests
  • Stateless tests
  • Stateful tests
  • Unit tests
  • Performance tests
  • Aarch64 tests
  • All with ASAN
  • All with TSAN
  • All with MSAN
  • All with UBSAN
  • All with Coverage
  • All Regression
  • Disable CI Cache

Regression jobs to run:

  • Fast suites (mostly <1h)
  • Aggregate Functions (2h)
  • Alter (1.5h)
  • Benchmark (30m)
  • CAS (content-addressed storage; Antalya only)
  • ClickHouse Keeper (1h)
  • Iceberg (2h)
  • LDAP (1h)
  • OAuth (5m)
  • Parquet (1.5h)
  • RBAC (1.5h)
  • SSL Server (1h)
  • S3 (2h)
  • S3 Export (2h)
  • Swarms (30m)
  • Tiered Storage (2h)

UnamedRus and others added 3 commits November 30, 2026 16:55
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 <dtitmoav@gmail.com>
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) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
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: #2181
Related: #2966
Co-authored-by: Cursor <cursoragent@cursor.com>
@ianton-ru ianton-ru added antalya performance Antalya Roadmap: Performance port-antalya PRs to be ported to all new Antalya releases antalya-26.8 labels Nov 30, 2026
@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Workflow [PR], commit [52331eb]

ianton-ru and others added 20 commits December 2, 2026 12:32
…read

The hedge used to run synchronously on the consumer thread. The consumer could not
take the result of the primary read even after it had finished, and a slow hedge
delayed it for as long as the hedge took. `ParquetPrefetcherHedgedWins` counted every
successful hedge, including the ones that lost to the primary.

Now the hedge runs as a job in the IO thread pool, and the consumer waits on
`completion`, which is notified by whichever read finishes first. The primary result
is preferred; the hedge result is used if the primary is still running or has failed
(then the consumer waits for the hedge). The job keeps a reference on the task, so
`hedge_buf` cannot be freed under it, and it cancels its read as soon as the primary
succeeds. A cap rejection no longer forbids hedging the task later.
`ParquetPrefetcherHedgedReads` counts started hedges, `ParquetPrefetcherHedgedWins`
only the hedges that finished before the primary.

Adds the failpoints `parquet_prefetcher_primary_read_pause` and
`parquet_prefetcher_hedge_job_pause` and the test `05821_parquet_hedged_reads_race`.

Related: #2979
Co-authored-by: Cursor <cursoragent@cursor.com>
…e-cache reads

`Prefetcher::canHedge` checked `!task->cached_region.has_value()` while the primary
task was in `Task::State::Running`. `task->cached_region` is a non-atomic
`std::optional` assigned on the IO thread in `Prefetcher::runTask`, so reading it
from a consumer thread before the acquire load of `Task::State::Done` was a data race.
Moreover, while the primary was still running `readBigAtRetainCells`, `cached_region`
was still empty (and remained empty on multi-cell spans), so page-cache reads were
not excluded from hedging.

Evaluate `seekable->supportsReadAtRetainCells()` once in
`Prefetcher::determineReadModeAndFileSize` into `supports_retain_cells` and check it
in both `canHedge` and `runTask`. Also forward `supportsReadAtRetainCells` and
`readBigAtRetainCells` through `AsynchronousBoundedReadBuffer` (draining any pending
initial prefetch first) and `BoundedReadBuffer` so small object-storage files wrapped
in async prefetch preserve page-cache awareness.

Adds stateless regression test `05822_parquet_hedged_reads_page_cache`.

Related: #2979
Co-authored-by: Cursor <cursoragent@cursor.com>
…t TTFB hedge trigger measures time to first byte

`copyFromIStreamWithProgressCallback` called the progress callback only after a whole chunk (1 MiB) had been read,
so for reads of up to one chunk the "first byte" signal fired when the read was already complete, and
`input_format_parquet_hedged_read_ttfb_threshold_ms` behaved like the total-time threshold. The first byte is now
taken on its own and reported immediately. Readers that do not report progress (local files, Azure) still
signal at the end of the read; the setting description says so.

Adds a gtest for the helper and a functional test with a failpoint that stalls the primary read after its first byte.

Co-authored-by: Cursor <cursoragent@cursor.com>
…etting value waits instead of expiring at once

The `UInt64` timeout was converted to the signed `std::chrono::milliseconds` and added to the nanosecond
`steady_clock` time point, so a very large `input_format_parquet_hedged_read_threshold_ms` or
`input_format_parquet_hedged_read_ttfb_threshold_ms` (for example the `UInt64` maximum, as a way to say "never")
made the deadline land in the past, and the hedge fired immediately. The timeout is now clamped to a year.

Adds a gtest for `wait_for` with huge timeouts.

Co-authored-by: Cursor <cursoragent@cursor.com>
…rmat_parquet_hedged_read_max_inflight = 0` mean no limit

`hedges_inflight` was a member of `Prefetcher`, which exists for each file reader, so a query reading many files
in parallel got the cap for each of them, while the setting says that it stops a slow region from doubling all
traffic. The counter now lives in `SharedResourcesExt`, shared by the file readers of the query.

`input_format_parquet_hedged_read_max_inflight = 0` used to mean "no hedges", while `input_format_parquet_hedged_read_max_bytes = 0`
means "no limit". Both now mean no limit.

Adds a functional test: a parked hedge holds the only slot of the query's cap, and no other file starts a hedge.

Co-authored-by: Cursor <cursoragent@cursor.com>
… to the reader's watermarks

The buffer of a hedged read (`hedge_buf`) is not charged to the reader's `MemoryUsageToken`: the token belongs to a
batch and only the thread that owns the batch can charge it, while the hedge runs in the IO thread pool. The memory
is bounded by `input_format_parquet_hedged_read_max_inflight` times `input_format_parquet_hedged_read_max_bytes` for
the query, and the query memory tracker sees it. Say so in the setting description and in the code.

Co-authored-by: Cursor <cursoragent@cursor.com>
…ad_max_inflight = 0` meaning no limit, and for its timing

The `no_inflight` case still expected no hedges for `max_inflight = 0`, which means no limit since the cap became a per-query limit.
It passed only because a hedge is issued only when a read takes longer than the threshold. For the same reason the `total`
case, which required a hedge to be issued, failed when the reads were fast. Only the cases where a hedge must not be issued
are asserted now; `05821_parquet_hedged_reads_race` and `05824_parquet_hedged_reads_max_inflight` stall a read to make a hedge certain.

Co-authored-by: Cursor <cursoragent@cursor.com>
… shutdown of its reader

The hedge job returns early if its reader was shut down while the job was in the queue (the end of a file, `LIMIT`, cancel).
That return skipped the release of the slot in the cap on the hedged reads. Since the cap became a per-query limit, the
counter outlives the reader, so every such job made the cap of the rest of the query smaller by one, until no hedge could
start (a cap of 4 by default).

The slot is now a `HedgeSlot`, released by its destructor, and owned by the hedge job. It is released when the job is over,
fails, never runs, or when `maybeStartHedge` returns early. It keeps the counter alive, and can't be released twice.

Adds gtests for `HedgeSlot`, including a job that never runs and a slot that outlives the owner of the counter.

Co-authored-by: Cursor <cursoragent@cursor.com>
`Prefetcher::runHedge` cancelled its read only when the primary read had
succeeded. `ShutdownHelper::shutdown` waits for running jobs, so a hedge that
was reading a slow object (`shutdownTasks`, `resetReadBuffer`, the destructor)
kept the shutdown, and the query cancellation, waiting for the whole transfer,
although nobody would use the data.

Now the progress callback of the hedge also returns `true` once the shutdown
is requested, and the resulting error is not logged, like the cancellation by
the primary.

The cancellation is checked on progress callbacks, so a read that has not yet
received its first byte is not interrupted.

Add a `gtest` with a fake remote file: the primary read stalls, the hedge
transfers slowly, and `shutdownTasks` must stop the hedge. It fails without
the change (the hedge goes on and delivers data).

Co-authored-by: Cursor <cursoragent@cursor.com>
…e hedge data is used

`Prefetcher::runHedge` incremented `ParquetPrefetcherHedgedWins` when the hedge
finished while the primary read was not `Done`. A consumer that wakes up later
and finds the primary `Done` prefers the primary's buffer and never looks at
`hedge_buf`, so such a hedge was counted as a win although none of its data
was used.

Now the event is incremented in `Prefetcher::getRangeData`, when a consumer
takes data from `hedge_buf`, once per task (`Task::hedge_win_counted`), because
one task can serve many ranges. A win is a hedge whose data was used, either
because it finished first or because the primary failed. The description of
the event is updated accordingly.

Co-authored-by: Cursor <cursoragent@cursor.com>
`SYSTEM WAIT FAILPOINT ... PAUSE` has no timeout. If the failpoint was never
reached (the query failed, or every read ran in a consumer thread instead of
the IO thread pool, where the pause is), the tests `05821`, `05823` and
`05824` waited for it until the test runner killed them after 20 minutes. This
happened once to `05824`.

`wait_for_pause` now runs the wait in the background and gives up with a clear
message, failing the test, when the query is gone or 120 seconds have passed.

Co-authored-by: Cursor <cursoragent@cursor.com>
…ready hedged

A task serves many ranges, and each consumer that blocks on a slow task came to
`Prefetcher::maybeStartHedge`: it waited for the threshold, took a slot of the
query-wide cap, and only then lost the `compare_exchange_strong` on
`hedge_state` to the consumer that had started the hedge. While it held the
slot, even if only for a moment, a consumer of another task could be refused a
hedge at the cap boundary, and the loser waited for the threshold once more for
nothing.

Now `maybeStartHedge` returns at once if the hedge of the task has been started,
before waiting and again before taking the slot. The `compare_exchange_strong`
stays as the check that decides between consumers arriving together.

Co-authored-by: Cursor <cursoragent@cursor.com>
…ByShutdown` fails early

An `ASSERT_EQ` that failed before the end of the test returned from a scope with
a joinable `std::thread` (`consumer`), which calls `std::terminate` and kills the
whole `unit_tests_dbms` run, or, before the thread was created, left the primary
read parked, so that the destructor of the `Prefetcher` waited for it forever.

A scope guard now always lets the primary read go, shuts the reader down and
joins the threads, so that a failed assertion fails only this test.

Co-authored-by: Cursor <cursoragent@cursor.com>
The error of a hedge was only logged, and a hedge is best effort: the primary
read decides the result. So a hedge path that always failed (for example, on a
memory limit or a network error) was visible only as the absence of wins.

Add the `ParquetPrefetcherHedgedFailures` profile event. It counts the hedges
that failed with an error, and not those that were cancelled because the
primary read finished or the reader was shut down, which is their normal end.

Add a `gtest` for a failing hedge (counted once, the consumer still gets the
data of the primary read), and check that a cancelled hedge is not counted.

Co-authored-by: Cursor <cursoragent@cursor.com>
…hat can be hedged

The primary read of every task got a progress callback, also with hedging
switched off. A reader that is given a callback (S3, HTTP) reads the first byte
as a read of its own, and the callback built the failpoint name, a `String`
that does not fit in the small string buffer, for every chunk of every read.

Now the callback is set only if `canHedge` is true for the task. The failpoint
name is made once.

Add a `gtest` that checks which reads are given a callback: none with hedging
off or for a read over `input_format_parquet_hedged_read_max_bytes`, and the
others with either threshold.

Co-authored-by: Cursor <cursoragent@cursor.com>
`input_format_parquet_hedged_read_threshold_ms` is ignored, without a message,
unless the reads are done by the IO thread pool of the reader
(`input_format_parquet_enable_row_group_prefetch` enabled and
`max_download_threads` greater than 0) and the file can be read by ranges at an
offset. A read through the userspace page cache is never hedged. None of this was in the description of
the settings. Say it in the description of `input_format_parquet_hedged_read_threshold_ms`,
and refer to it from `input_format_parquet_hedged_read_ttfb_threshold_ms`.

Co-authored-by: Cursor <cursoragent@cursor.com>
… `ParquetPrefetcher` test

Failing the assertion on purpose showed that the guard of
`ParquetPrefetcher.HedgeIsCancelledByShutdown` hung: it requested the shutdown
while the consumer was still waiting. A hedge job that the shutdown skips, because
it had not started, never finishes, and a consumer that waits for it after a
failed primary read waits forever. Join the consumer first, and shut the reader
down at the end. With the assertions failing the test now fails and does not hang.

Co-authored-by: Cursor <cursoragent@cursor.com>
…ing the read

A task that no IO thread has started yet is run by the consumer itself, which is not the stalled
read of the IO pool that the failpoints `parquet_prefetcher_primary_read_pause` and
`parquet_prefetcher_primary_after_first_byte_pause` stand for. When the consumers win all the tasks
of a query (the IO pool has just started, or the machine is busy), the query ended without reaching the
failpoint and the tests failed with "was not reached" (about one run in six on a loaded machine).

`wait_for_pause` now tells a query that ended from other failures, and `start_query_until_parked`
starts the query again in that case. The `query_log` checks take the last attempt of each query.
The tests also switch the userspace page cache off explicitly: a read through it is never hedged.

Co-authored-by: Cursor <cursoragent@cursor.com>
…ead, not when its job is queued

The slot of the cap on the running hedges was taken in `maybeStartHedge` and held by the job all the time it
waited in the queue of the IO thread pool, behind the prefetch tasks. A job whose primary read had finished by the
time it got a thread still held its slot meanwhile, and the hedges of other tasks were refused for nothing.

The job now takes the slot in `runHedge`, after it has found that the primary read has not succeeded yet, holds it
while the hedge reads, and a job that finds the cap reached leaves the task to its primary read (and notifies
`hedge_done`, so nobody waits for it). `ParquetPrefetcherHedgedReads` counts the hedges that read, and the
failpoint `parquet_prefetcher_hedge_job_pause` parks a hedge that holds its slot.

Co-authored-by: Cursor <cursoragent@cursor.com>
…whole query

The counter of the running hedges lives in the resources that the file readers of one scan (a table or a table
function of the query) share, so a query that reads several tables, for example a `JOIN` of two Parquet tables,
has the cap `input_format_parquet_hedged_read_max_inflight` for each of them. The setting description said it was
for the whole query.

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru and others added 19 commits December 2, 2026 18:38
The comment on `Task::HedgeState` said that the hedge job always leaves the state Running and notifies it. A job that
the shutdown of the reader skips does neither: it returns before it touches the task, because it can run after the
prefetcher is gone, and it keeps its reference to the task. That is deliberate, and no consumer waits for a hedge
during the shutdown, since the shutdown is requested by the thread that reads. Say so in the comments, and do not
change the behavior.

Co-authored-by: Cursor <cursoragent@cursor.com>
…e hedge cap

The comment in `Prefetcher::runHedge` and the description of `input_format_parquet_hedged_read_max_inflight` said that
the buffers of the running hedges are bounded by the cap times `input_format_parquet_hedged_read_max_bytes`. The cap
counts the hedges that read at once, but a hedge keeps its buffer until its task is released, which is after the last
consumer of the task. So the buffers of the finished hedges are not bounded by the cap. Correct both texts. The
behavior does not change: releasing the buffer of a hedge that has finished would need a consumer-side lifetime, and
that is a separate change.

Co-authored-by: Cursor <cursoragent@cursor.com>
…`max_download_threads`

The description of `input_format_parquet_hedged_read_threshold_ms` said that the cap of the hedges applies in a query,
while the description of `input_format_parquet_hedged_read_max_inflight` says that it is for a scan. The code applies
it per scan. It also said that the setting needs `max_download_threads` to be greater than 0, but 0 is the automatic
value, which is a nonzero number of threads, so the reads are hedged then. Say what the code does.

Co-authored-by: Cursor <cursoragent@cursor.com>
… are written

The comments of `05822_parquet_hedged_reads_page_cache` said that the first file is larger than twice
`max_download_buffer_size` "when lowered", and the second is smaller than that. The test never lowers
`max_download_buffer_size`: its config sets only `page_cache_max_size`. Describe the files by what the test writes,
which is 40000 rows in 4 row groups and 2000 rows in 4 row groups.

Co-authored-by: Cursor <cursoragent@cursor.com>
… machine

`05823_parquet_hedged_reads_ttfb` sums `ParquetPrefetcherHedgedReads` over the whole query, and checked that it is 0
while the transfer is stalled. The query reads many row groups with 4 download threads, and the threshold of 100 ms
is short: any other read whose first byte is slow under load hedges, and the test fails. Use a 1000 ms threshold for
the TTFB case, and wait twice that before the check, so that a hedge of the stalled transfer would still have been
issued by then. The total-time case keeps its 100 ms threshold.

Co-authored-by: Cursor <cursoragent@cursor.com>
In the case `primary_wins` of `05821_parquet_hedged_reads_race`, the query counts `ParquetPrefetcherHedgedWins` over the
whole query, and it expects 0. The threshold of 50 ms is short, so a read of another row group whose primary is slow
only because the machine is busy can hedge and win. The read that is parked stays parked for the whole case, so a
larger threshold only delays its hedge, which is still started before the check. Use 1000 ms in that case. The first
case keeps 50 ms, since it needs the hedge to win.

Co-authored-by: Cursor <cursoragent@cursor.com>
`ParquetPrefetcher.RefusedHedgeIsStartedByALaterConsumer` gave the job of the refused hedge 500 ms to run before it
released the slot of the cap. Under load the job could run later, and then the test saw a hedge that the cap did not
refuse. The job now pauses on the new failpoint `parquet_prefetcher_hedge_refused_pause` right after it has set the
state back to NotStarted, and the test waits for that pause. The test then knows the refusal has happened, and checks
that the refused job has not read. The failpoint is disabled in the cleanup of the test, so a failed assertion does
not leave the job paused.

Co-authored-by: Cursor <cursoragent@cursor.com>
…failed hedges

In `ParquetPrefetcher.FailedHedgeIsCounted` the consumer thread called `getRangeData` without a `try`. An exception that
escaped the thread would terminate the whole test binary, and every other test in it would be lost with the failure.
The other consumers of this file already catch: let the check of the flag report the failure instead.

Co-authored-by: Cursor <cursoragent@cursor.com>
…e settings

`ReadOptions::hedged_read_max_bytes` and `ReadOptions::hedged_read_max_inflight` defaulted to 0, which means "no limit",
while the settings `input_format_parquet_hedged_read_max_bytes` and `input_format_parquet_hedged_read_max_inflight`
default to 4 MiB and 4. A caller that builds `ReadOptions` itself and sets only a threshold got hedging that is not bounded
by the size of the read or by the number of hedges. Use the defaults of the settings.

Co-authored-by: Cursor <cursoragent@cursor.com>
…nstead of sleeping

The cap case of `05824_parquet_hedged_reads_max_inflight` slept for 3 seconds and then checked that the parked hedge was
the only one. That check can pass without the cap being exercised: the job of the parked hedge waited in the queue of the
IO pool behind the reads of the other files, took its slot when they were over, and nothing was left to be refused.

The test now waits for the event it is about: the failpoint `parquet_prefetcher_hedge_refused_pause` parks the first hedge
job that the cap refuses, and the hedges are counted at that moment. The IO pool has more threads than the query has reads,
so no hedge job waits in the queue.

Co-authored-by: Cursor <cursoragent@cursor.com>
…est with a failpoint

The test slept for 500 ms and then asserted that no hedge had started, so it
could pass without the cap being evaluated at all. Wait for the
`parquet_prefetcher_hedge_refused_pause` failpoint instead, which is reached
exactly when the hedge is refused by the cap.

`waitForPause` has no timeout, so a broken cap would hang the test. Run it in
`std::async` and bound the wait to 60 seconds, so a regression fails the test.
The same bounded wait is used in `RefusedHedgeIsStartedByALaterConsumer`.

Checked by setting the cap to 0 in `Prefetcher.cpp`: the test fails after 60
seconds instead of hanging.

Co-authored-by: Cursor <cursoragent@cursor.com>
…d_reads_ttfb` test

The test waited 2 seconds, and then counted the hedged reads, so it could pass
before the consumer of the stalled transfer had decided anything.

Add the failpoint `parquet_prefetcher_hedge_skipped_pause`. `Prefetcher::maybeStartHedge`
reaches it when the first byte has arrived, and the primary read of that task is the
one that is parked at `parquet_prefetcher_primary_after_first_byte_pause`. The flag
`Task::primary_at_stall_point` tells that task from the healthy ones, so the failpoint is
not hit by a read that is merely in progress. The test waits for the failpoint instead
of sleeping.

Co-authored-by: Cursor <cursoragent@cursor.com>
…il a second hedge is wanted

The case needs two consumers that want a hedge: the first hedge parks holding the only slot, and
the cap refuses the second. Only the first primary read was parked, and a consumer runs a task
itself when no IO thread has started it yet, so the consumers of the other files often finished
before they wanted a hedge, and the refusal was never reached (about 1 run in 4 failed).

Add the failpoint `parquet_prefetcher_primary_read_stall_pause`, which parks every primary read
of the IO pool, not only the first one. The case uses it, and if the refusal is not reached within
6 seconds (every other consumer ran its tasks itself), the attempt is made again, up to 15 times.

Co-authored-by: Cursor <cursoragent@cursor.com>
…reads_max_inflight` stops retrying

The retry loop said that the query had ended for every result of `wait_for_pause` other than
the limit, including a failure that `wait_for_pause` had already reported. Say it only for the
result that means it, and do not add a second message to the others.

Co-authored-by: Cursor <cursoragent@cursor.com>
…nTask`

`pauseFailPoint` takes a `String`, so each call built one from the name, and the names
are longer than the small string buffer. `runTask` made two of them (the second one is
new) for every read of the IO pool. Make them once, as the progress callback does for
the failpoint that it hits for every chunk.

Co-authored-by: Cursor <cursoragent@cursor.com>
`HedgeSlot` (a class, a `shared_ptr` counter built with an aliasing constructor, and its own gtest file)
was made for the time when the slot was taken in `maybeStartHedge` and carried by a queued job, which could
be skipped by the shutdown and outlive the reader. The slot is taken in `runHedge` now, and held by that
function only, which runs under the shutdown lock of the `Prefetcher`, so the counter in
`SharedResourcesExt` cannot go away under it.

Count first and check after, as before, and give the slot back with `SCOPE_EXIT` wherever the block is left,
or at once if the cap refuses the hedge. `HedgeIsCancelledByShutdown` now checks that a hedge that was
cancelled has given its slot back (it fails if the release is removed), instead of the `HedgeSlot` gtests.

Co-authored-by: Cursor <cursoragent@cursor.com>
…ead of copies of them

`ReadOptions` has the `FormatSettings` in its `format` member, and `ParquetV3BlockInputFormat` copied
the four `hedged_read_*` values into fields of `ReadOptions` of the same names, which had defaults of their
own (a third copy of the defaults of the settings). `Prefetcher::init` reads `options.format.parquet`
directly now, and the fields, their comment and the copying are gone. The defaults are those of
`FormatSettings` by construction, so they cannot drift from the settings.

Co-authored-by: Cursor <cursoragent@cursor.com>
…hedged_reads.lib`

`05821`, `05823` and `05824` each had their own copies of `arm`, `wait_for_pause`, `wait_for_pause_or_fail`,
`wait_for_all_rows`, `hedged_reads_of_running_query`, `finish_query` and `start_query_until_parked`, and
all four of them (with `05815`) the same `INSERT INTO FUNCTION s3` of the test file. About 100 lines were
identical in all three failpoint tests. Move them to a `.lib` file, as other tests do (for example
`02661_read_from_archive.lib`), with `write_parquet_file` for the data. The tests keep only what differs:
their `start_query`, their cleanup, and their cases. `05824` reads all the rows of the scan with
`wait_for_all_rows` too, instead of its own copy of the loop.

Co-authored-by: Cursor <cursoragent@cursor.com>
…rquet hedged reads

Two settings chose when to hedge a read: a threshold on the total time of the read
(`input_format_parquet_hedged_read_threshold_ms`) and one on its time to the first byte
(`input_format_parquet_hedged_read_ttfb_threshold_ms`, which took precedence). The total-time
one is removed, and the time-to-first-byte one is the only setting. The feature is not released,
so the setting is not renamed and needs no compatibility entry.

A hedge is now issued only when the first byte has not arrived in time, so a transfer that
streams slowly after its first byte is not hedged any more. For readers that do not report
the first byte (local files, Azure), the read is hedged when it has not finished in time, which
is what the total-time setting did for them. The removed code is the total-time wait in
`Prefetcher::maybeStartHedge`, the `hedged_read_threshold_ms` member, and the field of
`FormatSettings`. The tests use the remaining setting. `05823` no longer asserts that a stalled
transfer is hedged, and `05815` no longer has a total-time case.

Co-authored-by: Cursor <cursoragent@cursor.com>
@ianton-ru

Copy link
Copy Markdown
Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-03T13:05:14.242684Z 84352f8 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3efc4783a9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".


try
{
parser_shared_resources->io_runner([this, task, _shutdown = shutdown]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Run hedges outside the saturated primary I/O queue

When max_download_threads is 1, or whenever every I/O worker is occupied by stalled primary reads, this enqueues the hedge behind those same primaries. No worker can execute runHedge until a primary finishes, so the duplicate cannot reduce the tail latency it was created to mitigate. Use independent execution capacity for hedges or reserve I/O capacity so a timed-out primary cannot block its own hedge.

Useful? React with 👍 / 👎.

Comment on lines +588 to +590
readSync(task->hedge_buf.data(), task->length, task->offset, [this, task](size_t)
{
return task->state.load(std::memory_order_acquire) == Task::State::Done || shutdown->shutdown_requested();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make losing requests interruptible before their first byte

For an S3/HTTP hedge that stalls before delivering its first byte, this cancellation predicate is never invoked because progress callbacks begin only after a byte arrives. Even if the primary finishes and its result is used, the hedge retains the shutdown lock, and resetReadBuffer waits in shutdownTasks until the stalled request times out; similarly, a stalled primary is never canceled after the hedge wins because its callback always returns false. On a final read this preserves—or even adds—the network tail during query teardown, so cancellation needs to reach the underlying request while it is blocked rather than relying only on byte-progress callbacks.

Useful? React with 👍 / 👎.

ianton-ru and others added 3 commits December 3, 2026 13:26
…e a hedge runs and what cannot be cancelled

A hedge runs on the reading threads of the scan, behind the reads that are already queued, so it does not help when all of them are blocked by stalled reads (for example with `max_download_threads = 1`). A request that has not received its first byte has no progress step and cannot be cancelled: it goes on until it ends or times out, and the end of the query waits for it.

Related: #2979
Co-authored-by: Cursor <cursoragent@cursor.com>
The cancel flag of the progress callback of a primary read was always `false`, so a read that had lost to its hedge went on to the end and held its reading thread and the shutdown lock. It now stops at its next progress step once `hedge_state` is `Succeeded`, which is final, so the consumers are served by the hedge. A read that is stalled before its first byte has no progress step and still cannot be stopped.

Add the gtest `ParquetPrefetcher.PrimaryIsCancelledOnceTheHedgeHasWon`.

Related: #2979
Co-authored-by: Cursor <cursoragent@cursor.com>
…er.PrimaryIsCancelledOnceTheHedgeHasWon`

The last `getRangeData` of the test was a bare call in the test thread, so an exception from it would have called `std::terminate` for all the tests of the binary instead of failing this one. It is now checked with `EXPECT_NO_THROW`.

Related: #2979
Co-authored-by: Cursor <cursoragent@cursor.com>
@ianton-ru

Copy link
Copy Markdown
Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 84352f869f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 84352f869f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ianton-ru
ianton-ru marked this pull request as ready for review December 3, 2026 14:01

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

antalya antalya-26.8 performance Antalya Roadmap: Performance port-antalya PRs to be ported to all new Antalya releases

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants