-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathsnapshot_test.go
407 lines (360 loc) · 11.5 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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package frostdb
import (
"context"
"math"
"os"
"strconv"
"testing"
"time"
"github.com/apache/arrow/go/v17/arrow"
"github.com/apache/arrow/go/v17/arrow/array"
"github.com/apache/arrow/go/v17/arrow/memory"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
"github.com/polarsignals/frostdb/dynparquet"
"github.com/polarsignals/frostdb/query"
"github.com/polarsignals/frostdb/query/logicalplan"
)
// insertSampleRecords is the same helper function as insertSamples but it inserts arrow records instead.
func insertSampleRecords(ctx context.Context, t *testing.T, table *Table, timestamps ...int64) uint64 {
t.Helper()
var samples dynparquet.Samples
samples = make([]dynparquet.Sample, 0, len(timestamps))
for _, ts := range timestamps {
samples = append(samples, dynparquet.Sample{
ExampleType: "ex",
Labels: map[string]string{
"label1": "value1",
},
Stacktrace: []uuid.UUID{
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1},
},
Timestamp: ts,
})
}
ar, err := samples.ToRecord()
require.NoError(t, err)
tx, err := table.InsertRecord(ctx, ar)
require.NoError(t, err)
return tx
}
func TestSnapshot(t *testing.T) {
ctx := context.Background()
// Create a new DB with multiple tables and granules with
// compacted/uncompacted parts that have a mixture of arrow/parquet records.
t.Run("Empty", func(t *testing.T) {
c, err := New(
WithStoragePath(t.TempDir()),
WithWAL(),
WithSnapshotTriggerSize(math.MaxInt64),
)
require.NoError(t, err)
defer c.Close()
db, err := c.DB(ctx, "test")
require.NoError(t, err)
// Complete a txn so that the snapshot is created at txn 1, snapshots at
// txn 0 are considered empty so ignored.
_, _, commit := db.begin()
commit()
tx := db.highWatermark.Load()
require.NoError(t, db.snapshotAtTX(ctx, tx, db.snapshotWriter(tx)))
txBefore := db.highWatermark.Load()
tx, err = db.loadLatestSnapshot(ctx)
require.NoError(t, err)
require.Equal(t, txBefore, tx)
})
t.Run("WithData", func(t *testing.T) {
c, err := New(
WithStoragePath(t.TempDir()),
WithWAL(),
WithSnapshotTriggerSize(math.MaxInt64),
)
require.NoError(t, err)
defer c.Close()
db, err := c.DB(ctx, "test")
require.NoError(t, err)
config := NewTableConfig(dynparquet.SampleDefinition())
table, err := db.Table("table1", config)
require.NoError(t, err)
insertSampleRecords(ctx, t, table, 1, 2, 3)
require.NoError(t, table.EnsureCompaction())
insertSampleRecords(ctx, t, table, 4, 5, 6)
insertSampleRecords(ctx, t, table, 7, 8, 9)
const overrideConfigVal = 1234
config.RowGroupSize = overrideConfigVal
table, err = db.Table("table2", config)
require.NoError(t, err)
insertSampleRecords(ctx, t, table, 1, 2, 3)
insertSampleRecords(ctx, t, table, 4, 5, 6)
config.BlockReaderLimit = overrideConfigVal
_, err = db.Table("empty", config)
require.NoError(t, err)
highWatermark := db.highWatermark.Load()
// Insert a sample that should not be snapshot.
insertSampleRecords(ctx, t, table, 10)
require.NoError(t, db.snapshotAtTX(ctx, highWatermark, db.snapshotWriter(highWatermark)))
// Create another db and verify.
snapshotDB, err := c.DB(ctx, "testsnapshot")
require.NoError(t, err)
// Load the other db's latest snapshot.
tx, err := snapshotDB.loadLatestSnapshotFromDir(ctx, db.snapshotsDir())
require.NoError(t, err)
require.Equal(t, highWatermark, tx)
require.Equal(t, highWatermark, snapshotDB.highWatermark.Load())
require.Equal(t, len(db.tables), len(snapshotDB.tables))
snapshotEngine := query.NewEngine(memory.DefaultAllocator, snapshotDB.TableProvider())
for _, testCase := range []struct {
name string
expMaxTimestamp int
}{
{
name: "table1",
expMaxTimestamp: 9,
},
{
name: "table2",
expMaxTimestamp: 6,
},
{
name: "empty",
},
} {
if testCase.expMaxTimestamp != 0 {
aggrMax := []*logicalplan.AggregationFunction{
logicalplan.Max(logicalplan.Col("timestamp")),
}
require.NoError(
t,
snapshotEngine.ScanTable(testCase.name).Aggregate(aggrMax, nil).Execute(ctx,
func(_ context.Context,
r arrow.Record,
) error {
require.Equal(
t, testCase.expMaxTimestamp, int(r.Column(0).(*array.Int64).Int64Values()[0]),
)
return nil
}),
)
}
// Reset sync.Maps so reflect.DeepEqual can be used below.
db.tables[testCase.name].schema.ResetWriters()
db.tables[testCase.name].schema.ResetBuffers()
require.Equal(t, db.tables[testCase.name].config.Load(), snapshotDB.tables[testCase.name].config.Load())
}
})
t.Run("WithConcurrentWrites", func(t *testing.T) {
cancelCtx, cancelWrites := context.WithCancel(ctx)
c, err := New(
WithStoragePath(t.TempDir()),
WithWAL(),
WithSnapshotTriggerSize(math.MaxInt64),
)
require.NoError(t, err)
defer c.Close()
db, err := c.DB(ctx, "test")
require.NoError(t, err)
config := NewTableConfig(dynparquet.SampleDefinition())
const tableName = "table"
table, err := db.Table(tableName, config)
require.NoError(t, err)
highWatermarkAtStart := db.highWatermark.Load()
shouldStartSnapshotChan := make(chan struct{})
var errg errgroup.Group
errg.Go(func() error {
ts := int64(highWatermarkAtStart)
for cancelCtx.Err() == nil {
tx := insertSampleRecords(ctx, t, table, ts)
// This check simply ensures that the assumption that inserting
// timestamp n corresponds to the n+1th transaction (the +1
// corresponding to table creation). This assumption is required
// by the snapshot.
require.Equal(t, uint64(ts+1), tx)
ts++
if ts == 10 {
close(shouldStartSnapshotChan)
}
}
return nil
})
// Wait until some writes have happened.
<-shouldStartSnapshotChan
defer cancelWrites()
snapshotDB, err := c.DB(ctx, "testsnapshot")
require.NoError(t, err)
tx := db.highWatermark.Load()
require.NoError(t, db.snapshotAtTX(ctx, tx, db.snapshotWriter(tx)))
snapshotTx, err := snapshotDB.loadLatestSnapshotFromDir(ctx, db.snapshotsDir())
require.NoError(t, err)
require.NoError(
t,
query.NewEngine(
memory.DefaultAllocator, snapshotDB.TableProvider(),
).ScanTable(tableName).Aggregate(
[]*logicalplan.AggregationFunction{logicalplan.Max(logicalplan.Col("timestamp"))}, nil,
).Execute(ctx, func(_ context.Context, r arrow.Record) error {
require.Equal(
t, int(snapshotTx-highWatermarkAtStart), int(r.Column(0).(*array.Int64).Int64Values()[0]),
)
return nil
}),
)
cancelWrites()
require.NoError(t, errg.Wait())
})
}
// TestSnapshotWithWAL verifies that the interaction between snapshots and WAL
// entries works as expected. In general, snapshots should occur when a table
// block is rotated out.
func TestSnapshotWithWAL(t *testing.T) {
const dbAndTableName = "test"
var (
ctx = context.Background()
dir = t.TempDir()
snapshotTx uint64
firstWriteTimestamp int64
)
func() {
c, err := New(
WithWAL(),
WithStoragePath(dir),
WithSnapshotTriggerSize(1),
)
require.NoError(t, err)
defer c.Close()
db, err := c.DB(ctx, dbAndTableName)
require.NoError(t, err)
schema := dynparquet.SampleDefinition()
table, err := db.Table(dbAndTableName, NewTableConfig(schema))
require.NoError(t, err)
samples := dynparquet.NewTestSamples()
firstWriteTimestamp = samples[0].Timestamp
for i := range samples {
samples[i].Timestamp = firstWriteTimestamp
}
ctx := context.Background()
r, err := samples.ToRecord()
require.NoError(t, err)
_, err = table.InsertRecord(ctx, r)
require.NoError(t, err)
// No snapshots should have happened yet.
_, err = os.ReadDir(db.snapshotsDir())
require.ErrorIs(t, err, os.ErrNotExist)
for i := range samples {
samples[i].Timestamp = firstWriteTimestamp + 1
}
r, err = samples.ToRecord()
require.NoError(t, err)
// With this new insert, a snapshot should be triggered.
_, err = table.InsertRecord(ctx, r)
require.NoError(t, err)
require.Eventually(t, func() bool {
files, err := os.ReadDir(db.snapshotsDir())
require.NoError(t, err)
if len(files) != 1 {
return false
}
snapshotTx, err = strconv.ParseUint(files[0].Name()[:20], 10, 64)
require.NoError(t, err)
return true
}, 1*time.Second, 10*time.Millisecond, "expected a snapshot on disk")
}()
verifyC, err := New(
WithWAL(),
WithStoragePath(dir),
// Snapshot trigger size is not needed here, we only want to use this
// column store to verify correctness.
)
require.NoError(t, err)
defer verifyC.Close()
verifyDB, err := verifyC.DB(ctx, dbAndTableName)
require.NoError(t, err)
// Truncate all entries from the WAL up to but not including the second
// insert.
require.NoError(t, verifyDB.wal.Truncate(snapshotTx+1))
engine := query.NewEngine(memory.DefaultAllocator, verifyDB.TableProvider())
require.NoError(
t,
engine.ScanTable(dbAndTableName).
Aggregate(
[]*logicalplan.AggregationFunction{logicalplan.Min(logicalplan.Col("timestamp"))},
nil,
).Execute(ctx, func(_ context.Context, r arrow.Record) error {
// This check verifies that the snapshot data (i.e. the first
// write) is correctly loaded.
require.Equal(t, firstWriteTimestamp, r.Column(0).(*array.Int64).Value(0))
return nil
}),
)
require.NoError(
t,
engine.ScanTable(dbAndTableName).
Aggregate(
[]*logicalplan.AggregationFunction{logicalplan.Max(logicalplan.Col("timestamp"))},
nil,
).Execute(ctx, func(_ context.Context, r arrow.Record) error {
// This check verifies that the write that is only represented in
// WAL entries is still replayed (i.e. the second write) in the
// presence of a snapshot.
require.Equal(t, firstWriteTimestamp+1, r.Column(0).(*array.Int64).Value(0))
return nil
}),
)
}
func TestSnapshotIsTakenOnUncompressedInserts(t *testing.T) {
const dbAndTableName = "test"
var (
ctx = context.Background()
dir = t.TempDir()
)
const (
numInserts = 100
expectedUncompressedInsertSize = 2000
)
c, err := New(
WithWAL(),
WithStoragePath(dir),
WithSnapshotTriggerSize(expectedUncompressedInsertSize),
)
require.NoError(t, err)
defer c.Close()
db, err := c.DB(ctx, dbAndTableName)
require.NoError(t, err)
type model struct {
Bytes string `frostdb:",rle_dict"`
}
table, err := NewGenericTable[model](
db, dbAndTableName, memory.NewGoAllocator(),
)
require.NoError(t, err)
defer table.Release()
for i := 0; i < numInserts; i++ {
_, err = table.Write(ctx, model{Bytes: "test"})
require.NoError(t, err)
}
activeBlock := table.ActiveBlock()
require.True(t, activeBlock.Size() == expectedUncompressedInsertSize, "expected uncompressed insert size is wrong. The test should be updated.")
// This will force a compaction of all the inserts we have so far.
require.NoError(t, table.EnsureCompaction())
require.True(
t,
activeBlock.Size() < activeBlock.uncompressedInsertsSize.Load(),
"expected uncompressed inserts to be larger than compressed inserts. Did the compaction run?",
)
require.Zero(t, activeBlock.lastSnapshotSize.Load(), "expected no snapshots to be taken so far")
// These writes should now trigger a snapshot even though the active block
// size is much lower than the uncompressed insert size.
for i := 0; i < 2; i++ {
_, err = table.Write(ctx, model{Bytes: "test"})
require.NoError(t, err)
}
require.Eventually(
t,
func() bool {
return activeBlock.lastSnapshotSize.Load() > 0
},
1*time.Second,
10*time.Millisecond,
"expected snapshot to be taken",
)
}