Skip to content

feat: Store the canisters' consumed cycles in SubnetMetrics - #11297

Merged
mraszyk merged 6 commits into
masterfrom
mraszyk/store-consumed-cycles-by-canisters
Aug 26, 2026
Merged

mraszyk merged 6 commits into
masterfrom
mraszyk/store-consumed-cycles-by-canisters

Conversation

@mraszyk

@mraszyk mraszyk commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

SubnetMetrics::consumed_cycles_total() reports the cycles removed from
circulation 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 that
currently exist are not part of it; every consumer of the full total folded them
out of CanisterStates and added them on. That fold is O(|hot canisters|)
(the cold pool keeps a precomputed aggregate), it was spelled out once per
consumer, and it forced the /subnet subtree of the canonical state to depend
on CanisterStates for 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>/metrics reads that starting from the certification version
V29, which is not yet enabled (CURRENT_CERTIFICATION_VERSION is still
V28), so encode_subnet_metrics no longer takes the canisters' contribution
as a parameter and the /subnet subtree does not need CanisterStates at all.

The replicated_state_consumed_cycles_since_replica_started gauge reports the
same definition: ReplicatedStateMetrics::observe no longer accumulates the
canisters' 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 inline
sum 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_certify enqueues 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, 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 sometimes do not run message routing at all. Like the
repartitioning, it must therefore stay unconditional.

The field is transient: it is not persisted, and it is marked
#[validate_eq(Ignore)] because validate_eq_checkpoint compares the state
against a SystemMetadata loaded from the proto alone, where the field is zero.
SubnetMetrics derives ValidateEq and SystemMetadata::subnet_metrics is
compared with CompareWithValidateEq so that the exemption covers this field
alone and the rest of the struct stays validated field by field. This follows
RefundPool::{amounts, total}, which are likewise transient and re-derived on
load, and SystemMetadata::subnet_ids_at_last_reject_generation, which is
transient but merely reset. The field is pub, rather than hidden behind an
observer like its accumulating siblings, because the refresh overwrites it
wholesale.

ReplicatedState::new_from_checkpoint derives the field from the canisters it
loads. That 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; 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.rs show, and so is the state hash.

`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]>
@github-actions github-actions Bot added the feat label Aug 24, 2026
Comment thread rs/canonical_state/src/traversal.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.

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.

Comment thread rs/state_manager/tests/state_manager.rs Resolved
mraszyk and others added 2 commits August 25, 2026 08:12
`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]>
@mraszyk
mraszyk marked this pull request as ready for review August 25, 2026 11:16
@mraszyk
mraszyk requested a review from a team as a code owner August 25, 2026 11:16
@zeropath-ai

zeropath-ai Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

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

Security Overview
Detected Code Changes
Change Type Relevant files
Enhancement ► rs/canonical_state/src/encoding.rs
    Remove NominalCycles from encode_subnet_metrics signature and adjust encoding accordingly
► rs/canonical_state/src/encoding.rs
    Simplify encode_subnet_metrics to use (metrics, certification_version) only
Enhancement ► rs/canonical_state/src/encoding/tests/compatibility.rs
    Update compatibility test to reflect new encode_subnet_metrics usage (remove consumed_cycles_by_canisters parameter)
Enhancement ► rs/canonical_state/src/encoding/types.rs
    Adjust From implementation to drop NominalCycles parameter and align with new encoding
► rs/canonical_state/src/encoding/types.rs
    Update conversion to use (metrics, certification_version)
Enhancement ► rs/canonical_state/src/lazy_tree_conversion.rs
    Update subnet metrics blob generation to call encode_subnet_metrics(metrics, certification_version) directly
► rs/canonical_state/src/lazy_tree_conversion.rs
    Remove logic computing consumed_cycles_by_canisters for V29 and earlier
Enhancement ► rs/canonical_state/src/traversal.rs
    Tests: reflect new consumed_cycles_by_canisters handling in metrics expectations
Enhancement ► rs/replicated_state/src/metadata_state.rs
    SubnetMetrics: add ValidateEq attribute for subnet_metrics and update related struct annotations
► rs/replicated_state/src/metadata_state.rs
    Add new field consumed_cycles_by_canisters with Ignore validation
Enhancement ► rs/replicated_state/src/metadata_state.rs
    SubnetMetrics: add consumed_cycles_total_including_canisters() method
Enhancement ► rs/replicated_state/src/metadata_state/proto.rs
    Update TryFrom to initialize consumed_cycles_by_canisters to zero (transient)
Enhancement ► rs/replicated_state/src/replicated_state.rs
    In new_from_checkpoint, derive consumed_cycles_by_canisters from loaded canister states
► rs/replicated_state/src/replicated_state.rs
    Add refresh_consumed_cycles_by_canisters() method
Enhancement ► rs/replicated_state/src/metrics.rs
    Update consumed cycles gauge to use subnet_metrics.consumed_cycles_total_including_canisters() instead of folding from multiple fields
Enhancement ► rs/state_manager/src/lib.rs
    Call refresh_consumed_cycles_by_canisters() during state management before hashing

Comment thread rs/state_manager/tests/state_manager.rs Resolved
Comment thread rs/state_manager/tests/state_manager.rs Resolved

@alin-at-dfinity alin-at-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.

Only a couple of nitpicks and ranting about Claude's exceedingly verbose comments.

Comment on lines +389 to +392
// Transient, with no corresponding proto field:
// `ReplicatedState::new_from_checkpoint` derives it from the canisters
// it loads.
consumed_cycles_by_canisters: NominalCycles::zero(),

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That approach would have two downsides:

  • ReplicatedState::new_from_checkpoint does not derive the field anymore so some tests using that would get the default zero value;
  • the validate_eq_checkpoint would need to derive the value "manually" by changing validate_eq_canister_states from Result<(), String> to Result<NominalCycles, String>) and computing it inside.

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.

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?".

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread rs/state_manager/src/lib.rs Resolved
mraszyk and others added 3 commits August 25, 2026 14:56
`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]>
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]>
@mraszyk
mraszyk added this pull request to the merge queue Aug 26, 2026
Merged via the queue into master with commit aff3a5e Aug 26, 2026
68 of 71 checks passed
@mraszyk
mraszyk deleted the mraszyk/store-consumed-cycles-by-canisters branch August 26, 2026 11:45
mraszyk added a commit that referenced this pull request Aug 26, 2026
…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]>
pull Bot pushed a commit to mikeyhodl/ic that referenced this pull request Sep 15, 2026
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]>
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