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 c035068b fix(arrow): keep view data blocks within int32 offsets (#1617)
c035068b is described below

commit c035068b743d7a3a84c59cf1e26d109280485015
Author: Harrison Crosse <[email protected]>
AuthorDate: Wed Nov 18 16:46:59 2026 -0500

    fix(arrow): keep view data blocks within int32 offsets (#1617)
    
    ### Rationale for this change
    
    View builders can produce arrays that pass `ValidateFull` but panic on
    read because the end offset overflows `int32`.
    
    ### What changes are included in this PR?
    
    `BinaryView.Value`, `StringView.Value`, `ViewHeader.getBufferBytes` and
    `validateUtf8View` compute the end in `int`, so valid arrays from
    earlier releases read correctly.
    
    The builder also stops filling a block at `MaxInt32` bytes, so earlier
    releases can read its output. Calling `SetBlockSize` with a value above
    `MaxInt32` could otherwise produce negative offsets that no reader
    change can fix.
    
    ### Are these changes tested?
    
    Yes. I added tests for block boundaries, oversized blocks, reading view
    values, equality and UTF8 checks during casts.
    
    ### Are there any user-facing changes?
    
    Yes. View values whose end is past `MaxInt32` in a data block now read
    correctly. There is no API change.
    
    Closes #1614.
---
 arrow/array/binary.go                              |   4 +-
 arrow/array/bufferbuilder.go                       |  12 +-
 arrow/array/string.go                              |   4 +-
 arrow/array/view_block_limit_test.go               | 167 +++++++++++++++++++++
 arrow/compute/cast_view_block_limit_test.go        |  67 +++++++++
 .../compute/internal/kernels/binary_view_casts.go  |   4 +-
 arrow/datatype_viewheader.go                       |   4 +-
 7 files changed, 252 insertions(+), 10 deletions(-)

diff --git a/arrow/array/binary.go b/arrow/array/binary.go
index 1095d090..d903511a 100644
--- a/arrow/array/binary.go
+++ b/arrow/array/binary.go
@@ -608,9 +608,9 @@ func (a *BinaryView) Value(i int) []byte {
        if s.IsInline() {
                return s.InlineBytes()
        }
-       start := s.BufferOffset()
+       start := int(s.BufferOffset())
        buf := a.dataBuffers[s.BufferIndex()]
-       return buf.Bytes()[start : start+int32(s.Len())]
+       return buf.Bytes()[start : start+s.Len()]
 }
 
 func (a *BinaryView) ValueLen(i int) int {
diff --git a/arrow/array/bufferbuilder.go b/arrow/array/bufferbuilder.go
index 6d654d8f..8b7b7c6b 100644
--- a/arrow/array/bufferbuilder.go
+++ b/arrow/array/bufferbuilder.go
@@ -17,6 +17,7 @@
 package array
 
 import (
+       "math"
        "sync/atomic"
        "unsafe"
 
@@ -197,14 +198,14 @@ func (b *multiBufferBuilder) Reserve(nbytes int) {
        }
 
        curBuf := b.blocks[b.currentOutBuffer]
-       remain := curBuf.Cap() - curBuf.Len()
+       remain := blockRemaining(curBuf)
        if nbytes <= remain {
                return
        }
 
        // search for underfull block that has enough bytes
        for i, block := range b.blocks {
-               remaining := block.Cap() - block.Len()
+               remaining := blockRemaining(block)
                if nbytes <= remaining {
                        b.currentOutBuffer = i
                        return
@@ -232,6 +233,13 @@ func (b *multiBufferBuilder) RemainingBytes() int {
        return buf.Cap() - buf.Len()
 }
 
+// View offsets are int32, so the end of a value, offset plus length, must fit
+// in an int32. A block's usable capacity stops at MaxInt32 even when
+// allocation rounding or SetBlockSize made its buffer larger.
+func blockRemaining(buf *memory.Buffer) int {
+       return min(buf.Cap(), math.MaxInt32) - buf.Len()
+}
+
 func (b *multiBufferBuilder) Reset() {
        b.currentOutBuffer = 0
        for _, block := range b.Finish() {
diff --git a/arrow/array/string.go b/arrow/array/string.go
index e230fa17..5e432775 100644
--- a/arrow/array/string.go
+++ b/arrow/array/string.go
@@ -520,9 +520,9 @@ func (a *StringView) Value(i int) string {
        if s.IsInline() {
                return s.InlineString()
        }
-       start := s.BufferOffset()
+       start := int(s.BufferOffset())
        buf := a.dataBuffers[s.BufferIndex()]
-       value := buf.Bytes()[start : start+int32(s.Len())]
+       value := buf.Bytes()[start : start+s.Len()]
        return *(*string)(unsafe.Pointer(&value))
 }
 
diff --git a/arrow/array/view_block_limit_test.go 
b/arrow/array/view_block_limit_test.go
new file mode 100644
index 00000000..dcee7d59
--- /dev/null
+++ b/arrow/array/view_block_limit_test.go
@@ -0,0 +1,167 @@
+//go:build darwin || linux
+
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package array
+
+import (
+       "bytes"
+       "math"
+       "strconv"
+       "syscall"
+       "testing"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/memory"
+       "github.com/stretchr/testify/assert"
+       "github.com/stretchr/testify/require"
+)
+
+const (
+       viewTailLen    = 48
+       viewTailOffset = math.MaxInt32 + 1 - viewTailLen
+)
+
+// mappedBlock returns size bytes of address space that the system commits
+// only for the pages a test touches.
+func mappedBlock(t *testing.T, size int64) []byte {
+       t.Helper()
+       if strconv.IntSize < 64 {
+               t.Skip("blocks above the int32 range require a 64-bit int")
+       }
+       b, err := syscall.Mmap(-1, 0, int(size), 
syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_ANON|syscall.MAP_PRIVATE)
+       require.NoError(t, err)
+       t.Cleanup(func() { require.NoError(t, syscall.Munmap(b)) })
+       return b
+}
+
+type mappedAllocator struct {
+       memory.GoAllocator
+       block []byte
+}
+
+func (a *mappedAllocator) Allocate(size int) []byte {
+       if size < 1<<30 {
+               return a.GoAllocator.Allocate(size)
+       }
+       return a.block[:size:size]
+}
+
+// tailViewParts returns the headers and data buffer of a one element view
+// array whose value ends at the last byte of a 2 GiB block.
+func tailViewParts(t *testing.T, tail []byte) ([]byte, *memory.Buffer) {
+       t.Helper()
+       block := mappedBlock(t, math.MaxInt32+1)
+       copy(block[viewTailOffset:], tail)
+
+       var headers [1]arrow.ViewHeader
+       headers[0].SetBytes(tail)
+       headers[0].SetIndexOffset(0, viewTailOffset)
+       return append([]byte(nil), 
arrow.ViewHeaderTraits.CastToBytes(headers[:])...), memory.NewBufferBytes(block)
+}
+
+func TestBinaryViewBuilderKeepsOffsetsWithinInt32(t *testing.T) {
+       // The first value, 2147483600 bytes, is not appended: its block is
+       // reserved and marked full. The block capacity rounds up to 2^31, which
+       // leaves 48 bytes of slack. Only the last of them ends past MaxInt32.
+       tests := []struct {
+               name       string
+               valueLen   int
+               wantOffset int32
+       }{
+               {"value ending past MaxInt32 starts a new block", viewTailLen, 
0},
+               {"value ending at MaxInt32 stays in the block", viewTailLen - 
1, viewTailOffset},
+       }
+       for _, tc := range tests {
+               t.Run(tc.name, func(t *testing.T) {
+                       mem := 
memory.NewCheckedAllocator(&mappedAllocator{block: mappedBlock(t, 
math.MaxInt32+1)})
+                       defer mem.AssertSize(t, 0)
+
+                       b := NewBinaryViewBuilder(mem)
+                       defer b.Release()
+                       b.ReserveData(viewTailOffset)
+                       b.blockBuilder.blocks[0].ResizeNoShrink(viewTailOffset)
+                       b.Append(bytes.Repeat([]byte("v"), tc.valueLen))
+
+                       arr := b.NewBinaryViewArray()
+                       defer arr.Release()
+                       assert.Equal(t, tc.wantOffset, 
arr.ValueHeader(0).BufferOffset())
+               })
+       }
+}
+
+func TestBinaryViewBuilderBlockSizeAboveInt32(t *testing.T) {
+       const blockSize = math.MaxInt32 + 1 + 1<<20
+       mem := memory.NewCheckedAllocator(&mappedAllocator{block: 
mappedBlock(t, blockSize)})
+       defer mem.AssertSize(t, 0)
+
+       b := NewBinaryViewBuilder(mem)
+       defer b.Release()
+       b.SetBlockSize(blockSize)
+       b.ReserveData(1)
+       pastLimit := int64(math.MaxInt32) + 64
+       b.blockBuilder.blocks[0].ResizeNoShrink(int(pastLimit))
+       b.Append(bytes.Repeat([]byte("tail"), viewTailLen/4))
+
+       arr := b.NewBinaryViewArray()
+       defer arr.Release()
+       assert.Equal(t, int32(0), arr.ValueHeader(0).BufferOffset())
+}
+
+func TestBinaryViewValueEndingAtInt32Limit(t *testing.T) {
+       tail := bytes.Repeat([]byte("tail"), viewTailLen/4)
+       headers, block := tailViewParts(t, tail)
+       arr := makeBinaryViewArrayRaw(t, headers, []*memory.Buffer{block}, nil, 
0, 1, 0)
+       defer arr.Release()
+
+       require.NoError(t, arr.ValidateFull())
+       require.NotPanics(t, func() { assert.Equal(t, tail, arr.Value(0)) })
+}
+
+func TestStringViewValueEndingAtInt32Limit(t *testing.T) {
+       tail := bytes.Repeat([]byte("tail"), viewTailLen/4)
+       headers, block := tailViewParts(t, tail)
+       arr := makeStringViewArrayRaw(t, headers, []*memory.Buffer{block}, nil, 
0, 1, 0)
+       defer arr.Release()
+
+       require.NoError(t, arr.ValidateFull())
+       require.NotPanics(t, func() { assert.Equal(t, string(tail), 
arr.Value(0)) })
+}
+
+func TestBinaryViewEqualWithValueEndingAtInt32Limit(t *testing.T) {
+       tail := bytes.Repeat([]byte("tail"), viewTailLen/4)
+       headers, block := tailViewParts(t, tail)
+       arr := makeBinaryViewArrayRaw(t, headers, []*memory.Buffer{block}, nil, 
0, 1, 0)
+       defer arr.Release()
+
+       other := append([]byte(nil), tail...)
+       other[len(other)-1] = 'x'
+
+       b := NewBinaryViewBuilder(memory.DefaultAllocator)
+       defer b.Release()
+       b.Append(tail)
+       same := b.NewArray()
+       defer same.Release()
+       b.Append(other)
+       different := b.NewArray()
+       defer different.Release()
+
+       require.NotPanics(t, func() {
+               assert.True(t, Equal(arr, same))
+               assert.False(t, Equal(arr, different))
+       })
+}
diff --git a/arrow/compute/cast_view_block_limit_test.go 
b/arrow/compute/cast_view_block_limit_test.go
new file mode 100644
index 00000000..b474ebae
--- /dev/null
+++ b/arrow/compute/cast_view_block_limit_test.go
@@ -0,0 +1,67 @@
+//go:build darwin || linux
+
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package compute_test
+
+import (
+       "bytes"
+       "context"
+       "math"
+       "strconv"
+       "syscall"
+       "testing"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/array"
+       "github.com/apache/arrow-go/v18/arrow/compute"
+       "github.com/apache/arrow-go/v18/arrow/memory"
+       "github.com/stretchr/testify/assert"
+       "github.com/stretchr/testify/require"
+)
+
+func TestCastBinaryViewToStringViewChecksUTF8OfValueEndingAtInt32Limit(t 
*testing.T) {
+       if strconv.IntSize < 64 {
+               t.Skip("blocks above the int32 range require a 64-bit int")
+       }
+       const (
+               tailLen    = 48
+               tailOffset = math.MaxInt32 + 1 - tailLen
+       )
+       var size int64 = math.MaxInt32 + 1
+       // The system commits mapped pages only when they are touched.
+       block, err := syscall.Mmap(-1, 0, int(size), 
syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_ANON|syscall.MAP_PRIVATE)
+       require.NoError(t, err)
+       defer func() { require.NoError(t, syscall.Munmap(block)) }()
+
+       tail := bytes.Repeat([]byte("tail"), tailLen/4)
+       tail[tailLen-1] = 0xff
+       copy(block[tailOffset:], tail)
+
+       var headers [1]arrow.ViewHeader
+       headers[0].SetBytes(tail)
+       headers[0].SetIndexOffset(0, tailOffset)
+       viewBuf := memory.NewBufferBytes(append([]byte(nil), 
arrow.ViewHeaderTraits.CastToBytes(headers[:])...))
+       data := array.NewData(arrow.BinaryTypes.BinaryView, 1,
+               []*memory.Buffer{nil, viewBuf, memory.NewBufferBytes(block)}, 
nil, 0, 0)
+       defer data.Release()
+       in := array.NewBinaryViewData(data)
+       defer in.Release()
+
+       _, err = compute.CastArray(context.Background(), in, 
compute.SafeCastOptions(arrow.BinaryTypes.StringView))
+       assert.ErrorIs(t, err, arrow.ErrInvalid)
+}
diff --git a/arrow/compute/internal/kernels/binary_view_casts.go 
b/arrow/compute/internal/kernels/binary_view_casts.go
index 7092e0a2..ad36a631 100644
--- a/arrow/compute/internal/kernels/binary_view_casts.go
+++ b/arrow/compute/internal/kernels/binary_view_casts.go
@@ -40,8 +40,8 @@ func validateUtf8View(input *exec.ArraySpan) error {
                        if h.IsInline() {
                                return h.InlineBytes()
                        }
-                       off := h.BufferOffset()
-                       return dataBuffers[h.BufferIndex()][off : 
off+int32(h.Len())]
+                       off := int(h.BufferOffset())
+                       return dataBuffers[h.BufferIndex()][off : off+h.Len()]
                })
 }
 
diff --git a/arrow/datatype_viewheader.go b/arrow/datatype_viewheader.go
index ed6ed087..05dd0b92 100644
--- a/arrow/datatype_viewheader.go
+++ b/arrow/datatype_viewheader.go
@@ -126,8 +126,8 @@ func (sh *ViewHeader) Equals(buffers []*memory.Buffer, 
other *ViewHeader, otherB
 }
 
 func (sh *ViewHeader) getBufferBytes(buffers []*memory.Buffer) []byte {
-       offset := sh.BufferOffset()
-       return buffers[sh.BufferIndex()].Bytes()[offset : offset+sh.size]
+       offset := int(sh.BufferOffset())
+       return buffers[sh.BufferIndex()].Bytes()[offset : offset+sh.Len()]
 }
 
 func (sh *ViewHeader) inlinedAsInt64() int64 {

Reply via email to