Repository navigation
fix(reader): short-circuit empty results + stream LZ4 decompress to avoid >2 GiB byte[] - #132
Conversation
…void >2 GiB byte[]
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<u8>` 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 <gopal.lal@databricks.com>
| /// 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. |
There was a problem hiding this comment.
[Medium · HIGH confidence — flagged independently by security, test, performance]
This doc comment (and the PR description) claim peak memory is bounded by "a single arrow_ipc batch." That is not what the code does. parse_arrow_ipc still ends with .collect::<Vec<_>>() (line 138-140), materializing all batches of a chunk at once, and the inline provider then retains the whole result via VecDeque::from(batches) (src/reader/inline/provider.rs:142). For the exact repro cited (SELECT repeat('A',1024*1024) FROM range(10*1024)) delivered as a single inline attachment, the ~10 GB decoded result is still fully resident — this PR does not prevent that OOM.
What the change genuinely (and usefully) fixes: it eliminates the transient fully-decompressed Vec<u8>, removes one full memcpy, and lifts the >2 GiB contiguous-byte[] / IPC array-offset ceiling. Peak drops from (decompressed bytes + decoded batches) to (decoded batches per chunk).
Suggestion: reword to "peak memory is bounded by the full decoded result set for this chunk, not by the wire size — the win is removing the 2 GiB single-buffer limit and a redundant copy, not bounding decompression amplification." (Optional defense-in-depth: a cumulative decompressed-byte cap seeded from manifest.total_byte_count.)
Verified-against: src/reader/cloudfetch/arrow_parser.rs:138-140; src/reader/inline/provider.rs:126,142.
There was a problem hiding this comment.
Good catch — the overclaim is fixed in 59a6666.
Reworded both the rustdoc on MultiFrameLz4Reader and the inline comment in parse_arrow_ipc to state what the change actually does:
- Win: removes the >2 GiB single contiguous-buffer ceiling (an
i32-indexedbyte[]in JDBC, a single materializedVec<u8>here) and a redundant memcpy. Peak for a chunk drops from(decompressed bytes + decoded batches)to(decoded batches for this chunk). - Does NOT bound the total decoded result size —
parse_arrow_ipcstill returns aVec<RecordBatch>covering the whole chunk, so a 10 GB-class query still holds ~10 GB ofRecordBatchdata once the function returns. Called out explicitly in the new doc with a note that per-batch streaming would require a different signature (out of scope for this fix).
| } | ||
| } | ||
|
|
||
| impl<'a> Read for MultiFrameLz4Reader<'a> { |
There was a problem hiding this comment.
[Medium · MODERATE confidence — test (primary), language (small-buffer edge)]
This is the higher-risk change (a hand-written Read impl with new anti-infinite-loop control flow), yet it has no direct unit test — it is referenced only at its definition and the single call site (line 131). The following new branches are untested:
- the
consumed == 0stall →InvalidDatapath (line 71-83) — the one branch whose absence would be a hang; - partial-read / small-
bufdrain (a buffer smaller than one frame's output); - 3+ frame boundaries.
test_parse_multi_frame_compressed_arrow_ipc does flow through this path (confirmed — not dead code), but only at small scale with large buffers.
Recommendation: add a direct Read test that constructs MultiFrameLz4Reader::new(...) and calls read() with a 4-byte buffer, plus one fixture that drives the stall path. Cheap, deterministic, pins the exact new branches.
There was a problem hiding this comment.
Done in 59a6666 — added 5 direct unit tests for MultiFrameLz4Reader that exercise the new branches in isolation:
| Test | Branch covered |
|---|---|
multi_frame_reader_handles_empty_buf_without_corrupting_stream |
the new buf.is_empty() guard (your L1 comment) — issues a zero-length read first, then drains to verify state is intact |
multi_frame_reader_drains_correctly_with_small_buf |
partial-read / small-buf path across 3 frames using a 4-byte buffer |
multi_frame_reader_handles_three_or_more_frames |
5 concatenated frames, large-buf |
multi_frame_reader_does_not_spin_on_invalid_bytes |
the stall-path failure mode — verifies invalid input surfaces as InvalidData rather than spinning |
multi_frame_reader_yields_eof_on_empty_input |
empty input → clean EOF |
All passing. Tally: 708 / 708 (+5 from this round).
| return Err(io::Error::new( | ||
| io::ErrorKind::InvalidData, | ||
| format!( | ||
| "LZ4 decoder stalled with {} bytes remaining", |
There was a problem hiding this comment.
[Low · language; devils-advocate confirmed no consumer impact]
This carefully-worded "LZ4 decoder stalled" message (and genuine FrameDecoder decode errors) now propagate through StreamReader and get wrapped by the generic "Failed to read Arrow batches: {}" arm below, so callers can no longer distinguish an LZ4-frame failure from a malformed-Arrow failure. The underlying lz4 string is preserved inside {}, the ErrorCode stays io, and no consumer (src/, napi/, pyo3/) matches on these message strings — so this is debuggability-only, not a functional regression. Optional: keep the reader's two messages prefixed/greppable so they survive wrapping. The "Match the failure shape of the previous in-memory loop" comment is now slightly inaccurate.
There was a problem hiding this comment.
Done in 59a6666. Two changes:
- Stale comment — reworded the "Match the failure shape of the previous in-memory loop" line to say the message now propagates through
StreamReader's wrap and to explain the[multi-frame-lz4]prefix. - Greppable prefix — added
[multi-frame-lz4]to the stall message so it survives the"Failed to read Arrow batches: {}"envelope.FrameDecoder's own decode errors aren't prefixed (they come from upstream), but the kernel's two reader-internal errors are now distinguishable from Arrow-IPC failures via grep.
| fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { | ||
| loop { | ||
| if let Some(decoder) = self.current.as_mut() { | ||
| let n = decoder.read(buf)?; |
There was a problem hiding this comment.
[Low · language]
decoder.read(buf)? == 0 is interpreted unconditionally as "current frame exhausted, advance remaining." Per the std::io::Read contract a reader may also return Ok(0) when buf.len() == 0. If StreamReader ever passed an empty buffer, this would spuriously advance past a still-live frame and corrupt the stream. Not currently reachable (arrow's StreamReader always reads into non-empty buffers — verified) so this is a latent sharp edge, not an active bug. Optional one-liner at the top of read: if buf.is_empty() { return Ok(0); }.
There was a problem hiding this comment.
Done in 59a6666. Added if buf.is_empty() { return Ok(0); } at the top of read() with a comment explaining the std::io::Read contract corner. Covered by the new multi_frame_reader_handles_empty_buf_without_corrupting_stream test — issues a zero-length read first, then drains and asserts state is intact. Without the guard, that test would either short-read or fail.
| // 2. Parse Arrow IPC stream | ||
| let cursor = Cursor::new(bytes); | ||
| let reader = StreamReader::try_new(cursor, None) | ||
| let stream = StreamReader::try_new(reader, None) |
There was a problem hiding this comment.
[Low · performance]
StreamReader issues many small read() calls (4–8 byte length prefixes, then metadata), each crossing the Box<dyn Read> vtable into MultiFrameLz4Reader/FrameDecoder. The previous code read from an in-memory Cursor<Vec<u8>> where each read was a cheap memcpy. Wrapping the reader in std::io::BufReader::new(...) before handing it to StreamReader::try_new would coalesce these into block-sized reads and neutralize the marginal small-result regression. Low effort, standard idiom.
There was a problem hiding this comment.
Done in 59a6666 — wrapped the inner reader in std::io::BufReader::new(...) before StreamReader::try_new. Added a comment explaining why (StreamReader issues many 4–8 byte reads for length prefixes + FlatBuffer metadata; BufReader coalesces them to neutralise the small-result regression vs the prior Cursor<Vec<u8>> path). Standard idiom, low risk.
| // 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!( |
There was a problem hiding this comment.
[Low · architecture]
This Some(0) short-circuit returns before the status.state match arms (Failed/Canceled/Pending/Running). That is safe only because create_inner_reader is reached exclusively on terminal-success — enforced caller-side in src/client/sea.rs (both call sites gate on StatementOutcome::Done), not here. Verified correct today (those arms are already effectively dead for non-success states). Optional: add a one-line comment noting the short-circuit assumes a terminal-success response, so a future caller can't silently regress error reporting.
There was a problem hiding this comment.
Good catch. Done in 59a6666 — added a caller-contract block explaining that returning here before the status.state match arms is safe only because every caller of create_inner_reader has already verified StatementOutcome::Done in src/client/sea.rs, and naming the regression mode (a future caller invoking us on Failed/Canceled/Pending/Running with total_chunk_count == Some(0) would silently lose the error signal). A future change can either re-gate here or move the state check up.
Review SummaryPR #132 Score: 90/100 (LOW RISK) All 6 reviewers delivered clean findings. No Critical/High defects; no correctness, security, or compatibility regressions identified. Findings breakdown:
Clean bills:
See inline comments F1–F6 for details. |
…ts, BufReader
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<RecordBatch>` 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<Vec<u8>> 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 <gopal.lal@databricks.com>
Summary
Two related SEA result-fetch fixes — both apply to inline-Arrow AND CloudFetch paths, since both go through the same
parse_arrow_ipcchokepoint and the same manifest dispatch increate_inner_reader.1. Manifest-authoritative empty-result short-circuit
When
manifest.total_chunk_count == Some(0), return anEmptyReaderderived from the manifest schema before any branch dispatch (CloudFetch / inline / internal-link). The SEA server may attach a stubresultpayload alongside a zero-chunk manifest; trust the manifest and skip the chunk-fetch path entirely.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 (>1 GB results)
parse_arrow_ipcpreviously decompressed the entire LZ4 body into a singleVec<u8>before handing it toarrow_ipc::StreamReader. A query that compresses well but expands hugely — JDBC's known repro is:— would OOM the kernel or trip the IPC byte-array limit (
Cannot read more than 2,147,483,647 into a byte arrayin JDBC).The fix introduces
MultiFrameLz4Reader<'a>, aReadimpl that peels concatenated LZ4 frames on demand from a borrowed buffer. Piped directly intoStreamReader::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 the JDBC switch frombyte[] decompressedBytestoLZ4FrameInputStreaminSeaInlineArrowChunkProvider.processResultData.Single chokepoint:
parse_arrow_ipcis called by the CloudFetch chunk downloader, the single-chunk inline provider, and the multi-chunk inline streaming provider. One fix covers all three.Files changed
src/reader/cloudfetch/arrow_parser.rsMultiFrameLz4Reader+ refactoredparse_arrow_ipcto streamsrc/reader/mod.rstotal_chunk_count == 0short-circuit increate_inner_reader+ 3 unit tests+216 / -41, two files.
Test plan
zero_chunk_count_short_circuits_to_empty_reader— non-empty inline attachment with garbage bytes +total_chunk_count=0returnsEmptyReaderwithout parsing.absent_total_chunk_count_falls_through—Nonenot mis-read asSome(0).non_zero_total_chunk_count_does_not_short_circuit—Some(1)+ garbage bytes surfaces a parse error (proving the short-circuit didn't mask it).test_parse_multi_frame_compressed_arrow_ipc(PR perf(sea): request LZ4_FRAME compression + fix multi-frame decode #81 coverage) still passes through the new streaming path — validates multi-frame correctness.cargo +stable fmt --all— clean.cargo clippy --all-targets -- -D warnings— clean.cargo test— 703 passed, 0 failed.cargo checkagainst pyo3 + napi sibling workspaces — clean.Build & Test,PyO3 Checks,napi-checks,Security Scan,License Check,DCO.Out of scope
test_parse_multi_frame_compressed_arrow_ipccovers the multi-frame stream-reader correctness at small scale; the memory-bound claim is structural (the new path never callsVec::extend_from_sliceon decompressed output).This pull request and its description were written by Isaac.