Skip to content

feat(inline): multi-chunk inline-Arrow streaming with rolling window - #71

Merged
gopalldb merged 4 commits into
mainfrom
feat/inline-arrow-streaming
Jun 1, 2026
Merged

gopalldb merged 4 commits into
mainfrom
feat/inline-arrow-streaming

Conversation

@gopalldb

Copy link
Copy Markdown
Collaborator

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` 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 feat(reader): drop total_chunk_count reliance; use next_chunk_index for continuation #68 (bounded SEA API cleanup)
  2. PR feat(cloudfetch): batched link refresh on presigned-URL expiry #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` 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.

gopalldb added a commit that referenced this pull request May 25, 2026
…ck, rollout guard

Addresses 11 review items on PR #71 (multi-chunk inline-Arrow
streaming with rolling window).

### P0 — Critical

1. **Lost-wake deadlock on `Notify`.** The original
   consumer↔prefetch handshake used
   `Notify::notify_waiters()`, which does NOT buffer permits.
   The consumer would drop its mutex guard, then call
   `.notified().await`. If the prefetch pushed a chunk and
   notified between drop-of-lock and the consumer's `.notified()`,
   the wake was lost and the consumer hung forever.

   Fix: replace the Notify-based coordination with
   `tokio::sync::mpsc`. Channel send/recv handles wakes correctly
   AND gives natural backpressure (channel capacity =
   `max_chunks_in_memory - 1`). New regression test
   `lost_wake_race_does_not_hang` runs the tight push/pop loop
   under a 5s timeout.

2. **Prefetch task leaks Arc<Inner>, keeps RPC-ing after consumer
   drop.** The spawned task held its own `Arc::clone(&inner)`
   independent of the provider; the doc claimed "exits when
   Arc<Inner> drops" but the task itself held an Arc, so the
   count never reached 0 from consumer drop.

   Fix: provider stores the `JoinHandle` and aborts it on Drop.
   mpsc design also kills the task naturally — when the receiver
   drops, the next `tx.send().await` returns Err. New regression
   test `prefetch_task_exits_when_consumer_drops`.

### P1 — Important

3. **Sticky-error overwrite.** `err_slot.take()` consumed the
   error; the next call saw `None`, hit EOS, returned `Ok(None)`
   — silent EOS after an error.

   Fix: cloned sticky-error slot in `ConsumerState`. Once set,
   every subsequent `next_batch` returns the same error rather
   than silently transitioning to `Ok(None)`. New regression test
   `sticky_error_persists_across_calls`.

4. **`row_count == 0` + missing `next_chunk_index` infinite
   tight-loop.** If a server emitted a self-loop
   (`next_chunk_index <= chunk_index`) the prefetch would hammer
   the same chunk forever.

   Fix: prefetch task validates strict monotonicity
   (`next_chunk_index > chunk_index`) before sending the chunk
   onto the channel. Self-loops surface as a sticky `data_loss`
   error. New regression test
   `rejects_non_monotonic_next_chunk_index`.

5. **SEA client treated missing `row_count` as zero.** With an
   attachment present but `row_count: None`, the kernel computed
   `row_offset + row_count = row_offset` for the next fetch —
   silent data corruption.

   Fix: surface as `data_loss` error in `sea.rs::get_inline_chunk`
   when `attachment` is present but `row_count` is None. Allow
   missing `chunk_index` / `row_offset` to fall back to the
   request values (echo).

6. **`unwrap_or(chunk_index + 1)` violated the "never synthesised"
   contract.** Now uses the server-emitted `next_chunk_index`
   directly; on `None` the prefetch task closes the channel
   instead of synthesising.

