Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1482,6 +1482,27 @@ func BenchmarkOrAscendingParts(b *testing.B) {
}
}

// BenchmarkFastOrInterleaved unions bitmaps whose keys interleave with those
// already in FastOr's running result, so each source key is an interior insert.
func BenchmarkFastOrInterleaved(b *testing.B) {
for _, n := range []int{8, 64} {
parts := make([]*Bitmap, n)
for i := range parts {
part := NewBitmap()
for key := i; key < 65536; key += n {
part.Add(uint32(key)<<16 | uint32(i))
}
parts[i] = part
}
b.Run(fmt.Sprintf("parts=%d", n), func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
FastOr(parts...)
}
})
}
}

// bitmapOrBulkMergeTailAdjacentFixture builds a receiver holding keys
// [0, 4093] plus 4095, unioned with the single source-only key 4094. The lone
// insert lands just before the receiver's tail.
Expand Down
24 changes: 7 additions & 17 deletions fastaggregation.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,24 +71,14 @@ main:
}
s1 = x1.highlowcontainer.getKeyAtIndex(pos1)
} else if s1 > s2 {
x1.highlowcontainer.insertNewKeyValueAt(pos1, s2, x2.highlowcontainer.getContainerAtIndex(pos2).clone())
pos2++
pos1++
length1++
if pos2 == length2 {
break main
}
s2 = x2.highlowcontainer.getKeyAtIndex(pos2)
// A source-only key must be inserted at pos1. Inserting in
// place shifts the rest of the receiver once per inserted key,
// which is quadratic when many keys are interleaved. Finish
// the merge into fresh slices in a single linear pass instead.
x1.highlowcontainer.mergeBulk(&x2.highlowcontainer, pos1, pos1, pos2, mergeLazyOr)
return x1
} else {
c1 := x1.highlowcontainer.getWritableContainerAtIndex(pos1)
// runContainer16.lazyIOR falls back to a slow ior path
// (O(N log R) per merged element); promote to bitmapContainer
// first, whose lazy union is O(1024) regardless of cardinality.
// See https://github.com/RoaringBitmap/roaring/issues/81.
if rc, ok := c1.(*runContainer16); ok && !rc.isFull() {
c1 = rc.toBitmapContainer()
}
x1.highlowcontainer.containers[pos1] = c1.lazyIOR(x2.highlowcontainer.getContainerAtIndex(pos2))
x1.highlowcontainer.containers[pos1] = x1.highlowcontainer.getLazyUnionedWritableContainer(pos1, x2.highlowcontainer.getContainerAtIndex(pos2))
x1.highlowcontainer.needCopyOnWrite[pos1] = false
pos1++
pos2++
Expand Down
6 changes: 3 additions & 3 deletions roaring.go
Original file line number Diff line number Diff line change
Expand Up @@ -1638,7 +1638,7 @@ func (rb *Bitmap) Xor(x2 *Bitmap) {
// place shifts the aligned suffix once per inserted key, which
// is quadratic when many keys are interleaved. Finish the merge
// into fresh slices in a single linear pass instead.
rb.highlowcontainer.mergeBulk(&x2.highlowcontainer, pos1, pos1, pos2, true)
rb.highlowcontainer.mergeBulk(&x2.highlowcontainer, pos1, pos1, pos2, mergeXor)
return
} else {
c := rb.highlowcontainer.getWritableContainerAtIndex(pos1).ixor(x2.highlowcontainer.getContainerAtIndex(pos2))
Expand All @@ -1651,7 +1651,7 @@ func (rb *Bitmap) Xor(x2 *Bitmap) {
// place would shift the suffix once per removed key (also
// quadratic), so finish the merge into fresh slices,
// dropping this now-empty container.
rb.highlowcontainer.mergeBulk(&x2.highlowcontainer, pos1, pos1+1, pos2+1, true)
rb.highlowcontainer.mergeBulk(&x2.highlowcontainer, pos1, pos1+1, pos2+1, mergeXor)
return
}
}
Expand Down Expand Up @@ -1688,7 +1688,7 @@ main:
// aligned suffix once per inserted key, which is quadratic when
// many source-only keys are interleaved. Finish the merge into
// fresh slices in a single linear pass instead.
rb.highlowcontainer.mergeBulk(&x2.highlowcontainer, pos1, pos1, pos2, false)
rb.highlowcontainer.mergeBulk(&x2.highlowcontainer, pos1, pos1, pos2, mergeOr)
return
} else {
newcont := rb.highlowcontainer.getUnionedWritableContainer(pos1, x2.highlowcontainer.getContainerAtIndex(pos2))
Expand Down
21 changes: 21 additions & 0 deletions roaring64/benchmark_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package roaring64

import (
"fmt"
"math/rand"
"testing"
)
Expand Down Expand Up @@ -181,3 +182,23 @@ func BenchmarkOrAscendingParts(b *testing.B) {
}
}
}

