This is an automated email from the ASF dual-hosted git repository.
zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-go.git
The following commit(s) were added to refs/heads/main by this push:
new 186917be fix(arrow/ipc): account for the offset when truncating union
buffers (#1612)
186917be is described below
commit 186917be0b1344234bf83769050a6b124fd5ad9e
Author: Shivam Sharma <[email protected]>
AuthorDate: Thu Nov 19 02:01:16 2026 +0530
fix(arrow/ipc): account for the offset when truncating union buffers (#1612)
### Rationale for this change
The IPC writer fails on a sliced sparse or dense union array when its type
ids buffer has no spare capacity after the data:
```go
typeIDs := memory.NewBufferBytes([]byte{0, 1, 0, 1, 0, 1, 0, 1, 0, 1})
u := array.NewSparseUnion(arrow.SparseUnionOf(fields, codes), 10, children,
typeIDs, 0)
slice := array.NewSlice(u, 3, 7)
// writing a record batch that holds slice:
// arrow/ipc: unknown error while writing: runtime error: slice bounds out
of range [:13] with capacity 10
```
Arrays imported through the C Data interface have buffers like this, since
the imported memory is exactly `(offset + length) * byteWidth` bytes long.
`getTruncatedBuffer` slices the buffer starting at `offset * byteWidth`,
but caps the length at the full `buf.Len()` instead of the bytes left after the
start. With a non-zero offset the slice ends past the end of the buffer. When
the buffer has spare capacity there is no panic, but the bytes past the end of
the buffer are written along with the type ids.
### What changes are included in this PR?
`getTruncatedBuffer` now caps the length at `buf.Len() - offset*byteWidth`.
This is the same bound the fixed-width and binary view cases in `visit` already
use. `getTruncatedBuffer` is only used for the union type ids and for the dense
union value offsets when the offset is zero, so this one change covers both
union types. I checked the other places in `writer.go` that slice buffers by
offset and they already account for it.
### Are these changes tested?
Yes. `TestGetTruncatedBuffer` checks the function directly on a buffer with
no spare capacity, with byte widths 1 and 4. `TestWriteSlicedUnion` writes
slices of a sparse and a dense union built on such buffers, reads them back,
and checks that the result passes `ValidateFull` and equals the input, using a
checked allocator. On `main`, `TestGetTruncatedBuffer` panics and every slice
with a non-zero offset in `TestWriteSlicedUnion` fails with the error above.
Both pass with this change.
`go test ./arrow/ipc/...` passes, as do runs with `-tags assert,test
-short` and with `-tags assert,test,noasm -short`. `go vet`, gofmt and
golangci-lint report nothing for the changed package.
### Are there any user-facing changes?
Yes, a bug fix. Sliced union arrays whose buffers have no spare capacity
can now be written with the IPC writer, and the written type ids buffer no
longer includes bytes from outside the array's buffer.
AI assistance: I used Claude Code (Anthropic) to find this bug and write
the fix and the test. I reviewed the code and ran the tests locally.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---
arrow/ipc/writer.go | 3 +-
arrow/ipc/writer_test.go | 103 +++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 105 insertions(+), 1 deletion(-)
diff --git a/arrow/ipc/writer.go b/arrow/ipc/writer.go
index a32a8530..1d116594 100644
--- a/arrow/ipc/writer.go
+++ b/arrow/ipc/writer.go
@@ -1142,7 +1142,8 @@ func getTruncatedBuffer(offset, length int64, byteWidth
int32, buf *memory.Buffe
paddedLen := paddedLength(length*int64(byteWidth), kArrowAlignment)
if offset != 0 || paddedLen < int64(buf.Len()) {
- return memory.SliceBuffer(buf, int(offset*int64(byteWidth)),
int(min(paddedLen, int64(buf.Len()))))
+ start := offset * int64(byteWidth)
+ return memory.SliceBuffer(buf, int(start), int(min(paddedLen,
int64(buf.Len())-start)))
}
buf.Retain()
return buf
diff --git a/arrow/ipc/writer_test.go b/arrow/ipc/writer_test.go
index 0b38bd68..5e9fd1ff 100644
--- a/arrow/ipc/writer_test.go
+++ b/arrow/ipc/writer_test.go
@@ -375,6 +375,109 @@ func TestNewTruncatedBitmap(t *testing.T) {
assert.Equal(t, 8, bitutil.CountSetBits(result.Bytes(), 0, 8))
}
+func TestGetTruncatedBuffer(t *testing.T) {
+ assert.Nil(t, getTruncatedBuffer(0, 0, 1, nil), "input buffer is null")
+
+ // the buffer is exactly as long as the data, with no padding after it
+ buf := memory.NewBufferBytes([]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
+ defer buf.Release()
+
+ result := getTruncatedBuffer(0, 10, 1, buf)
+ defer result.Release()
+ assert.Same(t, buf, result, "no truncation necessary")
+
+ result = getTruncatedBuffer(6, 4, 1, buf)
+ defer result.Release()
+ assert.Equal(t, []byte{6, 7, 8, 9}, result.Bytes(), "truncate for
offset")
+
+ result = getTruncatedBuffer(1, 2, 4, buf)
+ defer result.Release()
+ assert.Equal(t, []byte{4, 5, 6, 7, 8, 9}, result.Bytes(), "truncate for
offset with byte width")
+
+ buf = memory.NewBufferBytes(make([]byte, 128))
+ defer buf.Release()
+
+ result = getTruncatedBuffer(0, 8, 1, buf)
+ defer result.Release()
+ assert.Equal(t, 64, result.Len(), "truncate to smaller buffer")
+
+ result = getTruncatedBuffer(100, 8, 1, buf)
+ defer result.Release()
+ assert.Equal(t, 28, result.Len(), "truncate for offset to the end of
the buffer")
+}
+
+func TestWriteSlicedUnion(t *testing.T) {
+ mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer mem.AssertSize(t, 0)
+
+ const n = 10
+ // buffers that are exactly as long as the data, as produced for
+ // example by the C Data interface, with no padding after them
+ typeIDs := memory.NewBufferBytes([]byte{0, 1, 0, 1, 0, 1, 0, 1, 0, 1})
+ valueOffsets := memory.NewBufferBytes(arrow.Int32Traits.CastToBytes(
+ []int32{0, 0, 1, 1, 2, 2, 3, 3, 4, 4}))
+
+ sparseInts, _, err := array.FromJSON(mem, arrow.PrimitiveTypes.Int32,
+ strings.NewReader(`[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`))
+ require.NoError(t, err)
+ defer sparseInts.Release()
+ sparseStrs, _, err := array.FromJSON(mem, arrow.BinaryTypes.String,
+ strings.NewReader(`["a", "b", "c", "d", "e", "f", "g", "h",
"i", "j"]`))
+ require.NoError(t, err)
+ defer sparseStrs.Release()
+
+ denseInts, _, err := array.FromJSON(mem, arrow.PrimitiveTypes.Int32,
+ strings.NewReader(`[0, 2, 4, 6, 8]`))
+ require.NoError(t, err)
+ defer denseInts.Release()
+ denseStrs, _, err := array.FromJSON(mem, arrow.BinaryTypes.String,
+ strings.NewReader(`["b", "d", "f", "h", "j"]`))
+ require.NoError(t, err)
+ defer denseStrs.Release()
+
+ fields := []arrow.Field{
+ {Name: "i", Type: arrow.PrimitiveTypes.Int32, Nullable: true},
+ {Name: "s", Type: arrow.BinaryTypes.String, Nullable: true},
+ }
+ codes := []arrow.UnionTypeCode{0, 1}
+
+ sparse := array.NewSparseUnion(arrow.SparseUnionOf(fields, codes), n,
+ []arrow.Array{sparseInts, sparseStrs}, typeIDs, 0)
+ defer sparse.Release()
+ dense := array.NewDenseUnion(arrow.DenseUnionOf(fields, codes), n,
+ []arrow.Array{denseInts, denseStrs}, typeIDs, valueOffsets, 0)
+ defer dense.Release()
+
+ for _, arr := range []arrow.Array{sparse, dense} {
+ t.Run(arr.DataType().Name(), func(t *testing.T) {
+ for _, sl := range []struct{ beg, end int64 }{{0, 4},
{3, 7}, {5, n}, {9, n}} {
+ t.Run(fmt.Sprintf("%d-%d", sl.beg, sl.end),
func(t *testing.T) {
+ slice := array.NewSlice(arr, sl.beg,
sl.end)
+ defer slice.Release()
+
+ schema :=
arrow.NewSchema([]arrow.Field{{Name: "u", Type: arr.DataType()}}, nil)
+ rec := array.NewRecordBatch(schema,
[]arrow.Array{slice}, int64(slice.Len()))
+ defer rec.Release()
+
+ var buf bytes.Buffer
+ w := NewWriter(&buf,
WithSchema(schema), WithAllocator(mem))
+ require.NoError(t, w.Write(rec))
+ require.NoError(t, w.Close())
+
+ r, err := NewReader(&buf,
WithAllocator(mem))
+ require.NoError(t, err)
+ defer r.Release()
+
+ require.True(t, r.Next())
+ got := r.RecordBatch().Column(0)
+ require.NoError(t,
array.ValidateFull(got))
+ assert.Truef(t, array.Equal(slice,
got), "got %s, want %s", got, slice)
+ })
+ }
+ })
+ }
+}
+
func TestGetZeroBasedValueOffsets(t *testing.T) {
alloc := memory.NewCheckedAllocator(memory.DefaultAllocator)
defer alloc.AssertSize(t, 0)