Skip to content

perf(blocksync): per-stage apply histograms and an unsafe-no-fsync switch for profiling - #1430

Merged
lklimek merged 2 commits into
v1.8-devfrom
bench/blocksync-stage-timing
Sep 10, 2026
Merged

lklimek merged 2 commits into
v1.8-devfrom
bench/blocksync-stage-timing

Conversation

@PastaPastaPasta

@PastaPastaPasta PastaPastaPasta commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Block sync reports partset, verify, save and exec per block, but exec is a single number covering the two ABCI calls, our own durable writes, the mempool update and the event publish. That is most of a block, and it was opaque.

This adds two things. Both follow the patterns the codebase already uses, per review: the timing lands in the existing Prometheus metrics, and the no-fsync policy is a constructor option on the stores rather than a package global.

Per-stage histograms

Two new histograms, labelled by stage, in milliseconds:

  • state_block_apply_stage_duration on state.Metrics: each stage of ProcessProposal and FinalizeBlock, so the old exec number is split into the ABCI calls, SaveABCIResponses, the state store write, the mempool update, evidence pool, pruning and the event publish.
  • consensus_block_sync_apply_stage_duration on consensus.Metrics, which the block sync applier already holds: partset, verify_commit, verify_block, save, exec, and wait, the idle time between one apply and the next.

They are no-ops with NopMetrics, so nothing changes for a node without Prometheus. Two findings that came out of the measurement:

The verify stage is a single BLS threshold verification. Splitting it:

verify_commit=1.896 ms   verify_block=0.009 ms

ValidateBlock is free; the whole stage is the signature. That is what #1427 and #1428 act on.

A single peer costs a third of the sync. wait is 2.2–3.5 ms/block with one peer and 0.003 ms with two: the applier is waiting on block fetch, not executing.

peers blocks/s ms/block
1 97.1 10.30
2 140.5 7.12

unsafe-no-fsync config option

This is a benchmarking correction rather than a tuning knob.

Go's os.File.Sync() on darwin issues F_FULLFSYNC, not fsync. Measured on an M-series Mac:

go File.Sync mean ms: 6.776
plain fsync  mean ms: 0.231

Tenderdash does three synchronous writes per block during block sync, so on macOS it spends about 20 ms a block that a Linux node does not. Same binaries, same chain:

blocks/s verify save exec
fsync 34.6 4.20 5.42 19.55
no fsync 92.4 3.47 0.04 6.79

Leaving it on hides everything else in a profile taken on macOS.

How it is scoped:

  • store.NewBlockStore(db, store.WithUnsafeNoFsync()) and state.NewStore(db, state.StoreWithUnsafeNoFsync()). Without the option every write is WriteSync/SetSync, as before.
  • state.NewStore takes ...StoreOption now instead of the old ...log.Logger; the logger moved to StoreWithLogger. Three callers passed a logger and were updated.
  • The option is applied in exactly two places, initDBs and makeNode, and only when the config flag is set. Rollback, reindex and inspect build their own stores and keep durable writes.
  • Setting it logs at error level on startup.

The name is deliberate. It removes durability: a power loss can leave the block store behind the application, which the replayer rejects with ErrAppBlockHeightTooHigh. Never set it on a node whose data matters.

Tests

  • internal/store and internal/state: a spy DB (internal/test/dbspy) counts syncing vs non-syncing writes, pinning the durable default on both the batch and single-key paths and the non-syncing selection with the option, with identical stored data.
  • internal/state: the stage timer attributes each interval once, and is silent with NopMetrics.
  • internal/blocksync: a successful apply records one sample per stage, wait only from the second block, and a failed commit check records verify_commit but not verify_block.
  • config: the generated file renders the flag off with its warning.
  • node: initDBs applies the policy only when configured.

Used throughout a full mainnet Platform replay, genesis to height 424,981, and for every A/B measurement behind #1427 and #1428.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 01a8687a-e55f-4199-9165-256c62323cd7

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@thepastaclaw

thepastaclaw commented Aug 31, 2026 •

Copy link
Copy Markdown

✅ Final review complete — no blockers (commit ee1ca0d) · triage: critical · Phase 2 only (queue backlog)