// BenchmarkOrXorInterleaved merges bitmaps whose keys interleave, so every
// source key must be inserted between two receiver keys.
func BenchmarkOrXorInterleaved(b *testing.B) {
for _, n := range []int{1024, 16384} {
left, right := interleavedPair(n, false)
b.Run(fmt.Sprintf("Or/keys=%d", n), func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
left.Clone().Or(right)
}
})
b.Run(fmt.Sprintf("Xor/keys=%d", n), func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
left.Clone().Xor(right)
}
})
}
}
36 changes: 20 additions & 16 deletions roaring64/roaring64.go
Original file line number Diff line number Diff line change
Expand Up @@ -649,22 +649,28 @@ func (rb *Bitmap) Xor(x2 *Bitmap) {
break
}
} else if s1 > s2 {
c := x2.highlowcontainer.getWritableContainerAtIndex(pos2)
rb.highlowcontainer.insertNewKeyValueAt(pos1, x2.highlowcontainer.getKeyAtIndex(pos2), c)
length1++
pos1++
pos2++
// A source-only key must be inserted at pos1. Inserting in
// place shifts the rest of the receiver once per inserted key,
// which is quadratic when many keys are interleaved. Finish
// the merge into fresh slices in a single linear pass instead.
rb.highlowcontainer.mergeBulk(&x2.highlowcontainer, pos1, pos1, pos2, true)
return
} else {
// TODO: couple be computed in-place for reduced memory usage
c := roaring.Xor(rb.highlowcontainer.getContainerAtIndex(pos1), x2.highlowcontainer.getContainerAtIndex(pos2))
if !c.IsEmpty() {
rb.highlowcontainer.setContainerAtIndex(pos1, c)
rb.highlowcontainer.needCopyOnWrite[pos1] = false
pos1++
pos2++
} else {
rb.highlowcontainer.removeAtIndex(pos1)
length1--
// The aligned containers cancelled out. Removing pos1 in
// place would shift the rest of the receiver once per
// removed key (also quadratic), so finish the merge into
// fresh slices, dropping this now-empty container.
rb.highlowcontainer.mergeBulk(&x2.highlowcontainer, pos1, pos1+1, pos2+1, true)
return
}
pos2++
}
} else {
break
Expand Down Expand Up @@ -694,14 +700,12 @@ main:
}
s1 = rb.highlowcontainer.getKeyAtIndex(pos1)
} else if s1 > s2 {
rb.highlowcontainer.insertNewKeyValueAt(pos1, s2, x2.highlowcontainer.getContainerAtIndex(pos2).Clone())
pos1++
length1++
pos2++
if pos2 == length2 {
break main
}
s2 = x2.highlowcontainer.getKeyAtIndex(pos2)
// A source-only key must be inserted at pos1. Inserting in
// place shifts the rest of the receiver once per inserted key,
// which is quadratic when many keys are interleaved. Finish
// the merge into fresh slices in a single linear pass instead.
rb.highlowcontainer.mergeBulk(&x2.highlowcontainer, pos1, pos1, pos2, false)
return
} else {
rb.highlowcontainer.getWritableContainerAtIndex(pos1).Or(x2.highlowcontainer.getContainerAtIndex(pos2))
pos1++
Expand Down
88 changes: 88 additions & 0 deletions roaring64/roaring64_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2191,3 +2191,91 @@ func TestOrPartsInKeyOrder(t *testing.T) {
}
assert.True(t, got.Equals(want))
}

// interleavedPair returns two bitmaps whose high keys interleave (left holds
// even keys, right odd ones) and, when overlap is set, also share every
// fourth key, with low bits chosen so that some shared containers cancel to
// empty under Xor and others survive.
func interleavedPair(n int, overlap bool) (*Bitmap, *Bitmap) {
left := NewBitmap()
right := NewBitmap()
for i := 0; i < n; i++ {
left.Add(uint64(2*i)<<32 | 1)
right.Add(uint64(2*i+1)<<32 | 2)
if overlap && i%4 == 0 {
shared := uint64(4*n+i) << 32
left.Add(shared | 3)
right.Add(shared | 3)
if i%8 == 0 {
right.Add(shared | 4)
}
}
}
return left, right
}

func referenceOp(left, right *Bitmap, xor bool) *Bitmap {
in := map[uint64]int{}
for _, v := range left.ToArray() {
in[v]++
}
for _, v := range right.ToArray() {
in[v]++
}
want := NewBitmap()
for v, n := range in {
if !xor || n == 1 {
want.Add(v)
}
}
return want
}

// TestOrXorBulkMerge covers the single-pass merge that Or and Xor fall back
// to once they meet a source-only key or (Xor) an aligned pair that cancels.
func TestOrXorBulkMerge(t *testing.T) {
for _, n := range []int{1, 2, 63, 1000} {
for _, overlap := range []bool{false, true} {
for _, xor := range []bool{false, true} {
left, right := interleavedPair(n, overlap)
leftCopy, rightCopy := left.Clone(), right.Clone()
want := referenceOp(left, right, xor)
got := left.Clone()
if xor {
got.Xor(right)
} else {
got.Or(right)
}
assert.True(t, got.Equals(want), "n=%d overlap=%v xor=%v", n, overlap, xor)
assert.NoError(t, got.Validate())
assert.True(t, left.Equals(leftCopy))
assert.True(t, right.Equals(rightCopy))
}
}
}
}

