Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
125 changes: 124 additions & 1 deletion src/client/sea.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
})
}

Expand Down Expand Up @@ -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<InlineChunkFetchResult> {
// 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()
}
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand All @@ -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();
Expand Down
55 changes: 55 additions & 0 deletions src/client/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<u8>>,
/// 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<i64>,
pub(crate) inline_row_offset: Option<i64>,
pub(crate) inline_row_count: Option<i64>,
pub(crate) inline_next_chunk_index: Option<i64>,
}

/// Result of fetching chunk links.
Expand Down Expand Up @@ -155,6 +165,30 @@ pub(crate) struct ChunkLinkFetchResult {
pub next_row_offset: Option<i64>,
}

/// 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<u8>,
/// 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<i64>,
}

impl ChunkLinkFetchResult {
/// Create an empty result indicating end of stream.
#[allow(
Expand Down Expand Up @@ -271,6 +305,27 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug {
row_offset: i64,
) -> Result<ChunkLinkFetchResult>;

/// 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<InlineChunkFetchResult>;

/// Polling cadence + ceiling the kernel should use when driving
/// `await_result` / `wait_for_completion`. v0 returns the
/// transport's `TransportConfig` directly; future transports
Expand Down
16 changes: 16 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
}
Expand Down
9 changes: 9 additions & 0 deletions src/reader/cloudfetch/link_fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1202,6 +1202,15 @@ mod tests {
})
}

async fn get_inline_chunk(
&self,
_statement_id: &str,
_chunk_index: i64,
_row_offset: i64,
) -> Result<crate::client::InlineChunkFetchResult> {
unimplemented!("get_inline_chunk not used by the link-fetcher mock")
}

fn poll_config(&self) -> crate::client::TransportConfig {
crate::client::TransportConfig::default()
}
Expand Down
25 changes: 20 additions & 5 deletions src/reader/inline/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Loading
Loading