From 779373c9b550b7957a0e844c175d232fd1c21d56 Mon Sep 17 00:00:00 2001 From: Gopal Lal Date: Fri, 5 Jun 2026 12:25:47 +0530 Subject: [PATCH 1/2] fix(reader): short-circuit empty results + stream LZ4 decompress to avoid >2 GiB byte[] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two related SEA result-fetch fixes; both apply to inline-Arrow AND CloudFetch paths because they share the same `parse_arrow_ipc` chokepoint plus the same manifest dispatch in `create_inner_reader`. (1) Manifest-authoritative empty-result short-circuit ------------------------------------------------- When `manifest.total_chunk_count == Some(0)`, return an `EmptyReader` derived from the manifest schema before any branch dispatch. The SEA server may attach a stub `result` payload (or empty `external_links`, or an inline attachment) alongside a zero-chunk manifest; trust the manifest and skip the chunk-fetch path entirely. Mirrors JDBC's manifest-first handling. Only fires on `Some(0)`. Absent or non-zero values continue with the existing flow — the field is deprecated on newer servers and absence must not be inferred as "empty". (2) Streaming LZ4 decompress ------------------------ `parse_arrow_ipc` previously decompressed the whole LZ4 body into a single `Vec` before handing it to `arrow_ipc::StreamReader`. A query that compresses well but expands hugely — JDBC's known repro is `SELECT repeat('A', 1024*1024) FROM range(10*1024)` — ships ~14 MB on the wire but decompresses to >2 GiB and either OOMs or hits the arrow_ipc byte-array limit (`Cannot read more than 2,147,483,647 into a byte array` in JDBC). The fix introduces `MultiFrameLz4Reader<'a>`, a `Read` impl that peels concatenated LZ4 frames on demand from a borrowed buffer. The reader is piped directly into `StreamReader::try_new`, so peak memory is bounded by one IPC record batch plus the LZ4 decoder's internal block buffer — never the total decompressed length. Mirrors JDBC's switch from `byte[] decompressedBytes` to `LZ4FrameInputStream`. Single chokepoint: `parse_arrow_ipc` is called by the CloudFetch chunk downloader, the single-chunk inline provider, and the multi-chunk inline streaming provider. One fix covers all three. Test coverage ------------- - `zero_chunk_count_short_circuits_to_empty_reader` — non-empty inline attachment with garbage bytes + manifest.total_chunk_count=0 returns an EmptyReader without parsing the bytes. - `absent_total_chunk_count_falls_through` — None must not be misinterpreted as Some(0). - `non_zero_total_chunk_count_does_not_short_circuit` — Some(1) + garbage inline bytes surfaces a parse error, proving the short- circuit didn't mask it. - Existing `test_parse_multi_frame_compressed_arrow_ipc` still passes through the new streaming path, validating multi-frame correctness. `cargo +stable fmt --all` clean. `cargo clippy --all-targets -- -D warnings` clean. `cargo test` — 703 passed, 0 failed. Co-authored-by: Isaac Signed-off-by: Gopal Lal --- src/reader/cloudfetch/arrow_parser.rs | 126 +++++++++++++++++-------- src/reader/mod.rs | 131 ++++++++++++++++++++++++++ 2 files changed, 216 insertions(+), 41 deletions(-) diff --git a/src/reader/cloudfetch/arrow_parser.rs b/src/reader/cloudfetch/arrow_parser.rs index e6f6f50a..a40c6ef5 100644 --- a/src/reader/cloudfetch/arrow_parser.rs +++ b/src/reader/cloudfetch/arrow_parser.rs @@ -25,7 +25,74 @@ 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, 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. Mirrors the JDBC driver's switch from +/// `decompress -> byte[]` to a streaming `LZ4FrameInputStream`. A 10TB- +/// logical / 14MB-on-wire chunk fed through this adapter peaks at a single +/// arrow_ipc batch's worth of memory, not the whole decompressed body. +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 { + 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. Match the + // failure shape of the previous in-memory loop. + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "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 +115,27 @@ 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 into + // a `Vec` — peak memory is bounded by the current IPC record + // batch plus the LZ4 decoder's internal block buffer, not the total + // decompressed length. + // + // This matters in practice: a query that ships ~14 MB compressed but + // would decompress to >2 GiB (e.g. `SELECT repeat('A', 1024*1024) FROM + // range(10*1024)`) would otherwise either OOM or trip the IPC byte- + // array limit. Mirrors the JDBC driver's switch from `byte[] + // decompressedBytes` to `LZ4FrameInputStream` in + // `SeaInlineArrowChunkProvider.processResultData`. + 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) + let stream = StreamReader::try_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)))?; diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 8fb3f628..b9b5e4eb 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -139,6 +139,32 @@ 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. + 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 +1745,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, + ); + } } From 59a666686f4ae30411919d432a21ef4247598e5e Mon Sep 17 00:00:00 2001 From: Gopal Lal Date: Mon, 8 Jun 2026 17:07:41 +0530 Subject: [PATCH 2/2] =?UTF-8?q?fix(reader):=20address=20PR=20#132=20review?= =?UTF-8?q?=20=E2=80=94=20accurate=20doc,=20direct=20Reader=20tests,=20Buf?= =?UTF-8?q?Reader?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses msrathore-db's review comments (6 items, all valid): M1 — arrow_parser.rs:45 (overclaim) The rustdoc + parse_arrow_ipc comment claimed peak memory was bounded by "a single arrow_ipc batch". That is not what the code does: `parse_arrow_ipc` still returns a `Vec` covering the whole chunk, so peak after return is the chunk's decoded size, not a single batch. Reworded both blocks to state the actual win — removing the >2 GiB single contiguous-buffer ceiling + one redundant memcpy — and to call out that per-batch streaming would require a different function signature (out of scope). M2 — arrow_parser.rs:63 (no direct tests for the new Read impl) Added 5 direct unit tests for `MultiFrameLz4Reader`: - empty-buf read must not advance frame state (the L1 fix below) - small-buf (4-byte) drain across 3 frames — partial-read path - 3+ concatenated frames — large-buf multi-frame path - invalid bytes surface as InvalidData, no spin - empty input yields clean EOF All passing. 5 new tests pin the new Read impl's branches in isolation rather than only through the parse_arrow_ipc integration. L1 — arrow_parser.rs:67 (latent: Ok(0) on empty buf misread as EOF-on-frame) Per std::io::Read contract, Ok(0) is allowed when buf.len()==0. Added `if buf.is_empty() { return Ok(0); }` at the top of read(). Arrow's StreamReader doesn't currently issue zero-length reads, but the bug would have been silent if it ever did. Companion test: `multi_frame_reader_handles_empty_buf_without_corrupting_stream`. L2 — arrow_parser.rs:81 (stale comment, error string greppability) Reworded the "Match the failure shape of the previous in-memory loop" comment to reflect that errors now propagate through StreamReader's wrap. Prefixed the reader-internal error string with `[multi-frame-lz4]` so it stays greppable after the generic "Failed to read Arrow batches" envelope swallows it. L3 — arrow_parser.rs:135 (small reads cross vtable / FrameDecoder) Wrapped the chain in `std::io::BufReader::new(...)` before handing to `StreamReader::try_new`. StreamReader issues many 4-8 byte reads for length prefixes + metadata; BufReader coalesces them into block-sized reads, neutralising the small-result regression vs the prior Cursor> path. Standard idiom. L4 — mod.rs:156 (terminal-success caller contract) The `total_chunk_count == Some(0)` short-circuit returns before the `status.state` match arms. Today safe because every caller of `create_inner_reader` has already verified `StatementOutcome::Done` in `src/client/sea.rs`. Added a one-line caller-contract comment so a future caller can't silently regress error reporting for Failed / Canceled / Pending / Running states. cargo +stable fmt --all clean. cargo clippy --all-targets -- -D warnings clean. cargo test — 708 passed, 0 failed (+5 from M2). Co-authored-by: Isaac Signed-off-by: Gopal Lal --- src/reader/cloudfetch/arrow_parser.rs | 220 +++++++++++++++++++++++--- src/reader/mod.rs | 9 ++ 2 files changed, 210 insertions(+), 19 deletions(-) diff --git a/src/reader/cloudfetch/arrow_parser.rs b/src/reader/cloudfetch/arrow_parser.rs index a40c6ef5..5c860723 100644 --- a/src/reader/cloudfetch/arrow_parser.rs +++ b/src/reader/cloudfetch/arrow_parser.rs @@ -25,7 +25,7 @@ use crate::types::sea::CompressionCodec; use arrow_array::RecordBatch; use arrow_ipc::reader::StreamReader; use lz4_flex::frame::FrameDecoder; -use std::io::{self, Cursor, Read}; +use std::io::{self, BufReader, Cursor, Read}; /// Streaming reader over a buffer that may concatenate multiple LZ4 frames. /// @@ -39,10 +39,20 @@ use std::io::{self, Cursor, Read}; /// /// Used by `parse_arrow_ipc` to pipe LZ4-compressed bodies directly into /// `arrow_ipc::reader::StreamReader` without ever materializing the full -/// decompressed payload. Mirrors the JDBC driver's switch from -/// `decompress -> byte[]` to a streaming `LZ4FrameInputStream`. A 10TB- -/// logical / 14MB-on-wire chunk fed through this adapter peaks at a single -/// arrow_ipc batch's worth of memory, not the whole decompressed body. +/// 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], @@ -62,6 +72,16 @@ impl<'a> MultiFrameLz4Reader<'a> { 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)?; @@ -73,12 +93,15 @@ impl<'a> Read for MultiFrameLz4Reader<'a> { 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. Match the - // failure shape of the previous in-memory loop. + // 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!( - "LZ4 decoder stalled with {} bytes remaining", + "[multi-frame-lz4] LZ4 decoder stalled with {} bytes remaining", self.remaining.len() ), )); @@ -116,23 +139,37 @@ impl<'a> Read for MultiFrameLz4Reader<'a> { /// - If Arrow IPC parsing fails pub fn parse_arrow_ipc(data: &[u8], compression: CompressionCodec) -> Result> { // Pipe the (possibly LZ4-decompressed) byte stream directly into the - // Arrow IPC reader. The decompressed body is never materialized into - // a `Vec` — peak memory is bounded by the current IPC record - // batch plus the LZ4 decoder's internal block buffer, not the total - // decompressed length. + // 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. // - // This matters in practice: a query that ships ~14 MB compressed but - // would decompress to >2 GiB (e.g. `SELECT repeat('A', 1024*1024) FROM - // range(10*1024)`) would otherwise either OOM or trip the IPC byte- - // array limit. Mirrors the JDBC driver's switch from `byte[] - // decompressedBytes` to `LZ4FrameInputStream` in - // `SeaInlineArrowChunkProvider.processResultData`. + // 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)), }; - let stream = StreamReader::try_new(reader, 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)))?; let batches: Vec = stream @@ -313,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 b9b5e4eb..909a1d66 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -153,6 +153,15 @@ impl ResultReaderFactory { // 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)