Skip to content

fix(replay): don't execute the replay target height as a checkpoint round - #11203

Merged
pierugo-dfinity merged 36 commits into
masterfrom
mraszyk/replay-target-height-round-type
Sep 14, 2026
Merged

pierugo-dfinity merged 36 commits into
masterfrom
mraszyk/replay-target-height-round-type

Conversation

@mraszyk

@mraszyk mraszyk commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Don't execute the last replayed height as a checkpoint round

Problem

deliver_batches() derived requires_full_state_hash partly from its
max_batch_height_to_deliver argument, so the last batch of a bounded delivery was
always flagged as requiring a full state hash. That flag does not only decide whether a
checkpoint is written: it also selects ExecutionRoundType::CheckpointRound, which
changes execution — it charges every canister for resource allocation and aborts all
paused executions.

Only ic-replay bounds the delivery, and it always does. So the last replayed height was
executed differently from the way the subnet executed that very same height. Since the
certification version was bumped to V29, /subnet/<subnet_id>/metrics includes
CanisterStates::total_consumed_cycles(), so the difference now changes the certification
hash and ic-replay reports

Hash mismatch! State divergence detected for outstanding shares!

Recoveries replay to the highest certification share height, which is essentially never a
summary height, so every recovery is affected.

Changes

Consensus — requires_full_state_hash is derived from the block alone, so every
replayed round is executed exactly the way the subnet executed it.

Batches — the checkpoint ic-replay needs is created by an extra batch instead. New
BatchContent::CheckpointingWithoutExecution, handled like BatchContent::Splitting:
message routing skips induction, execution and routing and only calls
checkpoint_round_with_no_execution(). The checkpoint therefore holds the state the
subnet computed for the last replayed height, with nothing on top of it but the per-round
bookkeeping message routing applies to every batch — the batch time, the canonicalization
every checkpoint round performs, and the subnet metrics. blockmaker_metrics becomes an
Option, None for batches that correspond to no finalized block, so no blockmaker is
credited for them.

ic-replay — a replay that replays blocks always ends in a checkpoint, created by
that extra batch:

  • the extra batch is skipped when the state it would checkpoint is already checkpointed —
    the last replayed block is a summary block, or no block was replayed at all;
  • the checkpoint therefore sits at least one height above the replay target height: one
    above if the subcommand contributes no ingress, higher if it does, since its messages
    are delivered in batches of their own first;
  • the number of batches delivered on top of the replayed blocks is reported in the replay
    output (ReplayOutput::extra_batches), so callers can recover the height of the last
    replayed block;
  • --replay-until-height now warns that the resulting checkpoint differs slightly from
    the replica's in-memory state at that height (checkpoint serialization), and that
    re-running the replay against the same pool shadows the heights above the target with
    the checkpoint just written;
  • restore-from-backup delivers the same checkpointing batch once it reaches its target
    height, instead of leaving the restored state in memory and reporting the latest CUP's
    params;
  • get-recovery-cup and update-registry-local-store read the state replayed before them
    and no longer replay any blocks themselves, so --replay-until-height is explicitly
    ignored (with a printed notice) and neither writes a checkpoint;
  • without a consensus pool there is no finalized tip to take the replica version from, so
    the new --replica-version supplies it; it cannot be looked up in the registry, since
    the subnet may well be stalled on a version older than the one the latest registry
    version assigns to it. Without a pool there is also no CUP to fall back on when the tip
    is in memory only, so the highest checkpoint is reported instead.

ic-recovery — no longer refuses to replay without a consensus pool (it warns and
asks for confirmation), so a recovery that cannot reach any node over SSH can still
execute its ic-replay subcommand on top of the local checkpoint. For such a recovery the
existing --replica-version is forwarded to every ic-replay invocation; it is already
part of the persisted RecoveryArgs, so giving it once survives a restart of the
recovery, and ic-replay is left to complain if it is missing. Whether a pool is there is
decided by the consensus store itself and no longer by the root it shares with the
certification store, which MergeCertificationPoolsStep creates on its own.
ValidateReplayStep subtracts the extra batch count reported by ic-replay instead of a
constant the flows had to guess.

