Skip to content

feat(replica): wait for the latest checkpoint's verification on shutdown - #12094

Merged
alin-at-dfinity merged 11 commits into
masterfrom
alin/replica-graceful-shutdown
Nov 18, 2026
Merged

alin-at-dfinity merged 11 commits into
masterfrom
alin/replica-graceful-shutdown

Conversation

@alin-at-dfinity

@alin-at-dfinity alin-at-dfinity commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

On SIGTERM, the replica's main returns without waiting for anything. The sandbox launcher, in the same process group and cgroup, gets the same SIGTERM and dies, which makes the replica abort. A checkpoint still being verified is abandoned. On restart, the replica archives it and state-syncs instead, re-reading and rehashing its whole local state: ~1 TB in ~4 minutes on a large mainnet subnet. Upgrades and reboots stop the replica this way. Upgrades lose this race regularly: the upgrade CUP needs only 2f+1 shares, so a slower node can get it while still verifying its checkpoint at that height. An estimated 26–36% of upgrades of large subnets lose it on at least one node.

With this change:

  • State Manager: a new StateManagerImpl::wait_for_latest_checkpoint() waits until the latest checkpoint is verified and its manifest persisted, checking every 100 ms, so that a restart neither archives the checkpoint nor recomputes its manifest. It doesn't wait for the rest of the checkpoint work (resetting the tip, merging), nor for a checkpoint the replica hasn't reached yet.
  • Replica: after SIGTERM or SIGINT, it calls wait_for_latest_checkpoint(), then exits right away, without tearing down the IC stack: the teardown would wait for the tip thread's queued work (resetting the tip, merging), which a restart redoes anyway, and stop the artifact processors while P2P still delivers to them. A watchdog exits with status 1 after 55 s.
  • Launcher, canister and compiler sandboxes: they ignore SIGTERM and SIGINT, which the replica handles, and exit when their socket to the replica reaches EOF, i.e. once the replica has exited. The compiler sandbox first finishes any compilation in progress. As this is in the shared sandbox entry points, sandboxes started by PocketIC, ic-replay, ic-recovery and the fuzzers also ignore both; they still exit on EOF. PocketIC handles Ctrl-C by deleting its instances, so that shutdown now runs with live sandboxes, like the replica's.
  • Orchestrator: it waits 60 s instead of 30 s after SIGTERM before sending SIGKILL, longer than the replica's 55 s. Both are below the 90 s systemd allows at reboot.

