forked from kelindar/column
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snapshot_test.go
381 lines (324 loc) · 9.39 KB
/
snapshot_test.go
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// Copyright (c) Roman Atachiants and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
package column
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/rand"
"runtime"
"sync"
"sync/atomic"
"testing"
"github.com/kelindar/async"
"github.com/kelindar/column/commit"
"github.com/stretchr/testify/assert"
)
/*
cpu: Intel(R) Core(TM) i7-9700K CPU @ 3.60GHz
BenchmarkSave/write-to-8 8 131800350 ns/op 981.98 MB/s 6539521 B/op 1950 allocs/op
BenchmarkSave/read-from-8 13 79411685 ns/op 1629.80 MB/s 135661336 B/op 4610 allocs/op
*/
func BenchmarkSave(b *testing.B) {
b.Run("write-state", func(b *testing.B) {
output := bytes.NewBuffer(nil)
input := loadPlayers(1e6)
runtime.GC()
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
output.Reset()
n, _ := input.writeState(output)
b.SetBytes(n)
}
})
b.Run("read-state", func(b *testing.B) {
buffer := bytes.NewBuffer(nil)
output := NewCollection()
input := loadPlayers(1e6)
input.writeState(buffer)
runtime.GC()
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
output.readState(bytes.NewBuffer(buffer.Bytes()))
b.SetBytes(int64(buffer.Len()))
}
})
}
// --------------------------- Streaming ----------------------------
// Test replication many times
func TestReplicate(t *testing.T) {
for x := 0; x < 20; x++ {
rand.Seed(int64(x))
runReplication(t, 10000, 50, runtime.NumCPU())
}
}
// runReplication runs a concurrent replication test
func runReplication(t *testing.T, updates, inserts, concurrency int) {
t.Run(fmt.Sprintf("replicate-%v-%v", updates, inserts), func(t *testing.T) {
writer := make(commit.Channel, 10)
object := map[string]interface{}{
"float64": float64(0),
"int32": int32(0),
"string": "",
}
// Create a primary
primary := NewCollection(Options{
Capacity: inserts,
Writer: &writer,
})
// Replica with the same schema
replica := NewCollection(Options{
Capacity: inserts,
})
// Create schemas and start streaming replication into the replica
primary.CreateColumnsOf(object)
replica.CreateColumnsOf(object)
var done sync.WaitGroup
done.Add(1)
go func() {
defer done.Done() // Drained
for change := range writer {
assert.NoError(t, replica.Replay(change))
}
}()
// Write some objects
for i := 0; i < inserts; i++ {
primary.InsertObject(object)
}
work := make(chan async.Task)
pool := async.Consume(context.Background(), 50, work)
defer pool.Cancel()
// Random concurrent updates
var wg sync.WaitGroup
wg.Add(updates)
for i := 0; i < updates; i++ {
work <- async.NewTask(func(ctx context.Context) (interface{}, error) {
defer wg.Done()
// Randomly update a column
primary.Query(func(txn *Txn) error {
txn.cursor = uint32(rand.Int31n(int32(inserts - 1)))
switch rand.Int31n(3) {
case 0:
col := txn.Float64("float64")
col.Set(math.Round(rand.Float64()*1000) / 100)
case 1:
col := txn.Int32("int32")
col.Set(rand.Int31n(100000))
case 2:
col := txn.String("string")
col.Set(fmt.Sprintf("hi %v", rand.Int31n(10)))
}
return nil
})
// Randomly delete an item
if rand.Int31n(5) == 0 {
primary.DeleteAt(uint32(rand.Int31n(int32(inserts - 1))))
}
// Randomly insert an item
if rand.Int31n(5) == 0 {
primary.InsertObject(object)
}
return nil, nil
})
}
// Replay all of the changes into the replica
wg.Wait()
close(writer)
done.Wait()
// Check if replica and primary are the same
if !assert.Equal(t, primary.Count(), replica.Count(), "replica and primary should be the same size") {
return
}
/*primary.Query(func(txn *Txn) error {
col1 := txn.Float64("float64")
return txn.Range(func(idx uint32) {
if v1, ok := col1.Get(idx); ok && v1 != 0 {
replica.SelectAt(idx, func(v Selector) {
assert.Equal(t, v1, v.FloatAt("float64"))
})
}
})
})*/
})
}
// --------------------------- Snapshotting ----------------------------
func TestSnapshot(t *testing.T) {
amount := 50000
buffer := bytes.NewBuffer(nil)
input := loadPlayers(amount)
var wg sync.WaitGroup
wg.Add(amount)
go func() {
for i := 0; i < amount; i++ {
assert.NoError(t, input.QueryAt(uint32(i), func(r Row) error {
r.SetEnum("name", "Roman")
return nil
}))
wg.Done()
}
}()
// Start snapshotting
assert.NoError(t, input.Snapshot(buffer))
assert.NotZero(t, buffer.Len())
// Restore the snapshot
wg.Wait()
output := newEmpty(amount)
assert.NoError(t, output.Restore(buffer))
assert.Equal(t, amount, output.Count())
}
func TestSnapshotFailures(t *testing.T) {
input := NewCollection()
input.CreateColumn("name", ForString())
input.Insert(func(r Row) error {
r.SetString("name", "Roman")
return nil
})
go input.Insert(func(r Row) error {
r.SetString("name", "Roman")
return nil
})
for size := 0; size < 80; size++ {
output := &limitWriter{Limit: size}
assert.Error(t, input.Snapshot(output),
fmt.Sprintf("write failure size=%d", size))
}
}
func TestRestoreIncomplete(t *testing.T) {
buffer := bytes.NewBuffer(nil)
output := newEmpty(500)
assert.Error(t, output.Restore(buffer))
}
func TestSnapshotFailedAppendCommit(t *testing.T) {
input := NewCollection()
input.CreateColumn("name", ForString())
input.record = commit.Open(&limitWriter{Limit: 0})
_, err := input.Insert(func(r Row) error {
r.SetString("name", "Roman")
return nil
})
assert.NoError(t, err)
}
// --------------------------- State Codec ----------------------------
func TestWriteTo(t *testing.T) {
input := NewCollection()
input.CreateColumn("name", ForEnum())
for i := 0; i < 2e4; i++ {
input.Insert(func(r Row) error {
r.SetEnum("name", "Roman")
return nil
})
}
// Write a snapshot into a buffer
buffer := bytes.NewBuffer(nil)
n, err := input.writeState(buffer)
assert.NotZero(t, n)
assert.NoError(t, err)
// Restore the collection from the snapshot
output := NewCollection()
output.CreateColumn("name", ForEnum())
m, err := output.readState(buffer)
assert.NotEmpty(t, m)
assert.NoError(t, err)
assert.Equal(t, input.Count(), output.Count())
assert.NoError(t, output.QueryAt(0, func(r Row) error {
name, _ := r.Enum("name")
assert.Equal(t, "Roman", name)
return nil
}))
}
func TestCollectionCodec(t *testing.T) {
input := loadPlayers(5e4)
// Write a snapshot into a buffer
buffer := bytes.NewBuffer(nil)
n, err := input.writeState(buffer)
assert.NotZero(t, n)
assert.NoError(t, err)
// Restore the collection from the snapshot
output := newEmpty(5e4)
m, err := output.readState(buffer)
assert.NotEmpty(t, m)
assert.NoError(t, err)
assert.Equal(t, input.Count(), output.Count())
}
func TestWriteToSizeUncompresed(t *testing.T) {
input := loadPlayers(1e4) // 10K
output := bytes.NewBuffer(nil)
_, err := input.writeState(output)
assert.NoError(t, err)
assert.NotZero(t, output.Len())
}
func TestWriteToFailures(t *testing.T) {
input := NewCollection()
input.CreateColumn("name", ForString())
input.Insert(func(r Row) error {
r.SetString("name", "Roman")
return nil
})
for size := 0; size < 69; size++ {
output := &limitWriter{Limit: size}
_, err := input.writeState(output)
assert.Error(t, err, fmt.Sprintf("write failure size=%d", size))
}
}
func TestWriteEmpty(t *testing.T) {
buffer := bytes.NewBuffer(nil)
{ // Write the collection
input := NewCollection()
input.CreateColumn("name", ForString())
_, err := input.writeState(buffer)
assert.NoError(t, err)
}
{ // Read the collection back
output := NewCollection()
output.CreateColumn("name", ForString())
_, err := output.readState(buffer)
assert.NoError(t, err)
assert.Equal(t, 0, output.Count())
}
}
func TestReadFromFailures(t *testing.T) {
input := NewCollection()
input.CreateColumn("name", ForString())
input.Insert(func(r Row) error {
r.SetString("name", "Roman")
return nil
})
buffer := bytes.NewBuffer(nil)
_, err := input.writeState(buffer)
assert.NoError(t, err)
for size := 0; size < buffer.Len()-1; size++ {
output := NewCollection()
output.CreateColumn("name", ForString())
_, err := output.readState(bytes.NewReader(buffer.Bytes()[:size]))
assert.Error(t, err, fmt.Sprintf("read size %v", size))
}
}
// --------------------------- Mocks & Fixtures ----------------------------
// noopWriter is a writer that simply counts the commits
type noopWriter struct {
commits uint64
}
// Write clones the commit and writes it into the writer
func (w *noopWriter) Append(commit commit.Commit) error {
atomic.AddUint64(&w.commits, 1)
return nil
}
// limitWriter is a io.Writer that allows for limiting input
type limitWriter struct {
value uint32
Limit int
}
// Write returns either an error or no error, depending on whether the limit is reached
func (w *limitWriter) Write(p []byte) (int, error) {
if n := atomic.AddUint32(&w.value, uint32(len(p))); int(n) > w.Limit {
return 0, io.ErrShortBuffer
}
return len(p), nil
}
func (w *limitWriter) Read(p []byte) (int, error) {
return 0, nil
}