--- a/core/blockchain/blockchain.go +++ b/core/blockchain/blockchain.go @@ -186,7 +186,11 @@ upgradeCacheMu sync.Mutex upgradeTipID uint upgradeWindows map[string]upgradeWindowCache + upgradeBlockMeta map[uint]upgradeSignalBlockMeta upgradeRebuildMu sync.Mutex + // upgradeMarkerNudgeLayer is the last main-tip layer at which a steady-forward + // marker refresh was attempted (see maybeNudgeUpgradeMarkerForward). Perf only. + upgradeMarkerNudgeLayer atomic.Uint64 no24hCheck bool } --- a/core/blockchain/process.go +++ b/core/blockchain/process.go @@ -664,6 +664,11 @@ } if reorgOccurred && !finalUpgradeMarkerRefreshed { b.RebuildUpgradesFromHeadersIfNeeded("reorg") + } else if !reorgOccurred && isMainChainTipChange { + // Steady forward progress: keep the rebuild marker fresh so it does not go + // stale across voting-window boundaries and force a full rescan at the next + // restart. Cheap, rate-limited, and never touches the consensus tally. + b.maybeNudgeUpgradeMarkerForward() } if connectedBlocks.Len() > 0 { start := time.Now() --- a/core/blockchain/upgrades.go +++ b/core/blockchain/upgrades.go @@ -37,6 +37,29 @@ tally upgradeSignalTally } +// upgradeSignalBlockMeta memoizes the immutable per-block data the signalling +// walk re-reads for every ProcessBlock. A block's layer, selected (main) parent, +// and header version are fixed once it is in the DAG (only the virtual block's +// main-parent moves, and the walk never visits it), so a block-id-keyed memo is +// always valid. It removes the pebble header+block reads that a live CPU profile +// (2026-11-21) measured as ~96% of per-block accept time during a backlog replay +// -- time spent holding ChainLock, which also starved getTemplateHealth. The +// tally produced is byte-identical to the uncached walk. +type upgradeSignalBlockMeta struct { + layer uint64 + mainParent uint + version uint32 + hasHeader bool +} + +// upgradeBlockMetaCacheCap bounds the memo. It MUST exceed the largest signalling +// window so a single countUpgradeSignalsInRange walk never overflows (which would +// clear the cache mid-walk and defeat the memo). The largest window is +// MainnetDAOStakingV2's 100_000 layers; this holds that plus slide headroom. +// Entries never go stale, so clearing on overflow only costs re-reads, never +// correctness. +const upgradeBlockMetaCacheCap = 1 << 19 + // upgradeRebuildStateVersion is bumped when the persisted rebuild marker no // longer proves that the current tally algorithm has scanned historical votes. const upgradeRebuildStateVersion uint64 = 2 @@ -45,6 +68,30 @@ // proof failure deliberately falls back to the historical rebuild. const finalUpgradeReconcileMaxParents = 8192 +// upgradeMarkerSettleSteps anchors the rebuild marker this many main-parent steps +// BELOW the tip (on a settled ancestor) so shallow head reorgs no longer move the +// marker off the main chain -- the next marker refresh's ancestry proof then succeeds +// instead of falling back to a full historical rebuild. The anchor never crosses a +// voting-window boundary (see settledUpgradeMarkerTip), so the completed-window +// checkpoint -- and therefore the consensus tally -- is unchanged. +const upgradeMarkerSettleSteps = 128 + +// upgradeMarkerAncestryMaxSteps bounds the marker ancestry proof independently of the +// shared finalUpgradeReconcileMaxParents reorg budget. After a fast catch-up the settled +// marker can sit tens of thousands of layers below the tip; the shared 8192 budget would +// be exhausted mid-walk and bail to a needless full rescan. +const upgradeMarkerAncestryMaxSteps = 1 << 20 + +// upgradeMarkerForwardNudgeLayers is how far the main tip advances, on steady +// forward progress with no reorg, before we attempt a cheap marker refresh. The +// marker is otherwise advanced only on reorgs and long peer-syncs, so a node +// mining steadily at tip let it go stale across voting-window boundaries -- then +// the next restart paid a full historical rescan. Nudging bounds that staleness +// so the boot path takes the cheap no-op or the bounded replay instead. This +// value only trades marker freshness against a periodic cheap refresh; it never +// affects the consensus tally. +const upgradeMarkerForwardNudgeLayers = 2048 + type upgradeRebuildState struct { Version uint64 TipID uint64 @@ -84,9 +131,19 @@ } type upgradeRebuildScanState struct { - def upgradeRebuildDefinition - result upgradeRebuildResult - relevant bool + def upgradeRebuildDefinition + result upgradeRebuildResult + relevant bool + // minWindowIndex is the lowest voting-window index this state should tally. + // Zero for a full historical scan (every window from StartLayer). The bounded + // rebuild sets it to the count of windows the persisted marker has already + // certified complete, so the walk re-derives ONLY the windows that completed + // since the marker and trusts the immutable persisted result for everything + // below. Windows below minWindowIndex are skipped in record(); because a + // not-yet-locked-in upgrade's pre-marker windows provably never reached + // threshold (persisted clean + ancestor-proven immutable), seeding the state + // clean at minWindowIndex yields a byte-identical result to the full scan. + minWindowIndex uint64 initialized bool windowIndex uint64 windowStart uint64 @@ -279,7 +336,11 @@ } func (b *BlockChain) upgradeMainParent(block blockdag.IBlock, steps *uint64) (blockdag.IBlock, bool) { - if block == nil || *steps >= finalUpgradeReconcileMaxParents || block.GetMainParent() == blockdag.MaxId { + return b.upgradeMainParentWithCap(block, steps, finalUpgradeReconcileMaxParents) +} + +func (b *BlockChain) upgradeMainParentWithCap(block blockdag.IBlock, steps *uint64, maxSteps uint64) (blockdag.IBlock, bool) { + if block == nil || *steps >= maxSteps || block.GetMainParent() == blockdag.MaxId { return nil, false } *steps++ @@ -290,7 +351,14 @@ return parent, true } -func (b *BlockChain) upgradeMarkerTipIsAncestor(marker upgradeRebuildState, tip blockdag.IBlock, steps *uint64) bool { +// upgradeMarkerTipIsAncestor walks the main-chain parents of tip looking for the marker +// block. It uses its OWN larger traversal budget (upgradeMarkerAncestryMaxSteps), +// independent of the shared reorg-walk budget, and short-circuits once it drops below the +// marker layer -- so a settled marker far below a freshly caught-up tip is still proven an +// ancestor instead of bailing to a full rescan. Bounded by the layer short-circuit, the +// height-monotonicity check in upgradeMainParentWithCap, and the step cap. +func (b *BlockChain) upgradeMarkerTipIsAncestor(marker upgradeRebuildState, tip blockdag.IBlock) bool { + ancestrySteps := uint64(0) for current := tip; current != nil; { if uint64(current.GetID()) == marker.TipID { return upgradeRebuildTipMatches(current, marker) @@ -298,7 +366,7 @@ if uint64(current.GetLayer()) < marker.TipLayer { return false } - next, ok := b.upgradeMainParent(current, steps) + next, ok := b.upgradeMainParentWithCap(current, &ancestrySteps, upgradeMarkerAncestryMaxSteps) if !ok { return false } @@ -378,7 +446,7 @@ steps := uint64(0) if previousTip != nil { changedFrom, ok := b.selectedParentReorgChangedFrom(previousTip, currentTip, &steps) - if !ok || !b.upgradeMarkerTipIsAncestor(*marker, previousTip, &steps) { + if !ok || !b.upgradeMarkerTipIsAncestor(*marker, previousTip) { return false } for _, def := range definitions { @@ -387,13 +455,13 @@ return false } } - } else if !b.upgradeMarkerTipIsAncestor(*marker, currentTip, &steps) { + } else if !b.upgradeMarkerTipIsAncestor(*marker, currentTip) { return false } storedResults := make([]upgradeRebuildResult, 0, len(definitions)) for _, def := range definitions { state, exists, loadErr := b.loadPersistedUpgradeState(def.Name) - if loadErr != nil || !exists || !state.Active || !state.LockedIn || !state.AnchorSet { + if loadErr != nil || !exists { return false } storedCompleted := upgradeCompletedVotingWindows(marker.TipLayer, def) @@ -401,9 +469,40 @@ if expectedCompleted < storedCompleted { return false } + persisted := upgradeResultFromState(def.Name, state) + + // A not-yet-locked-in upgrade (e.g. a fork still inside its signalling + // window, like MainnetDAOStakingV2) can only change state when a voting + // window COMPLETES -- lock-in is applied at window boundaries, in + // applyUpgradeWindowResult. So if no new window completed between the + // marker tip and the current tip (expectedCompleted == storedCompleted), + // its persisted pre-lock-in state is still authoritative and the marker + // can be advanced without replaying headers. If a window did complete in + // that gap we cannot prove the outcome cheaply, so we fall back to the + // full historical rebuild. + // + // Without this branch, the presence of a single not-locked-in upgrade + // forced EVERY marker refresh into a full floor rescan each time an + // unrelated always-on upgrade ticked its 2000-layer window (~20 min) -- + // the v0.1.2 regression that perpetually stalled template production on + // slower nodes. Consensus results are unchanged; only the redundant + // rescan is skipped. + if !state.LockedIn { + if state.Active || state.AnchorSet || state.ActivateAnchor != 0 || state.ThresholdAt != 0 { + return false + } + if expectedCompleted != storedCompleted { + return false + } + storedResults = append(storedResults, persisted) + continue + } + + if !state.Active || !state.AnchorSet { + return false + } atStored, validateErr := upgradeForwardBaseResult(state, def, storedCompleted, storedCompleted, marker.TipLayer) atCurrent, currentErr := upgradeForwardBaseResult(state, def, storedCompleted, expectedCompleted, uint64(currentTip.GetLayer())) - persisted := upgradeResultFromState(def.Name, state) if validateErr != nil || currentErr != nil || !atStored.Active || !atCurrent.Active || atStored != persisted || atCurrent != persisted { return false } @@ -413,11 +512,204 @@ if currentErr != nil || !upgradeRebuildResultsEqual(storedResults, currentResults) { return false } - if err := b.persistUpgradeRebuildState(b.newUpgradeRebuildState(currentTip)); err != nil { + markerTip := b.settledUpgradeMarkerTip(currentTip) + if err := b.persistUpgradeRebuildState(b.newUpgradeRebuildState(markerTip)); err != nil { + return false + } + b.resetUpgradeCache() + l.Info("upgrade rebuild final-state marker refreshed", "tip_id", markerTip.GetID(), "tip_layer", markerTip.GetLayer(), "head_layer", currentTip.GetLayer(), "upgrades", len(definitions)) + return true +} + +// boundedUpgradePlan is the per-upgrade decision the bounded rebuild makes from +// the persisted marker + persisted upgrade state, WITHOUT reading headers. +type boundedUpgradePlan struct { + def upgradeRebuildDefinition + replay bool // re-tally this upgrade's newly-completed windows + minWindowIndex uint64 // first window to replay (windows the marker certified) + result upgradeRebuildResult // used when replay == false +} + +// planBoundedUpgradeRebuild decides, for one upgrade, whether the bounded rebuild +// can trust the persisted state (and how) or must fall back to the full scan. It +// reads no headers, so it is deterministic and unit-testable. ok == false means +// "cannot do this cheaply; fall back to the full historical rebuild". +// +// It mirrors the per-definition reasoning in tryRefreshFinalUpgradeRebuildStateHeld: +// - a not-locked-in upgrade with no newly-completed window keeps its clean +// persisted result (the case that function already accepts); +// - a not-locked-in upgrade WITH newly-completed windows is replayed from the +// marker's completed-window count (the case that function bails on -> full +// scan today); the bounded rebuild re-derives exactly those windows; +// - a locked-in, active upgrade is carried forward via upgradeForwardBaseResult +// with no replay (immutable going forward), validated identically. +func planBoundedUpgradeRebuild(def upgradeRebuildDefinition, markerLayer, tipLayer uint64, state upgradeState, stateExists bool) (boundedUpgradePlan, bool) { + if !stateExists { + return boundedUpgradePlan{}, false + } + storedCompleted := upgradeCompletedVotingWindows(markerLayer, def) + expectedCompleted := upgradeCompletedVotingWindows(tipLayer, def) + if expectedCompleted < storedCompleted { + return boundedUpgradePlan{}, false + } + persisted := upgradeResultFromState(def.Name, state) + + if !state.LockedIn { + // A clean not-locked-in state must carry no activation metadata. + if state.Active || state.AnchorSet || state.ActivateAnchor != 0 || state.ThresholdAt != 0 { + return boundedUpgradePlan{}, false + } + if expectedCompleted == storedCompleted { + // No voting window completed since the marker: the persisted clean + // result is still authoritative (identical to tryRefresh's accept). + return boundedUpgradePlan{def: def, replay: false, result: persisted}, true + } + // New window(s) completed. Re-derive ONLY them, seeding the scan state + // clean (= the persisted not-locked-in result), starting at the first + // un-certified window. Pre-marker windows provably never reached threshold + // (persisted clean) and are immutable (ancestor-proven), so skipping them + // is byte-identical to the full scan. + return boundedUpgradePlan{def: def, replay: true, minWindowIndex: storedCompleted}, true + } + + // Locked-in: carry forward without replay, exactly as tryRefresh validates. + if !state.Active || !state.AnchorSet { + return boundedUpgradePlan{}, false + } + atStored, storedErr := upgradeForwardBaseResult(state, def, storedCompleted, storedCompleted, markerLayer) + atCurrent, currentErr := upgradeForwardBaseResult(state, def, storedCompleted, expectedCompleted, tipLayer) + if storedErr != nil || currentErr != nil || !atStored.Active || !atCurrent.Active || atStored != persisted || atCurrent != persisted { + return boundedUpgradePlan{}, false + } + return boundedUpgradePlan{def: def, replay: false, result: persisted}, true +} + +// boundedUpgradeScanState builds a scan state that re-tallies an upgrade starting +// at its first un-certified voting window. The seed result is clean, which equals +// the persisted not-locked-in result the bounded path has already validated. +func boundedUpgradeScanState(def upgradeRebuildDefinition, minWindowIndex uint64) upgradeRebuildScanState { + return upgradeRebuildScanState{ + def: def, + result: upgradeRebuildResult{Name: def.Name}, + relevant: true, + minWindowIndex: minWindowIndex, + } +} + +// tryBoundedUpgradeRebuildHeld handles the one case tryRefreshFinalUpgradeRebuildStateHeld +// bails on: a not-yet-locked-in upgrade whose voting window(s) completed since the +// persisted marker. Instead of the full minStart..tip rescan (~3M layers for a +// fork that started millions of layers ago, the overnight restart/reorg freeze), +// it replays ONLY the windows that completed since the marker -- bounded by the +// marker's staleness, at most a couple of WindowSizes when the marker is kept +// fresh. Completed windows below the marker are trusted from the persisted +// per-upgrade state, which is safe ONLY because the marker is proven an ancestor +// of the current tip (no reorg crossed the certified region). Any uncertainty +// returns false for the unchanged full rebuild. Caller holds upgradeRebuildMu. +func (b *BlockChain) tryBoundedUpgradeRebuildHeld() bool { + currentTip := b.bd.GetMainChainTip() + if currentTip == nil { + return false + } + marker, found, err := b.loadUpgradeRebuildState() + if err != nil || !found || marker.Version != upgradeRebuildStateVersion || marker.DefinitionsHash != upgradeDefinitionsHash() { + return false + } + // The marker must be an ancestor of the current tip. This is the whole safety + // basis: it proves no reorg rewrote any completed window at or below the + // marker, so every persisted completed-window result the bounded path trusts + // is immutable. A deep reorg that crossed the marker fails here -> full scan. + if !b.upgradeMarkerTipIsAncestor(*marker, currentTip) { + return false + } + definitions := currentUpgradeRebuildDefinitions() + tipLayer := uint64(currentTip.GetLayer()) + + plans := make([]boundedUpgradePlan, 0, len(definitions)) + replayStates := make([]upgradeRebuildScanState, 0, len(definitions)) + for _, def := range definitions { + state, exists, loadErr := b.loadPersistedUpgradeState(def.Name) + if loadErr != nil { + return false + } + plan, ok := planBoundedUpgradeRebuild(def, marker.TipLayer, tipLayer, state, exists) + if !ok { + return false + } + plans = append(plans, plan) + if plan.replay { + replayStates = append(replayStates, boundedUpgradeScanState(def, plan.minWindowIndex)) + } + } + if len(replayStates) == 0 { + // Nothing completed since the marker -> tryRefreshFinalUpgradeRebuildStateHeld + // already owns this (and ran before us). Decline rather than rewrite the marker. + return false + } + + replayResults, complete := b.rebuildUpgradeResultsFromHeaders(currentTip, tipLayer, replayStates) + if !complete { + return false + } + replayByName := make(map[string]upgradeRebuildResult, len(replayResults)) + for _, r := range replayResults { + replayByName[r.Name] = r + } + + merged := make([]upgradeRebuildResult, 0, len(plans)) + for _, plan := range plans { + if !plan.replay { + merged = append(merged, plan.result) + continue + } + r, ok := replayByName[plan.def.Name] + if !ok { + return false + } + // Defensive: the replay seeds clean and may only ADD a lock-in; it must + // never emit activation metadata without LockedIn. applyUpgradeWindowResult + // guarantees this; assert it so a future change cannot silently violate it. + if !r.LockedIn && (r.Active || r.AnchorSet || r.ActivateAnchor != 0 || r.ThresholdAt != 0) { + return false + } + merged = append(merged, r) + } + + // Commit exactly as rebuildUpgradesFromHeadersLocked's tail does: update the + // in-memory definitions, persist each per-upgrade state, then advance the + // marker to a settled ancestor and reset the window cache. + persistOK := true + for _, result := range merged { + var snapshot upgrades.UpgradeDefinition + upgrades.UpdateUpgrade(result.Name, func(u *upgrades.UpgradeDefinition) { + u.Active = result.Active + u.LockedIn = result.LockedIn + u.AnchorSet = result.AnchorSet + u.ActivateAnchor = result.ActivateAnchor + u.ThresholdAt = result.ThresholdAt + snapshot = *u + }) + if err := b.persistUpgradeState(result.Name, &snapshot); err != nil { + l.Warn("failed to persist bounded rebuild upgrade state", "name", result.Name, "err", err) + persistOK = false + } + } + if !persistOK { + return false + } + markerTip := b.settledUpgradeMarkerTip(currentTip) + if err := b.persistUpgradeRebuildState(b.newUpgradeRebuildState(markerTip)); err != nil { + l.Warn("failed to persist bounded rebuild marker", "err", err) return false } b.resetUpgradeCache() - l.Info("upgrade rebuild final-state marker refreshed", "tip_id", currentTip.GetID(), "tip_layer", currentTip.GetLayer(), "upgrades", len(definitions)) + l.Info("upgrade rebuild bounded replay completed", + "marker_tip_layer", marker.TipLayer, + "head_layer", tipLayer, + "new_marker_layer", markerTip.GetLayer(), + "replayed_upgrades", len(replayStates), + "upgrades", len(definitions), + ) return true } @@ -523,6 +815,35 @@ return true } +// settledUpgradeMarkerTip returns the deepest ancestor of tip -- up to +// upgradeMarkerSettleSteps main-parent steps back -- that is still in the SAME +// completed-voting-window phase as tip. Anchoring the rebuild marker there keeps it on +// the main chain across shallow head reorgs. Because the ancestor shares tip's window +// checkpoint (upgradeRebuildCheckpointMatches), no voting window completed in the gap, so +// the just-validated persisted tally is equally correct AS-OF the ancestor and the stored +// checkpoint is byte-identical -- consensus is unchanged. At a window boundary the walk +// stops early (possibly at tip itself), preserving correctness over reorg-resilience. +func (b *BlockChain) settledUpgradeMarkerTip(tip blockdag.IBlock) blockdag.IBlock { + if tip == nil { + return tip + } + definitions := currentUpgradeRebuildDefinitions() + tipLayer := uint64(tip.GetLayer()) + settled := tip + steps := uint64(0) + for i := 0; i < upgradeMarkerSettleSteps; i++ { + parent, ok := b.upgradeMainParent(settled, &steps) + if !ok { + break + } + if !upgradeRebuildCheckpointMatches(uint64(parent.GetLayer()), tipLayer, definitions) { + break + } + settled = parent + } + return settled +} + func upgradeRebuildCheckpoint(layer uint64, definitions []upgradeRebuildDefinition) string { parts := make([]string, 0, len(definitions)) for _, def := range definitions { @@ -595,6 +916,12 @@ if b.tryRefreshFinalUpgradeRebuildStateHeld(nil) { return } + // Before the full minStart..tip rescan, try the bounded replay of only the + // windows that completed since the persisted marker. Falls through to the full + // scan on any uncertainty. + if b.tryBoundedUpgradeRebuildHeld() { + return + } b.rebuildUpgradesFromHeadersLocked() } @@ -649,6 +976,12 @@ if b.tryRefreshFinalUpgradeRebuildStateHeld(nil) { return } + // Before the full minStart..tip rescan, try the bounded replay of only the + // windows that completed since the persisted marker. Falls through to the full + // scan on any uncertainty. + if b.tryBoundedUpgradeRebuildHeld() { + return + } b.rebuildUpgradesFromHeadersLocked() } @@ -686,7 +1019,8 @@ }) } - results, complete := b.rebuildUpgradeResultsFromHeaders(tip, now, definitions) + states := newUpgradeRebuildScanStates(now, definitions) + results, complete := b.rebuildUpgradeResultsFromHeaders(tip, now, states) persistOK := true for _, result := range results { @@ -707,7 +1041,10 @@ } if complete && persistOK { - if err := b.persistUpgradeRebuildState(state); err != nil { + // Anchor the marker on a settled ancestor (same voting-window phase as the + // scanned tip) so a shallow head reorg does not immediately invalidate it. + markerTip := b.settledUpgradeMarkerTip(tip) + if err := b.persistUpgradeRebuildState(b.newUpgradeRebuildState(markerTip)); err != nil { l.Warn("failed to persist upgrade rebuild marker", "err", err) } } else if !complete { @@ -769,9 +1106,15 @@ return next, found } -func (b *BlockChain) rebuildUpgradeResultsFromHeaders(tip blockdag.IBlock, now uint64, definitions []upgradeRebuildDefinition) ([]upgradeRebuildResult, bool) { - states := newUpgradeRebuildScanStates(now, definitions) - if tip == nil || len(definitions) == 0 { +// rebuildUpgradeResultsFromHeaders walks the main-parent chain from tip down to +// the lowest window floor implied by the provided scan states, tallying each +// relevant state's complete voting windows. Callers pass fully-formed states: +// newUpgradeRebuildScanStates for a full historical scan (every window), or +// bounded states (minWindowIndex set) for the bounded rebuild. The walk, the +// upgradeBlockMeta memo, and the ReadBlockById detached read are identical in +// both cases; only the floor and the per-state minWindowIndex differ. +func (b *BlockChain) rebuildUpgradeResultsFromHeaders(tip blockdag.IBlock, now uint64, states []upgradeRebuildScanState) ([]upgradeRebuildResult, bool) { + if tip == nil || len(states) == 0 { return finalizeUpgradeRebuildScanStates(states, now), true } @@ -781,8 +1124,11 @@ if !state.relevant { continue } - if relevantCount == 0 || state.def.StartLayer < minStart { - minStart = state.def.StartLayer + // A bounded state starts at its first un-certified window, not StartLayer. + // minWindowIndex is 0 for a full scan, so this reduces to StartLayer. + floor := state.def.StartLayer + state.minWindowIndex*state.def.WindowSize + if relevantCount == 0 || floor < minStart { + minStart = floor } relevantCount++ } @@ -795,18 +1141,64 @@ b.ChainRLock() defer b.ChainRUnlock() + // Serve each block's immutable (layer, main-parent, header version) from the + // upgradeBlockMeta memo instead of a raw pebble DAG-block + header read. A + // reorg re-runs this rebuild over the (up to 100k-layer) voting window on the + // single block-handler goroutine; the uncached walk did two pebble reads per + // block -- ReadBlockById plus GetBlockHeader's fetchHeaderByHash -- which + // starved the handler and froze imports (live goroutine dump 2026-11-22). The + // memo stores the same immutable facts countUpgradeSignalsInRange caches and + // is keyed by block id, so a warm reorg rescan is all cache hits with no + // pebble reads. upgradeCacheMu guards the shared memo exactly as + // evaluateUpgrades does; the lock order chainLock -> upgradeCacheMu -> + // bd.stateLock/DB matches the rest of the package (see evaluateUpgrades -> + // countUpgradeSignalsInRange). A cold cache falls back to the identical + // detached reads, so the tally and results are byte-for-byte unchanged. + b.upgradeCacheMu.Lock() + defer b.upgradeCacheMu.Unlock() + started := time.Now() lastLog := started var processed uint64 - for cur := tip; cur != nil; { - layer := uint64(cur.GetLayer()) + tipID := tip.GetID() + prevID := tipID + for curID := tipID; ; { + meta, ok := b.upgradeBlockMeta[curID] + if !ok { + // Cache miss: load the block with the same detached read the uncached + // rebuild used. ReadBlockById (not GetBlockById) keeps this deep + // historical walk from linking up to 100k blocks into the live DAG + // object graph. The tip is already in hand and never read from pebble. + var cur blockdag.IBlock + if curID == tipID { + cur = tip + } else { + loaded, err := b.bd.ReadBlockById(curID) + if err != nil || loaded == nil { + l.Warn("upgrade rebuild stopped at missing parent", "block_id", prevID, "parent_id", curID, "error", err) + return finalizeUpgradeRebuildScanStates(states, now), false + } + cur = loaded + } + hdr := b.GetBlockHeader(cur) + meta = upgradeSignalBlockMeta{ + layer: uint64(cur.GetLayer()), + mainParent: cur.GetMainParent(), + hasHeader: hdr != nil, + } + if hdr != nil { + meta.version = hdr.Version + b.putUpgradeBlockMeta(curID, meta) + } + } + + layer := meta.layer if layer < minStart { break } - hdr := b.GetBlockHeader(cur) - if hdr == nil { - l.Warn("upgrade rebuild stopped at missing header", "block_id", cur.GetID(), "layer", layer) + if !meta.hasHeader { + l.Warn("upgrade rebuild stopped at missing header", "block_id", curID, "layer", layer) return finalizeUpgradeRebuildScanStates(states, now), false } @@ -828,7 +1220,7 @@ continue } - state.record(layer, windowIndex, windowStart, hdr.Version, now) + state.record(layer, windowIndex, windowStart, meta.version, now) } processed++ @@ -842,20 +1234,15 @@ lastLog = time.Now() } - parentID := cur.GetMainParent() - if parentID == blockdag.MaxId { + if meta.mainParent == blockdag.MaxId { if layer > minStart { l.Warn("upgrade rebuild stopped before requested start layer", "last_layer", layer, "from_layer", minStart) return finalizeUpgradeRebuildScanStates(states, now), false } break } - next, err := b.bd.ReadBlockById(parentID) - if err != nil || next == nil { - l.Warn("upgrade rebuild stopped at missing parent", "block_id", cur.GetID(), "parent_id", parentID, "layer", layer, "error", err) - return finalizeUpgradeRebuildScanStates(states, now), false - } - cur = next + prevID = curID + curID = meta.mainParent } l.Info("upgrade rebuild header scan finished", "processed", processed, "duration", time.Since(started).String()) @@ -891,6 +1278,11 @@ } func (state *upgradeRebuildScanState) record(layer, windowIndex, windowStart uint64, version uint32, now uint64) { + // Windows the persisted marker already certified complete are not re-tallied by + // the bounded rebuild. For a full scan minWindowIndex is 0, so this is a no-op. + if windowIndex < state.minWindowIndex { + return + } if !state.initialized { state.startWindow(windowIndex, windowStart) } else if state.windowIndex != windowIndex { @@ -1067,28 +1459,60 @@ // The previous prefix-sized bitmap discarded those later votes until a // reorg/restart happened to force a longer rescan. tally := newUpgradeSignalTally(windowSize) - for cur := tip; cur != nil; { - layer := uint64(cur.GetLayer()) - if layer < from { - break - } - if layer <= to { + if tip == nil { + return tally + } + + // Walk the selected-parent chain from the tip back to `from`, exactly as the + // uncached version did, but serve each block's immutable (layer, main-parent, + // header version) from upgradeBlockMeta. Same blocks, same records, same order + // -> identical tally. Every caller (evaluateUpgrades here, and the header + // rebuild scan in rebuildUpgradeResultsFromHeaders) holds upgradeCacheMu while + // touching the memo, so it needs no further locking. + for id := tip.GetID(); ; { + meta, ok := b.upgradeBlockMeta[id] + if !ok { + cur := b.bd.GetBlockById(id) + if cur == nil { + break + } hdr := b.GetBlockHeader(cur) + meta = upgradeSignalBlockMeta{ + layer: uint64(cur.GetLayer()), + mainParent: cur.GetMainParent(), + hasHeader: hdr != nil, + } if hdr != nil { - recordUpgradeSignal(&tally, layer-from, hdr.Version, mask) + meta.version = hdr.Version + b.putUpgradeBlockMeta(id, meta) } } - - parentID := cur.GetMainParent() - if parentID == blockdag.MaxId { + if meta.layer < from { break } - cur = b.bd.GetBlockById(parentID) + if meta.layer <= to && meta.hasHeader { + recordUpgradeSignal(&tally, meta.layer-from, meta.version, mask) + } + if meta.mainParent == blockdag.MaxId { + break + } + id = meta.mainParent } return tally } +// putUpgradeBlockMeta stores an immutable block-meta entry and bounds the memo. +// Reached from countUpgradeSignalsInRange and the header rebuild scan, both under +// upgradeCacheMu. Entries never go stale, so clearing on overflow only forces +// re-reads. +func (b *BlockChain) putUpgradeBlockMeta(id uint, meta upgradeSignalBlockMeta) { + if b.upgradeBlockMeta == nil || len(b.upgradeBlockMeta) >= upgradeBlockMetaCacheCap { + b.upgradeBlockMeta = make(map[uint]upgradeSignalBlockMeta) + } + b.upgradeBlockMeta[id] = meta +} + // evaluateUpgrades recalculates voting windows for all known upgrades and // updates their state when thresholds are reached. The provided metric is a // deterministic chain value such as the layer or blue score of the current @@ -1243,3 +1667,34 @@ b.clearUpgradeWindowsLocked() b.upgradeTipID = blockdag.MaxId } + +// maybeNudgeUpgradeMarkerForward advances the upgrade rebuild marker on steady +// forward progress (no reorg) so it does not go stale across voting-window +// boundaries during long uptimes -- otherwise the marker moved only on reorgs +// and long peer-syncs, and a node mining steadily at tip paid a full historical +// rescan on its next restart. It runs at most once per +// upgradeMarkerForwardNudgeLayers of forward tip movement and only when the node +// is current. The refresh itself (tryRefreshFinalUpgradeRebuildState) is the same +// reviewed fast path used after reorgs/long-syncs: it never changes the consensus +// tally, only advances the marker when all upgrade state is already final, and +// leaves the marker untouched on any uncertainty. Must be called OUTSIDE +// chainLock (IsCurrent takes ChainRLock). +func (b *BlockChain) maybeNudgeUpgradeMarkerForward() { + tip := b.bd.GetMainChainTip() + if tip == nil { + return + } + layer := uint64(tip.GetLayer()) + last := b.upgradeMarkerNudgeLayer.Load() + if last != 0 && layer < last+upgradeMarkerForwardNudgeLayers { + return + } + if !b.IsCurrent() { + return + } + // CompareAndSwap so the refresh runs once per interval even if block handling + // ever becomes concurrent; it is cheap and race-free today. + if b.upgradeMarkerNudgeLayer.CompareAndSwap(last, layer) { + b.tryRefreshFinalUpgradeRebuildState(nil) + } +} --- a/p2p/peers/status.go +++ b/p2p/peers/status.go @@ -358,6 +358,14 @@ if age > snapshot.MaxGraphStateAge { snapshot.MaxGraphStateAge = age } + // A peer classified as being on a divergent main chain must not pin + // BestPeerLeadBlocks: its advertised main-order is on its own fork, not our + // catch-up distance. Sync-selection already skips such peers (peersync.go); + // mirror that here so one forked-but-ahead peer cannot wedge the mining gate + // at peer_lead_exceeds_tolerance indefinitely. It still counts as a consensus peer. + if obs := pe.ForkObservation(); obs != nil && obs.DivergentMainChain() { + continue + } if snapshot.BestPeerMainOrder == 0 || mainOrder > snapshot.BestPeerMainOrder || (mainOrder == snapshot.BestPeerMainOrder && (snapshot.BestPeerGraphStateAge == 0 || age < snapshot.BestPeerGraphStateAge)) { snapshot.BestPeerMainOrder = mainOrder