diff --git a/benchmark_test.go b/benchmark_test.go index 362a4131..bd93cd5f 100644 --- a/benchmark_test.go +++ b/benchmark_test.go @@ -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. diff --git a/fastaggregation.go b/fastaggregation.go index d7640510..9a3b3d32 100644 --- a/fastaggregation.go +++ b/fastaggregation.go @@ -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++ diff --git a/roaring.go b/roaring.go index 949d0ceb..c76b8332 100644 --- a/roaring.go +++ b/roaring.go @@ -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)) @@ -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 } } @@ -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)) diff --git a/roaring64/benchmark_test.go b/roaring64/benchmark_test.go index 90e00c07..64060f32 100644 --- a/roaring64/benchmark_test.go +++ b/roaring64/benchmark_test.go @@ -1,6 +1,7 @@ package roaring64 import ( + "fmt" "math/rand" "testing" ) @@ -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) + } + }) + } +} diff --git a/roaring64/roaring64.go b/roaring64/roaring64.go index 724e6b11..74c46024 100644 --- a/roaring64/roaring64.go +++ b/roaring64/roaring64.go @@ -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 @@ -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++ diff --git a/roaring64/roaring64_test.go b/roaring64/roaring64_test.go index 56396025..ebec1e44 100644 --- a/roaring64/roaring64_test.go +++ b/roaring64/roaring64_test.go @@ -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) + } + } + } +} diff --git a/roaring64/roaringarray64.go b/roaring64/roaringarray64.go index 6c85ae6e..9c2bf6e4 100644 --- a/roaring64/roaringarray64.go +++ b/roaring64/roaringarray64.go @@ -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 diff --git a/roaring_test.go b/roaring_test.go index 8cd5d2f5..a536228d 100644 --- a/roaring_test.go +++ b/roaring_test.go @@ -4232,6 +4232,73 @@ func TestOrPartsInKeyOrder(t *testing.T) { assert.True(t, FastOr(parts...).Equals(want)) } +// TestFastOrBulkMergeFixtures runs the Or bulk-merge fixtures through FastOr, +// whose in-place lazyOR finishes with the same single-pass merge once it meets +// a source-only key. +func TestFastOrBulkMergeFixtures(t *testing.T) { + for name, fixture := range bitmapOrBulkMergeFixtureCases() { + t.Run(name, func(t *testing.T) { + left := fixture.lefts[0] + right := fixture.rights[0] + want := bitmapOrBulkMergeExpected(left, right) + // a third bitmap makes FastOr take the in-place lazyOR path + // with left|right as the receiver and the other variant's left + // as the source + other := fixture.lefts[1] + want.Or(other) + got := FastOr(left, right, other) + assert.True(t, got.Equals(want)) + assert.NoError(t, got.Validate()) + assert.Equal(t, want.GetCardinality(), got.GetCardinality()) + }) + } +} + +// TestFastOrInterleavedParts unions many bitmaps whose keys interleave with +// those already in the running result, mixing array, bitmap and run +// containers, and checks FastOr against Or and the inputs' integrity. +func TestFastOrInterleavedParts(t *testing.T) { + r := rand.New(rand.NewSource(2)) + parts := make([]*Bitmap, 64) + want := NewBitmap() + for i := range parts { + part := NewBitmap() + for k := 0; k < 200; k++ { + key := uint32(r.Intn(4096)) + switch r.Intn(3) { + case 0: + part.Add(key<<16 | uint32(r.Intn(1<<16))) + case 1: + start := uint64(key)<<16 | uint64(r.Intn(1<<15)) + part.AddRange(start, start+uint64(1+r.Intn(1<<15))) + default: + for n := 0; n < 5000; n++ { + part.Add(key<<16 | uint32(r.Intn(1<<16))) + } + } + } + if i%2 == 0 { + part.RunOptimize() + } + parts[i] = part + want.Or(part) + } + snapshots := make([]*Bitmap, len(parts)) + for i, part := range parts { + snapshots[i] = part.Clone() + } + got := FastOr(parts...) + assert.True(t, got.Equals(want)) + assert.NoError(t, got.Validate()) + // mutating the result must not leak into any input + for i := 0; i < 4096; i += 3 { + got.Add(uint32(i)<<16 | 12345) + } + for i, part := range parts { + assert.True(t, part.Equals(snapshots[i]), "input %d changed", i) + } +} + func TestBitmapOrBulkMergeCopyOnWriteOwnership(t *testing.T) { fixture := bitmapOrBulkMergeInterleavedFixture(64, true) left := fixture.lefts[0] diff --git a/roaringarray.go b/roaringarray.go index 567d0c08..900a09ff 100644 --- a/roaringarray.go +++ b/roaringarray.go @@ -353,6 +353,20 @@ func (ra *roaringArray) getUnionedWritableContainer(pos int, other container) co return ra.getContainerAtIndex(pos).ior(other) } +// getLazyUnionedWritableContainer computes the lazy in-place union used by +// FastOr: the result may have an invalid cardinality until repairAfterLazy. +func (ra *roaringArray) getLazyUnionedWritableContainer(pos int, other container) container { + c := ra.getWritableContainerAtIndex(pos) + // 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 := c.(*runContainer16); ok && !rc.isFull() { + c = rc.toBitmapContainer() + } + return c.lazyIOR(other) +} + func (ra *roaringArray) getWritableContainerAtIndex(i int) container { if ra.needCopyOnWrite[i] { ra.containers[i] = ra.containers[i].clone() @@ -410,11 +424,20 @@ func (ra *roaringArray) copyOrSourceContainerAt(other *roaringArray, index int, return other.containers[index].clone(), 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. +// mergeOp selects how mergeBulk combines a pair of aligned containers. +type mergeOp uint8 + +const ( + mergeOr mergeOp = iota // union, as in Bitmap.Or + mergeXor // symmetric difference, as in Bitmap.Xor + mergeLazyOr // lazy union, as in FastOr; needs repairAfterLazy +) + +// mergeBulk finishes an in-place union (mergeOr, mergeLazyOr) or symmetric +// difference (mergeXor) 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. // // 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 @@ -427,7 +450,7 @@ func (ra *roaringArray) copyOrSourceContainerAt(other *roaringArray, index int, // Like every other roaringArray operation it assumes both arrays already hold // their keys in sorted order; that invariant is enforced at the load boundary // (Validate), not re-checked here. -func (ra *roaringArray) mergeBulk(other *roaringArray, dst, left, right int, xor bool) { +func (ra *roaringArray) mergeBulk(other *roaringArray, dst, left, right int, op mergeOp) { length1 := ra.size() length2 := other.size() receiverLastKey := ra.keys[length1-1] @@ -477,9 +500,12 @@ func (ra *roaringArray) mergeBulk(other *roaringArray, dst, left, right int, xor // Union of two non-empty containers is never empty, so the // isEmpty check only ever drops a container for xor. var c container - if xor { + switch op { + case mergeXor: c = ra.getWritableContainerAtIndex(left).ixor(other.containers[right]) - } else { + case mergeLazyOr: + c = ra.getLazyUnionedWritableContainer(left, other.containers[right]) + default: c = ra.getUnionedWritableContainer(left, other.containers[right]) } if !c.isEmpty() {