-
Notifications
You must be signed in to change notification settings - Fork 175
/
table.go
533 lines (444 loc) · 15.1 KB
/
table.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
package derived
import (
"fmt"
"sync"
"github.com/hashicorp/go-multierror"
"github.com/onflow/flow-go/fvm/storage/errors"
"github.com/onflow/flow-go/fvm/storage/logical"
"github.com/onflow/flow-go/fvm/storage/snapshot"
"github.com/onflow/flow-go/fvm/storage/state"
)
// ValueComputer is used by DerivedDataTable's GetOrCompute to compute the
// derived value when the value is not in DerivedDataTable (i.e., "cache miss").
type ValueComputer[TKey any, TVal any] interface {
Compute(txnState state.NestedTransactionPreparer, key TKey) (TVal, error)
}
type invalidatableEntry[TVal any] struct {
Value TVal // immutable after initialization.
ExecutionSnapshot *snapshot.ExecutionSnapshot // immutable after initialization.
isInvalid bool // Guarded by DerivedDataTable' lock.
}
// DerivedDataTable is a rudimentary fork-aware OCC database table for
// "caching" homogeneous (TKey, TVal) pairs for a particular block.
//
// The database table enforces atomicity and isolation, but not consistency and
// durability. Consistency depends on the user correctly implementing the
// table's invalidator. Durability is not needed since the values are derived
// from ledger and can be computed on the fly (This assumes that recomputation
// is idempotent).
//
// Furthermore, because data are derived, transaction validation looks
// a bit unusual when compared with a textbook OCC implementation. In
// particular, the transaction's invalidator represents "real" writes to the
// canonical source, whereas the transaction's readSet/writeSet entries
// represent "real" reads from the canonical source.
//
// Multiple tables are grouped together via Validate/Commit 2 phase commit to
// form the complete derived data database.
type DerivedDataTable[TKey comparable, TVal any] struct {
lock sync.RWMutex
items map[TKey]*invalidatableEntry[TVal]
latestCommitExecutionTime logical.Time
invalidators chainedTableInvalidators[TKey, TVal] // Guarded by lock.
}
type TableTransaction[TKey comparable, TVal any] struct {
table *DerivedDataTable[TKey, TVal]
// The start time when the snapshot first becomes readable (i.e., the
// "snapshotTime - 1"'s transaction committed the snapshot view).
snapshotTime logical.Time
// The transaction (or script)'s execution start time (aka TxIndex).
executionTime logical.Time
// toValidateTime is used to amortize cost of repeated Validate calls.
// Each Validate call will only validate the time range
// [toValidateTime, executionTime), and will advance toValidateTime to
// latestCommitExecutionTime + 1 if Validate succeeded.
//
// Note that since newly derived values are computed based on snapshotTime's
// view, each time a newly derived value is added to the transaction,
// toValidateTime is reset back to snapshotTime.
toValidateTime logical.Time
readSet map[TKey]*invalidatableEntry[TVal]
writeSet map[TKey]*invalidatableEntry[TVal]
// When isSnapshotReadTransaction is true, invalidators must be empty.
isSnapshotReadTransaction bool
invalidators chainedTableInvalidators[TKey, TVal]
// ignoreLatestCommitExecutionTime is used to bypass latestCommitExecutionTime checks during
// commit. This is used when operating in caching mode with scripts since "commits" are all done
// at the end of the block and are not expected to progress the execution time.
ignoreLatestCommitExecutionTime bool
}
func NewEmptyTable[
TKey comparable,
TVal any,
](
initialSnapshotTime logical.Time,
) *DerivedDataTable[TKey, TVal] {
return &DerivedDataTable[TKey, TVal]{
items: map[TKey]*invalidatableEntry[TVal]{},
latestCommitExecutionTime: initialSnapshotTime - 1,
invalidators: nil,
}
}
func (table *DerivedDataTable[TKey, TVal]) NewChildTable() *DerivedDataTable[TKey, TVal] {
table.lock.RLock()
defer table.lock.RUnlock()
items := make(
map[TKey]*invalidatableEntry[TVal],
len(table.items))
for key, entry := range table.items {
// Note: We need to deep copy the invalidatableEntry here since the
// entry may be valid in the parent table, but invalid in the child
// table.
items[key] = &invalidatableEntry[TVal]{
Value: entry.Value,
ExecutionSnapshot: entry.ExecutionSnapshot,
isInvalid: false,
}
}
return &DerivedDataTable[TKey, TVal]{
items: items,
latestCommitExecutionTime: logical.ParentBlockTime,
invalidators: nil,
}
}
func (table *DerivedDataTable[TKey, TVal]) NextTxIndexForTestingOnly() uint32 {
return uint32(table.LatestCommitExecutionTimeForTestingOnly()) + 1
}
func (table *DerivedDataTable[TKey, TVal]) LatestCommitExecutionTimeForTestingOnly() logical.Time {
table.lock.RLock()
defer table.lock.RUnlock()
return table.latestCommitExecutionTime
}
func (table *DerivedDataTable[TKey, TVal]) EntriesForTestingOnly() map[TKey]*invalidatableEntry[TVal] {
table.lock.RLock()
defer table.lock.RUnlock()
entries := make(
map[TKey]*invalidatableEntry[TVal],
len(table.items))
for key, entry := range table.items {
entries[key] = entry
}
return entries
}
func (table *DerivedDataTable[TKey, TVal]) InvalidatorsForTestingOnly() chainedTableInvalidators[TKey, TVal] {
table.lock.RLock()
defer table.lock.RUnlock()
return table.invalidators
}
func (table *DerivedDataTable[TKey, TVal]) GetForTestingOnly(
key TKey,
) *invalidatableEntry[TVal] {
return table.get(key)
}
func (table *DerivedDataTable[TKey, TVal]) get(
key TKey,
) *invalidatableEntry[TVal] {
table.lock.RLock()
defer table.lock.RUnlock()
return table.items[key]
}
func (table *DerivedDataTable[TKey, TVal]) unsafeValidate(
txn *TableTransaction[TKey, TVal],
) error {
if txn.isSnapshotReadTransaction &&
txn.invalidators.ShouldInvalidateEntries() {
return fmt.Errorf(
"invalid TableTransaction: snapshot read can't invalidate")
}
if table.latestCommitExecutionTime >= txn.executionTime {
return fmt.Errorf(
"invalid TableTransaction: non-increasing time (%v >= %v)",
table.latestCommitExecutionTime,
txn.executionTime)
}
for _, entry := range txn.readSet {
if entry.isInvalid {
if txn.snapshotTime == txn.executionTime {
// This should never happen since the transaction is
// sequentially executed.
return fmt.Errorf(
"invalid TableTransaction: unrecoverable outdated read set")
}
return errors.NewRetryableConflictError(
"invalid TableTransaction: outdated read set")
}
}
applicable := table.invalidators.ApplicableInvalidators(
txn.toValidateTime)
shouldInvalidateEntries := applicable.ShouldInvalidateEntries()
for key, entry := range txn.writeSet {
current, ok := table.items[key]
if ok && current != entry {
// The derived data table must always return the same item for a given key,
// otherwise the cadence runtime will have issues comparing resolved cadence types.
//
// for example:
// two transactions are run concurrently, first loads (cadence contracts)
// A and B where B depends on A. The second transaction also loads A and C,
// where C depends on A. The first transaction commits first.
// The A from the second transaction is equivalent to the A from
// the first transaction but it is not the same object.
//
// Overwriting A with the A from the second transaction will cause program B
// to break because it will not know the types from A returned from
// the cache in the future.
// Not overwriting A will cause program C to break because it will not know
// the types from A returned from the cache in the future.
//
// The solution is to treat this as a conflict and retry the transaction.
// When the transaction is retried, the A from the first transaction will
// be used to load C in the second transaction.
return errors.NewRetryableConflictError(
"invalid TableTransaction: write conflict")
}
if !shouldInvalidateEntries ||
!applicable.ShouldInvalidateEntry(
key,
entry.Value,
entry.ExecutionSnapshot,
) {
continue
}
if txn.snapshotTime == txn.executionTime {
// This should never happen since the transaction is
// sequentially executed.
return fmt.Errorf(
"invalid TableTransaction: unrecoverable outdated " +
"write set")
}
return errors.NewRetryableConflictError(
"invalid TableTransaction: outdated write set")
}
txn.toValidateTime = table.latestCommitExecutionTime + 1
return nil
}
func (table *DerivedDataTable[TKey, TVal]) validate(
txn *TableTransaction[TKey, TVal],
) error {
table.lock.RLock()
defer table.lock.RUnlock()
return table.unsafeValidate(txn)
}
func (table *DerivedDataTable[TKey, TVal]) commit(
txn *TableTransaction[TKey, TVal],
) error {
table.lock.Lock()
defer table.lock.Unlock()
if !txn.isSnapshotReadTransaction &&
!txn.ignoreLatestCommitExecutionTime &&
table.latestCommitExecutionTime+1 < txn.snapshotTime {
return fmt.Errorf(
"invalid TableTransaction: missing commit range [%v, %v)",
table.latestCommitExecutionTime+1,
txn.snapshotTime)
}
// NOTE: Instead of throwing out all the write entries, we can commit
// the valid write entries then return error.
err := table.unsafeValidate(txn)
if err != nil {
return err
}
// Don't perform actual commit for snapshot read transaction. This is
// safe since all values are derived from the primary source.
if txn.isSnapshotReadTransaction {
return nil
}
for key, entry := range txn.writeSet {
_, ok := table.items[key]
if ok {
// A previous transaction already committed an equivalent
// TableTransaction entry. Since both TableTransaction entry are
// valid, just reuse the existing one for future transactions.
continue
}
table.items[key] = entry
}
if txn.invalidators.ShouldInvalidateEntries() {
for key, entry := range table.items {
if txn.invalidators.ShouldInvalidateEntry(
key,
entry.Value,
entry.ExecutionSnapshot) {
entry.isInvalid = true
delete(table.items, key)
}
}
table.invalidators = append(
table.invalidators,
txn.invalidators...)
}
table.latestCommitExecutionTime = txn.executionTime
return nil
}
func (table *DerivedDataTable[TKey, TVal]) newTableTransaction(
snapshotTime logical.Time,
executionTime logical.Time,
isSnapshotReadTransaction bool,
ignoreLatestCommitExecutionTime bool,
) *TableTransaction[TKey, TVal] {
return &TableTransaction[TKey, TVal]{
table: table,
snapshotTime: snapshotTime,
executionTime: executionTime,
toValidateTime: snapshotTime,
readSet: map[TKey]*invalidatableEntry[TVal]{},
writeSet: map[TKey]*invalidatableEntry[TVal]{},
isSnapshotReadTransaction: isSnapshotReadTransaction,
ignoreLatestCommitExecutionTime: ignoreLatestCommitExecutionTime,
}
}
func (table *DerivedDataTable[TKey, TVal]) NewSnapshotReadTableTransaction() *TableTransaction[TKey, TVal] {
return table.newTableTransaction(
logical.EndOfBlockExecutionTime,
logical.EndOfBlockExecutionTime,
true,
false)
}
func (table *DerivedDataTable[TKey, TVal]) NewCachingSnapshotReadTableTransaction() *TableTransaction[TKey, TVal] {
return table.newTableTransaction(
logical.EndOfBlockExecutionTime,
logical.EndOfBlockExecutionTime,
false,
true)
}
func (table *DerivedDataTable[TKey, TVal]) NewTableTransaction(
snapshotTime logical.Time,
executionTime logical.Time,
) (
*TableTransaction[TKey, TVal],
error,
) {
if executionTime < 0 ||
executionTime > logical.LargestNormalTransactionExecutionTime {
return nil, fmt.Errorf(
"invalid TableTransactions: execution time out of bound: %v",
executionTime)
}
if snapshotTime > executionTime {
return nil, fmt.Errorf(
"invalid TableTransactions: snapshot > execution: %v > %v",
snapshotTime,
executionTime)
}
return table.newTableTransaction(
snapshotTime,
executionTime,
false,
false), nil
}
// Note: use GetOrCompute instead of Get/Set whenever possible.
func (txn *TableTransaction[TKey, TVal]) get(key TKey) (
TVal,
*snapshot.ExecutionSnapshot,
bool,
) {
writeEntry, ok := txn.writeSet[key]
if ok {
return writeEntry.Value, writeEntry.ExecutionSnapshot, true
}
readEntry := txn.readSet[key]
if readEntry != nil {
return readEntry.Value, readEntry.ExecutionSnapshot, true
}
readEntry = txn.table.get(key)
if readEntry != nil {
txn.readSet[key] = readEntry
return readEntry.Value, readEntry.ExecutionSnapshot, true
}
var defaultValue TVal
return defaultValue, nil, false
}
func (txn *TableTransaction[TKey, TVal]) GetForTestingOnly(key TKey) (
TVal,
*snapshot.ExecutionSnapshot,
bool,
) {
return txn.get(key)
}
func (txn *TableTransaction[TKey, TVal]) set(
key TKey,
value TVal,
snapshot *snapshot.ExecutionSnapshot,
) {
txn.writeSet[key] = &invalidatableEntry[TVal]{
Value: value,
ExecutionSnapshot: snapshot,
isInvalid: false,
}
// Since value is derived from snapshot's view. We need to reset the
// toValidateTime back to snapshot time to re-validate the entry.
txn.toValidateTime = txn.snapshotTime
}
func (txn *TableTransaction[TKey, TVal]) SetForTestingOnly(
key TKey,
value TVal,
snapshot *snapshot.ExecutionSnapshot,
) {
txn.set(key, value, snapshot)
}
// GetOrCompute returns the key's value. If a pre-computed value is available,
// then the pre-computed value is returned and the cached state is replayed on
// txnState. Otherwise, the value is computed using valFunc; both the value
// and the states used to compute the value are captured.
//
// Note: valFunc must be an idempotent function and it must not modify
// txnState's values.
func (txn *TableTransaction[TKey, TVal]) GetOrCompute(
txnState state.NestedTransactionPreparer,
key TKey,
computer ValueComputer[TKey, TVal],
) (
TVal,
error,
) {
var defaultVal TVal
val, state, ok := txn.get(key)
if ok {
err := txnState.AttachAndCommitNestedTransaction(state)
if err != nil {
return defaultVal, fmt.Errorf(
"failed to replay cached state: %w",
err)
}
return val, nil
}
nestedTxId, err := txnState.BeginNestedTransaction()
if err != nil {
return defaultVal, fmt.Errorf("failed to start nested txn: %w", err)
}
val, err = computer.Compute(txnState, key)
// Commit the nested transaction, even if the computation fails.
committedState, commitErr := txnState.CommitNestedTransaction(nestedTxId)
if commitErr != nil {
err = multierror.Append(err,
fmt.Errorf("failed to commit nested txn: %w", commitErr),
).ErrorOrNil()
}
if err != nil {
return defaultVal, fmt.Errorf("failed to derive value: %w", err)
}
txn.set(key, val, committedState)
return val, nil
}
func (txn *TableTransaction[TKey, TVal]) AddInvalidator(
invalidator TableInvalidator[TKey, TVal],
) {
if invalidator == nil || !invalidator.ShouldInvalidateEntries() {
return
}
txn.invalidators = append(
txn.invalidators,
tableInvalidatorAtTime[TKey, TVal]{
TableInvalidator: invalidator,
executionTime: txn.executionTime,
})
}
func (txn *TableTransaction[TKey, TVal]) Validate() error {
return txn.table.validate(txn)
}
func (txn *TableTransaction[TKey, TVal]) Commit() error {
return txn.table.commit(txn)
}
func (txn *TableTransaction[TKey, TVal]) ToValidateTimeForTestingOnly() logical.Time {
return txn.toValidateTime
}