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 70fe2743 perf(arrow/array): compare optional validity bitmaps in bulk 
(#1327)
70fe2743 is described below

commit 70fe274308deef403609ece0250d25787ee9b5d9
Author: Minh Vu <[email protected]>
AuthorDate: Mon Oct 19 17:14:48 2026 +0200

    perf(arrow/array): compare optional validity bitmaps in bulk (#1327)
    
    ### What
    
    - Speed up `Equal` and `ApproxEqual` when one array has no validity
    bitmap.
    
    ### Why
    
    - Comparing an absent bitmap with a materialized bitmap currently checks
    validity one row at a time.
    
    ### Implementation
    
    - Use `BitmapAllSet` on the present bitmap, scanning aligned words and
    respecting its slice offset.
    - Return as soon as an invalid bit is found instead of counting the full
    range.
    - Preserve empty-buffer handling and bitmap checks when declared null
    counts are inconsistent.
    
    ### Benchmark
    
    Command: `go test -run '^$' -bench '^BenchmarkArrayEqualValidityBitmap$'
    -benchmem ./arrow/array`
    
    Apple M1 Pro, Go 1.26.3, `GOMAXPROCS=1`. Medians of six alternating
    before/after runs, 300 ms per case. Each case compares 1,048,576 values
    with one absent bitmap and one materialized bitmap. Binary/string values
    are 8 bytes each.
    
    | Case | Before | After | Speedup |
    | --- | ---: | ---: | ---: |
    | Boolean, Equal | 8,806.5 µs | 21.3 µs | 414.4x |
    | Boolean, ApproxEqual | 4,643.2 µs | 20.9 µs | 221.9x |
    | Int8, Equal | 5,868.4 µs | 58.9 µs | 99.6x |
    | Int64, Equal | 7,586.4 µs | 494.7 µs | 15.3x |
    | Binary, Equal | 11,979.7 µs | 1,658.2 µs | 7.2x |
    | String, Equal | 8,959.1 µs | 1,895.6 µs | 4.7x |
    | String, ApproxEqual | 19,381.8 µs | 11,087.5 µs | 1.7x |
    
    No new allocations. The benchmark also covers 64-value arrays, unaligned
    slices, and controls with both bitmaps present or both absent.
    
    ### Compatibility
    
    - No data-format changes.
    - Adds one reusable bitmap utility; null semantics and slice offsets
    remain covered by the regression tests.
    
    ### Tests
    
    - `go test ./arrow/...`
    - `go test -race ./arrow/array`
    - `go test -tags noasm ./arrow/array`
    - `go vet -composites=false ./arrow/array`
---
 arrow/array/compare.go                          |  21 ++--
 arrow/array/compare_test.go                     |  85 ++++++++++++++++
 arrow/array/validity_equality_benchmark_test.go | 107 ++++++++++++++++++++
 arrow/bitutil/bitutil.go                        |  55 +++++++++++
 arrow/bitutil/bitutil_test.go                   | 125 ++++++++++++++++++++++++
 5 files changed, 383 insertions(+), 10 deletions(-)

diff --git a/arrow/array/compare.go b/arrow/array/compare.go
index 419add8c..826142e6 100644
--- a/arrow/array/compare.go
+++ b/arrow/array/compare.go
@@ -791,17 +791,11 @@ func validityBitmapEqual(left, right arrow.Array) bool {
 
        leftBitmap := left.NullBitmapBytes()
        rightBitmap := right.NullBitmapBytes()
-       if left.NullN() == 0 && len(leftBitmap) == 0 && len(rightBitmap) == 0 {
-               return true
+       if len(leftBitmap) == 0 {
+               return validityBitmapAllValid(right, rightBitmap)
        }
-
-       if len(leftBitmap) == 0 || len(rightBitmap) == 0 {
-               for i := range left.Len() {
-                       if left.IsNull(i) != right.IsNull(i) {
-                               return false
-                       }
-               }
-               return true
+       if len(rightBitmap) == 0 {
+               return validityBitmapAllValid(left, leftBitmap)
        }
 
        return bitutil.BitmapEquals(
@@ -810,6 +804,13 @@ func validityBitmapEqual(left, right arrow.Array) bool {
        )
 }
 
+// validityBitmapAllValid reports whether the materialized validity bitmap
+// contains only valid values in the array's logical range. A missing bitmap
+// also represents an all-valid range, matching arrow.Array.IsValid.
+func validityBitmapAllValid(arr arrow.Array, bitmap []byte) bool {
+       return len(bitmap) == 0 || bitutil.BitmapAllSet(bitmap, 
arr.Data().Offset(), arr.Len())
+}
+
 func arrayApproxEqualString(left, right *String) bool {
        for i := 0; i < left.Len(); i++ {
                if left.IsNull(i) {
diff --git a/arrow/array/compare_test.go b/arrow/array/compare_test.go
index 60e49fb2..fefdc7b6 100644
--- a/arrow/array/compare_test.go
+++ b/arrow/array/compare_test.go
@@ -24,6 +24,7 @@ import (
 
        "github.com/apache/arrow-go/v18/arrow"
        "github.com/apache/arrow-go/v18/arrow/array"
+       "github.com/apache/arrow-go/v18/arrow/bitutil"
        "github.com/apache/arrow-go/v18/arrow/float16"
        "github.com/apache/arrow-go/v18/arrow/internal/arrdata"
        "github.com/apache/arrow-go/v18/arrow/memory"
@@ -1065,6 +1066,90 @@ func TestArrayEqualValidityBitmapWithZeroNullCount(t 
*testing.T) {
        assert.False(t, array.Equal(left, right))
 }
 
+func TestArrayEqualOptionalValidityBitmap(t *testing.T) {
+       for _, length := range []int{0, 1, 7, 8, 9, 63, 64, 65, 129} {
+               for _, offset := range []int{0, 3, 8, 63, 65} {
+                       for _, empty := range []bool{false, true} {
+                               for _, nulls := range []int{0, 
array.UnknownNullCount} {
+                                       
t.Run(fmt.Sprintf("len=%d/offset=%d/empty=%t/nulls=%d", length, offset, empty, 
nulls), func(t *testing.T) {
+                                               var missing *memory.Buffer
+                                               if empty {
+                                                       missing = 
memory.NewBufferBytes([]byte{})
+                                                       defer missing.Release()
+                                               }
+                                               left := 
makeBooleanValidityEqualityArray(length, 5, missing, 0)
+                                               defer left.Release()
+
+                                               bitmap := make([]byte, 
bitutil.BytesForBits(int64(offset+length+1)))
+                                               for i := range length {
+                                                       bitutil.SetBit(bitmap, 
offset+i)
+                                               }
+                                               validity := 
memory.NewBufferBytes(bitmap)
+                                               defer validity.Release()
+                                               right := 
makeBooleanValidityEqualityArray(length, offset, validity, nulls)
+                                               defer right.Release()
+
+                                               assert.True(t, 
array.Equal(left, right))
+                                               assert.True(t, 
array.Equal(right, left))
+                                               assert.True(t, 
array.ApproxEqual(left, right))
+                                               assert.True(t, 
array.ApproxEqual(right, left))
+                                       })
+                               }
+                       }
+               }
+       }
+}
+
+func TestArrayEqualOptionalValidityBitmapMismatch(t *testing.T) {
+       const length = 129
+       for _, offset := range []int{0, 3, 65} {
+               for _, nullIndex := range []int{0, 7, 63, 64, length - 1} {
+                       for _, nulls := range []int{0, array.UnknownNullCount} {
+                               t.Run(fmt.Sprintf("offset=%d/null=%d/nulls=%d", 
offset, nullIndex, nulls), func(t *testing.T) {
+                                       left := 
makeBooleanValidityEqualityArray(length, 0, nil, 0)
+                                       defer left.Release()
+                                       bitmap := make([]byte, 
bitutil.BytesForBits(int64(offset+length)))
+                                       for i := range length {
+                                               bitutil.SetBit(bitmap, offset+i)
+                                       }
+                                       bitutil.ClearBit(bitmap, 
offset+nullIndex)
+                                       validity := 
memory.NewBufferBytes(bitmap)
+                                       defer validity.Release()
+                                       right := 
makeBooleanValidityEqualityArray(length, offset, validity, nulls)
+                                       defer right.Release()
+
+                                       assert.False(t, array.Equal(left, 
right))
+                                       assert.False(t, array.Equal(right, 
left))
+                                       assert.False(t, array.ApproxEqual(left, 
right))
+                                       assert.False(t, 
array.ApproxEqual(right, left))
+                               })
+                       }
+               }
+       }
+}
+
+func TestArrayEqualEmptyValidityRangePastBuffer(t *testing.T) {
+       left := makeBooleanValidityEqualityArray(0, 0, nil, 0)
+       defer left.Release()
+       validity := memory.NewBufferBytes([]byte{0xff})
+       defer validity.Release()
+       right := makeBooleanValidityEqualityArray(0, 64, validity, 0)
+       defer right.Release()
+
+       assert.True(t, array.Equal(left, right))
+       assert.True(t, array.Equal(right, left))
+       assert.True(t, array.ApproxEqual(left, right))
+       assert.True(t, array.ApproxEqual(right, left))
+}
+
+func makeBooleanValidityEqualityArray(length, offset int, validity 
*memory.Buffer, nulls int) *array.Boolean {
+       values := memory.NewBufferBytes(make([]byte, 
bitutil.BytesForBits(int64(offset+length))))
+       defer values.Release()
+       data := array.NewData(arrow.FixedWidthTypes.Boolean, length, 
[]*memory.Buffer{validity, values}, nil, nulls, offset)
+       defer data.Release()
+       return array.NewBooleanData(data)
+}
+
 func TestArrayEqualNull(t *testing.T) {
        mem := memory.NewCheckedAllocator(memory.NewGoAllocator())
        defer mem.AssertSize(t, 0)
diff --git a/arrow/array/validity_equality_benchmark_test.go 
b/arrow/array/validity_equality_benchmark_test.go
new file mode 100644
index 00000000..123d1111
--- /dev/null
+++ b/arrow/array/validity_equality_benchmark_test.go
@@ -0,0 +1,107 @@
+// 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_test
+
+import (
+       "bytes"
+       "fmt"
+       "testing"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/array"
+       "github.com/apache/arrow-go/v18/arrow/bitutil"
+       "github.com/apache/arrow-go/v18/arrow/memory"
+)
+
+func BenchmarkArrayEqualValidityBitmap(b *testing.B) {
+       for _, dtype := range []arrow.DataType{
+               arrow.FixedWidthTypes.Boolean,
+               arrow.PrimitiveTypes.Int8,
+               arrow.PrimitiveTypes.Int64,
+               arrow.BinaryTypes.Binary,
+               arrow.BinaryTypes.String,
+       } {
+               for _, length := range []int{64, 1024 * 1024} {
+                       for _, layout := range []struct {
+                               name                    string
+                               leftBitmap, rightBitmap bool
+                               rightOffset             int
+                       }{
+                               {"both", true, true, 0},
+                               {"mixed", false, true, 0},
+                               {"mixed_unaligned", false, true, 3},
+                               {"neither", false, false, 0},
+                       } {
+                               b.Run(fmt.Sprintf("%s/len=%d/%s", dtype.Name(), 
length, layout.name), func(b *testing.B) {
+                                       left := 
makeValidityEqualityBenchmarkArray(dtype, length, layout.leftBitmap)
+                                       defer left.Release()
+                                       rightBase := 
makeValidityEqualityBenchmarkArray(dtype, length+layout.rightOffset, 
layout.rightBitmap)
+                                       defer rightBase.Release()
+                                       right := array.NewSlice(rightBase, 
int64(layout.rightOffset), int64(length+layout.rightOffset))
+                                       defer right.Release()
+                                       b.Run("Equal", func(b *testing.B) {
+                                               b.ReportAllocs()
+                                               for b.Loop() {
+                                                       if !array.Equal(left, 
right) {
+                                                               
b.Fatal("expected equal arrays")
+                                                       }
+                                               }
+                                       })
+                                       b.Run("ApproxEqual", func(b *testing.B) 
{
+                                               b.ReportAllocs()
+                                               for b.Loop() {
+                                                       if 
!array.ApproxEqual(left, right) {
+                                                               
b.Fatal("expected approximately equal arrays")
+                                                       }
+                                               }
+                                       })
+                               })
+                       }
+               }
+       }
+}
+
+func makeValidityEqualityBenchmarkArray(dtype arrow.DataType, length int, 
withBitmap bool) arrow.Array {
+       buffers := make([]*memory.Buffer, 2)
+       if withBitmap {
+               buffers[0] = memory.NewBufferBytes(bytes.Repeat([]byte{0xff}, 
int(bitutil.BytesForBits(int64(length)))))
+       }
+       switch dtype.ID() {
+       case arrow.BOOL:
+               buffers[1] = memory.NewBufferBytes(make([]byte, 
bitutil.BytesForBits(int64(length))))
+       case arrow.INT8:
+               buffers[1] = memory.NewBufferBytes(make([]byte, length))
+       case arrow.INT64:
+               buffers[1] = memory.NewBufferBytes(make([]byte, length*8))
+       case arrow.BINARY, arrow.STRING:
+               offsets := make([]int32, length+1)
+               for i := range offsets {
+                       offsets[i] = int32(i * 8)
+               }
+               buffers[1] = 
memory.NewBufferBytes(arrow.Int32Traits.CastToBytes(offsets))
+               buffers = append(buffers, 
memory.NewBufferBytes(bytes.Repeat([]byte("abcdefgh"), length)))
+       }
+       data := array.NewData(dtype, length, buffers, nil, 0, 0)
+       defer data.Release()
+       for _, buffer := range buffers {
+               if buffer != nil {
+                       buffer.Release()
+               }
+       }
+       return array.MakeFromData(data)
+}
diff --git a/arrow/bitutil/bitutil.go b/arrow/bitutil/bitutil.go
index 720bc51c..da0d98b3 100644
--- a/arrow/bitutil/bitutil.go
+++ b/arrow/bitutil/bitutil.go
@@ -17,6 +17,7 @@
 package bitutil
 
 import (
+       "encoding/binary"
        "math"
        "math/bits"
        "unsafe"
@@ -112,6 +113,60 @@ func CountSetBits(buf []byte, offset, n int) int {
        return count
 }
 
+// BitmapAllSet reports whether all bits in the requested range are set.
+// For n == 0, it returns true for any buf and offset. Otherwise, buf must
+// cover offset+n bits or BitmapAllSet panics, matching CountSetBits.
+func BitmapAllSet(buf []byte, offset, n int) bool {
+       if n == 0 {
+               return true
+       }
+       // Validate the full range before returning early for a clear bit.
+       _ = buf[(uint(offset)+uint(n)-1)/8]
+       // Preserve the cheapest early exit for a null at the start.
+       if !BitIsSet(buf, offset) {
+               return false
+       }
+       if offset&7 != 0 {
+               leading := min(8-(offset&7), n)
+               mask := byte((1<<leading)-1) << (offset & 7)
+               if buf[offset/8]&mask != mask {
+                       return false
+               }
+               offset += leading
+               n -= leading
+       }
+       end := offset/8 + n/8
+       body := buf[offset/8 : end]
+       // One test per 512 bits keeps long all-valid scans branch-light.
+       if len(body) >= 64 {
+               bulkBytes := len(body) &^ 63
+               words := bytesToUint64(body[:bulkBytes])
+               for len(words) >= 8 {
+                       if 
words[0]&words[1]&words[2]&words[3]&words[4]&words[5]&words[6]&words[7] != 
^uint64(0) {
+                               return false
+                       }
+                       words = words[8:]
+               }
+               body = body[bulkBytes:]
+       }
+       for len(body) >= 8 {
+               if binary.LittleEndian.Uint64(body) != ^uint64(0) {
+                       return false
+               }
+               body = body[8:]
+       }
+       for _, v := range body {
+               if v != 255 {
+                       return false
+               }
+       }
+       if tail := n & 7; tail != 0 {
+               mask := byte(1<<tail) - 1
+               return buf[end]&mask == mask
+       }
+       return true
+}
+
 func countSetBitsWithOffset(buf []byte, offset, n int) int {
        count := 0
 
diff --git a/arrow/bitutil/bitutil_test.go b/arrow/bitutil/bitutil_test.go
index fcfd35e0..9f3d5cd2 100644
--- a/arrow/bitutil/bitutil_test.go
+++ b/arrow/bitutil/bitutil_test.go
@@ -223,6 +223,131 @@ func TestCountSetBitsOffset(t *testing.T) {
        }
 }
 
+func TestBitmapAllSetEmptyRange(t *testing.T) {
+       for _, tc := range []struct {
+               name string
+               buf  []byte
+       }{
+               {"nil", nil},
+               {"empty", []byte{}},
+               {"unset", []byte{0}},
+               {"set", []byte{0xff}},
+       } {
+               for _, offset := range []int{-1, 0, 1, 7, 8, 63, 64, 65, 1024} {
+                       t.Run(fmt.Sprintf("%s/offset=%d", tc.name, offset), 
func(t *testing.T) {
+                               if !bitutil.BitmapAllSet(tc.buf, offset, 0) {
+                                       t.Fatal("an empty bitmap range must be 
all-set")
+                               }
+                       })
+               }
+       }
+}
+
+func TestBitmapAllSetShortBufferPanics(t *testing.T) {
+       for _, tc := range []struct {
+               name   string
+               buf    []byte
+               offset int
+               n      int
+       }{
+               {"nil", nil, 0, 1},
+               {"past-end", []byte{0xff}, 8, 1},
+               {"cross-end", []byte{0xff}, 7, 2},
+               {"first-bit-clear", []byte{0}, 0, 9},
+               {"leading-bit-clear", []byte{0x7f}, 1, 8},
+               {"body-bit-clear", []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 
0xff, 0x7f}, 0, 65},
+       } {
+               t.Run(tc.name, func(t *testing.T) {
+                       assert.Panics(t, func() {
+                               bitutil.BitmapAllSet(tc.buf, tc.offset, tc.n)
+                       })
+               })
+       }
+}
+
+func TestBitmapAllSetWordBoundaries(t *testing.T) {
+       for storageOffset := 0; storageOffset < 8; storageOffset++ {
+               for offset := 0; offset < 64; offset++ {
+                       for _, n := range []int{1, 7, 8, 63, 64, 65, 511, 512, 
513, 1023, 1024, 1025} {
+                               storage := make([]byte, 
storageOffset+(offset+n+7)/8)
+                               bitmap := storage[storageOffset:]
+                               // Keep all padding and neighboring bits clear.
+                               for i := offset; i < offset+n; i++ {
+                                       bitutil.SetBit(bitmap, i)
+                               }
+                               if !bitutil.BitmapAllSet(bitmap, offset, n) {
+                                       t.Fatalf("all-set range rejected: 
storage=%d offset=%d length=%d", storageOffset, offset, n)
+                               }
+                               for i := offset; i < offset+n; i++ {
+                                       bitutil.ClearBit(bitmap, i)
+                                       if bitutil.BitmapAllSet(bitmap, offset, 
n) {
+                                               t.Fatalf("clear bit %d missed: 
storage=%d offset=%d length=%d", i, storageOffset, offset, n)
+                                       }
+                                       bitutil.SetBit(bitmap, i)
+                               }
+                       }
+               }
+       }
+}
+
+func BenchmarkBitmapAllSetScan(b *testing.B) {
+       for _, n := range []int{64, 1024, 65536, 1048576} {
+               for _, offset := range []int{0, 3} {
+                       for _, pattern := range []string{"all", "first-null", 
"last-null"} {
+                               b.Run(fmt.Sprintf("bits=%d/offset=%d/%s", n, 
offset, pattern), func(b *testing.B) {
+                                       bitmap := make([]byte, (offset+n+7)/8)
+                                       for i := range bitmap {
+                                               bitmap[i] = 0xff
+                                       }
+                                       switch pattern {
+                                       case "first-null":
+                                               bitutil.ClearBit(bitmap, offset)
+                                       case "last-null":
+                                               bitutil.ClearBit(bitmap, 
offset+n-1)
+                                       }
+                                       want := pattern == "all"
+                                       b.ReportAllocs()
+                                       for b.Loop() {
+                                               if bitutil.BitmapAllSet(bitmap, 
offset, n) != want {
+                                                       b.Fatal("unexpected 
bitmap result")
+                                               }
+                                       }
+                               })
+                       }
+               }
+       }
+}
+
+func FuzzBitmapAllSet(f *testing.F) {
+       for _, bitmap := range [][]byte{nil, {0}, {0xff}, {0x7e, 0xff, 0x81}, 
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}} {
+               for _, offset := range []uint16{0, 1, 7, 8, 63} {
+                       f.Add(bitmap, offset, uint16(65))
+               }
+       }
+       bulk := make([]byte, 129)
+       for i := range bulk {
+               bulk[i] = 0xff
+       }
+       f.Add(bulk, uint16(3), uint16(1024))
+       lateNull := append([]byte(nil), bulk...)
+       bitutil.ClearBit(lateNull, 1025)
+       f.Add(lateNull, uint16(3), uint16(1024))
+       f.Fuzz(func(t *testing.T, bitmap []byte, rawOffset, rawLength uint16) {
+               offset := int(rawOffset) % (len(bitmap)*8 + 1)
+               length := int(rawLength) % (len(bitmap)*8 - offset + 1)
+               want := true
+               for i := offset; i < offset+length; i++ {
+                       if !bitutil.BitIsSet(bitmap, i) {
+                               want = false
+                               break
+                       }
+               }
+               if got := bitutil.BitmapAllSet(bitmap, offset, length); got != 
want {
+                       t.Fatalf("BitmapAllSet(%x, %d, %d) = %t, want %t", 
bitmap, offset, length, got, want)
+               }
+       })
+}
+
 func TestSetBitsTo(t *testing.T) {
        for _, fillByte := range []byte{0x00, 0xFF} {
                {

Reply via email to