Testnet check, with an earlier version that tore down the IC stack after the wait: a single-node app subnet with ~5,000 canisters and 1.2 TB of state, at a typical load, stopped with systemctl stop ic-replica (the testnet's own orchestrator, with its 30 s grace period):

  • Right after checkpoint 405500 was created, before it was verified: the replica waited 20.7 s, 1.0 s of it for the verification and the rest for the manifest, then shut down. The testnet's orchestrator killed it at its 30 s grace period, after the manifest was persisted. No launcher or sandbox process was left, and on restart nothing was archived.
  • With no checkpoint pending: no wait, exit status 0 after 1.3 s.

The watchdog's 55 s cover the wait: validating a checkpoint took up to 39 s on the same testnet with 200k canisters, under load, with the manifest computed concurrently. If the wait takes longer, the replica exits with status 1 and the checkpoint is archived on restart, as without this change.

Tests: wait_for_latest_checkpoint() returns once a new checkpoint is verified and its manifest published; and the launcher and both sandboxes, started for real, surviving SIGTERM and SIGINT and exiting 0 on EOF (Linux only; with the default SIGTERM action, all three fail).

🤖 Generated with Claude Code

On SIGTERM, the replica returned at once and the sandbox launcher, getting the
same SIGTERM, died, aborting the replica and abandoning the verification of
its latest checkpoint, which the next start then archived and state-synced.

The replica now waits until its latest checkpoint is verified, with a 30 s
watchdog, before shutting down. The launcher and sandboxes ignore SIGTERM and
exit once the replica's socket closes. The orchestrator waits 45 s instead of
30 s before escalating to SIGKILL.

Co-Authored-By: Claude Opus 5.5 <[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.

🟡 Changes recommended

Process-group SIGINT still kills child processes and triggers a replica-aborting panic that bypasses the checkpoint-verification wait, while the unguarded /proc-based test fails on macOS.

2 open issues
What changed in this PR

This PR reduces checkpoint loss during replica shutdown by waiting for the latest local checkpoint to finish verification. It complements the orchestrator’s upgrade-time verification gate in #12093.

Changes:

  • Adds checkpoint-status lookup and shutdown polling, bounded by a 30-second watchdog.
  • Makes sandbox processes ignore SIGTERM and rely on socket closure for shutdown; extends the orchestrator’s grace period to 45 seconds.
  • Adds checkpoint-status and child-process shutdown tests.
File Description
rs/​state_layout/​src/​state_layout/​tests.rs Tests latest-checkpoint selection and status detection.
rs/​state_layout/​src/​state_layout.rs Adds filesystem-based latest-checkpoint status lookup.
rs/​replica/​Cargo.toml Adds the state-layout dependency.
rs/​replica/​BUILD.bazel Adds the matching Bazel dependency.
rs/​replica/​bin/​replica/​main.rs Adds verification waiting and a shutdown watchdog.
rs/​orchestrator/​src/​process_manager.rs Extends the shutdown grace period to 45 seconds.
rs/​canister_sandbox/​src/​replica_controller/​sandboxed_execution_controller.rs Tests SIGTERM survival and exit on socket closure.
rs/​canister_sandbox/​src/​lib.rs Adds shared SIGTERM handling for child processes.
rs/​canister_sandbox/​src/​launcher.rs Makes the launcher ignore SIGTERM.
rs/​canister_sandbox/​src/​compiler_sandbox.rs Makes the compiler sandbox ignore SIGTERM.
Cargo.lock Records the replica’s state-layout dependency.

Review effort: Balanced

Comment thread rs/canister_sandbox/src/lib.rs Resolved
…tor's SIGKILL

Verifying a checkpoint takes ~31 s with 200k canisters, and shutting down took
16 s on a 1.2 TB testnet state, so 30 s could cut the wait short. Both limits
stay below the 90 s systemd allows at reboot.

Co-Authored-By: Claude Opus 5.5 <[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.

🔵 Needs a closer look

Process-group SIGINT can still abort the replica before checkpoint verification finishes, and the new procfs-dependent test fails on macOS without a Linux gate or portable readiness check.

2 open issues

Review effort: Balanced

…inux only

The replica handles SIGINT like SIGTERM, but a process-group SIGINT (e.g.
Ctrl-C) still killed the launcher and sandboxes, making the replica abort. The
test reads `/proc`, so it now runs only on Linux, like this module's other
`/proc`-based tests.

Co-Authored-By: Claude Opus 5.5 <[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.

🔵 Needs a closer look

The watchdog’s synchronous error logging can block on output or a shared drain mutex before reaching process::exit(1), defeating the 55-second deadline.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Avoid blocking logging before watchdog process exit

rs/​replica/​bin/​replica/​main.rs:92

The watchdog can block before reaching process::exit(1): Error-level logging writes synchronously through a shared drain mutex (rs/monitoring/logger/src/lib.rs:62–91). If the output destination blocks or a stuck log write holds that mutex, this diagnostic defeats the 55-second deadline. Remove the synchronous diagnostic and its unused import/logger argument, or use a genuinely nonblocking diagnostic path.

2 resolved since last review

Review effort: Balanced

…tor's SIGKILL

Validating a checkpoint took 35–39 s on a 1.2 TB testnet state with 200k
canisters, under load, and shutting down took 16 s, so 55 s could still cut the
wait short. Both limits stay below the 90 s systemd allows at reboot.

Co-Authored-By: Claude Opus 5.5 <[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.

🔵 Needs a closer look

Human assessment is needed because synchronous watchdog logging can block the forced exit, undermining the replica’s 70-second shutdown deadline.

No open issues 🎉

Review effort: Balanced

…ng for the checkpoint marker

`StateManagerImpl::shutdown()` waits until the latest checkpoint is verified and
its manifest published, skipping the queued work that only matters to a replica
that keeps running: resetting the tip, merges not yet started and the rehash.
The replica calls it after SIGTERM or SIGINT, instead of polling the file system
for the checkpoint's unverified marker.

Co-Authored-By: Claude Opus 5.5 <[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.

🟡 Changes recommended

Shutdown enables skipping ResetTipAndMerge while batch delivery and commits remain active, risking invalid or unverified checkpoints; delivery must stop and in-flight commits drain before the flag is enabled, with verification workers kept alive.

1 open issue

Review effort: Balanced

Comment thread rs/replica/bin/replica/main.rs Resolved
…d checkpoint work

No wait can guarantee verifying the checkpoint a node should stop at, since a slow
node may not even have reached it; so `shutdown()` no longer loops until the latest
checkpoint is verified. Also moves it after the constructors.

Co-Authored-By: Claude Opus 5.5 <[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.

🔵 Needs a closer look

Human assessment is needed because checkpoint creation during shutdown can omit heap or stable-memory data while still passing validation, creating a critical data-loss risk.

1 open issue

Review effort: Balanced

…heckpoint()`

We can't shut the State Manager down properly without tearing down everything
that holds it, so a flag skipping its work would make it misbehave if the
replica kept running. Instead, the replica waits for the symptom: the latest
checkpoint verified and its manifest persisted, checking every 100 ms, so that
a restart neither archives the checkpoint nor recomputes the manifest.

Co-Authored-By: Claude Opus 5.5 <[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.

🟡 Changes recommended

Shutdown can treat an unverified state-sync checkpoint as verified and abandon regular checkpoint verification, while the new test does not confirm that manifest persistence completes before the wait returns.

3 open issues

Review effort: Balanced

Comment thread rs/state_manager/src/lib.rs Resolved
Comment thread rs/state_manager/tests/state_manager.rs Resolved
@alin-at-dfinity
alin-at-dfinity marked this pull request as ready for review November 17, 2026 21:17
@alin-at-dfinity
alin-at-dfinity requested a review from a team as a code owner November 17, 2026 21:17
@zeropath-ai

zeropath-ai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

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

Security Overview
Detected Code Changes
Change Type Relevant files
Refactor ► rs/canister_sandbox/src/compiler_sandbox.rs
    Add crate::ignore_shutdown_signals() call in compiler_sandbox_main
Refactor ► rs/canister_sandbox/src/launcher.rs
    Call ignore_shutdown_signals() in sandbox_launcher_main
Refactor ► rs/canister_sandbox/src/lib.rs
    Add use nix::sys::signal::{SigHandler, Signal, signal};
► rs/canister_sandbox/src/lib.rs
    Introduce ignore_shutdown_signals() function to ignore SIGTERM and SIGINT
Refactor ► rs/canister_sandbox/src/replica_controller/sandboxed_execution_controller.rs
    No direct file-level changes aside from context in test area; (part of related test enhancements)
Enhancement ► rs/replica/bin/replica/main.rs
    Add SHUTDOWN_TIMEOUT constant and integrate shutdown watchdog behavior during shutdown sequence
Enhancement ► rs/replica/src/setup_ic_stack.rs
    Modify return types to reflect StateManagerImpl usage and related test hooks
Enhancement ► rs/state_manager/src/lib.rs
    Add wait_for_latest_checkpoint() to wait for verification and manifest persistence before restart; include loop with timeout and logging
Enhancement ► rs/state_manager/tests/state_manager.rs
    Add test wait_for_latest_checkpoint_waits_for_verification_and_manifest

Comment thread rs/replica/bin/replica/main.rs Resolved
When `main` returns, the IC stack's join guards stop the artifact processors
while P2P keeps running on its runtime, so P2P logs an error for every artifact
it can no longer deliver. Shut down P2P's runtime right after waiting for the
latest checkpoint instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 18, 2026 10:49

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.

🟢 Approval recommended

No active review issues are recorded for the checkpoint-aware shutdown changes.

No open issues 🎉

Review effort: Balanced

@pierugo-dfinity

Copy link
Copy Markdown
Contributor

Something else that we could potentially explore:
If despite these changes, the replica starts with an unverified checkpoint, it could recompute the manifest locally and compare it with the CUP's state hash (that we could pass to StateManagerImpl's constructor). If they match, the replica does not need to state sync. If they don't, fall back to state sync.

With the changes of this PR, this scenario should happen much less frequently though, so I'm not sure how much of an improvement it would be.

Comment thread rs/replica/bin/replica/main.rs Resolved
Comment thread rs/replica/bin/replica/main.rs Resolved
Comment thread rs/orchestrator/src/process_manager.rs Resolved
Returning from `main` drops the IC stack: the State Manager's tip thread then
works through its queued checkpoint work (resetting the tip, merging) before
the process can exit, and shutting down P2P's runtime first could make a busy
sender loop panic on a cancelled task. Exit with `std::process::exit` right
after the wait instead, logging "IC Replica Terminating" while the async log
guard still exists. Without the teardown, 55 s cover the wait (verifying a
checkpoint took up to 39 s with 200k canisters under load), so the replica's
watchdog and the orchestrator's grace period go back to 55 s and 60 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 18, 2026 14:11
@alin-at-dfinity

Copy link
Copy Markdown
Contributor Author

@pierugo-dfinity Thanks, that's a good idea for a follow-up. Computed incrementally from the previous checkpoint's manifest, as at checkpoint time, it would cost about as much as a regular manifest (seconds on mainnet), rather than state sync's full rehash (about 4 minutes on large subnets). As this PR makes the case rare, I'd keep it separate.

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

Human assessment is needed because synchronous logging can block the watchdog and prevent it from enforcing the 55-second shutdown bound.

No open issues 🎉

Review effort: Balanced

Comment thread rs/replica/bin/replica/main.rs Resolved
`std::process::exit` runs no destructors, so the non-blocking log writer's
guard was never dropped, and whatever it still buffered at exit was lost.
Drop it explicitly right before exiting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 18, 2026 19:26

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

The final process::exit path bypasses IC-stack teardown, but testing covered an earlier version, leaving checkpoint reuse and child-process cleanup during shutdown and restart unverified.

No open issues 🎉

Review effort: Balanced

@alin-at-dfinity
alin-at-dfinity added this pull request to the merge queue Nov 18, 2026
Merged via the queue into master with commit c7010c4 Nov 18, 2026
44 checks passed
@alin-at-dfinity
alin-at-dfinity deleted the alin/replica-graceful-shutdown branch November 18, 2026 20:35
basvandijk added a commit that referenced this pull request Nov 18, 2026
…azel-lockfiles

Cargo.lock conflicted only in nss_icos's dependency list. Resolved by
taking this branch's Cargo.lock and running `cargo update --workspace`,
which applied master's manifest changes (#12021, #12094) and moved no
versions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
AleDema pushed a commit to AleDema/ic that referenced this pull request Nov 21, 2026
…amp cache on first use (dfinity#12192)

Loading a canister from a checkpoint rebuilds its log memory store's
first-timestamp cache by reading the ring buffer, which maps the store's
overlay file; dropping the loaded state then has to unmap it. Validating
a checkpoint loads every canister only to compare and drop it: with 200k
canisters, each drop took 0.57–0.65 ms, mostly in `munmap`, waiting for
the replica's memory map lock and flushing TLBs.

This leaves the cache empty on load and fills it on the first
`first_timestamp` call. Clones share it until mutated (every mutation
sets a fresh one), so the value the background metrics observation fills
in a committed state is there in the next round's state too, instead of
being recomputed every round.

Full checkpoint loads (at startup, or after state sync) still fill both
the header and first-timestamp caches, in the loader threads:
`ReplicatedState::new_from_checkpoint` sequentially reads every cold
canister's header (for its memory usage), and the retention metric
requires every store's first timestamp. Only validation leaves them
empty.

On a testnet node with 200k canisters under load, dropping a loaded
canister takes 3.2 µs instead of 634 µs, and validating a checkpoint
15.0 s instead of 19.2 s; most of the rest is `syncfs`, waiting for the
protobufs' writeback. That also shortens the shutdown wait for the
latest checkpoint's verification (dfinity#12094).

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

---------

Co-authored-by: Claude Opus 5.5 <[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