-
Notifications
You must be signed in to change notification settings - Fork 8
/
delta.go
1395 lines (1228 loc) · 48.4 KB
/
delta.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 contains the resources required to interact with a Delta table.
package delta
import (
"errors"
"fmt"
"math"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/rivian/delta-go/lock"
"github.com/rivian/delta-go/logstore"
"github.com/rivian/delta-go/state"
"github.com/rivian/delta-go/storage"
log "github.com/sirupsen/logrus"
"golang.org/x/exp/constraints"
"golang.org/x/exp/maps"
)
const (
clientVersion = "alpha-0.0.0"
maxReaderVersionSupported = 1
maxWriterVersionSupported = 1
)
var (
// ErrExceededCommitRetryAttempts is returned when the maximum number of commit retry attempts has been exceeded.
ErrExceededCommitRetryAttempts error = errors.New("exceeded commit retry attempts")
// ErrNotATable is returned when a Delta table is not valid.
ErrNotATable error = errors.New("not a table")
// ErrInvalidVersion is returned when a version is invalid.
ErrInvalidVersion error = errors.New("invalid version")
// ErrUnableToLoadVersion is returned when a version cannot be loaded.
ErrUnableToLoadVersion error = errors.New("unable to load specified version")
// ErrLockFailed is returned a lock fails unexpectedly.
ErrLockFailed error = errors.New("lock failed unexpectedly without an error")
// ErrNotImplemented is returned when a feature has not been implemented.
ErrNotImplemented error = errors.New("not implemented")
// ErrUnsupportedReaderVersion is returned when a reader version is unsupported.
ErrUnsupportedReaderVersion error = errors.New("reader version is unsupported")
// ErrUnsupportedWriterVersion is returned when a writer version is unsupported.
ErrUnsupportedWriterVersion error = errors.New("writer version is unsupported")
// ErrFailedToCopyTempFile is returned when a temp file fails to be copied into a commit URI.
ErrFailedToCopyTempFile error = errors.New("failed to copy temp file")
// ErrFailedToAcknowledgeCommit is returned when a commit fails to be acknowledged.
ErrFailedToAcknowledgeCommit error = errors.New("failed to acknowledge commit")
)
var (
commitFileRegex *regexp.Regexp = regexp.MustCompile(`^(\d{20}).json$`)
checkpointRegex *regexp.Regexp = regexp.MustCompile(`^(\d{20})\.checkpoint\.parquet$`)
checkpointPartsRegex *regexp.Regexp = regexp.MustCompile(`^(\d{20})\.checkpoint\.(\d{10})\.(\d{10})\.parquet$`)
commitOrCheckpointRegex *regexp.Regexp = regexp.MustCompile(`^(\d{20})\.((json$)|(checkpoint\.parquet$)|(checkpoint\.(\d{10})\.(\d{10})\.parquet$))`)
)
// Table represents a Delta table.
type Table struct {
// The state of the table as of the most recent loaded Delta log entry.
State TableState
// The remote store of the state of the table as of the most recent loaded Delta log entry.
StateStore state.Store
// object store to access log and data files
Store storage.ObjectStore
// Locking client to ensure optimistic locked commits from distributed workers
LockClient lock.Locker
// file metadata for latest checkpoint
LastCheckPoint *CheckPoint
// table versions associated with timestamps
VersionTimestamp map[int64]time.Time
// Log store which provides multi-cluster write support
LogStore logstore.LogStore
}
// NewTable creates a new Table struct without loading any data from backing storage.
//
// NOTE: This is for advanced users. If you don't know why you need to use this method, please
// call one of the `open_table` helper methods instead.
func NewTable(store storage.ObjectStore, lock lock.Locker, stateStore state.Store) *Table {
table := new(Table)
table.Store = store
table.StateStore = stateStore
table.LockClient = lock
table.LastCheckPoint = nil
table.State = *NewTableState(-1)
return table
}
// NewTableWithLogStore creates a new Table instance with a log store configured.
func NewTableWithLogStore(store storage.ObjectStore, lock lock.Locker, logStore logstore.LogStore) *Table {
t := new(Table)
t.State = *NewTableState(-1)
t.Store = store
t.LockClient = lock
t.LastCheckPoint = nil
t.LogStore = logStore
return t
}
// CreateTransaction creates a new Transaction for the Table.
// The transaction holds a mutable reference to the Table, preventing other references
// until the transaction is dropped.
func (t *Table) CreateTransaction(opts TransactionOptions) *Transaction {
opts.setOptionsDefaults()
transaction := new(Transaction)
transaction.Table = t
transaction.options = opts
return transaction
}
// setOptionsDefaults sets the default transaction options.
func (o *TransactionOptions) setOptionsDefaults() {
if o.MaxRetryCommitAttempts == 0 {
o.MaxRetryCommitAttempts = defaultMaxRetryCommitAttempts
}
if o.MaxRetryReadAttempts == 0 {
o.MaxRetryReadAttempts = defaultMaxReadAttempts
}
if o.MaxRetryWriteAttempts == 0 {
o.MaxRetryWriteAttempts = defaultMaxWriteAttempts
}
if o.RetryCommitAttemptsBeforeLoadingTable == 0 {
o.RetryCommitAttemptsBeforeLoadingTable = defaultRetryCommitAttemptsBeforeLoadingTable
}
if o.MaxRetryLogFixAttempts == 0 {
o.MaxRetryLogFixAttempts = defaultMaxRetryLogFixAttempts
}
}
// CommitURIFromVersion returns the URI of commit version.
func CommitURIFromVersion(version int64) storage.Path {
str := fmt.Sprintf("%020d.json", version)
path := storage.PathFromIter([]string{"_delta_log", str})
return path
}
// BaseCommitURI returns the base path of a commit URI.
func BaseCommitURI() storage.Path {
return storage.NewPath("_delta_log/")
}
// IsValidCommitURI returns true if a URI is a valid commit filename (not a checkpoint file, and not a temp commit).
func IsValidCommitURI(path storage.Path) bool {
match := commitFileRegex.MatchString(path.Base())
return match
}
// IsValidCommitOrCheckpointURI returns true if a URI is a valid commit or checkpoint file name.
// Otherwise, it returns false.
func IsValidCommitOrCheckpointURI(path storage.Path) bool {
return commitFileRegex.MatchString(path.Base()) || commitOrCheckpointRegex.MatchString(path.Base())
}
// CommitVersionFromURI returns true plus the version if the URI is a valid commit filename.
func CommitVersionFromURI(path storage.Path) (bool, int64) {
groups := commitFileRegex.FindStringSubmatch(path.Base())
if len(groups) == 2 {
version, err := strconv.ParseInt(groups[1], 10, 64)
if err == nil {
return true, int64(version)
}
}
return false, 0
}
// CommitOrCheckpointVersionFromURI returns true plus the version if the URI is a valid commit or checkpoint filename.
func CommitOrCheckpointVersionFromURI(path storage.Path) (bool, int64) {
groups := commitOrCheckpointRegex.FindStringSubmatch(path.Base())
if groups != nil {
version, err := strconv.ParseInt(groups[1], 10, 64)
if err == nil {
return true, int64(version)
}
}
return false, 0
}
// Create creates a Table with version 0 given the provided MetaData, Protocol, and CommitInfo.
// Note that if the protocol MinReaderVersion or MinWriterVersion is too high, the table will be created
// and then an error will be returned
func (t *Table) Create(metadata TableMetaData, protocol Protocol, commitInfo CommitInfo, addActions []Add) error {
meta := metadata.toMetaData()
// delta-go commit info will include the delta-go version and timestamp as of now
enrichedCommitInfo := maps.Clone(commitInfo)
enrichedCommitInfo["clientVersion"] = fmt.Sprintf("delta-go.%s", clientVersion)
enrichedCommitInfo["timestamp"] = time.Now().UnixMilli()
actions := []Action{
enrichedCommitInfo,
protocol,
meta,
}
for _, add := range addActions {
actions = append(actions, add)
}
var version int64
var err error
transaction := t.CreateTransaction(NewTransactionOptions())
transaction.AddActions(actions)
if t.LogStore != nil {
version, err = transaction.CommitLogStore()
if err != nil {
return err
}
} else {
preparedCommit, err := transaction.prepareCommit()
if err != nil {
return err
}
//Set StateStore Version=-1 synced with the table State Version
zeroState := state.CommitState{
Version: t.State.Version,
}
if err := transaction.Table.StateStore.Put(zeroState); err != nil {
return errors.Join(fmt.Errorf("failed to add commit state with version %d to state store", zeroState.Version), err)
}
if err := transaction.tryCommit(&preparedCommit); err != nil {
return err
}
version = t.State.Version
}
// Merge state from new commit version
newState, err := NewTableStateFromCommit(t, version)
if err != nil {
return err
}
if err := t.State.merge(newState, 150000, nil, false); err != nil && !errors.Is(err, ErrVersionOutOfOrder) {
return errors.Join(errors.New("failed to merge new state into existing state"), err)
}
// If either version is too high, we return an error, but we still create the table first
if protocol.MinReaderVersion > maxReaderVersionSupported {
err = ErrUnsupportedReaderVersion
}
if protocol.MinWriterVersion > maxWriterVersionSupported {
err = errors.Join(err, ErrUnsupportedWriterVersion)
}
return err
}
// Exists checks if a Table with version 0 exists in the object store.
func (t *Table) Exists() (bool, error) {
path := CommitURIFromVersion(0)
meta, err := t.Store.Head(path)
if errors.Is(err, storage.ErrObjectDoesNotExist) {
// Fallback: check for other variants of the version
logIterator := storage.NewListIterator(BaseCommitURI(), t.Store)
for {
meta, err := logIterator.Next()
if errors.Is(err, storage.ErrObjectDoesNotExist) {
break
}
if err != nil {
return false, err
}
isCommitOrCheckpoint, _ := CommitOrCheckpointVersionFromURI(meta.Location)
if isCommitOrCheckpoint {
return true, nil
}
}
return false, nil
}
// Object should have size
if meta.Size > 0 {
return true, nil
}
// other errors --> object does not exist
if err != nil {
return false, err
}
// no errors -> assume object exists
return true, nil
}
// ReadCommitVersion retrieves the actions from a commit log.
func (t *Table) ReadCommitVersion(version int64) ([]Action, error) {
path := CommitURIFromVersion(version)
transaction := t.CreateTransaction(NewTransactionOptions())
return transaction.ReadActions(path)
}
// LatestVersion gets the latest version of a table.
func (t *Table) LatestVersion() (int64, error) {
var (
minVersion int64
path = lastCheckpointPath()
bytes, err = t.Store.Get(path)
objects *storage.ListResult
)
if errors.Is(err, storage.ErrObjectDoesNotExist) {
for {
o, err := t.Store.List(storage.NewPath("_delta_log"), objects)
if err != nil {
return -1, errors.Join(errors.New("failed to list Delta log"), err)
}
objects = &o
found, v := findValidCommitOrCheckpointURI(objects.Objects)
if !found {
if objects.NextToken == "" {
return -1, ErrNotATable
}
continue
}
minVersion = v
break
}
} else {
checkpoint, err := checkpointFromBytes(bytes)
if err != nil {
return -1, errors.Join(errors.New("failed to get checkpoint from bytes"), err)
}
minVersion = checkpoint.Version
}
var (
maxVersion int64 = minVersion + 1
count float64
)
for {
if _, err = t.Store.Head(CommitURIFromVersion(maxVersion)); errors.Is(err, storage.ErrObjectDoesNotExist) {
break
} else {
count++
minVersion = maxVersion
maxVersion += int64(math.Pow(count, 2))
}
}
var (
latestVersion int64
currErr error
nextErr error
)
for minVersion <= maxVersion {
latestVersion = (minVersion + maxVersion) / 2
_, currErr = t.Store.Head(CommitURIFromVersion(latestVersion))
_, nextErr = t.Store.Head(CommitURIFromVersion(latestVersion + 1))
if currErr == nil && nextErr != nil {
break
} else if currErr != nil {
maxVersion = latestVersion - 1
} else {
minVersion = latestVersion + 1
}
}
return latestVersion, nil
}
func findValidCommitOrCheckpointURI(metadata []storage.ObjectMeta) (bool, int64) {
for _, m := range metadata {
if IsValidCommitOrCheckpointURI(m.Location) {
parsed, version := CommitVersionFromURI(m.Location)
if !parsed {
continue
}
return true, version
}
}
return false, -1
}
// syncStateStore syncs the table's state store with its latest version.
func (t *Table) syncStateStore() (err error) {
locked, err := t.LockClient.TryLock()
if err != nil {
return errors.Join(lock.ErrLockNotObtained, err)
}
defer func() {
// Defer the unlock and overwrite any errors if the unlock fails.
if unlockErr := t.LockClient.Unlock(); unlockErr != nil {
err = errors.Join(lock.ErrUnableToUnlock, err)
}
}()
if locked {
version, err := t.LatestVersion()
if err != nil {
return errors.Join(errors.New("failed to get latest version"), err)
}
state := state.CommitState{
Version: version,
}
if err := t.StateStore.Put(state); err != nil {
return errors.Join(errors.New("failed to put state"), err)
}
}
return nil
}
// Load loads the table state using the given configuration
func (t *Table) Load(config *OptimizeCheckpointConfiguration) error {
return t.LoadVersionWithConfiguration(nil, config)
}
// LoadVersion loads the table state at the specified version using default configuration options
func (t *Table) LoadVersion(version *int64) error {
return t.LoadVersionWithConfiguration(version, nil)
}
// LoadVersionWithConfiguration loads the table state at the specified version using the given configuration
func (t *Table) LoadVersionWithConfiguration(version *int64, config *OptimizeCheckpointConfiguration) error {
return t.loadVersionWithConfiguration(version, config, true)
}
func (t *Table) loadVersionWithConfiguration(version *int64, config *OptimizeCheckpointConfiguration, cleanupWorkingStorage bool) (returnErr error) {
t.LastCheckPoint = nil
t.State = *NewTableState(-1)
err := setupOnDiskOptimization(config, &t.State, 0)
if err != nil {
return err
}
if cleanupWorkingStorage && t.State.onDiskOptimization {
defer func() {
if err := config.WorkingStore.DeleteFolder(config.WorkingFolder); err != nil {
returnErr = errors.Join(fmt.Errorf("failed to delete folder %s", config.WorkingFolder), err)
}
}()
}
var checkpointLoadError error
if version != nil {
commitURI := CommitURIFromVersion(*version)
_, err := t.Store.Head(commitURI)
if errors.Is(err, storage.ErrObjectDoesNotExist) {
return ErrInvalidVersion
}
if err != nil {
return err
}
}
checkpoints, allReturned, err := t.findLatestCheckpointsForVersion(version)
if err != nil {
return err
}
// Attempt to load the most recent checkpoint; fall back as needed
for {
if len(checkpoints) == 0 {
break
}
// Checkpoints are sorted ascending
checkpointIndex := len(checkpoints) - 1
err = t.restoreCheckpoint(&checkpoints[checkpointIndex], config)
if err == nil {
// We successfully loaded a checkpoint
checkpointLoadError = nil
break
} else {
// Store the checkpoint load error for later in case we can't recover
checkpointLoadError = err
}
if allReturned {
// Pop the last checkpoint
checkpoints = checkpoints[:checkpointIndex]
} else {
// We didn't retrieve all checkpoints, so look for any earlier than the one that just failed
prevVersion := checkpoints[checkpointIndex].Version - 1
if prevVersion > 0 {
checkpoints, allReturned, err = t.findLatestCheckpointsForVersion(&prevVersion)
if err != nil {
return err
}
} else {
break
}
}
}
err = t.updateIncremental(version, config)
if err != nil {
// If we happened to get both a checkpoint read error and an incremental load error, it may be helpful to return both
return errors.Join(err, checkpointLoadError)
}
// If there was no error but we failed to load the specified version, return error indicating that
if version != nil && t.State.Version != *version {
return errors.Join(ErrUnableToLoadVersion, checkpointLoadError)
}
return nil
}
// Find the most recent checkpoint(s) at or before the given version
// If we are returning all checkpoints at or before the version, allReturned will be true, otherwise it will be false
// If we are able to use the _last_checkpoint to retrieve the checkpoint then we will just return that one, and set allReturned to false
// If we need to search through the directory for checkpoints, then allReturned will be true if the listing is ordered and false otherwise
func (t *Table) findLatestCheckpointsForVersion(version *int64) (checkpoints []CheckPoint, allReturned bool, err error) {
// First check if _last_checkpoint exists and is prior to the desired version
var errReadingLastCheckpoint error
path := lastCheckpointPath()
lastCheckpointBytes, err := t.Store.Get(path)
if err == nil {
checkpoint, err := checkpointFromBytes(lastCheckpointBytes)
if err != nil {
// If we were unable to read the _last_checkpoint file, do not return immediately - search for any checkpoint file to try to recover
// Save the error to return if we don't find a fallback checkpoint
errReadingLastCheckpoint = err
} else {
if version == nil || checkpoint.Version <= *version {
return []CheckPoint{*checkpoint}, false, nil
}
}
} else if !errors.Is(err, storage.ErrObjectDoesNotExist) {
return nil, false, err
}
logIterator := storage.NewListIterator(BaseCommitURI(), t.Store)
foundCheckpoints := make([]CheckPoint, 0, 20)
listResultsAreOrdered := t.Store.IsListOrdered()
for {
meta, err := logIterator.Next()
if errors.Is(err, storage.ErrObjectDoesNotExist) {
break
}
if err != nil {
return nil, false, err
}
checkpoint, _, err := checkpointInfoFromURI(storage.NewPath(meta.Location.Raw))
if err != nil {
return nil, false, err
}
if checkpoint != nil {
if version != nil && checkpoint.Version > *version {
// If list results are returned in order, and our search has passed the max version, stop looking
if listResultsAreOrdered {
break
}
continue
}
// For multi-part checkpoint, verify that all parts are present before using it
isCompleteCheckpoint := true
if checkpoint.Parts != nil {
isCompleteCheckpoint, err = DoesCheckpointVersionExist(t.Store, checkpoint.Version, true)
if err != nil && !errors.Is(err, ErrCheckpointIncomplete) && !errors.Is(err, ErrCheckpointInvalidMultipartFileName) {
return nil, false, err
}
}
if !isCompleteCheckpoint {
continue
}
// This checkpoint is valid so save it
foundCheckpoints = append(foundCheckpoints, *checkpoint)
}
// Finally, if list results are ordered, check if this is a regular commit and the version is greater
// than the max version
if listResultsAreOrdered && version != nil {
isCommit, checkpointVersion := CommitVersionFromURI(meta.Location)
if isCommit && checkpointVersion > *version {
break
}
}
}
if len(foundCheckpoints) == 0 && errReadingLastCheckpoint != nil {
// Here, if we had an error reading the _last_checkpoint file and we did not subsequently find an appropriate
// checkpoint file, return the earlier error
return nil, false, errReadingLastCheckpoint
}
// If list results were ordered, then found checkpoints are already ordered. Otherwise sort them.
if !listResultsAreOrdered {
sort.Slice(foundCheckpoints, func(i, j int) bool {
return foundCheckpoints[i].Version < foundCheckpoints[j].Version
})
}
return foundCheckpoints, true, nil
}
// GetCheckpointDataPaths returns the expected file path(s) for the given checkpoint Parquet files
// If it is a multi-part checkpoint then there will be one path for each part
func (t *Table) GetCheckpointDataPaths(checkpoint *CheckPoint) []storage.Path {
paths := make([]storage.Path, 0, 10)
prefix := fmt.Sprintf("%020d", checkpoint.Version)
if checkpoint.Parts == nil {
paths = append(paths, storage.PathFromIter([]string{"_delta_log", prefix + ".checkpoint.parquet"}))
} else {
for i := int32(0); i < *checkpoint.Parts; i++ {
part := fmt.Sprintf("%s.checkpoint.%010d.%010d.parquet", prefix, i+1, *checkpoint.Parts)
paths = append(paths, storage.PathFromIter([]string{"_delta_log", part}))
}
}
return paths
}
// Update the table state from the given checkpoint
func (t *Table) restoreCheckpoint(checkpoint *CheckPoint, config *OptimizeCheckpointConfiguration) error {
state, err := stateFromCheckpoint(t, checkpoint, config)
if err != nil {
return err
}
t.State = *state
return nil
}
// Updates the Table to the latest version by incrementally applying newer versions.
// It assumes that the table is already updated to the current version `self.version`.
// This function does not look for checkpoints
func (t *Table) updateIncremental(maxVersion *int64, config *OptimizeCheckpointConfiguration) error {
for {
if maxVersion != nil && t.State.Version == *maxVersion {
break
}
nextCommitVersion, nextCommitActions, noMoreCommits, err := t.nextCommitDetails()
if err != nil {
return err
}
if noMoreCommits {
break
}
newState, err := NewTableStateFromActions(nextCommitActions, nextCommitVersion)
if err != nil {
return err
}
// TODO configuration option for max rows per part? It is only used for on disk optimization.
err = t.State.merge(newState, 150000, config, false)
if err != nil {
return err
}
}
if t.State.Version == -1 {
return ErrInvalidVersion
}
if t.State.onDiskOptimization {
// We need to do one final "merge" to resolve any remaining adds/removes in our buffer
err := t.State.merge(nil, 150000, config, true)
if err != nil {
return err
}
}
return nil
}
// Get the actions inside the next commit log if it exists and return the next commit's version and its actions
// If the next commit doesn't exist, returns false in the third return parameter
func (t *Table) nextCommitDetails() (int64, []Action, bool, error) {
nextVersion := t.State.Version + 1
nextCommitURI := CommitURIFromVersion(nextVersion)
noMoreCommits := false
transaction := t.CreateTransaction(NewTransactionOptions())
actions, err := transaction.ReadActions(nextCommitURI)
if err != nil {
noMoreCommits = true
err = nil
}
return nextVersion, actions, noMoreCommits, err
}
// CreateCheckpoint creates a checkpoint for this table at the given version
// The existing table state will not be used or modified; a new table instance will be opened at the checkpoint version
// Returns whether the checkpoint was created and any error
// If the lock cannot be obtained, does not retry
func (t *Table) CreateCheckpoint(checkpointLock lock.Locker, checkpointConfiguration *CheckpointConfiguration, version int64) (bool, error) {
return CreateCheckpoint(t.Store, checkpointLock, checkpointConfiguration, version)
}
// CreateCheckpoint creates a checkpoint for a table located at the store for the given version
// If expired log cleanup is enabled on this table, then after a successful checkpoint, run the cleanup to delete expired logs
// Returns whether the checkpoint was created and any error
// If the lock cannot be obtained, does not retry - if other processes are checkpointing there's no need to duplicate the effort
func CreateCheckpoint(store storage.ObjectStore, checkpointLock lock.Locker, checkpointConfiguration *CheckpointConfiguration, version int64) (checkpointed bool, err error) {
// The table doesn't need a commit lock or state store as we are not going to perform any commits
table, err := openTableWithVersionAndConfiguration(store, nil, nil, version, &checkpointConfiguration.ReadWriteConfiguration, false)
if err != nil {
// If the UnsafeIgnoreUnsupportedReaderWriterVersionErrors option is true, we can ignore unsupported version errors
isUnsupportedVersionError := errors.Is(err, ErrUnsupportedReaderVersion) || errors.Is(err, ErrUnsupportedWriterVersion)
if !(isUnsupportedVersionError && checkpointConfiguration.UnsafeIgnoreUnsupportedReaderWriterVersionErrors) {
return false, err
}
}
if table.State.onDiskOptimization {
defer func() {
if deleteErr := checkpointConfiguration.ReadWriteConfiguration.WorkingStore.DeleteFolder(checkpointConfiguration.ReadWriteConfiguration.WorkingFolder); deleteErr != nil {
err = errors.Join(fmt.Errorf("failed to delete folder %s", checkpointConfiguration.ReadWriteConfiguration.WorkingFolder), deleteErr)
}
}()
}
locked, err := checkpointLock.TryLock()
if err != nil {
return false, err
}
if !locked {
// This is unexpected
return false, ErrLockFailed
}
defer func() {
// Defer the unlock and overwrite any errors if unlock fails
if unlockErr := checkpointLock.Unlock(); unlockErr != nil {
log.Debugf("delta-go: Unlock attempt failed. %v", unlockErr)
err = unlockErr
}
}()
err = createCheckpointFor(&table.State, table.Store, checkpointConfiguration)
if err != nil {
return false, err
}
if table.State.ExperimentalEnableExpiredLogCleanup && !checkpointConfiguration.DisableCleanup {
err = validateCheckpointAndCleanup(table, table.Store, version)
if err != nil {
return true, err
}
}
return true, err
}
// Cleanup expired logs before the given checkpoint version, after confirming there is a readable checkpoint
func validateCheckpointAndCleanup(table *Table, store storage.ObjectStore, checkpointVersion int64) error {
// First confirm there is a valid checkpoint at the given version
checkpoints, _, err := table.findLatestCheckpointsForVersion(&checkpointVersion)
if err != nil {
return err
}
if len(checkpoints) == 0 || checkpoints[len(checkpoints)-1].Version != checkpointVersion {
return ErrReadingCheckpoint
}
checkpoint := checkpoints[len(checkpoints)-1]
err = table.restoreCheckpoint(&checkpoint, nil)
if err != nil {
return err
}
if table.State.Version != checkpointVersion {
return ErrReadingCheckpoint
}
// Now remove expired logs before the checkpoint
_, err = removeExpiredLogsAndCheckpoints(checkpointVersion, time.Now().Add(-table.State.LogRetention), store)
return err
}
// TableMetaData represents the metadata of a Delta table.
type TableMetaData struct {
// Unique identifier for this table
ID uuid.UUID
/// User-provided identifier for this table
Name string
/// User-provided description for this table
Description string
/// Specification of the encoding for the files stored in the table
Format Format
/// Schema of the table
Schema Schema
/// An array containing the names of columns by which the data should be partitioned
PartitionColumns []string
/// The time when this metadata action is created, in milliseconds since the Unix epoch
CreatedTime time.Time
/// table properties
Configuration map[string]string
}
// NewTableMetaData creates a new TableMetaData instance.
func NewTableMetaData(name string, description string, format Format, schema Schema, partitionColumns []string, configuration map[string]string) *TableMetaData {
// Reference implementation uses uuid v4 to create GUID:
// https://github.com/delta-io/delta/blob/master/core/src/main/scala/org/apache/spark/sql/delta/actions/actions.scala#L350
metaData := new(TableMetaData)
metaData.ID = uuid.New()
metaData.Name = name
metaData.Description = description
metaData.Format = format
metaData.Schema = schema
metaData.PartitionColumns = partitionColumns
metaData.CreatedTime = time.Now()
metaData.Configuration = configuration
return metaData
}
// toMetaData converts a TableMetaData instance to a MetaData instance.
func (md *TableMetaData) toMetaData() MetaData {
createdTime := md.CreatedTime.UnixMilli()
metadata := MetaData{
ID: md.ID,
IDAsString: md.ID.String(),
Name: &md.Name,
Description: &md.Description,
Format: md.Format,
SchemaString: string(md.Schema.JSON()),
PartitionColumns: md.PartitionColumns,
CreatedTime: &createdTime,
Configuration: md.Configuration,
}
return metadata
}
// Transaction represents a Delta transaction.
// Clients that do not need to mutate action content in case a Transaction conflict is encountered
// may use the `commit` method and rely on optimistic concurrency to determine the
// appropriate Delta version number for a commit. A good example of this type of client is an
// append only client that does not need to maintain Transaction state with external systems.
// Clients that may need to do conflict resolution if the Delta version changes should use
// the `prepare_commit` and `try_commit_transaction` methods and manage the Delta version
// themselves so that they can resolve data conflicts that may occur between Delta versions.
//
// Please not that in case of non-retryable error the temporary commit file such as
// `_delta_log/_commit_<uuid>.json` will orphaned in storage.
type Transaction struct {
Table *Table
Actions []Action
Operation Operation
AppMetadata map[string]any
options TransactionOptions
}
// ReadActions gets actions from a file.
//
// With many concurrent readers/writers, there's a chance that concurrent recovery
// operations occur on the same file, i.e. the same temp file T(N) is copied into the
// target N.json file more than once. Though data loss will *NOT* occur, readers of N.json
// may receive an error from S3 as the ETag of N.json was changed. This is safe to
// retry, so we do so here.
func (t *Transaction) ReadActions(path storage.Path) ([]Action, error) {
var (
entry []byte
err error
attempt = 0
)
for {
if attempt >= int(t.options.MaxRetryReadAttempts) {
return nil, errors.Join(fmt.Errorf("failed to get actions after %d attempts", t.options.MaxRetryReadAttempts), err)
}
entry, err = t.Table.Store.Get(path)
if err != nil {
attempt++
log.Debugf("delta-go: Attempt number %d: failed to get log entry. %v", attempt, err)
continue
}
actions, err := ActionsFromLogEntries(entry)
if err != nil {
attempt++
log.Debugf("delta-go: Attempt number %d: failed to get actions from log entry. %v", attempt, err)
continue
}
return actions, nil
}
}
// CommitLogStore writes actions to a file.
//
// To commit for Delta version N:
// - Step 0: Fail if N.json already exists in the file system.
// - Step 1: Ensure that N-1.json exists. If not, perform a recovery.
// - Step 2: PREPARE the commit.
// - Write the actions into temp file T(N).
// - Write uncompleted commit entry E(N, T(N)) with mutual exclusion to the log store.
//
// - Step 3: COMMIT the commit to the Delta log.
// - Copy T(N) into N.json.
//
// - Step 4: ACKNOWLEDGE the commit.
// - Overwrite and complete commit entry E in the log store.
func (t *Transaction) CommitLogStore() (int64, error) {
var (
version int64
err error
attempt = 0
)
for {
if attempt >= int(t.options.MaxRetryWriteAttempts) {
return -1, errors.Join(fmt.Errorf("failed to commit with log store after %d attempts", t.options.MaxRetryWriteAttempts), err)
}
version, err = t.tryCommitLogStore()
if errors.Is(err, ErrFailedToCopyTempFile) || errors.Is(err, ErrFailedToAcknowledgeCommit) {
return version, err
} else if err != nil {
attempt++
log.Debugf("delta-go: Attempt number %d: failed to commit with log store. %v", attempt, err)
time.Sleep(t.options.RetryWaitDuration)
continue
}
return version, nil
}
}
func (t *Transaction) tryCommitLogStore() (version int64, err error) {
var currURI storage.Path
prevURI, err := t.Table.LogStore.Latest(t.Table.Store.BaseURI())
if errors.Is(err, logstore.ErrLatestDoesNotExist) {
if version, err := t.Table.LatestVersion(); err == nil {
var (
uri = CommitURIFromVersion(version).Raw
fileName = storage.NewPath(strings.Split(uri, "_delta_log/")[1])
seconds = t.Table.LogStore.ExpirationDelaySeconds()
)
entry := logstore.New(t.Table.Store.BaseURI(), fileName,
storage.NewPath("") /* tempPath */, true /* isComplete */, uint64(time.Now().Unix())+seconds)
if err := t.Table.LogStore.Put(entry, false); err != nil {
return -1, errors.Join(errors.New("failed to put first commit entry"), err)
}
log.WithFields(log.Fields{"tablePath": t.Table.Store.BaseURI().Raw, "fileName": fileName.Raw}).
Infof("delta-go: Put completed commit entry in empty log store")
currURI = CommitURIFromVersion(version + 1)
} else if errors.Is(err, ErrNotATable) {
currURI = CommitURIFromVersion(0)
} else {
return -1, errors.Join(fmt.Errorf("failed to determine if table %s exists", t.Table.Store.BaseURI().Raw), err)
}
} else if err != nil {
return -1, errors.Join(errors.New("failed to get latest log store entry"), err)
} else {
parsed, prevVersion := CommitVersionFromURI(prevURI.FileName())
if !parsed {
return -1, fmt.Errorf("failed to parse previous version from %s", prevURI.FileName().Raw)
}
currURI = CommitURIFromVersion(prevVersion + 1)
}
t.addCommitInfoIfNotPresent()
// Prevent concurrent writers from checking if N-1.json exists and performing a recovery
// where they all copy T(N-1) into N-1.json. Note that the mutual exclusion on writing
// into N.json from different machines is provided by the log store, not by this lock.
// Also note that this lock is for N.json, while the lock used during a recovery is for
// N-1.json. Thus, there is no deadlock.
versionLock, err := t.Table.LockClient.NewLock(t.Table.Store.BaseURI().Join(currURI).Raw)
if err != nil {
return -1, errors.Join(errors.New("failed to create lock"), err)
}
if _, err = versionLock.TryLock(); err != nil {
return -1, errors.Join(lock.ErrLockNotObtained, err)
}
defer func() {
// Defer the unlock and overwrite any errors if the unlock fails.
if unlockErr := versionLock.Unlock(); unlockErr != nil {
err = unlockErr
}
}()
fileName := storage.NewPath(strings.Split(currURI.Raw, "_delta_log/")[1])
parsed, currVersion := CommitVersionFromURI(currURI)
if !parsed {
return -1, fmt.Errorf("failed to parse previous version from %s", currURI.Raw)
}
// Step 0: Fail if N.json already exists in the file system.
if _, err = t.Table.Store.Head(currURI); err == nil {
return -1, errors.New("current version already exists")
}
// Step 1: Ensure that N-1.json exists.
if currVersion > 0 {
prevFileName := storage.NewPath(strings.Split(CommitURIFromVersion(currVersion-1).Raw, "_delta_log/")[1])
if prevEntry, err := t.Table.LogStore.Get(t.Table.Store.BaseURI(), prevFileName); err != nil {
return -1, errors.Join(errors.New("failed to get previous commit"), err)