forked from rivian/delta-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckpoint_test.go
1378 lines (1248 loc) · 43.8 KB
/
checkpoint_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
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
// Copyright 2023 Rivian Automotive, Inc.
// 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 delta
import (
"errors"
"io"
"os"
"path/filepath"
"reflect"
"sort"
"strconv"
"testing"
"time"
"github.com/google/uuid"
"github.com/rivian/delta-go/lock"
"github.com/rivian/delta-go/lock/filelock"
"github.com/rivian/delta-go/state"
"github.com/rivian/delta-go/state/filestate"
"github.com/rivian/delta-go/storage"
"github.com/rivian/delta-go/storage/filestore"
)
// Helper function to set up test state
func setupCheckpointTest(t *testing.T, inputFolder string) (store *filestore.FileObjectStore, state state.Store, lock lock.Locker, checkpointLock lock.Locker) {
t.Helper()
tmpDir := t.TempDir()
tmpPath := storage.NewPath(tmpDir)
store = filestore.New(tmpPath)
if len(inputFolder) > 0 {
// Copy input folder to temp folder
err := copyFilesToTempDirRecursively(t, inputFolder, tmpDir)
if err != nil {
t.Fatal(err)
}
}
deltaLogDirPath := filepath.Join(tmpDir, "_delta_log")
if err := os.MkdirAll(deltaLogDirPath, 0777); err != nil {
t.Errorf("Failed to create directory %s: %v", deltaLogDirPath, err)
}
state = filestate.New(tmpPath, "_delta_log/_commit.state")
lock = filelock.New(tmpPath, "_delta_log/_commit.lock", filelock.Options{})
checkpointLock = filelock.New(tmpPath, "_delta_log/_checkpoint.lock", filelock.Options{})
return
}
func copyFilesToTempDirRecursively(t *testing.T, inputFolder string, outputFolder string) error {
t.Helper()
results, err := os.ReadDir(inputFolder)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return err
}
for _, r := range results {
outputPath := filepath.Join(outputFolder, r.Name())
inputPath := filepath.Join(inputFolder, r.Name())
if r.IsDir() {
err = os.Mkdir(outputPath, 0755)
if err != nil {
return err
}
err = copyFilesToTempDirRecursively(t, inputPath, outputPath)
if err != nil {
return err
}
} else {
out, err := os.Create(outputPath)
if err != nil {
return err
}
in, err := os.Open(inputPath)
if err != nil {
return err
}
_, err = io.Copy(out, in)
if err != nil {
return err
}
}
}
return nil
}
func TestCheckpointInUseWorkingFolder(t *testing.T) {
store, _, _, checkpointLock := setupCheckpointTest(t, "testdata/checkpoints/simple")
checkpointConfiguration := NewCheckpointConfiguration()
optimizeConfig, err := NewOptimizeCheckpointConfiguration(store, 5)
if err != nil {
t.Fatal(err)
}
checkpointConfiguration.ReadWriteConfiguration = *optimizeConfig
tempFilePath := storage.NewPath(filepath.Join(optimizeConfig.WorkingFolder.Raw, "/test1.txt"))
err = store.Put(tempFilePath, []byte{1, 2, 3})
if err != nil {
t.Fatal(err)
}
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 5)
if !errors.Is(err, ErrCheckpointOptimizationWorkingFolder) {
t.Errorf("Expected error creating checkpoint with non-empty working folder, got %v", err)
}
// Remove the temp file and create the checkpoint
err = store.Delete(tempFilePath)
if err != nil {
t.Fatal(err)
}
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 5)
if err != nil {
t.Fatal(err)
}
// Replace the temp file
err = store.Put(tempFilePath, []byte{1, 2, 3})
if err != nil {
t.Fatal(err)
}
// This CreateCheckpoint follows a different code path but should return the same error
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 10)
if !errors.Is(err, ErrCheckpointOptimizationWorkingFolder) {
t.Errorf("Expected error creating checkpoint with non-empty working folder, got %v", err)
}
}
func TestSimpleCheckpoint(t *testing.T) {
for _, useOnDisk := range []bool{false, true} {
for _, concurrent := range []int{0, 4} {
store, state, lock, checkpointLock := setupCheckpointTest(t, "testdata/checkpoints/simple")
checkpointConfiguration := NewCheckpointConfiguration()
if useOnDisk {
path := storage.NewPath("tempCheckpoint")
readConfig := OptimizeCheckpointConfiguration{OnDiskOptimization: true, WorkingStore: store, WorkingFolder: path}
checkpointConfiguration.ReadWriteConfiguration = readConfig
}
checkpointConfiguration.ReadWriteConfiguration.ConcurrentCheckpointRead = concurrent
checkpointConfiguration.ReadWriteConfiguration.ConcurrentCheckpointWrite = concurrent
// Create a checkpoint at version 5
created, err := CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 5)
if err != nil {
t.Fatal(err)
}
if !created {
t.Fatal("Did not create checkpoint")
}
// Does the checkpoint exist
_, err = store.Head(storage.NewPath("_delta_log/00000000000000000005.checkpoint.parquet"))
if err != nil {
t.Fatal(err)
}
// Does _last_checkpoint point to the checkpoint file
table := NewTable(store, lock, state)
checkpoints, allReturned, err := table.findLatestCheckpointsForVersion(nil)
if err != nil {
t.Fatal(err)
}
if len(checkpoints) != 1 {
t.Errorf("expected %d checkpoint, found %d", 1, len(checkpoints))
}
if allReturned {
t.Errorf("allReturned is true but should be false since _last_checkpoint was used")
}
if len(checkpoints) > 0 {
lastCheckpoint := checkpoints[len(checkpoints)-1]
if lastCheckpoint.Version != 5 {
t.Errorf("last checkpoint version is %d, should be 5", lastCheckpoint.Version)
}
}
// Remove the previous log to make sure we use the checkpoint when loading
err = store.Delete(CommitURIFromVersion(4))
if err != nil {
t.Error(err)
}
// Checkpoint at version 10
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 10)
if err != nil {
t.Fatal(err)
}
// Checkpoint file exists
checkpointMeta, err := store.Head(storage.NewPath("_delta_log/00000000000000000010.checkpoint.parquet"))
if err != nil {
t.Fatal(err)
}
// Does _last_checkpoint point to the checkpoint file
checkpoints, allReturned, err = table.findLatestCheckpointsForVersion(nil)
if err != nil {
t.Fatal(err)
}
if len(checkpoints) != 1 {
t.Errorf("expected %d checkpoint, found %d", 1, len(checkpoints))
}
if allReturned {
t.Errorf("allReturned is true but should be false since _last_checkpoint was used")
}
if len(checkpoints) > 0 {
lastCheckpoint := checkpoints[len(checkpoints)-1]
if lastCheckpoint.Version != 10 {
t.Errorf("last checkpoint version is %d, should be 10", lastCheckpoint.Version)
}
if lastCheckpoint.NumOfAddFiles != 10 {
t.Errorf("last checkpoint number of add files is %d, should be 10", lastCheckpoint.NumOfAddFiles)
}
if lastCheckpoint.Size != 12 {
t.Errorf("last checkpoint number of actions is %d, should be 12", lastCheckpoint.Size)
}
if lastCheckpoint.SizeInBytes != checkpointMeta.Size {
t.Errorf("last checkpoint size in bytes is %d, should be %d", lastCheckpoint.SizeInBytes, checkpointMeta.Size)
}
}
// Remove the previous log to make sure we use the checkpoint when loading
err = store.Delete(CommitURIFromVersion(9))
if err != nil {
t.Error(err)
}
// Reload table
table, err = OpenTableWithConfiguration(store, lock, state, &checkpointConfiguration.ReadWriteConfiguration)
if err != nil {
t.Fatal(err)
}
if table.State.FileCount() != 12 {
t.Errorf("Found %d files, expected 12", table.State.FileCount())
}
// Can't create a checkpoint if it already exists
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 10)
if !errors.Is(err, ErrCheckpointAlreadyExists) {
t.Errorf("creating a checkpoint when it already exists did not return correct error, %v", err)
}
}
}
}
type tombstonesTestData struct {
ID int32 `parquet:"name=id, type=INT32" json:"id"`
}
func getTestAdd(offsetMillis int64) *Add {
add := new(Add)
path := uuid.NewString()
add.Path = path
add.Size = 100
dataChange := true
add.DataChange = dataChange
partitionValues := make(map[string]string)
add.PartitionValues = partitionValues
add.ModificationTime = time.Now().UnixMilli() - offsetMillis
return add
}
func getTestRemove(offsetMillis int64, path string) *Remove {
remove := new(Remove)
remove.Path = path
size := int64(100)
remove.Size = &size
remove.DataChange = true
partitionValues := make(map[string]string)
remove.PartitionValues = &partitionValues
deletionTimestamp := time.Now().UnixMilli() - offsetMillis
remove.DeletionTimestamp = &deletionTimestamp
return remove
}
func testDoCommit(t *testing.T, table *Table, actions []Action) (int64, error) {
t.Helper()
tx := table.CreateTransaction(NewTransactionOptions())
tx.AddActions(actions)
return tx.Commit()
}
func TestTombstones(t *testing.T) {
for _, useOnDisk := range []bool{false, true} {
for _, concurrent := range []int{0, 4} {
store, state, lock, checkpointLock := setupCheckpointTest(t, "")
checkpointConfiguration := NewCheckpointConfiguration()
if useOnDisk {
path := storage.NewPath("tempCheckpoint")
readConfig := OptimizeCheckpointConfiguration{OnDiskOptimization: true, WorkingStore: store, WorkingFolder: path}
checkpointConfiguration.ReadWriteConfiguration = readConfig
}
checkpointConfiguration.ReadWriteConfiguration.ConcurrentCheckpointRead = concurrent
checkpointConfiguration.ReadWriteConfiguration.ConcurrentCheckpointWrite = concurrent
table := NewTable(store, lock, state)
// Set tombstone expiry time to 2 hours
metadata := NewTableMetaData("", "", Format{}, GetSchema(new(tombstonesTestData)), make([]string, 0), map[string]string{string(DeletedFileRetentionDurationDeltaConfigKey): "interval 2 hours"})
protocol := new(Protocol).Default()
if err := table.Create(*metadata, protocol, CommitInfo{}, make([]Add, 0)); err != nil {
t.Errorf("Failed to create table: %v", err)
}
add1 := getTestAdd(3 * 60 * 1000) // 3 mins ago
add2 := getTestAdd(2 * 60 * 1000) // 2 mins ago
v, err := testDoCommit(t, table, []Action{add1})
if err != nil {
t.Fatal(err)
}
if v != 1 {
t.Errorf("Version is %d, expected 1", v)
}
v, err = testDoCommit(t, table, []Action{add2})
if err != nil {
t.Fatal(err)
}
if v != 2 {
t.Errorf("Version is %d, expected 2", v)
}
// Create a checkpoint
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 2)
if err != nil {
t.Fatal(err)
}
// Load the checkpoint
// Remove the previous log to make sure we use the checkpoint when loading
err = store.Delete(CommitURIFromVersion(1))
if err != nil {
t.Error(err)
}
// Reload table
table, err = OpenTableWithConfiguration(store, lock, state, &checkpointConfiguration.ReadWriteConfiguration)
if err != nil {
t.Fatal(err)
}
if table.State.FileCount() != 2 {
t.Errorf("state contains %d files, expected 2", table.State.FileCount())
}
if table.State.onDiskOptimization != useOnDisk {
t.Errorf("expected on disk optimization %v", useOnDisk)
}
if !useOnDisk {
// TODO - test contents of on-disk temp file
_, ok := table.State.Files[add1.Path]
if !ok {
t.Errorf("Missing file %s", add1.Path)
}
_, ok = table.State.Files[add2.Path]
if !ok {
t.Errorf("Missing file %s", add2.Path)
}
}
// Simulate an optimize at 5 minutes ago: the tombstones should not be expired since that's set to 2 hours
optimizeTime := int64(5) * 60 * 1000
remove1 := getTestRemove(optimizeTime, add1.Path)
remove2 := getTestRemove(optimizeTime, add2.Path)
add3 := getTestAdd(optimizeTime)
add4 := getTestAdd(optimizeTime)
v, err = testDoCommit(t, table, []Action{remove1, remove2, add3, add4})
if err != nil {
t.Fatal(err)
}
if v != 3 {
t.Errorf("Version is %d, expected 3", v)
}
// Create a checkpoint and load it
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 3)
if err != nil {
t.Fatal(err)
}
table, err = OpenTableWithConfiguration(store, lock, state, &checkpointConfiguration.ReadWriteConfiguration)
if err != nil {
t.Fatal(err)
}
// Verify only the new adds are present
if table.State.FileCount() != 2 {
t.Errorf("State contains %d files, expected 2", table.State.FileCount())
}
if !useOnDisk {
_, ok := table.State.Files[add3.Path]
if !ok {
t.Errorf("Missing file %s", add3.Path)
}
_, ok = table.State.Files[add4.Path]
if !ok {
t.Errorf("Missing file %s", add4.Path)
}
}
// Verify tombstones are present
if table.State.TombstoneCount() != 2 {
t.Errorf("State contains %d tombstones, expected 2", table.State.TombstoneCount())
}
}
}
}
func TestExpiredTombstones(t *testing.T) {
for _, useOnDisk := range []bool{false, true} {
for _, concurrent := range []int{0, 4} {
store, state, lock, checkpointLock := setupCheckpointTest(t, "")
checkpointConfiguration := NewCheckpointConfiguration()
if useOnDisk {
path := storage.NewPath("tempCheckpoint")
readConfig := OptimizeCheckpointConfiguration{OnDiskOptimization: true, WorkingStore: store, WorkingFolder: path}
checkpointConfiguration.ReadWriteConfiguration = readConfig
}
checkpointConfiguration.ReadWriteConfiguration.ConcurrentCheckpointRead = concurrent
checkpointConfiguration.ReadWriteConfiguration.ConcurrentCheckpointWrite = concurrent
table := NewTable(store, lock, state)
metadata := NewTableMetaData("", "", Format{}, GetSchema(new(tombstonesTestData)), make([]string, 0), map[string]string{string(DeletedFileRetentionDurationDeltaConfigKey): "interval 1 minute"})
protocol := new(Protocol).Default()
if err := table.Create(*metadata, protocol, CommitInfo{}, make([]Add, 0)); err != nil {
t.Errorf("Failed to create table: %v", err)
}
add1 := getTestAdd(3 * 60 * 1000) // 3 mins ago
add2 := getTestAdd(2 * 60 * 1000) // 2 mins ago
v, err := testDoCommit(t, table, []Action{add1})
if err != nil {
t.Fatal(err)
}
if v != 1 {
t.Errorf("Version is %d, expected 1", v)
}
v, err = testDoCommit(t, table, []Action{add2})
if err != nil {
t.Fatal(err)
}
if v != 2 {
t.Errorf("Version is %d, expected 2", v)
}
// Create a checkpoint
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 2)
if err != nil {
t.Fatal(err)
}
// Load the checkpoint
// Reload table
table, err = OpenTableWithConfiguration(store, lock, state, &checkpointConfiguration.ReadWriteConfiguration)
if err != nil {
t.Fatal(err)
}
if table.State.FileCount() != 2 {
t.Errorf("State contains %d files, expected 2", table.State.FileCount())
}
if !useOnDisk {
_, ok := table.State.Files[add1.Path]
if !ok {
t.Errorf("Missing file %s", add1.Path)
}
_, ok = table.State.Files[add2.Path]
if !ok {
t.Errorf("Missing file %s", add2.Path)
}
}
// Simulate an optimize
optimizeTime := int64(5) * 59 * 1000
remove1 := getTestRemove(optimizeTime, add1.Path)
remove2 := getTestRemove(optimizeTime, add2.Path)
add3 := getTestAdd(optimizeTime)
add4 := getTestAdd(optimizeTime)
v, err = testDoCommit(t, table, []Action{remove1, remove2, add3, add4})
if err != nil {
t.Fatal(err)
}
if v != 3 {
t.Errorf("Version is %d, expected 3", v)
}
// Create a checkpoint and load it
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 3)
if err != nil {
t.Fatal(err)
}
table, err = OpenTableWithConfiguration(store, lock, state, &checkpointConfiguration.ReadWriteConfiguration)
if err != nil {
t.Fatal(err)
}
// Verify only the new adds are present
if table.State.FileCount() != 2 {
t.Errorf("State contains %d files, expected 2", table.State.FileCount())
}
if !useOnDisk {
_, ok := table.State.Files[add3.Path]
if !ok {
t.Errorf("Missing file %s", add3.Path)
}
_, ok = table.State.Files[add4.Path]
if !ok {
t.Errorf("Missing file %s", add4.Path)
}
// Verify stale tombstones were removed
if table.State.TombstoneCount() != 0 {
t.Errorf("State contains %d tombstones, expected 0", table.State.TombstoneCount())
}
}
}
}
}
func TestCheckpointNoPartition(t *testing.T) {
for _, useOnDisk := range []bool{false, true} {
for _, concurrent := range []int{0, 4} {
store, stateStore, lock, checkpointLock := setupCheckpointTest(t, "")
checkpointConfiguration := NewCheckpointConfiguration()
if useOnDisk {
path := storage.NewPath("tempCheckpoint")
readConfig := OptimizeCheckpointConfiguration{OnDiskOptimization: true, WorkingStore: store, WorkingFolder: path}
checkpointConfiguration.ReadWriteConfiguration = readConfig
}
checkpointConfiguration.ReadWriteConfiguration.ConcurrentCheckpointRead = concurrent
checkpointConfiguration.ReadWriteConfiguration.ConcurrentCheckpointWrite = concurrent
table := NewTable(store, lock, stateStore)
metadata := NewTableMetaData("", "", Format{}, GetSchema(new(tombstonesTestData)), make([]string, 0), map[string]string{string(DeletedFileRetentionDurationDeltaConfigKey): "interval 1 minute"})
protocol := new(Protocol).Default()
if err := table.Create(*metadata, protocol, CommitInfo{}, make([]Add, 0)); err != nil {
t.Errorf("Failed to create table: %v", err)
}
add1 := getTestAdd(3 * 60 * 1000) // 3 mins ago
add2 := getTestAdd(2 * 60 * 1000) // 2 mins ago
v, err := testDoCommit(t, table, []Action{add1})
if err != nil {
t.Fatal(err)
}
if v != 1 {
t.Errorf("Version is %d, expected 1", v)
}
v, err = testDoCommit(t, table, []Action{add2})
if err != nil {
t.Fatal(err)
}
if v != 2 {
t.Errorf("Version is %d, expected 2", v)
}
// Create a checkpoint
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 2)
if err != nil {
t.Fatal(err)
}
// Load the checkpoint - don't use OpenTable since it will fall back to incremental if checkpoint read fails
var version int64 = 2
checkpoints, _, err := table.findLatestCheckpointsForVersion(&version)
if err != nil {
t.Fatal(err)
}
if len(checkpoints) == 0 {
t.Fatal("did not find checkpoint")
}
err = table.restoreCheckpoint(&checkpoints[len(checkpoints)-1], &checkpointConfiguration.ReadWriteConfiguration)
if err != nil {
t.Fatal(err)
}
if table.State.FileCount() != 2 {
t.Errorf("State contains %d files, expected 2", table.State.FileCount())
}
if !useOnDisk {
_, ok := table.State.Files[add1.Path]
if !ok {
t.Errorf("Missing file %s", add1.Path)
}
_, ok = table.State.Files[add2.Path]
if !ok {
t.Errorf("Missing file %s", add2.Path)
}
add1.DataChange = false
if !reflect.DeepEqual(table.State.Files[add1.Path], *add1) {
t.Errorf("Expected %v found %v", add1, table.State.Files[add1.Path])
}
}
}
}
}
func TestMultiPartCheckpoint(t *testing.T) {
for _, useOnDisk := range []bool{false, true} {
for _, concurrent := range []int{0, 4} {
store, stateStore, lock, checkpointLock := setupCheckpointTest(t, "")
checkpointConfiguration := NewCheckpointConfiguration()
checkpointConfiguration.MaxRowsPerPart = 5
if useOnDisk {
path := storage.NewPath("tempCheckpoint")
readConfig := OptimizeCheckpointConfiguration{OnDiskOptimization: true, WorkingStore: store, WorkingFolder: path, ConcurrentCheckpointRead: 4}
checkpointConfiguration.ReadWriteConfiguration = readConfig
}
checkpointConfiguration.ReadWriteConfiguration.ConcurrentCheckpointRead = concurrent
checkpointConfiguration.ReadWriteConfiguration.ConcurrentCheckpointWrite = concurrent
table := NewTable(store, lock, stateStore)
provider := "tester"
options := map[string]string{"hello": "world"}
metadata := NewTableMetaData("test-data", "For testing multi-part checkpoints", Format{Provider: provider, Options: options},
SchemaTypeStruct{}, make([]string, 0), map[string]string{"delta.isTest": "true"})
protocol := new(Protocol).Default()
if err := table.Create(*metadata, protocol, CommitInfo{}, make([]Add, 0)); err != nil {
t.Errorf("Failed to create table: %v", err)
}
paths := make([]string, 0, 10)
// Commit ten Add actions
for i := 0; i < 10; i++ {
add := getTestAdd(60 * 1000)
paths = append(paths, add.Path)
v, err := testDoCommit(t, table, []Action{add})
if err != nil {
t.Fatal(err)
}
if int(v) != i+1 {
t.Errorf("Version is %d, expected %d", v, i+1)
}
}
sort.Strings(paths)
// Commit a delete
remove := getTestRemove(0, paths[0])
v, err := testDoCommit(t, table, []Action{remove})
if err != nil {
t.Fatal(err)
}
if int(v) != 11 {
t.Errorf("Version is %d, expected %d", v, 11)
}
// And a txn
txn := new(Txn)
appID := "testApp"
txn.AppID = appID
lastUpdated := int64(time.Now().UnixMilli())
txn.LastUpdated = &lastUpdated
txnVersion := v
txn.Version = txnVersion
v, err = testDoCommit(t, table, []Action{txn})
if err != nil {
t.Fatal(err)
}
if int(v) != 12 {
t.Errorf("Version is %d, expected %d", v, 12)
}
// Create a checkpoint.
// There should be 14 rows: 1 protocol and 1 metadata, 10 adds, 1 remove and 1 txn.
// With max 5 rows per checkpoint part, we should get 3 parquet files.
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 12)
if err != nil {
t.Fatal(err)
}
// Do all three checkpoint files exist
_, err = store.Head(storage.NewPath("_delta_log/00000000000000000012.checkpoint.0000000001.0000000003.parquet"))
if err != nil {
t.Fatal(err)
}
_, err = store.Head(storage.NewPath("_delta_log/00000000000000000012.checkpoint.0000000002.0000000003.parquet"))
if err != nil {
t.Fatal(err)
}
_, err = store.Head(storage.NewPath("_delta_log/00000000000000000012.checkpoint.0000000003.0000000003.parquet"))
if err != nil {
t.Fatal(err)
}
// Does _last_checkpoint point to the checkpoint file
table = NewTable(store, lock, stateStore)
checkpoints, allReturned, err := table.findLatestCheckpointsForVersion(nil)
if err != nil {
t.Fatal(err)
}
if len(checkpoints) != 1 {
t.Errorf("expected %d checkpoint, found %d", 1, len(checkpoints))
}
if allReturned {
t.Errorf("allReturned is true but should be false since _last_checkpoint was used")
}
if len(checkpoints) > 0 {
lastCheckpoint := checkpoints[len(checkpoints)-1]
if lastCheckpoint.Version != 12 {
t.Errorf("last checkpoint version is %d, expected 12", lastCheckpoint.Version)
}
if lastCheckpoint.Parts == nil {
t.Error("last checkpoint parts count is nil, expected 3")
} else if *lastCheckpoint.Parts != 3 {
t.Errorf("last checkpoint parts count is %d, expected 3", *lastCheckpoint.Parts)
}
}
// Remove the previous commit to make sure we load the checkpoint files
err = store.Delete(CommitURIFromVersion(11))
if err != nil {
t.Error(err)
}
// Load the multipart checkpoint
err = table.Load(&checkpointConfiguration.ReadWriteConfiguration)
if err != nil {
t.Fatal(err)
}
// Check all the adds are correct; we removed the first add
if table.State.FileCount() != 9 {
t.Errorf("Found %d files, expected 9", table.State.FileCount())
} else {
if !useOnDisk {
keys := make([]string, 0, len(table.State.Files))
for k := range table.State.Files {
keys = append(keys, k)
}
sort.Strings(keys)
for i := 0; i < 9; i++ {
if keys[i] != paths[i+1] {
t.Errorf("Found path %s, expected %s", keys[i], paths[i])
}
}
}
}
// Check the metadata is correct
if table.State.CurrentMetadata.Name != metadata.Name {
t.Errorf("Found metadata name %s, expected %s", table.State.CurrentMetadata.Name, metadata.Name)
}
if table.State.CurrentMetadata.Description != metadata.Description {
t.Errorf("Found metadata description %s, expected %s", table.State.CurrentMetadata.Description, metadata.Description)
}
if !reflect.DeepEqual(table.State.CurrentMetadata.Format, metadata.Format) {
t.Errorf("Found metadata format %v, expected %v", table.State.CurrentMetadata.Format, metadata.Format)
}
if !reflect.DeepEqual(table.State.CurrentMetadata.Configuration, metadata.Configuration) {
t.Errorf("Found metadata configuration %v, expected %v", table.State.CurrentMetadata.Configuration, metadata.Configuration)
}
// Check the tombstone is correct
if table.State.TombstoneCount() != 1 {
t.Errorf("Found %d tombstones, expected 1", table.State.TombstoneCount())
} else {
if !useOnDisk {
checkpointRemove, ok := table.State.Tombstones[paths[0]]
if !ok {
t.Errorf("Missing expected tombstone %s", paths[0])
} else {
if remove.Path != checkpointRemove.Path {
t.Errorf("Found tombstone path %s, expected %s", remove.Path, checkpointRemove.Path)
}
}
}
}
// Check the txn is correct
if len(table.State.AppTransactionVersion) != 1 {
t.Errorf("Found %d app versions, expected 1", len(table.State.AppTransactionVersion))
} else {
version, ok := table.State.AppTransactionVersion[txn.AppID]
if !ok {
t.Error("Did not find expected app in app versions")
} else {
if version != txn.Version {
t.Errorf("Found version %d in app versions, expected %d", version, txn.Version)
}
}
}
// Verify correct protocol
if table.State.MinReaderVersion != protocol.MinReaderVersion {
t.Errorf("State MinReaderVersion is %d, expected %d", table.State.MinReaderVersion, protocol.MinReaderVersion)
}
if table.State.MinWriterVersion != protocol.MinWriterVersion {
t.Errorf("State MinWriterVersion is %d, expected %d", table.State.MinWriterVersion, protocol.MinWriterVersion)
}
// Remove _last_checkpoint
err = store.Delete(storage.NewPath("_delta_log/_last_checkpoint"))
if err != nil {
t.Fatal(err)
}
// Re-load and check version
err = table.Load(&checkpointConfiguration.ReadWriteConfiguration)
if err != nil {
t.Fatal(err)
}
if table.State.Version != 12 {
t.Errorf("Expected version %d, found %d", 12, table.State.Version)
}
}
}
}
func TestCheckpointInfoFromURI(t *testing.T) {
type test struct {
input string
wantCheckpoint *CheckPoint
wantPart int32
}
part63 := int32(63)
tests := []test{
{input: "_delta_log/00000000000000000000.json", wantCheckpoint: nil},
{input: "_delta_log/01234567890123456789.json", wantCheckpoint: nil},
{input: "_delta_log/_commit_aabbccdd-eeff-1122-3344-556677889900.json.tmp", wantCheckpoint: nil},
{input: "_delta_log/00000000000000000001.checkpoint.parquet.tmp", wantCheckpoint: nil},
{input: "_delta_log/tmp_00000000000000000001.checkpoint.parquet", wantCheckpoint: nil},
{input: "_delta_log/00000000000000000001.checkpoint.parquet", wantCheckpoint: &CheckPoint{Version: 1, Size: 0, Parts: nil}, wantPart: 0},
{input: "_delta_log/00000000000000123456.checkpoint.0000000002.0000000063.parquet", wantCheckpoint: &CheckPoint{Version: 123456, Size: 0, Parts: &part63}, wantPart: 2},
{input: "_delta_log/tmp_00000000000000123456.checkpoint.0000000002.0000000063.parquet", wantCheckpoint: nil},
}
for _, tc := range tests {
gotCheckpoint, gotPart, err := checkpointInfoFromURI(storage.NewPath(tc.input))
if err != nil {
t.Error(err)
}
if gotCheckpoint == nil {
if tc.wantCheckpoint != nil {
t.Errorf("expected %v, got nil for %s", tc.wantCheckpoint, tc.input)
}
continue
}
if tc.wantCheckpoint == nil {
t.Errorf("expected nil, got %v for %s", gotCheckpoint, tc.input)
continue
}
if !reflect.DeepEqual(*gotCheckpoint, *tc.wantCheckpoint) {
t.Errorf("expected %v, got %v for %s", *tc.wantCheckpoint, *gotCheckpoint, tc.input)
}
if gotPart != tc.wantPart {
t.Errorf("expected %d, got %d for %s", tc.wantPart, gotPart, tc.input)
}
}
}
func TestDoesCheckpointVersionExist(t *testing.T) {
store, _, _, checkpointLock := setupCheckpointTest(t, "testdata/checkpoints/simple")
checkpointConfiguration := NewCheckpointConfiguration()
checkpointConfiguration.MaxRowsPerPart = 8
// There is no checkpoint at version 5 yet
checkpointExists, err := DoesCheckpointVersionExist(store, 5, false)
if err != nil {
t.Fatal(err)
}
if checkpointExists {
t.Error("checkpoint should not exist")
}
// Create a checkpoint at version 5
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 5)
if err != nil {
t.Fatal(err)
}
// Verify checkpoint exists
checkpointExists, err = DoesCheckpointVersionExist(store, 5, false)
if err != nil {
t.Error(err)
}
if !checkpointExists {
t.Error("checkpoint should exist")
}
// Rename the checkpoint with a prefix
err = store.Rename(storage.NewPath("_delta_log/00000000000000000005.checkpoint.parquet"), storage.NewPath("_delta_log/test_00000000000000000005.checkpoint.parquet"))
if err != nil {
t.Error(err)
}
// Verify checkpoint does not exist
checkpointExists, err = DoesCheckpointVersionExist(store, 5, false)
if err != nil {
t.Error(err)
}
if checkpointExists {
t.Error("checkpoint should not exist")
}
// Rename the checkpoint with a suffix
err = store.Rename(storage.NewPath("_delta_log/test_00000000000000000005.checkpoint.parquet"), storage.NewPath("_delta_log/00000000000000000005.checkpoint.parquet.test"))
if err != nil {
t.Error(err)
}
// Verify checkpoint does not exist
checkpointExists, err = DoesCheckpointVersionExist(store, 5, false)
if err != nil {
t.Error(err)
}
if checkpointExists {
t.Error("checkpoint should not exist")
}
// Create a multi-part checkpoint at version 10
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 10)
if err != nil {
t.Fatal(err)
}
// Verify checkpoint exists without multi-part validation
checkpointExists, err = DoesCheckpointVersionExist(store, 10, false)
if err != nil {
t.Error(err)
}
if !checkpointExists {
t.Error("checkpoint should exist")
}
// Validate multi-part is all present
checkpointExists, err = DoesCheckpointVersionExist(store, 10, true)
if err != nil {
t.Error(err)
}
if !checkpointExists {
t.Error("checkpoint should exist")
}
// Rename a piece of the multi-part
err = store.Rename(storage.NewPath("_delta_log/00000000000000000010.checkpoint.0000000001.0000000002.parquet"), storage.NewPath("_delta_log/00000000000000000010.checkpoint.0000000001.0000000003.parquet"))
if err != nil {
t.Error(err)
}
// Validating the multi-part should return an error
_, err = DoesCheckpointVersionExist(store, 10, true)
if !errors.Is(err, ErrCheckpointInvalidMultipartFileName) {
t.Error("doesCheckpointVersionExist on incomplete checkpoint did not return correct error")
}
// Delete one piece of the multi-part
err = store.Delete(storage.NewPath("_delta_log/00000000000000000010.checkpoint.0000000001.0000000003.parquet"))
if err != nil {
t.Error(err)
}
// Validating the multi-part should return an error
_, err = DoesCheckpointVersionExist(store, 10, true)
if !errors.Is(err, ErrCheckpointIncomplete) {
t.Error("doesCheckpointVersionExist on incomplete checkpoint did not return correct error")
}
}
func TestInvalidCheckpointFallback(t *testing.T) {
store, state, lock, checkpointLock := setupCheckpointTest(t, "testdata/checkpoints/simple")
checkpointConfiguration := NewCheckpointConfiguration()
// Create a checkpoint at version 5
_, err := CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 5)
if err != nil {
t.Fatal(err)
}
// Create a checkpoint at version 10
_, err = CreateCheckpoint(store, checkpointLock, checkpointConfiguration, 10)
if err != nil {
t.Fatal(err)
}
// Replace the version 10 checkpoint with an invalid file
err = store.Put(storage.NewPath("_delta_log/00000000000000000010.checkpoint.parquet"), []byte("test"))
if err != nil {
t.Fatal(err)
}
// Open table; _last_checkpoint is pointing to an invalid checkpoint now
table, err := OpenTable(store, lock, state)
if err != nil {
t.Fatal(err)
}
// Make sure we still loaded the last version
if table.State.Version != 12 {
t.Errorf("expected version %d, found %d", 12, table.State.Version)