Repository navigation
feat(cloudfetch): batched link refresh on presigned-URL expiry - #69
Conversation
78df9b8 to
ba2f572
Compare
…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>
ba2f572 to
1282d43
Compare
| chunks: &Arc<DashMap<i64, ChunkEntry>>, | ||
| refresh_lock: &Arc<TokioMutex<()>>, | ||
| ) -> Result<()> { | ||
| let _guard = refresh_lock.lock().await; |
There was a problem hiding this comment.
[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):
- Wrap the RPC in
tokio::select!againstcancel_token.cancelled()so user-initiated cancel andDrop-driven cancel both unwind promptly. - Either bound the refresh RPC with a tighter dedicated
RetryStrategy(e.g. 30s overall), OR shrink the lock to "dedupe-only" viatry_lock-then-Notifyso a slow refresh doesn't park other in-flight tasks.
There was a problem hiding this comment.
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() { |
There was a problem hiding this comment.
[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 staticDownloadingentry in the DashMap and callsrefresh_links_batchdirectly. Notokio::spawn, no concurrentdownload_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 withrefresh_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_concurrentlybranch that "doesn't count against retry budget" — has zero unit-test coverage despite being a subtle correctness fix the PR explicitly motivates ("a task atmax_retries-1can 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:
- A direct
test_sea_link_fetcher_refetch_links_from*test againstMockDatabricksClient, matching the existing test pattern (see F9). - An integration test that spawns a
download_chunk_with_retry, runs a concurrent refresh, and asserts the failing stale-URL attempt doesn't count againstmax_retries.
There was a problem hiding this comment.
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:
- Post-refresh state is still
Downloading(no double-spawn opportunity). - The cached URL was actually swapped (not a no-op).
- 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 |
There was a problem hiding this comment.
[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:
- Task A finishes a failed download attempt for chunk 5 → enters retry-sleep → state is
DownloadRetry. - Concurrent refresh fires (perhaps triggered by chunk 7) and returns a window that includes 5 — the match arm resets chunk 5 to
UrlFetched. schedule_downloads's claim loop (line 437-490) seesUrlFetchedfor chunk 5 and spawns a second download task.chunks_in_memoryis incremented twice.- Task A wakes from
retry_delay, re-reads the (refreshed) link, also starts downloading. Two tasks now downloading the same chunk concurrently; both will writeentry.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
DownloadRetrydistinct fromUrlFetchedin 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
DownloadRetrysoschedule_downloadsdoesn't double-claim.
There was a problem hiding this comment.
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())); |
There was a problem hiding this comment.
[MEDIUM] — flagged by devils-advocate.
The post-failure check compares only cached_url != link.url. Two gaps:
-
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 30sLINK_EXPIRY_BUFFER_SECSwas 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. -
Headers:
CloudFetchLinkcarrieshttp_headers(used inchunk_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.
There was a problem hiding this comment.
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. | ||
| /// |
There was a problem hiding this comment.
[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).
There was a problem hiding this comment.
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!( |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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() { |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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 flipsall_links_fetched.test_sea_link_fetcher_refetch_links_from_advances_cursor—next_server_fetch_index+next_row_offsetadvance viafetch_max.test_sea_link_fetcher_refetch_links_from_empty_response— past-EOS request handlesend_of_stream()gracefully (no panic on empty.last()).
| chunk_index: i64, | ||
| row_offset: i64, | ||
| ) -> Result<Vec<CloudFetchLink>> { | ||
| let result = self |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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!( |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
[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:
streaming_provider.rs:726, 1407, 1561, 1611link_fetcher.rs:574, 691, 759, 1258, 1395(pre-existing from feat(reader): drop total_chunk_count reliance; use next_chunk_index for continuation #68; not strictly this PR's responsibility, but worth a sweep)
Fix: Rewrite each to describe what the code does and why, without naming a PR. The PR number lives in git blame.
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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() { |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
Code Review Squad — PR #69Merge 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 The HIGH RISK label is driven by three findings:
Findings summary
Items dropped from synthesis (informational)
Architecture / agent-compat highlights
Finding without inline locationF10 [LOW] — download_chunk_with_retry has 8 parameters — bundle into a DownloadContext struct[LOW] — flagged by maintainability.
Fix: Bundle |
Round-3 review — all 15 inline comments addressed in f009db0Per-finding replies are threaded under each inline comment. High-level summary: HIGH (3):
MEDIUM (5):
LOW (5):
Also folded the 8-arg 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 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(()); |
There was a problem hiding this comment.
[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:
-
Task B calls
refresh_links_batchfor chunk 50. -
Task A is mid-refresh of chunks
[0, 15]; Task B loses thecompare_exchangeand waits ondone.notified(). -
Task A releases the claim via the RAII guard, calling
notify_waiters(). -
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(());
-
Back in
download_chunk_with_retry(lines 620-672): the code does NOT loop onOk(()). 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 theif cached.is_expired()belt-and-braces check at line 662 → returnsErr("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):
-
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 }
-
Distinct return variant: return
RefreshOutcome::AnotherTaskRefreshed { covered: bool }sodownload_chunk_with_retrycan loop oncovered: falsewithout re-litigating the claim. -
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.urlagainst 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.
There was a problem hiding this comment.
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).
bee7c1f to
6003b2f
Compare
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>
…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>
f009db0 to
e677ca2
Compare
Round-4 follow-up — disjoint-window gap addressed in e677ca2Closes the residual gap the round-3 follow-up flagged (comment id=3302845089) in the 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 Fix. Combined Options 1 + 3 from the review:
Regression test Sync. Branch rebased onto latest main ( Tests: 22/22 streaming_provider + 483 lib pass, 0 fail. cargo fmt + cargo clippy --all-targets -- -D warnings clean. Branch tip: |
…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>
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:
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:
All 12 streaming_provider tests pass; clippy clean.
This pull request and its description were written by Isaac.