Skip to content
Open
19 changes: 18 additions & 1 deletion src/Nethermind/Nethermind.Db/FlatDbConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,23 @@ namespace Nethermind.Db;

public class FlatDbConfig : IFlatDbConfig
{
/// <summary>
/// EIP-8252 REORG_RETENTION_WINDOW: 262144 blocks = 8192 epochs x 32 slots = 2^18 (~36.4 days at
/// 12s slots). This is the retention horizon EIP-8252 chooses, not a hard cap on stall duration: it
/// covers leak-driven non-finality up to ~79% initial offline stake (ln(2f/(1-f))=2); a larger offline
/// share can take longer to recover and is expected to rely on external sync. Nethermind borrows the
/// number as the default long-finality force-persist backstop depth: the deepest non-finality span the
/// persisted-snapshot tier keeps reconstructable before forcing a persist to bound memory. The forced
/// fold defers rather than advancing the base past the window floor (head - W; see PersistenceManager),
/// so every in-window post-state — including the last finalized block's, which a reorg may fork at —
/// stays reconstructable to within one CompactSize of persist timing. A positive MaxInMemorySnapshotBytes
/// (byte pressure) can still shorten the window, and CompactSize=1 disables finalized folds. Under
/// healthy finality state folds toward the finalized boundary as usual; this only bounds how deep the
/// retained span may
/// grow while finality is stuck.
/// </summary>
public const ulong ReorgRetentionWindow = 262_144;

public bool Enabled { get; set; } = true;
public FlatDbOnRepair OnRepair { get; set; } = FlatDbOnRepair.Resync;
public bool HistoryEnabled { get; set; } = false;
Expand Down Expand Up @@ -61,7 +78,7 @@ public class FlatDbConfig : IFlatDbConfig
public ulong TrieCacheMemoryBudget { get; set; } = 512UL.MiB;
public ulong CompressedNodeRecordBufferMemoryBudget { get; set; } = 500UL.MiB;
public bool EnableLongFinality { get; set; } = true;
public ulong LongFinalityMaxReorgDepth { get; set; } = 90000;
public ulong LongFinalityMaxReorgDepth { get; set; } = ReorgRetentionWindow;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] The higher default lets payload validation discard the forkchoice-selected head’s state without a forkchoice change. With finality stalled at persisted base B and the selected head at B+100,000, the old backstop would already have folded past B, so NewPayloadHandler.ShouldProcessBlock could not execute a competing child of B. The new default retains B and lets that branch execute. EthereumMerge leaves the block-tree head unchanged, but FlatDbManager.AddSnapshot records each newly committed payload as the last committed state. If the competing branch reaches B+262,145 while forkchoice still selects the original head, ForcedPersistSeed follows the competing tip. FindSnapshotToPersist only checks for a conflicting finalized root at the fold endpoint, which is above B. RemoveSiblingAndDescendents then drops the selected branch’s snapshots if the branches have different state roots there, leaving the node unable to execute the next child of its selected head locally. Use the forkchoice-selected head for the depth and seed, and verify the fold endpoint lies on its ancestry before pruning. EIP-3675, Fork choice rule

public int MaxInMemoryBaseSnapshotCount { get; set; } = 160;
public long ArenaFileSizeBytes { get; set; } = 1.GiB;
public long PersistedSnapshotDedicatedArenaThresholdBytes { get; set; } = 1.GiB;
Expand Down
4 changes: 2 additions & 2 deletions src/Nethermind/Nethermind.Db/IFlatDbConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public interface IFlatDbConfig : IConfig
[ConfigItem(Description = "Fixed compaction schedule offset in blocks. When 0 or greater, overrides the per-instance offset in the metadata DB, which is neither read nor updated. Only the value modulo CompactSize matters. -1 to use the stored offset, generating a random one when absent.", DefaultValue = "-1")]
long CompactionOffset { get; set; }

[ConfigItem(Description = "Compact size", DefaultValue = "32")]
[ConfigItem(Description = "Number of blocks folded into the persisted base per RocksDB compaction step. CompactSize=1 makes NextFullCompactionAfter return ulong.MaxValue, disabling finalized-driven folds even while finality advances, so the retained snapshot span (and disk use) grows well beyond the finality-stall case and the force-persist backstop then drives all folds.", DefaultValue = "32")]
ulong CompactSize { get; set; }

[ConfigItem(Description = "Whether a fresh state sync uses the flat-state DB backend, and whether ImportFromPruningTrieState is honored. A node that already has a patricia-trie state DB keeps using it regardless of this setting; set to false to sync a fresh node on the patricia-trie backend instead.", DefaultValue = "true")]
Expand Down Expand Up @@ -162,7 +162,7 @@ public interface IFlatDbConfig : IConfig
[ConfigItem(Description = "Enable long finality support with persisted snapshots", DefaultValue = "true")]
bool EnableLongFinality { get; set; }

[ConfigItem(Description = "Force-persist backstop used when EnableLongFinality is on, in place of MaxReorgDepth. The persisted-snapshot tier serves deep reorgs, so this is much larger than the non-long-finality backstop.", DefaultValue = "90000")]
[ConfigItem(Description = "Force-persist backstop used when EnableLongFinality is on, in place of MaxReorgDepth. The persisted-snapshot tier serves deep reorgs down to this depth, so this is much larger than the non-long-finality backstop. The default is the EIP-8252 REORG_RETENTION_WINDOW (262144 blocks = 8192 epochs x 32 slots = 2^18, ~36.4 days): the retention horizon EIP-8252 chooses, covering leak-driven non-finality up to ~79% initial offline stake, not a hard cap on stall duration. During a finality stall the node keeps post-state reconstructable back toward where finality was lost, up to this many blocks, without sync; under healthy finality state still folds toward the finalized boundary, so this only bounds how deep the retained span grows while finality is stuck. The forced fold defers rather than advancing the base past the window floor (head - this depth), so every in-window post-state — including the last finalized block's, which a reorg may fork at — stays reconstructable to within one CompactSize of persist timing. A positive MaxInMemorySnapshotBytes (byte pressure) can still shorten the window, and CompactSize=1 disables finalized folds. Operators may override it; EnableLongFinality=false drops to the smaller in-memory MaxReorgDepth backstop and opts out of EIP-8252 retention. Only the flat-state store honours this window; nodes still on the legacy patricia-trie pruning store keep the configurable Pruning.PruningBoundary (default 64, floored at a 64-block minimum and raised well above it by many shipped configs, e.g. 256 or 4096) and gain nothing from this setting.", DefaultValue = "262144")]
ulong LongFinalityMaxReorgDepth { get; set; }

[ConfigItem(Description = "Maximum number of in-memory base snapshots before conversion to the persisted-snapshot tier kicks in. Counted as `SnapshotCount` of the in-memory repository, not a block-distance depth. Sized as a ~128 target plus one CompactSize of headroom, since a bulk (CompactSize-wide) conversion drops the in-memory count by up to CompactSize at a boundary — so the tier still retains ~128 base snapshots after each conversion.", DefaultValue = "160")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -648,7 +648,14 @@ public void Configuration_DefaultValues()
{
Assert.That(config.EnableLongFinality, Is.True);
Assert.That(config.MaxReorgDepth, Is.EqualTo(256));
Assert.That(config.LongFinalityMaxReorgDepth, Is.EqualTo(90000));
// EIP-8252: the default long-finality backstop borrows the REORG_RETENTION_WINDOW number. It
// caps how deep the retained span may grow while finality is stalled — the inactivity-leak bound
// on non-finality — rather than being an always-on retention target. Under healthy finality state
// still folds toward the finalized boundary as usual, which EIP-8252 permits.
Assert.That(config.LongFinalityMaxReorgDepth, Is.EqualTo(262144));
Assert.That(config.LongFinalityMaxReorgDepth, Is.EqualTo(FlatDbConfig.ReorgRetentionWindow));
Assert.That(config.LongFinalityMaxReorgDepth, Is.EqualTo(8192UL * 32),
"EIP-8252 REORG_RETENTION_WINDOW must equal 8192 epochs x 32 slots");
Assert.That(config.ArenaFileSizeBytes, Is.EqualTo(1L * 1024 * 1024 * 1024));
}
}
Expand Down
125 changes: 119 additions & 6 deletions src/Nethermind/Nethermind.State.Flat.Test/PersistenceManagerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -722,10 +722,13 @@ public void DetermineSnapshotAction_BackstopExceeded_SeedsFromInMemoryTier()
}

// With MinReorgDepth >= the configured backstop, the effective backstop is raised to
// MinReorgDepth + CompactSize, so a depth just past the configured 90000 does NOT force-persist,
// but one past MinReorgDepth + CompactSize does.
// MinReorgDepth + CompactSize (90016). A depth just past the configured 90000 does NOT force-persist.
// Past the effective backstop a CompactSize fold still force-persists only once the window floor has
// reached the chunk boundary (head >= backstop + CompactSize = 90032); between the backstop and that
// boundary the fold would overshoot the floor (pruning in-window state) and is deferred.
[TestCase(90001, false, TestName = "DetermineSnapshotAction_BackstopRaised_BelowMinPlusCompactSize_NoForce")]
[TestCase(90000 + 16 + 1, true, TestName = "DetermineSnapshotAction_BackstopRaised_AboveMinPlusCompactSize_Forces")]
[TestCase(90017, false, TestName = "DetermineSnapshotAction_BackstopRaised_PastBackstop_ChunkOvershoot_Deferred")]
[TestCase(90032, true, TestName = "DetermineSnapshotAction_BackstopRaised_FloorAtChunkBoundary_Forces")]
public void DetermineSnapshotAction_BackstopRaisedAboveMinReorgDepth(int latestBlock, bool expectForcedPersist)
{
// MinReorgDepth == configured backstop == 90000, CompactSize 16 → effective backstop 90016.
Expand Down Expand Up @@ -762,6 +765,115 @@ public void DetermineSnapshotAction_BackstopRaisedAboveMinReorgDepth(int latestB
toPersist?.Dispose();
}

// EIP-8252: under the default long-finality config the force-persist backstop depth IS the
// REORG_RETENTION_WINDOW. MinReorgDepth + CompactSize (128 + 32) stays far below it, so the effective
// backstop is the window itself (the strict `>` in DetermineSnapshotAction): a depth equal to the
// window does not force-persist. Past the window a CompactSize fold would advance the base ahead of the
// window floor (head - window) and prune state still inside the window, so it is deferred until the
// floor reaches the chunk boundary (head >= window + CompactSize); only then does it force-persist.
[TestCase(0UL, false, TestName = "DetermineSnapshotAction_BackstopAtRetentionWindow_AtWindow_NoForce")]
[TestCase(1UL, false, TestName = "DetermineSnapshotAction_BackstopAtRetentionWindow_PastWindow_ChunkOvershoot_Deferred")]
[TestCase(32UL, true, TestName = "DetermineSnapshotAction_BackstopAtRetentionWindow_FloorAtChunkBoundary_Forces")]
public void DetermineSnapshotAction_BackstopUsesReorgRetentionWindow(ulong pastWindow, bool expectForcedPersist)
{
FlatDbConfig config = new()
{
CompactSize = 32,
MinReorgDepth = 128,
MaxReorgDepth = 256,
LongFinalityMaxReorgDepth = FlatDbConfig.ReorgRetentionWindow,
EnableLongFinality = true,
MaxInMemoryBaseSnapshotCount = 160,
};
using PersistenceManager pm = new(
config,
ScheduleHelper.CreateWithOffset(config, 0),
_finalizedStateProvider,
_persistence,
_snapshotRepository,
NullStatePersistenceBarrier.Instance,
LimboLogs.Instance,
_persistedSnapshotCompactor,
_tier.Loader,
Substitute.For<IProcessExitSource>());

// Finalized far below the next boundary so only the backstop (not the finalized trigger) can fire;
// a registered base at tierTip gives FindSnapshotToPersist a candidate to return.
StateId tierTip = CreateStateId(config.CompactSize);
using Snapshot expected = CreateSnapshot(Block0, tierTip, compacted: false);
_finalizedStateProvider.SetFinalizedBlockNumber(5);

// The persisted base sits at Block0, so snapshotsDepth == the latest block number.
(_, Snapshot? toPersist, _) = pm.DetermineSnapshotAction(CreateStateId(FlatDbConfig.ReorgRetentionWindow + pastWindow));

Assert.That(toPersist is not null, Is.EqualTo(expectForcedPersist));
toPersist?.Dispose();
}

// Under a finality stall the clamp must keep every in-window block reconstructable, not just gate whether
// a persist fires. Without it the forced fold moves the base up to CompactSize past the window floor and
// prunes the oldest in-window blocks. Drive the persist and check the fork point survives.
[Test]
public async Task AddToPersistence_ForcedFoldAcrossWindowFloor_KeepsInWindowForkPointReadable()
{
FlatDbConfig config = new()
{
CompactSize = 32,
MinReorgDepth = 128,
MaxReorgDepth = 256,
LongFinalityMaxReorgDepth = FlatDbConfig.ReorgRetentionWindow,
EnableLongFinality = true,
MaxInMemoryBaseSnapshotCount = 160,
};
using PersistenceManager pm = new(
config,
ScheduleHelper.CreateWithOffset(config, 0),
_finalizedStateProvider,
_persistence,
_snapshotRepository,
NullStatePersistenceBarrier.Instance,
LimboLogs.Instance,
_persistedSnapshotCompactor,
_tier.Loader,
Substitute.For<IProcessExitSource>());

ulong window = FlatDbConfig.ReorgRetentionWindow;

// Base snapshots for blocks 1..CompactSize, a compacted edge over them (the fold picked first), then a
// compacted snapshot to head = window + 1, one block past the backstop where the forced persist fires.
List<Snapshot> leases = [];
List<StateId> canonical = [Block0];
for (ulong b = 1; b <= config.CompactSize; b++)
{
StateId s = CreateStateId(b);
leases.Add(CreateSnapshot(canonical[^1], s));
canonical.Add(s);
}
leases.Add(CreateSnapshot(Block0, canonical[^1], compacted: true));
StateId head = CreateStateId(window + 1);
leases.Add(CreateSnapshot(canonical[^1], head, compacted: true));
_snapshotRepository.SetLastCommittedStateId(head);
_finalizedStateProvider.SetFinalizedBlockNumber(0); // finality stalled: the window, not finality, bounds retention

await pm.AddToPersistence(head);

ulong windowLow = head.BlockNumber - window; // == 1: the oldest block the window must retain
StateId persistedBase = pm.GetCurrentPersistedStateId();

using (Assert.EnterMultipleScope())
{
// Base stayed at or below the floor...
Assert.That(persistedBase.BlockNumber, Is.LessThanOrEqualTo(windowLow),
"forced fold advanced the persisted base past the window floor");
// ...and every in-window block stays reconstructable.
for (ulong b = windowLow; b <= config.CompactSize; b++)
Assert.That(_snapshotRepository.HasState(canonical[(int)b]), Is.True,
$"post-state of in-window block {b} was pruned");
}

foreach (Snapshot s in leases) s.Dispose();
}

[TestCase(0UL, 40UL, false, TestName = "DetermineSnapshotAction_ByteBudgetDisabled_FinalizedBelowFloor_ReturnsNull")]
[TestCase(1UL, 40UL, false, TestName = "DetermineSnapshotAction_OverByteBudget_FinalizedBelowFloor_ReturnsNull")]
[TestCase(1UL, 79UL, false, TestName = "DetermineSnapshotAction_OverByteBudget_FinalizedOneBelowFloor_ReturnsNull")]
Expand Down Expand Up @@ -956,13 +1068,14 @@ public void DetermineSnapshotAction_FinalizedGatePassesButSeedMissing_BackstopSt
Substitute.For<IProcessExitSource>());

// Finalized at/above the next boundary so the finalized branch IS entered, but leave
// GetFinalizedHeader(16) unset so its seed resolves to null. Depth (90017) exceeds the
// effective backstop (MinReorgDepth + CompactSize = 90016), so the backstop must persist.
// GetFinalizedHeader(16) unset so its seed resolves to null. Depth (90032) exceeds the effective
// backstop (MinReorgDepth + CompactSize = 90016), and the window floor has reached the CompactSize
// boundary (90032 - 90016 = 16 = tierTip) so the fold does not overshoot it — the backstop persists.
StateId tierTip = CreateStateId(config.CompactSize);
using Snapshot expected = CreateSnapshot(Block0, tierTip, compacted: false);
_finalizedStateProvider.SetFinalizedBlockNumber(90000);

(_, Snapshot? toPersist, PersistenceManager.ConversionCandidate? toConvert) = pm.DetermineSnapshotAction(CreateStateId(90017));
(_, Snapshot? toPersist, PersistenceManager.ConversionCandidate? toConvert) = pm.DetermineSnapshotAction(CreateStateId(90032));

Assert.That(toPersist, Is.Not.Null, "Backstop must force a persist even when the finalized branch ran but found no seed");
using (Assert.EnterMultipleScope())
Expand Down
Loading
Loading