Skip to content

Commit 6291fc9

Browse files
authored
Merge pull request #22331 from karalabe/enforce-min-snap-difflayers
core/state/snapshot: ensure Cap retains a min number of layers
2 parents 915c614 + 9ec3329 commit 6291fc9

2 files changed

Lines changed: 65 additions & 93 deletions

File tree

‎core/state/snapshot/snapshot.go‎

Lines changed: 16 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,12 @@ func (t *Tree) Update(blockRoot common.Hash, parentRoot common.Hash, destructs m
300300
// Cap traverses downwards the snapshot tree from a head block hash until the
301301
// number of allowed layers are crossed. All layers beyond the permitted number
302302
// are flattened downwards.
303+
//
304+
// Note, the final diff layer count in general will be one more than the amount
305+
// requested. This happens because the bottom-most diff layer is the accumulator
306+
// which may or may not overflow and cascade to disk. Since this last layer's
307+
// survival is only known *after* capping, we need to omit it from the count if
308+
// we want to ensure that *at least* the requested number of diff layers remain.
303309
func (t *Tree) Cap(root common.Hash, layers int) error {
304310
// Retrieve the head snapshot to cap from
305311
snap := t.Snapshot(root)
@@ -324,10 +330,7 @@ func (t *Tree) Cap(root common.Hash, layers int) error {
324330
// Flattening the bottom-most diff layer requires special casing since there's
325331
// no child to rewire to the grandparent. In that case we can fake a temporary
326332
// child for the capping and then remove it.
327-
var persisted *diskLayer
328-
329-
switch layers {
330-
case 0:
333+
if layers == 0 {
331334
// If full commit was requested, flatten the diffs and merge onto disk
332335
diff.lock.RLock()
333336
base := diffToDisk(diff.flatten().(*diffLayer))
@@ -336,33 +339,9 @@ func (t *Tree) Cap(root common.Hash, layers int) error {
336339
// Replace the entire snapshot tree with the flat base
337340
t.layers = map[common.Hash]snapshot{base.root: base}
338341
return nil
339-
340-
case 1:
341-
// If full flattening was requested, flatten the diffs but only merge if the
342-
// memory limit was reached
343-
var (
344-
bottom *diffLayer
345-
base *diskLayer
346-
)
347-
diff.lock.RLock()
348-
bottom = diff.flatten().(*diffLayer)
349-
if bottom.memory >= aggregatorMemoryLimit {
350-
base = diffToDisk(bottom)
351-
}
352-
diff.lock.RUnlock()
353-
354-
// If all diff layers were removed, replace the entire snapshot tree
355-
if base != nil {
356-
t.layers = map[common.Hash]snapshot{base.root: base}
357-
return nil
358-
}
359-
// Merge the new aggregated layer into the snapshot tree, clean stales below
360-
t.layers[bottom.root] = bottom
361-
362-
default:
363-
// Many layers requested to be retained, cap normally
364-
persisted = t.cap(diff, layers)
365342
}
343+
persisted := t.cap(diff, layers)
344+
366345
// Remove any layer that is stale or links into a stale layer
367346
children := make(map[common.Hash][]common.Hash)
368347
for root, snap := range t.layers {
@@ -405,9 +384,15 @@ func (t *Tree) Cap(root common.Hash, layers int) error {
405384
// layer limit is reached, memory cap is also enforced (but not before).
406385
//
407386
// The method returns the new disk layer if diffs were persisted into it.
387+
//
388+
// Note, the final diff layer count in general will be one more than the amount
389+
// requested. This happens because the bottom-most diff layer is the accumulator
390+
// which may or may not overflow and cascade to disk. Since this last layer's
391+
// survival is only known *after* capping, we need to omit it from the count if
392+
// we want to ensure that *at least* the requested number of diff layers remain.
408393
func (t *Tree) cap(diff *diffLayer, layers int) *diskLayer {
409394
// Dive until we run out of layers or reach the persistent database
410-
for ; layers > 2; layers-- {
395+
for i := 0; i < layers-1; i++ {
411396
// If we still have diff layers below, continue down
412397
if parent, ok := diff.parent.(*diffLayer); ok {
413398
diff = parent

‎core/state/snapshot/snapshot_test.go‎

Lines changed: 49 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -162,57 +162,10 @@ func TestDiskLayerExternalInvalidationPartialFlatten(t *testing.T) {
162162
defer func(memcap uint64) { aggregatorMemoryLimit = memcap }(aggregatorMemoryLimit)
163163
aggregatorMemoryLimit = 0
164164

165-
if err := snaps.Cap(common.HexToHash("0x03"), 2); err != nil {
166-
t.Fatalf("failed to merge diff layer onto disk: %v", err)
167-
}
168-
// Since the base layer was modified, ensure that data retrievald on the external reference fail
169-
if acc, err := ref.Account(common.HexToHash("0x01")); err != ErrSnapshotStale {
170-
t.Errorf("stale reference returned account: %#x (err: %v)", acc, err)
171-
}
172-
if slot, err := ref.Storage(common.HexToHash("0xa1"), common.HexToHash("0xb1")); err != ErrSnapshotStale {
173-
t.Errorf("stale reference returned storage slot: %#x (err: %v)", slot, err)
174-
}
175-
if n := len(snaps.layers); n != 2 {
176-
t.Errorf("post-cap layer count mismatch: have %d, want %d", n, 2)
177-
fmt.Println(snaps.layers)
178-
}
179-
}
180-
181-
// Tests that if a diff layer becomes stale, no active external references will
182-
// be returned with junk data. This version of the test flattens every diff layer
183-
// to check internal corner case around the bottom-most memory accumulator.
184-
func TestDiffLayerExternalInvalidationFullFlatten(t *testing.T) {
185-
// Create an empty base layer and a snapshot tree out of it
186-
base := &diskLayer{
187-
diskdb: rawdb.NewMemoryDatabase(),
188-
root: common.HexToHash("0x01"),
189-
cache: fastcache.New(1024 * 500),
190-
}
191-
snaps := &Tree{
192-
layers: map[common.Hash]snapshot{
193-
base.root: base,
194-
},
195-
}
196-
// Commit two diffs on top and retrieve a reference to the bottommost
197-
accounts := map[common.Hash][]byte{
198-
common.HexToHash("0xa1"): randomAccount(),
199-
}
200-
if err := snaps.Update(common.HexToHash("0x02"), common.HexToHash("0x01"), nil, accounts, nil); err != nil {
201-
t.Fatalf("failed to create a diff layer: %v", err)
202-
}
203-
if err := snaps.Update(common.HexToHash("0x03"), common.HexToHash("0x02"), nil, accounts, nil); err != nil {
204-
t.Fatalf("failed to create a diff layer: %v", err)
205-
}
206-
if n := len(snaps.layers); n != 3 {
207-
t.Errorf("pre-cap layer count mismatch: have %d, want %d", n, 3)
208-
}
209-
ref := snaps.Snapshot(common.HexToHash("0x02"))
210-
211-
// Flatten the diff layer into the bottom accumulator
212165
if err := snaps.Cap(common.HexToHash("0x03"), 1); err != nil {
213-
t.Fatalf("failed to flatten diff layer into accumulator: %v", err)
166+
t.Fatalf("failed to merge accumulator onto disk: %v", err)
214167
}
215-
// Since the accumulator diff layer was modified, ensure that data retrievald on the external reference fail
168+
// Since the base layer was modified, ensure that data retrievald on the external reference fail
216169
if acc, err := ref.Account(common.HexToHash("0x01")); err != ErrSnapshotStale {
217170
t.Errorf("stale reference returned account: %#x (err: %v)", acc, err)
218171
}
@@ -267,7 +220,7 @@ func TestDiffLayerExternalInvalidationPartialFlatten(t *testing.T) {
267220
t.Errorf("layers modified, got %d exp %d", got, exp)
268221
}
269222
// Flatten the diff layer into the bottom accumulator
270-
if err := snaps.Cap(common.HexToHash("0x04"), 2); err != nil {
223+
if err := snaps.Cap(common.HexToHash("0x04"), 1); err != nil {
271224
t.Fatalf("failed to flatten diff layer into accumulator: %v", err)
272225
}
273226
// Since the accumulator diff layer was modified, ensure that data retrievald on the external reference fail
@@ -389,25 +342,24 @@ func TestSnaphots(t *testing.T) {
389342
// Create a starting base layer and a snapshot tree out of it
390343
base := &diskLayer{
391344
diskdb: rawdb.NewMemoryDatabase(),
392-
root: common.HexToHash("0x01"),
345+
root: makeRoot(1),
393346
cache: fastcache.New(1024 * 500),
394347
}
395348
snaps := &Tree{
396349
layers: map[common.Hash]snapshot{
397350
base.root: base,
398351
},
399352
}
400-
// Construct the snapshots with 128 layers
353+
// Construct the snapshots with 129 layers, flattening whatever's above that
401354
var (
402355
last = common.HexToHash("0x01")
403356
head common.Hash
404357
)
405-
// Flush another 128 layers, one diff will be flatten into the parent.
406-
for i := 0; i < 128; i++ {
358+
for i := 0; i < 129; i++ {
407359
head = makeRoot(uint64(i + 2))
408360
snaps.Update(head, last, nil, setAccount(fmt.Sprintf("%d", i+2)), nil)
409361
last = head
410-
snaps.Cap(head, 128) // 129 layers(128 diffs + 1 disk) are allowed, 129th is the persistent layer
362+
snaps.Cap(head, 128) // 130 layers (128 diffs + 1 accumulator + 1 disk)
411363
}
412364
var cases = []struct {
413365
headRoot common.Hash
@@ -417,22 +369,57 @@ func TestSnaphots(t *testing.T) {
417369
expectBottom common.Hash
418370
}{
419371
{head, 0, false, 0, common.Hash{}},
420-
{head, 64, false, 64, makeRoot(127 + 2 - 63)},
421-
{head, 128, false, 128, makeRoot(2)}, // All diff layers
422-
{head, 129, true, 128, makeRoot(2)}, // All diff layers
423-
{head, 129, false, 129, common.HexToHash("0x01")}, // All diff layers + disk layer
372+
{head, 64, false, 64, makeRoot(129 + 2 - 64)},
373+
{head, 128, false, 128, makeRoot(3)}, // Normal diff layers, no accumulator
374+
{head, 129, true, 129, makeRoot(2)}, // All diff layers, including accumulator
375+
{head, 130, false, 130, makeRoot(1)}, // All diff layers + disk layer
376+
}
377+
for i, c := range cases {
378+
layers := snaps.Snapshots(c.headRoot, c.limit, c.nodisk)
379+
if len(layers) != c.expected {
380+
t.Errorf("non-overflow test %d: returned snapshot layers are mismatched, want %v, got %v", i, c.expected, len(layers))
381+
}
382+
if len(layers) == 0 {
383+
continue
384+
}
385+
bottommost := layers[len(layers)-1]
386+
if bottommost.Root() != c.expectBottom {
387+
t.Errorf("non-overflow test %d: snapshot mismatch, want %v, get %v", i, c.expectBottom, bottommost.Root())
388+
}
389+
}
390+
// Above we've tested the normal capping, which leaves the accumulator live.
391+
// Test that if the bottommost accumulator diff layer overflows the allowed
392+
// memory limit, the snapshot tree gets capped to one less layer.
393+
// Commit the diff layer onto the disk and ensure it's persisted
394+
defer func(memcap uint64) { aggregatorMemoryLimit = memcap }(aggregatorMemoryLimit)
395+
aggregatorMemoryLimit = 0
396+
397+
snaps.Cap(head, 128) // 129 (128 diffs + 1 overflown accumulator + 1 disk)
398+
399+
cases = []struct {
400+
headRoot common.Hash
401+
limit int
402+
nodisk bool
403+
expected int
404+
expectBottom common.Hash
405+
}{
406+
{head, 0, false, 0, common.Hash{}},
407+
{head, 64, false, 64, makeRoot(129 + 2 - 64)},
408+
{head, 128, false, 128, makeRoot(3)}, // All diff layers, accumulator was flattened
409+
{head, 129, true, 128, makeRoot(3)}, // All diff layers, accumulator was flattened
410+
{head, 130, false, 129, makeRoot(2)}, // All diff layers + disk layer
424411
}
425-
for _, c := range cases {
412+
for i, c := range cases {
426413
layers := snaps.Snapshots(c.headRoot, c.limit, c.nodisk)
427414
if len(layers) != c.expected {
428-
t.Fatalf("Returned snapshot layers are mismatched, want %v, got %v", c.expected, len(layers))
415+
t.Errorf("overflow test %d: returned snapshot layers are mismatched, want %v, got %v", i, c.expected, len(layers))
429416
}
430417
if len(layers) == 0 {
431418
continue
432419
}
433420
bottommost := layers[len(layers)-1]
434421
if bottommost.Root() != c.expectBottom {
435-
t.Fatalf("Snapshot mismatch, want %v, get %v", c.expectBottom, bottommost.Root())
422+
t.Errorf("overflow test %d: snapshot mismatch, want %v, get %v", i, c.expectBottom, bottommost.Root())
436423
}
437424
}
438425
}

0 commit comments

Comments
 (0)