diff --git a/src/reader/cloudfetch/arrow_parser.rs b/src/reader/cloudfetch/arrow_parser.rs index e6f6f50a..5c860723 100644 --- a/src/reader/cloudfetch/arrow_parser.rs +++ b/src/reader/cloudfetch/arrow_parser.rs @@ -25,7 +25,97 @@ use crate::types::sea::CompressionCodec; use arrow_array::RecordBatch; use arrow_ipc::reader::StreamReader; use lz4_flex::frame::FrameDecoder; -use std::io::{Cursor, Read}; +use std::io::{self, BufReader, Cursor, Read}; + +/// Streaming reader over a buffer that may concatenate multiple LZ4 frames. +/// +/// Databricks LZ4_FRAME payloads pack one frame per server-side Arrow record +/// batch, end-to-end in a single body. `FrameDecoder::read` returns EOF at +/// each frame's end-marker, so a single `FrameDecoder` cannot read across +/// frame boundaries. This adapter peels frames lazily: as soon as the +/// current frame is exhausted, it advances past the consumed bytes and +/// starts a new `FrameDecoder` on whatever follows, transparently to the +/// caller. +/// +/// Used by `parse_arrow_ipc` to pipe LZ4-compressed bodies directly into +/// `arrow_ipc::reader::StreamReader` without ever materializing the full +/// decompressed payload as a single `Vec`. Mirrors the JDBC driver's +/// switch from `decompress -> byte[]` to a streaming `LZ4FrameInputStream`. +/// +/// What this does and does not bound: the win is removing the >2 GiB +/// single contiguous-buffer ceiling (an `i32`-indexed `byte[]` in JDBC, +/// a single materialized `Vec` here) and a redundant memcpy. Peak +/// memory for a chunk drops from `(decompressed bytes + decoded batches)` +/// to `(decoded batches for this chunk)`. It does NOT bound the total +/// decoded result size — a query that decompresses to ~10 GB will still +/// hold ~10 GB of `RecordBatch` data in memory once +/// `parse_arrow_ipc` finishes, because the function returns a +/// `Vec` covering the whole chunk. Per-batch streaming to +/// the consumer would require a different signature (an iterator over +/// `Result`); out of scope for this fix. +struct MultiFrameLz4Reader<'a> { + /// Bytes that have not yet been consumed by any frame decoder. + remaining: &'a [u8], + /// Active decoder for the current frame, if any. `None` between + /// frames (or before the first one). + current: Option>>, +} + +impl<'a> MultiFrameLz4Reader<'a> { + fn new(data: &'a [u8]) -> Self { + Self { + remaining: data, + current: None, + } + } +} + +impl<'a> Read for MultiFrameLz4Reader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + // Per the `std::io::Read` contract, `Ok(0)` is allowed when + // `buf.len() == 0`. Without this guard, the EOF-on-frame branch + // below would interpret the inner decoder's `Ok(0)` as "frame + // exhausted" and advance `remaining` past a still-live frame, + // corrupting subsequent reads. Arrow's `StreamReader` happens + // never to issue a zero-length read today (verified upstream), + // but the bug would be silent if it ever did. + if buf.is_empty() { + return Ok(0); + } + loop { + if let Some(decoder) = self.current.as_mut() { + let n = decoder.read(buf)?; + if n > 0 { + return Ok(n); + } + // EOF on this frame — recover the consumed-byte count + // from the inner cursor and advance `remaining`. + let consumed = decoder.get_ref().position() as usize; + if consumed == 0 { + // Defensive: a zero-progress decoder on a non-empty + // input would otherwise spin forever. Prefix the + // message with `[multi-frame-lz4]` so it stays + // greppable after `StreamReader` wraps it inside a + // generic "Failed to read Arrow batches" envelope + // in `parse_arrow_ipc`. + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "[multi-frame-lz4] LZ4 decoder stalled with {} bytes remaining", + self.remaining.len() + ), + )); + } + self.remaining = &self.remaining[consumed..]; + self.current = None; + } + if self.remaining.is_empty() { + return Ok(0); + } + self.current = Some(FrameDecoder::new(Cursor::new(self.remaining))); + } + } +} /// Parse Arrow IPC data into RecordBatches. /// @@ -48,50 +138,41 @@ use std::io::{Cursor, Read}; /// - If LZ4 decompression fails /// - If Arrow IPC parsing fails pub fn parse_arrow_ipc(data: &[u8], compression: CompressionCodec) -> Result> { - // 1. Decompress if needed - let decompressed: Vec; - let bytes: &[u8] = match compression { - CompressionCodec::Lz4Frame => { - // Databricks LZ4_FRAME payloads concatenate multiple LZ4 - // frames in one buffer (one frame per server-side arrow - // record batch). FrameDecoder::read_to_end short-circuits - // at the first frame's end marker, so we must loop and - // peel each frame off in sequence. Mirrors the Python - // connector's `_decompress_data` (cloudfetch/downloader.py). - let mut buf = Vec::new(); - let mut remaining = data; - while !remaining.is_empty() { - let mut decoder = FrameDecoder::new(Cursor::new(remaining)); - let before = buf.len(); - decoder - .read_to_end(&mut buf) - .map_err(|e| Error::io().message(format!("LZ4 decompression failed: {}", e)))?; - let consumed = decoder.into_inner().position() as usize; - if consumed == 0 { - // Defensive: avoid infinite loop if decoder makes no progress. - return Err(Error::io().message(format!( - "LZ4 decoder stalled with {} bytes remaining", - remaining.len() - ))); - } - if buf.len() == before && consumed == remaining.len() { - break; - } - remaining = &remaining[consumed..]; - } - decompressed = buf; - &decompressed - } - CompressionCodec::None => data, + // Pipe the (possibly LZ4-decompressed) byte stream directly into the + // Arrow IPC reader. The decompressed body is never materialized as a + // single `Vec` — that removes the >2 GiB contiguous-buffer + // ceiling that JDBC's `byte[] decompressedBytes` path hit on the + // 10 GB-class query below. The function still returns a + // `Vec` covering the whole chunk, so peak memory once + // this returns is the chunk's decoded size — not the wire size, but + // not bounded to a single batch either. See `MultiFrameLz4Reader` + // doc for the precise envelope. + // + // The query that makes this matter: + // `SELECT repeat('A', 1024*1024) FROM range(10*1024)` — ships + // ~14 MB compressed, decompresses to ~10 GB. Before this change + // that decompressed `Vec` either OOM'd at allocation or tripped + // the 2 GiB IPC array-offset limit. Mirrors the JDBC fix in + // `SeaInlineArrowChunkProvider.processResultData` (switch from + // `byte[] decompressedBytes` to `LZ4FrameInputStream`). + let reader: Box = match compression { + CompressionCodec::Lz4Frame => Box::new(MultiFrameLz4Reader::new(data)), + CompressionCodec::None => Box::new(Cursor::new(data)), }; - // 2. Parse Arrow IPC stream - let cursor = Cursor::new(bytes); - let reader = StreamReader::try_new(cursor, None) + // Wrap in `BufReader` so the many small reads `StreamReader` issues + // (4–8 byte continuation/length prefixes, then FlatBuffer metadata) + // are coalesced into block-sized reads against `MultiFrameLz4Reader` + // / `Cursor`. Without this, each prefix crosses the `Box` + // vtable and then a `FrameDecoder::read` call — measurable overhead + // on small results. The previous code read from an in-memory + // `Cursor>` where each `StreamReader` read was a cheap + // memcpy; `BufReader` restores equivalent behaviour while keeping + // the streaming decompress. + let stream = StreamReader::try_new(BufReader::new(reader), None) .map_err(|e| Error::io().message(format!("Failed to create Arrow IPC reader: {}", e)))?; - // 3. Collect all batches from the stream - let batches: Vec = reader + let batches: Vec = stream .into_iter() .collect::, _>>() .map_err(|e| Error::io().message(format!("Failed to read Arrow batches: {}", e)))?; @@ -269,4 +350,149 @@ mod tests { let result = parse_arrow_ipc(&buffer, CompressionCodec::None).unwrap(); assert!(result.is_empty()); } + + // ────────────────────────────────────────────────────────────── + // MultiFrameLz4Reader — direct Read-impl tests. + // + // The integration coverage above flows through `parse_arrow_ipc` + // with large buffers, so it hits the happy multi-frame path but + // can't pin the small-buf / stall / empty-buf branches. The tests + // below construct the reader directly and call `read()` so each + // new branch in the Read impl is exercised in isolation. + // ────────────────────────────────────────────────────────────── + + /// Helper: LZ4-encode `bytes` as a single frame. + fn encode_lz4_frame(bytes: &[u8]) -> Vec { + use lz4_flex::frame::FrameEncoder; + use std::io::Write; + let mut out = Vec::new(); + let mut enc = FrameEncoder::new(&mut out); + enc.write_all(bytes).unwrap(); + enc.finish().unwrap(); + out + } + + /// Helper: drain a `Read` into a `Vec` using a fixed-size + /// buffer. Returns (bytes, read_call_count) so tests can assert on + /// both the data and the call shape. + fn drain_with_buf_size(mut r: impl Read, buf_size: usize) -> (Vec, usize) { + let mut out = Vec::new(); + let mut buf = vec![0u8; buf_size]; + let mut reads = 0; + loop { + match r.read(&mut buf) { + Ok(0) => return (out, reads), + Ok(n) => { + out.extend_from_slice(&buf[..n]); + reads += 1; + } + Err(e) => panic!("read failed: {e}"), + } + } + } + + /// `Ok(0)` from `read` when `buf` is empty must NOT be confused + /// with "frame exhausted" — that path is the documented + /// std::io::Read contract corner. Without the guard at the top of + /// the read impl, the EOF-on-frame branch would advance + /// `remaining` past a still-live frame and corrupt subsequent + /// reads. Verify by issuing an empty read and then a normal read, + /// asserting the normal read still returns the full content. + #[test] + fn multi_frame_reader_handles_empty_buf_without_corrupting_stream() { + let payload = b"hello, lz4 frame!"; + let frame = encode_lz4_frame(payload); + let mut r = MultiFrameLz4Reader::new(&frame); + + // First call with zero-length buf: must return Ok(0) WITHOUT + // touching the underlying frame state. + let mut empty: [u8; 0] = []; + assert_eq!(r.read(&mut empty).unwrap(), 0); + + // Then drain into a real buf; if the first call corrupted + // state, this would either short-read or fail. + let (got, _reads) = drain_with_buf_size(&mut r, 64); + assert_eq!(&got, payload, "stream must be intact after empty read"); + } + + /// Small-buf drain across multiple frames: the reader must + /// transparently span frame boundaries while honouring a buf + /// smaller than one frame's output. Mirrors what `BufReader` + /// internals look like when refilling a small block. + #[test] + fn multi_frame_reader_drains_correctly_with_small_buf() { + // Three frames so we exercise more than one frame transition. + let p1 = b"first "; + let p2 = b"second "; + let p3 = b"third!!"; + let mut bytes = encode_lz4_frame(p1); + bytes.extend(encode_lz4_frame(p2)); + bytes.extend(encode_lz4_frame(p3)); + + // 4-byte buf is intentionally smaller than each payload + // (7 bytes) — forces multiple read() calls inside a single + // frame plus the cross-frame transitions. + let (got, reads) = drain_with_buf_size(MultiFrameLz4Reader::new(&bytes), 4); + let mut expected = Vec::new(); + expected.extend_from_slice(p1); + expected.extend_from_slice(p2); + expected.extend_from_slice(p3); + assert_eq!(got, expected, "all three frames must be drained in order"); + assert!( + reads >= expected.len() / 4, + "small buf must force multiple read() calls (got {reads} for {} bytes)", + expected.len() + ); + } + + /// 3+ concatenated frames must drain correctly into a single + /// buffer (large-buf case for the multi-frame path). Companion to + /// `multi_frame_reader_drains_correctly_with_small_buf` which + /// exercises the small-buf path on the same fixture shape. + #[test] + fn multi_frame_reader_handles_three_or_more_frames() { + let mut bytes = Vec::new(); + let mut expected = Vec::new(); + for i in 0..5 { + let payload = format!("frame-{i}-content").into_bytes(); + bytes.extend(encode_lz4_frame(&payload)); + expected.extend(payload); + } + + let (got, _) = drain_with_buf_size(MultiFrameLz4Reader::new(&bytes), 4096); + assert_eq!(got, expected, "5 frames must drain to concatenated payload"); + } + + /// Stall-path: if a non-empty `remaining` produces a decoder that + /// reports EOF immediately (consumed == 0), the reader must + /// surface an `InvalidData` error rather than spin. Drive this by + /// feeding garbage bytes that don't look like a valid LZ4 frame + /// header — `FrameDecoder::read` errors out immediately, which + /// our `?` propagates as an io::Error. This covers the + /// `consumed == 0` branch's failure mode for any genuinely + /// stuck decoder. + #[test] + fn multi_frame_reader_does_not_spin_on_invalid_bytes() { + // Bytes that don't start with the LZ4 frame magic + // (0x184D2204). FrameDecoder will error rather than make + // progress; our `?` returns it before we ever reach the + // `consumed == 0` arm. Either outcome (a propagated decode + // error OR the InvalidData stall path) is acceptable — the + // contract under test is "doesn't hang." + let bytes = b"\x00\x01\x02\x03\x04\x05\x06\x07not-a-valid-lz4-frame"; + let mut r = MultiFrameLz4Reader::new(bytes); + let mut buf = [0u8; 16]; + let err = r + .read(&mut buf) + .expect_err("invalid bytes must surface as error"); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + } + + /// Empty input → immediate EOF, no error. + #[test] + fn multi_frame_reader_yields_eof_on_empty_input() { + let mut r = MultiFrameLz4Reader::new(&[]); + let mut buf = [0u8; 16]; + assert_eq!(r.read(&mut buf).unwrap(), 0, "empty input must EOF cleanly"); + } } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 8fb3f628..909a1d66 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -139,6 +139,41 @@ impl ResultReaderFactory { .map(|s| CompressionCodec::from_manifest(Some(s))) .unwrap_or_default(); + // Manifest-authoritative empty-result short-circuit. + // + // When the SEA manifest reports `total_chunk_count = 0`, the + // result set is empty regardless of whatever `result` payload + // the server may have attached (external_links, inline-Arrow + // attachment, or internal-link). Returning an `EmptyReader` + // built from the manifest schema avoids walking the chunk- + // fetch path for a result we know has no rows, and mirrors + // the JDBC driver's manifest-first empty-result handling. + // + // Only fires when the field is explicitly `Some(0)`. Absent + // or non-zero values fall through to the existing branch + // dispatch — the manifest field is deprecated on newer + // servers and we must not infer "empty" from its absence. + // + // Caller contract: returning here before the `status.state` + // match arms below is safe only because every caller of + // `create_inner_reader` has already verified a terminal-success + // outcome (`StatementOutcome::Done` in `src/client/sea.rs`). + // A future caller that invokes us on a Failed / Canceled / + // Pending / Running state with `total_chunk_count == Some(0)` + // would silently lose the error signal — re-gate here if that + // ever changes. + if matches!( + response.manifest.as_ref().and_then(|m| m.total_chunk_count), + Some(0) + ) { + crate::klog::info!( + statement_id, + "Manifest reports total_chunk_count=0; short-circuiting to empty reader", + ); + let schema = Self::extract_schema_from_manifest(response.manifest.as_ref())?; + return Ok(Box::new(EmptyReader::new(schema))); + } + // Check result data for CloudFetch or inline results if let Some(ref result) = response.result { // Log what result data we have for debugging the decision path @@ -1719,4 +1754,109 @@ mod tests { err.message, ); } + + // ────────────────────────────────────────────────────────────── + // total_chunk_count == 0 manifest short-circuit. + // + // The SEA manifest is authoritative when it explicitly reports + // zero chunks: the result has no rows, regardless of any stray + // `result` payload the server may have attached. Absent or + // non-zero values must fall through to the existing branch + // dispatch (the field is deprecated on newer servers). + // ────────────────────────────────────────────────────────────── + + /// Zero-chunk manifest must produce an `EmptyReader` even when a + /// non-empty inline-Arrow attachment is also present. The factory + /// must trust the manifest and never reach the IPC parser. Bytes + /// that wouldn't parse as Arrow IPC are deliberately used so that + /// an accidental fall-through would surface as an `io` error + /// rather than a silent pass. + #[tokio::test] + async fn zero_chunk_count_short_circuits_to_empty_reader() { + let factory = factory_for_control_flow_test(); + let response = ExecuteResponse { + statement_id: "stmt-1".to_string(), + status: ok_status(), + manifest: Some(minimal_manifest(Some(0))), + 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), + inline_row_count: Some(0), + inline_next_chunk_index: None, + }), + }; + + let mut reader = factory + .create_inner_reader("stmt-1", &response) + .expect("zero-chunk manifest must succeed without parsing inline bytes"); + assert!( + reader.next_batch().await.unwrap().is_none(), + "zero-chunk reader must yield no batches", + ); + } + + /// Absent `total_chunk_count` (older servers / non-SEA path) must + /// NOT trip the short-circuit. With a `Succeeded` state and no + /// result payload, the factory falls through to the existing + /// state-based empty branch — also an `EmptyReader`, but reached + /// via a different code path. The test guards that the absence + /// of the field is not mis-read as `Some(0)`. + #[tokio::test] + async fn absent_total_chunk_count_falls_through() { + let factory = factory_for_control_flow_test(); + let response = ExecuteResponse { + statement_id: "stmt-1".to_string(), + status: ok_status(), + manifest: Some(minimal_manifest(None)), + result: None, + }; + + let mut reader = factory + .create_inner_reader("stmt-1", &response) + .expect("absent total_chunk_count + Succeeded state must yield empty reader"); + assert!(reader.next_batch().await.unwrap().is_none()); + } + + /// Non-zero `total_chunk_count` must NOT trip the short-circuit + /// even when the result payload is empty in shape. With + /// `total_chunk_count = 1` and a non-empty inline attachment of + /// garbage bytes, the factory takes the single-chunk inline path + /// and fails parsing — proving the short-circuit didn't fire + /// (which would have returned `Ok` with no batches). The exact + /// error code isn't part of the contract; we only assert that + /// it's not the manifest-driven `EmptyReader` path. + #[tokio::test] + async fn non_zero_total_chunk_count_does_not_short_circuit() { + 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, + 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, + }), + }; + + // Single-chunk inline path on garbage bytes — must surface as + // a parse error. If the short-circuit had fired, this would + // return `Ok` and we'd never reach the IPC parser. + let err = factory + .create_inner_reader("stmt-1", &response) + .err() + .expect("non-zero total_chunk_count + garbage inline must surface parse error"); + assert!( + !err.message.contains("total_chunk_count=0"), + "short-circuit must not have fired: {}", + err.message, + ); + } }