Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Common/ProfileEvents.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) \
Expand Down
12 changes: 12 additions & 0 deletions src/Core/FormatFactorySettings.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions src/Core/SettingsChangesHistory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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",
{
Expand Down
4 changes: 4 additions & 0 deletions src/Formats/FormatFactory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
4 changes: 4 additions & 0 deletions src/Formats/FormatSettings.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
91 changes: 87 additions & 4 deletions src/Processors/Formats/Impl/Parquet/Prefetcher.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
Expand Down Expand Up @@ -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<bool(size_t)> 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:
Expand Down Expand Up @@ -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
}
}

Expand All @@ -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<const char> Prefetcher::getRangeData(const PrefetchHandle & request)
{
const RequestState * req = request.request;
Expand All @@ -459,12 +517,33 @@ std::span<const char> 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);
Expand Down Expand Up @@ -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 (...)
Expand All @@ -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;
Expand Down
40 changes: 37 additions & 3 deletions src/Processors/Formats/Impl/Parquet/Prefetcher.h
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,10 @@ class Prefetcher
/// The returned pointer is valid as long as the PrefetchHandle is alive.
std::span<const char> 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; }

Expand Down Expand Up @@ -151,9 +153,23 @@ class Prefetcher
std::atomic<State> state {State::Scheduled};
/// How many RequestState-s in HasTask state point to this Task.
std::atomic<size_t> 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<char> hedge_buf;
std::atomic<int> hedge_winner {0};
std::atomic<bool> hedge_started {false};
};

enum class ReadMode
Expand Down Expand Up @@ -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<size_t> hedges_inflight {0};

std::shared_ptr<ShutdownHelper> shutdown = std::make_shared<ShutdownHelper>();

/// Locked when creating a Task.
Expand All @@ -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.
Expand Down
38 changes: 38 additions & 0 deletions src/Processors/Formats/Impl/Parquet/ReadCommon.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
#include <Common/futex.h>
#include <Formats/FormatParserSharedResources.h>

#include <chrono>

namespace DB::Parquet
{

Expand Down Expand Up @@ -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<std::chrono::nanoseconds>(deadline - now).count();
futexTimedWait(&val, WAITING, remaining_ns); // may wake spuriously / on partial timeout; loop re-checks
}
}

#else

bool CompletionNotification::check() const
Expand All @@ -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

}
Loading
Loading