Behaviour changes

  • When blocks are replayed, the checkpoint is created at a height above the replay
    target height — one above it, or more if the subcommand adds ingress messages.
  • update-registry-local-store replays no blocks any more: it only writes the local store
    from the state that is already there.
  • ic-recovery's --replica-version doubles as the version ic-replay is run with, and
    is required when replaying without a consensus pool.

Testing

requires_full_state_hash_ignores_max_batch_height_to_deliver in batch_delivery.rs
fails without the consensus fix. test_checkpointing_without_execution in
state_machine/tests.rs pins the new batch content down to
checkpoint_round_with_no_execution(): its Demux, Scheduler and StreamBuilder mocks
panic if anything is inducted, executed or routed, and it asserts that the canister states
come out unchanged and only the batch time moved.
merged_certifications_do_not_create_a_consensus_store in steps.rs pins down that the
merge step creates the shared pool root but no consensus store, which is what both
ReplayStep::exec() and Player::new() test for. The ic-replay extra-batch paths have
no unit coverage; the sr_* subnet-recovery system tests exercise them end to end,
replaying to a certification-share height.

🤖 Generated with Claude Code

…ound

`deliver_batches()` derived `requires_full_state_hash` partly from its
`max_batch_height_to_deliver` argument, so the last batch of a bounded
delivery was always flagged as requiring a full state hash:

    let persist_batch = Some(height) == max_batch_height_to_deliver;
    let requires_full_state_hash = block.payload.is_summary() || persist_batch;

That flag does not only decide whether a checkpoint is written: it also
selects `ExecutionRoundType::CheckpointRound`, which *changes execution*.
A checkpoint round charges every canister for resource allocation and
usage, bypassing the `CHARGE_INTERVAL_ROUNDS` gate, and aborts all paused
executions instead of only those above a limit.

Only `ic-replay` passes `Some(..)` here, and it always does -- even
without `--replay-until-height`, it passes `Some(finalized_height)`. So
the last replayed height was executed differently from the way the subnet
executed that very same height, and the resulting state differed in the
canisters' cycle balances and consumed cycles.

That difference used to be invisible to the certified state. Since the
current certification version was bumped to `V29`, `/subnet/<subnet_id>/metrics`
includes `CanisterStates::total_consumed_cycles()`, so it now changes the
certification hash, and `ic-replay` reports

    Hash mismatch! State divergence detected for outstanding shares!

against the subnet's certification shares at that height, refusing to
proceed without manual inspection. Subnet recoveries replay to the highest
certification share height, which is essentially never a summary height,
so every recovery is affected.

Derive `requires_full_state_hash` from the block alone, and have
`ic-replay` create the checkpoint it needs by always delivering an extra
batch at the end, one height above the last replayed block. The replayed
heights are then executed exactly as the subnet executed them, and the
checkpoint round happens at a height no node ever certified.

The replayed height is therefore one above the subnet's; account for it in
`ValidateReplayStep`, which already models this via `extra_batches`.

Both added tests fail without the corresponding change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@mraszyk mraszyk added the CI_ALL_BAZEL_TARGETS Runs all bazel targets label Aug 18, 2026
@github-actions github-actions Bot added the fix label Aug 18, 2026
@mraszyk mraszyk closed this Aug 19, 2026
@mraszyk mraszyk reopened this Aug 19, 2026
mraszyk and others added 4 commits August 19, 2026 08:46
Without a consensus pool no batches are replayed, so the on-disk
checkpoint is untouched and needs no extra batch to persist it;
delivering one anyway would mutate the state using the wall clock time,
producing a non-deterministic state hash. This restores the pre-existing
no-op behavior of a plain `ic-replay` invocation over a state directory
without a consensus pool (e.g. a state-only backup snapshot).

Recovery flows, on the other hand, always download the consensus pool,
so there a missing pool means the state was downloaded incorrectly:
make ic-recovery's replay step fail loudly in that case instead of
silently replaying no blocks.

Co-Authored-By: Claude Fable 5 <[email protected]>
- Make re-running the replay over the same data directory idempotent:
  once a previous invocation has delivered the extra batch and persisted
  the checkpoint above the replay target height, deliver no further
  extra batch. Otherwise every re-run would move the checkpoint (and
  thereby change the state hash) one height further, and only a run
  over pristine data would reproduce the recovery checkpoint.
- Rework the --replay-until-height consent prompt: replaying a
  consensus pool now creates a deterministic checkpoint via the extra
  batch, so warn only when restoring from a backup, where a non-CUP
  target height yields no persistent progress beyond the latest CUP.