7. **Rollout-skew silent truncation (same class as PR #68).** A
   pre-rollout server emitting multi-chunk inline-Arrow without
   `inline_next_chunk_index` would be silently treated as
   single-chunk.

   Fix: in `reader/mod.rs` cross-check with
   `manifest.total_chunk_count`. If manifest reports > 1 chunk
   but per-chunk `next_chunk_index` is absent, surface
   `data_loss` rather than silently truncate.

8. **Schema unavailable forever if initial chunk decodes to zero
   batches.** Paginated results may ship an empty leading chunk;
   `schema()` would return `None` and downstream wrappers (the
   FFI adapter) rejected the stream.

   Fix: pass the manifest-derived schema through to the streaming
   provider as a fallback for the zero-initial-batches case. New
   regression test `manifest_schema_fallback_when_initial_chunk_empty`.

### P2 — Minor

9. **`row_offset == 0` was omitted from URL on the inline path,**
   contradicting the contract comment.

   Fix: send `row_offset` unconditionally on the inline path
   (it's required by ThriftServer's FETCH_ABSOLUTE cursor for
   the first chunk too). CloudFetch path unchanged for now —
   that's gated on broader bounded-API rollout.

10. **Buffered chunks lost when error surfaces.** The sticky-
    error check ran BEFORE the drain-current-chunk check, so
    after an error, the consumer couldn't drain remaining
    batches in the current chunk.

    Fix: reordered. Drain buffered batches first, then surface
    sticky error / await next chunk.

11. **Double-Arc at the source construction site.** The
    suggested fix doesn't compile (different trait types →
    different vtables → no direct coercion). Documented as the
    necessary cost of trait-object narrowing for test
    ergonomics.

### Other

- Removed unused `last_chunk_index` field on `PrefetchTask`.
- Updated `create_inline_streaming_reader` to accept and pass
  the manifest schema fallback.

### Tests

14 inline tests pass (5 original + 9 new). 418 lib tests pass.
Clippy clean.

Co-authored-by: Isaac
Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
gopalldb added a commit that referenced this pull request May 25, 2026
…nse strictness

Addresses round-2 review feedback on PR #71:

### P1

B-1. **Slow-consumer backpressure not directly tested.** Existing
     tests drain back-to-back so backpressure was never exercised
     under a stalled consumer.

     Fix: new test `slow_consumer_observes_backpressure_plateau`
     pulls one batch, sleeps 100ms, asserts the mock's RPC count
     plateaus at the channel bound, sleeps another 100ms, asserts
     no further RPCs fired, then resumes draining and verifies all
     remaining chunks arrive. A future regression that increased
     channel capacity by mistake would fail this test.

B-2. **Rollout-guard branch in `reader/mod.rs` was unexercised.**
     The fix for P1-7 in the first review round had no test
     coverage. Given that PR #68 shipped an analogous untested
     bug, this was the highest-leverage missing test.

     Fix: two new tests in `reader/mod.rs::tests`:
     - `rollout_guard_errors_when_total_chunks_disagrees_with_next_chunk_index`
       — positive: server emits multi-chunk inline without
       per-chunk continuation, manifest reports total > 1 → must
       surface `data_loss` mentioning `total_chunk_count`.
     - `rollout_guard_does_not_fire_on_genuinely_single_chunk` —
       negative: total = 1 → guard must NOT trip even when the
       per-chunk field is absent.

     Required a `PanickingTransport` stub (all 20 trait methods
     `unreachable!()`) because the guard fires before any RPC.
     Lots of boilerplate but the test reads naturally; reusable
     for any future control-flow-only factory tests.

### P2

B-3. **Initial execute response was lenient about missing
     `row_count`** while the continuation-response path (PR #71
     P1-5) was strict — asymmetric strictness.

     Fix: applied the same strictness on the initial-response
     path. When `inline_next_chunk_index.is_some()` (server has
     opted into the streaming path), the initial response MUST
     populate `inline_chunk_index`, `inline_row_offset`, and
     `inline_row_count`. Missing any of them surfaces as
     `data_loss`. Two new tests cover the row_count and
     chunk_index cases.

B-4. **`total_chunks.unwrap()` after `is_some_and`** worked today
     but was a latent footgun.

     Fix: rewrote as `if let Some(total) = total_chunks { if
     total > 1 { ... } }` so the value is bound, not re-unwrapped.

B-5. **Synchronous Arrow IPC decode on the runtime worker.**
     Preexisting behaviour; reviewer flagged as defer-able with
     a `spawn_blocking` suggestion.

     Fix: doc-comment noting current measurements (~1-5 ms per
     20 MB chunk per PR #67's perf investigation) are inside
     the typical responsiveness budget, plus a pointer to where
     `tokio::task::spawn_blocking` should land if LZ4 pushes
     decode times into the tens-of-ms range. Defer the actual
     wrap pending measurements.

### Tests

5 new tests:
- `slow_consumer_observes_backpressure_plateau` (streaming.rs)
- `rollout_guard_errors_when_total_chunks_disagrees_with_next_chunk_index`
- `rollout_guard_does_not_fire_on_genuinely_single_chunk`
- `initial_response_requires_row_count_when_streaming`
- `initial_response_requires_chunk_index_when_streaming`

All 423 lib tests pass. Clippy clean.

Co-authored-by: Isaac
Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
@gopalldb
gopalldb requested a review from vikrantpuppala May 27, 2026 15:05
gopalldb added a commit that referenced this pull request May 27, 2026
…ck, rollout guard

Addresses 11 review items on PR #71 (multi-chunk inline-Arrow
streaming with rolling window).

### P0 — Critical

1. **Lost-wake deadlock on `Notify`.** The original
   consumer↔prefetch handshake used
   `Notify::notify_waiters()`, which does NOT buffer permits.
   The consumer would drop its mutex guard, then call
   `.notified().await`. If the prefetch pushed a chunk and
   notified between drop-of-lock and the consumer's `.notified()`,
   the wake was lost and the consumer hung forever.

   Fix: replace the Notify-based coordination with
   `tokio::sync::mpsc`. Channel send/recv handles wakes correctly
   AND gives natural backpressure (channel capacity =
   `max_chunks_in_memory - 1`). New regression test
   `lost_wake_race_does_not_hang` runs the tight push/pop loop
   under a 5s timeout.

2. **Prefetch task leaks Arc<Inner>, keeps RPC-ing after consumer
   drop.** The spawned task held its own `Arc::clone(&inner)`
   independent of the provider; the doc claimed "exits when
   Arc<Inner> drops" but the task itself held an Arc, so the
   count never reached 0 from consumer drop.

   Fix: provider stores the `JoinHandle` and aborts it on Drop.
   mpsc design also kills the task naturally — when the receiver
   drops, the next `tx.send().await` returns Err. New regression
   test `prefetch_task_exits_when_consumer_drops`.

### P1 — Important

3. **Sticky-error overwrite.** `err_slot.take()` consumed the
   error; the next call saw `None`, hit EOS, returned `Ok(None)`
   — silent EOS after an error.

   Fix: cloned sticky-error slot in `ConsumerState`. Once set,
   every subsequent `next_batch` returns the same error rather
   than silently transitioning to `Ok(None)`. New regression test
   `sticky_error_persists_across_calls`.

4. **`row_count == 0` + missing `next_chunk_index` infinite
   tight-loop.** If a server emitted a self-loop
   (`next_chunk_index <= chunk_index`) the prefetch would hammer
   the same chunk forever.

   Fix: prefetch task validates strict monotonicity
   (`next_chunk_index > chunk_index`) before sending the chunk
   onto the channel. Self-loops surface as a sticky `data_loss`
   error. New regression test
   `rejects_non_monotonic_next_chunk_index`.

5. **SEA client treated missing `row_count` as zero.** With an
   attachment present but `row_count: None`, the kernel computed
   `row_offset + row_count = row_offset` for the next fetch —
   silent data corruption.

   Fix: surface as `data_loss` error in `sea.rs::get_inline_chunk`
   when `attachment` is present but `row_count` is None. Allow
   missing `chunk_index` / `row_offset` to fall back to the
   request values (echo).

6. **`unwrap_or(chunk_index + 1)` violated the "never synthesised"
   contract.** Now uses the server-emitted `next_chunk_index`
   directly; on `None` the prefetch task closes the channel
   instead of synthesising.

7. **Rollout-skew silent truncation (same class as PR #68).** A
   pre-rollout server emitting multi-chunk inline-Arrow without
   `inline_next_chunk_index` would be silently treated as
   single-chunk.

   Fix: in `reader/mod.rs` cross-check with
   `manifest.total_chunk_count`. If manifest reports > 1 chunk
   but per-chunk `next_chunk_index` is absent, surface
   `data_loss` rather than silently truncate.

8. **Schema unavailable forever if initial chunk decodes to zero
   batches.** Paginated results may ship an empty leading chunk;
   `schema()` would return `None` and downstream wrappers (the
   FFI adapter) rejected the stream.

   Fix: pass the manifest-derived schema through to the streaming
   provider as a fallback for the zero-initial-batches case. New
   regression test `manifest_schema_fallback_when_initial_chunk_empty`.

### P2 — Minor

9. **`row_offset == 0` was omitted from URL on the inline path,**
   contradicting the contract comment.

   Fix: send `row_offset` unconditionally on the inline path
   (it's required by ThriftServer's FETCH_ABSOLUTE cursor for
   the first chunk too). CloudFetch path unchanged for now —
   that's gated on broader bounded-API rollout.

10. **Buffered chunks lost when error surfaces.** The sticky-
    error check ran BEFORE the drain-current-chunk check, so
    after an error, the consumer couldn't drain remaining
    batches in the current chunk.

    Fix: reordered. Drain buffered batches first, then surface
    sticky error / await next chunk.

11. **Double-Arc at the source construction site.** The
    suggested fix doesn't compile (different trait types →
    different vtables → no direct coercion). Documented as the
    necessary cost of trait-object narrowing for test
    ergonomics.

### Other

- Removed unused `last_chunk_index` field on `PrefetchTask`.
- Updated `create_inline_streaming_reader` to accept and pass
  the manifest schema fallback.

### Tests

14 inline tests pass (5 original + 9 new). 418 lib tests pass.
Clippy clean.

Co-authored-by: Isaac
Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
gopalldb added a commit that referenced this pull request May 27, 2026
…nse strictness

Addresses round-2 review feedback on PR #71:

### P1

B-1. **Slow-consumer backpressure not directly tested.** Existing
     tests drain back-to-back so backpressure was never exercised
     under a stalled consumer.

     Fix: new test `slow_consumer_observes_backpressure_plateau`
     pulls one batch, sleeps 100ms, asserts the mock's RPC count
     plateaus at the channel bound, sleeps another 100ms, asserts
     no further RPCs fired, then resumes draining and verifies all
     remaining chunks arrive. A future regression that increased
     channel capacity by mistake would fail this test.

B-2. **Rollout-guard branch in `reader/mod.rs` was unexercised.**
     The fix for P1-7 in the first review round had no test
     coverage. Given that PR #68 shipped an analogous untested
     bug, this was the highest-leverage missing test.

     Fix: two new tests in `reader/mod.rs::tests`:
     - `rollout_guard_errors_when_total_chunks_disagrees_with_next_chunk_index`
       — positive: server emits multi-chunk inline without
       per-chunk continuation, manifest reports total > 1 → must
       surface `data_loss` mentioning `total_chunk_count`.
     - `rollout_guard_does_not_fire_on_genuinely_single_chunk` —
       negative: total = 1 → guard must NOT trip even when the
       per-chunk field is absent.

     Required a `PanickingTransport` stub (all 20 trait methods
     `unreachable!()`) because the guard fires before any RPC.
     Lots of boilerplate but the test reads naturally; reusable
     for any future control-flow-only factory tests.

### P2

B-3. **Initial execute response was lenient about missing
     `row_count`** while the continuation-response path (PR #71
     P1-5) was strict — asymmetric strictness.

     Fix: applied the same strictness on the initial-response
     path. When `inline_next_chunk_index.is_some()` (server has
     opted into the streaming path), the initial response MUST
     populate `inline_chunk_index`, `inline_row_offset`, and
     `inline_row_count`. Missing any of them surfaces as
     `data_loss`. Two new tests cover the row_count and
     chunk_index cases.

B-4. **`total_chunks.unwrap()` after `is_some_and`** worked today
     but was a latent footgun.

     Fix: rewrote as `if let Some(total) = total_chunks { if
     total > 1 { ... } }` so the value is bound, not re-unwrapped.

B-5. **Synchronous Arrow IPC decode on the runtime worker.**
     Preexisting behaviour; reviewer flagged as defer-able with
     a `spawn_blocking` suggestion.

     Fix: doc-comment noting current measurements (~1-5 ms per
     20 MB chunk per PR #67's perf investigation) are inside
     the typical responsiveness budget, plus a pointer to where
     `tokio::task::spawn_blocking` should land if LZ4 pushes
     decode times into the tens-of-ms range. Defer the actual
     wrap pending measurements.

### Tests

5 new tests:
- `slow_consumer_observes_backpressure_plateau` (streaming.rs)
- `rollout_guard_errors_when_total_chunks_disagrees_with_next_chunk_index`
- `rollout_guard_does_not_fire_on_genuinely_single_chunk`
- `initial_response_requires_row_count_when_streaming`
- `initial_response_requires_chunk_index_when_streaming`

All 423 lib tests pass. Clippy clean.

Co-authored-by: Isaac
Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
@gopalldb
gopalldb force-pushed the feat/inline-arrow-streaming branch from 3409a2c to 10f39b4 Compare May 27, 2026 15:40
gopalldb added a commit that referenced this pull request May 27, 2026
After rebasing onto latest main, two main-side changes broke
the build:

- `ResultReaderFactory::extract_schema_from_manifest` was
  converted to an associated function (no `&self`) in main's
  PR #68 merge; PR #71's lambda call site still used method
  syntax `self.extract_schema_from_manifest(...)`. Updated
  to associated-function syntax `Self::extract_schema_from_manifest(...)`.
- `types::sea::GetChunksResponse` gained a new `attachment`
  field on this PR; the 4 `derive_chunk_fetch_result` test
  struct literals that landed via main (from PR #67's
  derive-helper extraction) need `attachment: None` to
  match the new struct shape.

Tests: 509 lib pass post-fixup. fmt + clippy clean.

Co-authored-by: Isaac
Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
gopalldb added 4 commits June 1, 2026 13:44
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 pattern
(~/repo/databricks-jdbc/src/main/java/com/databricks/jdbc/api/impl/
arrow/StreamingChunkProvider.java).

- New `Transport::get_inline_chunk(statement_id, chunk_index,
  row_offset) -> InlineChunkFetchResult` method on the trait,
  implemented on `SeaRestTransport`. Sends both `chunk_index` (path
  param) and `row_offset` (query param) per the bounded SEA API
  contract. Expects the server to return Arrow IPC bytes in
  `attachment` plus chunk metadata (chunk_index, row_offset,
  row_count, next_chunk_index).

- `InlineChunkFetchResult` value type carries the per-chunk
  metadata the kernel needs to walk the chunk chain.

- New `ResultConfig.inline_max_chunks_in_memory` knob (default 4),
  analogue of `cloudfetch_max_chunks_in_memory` for the inline
  path. Plumbed through `CloudFetchConfig`.

- New `InlineStreamingProvider` in `src/reader/inline/streaming.rs`:
  - Decodes the initial chunk (from the execute response's
    `attachment`) synchronously so callers get a usable schema.
  - Spawns a background prefetch task that sequentially fetches
    subsequent chunks via `get_inline_chunk`, decodes each, and
    pushes the decoded batches into a bounded rolling window.
  - Window bounded by `inline_max_chunks_in_memory`; when full,
    prefetch pauses on a `Notify` until the consumer drains a chunk.
  - Sequential by design — the SEA inline contract is one
    `GetResultData` at a time, no parallel downloads.
  - End-of-stream from the bounded SEA API contract: the
    server-emitted `next_chunk_index = None` on a fetched chunk
    flips the EOS flag. Never synthesised from `+ 1` arithmetic.

- Narrow `InlineChunkSource` trait (just the one method) 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` now branches on
  `inline_next_chunk_index`: when present alongside
  `inline_arrow_data`, construct the streaming reader; otherwise
  fall through to the existing single-chunk `InlineArrowProvider`.

- `ExecuteResultData` extended with four optional fields
  (`inline_chunk_index`, `inline_row_offset`, `inline_row_count`,
  `inline_next_chunk_index`) so the kernel can hand the inline-
  streaming provider its initial state without reaching back into
  the SEA response shape.

Four unit tests on `InlineStreamingProvider`:

- `streams_all_chunks_in_order` — three-chunk fixture, asserts all
  rows arrive in order across chunks.
- `respects_max_chunks_in_memory_bound` — with window = 1, asserts
  the prefetch task makes exactly 2 RPCs (not 3) — chunk 0 is the
  initial attachment.
- `single_chunk_no_prefetch_rpcs` — initial chunk has
  `next_chunk_index = None`, zero RPCs.
- `surfaces_prefetch_errors` — prefetch failure sticks; the
  consumer surfaces it on the next pull.

All 418 lib tests + 16 wiremock integration tests pass. Clippy
clean.

Co-authored-by: Isaac
Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
…ck, rollout guard

Addresses 11 review items on PR #71 (multi-chunk inline-Arrow
streaming with rolling window).

### P0 — Critical

1. **Lost-wake deadlock on `Notify`.** The original
   consumer↔prefetch handshake used
   `Notify::notify_waiters()`, which does NOT buffer permits.
   The consumer would drop its mutex guard, then call
   `.notified().await`. If the prefetch pushed a chunk and
   notified between drop-of-lock and the consumer's `.notified()`,
   the wake was lost and the consumer hung forever.

   Fix: replace the Notify-based coordination with
   `tokio::sync::mpsc`. Channel send/recv handles wakes correctly
   AND gives natural backpressure (channel capacity =
   `max_chunks_in_memory - 1`). New regression test
   `lost_wake_race_does_not_hang` runs the tight push/pop loop
   under a 5s timeout.

2. **Prefetch task leaks Arc<Inner>, keeps RPC-ing after consumer
   drop.** The spawned task held its own `Arc::clone(&inner)`
   independent of the provider; the doc claimed "exits when
   Arc<Inner> drops" but the task itself held an Arc, so the
   count never reached 0 from consumer drop.

   Fix: provider stores the `JoinHandle` and aborts it on Drop.
   mpsc design also kills the task naturally — when the receiver
   drops, the next `tx.send().await` returns Err. New regression
   test `prefetch_task_exits_when_consumer_drops`.

### P1 — Important

3. **Sticky-error overwrite.** `err_slot.take()` consumed the
   error; the next call saw `None`, hit EOS, returned `Ok(None)`
   — silent EOS after an error.

   Fix: cloned sticky-error slot in `ConsumerState`. Once set,
   every subsequent `next_batch` returns the same error rather
   than silently transitioning to `Ok(None)`. New regression test
   `sticky_error_persists_across_calls`.

4. **`row_count == 0` + missing `next_chunk_index` infinite
   tight-loop.** If a server emitted a self-loop
   (`next_chunk_index <= chunk_index`) the prefetch would hammer
   the same chunk forever.

   Fix: prefetch task validates strict monotonicity
   (`next_chunk_index > chunk_index`) before sending the chunk
   onto the channel. Self-loops surface as a sticky `data_loss`
   error. New regression test
   `rejects_non_monotonic_next_chunk_index`.

5. **SEA client treated missing `row_count` as zero.** With an
   attachment present but `row_count: None`, the kernel computed
   `row_offset + row_count = row_offset` for the next fetch —
   silent data corruption.

   Fix: surface as `data_loss` error in `sea.rs::get_inline_chunk`
   when `attachment` is present but `row_count` is None. Allow
   missing `chunk_index` / `row_offset` to fall back to the
   request values (echo).

6. **`unwrap_or(chunk_index + 1)` violated the "never synthesised"
   contract.** Now uses the server-emitted `next_chunk_index`
   directly; on `None` the prefetch task closes the channel
   instead of synthesising.

7. **Rollout-skew silent truncation (same class as PR #68).** A
   pre-rollout server emitting multi-chunk inline-Arrow without
   `inline_next_chunk_index` would be silently treated as
   single-chunk.

   Fix: in `reader/mod.rs` cross-check with
   `manifest.total_chunk_count`. If manifest reports > 1 chunk
   but per-chunk `next_chunk_index` is absent, surface
   `data_loss` rather than silently truncate.

8. **Schema unavailable forever if initial chunk decodes to zero
   batches.** Paginated results may ship an empty leading chunk;
   `schema()` would return `None` and downstream wrappers (the
   FFI adapter) rejected the stream.

   Fix: pass the manifest-derived schema through to the streaming
   provider as a fallback for the zero-initial-batches case. New
   regression test `manifest_schema_fallback_when_initial_chunk_empty`.

### P2 — Minor

9. **`row_offset == 0` was omitted from URL on the inline path,**
   contradicting the contract comment.

   Fix: send `row_offset` unconditionally on the inline path
   (it's required by ThriftServer's FETCH_ABSOLUTE cursor for
   the first chunk too). CloudFetch path unchanged for now —
   that's gated on broader bounded-API rollout.

10. **Buffered chunks lost when error surfaces.** The sticky-
    error check ran BEFORE the drain-current-chunk check, so
    after an error, the consumer couldn't drain remaining
    batches in the current chunk.

    Fix: reordered. Drain buffered batches first, then surface
    sticky error / await next chunk.

11. **Double-Arc at the source construction site.** The
    suggested fix doesn't compile (different trait types →
    different vtables → no direct coercion). Documented as the
    necessary cost of trait-object narrowing for test
    ergonomics.

### Other

- Removed unused `last_chunk_index` field on `PrefetchTask`.
- Updated `create_inline_streaming_reader` to accept and pass
  the manifest schema fallback.

### Tests

14 inline tests pass (5 original + 9 new). 418 lib tests pass.
Clippy clean.

Co-authored-by: Isaac
Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
…nse strictness

Addresses round-2 review feedback on PR #71:

### P1

B-1. **Slow-consumer backpressure not directly tested.** Existing
     tests drain back-to-back so backpressure was never exercised
     under a stalled consumer.

     Fix: new test `slow_consumer_observes_backpressure_plateau`
     pulls one batch, sleeps 100ms, asserts the mock's RPC count
     plateaus at the channel bound, sleeps another 100ms, asserts
     no further RPCs fired, then resumes draining and verifies all
     remaining chunks arrive. A future regression that increased
     channel capacity by mistake would fail this test.

B-2. **Rollout-guard branch in `reader/mod.rs` was unexercised.**
     The fix for P1-7 in the first review round had no test
     coverage. Given that PR #68 shipped an analogous untested
     bug, this was the highest-leverage missing test.

     Fix: two new tests in `reader/mod.rs::tests`:
     - `rollout_guard_errors_when_total_chunks_disagrees_with_next_chunk_index`
       — positive: server emits multi-chunk inline without
       per-chunk continuation, manifest reports total > 1 → must
       surface `data_loss` mentioning `total_chunk_count`.
     - `rollout_guard_does_not_fire_on_genuinely_single_chunk` —
       negative: total = 1 → guard must NOT trip even when the
       per-chunk field is absent.

     Required a `PanickingTransport` stub (all 20 trait methods
     `unreachable!()`) because the guard fires before any RPC.
     Lots of boilerplate but the test reads naturally; reusable
     for any future control-flow-only factory tests.

### P2

B-3. **Initial execute response was lenient about missing
     `row_count`** while the continuation-response path (PR #71
     P1-5) was strict — asymmetric strictness.

     Fix: applied the same strictness on the initial-response
     path. When `inline_next_chunk_index.is_some()` (server has
     opted into the streaming path), the initial response MUST
     populate `inline_chunk_index`, `inline_row_offset`, and
     `inline_row_count`. Missing any of them surfaces as
     `data_loss`. Two new tests cover the row_count and
     chunk_index cases.

B-4. **`total_chunks.unwrap()` after `is_some_and`** worked today
     but was a latent footgun.

     Fix: rewrote as `if let Some(total) = total_chunks { if
     total > 1 { ... } }` so the value is bound, not re-unwrapped.

B-5. **Synchronous Arrow IPC decode on the runtime worker.**
     Preexisting behaviour; reviewer flagged as defer-able with
     a `spawn_blocking` suggestion.

     Fix: doc-comment noting current measurements (~1-5 ms per
     20 MB chunk per PR #67's perf investigation) are inside
     the typical responsiveness budget, plus a pointer to where
     `tokio::task::spawn_blocking` should land if LZ4 pushes
     decode times into the tens-of-ms range. Defer the actual
     wrap pending measurements.

### Tests

5 new tests:
- `slow_consumer_observes_backpressure_plateau` (streaming.rs)
- `rollout_guard_errors_when_total_chunks_disagrees_with_next_chunk_index`
- `rollout_guard_does_not_fire_on_genuinely_single_chunk`
- `initial_response_requires_row_count_when_streaming`
- `initial_response_requires_chunk_index_when_streaming`

All 423 lib tests pass. Clippy clean.

Co-authored-by: Isaac
Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
After rebasing onto latest main, three main-side changes break
the PR's test surface:

- `ResultReaderFactory::extract_schema_from_manifest` was
  converted to an associated function (no `&self`) in main's
  PR #68 merge; PR #71's lambda call site still used method
  syntax `self.extract_schema_from_manifest(...)`. Updated
  to associated-function syntax `Self::extract_schema_from_manifest(...)`.
- `types::sea::GetChunksResponse` gained a new `attachment`
  field on this PR; the 4 `derive_chunk_fetch_result` test
  struct literals that landed via main (from PR #67's
  derive-helper extraction) need `attachment: None` to
  match the new struct shape.
- `types::sea::StatementStatus` gained 4 new fields on main
  (`num_modified_rows`, `display_message`, `diagnostic_info`,
  `error_details_json`); the `ok_status()` test helper in
  `src/reader/mod.rs` needs all four initialised to `None`
  to compile against the new struct shape.

Co-authored-by: Isaac
Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
@gopalldb
gopalldb force-pushed the feat/inline-arrow-streaming branch from 7920f7f to a18c8b8 Compare June 1, 2026 08:16
@gopalldb
gopalldb merged commit 2782995 into main Jun 1, 2026
12 of 13 checks passed

This branch had an error being deployed

1 failed deployment
azure-prod — a18c8b8c Deployed Jun 1, 2026 by gopalldb via v0 E2E surface #24
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