Skip to content

feat(cloudfetch): batched link refresh on presigned-URL expiry - #69

Merged
gopalldb merged 5 commits into
mainfrom
feat/batch-link-refresh
May 27, 2026
Merged

gopalldb merged 5 commits into
mainfrom
feat/batch-link-refresh

Conversation

@gopalldb

Copy link
Copy Markdown
Collaborator

Stacked on top of PR #68 (`feat/bounded-sea-api-cleanup`). Merge that first; this rebases automatically.

Summary

When a CloudFetch presigned URL has expired (or is about to), refresh the whole forward window in one SEA `get_result_chunks` RPC instead of one-per-chunk. Presigned URLs in a batch share an expiry window; refreshing one chunk almost always means the adjacent chunks need refreshing too.

Behaviour for parallel downloads (the non-obvious bit)

Per the design constraint: chunks that are already downloaded must not be re-downloaded. The refresh path walks every returned link and reconciles per-chunk state:

Current state What happens on refresh
`UrlFetched` / `DownloadFailed` / `DownloadRetry` / `Pending` Link replaced, state set to `UrlFetched`. `schedule_downloads` picks it up next loop.
`Downloading` Link replaced only. The in-flight download task owns the state machine and re-reads `entry.link` on its next retry iteration.
`Downloaded` / `ProcessingFailed` / `Cancelled` / `Released` Link replaced for bookkeeping; no re-download triggered. Bytes / terminal state preserved.

Concurrency: dedupe by mutex

`refresh_lock: Arc<TokioMutex<()>>` gates the path. If N download tasks all detect expired URLs at the same instant, only the first holder issues the RPC. The rest queue, then on entry re-check whether their chunk's link is already fresh — if so, skip the RPC entirely.

Proactive check in `schedule_downloads`

Before claiming a chunk for download, check `link.is_expired()`. If yes, trigger the batched refresh now. Avoids the wasted-RTT failure-then-refresh round-trip when the consumer pauses long enough for the queue to go stale.

Tests

5 new unit tests on the static `refresh_links_batch` helper:

  • `refresh_batch_updates_link_for_urlfetched_chunks` — one RPC covers all in-window chunks.
  • `refresh_batch_preserves_downloaded_state` — Downloaded chunk keeps its bytes; only link updated.
  • `refresh_batch_leaves_downloading_state_intact` — in-flight task's state not clobbered.
  • `refresh_batch_resets_download_failed_to_urlfetched` — failed chunks become re-schedulable.
  • `refresh_batch_dedups_concurrent_calls` — two concurrent callers → exactly one RPC.

All 12 streaming_provider tests pass; clippy clean.

This pull request and its description were written by Isaac.

@gopalldb
gopalldb force-pushed the feat/batch-link-refresh branch from 78df9b8 to ba2f572 Compare May 25, 2026 09:46
gopalldb added a commit that referenced this pull request May 25, 2026
…h cursors, coverage

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 <gopal.lal@databricks.com>
@gopalldb
gopalldb force-pushed the feat/batch-link-refresh branch from ba2f572 to 1282d43 Compare May 25, 2026 14:46
chunks: &Arc<DashMap<i64, ChunkEntry>>,
refresh_lock: &Arc<TokioMutex<()>>,
) -> Result<()> {
let _guard = refresh_lock.lock().await;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[HIGH] [HIGH CONFIDENCE] — flagged by devils-advocate.

refresh_links_batch takes refresh_lock.lock().await at line 708 and holds the guard across refetch_links_from at line 738. That RPC routes through DatabricksHttpClient::execute with the SEA RetryStrategy whose overall_timeout = 900s (src/client/retry.rs:127) and per-attempt read_timeout = 60s.

Realistic worst case (server returns 503, network blip): one refresh holds the lock for up to 15 minutes while every other download task that hits an expired URL is parked. Since max_chunks_in_memory = 16 (default), this can deadlock the entire stream for that duration.

The PR's docstring at lines 666-676 acknowledges the function isn't cancellation-aware but justifies it with "SEA RPCs are short" — the SEA retry config (900s overall budget) contradicts that claim.

Fix (one or both):

  1. Wrap the RPC in tokio::select! against cancel_token.cancelled() so user-initiated cancel and Drop-driven cancel both unwind promptly.
  2. Either bound the refresh RPC with a tighter dedicated RetryStrategy (e.g. 30s overall), OR shrink the lock to "dedupe-only" via try_lock-then-Notify so a slow refresh doesn't park other in-flight tasks.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F1 — addressed in f009db0.

Replaced TokioMutex held across the RPC with a CAS-claim coordinator (AtomicBool + Notify). The RPC itself is now wrapped in tokio::select! against the cancel token, and a small RAII drop-guard releases the claim on every exit path (success, RPC error, RPC cancel). The 900-second worst case no longer parks other download tasks — a provider drop or statement cancel unblocks all waiters promptly.

New test refresh_batch_cancellation_unblocks_immediately proves the cancel-aware path: a hanging mock RPC + a delayed cancel surfaces a clean error without waiting on the RPC, and asserts the in_progress flag is cleared via the RAII guard.

}

#[tokio::test]
async fn refresh_batch_leaves_downloading_state_intact() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[HIGH] [HIGH CONFIDENCE] — flagged by test + devils-advocate + security (3/3).

