Skip to content

fix(orchestrator): wait for processes to properly exit when restarting - #11744

Merged
pierugo-dfinity merged 27 commits into
masterfrom
pierugo/orchestrator/wait-for-process-to-exit
Oct 19, 2026
Merged

pierugo-dfinity merged 27 commits into
masterfrom
pierugo/orchestrator/wait-for-process-to-exit

Conversation

@pierugo-dfinity

@pierugo-dfinity pierugo-dfinity commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

There is quite a lot going on in this PR. It is more of a refactor of the orchestrator's process manager but it still introduces the following functional changes (motivated by existing issues, thus fix):

  • Today, when stopping a process, we just send a SIGTERM and instantly return. There's no guarantee that the process actually terminated, just that "it probably will in the future". This is great for not blocking the thread, but it is in contradiction with

    • The logic of stopping the replica before removing the state when leaving a subnet (today, there's technically a race where the state is removed while the replica is still running for a bit),
    • The logic of stopping-then-starting the replica when a recovery CUP is observed or the subnet ID changes,
    • The logic of stopping-then-starting ic-boundary when the domain name changes,
    • The upcoming logic of stopping-then-starting ic-gateway when its config changes.

    This PR thus modifies stop to block until the process actually terminated: if stop returned Ok(()), the process is guaranteed to have terminated, which fixes the cases above.

  • Moreover, stop does so by waiting up to 30 seconds, then tries again with SIGKILL for up to 10 seconds. This is in concordance with how systemd does it and allows force-killing a stuck process. This also means that this function could take up to 40 seconds to return, and blocks a tokio worker thread doing so (though I think that's acceptable since it should be very rare and the runtime has many threads).

  • The previous point means that the upgrade loop could hold a write-lock on MultipleProcessesManager for up to 40 seconds, preventing the dashboard from serving the processes' PIDs (that need a read-lock to that manager). Provide the dashboard with only a view of the processes' PIDs, not needing a lock on the entire manager. Also generalize over any number of processes with a type-erased trait ProcessObserver.

    • P.S.: We now display ic-boundary's PID on the dashboard.
  • Today, the stop_replica_if_recovery_cup_or_subnet_changed function in the upgrade loop is fragile because it assumes we will always reach it on the iteration where we observe the recovery CUP or subnet-split. Though, if there was an error between the observation and that call, then the next iteration would not re-observe it and the replica would not be restarted (this was already mentioned here).

    • We fix this by moving this responsibility out of the upgrade loop and move it to every implementer of Process. This allows to simplify the upgrade loop and to remove the IcBoundaryManager's custom restart logic by including it directly into ProcessManager<P> for any P: Process.

@github-actions github-actions Bot added the fix label Oct 2, 2026
@pierugo-dfinity pierugo-dfinity added the CI_ALL_BAZEL_TARGETS Runs all bazel targets label Oct 2, 2026

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.

Copilot review overview

🟡 Changes recommended

Process shutdown can report success while subprocesses in the managed process group remain alive.

Review effort: Balanced
Findings: 1 High severity

Open (1)
What changed in this PR

Refactors orchestrator process management to support reliable stop-and-restart behavior.

Changes:

  • Waits for termination, escalating from SIGTERM to SIGKILL.
  • Restarts processes when relevant runtime arguments change.
  • Exposes lock-independent process observers to the dashboard.
File Description
rs/​orchestrator/​src/​upgrade.rs Delegates restart decisions to process managers.
rs/​orchestrator/​src/​processes.rs Adds restart policies and process observers.
rs/​orchestrator/​src/​process_manager.rs Implements blocking process termination and escalation.
rs/​orchestrator/​src/​orchestrator.rs Wires managers and observers independently.
rs/​orchestrator/​src/​dashboard.rs Generalizes process PID reporting.
rs/​orchestrator/​src/​boundary_node.rs Migrates boundary-node lifecycle management.

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

Comment thread rs/orchestrator/src/process_manager.rs Resolved

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.

Copilot review overview

🔵 Needs a closer look

Process signaling, shutdown timing, and restart-state refactoring have broad operational impact requiring final human validation.

Review effort: Balanced
Findings: None

Resolved since last review (1)

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.

Copilot review overview

🔵 Needs a closer look

Process signaling, forced termination, and recovery restart behavior have substantial operational impact requiring final human validation.

Review effort: Balanced
Findings: None

@pierugo-dfinity
pierugo-dfinity marked this pull request as ready for review October 8, 2026 15:32
@pierugo-dfinity
pierugo-dfinity requested a review from a team as a code owner October 8, 2026 15:32
@pierugo-dfinity

Copy link
Copy Markdown
Contributor Author

Will wait for #11349 before merging to patch its ic-gateway custom restart implementation here

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.

🟡 Changes recommended

Recovery still ignores shutdown failures, and gateway restarts hold the shared configuration lock during blocking waits.

2 open findings

🧠 Review effort: Balanced

Comment thread rs/orchestrator/src/process_manager.rs Resolved
Comment thread rs/orchestrator/src/processes.rs Resolved

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

Shutdown and restart changes affect replica recovery and state-removal safety and warrant final human validation.

0 open findings

2 resolved since last review

🧠 Review effort: Balanced

@basvandijk

Copy link
Copy Markdown
Collaborator

@pierugo-dfinity I noticed the test //rs/tests/consensus:cup_explorer_test_local was flaking on this PR. Below is the Root Cause Analysis:

cup_explorer_test flakes on PR #11744: root cause

RCA of 2026-10-16. Root cause only: no fix has been implemented or run.

PR: #11744 "fix(orchestrator): wait for processes to properly exit when restarting"
(branch pierugo/orchestrator/wait-for-process-to-exit, head 1ca94005d4, merge-base 7546892bae).
The PR is open and approved (eichhorl, 2026-10-13). Merging it as is would bring this flake to master.

Summary

Failure signature, seen only on this PR (7 failed attempts):

assert_no_metrics_errors: The metric `consensus_invalidated_artifacts` on node <app node> exceeded the maximum allowed value: 1 > 0

The same node's journal shows (rs/artifact_pool/src/consensus_pool.rs:773):

Invalid consensus artifact (CryptoError(Malformed ThresBls12_381 signature: [] error: 'Expected threshold signature with 48 bytes but got 0 bytes'))
at height <H+1000>: CatchUpPackage(... signature: ThresholdSignature { signature: CombinedThresholdSig: 0x, ... })

The artifact is the test's own unsigned recovery CUP: the registry CUP at the halted CUP height + 1000.

Root cause. On master and on the PR, the orchestrator restarts the replica when it sees a higher unsigned (recovery) CUP. They differ in when the new replica starts:

  • Master: stop only sent SIGTERM. In the same tick, ensure_running still saw the old PID and returned. The new replica therefore started on the next upgrade-loop tick, 10.0–11.3 s later.
  • PR: stop waits until the old replica has exited. ensure_running then starts the new replica in the same tick, 13–110 ms after the stop.

Removing that ~10 s gap opens a race in cup_explorer_test. Each step below is backed by code and logs:

  1. The test halts the app subnet only with halt_at_cup_height. That stops block making but not validation. It then executes RecoverSubnet.
  2. The 4 app nodes pick up the recovery registry version in their own 10 s upgrade-loop ticks. Sometimes one node picks it up a full tick after another (a straddle), because the version is stored locally just after the laggard's tick but just before the early node's.
  3. The early node's new replica boots from the unsigned recovery CUP. 1.4–6.6 s later (about 1.6 s of that is loading 2 NiDKG transcripts) it sends that CUP to its peers as a P2P initial artifact.
  4. The laggard is still running its old, pre-recovery replica. That replica fetches the CUP (CUPs are always Wants) and validates it. The 0-byte threshold signature fails CspSignature::try_from before any registry lookup, which leads to HandleInvalid and consensus_invalidated_artifacts = 1. Two gates must both be open for this:
    • Connected: the old replica must have a QUIC connection to the new process. Only the lower NodeId dials, and a lower-id laggard re-dials only after the 5 s idle timeout.
    • Not yet halted: the old replica must not yet have loaded the recovery registry version. That version sets is_halted=true, which makes consensus return before the validator runs. The replica's registry client polls every 5 s.
  5. test ends 8.1–10.8 s after the proposal executes. assert_no_metrics_errors then reads the laggard's old replica, before the laggard's next tick restarts it and resets the counter.

Why master never fails:

  • In this test the metrics check runs a median 3.3 s after the first stop. So in 220 of 222 master runs, no new replica existed when the check ran.
  • Even later, every old app replica was stopped or is_halted within 5.62 s of the first stop (107/107 analysable runs). Master's earliest broadcast is at least 11.5 s after the first stop.

Master is protected by the 10 s restart gap, which was a side effect of the non-blocking SIGTERM, not a design guarantee. The replica-side code is identical on master and on the PR.

Effect. One WARN line and one counter increment on a replica that is about to be restarted anyway. There is no peer penalisation, no stall and no safety impact.

Evidence

Only PR #11744 has this signature

query last --non_success '//rs/tests/consensus:cup_explorer_test%' --month:

  • PR fix(orchestrator): wait for processes to properly exit when restarting #11744: 6 of 28 runs were FLAKY, and 7 of 35 attempts failed (20%, 95% CI about 10–36%). The failures span 4 of the 7 tested commits (b03af7c, 3f6d405, 79cb31a, 1ca9400). By variant:

    • _local 3/7
    • _head_nns_local 0/7
    • _farm 2/7
    • _head_nns_farm 1/7

    All 7 failed attempts have this signature. For _farm 2026-10-02 the test log was garbage-collected; its signature comes from the BuildBuddy console (cwzx4 1 > 0) and its mechanism from ES logs.

  • Master and other branches: every cup_explorer_test flake this month has the other signature, left: 5, right: 4. That is the DKG-attempts race in the RecoverSubnet proposal, fixed by fix: deflake //rs/tests/consensus:cup_explorer_test #11841. In those runs no recovery CUP was ever created.

  • Master passing runs: 222 _local/_head_nns_local logs from Oct 2–15 contain 0 Invalid consensus artifact lines.

Every failed attempt follows the same chain

Times are node UTC. For 2026-10-02 _local the times are corrected to driver time, because node clocks there were 0.6–1.55 s behind.

attempt (variant, commit) early node → laggard early stop → start broadcast laggard INVALID laggard is_halted check laggard restart
_local 10-15 a1 (1ca9400), H+1000=1150 ahvf4 → mcvwc 13:20:17.678 → .698 20.509 20.514 22.774 22.397 (s6l7u fails first) after log end (~27.7)
56mic → s6l7u 18.173 → .193 20.952 20.968 22.584 after log end
_local 10-14 a1 (79cb31a), 1165 nb4mb → 6ft42 14:57:51.338 → .448 53.520 53.546 55.571 57.103 58:01.876
_local 10-14 a2 (79cb31a), 1135 hrv6f → tnxux 15:07:57.331 → .411 59.633 59.647 08:01.466 08:02.956 08:06.549
_local 10-02 a1 (b03af7c), 1195 wcfxc → ygtsh 14:15:~47.0 (driver) 49.529 (driver) 49.548 (driver) – 55.133 ~57.05 (driver)
_farm 10-06 a1 (3f6d405), 1180 4ejqw → qlstf 09:13:50.308 → .332 54.654 54.669 not before log end 58.146 ~59.4 (extrapolated)
_head_nns_farm 10-14 a1 (79cb31a), 1165 niv4o → i3gwu 15:00:14.500 → .524 16.801 16.808 18.942 20.450 ~24.0 (extrapolated)
_farm 10-02 a1 (b03af7c) 6nik3 → cwzx4 14:12:53.297 → .323 55.616 55.626 58.452 58.961 13:04.249
  • In every failure, the node that exceeded the limit was still running its boot-time replica at check time. No restarted replica ever logged an INVALID.
  • The receiver de-duplicates by CUP id, so the counter is exactly 1 even when several early nodes send the CUP.
  • The check panics at the first node that exceeds the limit. In 10-15 it stopped at s6l7u, so mcvwc's INVALID was never reported.

The two gates explain the laggards that did not invalidate:

  • Not connected. In _local 10-14 a1, dximx and 4buzm had lower NodeIds than nb4mb, so they had to re-dial nb4mb's new process themselves. They halted at 55.51–55.52 and re-dialed only at 57.14. Result: no INVALID.
  • Already halted. In _farm 10-06 a1, z7avg and 3g7dt were connected to 4ejqw's new process from 50.71, but had loaded is_halted at 53.38, before its broadcast at 54.65. Result: no INVALID. qlstf stored the recovery version only at 54.650, so it was still validating and invalidated the CUP at 54.669.
  • Passing attempts. 5 of the 12 PR attempts with a straddle passed, because one of the gates closed in time. The margins were sometimes 43–159 ms. With both gates included, the model classifies all 7 failed and all 27 checkable passed PR attempts correctly.

Master counterfactual

  • Straddles do happen on master. In 16 of the 109 Oct 9–15 runs, laggards picked up the recovery a tick late (7 runs) or not before the log ended (9 runs). Under the PR's same-tick restart, 44 of 222 master runs (19.8%) would have had a laggard's old replica still alive after an early node's new replica could have come up.
  • Master never starts the new replica in the stop tick. Stop → new start was 10.009–11.279 s (median 10.043 s, n=59). Example from rca_master_local 2026-10-14T16:10:22:
    • h2hwr stopped at 16:15:47.702 and started again at 57.762, with its stack up at 16:16:00.443.
    • Its 3 laggards had loaded is_halted at 51.69 and stopped at 57.89–58.04.
    • No INVALID was logged.
  • Master's passing check is weak evidence on its own. 63% of app-replica metric reads on master failed with ECONNREFUSED and were silently skipped; in 53 of 109 runs no app replica was read at all. With 0 INVALID lines in the logs, nothing was hidden, though.

Mechanism in code

Line references are at 7546892bae unless marked with the PR commit 1ca94005d4.

Orchestrator on master (rs/orchestrator/src/):

  • upgrade.rs:408-416: stop_replica_if_recovery_cup_or_subnet_changed, then ensure_children_are_running. There is no await between them.
  • upgrade.rs:640-680: "Found higher unsigned CUP" leads to stop_replica.
  • process_manager.rs:124-143,213-219: stop is kill, which sends SIGTERM to the process group and returns.
  • process_manager.rs:221-241: is_running is pid_cell.is_some(). Only the wait_on_exit thread clears the PID, after the child has been reaped.
  • processes.rs:267-270: ensure_running returns early while is_running(). The next tick then starts the replica.
  • No other master path starts the replica sooner. The only exceptions are the NNS-failover re-exec, which needs registry_store_uri (None in this test), and the re-exec after a failed stop (never hit).

Orchestrator on the PR:

  • processes.rs:75-105 (1ca94005d4): ReplicaProcess::restart_decision returns Restart when the CUP is unsigned and height > cup_height. The boot replica has cup_height 0, hence the logged "(height 1150 > 0)".
  • processes.rs:361-386 (1ca94005d4): ensure_running calls stop()? and then falls through to build and start the new process.
  • process_manager.rs:283-318 (1ca94005d4): stop sends SIGTERM, waits up to 30 s, then sends SIGKILL and waits up to 10 s. In practice the replica aborts (wait status 6) 13–110 ms after SIGTERM.

Tick cadence:

  • orchestrator.rs:50,533-536: CHECK_INTERVAL_SECS = 10 s, slept after each check. The measured period is 10.02–10.15 s.
  • The registry replicator polls every 5 s (rs/config/src/nns_registry_replicator.rs:20). check() reads the latest registry version once, at its start (upgrade.rs:178).
  • The VMs boot together, so the app nodes' ticks are roughly in phase. Each node's 5 s replicator and 10 s loop are phase-correlated, so whether the store lands just before or just after a node's own tick is often close to a coin flip.
  • Tick start times are not logged; they are inferred from the "Persisting CUP" cadence (±0.3 s).

Sending the unsigned CUP:

  • rs/artifact_pool/src/consensus_pool.rs:464-483: init_genesis puts the startup CUP into the validated pool.
  • consensus_pool.rs:956-963: get_all_for_initial_broadcast always includes the highest validated CUP.
  • rs/replica/setup_ic_network/src/lib.rs:557-599: create_artifact_handler runs right after DkgKeyManager::new, which logs "Finished waiting on 2 transcripts".
  • rs/p2p/artifact_manager/src/lib.rs:146-152,256-280: the initial artifacts are sent as Deliver.
  • rs/p2p/consensus_manager/src/sender.rs:253-300: the sender re-checks the peer set every 5 s.
  • rs/p2p/quic_transport/src/connection_manager.rs:273-292: only the lower NodeId dials.
  • The CUP cannot reach the old replica any other way. The replica reads its CUP file only at startup, and /_/catch_up_package is read-only.

Invalidating it on the old replica:

  • rs/consensus/src/consensus/priority.rs:111: a CUP is always Wants.
  • rs/consensus/src/consensus/validator.rs:1716-1757: H+1000 is within the validation range.
  • rs/consensus/cup_utils/src/lib.rs:150-185: the signer check passes.
  • rs/crypto/src/sign/threshold_sig.rs:407: CspSignature::try_from fails before the registry lookup at :409. The error is reproducible, so it becomes InvalidArtifact.
  • consensus_pool.rs:498-499,771-780: HandleInvalid increments invalidated_artifacts and logs the WARN.

Halting:

  • halt_at_cup_height only blocks block making and batch delivery. The old replicas keep logging "Batch of height H+1 is not delivered because replica is halted", which shows on_state_change and the validator keep running.
  • rs/registry/canister/src/mutations/do_recover_subnet.rs:71-80: the recovery turns halt_at_cup_height into is_halted=true.
  • rs/consensus/src/consensus.rs:406-414: with is_halted, consensus returns before any subcomponent, including the validator.
  • The replica's registry client polls the local store every 5 s (rs/interfaces/registry/src/lib.rs:13). From local store to "consensus is halted by instructions" took 0.17–4.85 s.

Metric check:

  • rs/tests/driver/src/driver/group.rs:469-480: the default replica metrics include consensus_invalidated_artifacts with a maximum of 0.
  • rs/tests/driver/src/driver/test_env_api.rs:1128-1182: one read per node per endpoint. An unreachable node is skipped with an INFO line, and the first node over its limit panics.
  • group.rs:650-671: update_orchestrator_metrics_to_check, which the panic message suggests, only edits the orchestrator map, so it cannot relax this replica metric. Only remove_metrics_to_check can.

Scope

Why only cup_explorer_test. It is the only system test that both halts with halt_at_cup_height alone and recovers via RecoverSubnet with an unchanged replica version, and it ends about 8 s after the proposal. The sr_* tests are not affected:

  • Some take the subnet offline first (is_halted), so the old replicas stop validating.
  • Others change the replica version, which gives ReplicaVersionMismatch → RemoveFromUnvalidated, with no metric.
  • All of them wait for finalization above 1000 on every app node before the check, so the laggards have restarted with fresh counters.

On the PR branch, 264 of 266 recovery-test runs passed, and the 2 flakes have unrelated signatures. The nested nr_* NNS recovery tests never ran on this PR.

Production (unverified). ic-recovery's Halt step takes the subnet offline before any recovery CUP exists, so old replicas never validate it, on master or on the PR. The chain:

  • rs/recovery/src/app_subnet_recovery.rs:439-452
  • lib.rs:274-290
  • admin_helper.rs:84-119
  • rs/registry/admin/bin/main.rs:935-958 (DOWN_FOR_REPAIRS)
  • do_set_subnet_operational_level.rs:226-232 (is_halted=true)

Only flows that rely on halt_at_cup_height alone, or recover an un-halted subnet, are exposed. Nobody checked whether alerts use this metric or the WARN.

Flake rate

  • Once a straddle happens, NodeId order and the 5 s registry-poll phase decide pass or fail, sometimes by tens of ms. The outcome is effectively random, so a timing tweak will not make the test reliable.
  • A replay of master's timings with the PR's same-tick restart and both gates predicts about 9–14% failed attempts, depending on the baseline week. Observed: 20% (7/35). That is roughly consistent at these sample sizes.
  • The PR does not change tick or replicator timing. CHECK_INTERVAL_SECS and the replicator are untouched, and the tick-phase distributions match master.

Fix directions (untested, ranked)

  1. Consensus: don't send unsigned CUPs. In get_all_for_initial_broadcast, .filter(|cup| cup.is_signed()) at consensus_pool.rs:956-963.
    • It removes the cause: no peer can ever validate another node's unsigned CUP, and every orchestrator builds the registry CUP itself.
    • Unsigned CUPs sent by malicious peers still count as invalid.
    • /_/catch_up_package and the CUP explorer are unaffected.
    • Only test_get_all_validated needs adjusting, because fake CUPs are unsigned.
    • This belongs to the consensus team and would be a separate PR. Edge case, not verified: the unsigned random beacon at the recovery height can be invalidated only if the recovery height equals the old replica's beacon tip + 1.
  2. Test: wait for all app nodes to restart. In cup_explorer_test, after recovery, wait until every app node's orchestrator has restarted the replica, i.e. orchestrator_processes_start_attempts_total{process_name="replica"} >= 2 on :9091. Then the check reads the new replicas.
  3. Receiver side: RemoveFromUnvalidated instead of HandleInvalid when an unsigned CUP fails crypto.
    • This loses the signal for misbehaving peers.
    • It only helps once the pre-recovery replica version contains it.
    • An up-front is_signed() check would break validator unit tests that use unsigned fake CUPs.
  4. remove_metrics_to_check("consensus_invalidated_artifacts"). This is too blunt: it disables the check for all nodes and both sub-tests. Acceptable only as a commented stopgap pointing at option 1.
  5. Orchestrator: defer the start to the next tick. This is a timing hack. It brings back about 10 s of downtime and breaks two of the PR's new unit tests (processes.rs:612, upgrade.rs:3631-3691).

Not evaluated: have the test set is_halted before RecoverSubnet, as ic-recovery does. That would change what the test covers.

Caveats

  • Not reproduced on demand. The evidence is log forensics over 7 failed attempts, 27 checkable passed PR attempts and 222 master runs, plus code reading at both revisions.
  • Timestamps. Cross-node orderings at the millisecond level are within clock uncertainty: ≤ about 65 ms for _local on 10-14/15 and about 50 ms on farm. The 10-02 _local node clocks were corrected by 0.6–1.55 s. Causality rests on the code path plus consistent co-occurrence, not on strict timestamp order.
  • Test version. 6 of the 7 tested PR commits ran the test from before feat(cup_explorer): extract the threshold master public keys of a CUP #11786/fix: deflake //rs/tests/consensus:cup_explorer_test #11841: no test_extract_master_public_keys, and a different system-subnet DKG interval. The app-subnet mechanism is unaffected.
  • Not checkable. The _farm 2026-10-15 attempt cannot be classified, because its ES logs end before the recovery. Master _farm runs have no node logs.

Other flakes on the PR branch this month (unrelated signatures)

  • sr_app_same_nodes_with_chain_keys_test_head_nns_local: setup SSH health timeout.
  • sr_app_no_upgrade_enable_chain_keys_test_farm_colocate: ValidateReplayOutput, the known ic-replay race.
  • standard_engine_replica_version_test_local: "never came back online", also FLAKY 4 times on master.
  • ipv4_integration_test_head_nns_local and query_stats_above_threshold_local: different errors, not investigated.

Files

  • Logs. PR _local: 2026-10-16T07:24:57/, and 2026-10-16T07:25:50/2026-10-02T14:16:01_*. PR farm with ES IC logs: ../rca_pr_farm/. Master _local passes: ../rca_master_local/.
  • rca/scripts/:
    • jr.py: journald JSON extractor (jr.py LOG [regex] [--node P] [--crate R]).
    • recovery_timeline.py: per-node recovery timeline.
    • scan_runs.py: one line per attempt.
  • rca/agent_reports/: verdicts of the verification workflow. 5 investigations (orchestrator timing, replica gossip and validation, farm ES logs, metric check, fix directions), 3 skeptics (none refuted the claim, all with high confidence) and a completeness critic.
  • rca/agent_work/: their scripts and outputs. Notable:
    • skeptic_mech/halt_margin*: master's structural margin.
    • skeptic_mech/gated_cf*: the gated rate model.
    • replica_lens/bin/gates.py: the connection and halted gates.
    • metric_lens/master_straddle_partial.txt: the master straddle and partial runs.

@pierugo-dfinity

Copy link
Copy Markdown
Contributor Author

Thank you Bas this is very helpful!

@pierugo-dfinity

Copy link
Copy Markdown
Contributor Author

Summarized the issue and suggested fix number 1 in #11873

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]>
AleDema pushed a commit to AleDema/ic that referenced this pull request Oct 18, 2026
…lica before the crypto vault (dfinity#11874)

`ipv4_integration_test_head_nns_local` flaked on dfinity#11744 after removing
its unassigned node and letting it register itself again: the registry
stayed at version 3 until the 180 s timeout. The cause is a race in the
test's re-registration script that already exists on master:

1. The script stopped `ic-crypto-csp` (the crypto vault) before
`ic-replica` (the orchestrator). The vault is socket-activated, and the
orchestrator's vault client reconnects about 100 ms after losing its
connection. If the orchestrator is still alive at that point, the
reconnect starts a new vault, which can read the old `public_keys.pb`
and `sks_data.pb` before the script deletes them.
2. The node then comes back with its old keys and node ID. The
orchestrator checks its registration only once at startup, against a
local registry copy that predates the removal. The check passes
silently, so the node never registers again.

On master the vault was started again this way in 4 of 223 `_local`
attempts (2026-10-02..16). A failure also needs the new vault to read
the key files before the `rm`. The same timeout failed 4 Farm runs in
Jan–Mar 2026.

The fix changes both scripts that use this pattern:
`ipv4_integration_test` and `node_registration_test_common`, which the
two node registration tests share.
- Stop `ic-replica` first, then `ic-crypto-csp.socket` together with
`ic-crypto-csp.service`. No vault client is left to reconnect, and the
closed socket cannot start the vault before the keys are deleted. Start
the socket and the service again afterwards.
- Assert that the node registered with a new node ID. This catches a
node re-registering under its old ID, where the test would otherwise
pass. That happened once on master in
`node_registration_with_node_allowance_test_local`.

Verification, with local `_local` runs:
- Master's script with `sleep 0.3` between the two stops, which forces
the reconnect, failed 2 of 2 runs with the flake's signature: the old
node ID and a timeout at registry version 3.
- With this change, `ipv4_integration_test_local`,
`ipv4_integration_test_head_nns_local`,
`node_registration_with_node_allowance_test_local` and
`node_registration_with_max_rewardable_nodes_test_local` passed, and
each node registered with a new ID.

Labelled `CI_ALL_BAZEL_TARGETS` so that CI runs these system tests:
`ipv4_integration_test` is a `long_test`.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
@pierugo-dfinity
pierugo-dfinity added this pull request to the merge queue Oct 19, 2026
Merged via the queue into master with commit 3f40896 Oct 19, 2026
41 checks passed
@pierugo-dfinity
pierugo-dfinity deleted the pierugo/orchestrator/wait-for-process-to-exit branch October 19, 2026 11:12
maksym-arutyunyan pushed a commit to maksym-arutyunyan/ic that referenced this pull request Oct 20, 2026
CUPs taken from the registry, like genesis or recovery CUPs, are
unsigned but totally legitimate and end up in the replica's validated
pool on [replica
startup](https://sourcegraph.com/r/github.com/dfinity/ic@a5a6d8d45414a0303af808c8ef38eb428e5b89ea/-/blob/rs/artifact_pool/src/consensus_pool.rs?L481),
without checking their signatures (which would fail because empty). P2P
then replicates this artifact to the other peers' unvalidated pools,
which cannot validate it since the signature is missing and this could
raise an alert for suspicion of malicious behaviour.

Luckily, this rarely happens in production because:
- On genesis, the other peers will not pull this artifact because they
already have it in their own pools (passed by their own orchestrator).
- On recoveries, the same reasoning applies though there is still a
window where replica A has restarted with the new unsigned CUP, that
replica B pulls while still running the old replica. In practice though,
the subnet is normally
[halted](https://sourcegraph.com/r/github.com/dfinity/ic@a5a6d8d45414a0303af808c8ef38eb428e5b89ea/-/blob/rs/recovery/src/app_subnet_recovery.rs?L35-40)
and thus [does not validate any
artifact](https://sourcegraph.com/r/github.com/dfinity/ic@a5a6d8d45414a0303af808c8ef38eb428e5b89ea/-/blob/rs/consensus/src/consensus.rs?L407-415).
- On recoveries where the subnet is not `is_halted` but is
`halt_at_cup_height` (like in verifiable recoveries for resharing
chain-keys), there the validator still runs. For now, the alert never
triggered probably because the orchestrator stops the replica and
restarts it only at the next iteration of the upgrade loop 10 seconds
later, which considerably reduces the timing window. With
dfinity#11744 though, the replica will be
restarted right away, and we might observe this alert.

For good practice, do not make replicas broadcast unsigned CUPs during
pool initialization since other replicas would not be able to validate
it anyways.

Kudos to @basvandijk for detecting the flakiness on the aforementioned
PR and suggesting a fix!

---------

Co-authored-by: Leo Eichhorn <[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