File: bloomfilter_test.go

package info (click to toggle)
golang-github-greatroar-blobloom 0.4.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 188 kB
  • sloc: asm: 217; sh: 11; makefile: 3
file content (327 lines) | stat: -rw-r--r-- 6,372 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// Licensed 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 blobloom

import (
	"crypto/sha256"
	"encoding/binary"
	"encoding/hex"
	"math"
	"math/rand"
	"sync"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestSimple(t *testing.T) {
	t.Parallel()

	keys := randomU64(10000, 0x758e326)

	for _, config := range []struct {
		nbits   uint64
		nhashes int
	}{
		{1, 2},
		{1024, 4},
		{100, 3},
		{10000, 7},
		{1000000, 14},
	} {
		f := New(config.nbits, config.nhashes)
		assert.GreaterOrEqual(t, f.NumBits(), config.nbits)
		assert.LessOrEqual(t, f.NumBits(), config.nbits+BlockBits)

		for _, k := range keys {
			assert.False(t, f.Has(k))
		}
		for _, k := range keys {
			f.Add(k)
		}
		for _, k := range keys {
			assert.True(t, f.Has(k))
		}

		f.Clear()
		for _, k := range keys {
			assert.False(t, f.Has(k))
		}
	}
}

func TestUse(t *testing.T) {
	t.Parallel()

	const n = 100000

	// For FPR = .01, n = 100000, the optimal number of bits is 958505.84
	// for a standard Bloom filter.
	f := NewOptimized(Config{
		Capacity: n,
		FPRate:   .01,
	})
	if f.NumBits() < 958506 {
		t.Fatalf("bloom filter with %d bits too small", f.NumBits())
	}

	t.Logf("k = %d; m/n = %d/%d = %.3f",
		f.k, f.NumBits(), n, float64(f.NumBits())/n)

	// Generate random hash values for n keys. Pretend the keys are all distinct,
	// even if the hashes are not.
	// Assume that 100k random SHA-256 values are all distinct.
	r := rand.New(rand.NewSource(0xb1007))
	hashes := make([]uint64, n)
	for i := range hashes {
		hashes[i] = r.Uint64()
	}

	for _, h := range hashes {
		f.Add(h)
	}

	for _, h := range hashes {
		if !f.Has(h) {
			t.Errorf("%032x added to Bloom filter but not found", h)
		}
	}

	// Generate some more random hashes to get a sense of the FPR.
	// Pretend these represent unique keys, distinct from the ones we added.
	const nTest = 10000
	fp := 0
	for i := 0; i < nTest; i++ {
		if f.Has(r.Uint64()) {
			fp++
		}
	}

	fpr := float64(fp) / nTest
	assert.Less(t, fpr, .02)
	t.Logf("FPR = %.5f\n", fpr)
}

func TestDoubleHashing(t *testing.T) {
	t.Parallel()

	var h1, h2 uint32 = 0, 0

	for i := 0; i < 20; i++ {
		h1, h2 = doublehash(h1, h2, i)
		assert.NotEqual(t, h2, 0)
	}
}

func TestReducerange(t *testing.T) {
	t.Parallel()

	for i := 0; i < 40000; i++ {
		m := rand.Uint32()
		j := reducerange(rand.Uint32(), m)
		if m == 0 {
			assert.Equal(t, j, 0)
		}
		assert.Less(t, j, m)
	}
}

func TestAtomic(t *testing.T) {
	var (
		ch  = make(chan uint64)
		f   = New(1<<13, 4)
		ref = New(1<<13, 4)
	)

	go func() {
		r := rand.New(rand.NewSource(0xaeb15))
		for i := 0; i < 1e4; i++ {
			h := r.Uint64()
			ref.Add(h)
			ch <- h
		}
		close(ch)
	}()

	var wg sync.WaitGroup
	for i := 0; i < 4; i++ {
		wg.Add(1)
		go func() {
			for h := range ch {
				f.AddAtomic(h)
			}
			wg.Done()
		}()
	}
	wg.Wait()

	assert.Equal(t, ref, f)
}

func TestCardinality(t *testing.T) {
	t.Parallel()

	const cap = 1e4
	f := NewOptimized(Config{
		Capacity: cap,
		FPRate:   .0015,
	})

	assert.EqualValues(t, 0, f.Cardinality())

	r := rand.New(rand.NewSource(0x81feae2b))

	var sumN, sumNhat float64
	for n := 1.0; n <= 5*cap; n++ {
		f.Add(r.Uint64())

		nhat := f.Cardinality()
		assert.InDelta(t, 1, nhat/float64(n), 0.09)

		sumN += n
		sumNhat += nhat
		if int(n)%cap == 0 {
			// On average, we want to be less than a percent off.
			assert.InDelta(t, 1, sumNhat/sumN, 0.008)
		}
	}
}

func TestCardinalityFull(t *testing.T) {
	t.Parallel()

	f := New(BlockBits, 2)
	for i := range f.b {
		for j := range f.b[i] {
			f.b[i][j] = ^uint32(0)
		}
	}

	assert.Equal(t, math.Inf(+1), f.Cardinality())
}

func TestIntersect(t *testing.T) {
	t.Parallel()

	const n uint64 = 1e4
	const seed = 0x5544332211
	hashes := randomU64(int(n), seed)

	f := NewOptimized(Config{Capacity: n, FPRate: 1e-3})
	g := NewOptimized(Config{Capacity: n, FPRate: 1e-3})
	i := NewOptimized(Config{Capacity: n, FPRate: 1e-3})

	for _, h := range hashes[:n/3] {
		f.Add(h)
	}
	for _, h := range hashes[n/3 : 2*n/3] {
		f.Add(h)
		g.Add(h)
		i.Add(h)
	}
	for _, h := range hashes[n/3:] {
		g.Add(h)
	}

	expectFPR := math.Min(f.FPRate(n), g.FPRate(n))

	f.Intersect(g)
	assert.NotEqual(t, i, g)

	for _, h := range hashes[n/3 : 2*n/3] {
		assert.True(t, f.Has(h))
	}

	var fp uint64
	for _, h := range hashes {
		if f.Has(h) && !i.Has(h) {
			fp++
		}
	}
	actualFPR := float64(fp) / float64(n)
	assert.Less(t, actualFPR, 2*expectFPR)
	t.Logf("FPR = %f", actualFPR)

	assert.Panics(t, func() { f.Intersect(New(f.NumBits(), 9)) })
	assert.Panics(t, func() { f.Union(New(n+BlockBits, f.k)) })
}

func TestUnion(t *testing.T) {
	t.Parallel()

	const n = 1e5
	hashes := randomU64(n, 0xa6e98fb)

	f := New(n, 5)
	g := New(n, 5)
	u := New(n, 5)

	for _, h := range hashes[:n/2] {
		f.Add(h)
		u.Add(h)
	}
	for _, h := range hashes[n/2:] {
		g.Add(h)
		u.Add(h)
	}

	assert.NotEqual(t, f, g)

	f.Union(g)
	assert.Equal(t, u, f)
	assert.NotEqual(t, u, g)

	g.Union(f)
	assert.Equal(t, u, g)

	assert.Panics(t, func() { f.Union(New(n, 4)) })
	assert.Panics(t, func() { f.Union(New(n+BlockBits, 5)) })
}

func randomU64(n int, seed int64) []uint64 {
	r := rand.New(rand.NewSource(seed))
	p := make([]uint64, n)
	for i := range p {
		p[i] = r.Uint64()
	}
	return p
}

func TestUnionSmall(t *testing.T) {
	f := New(BlockBits, 2)
	g := New(BlockBits, 2)

	g.Add(42)

	f.Union(g)
	assert.True(t, f.Has(42))
}

// This test ensures that the switch from 64-bit to 32-bit words did not
// alter the little-endian serialization of blocks.
func TestBlockLayout(t *testing.T) {
	t.Parallel()

	var b block
	b.setbit(0)
	b.setbit(1)
	b.setbit(111)
	b.setbit(499)

	assert.Equal(t, BlockBits, 8*binary.Size(b))

	h := sha256.New()
	binary.Write(h, binary.LittleEndian, b)
	expect := "aa7f8c411600fa387f0c10641eab428a7ed2f27a86171ac69f0e2087b2aa9140"
	assert.Equal(t, expect, hex.EncodeToString(h.Sum(nil)))
}