Skip to content

feat: per-region bandwidth accounting (#750) - #816

Merged
thiras merged 14 commits into
mainfrom
feat/750-per-region-bandwidth-accounting
Jun 6, 2026
Merged

thiras merged 14 commits into
mainfrom
feat/750-per-region-bandwidth-accounting

Conversation

@thiras

@thiras thiras commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements per-region bandwidth accounting (closes #750). A RegionAccountant aggregates bytes served (and, via a documented forward seam, bytes pulled) keyed by the counterparty peer's self-attested NodeAnnounceBody.region (ADR 030), with an UNKNOWN bucket for unattributable traffic. Exposed three ways: a periodic structured log, an admin_v1_regionStats RPC, and a decdn node region-stats CLI command.

Key design decisions

  • Attribution = counterparty peer region — the only breakdown the wire protocol supports (no client-side region exists). Non-peer end-clients / unknown peers fall into an UNKNOWN bucket.
  • No labeled Prometheus counters — the iroh_metrics backend has no dynamic/per-field labels (see metrics.rs), so region (an open-ended key) is surfaced via structured log + admin RPC + CLI instead.
  • bytes_in is a forward-compatible seam — node-to-node paid pull-through isn't orchestrated in production yet, so record_pulled has no production caller; bytes_in reads 0 until that lands. Fully modeled and tested so the surface is ready.
  • Cumulative-since-start, in-memory (Prometheus-counter semantics); poisoned-lock paths recover (into_inner) rather than flatlining.

What's included

  • RegionAccountant + RegionResolver/PeerTableResolver (crates/node/src/region_accounting.rs)
  • Bytes-out recorded at each accepted voucher in the cdn/client/v1 handler (after payment commit — best-effort, can't fail the stream)
  • Periodic run_region_accounting_log task gated by observability.region_accounting_interval_sec (default 3600, 0 disables), surfaced in decdn config validate/init
  • admin_v1_regionStats RPC + DTOs in decdn_common::admin
  • decdn node region-stats CLI command

Test Plan

  • cargo build clean
  • cargo fmt --check clean
  • cargo clippy --workspace --all-targets -- -D warnings clean
  • cargo nextest run — 1463 passed, 0 skipped
  • cargo deny check ok
  • Unit tests: bucketing, UNKNOWN fallback, saturating add, sorted snapshot, record_pulled seam, concurrent-summation, PeerTableResolver against a real peer table
  • Integration test: real signed-voucher delivery through the live ClientHandler crossing a voucher boundary, asserting served bytes land under the resolved region
  • Admin RPC empty + attached-snapshot tests; DTO round-trip + legacy-shape (serde-default) tests
  • Config: default + explicit (0/60) interval resolution
  • Reviewed by 5-agent pr-review-toolkit pass; findings addressed (poisoned-lock recovery, Direction split, centralized sentinel, doc/test gaps)

🤖 Generated with Claude Code

thiras and others added 11 commits June 5, 2026 01:56
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- recover poisoned totals lock at error! instead of silently flatlining
- replace positional add() with a Direction split
- centralize UNKNOWN_REGION sentinel in decdn_common::admin
- doc fixes (NodeAnnounceBody.region, drop stale 'later task' note)
- tests: explicit config interval resolution, concurrent summation, PeerTableResolver

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings June 5, 2026 00:31

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request implements per-region bandwidth accounting to track cumulative bytes served and pulled per geographic region. It introduces a RegionAccountant that resolves peer regions from the gossip table, wires this into the paid-delivery handler, adds a periodic logging task, and exposes the stats via a new admin RPC endpoint and CLI command. The review feedback suggests a minor optimization to use sort_unstable_by instead of sort_by when sorting the region stats snapshot for better performance.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread crates/node/src/region_accounting.rs Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Adds a new in-memory “per-region bandwidth accounting” facility to the node, attributing bytes in/out to the counterparty peer’s self-attested NodeAnnounceBody.region (with an UNKNOWN bucket), and exposes the resulting cumulative counters via periodic structured logs, a new admin RPC, and a CLI subcommand.

Changes:

  • Introduces RegionAccountant + RegionResolver/PeerTableResolver for per-region byte aggregation in decdn-node.
  • Wires bytes-out recording into the paid voucher acceptance path; adds periodic region-bandwidth logging controlled by a new observability config knob.
  • Exposes stats via admin_v1_regionStats (DTOs + server impl) and decdn node region-stats (CLI + formatting tests).

Reviewed changes

Copilot reviewed 21 out of 22 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
docs/superpowers/specs/2026-06-05-per-region-bandwidth-accounting-design.md Design spec for attribution rules and surfaces (log/RPC/CLI).
docs/superpowers/plans/2026-06-05-per-region-bandwidth-accounting.md Step-by-step implementation plan for the feature.
Cargo.toml Adds async-trait to workspace dependencies.
Cargo.lock Records async-trait as a dependency for decdn-node.
crates/common/src/admin.rs Adds RegionBytes/RegionStatsResponse + AdminRpc::region_stats method and serde tests.
crates/common/src/config/types.rs Adds raw TOML knob observability.region_accounting_interval_sec.
crates/common/src/config/resolved.rs Adds resolved region_accounting_interval_sec.
crates/common/src/config/mod.rs Adds default constant + config resolver/tests for the new knob.
crates/common/src/cli/node.rs Adds node region-stats CLI args + subcommand variant.
crates/common/src/cli/mod.rs Re-exports RegionStatsArgs.
crates/cli/src/commands/node.rs Implements the region-stats command + table rendering + tests.
crates/cli/src/commands/config.rs Surfaces region_accounting_interval_sec in config validate output + default config comment.
crates/cli/tests/config_validate.rs Updates expected resolved config for new observability field.
crates/node/src/region_accounting.rs New accountant/resolver module + unit tests and peer-table resolver test.
crates/node/src/lib.rs Exposes region_accounting module.
crates/node/src/handlers/client.rs Attaches/wires accountant; records bytes_out on voucher acceptance.
crates/node/src/runtime/mod.rs Builds/attaches accountant, spawns periodic log task, wires admin state, adds shutdown test.
crates/node/src/admin.rs Implements admin_v1_regionStats, wires accountant into AdminState, adds unit tests.
crates/node/src/runtime/reload.rs Updates test config seeds for new resolved field.
crates/node/tests/client_loopback.rs Integration test ensuring voucher acceptance records bytes_out to the correct region.
crates/node/tests/sighup_signal.rs Updates test config seed for new resolved field.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 87.19% (was 87.24%, ▼ 0.05%) — 28813/33048 lines

File Coverage Lines Δ
crates/cli/src/commands/config.rs 61.72% 79/128 ▲ +0.12%
crates/cli/src/commands/node.rs 82.87% 982/1185 ▼ 1.50%
crates/common/src/admin.rs 96.37% 186/193 ▲ +0.89%
crates/common/src/config/mod.rs 96.37% 4933/5119 ▲ +0.02%
crates/common/src/config/resolved.rs 100.00% 19/19 ● 0.00%
crates/node/src/admin.rs 95.12% 1110/1167 ▲ +0.15%
crates/node/src/handlers/client.rs 76.81% 457/595 ▲ +0.28%
crates/node/src/region_accounting.rs 93.10% 162/174 new
crates/node/src/runtime/mod.rs 44.53% 558/1253 ▲ +0.51%
crates/node/src/runtime/reload.rs 95.09% 1413/1486 ▲ +0.01%
History
Commit Total Δ vs base
c481e54 87.16% ▲ +0.01%
5efaa95 87.12% ▼ 0.03%
43e30ab (HEAD) 87.19% ▼ 0.05%

#750)

- region_accounting: sort_unstable_by (unique region keys, no stability needed) per review
- remove the design spec and implementation plan docs from the PR

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

@alpergundogdu alpergundogdu 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.

Review — per-region bandwidth accounting

Clean and well-tested. The core RegionAccountant is correct: per-interval delta_bytes recording (no double-counting vs. the voucher loop), proper UNKNOWN fallback, saturating adds, sorted snapshots, poisoned-lock recovery via into_inner(), and — the easy thing to get wrong here — no lock held across an await: record_served/record_pulled resolve the region under the async RwLock (guard dropped) and only then call the synchronous bump over the std Mutex with no await inside. Best-effort recording at the call site can't fail the stream. Strong coverage (100-task concurrent-summation, saturation, sorting, UNKNOWN, RPC empty-vs-attached, end-to-end loopback wiring guard, shutdown-promptness). No blockers and no anti-panic violations found. A few should-fix/nits:

1. (Should-fix) Asymmetric back-compat: RegionStatsResponse.regions lacks #[serde(default)]. The inner RegionBytes.bytes_in/bytes_out get #[serde(default)] for forward-compat, but the outer regions field doesn't. The PR's own rationale for returning an empty list rather than erroring ("a node with no accounting wired has nothing to report") argues for tolerating an older/partial server that omits regions entirely. Add #[serde(default)] on regions to match the field-level back-compat posture. Medium confidence — consistency/robustness, not a live bug, since the current server always emits the field.

2. (Nit) Doc-comment renders a serde attribute as public rustdoc prose. On RegionBytes.bytes_in, the line /// #[serde(default)] keeps older servers… round-tripping. is a /// doc line, so the attribute note leaks into the public API docs (and bytes_out omits it, so it's asymmetric). Make it a plain // implementation comment.

3. (Expectation note, not a bug) UNKNOWN will likely dominate bytes_out. Attribution keys on the paying client's node id, and on cdn/client/v1 the payer is frequently a non-peer end-client not in the gossip peer table → PeerTableResolver returns None → UNKNOWN. Only node-to-node serving resolves to a real region. This matches the DTO doc and looks intended, but operators reading "per-region bandwidth" may be surprised most served bytes land in UNKNOWN — worth making explicit in the metric/admin docs.

4. (Nit) Empty-snapshot tick emits zero log lines. run_region_accounting_log's tick iterates accountant.snapshot(), so on an idle node it logs nothing — a scraper can't distinguish "idle" from "log task dead." The CLI path has a (no region data) sentinel; consider a matching if snapshot.is_empty() trace heartbeat. Minor; the shutdown-promptness test already guards task liveness.

5. (Awareness) record_pulled / Direction::In is dead in production but correctly guarded. No production caller yet (documented seam); bytes_in reads 0 forever until a pull orchestrator wires it. The loopback test asserts bytes_in == 0 and the doc is explicit, so this is fine — flagging only so reviewers don't mistake it for a bug, and so the future pull-through PR remembers to call it.

Config resolution (DEFAULT_REGION_ACCOUNTING_INTERVAL_SEC = 3600, 0 disables, all ResolvedObservability constructors updated) and the admin RPC/DTO round-trip + legacy-shape tests all check out. LGTM after #1/#2; the rest are optional.


Generated by Claude Code

…rtbeat (#750)

Per Alper's review on #816:

- #1 (should-fix): add `#[serde(default)]` to `RegionStatsResponse.regions`
  so an older/partial server omitting the field deserializes to an empty
  list, matching the field-level back-compat posture on `RegionBytes`.
  Adds an omitted-`regions` round-trip test.
- #4 (nit): emit a `trace` idle heartbeat from the periodic log task when
  the snapshot is empty, so a scraper can distinguish an idle node from a
  dead log task. Extracted `log_region_snapshot` to keep the task under
  the cognitive-complexity gate.

#2's doc-comment is left as a `///` line to match the file-wide convention
(every `#[serde(default)]` field documents its rationale in rustdoc).

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

thiras commented Jun 6, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in 8d452a3.

#1 (serde(default) on regions) — Fixed. Added #[serde(default)] to RegionStatsResponse.regions so an older/partial server omitting the field round-trips as an empty list, matching the field-level back-compat posture on RegionBytes. Added a {} → empty-regions round-trip test (region_stats_response_omitted_regions_defaults_empty).

#2 (doc-comment on bytes_in) — Keeping it as a /// line rather than converting to //. The asymmetry you spotted is real, but the suggested fix would make this the lone exception in admin.rs, where every #[serde(default)] field documents its rationale in rustdoc (in_flight_streams, wait_admin_honored, and the ChannelSnapshot back-compat fields at lines 317/407). Following the file convention over breaking it for one field.

#3 (UNKNOWN dominates bytes_out) — Agreed it's the expected shape; already called out in the RegionBytes DTO doc ("a non-peer end-client, or a peer not in the table"). No code change.

#4 (empty-snapshot heartbeat) — Added. The periodic log task now emits a trace region_bandwidth_idle heartbeat when the snapshot is empty, so a scraper can tell an idle node from a dead task. Extracted log_region_snapshot to keep the task under the cognitive-complexity gate.

#5 (record_pulled dead-but-guarded) — Acknowledged, no action; the future pull-through PR wires the Direction::In caller.

772 tests pass, clippy/fmt clean.

…andwidth-accounting

# Conflicts:
#	crates/node/src/handlers/client.rs
@thiras
thiras merged commit de0321f into main Jun 6, 2026
22 checks passed
@thiras
thiras deleted the feat/750-per-region-bandwidth-accounting branch June 6, 2026 11:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants