-
Notifications
You must be signed in to change notification settings - Fork 373
Expand file tree
/
Copy pathpostgres_shared_test.go
More file actions
2100 lines (1768 loc) · 63.8 KB
/
postgres_shared_test.go
File metadata and controls
2100 lines (1768 loc) · 63.8 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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//go:build ci && docker
package postgres
import (
"context"
"fmt"
"math/rand"
"strings"
"sync"
"testing"
"time"
sq "github.com/Masterminds/squirrel"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
"golang.org/x/sync/errgroup"
"github.com/authzed/spicedb/internal/datastore/common"
pgcommon "github.com/authzed/spicedb/internal/datastore/postgres/common"
"github.com/authzed/spicedb/internal/datastore/postgres/schema"
pgversion "github.com/authzed/spicedb/internal/datastore/postgres/version"
"github.com/authzed/spicedb/internal/datastore/proxy"
"github.com/authzed/spicedb/internal/datastore/proxy/indexcheck"
"github.com/authzed/spicedb/internal/testfixtures"
testdatastore "github.com/authzed/spicedb/internal/testserver/datastore"
"github.com/authzed/spicedb/pkg/datastore"
"github.com/authzed/spicedb/pkg/datastore/options"
"github.com/authzed/spicedb/pkg/datastore/queryshape"
"github.com/authzed/spicedb/pkg/datastore/test"
"github.com/authzed/spicedb/pkg/migrate"
"github.com/authzed/spicedb/pkg/namespace"
"github.com/authzed/spicedb/pkg/tuple"
)
const pgSerializationFailure = "40001"
const (
veryLargeGCInterval = 90000 * time.Second
)
var pgFactory = test.NewTesterFactory(&pgconn.PgError{Code: pgSerializationFailure})
type postgresTestConfig struct {
targetMigration string
migrationPhase string
pgVersion string
pgbouncer bool
}
// the global OTel tracer is used everywhere, so we synchronize tests over a global test tracer
var (
otelMutex = sync.Mutex{}
testTraceProvider *trace.TracerProvider
)
func init() {
testTraceProvider = trace.NewTracerProvider(
trace.WithSampler(trace.AlwaysSample()),
)
otel.SetTracerProvider(testTraceProvider)
}
func testPostgresDatastore(t *testing.T, config postgresTestConfig) {
pgbouncerStr := ""
if config.pgbouncer {
pgbouncerStr = "pgbouncer-"
}
t.Run(fmt.Sprintf("%spostgres-%s-%s-%s-gc", pgbouncerStr, config.pgVersion, config.targetMigration, config.migrationPhase), func(t *testing.T) {
b := testdatastore.RunPostgresForTesting(t, "", config.targetMigration, config.pgVersion, config.pgbouncer)
ctx := context.Background()
// NOTE: gc tests take exclusive locks, so they are run under non-parallel.
test.OnlyGCTests(t, test.DatastoreTesterFunc(func(_ testing.TB, revisionQuantization, gcInterval, gcWindow time.Duration, watchBufferLength uint16) (datastore.Datastore, error) {
ds := b.NewDatastore(t, func(engine, uri string) datastore.Datastore {
ds, err := newPostgresDatastore(ctx, uri, primaryInstanceID,
RevisionQuantization(revisionQuantization),
GCWindow(gcWindow),
GCInterval(gcInterval),
WatchBufferLength(watchBufferLength),
DebugAnalyzeBeforeStatistics(),
MigrationPhase(config.migrationPhase),
WithRevisionHeartbeat(false), // heartbeat revision messes with tests that assert over revisions
)
require.NoError(t, err)
return ds
})
return ds, nil
}), false)
t.Run("TestLocking", createMultiDatastoreTest(
b,
LockingTest,
RevisionQuantization(0),
GCWindow(1000*time.Second),
GCInterval(veryLargeGCInterval),
WatchBufferLength(50),
MigrationPhase(config.migrationPhase),
ReadConnsMinOpen(10),
ReadConnsMaxOpen(10),
WriteConnsMinOpen(10),
WriteConnsMaxOpen(10),
))
})
t.Run(fmt.Sprintf("%spostgres-%s-%s-%s", pgbouncerStr, config.pgVersion, config.targetMigration, config.migrationPhase), func(t *testing.T) {
b := testdatastore.RunPostgresForTesting(t, "", config.targetMigration, config.pgVersion, config.pgbouncer)
ctx := context.Background()
test.AllWithExceptions(t, pgFactory.NewTester(test.DatastoreTesterFunc(func(_ testing.TB, revisionQuantization, _, gcWindow time.Duration, watchBufferLength uint16) (datastore.Datastore, error) {
ds := b.NewDatastore(t, func(engine, uri string) datastore.Datastore {
ds, err := newPostgresDatastore(ctx, uri, primaryInstanceID,
RevisionQuantization(revisionQuantization),
GCWindow(gcWindow),
GCInterval(veryLargeGCInterval),
WatchBufferLength(watchBufferLength),
DebugAnalyzeBeforeStatistics(),
MigrationPhase(config.migrationPhase),
WithRevisionHeartbeat(false), // heartbeat revision messes with tests that assert over revisions
)
require.NoError(t, err)
return indexcheck.WrapWithIndexCheckingDatastoreProxyIfApplicable(ds)
})
return ds, nil
})), test.WithCategories(test.GCCategory), false)
t.Run("TransactionTimestamps", createDatastoreTest(
b,
TransactionTimestampsTest,
RevisionQuantization(0),
GCWindow(1*time.Millisecond),
GCInterval(veryLargeGCInterval),
WatchBufferLength(1),
MigrationPhase(config.migrationPhase),
))
t.Run("QuantizedRevisions", func(t *testing.T) {
QuantizedRevisionTest(t, b)
})
t.Run("OverlappingRevision", func(t *testing.T) {
OverlappingRevisionTest(t, b)
})
t.Run("WatchNotEnabled", func(t *testing.T) {
WatchNotEnabledTest(t, b, config.pgVersion)
})
t.Run("GCQueriesServedByExpectedIndexes", func(t *testing.T) {
GCQueriesServedByExpectedIndexes(t, b, config.pgVersion)
})
if config.migrationPhase == "" {
t.Run("RevisionInversion", createDatastoreTest(
b,
RevisionInversionTest,
RevisionQuantization(0),
GCWindow(1*time.Millisecond),
GCInterval(veryLargeGCInterval),
WatchBufferLength(1),
MigrationPhase(config.migrationPhase),
))
t.Run("ConcurrentRevisionHead", createDatastoreTest(
b,
ConcurrentRevisionHeadTest,
RevisionQuantization(0),
GCWindow(1*time.Millisecond),
GCInterval(veryLargeGCInterval),
WatchBufferLength(1),
MigrationPhase(config.migrationPhase),
))
t.Run("ConcurrentRevisionWatch", createDatastoreTest(
b,
ConcurrentRevisionWatchTest,
RevisionQuantization(0),
GCWindow(1*time.Millisecond),
GCInterval(veryLargeGCInterval),
WatchBufferLength(50),
MigrationPhase(config.migrationPhase),
WithRevisionHeartbeat(false),
))
t.Run("OverlappingRevisionWatch", createDatastoreTest(
b,
OverlappingRevisionWatchTest,
RevisionQuantization(0),
GCWindow(1*time.Millisecond),
GCInterval(veryLargeGCInterval),
WatchBufferLength(50),
MigrationPhase(config.migrationPhase),
))
t.Run("RepairTransactionsTest", createDatastoreTest(
b,
RepairTransactionsTest,
RevisionQuantization(0),
GCWindow(1*time.Millisecond),
GCInterval(veryLargeGCInterval),
WatchBufferLength(1),
MigrationPhase(config.migrationPhase),
))
t.Run("TestNullCaveatWatch", createDatastoreTest(
b,
NullCaveatWatchTest,
RevisionQuantization(0),
GCWindow(1*time.Millisecond),
GCInterval(veryLargeGCInterval),
WatchBufferLength(50),
MigrationPhase(config.migrationPhase),
))
t.Run("TestRevisionTimestampAndTransactionID", createDatastoreTest(
b,
RevisionTimestampAndTransactionIDTest,
RevisionQuantization(0),
GCWindow(1*time.Millisecond),
GCInterval(veryLargeGCInterval),
WatchBufferLength(50),
MigrationPhase(config.migrationPhase),
))
t.Run("TestContinuousCheckpointTest", createDatastoreTest(
b,
ContinuousCheckpointTest,
RevisionQuantization(100*time.Millisecond),
GCInterval(veryLargeGCInterval),
WatchBufferLength(50),
MigrationPhase(config.migrationPhase),
WithRevisionHeartbeat(true),
))
t.Run("TestSerializationError", createDatastoreTest(
b,
SerializationErrorTest,
RevisionQuantization(0),
GCWindow(1*time.Millisecond),
GCInterval(veryLargeGCInterval),
WatchBufferLength(50),
MigrationPhase(config.migrationPhase),
))
t.Run("ReadWriteTxReturnsOptionalRevisionFields", createDatastoreTest(
b,
ReadWriteTxReturnsOptionalRevisionFields,
RevisionQuantization(0),
GCWindow(1*time.Millisecond),
GCInterval(veryLargeGCInterval),
WatchBufferLength(50),
MigrationPhase(config.migrationPhase),
))
t.Run("TestStrictReadMode", createReplicaDatastoreTest(
b,
StrictReadModeTest,
RevisionQuantization(0),
GCWindow(1000*time.Second),
GCInterval(veryLargeGCInterval),
WatchBufferLength(50),
MigrationPhase(config.migrationPhase),
))
t.Run("TestStrictReadModeFallback", createReplicaDatastoreTest(
b,
StrictReadModeFallbackTest,
RevisionQuantization(0),
GCWindow(1000*time.Second),
GCInterval(veryLargeGCInterval),
WatchBufferLength(50),
MigrationPhase(config.migrationPhase),
))
}
t.Run("OTelTracing", createDatastoreTest(
b,
OTelTracingTest,
RevisionQuantization(0),
GCWindow(1*time.Millisecond),
GCInterval(veryLargeGCInterval),
WatchBufferLength(1),
MigrationPhase(config.migrationPhase),
))
t.Run("ExceedInsertQuerySizeTest", createDatastoreTest(
b,
ExceedInsertQuerySizeTest,
RevisionQuantization(0),
GCWindow(1*time.Millisecond),
GCInterval(veryLargeGCInterval),
WatchBufferLength(1),
MigrationPhase(config.migrationPhase),
))
})
}
func testPostgresDatastoreWithoutCommitTimestamps(t *testing.T, config postgresTestConfig) {
pgVersion := config.pgVersion
enablePgbouncer := config.pgbouncer
t.Run(fmt.Sprintf("postgres-%s", pgVersion), func(t *testing.T) {
ctx := context.Background()
b := testdatastore.RunPostgresForTestingWithCommitTimestamps(t, "", "head", false, pgVersion, enablePgbouncer)
// NOTE: watch API requires the commit timestamps, so we skip those tests here.
// NOTE: gc tests take exclusive locks, so they are run under non-parallel.
test.AllWithExceptions(t, pgFactory.NewTester(test.DatastoreTesterFunc(func(_ testing.TB, revisionQuantization, _, gcWindow time.Duration, watchBufferLength uint16) (datastore.Datastore, error) {
ds := b.NewDatastore(t, func(engine, uri string) datastore.Datastore {
ds, err := newPostgresDatastore(ctx, uri, primaryInstanceID,
RevisionQuantization(revisionQuantization),
GCWindow(gcWindow),
GCInterval(veryLargeGCInterval),
WatchBufferLength(watchBufferLength),
DebugAnalyzeBeforeStatistics(),
WithRevisionHeartbeat(false),
)
require.NoError(t, err)
return ds
})
return ds, nil
})), test.WithCategories(test.WatchCategory, test.GCCategory), false)
})
t.Run(fmt.Sprintf("postgres-%s-gc", pgVersion), func(t *testing.T) {
ctx := context.Background()
b := testdatastore.RunPostgresForTestingWithCommitTimestamps(t, "", "head", false, pgVersion, enablePgbouncer)
test.OnlyGCTests(t, test.DatastoreTesterFunc(func(_ testing.TB, revisionQuantization, gcInterval, gcWindow time.Duration, watchBufferLength uint16) (datastore.Datastore, error) {
ds := b.NewDatastore(t, func(engine, uri string) datastore.Datastore {
ds, err := newPostgresDatastore(ctx, uri, primaryInstanceID,
RevisionQuantization(revisionQuantization),
GCWindow(gcWindow),
GCInterval(gcInterval),
WatchBufferLength(watchBufferLength),
DebugAnalyzeBeforeStatistics(),
WithRevisionHeartbeat(false),
)
require.NoError(t, err)
return ds
})
return ds, nil
}), false)
})
}
type datastoreTestFunc func(t *testing.T, ds datastore.Datastore)
func createDatastoreTest(b testdatastore.RunningEngineForTest, tf datastoreTestFunc, options ...Option) func(*testing.T) {
return func(t *testing.T) {
t.Helper()
ctx := context.Background()
ds := b.NewDatastore(t, func(engine, uri string) datastore.Datastore {
ds, err := newPostgresDatastore(ctx, uri, primaryInstanceID, options...)
require.NoError(t, err)
return ds
})
defer ds.Close()
tf(t, ds)
}
}
func createReplicaDatastoreTest(b testdatastore.RunningEngineForTest, tf multiDatastoreTestFunc, options ...Option) func(*testing.T) {
return func(t *testing.T) {
ctx := context.Background()
var replicaDS datastore.Datastore
ds := b.NewDatastore(t, func(engine, uri string) datastore.Datastore {
ds, err := newPostgresDatastore(ctx, uri, primaryInstanceID, options...)
require.NoError(t, err)
ds2, err := newPostgresDatastore(ctx, uri, 42, append(options, ReadStrictMode(true))...)
require.NoError(t, err)
replicaDS = ds2
return ds
})
defer ds.Close()
tf(t, ds, replicaDS)
}
}
type multiDatastoreTestFunc func(t *testing.T, ds1 datastore.Datastore, ds2 datastore.Datastore)
func createMultiDatastoreTest(b testdatastore.RunningEngineForTest, tf multiDatastoreTestFunc, options ...Option) func(*testing.T) {
return func(t *testing.T) {
ctx := context.Background()
var secondDS datastore.Datastore
ds := b.NewDatastore(t, func(engine, uri string) datastore.Datastore {
ds, err := newPostgresDatastore(ctx, uri, primaryInstanceID, options...)
require.NoError(t, err)
ds2, err := newPostgresDatastore(ctx, uri, primaryInstanceID, options...)
require.NoError(t, err)
secondDS = ds2
return ds
})
defer ds.Close()
tf(t, ds, secondDS)
}
}
func SerializationErrorTest(t *testing.T, ds datastore.Datastore) {
require := require.New(t)
ctx := context.Background()
r, err := ds.ReadyState(ctx)
require.NoError(err)
require.True(r.IsReady)
_, err = ds.ReadWriteTx(ctx, func(ctx context.Context, rwt datastore.ReadWriteTransaction) error {
updates := []tuple.RelationshipUpdate{
tuple.Create(tuple.MustParse("resource:resource#reader@user:user#...")),
}
rwt.(*pgReadWriteTXN).tx = txWithSerializationError{rwt.(*pgReadWriteTXN).tx}
return rwt.WriteRelationships(ctx, updates)
}, options.WithDisableRetries(true) /* ensures the error is returned immediately */)
require.Contains(err.Error(), "unable to write relationships due to a serialization error")
}
func ReadWriteTxReturnsOptionalRevisionFields(t *testing.T, ds datastore.Datastore) {
require := require.New(t)
ctx := context.Background()
r, err := ds.ReadyState(ctx)
require.NoError(err)
require.True(r.IsReady)
rev, err := ds.ReadWriteTx(ctx, func(ctx context.Context, rwt datastore.ReadWriteTransaction) error {
updates := []tuple.RelationshipUpdate{
tuple.Create(tuple.MustParse("resource:resource#reader@user:user#...")),
}
return rwt.WriteRelationships(ctx, updates)
}, options.WithDisableRetries(true) /* ensures the error is returned immediately */)
require.NoError(err)
pgRev, ok := rev.(postgresRevision)
require.True(ok)
require.Positive(pgRev.optionalInexactNanosTimestamp, "revision timestamp should be set")
require.True(pgRev.optionalTxID.Valid, "revision txid be set")
}
type txWithSerializationError struct {
pgx.Tx
}
func (txwse txWithSerializationError) Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error) {
return pgconn.CommandTag{}, &pgconn.PgError{
Code: pgSerializationFailure,
Message: "fake serialization error",
}
}
func GarbageCollectionTest(t *testing.T, ds datastore.Datastore) {
require := require.New(t)
ctx := context.Background()
r, err := ds.ReadyState(ctx)
require.NoError(err)
require.True(r.IsReady)
firstWrite, err := ds.ReadWriteTx(ctx, func(ctx context.Context, rwt datastore.ReadWriteTransaction) error {
// Write basic namespaces.
return rwt.LegacyWriteNamespaces(ctx, namespace.Namespace(
"resource",
namespace.MustRelation("reader", nil),
), namespace.Namespace("user"))
})
require.NoError(err)
// Run GC at the transaction and ensure no relationships are removed.
pds := ds.(*pgDatastore)
pgg, err := pds.BuildGarbageCollector(ctx)
require.NoError(err)
defer pgg.Close()
// Nothing to GC
removed, err := pgg.DeleteBeforeTx(ctx, firstWrite)
require.NoError(err)
require.Zero(removed.Relationships)
require.Zero(removed.Namespaces)
// Replace the namespace with a new one.
updateTwoNamespaces, err := ds.ReadWriteTx(ctx, func(ctx context.Context, rwt datastore.ReadWriteTransaction) error {
return rwt.LegacyWriteNamespaces(
ctx,
namespace.Namespace(
"resource",
namespace.MustRelation("reader", nil),
namespace.MustRelation("unused", nil),
),
namespace.Namespace("user"),
)
})
require.NoError(err)
// Run GC to remove the old transaction
removed, err = pgg.DeleteBeforeTx(ctx, updateTwoNamespaces)
require.NoError(err)
require.Zero(removed.Relationships)
require.Equal(int64(1), removed.Transactions) // firstWrite
require.Equal(int64(2), removed.Namespaces) // resource, user
// Write a relationship.
rel := tuple.MustParse("resource:someresource#reader@user:someuser#...")
wroteOneRelationship, err := common.WriteRelationships(ctx, ds, tuple.UpdateOperationCreate, rel)
require.NoError(err)
// Run GC at the transaction and ensure no relationships are removed, but 1 transaction (the previous write namespace) is.
removed, err = pgg.DeleteBeforeTx(ctx, wroteOneRelationship)
require.NoError(err)
require.Zero(removed.Relationships)
require.Equal(int64(1), removed.Transactions) // updateTwoNamespaces
require.Zero(removed.Namespaces)
// Run GC again and ensure there are no changes.
removed, err = pgg.DeleteBeforeTx(ctx, wroteOneRelationship)
require.NoError(err)
require.Zero(removed.Relationships)
require.Zero(removed.Transactions)
require.Zero(removed.Namespaces)
// Ensure the relationship is still present.
tRequire := testfixtures.RelationshipChecker{Require: require, DS: ds}
tRequire.RelationshipExists(ctx, rel, wroteOneRelationship)
// Overwrite the relationship by changing its caveat.
rel = tuple.MustWithCaveat(rel, "somecaveat")
relOverwrittenAt, err := common.WriteRelationships(ctx, ds, tuple.UpdateOperationTouch, rel)
require.NoError(err)
// Run GC, which won't clean anything because we're dropping the write transaction only
removed, err = pgg.DeleteBeforeTx(ctx, relOverwrittenAt)
require.NoError(err)
require.Equal(int64(1), removed.Relationships) // wroteOneRelationship
require.Equal(int64(1), removed.Transactions) // wroteOneRelationship
require.Zero(removed.Namespaces)
// Run GC again and ensure there are no changes.
removed, err = pgg.DeleteBeforeTx(ctx, relOverwrittenAt)
require.NoError(err)
require.Zero(removed.Relationships)
require.Zero(removed.Transactions)
require.Zero(removed.Namespaces)
// Ensure the relationship is still present.
tRequire.RelationshipExists(ctx, rel, relOverwrittenAt)
// Delete the relationship.
relDeletedAt, err := common.WriteRelationships(ctx, ds, tuple.UpdateOperationDelete, rel)
require.NoError(err)
// Ensure the relationship is gone.
tRequire.NoRelationshipExists(ctx, rel, relDeletedAt)
// Run GC, which will now drop the overwrite transaction only and the first rel revision
removed, err = pgg.DeleteBeforeTx(ctx, relDeletedAt)
require.NoError(err)
require.Equal(int64(1), removed.Relationships)
require.Equal(int64(1), removed.Transactions) // relOverwrittenAt
require.Zero(removed.Namespaces)
// Run GC again and ensure there are no changes.
removed, err = pgg.DeleteBeforeTx(ctx, relDeletedAt)
require.NoError(err)
require.Zero(removed.Relationships)
require.Zero(removed.Transactions)
require.Zero(removed.Namespaces)
// Write a the relationship a few times.
var relLastWriteAt datastore.Revision
for i := 0; i < 3; i++ {
rel = tuple.MustWithCaveat(rel, fmt.Sprintf("somecaveat%d", i))
var err error
relLastWriteAt, err = common.WriteRelationships(ctx, ds, tuple.UpdateOperationTouch, rel)
require.NoError(err)
}
// Run GC at the transaction and ensure the older copies of the relationships are removed,
// as well as the 2 older write transactions and the older delete transaction.
removed, err = pgg.DeleteBeforeTx(ctx, relLastWriteAt)
require.NoError(err)
require.Equal(int64(2), removed.Relationships) // delete, old1
require.Equal(int64(3), removed.Transactions) // removed, write1, write2
require.Zero(removed.Namespaces)
// Ensure the relationship is still present.
tRequire.RelationshipExists(ctx, rel, relLastWriteAt)
// Inject a transaction to clean up the last write
lastRev, err := pds.ReadWriteTx(ctx, func(ctx context.Context, rwt datastore.ReadWriteTransaction) error {
return nil
})
require.NoError(err)
// Run GC to clean up the last write
removed, err = pgg.DeleteBeforeTx(ctx, lastRev)
require.NoError(err)
require.Zero(removed.Relationships) // write3
require.Equal(int64(1), removed.Transactions) // write3
require.Zero(removed.Namespaces)
}
func TransactionTimestampsTest(t *testing.T, ds datastore.Datastore) {
require := require.New(t)
ctx := context.Background()
r, err := ds.ReadyState(ctx)
require.NoError(err)
require.True(r.IsReady)
// Setting db default time zone to before UTC
pgd := ds.(*pgDatastore)
pgg, err := pgd.BuildGarbageCollector(ctx)
require.NoError(err)
defer pgg.Close()
_, err = pgd.writePool.Exec(ctx, "SET TIME ZONE 'America/New_York';")
require.NoError(err)
// Get timestamp in UTC as reference
startTimeUTC, err := pgg.Now(ctx)
require.NoError(err)
// Transaction timestamp should not be stored in system time zone
tx, err := pgd.writePool.Begin(ctx)
require.NoError(err)
txXID, _, newTS, err := createNewTransaction(ctx, tx, nil)
require.NoError(err)
err = tx.Commit(ctx)
require.NoError(err)
var readTS time.Time
sql, args, err := psql.Select("timestamp").From(schema.TableTransaction).Where(sq.Eq{"xid": txXID}).ToSql()
require.NoError(err)
err = pgd.readPool.QueryRow(ctx, sql, args...).Scan(&readTS)
require.NoError(err)
// Transaction timestamp will be before the reference time if it was stored
// in the default time zone and reinterpreted
require.True(startTimeUTC.Before(readTS))
require.Equal(readTS, newTS)
}
func GarbageCollectionByTimeTest(t *testing.T, ds datastore.Datastore) {
require := require.New(t)
ctx := context.Background()
r, err := ds.ReadyState(ctx)
require.NoError(err)
require.True(r.IsReady)
// Write basic namespaces.
_, err = ds.ReadWriteTx(ctx, func(ctx context.Context, rwt datastore.ReadWriteTransaction) error {
return rwt.LegacyWriteNamespaces(ctx, namespace.Namespace(
"resource",
namespace.MustRelation("reader", nil),
), namespace.Namespace("user"))
})
require.NoError(err)
pds := ds.(*pgDatastore)
pgg, err := pds.BuildGarbageCollector(ctx)
require.NoError(err)
defer pgg.Close()
// Sleep 1ms to ensure GC will delete the previous transaction.
time.Sleep(1 * time.Millisecond)
// Write a relationship.
rel := tuple.MustParse("resource:someresource#reader@user:someuser#...")
relLastWriteAt, err := common.WriteRelationships(ctx, ds, tuple.UpdateOperationCreate, rel)
require.NoError(err)
// Run GC and ensure only transactions were removed.
afterWrite, err := pgg.Now(ctx)
require.NoError(err)
afterWriteTx, err := pgg.TxIDBefore(ctx, afterWrite)
require.NoError(err)
removed, err := pgg.DeleteBeforeTx(ctx, afterWriteTx)
require.NoError(err)
require.Zero(removed.Relationships)
require.Positive(removed.Transactions)
require.Zero(removed.Namespaces)
// Ensure the relationship is still present.
tRequire := testfixtures.RelationshipChecker{Require: require, DS: ds}
tRequire.RelationshipExists(ctx, rel, relLastWriteAt)
// Sleep 1ms to ensure GC will delete the previous write.
time.Sleep(1 * time.Millisecond)
// Delete the relationship.
relDeletedAt, err := common.WriteRelationships(ctx, ds, tuple.UpdateOperationDelete, rel)
require.NoError(err)
// Inject a revision to sweep up the last revision
_, err = pds.ReadWriteTx(ctx, func(ctx context.Context, rwt datastore.ReadWriteTransaction) error {
return nil
})
require.NoError(err)
// Run GC and ensure the relationship is not removed.
afterDelete, err := pgg.Now(ctx)
require.NoError(err)
afterDeleteTx, err := pgg.TxIDBefore(ctx, afterDelete)
require.NoError(err)
removed, err = pgg.DeleteBeforeTx(ctx, afterDeleteTx)
require.NoError(err)
require.Equal(int64(1), removed.Relationships)
require.Equal(int64(2), removed.Transactions) // relDeletedAt, injected
require.Zero(removed.Namespaces)
// Ensure the relationship is still not present.
tRequire.NoRelationshipExists(ctx, rel, relDeletedAt)
}
const chunkRelationshipCount = 2000
func ChunkedGarbageCollectionTest(t *testing.T, ds datastore.Datastore) {
require := require.New(t)
ctx := context.Background()
r, err := ds.ReadyState(ctx)
require.NoError(err)
require.True(r.IsReady)
// Write basic namespaces.
_, err = ds.ReadWriteTx(ctx, func(ctx context.Context, rwt datastore.ReadWriteTransaction) error {
return rwt.LegacyWriteNamespaces(ctx, namespace.Namespace(
"resource",
namespace.MustRelation("reader", nil),
), namespace.Namespace("user"))
})
require.NoError(err)
pds := ds.(*pgDatastore)
pgg, err := pds.BuildGarbageCollector(ctx)
require.NoError(err)
defer pgg.Close()
// Prepare relationships to write.
var rels []tuple.Relationship
for i := 0; i < chunkRelationshipCount; i++ {
rel := tuple.MustParse(fmt.Sprintf("resource:resource-%d#reader@user:someuser#...", i))
rels = append(rels, rel)
}
// Write a large number of relationships.
writtenAt, err := common.WriteRelationships(ctx, ds, tuple.UpdateOperationCreate, rels...)
require.NoError(err)
// Ensure the relationships were written.
tRequire := testfixtures.RelationshipChecker{Require: require, DS: ds}
for _, rel := range rels {
tRequire.RelationshipExists(ctx, rel, writtenAt)
}
// Run GC and ensure only transactions were removed.
afterWrite, err := pgg.Now(ctx)
require.NoError(err)
afterWriteTx, err := pgg.TxIDBefore(ctx, afterWrite)
require.NoError(err)
removed, err := pgg.DeleteBeforeTx(ctx, afterWriteTx)
require.NoError(err)
require.Zero(removed.Relationships)
require.Positive(removed.Transactions)
require.Zero(removed.Namespaces)
// Sleep to ensure the relationships will GC.
time.Sleep(1 * time.Millisecond)
// Delete all the relationships.
deletedAt, err := common.WriteRelationships(ctx, ds, tuple.UpdateOperationDelete, rels...)
require.NoError(err)
// Inject a revision to sweep up the last revision
_, err = pds.ReadWriteTx(ctx, func(ctx context.Context, rwt datastore.ReadWriteTransaction) error {
return nil
})
require.NoError(err)
// Ensure the relationships were deleted.
for _, rel := range rels {
tRequire.NoRelationshipExists(ctx, rel, deletedAt)
}
// Sleep to ensure GC.
time.Sleep(1 * time.Millisecond)
// Run GC and ensure all the stale relationships are removed.
afterDelete, err := pgg.Now(ctx)
require.NoError(err)
afterDeleteTx, err := pgg.TxIDBefore(ctx, afterDelete)
require.NoError(err)
removed, err = pgg.DeleteBeforeTx(ctx, afterDeleteTx)
require.NoError(err)
require.Equal(int64(chunkRelationshipCount), removed.Relationships)
require.Equal(int64(2), removed.Transactions)
require.Zero(removed.Namespaces)
}
func QuantizedRevisionTest(t *testing.T, b testdatastore.RunningEngineForTest) {
testCases := []struct {
testName string
quantization time.Duration
followerReadDelay time.Duration
relativeTimes []time.Duration
numLower uint64
numHigher uint64
}{
{
"DefaultRevision",
1 * time.Second,
0,
[]time.Duration{},
0, 0,
},
{
"OnlyPastRevisions",
1 * time.Second,
0,
[]time.Duration{-2 * time.Second},
1, 0,
},
{
"OldestInWindowIsSelected",
1 * time.Second,
0,
[]time.Duration{1 * time.Millisecond, 2 * time.Millisecond},
1, 1,
},
{
"ShouldObservePreviousAndCurrent",
1 * time.Second,
0,
[]time.Duration{-1 * time.Second, 0},
2, 0,
},
{
"OnlyFutureRevisions",
1 * time.Second,
0,
[]time.Duration{2 * time.Second},
1, 0,
},
{
"QuantizedLower",
2 * time.Second,
0,
[]time.Duration{-4 * time.Second, -1 * time.Nanosecond, 0},
2, 1,
},
{
"QuantizedRecentWithFollowerReadDelay",
500 * time.Millisecond,
2 * time.Second,
[]time.Duration{-4 * time.Second, -2 * time.Second, 0},
2, 1,
},
{
"QuantizedRecentWithoutFollowerReadDelay",
500 * time.Millisecond,
0,
[]time.Duration{-4 * time.Second, -2 * time.Second, 0},
3, 0,
},
{
"QuantizationDisabled",
1 * time.Nanosecond,
0,
[]time.Duration{-2 * time.Second, -1 * time.Nanosecond, 0},
3, 0,
},
}
for _, tc := range testCases {
t.Run(tc.testName, func(t *testing.T) {
require := require.New(t)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var conn *pgx.Conn
ds := b.NewDatastore(t, func(engine, uri string) datastore.Datastore {
var err error
conn, err = pgx.Connect(ctx, uri)
require.NoError(err)
RegisterTypes(conn.TypeMap())
ds, err := newPostgresDatastore(
ctx,
uri,
primaryInstanceID,
RevisionQuantization(tc.quantization),
GCWindow(24*time.Hour),
WatchBufferLength(1),
FollowerReadDelay(tc.followerReadDelay),
WithRevisionHeartbeat(false),
)
require.NoError(err)
return ds
})
defer ds.Close()
// set a random time zone to ensure the queries are unaffected by tz
_, err := conn.Exec(ctx, fmt.Sprintf("SET TIME ZONE -%d", rand.Intn(8)+1)) //nolint:gosec
require.NoError(err)
var dbNow time.Time
err = conn.QueryRow(ctx, "SELECT (NOW() AT TIME ZONE 'utc')").Scan(&dbNow)
require.NoError(err)
if len(tc.relativeTimes) > 0 {
psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar)
insertTxn := psql.Insert(schema.TableTransaction).Columns(schema.ColTimestamp)
for _, offset := range tc.relativeTimes {
sql, args, err := insertTxn.Values(dbNow.Add(offset)).ToSql()
require.NoError(err)
_, err = conn.Exec(ctx, sql, args...)
require.NoError(err)
}
}
assertRevisionLowerAndHigher(ctx, t, ds, conn, tc.numLower, tc.numHigher)
})
}
}
func OverlappingRevisionTest(t *testing.T, b testdatastore.RunningEngineForTest) {
testCases := []struct {
testName string
quantization time.Duration
followerReadDelay time.Duration
revisions []postgresRevision
numLower uint64
numHigher uint64
}{
{ // the two revisions are concurrent, and given they are past the quantization window (are way in the past, around unix epoch)
// the function should return a revision snapshot that captures both of them
"ConcurrentRevisions",
5 * time.Second,
0,
[]postgresRevision{
{optionalTxID: NewXid8(3), snapshot: pgSnapshot{xmin: 1, xmax: 4, xipList: []uint64{2}}, optionalInexactNanosTimestamp: uint64((time.Second * 1) * time.Nanosecond)},
{optionalTxID: NewXid8(2), snapshot: pgSnapshot{xmin: 1, xmax: 4, xipList: []uint64{3}}, optionalInexactNanosTimestamp: uint64((time.Second * 2) * time.Nanosecond)},
},
2, 0,
},
}
for _, tc := range testCases {
t.Run(tc.testName, func(t *testing.T) {
require := require.New(t)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var conn *pgx.Conn
ds := b.NewDatastore(t, func(engine, uri string) datastore.Datastore {
var err error
conn, err = pgx.Connect(ctx, uri)
require.NoError(err)
RegisterTypes(conn.TypeMap())
ds, err := newPostgresDatastore(
ctx,
uri,
primaryInstanceID,
RevisionQuantization(tc.quantization),
GCWindow(24*time.Hour),
WatchBufferLength(1),
FollowerReadDelay(tc.followerReadDelay),