Repository navigation
Expand file tree
/
Copy pathcommit_test.go
More file actions
543 lines (497 loc) · 14.2 KB
/
Copy pathcommit_test.go
File metadata and controls
543 lines (497 loc) · 14.2 KB
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
package sqliteq
import (
"bytes"
"database/sql"
"database/sql/driver"
"errors"
"runtime"
"strconv"
"sync"
"testing"
"time"
)
// goid returns the calling goroutine's id, parsed from its stack header.
func goid() uint64 {
buf := make([]byte, 64)
buf = buf[:runtime.Stack(buf, false)]
buf = bytes.TrimPrefix(buf, []byte("goroutine "))
id, _ := strconv.ParseUint(string(buf[:bytes.IndexByte(buf, ' ')]), 10, 64)
return id
}
// waitAll fails the test if wg is not done within d.
func waitAll(t *testing.T, wg *sync.WaitGroup, d time.Duration) {
t.Helper()
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(d):
t.Fatalf("Calls did not return within %v", d)
}
}
// runOps is a fake commit: it runs every op without a transaction and sends
// each its own result.
func runOps(ops []*op) {
for _, o := range ops {
ok, err := o.run(nil)
o.done <- result{ok: ok && err == nil}
}
}
func TestBatcherEveryCallGetsItsResult(t *testing.T) {
b := &batcher{commit: runOps}
const goroutines, calls = 50, 200
var wg sync.WaitGroup
for g := 0; g < goroutines; g++ {
wg.Add(1)
go func(g int) {
defer wg.Done()
for i := 0; i < calls; i++ {
want := i%7 != 0
if got := b.do(func(*sql.Tx) (bool, error) { return want, nil }); got != want {
t.Errorf("goroutine %d call %d: got %t, want %t", g, i, got, want)
}
}
}(g)
}
waitAll(t, &wg, time.Minute)
}
func TestBatcherLeaderHandsOff(t *testing.T) {
// Only the leader runs commit, so these need no lock of their own
type round struct {
leader uint64
callers map[uint64]bool // goroutines with an op in the round
}
var (
rounds []round
caller map[uint64]bool // the round being committed
)
b := &batcher{}
b.commit = func(ops []*op) {
caller = map[uint64]bool{}
runOps(ops) // each run records its caller
rounds = append(rounds, round{goid(), caller})
time.Sleep(50 * time.Microsecond)
}
const goroutines, calls = 32, 300
var wg sync.WaitGroup
for g := 0; g < goroutines; g++ {
wg.Add(1)
go func() {
defer wg.Done()
me := goid()
for i := 0; i < calls; i++ {
if !b.do(func(*sql.Tx) (bool, error) { caller[me] = true; return true, nil }) {
t.Errorf("call %d failed", i)
}
}
}()
}
waitAll(t, &wg, time.Minute)
// A goroutine has one call in flight, so a round holding the leader's own
// op starts its turn; a round without it must be the second of that turn
n := 0
for i, r := range rounds {
n += len(r.callers)
if r.callers[r.leader] {
continue
}
if i == 0 || rounds[i-1].leader != r.leader || !rounds[i-1].callers[r.leader] {
t.Fatalf("round %d: goroutine %d led more than its own round plus one", i, r.leader)
}
}
if n != goroutines*calls {
t.Errorf("Rounds held %d calls, want %d", n, goroutines*calls)
}
}
// TestBatcherHandOffDoesNotWait checks that once a leader has ended its turn,
// the next round does not wait for the waiting op it woke: a caller arriving
// first takes the lead and commits that op with its own.
func TestBatcherHandOffDoesNotWait(t *testing.T) {
gate := make(chan struct{})
rounds := 0 // touched by the leader only
b := &batcher{}
b.commit = func(ops []*op) {
if rounds < 2 {
<-gate
}
rounds++
runOps(ops)
}
waitFor := func(what string, cond func() bool) {
t.Helper()
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(time.Millisecond) {
b.mu.Lock()
ok := cond()
b.mu.Unlock()
if ok {
return
}
if time.Now().After(deadline) {
t.Fatalf("Timed out waiting for %s", what)
}
}
}
ok := func(*sql.Tx) (bool, error) { return true, nil }
go b.do(ok) // leads round 1, held at the gate
waitFor("round 1", func() bool { return b.leading && len(b.pending) == 0 })
go b.do(ok) // waits, then commits in round 2
waitFor("a waiter", func() bool { return len(b.pending) == 1 })
gate <- struct{}{}
waitFor("round 2", func() bool { return len(b.pending) == 0 })
// An op whose caller is slow to wake: nothing reads its done
slow := &op{run: ok, done: make(chan result, 2)}
b.mu.Lock()
b.pending = append(b.pending, slow)
b.mu.Unlock()
gate <- struct{}{} // the leader ends its turn with slow waiting
waitFor("the turn to end", func() bool { return len(slow.done) == 1 })
// A caller arriving before slow wakes up
got := make(chan bool, 1)
go func() { got <- b.do(ok) }()
select {
case r := <-got:
if !r {
t.Error("The new caller's write failed")
}
case <-time.After(5 * time.Second):
t.Fatal("The new caller waited for the woken op to take the lead")
}
if r := slow.outcome(); !r {
t.Error("The slow op's write failed")
}
}
// oneRound runs first and, once it leads a round blocked on the file mutex,
// starts rest, so that every call of rest commits in the one round after
// first's. It returns each call's result, first's at index 0.
func oneRound(t *testing.T, f *file, first func() bool, rest []func() bool) []bool {
t.Helper()
waitFor := func(what string, cond func() bool) {
t.Helper()
for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(time.Millisecond) {
f.b.mu.Lock()
ok := cond()
f.b.mu.Unlock()
if ok {
return
}
if time.Now().After(deadline) {
f.mu.Unlock()
t.Fatalf("Timed out waiting for %s", what)
}
}
}
got := make([]bool, 1+len(rest))
var wg sync.WaitGroup
call := func(i int, fn func() bool) {
wg.Add(1)
go func() {
defer wg.Done()
got[i] = fn()
}()
}
before := f.rounds.Load()
f.mu.Lock()
call(0, first)
waitFor("a leader", func() bool { return f.b.leading && len(f.b.pending) == 0 })
for i, fn := range rest {
call(i+1, fn)
}
waitFor("the calls to queue up", func() bool { return len(f.b.pending) == len(rest) })
f.mu.Unlock()
waitAll(t, &wg, 10*time.Second)
if n := f.rounds.Load() - before; n != 2 {
t.Errorf("Expected 2 rounds, got %d", n)
}
return got
}
// TestGroupCommitOneBadCall checks that an add that fails inside a shared
// round fails alone.
func TestGroupCommitOneBadCall(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
add := func() bool { return q.Enqueue([]byte("x")) }
rest := []func() bool{func() bool { return q.Enqueue(nil) }}
for i := 0; i < 63; i++ {
rest = append(rest, add)
}
got := oneRound(t, q.f, add, rest)
if got[1] {
t.Error("Enqueue(nil) succeeded")
}
for i, ok := range got {
if i != 1 && !ok {
t.Errorf("Enqueue %d failed", i)
}
}
if n := q.Len(); n != 64 {
t.Errorf("Expected 64 pending items, got %d", n)
}
}
// TestGroupAckAfterFailedRound shares one round between 32 good acks, 4 acks
// of ids no row has, and a failing add, so the round fails and falls back.
func TestGroupAckAfterFailedRound(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
enqueueN(t, q, 32)
items, ackIDs := make([]any, 32), make([]string, 32)
if n, _, err := q.DequeueBatchWithAckIds(items, ackIDs); err != nil || n != 32 {
t.Fatalf("Claimed %d, %v; want 32", n, err)
}
ack := func(id string) func() bool { return func() bool { return q.Acknowledge(id) } }
rest := []func() bool{}
for _, id := range ackIDs[1:] {
rest = append(rest, ack(id))
}
for i := 0; i < 4; i++ {
rest = append(rest, ack(strconv.Itoa(1_000_000+i))) // numeric, so they reach the round
}
rest = append(rest, func() bool { return q.Enqueue(nil) })
got := oneRound(t, q.f, ack(ackIDs[0]), rest)
for i := 0; i < 32; i++ {
if !got[i] {
t.Errorf("Acknowledge(%s) failed", ackIDs[i])
}
}
for i := 32; i < len(got); i++ {
if got[i] {
t.Errorf("Call %d succeeded, want false", i)
}
}
if n := countRows(t, q.f.db, "1"); n != 0 {
t.Errorf("Expected no rows left, got %d", n)
}
}
// TestCommitRoundFallsBackPerOp runs a round whose second op errors: the
// grouped transaction rolls back, and each op then commits alone.
func TestCommitRoundFallsBackPerOp(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
add := func(tx *sql.Tx) (bool, error) {
_, err := tx.Stmt(q.insert).Exec([]byte("x"), time.Now(), time.Now(), nil)
return err == nil, err
}
bad := func(*sql.Tx) (bool, error) { return false, errors.New("bad op") }
ops := []*op{
{run: add, done: make(chan result, 1)},
{run: bad, done: make(chan result, 1)},
{run: add, done: make(chan result, 1)},
}
q.f.commitRound(ops)
for i, want := range []bool{true, false, true} {
select {
case r := <-ops[i].done:
if r.ok != want || r.lead {
t.Errorf("op %d: got %+v, want ok=%t", i, r, want)
}
default:
t.Errorf("op %d got no result", i)
}
if len(ops[i].done) != 0 {
t.Errorf("op %d got more than one result", i)
}
}
if n := q.Len(); n != 2 {
t.Errorf("Expected 2 pending items, got %d", n)
}
}
// TestCommitRoundGroupedResults runs a round that commits: each op gets its
// own outcome, from one shared transaction.
func TestCommitRoundGroupedResults(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
want := []bool{true, false, true, true}
txs := make([]*sql.Tx, len(want))
ops := make([]*op, len(want))
for i, ok := range want {
ops[i] = &op{
run: func(tx *sql.Tx) (bool, error) {
txs[i] = tx
return ok, nil
},
done: make(chan result, 2),
}
}
q.f.commitRound(ops)
for i, w := range want {
if n := len(ops[i].done); n != 1 {
t.Errorf("op %d got %d results, want 1", i, n)
continue
}
if r := <-ops[i].done; r.ok != w || r.lead {
t.Errorf("op %d: got %+v, want ok=%t", i, r, w)
}
}
for i, tx := range txs {
if tx == nil || tx != txs[0] {
t.Errorf("op %d did not run in the round's one transaction", i)
}
}
}
// panicValuer is an item whose conversion for the driver panics.
type panicValuer struct{}
func (panicValuer) Value() (driver.Value, error) { panic("panicValuer") }
// TestEnqueuePanickingItem checks that an item panicking in its conversion
// panics in its own caller and leaves the file's group commit working.
func TestEnqueuePanickingItem(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
func() {
defer func() {
if recover() == nil {
t.Error("Enqueue of a panicking item did not panic")
}
}()
q.Enqueue(panicValuer{})
}()
done := make(chan error, 1)
go func() {
if !q.Enqueue([]byte("x")) {
done <- errors.New("Enqueue failed")
return
}
_, ok, ackID := q.DequeueWithAckId()
if !ok {
done <- errors.New("DequeueWithAckId failed")
return
}
if !q.Acknowledge(ackID) {
done <- errors.New("Acknowledge failed")
return
}
done <- nil
}()
select {
case err := <-done:
if err != nil {
t.Error(err)
}
case <-time.After(10 * time.Second):
t.Fatal("Writes after the panic did not return")
}
}
// TestCommitRoundOneOpAutocommits checks that a round of one op runs without
// a transaction, and a round of more shares one.
func TestCommitRoundOneOpAutocommits(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
var txs []*sql.Tx
record := func(tx *sql.Tx) (bool, error) {
txs = append(txs, tx)
return true, nil
}
newOp := func() *op { return &op{run: record, done: make(chan result, 1)} }
q.f.commitRound([]*op{newOp()})
q.f.commitRound([]*op{newOp(), newOp()})
if len(txs) != 3 {
t.Fatalf("Expected 3 runs, got %d", len(txs))
}
if txs[0] != nil {
t.Error("A round of one op ran in a transaction")
}
if txs[1] == nil || txs[1] != txs[2] {
t.Error("A round of two ops did not share one transaction")
}
}
// TestGroupCommitBatches checks that writes queued behind a running round,
// adds and acks alike, all commit in the one round after it.
func TestGroupCommitBatches(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
enqueueN(t, q, 16)
items, ackIDs := make([]any, 16), make([]string, 16)
if n, _, err := q.DequeueBatchWithAckIds(items, ackIDs); err != nil || n != 16 {
t.Fatalf("Claimed %d, %v; want 16", n, err)
}
add := func() bool { return q.Enqueue([]byte("x")) }
rest := []func() bool{}
for i := 0; i < 15; i++ {
rest = append(rest, add)
}
for _, id := range ackIDs {
rest = append(rest, func() bool { return q.Acknowledge(id) })
}
// oneRound fails the test unless exactly 2 rounds ran
for i, ok := range oneRound(t, q.f, add, rest) {
if !ok {
t.Errorf("Call %d failed", i)
}
}
if n := countRows(t, q.f.db, "1"); n != 16 {
t.Errorf("Expected 16 rows (the adds), got %d", n)
}
if n := q.Len(); n != 16 {
t.Errorf("Expected 16 pending items, got %d", n)
}
}
// TestGroupCommitAfterClose closes the store under running writers: every
// call still returns.
func TestGroupCommitAfterClose(t *testing.T) {
q, qs := openQueue(t)
var wg sync.WaitGroup
for g := 0; g < 16; g++ {
wg.Add(1)
go func() {
defer wg.Done()
for q.Enqueue([]byte("x")) {
q.Acknowledge("1")
}
}()
}
time.Sleep(20 * time.Millisecond)
if err := qs.Close(); err != nil {
t.Errorf("Close failed: %v", err)
}
waitAll(t, &wg, 10*time.Second)
}
// Finishes that share a round write their outcomes in its transaction,
// and again each in its own when a bad call fails the round.
func TestGroupFinishOutcomes(t *testing.T) {
for _, fail := range []bool{false, true} {
t.Run(map[bool]string{false: "shared", true: "fallback"}[fail], func(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
for _, id := range []string{"a", "b", "c", "d"} {
q.Enqueue(job(id))
}
items, acks := make([]any, 4), make([]string, 4)
if n, _, err := q.DequeueBatchWithAckIds(items, acks); err != nil || n != 4 {
t.Fatalf("got %d %v", n, err)
}
rest := []func() bool{
func() bool { return q.Reject(acks[1], "r") },
func() bool { return q.AcknowledgeResult(acks[2], []byte(`1`)) },
func() bool { return q.AcknowledgeCancelled(acks[3], "c") },
}
if fail {
rest = append(rest, func() bool { return q.Enqueue(nil) })
}
got := oneRound(t, q.f, func() bool { return q.Acknowledge(acks[0]) }, rest)
for i, ok := range got[:4] {
if !ok {
t.Errorf("finish %d failed", i)
}
}
want := map[string]string{"a": "completed||", "b": "failed|r|", "c": "completed||1", "d": "cancelled|c|"}
rows, err := q.f.db.Query("SELECT job_id, state, COALESCE(error, ''), COALESCE(CAST(result AS TEXT), '') FROM " + q.jobs)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
n := 0
for rows.Next() {
var id, state, e, r string
rows.Scan(&id, &state, &e, &r)
if g := state + "|" + e + "|" + r; g != want[id] {
t.Errorf("%s: got %s, want %s", id, g, want[id])
}
n++
}
if n != 4 {
t.Errorf("Expected 4 records, got %d", n)
}
})
}
}