Skip to content

Commit f009db0

Browse files
committed
review(pr69): address round-3 feedback — coordinator pattern, dynamic-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>
1 parent 1282d43 commit f009db0

3 files changed

Lines changed: 1155 additions & 248 deletions

File tree

‎src/reader/cloudfetch/link_fetcher.rs‎

Lines changed: 192 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,17 @@ pub(crate) trait ChunkLinkFetcher: Send + Sync + std::fmt::Debug {
114114
chunk_index: i64,
115115
row_offset: i64,
116116
) -> Result<Vec<CloudFetchLink>>;
117+
118+
/// Identifier of the statement this fetcher is bound to, if
119+
/// known. Used by downstream consumers (e.g. the streaming
120+
/// provider) to attach a `statement_id` field to log lines so
121+
/// operators can filter by query.
122+
///
123+
/// Default implementation returns `None` — mock fetchers and
124+
/// non-SEA transports don't need to surface anything.
125+
fn statement_id(&self) -> Option<&str> {
126+
None
127+
}
117128
}
118129

119130
/// SEA implementation of ChunkLinkFetcher with caching and proactive prefetching.
@@ -571,8 +582,7 @@ impl SeaChunkLinkFetcher {
571582
} else {
572583
// Empty batch but `has_more` is true. Force
573584
// forward progress so the loop can't spin
574-
// re-issuing the same RPC (P1 #2 in PR #68
575-
// review). Two strategies:
585+
// re-issuing the same RPC. Two strategies:
576586
// 1. If the server gave us a
577587
// `next_chunk_index` hint, use it.
578588
// 2. Otherwise bump past
@@ -688,7 +698,7 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle {
688698
// — a `for i in start..server_fetch_index` with silent
689699
// `is_none()` skip would return a non-contiguous slice and
690700
// hang the streaming provider's wait_for_chunk on the
691-
// first missing index (P1 #1 in PR #68 review).
701+
// first missing index.
692702
if start_chunk_index < server_fetch_index {
693703
let mut links = Vec::new();
694704
let mut i = start_chunk_index;
@@ -756,8 +766,8 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle {
756766
None => {
757767
// Empty response. Honour the server's has_more
758768
// signal AND defend against an empty-with-has_more
759-
// spin (P1 #2 in PR #68 review): force forward
760-
// progress on next_server_fetch_index so the next
769+
// spin: force forward progress on
770+
// next_server_fetch_index so the next
761771
// call asks for a different chunk index. The
762772
// server is expected to either yield links or
763773
// signal end-of-stream — a perpetual "I have more
@@ -818,6 +828,21 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle {
818828
.get_result_chunks(&self.inner.statement_id, chunk_index, row_offset)
819829
.await?;
820830

831+
// The SEA contract today caps the number of links in a
832+
// single `get_result_chunks` response to ~empirical bounds
833+
// (≤ a few hundred chunks per page). If SEA ever changes
834+
// and a page returns thousands of links, the downstream
835+
// reconciliation loop (which mutates a DashMap entry per
836+
// link) is a quiet O(N) hotspot. `debug_assert!` makes the
837+
// assumption loud in debug builds without paying for it in
838+
// release.
839+
debug_assert!(
840+
result.links.len() <= 10_000,
841+
"implausibly large refresh response ({} links) — \
842+
SEA contract may have changed; review the cap",
843+
result.links.len(),
844+
);
845+
821846
// Refresh the internal link cache with every link the server
822847
// returned. The caller will reconcile per-chunk state in the
823848
// streaming provider (which knows which chunks are already
@@ -858,6 +883,10 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle {
858883

859884
Ok(result.links)
860885
}
886+
887+
fn statement_id(&self) -> Option<&str> {
888+
Some(&self.inner.statement_id)
889+
}
861890
}
862891

863892
#[cfg(test)]
@@ -1232,6 +1261,162 @@ mod tests {
12321261
assert!(result.is_err());
12331262
}
12341263

1264+
// ──────────────────────────────────────────────────────────────
1265+
// refetch_links_from coverage — exercises the batched-refresh
1266+
// entry point used by the streaming provider's expiry path.
1267+
// The SEA impl writes the cache, advances the row-offset and
1268+
// server-fetch cursors, and reconciles EOS — none of which
1269+
// was tested directly before (only via mocks at the trait
1270+
// level inside the streaming provider).
1271+
// ──────────────────────────────────────────────────────────────
1272+
1273+
#[tokio::test]
1274+
async fn test_sea_link_fetcher_refetch_links_from_writes_cache() {
1275+
// After `refetch_links_from`, every link in the response
1276+
// must be in the internal cache so subsequent
1277+
// `fetch_links` / `refetch_link` calls see the new URLs
1278+
// without an extra round trip.
1279+
let links = vec![
1280+
vec![create_test_link(0)],
1281+
vec![create_test_link(1)],
1282+
vec![create_test_link_terminal(2)],
1283+
];
1284+
let client = Arc::new(MockDatabricksClient::new(links));
1285+
let fetcher = SeaChunkLinkFetcher::new(
1286+
client,
1287+
"test-statement",
1288+
&[],
1289+
None,
1290+
128,
1291+
tokio::runtime::Handle::current(),
1292+
);
1293+
let handle = SeaChunkLinkFetcherHandle::new(fetcher);
1294+
1295+
// Request a refresh batch from chunk 1 onward.
1296+
let refreshed = handle.refetch_links_from(1, 1000).await.unwrap();
1297+
1298+
// Mock returns one link per `get_result_chunks` call —
1299+
// the chunk at the requested index. Refresh response is
1300+
// a single link for chunk 1.
1301+
assert_eq!(refreshed.len(), 1);
1302+
assert_eq!(refreshed[0].chunk_index, 1);
1303+
1304+
// Cache was updated.
1305+
assert!(handle.inner.has_link(1));
1306+
}
1307+
1308+
#[tokio::test]
1309+
async fn test_sea_link_fetcher_refetch_links_from_advances_eos() {
1310+
// When `refetch_links_from` returns a terminal link
1311+
// (`next_chunk_index = None`), the `all_links_fetched`
1312+
// flag must flip so subsequent `fetch_links` calls
1313+
// short-circuit instead of hitting the server again.
1314+
let links = vec![vec![create_test_link_terminal(0)]];
1315+
let client = Arc::new(MockDatabricksClient::new(links));
1316+
let fetcher = SeaChunkLinkFetcher::new(
1317+
client,
1318+
"test-statement",
1319+
&[],
1320+
None,
1321+
128,
1322+
tokio::runtime::Handle::current(),
1323+
);
1324+
let handle = SeaChunkLinkFetcherHandle::new(fetcher);
1325+
1326+
// Pre-condition: not yet at EOS.
1327+
assert!(!handle.inner.all_links_fetched.load(Ordering::Acquire));
1328+
1329+
let _ = handle.refetch_links_from(0, 0).await.unwrap();
1330+
1331+
// Post-condition: EOS flipped on after the terminal link
1332+
// landed in the refresh response.
1333+
assert!(
1334+
handle.inner.all_links_fetched.load(Ordering::Acquire),
1335+
"terminal link in refresh response must flip all_links_fetched",
1336+
);
1337+
}
1338+
1339+
#[tokio::test]
1340+
async fn test_sea_link_fetcher_refetch_links_from_advances_cursor() {
1341+
// `refetch_links_from` mirrors `fetch_links`'s cursor
1342+
// advancement (`next_server_fetch_index` via `fetch_max`,
1343+
// `next_row_offset` via `fetch_max`). A subsequent
1344+
// prefetch must NOT re-issue the chunk we just refreshed.
1345+
let links = vec![
1346+
vec![create_test_link(0)],
1347+
vec![create_test_link(1)],
1348+
vec![create_test_link_terminal(2)],
1349+
];
1350+
let client = Arc::new(MockDatabricksClient::new(links));
1351+
let fetcher = SeaChunkLinkFetcher::new(
1352+
client,
1353+
"test-statement",
1354+
&[],
1355+
None,
1356+
128,
1357+
tokio::runtime::Handle::current(),
1358+
);
1359+
let handle = SeaChunkLinkFetcherHandle::new(fetcher);
1360+
1361+
// Pre-condition: cursor at 0.
1362+
assert_eq!(
1363+
handle.inner.next_server_fetch_index.load(Ordering::Acquire),
1364+
0
1365+
);
1366+
assert_eq!(handle.inner.next_row_offset.load(Ordering::Acquire), 0);
1367+
1368+
// Refresh from chunk 0. The non-terminal link's
1369+
// continuation should advance the cursor past 0.
1370+
let _ = handle.refetch_links_from(0, 0).await.unwrap();
1371+
1372+
// `next_server_fetch_index` advances past the refreshed
1373+
// index — refresh of chunk 0 should leave it at 1 (or
1374+
// higher, depending on the test link's `next_chunk_index`
1375+
// hint).
1376+
let new_idx = handle.inner.next_server_fetch_index.load(Ordering::Acquire);
1377+
assert!(
1378+
new_idx >= 1,
1379+
"next_server_fetch_index must advance past refreshed chunk; got {}",
1380+
new_idx,
1381+
);
1382+
1383+
// `next_row_offset` advances past chunk 0's rows
1384+
// (row_offset=0 + row_count=1000 = 1000).
1385+
let new_offset = handle.inner.next_row_offset.load(Ordering::Acquire);
1386+
assert_eq!(
1387+
new_offset, 1000,
1388+
"next_row_offset must advance to row_offset + row_count",
1389+
);
1390+
}
1391+
1392+
#[tokio::test]
1393+
async fn test_sea_link_fetcher_refetch_links_from_empty_response() {
1394+
// A `get_result_chunks` call past end-of-stream returns
1395+
// `ChunkLinkFetchResult::end_of_stream()` (empty links,
1396+
// `has_more = false`). `refetch_links_from` must handle
1397+
// this gracefully — no panic on empty `.last()`, no
1398+
// bogus cursor update.
1399+
let links = vec![vec![create_test_link_terminal(0)]];
1400+
let client = Arc::new(MockDatabricksClient::new(links));
1401+
let fetcher = SeaChunkLinkFetcher::new(
1402+
client,
1403+
"test-statement",
1404+
&[],
1405+
None,
1406+
128,
1407+
tokio::runtime::Handle::current(),
1408+
);
1409+
let handle = SeaChunkLinkFetcherHandle::new(fetcher);
1410+
1411+
// Ask for a chunk past the end — mock returns
1412+
// end_of_stream (empty links).
1413+
let refreshed = handle.refetch_links_from(99, 0).await.unwrap();
1414+
assert!(
1415+
refreshed.is_empty(),
1416+
"past-EOS request should return empty vec, not error",
1417+
);
1418+
}
1419+
12351420
#[tokio::test]
12361421
async fn test_sea_link_fetcher_all_links_fetched_flag() {
12371422
let links = vec![vec![create_test_link_terminal(0)]];
@@ -1255,7 +1440,7 @@ mod tests {
12551440
}
12561441

12571442
// ──────────────────────────────────────────────────────────────
1258-
// Continuation tests (PR #68 P1.3 feedback).
1443+
// Continuation tests.
12591444
//
12601445
// These exercise the bounded-SEA-API control flow directly,
12611446
// bypassing the async prefetch race so a regression in
@@ -1392,7 +1577,7 @@ mod tests {
13921577
}
13931578

13941579
// ──────────────────────────────────────────────────────────────
1395-
// total_chunk_count transition-period fallback (PR #68 P0).
1580+
// total_chunk_count transition-period fallback.
13961581
// ──────────────────────────────────────────────────────────────
13971582

13981583
#[tokio::test]

0 commit comments

Comments
 (0)