Comment thread internal/store/nosync.go Outdated
// TD_UNSAFE_NOSYNC=1 to take durability out of the measurement. Never set it on
// a node whose data you care about: a power loss can then leave the block store
// behind the application.
var unsafeNoSync = os.Getenv("TD_UNSAFE_NOSYNC") == "1"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Correct approach would be to extend the BlockStore struct with a setting that will define sync mode, not defining some global env vars, messing up the design patterns we use in Tenderdash.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Agreed — checked the actual blast radius for this. Both BlockStore and internal/state's dbStore are constructed in exactly one place each (NewBlockStore, NewStore), with no struct literals elsewhere, so this is contained:

  • Add unsafeNoSync bool to BlockStore (store.go) and to dbStore (internal/state/store.go).
  • Turn the constructors into functional options: NewBlockStore(db, opts...) / NewStore(db, logger, opts...) with a WithUnsafeNoSync() option — variadic, so none of the 4+4 existing call sites (node/setup.go, reindex_event.go, replay_file.go, inspect.go, node/node.go) need to change.
  • Convert the free-function writeBatch/dbSet in both nosync.go files into methods on the structs; delete both files' package-level os.Getenv reads.
  • Wire the option at exactly one call site (node/setup.go, where both stores get built for the live node) — that's also the natural place for a startup log line making the mode visible, which this PR is currently missing.

This also fixes the other blocking finding for free: internal/state/rollback.go's Rollback(bs BlockStore, ss Store) takes already-constructed stores and never builds its own — right now it silently inherits the global env var; with a struct field it structurally can't unless cmd/tenderdash/commands/rollback.go deliberately opts in, which it never would.

Net: roughly 60-80 lines across store.go/internal/state/store.go, no test churn (default behavior is unchanged when no option is passed). The same treatment applies to internal/state/nosync.go's dbSet/writeBatch pair.

🤖 Co-authored by Claudius the Magnificent AI Agent

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done in 8eb7c01. Both stores now take constructor options: store.NewBlockStore(db, store.WithUnsafeNoFsync()) and state.NewStore(db, state.StoreWithUnsafeNoFsync()). The env vars and both nosync.go files are gone. The option is applied only in initDBs and makeNode, gated on a new unsafe-no-fsync config flag, and logged at error level on startup. Rollback, reindex and inspect keep durable writes, and TestInitDBsAppliesUnsafeNoFsyncOnlyWhenConfigured pins that.


🤖 Posted autonomously by Claude on behalf of pasta.

@Claudius-Maginificent Claudius-Maginificent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

One more design-pattern note, on TD_BLOCK_PERF this time — see the inline comment. See summary comment for full report.

🤖 Co-authored by Claudius the Magnificent AI Agent

Comment thread internal/state/execperf.go Outdated
// per-block cost of block sync can be attributed to the application, to our own
// durable writes, or to signature verification. Enabled with TD_BLOCK_PERF=1.
type execPerf struct {
mtx sync.Mutex

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This reimplements telemetry the codebase already has. internal/state/metrics.go has a real Prometheus histogram (BlockProcessingTime, .Observe()'d at execution.go:527, go-kit/metrics-backed with a discard.NewHistogram() no-op when unused — i.e. already near-zero-cost when idle, no env var needed). internal/blocksync's applier already holds a *consensus.Metrics handle (applierWithMetrics) at the exact call site where this file's lap-timers go.

This file instead builds a parallel system: a process-global singleton with its own mutex+map, a second independent os.Getenv("TD_BLOCK_PERF") read in internal/blocksync/perf.go that has to mirror this one (per its own comment), and periodic log.Info lines instead of a queryable metric.

Suggested fix: delete this file and internal/blocksync/perf.go; add VerifyCommitSig, VerifyValidateBlock, ApplyGap, Save (etc.) as metrics.Histogram fields on state.Metrics (same metricsgen pattern as BlockProcessingTime), and .Observe() them at the same call sites this file's laps mark. No env var, always on, and it lands in whatever Prometheus/Grafana stack already scrapes this node instead of requiring a log-grep-and-average workflow.

🤖 Co-authored by Claudius the Magnificent AI Agent

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed and done in 8eb7c01. execperf.go, perf.go and TD_BLOCK_PERF are removed. The timing is now two metricsgen histograms labelled by stage: state_block_apply_stage_duration on state.Metrics for the ProcessProposal/FinalizeBlock stages, and consensus_block_sync_apply_stage_duration on the consensus.Metrics the applier already holds for partset, verify_commit, verify_block, save, exec and wait. Both are no-ops with NopMetrics.


🤖 Posted autonomously by Claude on behalf of pasta.

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Preliminary review — GLM Flash blocker gate

The default path preserves synchronous writes and verification order, and focused tests for internal/state, internal/store, and internal/blocksync pass. The package-global no-sync switch must be scoped and surfaced before merge; the untested branches and nonportable build script also need cleanup, while the deferred validation timing is a smaller measurement-accuracy issue.

Source: reviewer 1: glm-5.3-flash (agent: phase1-reviewer, role: general); reviewer 2: glm-5.3-flash (agent: phase1-reviewer, role: tenderdash-consensus-security); final verifier: gpt-5.6-sol (agent: sol-verifier, role: verifier)

Validated blockers were found by the Phase-1 GLM Flash review and confirmed by a fresh Sol verifier. Phase 2 is deferred until a fresh same-head revalidation clears the blocker gate.

Review provenance

  • Phase 1 reviewers (GLM Flash): glm-5.3-flash — general (completed); agent phase1-reviewer, glm-5.3-flash — tenderdash-consensus-security (completed); agent phase1-reviewer
  • Fresh verifier (Sol): gpt-5.6-sol — verifier; agent sol-verifier
  • Phase 2 reviewers (Sol): not run (deferred by blocker gate)

🔴 1 blocking | 🟡 2 suggestion(s) | 💬 1 nitpick(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/store/nosync.go`:
- [BLOCKING] internal/store/nosync.go:16-23: Scope and surface the unsafe no-sync policy explicitly
  The package-level environment checks here and in internal/state/nosync.go change the durability policy of every BlockStore and state Store in the process, rather than only stores created for the intended benchmark run. This includes normal consensus writes, pruning, Bootstrap, and the rollback command: loadStateAndBlockStore constructs ordinary stores, and Rollback calls Store.Save while --store additionally calls BlockStore.DeleteBlock, all of which now inherit TD_UNSAFE_NOSYNC. The variable is not represented in Config and no startup log or status output reports that durable writes have been disabled, so an exported benchmark environment can silently affect recovery tooling. Store the policy on BlockStore and dbStore through constructor options that default to synchronous writes, opt in only at the intended node construction path, and emit a prominent startup warning when enabled.

In `internal/state/nosync.go`:
- [SUGGESTION] internal/state/nosync.go:11-25: Add coverage for no-sync selection and performance accounting
  No tests were added for either new durability branch or for execPerf and the block-sync lap integration. Existing package tests exercise only the default process environment, so they do not verify that the unsafe mode selects Write/Set rather than WriteSync/SetSync, while preserving the same stored data and error propagation. The timing code likewise lacks checks for accumulation, sorted reporting, interval reset, disabled behavior, and cross-package RecordPerf samples. These changes are under internal/state and internal/store, where the project requires tests; making the sync policy an explicit per-store option would also make both modes deterministic to test.

In `build.sh`:
- [SUGGESTION] build.sh:1-10: Do not add a generic root build script that only works on a prepared macOS host
  This script unconditionally invokes Homebrew under set -e, so ./build.sh fails immediately on Linux, and it assumes the native BLS artifacts have already been built. It also bypasses the repository's BUILD_TAGS, read-only module mode, and version linker flags, producing a different binary from the standard build. The Makefile already performs the OS-specific GMP setup and makes build depend on build-bls. Remove this local helper, or implement a clearly named and Darwin-guarded Makefile/scripts target that reuses the repository build variables while omitting only the unsupported static linker flags.

In `internal/blocksync/applier.go`:
- [NITPICK] internal/blocksync/applier.go:133-136: Do not record commit-error handling as block validation time
  The verify_validate_block timer is deferred before the VerifyCommit error check. When commit verification fails, ValidateBlock is never called, but the deferred timer still records the error wrapping and logger call under verify_validate_block. Failed attempts also add timing totals without reaching perf.block, which increments the reporting denominator only after a finalized block, so repeated invalid commits can noticeably distort the reported mean. Call lp.done("verify_validate_block") immediately after ValidateBlock returns instead of deferring it across both error paths.

Comment thread internal/store/nosync.go Outdated
Comment on lines +16 to +23
var unsafeNoSync = os.Getenv("TD_UNSAFE_NOSYNC") == "1"

func writeBatch(batch dbm.Batch) error {
if unsafeNoSync {
return batch.Write()
}
return batch.WriteSync()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Blocking: Scope and surface the unsafe no-sync policy explicitly

The package-level environment checks here and in internal/state/nosync.go change the durability policy of every BlockStore and state Store in the process, rather than only stores created for the intended benchmark run. This includes normal consensus writes, pruning, Bootstrap, and the rollback command: loadStateAndBlockStore constructs ordinary stores, and Rollback calls Store.Save while --store additionally calls BlockStore.DeleteBlock, all of which now inherit TD_UNSAFE_NOSYNC. The variable is not represented in Config and no startup log or status output reports that durable writes have been disabled, so an exported benchmark environment can silently affect recovery tooling. Store the policy on BlockStore and dbStore through constructor options that default to synchronous writes, opt in only at the intended node construction path, and emit a prominent startup warning when enabled.

source: ['codex']

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 8eb7c01: per-store constructor options defaulting to durable writes, opted in only at node construction from a config flag, with a startup warning. See the reply to lklimek above for details.


🤖 Posted autonomously by Claude on behalf of pasta.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Resolved (re-reviewed at 8eb7c017): Your constructor options now keep the policy on each store, default to synchronous writes, and are applied through config-gated node construction with an error-level warning. I also verified that rollback, reindex, and inspect construct stores without these options, removing the process-wide environment leakage.

Comment thread internal/state/nosync.go Outdated
Comment on lines +11 to +25
var unsafeNoSync = os.Getenv("TD_UNSAFE_NOSYNC") == "1"

func writeBatch(batch dbm.Batch) error {
if unsafeNoSync {
return batch.Write()
}
return batch.WriteSync()
}

func dbSet(db dbm.DB, key, value []byte) error {
if unsafeNoSync {
return db.Set(key, value)
}
return db.SetSync(key, value)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Suggestion: Add coverage for no-sync selection and performance accounting

No tests were added for either new durability branch or for execPerf and the block-sync lap integration. Existing package tests exercise only the default process environment, so they do not verify that the unsafe mode selects Write/Set rather than WriteSync/SetSync, while preserving the same stored data and error propagation. The timing code likewise lacks checks for accumulation, sorted reporting, interval reset, disabled behavior, and cross-package RecordPerf samples. These changes are under internal/state and internal/store, where the project requires tests; making the sync policy an explicit per-store option would also make both modes deterministic to test.

source: ['codex']

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added in 8eb7c01: spy-DB tests in both internal/store and internal/state covering the durable default and the no-fsync selection on both the batch and single-key paths; stage timer tests in internal/state; applier tests that check one sample per stage, wait only from the second block, and that a failed commit check does not record verify_block; a config rendering test; and a node wiring test.


🤖 Posted autonomously by Claude on behalf of pasta.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Resolved (re-reviewed at 8eb7c017): The new spy-DB tests cover default and opt-in write selection, while the timer/applier tests cover stage attribution, no-op metrics, and failed commit verification. The old aggregation/reporting implementation has been removed, so its former accumulation, sorting, and reset coverage requirements no longer apply.

Comment thread build.sh Outdated
Comment on lines +1 to +10
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
BLS=$PWD/third_party/bls-signatures
GMP=$(brew --prefix gmp)
export CGO_ENABLED=1
export CGO_CXXFLAGS="-I$BLS/build/depends/relic/include -I$BLS/src/depends/mimalloc/include -I$BLS/src/depends/relic/include -I$BLS/src/include -I$GMP/include"
export CGO_LDFLAGS="-L$BLS/build/depends/mimalloc -L$BLS/build/depends/relic/lib -L$BLS/build/src -ldashbls -lrelic_s -lmimalloc-secure -lgmp -L$GMP/lib"
go build -trimpath -o build/tenderdash ./cmd/tenderdash
echo "built build/tenderdash"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Suggestion: Do not add a generic root build script that only works on a prepared macOS host

This script unconditionally invokes Homebrew under set -e, so ./build.sh fails immediately on Linux, and it assumes the native BLS artifacts have already been built. It also bypasses the repository's BUILD_TAGS, read-only module mode, and version linker flags, producing a different binary from the standard build. The Makefile already performs the OS-specific GMP setup and makes build depend on build-bls. Remove this local helper, or implement a clearly named and Darwin-guarded Makefile/scripts target that reuses the repository build variables while omitting only the unsupported static linker flags.

source: ['codex']

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Removed in 8eb7c01.


🤖 Posted autonomously by Claude on behalf of pasta.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Resolved (re-reviewed at 8eb7c017): Confirmed that the root build.sh helper is absent from the current head. The prepared-macOS-only build entrypoint is no longer part of this change.

Comment thread internal/blocksync/applier.go Outdated
Comment on lines +133 to +136
lp := startLapBS()
err := e.state.Validators.VerifyCommit(e.state.ChainID, blockID, block.Height, commit)
lp.done("verify_commit_sig")
defer func() { lp.done("verify_validate_block") }()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💬 Nitpick: Do not record commit-error handling as block validation time

The verify_validate_block timer is deferred before the VerifyCommit error check. When commit verification fails, ValidateBlock is never called, but the deferred timer still records the error wrapping and logger call under verify_validate_block. Failed attempts also add timing totals without reaching perf.block, which increments the reporting denominator only after a finalized block, so repeated invalid commits can noticeably distort the reported mean. Call lp.done("verify_validate_block") immediately after ValidateBlock returns instead of deferring it across both error paths.

source: ['codex']

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 8eb7c01: the two checks are timed as separate verify_commit and verify_block samples taken directly around each call, and TestBlockApplierVerifyFailureTimesOnlyTheCheckThatRan guards that a failed commit check records nothing under verify_block.


🤖 Posted autonomously by Claude on behalf of pasta.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Resolved (re-reviewed at 8eb7c017): The verification calls are now measured immediately and independently, and your regression test confirms that failed commit verification emits no verify_block sample. The old successful-block reporting denominator was also removed with the custom profiler.

…itch for profiling

Block sync reported a single exec number covering both ABCI calls, our own durable writes, the mempool update and the event publish. This adds two Prometheus histograms, state_block_apply_stage_duration and consensus_block_sync_apply_stage_duration, labelled by stage, so a slow sync can be attributed to signature verification, the application, disk or block fetching without a profiler. The verify stage is split into the commit signature check and block validation, and the applier records the idle time between blocks.

It also adds unsafe-no-fsync to config: block store and state store writes then return before reaching disk. On macOS Go's File.Sync issues F_FULLFSYNC, about 7 ms per call, and three of them per block hide everything else in a profile. The policy is a constructor option on both stores, applied only where the node builds them, and logged prominently at startup. Rollback, reindex and inspect keep durable writes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@PastaPastaPasta
PastaPastaPasta force-pushed the bench/blocksync-stage-timing branch from aefda6c to 8eb7c01 Compare September 8, 2026 03:13
@PastaPastaPasta PastaPastaPasta changed the title bench(blocksync): per-block stage timing and a no-fsync switch for profiling perf(blocksync): per-stage apply histograms and an unsafe-no-fsync switch for profiling Sep 8, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Final validation — Phase 2 only (queue backlog)

At head 8eb7c01, all four prior findings are addressed by the constructor-scoped durability policy, startup warning, replacement metrics, and added regression coverage. Both new findings are confirmed: failed apply attempts distort idle-time accounting, and the stage-timer test has a scheduler-dependent assertion; neither is blocking. Verification was source-based; tests were not rerun, and the worktree remains clean.

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: critical by gpt-6-astra (effort low) — The PR changes durable-write selection in block and state stores and wires an unsafe no-fsync option into node startup, where incorrect scoping or defaults could cause crash-related data loss or application/state divergence, while also modifying consensus-adjacent block execution and sync instrumentation.
  • Phase 1 reviewers: not run (skipped for throughput: 38 PRs queued, above the 10 limit)
  • Fresh verifier: gpt-6-astra — final-verifier; agent astra-verifier
  • Phase 2 reviewers: gpt-6-astra — general (completed, effort xhigh); agent phase2-reviewer, gpt-6-astra — tenderdash-consensus-security (completed, effort xhigh); agent phase2-reviewer

🟡 1 suggestion(s) | 💬 1 nitpick(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/state/metrics_test.go`:
- [SUGGESTION] internal/state/metrics_test.go:24-30: Avoid a scheduling deadline in the stage-timer unit test
  The second stage must finish in less than 20 ms for this assertion to pass, but time.Sleep(2 * time.Millisecond) guarantees only a minimum delay. A scheduler pause or GC between the two done calls can therefore fail the test even when the timer correctly excludes the first stage. Capture timer.last before and after each done call and compare each recorded sample with its corresponding adjacent timestamp difference, or inject a fake clock, so the test verifies interval attribution without a scheduling deadline.

In `internal/blocksync/applier.go`:
- [NITPICK] internal/blocksync/applier.go:109: Advance the idle-time boundary when Apply returns an error
  Apply observes wait before every attempt but updates lastDone only after success. After a successful apply followed by a verification failure, the next attempt measures from the earlier successful completion again. Its wait sample includes both the wait already recorded for the failed attempt and the time spent processing that attempt, double-counting elapsed time and attributing verification work to fetching. Update lastDone on every return with a deferred closure registered after the deferred unlock, so the timestamp is written while e.mtx is still held, and add a success/failure/retry regression test.

Comment thread internal/state/metrics_test.go Outdated
Comment on lines +24 to +30
time.Sleep(2 * time.Millisecond)
timer.done("second")

require.Len(t, h.Samples["first"], 1)
require.Len(t, h.Samples["second"], 1)
require.GreaterOrEqual(t, h.Samples["first"][0], 20.0, "first stage covers its own sleep, in ms")
require.Less(t, h.Samples["second"][0], 20.0, "second stage must not include the first")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Suggestion: Avoid a scheduling deadline in the stage-timer unit test

The second stage must finish in less than 20 ms for this assertion to pass, but time.Sleep(2 * time.Millisecond) guarantees only a minimum delay. A scheduler pause or GC between the two done calls can therefore fail the test even when the timer correctly excludes the first stage. Capture timer.last before and after each done call and compare each recorded sample with its corresponding adjacent timestamp difference, or inject a fake clock, so the test verifies interval attribution without a scheduling deadline.

source: ['claude']

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Resolved (re-reviewed at ee1ca0d8): The stage-timer test now captures the timer's recorded timestamps and compares exact intervals, eliminating scheduler-dependent sleeps and deadline-sensitive assertions.

Comment thread internal/blocksync/applier.go Outdated
// ByteSize is the size of the serialized block we just built, so the metric
// costs nothing extra here
e.metrics.RecordConsMetrics(block, blockParts.ByteSize())
e.lastDone = time.Now()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💬 Nitpick: Advance the idle-time boundary when Apply returns an error

Apply observes wait before every attempt but updates lastDone only after success. After a successful apply followed by a verification failure, the next attempt measures from the earlier successful completion again. Its wait sample includes both the wait already recorded for the failed attempt and the time spent processing that attempt, double-counting elapsed time and attributing verification work to fetching. Update lastDone on every return with a deferred closure registered after the deferred unlock, so the timestamp is written while e.mtx is still held, and add a success/failure/retry regression test.

source: ['claude']

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Resolved (re-reviewed at ee1ca0d8): The applier now updates lastDone in a deferred function, so the idle-time boundary advances on successful returns, validation errors, and other error paths before Apply releases its mutex.

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Final validation — Phase 2 only (queue backlog)

Both prior findings are fixed: failed Apply attempts now advance the idle-time boundary, and the stage-timer test compares recorded intervals without scheduling deadlines. The unsafe durability policy remains explicitly opt-in and scoped to individual stores, and the stage histograms use the existing metrics infrastructure. Focused tests and race tests passed for blocksync, state, store, node, and config; no in-scope findings remain.

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: critical by gpt-6-astra (effort low) — The PR changes synchronous-write policy in block and state stores and instruments consensus-adjacent block application paths, where incorrect defaults, option propagation, or timing side effects could compromise crash recovery, persisted-state consistency, or node operation.
  • Phase 1 reviewers: not run (skipped for throughput: 14 PRs queued, above the 10 limit)
  • Fresh verifier: gpt-6-astra — final-verifier; agent astra-verifier
  • Phase 2 reviewers: gpt-6-astra — general (completed, effort xhigh); agent phase2-reviewer, gpt-6-astra — tenderdash-consensus-security (completed, effort xhigh); agent phase2-reviewer

@lklimek
lklimek merged commit 0722e43 into v1.8-dev Sep 10, 2026
21 checks passed
@lklimek
lklimek deleted the bench/blocksync-stage-timing branch September 10, 2026 07:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants