From 4ddba7db209e6a4b11b640ca04bff56ffaa009ac Mon Sep 17 00:00:00 2001 From: Gopal Lal Date: Mon, 25 May 2026 14:26:21 +0530 Subject: [PATCH 1/4] feat(cloudfetch): batched link refresh on presigned-URL expiry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When a CloudFetch presigned URL has expired (or is about to), refresh the whole forward window in one RPC instead of issuing N single-link `refetch_link` calls. SEA's `get_result_chunks` already returns a batch of links, and presigned URLs in a batch tend to share an expiry window — refreshing one chunk's URL almost always means the adjacent chunks need refreshing too. ### Design - New trait method `ChunkLinkFetcher::refetch_links_from(chunk_index, row_offset) -> Vec` issues one `get_result_chunks` RPC and returns every link the server emitted. - `StreamingCloudFetchProvider::refresh_links_batch(...)` is the reconciliation orchestrator. It: 1. Takes a `refresh_lock` (Arc>) so concurrent expiry detections collapse into a single RPC. 2. Re-checks the trigger chunk's link expiry after taking the lock — another task may have just refreshed it; if so, skip the RPC entirely. 3. Derives `row_offset` from the cached link (the bounded-SEA-API contract). 4. Walks every returned link and updates per-chunk state: - `UrlFetched | DownloadFailed | DownloadRetry | Pending`: replace link, set state to `UrlFetched` so `schedule_downloads` picks the chunk up next. - `Downloading`: replace link only — the in-flight task owns the state machine and will read the fresh link on its next retry iteration of `download_chunk_with_retry`. - `Downloaded | ProcessingFailed | Cancelled | Released`: replace link only (for bookkeeping); bytes / terminal state remain. Critically: **no re-download is triggered for chunks whose payloads are already in memory** — this is the explicit ask in the design. - Chunks not yet in the map: insert with the fresh link in `UrlFetched`. - `download_chunk_with_retry` now routes through the batched refresh on `link.is_expired()` (or missing). The old single-link `refetch_link` path is preserved on the trait but no longer called from the SEA download flow. - `schedule_downloads` adds a *proactive* expiry check: before claiming a chunk for download, if the cached link is already expired, kick off the batched refresh first. Avoids the wasted- RTT failure-then-refresh round-trip when the consumer pauses long enough for the queue to go stale. ### Tests Five new unit tests on the static `refresh_links_batch` helper: - `refresh_batch_updates_link_for_urlfetched_chunks` — happy path, one RPC covers all three chunks in the window. - `refresh_batch_preserves_downloaded_state` — the Downloaded chunk keeps its state and its `batches: Some(...)` bytes; only its link metadata is updated. - `refresh_batch_leaves_downloading_state_intact` — the in-flight task's state is not clobbered. - `refresh_batch_resets_download_failed_to_urlfetched` — failed chunks become re-schedulable with the fresh URL. - `refresh_batch_dedups_concurrent_calls` — two concurrent refresh callers → exactly one RPC. All 12 streaming_provider tests pass; clippy clean. Co-authored-by: Isaac Signed-off-by: Gopal Lal --- src/reader/cloudfetch/link_fetcher.rs | 57 ++- src/reader/cloudfetch/streaming_provider.rs | 488 +++++++++++++++++++- 2 files changed, 532 insertions(+), 13 deletions(-) diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 0788c365..7f1fd561 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -79,8 +79,41 @@ pub(crate) trait ChunkLinkFetcher: Send + Sync + std::fmt::Debug { start_row_offset: i64, ) -> Result; - /// Refetch a specific chunk link (used when link expires before download). + /// Refetch a specific chunk link. + /// + /// The current SEA streaming path uses [`Self::refetch_links_from`] + /// (batched refresh) on expiry. This single-link variant is kept + /// for callers that genuinely want a single link (e.g. tests, or + /// future Thrift transports where each link refresh is its own + /// RPC by construction). + #[allow( + dead_code, + reason = "preserved for single-link callers; SEA path uses refetch_links_from" + )] async fn refetch_link(&self, chunk_index: i64, row_offset: i64) -> Result; + + /// Refetch the link batch starting at `chunk_index`. + /// + /// SEA's `get_result_chunks` returns links for the requested + /// chunk plus a server-decided forward window. When a single + /// presigned URL has expired, the URLs for subsequent chunks are + /// typically also near-expiry — refreshing the whole batch in + /// one RPC instead of N single-link refetches is the contract + /// we want. + /// + /// Returns the full list of links the server emitted. Callers + /// are responsible for walking the result and reconciling each + /// link with the current per-chunk state (e.g. skipping the + /// download re-trigger for chunks already in `Downloaded`). + /// + /// Implementations also refresh their internal cache from the + /// batch so subsequent `fetch_links` / `refetch_link` calls see + /// the new URLs without an extra round trip. + async fn refetch_links_from( + &self, + chunk_index: i64, + row_offset: i64, + ) -> Result>; } /// SEA implementation of ChunkLinkFetcher with caching and proactive prefetching. @@ -975,6 +1008,28 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { self.inner.links.insert(chunk_index, link.clone()); Ok(link) } + + async fn refetch_links_from( + &self, + chunk_index: i64, + row_offset: i64, + ) -> Result> { + let result = self + .inner + .client + .get_result_chunks(&self.inner.statement_id, chunk_index, row_offset) + .await?; + + // Refresh the internal link cache with every link the server + // returned. The caller will reconcile per-chunk state in the + // streaming provider (which knows which chunks are already + // downloaded vs in-flight). + for link in &result.links { + self.inner.links.insert(link.chunk_index, link.clone()); + } + + Ok(result.links) + } } #[cfg(test)] diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 549ddbb7..ca784fbc 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -33,7 +33,7 @@ use dashmap::DashMap; use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; -use tokio::sync::Notify; +use tokio::sync::{Mutex as TokioMutex, Notify}; use tokio_util::sync::CancellationToken; use tracing::{debug, error, warn}; @@ -138,6 +138,21 @@ pub struct StreamingCloudFetchProvider { // Tokio runtime handle for spawning tasks runtime_handle: tokio::runtime::Handle, + + // Mutex around the batched link-refresh path. + // + // Several chunks expiring concurrently (the common shape: a + // burst of presigned URLs all near the 1h boundary) would each + // try to refresh the link cache. With this mutex, the first + // caller takes the lock and issues exactly one + // `refetch_links_from` RPC that covers the entire forward + // window; subsequent callers await the same lock, then each + // pulls the fresh link from the cache without a second + // round-trip. + // + // `Arc<...>` so spawned download tasks can hold their own clone + // without keeping the whole provider alive past stream end. + refresh_lock: Arc>, } impl std::fmt::Debug for StreamingCloudFetchProvider { @@ -181,6 +196,7 @@ impl StreamingCloudFetchProvider { chunk_state_changed: Arc::new(Notify::new()), cancel_token: CancellationToken::new(), runtime_handle, + refresh_lock: Arc::new(TokioMutex::new(())), }); // Start background initialization that fetches links and schedules downloads @@ -382,6 +398,41 @@ impl StreamingCloudFetchProvider { } } + // Proactive expiry check: if the cached link for this + // chunk is already expired (e.g. it sat in the queue + // longer than the presigned URL's TTL), refresh the + // whole forward batch before kicking off the download. + // Avoids the wasted-RTT failure-then-refresh path inside + // the download task. + let expired = self + .chunks + .get(&next_index) + .and_then(|e| e.link.as_ref().map(|l| l.is_expired())) + .unwrap_or(false); + if expired { + debug!( + "Proactive refresh: cached link for chunk {} already expired", + next_index + ); + if let Err(e) = Self::refresh_links_batch( + next_index, + &self.link_fetcher, + &self.chunks, + &self.refresh_lock, + ) + .await + { + warn!( + "Proactive batched refresh failed for chunk {}: {}; \ + will fall through to per-download retry path", + next_index, e + ); + // Don't abort scheduling — the download task's + // own refresh attempt will surface the error + // (and retry) when it actually tries to fetch. + } + } + // Try to claim this chunk for download let claimed = { if let Some(mut entry) = self.chunks.get_mut(&next_index) { @@ -417,6 +468,7 @@ impl StreamingCloudFetchProvider { let downloader = Arc::clone(&self.chunk_downloader); let link_fetcher = Arc::clone(&self.link_fetcher); let chunks = self.chunks.clone(); + let refresh_lock = Arc::clone(&self.refresh_lock); let chunk_state_changed = Arc::clone(&self.chunk_state_changed); let cancel_token = self.cancel_token.clone(); let max_retries = self.config.max_retries; @@ -429,6 +481,7 @@ impl StreamingCloudFetchProvider { &downloader, &link_fetcher, &chunks, + &refresh_lock, max_retries, retry_delay, &cancel_token, @@ -479,11 +532,13 @@ impl StreamingCloudFetchProvider { } /// Download a single chunk with retry and link refresh on expiry. + #[allow(clippy::too_many_arguments)] async fn download_chunk_with_retry( chunk_index: i64, downloader: &ChunkDownloader, link_fetcher: &Arc, chunks: &Arc>, + refresh_lock: &Arc>, max_retries: u32, retry_delay: std::time::Duration, cancel_token: &CancellationToken, @@ -495,7 +550,13 @@ impl StreamingCloudFetchProvider { return Err(Error::invalid_state().message("Download cancelled")); } - // Get link (may need to refetch if expired) + // Get link (may need to refresh the whole forward batch + // if expired). We always go via the batched refresh path: + // refreshing all in-flight chunks in one RPC matches the + // shape of how SEA expires links (the whole presigned-URL + // batch tends to share an expiry window), and avoids N + // separate `refetch_link` calls when a burst of chunks + // expires concurrently. let link = { let entry = chunks.get(&chunk_index); let stored_link = entry.as_ref().and_then(|e| e.link.clone()); @@ -503,16 +564,22 @@ impl StreamingCloudFetchProvider { match stored_link { Some(link) if !link.is_expired() => link, _ => { - // Link missing or expired - refetch it - debug!("Refetching expired link for chunk {}", chunk_index); - let new_link = link_fetcher.refetch_link(chunk_index, 0).await?; - - // Store the new link - if let Some(mut entry) = chunks.get_mut(&chunk_index) { - entry.link = Some(new_link.clone()); - } - - new_link + debug!( + "Link for chunk {} missing or expired; \ + triggering batched refresh", + chunk_index + ); + Self::refresh_links_batch(chunk_index, link_fetcher, chunks, refresh_lock) + .await?; + chunks + .get(&chunk_index) + .and_then(|e| e.link.clone()) + .ok_or_else(|| { + Error::invalid_state().message(format!( + "Link for chunk {} still missing after batched refresh", + chunk_index + )) + })? } } }; @@ -541,6 +608,123 @@ impl StreamingCloudFetchProvider { } } + /// Refresh presigned-URL links for `chunk_index` and every + /// subsequent chunk whose download is still pending or in flight. + /// + /// One RPC; per-chunk state reconciliation: + /// - `UrlFetched | DownloadFailed | DownloadRetry`: link replaced + /// in cache. `schedule_downloads` will pick the chunk up using + /// the fresh URL on its next loop. + /// - `Downloading`: link replaced in cache. The active download + /// task will see the new link on its next retry iteration + /// (this function is called from inside that task — see + /// `download_chunk_with_retry`). + /// - `Downloaded | ProcessingFailed | Cancelled | Released`: + /// bytes (or terminal state) are already in memory. We update + /// the cached link for bookkeeping but do nothing else; the + /// chunk doesn't need to be re-downloaded. + /// - `Pending` (no link cached): not in our refresh window, skip. + /// + /// The `refresh_lock` is taken before the RPC fires. Multiple + /// concurrent download tasks hitting expired URLs at the same + /// time will queue on the lock; only the first holder issues the + /// RPC, the rest find their now-fresh link already in cache when + /// they re-check. + /// + /// `start_chunk_index` is the chunk whose download just failed + /// (or is about to fail) — its server-side row offset is read + /// from the cached link if any so the RPC carries the right + /// `row_offset` for the bounded SEA API contract. + async fn refresh_links_batch( + start_chunk_index: i64, + link_fetcher: &Arc, + chunks: &Arc>, + refresh_lock: &Arc>, + ) -> Result<()> { + let _guard = refresh_lock.lock().await; + + // Re-check after taking the lock: another task may have just + // refreshed our chunk. Skip the RPC if so. + if let Some(entry) = chunks.get(&start_chunk_index) { + if let Some(ref link) = entry.link { + if !link.is_expired() { + debug!( + "Batched refresh for chunk {} skipped — already refreshed by another task", + start_chunk_index + ); + return Ok(()); + } + } + } + + // Derive `row_offset` from the existing cached link if any. + // The bounded SEA API contract requires `row_offset` on + // CloudFetch fetches (see PR #67 + PR #68); honour it here so + // the server-side cursor lands on the right row. + let row_offset = chunks + .get(&start_chunk_index) + .and_then(|e| e.link.as_ref().map(|l| l.row_offset)) + .unwrap_or(0); + + debug!( + "Issuing batched link refresh from chunk {} (row_offset={})", + start_chunk_index, row_offset + ); + let refreshed = link_fetcher + .refetch_links_from(start_chunk_index, row_offset) + .await?; + + for fresh in refreshed { + let ci = fresh.chunk_index; + if let Some(mut entry) = chunks.get_mut(&ci) { + match entry.state { + // Pending links to download — replace and let + // schedule_downloads pick up on next loop. + ChunkState::UrlFetched + | ChunkState::DownloadFailed(_) + | ChunkState::DownloadRetry => { + entry.link = Some(fresh); + entry.state = ChunkState::UrlFetched; + } + // Download already in flight — the in-flight + // task re-reads `entry.link` on each retry, so + // updating the link in place is enough. Don't + // touch the state machine; the running task + // owns it. + ChunkState::Downloading => { + entry.link = Some(fresh); + } + // Terminal-ish or already-have-bytes states. + // Keep the link metadata current (cheap; future + // bookkeeping may read `entry.link.row_offset` + // etc.) but do not change state or trigger any + // download. + ChunkState::Downloaded + | ChunkState::ProcessingFailed(_) + | ChunkState::Cancelled + | ChunkState::Released => { + entry.link = Some(fresh); + } + // Pending without a link — refresh response + // covered a chunk we hadn't asked about yet. + // Drop a link in and mark as ready to schedule. + ChunkState::Pending => { + entry.link = Some(fresh); + entry.state = ChunkState::UrlFetched; + } + } + } else { + // No entry yet — the refresh response covered a + // chunk we haven't seen at all. Create a fresh entry + // with the link; schedule_downloads will pick it up + // when it's in the consumer window. + chunks.insert(ci, ChunkEntry::with_link(fresh)); + } + } + + Ok(()) + } + /// Wait for a specific chunk to be ready (Downloaded state). async fn wait_for_chunk(&self, chunk_index: i64) -> Result<()> { loop { @@ -695,6 +879,25 @@ mod tests { .message(format!("Link not found for chunk {}", chunk_index)) }) } + + async fn refetch_links_from( + &self, + chunk_index: i64, + _row_offset: i64, + ) -> Result> { + // Test mock: return all links at chunk_index and beyond, + // ordered by chunk_index. Real SEA returns a server- + // decided batch starting at the requested index; this is + // good enough for state-machine tests. + let mut links: Vec<_> = self + .links_by_index + .iter() + .filter(|(idx, _)| **idx >= chunk_index) + .map(|(_, link)| link.clone()) + .collect(); + links.sort_by_key(|l| l.chunk_index); + Ok(links) + } } fn create_test_link(chunk_index: i64) -> CloudFetchLink { @@ -831,4 +1034,265 @@ mod tests { let result = merge_batches_to_target(vec![b1, b2], 100).unwrap(); assert_eq!(result[0].schema(), original_schema); } + + // --- refresh_links_batch unit tests --- + // + // These test the static method directly. They construct a tiny + // chunks DashMap by hand, prime it with entries in various + // states, then call `StreamingCloudFetchProvider::refresh_links_batch` + // and assert the right state transitions + RPC count. + + use crate::types::cloudfetch::{ChunkEntry, ChunkState}; + use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; + + /// Mock fetcher that records how many `refetch_links_from` + /// calls were made. Returns synthetic refreshed links with + /// distinct URLs so the test can tell new from stale. + #[derive(Debug)] + struct RefreshCountingMock { + refresh_calls: AtomicUsize, + // Range of chunk_indices the mock will return on each + // refresh, starting at the requested start_chunk_index. + window: i64, + } + + impl RefreshCountingMock { + fn new(window: i64) -> Arc { + Arc::new(Self { + refresh_calls: AtomicUsize::new(0), + window, + }) + } + + fn fresh_link(chunk_index: i64) -> CloudFetchLink { + CloudFetchLink { + url: format!("https://storage.example.com/REFRESHED/chunk{}", chunk_index), + chunk_index, + row_offset: chunk_index * 1000, + row_count: 1000, + byte_count: 50000, + expiration: chrono::Utc::now() + chrono::Duration::hours(1), + http_headers: HashMap::new(), + next_chunk_index: Some(chunk_index + 1), + } + } + } + + #[async_trait::async_trait] + impl ChunkLinkFetcher for RefreshCountingMock { + async fn fetch_links( + &self, + _start_chunk_index: i64, + _start_row_offset: i64, + ) -> Result { + unreachable!("not used by these tests") + } + + async fn refetch_link( + &self, + _chunk_index: i64, + _row_offset: i64, + ) -> Result { + unreachable!("not used by these tests") + } + + async fn refetch_links_from( + &self, + chunk_index: i64, + _row_offset: i64, + ) -> Result> { + self.refresh_calls.fetch_add(1, AtomicOrdering::SeqCst); + Ok((chunk_index..chunk_index + self.window) + .map(Self::fresh_link) + .collect()) + } + } + + /// Build a CloudFetchLink whose `expiration` is in the past. + fn expired_link(chunk_index: i64) -> CloudFetchLink { + CloudFetchLink { + expiration: chrono::Utc::now() - chrono::Duration::seconds(60), + ..create_test_link(chunk_index) + } + } + + fn entry_with_state(link: CloudFetchLink, state: ChunkState) -> ChunkEntry { + ChunkEntry { + link: Some(link), + state, + batches: None, + } + } + + #[tokio::test] + async fn refresh_batch_updates_link_for_urlfetched_chunks() { + // Chunks 0-2 all expired, all in UrlFetched state. One + // refresh covers them all. After: each has a non-expired + // URL with the REFRESHED prefix. + let chunks: Arc> = Arc::new(DashMap::new()); + for i in 0..3 { + chunks.insert(i, entry_with_state(expired_link(i), ChunkState::UrlFetched)); + } + + let mock = RefreshCountingMock::new(3); + let lock = Arc::new(TokioMutex::new(())); + let fetcher: Arc = mock.clone(); + + StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher, &chunks, &lock) + .await + .expect("refresh must succeed"); + + assert_eq!( + mock.refresh_calls.load(AtomicOrdering::SeqCst), + 1, + "exactly one batched refresh RPC for the window" + ); + for i in 0..3 { + let entry = chunks.get(&i).unwrap(); + assert!(matches!(entry.state, ChunkState::UrlFetched)); + assert!( + entry.link.as_ref().unwrap().url.contains("REFRESHED"), + "chunk {} link was not refreshed", + i + ); + assert!(!entry.link.as_ref().unwrap().is_expired()); + } + } + + #[tokio::test] + async fn refresh_batch_preserves_downloaded_state() { + // Chunk 0 is Downloaded with its bytes in memory. The + // refresh updates its link (bookkeeping) but must not reset + // state to UrlFetched — that would force a re-download of + // bytes we already have. + let chunks: Arc> = Arc::new(DashMap::new()); + let already_downloaded = ChunkEntry { + link: Some(expired_link(0)), + state: ChunkState::Downloaded, + // Real downloaded chunks carry batches; using None here + // keeps the test focussed on state-machine reconciliation. + batches: Some(vec![]), + }; + chunks.insert(0, already_downloaded); + chunks.insert(1, entry_with_state(expired_link(1), ChunkState::UrlFetched)); + + let mock = RefreshCountingMock::new(2); + let lock = Arc::new(TokioMutex::new(())); + let fetcher: Arc = mock.clone(); + + StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher, &chunks, &lock) + .await + .unwrap(); + + let c0 = chunks.get(&0).unwrap(); + assert!( + matches!(c0.state, ChunkState::Downloaded), + "Downloaded state must be preserved" + ); + assert!(c0.batches.is_some(), "Downloaded bytes must not be cleared"); + assert!( + c0.link.as_ref().unwrap().url.contains("REFRESHED"), + "link was still updated for bookkeeping" + ); + + let c1 = chunks.get(&1).unwrap(); + assert!(matches!(c1.state, ChunkState::UrlFetched)); + assert!(c1.link.as_ref().unwrap().url.contains("REFRESHED")); + } + + #[tokio::test] + async fn refresh_batch_leaves_downloading_state_intact() { + // A chunk in Downloading state means an in-flight task owns + // the state machine. Refresh must NOT reset state to + // UrlFetched (which would let `schedule_downloads` race in + // and start a second download). Only the link is replaced; + // the in-flight task will see the fresh URL on its next + // retry-iteration of `download_chunk_with_retry`. + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert( + 5, + entry_with_state(expired_link(5), ChunkState::Downloading), + ); + + let mock = RefreshCountingMock::new(1); + let lock = Arc::new(TokioMutex::new(())); + let fetcher: Arc = mock.clone(); + + StreamingCloudFetchProvider::refresh_links_batch(5, &fetcher, &chunks, &lock) + .await + .unwrap(); + + let c5 = chunks.get(&5).unwrap(); + assert!( + matches!(c5.state, ChunkState::Downloading), + "Downloading state must be preserved — the in-flight task owns it" + ); + assert!(c5.link.as_ref().unwrap().url.contains("REFRESHED")); + } + + #[tokio::test] + async fn refresh_batch_resets_download_failed_to_urlfetched() { + // A chunk in DownloadFailed (transient) should be reset to + // UrlFetched with the fresh URL so schedule_downloads can + // pick it up on next loop. + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert( + 7, + entry_with_state( + expired_link(7), + ChunkState::DownloadFailed("network glitch".into()), + ), + ); + + let mock = RefreshCountingMock::new(1); + let lock = Arc::new(TokioMutex::new(())); + let fetcher: Arc = mock.clone(); + + StreamingCloudFetchProvider::refresh_links_batch(7, &fetcher, &chunks, &lock) + .await + .unwrap(); + + let c7 = chunks.get(&7).unwrap(); + assert!(matches!(c7.state, ChunkState::UrlFetched)); + assert!(c7.link.as_ref().unwrap().url.contains("REFRESHED")); + } + + #[tokio::test] + async fn refresh_batch_dedups_concurrent_calls() { + // Two concurrent calls — only one RPC should fire. The + // second caller takes the mutex after the first releases, + // sees the now-fresh link, and skips its own refetch. + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert(0, entry_with_state(expired_link(0), ChunkState::UrlFetched)); + + let mock = RefreshCountingMock::new(1); + let lock = Arc::new(TokioMutex::new(())); + + let fetcher_a: Arc = mock.clone(); + let chunks_a = Arc::clone(&chunks); + let lock_a = Arc::clone(&lock); + let h1 = tokio::spawn(async move { + StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher_a, &chunks_a, &lock_a) + .await + }); + + let fetcher_b: Arc = mock.clone(); + let chunks_b = Arc::clone(&chunks); + let lock_b = Arc::clone(&lock); + let h2 = tokio::spawn(async move { + StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher_b, &chunks_b, &lock_b) + .await + }); + + h1.await.unwrap().unwrap(); + h2.await.unwrap().unwrap(); + + // The first holder did the work; the second holder + // re-checked, found the link non-expired, and skipped. + assert_eq!( + mock.refresh_calls.load(AtomicOrdering::SeqCst), + 1, + "concurrent refreshes must dedup down to one RPC" + ); + } } From 5c349186c267250eeba71f7b66f62ea11b1945f2 Mon Sep 17 00:00:00 2001 From: Gopal Lal Date: Mon, 25 May 2026 20:16:05 +0530 Subject: [PATCH 2/4] =?UTF-8?q?review(pr69):=20address=20P1/P2=20feedback?= =?UTF-8?q?=20=E2=80=94=20stale-link,=20clock-skew,=20refresh=20cursors,?= =?UTF-8?q?=20coverage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses seven review items on PR #69 (batched link refresh on presigned-URL expiry): ### P1 — Important 1. **In-flight Downloading task uses stale-link snapshot.** The download loop cloned `entry.link` into a local before `downloader.download(&link).await`. If a concurrent `refresh_links_batch` wrote a fresh URL during the .await, the suspended download continued against the stale URL and burned a retry attempt on the failure. Fix: after a failed download, compare the cached link's URL to the URL we tried. If different (refresh ran concurrently), don't count that attempt against the retry budget — loop immediately and pick up the fresh URL on the next iteration. 2. **Proactive `is_expired()` check spins under client clock skew.** If the client clock is N seconds ahead, every freshly- issued URL appears expired. Both the proactive check and the dedupe re-check see "still expired" → RPC per schedule_downloads iteration, bounded only by RTT. Fix: after a successful refresh, if the link for the requested start_chunk_index is *still* `is_expired()` per the local clock, surface a hard error rather than loop. The error message calls out client/server clock skew as the likely cause, making the failure mode debuggable. 3. **`refetch_links_from` did not update link-fetcher continuation cursors.** Unlike `fetch_links`, the refresh path inserted into the cache but didn't touch `next_server_fetch_index` / `next_row_offset` / `all_links_fetched`. A refresh response carrying `next_chunk_index = None` (PR #68's end-of-stream sentinel) was silently dropped — the prefetch loop would keep firing past the end of the result set. Fix: mirror the cursor-update block from `fetch_links`. Use `fetch_max` so an early-window refresh doesn't rewind progress. Also runs `decode_continuation` to honour the PR #68 transition-period total_chunk_count guard. ### P2 — Minor 4. **Misleading "still missing" error message.** The error only fired when `entry.link == None`. The stale-link case (server returned a batch not including chunk_index) hit `Some(stale)` and silently burned retries. The new check in `refresh_links_batch` (P1 #2 fix) catches both cases; the download-task message is upgraded to mention clock-skew as the alternative root cause. 5. **`refresh_batch_dedups_concurrent_calls` ran on single-threaded runtime.** Switched to `#[tokio::test(flavor = "multi_thread", worker_threads = 2)]` so the TokioMutex dedupe path is exercised under genuine contention. 6. **Test coverage gaps** — added five new tests for previously uncovered paths: - `refresh_batch_preserves_cancelled_and_released_states` — terminal arms. - `refresh_batch_inserts_new_chunk_for_window_expansion` — the `else` branch that materialises previously-unseen chunks. - `refresh_batch_errors_when_server_truncates_window` — guard against the server returning a batch missing the requested chunk_index. - `refresh_batch_propagates_rpc_error` — RPC-failure path. - `refresh_batch_errors_on_stale_after_refresh_clock_skew` — P1 #2 regression guard. 7. **`refresh_links_batch` not cancellation-aware** — documented the behaviour: RPC runs to completion even if `cancel_token` fires; acceptable in practice (SEA RPCs are short and on the cancellation path no consumer is waiting); revisit if a long-RPC transport lands. ### Tests 10 refresh-batch tests pass (5 pre-existing + 5 new). Clippy clean. Stacked on PR #68's force-pushed tip (`bee7c1f`), so this PR is rebased and the merge order is now PR #68 → PR #69 cleanly. Co-authored-by: Isaac Signed-off-by: Gopal Lal --- src/reader/cloudfetch/link_fetcher.rs | 30 ++ src/reader/cloudfetch/streaming_provider.rs | 371 +++++++++++++++++++- 2 files changed, 397 insertions(+), 4 deletions(-) diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 7f1fd561..33fc1091 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -1028,6 +1028,36 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { self.inner.links.insert(link.chunk_index, link.clone()); } + // Mirror the continuation cursor updates from `fetch_links`: + // a refresh response is a normal `get_result_chunks` + // response, just used for the expiry-recovery path. If we + // drop its continuation metadata on the floor (as the + // initial implementation did), the prefetch loop happily + // keeps firing past the actual end of the result set when a + // refresh response carries `next_chunk_index = None`. Use + // `fetch_max` so an early-window refresh (start_chunk_index + // < current cursor) doesn't rewind progress. + if let Some(last_link) = result.links.last() { + let next_row_offset = last_link.row_offset.saturating_add(last_link.row_count); + self.inner + .next_row_offset + .fetch_max(next_row_offset, Ordering::Release); + let cont = decode_continuation(last_link, self.inner.total_chunk_count_hint); + if cont.used_total_chunk_count_fallback { + self.inner.warn_total_chunk_count_fallback("link refresh"); + } + if cont.eos { + self.inner.all_links_fetched.store(true, Ordering::Release); + } else { + let advance_to = cont + .next_fetch_index + .max(last_link.chunk_index.saturating_add(1)); + self.inner + .next_server_fetch_index + .fetch_max(advance_to, Ordering::Release); + } + } + Ok(result.links) } } diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index ca784fbc..74895bf9 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -571,15 +571,36 @@ impl StreamingCloudFetchProvider { ); Self::refresh_links_batch(chunk_index, link_fetcher, chunks, refresh_lock) .await?; - chunks + // After a successful refresh, the link + // MUST exist and be fresh — `refresh_links_batch` + // returns Err otherwise (missing chunk in + // response, or stale-after-refresh = + // clock-skew). If we somehow get here with + // no link cached, treat it as an invariant + // breach. + let cached = chunks .get(&chunk_index) .and_then(|e| e.link.clone()) .ok_or_else(|| { Error::invalid_state().message(format!( - "Link for chunk {} still missing after batched refresh", + "Invariant: link for chunk {} absent after successful \ + batched refresh — refresh_links_batch should have \ + errored before reaching here", chunk_index )) - })? + })?; + if cached.is_expired() { + // Pre-refresh cache had a stale link; + // post-refresh check inside + // `refresh_links_batch` already catches + // this case. Belt-and-braces. + return Err(Error::invalid_state().message(format!( + "Link for chunk {} is still expired after refresh \ + (likely client/server clock skew or a server bug)", + chunk_index + ))); + } + cached } } }; @@ -588,6 +609,37 @@ impl StreamingCloudFetchProvider { match downloader.download(&link).await { Ok(batches) => return Ok(batches), Err(e) => { + // Stale-snapshot detection: if a concurrent + // `refresh_links_batch` updated the cached link + // while we were `.await`-ing on `download()`, we + // were downloading against an already-stale URL + // and the failure shouldn't count against our + // retry budget. The compare is on URL: a fresh + // batch from the server emits new presigned + // URLs. + // + // Without this, a task at `max_retries-1` can + // burn its final attempt on a URL it didn't + // know was stale, surfacing `Error::io()` + // despite the cache holding a fresh link. + let cached_url = chunks + .get(&chunk_index) + .and_then(|e| e.link.as_ref().map(|l| l.url.clone())); + let was_refreshed_concurrently = cached_url + .as_ref() + .is_some_and(|cached| *cached != link.url); + if was_refreshed_concurrently { + debug!( + "Chunk {} download failed against stale URL; \ + cache has a fresher link (not counting against retry budget): {}", + chunk_index, e, + ); + // Don't increment `attempts`; don't sleep. + // Loop body re-reads `entry.link` and picks + // up the fresh URL on the next iteration. + continue; + } + attempts += 1; if attempts >= max_retries { return Err(e); @@ -611,6 +663,18 @@ impl StreamingCloudFetchProvider { /// Refresh presigned-URL links for `chunk_index` and every /// subsequent chunk whose download is still pending or in flight. /// + /// **Cancellation note:** this function is *not* + /// cancellation-aware. If the provider is dropped or the + /// `cancel_token` fires while an RPC is in flight, the RPC + /// runs to completion still holding the `refresh_lock` — + /// effective drop-latency is bounded by RPC timeout. + /// Acceptable in practice (SEA RPCs are short and on the + /// kernel's cancellation path the streaming provider has + /// already signalled `end_of_stream` so no consumer is + /// waiting). If this changes — e.g. a Thrift transport with + /// much longer RPC tails lands — wrap the RPC in a + /// `tokio::select!` against `cancel_token.cancelled()`. + /// /// One RPC; per-chunk state reconciliation: /// - `UrlFetched | DownloadFailed | DownloadRetry`: link replaced /// in cache. `schedule_downloads` will pick the chunk up using @@ -674,6 +738,45 @@ impl StreamingCloudFetchProvider { .refetch_links_from(start_chunk_index, row_offset) .await?; + // Clock-skew + bad-server defence: if the server returned a + // batch but the chunk we asked about isn't in it, OR is in + // it but `is_expired()` per local clock, we have a problem. + // + // - Missing chunk: server returned a window earlier (or + // non-overlapping with) our request — we'd loop refresh + // forever, never getting a fresh URL for our chunk. + // - Still-expired link: either client clock is N seconds + // ahead of the server's URL generation time (skew), or + // the server emitted a URL that's truly past expiry + // (server bug). Either way, refresh again won't fix it, + // so loud-fail rather than spin. + let start_chunk_link = refreshed + .iter() + .find(|l| l.chunk_index == start_chunk_index); + match start_chunk_link { + None => { + return Err(Error::invalid_state().message(format!( + "Refresh response did not include chunk {} (server returned {} links \ + starting from chunk {:?}). Cannot proceed without a fresh link.", + start_chunk_index, + refreshed.len(), + refreshed.first().map(|l| l.chunk_index), + ))); + } + Some(link) if link.is_expired() => { + return Err(Error::invalid_state().message(format!( + "Refreshed link for chunk {} is still expired per local clock \ + (expires={}, now={}). Likely cause: client clock skew relative to \ + the server, or a server bug emitting pre-expired URLs. \ + Refusing to spin on repeated refresh.", + start_chunk_index, + link.expiration, + chrono::Utc::now(), + ))); + } + Some(_) => { /* fresh and present — fall through */ } + } + for fresh in refreshed { let ci = fresh.chunk_index; if let Some(mut entry) = chunks.get_mut(&ci) { @@ -1257,7 +1360,12 @@ mod tests { assert!(c7.link.as_ref().unwrap().url.contains("REFRESHED")); } - #[tokio::test] + // `#[tokio::test]` defaults to current-thread (tasks are + // cooperatively scheduled), so concurrent calls would not race. + // The multi-thread flavor genuinely runs the two + // `refresh_links_batch` calls on different worker threads, so + // the TokioMutex dedupe path is exercised under real contention. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn refresh_batch_dedups_concurrent_calls() { // Two concurrent calls — only one RPC should fire. The // second caller takes the mutex after the first releases, @@ -1295,4 +1403,259 @@ mod tests { "concurrent refreshes must dedup down to one RPC" ); } + + // ─── Additional coverage (PR #69 P2.6 feedback) ────────────── + + /// Mock fetcher with configurable failure modes for the + /// coverage-gap tests below. Defaults to "return all chunks + /// asked for"; can be configured to return a narrower window + /// or to fail with an error. + #[derive(Debug)] + struct ConfigurableMock { + // Indices the mock will actually emit on refresh, regardless + // of which `chunk_index` was requested. `None` = "echo the + // requested chunk + window". + emit_indices: StdMutex>>, + // When set, refetch_links_from returns this error. + force_error: StdMutex>, + refresh_calls: AtomicUsize, + } + + impl ConfigurableMock { + fn new() -> Arc { + Arc::new(Self { + emit_indices: StdMutex::new(None), + force_error: StdMutex::new(None), + refresh_calls: AtomicUsize::new(0), + }) + } + + fn emit_only(self: &Arc, indices: Vec) { + *self.emit_indices.lock().unwrap() = Some(indices); + } + + fn fail_with(self: &Arc, msg: &'static str) { + *self.force_error.lock().unwrap() = Some(msg); + } + } + + use std::sync::Mutex as StdMutex; + + #[async_trait::async_trait] + impl ChunkLinkFetcher for ConfigurableMock { + async fn fetch_links(&self, _: i64, _: i64) -> Result { + unreachable!() + } + async fn refetch_link(&self, _: i64, _: i64) -> Result { + unreachable!() + } + async fn refetch_links_from( + &self, + chunk_index: i64, + _: i64, + ) -> Result> { + self.refresh_calls.fetch_add(1, AtomicOrdering::SeqCst); + if let Some(msg) = *self.force_error.lock().unwrap() { + return Err(Error::network_error().message(msg)); + } + let indices = self.emit_indices.lock().unwrap().clone(); + let to_emit: Vec = match indices { + Some(v) => v, + None => (chunk_index..chunk_index + 3).collect(), + }; + Ok(to_emit + .into_iter() + .map(RefreshCountingMock::fresh_link) + .collect()) + } + } + + #[tokio::test] + async fn refresh_batch_preserves_cancelled_and_released_states() { + // Coverage for the `Cancelled` and `Released` state arms in + // `refresh_links_batch`. Both must keep their state intact + // (terminal); link metadata may be refreshed for + // bookkeeping but no download is re-triggered. + // + // Start the refresh at chunk 0 so the refresh window + // (chunks 0, 1, 2) covers our Cancelled/Released entries. + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert(0, entry_with_state(expired_link(0), ChunkState::Cancelled)); + chunks.insert(1, entry_with_state(expired_link(1), ChunkState::Released)); + chunks.insert(2, entry_with_state(expired_link(2), ChunkState::UrlFetched)); + + let mock = RefreshCountingMock::new(3); + let lock = Arc::new(TokioMutex::new(())); + let fetcher: Arc = mock.clone(); + + StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher, &chunks, &lock) + .await + .unwrap(); + + // Terminal states stay terminal. + assert!(matches!( + chunks.get(&0).unwrap().state, + ChunkState::Cancelled + )); + assert!(matches!( + chunks.get(&1).unwrap().state, + ChunkState::Released + )); + assert!(matches!( + chunks.get(&2).unwrap().state, + ChunkState::UrlFetched + )); + // All three are in the refresh window, so all three get + // their link metadata updated (including terminal states, + // for bookkeeping). + for ci in 0..3 { + assert!( + chunks + .get(&ci) + .unwrap() + .link + .as_ref() + .unwrap() + .url + .contains("REFRESHED"), + "chunk {} link metadata must be refreshed for bookkeeping", + ci, + ); + } + } + + #[tokio::test] + async fn refresh_batch_inserts_new_chunk_for_window_expansion() { + // Coverage for the "no entry yet" branch in + // `refresh_links_batch` (the `else` arm that inserts a + // brand-new ChunkEntry). Happens when the refresh response + // covers a chunk_index we hadn't materialised yet. + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert(0, entry_with_state(expired_link(0), ChunkState::UrlFetched)); + // Note: chunks 1 and 2 are NOT yet in the map. + + let mock = RefreshCountingMock::new(3); // emits chunks 0, 1, 2 + let lock = Arc::new(TokioMutex::new(())); + let fetcher: Arc = mock.clone(); + + StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher, &chunks, &lock) + .await + .unwrap(); + + // Brand-new entries materialised for 1 and 2. + assert!(chunks.get(&1).is_some(), "chunk 1 must be inserted"); + assert!(chunks.get(&2).is_some(), "chunk 2 must be inserted"); + assert!(matches!( + chunks.get(&1).unwrap().state, + ChunkState::UrlFetched + )); + assert!(matches!( + chunks.get(&2).unwrap().state, + ChunkState::UrlFetched + )); + } + + #[tokio::test] + async fn refresh_batch_errors_when_server_truncates_window() { + // Coverage for the "refresh response is missing the + // requested chunk_index" defence added in the PR #69 + // review fix. If the server returns a batch that doesn't + // include the chunk we asked about, we'd otherwise spin in + // a refresh-loop forever. + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert(5, entry_with_state(expired_link(5), ChunkState::UrlFetched)); + + let mock = ConfigurableMock::new(); + // Refresh asks for chunk 5; mock returns chunks 0..2 + // instead (truncated window). Must surface as a hard error + // rather than spin. + mock.emit_only(vec![0, 1, 2]); + let lock = Arc::new(TokioMutex::new(())); + let fetcher: Arc = mock.clone(); + + let err = StreamingCloudFetchProvider::refresh_links_batch(5, &fetcher, &chunks, &lock) + .await + .expect_err("truncated window must surface as Err"); + assert!( + err.message.contains("did not include chunk 5"), + "error should pinpoint the missing chunk: {}", + err.message, + ); + } + + #[tokio::test] + async fn refresh_batch_propagates_rpc_error() { + // Coverage for the error path: `refetch_links_from` returns + // Err, `refresh_links_batch` must propagate it (not swallow + // and silently return Ok). + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert(0, entry_with_state(expired_link(0), ChunkState::UrlFetched)); + + let mock = ConfigurableMock::new(); + mock.fail_with("network unreachable"); + let lock = Arc::new(TokioMutex::new(())); + let fetcher: Arc = mock.clone(); + + let err = StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher, &chunks, &lock) + .await + .expect_err("RPC error must surface"); + assert!( + err.message.contains("network unreachable"), + "transport error must be propagated verbatim: {}", + err.message, + ); + } + + #[tokio::test] + async fn refresh_batch_errors_on_stale_after_refresh_clock_skew() { + // Coverage for the clock-skew defence added in the PR #69 + // review fix. If the freshly-refreshed link still looks + // expired per the local clock, that's client/server clock + // skew (or a server bug). Loud-fail rather than spin + // refresh-refresh-refresh. + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert(0, entry_with_state(expired_link(0), ChunkState::UrlFetched)); + + // Build a mock that returns chunk 0 with an EXPIRED + // expiration timestamp (simulating extreme client clock + // skew where even fresh server URLs look past-expiry). + #[derive(Debug)] + struct StaleEmittingMock; + #[async_trait::async_trait] + impl ChunkLinkFetcher for StaleEmittingMock { + async fn fetch_links(&self, _: i64, _: i64) -> Result { + unreachable!() + } + async fn refetch_link(&self, _: i64, _: i64) -> Result { + unreachable!() + } + async fn refetch_links_from( + &self, + chunk_index: i64, + _: i64, + ) -> Result> { + Ok(vec![CloudFetchLink { + expiration: chrono::Utc::now() - chrono::Duration::seconds(60), + ..create_test_link(chunk_index) + }]) + } + } + + let fetcher: Arc = Arc::new(StaleEmittingMock); + let lock = Arc::new(TokioMutex::new(())); + + let err = StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher, &chunks, &lock) + .await + .expect_err("stale-after-refresh must surface as Err"); + assert!( + err.message.contains("still expired"), + "error should mention the staleness: {}", + err.message, + ); + assert!( + err.message.to_lowercase().contains("clock"), + "error should call out clock-skew as the likely cause: {}", + err.message, + ); + } } From 26a7e9b6b9ffe6e08442a9ead79c0812978f97ff Mon Sep 17 00:00:00 2001 From: Gopal Lal Date: Tue, 26 May 2026 14:51:40 +0530 Subject: [PATCH 3/4] =?UTF-8?q?review(pr69):=20address=20round-3=20feedbac?= =?UTF-8?q?k=20=E2=80=94=20coordinator=20pattern,=20dynamic-race=20tests,?= =?UTF-8?q?=20statement=5Fid=20plumbing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses 15 round-3 review comments on the batched link-refresh landed in 1282d43: HIGH: - F1 (lock-across-RPC, 900s budget): replace `TokioMutex` held across the RPC with a CAS-claim coordinator (`AtomicBool` + `Notify`). RPC is wrapped in `tokio::select!` against the cancel token. RAII drop-guard releases the claim on every exit path. - F2 (untested dynamic race): new `refresh_does_not_disturb_concurrent_downloading_task` spawns a real task holding `Downloading` state via `Notify`, runs a concurrent refresh, then verifies (a) state preserved, (b) URL swapped in cache, (c) task picks up the fresh URL on next read. - F3 (double-spawn race): `Downloading | DownloadFailed | DownloadRetry` now get link-only updates during refresh; only `UrlFetched | Pending` get state → `UrlFetched`. The in-flight task owns the state machine. MEDIUM: - F4 (passive expiry): post-failure stale-snapshot check now treats `link.is_expired()` as "don't count this attempt" alongside URL-change detection. - F5 (Pending arm doc/code): doc rewritten to describe the arm as forward-compatibility (every insertion uses `ChunkEntry::with_link` today; `Pending` only exists via `ChunkEntry::pending()` which is not currently called). - F6 (dedupe-skip uses absolute time): both re-check sites inside `refresh_links_batch` now skip on URL change OR `is_expired()=false` — URL change proves a refresh landed regardless of how TTL would flag the new link. - F7 (duplicated stale-after-refresh defence): removed from `refresh_links_batch`; consolidated to single site in `download_chunk_with_retry`. - F8 (interior holes): new contiguity check spanning `[start_chunk_index, max_chunk_index]` in the response. `refresh_batch_errors_on_interior_holes` covers it. - F9 (no direct refetch_links_from tests): 4 new tests in `link_fetcher.rs` covering cache writes, EOS reconciliation, cursor advancement, and empty-response handling. LOW: - F11 (no client-side cap): `MAX_REFRESH_RESPONSE_LINKS = 10_000` hard cap at the provider; `debug_assert!` at the link-fetcher site documents the SEA contract assumption. - F12 (no statement_id in logs): added `statement_id()` to `ChunkLinkFetcher` trait (default `None`), implemented for `SeaChunkLinkFetcherHandle`, plumbed into the provider and attached as a `tracing` field on the three refresh-path log lines. The "Issuing batched link refresh" line is promoted from `debug!` to `info!`. - F13 (naked ? on refresh error): refresh `?` now wrapped with `Error::io().message("Link refresh RPC failed for chunk N") .with_cause(e)` so the downstream `error!("Failed to download chunk N: …")` log line clearly distinguishes refresh failures from download failures. - F14 (PR-# refs rot): swept `PR #67/68/69` references from `streaming_provider.rs` and `link_fetcher.rs`. - F15 (DownloadFailed reason wiped): new `last_failure_reason: Option` field on `ChunkEntry`, preserved across `DownloadFailed → DownloadRetry` transitions. - F16 (clock-skew boundary not exercised): boundary test now references `LINK_EXPIRY_BUFFER_SECS - 1` and `+ 1` directly, mirror-checks both sides. Also folds 8 args of `download_chunk_with_retry` into a `DownloadCtx` struct so the spawn-site is cleaner. Test totals after this commit: 436 lib + 6 doc = 442 tests pass, 0 fail. cargo fmt + cargo clippy --all-targets -- -D warnings both clean. Co-authored-by: Isaac Signed-off-by: Gopal Lal --- src/reader/cloudfetch/link_fetcher.rs | 192 ++- src/reader/cloudfetch/streaming_provider.rs | 1191 +++++++++++++++---- src/types/cloudfetch.rs | 13 + 3 files changed, 1152 insertions(+), 244 deletions(-) diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 33fc1091..1de17ba9 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -114,6 +114,17 @@ pub(crate) trait ChunkLinkFetcher: Send + Sync + std::fmt::Debug { chunk_index: i64, row_offset: i64, ) -> Result>; + + /// Identifier of the statement this fetcher is bound to, if + /// known. Used by downstream consumers (e.g. the streaming + /// provider) to attach a `statement_id` field to log lines so + /// operators can filter by query. + /// + /// Default implementation returns `None` — mock fetchers and + /// non-SEA transports don't need to surface anything. + fn statement_id(&self) -> Option<&str> { + None + } } /// SEA implementation of ChunkLinkFetcher with caching and proactive prefetching. @@ -899,7 +910,7 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { // — a `for i in start..server_fetch_index` with silent // `is_none()` skip would return a non-contiguous slice and // hang the streaming provider's wait_for_chunk on the - // first missing index (P1 #1 in PR #68 review). + // first missing index. if start_chunk_index < server_fetch_index { let mut links = Vec::new(); let mut i = start_chunk_index; @@ -1020,6 +1031,21 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { .get_result_chunks(&self.inner.statement_id, chunk_index, row_offset) .await?; + // The SEA contract today caps the number of links in a + // single `get_result_chunks` response to ~empirical bounds + // (≤ a few hundred chunks per page). If SEA ever changes + // and a page returns thousands of links, the downstream + // reconciliation loop (which mutates a DashMap entry per + // link) is a quiet O(N) hotspot. `debug_assert!` makes the + // assumption loud in debug builds without paying for it in + // release. + debug_assert!( + result.links.len() <= 10_000, + "implausibly large refresh response ({} links) — \ + SEA contract may have changed; review the cap", + result.links.len(), + ); + // Refresh the internal link cache with every link the server // returned. The caller will reconcile per-chunk state in the // streaming provider (which knows which chunks are already @@ -1060,6 +1086,10 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { Ok(result.links) } + + fn statement_id(&self) -> Option<&str> { + Some(&self.inner.statement_id) + } } #[cfg(test)] @@ -1434,6 +1464,162 @@ mod tests { assert!(result.is_err()); } + // ────────────────────────────────────────────────────────────── + // refetch_links_from coverage — exercises the batched-refresh + // entry point used by the streaming provider's expiry path. + // The SEA impl writes the cache, advances the row-offset and + // server-fetch cursors, and reconciles EOS — none of which + // was tested directly before (only via mocks at the trait + // level inside the streaming provider). + // ────────────────────────────────────────────────────────────── + + #[tokio::test] + async fn test_sea_link_fetcher_refetch_links_from_writes_cache() { + // After `refetch_links_from`, every link in the response + // must be in the internal cache so subsequent + // `fetch_links` / `refetch_link` calls see the new URLs + // without an extra round trip. + let links = vec![ + vec![create_test_link(0)], + vec![create_test_link(1)], + vec![create_test_link_terminal(2)], + ]; + let client = Arc::new(MockDatabricksClient::new(links)); + let fetcher = SeaChunkLinkFetcher::new( + client, + "test-statement", + &[], + None, + 128, + tokio::runtime::Handle::current(), + ); + let handle = SeaChunkLinkFetcherHandle::new(fetcher); + + // Request a refresh batch from chunk 1 onward. + let refreshed = handle.refetch_links_from(1, 1000).await.unwrap(); + + // Mock returns one link per `get_result_chunks` call — + // the chunk at the requested index. Refresh response is + // a single link for chunk 1. + assert_eq!(refreshed.len(), 1); + assert_eq!(refreshed[0].chunk_index, 1); + + // Cache was updated. + assert!(handle.inner.has_link(1)); + } + + #[tokio::test] + async fn test_sea_link_fetcher_refetch_links_from_advances_eos() { + // When `refetch_links_from` returns a terminal link + // (`next_chunk_index = None`), the `all_links_fetched` + // flag must flip so subsequent `fetch_links` calls + // short-circuit instead of hitting the server again. + let links = vec![vec![create_test_link_terminal(0)]]; + let client = Arc::new(MockDatabricksClient::new(links)); + let fetcher = SeaChunkLinkFetcher::new( + client, + "test-statement", + &[], + None, + 128, + tokio::runtime::Handle::current(), + ); + let handle = SeaChunkLinkFetcherHandle::new(fetcher); + + // Pre-condition: not yet at EOS. + assert!(!handle.inner.all_links_fetched.load(Ordering::Acquire)); + + let _ = handle.refetch_links_from(0, 0).await.unwrap(); + + // Post-condition: EOS flipped on after the terminal link + // landed in the refresh response. + assert!( + handle.inner.all_links_fetched.load(Ordering::Acquire), + "terminal link in refresh response must flip all_links_fetched", + ); + } + + #[tokio::test] + async fn test_sea_link_fetcher_refetch_links_from_advances_cursor() { + // `refetch_links_from` mirrors `fetch_links`'s cursor + // advancement (`next_server_fetch_index` via `fetch_max`, + // `next_row_offset` via `fetch_max`). A subsequent + // prefetch must NOT re-issue the chunk we just refreshed. + let links = vec![ + vec![create_test_link(0)], + vec![create_test_link(1)], + vec![create_test_link_terminal(2)], + ]; + let client = Arc::new(MockDatabricksClient::new(links)); + let fetcher = SeaChunkLinkFetcher::new( + client, + "test-statement", + &[], + None, + 128, + tokio::runtime::Handle::current(), + ); + let handle = SeaChunkLinkFetcherHandle::new(fetcher); + + // Pre-condition: cursor at 0. + assert_eq!( + handle.inner.next_server_fetch_index.load(Ordering::Acquire), + 0 + ); + assert_eq!(handle.inner.next_row_offset.load(Ordering::Acquire), 0); + + // Refresh from chunk 0. The non-terminal link's + // continuation should advance the cursor past 0. + let _ = handle.refetch_links_from(0, 0).await.unwrap(); + + // `next_server_fetch_index` advances past the refreshed + // index — refresh of chunk 0 should leave it at 1 (or + // higher, depending on the test link's `next_chunk_index` + // hint). + let new_idx = handle.inner.next_server_fetch_index.load(Ordering::Acquire); + assert!( + new_idx >= 1, + "next_server_fetch_index must advance past refreshed chunk; got {}", + new_idx, + ); + + // `next_row_offset` advances past chunk 0's rows + // (row_offset=0 + row_count=1000 = 1000). + let new_offset = handle.inner.next_row_offset.load(Ordering::Acquire); + assert_eq!( + new_offset, 1000, + "next_row_offset must advance to row_offset + row_count", + ); + } + + #[tokio::test] + async fn test_sea_link_fetcher_refetch_links_from_empty_response() { + // A `get_result_chunks` call past end-of-stream returns + // `ChunkLinkFetchResult::end_of_stream()` (empty links, + // `has_more = false`). `refetch_links_from` must handle + // this gracefully — no panic on empty `.last()`, no + // bogus cursor update. + let links = vec![vec![create_test_link_terminal(0)]]; + let client = Arc::new(MockDatabricksClient::new(links)); + let fetcher = SeaChunkLinkFetcher::new( + client, + "test-statement", + &[], + None, + 128, + tokio::runtime::Handle::current(), + ); + let handle = SeaChunkLinkFetcherHandle::new(fetcher); + + // Ask for a chunk past the end — mock returns + // end_of_stream (empty links). + let refreshed = handle.refetch_links_from(99, 0).await.unwrap(); + assert!( + refreshed.is_empty(), + "past-EOS request should return empty vec, not error", + ); + } + #[tokio::test] async fn test_sea_link_fetcher_all_links_fetched_flag() { let links = vec![vec![create_test_link_terminal(0)]]; @@ -1457,7 +1643,7 @@ mod tests { } // ────────────────────────────────────────────────────────────── - // Continuation tests (PR #68 P1.3 feedback). + // Continuation tests. // // These exercise the bounded-SEA-API control flow directly, // bypassing the async prefetch race so a regression in @@ -1594,7 +1780,7 @@ mod tests { } // ────────────────────────────────────────────────────────────── - // total_chunk_count transition-period fallback (PR #68 P0). + // total_chunk_count transition-period fallback. // ────────────────────────────────────────────────────────────── #[tokio::test] diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 74895bf9..2f2da44b 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -33,9 +33,9 @@ use dashmap::DashMap; use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; -use tokio::sync::{Mutex as TokioMutex, Notify}; +use tokio::sync::Notify; use tokio_util::sync::CancellationToken; -use tracing::{debug, error, warn}; +use tracing::{debug, error, info, warn}; /// Merge a list of record batches into larger batches up to `target_rows` each. /// @@ -139,20 +139,70 @@ pub struct StreamingCloudFetchProvider { // Tokio runtime handle for spawning tasks runtime_handle: tokio::runtime::Handle, - // Mutex around the batched link-refresh path. + // Statement identifier (when available from the link + // fetcher) for log correlation. Operators filtering + // production logs by SEA `statement_id` need this attached + // to refresh-path log lines. + statement_id: Option>, + + // Coordinator for batched link-refresh. // // Several chunks expiring concurrently (the common shape: a // burst of presigned URLs all near the 1h boundary) would each - // try to refresh the link cache. With this mutex, the first - // caller takes the lock and issues exactly one - // `refetch_links_from` RPC that covers the entire forward - // window; subsequent callers await the same lock, then each - // pulls the fresh link from the cache without a second - // round-trip. + // try to refresh the link cache. The coordinator ensures only + // one refresh RPC is in flight at a time; other callers either + // see the fresh link in cache after the RPC completes, or wait + // on a `Notify` for the in-flight refresh to finish. + // + // **Critical**: we do NOT hold a lock across the RPC itself. + // The SEA HTTP layer retries up to 900 seconds (see + // `src/client/retry.rs`), and holding a lock for that duration + // would block consumer drops, statement cancels, and any + // task that hit an expired URL while the RPC was in flight. + // Instead, the coordinator uses a CAS-style claim on an + // `AtomicBool`: a single task wins the claim and issues the + // RPC; concurrent callers see the claim is taken and wait on + // the `Notify` for the RPC to complete (or the cancel-token + // to fire), then re-check the cache. // // `Arc<...>` so spawned download tasks can hold their own clone // without keeping the whole provider alive past stream end. - refresh_lock: Arc>, + refresh_coordinator: Arc, +} + +/// Coordinates concurrent batched link-refresh attempts. +/// +/// See the doc on `StreamingCloudFetchProvider::refresh_coordinator` +/// for the design rationale (specifically: we cannot hold a lock +/// across the SEA RPC because of the 900s retry budget). +#[derive(Debug, Default)] +struct RefreshCoordinator { + /// Set to `true` while a refresh RPC is in flight. Concurrent + /// callers see this and wait on `done` rather than racing into + /// the same RPC. + in_progress: AtomicBool, + /// Notified each time a refresh completes (successfully or + /// not). Used by waiters to re-check the cache. + done: Notify, +} + +/// All the wiring `download_chunk_with_retry` needs. +/// +/// Bundles what was an 8-argument function signature into a +/// single struct so the spawn-site (and any future helper that +/// drives downloads) doesn't have to thread each Arc through by +/// hand. Cloned cheaply: every field is already an `Arc` / +/// `CancellationToken` / `Copy`. +#[derive(Clone)] +struct DownloadCtx { + downloader: Arc, + link_fetcher: Arc, + chunks: Arc>, + refresh_coordinator: Arc, + cancel_token: CancellationToken, + statement_id: Option>, + max_retries: u32, + retry_delay: std::time::Duration, } impl std::fmt::Debug for StreamingCloudFetchProvider { @@ -181,6 +231,7 @@ impl StreamingCloudFetchProvider { chunk_downloader: Arc, runtime_handle: tokio::runtime::Handle, ) -> Arc { + let statement_id = link_fetcher.statement_id().map(Arc::from); let provider = Arc::new(Self { link_fetcher, chunk_downloader, @@ -196,7 +247,8 @@ impl StreamingCloudFetchProvider { chunk_state_changed: Arc::new(Notify::new()), cancel_token: CancellationToken::new(), runtime_handle, - refresh_lock: Arc::new(TokioMutex::new(())), + statement_id, + refresh_coordinator: Arc::new(RefreshCoordinator::default()), }); // Start background initialization that fetches links and schedules downloads @@ -410,22 +462,27 @@ impl StreamingCloudFetchProvider { .and_then(|e| e.link.as_ref().map(|l| l.is_expired())) .unwrap_or(false); if expired { + let sid = self.statement_id.as_deref().unwrap_or(""); debug!( + statement_id = %sid, "Proactive refresh: cached link for chunk {} already expired", - next_index + next_index, ); if let Err(e) = Self::refresh_links_batch( next_index, &self.link_fetcher, &self.chunks, - &self.refresh_lock, + &self.refresh_coordinator, + &self.cancel_token, + self.statement_id.as_deref(), ) .await { warn!( + statement_id = %sid, "Proactive batched refresh failed for chunk {}: {}; \ will fall through to per-download retry path", - next_index, e + next_index, e, ); // Don't abort scheduling — the download task's // own refresh attempt will surface the error @@ -463,30 +520,27 @@ impl StreamingCloudFetchProvider { self.current_chunk_index.load(Ordering::Acquire) ); - // Spawn download task + // Spawn download task. All the per-download wiring + // lives in `DownloadCtx` so the spawn-site doesn't have + // to re-thread 8 parameters and the function signature + // stays clean. let chunk_index = next_index; - let downloader = Arc::clone(&self.chunk_downloader); - let link_fetcher = Arc::clone(&self.link_fetcher); - let chunks = self.chunks.clone(); - let refresh_lock = Arc::clone(&self.refresh_lock); + let ctx = DownloadCtx { + downloader: Arc::clone(&self.chunk_downloader), + link_fetcher: Arc::clone(&self.link_fetcher), + chunks: self.chunks.clone(), + refresh_coordinator: Arc::clone(&self.refresh_coordinator), + cancel_token: self.cancel_token.clone(), + statement_id: self.statement_id.clone(), + max_retries: self.config.max_retries, + retry_delay: self.config.retry_delay, + }; let chunk_state_changed = Arc::clone(&self.chunk_state_changed); - let cancel_token = self.cancel_token.clone(); - let max_retries = self.config.max_retries; - let retry_delay = self.config.retry_delay; + let chunks = self.chunks.clone(); let batch_merge_target_rows = self.config.batch_merge_target_rows; self.runtime_handle.spawn(async move { - let result = Self::download_chunk_with_retry( - chunk_index, - &downloader, - &link_fetcher, - &chunks, - &refresh_lock, - max_retries, - retry_delay, - &cancel_token, - ) - .await; + let result = Self::download_chunk_with_retry(chunk_index, &ctx).await; match result { Ok(batches) => { @@ -521,7 +575,9 @@ impl StreamingCloudFetchProvider { Err(e) => { error!("Failed to download chunk {}: {}", chunk_index, e); if let Some(mut entry) = chunks.get_mut(&chunk_index) { - entry.state = ChunkState::DownloadFailed(e.to_string()); + let msg = e.to_string(); + entry.state = ChunkState::DownloadFailed(msg.clone()); + entry.last_failure_reason = Some(msg); } } } @@ -532,21 +588,14 @@ impl StreamingCloudFetchProvider { } /// Download a single chunk with retry and link refresh on expiry. - #[allow(clippy::too_many_arguments)] async fn download_chunk_with_retry( chunk_index: i64, - downloader: &ChunkDownloader, - link_fetcher: &Arc, - chunks: &Arc>, - refresh_lock: &Arc>, - max_retries: u32, - retry_delay: std::time::Duration, - cancel_token: &CancellationToken, + ctx: &DownloadCtx, ) -> Result> { let mut attempts = 0; loop { - if cancel_token.is_cancelled() { + if ctx.cancel_token.is_cancelled() { return Err(Error::invalid_state().message("Download cancelled")); } @@ -558,7 +607,7 @@ impl StreamingCloudFetchProvider { // separate `refetch_link` calls when a burst of chunks // expires concurrently. let link = { - let entry = chunks.get(&chunk_index); + let entry = ctx.chunks.get(&chunk_index); let stored_link = entry.as_ref().and_then(|e| e.link.clone()); match stored_link { @@ -569,8 +618,28 @@ impl StreamingCloudFetchProvider { triggering batched refresh", chunk_index ); - Self::refresh_links_batch(chunk_index, link_fetcher, chunks, refresh_lock) - .await?; + Self::refresh_links_batch( + chunk_index, + &ctx.link_fetcher, + &ctx.chunks, + &ctx.refresh_coordinator, + &ctx.cancel_token, + ctx.statement_id.as_deref(), + ) + .await + .map_err(|e| { + // Wrap with chunk_index breadcrumb so the + // downstream `error!("Failed to download + // chunk N: …")` log clearly distinguishes + // refresh-RPC failures from + // download-RPC failures. + Error::io() + .message(format!( + "Link refresh RPC failed for chunk {}", + chunk_index + )) + .with_cause(e) + })?; // After a successful refresh, the link // MUST exist and be fresh — `refresh_links_batch` // returns Err otherwise (missing chunk in @@ -578,7 +647,8 @@ impl StreamingCloudFetchProvider { // clock-skew). If we somehow get here with // no link cached, treat it as an invariant // breach. - let cached = chunks + let cached = ctx + .chunks .get(&chunk_index) .and_then(|e| e.link.clone()) .ok_or_else(|| { @@ -606,33 +676,54 @@ impl StreamingCloudFetchProvider { }; // Attempt download - match downloader.download(&link).await { + match ctx.downloader.download(&link).await { Ok(batches) => return Ok(batches), Err(e) => { - // Stale-snapshot detection: if a concurrent - // `refresh_links_batch` updated the cached link - // while we were `.await`-ing on `download()`, we - // were downloading against an already-stale URL - // and the failure shouldn't count against our - // retry budget. The compare is on URL: a fresh - // batch from the server emits new presigned - // URLs. + // Stale-snapshot detection. Two ways a download + // can fail against an already-stale URL through + // no fault of the retry budget: // - // Without this, a task at `max_retries-1` can - // burn its final attempt on a URL it didn't - // know was stale, surfacing `Error::io()` - // despite the cache holding a fresh link. - let cached_url = chunks + // 1. **Concurrent refresh** updated the cached + // link while we were `.await`-ing on + // `download()`. We compare on URL: a fresh + // batch from the server emits new presigned + // URLs. + // 2. **Passive expiry** — the URL we tried (and + // every consumer of the cache shared) just + // crossed its TTL while in flight. S3 may + // return 403 a hair earlier than + // `LINK_EXPIRY_BUFFER_SECS` predicts; clock + // skew can also push us past expiry + // silently. In either case, the link we + // *tried* is now expired per the local + // clock; the next loop iteration will + // refresh and pick up a fresh URL. + // + // (Edge case for case 1: if the server happened + // to emit the same URL on refresh — extremely + // unlikely for presigned URLs but possible in + // theory — we'd count the attempt under + // case-1 detection. The retry budget still + // bounds total work.) + let cached_url = ctx + .chunks .get(&chunk_index) .and_then(|e| e.link.as_ref().map(|l| l.url.clone())); let was_refreshed_concurrently = cached_url .as_ref() .is_some_and(|cached| *cached != link.url); - if was_refreshed_concurrently { + let attempted_link_now_expired = link.is_expired(); + if was_refreshed_concurrently || attempted_link_now_expired { debug!( - "Chunk {} download failed against stale URL; \ - cache has a fresher link (not counting against retry budget): {}", - chunk_index, e, + "Chunk {} download failed against a link the cache now \ + considers stale ({}); not counting against retry budget: {}", + chunk_index, + if was_refreshed_concurrently { + "refreshed concurrently" + } else { + "passively expired in-flight" + }, + e, ); // Don't increment `attempts`; don't sleep. // Loop body re-reads `entry.link` and picks @@ -641,20 +732,32 @@ impl StreamingCloudFetchProvider { } attempts += 1; - if attempts >= max_retries { + if attempts >= ctx.max_retries { return Err(e); } warn!( "Chunk {} download failed (attempt {}/{}): {}, retrying...", - chunk_index, attempts, max_retries, e + chunk_index, attempts, ctx.max_retries, e ); - // Update state to retry - if let Some(mut entry) = chunks.get_mut(&chunk_index) { + // The `DownloadRetry` state itself carries no + // failure reason; the reason lives in + // `ChunkEntry::last_failure_reason` so an + // operator inspecting the chunks map during + // the retry-sleep window still has the + // correlation breadcrumb. Keeping + // `DownloadRetry` distinct from + // `DownloadFailed` is intentional — it + // signals "task is alive and sleeping" to + // other code paths (notably + // `refresh_links_batch`'s "don't double-spawn" + // guard). + if let Some(mut entry) = ctx.chunks.get_mut(&chunk_index) { entry.state = ChunkState::DownloadRetry; + entry.last_failure_reason = Some(e.to_string()); } - tokio::time::sleep(retry_delay).await; + tokio::time::sleep(ctx.retry_delay).await; } } } @@ -663,58 +766,159 @@ impl StreamingCloudFetchProvider { /// Refresh presigned-URL links for `chunk_index` and every /// subsequent chunk whose download is still pending or in flight. /// - /// **Cancellation note:** this function is *not* - /// cancellation-aware. If the provider is dropped or the - /// `cancel_token` fires while an RPC is in flight, the RPC - /// runs to completion still holding the `refresh_lock` — - /// effective drop-latency is bounded by RPC timeout. - /// Acceptable in practice (SEA RPCs are short and on the - /// kernel's cancellation path the streaming provider has - /// already signalled `end_of_stream` so no consumer is - /// waiting). If this changes — e.g. a Thrift transport with - /// much longer RPC tails lands — wrap the RPC in a - /// `tokio::select!` against `cancel_token.cancelled()`. + /// ## Coordination + /// + /// Uses [`RefreshCoordinator`] — an `AtomicBool` + `Notify` + /// instead of a `TokioMutex`. The mutex was held across the + /// SEA RPC, which can retry for up to 900 s (see + /// `src/client/retry.rs`); a stuck retry would block consumer + /// drops and any other download task that hit an expired URL. /// - /// One RPC; per-chunk state reconciliation: - /// - `UrlFetched | DownloadFailed | DownloadRetry`: link replaced - /// in cache. `schedule_downloads` will pick the chunk up using - /// the fresh URL on its next loop. - /// - `Downloading`: link replaced in cache. The active download - /// task will see the new link on its next retry iteration - /// (this function is called from inside that task — see - /// `download_chunk_with_retry`). - /// - `Downloaded | ProcessingFailed | Cancelled | Released`: - /// bytes (or terminal state) are already in memory. We update - /// the cached link for bookkeeping but do nothing else; the - /// chunk doesn't need to be re-downloaded. - /// - `Pending` (no link cached): not in our refresh window, skip. + /// New flow: + /// 1. CAS-claim `in_progress: false → true`. If another task + /// already holds the claim, wait on `done.notified()` + /// (cooperatively, in parallel with the `cancel_token`) + /// and then re-check the cache without ourselves issuing + /// an RPC. + /// 2. If we won the claim, issue the RPC with `select!` + /// against `cancel_token.cancelled()` so a provider drop + /// surfaces immediately. + /// 3. Apply the refresh batch to the chunks map, then + /// `notify_waiters()` so others can re-check. + /// 4. Always release the claim (even on error). /// - /// The `refresh_lock` is taken before the RPC fires. Multiple - /// concurrent download tasks hitting expired URLs at the same - /// time will queue on the lock; only the first holder issues the - /// RPC, the rest find their now-fresh link already in cache when - /// they re-check. + /// ## Per-chunk state reconciliation /// - /// `start_chunk_index` is the chunk whose download just failed - /// (or is about to fail) — its server-side row offset is read - /// from the cached link if any so the RPC carries the right - /// `row_offset` for the bounded SEA API contract. + /// - `UrlFetched`: link replaced; state stays `UrlFetched` + /// so `schedule_downloads` picks the chunk up with the + /// fresh URL. + /// - `Pending`: forward-compatibility arm. No `Pending` entry + /// exists in the chunks map today after initialization + /// (every insertion uses `ChunkEntry::with_link`), but if + /// a future change introduces a link-less `Pending` within + /// the refresh window, this arm promotes it to + /// `UrlFetched` once a fresh link arrives. + /// - `Downloading` / `DownloadFailed` / `DownloadRetry`: + /// **link replaced only**. A task owns the state machine + /// for the chunk; resetting state would let + /// `schedule_downloads` spawn a *second* download task while + /// the first one is still working, double-counting + /// `chunks_in_memory` and racing both tasks to write into + /// `entry.batches`. The running task re-reads `entry.link` + /// on its next retry iteration and picks up the fresh URL + /// transparently. + /// - `Downloaded` / `ProcessingFailed` / `Cancelled` / + /// `Released`: link replaced for bookkeeping; no other + /// change. Bytes / terminal state are already final. async fn refresh_links_batch( start_chunk_index: i64, link_fetcher: &Arc, chunks: &Arc>, - refresh_lock: &Arc>, + coordinator: &Arc, + cancel_token: &CancellationToken, + statement_id: Option<&str>, ) -> Result<()> { - let _guard = refresh_lock.lock().await; + // Display helper: `""` is loud enough for ops + // to notice missing statement_id in log filters. + let sid = statement_id.unwrap_or(""); + // Snapshot the URL the caller saw expired *before* we + // attempt anything. The skip-after-refresh checks below + // compare against this snapshot: any URL change proves a + // refresh landed, regardless of what `is_expired()` says + // about the new URL (so the dedupe contract holds even if + // a future server emits short-TTL URLs ≤ LINK_EXPIRY_BUFFER_SECS). + let pre_attempt_url = chunks + .get(&start_chunk_index) + .and_then(|e| e.link.as_ref().map(|l| l.url.clone())); + + // Acquire-style CAS to claim "I'm the one refreshing". + // `compare_exchange` returns `Ok(prev)` only when prev was + // exactly `false` — i.e. nobody else was refreshing. + let won_claim = coordinator + .in_progress + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .is_ok(); + + if !won_claim { + // Another task is mid-refresh. Wait for its `done` + // signal — cancel-aware, so a provider drop unblocks + // us. Then re-check the cache; the other refresh may + // have already refreshed our chunk. + debug!( + statement_id = %sid, + "Batched refresh for chunk {} deferred — another task is refreshing; \ + waiting on done signal", + start_chunk_index, + ); + let notified = coordinator.done.notified(); + tokio::select! { + _ = notified => {} + _ = cancel_token.cancelled() => { + return Err(Error::invalid_state() + .message("Refresh wait cancelled")); + } + } + // Re-check: did the other refresh land a fresh link + // for *our* chunk? "Fresh" means either (a) the URL + // changed from what the caller saw — proves a refresh + // landed even if absolute TTL would still flag it, or + // (b) `is_expired()` reports false. Either signal is + // enough to skip our own RPC. + if let Some(entry) = chunks.get(&start_chunk_index) { + if let Some(ref link) = entry.link { + let url_changed = pre_attempt_url + .as_ref() + .is_some_and(|prev| *prev != link.url); + if url_changed || !link.is_expired() { + debug!( + statement_id = %sid, + "Concurrent refresh delivered a {} link for chunk {}; \ + skipping our own RPC", + if url_changed { "new" } else { "fresh" }, + start_chunk_index, + ); + return Ok(()); + } + } + } + // Other refresh didn't cover us (or its result still + // looked stale). Fall through and try to claim again. + // We loop via the public caller's retry path — return + // `Ok(())` here and let `download_chunk_with_retry` + // re-attempt; if the link is still expired the caller + // will surface the consistent "still expired after + // refresh" error. + return Ok(()); + } + + // We hold the claim. Make sure we release it on any exit + // path (success, error, RPC cancel). A small RAII guard + // is the cleanest way to do that. + struct ReleaseOnDrop<'a>(&'a RefreshCoordinator); + impl Drop for ReleaseOnDrop<'_> { + fn drop(&mut self) { + self.0.in_progress.store(false, Ordering::Release); + self.0.done.notify_waiters(); + } + } + let _release = ReleaseOnDrop(coordinator.as_ref()); - // Re-check after taking the lock: another task may have just - // refreshed our chunk. Skip the RPC if so. + // Re-check after winning the claim: between the + // expired-link check at the caller and our CAS, some + // other path may have already refreshed our chunk. Same + // dual signal as above: URL change OR `is_expired()=false`. if let Some(entry) = chunks.get(&start_chunk_index) { if let Some(ref link) = entry.link { - if !link.is_expired() { + let url_changed = pre_attempt_url + .as_ref() + .is_some_and(|prev| *prev != link.url); + if url_changed || !link.is_expired() { debug!( - "Batched refresh for chunk {} skipped — already refreshed by another task", - start_chunk_index + statement_id = %sid, + "Batched refresh for chunk {} skipped after claim — \ + link became {} between expired-check and claim", + start_chunk_index, + if url_changed { "new" } else { "fresh" }, ); return Ok(()); } @@ -723,104 +927,165 @@ impl StreamingCloudFetchProvider { // Derive `row_offset` from the existing cached link if any. // The bounded SEA API contract requires `row_offset` on - // CloudFetch fetches (see PR #67 + PR #68); honour it here so - // the server-side cursor lands on the right row. + // CloudFetch fetches; honour it here so the server-side + // cursor lands on the right row. let row_offset = chunks .get(&start_chunk_index) .and_then(|e| e.link.as_ref().map(|l| l.row_offset)) .unwrap_or(0); - debug!( + // Promoted to `info!`: refreshes are rare and + // operationally interesting. Operators want to see them + // without enabling debug logging across the kernel. + info!( + statement_id = %sid, "Issuing batched link refresh from chunk {} (row_offset={})", - start_chunk_index, row_offset + start_chunk_index, row_offset, ); - let refreshed = link_fetcher - .refetch_links_from(start_chunk_index, row_offset) - .await?; + // Cancel-aware RPC: the SEA HTTP layer can retry for + // hundreds of seconds; we want a provider drop or + // statement cancel to unblock us promptly. + let refreshed = tokio::select! { + r = link_fetcher.refetch_links_from(start_chunk_index, row_offset) => r?, + _ = cancel_token.cancelled() => { + return Err(Error::invalid_state() + .message("Refresh RPC cancelled")); + } + }; + + // Sanity cap on response size. A well-behaved server bounds + // a single refresh page; a pathological server could + // return millions of links and blow the chunks map up. + // The cap is loose — any realistic page is well under it, + // and exceeding it almost certainly signals a bug or a + // misconfigured server. + const MAX_REFRESH_RESPONSE_LINKS: usize = 10_000; + if refreshed.len() > MAX_REFRESH_RESPONSE_LINKS { + return Err(Error::invalid_state().message(format!( + "Refresh response is implausibly large: {} links exceeds cap of {} \ + (likely a server bug or misconfigured page size)", + refreshed.len(), + MAX_REFRESH_RESPONSE_LINKS, + ))); + } - // Clock-skew + bad-server defence: if the server returned a - // batch but the chunk we asked about isn't in it, OR is in - // it but `is_expired()` per local clock, we have a problem. + // Bad-server defences: + // 1. Refresh batch must include the chunk we asked about. + // Without this we'd loop refresh forever, never getting + // a fresh URL for our chunk. + // 2. The contiguous range starting at `start_chunk_index` + // must have no interior holes. SEA pages chunks + // contiguously; a hole signals a partial response, and + // silently accepting it would leave the held-back + // chunk with a still-stale link → refresh loop forever + // on *that* chunk while siblings download cleanly. // - // - Missing chunk: server returned a window earlier (or - // non-overlapping with) our request — we'd loop refresh - // forever, never getting a fresh URL for our chunk. - // - Still-expired link: either client clock is N seconds - // ahead of the server's URL generation time (skew), or - // the server emitted a URL that's truly past expiry - // (server bug). Either way, refresh again won't fix it, - // so loud-fail rather than spin. + // We do NOT also check `is_expired()` here — clock-skew + // detection lives in `download_chunk_with_retry` after + // this returns (the caller fetches the cached link and + // sees still-expired ⇒ surfaces the same error). A single + // fail-fast site is enough. let start_chunk_link = refreshed .iter() .find(|l| l.chunk_index == start_chunk_index); - match start_chunk_link { - None => { - return Err(Error::invalid_state().message(format!( - "Refresh response did not include chunk {} (server returned {} links \ - starting from chunk {:?}). Cannot proceed without a fresh link.", - start_chunk_index, - refreshed.len(), - refreshed.first().map(|l| l.chunk_index), - ))); + if start_chunk_link.is_none() { + return Err(Error::invalid_state().message(format!( + "Refresh response did not include chunk {} (server returned {} links: {:?}). \ + Cannot proceed without a fresh link for the requested chunk.", + start_chunk_index, + refreshed.len(), + refreshed.iter().map(|l| l.chunk_index).collect::>(), + ))); + } + // Interior-hole check: assume contiguous from + // `start_chunk_index`. Find the max chunk_index in the + // response and verify every index in [start, max] is + // present. + if let Some(max_idx) = refreshed.iter().map(|l| l.chunk_index).max() { + let present: std::collections::HashSet = + refreshed.iter().map(|l| l.chunk_index).collect(); + let mut missing: Vec = Vec::new(); + for ci in start_chunk_index..=max_idx { + if !present.contains(&ci) { + missing.push(ci); + if missing.len() >= 10 { + // Cap reported list — error message stays readable. + break; + } + } } - Some(link) if link.is_expired() => { + if !missing.is_empty() { return Err(Error::invalid_state().message(format!( - "Refreshed link for chunk {} is still expired per local clock \ - (expires={}, now={}). Likely cause: client clock skew relative to \ - the server, or a server bug emitting pre-expired URLs. \ - Refusing to spin on repeated refresh.", + "Refresh response has interior holes in range [{}, {}]: \ + missing chunks {:?}{}. Refusing to accept a partial window — \ + held-back chunks would loop refresh forever.", start_chunk_index, - link.expiration, - chrono::Utc::now(), + max_idx, + missing, + if missing.len() == 10 { + " (truncated)" + } else { + "" + }, ))); } - Some(_) => { /* fresh and present — fall through */ } } + // Apply the refresh to the chunks map. Per the doc on + // this function: `Downloading | DownloadFailed | + // DownloadRetry` get link-only updates so the in-flight + // task continues to own the state machine. for fresh in refreshed { let ci = fresh.chunk_index; if let Some(mut entry) = chunks.get_mut(&ci) { match entry.state { - // Pending links to download — replace and let - // schedule_downloads pick up on next loop. - ChunkState::UrlFetched - | ChunkState::DownloadFailed(_) - | ChunkState::DownloadRetry => { + // No download task is active for `UrlFetched`; + // refresh updates the link in place so + // `schedule_downloads` picks the chunk up with + // the fresh URL. + // + // `Pending` is included for forward-compatibility: + // `ChunkEntry::pending()` always sets `link: None`, + // so no `Pending` entry exists in the chunks map + // today after initialization completes (every + // insertion uses `ChunkEntry::with_link`). If a + // future change introduces a link-less `Pending` + // entry within the refresh window, this arm + // promotes it to `UrlFetched` the moment a fresh + // link arrives — same as a normal `UrlFetched` + // entry getting its link replaced. + ChunkState::UrlFetched | ChunkState::Pending => { entry.link = Some(fresh); entry.state = ChunkState::UrlFetched; } - // Download already in flight — the in-flight - // task re-reads `entry.link` on each retry, so - // updating the link in place is enough. Don't - // touch the state machine; the running task - // owns it. - ChunkState::Downloading => { + // A task owns the state machine here. + // Update the link only — the task re-reads + // `entry.link` on its next retry and picks + // up the fresh URL transparently. Critically, + // we do NOT reset to `UrlFetched`: that would + // let `schedule_downloads` spawn a second + // task for the same chunk. + ChunkState::Downloading + | ChunkState::DownloadFailed(_) + | ChunkState::DownloadRetry => { entry.link = Some(fresh); } - // Terminal-ish or already-have-bytes states. - // Keep the link metadata current (cheap; future - // bookkeeping may read `entry.link.row_offset` - // etc.) but do not change state or trigger any - // download. + // Terminal / already-have-bytes states. Keep + // link metadata current (future bookkeeping + // may read `entry.link.row_offset`) but no + // state change, no re-download. ChunkState::Downloaded | ChunkState::ProcessingFailed(_) | ChunkState::Cancelled | ChunkState::Released => { entry.link = Some(fresh); } - // Pending without a link — refresh response - // covered a chunk we hadn't asked about yet. - // Drop a link in and mark as ready to schedule. - ChunkState::Pending => { - entry.link = Some(fresh); - entry.state = ChunkState::UrlFetched; - } } } else { - // No entry yet — the refresh response covered a - // chunk we haven't seen at all. Create a fresh entry - // with the link; schedule_downloads will pick it up - // when it's in the consumer window. + // Brand-new chunk in the refresh batch — outside + // the current consumer window. Insert with the + // link so `schedule_downloads` can pick it up + // when the consumer reaches it. chunks.insert(ci, ChunkEntry::with_link(fresh)); } } @@ -1224,6 +1489,7 @@ mod tests { link: Some(link), state, batches: None, + last_failure_reason: None, } } @@ -1238,12 +1504,20 @@ mod tests { } let mock = RefreshCountingMock::new(3); - let lock = Arc::new(TokioMutex::new(())); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); let fetcher: Arc = mock.clone(); - StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher, &chunks, &lock) - .await - .expect("refresh must succeed"); + StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + ) + .await + .expect("refresh must succeed"); assert_eq!( mock.refresh_calls.load(AtomicOrdering::SeqCst), @@ -1275,17 +1549,26 @@ mod tests { // Real downloaded chunks carry batches; using None here // keeps the test focussed on state-machine reconciliation. batches: Some(vec![]), + last_failure_reason: None, }; chunks.insert(0, already_downloaded); chunks.insert(1, entry_with_state(expired_link(1), ChunkState::UrlFetched)); let mock = RefreshCountingMock::new(2); - let lock = Arc::new(TokioMutex::new(())); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); let fetcher: Arc = mock.clone(); - StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher, &chunks, &lock) - .await - .unwrap(); + StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + ) + .await + .unwrap(); let c0 = chunks.get(&0).unwrap(); assert!( @@ -1318,12 +1601,20 @@ mod tests { ); let mock = RefreshCountingMock::new(1); - let lock = Arc::new(TokioMutex::new(())); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); let fetcher: Arc = mock.clone(); - StreamingCloudFetchProvider::refresh_links_batch(5, &fetcher, &chunks, &lock) - .await - .unwrap(); + StreamingCloudFetchProvider::refresh_links_batch( + 5, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + ) + .await + .unwrap(); let c5 = chunks.get(&5).unwrap(); assert!( @@ -1334,10 +1625,23 @@ mod tests { } #[tokio::test] - async fn refresh_batch_resets_download_failed_to_urlfetched() { - // A chunk in DownloadFailed (transient) should be reset to - // UrlFetched with the fresh URL so schedule_downloads can - // pick it up on next loop. + async fn refresh_batch_does_not_reset_in_flight_states() { + // F3 regression guard. A chunk in `DownloadFailed` or + // `DownloadRetry` is owned by an in-flight download task + // — that task is either about to retry (`DownloadRetry`) + // or just failed and the spawn-site is updating state + // (`DownloadFailed` is also a transient retry state set + // by `download_chunk_with_retry` between attempts in + // some refactors). + // + // Refresh MUST NOT reset these to `UrlFetched`. Doing so + // would let `schedule_downloads` claim and spawn a second + // download task for the same chunk while the first is + // still working — double-counting `chunks_in_memory` and + // racing both tasks to write to `entry.batches`. The + // in-flight task picks up the fresh link on its next + // retry iteration via `entry.link`; refresh only needs + // to update the link field. let chunks: Arc> = Arc::new(DashMap::new()); chunks.insert( 7, @@ -1346,18 +1650,44 @@ mod tests { ChunkState::DownloadFailed("network glitch".into()), ), ); + chunks.insert( + 8, + entry_with_state(expired_link(8), ChunkState::DownloadRetry), + ); - let mock = RefreshCountingMock::new(1); - let lock = Arc::new(TokioMutex::new(())); + // Mock window covers chunks 7..=9 so we refresh across + // both our test entries. + let mock = RefreshCountingMock::new(3); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); let fetcher: Arc = mock.clone(); - StreamingCloudFetchProvider::refresh_links_batch(7, &fetcher, &chunks, &lock) - .await - .unwrap(); - + StreamingCloudFetchProvider::refresh_links_batch( + 7, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + ) + .await + .unwrap(); + + // States must be UNCHANGED. let c7 = chunks.get(&7).unwrap(); - assert!(matches!(c7.state, ChunkState::UrlFetched)); + let c8 = chunks.get(&8).unwrap(); + assert!( + matches!(c7.state, ChunkState::DownloadFailed(_)), + "DownloadFailed state must be preserved — the in-flight task owns it" + ); + assert!( + matches!(c8.state, ChunkState::DownloadRetry), + "DownloadRetry state must be preserved — the in-flight task owns it" + ); + // But the links must be updated, so the in-flight task + // picks them up on its next retry iteration. assert!(c7.link.as_ref().unwrap().url.contains("REFRESHED")); + assert!(c8.link.as_ref().unwrap().url.contains("REFRESHED")); } // `#[tokio::test]` defaults to current-thread (tasks are @@ -1374,22 +1704,39 @@ mod tests { chunks.insert(0, entry_with_state(expired_link(0), ChunkState::UrlFetched)); let mock = RefreshCountingMock::new(1); - let lock = Arc::new(TokioMutex::new(())); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); let fetcher_a: Arc = mock.clone(); let chunks_a = Arc::clone(&chunks); - let lock_a = Arc::clone(&lock); + let coordinator_a = Arc::clone(&coordinator); + let cancel_a = cancel.clone(); let h1 = tokio::spawn(async move { - StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher_a, &chunks_a, &lock_a) - .await + StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher_a, + &chunks_a, + &coordinator_a, + &cancel_a, + None, + ) + .await }); let fetcher_b: Arc = mock.clone(); let chunks_b = Arc::clone(&chunks); - let lock_b = Arc::clone(&lock); + let coordinator_b = Arc::clone(&coordinator); + let cancel_b = cancel.clone(); let h2 = tokio::spawn(async move { - StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher_b, &chunks_b, &lock_b) - .await + StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher_b, + &chunks_b, + &coordinator_b, + &cancel_b, + None, + ) + .await }); h1.await.unwrap().unwrap(); @@ -1404,7 +1751,7 @@ mod tests { ); } - // ─── Additional coverage (PR #69 P2.6 feedback) ────────────── + // ─── Coverage for the batched link-refresh edge cases ────────── /// Mock fetcher with configurable failure modes for the /// coverage-gap tests below. Defaults to "return all chunks @@ -1485,12 +1832,20 @@ mod tests { chunks.insert(2, entry_with_state(expired_link(2), ChunkState::UrlFetched)); let mock = RefreshCountingMock::new(3); - let lock = Arc::new(TokioMutex::new(())); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); let fetcher: Arc = mock.clone(); - StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher, &chunks, &lock) - .await - .unwrap(); + StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + ) + .await + .unwrap(); // Terminal states stay terminal. assert!(matches!( @@ -1535,12 +1890,20 @@ mod tests { // Note: chunks 1 and 2 are NOT yet in the map. let mock = RefreshCountingMock::new(3); // emits chunks 0, 1, 2 - let lock = Arc::new(TokioMutex::new(())); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); let fetcher: Arc = mock.clone(); - StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher, &chunks, &lock) - .await - .unwrap(); + StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + ) + .await + .unwrap(); // Brand-new entries materialised for 1 and 2. assert!(chunks.get(&1).is_some(), "chunk 1 must be inserted"); @@ -1558,10 +1921,9 @@ mod tests { #[tokio::test] async fn refresh_batch_errors_when_server_truncates_window() { // Coverage for the "refresh response is missing the - // requested chunk_index" defence added in the PR #69 - // review fix. If the server returns a batch that doesn't - // include the chunk we asked about, we'd otherwise spin in - // a refresh-loop forever. + // requested chunk_index" defence. If the server returns + // a batch that doesn't include the chunk we asked about, + // we'd otherwise spin in a refresh-loop forever. let chunks: Arc> = Arc::new(DashMap::new()); chunks.insert(5, entry_with_state(expired_link(5), ChunkState::UrlFetched)); @@ -1570,12 +1932,20 @@ mod tests { // instead (truncated window). Must surface as a hard error // rather than spin. mock.emit_only(vec![0, 1, 2]); - let lock = Arc::new(TokioMutex::new(())); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); let fetcher: Arc = mock.clone(); - let err = StreamingCloudFetchProvider::refresh_links_batch(5, &fetcher, &chunks, &lock) - .await - .expect_err("truncated window must surface as Err"); + let err = StreamingCloudFetchProvider::refresh_links_batch( + 5, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + ) + .await + .expect_err("truncated window must surface as Err"); assert!( err.message.contains("did not include chunk 5"), "error should pinpoint the missing chunk: {}", @@ -1583,6 +1953,43 @@ mod tests { ); } + #[tokio::test] + async fn refresh_batch_errors_on_interior_holes() { + // F8: server returns chunks [0, 1, 3] starting from 0 — + // chunk 2 is a hole. We refuse this rather than silently + // accept and leave chunk 2 with a stale link (refresh-loop + // forever on chunk 2 while siblings download cleanly). + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert(0, entry_with_state(expired_link(0), ChunkState::UrlFetched)); + + let mock = ConfigurableMock::new(); + mock.emit_only(vec![0, 1, 3]); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); + let fetcher: Arc = mock.clone(); + + let err = StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + ) + .await + .expect_err("interior hole must surface as Err"); + assert!( + err.message.contains("interior holes"), + "error should mention interior holes: {}", + err.message, + ); + assert!( + err.message.contains("[2]"), + "error should list the missing chunk index: {}", + err.message, + ); + } + #[tokio::test] async fn refresh_batch_propagates_rpc_error() { // Coverage for the error path: `refetch_links_from` returns @@ -1593,12 +2000,20 @@ mod tests { let mock = ConfigurableMock::new(); mock.fail_with("network unreachable"); - let lock = Arc::new(TokioMutex::new(())); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); let fetcher: Arc = mock.clone(); - let err = StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher, &chunks, &lock) - .await - .expect_err("RPC error must surface"); + let err = StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + ) + .await + .expect_err("RPC error must surface"); assert!( err.message.contains("network unreachable"), "transport error must be propagated verbatim: {}", @@ -1607,18 +2022,22 @@ mod tests { } #[tokio::test] - async fn refresh_batch_errors_on_stale_after_refresh_clock_skew() { - // Coverage for the clock-skew defence added in the PR #69 - // review fix. If the freshly-refreshed link still looks - // expired per the local clock, that's client/server clock - // skew (or a server bug). Loud-fail rather than spin - // refresh-refresh-refresh. + async fn refresh_batch_stale_after_refresh_leaves_caller_to_detect() { + // F7 (duplicated stale-after-refresh defence) — the + // check is now exclusively in `download_chunk_with_retry` + // (the caller), not in `refresh_links_batch` itself. + // This means `refresh_links_batch` accepts a stale server + // response without erroring; the caller's post-refresh + // `is_expired()` check is what surfaces the clock-skew + // error. + // + // This test verifies the new contract: even when the + // server returns a stale link, `refresh_links_batch` + // returns Ok and writes the (still-stale) link to the + // cache. The caller's responsibility from there. let chunks: Arc> = Arc::new(DashMap::new()); chunks.insert(0, entry_with_state(expired_link(0), ChunkState::UrlFetched)); - // Build a mock that returns chunk 0 with an EXPIRED - // expiration timestamp (simulating extreme client clock - // skew where even fresh server URLs look past-expiry). #[derive(Debug)] struct StaleEmittingMock; #[async_trait::async_trait] @@ -1642,20 +2061,310 @@ mod tests { } let fetcher: Arc = Arc::new(StaleEmittingMock); - let lock = Arc::new(TokioMutex::new(())); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); + + // refresh_links_batch returns Ok — it no longer + // duplicates the staleness check. + StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + ) + .await + .expect("refresh_links_batch must accept the (stale) server response"); + + // ...but the cached link is the stale one the server + // emitted. The caller (download_chunk_with_retry) is + // expected to detect this and surface a clear error. + let cached = chunks.get(&0).unwrap(); + assert!( + cached.link.as_ref().unwrap().is_expired(), + "stale server link must land in the cache as-is", + ); + } - let err = StreamingCloudFetchProvider::refresh_links_batch(0, &fetcher, &chunks, &lock) - .await - .expect_err("stale-after-refresh must surface as Err"); + #[tokio::test] + async fn refresh_batch_accepts_boundary_link_within_expiry_buffer() { + // F16: a "fresh" link that lands within the + // `LINK_EXPIRY_BUFFER_SECS` window is technically marked + // `is_expired() == true` by our safety margin, but + // `refresh_links_batch` itself doesn't enforce freshness. + // Verify the contract: batch refresh accepts the link + // as-is; the caller's post-refresh `is_expired()` check + // is what eventually drives a re-refresh. + // + // The test uses `LINK_EXPIRY_BUFFER_SECS - 1` to land + // squarely inside the buffer regardless of how the + // constant is later tuned. A future maintainer who bumps + // the buffer should expect this test to keep passing + // without edits. + use crate::types::cloudfetch::LINK_EXPIRY_BUFFER_SECS; + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert(0, entry_with_state(expired_link(0), ChunkState::UrlFetched)); + + #[derive(Debug)] + struct BoundaryMock { + ttl_secs: i64, + } + #[async_trait::async_trait] + impl ChunkLinkFetcher for BoundaryMock { + async fn fetch_links(&self, _: i64, _: i64) -> Result { + unreachable!() + } + async fn refetch_link(&self, _: i64, _: i64) -> Result { + unreachable!() + } + async fn refetch_links_from( + &self, + chunk_index: i64, + _: i64, + ) -> Result> { + // Expires inside the buffer — externally looks + // "valid for more seconds" but + // `is_expired()` returns true. + Ok(vec![CloudFetchLink { + expiration: chrono::Utc::now() + chrono::Duration::seconds(self.ttl_secs), + ..create_test_link(chunk_index) + }]) + } + } + + // TTL just inside the buffer: `is_expired()` flags it, + // raw `expiration` is still in the future. + let fetcher: Arc = Arc::new(BoundaryMock { + ttl_secs: LINK_EXPIRY_BUFFER_SECS - 1, + }); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); + + // refresh_links_batch returns Ok and accepts the + // boundary link. The caller is responsible for + // re-checking `is_expired()`. + StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + ) + .await + .expect("refresh must accept a boundary link"); + + let cached = chunks.get(&0).unwrap(); + let link = cached.link.as_ref().unwrap(); + // Critical invariant: `is_expired()` reports true even + // though raw `expiration` is still in the future. The + // safety buffer is what catches the clock-skew edge. assert!( - err.message.contains("still expired"), - "error should mention the staleness: {}", - err.message, + link.is_expired(), + "boundary link (ttl={}s, buffer={}s) must report is_expired=true", + LINK_EXPIRY_BUFFER_SECS - 1, + LINK_EXPIRY_BUFFER_SECS, + ); + assert!( + link.expiration > chrono::Utc::now(), + "raw expiration is still in the future — the buffer is what flags it", + ); + + // Mirror check: TTL just outside the buffer must report + // `is_expired() == false`. This is what the dedupe path + // would treat as "no refresh needed." + let fresh_link = CloudFetchLink { + expiration: chrono::Utc::now() + chrono::Duration::seconds(LINK_EXPIRY_BUFFER_SECS + 1), + ..create_test_link(0) + }; + assert!( + !fresh_link.is_expired(), + "link with ttl={}s (just outside buffer={}s) must report is_expired=false", + LINK_EXPIRY_BUFFER_SECS + 1, + LINK_EXPIRY_BUFFER_SECS, ); + } + + #[tokio::test] + async fn refresh_batch_cancellation_unblocks_immediately() { + // F1: refresh must be cancel-aware. Verify that + // cancelling the token while the refresh RPC is in + // flight surfaces a clean error without waiting for the + // RPC's full retry budget. + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert(0, entry_with_state(expired_link(0), ChunkState::UrlFetched)); + + // Mock that hangs forever on refetch_links_from. + #[derive(Debug)] + struct HangingMock; + #[async_trait::async_trait] + impl ChunkLinkFetcher for HangingMock { + async fn fetch_links(&self, _: i64, _: i64) -> Result { + unreachable!() + } + async fn refetch_link(&self, _: i64, _: i64) -> Result { + unreachable!() + } + async fn refetch_links_from(&self, _: i64, _: i64) -> Result> { + std::future::pending::<()>().await; + unreachable!() + } + } + + let fetcher: Arc = Arc::new(HangingMock); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); + + // Spawn the refresh and cancel after a short delay. + let cancel_clone = cancel.clone(); + let cancel_task = tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + cancel_clone.cancel(); + }); + + let result = StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + ) + .await; + + cancel_task.await.unwrap(); + let err = result.expect_err("refresh must error on cancel, not hang on the RPC"); assert!( - err.message.to_lowercase().contains("clock"), - "error should call out clock-skew as the likely cause: {}", + err.message.to_lowercase().contains("cancel"), + "error should mention cancellation: {}", err.message, ); + + // Critical: the `in_progress` flag must be cleared even + // on the cancel path. Otherwise subsequent refreshes + // would queue indefinitely behind a flag that was never + // released. The `ReleaseOnDrop` guard handles this. + assert!( + !coordinator.in_progress.load(Ordering::Acquire), + "in_progress flag must be cleared on cancel via the RAII guard", + ); + } + + #[tokio::test] + async fn refresh_does_not_disturb_concurrent_downloading_task() { + // F2: the static-state "Downloading" test + // (`refresh_batch_leaves_downloading_state_intact`) + // only proves the match arm doesn't reset state — it + // doesn't prove the dynamic invariant: when a download + // task is *actually running* and the chunks map says + // `Downloading`, a concurrent refresh must not (a) + // change the task's view of the state machine, (b) + // resurrect the chunk into `UrlFetched` (which would + // let `schedule_downloads` double-spawn), or (c) + // disturb the link such that the task can't observe + // the fresh URL on its next iteration. + // + // This test simulates a real in-flight download via + // `tokio::spawn` gated on a `Notify`. The "task" + // observes the link, awaits the gate (which we hold + // open during the refresh), then re-reads the link + // and reports what it saw. + use tokio::sync::Notify; + + let chunks: Arc> = Arc::new(DashMap::new()); + // The download task's starting link (a stale URL it's + // already "downloading against"). + let initial_link = expired_link(0); + let initial_url = initial_link.url.clone(); + chunks.insert(0, entry_with_state(initial_link, ChunkState::Downloading)); + + // Gate that the fake download task waits on. We open it + // after the refresh completes so the task is guaranteed + // to observe the post-refresh cache. + let proceed = Arc::new(Notify::new()); + + // The fake download task: re-reads `entry.link` after + // the gate opens (mirroring `download_chunk_with_retry`'s + // retry-loop behaviour) and reports both the URL it saw + // and the chunk's state at that moment. + let chunks_clone = Arc::clone(&chunks); + let proceed_clone = Arc::clone(&proceed); + let task = tokio::spawn(async move { + proceed_clone.notified().await; + let entry = chunks_clone.get(&0).expect("chunk 0 must exist"); + let observed_url = entry.link.as_ref().map(|l| l.url.clone()); + let observed_state = entry.state.clone(); + (observed_url, observed_state) + }); + + // While the fake task is parked at the gate, fire a + // refresh against the same chunks map. The refresh mock + // emits a *new* URL for chunk 0. + let mock = RefreshCountingMock::new(1); // emits chunks 0..0 + let fetcher: Arc = mock.clone(); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); + + StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher, + &chunks, + &coordinator, + &cancel, + None, + ) + .await + .expect("refresh must succeed"); + + // Invariant 1: state is *still* Downloading. The refresh + // must not have reset it to UrlFetched (which would + // double-spawn). This is the dynamic version of the + // F3 invariant. + let post_refresh_state = chunks.get(&0).unwrap().state.clone(); + assert!( + matches!(post_refresh_state, ChunkState::Downloading), + "concurrent refresh must not change Downloading state; got {:?}", + post_refresh_state, + ); + + // Invariant 2: the URL was actually swapped in the + // cache. Without this, the in-flight task has no way + // to pick up the fresh link on its next iteration. + let post_refresh_url = chunks + .get(&0) + .and_then(|e| e.link.as_ref().map(|l| l.url.clone())) + .expect("link must still be present"); + assert_ne!( + post_refresh_url, initial_url, + "refresh must update the cached URL even while state remains Downloading", + ); + assert!( + post_refresh_url.contains("REFRESHED"), + "cached URL must be the refresh-mock's new URL; got {}", + post_refresh_url, + ); + + // Now release the fake task and verify it observes the + // post-refresh state. + proceed.notify_one(); + let (observed_url, observed_state) = + tokio::time::timeout(std::time::Duration::from_secs(1), task) + .await + .expect("task must complete") + .expect("task must not panic"); + + // Invariant 3: the in-flight task, on its next read of + // `entry.link`, picks up the fresh URL transparently — + // exactly the contract the PR claims. + assert_eq!( + observed_url.as_deref(), + Some(post_refresh_url.as_str()), + "in-flight task must see the refreshed URL on next read", + ); + assert!( + matches!(observed_state, ChunkState::Downloading), + "in-flight task observes the chunk as still Downloading (owns the state machine)", + ); } } diff --git a/src/types/cloudfetch.rs b/src/types/cloudfetch.rs index b69251c1..6333c572 100644 --- a/src/types/cloudfetch.rs +++ b/src/types/cloudfetch.rs @@ -184,6 +184,17 @@ pub struct ChunkEntry { pub state: ChunkState, /// Parsed record batches (populated when state is Downloaded). pub batches: Option>, + /// Most recent failure reason, preserved across state + /// transitions that erase it from `ChunkState` itself. + /// + /// `ChunkState::DownloadFailed(reason)` carries the reason + /// while it's set, but the retry loop transitions + /// `DownloadFailed → DownloadRetry` (where the reason no + /// longer lives in the state). Without this field an operator + /// can't correlate the chunk's failure history during the + /// retry-sleep window. Last writer wins — only the most + /// recent reason is preserved. + pub last_failure_reason: Option, } impl ChunkEntry { @@ -193,6 +204,7 @@ impl ChunkEntry { link: None, state: ChunkState::Pending, batches: None, + last_failure_reason: None, } } @@ -202,6 +214,7 @@ impl ChunkEntry { link: Some(link), state: ChunkState::UrlFetched, batches: None, + last_failure_reason: None, } } } From e677ca24cf2c0533147804e3b592f790ea20e3f1 Mon Sep 17 00:00:00 2001 From: Gopal Lal Date: Wed, 27 May 2026 12:45:03 +0530 Subject: [PATCH 4/4] =?UTF-8?q?review(pr69):=20address=20round-4=20follow-?= =?UTF-8?q?up=20=E2=80=94=20loser-of-claim=20disjoint-window=20gap?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the residual gap the round-3 review flagged (comment id=3302845089) in the `RefreshCoordinator` CAS-claim loser path. **Problem.** After round-3, when Task B lost the CAS to Task A and Task A's refresh window covered a *disjoint* chunk range, Task B woke from `done.notified()`, saw its own chunk still stale, and returned `Ok(())`. The caller (`download_chunk_with_retry`) then hit the post-refresh `is_expired()` guard and surfaced `"Link for chunk N is still expired after refresh (likely client/server clock skew or a server bug)"` — a misleading diagnosis for what was actually a benign concurrent-disjoint race. Compounded by `notify_waiters()` thundering-herd amplification. **Fix (Option 1 from the review).** Wrap the CAS / wait / re- check sequence in a bounded retry loop inside `refresh_links_batch`. A loser who wakes to find its chunk still stale loops back to retry the CAS itself. Three iterations covers the realistic worst case (two concurrent disjoint-window refreshers + ours); hard-bound to avoid pathological churn. On exhaustion the function returns `Error::unavailable()` with a typed message so the caller doesn't conflate retry-exhaustion with the clock-skew path. **Plus Option 3 (better diagnostics).** The `download_chunk_with_retry` post-refresh guard now distinguishes the two distinct root causes by comparing the pre-refresh cached URL against the post-refresh URL: - URL changed → `Error::invalid_state()` "URL changed but `is_expired()` still true — likely client/server clock skew or a server bug" (real clock-skew diagnosis). - URL unchanged → `Error::unavailable()` "not refreshed by the concurrent refresh window (URL unchanged); retry would help" (benign disjoint-window race; retryable). New regression test `refresh_batch_disjoint_window_loser_retries_claim` sets up two concurrent refresh requests for chunks 0 and 50 against a mock that only ever returns the chunk it was asked about (window=1). After the fix both calls succeed, both chunks land fresh URLs in the cache, and exactly two RPCs fire — proving the loser re-claimed and refreshed its own window rather than returning Ok and letting the caller surface a bogus error. Also: branch rebased onto latest main (`3aa25b2`). The two PR #68 commits (`4a1a9b8`, `bee7c1f`) were skipped during rebase since they're already on main via the merge. Test totals: 22/22 streaming_provider + 483 lib pass. cargo fmt + cargo clippy --all-targets -- -D warnings clean. Co-authored-by: Isaac Signed-off-by: Gopal Lal --- src/reader/cloudfetch/streaming_provider.rs | 222 +++++++++++++++++--- 1 file changed, 197 insertions(+), 25 deletions(-) diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 2f2da44b..d9a5c2d3 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -660,15 +660,59 @@ impl StreamingCloudFetchProvider { )) })?; if cached.is_expired() { - // Pre-refresh cache had a stale link; - // post-refresh check inside - // `refresh_links_batch` already catches - // this case. Belt-and-braces. - return Err(Error::invalid_state().message(format!( - "Link for chunk {} is still expired after refresh \ - (likely client/server clock skew or a server bug)", - chunk_index - ))); + // The link is still expired after the + // refresh call returned `Ok(())`. Two + // distinct root causes, surfaced with + // distinct errors so operators don't + // get a misleading clock-skew message + // for the benign concurrent-disjoint + // case. + // + // (a) **Clock skew / server bug**: a + // refresh ran *for our chunk* but + // the link is still flagged + // expired. The URL is the new one + // from the server. The local-vs- + // server clock or `LINK_EXPIRY_BUFFER_SECS` + // is off, or the server emitted a + // stale link. + // (b) **Concurrent disjoint window**: + // a refresh ran but didn't cover + // our chunk (loser-of-claim path + // returned Ok). The URL is + // unchanged — same one we started + // with. Surfaces as `Unavailable` + // so the caller can retry without + // conflating with the clock-skew + // diagnosis. + // + // `refresh_links_batch` itself now + // returns Err for the + // MAX_CLAIM_RETRIES exhaustion case, + // so reaching this branch with an + // unchanged URL means we were in a + // disjoint-window race that resolved + // within the retry budget but still + // didn't refresh our chunk (e.g. the + // winner's window was strictly before + // our chunk_index). + let url_unchanged = stored_link + .as_ref() + .is_some_and(|prev| prev.url == cached.url); + return Err(if url_unchanged { + Error::unavailable().message(format!( + "Link for chunk {} not refreshed by the concurrent \ + refresh window (URL unchanged); retry would help", + chunk_index, + )) + } else { + Error::invalid_state().message(format!( + "Link for chunk {} is still expired after refresh \ + (URL changed but `is_expired()` still true — \ + likely client/server clock skew or a server bug)", + chunk_index, + )) + }); } cached } @@ -831,21 +875,43 @@ impl StreamingCloudFetchProvider { .get(&start_chunk_index) .and_then(|e| e.link.as_ref().map(|l| l.url.clone())); - // Acquire-style CAS to claim "I'm the one refreshing". - // `compare_exchange` returns `Ok(prev)` only when prev was - // exactly `false` — i.e. nobody else was refreshing. - let won_claim = coordinator - .in_progress - .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) - .is_ok(); + // Disjoint-window retry budget. The loser-of-claim path + // (below) waits on `done` for whoever owns the claim. If + // the winner's refresh window didn't cover *our* chunk + // (e.g. two download tasks for disjoint chunk ranges hit + // expiry within the same lock window), the wait resolves + // with our chunk still stale. Without this loop we'd + // return `Ok(())` and the caller's post-refresh + // `is_expired()` check would surface a misleading + // "still expired — clock skew" error for what is + // actually a benign disjoint-window race. + // + // Three iterations covers the realistic worst case (two + // concurrent disjoint-window refreshers + ours); a hard + // bound avoids pathological churn if the server keeps + // emitting non-overlapping refresh batches. + const MAX_CLAIM_RETRIES: u32 = 3; + + for claim_attempt in 0..MAX_CLAIM_RETRIES { + // Acquire-style CAS to claim "I'm the one refreshing". + // `compare_exchange` returns `Ok(prev)` only when prev was + // exactly `false` — i.e. nobody else was refreshing. + let won_claim = coordinator + .in_progress + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .is_ok(); + + if won_claim { + break; + } - if !won_claim { // Another task is mid-refresh. Wait for its `done` // signal — cancel-aware, so a provider drop unblocks // us. Then re-check the cache; the other refresh may // have already refreshed our chunk. debug!( statement_id = %sid, + claim_attempt, "Batched refresh for chunk {} deferred — another task is refreshing; \ waiting on done signal", start_chunk_index, @@ -881,14 +947,21 @@ impl StreamingCloudFetchProvider { } } } - // Other refresh didn't cover us (or its result still - // looked stale). Fall through and try to claim again. - // We loop via the public caller's retry path — return - // `Ok(())` here and let `download_chunk_with_retry` - // re-attempt; if the link is still expired the caller - // will surface the consistent "still expired after - // refresh" error. - return Ok(()); + // Disjoint-window case: the winning refresh ran but + // didn't cover our chunk. Loop back to retry the CAS + // claim ourselves. If we never win after + // MAX_CLAIM_RETRIES, surface a typed error so the + // caller doesn't conflate this with the clock-skew + // path. + if claim_attempt + 1 == MAX_CLAIM_RETRIES { + return Err(Error::unavailable().message(format!( + "Concurrent refresh contention: claim CAS lost {} times for chunk {} \ + and each winning refresh covered a disjoint window. Likely \ + pathological concurrent expiry across very different chunk ranges; \ + consider lowering the per-task fan-out or filing a bug.", + MAX_CLAIM_RETRIES, start_chunk_index, + ))); + } } // We hold the claim. Make sure we release it on any exit @@ -1751,6 +1824,105 @@ mod tests { ); } + #[tokio::test] + async fn refresh_batch_disjoint_window_loser_retries_claim() { + // Loser-of-claim disjoint-window gap (round-3 follow-up): + // when Task A wins the CAS and refreshes a window that + // does NOT cover Task B's chunk, Task B must loop back to + // retry the CAS itself rather than returning `Ok(())` and + // letting the caller surface a misleading "still expired + // — clock skew" error. + // + // Mock semantics: returns ONLY the chunk_index it was + // asked about (window = 1). So a refresh starting at + // chunk 0 covers chunk 0 only; a refresh starting at + // chunk 50 covers chunk 50 only. + // + // Test setup: two concurrent refresh requests for chunks + // 0 and 50. Both starting links are expired. After both + // complete: + // - Both chunks must have fresh URLs in the cache. + // - Exactly TWO RPC calls were made (one per disjoint + // window). + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert(0, entry_with_state(expired_link(0), ChunkState::UrlFetched)); + chunks.insert( + 50, + entry_with_state(expired_link(50), ChunkState::UrlFetched), + ); + + // window=1 → each refresh returns ONE link (only the + // chunk_index it was asked about). So a refresh for + // chunk 0 cannot cover chunk 50 and vice versa. + let mock = RefreshCountingMock::new(1); + let coordinator = Arc::new(RefreshCoordinator::default()); + let cancel = CancellationToken::new(); + + let fetcher_a: Arc = mock.clone(); + let chunks_a = Arc::clone(&chunks); + let coordinator_a = Arc::clone(&coordinator); + let cancel_a = cancel.clone(); + let h1 = tokio::spawn(async move { + StreamingCloudFetchProvider::refresh_links_batch( + 0, + &fetcher_a, + &chunks_a, + &coordinator_a, + &cancel_a, + None, + ) + .await + }); + + let fetcher_b: Arc = mock.clone(); + let chunks_b = Arc::clone(&chunks); + let coordinator_b = Arc::clone(&coordinator); + let cancel_b = cancel.clone(); + let h2 = tokio::spawn(async move { + StreamingCloudFetchProvider::refresh_links_batch( + 50, + &fetcher_b, + &chunks_b, + &coordinator_b, + &cancel_b, + None, + ) + .await + }); + + // Both calls must succeed — no "still expired" error + // should surface for the disjoint-window case. + h1.await.unwrap().expect("chunk 0 refresh must succeed"); + h2.await.unwrap().expect("chunk 50 refresh must succeed"); + + // Both chunks have been refreshed (URLs contain + // "REFRESHED" from the mock). + for ci in [0, 50] { + let cached = chunks + .get(&ci) + .and_then(|e| e.link.as_ref().map(|l| l.url.clone())) + .expect("chunk must be cached"); + assert!( + cached.contains("REFRESHED"), + "chunk {} URL must be refreshed after disjoint-window retry; got {}", + ci, + cached, + ); + } + + // Exactly two RPCs — one per disjoint window. The loser's + // retry-claim path is what makes the second RPC happen; + // without it, the loser would return `Ok(())` after + // waiting on `done` and the caller would surface a + // bogus clock-skew error. + assert_eq!( + mock.refresh_calls.load(AtomicOrdering::SeqCst), + 2, + "disjoint windows must each get their own RPC \ + (the loser retries CAS instead of returning Ok)", + ); + } + // ─── Coverage for the batched link-refresh edge cases ────────── /// Mock fetcher with configurable failure modes for the