// TestOrXorDoNotShareSourceContainers checks that a container copied from the
// source for a key the receiver lacks is the receiver's own: mutating either
// bitmap afterwards must not change the other.
func TestOrXorDoNotShareSourceContainers(t *testing.T) {
for _, xor := range []bool{false, true} {
for _, cow := range []bool{false, true} {
receiver := BitmapOf(0, 2<<32)
source := BitmapOf(1<<32, 3<<32)
receiver.SetCopyOnWrite(cow)
source.SetCopyOnWrite(cow)
if xor {
receiver.Xor(source)
} else {
receiver.Or(source)
}
for _, hi := range []uint64{1, 3} { // interior and trailing keys
receiver.Add(hi<<32 | 5)
assert.False(t, source.Contains(hi<<32|5), "xor=%v cow=%v hi=%d", xor, cow, hi)
source.Add(hi<<32 | 6)
assert.False(t, receiver.Contains(hi<<32|6), "xor=%v cow=%v hi=%d", xor, cow, hi)
}
}
}
}
91 changes: 91 additions & 0 deletions roaring64/roaringarray64.go
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,97 @@ func (ra *roaringArray64) insertNewKeyValueAt(i int, key uint32, value *roaring.
ra.needCopyOnWrite[i] = false
}

// mergeBulk finishes an in-place union (xor == false) or symmetric difference
// (xor == true) once the receiver's structure must change and continuing in
// place would shift the aligned suffix once per changed key -- quadratic when
// many keys are interleaved. It merges the two suffixes forward into fresh
// slices in a single pass instead. It mirrors roaringArray.mergeBulk in the
// root package.
//
// The change that triggers it is a source-only key that must be inserted, or
// (xor only) an aligned pair that cancelled to an empty container. dst is the
// write cursor: the prefix [0, dst) is already final and copied over unchanged.
// left/right are the receiver/source scan positions; the caller advances them
// past an already-consumed aligned-empty pair. For a union a source-only key is
// always inserted, so dst == left; the xor caller may pass dst < left to drop
// the emptied container.
func (ra *roaringArray64) mergeBulk(other *roaringArray64, dst, left, right int, xor bool) {
length1 := ra.size()
length2 := other.size()

// First pass over the keys only: count the distinct keys of the two
// suffixes, the exact result size for a union and a tight upper bound for
// a xor, so the appends below never reallocate.
distinct := 0
l, r := left, right
for l < length1 && r < length2 {
if ra.keys[l] < other.keys[r] {
l++
} else if ra.keys[l] > other.keys[r] {
r++
} else {
l++
r++
}
distinct++
}
distinct += (length1 - l) + (length2 - r)
total := dst + distinct
keys := make([]uint32, dst, total)
containers := make([]*roaring.Bitmap, dst, total)
needCopyOnWrite := make([]bool, dst, total)
copy(keys, ra.keys[:dst])
copy(containers, ra.containers[:dst])
copy(needCopyOnWrite, ra.needCopyOnWrite[:dst])

for left < length1 && right < length2 {
s1 := ra.keys[left]
s2 := other.keys[right]
if s1 < s2 {
keys = append(keys, s1)
containers = append(containers, ra.containers[left])
needCopyOnWrite = append(needCopyOnWrite, ra.needCopyOnWrite[left])
left++
} else if s1 > s2 {
// An interior source-only key: always cloned, so that later
// receiver mutations cannot leak into the source.
keys = append(keys, s2)
containers = append(containers, other.containers[right].Clone())
needCopyOnWrite = append(needCopyOnWrite, false)
right++
} else {
var c *roaring.Bitmap
if xor {
c = roaring.Xor(ra.containers[left], other.containers[right])
} else {
c = ra.getWritableContainerAtIndex(left)
c.Or(other.containers[right])
}
// The union of two non-empty containers is never empty, so this
// only ever drops a container for xor.
if !c.IsEmpty() {
keys = append(keys, s1)
containers = append(containers, c)
needCopyOnWrite = append(needCopyOnWrite, false)
}
left++
right++
}
}
for ; left < length1; left++ {
keys = append(keys, ra.keys[left])
containers = append(containers, ra.containers[left])
needCopyOnWrite = append(needCopyOnWrite, ra.needCopyOnWrite[left])
}

ra.keys = keys
ra.containers = containers
ra.needCopyOnWrite = needCopyOnWrite
// The source keys left over are all past the receiver's last key: append
// them as Or and Xor do for their trailing suffix.
ra.appendCopyMany(*other, right, length2)
}

func (ra *roaringArray64) remove(key uint32) bool {
i := ra.binarySearch(0, int64(len(ra.keys)), key)
if i >= 0 { // if a new key
Expand Down
Loading
Loading