Repository navigation
feat: per-region bandwidth accounting (#750) - #816
Conversation
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…750) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…+ init (#750) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
#750) 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]>
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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/PeerTableResolverfor per-region byte aggregation indecdn-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) anddecdn 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.
Coverage reportTotal: 87.19% (was 87.24%, ▼ 0.05%) — 28813/33048 lines
History
|
#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
left a comment
There was a problem hiding this comment.
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]>
|
Addressed in 8d452a3. #1 (serde(default) on #2 (doc-comment on #3 (UNKNOWN dominates #4 (empty-snapshot heartbeat) — Added. The periodic log task now emits a #5 ( 772 tests pass, clippy/fmt clean. |
…andwidth-accounting # Conflicts: # crates/node/src/handlers/client.rs
Summary
Implements per-region bandwidth accounting (closes #750). A
RegionAccountantaggregates bytes served (and, via a documented forward seam, bytes pulled) keyed by the counterparty peer's self-attestedNodeAnnounceBody.region(ADR 030), with anUNKNOWNbucket for unattributable traffic. Exposed three ways: a periodic structured log, anadmin_v1_regionStatsRPC, and adecdn node region-statsCLI command.Key design decisions
UNKNOWNbucket.iroh_metricsbackend has no dynamic/per-field labels (seemetrics.rs), so region (an open-ended key) is surfaced via structured log + admin RPC + CLI instead.bytes_inis a forward-compatible seam — node-to-node paid pull-through isn't orchestrated in production yet, sorecord_pulledhas no production caller;bytes_inreads0until that lands. Fully modeled and tested so the surface is ready.into_inner) rather than flatlining.What's included
RegionAccountant+RegionResolver/PeerTableResolver(crates/node/src/region_accounting.rs)cdn/client/v1handler (after payment commit — best-effort, can't fail the stream)run_region_accounting_logtask gated byobservability.region_accounting_interval_sec(default 3600,0disables), surfaced indecdn config validate/initadmin_v1_regionStatsRPC + DTOs indecdn_common::admindecdn node region-statsCLI commandTest Plan
cargo buildcleancargo fmt --checkcleancargo clippy --workspace --all-targets -- -D warningscleancargo nextest run— 1463 passed, 0 skippedcargo deny checkokrecord_pulledseam, concurrent-summation,PeerTableResolveragainst a real peer tableClientHandlercrossing a voucher boundary, asserting served bytes land under the resolved region0/60) interval resolution🤖 Generated with Claude Code