diff --git a/arraycontainer.go b/arraycontainer.go index 1c9f32fe..4f066c73 100644 --- a/arraycontainer.go +++ b/arraycontainer.go @@ -1319,7 +1319,7 @@ func (ac *arrayContainer) toEfficientContainer() container { sizeAsBitmapContainer := bitmapContainerSizeInBytes() card := ac.getCardinality() sizeAsArrayContainer := arrayContainerSizeInBytes(card) - if sizeAsRunContainer < minOfInt(sizeAsBitmapContainer, sizeAsArrayContainer) { + if numRuns <= maxRunsInRunContainer && sizeAsRunContainer < minOfInt(sizeAsBitmapContainer, sizeAsArrayContainer) { return newRunContainer16FromArrayRuns(ac, numRuns) } if card <= arrayDefaultMaxSize { diff --git a/bitmapcontainer.go b/bitmapcontainer.go index c786c62d..9833bd01 100644 --- a/bitmapcontainer.go +++ b/bitmapcontainer.go @@ -1325,7 +1325,7 @@ func (bc *bitmapContainer) toEfficientContainer() container { numRuns := bc.numberOfRunsUpTo(minSize / perIntervalRc16Size) sizeAsRunContainer := runContainer16SerializedSizeInBytes(numRuns) - if sizeAsRunContainer < minSize { + if numRuns <= maxRunsInRunContainer && sizeAsRunContainer < minSize { return newRunContainer16FromBitmapContainerRuns(bc, numRuns) } if card <= arrayDefaultMaxSize { diff --git a/bitmapcontainer_test.go b/bitmapcontainer_test.go index 6ea33398..9fa187fd 100644 --- a/bitmapcontainer_test.go +++ b/bitmapcontainer_test.go @@ -321,7 +321,7 @@ func TestBitmapContainerIAndNot(t *testing.T) { for i := 0; i < arrayDefaultMaxSize-3; i++ { rc = rc.iaddRange(i*3, i*3+1) } - rc.iaddRange(math.MaxUint16-3, math.MaxUint16+1) + rc = rc.iaddRange(math.MaxUint16-3, math.MaxUint16+1) bc = bc.iandNot(rc) @@ -783,7 +783,8 @@ func TestBitmapContainerToEfficientContainerChoice(t *testing.T) { card := bc.getCardinality() want := bitmapContype switch { - case runContainer16SerializedSizeInBytes(numRuns) < min(bitmapContainerSizeInBytes(), arrayContainerSizeInBytes(card)): + case numRuns <= maxRunsInRunContainer && + runContainer16SerializedSizeInBytes(numRuns) < min(bitmapContainerSizeInBytes(), arrayContainerSizeInBytes(card)): want = run16Contype case card <= arrayDefaultMaxSize: want = arrayContype diff --git a/roaring64/roaring64_test.go b/roaring64/roaring64_test.go index 106303ce..f909b772 100644 --- a/roaring64/roaring64_test.go +++ b/roaring64/roaring64_test.go @@ -2142,16 +2142,19 @@ func TestRoaringArray64SortOrder(t *testing.T) { }) } -func TestRunOptimizeRecoversSpaceAfterRemoveRange(t *testing.T) { +func TestRemoveRangeDoesNotGrowRunsPastBitmapSize(t *testing.T) { bm := New() bm.AddRange(0, 65536) for i := uint64(0); i < 65536; i += 2 { - bm.RemoveRange(i, i+1) // each remaining value becomes a run of length one + bm.RemoveRange(i, i+1) // each remaining value would be a run of length one } + // A run container with 32768 runs would take about 128 KiB; once it + // passes 2047 runs it must become a bitmap container instead. + assert.False(t, bm.HasRunCompression()) + assert.Less(t, bm.GetSerializedSizeInBytes(), uint64(8192+64)) + assert.Equal(t, uint64(32768), bm.GetCardinality()) expected := bm.Clone() - before := bm.GetSerializedSizeInBytes() bm.RunOptimize() - assert.Less(t, bm.GetSerializedSizeInBytes(), before/10) assert.False(t, bm.HasRunCompression()) assert.True(t, expected.Equals(bm)) } diff --git a/roaring_test.go b/roaring_test.go index de3b9578..947f0051 100644 --- a/roaring_test.go +++ b/roaring_test.go @@ -455,7 +455,7 @@ func hashTest(t *testing.T, N uint64) { 4: {0: 3431046584319368119, 1: 8614077757284407143}, 8: {0: 10577784705589702583, 1: 11227064421971279799}, 16: {0: 13582283525559942071, 1: 8280698677262929847}, - 32: {0: 15930731229079543980, 1: 14540819050448025772}, + 32: {0: 15930731229079543980, 1: 8379075619665720492}, 64: {0: 15074197189812092501, 1: 8183429771446961749}, 128: {0: 16353918313334514501, 1: 8211290591646809413}, 256: {0: 17541269277318240901, 1: 15870350090812465285}, @@ -474,7 +474,7 @@ func hashTest(t *testing.T, N uint64) { 4: {0: 4410347288001337270, 1: 8610110719330578755}, 8: {0: 8603373155648831414, 1: 2315836927982075848}, 16: {0: 16944482119189024652, 1: 4822482652523786870}, - 32: {0: 6928244183881028666, 1: 10404343182114103400}, + 32: {0: 6928244183881028666, 1: 17964257898188937832}, 64: {0: 3024916132362050707, 1: 18344738716466403161}, 128: {0: 3834944388080394183, 1: 11965577797857582925}, 256: {0: 12578054101381780383, 1: 6432236967053365413}, @@ -493,7 +493,7 @@ func hashTest(t *testing.T, N uint64) { 4: {0: 2746848181595101094, 1: 8606425156353572383}, 8: {0: 16463913002427077937, 1: 4531009983748580157}, 16: {0: 5620696034248496124, 1: 1681598425519654588}, - 32: {0: 14741226801656710698, 1: 15129443590117138858}, + 32: {0: 14741226801656710698, 1: 12294437372374694826}, 64: {0: 6054465815016208075, 1: 17167720527236979867}, 128: {0: 16740558302224955231, 1: 6094338199568812847}, 256: {0: 16186283226139238340, 1: 9873750830371717112}, @@ -4294,16 +4294,19 @@ func TestValidateAcceptsRunContainersThatAreNotTheSmallestEncoding(t *testing.T) assert.True(t, expected.Equals(deserialized)) } -func TestRunOptimizeRecoversSpaceAfterRemoveRange(t *testing.T) { +func TestRemoveRangeDoesNotGrowRunsPastBitmapSize(t *testing.T) { bm := New() bm.AddRange(0, 65536) for i := uint64(0); i < 65536; i += 2 { - bm.RemoveRange(i, i+1) // each remaining value becomes a run of length one + bm.RemoveRange(i, i+1) // each remaining value would be a run of length one } + // A run container with 32768 runs would take about 128 KiB; once it + // passes 2047 runs it must become a bitmap container instead. + assert.False(t, bm.HasRunCompression()) + assert.Less(t, bm.GetSerializedSizeInBytes(), uint64(8192+64)) + assert.Equal(t, uint64(32768), bm.GetCardinality()) expected := bm.Clone() - before := bm.GetSerializedSizeInBytes() bm.RunOptimize() - assert.Less(t, bm.GetSerializedSizeInBytes(), before/10) assert.False(t, bm.HasRunCompression()) assert.True(t, expected.Equals(bm)) require.NoError(t, bm.Validate()) diff --git a/runcontainer.go b/runcontainer.go index dc8ebb50..c9f2c1c0 100644 --- a/runcontainer.go +++ b/runcontainer.go @@ -73,6 +73,25 @@ var ( MaxIntervalsSum = 2048 ) +// maxRunsInRunContainer is the most runs a run container may hold. With +// 2048 runs or more, a serialized run container (4 bytes per run plus 2 +// bytes) is larger than the 8192 bytes of a bitmap container's words, so +// operations convert it to an array or a bitmap container instead. The other +// Roaring implementations never produce such run containers either. +const maxRunsInRunContainer = 2047 + +// limitRuns returns rc if it has at most maxRunsInRunContainer runs, and +// otherwise an equivalent array or bitmap container. +func (rc *runContainer16) limitRuns() container { + if len(rc.iv) <= maxRunsInRunContainer { + return rc + } + if rc.getCardinality() <= arrayDefaultMaxSize { + return rc.toArrayContainer() + } + return newBitmapContainerFromRun(rc) +} + func newInterval16Range(start, last uint16) interval16 { if last < start { panic(fmt.Sprintf("last (%d) cannot be smaller than start (%d)", last, start)) @@ -2117,7 +2136,7 @@ func (rc *runContainer16) iaddRange(firstOfRange, endx int) container { }, }) *rc = *rc.union(addme) - return rc + return rc.limitRuns() } // remove the values in the range [firstOfRange,endx) @@ -2132,7 +2151,7 @@ func (rc *runContainer16) iremoveRange(firstOfRange, endx int) container { } x := newInterval16Range(uint16(firstOfRange), uint16(endx-1)) rc.isubtract(x) - return rc + return rc.limitRuns() } // not flip the values in the range [firstOfRange,endx) @@ -2141,7 +2160,7 @@ func (rc *runContainer16) not(firstOfRange, endx int) container { panic(fmt.Sprintf("invalid %v = endx > firstOfRange = %v", endx, firstOfRange)) } - return rc.Not(firstOfRange, endx) + return rc.Not(firstOfRange, endx).limitRuns() } // Not flips the values in the range [firstOfRange,endx). @@ -2253,7 +2272,7 @@ func (rc *runContainer16) or(a container) container { } switch c := a.(type) { case *runContainer16: - return rc.union(c) + return rc.union(c).limitRuns() case *arrayContainer: return rc.orArray(c) case *bitmapContainer: @@ -2788,7 +2807,7 @@ func (rc *runContainer16) toEfficientContainer() container { sizeAsBitmapContainer := bitmapContainerSizeInBytes() card := rc.getCardinality() sizeAsArrayContainer := arrayContainerSizeInBytes(card) - if sizeAsRunContainer < minOfInt(sizeAsBitmapContainer, sizeAsArrayContainer) { + if len(rc.iv) <= maxRunsInRunContainer && sizeAsRunContainer < minOfInt(sizeAsBitmapContainer, sizeAsArrayContainer) { return rc } if card <= arrayDefaultMaxSize { @@ -2802,7 +2821,7 @@ func (rc *runContainer16) toEfficientContainerFromCardinality(card int) containe sizeAsRunContainer := rc.getSizeInBytes() sizeAsBitmapContainer := bitmapContainerSizeInBytes() sizeAsArrayContainer := arrayContainerSizeInBytes(card) - if sizeAsRunContainer < minOfInt(sizeAsBitmapContainer, sizeAsArrayContainer) { + if len(rc.iv) <= maxRunsInRunContainer && sizeAsRunContainer < minOfInt(sizeAsBitmapContainer, sizeAsArrayContainer) { return rc } if card <= arrayDefaultMaxSize { diff --git a/runcontainer_maxruns_test.go b/runcontainer_maxruns_test.go new file mode 100644 index 00000000..079ff953 --- /dev/null +++ b/runcontainer_maxruns_test.go @@ -0,0 +1,270 @@ +package roaring + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// runsEvery returns n runs of runLen values, one starting every stride values. +func runsEvery(n, stride, runLen int) []interval16 { + iv := make([]interval16, n) + for i := range iv { + iv[i] = interval16{start: uint16(i * stride), length: uint16(runLen - 1)} + } + return iv +} + +// assertRunLimit fails if any run container of rb holds more than +// maxRunsInRunContainer runs. +func assertRunLimit(t *testing.T, rb *Bitmap) { + t.Helper() + for i, c := range rb.highlowcontainer.containers { + if rc, ok := c.(*runContainer16); ok { + assert.LessOrEqual(t, len(rc.iv), maxRunsInRunContainer, + "run container at index %d has too many runs", i) + } + } +} + +// assertNotOverfullRun fails if c is a run container with more than +// maxRunsInRunContainer runs. +func assertNotOverfullRun(t *testing.T, c container) { + t.Helper() + if rc, ok := c.(*runContainer16); ok { + assert.LessOrEqual(t, len(rc.iv), maxRunsInRunContainer) + } +} + +// fullRunContainer returns a run container holding maxRunsInRunContainer +// runs of three values, one every 32 values: the largest run container that +// is still smaller than a bitmap container. +func fullRunContainer() *runContainer16 { + return newRunContainer16TakeOwnership(runsEvery(maxRunsInRunContainer, 32, 3)) +} + +func TestRunContainerMaxRunsSize(t *testing.T) { + // A run container at the limit is smaller than a bitmap container; one + // more run would make it larger. + const bitmapBytes = (1 << 16) / 8 + assert.Less(t, runContainer16SerializedSizeInBytes(maxRunsInRunContainer), bitmapBytes) + assert.Greater(t, runContainer16SerializedSizeInBytes(maxRunsInRunContainer+1), bitmapBytes) + assert.IsType(t, &runContainer16{}, fullRunContainer().toEfficientContainer()) + + // Containers with one run more than the limit, in each type, must not + // become run containers. + over := newRunContainer16TakeOwnership(runsEvery(maxRunsInRunContainer+1, 32, 3)) + assert.IsType(t, &bitmapContainer{}, over.toEfficientContainer()) + assert.IsType(t, &bitmapContainer{}, over.toEfficientContainerFromCardinality(over.getCardinality())) + assert.IsType(t, &bitmapContainer{}, over.toBitmapContainer().toEfficientContainer()) + // An oversized array container (more than arrayDefaultMaxSize values) is + // compared against a bitmap container too. + assert.IsType(t, &bitmapContainer{}, over.toArrayContainer().toEfficientContainer()) +} + +func TestRunContainerMaxRunsLimitRuns(t *testing.T) { + rc := fullRunContainer() + assert.Same(t, rc, rc.limitRuns()) + + // 2048 runs of three values: too many values for an array container. + big := newRunContainer16TakeOwnership(runsEvery(maxRunsInRunContainer+1, 32, 3)) + c := big.limitRuns() + require.IsType(t, &bitmapContainer{}, c) + assert.True(t, c.equals(big)) + + // 2048 runs of one value: few enough values for an array container. + small := newRunContainer16TakeOwnership(runsEvery(maxRunsInRunContainer+1, 2, 1)) + c = small.limitRuns() + require.IsType(t, &arrayContainer{}, c) + assert.True(t, c.equals(small)) +} + +func TestRunContainerMaxRunsOps(t *testing.T) { + extra := newRunContainer16Range(65520, 65522) + + t.Run("or", func(t *testing.T) { + rc := fullRunContainer() + c := rc.or(extra) + assertNotOverfullRun(t, c) + assert.Equal(t, rc.getCardinality()+3, c.getCardinality()) + assert.True(t, c.contains(65521)) + }) + + t.Run("ior", func(t *testing.T) { + rc := fullRunContainer() + want := rc.getCardinality() + 3 + c := rc.ior(extra) + assertNotOverfullRun(t, c) + assert.Equal(t, want, c.getCardinality()) + }) + + t.Run("lazyOR", func(t *testing.T) { + rc := fullRunContainer() + c := rc.lazyOR(extra) + assertNotOverfullRun(t, c) + assert.Equal(t, rc.getCardinality()+3, c.getCardinality()) + }) + + t.Run("iaddRange", func(t *testing.T) { + rc := fullRunContainer() + want := rc.getCardinality() + 3 + c := rc.iaddRange(65520, 65523) + assertNotOverfullRun(t, c) + assert.Equal(t, want, c.getCardinality()) + }) + + t.Run("iadd", func(t *testing.T) { + rc := fullRunContainer() + want := rc.getCardinality() + 1 + c := rc.iaddReturnMinimized(65520) + assertNotOverfullRun(t, c) + assert.Equal(t, want, c.getCardinality()) + }) + + t.Run("iremoveRange", func(t *testing.T) { + // 2046 short runs and one long run at the end: removing from the + // middle of the long run splits it into two. + iv := runsEvery(maxRunsInRunContainer-1, 16, 3) + iv = append(iv, interval16{start: 40000, length: 10000}) + rc := newRunContainer16TakeOwnership(iv) + want := rc.getCardinality() - 10 + c := rc.iremoveRange(45000, 45010) + assertNotOverfullRun(t, c) + assert.Equal(t, want, c.getCardinality()) + assert.False(t, c.contains(45005)) + assert.True(t, c.contains(45010)) + }) + + t.Run("iremove", func(t *testing.T) { + iv := runsEvery(maxRunsInRunContainer-1, 16, 3) + iv = append(iv, interval16{start: 40000, length: 10000}) + rc := newRunContainer16TakeOwnership(iv) + want := rc.getCardinality() - 1 + c := rc.iremoveReturnMinimized(45000) + assertNotOverfullRun(t, c) + assert.Equal(t, want, c.getCardinality()) + }) + + t.Run("not", func(t *testing.T) { + // Flipping [0, 65536) of the full container yields 2048 runs. + rc := fullRunContainer() + want := 65536 - rc.getCardinality() + c := rc.not(0, 65536) + assertNotOverfullRun(t, c) + assert.Equal(t, want, c.getCardinality()) + assert.False(t, c.contains(0)) + assert.True(t, c.contains(3)) + }) + + t.Run("inot", func(t *testing.T) { + rc := fullRunContainer() + want := 65536 - rc.getCardinality() + c := rc.inot(0, 65536) + assertNotOverfullRun(t, c) + assert.Equal(t, want, c.getCardinality()) + }) + + t.Run("andNot", func(t *testing.T) { + // Punching a hole in each long run doubles the number of runs. + long := newRunContainer16TakeOwnership(runsEvery(1500, 40, 20)) + holes := newRunContainer16TakeOwnership(runsEvery(1500, 40, 1)) + for i := range holes.iv { + holes.iv[i].start += 10 + } + want := long.getCardinality() - 1500 + c := long.andNot(holes) + assertNotOverfullRun(t, c) + assert.Equal(t, want, c.getCardinality()) + + c = long.iandNot(holes) + assertNotOverfullRun(t, c) + assert.Equal(t, want, c.getCardinality()) + }) +} + +func TestBitmapMaxRuns(t *testing.T) { + // base has a single container holding maxRunsInRunContainer runs. + base := func() *Bitmap { + rb := NewBitmap() + for i := 0; i < maxRunsInRunContainer; i++ { + rb.AddRange(uint64(i*32), uint64(i*32+3)) + } + rb.RunOptimize() + require.IsType(t, &runContainer16{}, rb.highlowcontainer.containers[0]) + return rb + } + extra := func() *Bitmap { + rb := NewBitmap() + rb.AddRange(65520, 65523) + return rb + } + + t.Run("OrRun", func(t *testing.T) { + other := extra() + other.AddRange(65530, 65536) + other.RunOptimize() + require.IsType(t, &runContainer16{}, other.highlowcontainer.containers[0]) + rb := Or(base(), other) + assertRunLimit(t, rb) + assert.Equal(t, uint64(maxRunsInRunContainer*3+9), rb.GetCardinality()) + }) + + t.Run("Or", func(t *testing.T) { + rb := Or(base(), extra()) + assertRunLimit(t, rb) + assert.Equal(t, uint64(maxRunsInRunContainer*3+3), rb.GetCardinality()) + }) + + t.Run("InPlaceOr", func(t *testing.T) { + rb := base() + rb.Or(extra()) + assertRunLimit(t, rb) + assert.Equal(t, uint64(maxRunsInRunContainer*3+3), rb.GetCardinality()) + }) + + t.Run("FastOr", func(t *testing.T) { + rb := FastOr(base(), extra()) + assertRunLimit(t, rb) + assert.Equal(t, uint64(maxRunsInRunContainer*3+3), rb.GetCardinality()) + }) + + t.Run("AddRange", func(t *testing.T) { + rb := base() + rb.AddRange(65520, 65523) + assertRunLimit(t, rb) + assert.Equal(t, uint64(maxRunsInRunContainer*3+3), rb.GetCardinality()) + }) + + t.Run("Add", func(t *testing.T) { + rb := base() + rb.Add(65520) + assertRunLimit(t, rb) + assert.Equal(t, uint64(maxRunsInRunContainer*3+1), rb.GetCardinality()) + }) + + t.Run("Flip", func(t *testing.T) { + rb := base() + rb.Flip(0, 65536) + assertRunLimit(t, rb) + assert.Equal(t, uint64(65536-maxRunsInRunContainer*3), rb.GetCardinality()) + + rb = Flip(base(), 0, 65536) + assertRunLimit(t, rb) + assert.Equal(t, uint64(65536-maxRunsInRunContainer*3), rb.GetCardinality()) + }) + + t.Run("RemoveRange", func(t *testing.T) { + rb := NewBitmap() + for i := 0; i < maxRunsInRunContainer-1; i++ { + rb.AddRange(uint64(i*16), uint64(i*16+3)) + } + rb.AddRange(40000, 50001) + rb.RunOptimize() + require.IsType(t, &runContainer16{}, rb.highlowcontainer.containers[0]) + want := rb.GetCardinality() - 10 + rb.RemoveRange(45000, 45010) + assertRunLimit(t, rb) + assert.Equal(t, want, rb.GetCardinality()) + }) +}