The PR's headline claim is "Downloading chunks get only their link replaced — the in-flight task re-reads entry.link on its next retry iteration." But:

  • refresh_batch_leaves_downloading_state_intact (line 1307) only sets up a static Downloading entry in the DashMap and calls refresh_links_batch directly. No tokio::spawn, no concurrent download_chunk_with_retry. The test asserts the match arm doesn't reset state; it does NOT prove the in-flight task observes the new URL or that the stale-snapshot detection actually fires.
  • download_chunk_with_retry's integration with refresh_links_batch (lines 553-606) — including the "invariant: link must exist" check and the belt-and-braces "still-expired-after-refresh" guard — has zero unit-test coverage.
  • The stale-snapshot detection (lines 612-641) — the was_refreshed_concurrently branch that "doesn't count against retry budget" — has zero unit-test coverage despite being a subtle correctness fix the PR explicitly motivates ("a task at max_retries-1 can burn its final attempt on a URL it didn't know was stale").
  • The proactive expiry check in schedule_downloads (lines 417-433) is also entirely untested — neither the trigger condition nor the swallowed-error fallthrough.

Fix: Add at minimum:

  1. A direct test_sea_link_fetcher_refetch_links_from* test against MockDatabricksClient, matching the existing test pattern (see F9).
  2. An integration test that spawns a download_chunk_with_retry, runs a concurrent refresh, and asserts the failing stale-URL attempt doesn't count against max_retries.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F2 — addressed in f009db0 (plus F9 below).

New test refresh_does_not_disturb_concurrent_downloading_task spawns a real tokio::spawn task holding Downloading state via a Notify gate, runs a concurrent refresh_links_batch, then releases the gate. It verifies the three invariants of the contract:

  1. Post-refresh state is still Downloading (no double-spawn opportunity).
  2. The cached URL was actually swapped (not a no-op).
  3. The in-flight task, on its next read of entry.link, picks up the fresh URL transparently.

This exercises the dynamic interleaving the static-state test couldn't reach. The integration of download_chunk_with_retry with refresh_links_batch end-to-end still relies on the streaming-provider-level tests for the trait wiring; testing it via the real ChunkDownloader would require a trait-level refactor that's out of scope here.

