← Back to Pull requests

fix: Export a zero offset for empty arrays with an empty offsets buffer #966

Merged
rustyconover merged 3 files (151 lines) on Oct 17, 2026 04:31 UTC
View on GitHub
rustyconover rustyconover commented on Oct 16, 2026 14:58 UTC
Author

An empty variable-size array (string, binary, their large variants, list, large list, map) needs one offset, offsets[0], even though it has no elements. The C data interface doesn't carry buffer sizes, so consumers read offsets[0] without checking. Arrow C++'s ImportArray() does this, for example.

IPC allows a zero-length offsets buffer for an empty array, and nanoarrow's own encoder writes one, since ArrowArrayViewSetArray() sizes the offsets buffer of a length-0 array as 0 bytes. When such an array is decoded, ArrowArrayFinishBuilding() leaves the empty buffer as it is. If the buffer is NULL, it reserves one byte but never initializes it. Either way, the exported ArrowArray has an offsets pointer with no valid offset behind it. With shared buffers, that pointer points into whatever follows in the message body.

I found this moving a DuckDB extension's IPC from Arrow C++ to nanoarrow. A MAP column holding a single NULL round-trips through a worker as an empty key/value child. After nanoarrow decoded it and Arrow C++ imported it, about one run in four failed ValidateFull() with array starts at negative offset -2099303496. The value depends on whatever bytes happen to sit in the message body after the empty buffer.

With this PR, ArrowArrayFinalizeBuffers() gives a DATA_OFFSET buffer of an empty array, if it holds no bytes, a single zero offset of the right width (4 or 8 bytes). This works for both owned and shared buffers: the shared reference is released, and the buffer is replaced with an owned one. Arrays with elements are left alone, so validation still reports a truncated offsets buffer as before (ArrayTestExplicitValidationLevel checks this).

