Repository navigation
feat: Store the canisters' consumed cycles in SubnetMetrics - #11297
Conversation
`SubnetMetrics::consumed_cycles_total` reports all cycles removed from
circulation on the subnet: a subnet-level aggregate, plus the cycles consumed by
the canisters that currently exist. The subnet-level half is a stored field,
while the canisters' half was folded out of `CanisterStates` by each consumer on
demand -- `O(|hot canisters|)` per read, and evaluated at a different point in
the round than the half it is added to.
Hold the canisters' half in a new `SubnetMetrics::consumed_cycles_by_canisters`,
refreshed once per round, and add `consumed_cycles_total_including_canisters()`
as the single `O(1)` definition of the total. The canonical state tree at
`/subnet/<subnet_id>/metrics` reads that, so `encode_subnet_metrics` no longer
takes the canisters' contribution as a parameter and the `/subnet` subtree does
not need `CanisterStates` at all.
The refresh lives in `StateManagerImpl::commit_and_certify`, beside
`repartition_canister_states()`. That is the one choke point every committed
state passes through, with nothing able to mutate a canister between the refresh
and the hash; refreshing earlier (in message routing or the scheduler) would go
stale, because canisters are still charged afterwards -- HTTP spend refunds,
stream-builder rejects, message shedding -- and because drivers such as
`StateMachine` tests never run message routing at all. Like the repartitioning,
it must therefore stay unconditional.
The field is transient: it is not persisted, is marked `#[validate_eq(Ignore)]`
so that `validate_eq_checkpoint` does not compare it against a checkpoint that
does not carry it, and is derived from the loaded canisters by
`ReplicatedState::new_from_checkpoint`. `SubnetMetrics` derives `ValidateEq` and
`SystemMetadata::subnet_metrics` is compared with `CompareWithValidateEq` so the
exemption covers this field alone and the rest of the struct stays validated
field by field. This follows `SystemMetadata::subnet_ids_at_last_reject_generation`
and `RefundPool::{amounts, total}`.
Deriving at load is what makes a replica restarting from a checkpoint agree with
one that kept running, and hence certify the same
`/subnet/<subnet_id>/metrics` leaf; `consumed_cycles_by_canisters_is_rederived_at_restart`
pins it. The certified encoding is unchanged, as the untouched expected bytes in
`encoding/tests/compatibility.rs` show, and so is the state hash.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Stores canister-consumed cycles in subnet metrics for consistent, constant-time certified-state encoding.
Changes:
- Refreshes the aggregate whenever state is committed or restored.
- Uses the stored aggregate for V29 canonical encoding.
- Adds restart and compatibility coverage.
Reviewed changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
rs/state_manager/tests/state_manager.rs |
Tests restart derivation and hash stability. |
rs/state_manager/src/lib.rs |
Refreshes the aggregate before hashing. |
rs/replicated_state/src/replicated_state.rs |
Derives and refreshes the aggregate. |
rs/replicated_state/src/metadata_state/proto.rs |
Initializes the transient field on decode. |
rs/replicated_state/src/metadata_state.rs |
Defines the field and total calculation. |
rs/canonical_state/tests/compatibility.rs |
Updates compatibility encoding invocation. |
rs/canonical_state/src/traversal.rs |
Tests traversal with the stored aggregate. |
rs/canonical_state/src/lazy_tree_conversion.rs |
Removes canister-state dependency from subnet traversal. |
rs/canonical_state/src/encoding/types.rs |
Uses the new total calculation for V29. |
rs/canonical_state/src/encoding/tests/compatibility.rs |
Preserves expected encoded bytes. |
rs/canonical_state/src/encoding.rs |
Simplifies the subnet metrics encoder API. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
`ReplicatedStateMetrics::observe` reconstructed the total consumed cycles by folding over the canisters and adding the subnet-level fields itself, duplicating the accounting rules that `SubnetMetrics::consumed_cycles_total_including_canisters()` already encodes for the certified state tree. Set the gauge from that aggregate instead, so the Prometheus value cannot drift from the certified one when a use case changes. The per-use-case breakdowns keep their folds, as no aggregate holds them. `consumed_cycles_by_canisters` is refreshed in `StateManagerImpl::commit_and_certify` right before the observed state is handed off to the metrics thread, so the canisters' half is up to date. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
✅ No security or compliance issues detected. Reviewed everything up to 34ad262. Security OverviewDetected Code Changes
|
alin-at-dfinity
left a comment
There was a problem hiding this comment.
Only a couple of nitpicks and ranting about Claude's exceedingly verbose comments.
| // Transient, with no corresponding proto field: | ||
| // `ReplicatedState::new_from_checkpoint` derives it from the canisters | ||
| // it loads. | ||
| consumed_cycles_by_canisters: NominalCycles::zero(), |
There was a problem hiding this comment.
The usual approach we take with transient fields is to initialize them as early as possible by precomputing the value and passing it into the TryFrom implementation along the proto: impl TryFrom<(pb_foo::Foo, NominalCycles)> for Foo. That way you wouldn't e.g. need the #[validate_eq(Ignore)] and rely on checkpoint validation as an additional consistency check.
There was a problem hiding this comment.
That approach would have two downsides:
ReplicatedState::new_from_checkpointdoes not derive the field anymore so some tests using that would get the default zero value;- the
validate_eq_checkpointwould need to derive the value "manually" by changingvalidate_eq_canister_statesfromResult<(), String>toResult<NominalCycles, String>)and computing it inside.
There was a problem hiding this comment.
ReplicatedState::new_from_checkpoint would derive the field: it first loads the canisters, computes their consumed cycles, then passes the amount to the metadata state loader.
Otherwise you wouldn't be able to construct a MetadataState. And that's precisely the point.
I believe the same applies to validate_eq_checkpoint: every MetadataState would have to have an accurate (at least as of last round) consumed_cycles_by_canisters; there's never any need to guard against "what if it wasn't set?".
There was a problem hiding this comment.
Else, I suppose you could move consumed_cycles_by_canisters into CanisterStates, so it's initialized as soon as canister states are loaded. But that may break users that only have the MetadataState, not CanisterStates; or whenever you temporarily remove a canister from CanisterStates to mutate it.
There was a problem hiding this comment.
ReplicatedState::new_from_checkpoint would derive the field: it first loads the canisters, computes their consumed cycles, then passes the amount to the metadata state loader.
ReplicatedState::new_from_checkpoint receives the components as input arguments:
pub fn new_from_checkpoint(
canister_states: BTreeMap<CanisterId, Arc<CanisterState>>,
mut metadata: SystemMetadata,
subnet_queues: CanisterQueues,
refunds: RefundPool,
epoch_query_stats: RawQueryStats,
) -> Self {
So I'll keep the merged version.
`consumed_cycles_by_canisters_is_rederived_at_restart` compared the hashes returned by `wait_for_checkpoint`, which are manifest hashes over the checkpoint's on-disk files. The aggregate is deliberately not persisted, so the manifest cannot observe it and the comparison did not pin the property the test claimed to. Comparing certified state hashes instead would not help today either: `commit_and_certify` overwrites `certification_version` with `CURRENT_CERTIFICATION_VERSION` (V28), and the `/subnet/<subnet_id>/metrics` leaf only includes `consumed_cycles_by_canisters` from V29 on. Drop the test for now; it can return, comparing the hashes from `list_state_hashes_to_certify`, once `CURRENT_CERTIFICATION_VERSION` is V29. That the leaf covers the field at V29 stays pinned by the traversal test in `rs/canonical_state/src/traversal.rs`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Alin Sinpalean <[email protected]>
Address review feedback: the doc comment on `refresh_consumed_cycles_by_canisters` explained what its caller does and when, which belongs in (and was already duplicated by) the inline comment in `commit_and_certify`. Keep the doc comment to what the method is, and make the caller's comment carry the "must stay unconditional" reasoning on its own. Also drop the observation about ordering against `repartition_canister_states`, which is irrelevant there. Trim the same verbosity from the two neighbours it applies to: the `consumed_cycles_by_canisters` field doc and the gauge comment in `ReplicatedStateMetrics::observe`. Comments only; no behaviour change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…oint `consumed_cycles_total_including_canisters` conflicted only in its doc comment: master landed #11297 (the same work this branch had merged from `mraszyk/store-consumed-cycles-by-canisters`) listing two consumers of the definition, while this branch lists three. Kept ours -- the `subnet_metrics` management canister method is the third consumer, and this branch is what adds it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
All mainnet subnets run replica versions supporting up to `V29`, so the current certification version can be bumped to `V29`. This makes the fixed `consumed_cycles_total` (which no longer double counts the cycles consumed by deleted canisters and additionally includes the cycles consumed by all non-deleted canisters) visible in `/subnet/<subnet_id>/metrics`. `SystemMetadata` encodes the current certification version, hence the expected hashes in `rs/state_manager/src/manifest/split/tests.rs` had to be updated. ## Tests The cycles consumed by the canisters that still exist are not persisted: they are derived by `ReplicatedState::new_from_checkpoint` on load and refreshed by `StateManagerImpl::commit_and_certify` on every committed state. Now that `/subnet/<subnet_id>/metrics` certifies them, three `StateMachine` tests pin that, as promised in dfinity#11297. - `subnet_metrics_are_unchanged_across_a_restart` writes a checkpoint and restarts the node, asserting the same `SubnetMetrics` and the same certified `/subnet/<subnet_id>/metrics` leaf, read via `read_certified_state`. - `consumed_cycles_in_subnet_metrics_are_refreshed_every_round` installs a heartbeat burning cycles every round, and after each tick asserts the aggregate against one recomputed from the state, and that it grew by at least the burned amount. - `consumed_cycles_in_subnet_metrics_are_refreshed_when_a_canister_is_deleted` deletes the only canister on the subnet, so that nothing else consumes cycles meanwhile and the aggregate can be pinned to exactly the balance burned with it -- the canister's consumption having merely moved from the canisters' part into `consumed_cycles_by_deleted_canisters`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
SubnetMetrics::consumed_cycles_total()reports the cycles removed fromcirculation by the subnet itself and by canisters that have since been deleted:
a sum over three scalar fields plus the subnet-level entries of
consumed_cycles_by_use_case. The cycles consumed by the canisters thatcurrently exist are not part of it; every consumer of the full total folded them
out of
CanisterStatesand added them on. That fold isO(|hot canisters|)(the cold pool keeps a precomputed aggregate), it was spelled out once per
consumer, and it forced the
/subnetsubtree of the canonical state to dependon
CanisterStatesfor a single leaf.Hold the canisters' part in a new
SubnetMetrics::consumed_cycles_by_canisters,refreshed once per round, and add
consumed_cycles_total_including_canisters()as the single definition of the full total -- constant time, being
consumed_cycles_total()plus one field. The canonical state tree at/subnet/<subnet_id>/metricsreads that starting from the certification versionV29, which is not yet enabled (CURRENT_CERTIFICATION_VERSIONis stillV28), soencode_subnet_metricsno longer takes the canisters' contributionas a parameter and the
/subnetsubtree does not needCanisterStatesat all.The
replicated_state_consumed_cycles_since_replica_startedgauge reports thesame definition:
ReplicatedStateMetrics::observeno longer accumulates thecanisters' consumed cycles while iterating them, nor adds the subnet-level use
cases one by one afterwards, but sets the gauge from
consumed_cycles_total_including_canisters(). The reported value is unchanged,as
consumed_cycles_total()covers exactly the same use cases that the inlinesum did, and the gauge can no longer drift from the certified leaf. Unlike that
leaf, this path is live today; it reads a refreshed value because
commit_and_certifyenqueues the observation after the refresh described below.The per-use-case breakdowns alongside the gauge still fold over the canisters,
as no aggregate holds them.
The refresh lives in
StateManagerImpl::commit_and_certify, besiderepartition_canister_states(). That is the one choke point every committedstate passes through, with nothing able to mutate a canister between the refresh
and the hash; refreshing earlier (in message routing or the scheduler) would go
stale, because canisters are still charged afterwards -- HTTP spend refunds,
stream-builder rejects, message shedding -- and because drivers such as
StateMachinetests sometimes do not run message routing at all. Like therepartitioning, it must therefore stay unconditional.
The field is transient: it is not persisted, and it is marked
#[validate_eq(Ignore)]becausevalidate_eq_checkpointcompares the stateagainst a
SystemMetadataloaded from the proto alone, where the field is zero.SubnetMetricsderivesValidateEqandSystemMetadata::subnet_metricsiscompared with
CompareWithValidateEqso that the exemption covers this fieldalone and the rest of the struct stays validated field by field. This follows
RefundPool::{amounts, total}, which are likewise transient and re-derived onload, and
SystemMetadata::subnet_ids_at_last_reject_generation, which istransient but merely reset. The field is
pub, rather than hidden behind anobserver like its accumulating siblings, because the refresh overwrites it
wholesale.
ReplicatedState::new_from_checkpointderives the field from the canisters itloads. That is what makes a replica restarting from a checkpoint agree with one
that kept running, and hence certify the same
/subnet/<subnet_id>/metricsleaf; a test for that will be added when bumping the certification version. The certified
encoding is unchanged, as the untouched expected bytes in
encoding/tests/compatibility.rsshow, and so is the state hash.