match entry.state {
// Pending links to download — replace and let
// schedule_downloads pick up on next loop.
ChunkState::UrlFetched

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[HIGH] [MODERATE CONFIDENCE] — flagged by security (concurrency observation) + devils-advocate.

ChunkState::UrlFetched
| ChunkState::DownloadFailed(_)
| ChunkState::DownloadRetry => {
    entry.link = Some(fresh);
    entry.state = ChunkState::UrlFetched;
}

Scenario:

  1. Task A finishes a failed download attempt for chunk 5 → enters retry-sleep → state is DownloadRetry.
  2. Concurrent refresh fires (perhaps triggered by chunk 7) and returns a window that includes 5 — the match arm resets chunk 5 to UrlFetched.
  3. schedule_downloads's claim loop (line 437-490) sees UrlFetched for chunk 5 and spawns a second download task. chunks_in_memory is incremented twice.
  4. Task A wakes from retry_delay, re-reads the (refreshed) link, also starts downloading. Two tasks now downloading the same chunk concurrently; both will write entry.batches = Some(...). Last writer wins; memory accounting drifts.

Final state is consistent (the chunk gets downloaded) but the kernel briefly double-spawns, distorting chunks_in_memory (the runaway-memory guard from PR #68).

Fix: Either

  • (a) Keep DownloadRetry distinct from UrlFetched in the match — refresh updates the link but leaves the state alone (Task A retains ownership of the retry budget), OR
  • (b) Have the proactive expiry path skip chunks whose state is DownloadRetry so schedule_downloads doesn't double-claim.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F3 — addressed in f009db0.

The match now distinguishes the in-flight states from the idle ones:

ChunkState::UrlFetched | ChunkState::Pending => {
    entry.link = Some(fresh);
    entry.state = ChunkState::UrlFetched;
}
ChunkState::Downloading
| ChunkState::DownloadFailed(_)
| ChunkState::DownloadRetry => {
    entry.link = Some(fresh);  // link-only; state preserved
}

DownloadRetry (and DownloadFailed, and Downloading) keep their state on refresh — the in-flight task continues to own the state machine. schedule_downloads only spawns for UrlFetched, so the double-spawn path is gone.

New test refresh_batch_does_not_reset_in_flight_states covers this, and F2's dynamic-race test extends it to a real tokio::spawn scenario.

// 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()));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[MEDIUM] — flagged by devils-advocate.

The post-failure check compares only cached_url != link.url. Two gaps:

  1. Passive expiry: if no concurrent refresh ran but the URL itself became invalid in-flight (S3 expired the signature slightly earlier than is_expired() predicted; clock skew the other direction; the 30s LINK_EXPIRY_BUFFER_SECS was insufficient), cached_url == link.url → stale-snapshot logic does NOT fire → attempts++ even though the failure is link-expiry, not transient. This is rare in practice (30s buffer absorbs most skew) but worth defending against.

  2. Headers: CloudFetchLink carries http_headers (used in chunk_downloader.rs:84-86). If a refresh ever updates only headers (e.g. Azure SAS rotation with stable URL), the URL compare misses the staleness.

Fix: Add link.is_expired() to the post-failure check (treat as "don't count this attempt"); consider comparing on the full (url, http_headers) tuple.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F4 — addressed in f009db0.

The post-failure check now treats link.is_expired() as "don't count this attempt" alongside the URL-change detection:

let was_refreshed_concurrently = cached_url
    .as_ref()
    .is_some_and(|cached| *cached != link.url);
let attempted_link_now_expired = link.is_expired();
if was_refreshed_concurrently || attempted_link_now_expired {
    // not counting against retry budget
    continue;
}

Covers the passive-expiry case (S3 expires early, clock skew, insufficient LINK_EXPIRY_BUFFER_SECS). Headers-only refresh (Azure SAS rotation with stable URL) isn't addressed in this PR — would need plumbing http_headers into the compare and isn't observably broken today. Filing as follow-up if/when SEA's SAS handling lands.

/// 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.
///

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[MEDIUM] [HIGH CONFIDENCE] — flagged by devils-advocate.

The leading docstring at line 691 says:

Pending (no link cached): not in our refresh window, skip.

But the actual match arm at lines 814-817 does the opposite:

ChunkState::Pending => {
    entry.link = Some(fresh);
    entry.state = ChunkState::UrlFetched;
}

The inline comment at lines 811-813 agrees with the code ("refresh response covered a chunk we hadn't asked about yet — drop a link in and mark as ready"). The leading docstring is stale and will mislead future maintainers reasoning about the contract.

Fix: Update the leading docstring to match the code, or document that Pending entries with cached links can exist (which ChunkEntry::pending() at types/cloudfetch.rs:180 makes impossible today — Pending always implies link: None, so the Pending match arm is unreachable today; either delete it with unreachable!() or document the future flow that produces it).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F5 — addressed in f009db0.

You're right that ChunkEntry::pending() is the only way to land a Pending entry today, and no code path in this provider calls it. I chose against unreachable!() because a future caller adding a link-less Pending entry within the refresh window would crash production. Instead, I rewrote both the leading docstring and the inline comment to describe the arm as forward-compatibility:

// `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.

Doc and code now agree.

if let Some(entry) = chunks.get(&start_chunk_index) {
if let Some(ref link) = entry.link {
if !link.is_expired() {
debug!(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[MEDIUM] [LOW CONFIDENCE] — flagged by devils-advocate.

After taking the lock, the second caller checks if !link.is_expired() { return Ok(()) }. is_expired() returns true when Utc::now() + LINK_EXPIRY_BUFFER_SECS (30s) >= self.expiration.

If a server ever emits a presigned URL with TTL ≤ 30s (or if LINK_EXPIRY_BUFFER_SECS is bumped), all N queued callers will conclude "still expired" and fire N RPCs — defeating the dedupe contract.

Today's SEA TTLs are hours, so this is theoretical. But the dedupe-skip should logically be "URL changed from what I observed before the lock", not "URL is fresh per absolute time."

Fix: Capture the URL string before lock().await (e.g. let pre_lock_url = chunks.get(&start).and_then(|e| e.link.as_ref().map(|l| l.url.clone()))) and compare it to the cached URL after acquiring the lock; skip if they differ.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F6 — addressed in f009db0.

Good call — even though SEA's TTLs are hours today, the dedupe contract should rest on "URL changed from what I observed before the claim," not absolute time. Both re-check sites (the waiter wake-up path and the post-claim recheck) now snapshot the URL before the CAS attempt and skip on URL change OR is_expired()=false:

let pre_attempt_url = chunks
    .get(&start_chunk_index)
    .and_then(|e| e.link.as_ref().map(|l| l.url.clone()));
// ...later:
let url_changed = pre_attempt_url
    .as_ref()
    .is_some_and(|prev| *prev != link.url);
if url_changed || !link.is_expired() {
    // skip our own RPC
    return Ok(());
}

A fresh batch from the server emits new presigned URLs (your point), so URL-change alone proves a refresh landed even if the new TTL would flag as expired.

chunk_index
))
})?;
if cached.is_expired() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[MEDIUM] [HIGH CONFIDENCE] — flagged by maintainability + language.

The "belt-and-braces" check at lines 592-602 (if cached.is_expired() { return Err(...) }) duplicates the upstream check inside refresh_links_batch at lines 759-776. Two defenses for the same invariant add maintenance burden — when the invariant evolves, both sites must change together.

Fix: Keep the upstream check inside refresh_links_batch — it fails earlier (before the cached link is even consulted), has the better error message including expiration timestamps, and is the single source of truth. Remove the duplicate at lines 592-602.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F7 — addressed in f009db0.

Removed the duplicate stale-after-refresh check from refresh_links_batch. The clock-skew defence now lives in a single site inside download_chunk_with_retry (the caller fetches the cached link post-refresh and surfaces the same error message). One source of truth.

The direct-call test for refresh_links_batch that asserted the old check is fixed by refresh_batch_stale_after_refresh_leaves_caller_to_detect, which verifies the new contract: refresh_links_batch accepts the stale server response and writes the (still-stale) link to the cache; the caller is expected to detect it.

// 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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[MEDIUM] — flagged by devils-advocate.

The check refreshed.iter().find(|l| l.chunk_index == start_chunk_index) (line 753-755) only catches "start chunk completely missing." A response like [5, 7, 8, 9] where the caller asked about chunk 5 passes the check, but chunk 6 is silently absent. If chunk 6 is in Downloading state, it keeps its stale URL and will fail its in-flight download.

Fix: Validate contiguity of refreshed[].chunk_index from start_chunk_index upward, or explicitly require the response to cover the full requested window.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F8 — addressed in f009db0.

New contiguity check spanning [start_chunk_index, max_chunk_index] in the response — collects up to 10 missing indices for the error message:

if let Some(max_idx) = refreshed.iter().map(|l| l.chunk_index).max() {
    let present: HashSet<i64> = refreshed.iter().map(|l| l.chunk_index).collect();
    let mut missing = Vec::new();
    for ci in start_chunk_index..=max_idx {
        if !present.contains(&ci) {
            missing.push(ci);
            if missing.len() >= 10 { break; }
        }
    }
    if !missing.is_empty() {
        return Err(/* lists missing chunks */);
    }
}

New test refresh_batch_errors_on_interior_holes covers the case where a refresh response is [0, 1, 3] with chunk 2 missing.

Ok(link)
}

async fn refetch_links_from(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[MEDIUM] [HIGH CONFIDENCE] — flagged by test.

The new impl at link_fetcher.rs:810-859 (~50 LoC) writes the link cache, advances next_row_offset via fetch_max, calls decode_continuation, updates next_server_fetch_index via fetch_max, sets all_links_fetched, and emits warn_total_chunk_count_fallback. The continuation-cursor / EOS reconciliation is exactly the kind of logic that bit the team in PR #66 / PR #68 (per inline comments).

All testing of refetch_links_from in this PR is via mocks at the ChunkLinkFetcher trait level (in streaming_provider.rs tests). The SEA impl itself — including the cursor advancement, EOS reconciliation, and total_chunk_count_hint fallback — goes to production untested.

Fix: Add a test_sea_link_fetcher_refetch_links_from* test using MockDatabricksClient, matching the existing test pattern for refetch_link and fetch_links. Cover at minimum: single-batch refresh, EOS reconciliation (terminal link), and continuation-cursor advancement.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F9 — addressed in f009db0.

Added 4 direct tests for SeaChunkLinkFetcherHandle::refetch_links_from against MockDatabricksClient, matching the existing test_sea_link_fetcher_refetch_link pattern:

  • test_sea_link_fetcher_refetch_links_from_writes_cache — every link in the response lands in the internal cache.
  • test_sea_link_fetcher_refetch_links_from_advances_eos — terminal link flips all_links_fetched.
  • test_sea_link_fetcher_refetch_links_from_advances_cursor — next_server_fetch_index + next_row_offset advance via fetch_max.
  • test_sea_link_fetcher_refetch_links_from_empty_response — past-EOS request handles end_of_stream() gracefully (no panic on empty .last()).

chunk_index: i64,
row_offset: i64,
) -> Result<Vec<CloudFetchLink>> {
let result = self

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW] — flagged by performance.

refetch_links_from calls client.get_result_chunks(...) with no limit param — server decides the batch size. If the server returns the entire remainder (10k+ chunks), the reconciliation loop iterates 10k DashMap get_mut calls under the held refresh_lock (compounding F1).

Today bounded by SEA's empirical batch cap, but there's no client-side defense. The PR's "server-decided forward window" framing relies on SEA's contract — if that contract ever changes, the kernel silently OOMs.

Fix: Document the assumed SEA cap inline at this line; consider debug_assert!(result.links.len() <= REASONABLE_CAP) so an oversized response is loud, not silent.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F11 — addressed in f009db0.

Added debug_assert! at the link-fetcher site documenting the SEA contract assumption (≤ 10k links per page); a MAX_REFRESH_RESPONSE_LINKS = 10_000 hard cap also lives at the provider's refresh_links_batch to surface as an Err in release builds if SEA ever changes contract. Loud-fail rather than silent OOM.

.and_then(|e| e.link.as_ref().map(|l| l.row_offset))
.unwrap_or(0);

debug!(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW] — flagged by ops.

Every refresh emits debug!("Issuing batched link refresh from chunk N (row_offset=…)") but with no statement_id field. The existing pattern in link_fetcher.rs:399-408 (warn_total_chunk_count_fallback) does it right: tracing::warn!(statement_id = %self.statement_id, ...).

Operators filtering production logs by statement_id (the normal SEA correlation key) won't find these refresh lines. Counting refreshes per query becomes impossible.

Fix: Plumb statement_id into StreamingCloudFetchProvider (one-time, on construction) and add it as a tracing field on the three refresh-path log lines (:733, :715, :413). Also consider promoting :733 from debug! to info! — refreshes are rare and operationally interesting.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F12 — addressed in f009db0.

Added statement_id() -> Option<&str> to the ChunkLinkFetcher trait (default None so mocks and non-SEA transports don't need to opt in). SeaChunkLinkFetcherHandle returns Some(&self.inner.statement_id). The provider reads it once at construction time and threads it through DownloadCtx and refresh_links_batch.

All three refresh-path log lines now carry it as a tracing field:

info!(
    statement_id = %sid,
    "Issuing batched link refresh from chunk {} (row_offset={})",
    start_chunk_index, row_offset,
);

Also promoted the "Issuing batched link refresh" line from debug! to info! per your suggestion — refreshes are rare and operationally interesting.

triggering batched refresh",
chunk_index
);
Self::refresh_links_batch(chunk_index, link_fetcher, chunks, refresh_lock)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW] — flagged by ops.