Things worth a look in review:

  • ArrowArrayFinalizeBuffers() only runs at NANOARROW_VALIDATION_LEVEL_DEFAULT or higher, because it assumes CPU data access. Decoding at MINIMAL or NONE still exports the empty buffer unchanged. I've left that gate alone. Putting a host buffer behind a device array would be worse.

  • An alternative would be for the encoder to always write offsets[0], as Arrow C++ does. That only covers streams nanoarrow wrote itself, though. Other writers can emit zero-length offsets buffers too, so the fix belongs on the decode side.
  • Tests: NanoarrowIpcWriter.RoundtripEmptyArraysHaveZeroOffset writes a zero-row batch with string, large_binary and list<int32> columns. It reads the batch back with and without shared buffers, then checks that each exported offsets buffer has a size of 4 or 8 bytes and holds 0. The test fails on main, where the buffers are 0 bytes. ctest passes locally (macOS arm64, Debug, 389 tests). The touched suites (array, IPC writer/reader/decoder) pass under ASan/UBSan. array_test needs allocator_may_return_null=1 there, as it does on main.

    🤖 Generated with Claude Code

    Diff: 151 lines (+151 / -0) across 3 files Reviewer: paleolimbot Review duration: 813m
    All Vouch review confidence checks passed
    Residual risk 0.04 = Change Risk (0.36) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.36 · 151 lines diff across 3 files
    0.36
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.94 · 4 substantive comment(s)
    0.94
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    88%
    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.301
    Real PR Conversation Timeline
    7 items
    codecov-commenter codecov-commenter commented on Oct 16, 2026 15:04 UTC
    Contributor

    Codecov Report


    :white_check_mark: All modified and coverable lines are covered by tests.
    :white_check_mark: Project coverage is 78.28%. Comparing base (e5f3d0a) to head (31f9949).

    <details><summary>Additional details and impacted files</summary>

    @@            Coverage Diff             @@
    ##             main     #966      +/-   ##
    ==========================================
    + Coverage   78.24%   78.28%   +0.04%     
    ==========================================
      Files         106      106              
      Lines       16901    16906       +5     
      Branches     2012     2012              
    ==========================================
    + Hits        13224    13235      +11     
    + Misses       2435     2429       -6     
      Partials     1242     1242              
    

    </details>

    :umbrella: View full report in Codecov by Harness.
    :loudspeaker: Have feedback on the report? Share it here.
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • </details>

    paleolimbot paleolimbot commented on code on Oct 16, 2026 15:13 UTC
    Code Review
    src/nanoarrow/ipc/writer_test.cc:1
    @@ -726,3 +726,91 @@ TEST(NanoarrowIpcWriter, CompressedDictionaryStream) {
       EXPECT_EQ(std::string(v0.data, v0.size_bytes), "foo");
       EXPECT_EQ(std::string(v1.data, v1.size_bytes), "bar");
     }
    +
    +TEST(NanoarrowIpcWriter, RoundtripEmptyArraysHaveZeroOffset) {
    +  // nanoarrow's encoder writes a zero-length offsets buffer for an empty array (as IPC
    +  // permits). Decoded arrays must still export offsets[0] == 0 through the C data
    +  // interface, which carries no buffer sizes, whether or not the body is shared.
    +  struct ArrowError error;

    Probably this is more appropriate as a test for ArrowArrayFinalizeBuffers in array_test.cc, although I get the motivating use case was IPC reads.

    The IPC read case is I think better tested with a record batch bytes fixture (you can construct the schema programmatically to save space).

    paleolimbot paleolimbot approved these changes on Oct 16, 2026 15:17 UTC
    Approved Reviewer

    I think we should test this differently, but the change itself is great...thank you!

    It may be a bit of a gotcha that reducing the verification level may produce arrays that will crash Arrow C++. It came up a while back that we should possibly avoid reading any buffers of arrays with length 0 and I thought Arrow C++ fixed it (I believe we fixed it here); however, this is still a good change to make.

    rustyconover rustyconover commented on code on Oct 16, 2026 15:59 UTC
    Code Review
    src/nanoarrow/ipc/writer_test.cc:1
    @@ -726,3 +726,91 @@ TEST(NanoarrowIpcWriter, CompressedDictionaryStream) {
       EXPECT_EQ(std::string(v0.data, v0.size_bytes), "foo");
       EXPECT_EQ(std::string(v1.data, v1.size_bytes), "bar");
     }
    +
    +TEST(NanoarrowIpcWriter, RoundtripEmptyArraysHaveZeroOffset) {
    +  // nanoarrow's encoder writes a zero-length offsets buffer for an empty array (as IPC
    +  // permits). Decoded arrays must still export offsets[0] == 0 through the C data
    +  // interface, which carries no buffer sizes, whether or not the body is shared.
    +  struct ArrowError error;

    Moved. ArrayTestFinishBuildingEmptyArrayOffsets in array_test.cc checks ArrowArrayFinishBuildingDefault() on empty string, large binary and list arrays, both when the offsets buffer was never allocated and when it has 0 bytes over storage filled with 0xff. The IPC case is now NanoarrowIpcDecodeEmptyArrayOffsets in decoder_test.cc. It uses a record batch bytes fixture (one row of struct<l: list<string>, i: int32>, with the schema built in code) where the empty string array's 0-byte offsets buffer sits at the same body offset as i's data, 0x55555555. It decodes with both a borrowed and a shared body. Both tests fail on main. I removed the round-trip test from writer_test.cc.

    rustyconover rustyconover commented on Oct 16, 2026 15:59 UTC
    Author

    Thanks! Agreed on the gotcha with lower validation levels. I ran into exactly that: decoding at NANOARROW_VALIDATION_LEVEL_MINIMAL (to match what Arrow C++'s reader checks) skips ArrowArrayFinalizeBuffers(), so the empty offsets buffer is exported unchanged. I worked around it on my side. It might be worth decoupling the zero offset (and the existing non-NULL data pointer) from the validation level for arrays we know are on the CPU, which the IPC decoder's output always is. I'm happy to do that as a follow-up if you think it's worthwhile.

    paleolimbot paleolimbot approved these changes on Oct 17, 2026 04:31 UTC
    Approved Reviewer

    Thank you!

    Not sure what the best solution is for minimal validation here...default validation is probably not much slower and would be what I'd recommend here (if it is a lot slower for some reason we could separate CPU access from validation level in a follow up as you noted).

    Reviewers
    Assignees
    rustyconover rustyconover
    Labels
    risk: low confidence: 88.6% 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: 36.0% (MEDIUM) · Higher = larger blast radius
    36.0%
    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: 88.6% · Lower = rushed or shallow review
    88.6%
    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: 4.1% · Safe to merge
    4.1%