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..a95f2b52 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,121 @@ 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 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={})", + 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). + // + // `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.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!( + "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() } @@ -1194,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(); @@ -1230,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(); @@ -1259,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(); @@ -1279,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/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..a8d334f4 --- /dev/null +++ b/src/reader/inline/streaming.rs @@ -0,0 +1,1093 @@ +// 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. +//! +//! ## Coordination +//! +//! The producer (background prefetch task) and the consumer (kernel +//! caller pulling batches) communicate through a bounded +//! `tokio::sync::mpsc` channel: +//! +//! - 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 +//! +//! 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::sync::Arc; +use tokio::sync::{mpsc, Mutex as TokioMutex}; +use tokio::task::JoinHandle; +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. 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, +} + +/// Multi-chunk inline-Arrow streaming provider. +/// +/// 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, + + /// JoinHandle of the prefetch task. `Some(handle)` while the + /// task is running; `take()`n and `abort()`ed in `Drop`. + prefetch_handle: TokioMutex>>, +} + +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 { + /// 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`). + /// + /// # Arguments + /// * `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` / `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. + /// * `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( + 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, + 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)?; + + // 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: initial_batches, + }; + + // 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); + + // 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 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 { + consumer: TokioMutex::new(consumer), + schema, + prefetch_handle: TokioMutex::new(prefetch_handle), + })) + } + + /// 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. + /// + /// 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 { + // 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; + } + + // 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); + } + None => { + // Channel closed: clean EOS. + return Ok(None); + } + } + } + } +} + +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(); + } + } + } +} + +/// 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, +} + +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(&self.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 + ); + let _ = self.tx.send(Err(e)).await; + return; + } + }; + + // 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. + // + // **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) => { + error!( + "inline prefetch: parse_arrow_ipc(chunk={}, bytes={}) failed: {}", + chunk_index, + fetch_result.bytes.len(), + e + ); + let _ = self.tx.send(Err(e)).await; + return; + } + }; + + let chunk_idx = fetch_result.chunk_index; + let batch_count = batches.len(); + 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, + })) + .await + .is_err() + { + debug!( + "inline prefetch: consumer dropped while sending chunk {}; \ + task exiting", + chunk_idx, + ); + 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; + } + } + } + } +} + +#[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, Ordering}; + use std::sync::Mutex as StdMutex; + + #[derive(Clone, Debug)] + struct MockChunk { + bytes: Vec, + chunk_index: i64, + row_offset: i64, + row_count: i64, + next_chunk_index: Option, + } + + /// Mock chunk-source. Records the RPC count so tests can assert + /// the 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 + } + + 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]), + 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() { + 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, + 4, + None, + tokio::runtime::Handle::current(), + ) + .unwrap(); + + 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); + 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() { + 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(); + + 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() { + 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, + }; + + 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, + None, + 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); + } + + #[tokio::test] + async fn surfaces_prefetch_errors() { + 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, + None, + 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("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); + } + + /// 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 38258b62..3ac5b97a 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,116 @@ 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. + // + // 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() { + 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={}", + 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(), + inline_chunk_index, + inline_row_offset, + inline_row_count, + Some(next_idx), + compression, + manifest_schema, + ); + } + + // 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 +437,66 @@ 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. + /// + /// `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, + statement_id: &str, + initial_attachment: Vec, + initial_chunk_index: i64, + initial_row_offset: i64, + initial_row_count: i64, + next_chunk_index: Option, + compression: CompressionCodec, + manifest_schema: Option, + ) -> 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, + ); + + // 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( + 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, + manifest_schema, + self.runtime_handle.clone(), + )?; + + Ok(Box::new(InlineStreamingReader::new(provider))) + } } /// Trait for result readers. @@ -411,6 +581,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 @@ -1080,4 +1282,347 @@ 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::, + num_modified_rows: None, + display_message: None, + diagnostic_info: None, + error_details_json: 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, + ); + } } 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)]