Skip to content
Merged
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
117 changes: 115 additions & 2 deletions src/reader/cloudfetch/streaming_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use crate::kernel_error::{Error, Result};
use crate::klog::{debug, error, info, warn};
use crate::reader::cloudfetch::chunk_downloader::ChunkDownloader;
use crate::reader::cloudfetch::link_fetcher::ChunkLinkFetcher;
use crate::reader::ResultReaderMetrics;
use crate::types::cloudfetch::{
ChunkEntry, ChunkState, CloudFetchConfig, DEFAULT_CHUNK_READY_TIMEOUT_SECS,
};
Expand All @@ -32,7 +33,7 @@ use arrow_schema::SchemaRef;
use arrow_select::concat::concat_batches;
use dashmap::DashMap;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering};
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicI64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use tokio::sync::Notify;
use tokio_util::sync::CancellationToken;
Expand Down Expand Up @@ -168,6 +169,8 @@ pub struct StreamingCloudFetchProvider {
// `Arc<...>` so spawned download tasks can hold their own clone
// without keeping the whole provider alive past stream end.
refresh_coordinator: Arc<RefreshCoordinator>,

metrics: Arc<CloudFetchMetrics>,
}

/// Coordinates concurrent batched link-refresh attempts.
Expand Down Expand Up @@ -201,10 +204,90 @@ struct DownloadCtx {
refresh_coordinator: Arc<RefreshCoordinator>,
cancel_token: CancellationToken,
statement_id: Option<Arc<str>>,
metrics: Arc<CloudFetchMetrics>,
max_retries: u32,
retry_delay: std::time::Duration,
}

#[derive(Debug)]
struct CloudFetchMetrics {
total_chunks_present: Option<i32>,
total_chunks_iterated: AtomicI32,
chunks_downloaded: AtomicI32,
initial_chunk_latency_ms: AtomicI64,
slowest_chunk_latency_ms: AtomicI64,
sum_chunks_download_time_ms: AtomicI64,
}

impl CloudFetchMetrics {
fn new(total_chunks_present: Option<i32>) -> Self {
Self {
total_chunks_present,
total_chunks_iterated: AtomicI32::new(0),
chunks_downloaded: AtomicI32::new(0),
initial_chunk_latency_ms: AtomicI64::new(-1),
slowest_chunk_latency_ms: AtomicI64::new(0),
sum_chunks_download_time_ms: AtomicI64::new(0),
}
}

fn record_chunk_download(&self, chunk_index: i64, elapsed: std::time::Duration) {
let millis = elapsed.as_millis().try_into().unwrap_or(i64::MAX);
// `initial_chunk_latency` is the time to download chunk 0
// specifically, not the first download to *complete*. Under
// concurrency the fastest/smallest chunk often finishes first,
// so a first-to-complete gate would report a misleading value.
// Gate strictly on `chunk_index == 0` to match the JDBC/C#
// drivers' `initialChunkLatency` semantic.
if chunk_index == 0 {
self.initial_chunk_latency_ms
.store(millis, Ordering::Release);
}
self.slowest_chunk_latency_ms
.fetch_max(millis, Ordering::AcqRel);
self.sum_chunks_download_time_ms
.fetch_add(millis, Ordering::AcqRel);
// Count completed downloads so `snapshot` can distinguish a
// real ~0ms download from "no download ever completed". Both
// `slowest`/`sum` atomics initialize to 0, so without this
// counter a stream dropped/errored before any download finished
// would report `Some(0)` — indistinguishable from a genuine
// 0ms download and skewing server-side latency aggregates.
self.chunks_downloaded.fetch_add(1, Ordering::AcqRel);
}

fn record_chunk_iterated(&self) {
self.total_chunks_iterated.fetch_add(1, Ordering::AcqRel);
}

fn snapshot(&self) -> ResultReaderMetrics {
let initial = self.initial_chunk_latency_ms.load(Ordering::Acquire);
let iterated = self.total_chunks_iterated.load(Ordering::Acquire);
// Only emit `slowest`/`sum` once at least one download has
// completed. Both atomics initialize to 0, so gating on this
// counter keeps a no-download snapshot reporting `None` rather
// than a misleading `Some(0)` — mirroring the `-1` sentinel /
// `None` treatment of `initial_chunk_latency` above.
let downloaded = self.chunks_downloaded.load(Ordering::Acquire) > 0;
ResultReaderMetrics {
total_chunks_present: self.total_chunks_present,
total_chunks_iterated: Some(iterated),
initial_chunk_latency: (initial >= 0)
.then(|| std::time::Duration::from_millis(initial as u64)),
slowest_chunk_latency: downloaded.then(|| {
std::time::Duration::from_millis(
self.slowest_chunk_latency_ms.load(Ordering::Acquire) as u64,
)
}),
sum_chunks_download_time: downloaded.then(|| {
std::time::Duration::from_millis(
self.sum_chunks_download_time_ms.load(Ordering::Acquire) as u64,
)
}),
}
}
}

impl std::fmt::Debug for StreamingCloudFetchProvider {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StreamingCloudFetchProvider")
Expand Down Expand Up @@ -261,6 +344,7 @@ impl StreamingCloudFetchProvider {
config: CloudFetchConfig,
link_fetcher: Arc<dyn ChunkLinkFetcher>,
chunk_downloader: Arc<ChunkDownloader>,
total_chunks_present: Option<i32>,
runtime_handle: tokio::runtime::Handle,
) -> Arc<Self> {
let statement_id = link_fetcher.statement_id().map(Arc::from);
Expand All @@ -281,6 +365,7 @@ impl StreamingCloudFetchProvider {
runtime_handle,
statement_id,
refresh_coordinator: Arc::new(RefreshCoordinator::default()),
metrics: Arc::new(CloudFetchMetrics::new(total_chunks_present)),
});

// Start background initialization that fetches links and schedules downloads
Expand Down Expand Up @@ -379,6 +464,7 @@ impl StreamingCloudFetchProvider {

// Move to next chunk
let next_chunk = self.current_chunk_index.fetch_add(1, Ordering::Release) + 1;
self.metrics.record_chunk_iterated();

debug!(
"Released chunk {}: chunks_in_memory={}/{}, consumer advancing to {}",
Expand Down Expand Up @@ -564,6 +650,7 @@ impl StreamingCloudFetchProvider {
refresh_coordinator: Arc::clone(&self.refresh_coordinator),
cancel_token: self.cancel_token.clone(),
statement_id: self.statement_id.clone(),
metrics: Arc::clone(&self.metrics),
max_retries: self.config.max_retries,
retry_delay: self.config.retry_delay,
};
Expand Down Expand Up @@ -765,8 +852,13 @@ impl StreamingCloudFetchProvider {
};

// Attempt download
let download_started = std::time::Instant::now();
Comment thread
jay-xiao446 marked this conversation as resolved.
Resolved
Comment thread
jay-xiao446 marked this conversation as resolved.
Resolved
Comment thread
jay-xiao446 marked this conversation as resolved.
Resolved

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low — download_started is (re)initialized inside the retry loop, immediately before each ctx.downloader.download(&link).await attempt. record_chunk_download is therefore called with only the final successful attempt's elapsed time. For chunk 0 this means initial_chunk_latency excludes any time spent on failed/retried attempts (network error, stale-link refresh, retry backoff sleeps).

The comment above record_chunk_download states the intent is to match the JDBC/C# initialChunkLatency semantic ("time to download chunk 0"). If those drivers measure from first-attempt start (i.e. include retry cost), this under-reports on retried chunks. If they measure only the successful attempt, this is correct. Worth a quick confirm against the reference drivers; if end-to-end timing is intended, hoist download_started above the retry loop for chunk 0.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Confirmed against the JDBC reference driver: the current per-attempt timer placement is correct and no change is needed. In JDBC, the retry loop lives in StreamingChunkDownloadTask.call() (link-refresh + RETRY_DELAY_MS backoff), but telemetry is recorded inside ArrowResultChunk.downloadData(), which captures startTime = System.nanoTime() at the top of each invocation and reports only that single attempt. Because the outer loop re-invokes downloadData on each retry, the recorded downloadTimeMs — and thus initialChunkLatencyMillis for chunk 0 (StatementTelemetryDetails.recordChunkDownloadLatency: if (chunkIndex == 0) setInitialChunkLatencyMillis(latencyMillis)) — reflects only the final successful attempt, excluding failed attempts, link-refresh RPC, and backoff sleeps. That is exactly what this code does: download_started is reset before each ctx.downloader.download(&link).await, and record_chunk_download fires only on the Ok branch, so retry/refresh/backoff cost is excluded. The reviewer's own condition ("If those drivers measure only the successful attempt, this is correct") is therefore satisfied — the timer should NOT be hoisted above the retry loop.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The finding was explicitly a confirmation request against the reference drivers, and the analysis here is internally consistent — but everything load-bearing in it describes JDBC internals (ArrowResultChunk.downloadData capturing startTime per invocation, recordChunkDownloadLatency gating on chunkIndex == 0) that live outside this repo and that I can't verify from the checked-out source or the current-code snippet. The snippet only confirms what was never in dispute: the Rust timer is per-attempt. Since no code change was pushed and the correctness pivot rests entirely on an unverifiable external-driver claim, I'll leave this open as a low-severity note for a human with the JDBC source in hand to confirm the initialChunkLatencyMillis semantic before closing it out — if that reference behavior is as described, no code change is needed.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Verified the JDBC reference source directly (the review-bot said it lacked access). ArrowResultChunk.downloadData() captures startTime = System.nanoTime() per invocation and records latency only after checkHTTPError succeeds; StreamingChunkDownloadTask.call() holds the retry loop, RETRY_DELAY_MS backoff, and link refresh OUTSIDE downloadData, re-invoking it per retry; StatementTelemetryDetails.recordChunkDownloadLatency gates initialChunkLatency on chunkIndex==0. JDBC therefore measures only the final successful attempt — the reviewer's own condition for correctness. The Rust code (download_started reset before each download() attempt, record_chunk_download only on Ok) matches exactly. No code change warranted; the timer should not be hoisted.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I appreciate the detailed walkthrough of the JDBC internals, but the correctness pivot here rests entirely on reference-driver behavior (ArrowResultChunk.downloadData capturing startTime per invocation, the retry loop living in StreamingChunkDownloadTask.call() outside it, and recordChunkDownloadLatency gating on chunkIndex == 0) that isn't present in this repo and can't be confirmed from the checked-out source or the current-code snippet. No code change was pushed, and the snippet only re-confirms the point that was never disputed — that the Rust timer is per-attempt. This was posed as a confirmation request against the reference drivers, so I'll leave it open as a low-severity note for a human with the JDBC source in hand: if the initialChunkLatencyMillis semantic is indeed "final successful attempt only" as described, then no change is needed and this can be closed out.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⛔ NEEDS HUMAN DECISION — the bots can't resolve this thread; a maintainer's input is required.

No code change needed: verified in src/reader/cloudfetch/streaming_provider.rs (~L855-859) that download_started is reset before each download() attempt and record_chunk_download fires only on the Ok branch, so the timer deliberately captures the final successful attempt — matching the reviewer's own stated condition for correctness. The remaining pivot rests entirely on JDBC reference-driver semantics (ArrowResultChunk.downloadData per-invocation startTime; recordChunkDownloadLatency gating on chunkIndex==0) which the review-bot cannot verify from the checked-out source and has twice asked a human to confirm. The thread has converged and needs a human with the JDBC source to close it out; further bot replies won't help.

match ctx.downloader.download(&link).await {
Ok(batches) => return Ok(batches),
Ok(batches) => {
ctx.metrics
.record_chunk_download(chunk_index, download_started.elapsed());
return Ok(batches);
}
Err(e) => {
// Every completed download failure consumes the hard attempt
// budget, even when its link became stale while in flight.
Expand Down Expand Up @@ -853,6 +945,26 @@ impl StreamingCloudFetchProvider {
}
}

pub(crate) fn metrics(&self) -> Option<ResultReaderMetrics> {
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
let snapshot = self.metrics.snapshot();
// Surface metrics whenever *any* datum was captured, not just
// once a chunk has been iterated (released from the buffer).
// `total_chunks_present` is known from the manifest at
// construction and `initial_chunk_latency` is stamped at
// chunk-0 download completion — both fire before the first
// `record_chunk_iterated`. Gating strictly on `iterated > 0`
// would drop this data for a stream that downloads but is
// dropped/errors before releasing any chunk, losing useful
// telemetry for partial/failed consumption.
let has_data = snapshot.total_chunks_present.is_some()
|| snapshot
.total_chunks_iterated
.is_some_and(|count| count > 0)
|| snapshot.initial_chunk_latency.is_some()
|| snapshot.slowest_chunk_latency.is_some();
has_data.then_some(snapshot)
}

/// Refresh presigned-URL links for `chunk_index` and every
/// subsequent chunk whose download is still pending or in flight.
///
Expand Down Expand Up @@ -1504,6 +1616,7 @@ mod tests {
refresh_coordinator: Arc::new(RefreshCoordinator::default()),
cancel_token: CancellationToken::new(),
statement_id: None,
metrics: Arc::new(CloudFetchMetrics::new(Some(1))),
max_retries: MAX_DOWNLOAD_ATTEMPTS,
retry_delay: std::time::Duration::ZERO,
};
Expand Down
24 changes: 24 additions & 0 deletions src/reader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ use arrow_array::RecordBatch;
use arrow_schema::{ArrowError, Field, Schema, SchemaRef};
use async_trait::async_trait;
use std::sync::Arc;
use std::time::Duration;

pub use cloudfetch::StreamingCloudFetchProvider as CloudFetchReader;

Expand Down Expand Up @@ -469,6 +470,7 @@ impl ResultReaderFactory {
self.config.clone(),
link_fetcher,
chunk_downloader,
total_chunk_count.and_then(|count| count.try_into().ok()),
self.runtime_handle.clone(),
);

Expand Down Expand Up @@ -590,6 +592,24 @@ pub trait ResultReader: Send + Sync {

/// Get the next record batch, or None if end of results.
async fn next_batch(&mut self) -> Result<Option<RecordBatch>>;

/// Optional reader-level metrics accumulated below `ResultStream`.
///
/// CloudFetch overrides this to surface chunk download metrics into
/// statement telemetry. Inline/in-memory readers keep the default.
fn metrics(&self) -> Option<ResultReaderMetrics> {
None
}
}

#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default)]
pub struct ResultReaderMetrics {
pub total_chunks_present: Option<i32>,
pub total_chunks_iterated: Option<i32>,
pub initial_chunk_latency: Option<Duration>,
pub slowest_chunk_latency: Option<Duration>,
pub sum_chunks_download_time: Option<Duration>,
}

/// Wrapper for StreamingCloudFetchProvider that implements ResultReader.
Expand All @@ -612,6 +632,10 @@ impl ResultReader for CloudFetchResultReader {
async fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
self.provider.next_batch().await
}

fn metrics(&self) -> Option<ResultReaderMetrics> {
self.provider.metrics()
}
}

/// Reader for inline Arrow results.
Expand Down
6 changes: 5 additions & 1 deletion src/reader/post_processor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
mod json;

use crate::kernel_error::{Error, Result};
use crate::reader::{ResultReader, ResultReaderAdapter};
use crate::reader::{ResultReader, ResultReaderAdapter, ResultReaderMetrics};
use crate::types::sea::ResultManifest;
use arrow_array::builder::StringBuilder;
use arrow_array::{ArrayRef, RecordBatch};
Expand Down Expand Up @@ -240,6 +240,10 @@ impl ResultReader for ResultPostProcessor {
None => Ok(Some(batch)),
}
}

fn metrics(&self) -> Option<ResultReaderMetrics> {
self.inner.metrics()
}
}

/// Compare schemas by their field sequence including per-field
Expand Down
Loading
Loading