← Back to Pull requests

fix(encoding): split legacy decode batches before i32 offset overflow #9225

Merged
lance-gatefixer[bot] merged 10 files (849 lines) on Sep 21, 2026 17:18 UTC
View on GitHub
lance-gatefixer[bot] lance-gatefixer[bot] commented on Sep 14, 2026 22:38 UTC
Author

Summary

Split legacy-path (2.0) decode batches before Arrow's i32 offset capacity is exceeded, using a byte budget, so batch shapes are unchanged for normal data.

Root cause

The legacy decode path (array_encoding/) concatenates all decoded pages needed for the requested row batch. Individual page arrays are valid, but their combined variable-width data can exceed the i32 offset capacity required by Arrow Utf8/Binary/List arrays (#9223, Offset overflow error: N with N just past i32::MAX).

Approach

LogicalPageDecoder::max_rows_to_drain(num_rows, byte_budget): before draining a batch of an i32-offset column, the root decoder reports how many rows fit within an i32::MAX variable-width byte budget.

  • ListPageDecoder counts bytes exactly from its page offsets (strings are lists of u8 on this path, so this covers Utf8/Binary precisely); nested item arrays get their own budget.

  • ChildState accumulates across pages against the budget, so a batch spans as many pages as actually fit — batch shapes are unchanged unless a batch would genuinely overflow.

  • A batch whose single first row exceeds the budget fails with an actionable NotSupported error at the stream root.

  • decode_batch (single-batch contract for EncodedBatch) opts out.
  • Scope: this PR only touches the legacy path. The structural (2.1+) path has the same defect but exact splitting there needs the decoded-size reporting from #8793; once that lands, a follow-up applies the same budget at StructuralBatchDecodeStream (a working implementation, including fixes to #8793's miniblock accounting, was validated on this branch previously — see the review discussion and https://github.com/lance-format/lance/pull/8793#issuecomment-5736247183).

    Validation

  • cargo test -p lance-encoding (1845 passed) and cargo test -p lance-file (183 passed) — with the existing exact batch-shape assertions untouched, which is the regression proof that shapes are preserved for data within budget

  • cargo clippy --tests -- -D warnings, cargo fmt

  • New tests: cross-page spanning without splits, budget-exhaustion splitting (fake per-row byte reporting, no gigabyte allocations), ListPageDecoder reduced-budget accounting

  • Benchmarked on a 21 GiB production-like table (320-core host, warm cache): batch shapes and scan throughput identical to main within noise across string/list columns and batch sizes
  • Partially addresses #9223 (the array_encoding site; the structural site is deferred to the #8793 follow-up).

    🤖 Generated with Claude Code

    Diff: 849 lines (+838 / -11) across 10 files Reviewer: ChilePiquin Review duration: 9760m
    All Vouch review confidence checks passed
    Residual risk 0.14 = Change Risk (0.56) × (1 − Review Confidence (0.75)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.56 · 849 lines diff across 10 files
    0.56
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.51 · 5 substantive comment(s)
    0.51
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    74%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    27 items
    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on Sep 14, 2026 22:48 UTC
    Reviewer

    ✅ Gate recommendation: approve.

    This preserves Arrow’s i32-offset invariant by splitting requested decode batches at safe page or list-offset boundaries across both decoder paths. The approach retains the public maximum-batch-size contract and covers Utf8, Binary, List, Map, and nested types without changing the storage format.

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on Sep 14, 2026 22:57 UTC
    Reviewer

    ✅ Gate recommendation: approve.

    The updated regression test correctly treats the requested batch size as an upper bound while still verifying every row and its order. The overflow fix remains fully covered, and the focused tests, library suite, formatting check, and clippy check all pass.

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on Sep 16, 2026 01:06 UTC
    Reviewer

    ✅ Gate recommendation: approve.

    The merged decoder still splits variable-width output before Arrow’s i32 offset capacity while preserving the requested batch size as an upper bound. The conflict resolution also retains main’s checked index-range conversion without changing the storage or public API contracts.

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on Sep 18, 2026 19:38 UTC
    Reviewer

    ❌ Gate recommendation: request changes.

    The byte-budget design is safe only when every supported decoder supplies a conservative decoded-size bound and validates file-derived metadata before planning. This revision still has three independent violations of that contract, including a compatibility regression for legacy Zstd data. The page-boundary split from the earlier revision remains the safer minimal fix; if preserving batch shapes is required, every unknown, legacy, or malformed size path must fall back conservatively instead of guessing from compressed bytes.

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on code on Sep 18, 2026 19:38 UTC
    Code Review
    rust/lance-encoding/src/encodings/logical/primitive.rs:1
    @@ -3940,6 +4109,37 @@ impl VariableFullZipDecoder {
     }
     
     impl StructuralPageDecoder for VariableFullZipDecoder {
    +    fn decoded_bytes(&self, num_rows: u64) -> Result<u64> {
    +        if num_rows == 0 {
    +            return Ok(0);
    +        }
    +        let start = self.current_idx;
    +        let end = start + num_rows as usize;
    +        debug_assert!(
    +            end < self.data_starts.len(),
    +            "decoded_bytes({num_rows}) exceeds available rows; data_starts.len()={}",
    +            self.data_starts.len()
    +        );
    +        // The offsets buffer holds one entry per visible item plus a final sentinel.
    +        // offset_starts[i] is the byte position of the i-th row's first offset entry.
    +        let offset_end = self.offset_starts[end] + (self.bits_per_offset as usize / 8);
    +        let offset_bytes = (offset_end - self.offset_starts[start]) as u64;
    +
    +        let data_start = self.data_starts[start];
    +        let data_end = self.data_starts[end];
    +        let data_slice = &self.data.as_ref()[data_start..data_end];
    +        let offsets_slice = &self.offsets.as_ref()[self.offset_starts[start]..offset_end];
    +
    +        // Ask the decompressor for the pessimistic decoded size; fall back to the
    +        // compressed size when the decompressor can't report one.
    +        let value_bytes = self
    +            .decompressor
    +            .decompressed_size(data_slice, offsets_slice, self.bits_per_offset)
    +            .unwrap_or((data_end - data_start) as u64);

    Compressed bytes are not a conservative decoded-size bound. PackedStructVariablePerValueDecompressor still returns None, and FsstPerValueDecompressor similarly converts an unknown inner size into a compressed-byte estimate, so this path can select a batch whose decoded i32-offset data exceeds the budget and recreate #9223. Propagate “size unavailable” to the existing page-boundary fallback, or compute a proven upper bound for every supported decoder. This is the unresolved same finding from #8793.

    <details><summary>Reproducer</summary>

    I supplied one stored byte to an in-module variable decompressor that expands it to 1,024 bytes while retaining the default unavailable size report, then asserted that the planned size was at least the decoded allocation. cargo test -p lance-encoding test_variable_full_zip_unknown_size_never_underestimates -- --nocapture failed with planned=9, actual=1032.

    </details>

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on code on Sep 18, 2026 19:38 UTC
    Code Review
    rust/lance-encoding/src/encodings/physical/block.rs:1
    @@ -296,6 +304,14 @@ mod zstd {
                     level: Some(self.compression_level),
                 }
             }
    +
    +        fn decompressed_size_of_value(&self, compressed: &[u8]) -> Option<u64> {
    +            // compress() always writes an 8-byte LE decompressed-length prefix first.
    +            if compressed.len() < 8 {
    +                return None;
    +            }
    +            Some(u64::from_le_bytes(compressed[..8].try_into().unwrap()))

    The read path deliberately supports legacy raw Zstd frames through is_raw_stream_format, but this method always interprets their first eight bytes as the newer Lance length prefix. That makes byte planning reject valid existing data as a single row over the i32 limit. Use the same framing detection here and obtain the raw frame’s content size, or return unavailable so planning falls back at the page boundary. This is the unresolved compatibility finding from #8793.

    <details><summary>Reproducer</summary>

    I extended the existing raw-Zstd round-trip test to expect the decoded size of its 13-byte Hello, world! value. cargo test -p lance-encoding test_compress_zstd_raw_stream_format_and_decompress_with_length_prefixed -- --nocapture returned Some(29651633825625384) instead of Some(13).

    </details>

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on code on Sep 18, 2026 19:38 UTC
    Code Review
    rust/lance-encoding/src/encodings/physical/binary.rs:1
    @@ -318,6 +318,51 @@ fn chunk_offset_violation_error<T: Copy + Into<u64>>(offsets: &[T], chunk_len: u
     }
     
     impl MiniBlockDecompressor for BinaryMiniBlockDecompressor {
    +    /// Returns the exact decoded byte count for `num_rows` binary values starting at
    +    /// `offset_in_chunk` within the chunk.
    +    ///
    +    /// The binary mini-block format stores all offsets at the front of the single-element
    +    /// buffer followed by the value bytes. The byte count for a slice of values is simply
    +    /// `offset[offset_in_chunk + num_rows] - offset[offset_in_chunk]` (string data bytes)
    +    /// plus `(num_rows + 1) × bytes_per_offset` (the offset array slice itself).
    +    fn decoded_bytes_from_chunk(
    +        &self,
    +        chunk_buffers: &[crate::buffer::LanceBuffer],
    +        offset_in_chunk: u64,
    +        num_rows: u64,
    +    ) -> Option<u64> {
    +        if chunk_buffers.len() != 1 {
    +            return None;
    +        }
    +        let data = &chunk_buffers[0];
    +        let bytes_per_offset = self.bits_per_offset as usize / 8;
    +        let start = offset_in_chunk as usize;
    +        let end = (offset_in_chunk + num_rows) as usize;
    +        // Need at least end + 1 offset entries to read [start..=end].
    +        let needed = (end + 1) * bytes_per_offset;
    +        if data.len() < needed {
    +            return None;
    +        }
    +        let data_bytes = if self.bits_per_offset == 64 {
    +            let offsets = data.borrow_to_typed_slice::<u64>();
    +            let slice = offsets.as_ref();
    +            if slice.len() <= end {
    +                return None;
    +            }
    +            slice[end].wrapping_sub(slice[start])
    +        } else {
    +            let offsets = data.borrow_to_typed_slice::<u32>();
    +            let slice = offsets.as_ref();
    +            if slice.len() <= end {
    +                return None;
    +            }
    +            (slice[end].wrapping_sub(slice[start])) as u64

    These offsets come from the file, but wrapping_sub bypasses the monotonicity validation performed by decompress. A decreasing 64-bit offset produces a near-u64::MAX size, so the following addition panics when overflow checks are enabled and wraps to an underestimate otherwise, before the existing corrupt-file validator runs. Use checked subtraction with the same bounds rules and return unavailable or a typed corruption error. This is the unresolved validation finding from #8793.

    <details><summary>Reproducer</summary>

    I added decoded_bytes_from_chunk(&[chunk_u64(&[16, 8], &[])], 0, 1) to the existing corrupt-offset test and expected None. cargo test -p lance-encoding test_binary_miniblock_rejects_corrupt_offsets -- --nocapture panicked at the returned-size addition with attempt to add with overflow.

    </details>

    LuQQiu LuQQiu commented on Sep 18, 2026 20:00 UTC
    Contributor

    Ran a 3-way A/B on real data to compare batch shapes and scan throughput: baseline (main w/o this PR), page-clamp (this PR's original revision), and byte-budget (current head). Setup: 8 fragments (320K rows, 21 GiB) of a production-like 2.2-format table copied verbatim to local NVMe, warm page cache, 320-core host, Scanner::project([col]).batch_size(N), release builds, best-of-3 warm runs.

    Batch shapes (the regression surface):

    | column | batch_size | baseline | page-clamp (old rev) | byte-budget (this rev) |
    |---|---|---|---|---|
    | summary Utf8 ~832B/row (miniblock) | 32768 | 16 batches, max 32768 | 40 batches, max 8192 | 16 batches, max 32768 ✅ |
    | tags List\<Utf8\> | 8192 | 40 batches, min 7232 | 44 batches, min 7 | 40 batches, min 7232 ✅ |
    | tags List\<Utf8\> | 32768 | 16 batches, 7232–32768 | 16 batches, 15342–24658 | 16 batches, 7232–32768 ✅ |
    | full_content LargeUtf8 ~156KB/row | 8192/16384/32768 | unchanged | unchanged | unchanged |

    The page-clamp revision breaks requested batch sizes on ordinary i32-offset columns (2.5× more batches on a plain 800-byte string column at bs=32768; 7-row runt batches on a list column). The byte-budget revision reproduces baseline shapes exactly in every case.

    Throughput: identical to baseline within run-to-run noise (±3%) in all cells, e.g. full_content bs=8192: baseline 9.2 GiB/s vs byte-budget 9.0 GiB/s; summary/tags walls equal at equal shapes. The per-batch budget walk (offset-table reads, no decompression) is not measurable.

    Splitting-when-actually-needed is covered by the unit tests (budget-exhaustion tests with synthetic per-row byte reporting), since no real column here can exceed 2 GiB of i32-offset data within a fragment.

    LuQQiu LuQQiu requested changes on Sep 18, 2026 21:12 UTC
    Changes Requested Reviewer
    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on code on Sep 18, 2026 21:31 UTC
    Code Review
    rust/lance-encoding/src/encodings/logical/primitive.rs:1
    @@ -3940,6 +4109,37 @@ impl VariableFullZipDecoder {
     }
     
     impl StructuralPageDecoder for VariableFullZipDecoder {
    +    fn decoded_bytes(&self, num_rows: u64) -> Result<u64> {
    +        if num_rows == 0 {
    +            return Ok(0);
    +        }
    +        let start = self.current_idx;
    +        let end = start + num_rows as usize;
    +        debug_assert!(
    +            end < self.data_starts.len(),
    +            "decoded_bytes({num_rows}) exceeds available rows; data_starts.len()={}",
    +            self.data_starts.len()
    +        );
    +        // The offsets buffer holds one entry per visible item plus a final sentinel.
    +        // offset_starts[i] is the byte position of the i-th row's first offset entry.
    +        let offset_end = self.offset_starts[end] + (self.bits_per_offset as usize / 8);
    +        let offset_bytes = (offset_end - self.offset_starts[start]) as u64;
    +
    +        let data_start = self.data_starts[start];
    +        let data_end = self.data_starts[end];
    +        let data_slice = &self.data.as_ref()[data_start..data_end];
    +        let offsets_slice = &self.offsets.as_ref()[self.offset_starts[start]..offset_end];
    +
    +        // Ask the decompressor for the pessimistic decoded size; fall back to the
    +        // compressed size when the decompressor can't report one.
    +        let value_bytes = self
    +            .decompressor
    +            .decompressed_size(data_slice, offsets_slice, self.bits_per_offset)
    +            .unwrap_or((data_end - data_start) as u64);

    Fixed in ab493dab: the structural decoded-size planning code that used compressed bytes when an exact size was unavailable has been removed from this PR. The current change is limited to exact legacy v2.0 list-offset accounting, so this underestimation path is no longer introduced here.

    <!-- lance-gatekeeper-review-feedback:v2 agent=5eb6744645b965fcb8d0820ba71789d3 root=PRRC_kwDOHn_KdM7xZ_7o head=ab493dab9f2ef217ba6284e24572876e0d8e0e02 action=addressed -->

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on code on Sep 18, 2026 21:31 UTC
    Code Review
    rust/lance-encoding/src/encodings/physical/block.rs:1
    @@ -296,6 +304,14 @@ mod zstd {
                     level: Some(self.compression_level),
                 }
             }
    +
    +        fn decompressed_size_of_value(&self, compressed: &[u8]) -> Option<u64> {
    +            // compress() always writes an 8-byte LE decompressed-length prefix first.
    +            if compressed.len() < 8 {
    +                return None;
    +            }
    +            Some(u64::from_le_bytes(compressed[..8].try_into().unwrap()))

    Fixed in ab493dab: the structural Zstd size-planning changes have been removed from this PR, so legacy raw Zstd frames no longer pass through the incompatible length-prefix interpretation introduced by the earlier revision.

    <!-- lance-gatekeeper-review-feedback:v2 agent=5eb6744645b965fcb8d0820ba71789d3 root=PRRC_kwDOHn_KdM7xZ_7v head=ab493dab9f2ef217ba6284e24572876e0d8e0e02 action=addressed -->

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on code on Sep 18, 2026 21:31 UTC
    Code Review
    rust/lance-encoding/src/encodings/physical/binary.rs:1
    @@ -318,6 +318,51 @@ fn chunk_offset_violation_error<T: Copy + Into<u64>>(offsets: &[T], chunk_len: u
     }
     
     impl MiniBlockDecompressor for BinaryMiniBlockDecompressor {
    +    /// Returns the exact decoded byte count for `num_rows` binary values starting at
    +    /// `offset_in_chunk` within the chunk.
    +    ///
    +    /// The binary mini-block format stores all offsets at the front of the single-element
    +    /// buffer followed by the value bytes. The byte count for a slice of values is simply
    +    /// `offset[offset_in_chunk + num_rows] - offset[offset_in_chunk]` (string data bytes)
    +    /// plus `(num_rows + 1) × bytes_per_offset` (the offset array slice itself).
    +    fn decoded_bytes_from_chunk(
    +        &self,
    +        chunk_buffers: &[crate::buffer::LanceBuffer],
    +        offset_in_chunk: u64,
    +        num_rows: u64,
    +    ) -> Option<u64> {
    +        if chunk_buffers.len() != 1 {
    +            return None;
    +        }
    +        let data = &chunk_buffers[0];
    +        let bytes_per_offset = self.bits_per_offset as usize / 8;
    +        let start = offset_in_chunk as usize;
    +        let end = (offset_in_chunk + num_rows) as usize;
    +        // Need at least end + 1 offset entries to read [start..=end].
    +        let needed = (end + 1) * bytes_per_offset;
    +        if data.len() < needed {
    +            return None;
    +        }
    +        let data_bytes = if self.bits_per_offset == 64 {
    +            let offsets = data.borrow_to_typed_slice::<u64>();
    +            let slice = offsets.as_ref();
    +            if slice.len() <= end {
    +                return None;
    +            }
    +            slice[end].wrapping_sub(slice[start])
    +        } else {
    +            let offsets = data.borrow_to_typed_slice::<u32>();
    +            let slice = offsets.as_ref();
    +            if slice.len() <= end {
    +                return None;
    +            }
    +            (slice[end].wrapping_sub(slice[start])) as u64

    Fixed in ab493dab: the structural miniblock decoded-size planner and its unchecked offset arithmetic have been removed from this PR. The current legacy-path implementation reads normalized list offsets and does not use this malformed-metadata path.

    <!-- lance-gatekeeper-review-feedback:v2 agent=5eb6744645b965fcb8d0820ba71789d3 root=PRRC_kwDOHn_KdM7xZ_71 head=ab493dab9f2ef217ba6284e24572876e0d8e0e02 action=addressed -->

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on Sep 18, 2026 21:31 UTC
    Reviewer

    ✅ Gate recommendation: approve.

    Current head narrows the fix to legacy v2.0 decoding and removes the structural byte-planning code behind the prior blockers. The remaining offset-based mechanism splits only batches that would overflow Arrow’s i32 buffers, carries budgets across pages and nested lists, and preserves ordinary batch shapes. Structural v2.1+ coverage can proceed separately after #8793; it is no longer a prerequisite for this independently useful legacy fix.

    LuQQiu LuQQiu commented on Sep 18, 2026 21:45 UTC
    Contributor

    Good catch — confirmed and fixed in da148c23f. The common Utf8/Binary chain (ArrayEncoding::Binary → PrimitiveFieldDecoder) did bypass the budget via the max_rows_to_drain default; only the string-as-List<u8> compat path was covered.

    The fix adds PrimitivePageDecoder::variable_width_bytes(rows_to_skip, num_rows):

  • physical BinaryPageDecoder: exact, from its decoded_indices (value bytes + emitted offsets)

  • FsstPageDecoder: inner (compressed) count × 8 pessimistic bound

  • BasicPageDecoder: delegates to the values decoder

  • dictionary decoders: dictionary-size bounds

  • default None → PrimitiveFieldDecoder conservatively charges the whole budget so nothing stacks onto rows of an encoding that can't report sizes
  • PrimitiveFieldDecoder::max_rows_to_drain consults it under has_i32_offsets and takes the largest prefix that fits (binary search over the monotone byte count; no decoding happens during accounting).

    Added the requested tests in physical/binary.rs: byte accounting on a real physical binary page, PrimitiveFieldDecoder truncation at a reduced budget (full / full−1 / 0), and two real physical pages accumulating against one budget through SimpleStructDecoder (spans the page boundary when both fit, splits mid-page-2, stops at the boundary when only page 1 fits). Full lance-encoding (1848) + lance-file (183) suites pass.

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on code on Sep 18, 2026 21:55 UTC
    Code Review
    rust/lance-encoding/src/array_encoding/logical/primitive.rs:1
    @@ -368,6 +370,55 @@ impl LogicalPageDecoder for PrimitiveFieldDecoder {
             })
         }
     
    +    fn max_rows_to_drain(&self, num_rows: u64, byte_budget: u64) -> Result<DrainLimit> {
    +        if num_rows == 0 || !has_i32_offsets(&self.data_type) {
    +            return Ok(DrainLimit {
    +                rows: num_rows,
    +                bytes: 0,
    +            });
    +        }
    +        let Some(physical_decoder) = self.physical_decoder.as_ref() else {
    +            return Err(lance_core::Error::internal(format!(
    +                "max_rows_to_drain was called on primitive field decoder for data type {} on column {} but the decoder was never awaited",
    +                self.data_type, self.column_index
    +            )));
    +        };
    +        match physical_decoder.variable_width_bytes(self.rows_drained, num_rows)? {
    +            Some(bytes) if bytes <= byte_budget => Ok(DrainLimit {
    +                rows: num_rows,
    +                bytes,
    +            }),
    +            Some(_) => {

    A conservative upper bound is not proof that the first row exceeds the i32 offset domain. The trait explicitly permits upper bounds, yet this branch can return zero rows and the stream root converts that into a terminal NotSupported error without decoding. The new Binary counter already reproduces this for an exact-fit value because it adds offset-buffer bytes to a budget whose invariant is the maximum offset value; FSST and dictionary bounds are looser. This regresses the stable legacy reader for otherwise valid data. Track only constrained offset-domain consumption when it is exact, or distinguish estimates and isolate or decode the row before declaring it impossible.

    <details><summary>Reproducer</summary>

    I added this beside the new physical-binary tests and ran cargo test -p lance-encoding test_single_binary_row_that_exactly_fills_offset_budget_is_accepted -- --nocapture:

    #[test]
    fn test_single_binary_row_that_exactly_fills_offset_budget_is_accepted() {
        use crate::array_encoding::logical::primitive::PrimitiveFieldDecoder;
        use crate::decoder::LogicalPageDecoder;
    
        let decoder = PrimitiveFieldDecoder::new_from_data(
            Arc::new(binary_page(&[100])), DataType::Utf8, 1, false,
        );
        let limit = decoder.max_rows_to_drain(1, 100).unwrap();
        assert_eq!(limit.rows, 1);
    }
    

    It failed with left: 0, right: 1. The value offset ends at 100 and therefore fits the scaled offset budget; only the newly charged offset-buffer storage pushes the reported size over it.

    </details>

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on code on Sep 18, 2026 21:55 UTC
    Code Review
    rust/lance-encoding/src/array_encoding/logical/primitive.rs:1
    @@ -368,6 +370,55 @@ impl LogicalPageDecoder for PrimitiveFieldDecoder {
             })
         }
     
    +    fn max_rows_to_drain(&self, num_rows: u64, byte_budget: u64) -> Result<DrainLimit> {
    +        if num_rows == 0 || !has_i32_offsets(&self.data_type) {
    +            return Ok(DrainLimit {
    +                rows: num_rows,
    +                bytes: 0,
    +            });
    +        }
    +        let Some(physical_decoder) = self.physical_decoder.as_ref() else {
    +            return Err(lance_core::Error::internal(format!(
    +                "max_rows_to_drain was called on primitive field decoder for data type {} on column {} but the decoder was never awaited",
    +                self.data_type, self.column_index
    +            )));
    +        };
    +        match physical_decoder.variable_width_bytes(self.rows_drained, num_rows)? {
    +            Some(bytes) if bytes <= byte_budget => Ok(DrainLimit {
    +                rows: num_rows,
    +                bytes,
    +            }),
    +            Some(_) => {
    +                // Largest prefix of the request that still fits the budget.
    +                // `variable_width_bytes` is monotonically non-decreasing in the row
    +                // count; zero rows always fit.
    +                let mut fits = 0u64;
    +                let mut too_big = num_rows;
    +                while fits + 1 < too_big {
    +                    let mid = fits + (too_big - fits) / 2;
    +                    let mid_bytes = physical_decoder
    +                        .variable_width_bytes(self.rows_drained, mid)?
    +                        .unwrap_or(0);
    +                    if mid_bytes <= byte_budget {
    +                        fits = mid;
    +                    } else {
    +                        too_big = mid;
    +                    }
    +                }
    +                let bytes = physical_decoder
    +                    .variable_width_bytes(self.rows_drained, fits)?
    +                    .unwrap_or(0);
    +                Ok(DrainLimit { rows: fits, bytes })
    +            }
    +            // The encoding cannot report sizes: conservatively charge the whole
    +            // budget so nothing stacks onto this page's rows within the batch.
    +            None => Ok(DrainLimit {

    None does not isolate an unreportable page. The first unknown page consumes the remaining budget, but ChildState still asks the next page with byte_budget == 0; this arm then accepts every row and reports zero additional bytes. Two unknown pages can therefore be concatenated over i32 max and recreate #9223. FixedSizeBinaryDecoder is a supported decoder that still uses the default None. Admit an unknown page only on a fresh budget and end that batch after it, or supply exact accounting.

    <details><summary>Reproducer</summary>

    I added this beside the new physical-binary tests and ran cargo test -p lance-encoding test_unknown_size_page_stops_before_next_unknown_page -- --nocapture:

    #[test]
    fn test_unknown_size_page_stops_before_next_unknown_page() {
        use crate::array_encoding::logical::primitive::PrimitiveFieldDecoder;
        use crate::array_encoding::logical::r#struct::SimpleStructDecoder;
        use crate::decoder::{DecoderReady, LogicalPageDecoder};
        use arrow_schema::{Field as ArrowField, Fields};
        use std::collections::VecDeque;
    
        let fields = Fields::from(vec![ArrowField::new("value", DataType::Utf8, false)]);
        let mut root = SimpleStructDecoder::new(fields, 6);
        for _ in 0..2 {
            root.accept_child(DecoderReady {
                decoder: Box::new(PrimitiveFieldDecoder::new_from_data(
                    Arc::new(NeverDecodedStub), DataType::Utf8, 3, false,
                )),
                path: VecDeque::from([0]),
            }).unwrap();
        }
        let limit = root.max_rows_to_drain(6, 100).unwrap();
        assert_eq!((limit.rows, limit.bytes), (3, 100));
    }
    

    It failed with left: (6, 100), right: (3, 100), confirming that the second unknown page bypasses the exhausted budget.

    </details>

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on Sep 18, 2026 21:55 UTC
    Reviewer

    ❌ Gate recommendation: request changes.

    Physical accounting now reaches the common legacy Binary path, but the new size protocol is not yet safe at its fallback boundaries: an unavailable size can still let multiple pages stack past the i32 limit, while a conservative bound can be mistaken for proof that a valid row is undecodable. Keep exact offset-domain accounting where available, but make unknown or estimated cases fall back to an isolated page or row (or represent exactness explicitly) so the stable legacy reader neither recreates #9223 nor rejects previously readable data.

    LuQQiu LuQQiu commented on Sep 18, 2026 21:56 UTC
    Contributor

    Both points addressed in d0a034feb.

    P1 (unknown-size fallback): confirmed — the fallback returned rows = all, bytes = 0 once the budget was reduced, so unknown-size pages stacked past the limit exactly as described. Fixed: an unknown-size page is accepted only while the batch has accumulated no variable-width bytes (byte_budget >= I32_OFFSET_BYTE_BUDGET, which only holds before any consumption since budgets only decrease), charging the entire budget; otherwise it contributes zero rows so the batch ends before it. Two unknown-size pages now split at the page boundary — regression test added (test_unknown_size_pages_split_at_page_boundaries, using a stub with the default variable_width_bytes).

    For FixedSizeBinaryDecoder specifically I went one step further than the fallback: it now reports exact sizes (num_rows byte_width), since leaving fixed-size string columns on the conservative page-per-batch fallback would have been a batch-shape regression for a real, current encoding. The requested two-page test is there (test_fixed_size_binary_pages_split_by_byte_budget): pages fit individually but not together, and the batch splits at exactly the row the budget allows (plus a boundary-exact case).

    Modeling nit: agreed and applied — the budget now counts value bytes only (dropped the (num_rows + 1) 4 offsets term in the physical binary decoder and the per-row paddings in the dictionary decoders); the trait doc now states the contract explicitly.

    lance-encoding (1850) + lance-file (183) suites pass, clippy clean.

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on code on Sep 18, 2026 22:03 UTC
    Code Review
    rust/lance-encoding/src/array_encoding/logical/primitive.rs:1
    @@ -368,6 +370,55 @@ impl LogicalPageDecoder for PrimitiveFieldDecoder {
             })
         }
     
    +    fn max_rows_to_drain(&self, num_rows: u64, byte_budget: u64) -> Result<DrainLimit> {
    +        if num_rows == 0 || !has_i32_offsets(&self.data_type) {
    +            return Ok(DrainLimit {
    +                rows: num_rows,
    +                bytes: 0,
    +            });
    +        }
    +        let Some(physical_decoder) = self.physical_decoder.as_ref() else {
    +            return Err(lance_core::Error::internal(format!(
    +                "max_rows_to_drain was called on primitive field decoder for data type {} on column {} but the decoder was never awaited",
    +                self.data_type, self.column_index
    +            )));
    +        };
    +        match physical_decoder.variable_width_bytes(self.rows_drained, num_rows)? {
    +            Some(bytes) if bytes <= byte_budget => Ok(DrainLimit {
    +                rows: num_rows,
    +                bytes,
    +            }),
    +            Some(_) => {
    +                // Largest prefix of the request that still fits the budget.
    +                // `variable_width_bytes` is monotonically non-decreasing in the row
    +                // count; zero rows always fit.
    +                let mut fits = 0u64;
    +                let mut too_big = num_rows;
    +                while fits + 1 < too_big {
    +                    let mid = fits + (too_big - fits) / 2;
    +                    let mid_bytes = physical_decoder
    +                        .variable_width_bytes(self.rows_drained, mid)?
    +                        .unwrap_or(0);
    +                    if mid_bytes <= byte_budget {
    +                        fits = mid;
    +                    } else {
    +                        too_big = mid;
    +                    }
    +                }
    +                let bytes = physical_decoder
    +                    .variable_width_bytes(self.rows_drained, fits)?
    +                    .unwrap_or(0);
    +                Ok(DrainLimit { rows: fits, bytes })
    +            }
    +            // The encoding cannot report sizes: conservatively charge the whole
    +            // budget so nothing stacks onto this page's rows within the batch.
    +            None => Ok(DrainLimit {

    Fixed in d0a034f: unknown-size pages now stop at the page boundary once any variable-width budget is consumed, and FixedSizeBinaryDecoder reports exact value bytes. The focused unknown-page and fixed-size-binary regressions both pass on this head.

    <!-- lance-gatekeeper-review-feedback:v2 agent=5eb6744645b965fcb8d0820ba71789d3 root=PRRC_kwDOHn_KdM7xdWT1 head=d0a034feb5e40995397c08444f7fc2764d01c1e5 action=addressed -->

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on Sep 18, 2026 22:04 UTC
    Reviewer

    ❌ Gate recommendation: request changes.

    The unknown-size page issue is fixed, but the upper-bound finding remains: FSST’s conservative 8× estimate can produce a zero-row plan that the stream treats as proof that one otherwise readable row exceeds the i32 offset domain. Keep exact accounting for exact decoders, but distinguish estimates and isolate or decode one row before returning NotSupported.

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on code on Sep 18, 2026 22:07 UTC
    Code Review
    rust/lance-encoding/src/array_encoding/logical/primitive.rs:1
    @@ -368,6 +370,55 @@ impl LogicalPageDecoder for PrimitiveFieldDecoder {
             })
         }
     
    +    fn max_rows_to_drain(&self, num_rows: u64, byte_budget: u64) -> Result<DrainLimit> {
    +        if num_rows == 0 || !has_i32_offsets(&self.data_type) {
    +            return Ok(DrainLimit {
    +                rows: num_rows,
    +                bytes: 0,
    +            });
    +        }
    +        let Some(physical_decoder) = self.physical_decoder.as_ref() else {
    +            return Err(lance_core::Error::internal(format!(
    +                "max_rows_to_drain was called on primitive field decoder for data type {} on column {} but the decoder was never awaited",
    +                self.data_type, self.column_index
    +            )));
    +        };
    +        match physical_decoder.variable_width_bytes(self.rows_drained, num_rows)? {
    +            Some(bytes) if bytes <= byte_budget => Ok(DrainLimit {
    +                rows: num_rows,
    +                bytes,
    +            }),
    +            Some(_) => {

    This remains on d0a034f. The exact Binary counter is fixed, but FsstPageDecoder::variable_width_bytes still returns compressed_bytes * 8, and this branch still treats that upper bound as exact overflow proof.

    <details><summary>Current reproducer</summary>

    I added an in-module test that compressed one valid 88,000-byte Utf8 row with fsst::fsst::compress, decoded the resulting page successfully with FsstPageDecoder::decode, and used the decoded value length as the scaled byte budget. The test then asserted:

    assert!(actual_value_bytes < compressed_len * 8);
    let decoder = PrimitiveFieldDecoder::new_from_data(
        fsst_decoder, DataType::Utf8, 1, false,
    );
    let limit = decoder.max_rows_to_drain(1, actual_value_bytes).unwrap();
    assert_eq!(limit.rows, 1);
    

    cargo test -p lance-encoding conservative_fsst_bound_is_not_exact_overflow_proof -- --nocapture failed with left: 0, right: 1; the temporary test was then removed.

    </details>

    <!-- lance-gatekeeper-review-feedback:v2 agent=5eb6744645b965fcb8d0820ba71789d3 root=PRRC_kwDOHn_KdM7xdWTu head=d0a034feb5e40995397c08444f7fc2764d01c1e5 action=keep -->

    LuQQiu LuQQiu commented on Sep 18, 2026 22:42 UTC
    Contributor

    Follow-ups on the remaining round-3 findings, in 9dd6834:

  • Over-estimation regressions (FSST hard error, dictionary inflation): the root clamp now always advances a batch by at least one row instead of erroring. A row whose estimated size exceeds the whole budget (e.g. FSST's 8× bound on a large compressed value) is emitted as its own single-row batch and decodes fine; a genuinely oversized row then hits the same arrow-level offset error it always did — availability is never worse than main, and the single_row_over_budget error class is gone entirely (which also moots the missing-context complaint about that message).

  • Dictionary: now exact — the u8 indices are decoded (cheap, and no value decoding) and each requested row's dictionary entry length is summed, replacing the max-entry-length × rows over-estimate.

  • Iterator error fuse: the blocking iterator zeroes rows_remaining on error, matching the stream's behavior, instead of re-emitting the error for every remaining batch. The clamp logic is shared between both paths (clamp_rows_to_i32_budget).

  • FSST 8× early splitting remains as a documented conservative bound: computing exact decompressed lengths needs a length-only scan API in the fsst crate (symbol-table parsing must match decompress byte-for-byte), which I'd rather do as a focused follow-up than inline here. With the min-one-row rule the bound can only split batches of >256 MiB compressed FSST data early — it can no longer fail anything.
  • Note on sequencing: the FixedSizeBinary gap, the unknown-size stacking, and the offsets-in-budget modeling from this review were already fixed in d0a034fe (pushed while this review was running) — the review ran against da148c23. Current head: exact accounting for physical binary, fixed-size-binary, and both dictionary decoders; 8× bound for FSST; unknown-size encodings take a page alone at batch start and never stack.

    lance-encoding (1851) + lance-file (183) pass, clippy clean.

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on code on Sep 18, 2026 22:47 UTC
    Code Review
    rust/lance-encoding/src/array_encoding/logical/primitive.rs:1
    @@ -368,6 +370,55 @@ impl LogicalPageDecoder for PrimitiveFieldDecoder {
             })
         }
     
    +    fn max_rows_to_drain(&self, num_rows: u64, byte_budget: u64) -> Result<DrainLimit> {
    +        if num_rows == 0 || !has_i32_offsets(&self.data_type) {
    +            return Ok(DrainLimit {
    +                rows: num_rows,
    +                bytes: 0,
    +            });
    +        }
    +        let Some(physical_decoder) = self.physical_decoder.as_ref() else {
    +            return Err(lance_core::Error::internal(format!(
    +                "max_rows_to_drain was called on primitive field decoder for data type {} on column {} but the decoder was never awaited",
    +                self.data_type, self.column_index
    +            )));
    +        };
    +        match physical_decoder.variable_width_bytes(self.rows_drained, num_rows)? {
    +            Some(bytes) if bytes <= byte_budget => Ok(DrainLimit {
    +                rows: num_rows,
    +                bytes,
    +            }),
    +            Some(_) => {

    Fixed in 9dd6834: both the stream and blocking iterator now clamp a zero-row estimate to one row before decoding. The prior real-FSST reproducer now emits and decodes its valid 88,000-byte row successfully, while genuinely oversized rows retain the Arrow-layer failure. The new over-budget stream regression and dictionary suite also pass.

    <!-- lance-gatekeeper-review-feedback:v2 agent=5eb6744645b965fcb8d0820ba71789d3 root=PRRC_kwDOHn_KdM7xdWTu head=9dd683427f91d67e668d7f0a69196ea986b93fee action=addressed -->

    lance-gatekeeper[bot] lance-gatekeeper[bot] commented on Sep 18, 2026 22:48 UTC
    Reviewer

    ✅ Gate recommendation: approve.

    The remaining estimate-bound failure is fixed: conservative FSST bounds now force a one-row batch instead of a pre-decode failure, while exact decoders continue splitting at safe value-byte boundaries. The shared clamp covers both async and blocking decode paths, and the dictionary path now accounts for selected values exactly.

    ChilePiquin ChilePiquin approved these changes on Sep 21, 2026 16:49 UTC
    Approved Reviewer

    Approved these changes.

    LuQQiu LuQQiu approved these changes on Sep 21, 2026 17:18 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    lance-gatefixer[bot] lance-gatefixer[bot]
    Labels
    risk: low confidence: 74.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 56.2% (MEDIUM) · Higher = larger blast radius
    56.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 74.7% · Lower = rushed or shallow review
    74.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 14.2% · Safe to merge
    14.2%