From c6baf9e2703da39445a28ce90be0ca0f3cda12ef Mon Sep 17 00:00:00 2001 From: Gopal Lal Date: Mon, 25 May 2026 15:10:13 +0530 Subject: [PATCH 1/4] feat(inline): multi-chunk inline-Arrow streaming with rolling window MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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` 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 --- src/client/mod.rs | 4 +- src/client/sea.rs | 105 +++- src/client/transport.rs | 55 ++ src/config.rs | 16 + src/reader/cloudfetch/link_fetcher.rs | 9 + src/reader/inline/mod.rs | 25 +- src/reader/inline/streaming.rs | 711 ++++++++++++++++++++++++++ src/reader/mod.rs | 107 +++- src/session.rs | 1 + src/types/cloudfetch.rs | 7 + src/types/sea.rs | 6 + 11 files changed, 1037 insertions(+), 9 deletions(-) create mode 100644 src/reader/inline/streaming.rs diff --git a/src/client/mod.rs b/src/client/mod.rs index ea52828d..f49bdd4e 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -45,6 +45,6 @@ pub use retry::{ // Crate-internal surface — `Transport` trait + its value types. pub(crate) use sea::SeaRestTransport; pub(crate) use transport::{ - ChunkLinkFetchResult, ExecuteResponse, ExecuteResult, ExecuteResultData, SessionInfo, - Transport, TransportConfig, + ChunkLinkFetchResult, ExecuteResponse, ExecuteResult, ExecuteResultData, + InlineChunkFetchResult, SessionInfo, Transport, TransportConfig, }; diff --git a/src/client/sea.rs b/src/client/sea.rs index 7f23d389..355aa4b0 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -20,7 +20,7 @@ use crate::client::retry::RequestType; use crate::client::{ ChunkLinkFetchResult, DatabricksHttpClient, ExecuteResponse, ExecuteResult, ExecuteResultData, - SessionInfo, Transport, TransportConfig, + InlineChunkFetchResult, SessionInfo, Transport, TransportConfig, }; use crate::kernel_error::{Error, Result}; use crate::metadata::sql::SqlCommandBuilder; @@ -210,6 +210,10 @@ impl SeaRestTransport { next_chunk_internal_link: result.next_chunk_internal_link.clone(), external_links, inline_arrow_data: result.attachment.clone(), + inline_chunk_index: result.chunk_index, + inline_row_offset: result.row_offset, + inline_row_count: result.row_count, + inline_next_chunk_index: result.next_chunk_index, }) } @@ -819,6 +823,105 @@ impl Transport for SeaRestTransport { Ok(result) } + async fn get_inline_chunk( + &self, + statement_id: &str, + chunk_index: i64, + row_offset: i64, + ) -> Result { + // Same endpoint as CloudFetch chunk-link fetching, but on + // the inline-Arrow path the response carries Arrow IPC bytes + // in `attachment` instead of `external_links`. `row_offset` + // is sent as a query parameter — required from drivers per + // the bounded SEA API contract (and explicitly required for + // the SEA inline-Arrow path that ThriftServer routes via + // FETCH_ABSOLUTE). + let url = if row_offset > 0 { + format!( + "{}/statements/{}/result/chunks/{}?row_offset={}", + self.base_url(), + statement_id, + chunk_index, + row_offset + ) + } else { + format!( + "{}/statements/{}/result/chunks/{}", + self.base_url(), + statement_id, + chunk_index + ) + }; + + debug!( + "Getting inline chunk {} at {} (row_offset={})", + chunk_index, url, row_offset + ); + + let request = self + .http_client + .inner() + .request(Method::GET, &url) + .build() + .map_err(|e| { + Error::invalid_argument().message(format!("Failed to build request: {e}")) + })?; + + let response = self + .http_client + .execute(request, RequestType::GetResultChunks) + .await?; + let body = response + .text() + .await + .map_err(|e| Error::network_error().message(format!("Failed to read response: {e}")))?; + + let chunks_response: GetChunksResponse = serde_json::from_str(&body).map_err(|e| { + Error::data_loss().message(format!( + "Failed to parse inline chunk response: {e} - body: {body}" + )) + })?; + + // Inline-Arrow path: bytes must be present in `attachment`. + // If the server returned an external_links response on what + // we expected to be the inline path, surface a clear error + // (probably the session conf didn't take effect server-side). + let bytes = chunks_response.attachment.ok_or_else(|| { + Error::data_loss().message(format!( + "Inline chunk {} response missing `attachment` field — \ + server may have ignored the can_cloud_download session \ + conf and returned a CloudFetch response. Body: {}", + chunk_index, body + )) + })?; + + // Per the bounded SEA API contract, the chunk metadata we + // need is on the response itself (top-level, not nested). + // Defaults are defensive: if the server omits these we still + // surface a usable chunk but with conservative metadata. + let chunk_idx = chunks_response.chunk_index.unwrap_or(chunk_index); + let returned_row_offset = chunks_response.row_offset.unwrap_or(row_offset); + let row_count = chunks_response.row_count.unwrap_or(0); + let next_chunk_index = chunks_response.next_chunk_index; + + debug!( + "Inline chunk {} response: row_offset={}, row_count={}, next_chunk_index={:?}, bytes={}", + chunk_idx, + returned_row_offset, + row_count, + next_chunk_index, + bytes.len(), + ); + + Ok(InlineChunkFetchResult { + bytes, + chunk_index: chunk_idx, + row_offset: returned_row_offset, + row_count, + next_chunk_index, + }) + } + fn poll_config(&self) -> TransportConfig { self.config.clone() } diff --git a/src/client/transport.rs b/src/client/transport.rs index 41040dca..237150e9 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -122,6 +122,16 @@ pub(crate) struct ExecuteResultData { /// Inline Arrow IPC data (decoded from base64). /// Present when server returns inline results instead of CloudFetch. pub(crate) inline_arrow_data: Option>, + /// Per-chunk metadata for the inline-Arrow streaming path. Only + /// meaningful when `inline_arrow_data` is `Some(_)`. The + /// `inline_next_chunk_index` field is the signal: `Some(N)` → + /// the kernel should construct an [`InlineStreamingProvider`] + /// (multi-chunk inline); `None` → the result fits in a single + /// chunk and the legacy [`InlineArrowProvider`] is enough. + pub(crate) inline_chunk_index: Option, + pub(crate) inline_row_offset: Option, + pub(crate) inline_row_count: Option, + pub(crate) inline_next_chunk_index: Option, } /// Result of fetching chunk links. @@ -155,6 +165,30 @@ pub(crate) struct ChunkLinkFetchResult { pub next_row_offset: Option, } +/// One inline-Arrow chunk fetched via `GetResultData`. +/// +/// Returned by [`Transport::get_inline_chunk`] for the SEA inline- +/// Arrow streaming path. Carries the chunk's Arrow IPC bytes +/// inline (no separate cloud download) plus the metadata the kernel +/// needs to walk the chunk chain: `chunk_index`, `row_offset`, +/// `row_count`, and the server-emitted `next_chunk_index`. +#[derive(Debug, Clone)] +pub(crate) struct InlineChunkFetchResult { + /// Arrow IPC bytes (already base64-decoded by the SEA client). + pub bytes: Vec, + /// Index of this chunk in the result set. + pub chunk_index: i64, + /// Row position (0-based) of the first row in this chunk. + pub row_offset: i64, + /// Number of rows in this chunk. + pub row_count: i64, + /// `chunk_index` to ask for in the next `GetResultData` call. + /// `None` marks end-of-stream for inline-Arrow link discovery + /// (per the bounded SEA API contract — same end-of-stream + /// signal as CloudFetch's per-link `next_chunk_index`). + pub next_chunk_index: Option, +} + impl ChunkLinkFetchResult { /// Create an empty result indicating end of stream. #[allow( @@ -271,6 +305,27 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { row_offset: i64, ) -> Result; + /// Fetch one inline-Arrow chunk by `chunk_index` (+ server-side + /// `row_offset`). + /// + /// Used by the inline-Arrow streaming path that lights up when + /// `ResultConfig.cloudfetch_enabled == false` (i.e. SEA's + /// `can_cloud_download=false` session conf). The server-side + /// response for this path carries Arrow IPC bytes inline in + /// `attachment` rather than emitting `external_links`. + /// + /// Per the bounded SEA API contract for OSS drivers: + /// - `chunk_index` is derived from the *previous* chunk's + /// `next_chunk_index`. Never synthesised as `prev + 1`. + /// - `row_offset` is derived from the previous chunk's + /// `row_offset + row_count`. Sent on every fetch. + async fn get_inline_chunk( + &self, + statement_id: &str, + chunk_index: i64, + row_offset: i64, + ) -> Result; + /// Polling cadence + ceiling the kernel should use when driving /// `await_result` / `wait_for_completion`. v0 returns the /// transport's `TransportConfig` directly; future transports diff --git a/src/config.rs b/src/config.rs index 1397fcf5..ac1dfc59 100644 --- a/src/config.rs +++ b/src/config.rs @@ -493,6 +493,21 @@ pub struct ResultConfig { /// Bounds parallelism and peak RSS. pub cloudfetch_max_chunks_in_memory: usize, + /// Maximum number of decompressed Arrow chunks the inline-Arrow + /// streaming reader holds in memory at once. Analogue of + /// [`Self::cloudfetch_max_chunks_in_memory`] for the inline path + /// (used when [`Self::cloudfetch_enabled`] is `false`). + /// + /// The inline path is sequential per the SEA contract — one + /// `GetResultData` call at a time — so this knob bounds the + /// **prefetch window** (chunks the kernel pulls ahead of the + /// consumer) rather than the download parallelism. Larger values + /// give the consumer a deeper buffer at the cost of memory. + /// + /// Default `4`. Range 1..=N; `1` disables prefetching and gives + /// strict lazy fetch-on-demand semantics. + pub inline_max_chunks_in_memory: usize, + /// When `true`, every column of complex type (`List` / /// `LargeList` / `FixedSizeList` / `Map` / `Struct`, plus the /// precise types `VARIANT` / `GEOMETRY` / `GEOGRAPHY` carried in @@ -534,6 +549,7 @@ impl Default for ResultConfig { cloudfetch_enabled: true, cloudfetch_link_prefetch_window: 10, cloudfetch_max_chunks_in_memory: 16, + inline_max_chunks_in_memory: 4, complex_types_as_json: false, intervals_as_string: false, } diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index a536b488..3af8f5ed 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -1202,6 +1202,15 @@ mod tests { }) } + async fn get_inline_chunk( + &self, + _statement_id: &str, + _chunk_index: i64, + _row_offset: i64, + ) -> Result { + unimplemented!("get_inline_chunk not used by the link-fetcher mock") + } + fn poll_config(&self) -> crate::client::TransportConfig { crate::client::TransportConfig::default() } diff --git a/src/reader/inline/mod.rs b/src/reader/inline/mod.rs index 8d8b77f1..f859e45c 100644 --- a/src/reader/inline/mod.rs +++ b/src/reader/inline/mod.rs @@ -14,13 +14,28 @@ //! Inline Arrow results support. //! -//! This module handles inline Arrow results that are embedded directly in the -//! API response (via the `attachment` field) rather than being downloaded from -//! cloud storage via CloudFetch. +//! This module handles inline Arrow results that are embedded directly +//! in the API response (via the `attachment` field) rather than being +//! downloaded from cloud storage via CloudFetch. //! -//! Inline results are used for small result sets where the overhead of CloudFetch -//! (presigned URL generation, separate HTTP download) would be inefficient. +//! Two paths live here: +//! +//! - [`InlineArrowProvider`] (in [`provider`]) — single-chunk case. +//! The whole result fits in one `attachment`; we parse it up front +//! and yield batches synchronously. Used when the initial execute +//! response embeds the full result and `next_chunk_index` is +//! absent. +//! +//! - [`InlineStreamingProvider`] (in [`streaming`]) — multi-chunk +//! case. The server returns one chunk at a time via +//! `GET /result/chunks/{idx}?row_offset=N`; the kernel maintains a +//! bounded rolling window of pre-decoded chunks ahead of the +//! consumer. Used when CloudFetch is disabled +//! (`can_cloud_download=false` session conf) and the result is +//! large enough that the server paginates it. mod provider; +mod streaming; pub use provider::InlineArrowProvider; +pub(crate) use streaming::{InlineChunkSource, InlineStreamingProvider}; diff --git a/src/reader/inline/streaming.rs b/src/reader/inline/streaming.rs new file mode 100644 index 00000000..4678bbb0 --- /dev/null +++ b/src/reader/inline/streaming.rs @@ -0,0 +1,711 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! `InlineStreamingProvider` — rolling-window prefetch for multi-chunk inline Arrow. +//! +//! Lights up when the session has `can_cloud_download = false`. The +//! server returns chunks one at a time via `GET /result/chunks/{idx}` +//! with Arrow IPC bytes in `attachment`; this provider keeps a bounded +//! number of those chunks decoded and ready in memory ahead of the +//! consumer so the per-chunk SEA round-trip latency is hidden behind +//! `RecordBatch` iteration. +//! +//! ## Design (modelled on JDBC's `StreamingChunkProvider`) +//! +//! ```text +//! Server Prefetch task Consumer +//! ────── ───────────── ──────── +//! fetch chunk N ──┐ +//! responds with bytes ──> decode IPC │ +//! push to window ──┘──> [chunk N][chunk N+1]... +//! (until window full) │ +//! │ +//! pull batch ◄── caller +//! ``` +//! +//! - One sequential prefetch task (the SEA inline contract is "one +//! `GetResultData` at a time" — there's no parallel download). +//! - Bounded by `max_chunks_in_memory` (analogous to +//! `ResultConfig::cloudfetch_max_chunks_in_memory`). +//! - When the consumer drains a chunk's batches, the entry is +//! popped, freeing a slot. A `Notify` wakes the prefetch task so +//! it can pull the next chunk in. +//! +//! ## Bounded SEA API contract +//! +//! Every `get_inline_chunk` call carries **both** `chunk_index` and +//! `row_offset`. The next-fetch values come from the previous chunk's +//! server-emitted `next_chunk_index` and `row_offset + row_count` +//! respectively. End-of-stream is the absence of `next_chunk_index` +//! on a fetched chunk — never synthesised from `chunk_index + 1`. + +use crate::client::{InlineChunkFetchResult, Transport}; +use crate::kernel_error::{Error, Result}; +use crate::reader::cloudfetch::parse_arrow_ipc; +use crate::types::sea::CompressionCodec; +use arrow_array::RecordBatch; +use arrow_schema::SchemaRef; +use async_trait::async_trait; +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; +use std::sync::Arc; +use tokio::sync::{Mutex as TokioMutex, Notify}; +use tracing::{debug, error, instrument}; + +/// Narrow source trait for inline-chunk fetches. +/// +/// Lets the streaming provider depend on just the one method it +/// needs (so tests don't have to build a full `Transport` mock with +/// `unreachable!()` for the 20-odd metadata RPCs). Production code +/// uses the blanket impl on `Arc`. +#[async_trait] +pub(crate) trait InlineChunkSource: Send + Sync + std::fmt::Debug { + async fn get_inline_chunk( + &self, + statement_id: &str, + chunk_index: i64, + row_offset: i64, + ) -> Result; +} + +#[async_trait] +impl InlineChunkSource for Arc { + async fn get_inline_chunk( + &self, + statement_id: &str, + chunk_index: i64, + row_offset: i64, + ) -> Result { + Transport::get_inline_chunk(self.as_ref(), statement_id, chunk_index, row_offset).await + } +} + +/// One pre-decoded inline-Arrow chunk sitting in the rolling window. +#[derive(Debug)] +struct InlineChunkEntry { + chunk_index: i64, + /// Decoded Arrow batches, drained one at a time by `next_batch`. + /// `VecDeque` so we can `pop_front` in O(1). + batches: VecDeque, +} + +/// Shared state between the prefetch task and the consumer. +/// +/// `Arc` so the spawned task holds its own clone without +/// keeping the provider alive past stream end. +#[derive(Debug)] +struct Inner { + source: Arc, + statement_id: String, + compression: CompressionCodec, + + /// Rolling window of pre-decoded chunks, ordered by `chunk_index`. + /// Pushed to the back by the prefetch task; drained from the + /// front by the consumer. + /// + /// A `TokioMutex` (not `std::sync::Mutex`) so the consumer can + /// `.await` while holding it would be a footgun — we deliberately + /// only hold the lock for the duration of a `pop` or `push_back`. + chunks: TokioMutex>, + + /// `chunk_index` to ask for in the next `get_inline_chunk` call. + /// Initialised from the initial response; updated each prefetch + /// from the server-emitted `next_chunk_index`. + next_fetch_chunk_index: AtomicI64, + + /// Row offset to send on the next `get_inline_chunk` call. + /// Initialised + updated alongside `next_fetch_chunk_index`. + next_fetch_row_offset: AtomicI64, + + /// End-of-stream sentinel — flipped when the *previously fetched + /// chunk* had `next_chunk_index = None`. Once set, no further + /// prefetch is issued; the consumer drains the remaining + /// `chunks` window and then sees EOF. + end_of_stream: AtomicBool, + + /// First-error sticky slot. The prefetch task records its first + /// failure here; the consumer surfaces it on the next pull. + /// Once set, the task exits — the kernel does not retry the SEA + /// path here (HTTP-level retries already happened inside the + /// transport). + error: TokioMutex>, + + /// Bound on the rolling window. + max_chunks_in_memory: usize, + + /// Bell for the consumer ↔ prefetch handshake: + /// + /// - Prefetch task notifies when it pushes a chunk or sets an + /// error / EOF. + /// - Consumer notifies when it pops a chunk (so prefetch can + /// resume if the window was full). + notify: Notify, +} + +/// Multi-chunk inline-Arrow streaming provider. +#[derive(Debug)] +pub(crate) struct InlineStreamingProvider { + inner: Arc, + /// Cached schema. Set when the first batch is decoded. + schema: Option, +} + +impl InlineStreamingProvider { + /// Build a streaming provider seeded by the first chunk's payload + /// (which the kernel already received in the initial execute + /// response — see `reader/mod.rs::create_inner_reader`). + /// + /// The initial chunk is decoded synchronously so callers get a + /// usable schema back from `schema()` even before the background + /// prefetch task has done any work. + /// + /// # Arguments + /// * `transport` — for issuing `get_inline_chunk` RPCs. + /// * `statement_id` — for the URL path. + /// * `initial_attachment` — Arrow IPC bytes the kernel already + /// has from the initial execute response. + /// * `initial_chunk_index` — the first chunk's index (0 in + /// practice; pass whatever the manifest reported). + /// * `initial_row_offset` / `initial_row_count` — same. + /// * `next_chunk_index` — server's `next_chunk_index` on the + /// initial chunk. `Some(N)` → more chunks to fetch starting at + /// N; `None` → single-chunk result, no further fetches. + /// * `compression` — Arrow IPC compression codec from the + /// manifest. + /// * `max_chunks_in_memory` — bound on the rolling window + /// (`ResultConfig::inline_max_chunks_in_memory`). + /// * `runtime_handle` — for spawning the prefetch task. + #[allow(clippy::too_many_arguments)] + pub(crate) fn new( + source: Arc, + statement_id: impl Into, + initial_attachment: Vec, + initial_chunk_index: i64, + initial_row_offset: i64, + initial_row_count: i64, + next_chunk_index: Option, + compression: CompressionCodec, + max_chunks_in_memory: usize, + runtime_handle: tokio::runtime::Handle, + ) -> Result> { + // Decode the initial chunk synchronously so we can return a + // schema-bearing provider to the caller. + let initial_batches = parse_arrow_ipc(&initial_attachment, compression)?; + let schema = initial_batches.first().map(|b| b.schema()); + + let initial_entry = InlineChunkEntry { + chunk_index: initial_chunk_index, + batches: VecDeque::from(initial_batches), + }; + + // Next-fetch state comes from the initial chunk's metadata. + // If `next_chunk_index` is None we are at end-of-stream + // already — the prefetch task will see the flag and exit + // without making any RPC. + let (next_idx, eos) = match next_chunk_index { + Some(idx) => (idx, false), + None => (0, true), + }; + let next_row_offset = initial_row_offset + initial_row_count; + + // Bound the window at >=1 so we always have room to push + // the chunk currently being decoded. + let max_in_memory = max_chunks_in_memory.max(1); + + let mut window = VecDeque::with_capacity(max_in_memory); + window.push_back(initial_entry); + + let inner = Arc::new(Inner { + source, + statement_id: statement_id.into(), + compression, + chunks: TokioMutex::new(window), + next_fetch_chunk_index: AtomicI64::new(next_idx), + next_fetch_row_offset: AtomicI64::new(next_row_offset), + end_of_stream: AtomicBool::new(eos), + error: TokioMutex::new(None), + max_chunks_in_memory: max_in_memory, + notify: Notify::new(), + }); + + // Spawn the prefetch task. It exits when end-of-stream is + // reached, an error fires, or the `Arc` is dropped + // (when the last consumer goes away the only Arc holder is + // the task itself — `Inner` doesn't strong-cycle, so on + // drop-of-consumer the task notices via `chunks` lock + // returning a poisoned/no-longer-served chunks deque on + // next iteration; in practice we rely on `end_of_stream` + // being set when the consumer is done). + if !eos { + let task_inner = Arc::clone(&inner); + runtime_handle.spawn(async move { + Self::prefetch_loop(task_inner).await; + }); + } + + Ok(Arc::new(Self { inner, schema })) + } + + /// Decoded schema from the first chunk. `None` if the initial + /// chunk had no batches (empty result set). + pub(crate) fn schema(&self) -> Option<&SchemaRef> { + self.schema.as_ref() + } + + /// Pull the next Arrow batch. + /// + /// - If the head chunk has batches buffered, drain one. + /// - When the head chunk is drained, pop it and notify the + /// prefetch task (window slot freed). Then loop and try again. + /// - If the window is empty and not at EOS, await the prefetch + /// task pushing the next chunk. + /// - If the window is empty and EOS is set, return `Ok(None)`. + /// - If the prefetch task recorded an error, surface it. + #[instrument(name = "inline_stream.next_batch", skip(self))] + pub(crate) async fn next_batch(&self) -> Result> { + loop { + // Check for prefetch error first — fail fast. + { + let mut err_slot = self.inner.error.lock().await; + if let Some(err) = err_slot.take() { + return Err(err); + } + } + + // Try to drain a batch from the head chunk. + { + let mut guard = self.inner.chunks.lock().await; + if let Some(head) = guard.front_mut() { + if let Some(batch) = head.batches.pop_front() { + // Still more in this chunk — return it directly. + return Ok(Some(batch)); + } + // Head chunk drained — pop it and let the + // prefetch task know there's room for one more. + let popped = guard.pop_front().unwrap(); + debug!( + "Drained inline chunk {} from rolling window; \ + {} chunks remain buffered", + popped.chunk_index, + guard.len() + ); + drop(guard); + self.inner.notify.notify_waiters(); + // Loop: there may already be more chunks in the + // window behind the popped one. + continue; + } + // Window empty. + if self.inner.end_of_stream.load(Ordering::Acquire) { + return Ok(None); + } + // Drop the lock before awaiting so the prefetch task + // can push. + drop(guard); + } + + // Wait for the prefetch task to push a chunk (or set EOS, + // or record an error). `notified()` is edge-triggered; + // capture it before the lock is dropped above ideally, + // but for now the loop's recheck-on-wake handles a race + // where the notification fires between the empty-check + // and `notified()`. + self.inner.notify.notified().await; + } + } + + /// Background loop: fetch chunks sequentially, decode, push into + /// the window. Pauses (via `notify`) when the window is full. + /// Exits on end-of-stream, error, or runtime shutdown. + async fn prefetch_loop(inner: Arc) { + loop { + // Stop if we've already hit EOS. + if inner.end_of_stream.load(Ordering::Acquire) { + debug!("inline prefetch: end-of-stream reached, task exiting"); + return; + } + + // Wait for window space if full. + loop { + let window_len = inner.chunks.lock().await.len(); + if window_len < inner.max_chunks_in_memory { + break; + } + debug!( + "inline prefetch: window full ({}/{}), pausing", + window_len, inner.max_chunks_in_memory + ); + inner.notify.notified().await; + } + + let chunk_index = inner.next_fetch_chunk_index.load(Ordering::Acquire); + let row_offset = inner.next_fetch_row_offset.load(Ordering::Acquire); + + // Issue the SEA RPC. Errors are recorded sticky; + // consumer surfaces on next `next_batch()` pull. + let fetch_result = match inner + .source + .get_inline_chunk(&inner.statement_id, chunk_index, row_offset) + .await + { + Ok(r) => r, + Err(e) => { + error!( + "inline prefetch: get_inline_chunk(chunk={}, row_offset={}) failed: {}", + chunk_index, row_offset, e + ); + *inner.error.lock().await = Some(e); + inner.end_of_stream.store(true, Ordering::Release); + inner.notify.notify_waiters(); + return; + } + }; + + // Decode synchronously. Arrow IPC parsing is fast + // (microseconds per MB on the kernel's measurements) and + // doing it here keeps the consumer hot-path zero-CPU. + let batches = match parse_arrow_ipc(&fetch_result.bytes, inner.compression) { + Ok(b) => b, + Err(e) => { + error!( + "inline prefetch: parse_arrow_ipc(chunk={}, bytes={}) failed: {}", + chunk_index, + fetch_result.bytes.len(), + e + ); + *inner.error.lock().await = Some(e); + inner.end_of_stream.store(true, Ordering::Release); + inner.notify.notify_waiters(); + return; + } + }; + + // Per the bounded SEA API contract: next-fetch state + // comes from the server's `next_chunk_index` and the + // chunk's own `row_offset + row_count`. Never synthesised. + let advance_to = fetch_result + .next_chunk_index + .unwrap_or(fetch_result.chunk_index + 1); + let next_row = fetch_result.row_offset + fetch_result.row_count; + inner + .next_fetch_chunk_index + .store(advance_to, Ordering::Release); + inner + .next_fetch_row_offset + .store(next_row, Ordering::Release); + + if fetch_result.next_chunk_index.is_none() { + inner.end_of_stream.store(true, Ordering::Release); + } + + let chunk_idx = fetch_result.chunk_index; + let batch_count = batches.len(); + + // Push the new chunk onto the window. + { + let mut guard = inner.chunks.lock().await; + guard.push_back(InlineChunkEntry { + chunk_index: chunk_idx, + batches: VecDeque::from(batches), + }); + debug!( + "inline prefetch: pushed chunk {} ({} batches); \ + window now has {} chunks; eos={}", + chunk_idx, + batch_count, + guard.len(), + inner.end_of_stream.load(Ordering::Acquire), + ); + } + inner.notify.notify_waiters(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::{Int32Array, RecordBatch}; + use arrow_ipc::writer::StreamWriter; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::atomic::AtomicUsize; + use std::sync::Mutex as StdMutex; + + /// One mock inline chunk: pre-built Arrow IPC bytes plus the + /// metadata the server would emit alongside it. + #[derive(Clone, Debug)] + struct MockChunk { + bytes: Vec, + chunk_index: i64, + row_offset: i64, + row_count: i64, + next_chunk_index: Option, + } + + /// Mock chunk-source that serves a scripted list of inline + /// chunks in order. Records the RPC count so tests can assert + /// the prefetch bound was respected. + #[derive(Debug)] + struct MockSource { + chunks: StdMutex>, + calls: AtomicUsize, + } + + impl MockSource { + fn new(chunks: Vec) -> Arc { + Arc::new(Self { + chunks: StdMutex::new(chunks), + calls: AtomicUsize::new(0), + }) + } + + fn call_count(&self) -> usize { + self.calls.load(Ordering::SeqCst) + } + } + + #[async_trait] + impl InlineChunkSource for MockSource { + async fn get_inline_chunk( + &self, + _statement_id: &str, + chunk_index: i64, + _row_offset: i64, + ) -> Result { + self.calls.fetch_add(1, Ordering::SeqCst); + let mut chunks = self.chunks.lock().unwrap(); + let position = chunks + .iter() + .position(|c| c.chunk_index == chunk_index) + .ok_or_else(|| { + Error::invalid_state() + .message(format!("mock: no chunk {} scripted", chunk_index)) + })?; + let c = chunks.remove(position); + Ok(InlineChunkFetchResult { + bytes: c.bytes, + chunk_index: c.chunk_index, + row_offset: c.row_offset, + row_count: c.row_count, + next_chunk_index: c.next_chunk_index, + }) + } + } + + fn build_ipc_bytes(values: &[i32]) -> Vec { + let schema = Arc::new(Schema::new(vec![Field::new("n", DataType::Int32, false)])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(values.to_vec()))], + ) + .unwrap(); + let mut buf = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut buf, &schema).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + buf + } + + /// Build a fixture: 3 inline chunks, indices 0/1/2, chunk 2 is + /// terminal (`next_chunk_index = None`). Chunk 0's bytes are + /// passed to `InlineStreamingProvider::new` directly as the + /// "initial attachment" — only chunks 1 and 2 are served by the + /// mock transport. + fn three_chunk_fixture() -> (Vec, MockChunk, MockChunk, MockChunk) { + let c0 = MockChunk { + bytes: build_ipc_bytes(&[1, 2, 3]), + chunk_index: 0, + row_offset: 0, + row_count: 3, + next_chunk_index: Some(1), + }; + let c1 = MockChunk { + bytes: build_ipc_bytes(&[4, 5, 6]), + chunk_index: 1, + row_offset: 3, + row_count: 3, + next_chunk_index: Some(2), + }; + let c2 = MockChunk { + bytes: build_ipc_bytes(&[7, 8, 9]), + chunk_index: 2, + row_offset: 6, + row_count: 3, + next_chunk_index: None, + }; + (c0.bytes.clone(), c0, c1, c2) + } + + fn count_rows(batches: &[RecordBatch]) -> usize { + batches.iter().map(|b| b.num_rows()).sum() + } + + #[tokio::test] + async fn streams_all_chunks_in_order() { + // Three-chunk fixture; assert all 9 rows arrive in order. + let (initial_bytes, c0, c1, c2) = three_chunk_fixture(); + let source: Arc = MockSource::new(vec![c1.clone(), c2.clone()]); + + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + initial_bytes, + c0.chunk_index, + c0.row_offset, + c0.row_count, + c0.next_chunk_index, + CompressionCodec::None, + /* max_chunks_in_memory */ 4, + tokio::runtime::Handle::current(), + ) + .expect("provider build"); + + let mut batches = Vec::new(); + while let Some(b) = provider.next_batch().await.unwrap() { + batches.push(b); + } + + assert_eq!(batches.len(), 3, "one batch per chunk"); + assert_eq!(count_rows(&batches), 9); + // Spot-check the ordering: chunk 0 has [1,2,3], chunk 2 has + // [7,8,9]; the i32 values per-row prove ordering. + let last = batches.last().unwrap(); + let arr = last + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(arr.values(), &[7, 8, 9]); + } + + #[tokio::test] + async fn respects_max_chunks_in_memory_bound() { + // Fixture is 3 chunks total. With max_chunks_in_memory = 1, + // the prefetch task must NOT race ahead and pull all chunks + // up front; it pulls one, waits for the consumer to drain, + // then pulls the next. + let (initial_bytes, c0, c1, c2) = three_chunk_fixture(); + let mock = MockSource::new(vec![c1.clone(), c2.clone()]); + let source: Arc = mock.clone(); + + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + initial_bytes, + c0.chunk_index, + c0.row_offset, + c0.row_count, + c0.next_chunk_index, + CompressionCodec::None, + /* max_chunks_in_memory */ 1, + tokio::runtime::Handle::current(), + ) + .expect("provider build"); + + // Drain everything. The kernel makes exactly 2 inline-chunk + // RPCs (for chunks 1 and 2; chunk 0 was the initial + // attachment). + let _b0 = provider.next_batch().await.unwrap().unwrap(); + let _b1 = provider.next_batch().await.unwrap().unwrap(); + let _b2 = provider.next_batch().await.unwrap().unwrap(); + let eof = provider.next_batch().await.unwrap(); + assert!(eof.is_none(), "EOS after draining all chunks"); + assert_eq!( + mock.call_count(), + 2, + "tight window must not over-fetch (chunk 0 from initial attachment + 2 RPCs)" + ); + } + + #[tokio::test] + async fn single_chunk_no_prefetch_rpcs() { + // If the initial response is the *only* chunk (next_chunk_index + // is None on the server side), the streaming provider should + // make zero RPCs. + let mock = MockSource::new(vec![]); + let source: Arc = mock.clone(); + + let initial = MockChunk { + bytes: build_ipc_bytes(&[42]), + chunk_index: 0, + row_offset: 0, + row_count: 1, + next_chunk_index: None, // single-chunk result + }; + + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + initial.bytes.clone(), + initial.chunk_index, + initial.row_offset, + initial.row_count, + initial.next_chunk_index, + CompressionCodec::None, + 4, + tokio::runtime::Handle::current(), + ) + .unwrap(); + + let b = provider.next_batch().await.unwrap().unwrap(); + assert_eq!(b.num_rows(), 1); + let eof = provider.next_batch().await.unwrap(); + assert!(eof.is_none()); + assert_eq!( + mock.call_count(), + 0, + "no inline-chunk RPC needed for a single-chunk inline result", + ); + } + + #[tokio::test] + async fn surfaces_prefetch_errors() { + // Mock the first prefetch RPC to be missing — provider + // should surface the error from `next_batch()`. + let (initial_bytes, c0, _, _) = three_chunk_fixture(); + // Empty mock → first prefetch (chunk 1) returns Err. + let source: Arc = MockSource::new(vec![]); + + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + initial_bytes, + c0.chunk_index, + c0.row_offset, + c0.row_count, + c0.next_chunk_index, + CompressionCodec::None, + 4, + tokio::runtime::Handle::current(), + ) + .unwrap(); + + // First pull yields chunk 0 (initial attachment). + let _ = provider.next_batch().await.unwrap().unwrap(); + // Second pull awaits prefetch; the prefetch task fails, + // records the error, and notifies. Consumer surfaces it. + let err = provider + .next_batch() + .await + .expect_err("prefetch failure must surface"); + assert!( + err.message.to_lowercase().contains("no chunk") + || err.message.to_lowercase().contains("chunk"), + "error mentions the missing chunk: {}", + err.message + ); + } +} diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 38258b62..2e65c80c 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -30,7 +30,7 @@ use crate::kernel_error::{Error, Result}; use crate::reader::cloudfetch::chunk_downloader::ChunkDownloader; use crate::reader::cloudfetch::link_fetcher::{SeaChunkLinkFetcher, SeaChunkLinkFetcherHandle}; use crate::reader::cloudfetch::streaming_provider::StreamingCloudFetchProvider; -use crate::reader::inline::InlineArrowProvider; +use crate::reader::inline::{InlineArrowProvider, InlineStreamingProvider}; use crate::reader::post_processor::{PostProcessOptions, ResultPostProcessor}; use crate::types::cloudfetch::{CloudFetchConfig, CloudFetchLink}; use crate::types::sea::{CompressionCodec, ResultManifest, StatementState}; @@ -178,6 +178,36 @@ impl ResultReaderFactory { // Priority 2: Inline Arrow (attachment present) if let Some(ref inline_data) = result.inline_arrow_data { if !inline_data.is_empty() { + // Multi-chunk inline-Arrow streaming path: kicks + // in when the server emitted a `next_chunk_index` + // alongside the initial inline attachment. The + // streaming provider holds a rolling window of + // pre-decoded chunks ahead of the consumer + // (bounded by `inline_max_chunks_in_memory`); each + // continuation `get_inline_chunk` carries both + // chunk_index (= prev `next_chunk_index`) and + // row_offset (= prev `row_offset + row_count`) + // per the bounded SEA API contract. + if let Some(next_idx) = result.inline_next_chunk_index { + tracing::info!( + "Using inline-Arrow streaming reader: {} bytes initial chunk, \ + next_chunk_index={}", + inline_data.len(), + next_idx, + ); + return self.create_inline_streaming_reader( + statement_id, + inline_data.clone(), + result.inline_chunk_index.unwrap_or(0), + result.inline_row_offset.unwrap_or(0), + result.inline_row_count.unwrap_or(0), + Some(next_idx), + compression, + ); + } + + // Single-chunk inline: legacy fast path, parses + // the whole result up front. tracing::info!( "Using inline Arrow reader: {} bytes of Arrow IPC data", inline_data.len() @@ -327,6 +357,49 @@ impl ResultReaderFactory { Ok(Box::new(InlineArrowReader::new(provider))) } + + /// Build a multi-chunk inline-Arrow streaming reader. + /// + /// Wraps the [`InlineStreamingProvider`] in a [`ResultReader`] + /// adapter so the rest of the kernel can treat the inline + /// streaming path identically to CloudFetch. + #[allow(clippy::too_many_arguments)] + fn create_inline_streaming_reader( + &self, + statement_id: &str, + initial_attachment: Vec, + initial_chunk_index: i64, + initial_row_offset: i64, + initial_row_count: i64, + next_chunk_index: Option, + compression: CompressionCodec, + ) -> Result> { + tracing::debug!( + "Creating inline-Arrow streaming reader: stmt={}, initial_chunk={}, \ + next_chunk={:?}, max_in_memory={}", + statement_id, + initial_chunk_index, + next_chunk_index, + self.config.inline_max_chunks_in_memory, + ); + + let source: Arc = + Arc::new(self.client.clone()); + let provider = InlineStreamingProvider::new( + source, + statement_id.to_string(), + initial_attachment, + initial_chunk_index, + initial_row_offset, + initial_row_count, + next_chunk_index, + compression, + self.config.inline_max_chunks_in_memory, + self.runtime_handle.clone(), + )?; + + Ok(Box::new(InlineStreamingReader::new(provider))) + } } /// Trait for result readers. @@ -411,6 +484,38 @@ impl ResultReader for InlineArrowReader { } } +/// Reader for multi-chunk inline-Arrow streaming. +/// +/// Wraps [`InlineStreamingProvider`] to implement the [`ResultReader`] +/// trait. The provider's prefetch task fills a bounded rolling +/// window of decoded chunks; `next_batch` pulls one Arrow batch at +/// a time from the head of that window. +struct InlineStreamingReader { + provider: Arc, + /// Cached schema (extracted from the initial chunk). + schema: Option, +} + +impl InlineStreamingReader { + fn new(provider: Arc) -> Self { + let schema = provider.schema().cloned(); + Self { provider, schema } + } +} + +#[async_trait] +impl ResultReader for InlineStreamingReader { + async fn schema(&self) -> Result { + self.schema.clone().ok_or_else(|| { + Error::invalid_state().message("Schema not available for inline-Arrow streaming result") + }) + } + + async fn next_batch(&mut self) -> Result> { + self.provider.next_batch().await + } +} + /// In-memory result reader. /// /// Yields a fixed `Vec` from memory, one batch per call diff --git a/src/session.rs b/src/session.rs index 799edb88..9d07facf 100644 --- a/src/session.rs +++ b/src/session.rs @@ -633,6 +633,7 @@ fn result_to_cloudfetch_config( enabled: result.cloudfetch_enabled, link_prefetch_window: result.cloudfetch_link_prefetch_window, max_chunks_in_memory: result.cloudfetch_max_chunks_in_memory, + inline_max_chunks_in_memory: result.inline_max_chunks_in_memory, ..Default::default() } } diff --git a/src/types/cloudfetch.rs b/src/types/cloudfetch.rs index 6333c572..c18fd452 100644 --- a/src/types/cloudfetch.rs +++ b/src/types/cloudfetch.rs @@ -54,6 +54,12 @@ pub struct CloudFetchConfig { /// When > 0, consecutive small batches are concatenated into larger batches /// of approximately this many rows before being served to consumers. pub batch_merge_target_rows: usize, + /// Rolling-window bound for the multi-chunk inline-Arrow path + /// (used when CloudFetch is disabled at the session level via + /// `can_cloud_download=false`). Analogue of + /// [`Self::max_chunks_in_memory`] but for sequential inline + /// prefetches rather than parallel cloud downloads. + pub inline_max_chunks_in_memory: usize, } impl Default for CloudFetchConfig { @@ -69,6 +75,7 @@ impl Default for CloudFetchConfig { speed_threshold_mbps: 0.1, enabled: true, batch_merge_target_rows: 0, + inline_max_chunks_in_memory: 4, } } } diff --git a/src/types/sea.rs b/src/types/sea.rs index 0608363e..a93fb3d3 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -385,6 +385,12 @@ pub struct GetChunksResponse { pub next_chunk_index: Option, #[serde(default)] pub external_links: Option>, + /// Inline Arrow IPC bytes (base64-decoded by serde) for the + /// inline-Arrow streaming path. Populated when the server + /// returns chunks inline rather than via CloudFetch — i.e. when + /// the session was opened with `can_cloud_download=false`. + #[serde(default, deserialize_with = "deserialize_base64_attachment")] + pub attachment: Option>, } #[cfg(test)] From 3e7d21cd9bf3ef6a52e21e51e78343dafa001bec Mon Sep 17 00:00:00 2001 From: Gopal Lal Date: Mon, 25 May 2026 22:10:06 +0530 Subject: [PATCH 2/4] =?UTF-8?q?review(pr71):=20address=20P0/P1/P2=20feedba?= =?UTF-8?q?ck=20=E2=80=94=20mpsc=20rewrite,=20schema=20fallback,=20rollout?= =?UTF-8?q?=20guard?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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, 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 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 --- src/client/sea.rs | 62 ++- src/reader/inline/streaming.rs | 846 ++++++++++++++++++++++----------- src/reader/mod.rs | 64 +++ 3 files changed, 662 insertions(+), 310 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index 355aa4b0..c3062974 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -832,26 +832,25 @@ impl Transport for SeaRestTransport { // Same endpoint as CloudFetch chunk-link fetching, but on // the inline-Arrow path the response carries Arrow IPC bytes // in `attachment` instead of `external_links`. `row_offset` - // is sent as a query parameter — required from drivers per - // the bounded SEA API contract (and explicitly required for - // the SEA inline-Arrow path that ThriftServer routes via - // FETCH_ABSOLUTE). - let url = if row_offset > 0 { - format!( - "{}/statements/{}/result/chunks/{}?row_offset={}", - self.base_url(), - statement_id, - chunk_index, - row_offset - ) - } else { - format!( - "{}/statements/{}/result/chunks/{}", - self.base_url(), - statement_id, - chunk_index - ) - }; + // is sent unconditionally on the inline path — required + // from drivers per the bounded SEA API contract, and the + // ThriftServer `FETCH_ABSOLUTE` cursor needs it to find + // the right row even when row_offset == 0 (the first + // chunk of a paginated inline result is still a fetch + // with row_offset = 0; omitting the parameter would be + // ambiguous from the server's perspective). + debug_assert!( + row_offset >= 0, + "row_offset must be non-negative on the SEA wire (got {row_offset})", + ); + let row_offset = row_offset.max(0); + let url = format!( + "{}/statements/{}/result/chunks/{}?row_offset={}", + self.base_url(), + statement_id, + chunk_index, + row_offset, + ); debug!( "Getting inline chunk {} at {} (row_offset={})", @@ -897,11 +896,28 @@ impl Transport for SeaRestTransport { // Per the bounded SEA API contract, the chunk metadata we // need is on the response itself (top-level, not nested). - // Defaults are defensive: if the server omits these we still - // surface a usable chunk but with conservative metadata. + // + // `chunk_index` and `row_offset`: fall back to the values + // we sent in the request — the server is supposed to echo + // them back, but a missing field can be reconstructed from + // the request without ambiguity. + // + // `row_count`: cannot be defaulted. A missing `row_count` + // on a response that DOES carry an attachment is a server + // contract violation; defaulting it to 0 would silently + // corrupt the next-fetch row_offset (we compute + // `row_offset + row_count` for the continuation). Surface + // as `data_loss` so the consumer sees a typed error rather + // than silently-dropped rows. let chunk_idx = chunks_response.chunk_index.unwrap_or(chunk_index); let returned_row_offset = chunks_response.row_offset.unwrap_or(row_offset); - let row_count = chunks_response.row_count.unwrap_or(0); + let row_count = chunks_response.row_count.ok_or_else(|| { + Error::data_loss().message(format!( + "Inline chunk {} response carries `attachment` but no `row_count` — \ + cannot derive next-fetch row_offset safely. Body: {}", + chunk_idx, body, + )) + })?; let next_chunk_index = chunks_response.next_chunk_index; debug!( diff --git a/src/reader/inline/streaming.rs b/src/reader/inline/streaming.rs index 4678bbb0..861f3be0 100644 --- a/src/reader/inline/streaming.rs +++ b/src/reader/inline/streaming.rs @@ -21,26 +21,38 @@ //! consumer so the per-chunk SEA round-trip latency is hidden behind //! `RecordBatch` iteration. //! -//! ## Design (modelled on JDBC's `StreamingChunkProvider`) +//! ## Coordination //! -//! ```text -//! Server Prefetch task Consumer -//! ────── ───────────── ──────── -//! fetch chunk N ──┐ -//! responds with bytes ──> decode IPC │ -//! push to window ──┘──> [chunk N][chunk N+1]... -//! (until window full) │ -//! │ -//! pull batch ◄── caller -//! ``` +//! The producer (background prefetch task) and the consumer (kernel +//! caller pulling batches) communicate through a bounded +//! `tokio::sync::mpsc` channel: //! -//! - One sequential prefetch task (the SEA inline contract is "one -//! `GetResultData` at a time" — there's no parallel download). -//! - Bounded by `max_chunks_in_memory` (analogous to -//! `ResultConfig::cloudfetch_max_chunks_in_memory`). -//! - When the consumer drains a chunk's batches, the entry is -//! popped, freeing a slot. A `Notify` wakes the prefetch task so -//! it can pull the next chunk in. +//! - Sender: prefetch task pushes one `Result` per +//! chunk. Channel capacity gives the rolling-window bound. +//! - Receiver: consumer awaits one entry at a time, then walks its +//! batches synchronously. +//! +//! Why mpsc and not `Notify`: `tokio::sync::Notify::notify_waiters()` +//! does NOT buffer permits. If the consumer drops a lock and the +//! prefetch pushes+notifies before the consumer calls +//! `.notified().await`, the wake is lost and the consumer hangs +//! forever. mpsc's `send`/`recv` handle the wake correctly out of the +//! box and add natural backpressure when the channel fills. +//! +//! Why one channel of `Result<...>` instead of separate data/error +//! signals: errors become sticky for free — the prefetch task drops +//! its sender after sending the error, so the receiver gets the +//! `Err`, and every subsequent `recv()` returns `None` (channel +//! closed) which we map to a recorded sticky error so consumers can't +//! "scroll past" a transport failure. +//! +//! ## Cancellation / cleanup +//! +//! The provider stores the `JoinHandle` of its prefetch task and +//! aborts it in `Drop`. Dropping the receiver also makes +//! `Sender::send().await` return `Err`, causing the task's next loop +//! iteration to exit naturally; the explicit `abort()` covers the +//! case where the task is blocked on the SEA RPC itself. //! //! ## Bounded SEA API contract //! @@ -57,10 +69,9 @@ use crate::types::sea::CompressionCodec; use arrow_array::RecordBatch; use arrow_schema::SchemaRef; use async_trait::async_trait; -use std::collections::VecDeque; -use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; use std::sync::Arc; -use tokio::sync::{Mutex as TokioMutex, Notify}; +use tokio::sync::{mpsc, Mutex as TokioMutex}; +use tokio::task::JoinHandle; use tracing::{debug, error, instrument}; /// Narrow source trait for inline-chunk fetches. @@ -95,70 +106,59 @@ impl InlineChunkSource for Arc { #[derive(Debug)] struct InlineChunkEntry { chunk_index: i64, - /// Decoded Arrow batches, drained one at a time by `next_batch`. - /// `VecDeque` so we can `pop_front` in O(1). - batches: VecDeque, + /// Decoded Arrow batches. Iterating left to right; we drain by + /// `.into_iter()` once we own the entry on the consumer side, so + /// no shared interior mutability is needed. + batches: Vec, } -/// Shared state between the prefetch task and the consumer. +/// Multi-chunk inline-Arrow streaming provider. /// -/// `Arc` so the spawned task holds its own clone without -/// keeping the provider alive past stream end. -#[derive(Debug)] -struct Inner { - source: Arc, - statement_id: String, - compression: CompressionCodec, +/// Holds the receiver for the prefetch task's chunk channel and a +/// sticky-error slot for surfacing prefetch failures to callers that +/// have already observed at least one error. +pub(crate) struct InlineStreamingProvider { + /// Consumer state. `TokioMutex` because `next_batch(&self)` takes + /// `&self` for ergonomics (the kernel's `ResultReader` trait takes + /// `&mut self`, but we wrap this in an `Arc` + /// for spawned-task safety on the prefetch side; consumers are + /// single-threaded in practice). + consumer: TokioMutex, + + /// Cached schema. Set on construction from either the initial + /// chunk's first batch OR — when the initial chunk is empty — + /// the manifest. `None` only when both sources are empty (legal + /// for a truly empty result set). + schema: Option, - /// Rolling window of pre-decoded chunks, ordered by `chunk_index`. - /// Pushed to the back by the prefetch task; drained from the - /// front by the consumer. - /// - /// A `TokioMutex` (not `std::sync::Mutex`) so the consumer can - /// `.await` while holding it would be a footgun — we deliberately - /// only hold the lock for the duration of a `pop` or `push_back`. - chunks: TokioMutex>, - - /// `chunk_index` to ask for in the next `get_inline_chunk` call. - /// Initialised from the initial response; updated each prefetch - /// from the server-emitted `next_chunk_index`. - next_fetch_chunk_index: AtomicI64, - - /// Row offset to send on the next `get_inline_chunk` call. - /// Initialised + updated alongside `next_fetch_chunk_index`. - next_fetch_row_offset: AtomicI64, - - /// End-of-stream sentinel — flipped when the *previously fetched - /// chunk* had `next_chunk_index = None`. Once set, no further - /// prefetch is issued; the consumer drains the remaining - /// `chunks` window and then sees EOF. - end_of_stream: AtomicBool, - - /// First-error sticky slot. The prefetch task records its first - /// failure here; the consumer surfaces it on the next pull. - /// Once set, the task exits — the kernel does not retry the SEA - /// path here (HTTP-level retries already happened inside the - /// transport). - error: TokioMutex>, - - /// Bound on the rolling window. - max_chunks_in_memory: usize, - - /// Bell for the consumer ↔ prefetch handshake: - /// - /// - Prefetch task notifies when it pushes a chunk or sets an - /// error / EOF. - /// - Consumer notifies when it pops a chunk (so prefetch can - /// resume if the window was full). - notify: Notify, + /// JoinHandle of the prefetch task. `Some(handle)` while the + /// task is running; `take()`n and `abort()`ed in `Drop`. + prefetch_handle: TokioMutex>>, } -/// Multi-chunk inline-Arrow streaming provider. -#[derive(Debug)] -pub(crate) struct InlineStreamingProvider { - inner: Arc, - /// Cached schema. Set when the first batch is decoded. - schema: Option, +impl std::fmt::Debug for InlineStreamingProvider { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("InlineStreamingProvider") + .field("schema_present", &self.schema.is_some()) + .finish_non_exhaustive() + } +} + +/// Consumer-side mutable state. Wrapped in `TokioMutex` so +/// `next_batch(&self)` can mutate. +struct ConsumerState { + /// Channel of chunks pushed by the prefetch task. + rx: mpsc::Receiver>, + /// The current chunk we're walking through (if any). + current: Option, + /// Index into `current.batches` for the next batch to yield. + cursor: usize, + /// Sticky-error slot. Once the prefetch task surfaces an error + /// (or the channel closes prematurely), this is set and every + /// subsequent `next_batch()` call returns the same error rather + /// than silently transitioning to "successful EOS". Cloned for + /// each surfacing so the slot itself survives. + sticky_error: Option, } impl InlineStreamingProvider { @@ -166,25 +166,24 @@ impl InlineStreamingProvider { /// (which the kernel already received in the initial execute /// response — see `reader/mod.rs::create_inner_reader`). /// - /// The initial chunk is decoded synchronously so callers get a - /// usable schema back from `schema()` even before the background - /// prefetch task has done any work. - /// /// # Arguments - /// * `transport` — for issuing `get_inline_chunk` RPCs. + /// * `source` — for issuing `get_inline_chunk` RPCs. /// * `statement_id` — for the URL path. /// * `initial_attachment` — Arrow IPC bytes the kernel already /// has from the initial execute response. - /// * `initial_chunk_index` — the first chunk's index (0 in - /// practice; pass whatever the manifest reported). - /// * `initial_row_offset` / `initial_row_count` — same. + /// * `initial_chunk_index` / `initial_row_offset` / + /// `initial_row_count` — initial chunk metadata. /// * `next_chunk_index` — server's `next_chunk_index` on the /// initial chunk. `Some(N)` → more chunks to fetch starting at /// N; `None` → single-chunk result, no further fetches. /// * `compression` — Arrow IPC compression codec from the /// manifest. - /// * `max_chunks_in_memory` — bound on the rolling window - /// (`ResultConfig::inline_max_chunks_in_memory`). + /// * `max_chunks_in_memory` — bound on the rolling window. + /// * `manifest_schema` — fallback schema extracted from the + /// result manifest; used when the initial chunk decodes to + /// zero batches (legal on paginated results where the first + /// chunk is intentionally tiny). Pass `None` if no manifest + /// is available. /// * `runtime_handle` — for spawning the prefetch task. #[allow(clippy::too_many_arguments)] pub(crate) fn new( @@ -197,166 +196,199 @@ impl InlineStreamingProvider { next_chunk_index: Option, compression: CompressionCodec, max_chunks_in_memory: usize, + manifest_schema: Option, runtime_handle: tokio::runtime::Handle, ) -> Result> { // Decode the initial chunk synchronously so we can return a // schema-bearing provider to the caller. let initial_batches = parse_arrow_ipc(&initial_attachment, compression)?; - let schema = initial_batches.first().map(|b| b.schema()); + + // Schema source priority: + // 1. The first batch of the initial chunk (most-authoritative, + // matches what consumers will actually iterate). + // 2. The manifest-derived schema (load-bearing for + // paginated results where the initial chunk has zero + // batches — without this fallback, + // `ResultReaderAdapter::new` rejects the stream). + let schema = initial_batches + .first() + .map(|b| b.schema()) + .or(manifest_schema); let initial_entry = InlineChunkEntry { chunk_index: initial_chunk_index, - batches: VecDeque::from(initial_batches), - }; - - // Next-fetch state comes from the initial chunk's metadata. - // If `next_chunk_index` is None we are at end-of-stream - // already — the prefetch task will see the flag and exit - // without making any RPC. - let (next_idx, eos) = match next_chunk_index { - Some(idx) => (idx, false), - None => (0, true), + batches: initial_batches, }; - let next_row_offset = initial_row_offset + initial_row_count; - // Bound the window at >=1 so we always have room to push - // the chunk currently being decoded. + // Bound the window at >=1 so the channel can always accept + // at least one chunk from the prefetch task even if the + // caller passed 0 by mistake. let max_in_memory = max_chunks_in_memory.max(1); - let mut window = VecDeque::with_capacity(max_in_memory); - window.push_back(initial_entry); + // Channel capacity = max_in_memory - 1: the consumer always + // holds one chunk in `current`, so total chunks in memory = + // 1 (current) + channel.len() ≤ max_in_memory. mpsc requires + // capacity ≥ 1, so saturate at 1. + let channel_cap = max_in_memory.saturating_sub(1).max(1); + let (tx, rx) = mpsc::channel::>(channel_cap); + + let consumer = ConsumerState { + rx, + current: Some(initial_entry), + cursor: 0, + sticky_error: None, + }; - let inner = Arc::new(Inner { - source, - statement_id: statement_id.into(), - compression, - chunks: TokioMutex::new(window), - next_fetch_chunk_index: AtomicI64::new(next_idx), - next_fetch_row_offset: AtomicI64::new(next_row_offset), - end_of_stream: AtomicBool::new(eos), - error: TokioMutex::new(None), - max_chunks_in_memory: max_in_memory, - notify: Notify::new(), - }); - - // Spawn the prefetch task. It exits when end-of-stream is - // reached, an error fires, or the `Arc` is dropped - // (when the last consumer goes away the only Arc holder is - // the task itself — `Inner` doesn't strong-cycle, so on - // drop-of-consumer the task notices via `chunks` lock - // returning a poisoned/no-longer-served chunks deque on - // next iteration; in practice we rely on `end_of_stream` - // being set when the consumer is done). - if !eos { - let task_inner = Arc::clone(&inner); - runtime_handle.spawn(async move { - Self::prefetch_loop(task_inner).await; - }); - } + let prefetch_handle = if let Some(initial_next_idx) = next_chunk_index { + let statement_id = statement_id.into(); + let initial_next_row = initial_row_offset.saturating_add(initial_row_count); + let task = PrefetchTask { + source, + statement_id, + compression, + tx, + next_chunk_index: initial_next_idx, + next_row_offset: initial_next_row, + }; + Some(runtime_handle.spawn(async move { + task.run().await; + })) + } else { + // Single-chunk result: no prefetch task to spawn. Drop + // the sender so the receiver sees channel-closed + // immediately when it tries to recv after draining the + // initial chunk. + drop(tx); + None + }; - Ok(Arc::new(Self { inner, schema })) + Ok(Arc::new(Self { + consumer: TokioMutex::new(consumer), + schema, + prefetch_handle: TokioMutex::new(prefetch_handle), + })) } - /// Decoded schema from the first chunk. `None` if the initial - /// chunk had no batches (empty result set). + /// Decoded schema. `None` only when the initial chunk had zero + /// batches AND no manifest schema was provided — the truly-empty + /// result case. pub(crate) fn schema(&self) -> Option<&SchemaRef> { self.schema.as_ref() } /// Pull the next Arrow batch. /// - /// - If the head chunk has batches buffered, drain one. - /// - When the head chunk is drained, pop it and notify the - /// prefetch task (window slot freed). Then loop and try again. - /// - If the window is empty and not at EOS, await the prefetch - /// task pushing the next chunk. - /// - If the window is empty and EOS is set, return `Ok(None)`. - /// - If the prefetch task recorded an error, surface it. + /// Semantics: + /// - Drains batches from the current chunk first. + /// - When current is drained, awaits the next chunk from the + /// prefetch channel. + /// - If the prefetch task surfaced an error (via the channel), + /// the error is stored sticky: every subsequent + /// `next_batch()` call returns the same error rather than + /// silently transitioning to `Ok(None)`. This matches JDBC's + /// `StreamingChunkProvider` semantics. + /// - End-of-stream → `Ok(None)`. #[instrument(name = "inline_stream.next_batch", skip(self))] pub(crate) async fn next_batch(&self) -> Result> { + let mut state = self.consumer.lock().await; + loop { - // Check for prefetch error first — fail fast. - { - let mut err_slot = self.inner.error.lock().await; - if let Some(err) = err_slot.take() { - return Err(err); + // Drain a batch from the current chunk first — even if + // the prefetch task has set a sticky error, the + // already-buffered batches were successfully fetched + // and the consumer should receive them before the + // error surfaces. Only when no more buffered data is + // available do we consult the sticky-error slot or the + // channel. + if let Some(ref current) = state.current { + if state.cursor < current.batches.len() { + let batch = current.batches[state.cursor].clone(); + state.cursor += 1; + return Ok(Some(batch)); } + // Current chunk fully drained; advance. + debug!( + "Drained inline chunk {} ({} batches)", + current.chunk_index, + current.batches.len(), + ); + state.current = None; + state.cursor = 0; } - // Try to drain a batch from the head chunk. - { - let mut guard = self.inner.chunks.lock().await; - if let Some(head) = guard.front_mut() { - if let Some(batch) = head.batches.pop_front() { - // Still more in this chunk — return it directly. - return Ok(Some(batch)); - } - // Head chunk drained — pop it and let the - // prefetch task know there's room for one more. - let popped = guard.pop_front().unwrap(); - debug!( - "Drained inline chunk {} from rolling window; \ - {} chunks remain buffered", - popped.chunk_index, - guard.len() - ); - drop(guard); - self.inner.notify.notify_waiters(); - // Loop: there may already be more chunks in the - // window behind the popped one. - continue; + // Buffered chunk is drained. Sticky-error short- + // circuit: once we've surfaced an error, every + // subsequent call returns the same error. Consumers + // cannot scroll past a transport failure. + if let Some(ref e) = state.sticky_error { + return Err(e.clone()); + } + + // Need to recv the next chunk from the prefetch task. + match state.rx.recv().await { + Some(Ok(entry)) => { + state.current = Some(entry); + // Loop back to drain. + } + Some(Err(e)) => { + // Store sticky and surface on this call. + state.sticky_error = Some(e.clone()); + return Err(e); } - // Window empty. - if self.inner.end_of_stream.load(Ordering::Acquire) { + None => { + // Channel closed: clean EOS. return Ok(None); } - // Drop the lock before awaiting so the prefetch task - // can push. - drop(guard); } - - // Wait for the prefetch task to push a chunk (or set EOS, - // or record an error). `notified()` is edge-triggered; - // capture it before the lock is dropped above ideally, - // but for now the loop's recheck-on-wake handles a race - // where the notification fires between the empty-check - // and `notified()`. - self.inner.notify.notified().await; } } +} - /// Background loop: fetch chunks sequentially, decode, push into - /// the window. Pauses (via `notify`) when the window is full. - /// Exits on end-of-stream, error, or runtime shutdown. - async fn prefetch_loop(inner: Arc) { - loop { - // Stop if we've already hit EOS. - if inner.end_of_stream.load(Ordering::Acquire) { - debug!("inline prefetch: end-of-stream reached, task exiting"); - return; - } - - // Wait for window space if full. - loop { - let window_len = inner.chunks.lock().await.len(); - if window_len < inner.max_chunks_in_memory { - break; - } - debug!( - "inline prefetch: window full ({}/{}), pausing", - window_len, inner.max_chunks_in_memory - ); - inner.notify.notified().await; +impl Drop for InlineStreamingProvider { + fn drop(&mut self) { + // Abort the prefetch task so it stops issuing RPCs the + // consumer can no longer observe. The task may have already + // exited (EOS, error, or runtime shutdown); `abort()` on a + // finished JoinHandle is a no-op. + // + // Note: this `Drop` is sync, so we can't `.lock().await`. We + // use `try_lock` which succeeds because no other task can + // hold the lock at drop time (the provider's `Arc` count is + // zero, otherwise we wouldn't be in `Drop`). + if let Ok(mut guard) = self.prefetch_handle.try_lock() { + if let Some(handle) = guard.take() { + handle.abort(); } + } + } +} - let chunk_index = inner.next_fetch_chunk_index.load(Ordering::Acquire); - let row_offset = inner.next_fetch_row_offset.load(Ordering::Acquire); +/// Self-contained state for the background prefetch task. Holds +/// everything the task needs so the loop body has no shared +/// state with the consumer beyond the `tx` channel — easy to +/// reason about, easy to abort. +struct PrefetchTask { + source: Arc, + statement_id: String, + compression: CompressionCodec, + tx: mpsc::Sender>, + next_chunk_index: i64, + next_row_offset: i64, +} - // Issue the SEA RPC. Errors are recorded sticky; - // consumer surfaces on next `next_batch()` pull. - let fetch_result = match inner +impl PrefetchTask { + async fn run(mut self) { + loop { + // The send path naturally pauses when the channel is + // full — that's our rolling-window backpressure. If + // the receiver has been dropped (consumer gone), + // `send().await` returns `Err` and we exit cleanly. + let chunk_index = self.next_chunk_index; + let row_offset = self.next_row_offset; + + let fetch_result = match self .source - .get_inline_chunk(&inner.statement_id, chunk_index, row_offset) + .get_inline_chunk(&self.statement_id, chunk_index, row_offset) .await { Ok(r) => r, @@ -365,17 +397,36 @@ impl InlineStreamingProvider { "inline prefetch: get_inline_chunk(chunk={}, row_offset={}) failed: {}", chunk_index, row_offset, e ); - *inner.error.lock().await = Some(e); - inner.end_of_stream.store(true, Ordering::Release); - inner.notify.notify_waiters(); + let _ = self.tx.send(Err(e)).await; return; } }; - // Decode synchronously. Arrow IPC parsing is fast - // (microseconds per MB on the kernel's measurements) and + // Validate the server response. Self-loops and + // missing `next_chunk_index` on a non-terminal chunk + // would otherwise spin the prefetch loop forever. + // + // Strict-monotonic continuation: server-provided + // `next_chunk_index` MUST be > current chunk_index. + // Equal or less means the server emitted a self-loop + // (a server bug). Surface as a hard error sticky on + // the channel; do not synthesise our way past it. + if let Some(next) = fetch_result.next_chunk_index { + if next <= fetch_result.chunk_index { + let err = Error::data_loss().message(format!( + "Server returned non-monotonic next_chunk_index: \ + chunk={} next_chunk_index={}; refusing to spin", + fetch_result.chunk_index, next, + )); + error!("inline prefetch: {}", err); + let _ = self.tx.send(Err(err)).await; + return; + } + } + + // Decode synchronously. Arrow IPC parsing is fast and // doing it here keeps the consumer hot-path zero-CPU. - let batches = match parse_arrow_ipc(&fetch_result.bytes, inner.compression) { + let batches = match parse_arrow_ipc(&fetch_result.bytes, self.compression) { Ok(b) => b, Err(e) => { error!( @@ -384,51 +435,63 @@ impl InlineStreamingProvider { fetch_result.bytes.len(), e ); - *inner.error.lock().await = Some(e); - inner.end_of_stream.store(true, Ordering::Release); - inner.notify.notify_waiters(); + let _ = self.tx.send(Err(e)).await; return; } }; - // Per the bounded SEA API contract: next-fetch state - // comes from the server's `next_chunk_index` and the - // chunk's own `row_offset + row_count`. Never synthesised. - let advance_to = fetch_result - .next_chunk_index - .unwrap_or(fetch_result.chunk_index + 1); - let next_row = fetch_result.row_offset + fetch_result.row_count; - inner - .next_fetch_chunk_index - .store(advance_to, Ordering::Release); - inner - .next_fetch_row_offset - .store(next_row, Ordering::Release); - - if fetch_result.next_chunk_index.is_none() { - inner.end_of_stream.store(true, Ordering::Release); - } - let chunk_idx = fetch_result.chunk_index; let batch_count = batches.len(); - - // Push the new chunk onto the window. - { - let mut guard = inner.chunks.lock().await; - guard.push_back(InlineChunkEntry { + let server_next_idx = fetch_result.next_chunk_index; + + // Send the chunk to the consumer. If the consumer has + // dropped (Provider::drop ran), `send` returns Err + // and we exit. + if self + .tx + .send(Ok(InlineChunkEntry { chunk_index: chunk_idx, - batches: VecDeque::from(batches), - }); + batches, + })) + .await + .is_err() + { debug!( - "inline prefetch: pushed chunk {} ({} batches); \ - window now has {} chunks; eos={}", + "inline prefetch: consumer dropped while sending chunk {}; \ + task exiting", chunk_idx, - batch_count, - guard.len(), - inner.end_of_stream.load(Ordering::Acquire), ); + return; + } + + debug!( + "inline prefetch: pushed chunk {} ({} batches); \ + next_chunk_index={:?}", + chunk_idx, batch_count, server_next_idx, + ); + + // Advance next-fetch cursors. Per the bounded SEA API + // contract: the kernel MUST NOT synthesise `chunk_index + // + 1` as the continuation. We use the server-emitted + // `next_chunk_index` directly and stop on `None`. + match server_next_idx { + Some(idx) => { + self.next_chunk_index = idx; + self.next_row_offset = fetch_result + .row_offset + .saturating_add(fetch_result.row_count); + } + None => { + // End-of-stream signal from server. Drop the + // sender so the receiver gets channel-closed + // on its next recv() call — clean EOS. + debug!( + "inline prefetch: end-of-stream after chunk {}; closing channel", + chunk_idx, + ); + return; + } } - inner.notify.notify_waiters(); } } } @@ -439,11 +502,9 @@ mod tests { use arrow_array::{Int32Array, RecordBatch}; use arrow_ipc::writer::StreamWriter; use arrow_schema::{DataType, Field, Schema}; - use std::sync::atomic::AtomicUsize; + use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex as StdMutex; - /// One mock inline chunk: pre-built Arrow IPC bytes plus the - /// metadata the server would emit alongside it. #[derive(Clone, Debug)] struct MockChunk { bytes: Vec, @@ -453,9 +514,8 @@ mod tests { next_chunk_index: Option, } - /// Mock chunk-source that serves a scripted list of inline - /// chunks in order. Records the RPC count so tests can assert - /// the prefetch bound was respected. + /// Mock chunk-source. Records the RPC count so tests can assert + /// the bound was respected. #[derive(Debug)] struct MockSource { chunks: StdMutex>, @@ -519,11 +579,16 @@ mod tests { buf } - /// Build a fixture: 3 inline chunks, indices 0/1/2, chunk 2 is - /// terminal (`next_chunk_index = None`). Chunk 0's bytes are - /// passed to `InlineStreamingProvider::new` directly as the - /// "initial attachment" — only chunks 1 and 2 are served by the - /// mock transport. + fn build_empty_ipc_bytes() -> Vec { + let schema = Arc::new(Schema::new(vec![Field::new("n", DataType::Int32, false)])); + let mut buf = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut buf, &schema).unwrap(); + writer.finish().unwrap(); + } + buf + } + fn three_chunk_fixture() -> (Vec, MockChunk, MockChunk, MockChunk) { let c0 = MockChunk { bytes: build_ipc_bytes(&[1, 2, 3]), @@ -555,7 +620,6 @@ mod tests { #[tokio::test] async fn streams_all_chunks_in_order() { - // Three-chunk fixture; assert all 9 rows arrive in order. let (initial_bytes, c0, c1, c2) = three_chunk_fixture(); let source: Arc = MockSource::new(vec![c1.clone(), c2.clone()]); @@ -568,10 +632,11 @@ mod tests { c0.row_count, c0.next_chunk_index, CompressionCodec::None, - /* max_chunks_in_memory */ 4, + 4, + None, tokio::runtime::Handle::current(), ) - .expect("provider build"); + .unwrap(); let mut batches = Vec::new(); while let Some(b) = provider.next_batch().await.unwrap() { @@ -580,8 +645,6 @@ mod tests { assert_eq!(batches.len(), 3, "one batch per chunk"); assert_eq!(count_rows(&batches), 9); - // Spot-check the ordering: chunk 0 has [1,2,3], chunk 2 has - // [7,8,9]; the i32 values per-row prove ordering. let last = batches.last().unwrap(); let arr = last .column(0) @@ -593,10 +656,6 @@ mod tests { #[tokio::test] async fn respects_max_chunks_in_memory_bound() { - // Fixture is 3 chunks total. With max_chunks_in_memory = 1, - // the prefetch task must NOT race ahead and pull all chunks - // up front; it pulls one, waits for the consumer to drain, - // then pulls the next. let (initial_bytes, c0, c1, c2) = three_chunk_fixture(); let mock = MockSource::new(vec![c1.clone(), c2.clone()]); let source: Arc = mock.clone(); @@ -611,13 +670,11 @@ mod tests { c0.next_chunk_index, CompressionCodec::None, /* max_chunks_in_memory */ 1, + None, tokio::runtime::Handle::current(), ) - .expect("provider build"); + .unwrap(); - // Drain everything. The kernel makes exactly 2 inline-chunk - // RPCs (for chunks 1 and 2; chunk 0 was the initial - // attachment). let _b0 = provider.next_batch().await.unwrap().unwrap(); let _b1 = provider.next_batch().await.unwrap().unwrap(); let _b2 = provider.next_batch().await.unwrap().unwrap(); @@ -632,9 +689,6 @@ mod tests { #[tokio::test] async fn single_chunk_no_prefetch_rpcs() { - // If the initial response is the *only* chunk (next_chunk_index - // is None on the server side), the streaming provider should - // make zero RPCs. let mock = MockSource::new(vec![]); let source: Arc = mock.clone(); @@ -643,7 +697,7 @@ mod tests { chunk_index: 0, row_offset: 0, row_count: 1, - next_chunk_index: None, // single-chunk result + next_chunk_index: None, }; let provider = InlineStreamingProvider::new( @@ -656,6 +710,7 @@ mod tests { initial.next_chunk_index, CompressionCodec::None, 4, + None, tokio::runtime::Handle::current(), ) .unwrap(); @@ -664,17 +719,11 @@ mod tests { assert_eq!(b.num_rows(), 1); let eof = provider.next_batch().await.unwrap(); assert!(eof.is_none()); - assert_eq!( - mock.call_count(), - 0, - "no inline-chunk RPC needed for a single-chunk inline result", - ); + assert_eq!(mock.call_count(), 0); } #[tokio::test] async fn surfaces_prefetch_errors() { - // Mock the first prefetch RPC to be missing — provider - // should surface the error from `next_batch()`. let (initial_bytes, c0, _, _) = three_chunk_fixture(); // Empty mock → first prefetch (chunk 1) returns Err. let source: Arc = MockSource::new(vec![]); @@ -689,6 +738,7 @@ mod tests { c0.next_chunk_index, CompressionCodec::None, 4, + None, tokio::runtime::Handle::current(), ) .unwrap(); @@ -702,10 +752,232 @@ mod tests { .await .expect_err("prefetch failure must surface"); assert!( - err.message.to_lowercase().contains("no chunk") - || err.message.to_lowercase().contains("chunk"), + err.message.to_lowercase().contains("chunk"), "error mentions the missing chunk: {}", err.message ); } + + #[tokio::test] + async fn sticky_error_persists_across_calls() { + // P1 #3 regression guard. After an error is surfaced once, + // subsequent next_batch() calls must return the same error, + // NOT silently transition to Ok(None) (which would lie to + // consumers about result completeness). + let (initial_bytes, c0, _, _) = three_chunk_fixture(); + let source: Arc = MockSource::new(vec![]); + + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + initial_bytes, + c0.chunk_index, + c0.row_offset, + c0.row_count, + c0.next_chunk_index, + CompressionCodec::None, + 4, + None, + tokio::runtime::Handle::current(), + ) + .unwrap(); + + // Drain chunk 0. + let _ = provider.next_batch().await.unwrap().unwrap(); + // First failed call. + let err1 = provider.next_batch().await.unwrap_err(); + // Subsequent calls must keep failing. + let err2 = provider.next_batch().await.unwrap_err(); + let err3 = provider.next_batch().await.unwrap_err(); + assert_eq!(err1.message, err2.message); + assert_eq!(err2.message, err3.message); + } + + #[tokio::test] + async fn rejects_non_monotonic_next_chunk_index() { + // P1 #4 regression guard. If the server emits a self-loop + // (`next_chunk_index <= chunk_index`), the prefetch task + // would otherwise spin forever. Must surface as a sticky + // data_loss error. + let (initial_bytes, c0, _, _) = three_chunk_fixture(); + let bad_chunk = MockChunk { + bytes: build_ipc_bytes(&[10]), + chunk_index: 1, + row_offset: 3, + row_count: 1, + next_chunk_index: Some(1), // self-loop + }; + let source: Arc = MockSource::new(vec![bad_chunk]); + + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + initial_bytes, + c0.chunk_index, + c0.row_offset, + c0.row_count, + c0.next_chunk_index, + CompressionCodec::None, + 4, + None, + tokio::runtime::Handle::current(), + ) + .unwrap(); + + // Drain chunk 0 (initial attachment) — succeeds. + let _ = provider.next_batch().await.unwrap().unwrap(); + // The prefetch task validates `next_chunk_index > + // chunk_index` BEFORE sending the chunk through the + // channel — a self-loop is fail-fast, the consumer never + // sees chunk 1's data. The next pull surfaces the error. + let err = provider.next_batch().await.unwrap_err(); + assert!( + err.message + .to_lowercase() + .contains("non-monotonic next_chunk_index"), + "error should call out the self-loop: {}", + err.message, + ); + } + + #[tokio::test] + async fn manifest_schema_fallback_when_initial_chunk_empty() { + // P1 #8 regression guard. When the initial chunk decodes to + // zero batches (legal on paginated results), the provider + // must fall back to the manifest-derived schema. Without + // the fallback, schema() returns None forever and + // ResultReaderAdapter::new rejects the stream. + let manifest_schema = Arc::new(Schema::new(vec![ + Field::new("colA", DataType::Int32, false), + Field::new("colB", DataType::Int32, true), + ])); + + let empty_bytes = build_empty_ipc_bytes(); + let source: Arc = MockSource::new(vec![]); + + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + empty_bytes, + 0, + 0, + 0, + None, // single-chunk empty result + CompressionCodec::None, + 4, + Some(manifest_schema.clone()), + tokio::runtime::Handle::current(), + ) + .unwrap(); + + let schema = provider + .schema() + .expect("manifest fallback must produce a schema"); + assert_eq!(schema.fields().len(), 2); + assert_eq!(schema.field(0).name(), "colA"); + assert_eq!(schema.field(1).name(), "colB"); + } + + #[tokio::test] + async fn prefetch_task_exits_when_consumer_drops() { + // P0 #2 regression guard. The prefetch task must not keep + // RPC-ing after the consumer has dropped the provider. + // mpsc-based design gives us this for free: when the + // receiver drops, the next `tx.send().await` returns Err + // and the task exits. + let (initial_bytes, c0, c1, c2) = three_chunk_fixture(); + let mock = MockSource::new(vec![c1.clone(), c2.clone()]); + let source: Arc = mock.clone(); + + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + initial_bytes, + c0.chunk_index, + c0.row_offset, + c0.row_count, + c0.next_chunk_index, + CompressionCodec::None, + /* max_chunks_in_memory = */ 1, + None, + tokio::runtime::Handle::current(), + ) + .unwrap(); + + // Pull only the first batch (initial attachment); the + // prefetch task is now blocked trying to send chunk 1 into + // the bounded channel. + let _ = provider.next_batch().await.unwrap().unwrap(); + // Drop the provider. The Drop impl aborts the prefetch + // task; the mpsc channel close path would also exit it on + // the next loop iteration. + drop(provider); + + // Give tokio a moment to actually run the abort. Without + // this yield the test would be flaky because abort() is + // asynchronous (it sets a cancellation flag the task + // checks at await points). + tokio::task::yield_now().await; + tokio::task::yield_now().await; + + // The prefetch task at most made one more RPC (the one in + // flight when we dropped). It must not have made more. + let calls_after_drop = mock.call_count(); + // Give a generous timeout — if the task were really still + // running, it would have made ALL the remaining calls (2 + // in this fixture) in the next few millis. + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + let calls_after_wait = mock.call_count(); + assert!( + calls_after_wait <= calls_after_drop + 1, + "prefetch task kept RPC-ing after consumer drop: \ + {} calls right after drop, {} after a 50ms wait", + calls_after_drop, + calls_after_wait, + ); + } + + #[tokio::test] + async fn lost_wake_race_does_not_hang() { + // P0 #1 regression guard. With the old Notify-based + // implementation, a tight push/pop loop could lose the + // wake-up between the consumer's empty-check and the + // notified().await. With mpsc, recv() handles the wake + // correctly and this test completes cleanly. + // + // We exercise the race by setting max_chunks_in_memory = 1 + // (channel capacity 1) and draining as fast as possible. + let (initial_bytes, c0, c1, c2) = three_chunk_fixture(); + let source: Arc = MockSource::new(vec![c1.clone(), c2.clone()]); + + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + initial_bytes, + c0.chunk_index, + c0.row_offset, + c0.row_count, + c0.next_chunk_index, + CompressionCodec::None, + 1, + None, + tokio::runtime::Handle::current(), + ) + .unwrap(); + + let drain = async { + let mut total = 0; + while let Some(b) = provider.next_batch().await.unwrap() { + total += b.num_rows(); + } + total + }; + + // 5s timeout — old impl could hang forever; new impl + // completes in microseconds. + let total = tokio::time::timeout(std::time::Duration::from_secs(5), drain) + .await + .expect("must complete within 5s — lost-wake hang detected"); + assert_eq!(total, 9); + } } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 2e65c80c..f6b34b97 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -188,6 +188,33 @@ impl ResultReaderFactory { // chunk_index (= prev `next_chunk_index`) and // row_offset (= prev `row_offset + row_count`) // per the bounded SEA API contract. + // + // Rollout-skew guard: a pre-rollout server may + // emit a multi-chunk inline-Arrow result without + // populating `next_chunk_index` on the + // attachment-bearing response. The manifest's + // (deprecated but still emitted) `total_chunk_count` + // distinguishes that case from a genuinely + // single-chunk result. When the per-link signal + // is absent but `total_chunk_count > 1`, we + // refuse to silently truncate — instead surface + // a clear error so the rollout asymmetry is + // visible. Mirrors the PR #68 transition-period + // fix on CloudFetch. + let total_chunks = response.manifest.as_ref().and_then(|m| m.total_chunk_count); + if result.inline_next_chunk_index.is_none() + && total_chunks.is_some_and(|t| t > 1) + { + return Err(Error::data_loss().message(format!( + "Inline-Arrow response is missing per-chunk \ + next_chunk_index but the manifest reports \ + total_chunk_count={}. Likely cause: server has not \ + rolled out the bounded SEA API per-chunk \ + continuation field. Refusing to silently truncate \ + a multi-chunk result.", + total_chunks.unwrap(), + ))); + } if let Some(next_idx) = result.inline_next_chunk_index { tracing::info!( "Using inline-Arrow streaming reader: {} bytes initial chunk, \ @@ -195,6 +222,25 @@ impl ResultReaderFactory { inline_data.len(), next_idx, ); + // Pass the manifest-derived schema as a + // fallback for the case where the initial + // chunk decodes to zero batches (paginated + // results sometimes ship an empty leading + // chunk). Without this, `schema()` would + // return `None` and downstream wrappers + // would reject the stream. + let manifest_schema = response.manifest.as_ref().and_then(|m| { + match self.extract_schema_from_manifest(Some(m)) { + Ok(s) => Some(s), + Err(e) => { + tracing::warn!( + "Failed to extract manifest schema for inline-Arrow \ + streaming fallback; proceeding without it: {e}" + ); + None + } + } + }); return self.create_inline_streaming_reader( statement_id, inline_data.clone(), @@ -203,6 +249,7 @@ impl ResultReaderFactory { result.inline_row_count.unwrap_or(0), Some(next_idx), compression, + manifest_schema, ); } @@ -363,6 +410,10 @@ impl ResultReaderFactory { /// Wraps the [`InlineStreamingProvider`] in a [`ResultReader`] /// adapter so the rest of the kernel can treat the inline /// streaming path identically to CloudFetch. + /// + /// `manifest_schema` is forwarded to the provider as a fallback + /// for the case where the initial chunk decodes to zero + /// batches. See the comment at the call-site for context. #[allow(clippy::too_many_arguments)] fn create_inline_streaming_reader( &self, @@ -373,6 +424,7 @@ impl ResultReaderFactory { initial_row_count: i64, next_chunk_index: Option, compression: CompressionCodec, + manifest_schema: Option, ) -> Result> { tracing::debug!( "Creating inline-Arrow streaming reader: stmt={}, initial_chunk={}, \ @@ -383,6 +435,17 @@ impl ResultReaderFactory { self.config.inline_max_chunks_in_memory, ); + // Note: `Arc::new(self.client.clone())` produces + // `Arc>` because the blanket impl of + // `InlineChunkSource` is on `Arc` (not on + // `dyn Transport`), and trait-objects of different traits + // don't share a vtable so direct coercion + // `Arc` → `Arc` + // isn't legal. The outer `Arc::new` is the price of using a + // narrow trait so test mocks don't have to stub the full + // 20-method `Transport` surface; net cost is one extra + // pointer + one extra deref per RPC, negligible vs the SEA + // round-trip. let source: Arc = Arc::new(self.client.clone()); let provider = InlineStreamingProvider::new( @@ -395,6 +458,7 @@ impl ResultReaderFactory { next_chunk_index, compression, self.config.inline_max_chunks_in_memory, + manifest_schema, self.runtime_handle.clone(), )?; From 0d8468538174298cbb1a4bfed725f6b439cc8a04 Mon Sep 17 00:00:00 2001 From: Gopal Lal Date: Mon, 25 May 2026 22:45:44 +0530 Subject: [PATCH 3/4] review(pr71-r2): backpressure test, rollout-guard test, initial-response strictness MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/reader/inline/streaming.rs | 110 +++++++++ src/reader/mod.rs | 402 +++++++++++++++++++++++++++++++-- 2 files changed, 497 insertions(+), 15 deletions(-) diff --git a/src/reader/inline/streaming.rs b/src/reader/inline/streaming.rs index 861f3be0..a8d334f4 100644 --- a/src/reader/inline/streaming.rs +++ b/src/reader/inline/streaming.rs @@ -426,6 +426,17 @@ impl PrefetchTask { // Decode synchronously. Arrow IPC parsing is fast and // doing it here keeps the consumer hot-path zero-CPU. + // + // **Performance note:** on the current-thread tokio + // runtime, large LZ4-compressed chunks could starve + // the consumer task during decode. Today's perf + // measurements (per PR #67) show ~1-5 ms per 20 MB + // uncompressed Arrow IPC chunk — well inside the + // typical 10 ms responsiveness budget. If LZ4 push + // that into the tens-of-ms range, wrap this in + // `tokio::task::spawn_blocking` (the cost is one + // extra mpsc-channel-hop's worth of latency). Defer + // pending measurements that justify the complexity. let batches = match parse_arrow_ipc(&fetch_result.bytes, self.compression) { Ok(b) => b, Err(e) => { @@ -980,4 +991,103 @@ mod tests { .expect("must complete within 5s — lost-wake hang detected"); assert_eq!(total, 9); } + + /// Backpressure regression guard (PR #71 round-2, B-1). + /// + /// Pulls one batch (draining the initial chunk's only batch), + /// then sleeps long enough for the prefetch task to fill the + /// channel and block on `tx.send().await`. Asserts that the + /// RPC count plateaus at the expected bound *and stays there* + /// during the pause — proving the bounded channel is gating + /// the prefetch task, not letting it race ahead. Then resumes + /// draining and verifies the remaining chunks arrive. + /// + /// Without backpressure, the prefetch task would speedrun the + /// fixture during the sleep and `call_count` would be the + /// total chunks, not the bound. + #[tokio::test] + async fn slow_consumer_observes_backpressure_plateau() { + // Five-chunk fixture so there's room for multiple prefetched + // chunks to fit in a small channel and several to be left + // pending behind it. + let initial_bytes = build_ipc_bytes(&[1]); + let mut server_chunks: Vec = Vec::new(); + for i in 1..5 { + server_chunks.push(MockChunk { + bytes: build_ipc_bytes(&[(i as i32) + 1]), + chunk_index: i, + row_offset: i, + row_count: 1, + next_chunk_index: if i < 4 { Some(i + 1) } else { None }, + }); + } + let mock = MockSource::new(server_chunks); + let source: Arc = mock.clone(); + + // max_chunks_in_memory = 2 → channel capacity = 1. So at + // any moment the prefetch task has at most: 1 chunk in + // the consumer's `current`, 1 chunk in the channel, 1 + // chunk being prepared (sent but the sender call is what + // blocks). After the consumer drains the first chunk and + // pauses, prefetch makes 2 RPCs and then blocks on + // `tx.send().await` for the 3rd. + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + initial_bytes, + 0, // initial_chunk_index + 0, // initial_row_offset + 1, // initial_row_count + Some(1), + CompressionCodec::None, + /* max_chunks_in_memory = */ 2, + None, + tokio::runtime::Handle::current(), + ) + .unwrap(); + + // Drain the initial chunk (1 batch). After this, the + // prefetch task can start filling the channel. + let _b0 = provider.next_batch().await.unwrap().unwrap(); + + // Sleep long enough for the prefetch task to fill the + // channel and block on send. The channel capacity is 1, so + // after this the task should have made exactly 1 RPC (chunk + // 1, currently sitting in the channel) and be blocked + // trying to send chunk 2. + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + let calls_at_plateau = mock.call_count(); + + // Sleep again. If the channel were truly bounded, the RPC + // count should NOT increase further during this pause. + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + let calls_after_more_sleep = mock.call_count(); + + assert_eq!( + calls_at_plateau, calls_after_more_sleep, + "backpressure regression: RPC count climbed during \ + consumer pause ({} → {}) — channel is unbounded or \ + capacity exceeds the configured max_chunks_in_memory", + calls_at_plateau, calls_after_more_sleep, + ); + // And the count is bounded: max 2 RPCs queued (one in the + // channel, one being prepared to send). Anything more + // means we leaked the bound. + assert!( + calls_at_plateau <= 2, + "prefetch task raced past the channel bound: \ + {} RPCs while consumer paused (expected ≤ 2)", + calls_at_plateau, + ); + + // Resume draining; everything should still arrive + // correctly. This proves backpressure didn't cause a + // permanent stall. + let mut total_batches = 1; // already drained chunk 0 + while let Some(_b) = provider.next_batch().await.unwrap() { + total_batches += 1; + } + assert_eq!(total_batches, 5, "all 5 chunks must arrive after resume"); + assert_eq!(mock.call_count(), 4, "exactly 4 RPCs total (chunks 1-4)"); + } } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index f6b34b97..0a50c44e 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -202,20 +202,53 @@ impl ResultReaderFactory { // visible. Mirrors the PR #68 transition-period // fix on CloudFetch. let total_chunks = response.manifest.as_ref().and_then(|m| m.total_chunk_count); - if result.inline_next_chunk_index.is_none() - && total_chunks.is_some_and(|t| t > 1) - { - return Err(Error::data_loss().message(format!( - "Inline-Arrow response is missing per-chunk \ - next_chunk_index but the manifest reports \ - total_chunk_count={}. Likely cause: server has not \ - rolled out the bounded SEA API per-chunk \ - continuation field. Refusing to silently truncate \ - a multi-chunk result.", - total_chunks.unwrap(), - ))); + if result.inline_next_chunk_index.is_none() { + if let Some(total) = total_chunks { + if total > 1 { + return Err(Error::data_loss().message(format!( + "Inline-Arrow response is missing per-chunk \ + next_chunk_index but the manifest reports \ + total_chunk_count={}. Likely cause: server has not \ + rolled out the bounded SEA API per-chunk \ + continuation field. Refusing to silently truncate \ + a multi-chunk result.", + total, + ))); + } + } } if let Some(next_idx) = result.inline_next_chunk_index { + // Strict: when the server has opted into the + // multi-chunk streaming path (signalled by + // emitting `next_chunk_index`), the per-chunk + // metadata MUST be present too. Defaulting + // `row_count` to 0 would silently corrupt the + // next-fetch row_offset (we compute + // `row_offset + row_count` for the + // continuation). Symmetric with the strict + // handling in `sea.rs::get_inline_chunk` for + // continuation responses. + let inline_chunk_index = result.inline_chunk_index.ok_or_else(|| { + Error::data_loss().message( + "Inline-Arrow initial response has \ + next_chunk_index but is missing chunk_index — \ + server contract violation", + ) + })?; + let inline_row_offset = result.inline_row_offset.ok_or_else(|| { + Error::data_loss().message( + "Inline-Arrow initial response has \ + next_chunk_index but is missing row_offset — \ + server contract violation", + ) + })?; + let inline_row_count = result.inline_row_count.ok_or_else(|| { + Error::data_loss().message( + "Inline-Arrow initial response has \ + next_chunk_index but is missing row_count — \ + cannot derive next-fetch row_offset safely", + ) + })?; tracing::info!( "Using inline-Arrow streaming reader: {} bytes initial chunk, \ next_chunk_index={}", @@ -244,9 +277,9 @@ impl ResultReaderFactory { return self.create_inline_streaming_reader( statement_id, inline_data.clone(), - result.inline_chunk_index.unwrap_or(0), - result.inline_row_offset.unwrap_or(0), - result.inline_row_count.unwrap_or(0), + inline_chunk_index, + inline_row_offset, + inline_row_count, Some(next_idx), compression, manifest_schema, @@ -1249,4 +1282,343 @@ mod tests { // ManifestAugmentingReader behaviour is now covered by // `post_processor::tests` — the wrapper itself was folded into // `ResultPostProcessor`. + + // ────────────────────────────────────────────────────────────── + // ResultReaderFactory::create_inner_reader — rollout-guard and + // initial-response strictness tests (PR #71 round-2 feedback + // B-2, B-3). + // + // The rollout-guard fires before any Transport method is + // called, so the test only needs a `Transport` impl that + // compiles. We use a panicking stub. + // ────────────────────────────────────────────────────────────── + + use crate::client::{ + ChunkLinkFetchResult, DatabricksHttpClient, ExecuteResponse, ExecuteResult, + ExecuteResultData, HttpClientConfig, InlineChunkFetchResult, SessionInfo, TransportConfig, + }; + use crate::kernel_error::ErrorCode; + use crate::reader::post_processor::PostProcessOptions; + use crate::types::sea::{ExecuteParams, ServiceError, StatementStatus}; + use std::collections::HashMap; + + /// Transport stub that panics on every method. Adequate for + /// tests that exercise the *factory's* synchronous control + /// flow before any RPC fires (e.g. the rollout-skew guard). + #[derive(Debug)] + struct PanickingTransport; + + #[async_trait] + impl Transport for PanickingTransport { + async fn create_session( + &self, + _: Option<&str>, + _: Option<&str>, + _: HashMap, + ) -> Result { + unreachable!("PanickingTransport: not used by these tests") + } + async fn delete_session(&self, _: &str) -> Result<()> { + unreachable!() + } + async fn execute_statement( + &self, + _: &str, + _: &str, + _: &ExecuteParams, + ) -> Result { + unreachable!() + } + async fn submit_statement( + &self, + _: &str, + _: &str, + _: &ExecuteParams, + ) -> Result { + unreachable!() + } + async fn fetch_completed_result(&self, _: &str) -> Result> { + unreachable!() + } + async fn statement_status(&self, _: &str) -> Result { + unreachable!() + } + async fn get_result_chunks(&self, _: &str, _: i64, _: i64) -> Result { + unreachable!() + } + async fn get_inline_chunk( + &self, + _: &str, + _: i64, + _: i64, + ) -> Result { + unreachable!() + } + fn poll_config(&self) -> TransportConfig { + TransportConfig::default() + } + async fn cancel_statement(&self, _: &str) -> Result<()> { + unreachable!() + } + async fn close_statement(&self, _: &str) -> Result<()> { + unreachable!() + } + async fn list_catalogs(&self, _: &str) -> Result { + unreachable!() + } + async fn list_schemas( + &self, + _: &str, + _: Option<&str>, + _: Option<&str>, + ) -> Result { + unreachable!() + } + async fn list_tables( + &self, + _: &str, + _: Option<&str>, + _: Option<&str>, + _: Option<&str>, + _: Option<&[&str]>, + ) -> Result { + unreachable!() + } + async fn list_columns( + &self, + _: &str, + _: Option<&str>, + _: Option<&str>, + _: Option<&str>, + _: Option<&str>, + ) -> Result { + unreachable!() + } + async fn list_procedures( + &self, + _: &str, + _: Option<&str>, + _: Option<&str>, + _: Option<&str>, + ) -> Result { + unreachable!() + } + async fn list_functions( + &self, + _: &str, + _: Option<&str>, + _: Option<&str>, + _: Option<&str>, + ) -> Result { + unreachable!() + } + async fn list_primary_keys( + &self, + _: &str, + _: &str, + _: &str, + _: &str, + ) -> Result { + unreachable!() + } + async fn list_foreign_keys( + &self, + _: &str, + _: Option<&str>, + _: Option<&str>, + _: Option<&str>, + _: &str, + _: &str, + _: &str, + ) -> Result { + unreachable!() + } + fn list_table_types(&self) -> Vec { + unreachable!() + } + } + + /// Build a `ResultReaderFactory` against the panicking stub + /// transport. Used by control-flow tests that don't fire any + /// RPC. + fn factory_for_control_flow_test() -> ResultReaderFactory { + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()).unwrap(), + ); + let runtime = tokio::runtime::Handle::current(); + ResultReaderFactory::new( + Arc::new(PanickingTransport), + http_client, + CloudFetchConfig::default(), + PostProcessOptions::default(), + runtime, + ) + } + + fn ok_status() -> StatementStatus { + StatementStatus { + state: StatementState::Succeeded, + error: None::, + } + } + + fn minimal_manifest(total_chunk_count: Option) -> ResultManifest { + ResultManifest { + format: "ARROW_STREAM".to_string(), + schema: ResultSchema { + column_count: 0, + columns: vec![], + }, + total_chunk_count, + total_row_count: None, + total_byte_count: None, + truncated: false, + chunks: None, + result_compression: None, + } + } + + /// B-2: the rollout-guard branch. Server emits multi-chunk + /// inline-Arrow (manifest says total_chunk_count = 2) but + /// without the per-chunk `next_chunk_index` field. The factory + /// MUST surface `data_loss` rather than silently truncate the + /// result after the first chunk. + #[tokio::test] + async fn rollout_guard_errors_when_total_chunks_disagrees_with_next_chunk_index() { + let factory = factory_for_control_flow_test(); + let response = ExecuteResponse { + statement_id: "stmt-1".to_string(), + status: ok_status(), + manifest: Some(minimal_manifest(Some(2))), + result: Some(ExecuteResultData { + next_chunk_internal_link: None, + external_links: None, + // Non-empty inline payload, but per-chunk + // continuation is missing. + inline_arrow_data: Some(vec![1u8, 2, 3]), + inline_chunk_index: Some(0), + inline_row_offset: Some(0), + inline_row_count: Some(0), + inline_next_chunk_index: None, + }), + }; + + let err = match factory.create_inner_reader("stmt-1", &response) { + Ok(_) => panic!("rollout-skew must surface as Err"), + Err(e) => e, + }; + assert_eq!(err.code, ErrorCode::DataLoss); + assert!( + err.message.contains("total_chunk_count"), + "error must call out the total_chunk_count discrepancy: {}", + err.message, + ); + } + + /// B-2 negative: when total_chunk_count says 1 (genuinely + /// single-chunk), the rollout guard MUST NOT fire. The + /// single-chunk inline path is taken instead, which would only + /// error if the bytes don't parse as Arrow IPC — but the + /// rollout guard runs BEFORE the parse, so it suffices to + /// confirm the error (if any) is NOT a `data_loss` mentioning + /// `total_chunk_count`. + #[tokio::test] + async fn rollout_guard_does_not_fire_on_genuinely_single_chunk() { + let factory = factory_for_control_flow_test(); + let response = ExecuteResponse { + statement_id: "stmt-1".to_string(), + status: ok_status(), + manifest: Some(minimal_manifest(Some(1))), + result: Some(ExecuteResultData { + next_chunk_internal_link: None, + external_links: None, + // Garbage bytes — the rollout guard won't reach the + // IPC parse step, so this is fine for the guard + // test. If we ever hit `data_loss` mentioning + // `total_chunk_count`, the guard erroneously fired. + inline_arrow_data: Some(vec![1u8, 2, 3]), + inline_chunk_index: Some(0), + inline_row_offset: Some(0), + inline_row_count: Some(1), + inline_next_chunk_index: None, + }), + }; + + match factory.create_inner_reader("stmt-1", &response) { + // OK or any non-rollout-guard error is acceptable — + // we're proving the guard is *not* the failure mode. + Ok(_) => {} + Err(e) => assert!( + !e.message.contains("total_chunk_count"), + "rollout guard erroneously fired for single-chunk: {}", + e.message, + ), + } + } + + /// B-3: initial execute response must be strict about + /// `row_count` when `next_chunk_index.is_some()`. Defaulting + /// to 0 would silently corrupt the next-fetch row_offset. + #[tokio::test] + async fn initial_response_requires_row_count_when_streaming() { + let factory = factory_for_control_flow_test(); + let response = ExecuteResponse { + statement_id: "stmt-1".to_string(), + status: ok_status(), + manifest: Some(minimal_manifest(Some(2))), + result: Some(ExecuteResultData { + next_chunk_internal_link: None, + external_links: None, + inline_arrow_data: Some(vec![1u8, 2, 3]), + inline_chunk_index: Some(0), + inline_row_offset: Some(0), + // Critical: row_count missing on an + // attachment-bearing response that opts into + // streaming (next_chunk_index is Some). + inline_row_count: None, + inline_next_chunk_index: Some(1), + }), + }; + + let err = match factory.create_inner_reader("stmt-1", &response) { + Ok(_) => panic!("missing row_count on streaming response must surface as Err"), + Err(e) => e, + }; + assert_eq!(err.code, ErrorCode::DataLoss); + assert!( + err.message.to_lowercase().contains("row_count"), + "error must mention the missing field: {}", + err.message, + ); + } + + #[tokio::test] + async fn initial_response_requires_chunk_index_when_streaming() { + let factory = factory_for_control_flow_test(); + let response = ExecuteResponse { + statement_id: "stmt-1".to_string(), + status: ok_status(), + manifest: Some(minimal_manifest(Some(2))), + result: Some(ExecuteResultData { + next_chunk_internal_link: None, + external_links: None, + inline_arrow_data: Some(vec![1u8, 2, 3]), + inline_chunk_index: None, + inline_row_offset: Some(0), + inline_row_count: Some(1), + inline_next_chunk_index: Some(1), + }), + }; + + let err = match factory.create_inner_reader("stmt-1", &response) { + Ok(_) => panic!("missing chunk_index on streaming response must surface as Err"), + Err(e) => e, + }; + assert_eq!(err.code, ErrorCode::DataLoss); + assert!( + err.message.to_lowercase().contains("chunk_index"), + "error must mention the missing field: {}", + err.message, + ); + } } From a18c8b8c5a6f444817819f042081c74b77822981 Mon Sep 17 00:00:00 2001 From: Gopal Lal Date: Wed, 27 May 2026 21:10:08 +0530 Subject: [PATCH 4/4] chore(pr71): post-rebase fixups for main moves 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 --- src/client/sea.rs | 4 ++++ src/reader/mod.rs | 6 +++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index c3062974..a95f2b52 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -1313,6 +1313,7 @@ mod tests { // Last link signals end-of-stream. test_external_link(2, 2000, 1000, None), ]), + attachment: None, }; let result = derive_chunk_fetch_result(response).unwrap(); @@ -1349,6 +1350,7 @@ mod tests { // reader would report next=6 and offset=6000 — wrong. test_external_link(7, 7000, 500, Some(8)), ]), + attachment: None, }; let result = derive_chunk_fetch_result(response).unwrap(); @@ -1378,6 +1380,7 @@ mod tests { row_count: None, next_chunk_index: Some(99), external_links: Some(vec![test_external_link(5, 5000, 1000, Some(6))]), + attachment: None, }; let result = derive_chunk_fetch_result(response).unwrap(); @@ -1398,6 +1401,7 @@ mod tests { row_count: None, next_chunk_index: None, external_links: None, + attachment: None, }; let result = derive_chunk_fetch_result(response).unwrap(); diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 0a50c44e..3ac5b97a 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -263,7 +263,7 @@ impl ResultReaderFactory { // return `None` and downstream wrappers // would reject the stream. let manifest_schema = response.manifest.as_ref().and_then(|m| { - match self.extract_schema_from_manifest(Some(m)) { + match Self::extract_schema_from_manifest(Some(m)) { Ok(s) => Some(s), Err(e) => { tracing::warn!( @@ -1459,6 +1459,10 @@ mod tests { StatementStatus { state: StatementState::Succeeded, error: None::, + num_modified_rows: None, + display_message: None, + diagnostic_info: None, + error_details_json: None, } }