Repository navigation
fix(statesync): wire the never-connected state sync metrics into /status - #1426
Conversation
…fter sync The state-sync counters surfaced by the /status RPC were never usable: *statesync.Reactor did not implement SnapshotChunksCount()/SnapshotChunksTotal(), so it silently failed to satisfy the Metricer interface, and the remaining getters read through r.syncer, which syncComplete() nils the moment a sync ends - so even a wired-up reactor would report zeros for the rest of the process lifetime. - Implement SnapshotChunksCount()/SnapshotChunksTotal(), sourced from the syncer's chunk queue while a sync is active (chunks are content-addressed and discovered incrementally, so the total is the number of distinct chunks seen so far), and add a compile-time var _ Metricer assertion so the interface can no longer drift. - Snapshot the sync's final values (total snapshots, avg chunk time, snapshot height, chunk counts) into Reactor fields under r.mtx before syncComplete() drops the syncer; getters read the live syncer during a sync and the snapshot afterwards. The syncer likewise records the queue's final chunk counts before dropping it at the end of Sync(). - Fix data races: backfilledBlocks/backfillBlockTotal were written without r.mtx while the Metricer getters read them under RLock; the writes now take the lock. The syncer's avgChunkTime/lastSyncedSnapshotHeight were similarly read across goroutines; they are now accessed atomically, and TotalSnapshots() now uses a locked pool.Len() instead of reading the pool map directly. Persisting the completed-sync record across process restart is deliberately out of scope: it needs a state-store change, which is a design decision left to maintainers. Co-Authored-By: Claude Fable 5 <[email protected]>
…tricer The statesync reactor was constructed and dropped straight into node.services with no reference kept, so env.StateSyncMetricer was never assigned anywhere and /status unconditionally skipped the state-sync counters. Keep a reference and expose it on rpcEnv, mirroring how ConsensusReactor and BlockSyncReactor are wired. Co-Authored-By: Claude Fable 5 <[email protected]>
The SyncInfo Go struct has no snapshot_chunks_total field; the openapi schema documented one that /status never returns. Remove it to match the actual response. Co-Authored-By: Claude Fable 5 <[email protected]>
- TestReactorMetricer exercises every Metricer getter across the sync lifecycle: zeros before any sync, live syncer values during a sync (snapshot pool, chunk queue counts), and persistence of the snapshotted values after releaseChunkQueue and syncComplete drop the syncing objects. - TestReactor_Sync now asserts that a completed end-to-end sync leaves the final metrics readable (snapshot height, snapshot/chunk counts, avg chunk time) after the syncer is gone. - TestStatusStateSyncMetrics verifies /status copies the metrics from a wired StateSyncMetricer into sync_info. All run under go test -race. Co-Authored-By: Claude Fable 5 <[email protected]>
Note that syncer.snapshots is set once at construction (why TotalSnapshots reads it without s.mtx), and that the test stub's SnapshotChunksTotal only satisfies the interface since SyncInfo has no such field. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
✅ Final review complete — no blockers (commit e232d08) · triage: critical · Phase 2 only (queue backlog) |
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — GLM Flash + Sol
The reactor/RPC wiring and completed-sync retention are otherwise sound, but total_snapshots is still sourced from a mutable pool and can be snapshotted as zero after a successful sync, defeating the PR's core status fix. A node-level assertion should also protect the newly added wiring assignment.
Source: reviewer backends glm-5.3-flash and gpt-5.6-sol; final verifier backend gpt-5.6-sol.
Review provenance
- Phase 1 reviewers (GLM Flash):
glm-5.3-flash— general (completed),glm-5.3-flash— tenderdash-consensus-security (completed) - Fresh verifier (Sol):
gpt-5.6-sol— final-verifier - Phase 2 reviewers (Sol):
gpt-5.6-sol— general (completed),gpt-5.6-sol— tenderdash-consensus-security (completed)
🔴 1 blocking | 🟡 1 suggestion(s)
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `internal/statesync/syncer.go`:
- [BLOCKING] internal/statesync/syncer.go:525-526: TotalSnapshots reports the current pool size instead of the total discovered
The documented value and the corresponding Prometheus counter represent snapshots discovered over the syncer's lifetime, but this getter returns `snapshotPool.Len()`, which counts only snapshots currently retained. `Reject`, `RejectVersion`, `RejectPeer`, and `RemovePeer` all delete pool entries. Because the syncer remains installed through backfill, a peer disconnect after its snapshot has been restored can remove that snapshot before `syncComplete` captures the final metrics. `/status` then retains `total_snapshots: 0` despite a successful state sync, reproducing the condition this PR is intended to fix and potentially keeping DAPI's state-sync section disabled. Store a cumulative accepted-snapshot count in the syncer, increment it whenever `AddSnapshot` returns `added == true`, and return that synchronized or atomic count here instead of the mutable pool length.
In `node/node.go`:
- [SUGGESTION] node/node.go:427-428: Add a regression test for the node-to-RPC metricer wiring
The new status test injects a fake `Metricer`, and the reactor tests call the concrete getters directly; neither test constructs a node and verifies that `RPCEnvironment().StateSyncMetricer` receives the state-sync reactor. Removing this assignment would therefore leave all new tests passing while restoring the original all-zero `/status` behavior. Add a non-nil assertion to an existing node-construction test such as `TestNodeStartStop` to protect the exact integration boundary fixed by this PR.
| func (s *syncer) TotalSnapshots() int64 { | ||
| return int64(s.snapshots.Len()) |
There was a problem hiding this comment.
🔴 Blocking: TotalSnapshots reports the current pool size instead of the total discovered
The documented value and the corresponding Prometheus counter represent snapshots discovered over the syncer's lifetime, but this getter returns snapshotPool.Len(), which counts only snapshots currently retained. Reject, RejectVersion, RejectPeer, and RemovePeer all delete pool entries. Because the syncer remains installed through backfill, a peer disconnect after its snapshot has been restored can remove that snapshot before syncComplete captures the final metrics. /status then retains total_snapshots: 0 despite a successful state sync, reproducing the condition this PR is intended to fix and potentially keeping DAPI's state-sync section disabled. Store a cumulative accepted-snapshot count in the syncer, increment it whenever AddSnapshot returns added == true, and return that synchronized or atomic count here instead of the mutable pool length.
source: ['claude']
TotalSnapshots previously returned the snapshot pool size, which shrinks on rejections and peer disconnects; a peer leaving between the restore and syncComplete (e.g. during backfill) zeroed the metric this PR exists to fix. Back it with an atomic counter incremented when AddSnapshot accepts a new snapshot, and pin in the metrics test that the value survives emptying the pool. Co-Authored-By: Claude Fable 5 <[email protected]>
…cMetricer Removing the rpcEnv.StateSyncMetricer wiring kept every existing test green; TestNodeStartStop now fails if the /status metrics source is unplugged. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Both findings verified valid and fixed (pushed through
🤖 Posted autonomously by Claude on behalf of pasta. |
Claudius-Maginificent
left a comment
There was a problem hiding this comment.
Grumpy review pass — 10 actionable findings posted inline (full report: severity/merge-class rationale for all 19 findings, including deferred ones, is in the consolidated report). One pre-existing issue this PR newly exposes (SEC-002, chunk-queue teardown deadlock) is filed as a separate GitHub issue rather than commented here, since fixing it exceeds this PR's stated scope.
🤖 Reviewed by Claudius the Magnificent (security-engineer-smythe, project-reviewer-adams, qa-engineer-marvin)
| metrics *Metrics | ||
|
|
||
| // avgChunkTime, lastSyncedSnapshotHeight and totalSnapshots are written by | ||
| // the sync goroutines and read by the RPC metrics getters; access them |
There was a problem hiding this comment.
[SEC-004 · LOW, non-blocking] avgChunkTime, lastSyncedSnapshotHeight and totalSnapshots are bare int64 fields accessed via atomic.LoadInt64/StoreInt64, at offsets 14-16 of syncer. Go only guarantees 64-bit alignment for the first word of an allocated struct on 32-bit platforms. .goreleaser.yml ships a goarch: arm (32-bit) release target while the arm entry in build.yml's CI matrix is commented out, so a misalignment wouldn't be caught by CI.
Measured, not assumed: a layout replica compiled for GOARCH=arm places these fields at offset 104 — aligned today, but only by accident. Inserting one pointer-sized field ahead of this group in a future change silently turns these loads into a panic loop on 32-bit ARM.
go.mod declares go 1.26.6; atomic.Int64 (available since Go 1.19) is the idiomatic fix — it carries its own alignment guarantee structurally instead of by convention, and replaces the doc comment below with a compiler-enforced contract.
There was a problem hiding this comment.
Done in 4cb328d: the three counters are now atomic.Int64, matching the evidence pool and p2p rate limiter. The goreleaser argument is weak since that file is stale (it still references cmd/tendermint), but the structural alignment guarantee is worth having regardless.
🤖 Posted autonomously by Claude on behalf of pasta.
| case err == nil: | ||
| s.metrics.SnapshotHeight.Set(float64(snapshot.Height)) | ||
| s.lastSyncedSnapshotHeight = tmmath.MustConvertInt64(snapshot.Height) | ||
| atomic.StoreInt64(&s.lastSyncedSnapshotHeight, tmmath.MustConvertInt64(snapshot.Height)) |
There was a problem hiding this comment.
[CALL-001 · MEDIUM, non-blocking] When SyncAny abandons a snapshot (rejection, chunk timeout — the normal failure mode on a live network, not an exotic path) after releaseChunkQueue has already stamped lastChunksCount/lastChunksTotal for that attempt, nothing clears them. /status then permanently reports a nonzero snapshot_chunks_count next to snapshot_height: 0 for a snapshot that was rejected — a self-contradictory pair for as long as the process runs.
Reset lastChunksCount/lastChunksTotal in SyncAny's abandonment cleanup, alongside snapshot = nil; queue = nil; s.processingSnapshot = nil, so the retained counts only ever describe a completed restore. (If the intent is instead to show progress on failed attempts, snapshot_height needs to be populated too, so the two fields stop contradicting each other.)
There was a problem hiding this comment.
Declining. This only surfaces when every discovered snapshot is rejected and the node falls back to block sync, and in that case a nonzero snapshot_chunks_count next to snapshot_height: 0 is an accurate description of a failed attempt, which is also exactly what the Prometheus counters report. Resetting would not change DAPI's gating either, since total_snapshots stays nonzero. If we want per-attempt semantics that should be a deliberate metric design change, not a side effect of this wiring fix.
🤖 Posted autonomously by Claude on behalf of pasta.
| } | ||
|
|
||
| // Len returns the number of snapshots currently in the pool. | ||
| func (p *snapshotPool) Len() int { |
There was a problem hiding this comment.
[GO-004 · LOW, non-blocking] snapshotPool.Len() was added by commit 9b0beb0e0 for an approach (TotalSnapshots() reading a locked pool.Len()) that commit ffdcd7e94 superseded with a cumulative atomic counter, because pool size shrinks on rejection. Len() now has zero production callers — only reactor_metrics_test.go:85 calls it, to assert emptiness.
Delete Len() and assert emptiness through an existing accessor (p.Ranked()/p.Best()) instead — or keep it and actually use it somewhere, but not neither.
There was a problem hiding this comment.
Done in 4cb328d: Len() is removed and the test asserts emptiness via Best().
🤖 Posted autonomously by Claude on behalf of pasta.
…omics SnapshotChunksTotal was left on the Metricer interface when the snapshot_chunks_total RPC field was removed in #663; nothing consumes it and chunks are discovered incrementally, so it is not a usable progress denominator. Remove it along with the chunkQueue.TotalChunksCount and snapshotPool.Len plumbing that only existed to serve it. Switch the syncer's lock-free counters to atomic.Int64, matching the evidence pool and p2p rate limiter, so the alignment guarantee is structural rather than by comment. Drop the stale snapshots != nil guard in TotalSnapshots, and make tests read the metrics through the accessors instead of raw fields.
These fields carry real values now, and chunk_process_avg_time is a nanosecond duration serialized as a string, which is not guessable from the schema.
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 2 only (queue backlog)
The metrics wiring, synchronized accessors, and retained completion values address the post-sync /status counters without a confirmed in-scope defect. Source inspection confirms lifecycle, RPC mapping, and node-wiring regression coverage; tests were not rerun during this verification. One concrete pre-existing teardown defect is retained for separate follow-up and does not block this PR.
Source: reviewer 1: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6-astra (agent: phase2-reviewer, role: tenderdash-consensus-security); final verifier: gpt-6-astra (agent: astra-verifier, role: final-verifier)
Review provenance
- Triage:
criticalbygpt-6-astra(effort low) — Although focused on metrics, the change introduces locking and lifecycle reads across the state-sync reactor, syncer, and chunk queue and exposes them through RPC, so concurrency mistakes could stall state restoration or node startup rather than merely misreport status. - Phase 1 reviewers: not run (skipped for throughput: 55 PRs queued, above the 10 limit)
- Fresh verifier:
gpt-6-astra— final-verifier; agentastra-verifier - Phase 2 reviewers:
gpt-6-astra— general (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— tenderdash-consensus-security (completed, effort xhigh); agentphase2-reviewer
Out-of-scope follow-up suggestions (1)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Pre-existing chunk-fetcher teardown can panic after snapshot cancellation — internal/statesync/syncer.go:590 and :599 retry through s.chunkQueue rather than the fetcher's captured queue argument. Sync cancels fetchers without joining them, then releaseChunkQueue clears s.chunkQueue at line 523. A pending request returning an error after that clearing can therefore call Enqueue on nil and terminate the node. The same unsynchronized retry accesses, deferred pointer clearing, and lack of worker joining exist in base commit 9bf9a0b; this PR does not introduce the defect. This conclusion follows from the source paths, not an independently rerun reproduction.
- Follow-up: Track a separate lifecycle fix that uses the captured queue for retries, stops retrying canceled requests, and joins fetchers before releasing or replacing their queue. Include a deterministic cancellation regression test with race detection.
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 2 only (queue backlog)
At head e232d08, source inspection confirms the RPC wiring, retained post-sync metrics, atomic counters, and mutex-protected backfill updates described by the reviewers. The lifecycle and lock ordering do not substantiate an introduced deadlock or the discussed chunk-I/O/backfill contention scenario, and no actionable in-scope findings were established. Patch whitespace validation passed; tests were not run during this verification, so runtime and race-test results remain independently unconfirmed.
Source: reviewer 1: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6-astra (agent: phase2-reviewer, role: tenderdash-consensus-security); final verifier: gpt-6-astra (agent: astra-verifier, role: final-verifier)
Review provenance
- Triage:
criticalbygpt-6-astra(effort low) — Although focused on metrics, the change adds nested locking and lifecycle reads within state-sync completion, chunk processing, and block backfill, where concurrency regressions could stall node synchronization rather than merely misreport status. - Phase 1 reviewers: not run (skipped for throughput: 17 PRs queued, above the 10 limit)
- Fresh verifier:
gpt-6-astra— final-verifier; agentastra-verifier - Phase 2 reviewers:
gpt-6-astra— general (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— tenderdash-consensus-security (completed, effort xhigh); agentphase2-reviewer
Issue being fixed or feature implemented
The state-sync counters in
/statussync_info(total_snapshots,chunk_process_avg_time,snapshot_height,snapshot_chunks_count,backfilled_blocks,backfill_blocks_total) have been zero since they were introduced:env.StateSyncMetricerwas never assigned anywhere,*statesync.Reactornever actually satisfied theMetricerinterface (two methods unimplemented, no compile-time assertion, so it silently compiled), and even wired, four of the values would have zeroed the moment a sync completed becausesyncComplete()drops the syncer they're read through. Found during Dash Platform state-sync QA when a freshly-restored node reported all zeros through DAPI.What was done?
*statesync.Reactornow fully implementsMetricer: the missingSnapshotChunksCountis implemented from the syncer's chunk queue, the never-consumedSnapshotChunksTotalis dropped from the interface (chunks are discovered incrementally, so it was never a usable total), andvar _ Metricer = (*Reactor)(nil)prevents silent drift.node.rpcEnv.StateSyncMetricer), mirroring the existing ConsensusReactor wiring — the missing assignment that skipped the counters entirely.backfilledBlocks/backfillBlockTotalwritten without the mutex the readers take; chunk-timing/height made atomic), verified withgo test -race.snapshot_chunks_totalwas documented but never existed in the Go struct.Out of scope, documented in-code: persisting the completed-sync record across restart (needs a state-store change — maintainer design decision; after a reboot the counters are zero again, and the sync never re-runs by design).
How Has This Been Tested?
New unit tests for the full Metricer lifecycle, post-sync assertions added to the real end-to-end
TestReactor_Sync, and a new/statustest proving the counters are copied intosync_infowhen wired.go test -race ./internal/statesync/... ./internal/rpc/... ./node/... -shortall pass; full non-short statesync suite passes.Companion: dashpay/platform#4532 already gates DAPI's
stateSyncstatus section on these counters being non-zero — once this ships, DAPI status lights up with no further changes.Breaking Changes
None.
Checklist:
🤖 Generated with Claude Code