- When restoring from a backup reaches a target height without a
  checkpoint, say so explicitly instead of silently reporting the
  state params of the latest CUP.

Co-Authored-By: Claude Fable 5 <[email protected]>
The extra batch that `ic-replay` delivers to persist the state it
replayed does not correspond to any block, so its round should have no
effect beyond what creating a checkpoint requires. Yet it used to be an
ordinary data batch, i.e. its round inducted and executed messages
(heartbeats, global timers, leftover queue traffic) that the subnet
itself never executed at that point, and charged all canisters for
resource allocation.

Introduce `BatchContent::Checkpointing`, handled like
`BatchContent::Splitting` in that message routing skips induction,
execution and routing altogether and only calls
`checkpoint_round_with_no_execution()`, which aborts paused executions
and wipes the `SystemMetadata` caches. The resulting checkpoint contains
exactly the state the subnet computed for the last replayed height.

Note that not charging for resource allocation in this round loses
nothing: charging is duration-based, so the first charging round after
the subnet resumes covers the same interval.

Also stop attributing the extra batches to a test blockmaker: their
`blockmaker_metrics` are `None` now, so that no blockmaker is credited
for a batch that no node ever proposed.

Co-Authored-By: Claude Fable 5 <[email protected]>
Drop `round_type_decides_whether_a_non_charging_round_charges`: it only
characterizes pre-existing scheduler behaviour and passes without the fix,
so `requires_full_state_hash_ignores_max_batch_height_to_deliver` in
`batch_delivery.rs` is the actual regression test.

Fix two comments in `player.rs`:

- delivering an extra batch on every re-run makes the state hash depend on
  how many times the replay was run; it is a run over *pristine* data whose
  hash would then no longer be reproduced (the claim was inverted).
- the replayed height is executed the way the subnet executed it so that the
  resulting certified state is *identical* to the one the subnet certified,
  not merely comparable to its certification shares.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@mraszyk
mraszyk force-pushed the mraszyk/replay-target-height-round-type branch from 860b318 to a6c4a15 Compare August 19, 2026 11:26
@mraszyk
mraszyk marked this pull request as ready for review August 19, 2026 13:30
@mraszyk
mraszyk requested a review from a team as a code owner August 19, 2026 13:30
@zeropath-ai

zeropath-ai Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

✅ No security or compliance issues detected. Reviewed everything up to c939cb5.

Security Overview
Detected Code Changes
Change Type Relevant files
Enhancement ► rs/consensus/src/consensus/batch_delivery.rs
       Adjust requires_full_state_hash handling and metrics updates
► rs/determinism_test/src/lib.rs
       Update test expectations to account for Some(blockmaker_metrics) in batch construction
► rs/messaging/src/message_routing.rs
       Make blockmaker_metrics optional and guard metrics updates accordingly
► rs/messaging/src/state_machine.rs
       Handle BatchContent::CheckpointingWithoutExecution by aborting checkpointing path while preserving state
► rs/messaging/src/state_machine/tests.rs
       Update test fixture to include new checkpointing scenario and adjust expectations
► rs/recovery/src/app_subnet_recovery.rs
       Comment/case for replay until height with checkpoint considerations
► rs/recovery/src/cmd.rs
       Document replica_version handling for recovery tool args
► rs/recovery/src/lib.rs
       Widen state/replay output types to ReplayOutput; propagate replica_version through recovery flows
► rs/recovery/src/nns_recovery_failover_nodes.rs
       Align validate replay step with new get_validate_replay_step signature
► rs/recovery/src/nns_recovery_same_nodes.rs
       Align replay step usage with new get_validate_replay_step signature and messaging
► rs/recovery/src/replay_helper.rs
       Introduce ReplayOutput type usage and adapt read/store to new ReplayOutput
► rs/recovery/src/steps.rs
       Add replica_version support in replay step descriptions and steps; expose replica_version in ReplayStep and related helpers
► rs/replay/src/cmd.rs
       Update replay tool args documentation regarding replay_until_height and replica_version
► rs/replay/src/lib.rs
       Adapt replay logic to return ReplayOutput and support scenarios with/without consensus pool including extra batches
► rs/replay/src/player.rs
       Drop BatchMakerMetrics from Batch type in favor of optional usage; adjust imports