When the on-demand refresh_links_batch call at line 572 fails, the error propagates via ? straight into the download retry loop, which logs error!("Failed to download chunk N: <err>") at line 522.

Operators see "Failed to download chunk N: " with no breadcrumb that this was a refresh failure, not a fetch failure. The proactive path at :417-433 handles this correctly with a warn! wrap that names "Proactive batched refresh failed for chunk N: …; will fall through to per-download retry path".

Fix: Wrap with Error::*().with_source(e).message(format!("Link refresh RPC failed for chunk {}", chunk_index)) before ? propagates.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F13 — addressed in f009db0.

Refresh ? now wrapped with a chunk-index breadcrumb so the downstream error!("Failed to download chunk N: …") log line clearly distinguishes refresh failures from download failures:

Self::refresh_links_batch(...)
    .await
    .map_err(|e| {
        Error::io()
            .message(format!("Link refresh RPC failed for chunk {}", chunk_index))
            .with_cause(e)
    })?;

(Note: the kernel-error API exposes with_cause(Error), not with_source, so the construction uses .message(...).with_cause(e).)


// 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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW] [HIGH CONFIDENCE] — flagged by maintainability + agent-compat.

Comments referencing PR numbers (PR #67, PR #68, PR #69, P2.6 feedback, PR #69 review fix) rot post-merge — readers landing on the file via grep have no way to recover the PR archeology. Locations:

Fix: Rewrite each to describe what the code does and why, without naming a PR. The PR number lives in git blame.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F14 — addressed in f009db0.

Swept all PR #67/68/69/P2.6 feedback/PR #69 review fix references from both streaming_provider.rs and link_fetcher.rs. Rewrote each comment to describe what and why without naming a PR. git blame keeps the archeology.

| ChunkState::DownloadFailed(_)
| ChunkState::DownloadRetry => {
entry.link = Some(fresh);
entry.state = ChunkState::UrlFetched;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW] — flagged by devils-advocate.

A chunk in DownloadFailed("403 Forbidden") gets reset to ChunkState::UrlFetched, throwing away the failure reason at line 790. If the next attempt also fails for a non-link reason, the original error is lost — debuggability regression.

Fix: Log the reason at debug! before reset, or preserve it in a last_failure_reason: Option<String> field on ChunkEntry so an operator can correlate the chunk's full failure history.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F15 — addressed in f009db0.

Added last_failure_reason: Option<String> to ChunkEntry, written on the DownloadFailed transition AND mirrored on the DownloadFailed → DownloadRetry transition:

// On download failure:
entry.state = ChunkState::DownloadFailed(msg.clone());
entry.last_failure_reason = Some(msg);

// Later, on transition to DownloadRetry:
entry.state = ChunkState::DownloadRetry;
entry.last_failure_reason = Some(e.to_string());

Last-writer-wins. An operator inspecting the chunks map during the retry-sleep window now has the correlation breadcrumb even though DownloadRetry itself doesn't carry a reason.

}

#[tokio::test]
async fn refresh_batch_errors_on_stale_after_refresh_clock_skew() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW] — flagged by test + devils-advocate.

refresh_batch_errors_on_stale_after_refresh_clock_skew uses an expiration 60s in the past. LINK_EXPIRY_BUFFER_SECS = 30 (types/cloudfetch.rs:30), so any TTL ≤ 30s in the future would also be flagged "still expired."

The test doesn't probe the boundary (TTL = 29s should fail, TTL = 31s should pass) and doesn't comment on why 60s was the chosen value.

Fix: Parameterize the test or add a comment naming the threshold (LINK_EXPIRY_BUFFER_SECS = 30s) so a future maintainer who bumps the buffer knows to update the test.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

F16 — addressed in f009db0.

The original 60s-past test was rewritten earlier as refresh_batch_stale_after_refresh_leaves_caller_to_detect. To probe the boundary explicitly, refresh_batch_accepts_boundary_link_within_expiry_buffer now uses LINK_EXPIRY_BUFFER_SECS - 1 (inside the buffer — flagged) and mirror-checks LINK_EXPIRY_BUFFER_SECS + 1 (outside the buffer — not flagged). A future maintainer who bumps the buffer doesn't need to touch the test.

@vikrantpuppala

Copy link
Copy Markdown
Collaborator

Code Review Squad — PR #69

Merge Safety Score: 45 / 100 — HIGH RISK

9/9 specialised reviewers delivered (security, devils-advocate, language, test, architecture, maintainability, ops, performance, agent-compat). The optimization is real and well-targeted — per-state reconciliation is type-driven (exhaustive match across 9 ChunkState variants), error messages are unusually well-crafted, dedupe-by-mutex is sound in principle, and the architecture / agent-compat / language angles each came back LGTM-with-nits.

The HIGH RISK label is driven by three findings:

  1. F1: refresh_lock is held across an RPC with up to 900-second retry budget (src/client/retry.rs:127) and zero cancellation-awareness. The PR's docstring acknowledges this isn't cancel-aware but justifies it with "SEA RPCs are short" — the SEA retry config directly contradicts that.
  2. F2: The PR's load-bearing dynamic behavior (in-flight Downloading task picking up a fresh URL on retry) has no test coverage. The named test (refresh_batch_leaves_downloading_state_intact) sets up a static Downloading entry without any concurrent download task — it only proves the match arm doesn't reset state, not that the dynamic race works.
  3. F3: The refresh resets DownloadFailed/DownloadRetry to UrlFetched, which lets schedule_downloads claim and spawn a second download task for a chunk that Task A is still working on. Memory accounting (chunks_in_memory, the guard from PR feat(reader): drop total_chunk_count reliance; use next_chunk_index for continuation #68) briefly drifts.

Findings summary

  • F1–F3 [HIGH] Lock-across-900s-RPC, untested dynamic race, double-spawn window.
  • F4–F9 [MEDIUM] Stale-snapshot URL-only compare, Pending arm doc/code contradiction, dedupe re-check uses absolute is_expired(), duplicated stale-after-refresh defense, truncated-window misses interior holes, SeaChunkLinkFetcherHandle::refetch_links_from has zero unit tests.
  • F10–F16 [LOW] #[allow(clippy::too_many_arguments)], no client-side cap on batched RPC, refresh logs lack statement_id, naked ? on refresh error, PR-number comments rot, DownloadFailed reason wiped, clock-skew test doesn't probe boundary.

Items dropped from synthesis (informational)

  • Pre-existing presigned-URL log leak in chunk_downloader.rs:78 (security S1) — pre-existing; widened blast radius via this PR's new refresh path through get_result_chunks. Worth a follow-up.
  • Pre-existing JSON-parse-failure log of full response body (security S2) — same.
  • #[allow(dead_code)] on refetch_link — defensible "future Thrift" plumbing; left as-is.

Architecture / agent-compat highlights

  • Per-state match is exhaustive (no _ => catch-all) — adding a new ChunkState variant will fail compile.
  • Error messages are unusually self-documenting: the stale-after-refresh error names both possible causes (client clock skew, server bug) and explains the non-retry decision ("Refusing to spin on repeated refresh").
  • pyo3/napi/ffi: zero references to any changed symbol. No wrapper breakage.

Finding without inline location

F10 [LOW] — download_chunk_with_retry has 8 parameters — bundle into a DownloadContext struct

[LOW] — flagged by maintainability.

download_chunk_with_retry at streaming_provider.rs:541 now has 8 parameters and is gated by #[allow(clippy::too_many_arguments)]. The allow is a maintainability smell — every new parameter forces the call site to be re-threaded.

Fix: Bundle chunks, refresh_lock, link_fetcher, downloader, cancel_token into a DownloadContext struct and pass it by reference. Removes the lint allow and makes future plumbing changes one-line edits.

@gopalldb

Copy link
Copy Markdown
Collaborator Author

Round-3 review — all 15 inline comments addressed in f009db0

Per-finding replies are threaded under each inline comment. High-level summary:

HIGH (3):

  • F1 lock-across-RPC → CAS-claim coordinator (AtomicBool + Notify) + tokio::select! against cancel token + RAII drop-guard. No lock held across the RPC; cancellation unblocks promptly.
  • F2 dynamic-race coverage → refresh_does_not_disturb_concurrent_downloading_task with a real tokio::spawn task gated on Notify.
  • F3 double-spawn → Downloading | DownloadFailed | DownloadRetry get link-only updates; in-flight task owns the state machine.

MEDIUM (5):

  • F4 post-failure check now treats link.is_expired() as stale-snapshot (passive expiry coverage).
  • F5 Pending arm doc rewritten as forward-compatibility (matches the code).
  • F6 dedupe-skip compares URL change pre-claim vs post-claim, not absolute time.
  • F7 stale-after-refresh defence consolidated to a single site (download_chunk_with_retry).
  • F8 interior-hole detection in refresh response.
  • F9 4 direct tests for SeaChunkLinkFetcherHandle::refetch_links_from.

LOW (5):

  • F11 MAX_REFRESH_RESPONSE_LINKS = 10_000 cap + debug_assert! at the link-fetcher.
  • F12 statement_id() plumbed through trait → provider → log lines; "Issuing batched link refresh" promoted to info!.
  • F13 refresh ? wrapped with chunk-index breadcrumb via Error::io().message(...).with_cause(e).
  • F14 all PR #67/68/69 refs removed from streaming_provider.rs + link_fetcher.rs.
  • F15 new last_failure_reason: Option<String> field on ChunkEntry, preserved across DownloadFailed → DownloadRetry.
  • F16 boundary test now references LINK_EXPIRY_BUFFER_SECS - 1 and + 1 directly, mirror-checks both sides.

Also folded the 8-arg download_chunk_with_retry signature into a DownloadCtx struct.

Tests: 436 lib + 6 doc = 442 pass, 0 fail. 11 new tests added across the two rounds (5 in round-2 already on this branch; 6 new in this commit + 4 new in link_fetcher.rs). cargo fmt, cargo clippy --all-targets -- -D warnings clean.

This commit is on top of 1282d43 (round-2). Diff: +1155 / -248 across 3 files.

// re-attempt; if the link is still expired the caller
// will surface the consistent "still expired after
// refresh" error.
return Ok(());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[MEDIUM] [HIGH CONFIDENCE] — follow-up after the round-3 review (commit f009db0).

The round-3 commit replaced the held-across-await TokioMutex with the RefreshCoordinator CAS-claim coordinator (which correctly addresses the F1 900s lock-budget concern). But the loser-of-claim path has a residual gap.

Trace:

  1. Task B calls refresh_links_batch for chunk 50.

  2. Task A is mid-refresh of chunks [0, 15]; Task B loses the compare_exchange and waits on done.notified().

  3. Task A releases the claim via the RAII guard, calling notify_waiters().

  4. Task B wakes, re-checks chunk 50 (lines 868-883): URL unchanged (Task A's window didn't include 50), is_expired() still true. Falls through to:

    // 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(());
  5. Back in download_chunk_with_retry (lines 620-672): the code does NOT loop on Ok(()). It proceeds past the refresh call, reads the cached link (which is still Task A's stale chunk-50 link, since Task A didn't refresh chunk 50), and hits the if cached.is_expired() belt-and-braces check at line 662 → returns Err("Link for chunk 50 is still expired after refresh (likely client/server clock skew or a server bug)").

The "loop via the caller's retry path" intent in the comment is not actually implemented. The caller assumes a refresh ran for this chunk and surfaces a misleading error blaming clock skew or a server bug when the real cause is "a concurrent refresh happened, but for a disjoint window."

Realistic trigger: Two download tasks for non-overlapping chunk ranges (e.g. one for chunks near the start of a long result stream, one for chunks far into the stream) hit their respective presigned-URL expiries within the same lock window. Today's SEA batching tends to colocate URLs in the same expiry cohort, so the windows usually overlap — but the architecture promises "queued callers re-check and skip the RPC if their chunk is already fresh," and the loser path violates that contract for the disjoint case.

Compounded by:

  • N2 (thundering herd): notify_waiters() wakes ALL queued tasks; each independently runs this same code path. A burst of N waiters for disjoint windows produces N spurious "still expired after refresh" errors.
  • N4 (lost diagnostic detail): The downstream error message no longer carries expires=<timestamp>, now=<timestamp> (those were in the upstream check that F7 removed), so the operator gets a clock-skew suggestion that's diagnostically wrong for this scenario.

Fix options (in order of preference):

  1. Loop inside refresh_links_batch: re-attempt the CAS claim if the waited refresh didn't cover us. Bound by a max-loop-count to avoid pathological churn (e.g. 3 iterations matches the typical worst-case for disjoint windows in the same expiry cohort).

    // Sketch:
    for attempt in 0..MAX_REFRESH_CLAIM_RETRIES {
        // existing CAS + wait-or-claim logic
        // if Lost AND wait completed AND our chunk still stale: continue
        // else: break or return
    }
  2. Distinct return variant: return RefreshOutcome::AnotherTaskRefreshed { covered: bool } so download_chunk_with_retry can loop on covered: false without re-litigating the claim.

  3. Minimum (low-effort): at least fix the downstream error message to differentiate "stale-after-refresh-of-this-chunk" (real clock skew or server bug) from "no-refresh-actually-ran-for-this-chunk" (concurrent disjoint window — expected, should retry). The check at lines 662-672 has enough context to know which case it's in: compare cached.url against the pre-call URL — if unchanged, no refresh ran for this chunk.

Option 1 is the cleanest. Option 3 is a one-line improvement that at least stops misleading operators.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Round-4 follow-up — addressed in e677ca2.

Great catch on the loser-of-claim disjoint-window gap. Went with Option 1 (loop inside refresh_links_batch) + Option 3 (differentiated error message) combined — the loop fixes the bug at the source, the error message fix protects diagnostics on the (now-rare) MAX_CLAIM_RETRIES exhaustion path.

Option 1 — bounded CAS-retry loop:

const MAX_CLAIM_RETRIES: u32 = 3;
for claim_attempt in 0..MAX_CLAIM_RETRIES {
    let won_claim = coordinator.in_progress
        .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
        .is_ok();
    if won_claim { break; }

    // Wait on done.notified() + cancel
    // Re-check: URL changed OR !is_expired() → Ok(()) and skip RPC
    // Otherwise: disjoint-window case → loop back to retry CAS
    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. ...",
            MAX_CLAIM_RETRIES, start_chunk_index,
        )));
    }
}

Three iterations matches the realistic worst case you noted (two concurrent disjoint-window refreshers + ours). Hard-bound so a pathological server can't produce unbounded churn.

Option 3 — differentiated error message in download_chunk_with_retry:

The post-refresh if cached.is_expired() guard now compares the cached URL against the pre-refresh stored_link.url:

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,
    ))
});
  • URL unchanged → Error::unavailable() (retryable). Surfaces only on MAX_CLAIM_RETRIES exhaustion (rare; pathological concurrent expiry across very different chunk ranges).
  • URL changed but still expired → Error::invalid_state() (real clock-skew diagnosis).

On N2 (thundering herd): the bounded retry loop limits each waiter to at most 3 CAS attempts, so a burst of N waiters for disjoint windows produces at most N successful refreshes (one per disjoint window — that's the correct behaviour, not amplification). Each waiter individually contends only briefly.

On N4 (lost diagnostic detail): the expires=<ts>, now=<ts> breadcrumbs from the pre-F7 upstream check could be re-added if you want them on the residual error paths. Today's error messages name the chunk and the URL-changed-vs-unchanged signal, which is the actionable info — happy to add timestamps if you'd find them useful for operator triage.

Regression test refresh_batch_disjoint_window_loser_retries_claim:

// Mock window=1 — each refresh returns ONLY the chunk_index it
// was asked about. So a refresh for chunk 0 cannot cover chunk
// 50 and vice versa. Two concurrent calls must each get their
// own RPC.
let mock = RefreshCountingMock::new(1);
// chunks 0 and 50 both expired
let h1 = tokio::spawn(refresh_links_batch(0, ...));
let h2 = tokio::spawn(refresh_links_batch(50, ...));
h1.await.unwrap().expect("chunk 0 refresh must succeed");
h2.await.unwrap().expect("chunk 50 refresh must succeed");
assert_eq!(mock.refresh_calls.load(...), 2,
    "disjoint windows must each get their own RPC");

Without the fix, this test would either fail with the misleading clock-skew error OR pass with only 1 RPC (the loser returns Ok(()) and the caller fails downstream). With the fix, both chunks get fresh URLs and exactly 2 RPCs fire.

Tests: 22/22 streaming_provider + 483 lib pass. Branch rebased onto latest main (3aa25b2); PR base also repointed feat/bounded-sea-api-cleanup → main (PR #68 has since merged).

@gopalldb
gopalldb force-pushed the feat/bounded-sea-api-cleanup branch from bee7c1f to 6003b2f Compare May 26, 2026 09:46
gopalldb added 3 commits May 27, 2026 12:39
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<CloudFetchLink>` 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<TokioMutex<()>>) 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 <gopal.lal@databricks.com>
…h cursors, coverage

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 <gopal.lal@databricks.com>
…-race tests, statement_id plumbing

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<String>` 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 <gopal.lal@databricks.com>
@gopalldb
gopalldb changed the base branch from feat/bounded-sea-api-cleanup to main May 27, 2026 07:13
…dow gap

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 <gopal.lal@databricks.com>
@gopalldb
gopalldb force-pushed the feat/batch-link-refresh branch from f009db0 to e677ca2 Compare May 27, 2026 07:15
@gopalldb

Copy link
Copy Markdown
Collaborator Author

Round-4 follow-up — disjoint-window gap addressed in e677ca2

Closes the residual gap the round-3 follow-up flagged (comment id=3302845089) in the RefreshCoordinator loser-of-claim path.

The bug. Round-3's CAS-claim coordinator correctly addresses F1's 900s lock-budget concern. But when Task A wins the claim and its refresh window covers a disjoint chunk range from Task B's request, Task B woke from done.notified(), saw its own chunk still stale, and returned Ok(()). The caller's post-refresh is_expired() guard then surfaced a misleading "still expired — clock skew" error for what was actually a benign concurrent-disjoint race.

Fix. Combined Options 1 + 3 from the review:

  1. Bounded CAS-retry loop inside refresh_links_batch — loser who wakes to find its chunk still stale loops back to re-attempt the CAS itself. MAX_CLAIM_RETRIES = 3 covers the realistic worst case; exhaustion surfaces as Error::unavailable() with a typed message so the caller doesn't conflate it with the clock-skew path.

  2. Differentiated error message in download_chunk_with_retry's post-refresh guard — compares pre-refresh stored_link.url to post-refresh cached.url:

    • URL changed but still expired → Error::invalid_state() "URL changed but is_expired() still true — likely clock skew or server bug" (the real diagnosis).
    • URL unchanged → Error::unavailable() "not refreshed by the concurrent refresh window; retry would help" (the disjoint-window race; retryable).

Regression test refresh_batch_disjoint_window_loser_retries_claim: two concurrent refreshes for chunks 0 and 50 against a mock that returns only the chunk it was asked about. Both calls succeed; both chunks get fresh URLs; exactly 2 RPCs fire.

Sync. 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. PR base also repointed feat/bounded-sea-api-cleanup → main.

Tests: 22/22 streaming_provider + 483 lib pass, 0 fail. cargo fmt + cargo clippy --all-targets -- -D warnings clean.

Branch tip: e677ca2.

@gopalldb
gopalldb merged commit fad787b into main May 27, 2026
gopalldb added a commit that referenced this pull request Jun 1, 2026
…71)

## Summary

Implements the SEA inline-Arrow streaming path that lights up when the
session was opened with \`can_cloud_download = false\`. The server
paginates results via \`GET /result/chunks/{idx}\` with Arrow IPC bytes
in \`attachment\` (no separate cloud download). The kernel maintains a
bounded rolling window of pre-decoded chunks ahead of the consumer so
per-chunk SEA round-trip latency is hidden behind RecordBatch iteration.

Modelled on JDBC's
[\`StreamingChunkProvider\`](~/repo/databricks-jdbc/src/main/java/com/databricks/jdbc/api/impl/arrow/StreamingChunkProvider.java)
pattern.

## Conflicts with stacked PRs

This PR is off \`main\` and **conflicts with PR #68 and PR #69** at
merge time. The conflicts are narrow:

- \`src/client/transport.rs\` — both add fields to \`ExecuteResultData\`
/ new trait methods on \`Transport\`.
- \`src/reader/cloudfetch/link_fetcher.rs\` — mock impl needs the new
\`get_inline_chunk\` stub.
- \`src/client/sea.rs\` — both extend the \`Transport\` impl.

Merge order:
1. PR #68 (bounded SEA API cleanup)
2. PR #69 (batched link refresh)
3. **This PR** (rebases onto the merged tip; conflicts are stub
additions)

## Changes

- New \`Transport::get_inline_chunk(statement_id, chunk_index,
row_offset) -> InlineChunkFetchResult\` method, implemented on
\`SeaRestTransport\`. Sends \`chunk_index\` (path param) +
\`row_offset\` (query param) per the bounded SEA API contract.

- New \`ResultConfig.inline_max_chunks_in_memory\` knob (default 4).
Analogue of \`cloudfetch_max_chunks_in_memory\` but for the sequential
inline-Arrow prefetch path.

- New \`InlineStreamingProvider\` in \`src/reader/inline/streaming.rs\`:
- Initial chunk (from execute response \`attachment\`) decoded
synchronously so callers get a schema.
- Background prefetch task fetches subsequent chunks sequentially,
decodes each, pushes batches into a bounded rolling window.
- When window full, prefetch pauses on a \`Notify\` until the consumer
drains a chunk.
- Sequential by design — SEA inline contract is one \`GetResultData\` at
a time.
- End-of-stream: server-emitted \`next_chunk_index = None\` on a fetched
chunk. Never synthesised.

- Narrow \`InlineChunkSource\` trait so test mocks don't have to stub
the full 20-method \`Transport\` surface. Blanket impl on \`Arc<dyn
Transport>\` connects to production.

- \`ResultReaderFactory::create_inner_reader\` branches on
\`inline_next_chunk_index\`: present → multi-chunk streaming reader;
absent → existing single-chunk \`InlineArrowProvider\`.

- \`ExecuteResultData\` extended with four optional fields
(\`inline_chunk_index\`, \`inline_row_offset\`, \`inline_row_count\`,
\`inline_next_chunk_index\`) carrying initial-chunk metadata from the
execute response.

## Parallel-download safety

N/A on the inline path — the SEA contract is sequential
one-chunk-at-a-time fetches. The rolling window bounds memory; there's
no concurrent network load on the inline path by design. (CloudFetch
keeps its parallel-download model.)

## Tests

Four new unit tests on \`InlineStreamingProvider\`:

- \`streams_all_chunks_in_order\` — three-chunk fixture, all rows arrive
in order.
- \`respects_max_chunks_in_memory_bound\` — window = 1, asserts the
prefetch task makes exactly 2 RPCs.
- \`single_chunk_no_prefetch_rpcs\` — initial \`next_chunk_index =
None\`, zero RPCs.
- \`surfaces_prefetch_errors\` — prefetch failure surfaces on the next
consumer pull.

All 418 lib tests + 16 wiremock integration tests pass; clippy clean.

This pull request and its description were written by Isaac.

---------

Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants