Skip to content
Closed
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
82 changes: 80 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,67 @@ 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,
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),
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, elapsed: std::time::Duration) {
let millis = elapsed.as_millis().try_into().unwrap_or(i64::MAX);
let _ = self.initial_chunk_latency_ms.compare_exchange(

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 — initial_chunk_latency_ms is set by the first download to complete, not the latency of chunk 0. record_chunk_download runs inside the Ok(batches) arm of each concurrently-spawned download_chunk_with_retry task, and the compare_exchange(-1, millis) seats whichever task finishes first. Because chunk downloads run in parallel (spawned at streaming_provider.rs:647), the "first completed" chunk is frequently not chunk 0 — a small later chunk can win the race. If this metric is meant to mirror the reference drivers' notion of time-to-first-chunk (chunk 0 in result order), the value reported here can be misleading. Consider recording chunk 0's own download time specifically, or renaming the field to reflect "first-completed-download" semantics.

-1,
millis,
Ordering::AcqRel,
Ordering::Acquire,
);
self.slowest_chunk_latency_ms
.fetch_max(millis, Ordering::AcqRel);
self.sum_chunks_download_time_ms
.fetch_add(millis, 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);
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: Some(std::time::Duration::from_millis(
self.slowest_chunk_latency_ms.load(Ordering::Acquire) as u64,
)),
sum_chunks_download_time: Some(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 +321,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 +342,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 +441,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 +627,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 +829,13 @@ impl StreamingCloudFetchProvider {
};

// Attempt download
let download_started = std::time::Instant::now();
match ctx.downloader.download(&link).await {
Ok(batches) => return Ok(batches),
Ok(batches) => {
ctx.metrics
.record_chunk_download(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 +922,14 @@ impl StreamingCloudFetchProvider {
}
}

pub(crate) fn metrics(&self) -> Option<ResultReaderMetrics> {
let snapshot = self.metrics.snapshot();
snapshot
.total_chunks_iterated
.is_some_and(|count| count > 0)
.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 +1581,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