► rs/consensus/src/consensus/batch_delivery.rs (tests)

@pierugo-dfinity pierugo-dfinity left a comment

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.

In ic-replay, instead of predicting the operator's thought process and behave as what we think makes more sense today (i.e. execute an extra checkpointing batch, but actually not if there's no consensus pool, and actually not if we replayed beforehand), what about leaving the decision of adding an extra checkpointing batch as a CLI argument?
By default, we wouldn't include an extra batch and thus not create a checkpoint. The operator could safely replay as many times as they want without "committing" to/persisting anything. When they want to commit, they would pass the flag.
I think it would simplify the ic-replay implementation

During recoveries, I guess we can always enable that flag, even when no consensus pool was downloaded (maybe we weren't able to SSH in? See next comment), still displaying a confirmation prompt maybe.

Comment thread rs/messaging/src/message_routing.rs Resolved
Comment thread rs/recovery/src/app_subnet_recovery.rs Resolved
Comment thread rs/recovery/src/steps.rs Resolved
Comment thread rs/replay/src/player.rs Resolved
Comment thread rs/replay/src/player.rs Resolved
Comment thread rs/replay/src/player.rs Resolved
Comment thread rs/replay/src/player.rs Resolved
@mraszyk
mraszyk marked this pull request as draft August 26, 2026 15:13
mraszyk and others added 7 commits August 27, 2026 13:31
- `deliver_extra_batch`: key the early return on the absence of a consensus
  pool instead of on `target_height` being `None`.
- `restore_from_backup`: document when the reported state height can be below
  the last replayed height.
- `FakeBatchProcessorImpl`: `unimplemented!` on `BatchContent::Checkpointing`,
  which only `ic-replay` delivers and always to the real batch processor.
- `requires_full_state_hash_ignores_max_batch_height_to_deliver`: build the
  dependencies via `DependenciesBuilder::new`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…et-height-round-type

# Conflicts:
#	rs/consensus/src/consensus/batch_delivery.rs
#	rs/determinism_test/src/lib.rs
#	rs/messaging/src/message_routing/tests.rs
#	rs/messaging/src/state_machine/tests.rs
#	rs/replay/src/player.rs
#	rs/test_utilities/types/src/batch/batch_builder.rs
…_step

Keep the recovery flows free of the `ic-replay` implementation detail that
every invocation delivers one extra batch at the end to create the
checkpoint: their `extra_batches` arguments count only the batches the flow
itself adds, and `get_validate_replay_step` adds the checkpointing one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`ReplayStep` refused to run without a consensus pool, on the grounds that a
missing pool means the state was downloaded incorrectly. But the pool is
downloaded over SSH, so a recovery that cannot reach any node has no pool and
still wants to execute the extra batch of its `ic-replay` subcommand on top of
the latest local checkpoint.

Warn what will happen instead and let the operator confirm, and have
`ic-replay` report the pool-less skip of the checkpointing batch so the no-op
is visible in its output.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Replaying up to a CUP height already creates the checkpoint, as the batch of a
summary block requires a full state hash. Delivering the extra batch on top of
it would move the checkpoint (and thereby the reported state hash) one height
further for no reason, so skip it whenever the state it would checkpoint is
already checkpointed.

The number of extra batches is therefore no longer a constant the recovery
flows can assume: `ic-replay` reports it in its output and `ValidateReplayStep`
subtracts the reported number, which also fixes the count in the upgrade case,
where the ingress batch is followed by a separate checkpointing batch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`ic-replay` decided by itself whether the replayed state should be persisted:
it delivered an extra checkpointing batch, but not without a consensus pool,
and not if a previous run had already delivered one. Replace that guesswork
with `--create-checkpoint`.

Without the flag nothing is persisted, so a replay can be re-run as often as
needed; with it the state is committed. What remains is not a policy decision
but a no-op check: the batch is skipped if the state it would checkpoint is
already checkpointed, i.e. the last replayed block is a summary block or no
block was replayed at all. The latter subsumes the former pool-less guard.

Recoveries always pass the flag, except for the steps that only read the state
(the recovery CUP) or only write the registry local store.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

Copilot AI left a comment

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.

Pull request overview

Prevents bounded replay rounds from incorrectly executing as checkpoint rounds and adds explicit replay checkpoint creation.

Changes:

  • Derives checkpoint execution solely from block content.
  • Adds checkpoint-only batches and optional blockmaker metrics.
  • Adds --create-checkpoint and reports extra replay batches to recovery flows.

Reviewed changes

Copilot reviewed 18 out of 18 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
rs/types/types/src/batch.rs Adds checkpoint-only batches and optional blockmaker metrics.
rs/test_utilities/types/src/batch/batch_builder.rs Updates test batch construction.
rs/state_machine_tests/src/lib.rs Wraps blockmaker metrics in Some.
rs/replay/src/player.rs Implements explicit checkpoint batches and extra-batch reporting.
rs/replay/src/lib.rs Propagates checkpoint configuration and replay results.
rs/replay/src/cmd.rs Adds --create-checkpoint.
rs/recovery/src/steps.rs Updates replay execution and validation.
rs/recovery/src/replay_helper.rs Passes checkpoint configuration to replay.
rs/recovery/src/nns_recovery_same_nodes.rs Uses reported extra-batch counts.
rs/recovery/src/nns_recovery_failover_nodes.rs Updates replay validation construction.
rs/recovery/src/lib.rs Simplifies validation-step API.
rs/recovery/src/app_subnet_recovery.rs Updates replay validation construction.
rs/messaging/src/state_machine/tests.rs Updates batch variants and metrics.
rs/messaging/src/state_machine.rs Handles checkpoint-only rounds.
rs/messaging/src/message_routing/tests.rs Updates test batches for optional metrics.
rs/messaging/src/message_routing.rs Skips blockmaker accounting for synthetic batches.
rs/determinism_test/src/lib.rs Updates deterministic test batches.
rs/consensus/src/consensus/batch_delivery.rs Stops forcing bounded deliveries into checkpoint rounds.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread rs/replay/src/cmd.rs Resolved
Comment thread rs/recovery/src/steps.rs Resolved
mraszyk and others added 2 commits August 27, 2026 15:13
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
`Player::new` panicked when neither a consensus pool nor `--replica-version`
was available, so the pool-less replay the recovery now allows could not
actually run: `replay_helper::replay` always passes `replica_version: None`,
and no recovery flow has the right version to pass (`upgrade_version` is the
version to upgrade *to*, applied after the replay via the CUP, whereas the
extra batch executes under the version the subnet is currently on).

Fall back to the subnet's replica version from the local registry, looked up
the same way consensus stamps a block's version. This matches the pool-less
`deliver_extra_batch`, which already takes its registry version from the
latest local registry version. `--replica-version` stays an override, and the
panic remains only as a last resort.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread rs/messaging/src/state_machine.rs Resolved
Comment thread rs/types/types/src/batch.rs Resolved
Comment thread rs/messaging/src/state_machine.rs Resolved
Comment thread rs/messaging/src/state_machine/tests.rs Resolved
Comment thread rs/replay/src/player.rs Resolved
Comment thread rs/replay/src/player.rs Resolved
Comment thread rs/replay/src/player.rs Resolved
Comment thread rs/replay/src/player.rs Resolved
Comment thread rs/replay/src/player.rs Resolved
…et-height-round-type

# Conflicts:
#	rs/consensus/src/consensus/batch_delivery.rs

Copilot AI left a comment

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.

🔵 Needs a closer look

Recovery without a consensus pool still reaches a panic when no replica version was supplied.

Review details

Suppressed comments (1)

rs/recovery/src/steps.rs:483

  • When the consensus store is absent but a checkpoint exists, this branch never enforces the newly required replica version. If replica_version is None, execution reaches Player::new() and panics while unwrapping it, which spawn_blocking only reports as a generic join failure. Reject the step here with an actionable --replica-version error before invoking ic-replay.
        if !consensus_store_path.exists() {
  • Files reviewed: 19/19 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

pull Bot pushed a commit to bit-cook/ic that referenced this pull request Sep 8, 2026
The test is consistently failing. To reduce noise in alerts, we disable
the test until it is green again (will require
dfinity#11203 to be merged).
Comment thread rs/recovery/src/steps.rs Resolved
Comment thread rs/replay/src/lib.rs Resolved
Comment thread rs/replay/src/player.rs Resolved
Comment thread rs/replay/src/lib.rs Resolved
Comment thread rs/replay/src/cmd.rs Resolved
Comment thread rs/recovery/src/app_subnet_recovery.rs Resolved
Comment thread rs/replay/src/lib.rs Resolved
Comment thread rs/replay/src/cmd.rs Resolved
Comment thread rs/recovery/src/steps.rs Resolved
Comment thread rs/replay/src/player.rs Resolved
@pierugo-dfinity
pierugo-dfinity added this pull request to the merge queue Sep 14, 2026
Merged via the queue into master with commit 20c396c Sep 14, 2026
42 of 43 checks passed
@pierugo-dfinity
pierugo-dfinity deleted the mraszyk/replay-target-height-round-type branch September 14, 2026 10:41
pull Bot pushed a commit to mikeyhodl/ic that referenced this pull request Sep 17, 2026
Now that dfinity#11203 has merged, we can reenable the mainnet NNS recovery
system test.

Due to compatibility reasons, this test must be turned into a "remote"
recovery (which could lead to a few extra minutes of test time) but can
be turned back to "local" once the changes reach mainnet.
pull Bot pushed a commit to bit-cook/ic that referenced this pull request Sep 21, 2026
Sorry for the back-and-forth 😅 

When reenabling the system test in dfinity#11599, I had successfully tested it
locally but had not pulled master completely, and in particular, did not
include dfinity#11184. Unfortunately, the latter change is exactly the type of
changes that are "incompatible" when using the HEAD version of
`ic-replay`/`ic-recovery`, as mentioned
[here](https://github.com/dfinity/ic/blob/45abaf452188db7d8a45f09529e46f8a46bab165/rs/tests/testnets/mainnet_nns/src/lib.rs#L77-L78).

Once dfinity#11203 reaches mainnet NNS, we'll be able to reenable the system
test. Will wait until then.
alin-at-dfinity pushed a commit that referenced this pull request Sep 22, 2026
Sorry for the back-and-forth 😅 

When reenabling the system test in #11599, I had successfully tested it
locally but had not pulled master completely, and in particular, did not
include #11184. Unfortunately, the latter change is exactly the type of
changes that are "incompatible" when using the HEAD version of
`ic-replay`/`ic-recovery`, as mentioned
[here](https://github.com/dfinity/ic/blob/45abaf452188db7d8a45f09529e46f8a46bab165/rs/tests/testnets/mainnet_nns/src/lib.rs#L77-L78).

Once #11203 reaches mainnet NNS, we'll be able to reenable the system
test. Will wait until then.
valorjesson-commits pushed a commit to Marketearth/ic that referenced this pull request Oct 3, 2026
dfinity#11203 has reached mainnet NNS and we can reenable the mainnet NNS
Recovery system test again.
AleDema pushed a commit to AleDema/ic that referenced this pull request Oct 18, 2026
…nable_chain_keys_test_farm_colocate (dfinity#11818)

## Problem


`//rs/tests/consensus/subnet_recovery:sr_app_no_upgrade_enable_chain_keys_test_farm_colocate`
flaked once in the week up to 2026-10-11 ([2026-10-05 16:19
UTC](https://dash.dm1-idx1.dfinity.network/invocation/b6dca5c2-ade4-4df4-94c4-d5d47bda5ff1?target=//rs/tests/consensus/subnet_recovery:sr_app_no_upgrade_enable_chain_keys_test_farm_colocate),
on PR dfinity#11744's branch). The recovery tool failed in
`ValidateReplayOutput`:

```
Execution of step ValidateReplayOutput failed: Output error: Invalid output: Replay height smaller than certification height.
```

`ic-replay` had replayed 45 batches up to height 245 (the certification
height), delivered the extra checkpointing batch 246 and logged `Created
unverified checkpoint @246`, `Computed root hash ... of state @246` and
`Validated checkpoint @246`. Yet its `ReplayOutput` reported the latest
CUP's state, `StateParams { height: 200, hash: f3f4ff1b... }`, so the
validation compared 200 - 1 against 245. In the passing attempts `Height
after replay` is the certification height + 1, as intended since dfinity#11203.

## Root cause

`Player::get_latest_state_params` read the hash of the latest state once
and treated *any* `Err` from `get_state_hash_at` as "the latest state
exists in memory only", falling back to the latest CUP. That read can
fail transiently for a checkpoint that already exists on disk:

- For a checkpoint round, `commit_and_certify` enqueues
`ComputeManifest` and `ValidateReplicatedStateAndFinalize` on the tip
channel, then has the hash thread insert `states_metadata[height]`
(without a manifest yet) and publish the new `latest_state_height`,
waits for it, and only then enqueues the follow-up `WaitForManifest`
request that publishes the manifest (and `ResetTipAndMerge`).
- `ic-replay`'s `wait_for_state` polls `latest_state_height` every 500
ms and then calls `flush_tip_channel`. If it observes the new height
before `WaitForManifest` is enqueued, its `Wait` request lands between
`ValidateReplicatedStateAndFinalize` and `WaitForManifest`: the flush
returns as soon as the checkpoint is validated, while the root hash is
still unpublished, and `get_state_hash_at` returns
`Transient(HashNotComputedYet)`.

The failing log shows this interleaving. Checkpoint 246 was created and
its certification hash computed at 16:19:36.635; `ic-replay` saw height
246 at .664 (one poll later) and its flush returned at .797, right after
`Validated checkpoint @246`; two further `wait_for_state` calls at .797
and .798 returned immediately, so `WaitForManifest` was still not
enqueued; `ReplayOutput { height: 200 }` was printed at .975, and
`ResetTipAndMerge` (enqueued together with `WaitForManifest`) ran at
.969, during the state manager's drop. Why `commit_and_certify` needed
more than 160 ms between publishing the height and enqueueing the
follow-ups is inferred, not shown: the hash thread persists the states
metadata with an fsync before it answers, and this run's checkpoint
creation took 470 ms against 10 ms in the passing attempt.

The window exists since async hashing moved the height publication onto
the hash thread (dfinity#8464, reverted in dfinity#10001, re-landed as dfinity#10071 on
2026-05-08); the single read in `ic-replay` dates from 2022.

This is not only a flake: the recovery tool went on to delete every
checkpoint but the highest (246) while the state params it would put
into the recovery CUP were those of height 200. `ValidateReplayOutput`
caught it here, but the corrupted-CUP recoveries skip that step.

## Fix

Read the hash with the existing `get_state_hash` helper, which retries
transient errors every second and returns `None` only for
`StateNotFullyCertified`, i.e. a state that really exists in memory
only; the fallback to the CUP (or, without a consensus pool, to the
highest checkpoint, now read the same way) is unchanged for that case.
The helper answers height 0, which is never a checkpoint, with `None`
without polling (an empty state directory would otherwise make the state
manager report it as not committed yet forever), so
`update-registry-local-store` on an empty state fails as before instead
of waiting. Unit tests pin both `None` cases down.

Behaviour changes to be aware of: a `StateRemoved` error for the latest
state, which cannot happen, now panics instead of silently reporting the
CUP; and like `verify_latest_cup`, which already used the helper, the
poll is unbounded, so a manifest that is never published would make
`ic-replay` log "Waiting for state hash" every second rather than report
a wrong height.

Follow-up for the state manager (not in this PR): `flush_tip_channel` is
documented to finish "all asynchronous checkpointing operations,
including ... manifest computation", but a caller on another thread can
flush before `commit_and_certify` has enqueued `WaitForManifest`.
`ic-replay` was the only such caller; the other callers flush from the
committing thread.

Not related to dfinity#11795: that change only touches the Local backend's
bridge, and this run was colocated on Farm.

## Testing

- `cargo check --all-targets --all-features -p ic-replay`, `cargo fmt`,
`./ci/scripts/rust-lint.sh`.
- `bazel build //rs/replay:replay`; `bazel test
//rs/recovery:recovery_test //rs/replay:player_integration_tests
//rs/replay:replay_doc_test //rs/replay:replay_test` (rerun after each
review follow-up).
- `bazel test --runs_per_test=3 --jobs=3
//rs/tests/consensus/subnet_recovery:sr_app_no_upgrade_enable_chain_keys_test_farm_colocate`:
3/3 passed on Farm (372 s, 390 s, 380 s), each with `Height after
replay` = certification height + 1. Passing runs cannot exercise the
window, which needs the checkpoint's I/O to be slow; the evidence for
the fix is the log analysis above and the unit tests.

This PR was created following the steps in
`.claude/skills/fix-flaky-tests/SKILL.md`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants