Skip to content

fix: batch six review follow-ups (#1346, #1347, #1348, #1349, #1359, #1361) - #1362

Merged
thiras merged 8 commits into
mainfrom
fix/batch-six-review-followups
Jul 21, 2026
Merged

thiras merged 8 commits into
mainfrom
fix/batch-six-review-followups

Conversation

@thiras

@thiras thiras commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1346, #1347, #1348, #1349, #1359, #1361.

Six filed review follow-ups, batched per the #1358 / #1360 precedent. Five come from the multi-agent reviews of #1360 (bond exit) and #1341 (registry bootstrap); #1347 is the residual half of an earlier batch.

What's in it

Issue Change
#1361 CapacityBond.declareMbps(0) is now accepted from an inactive operator, releasing a declared tier that four deactivation paths could otherwise never clear. Active operators still revert DeclaredCapacityOutOfBand. +49 bytes (23,411 / 24,576).
#1359 New decdn node deregister, plus unbond --all issues declareMbps(0) for unregistered operators — without which #1361 had no CLI path at all.
#1348 New decdn_protocol::Region newtype; NodeCandidate.region_hint String → Option<Region>; PEER_CACHE_VERSION 1→2.
#1349 Registry retry budget made aggregate across pages (was 36 s × N); --timeout-ms now bounds the registry read.
#1347 tx::run_then_cleanup extracted and tested; deferral note rewritten with the actual reason.
#1346 [cache] peer_cache_path dropped from ADR 012.

Review round

A five-agent review ran against the branch before opening this PR. Every actionable finding was verified independently (Foundry probes, mutation tests) and fixed in a151571d. The three that mattered most:

  • The discovery timeout cancelled the ADR-012 peer-cache fallback. The bound wrapped the whole discovery call, so a client with a usable peers.json and a flaky RPC got a hard failure instead of a degraded fetch. Moved inside bootstrap_nodes, around the registry read alone.
  • The "trapped bond" justification was wrong by ~100×. CapacityBond: a declared tier can only be cleared by deregisterNode, so ejected and never-registered operators stay pinned to the curve floor #1361's premise — and my ADR text — claimed a slashed operator's whole residual was unwithdrawable. A Foundry probe showed a tier-down declaration always released all but bondRequired(minCapacityMbps): 199.7 of 20,252.7 TOKEN was actually trapped. Corrected in ADR 026, the contract NatSpec, the CLI, and the test docstring. The change still stands on its merits (one-step exit; and the blacklist-ejected operator genuinely had none).
  • Two tests were vacuous — the --all retarget and the discovery timeout both passed with the feature mutated out. all_target was extracted as a pure function so the decision is observable at all (Asserter answers by queue position, not calldata).

Also fixed: --region usa was silently ignored; Region's derived Debug printed region Some(Region([85, 83])) to operators; ADR 003 was never updated and contradicted the shipped contract.

Verification

  • 2,624 Rust tests; 762 Solidity tests
  • FOUNDRY_PROFILE=ci forge build --sizes --deny warnings, .gas-snapshot, slither (exit 0), aderyn (0 highs)
  • clippy -D warnings, rustdoc, decdn-protocol public-API snapshot
  • G-NODE-06 against a real chain, including new legs 10 (full exit via deregister) and 11 (inactive-operator exit via --all)
  • --timeout-ms 5000 against an unreachable RPC returns in 5.04 s, via the bootstrap path so the cache is still consulted

Notes for the reviewer

  • pre-commit run --all-files fails on .github/workflows/issue-triage.{md,lock.yml} — pre-existing on main, untouched here.
  • The review fixes are a separate commit (a151571d) rather than squashed into the six, so the defects and their fixes stay legible. Happy to squash if preferred.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added decdn node deregister with dry-run, confirmation, and JSON output support.
    • Full exits now let inactive or ejected operators release declared capacity and unbond remaining funds.
    • Added validated, normalized region handling for discovery and CLI input.
    • Registry discovery now respects the configured timeout and falls back to cached peers when needed.
  • Bug Fixes

    • Improved cleanup after token swaps, including failed transactions.
  • Documentation

    • Clarified deregistration, re-onboarding, capacity tiers, and exit behavior.

thiras and others added 7 commits July 21, 2026 23:03
…1361)

`deregisterNode` is the only writer that clears `declaredMbps`, and it
reverts `NodeNotActive`. `declareMbps` carried no active-node gate, so a
tier could be declared in four states it could never be cleared from —
bonded-and-declared-but-never-registered (directly reachable from
`decdn node bond --mbps N`), auto-ejected by slashing, blacklist-ejected,
or displaced by `reclaimNodeId` — and `requestUnbond`'s
`bondRequired(declaredMbps)` floor then pinned the bond indefinitely.

Where a slash had already taken the bond below that floor, none of the
remainder was withdrawable, and freeing it cost several times the trapped
amount in fresh capital. A blacklist-ejected operator had no escape at
all: `registerNode` reverts until governance calls `unEjectNode`.

`declareMbps(0)` is now accepted from an inactive operator, and only
then — skipping both the band floor and the curve check a slashed
operator can no longer meet. An active operator's `declareMbps(0)` still
reverts `DeclaredCapacityOutOfBand`, so this is not a second, unlogged
way to leave the active set; a registered node still exits through
`deregisterNode`, which alone removes it from the registered set and
bumps `registrationNonce`.

The released bond stays fully slashable for the whole 14-day window
(`_reduceBondAtTier` reaches bond in the unbonding queue), so this
shortens no exposure — it stops a curve floor outliving the registration
it was sized for. Recorded in ADR 026 § Capacity-bond curve, which
previously documented the asymmetry as a known gap.

`test_ejectedOperator_keepsTheTierAndCannotUnbond` pinned the old
behavior and is rewritten as `..._canReleaseTheTierAndExit`; the
never-registered, blacklist-ejected, and active-operator-still-reverts
cases are new. Costs 49 bytes (23,411 / 24,576).

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

`CapacityBond.deregisterNode` is the entry point to a full bond exit — it
clears `declaredMbps`, releasing the `bondRequired(declaredMbps)` floor
`requestUnbond` enforces (#1351). The CLI covered the last two legs
(`decdn node unbond`) and the entry leg on the way in (`decdn node
register`), but an operator who wanted to leave had to hand-craft the
`deregisterNode` transaction.

`decdn node deregister` follows `unbond`'s shape: `--dry-run`, a `--json`
receipt, and the same `decide_confirmation` / `confirm_or_bail` split. It
is at least as consequential as starting an unbonding window — it drops
the node from the active set, bumps `registrationNonce[nodeId]`
(invalidating previously-signed registration signatures), and clears the
tier — so it discloses those on every run and refuses headless without
`--yes`. The load-bearing line is that the bond is NOT returned by this
call and stays fully slashable, which is the misconception the command's
name most invites.

The pre-flight reads `getNodeByAddress().active`, not `isActive`: the
latter also requires bond over `minBond` and no request in flight, so an
operator mid-unbonding is `isActive == false` yet still deregisterable.
That divergence is real in the journey — leg 9 leaves the fixture
registered with `isActive` false — and it distinguishes the two inactive
states, which have different exits: an ejected operator is pointed at
`unbond --all`, never at `register`, which reverts for them.

`unbond --all` is what makes that advice true. For an operator NOT in the
registered set it now sends `declareMbps(0)` first (#1361, accepted only
from an inactive operator), retargeting the curve floor to
`bondRequired(0) == 0` — a full exit. Without it the contract fix landed
in the previous commit would have had no CLI path at all. An active
operator's `--all` is unchanged; clearing their tier is `deregister`'s
job.

G-NODE-06 gains the exit leg: preview, refuse-unconfirmed, deregister,
refuse-twice, then `--all` -> withdraw -> `activeBond == 0`. Every leg
before it left the tier standing, so nothing had ever taken the
operator's last TOKEN out end to end.

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

`NodeCandidate.region_hint` was a `String` documented as an ISO 3166-1
alpha-2 code (ADR 030) with nothing enforcing it, so every consumer had to
re-derive the invariant. `select_candidates` compensated at the call site
with `trim()` + `eq_ignore_ascii_case`, because one side of the comparison
came normalized from config (`normalize_region`) and the other raw from
the chain. The `PartialEq`/`Eq` derives added in #1341 then compared it
structurally, so the same node registered as ` us ` vs `US` compared
unequal — latent today (only tests consume `Eq`) but any future
`dedup`/`contains`/`retain` over candidates would fail to dedupe.

`decdn_protocol::Region` does the trim + uppercase + allowlist once, at
the parse boundary, next to the `is_valid_region` it wraps. Two bytes,
`Copy`, serializing as the plain 2-character string. The deserializer
re-runs the allowlist rather than deriving over the byte array, so a
persisted or wire-sourced value cannot reintroduce arbitrary bytes past
the boundary — which is also what restores the 16-byte bound on the
peer-cache read path.

`region_hint` becomes `Option<Region>`. Unrecognized codes parse to `None`
and sort into the "rest" bucket rather than dropping the candidate:
`CapacityBond` permits any string up to 16 bytes and ADR 030 § Cross-ADR
Impact explicitly declines to tighten it, so rejecting a node over a
purely advisory field would be stricter than the source of truth and
would silently shrink the fetchable set. `select_candidates` becomes a
plain equality.

`PEER_CACHE_VERSION` 1 -> 2: a v1 file can hold a region string the
validating deserializer now rejects, which would fail the whole-file
decode rather than the one field. The narrow `CacheVersion` decode
already makes that a cache miss. Two version-mismatch tests hardcoded the
literals `1`/`2`; they now derive both from the constant, so the next
bump cannot silently turn them into a comparison of stale numbers.

`common`'s `normalize_region` is deliberately not migrated — out of scope,
and it drags config error messages and their tests along.

Public-API snapshot regenerated (additions only, no removals).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Nothing bounded node discovery. `PullDeadlines` is constructed after
`resolve_target_node` runs and wraps only the `stream_fetch` leg, so
neither `--stall-timeout-ms` nor `--timeout-ms` covered it. Since #1341
that window is real: the registry read retries on the ADR 012 schedule, so
a fully-failing page costs 36 s — and the budget reset per page, so an
N-page read reached 36 s × N. `decdn fetch --timeout-ms 5000` could
therefore sit for well over 5 s before the transfer it caps had started.

Two changes, neither adding a knob:

The retry budget is now aggregate across the whole read. `attempt` moves
outside the pagination loop, so a page that retries twice leaves one for
everything after it. The ADR's "retry 3×" is read as a property of the
read — the unit the caller actually waits on — rather than of a page
count that follows how many nodes are registered and that the caller
cannot see. A successful page deliberately does not refund the budget;
refunding would restore the unbounded case exactly, since a registry
failing every other call would alternate success and retry forever.

`--timeout-ms` now bounds discovery too, with the help text corrected from
"a single blob fetch". It is a separate budget of the same size, not a
shared one: sharing would make `bundle pull`'s documented per-entry fetch
cap depend on how long discovery took. Two budgets means the true worst
case is 2× the flag, which is the honest cost of not adding a fifth
timeout for operators to reason about.

Verified against an unreachable RPC: `--timeout-ms 5000` now returns in
5.04 s naming the flag and offering `--node-id`, where it previously ran
the schedule out.

ADR 012 § Bootstrap step 3 records both the aggregate budget and the
outer deadline.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…on-chain test stays deferred (#1347)

Both swap venues run their allowance resets after the swap on every path,
and both carried a note deferring the end-to-end test. #1358 corrected the
note's false premise (it claimed the pinned alloy shipped no `Asserter`);
this is the reassessment the issue also asked for.

Finding: `Asserter` still does not close the gap, for a reason worth
recording so it is not re-litigated. It is a FIFO transport mock with no
method awareness, which makes read paths trivial to drive — `unbond`'s
`plan_computation` does exactly that — but a `send()` fans out the filler
stack's estimateGas/nonce/chainId/feeHistory requests concurrently, so
responses cannot be matched to methods. Measured against the real
`swap_exact_out`: the remaining-queue length is 0 no matter how many
responses are pushed, so it cannot even distinguish "the reset ran" from
"it did not". A test built on it would pin alloy's filler internals.

The property the deferred test was protecting is control flow, though, so
it is now tested as control flow. `tx::run_then_cleanup` names the
"run work, always clean up, return work's result unchanged" pattern both
venues implement by hand, and its tests drive the Ok path, the Err path,
and the ordering with plain closures and no RPC at all. The shape it
replaces (`let r = async { … }.await; cleanup().await; r`) is easy to
break with a stray `?`, which is precisely the bug that would leave a
router holding a standing USDC allowance after a failed onboarding.

`cleanup` is a closure returning a future rather than a future: taking
both eagerly makes them simultaneously-live locals, so the combined state
machine is their sum, and that pushed `decdn`'s `Command::Setup` future
past clippy's `large_futures` threshold — a `-D warnings` CI failure.
Constructing the cleanup future only after `work` finishes lets the two
share space.

What remains deferred is only the on-chain version: approve succeeds, the
swap reverts on-chain, and the reset is observed against real allowance
state. That needs an anvil dev-dep this crate does not have.

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

ADR 012 § Client Configuration listed `peer_cache_path` in the default
config block, but no code parses it: the filename is the hardcoded
`PEER_CACHE_FILE` const joined onto the resolved client data dir, so
setting the key was silently ignored. #1341 annotated it NOT YET
IMPLEMENTED rather than deciding; this decides.

Removed rather than implemented. The code does not lack the override, it
deliberately replaced it — `--data-dir` / `[identity] data_dir` already
moves the whole client state directory, and the file tree earlier in the
same section documents `peers.json` living inside it. Wiring a
second, narrower way to move one file would be a knob with no
demonstrated demand, at the ~5 surfacing sites the convention requires.

`[bootstrap] registry_refresh_secs` is the same shape on the surface —
present, unimplemented — but the opposite case, so it stays and is now
annotated to say why: step 8's periodic refresh has no code behind it
because `decdn fetch` is one-shot and re-reads the registry per
invocation, but it remains the intended design. Recording the distinction
so this is not re-discovered as the same finding.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A five-agent review of the branch surfaced two functional defects, a
materially wrong economic claim, three vacuous tests, and a batch of stale
comments. Fixes, grouped:

**Functional — discovery timeout cancelled the cache fallback (#1349).**
The `tokio::time::timeout` wrapped `discover_provider` /
`discover_candidates`, which contain the ADR 012 § Bootstrap step 4
peer-cache fallback, so a client with a usable `peers.json` and a flaky
RPC got a hard failure instead of a degraded fetch. The bound moved INSIDE
`bootstrap_nodes`, around the `active_nodes` read alone — a timeout is now
just another registry-read failure that `resolve_bootstrap` handles via
the cache, warning and all. New test
`a_timed_out_registry_read_still_falls_back_to_the_cache` pins it
(mutation-checked: the old call-site wrapper fails it).

**Functional — `--region usa` was silently ignored (#1348/#1349).** The
CLI path never ran `normalize_region`, so an unrecognized `--region`
parsed to `None` and discovery skipped locality ordering with no message.
Now validated at parse time via a `Region`-backed `value_parser`; any
spelling of a valid code is normalized, an invalid one is rejected naming
the format.

**Economics — the "trapped bond" claim was wrong by ~100x (#1361).** All
four sites (ADR 026, CapacityBond NatSpec, unbond.rs, the test docstring)
claimed a slashed operator's whole residual was unwithdrawable. `declareMbps`
enforces no monotonicity, so declaring DOWN to `minCapacityMbps` always
released everything above `bondRequired(minCapacityMbps)` — measured 199.7
of 20,252.7 TOKEN actually trapped. Corrected to describe #1361 as a
one-step release replacing a two-step tier-down, with the blacklist-ejected
operator (no re-registration at all) as the case with no prior escape. Also
corrected the "fully slashable" over-read (at-risk, not removable; ladder
caps at 50%/offense).

**Stale ADR/NatSpec.** ADR 003 (never updated by the batch, now
contradicted the shipped contract on two counts), `deregisterNode`'s own
NatSpec, `declaredMbps`'s `@notice`, ADR 019's auto-ejection sentence
(asserted a curve re-check that is really an `OperatorEjected` latch +
`minBond` reinstatement), and a dangling test-comment reference.

**Vacuous tests.** The `--all` retarget decision was extracted to a pure
`all_target`, because `Asserter` answers by queue position and cannot
observe `bondRequired`'s argument — the old test passed with the retarget
mutated away (verified). Restored the pre-release `BondBelowCurve` revert
assertion the rewritten ejected-operator test dropped. Added a real
on-chain leg 11 to G-NODE-06: the `#1361` `declareMbps(0)` path had no
chain coverage (leg 10 cleared the tier via `deregister` first).

**Type surface (#1348).** `Region` derived `Debug` over `[u8; 2]`, so
`decdn fetch` printed `region Some(Region([85, 83]))`; hand-wrote `Debug`
to render the code, and added an exhaustive round-trip test proving the
`unwrap_or("")` / `ok()?` fallbacks unreachable. Corrected the
`select_candidates` comment that claimed an upstream validation invariant
no code enforces, the misleading `declareMbps(0)` failure hint, the
overstated `Asserter` "measured" claim, `run_then_cleanup`'s missing
cancellation caveat, and the "different exits" comments (both inactive
states exit the same way; they differ on re-entry). Public-API snapshot
regenerated for the manual `Debug`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 21, 2026 22:17
@gemini-code-assist

Copy link
Copy Markdown

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@thiras, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 44 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 6f8dd9c2-527a-415b-9847-b19429bcead6

📥 Commits

Reviewing files that changed from the base of the PR and between a151571 and 98735a5.

📒 Files selected for processing (1)
  • crates/protocol/src/region.rs

Walkthrough

This PR adds inactive capacity-tier release and decdn node deregister, updates full-exit flows and tests, introduces typed region handling and bounded registry discovery, documents client behavior, and centralizes swap cleanup execution.

Changes

Capacity exit lifecycle

Layer / File(s) Summary
Capacity lifecycle rules
adr/*.md, contracts/src/CapacityBond.sol, crates/incentive/src/capacity_bond.rs, contracts/.gas-snapshot
Inactive operators can clear declaredMbps with declareMbps(0), while registered nodes clear it through deregisterNode; bond-floor and exit documentation and snapshots are updated.
Exit regression coverage
contracts/test/CapacityBond.t.sol, crates/e2e/src/*, crates/e2e/tests/g_node_06_unbond.rs
Tests cover inactive tier release, active-operator rejection, deregistration, delayed withdrawal, and final balances.
Deregister and full-exit commands
crates/common/src/cli/node.rs, crates/cli/src/commands/{deregister,node,unbond,mod,setup}.rs
The CLI adds deregistration planning, confirmation, transaction output, dispatch, and inactive unbond --all tier clearing.

Client discovery and region model

Layer / File(s) Summary
Validated region type
crates/protocol/src/{region.rs,lib.rs}, crates/protocol/Cargo.toml
A normalized Region type supports parsing, formatting, serde, public re-exports, and validation tests.
Typed candidate discovery
crates/client-pull/src/discovery.rs
Discovery uses typed region hints, aggregate pagination retry budgets, registry timeouts, peer-cache fallback, and versioned cache handling.
Fetch configuration and integration
crates/common/src/cli/fetch.rs, crates/cli/src/commands/{fetch,bundle_pull}.rs
Fetch validates region flags, derives discovery deadlines from --timeout-ms, and passes the cap through discovery paths.
Client behavior specification
adr/012-client.md
The ADR documents retry and timeout bounds, peer-cache location, and the currently unimplemented periodic refresh.

Swap transaction cleanup

Layer / File(s) Summary
Work and cleanup orchestration
crates/incentive/src/tx.rs
run_then_cleanup executes cleanup after successful or failed work while preserving the work result.
Swap allowance cleanup
crates/incentive/src/{swap_balancer,swap_uniswap}.rs
Balancer and Uniswap exact-out swaps use the helper for allowance resets and update cleanup coverage notes.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Operator
  participant CLI
  participant CapacityBond
  participant Unbonding
  Operator->>CLI: decdn node deregister
  CLI->>CapacityBond: read node, ejected, tier, and bond state
  CLI->>Operator: request confirmation
  Operator->>CLI: confirm with --yes or prompt
  CLI->>CapacityBond: deregisterNode
  Operator->>CLI: unbond --all
  CLI->>CapacityBond: requestUnbond
  CLI->>Unbonding: wait for withdrawal window
  Operator->>CapacityBond: unbond
Loading
sequenceDiagram
  participant ClientFetch
  participant Discovery
  participant CapacityBond
  participant PeerCache
  ClientFetch->>Discovery: bootstrap with discovery_cap
  Discovery->>CapacityBond: paginated getActiveNodes read
  CapacityBond-->>Discovery: registry data or timeout
  Discovery->>PeerCache: use peers.json on registry failure
  PeerCache-->>ClientFetch: candidate set
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Contracts coverage

Line coverage: 89.17% (2511/2816 lines)
▲ +0.01pp vs base (89.16% → 89.17%)
Run: 29874173420

@github-actions

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

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

This PR batches six follow-ups across contracts, Rust crates, CLI UX, e2e coverage, and ADRs. It closes gaps around (1) fully exiting the bond lifecycle from the CLI, (2) clearing declared capacity tiers for inactive operators, (3) tightening/typing region handling, and (4) bounding/clarifying discovery retry + timeout behavior.

Changes:

  • Contracts + tests: allow CapacityBond.declareMbps(0) only for inactive operators to release a stuck declared tier; keep the active-operator band check.
  • CLI + e2e: add decdn node deregister and extend the G-NODE-06 journey to cover full exit paths, including inactive-operator --all exit behavior.
  • Client discovery + protocol typing: introduce decdn_protocol::Region, retune peer-cache encoding/version, and bound registry reads with --timeout-ms (plus make retries aggregate across pages).

Reviewed changes

Copilot reviewed 29 out of 30 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
crates/protocol/tests/snapshots/public_api__public_api.snap Updates public API snapshot to include Region / InvalidRegion exports.
crates/protocol/src/region.rs Adds Region newtype + parsing/serde + tests on normalization and error behavior.
crates/protocol/src/lib.rs Re-exports Region and InvalidRegion from the protocol crate root.
crates/protocol/Cargo.toml Adds serde_json as a dev-dependency for Region serde round-trip tests.
crates/incentive/src/tx.rs Extracts run_then_cleanup helper and adds unit tests for cleanup sequencing.
crates/incentive/src/swap_uniswap.rs Routes swap execution through run_then_cleanup for guaranteed allowance reset.
crates/incentive/src/swap_balancer.rs Routes swap execution through run_then_cleanup for guaranteed allowance resets.
crates/incentive/src/capacity_bond.rs Extends CapacityBond bindings with getNodeByAddress and ejected for CLI logic.
crates/e2e/tests/g_node_06_unbond.rs Adds e2e legs for node deregister and inactive-operator --all exit.
crates/e2e/src/chain.rs Adds is_registered helper based on getNodeByAddress().active.
crates/e2e/src/bindings.rs Adds NodeInfo struct + getNodeByAddress to e2e Solidity bindings.
crates/common/src/cli/node.rs Adds Deregister subcommand and documents --all behavior for inactive operators.
crates/common/src/cli/mod.rs Re-exports DeregisterArgs.
crates/common/src/cli/fetch.rs Validates --region at parse time; redefines --timeout-ms to also bound registry reads.
crates/client-pull/src/discovery.rs Switches region_hint to Option<Region>, bumps peer-cache version, bounds registry read with timeout, and makes retries aggregate across pages.
crates/cli/src/commands/unbond.rs Implements inactive-operator tier release via declareMbps(0) under --all, with testable decision logic.
crates/cli/src/commands/setup.rs Updates guidance to use decdn node deregister instead of “deregister on-chain”.
crates/cli/src/commands/node.rs Dispatches the new NodeCommand::Deregister handler.
crates/cli/src/commands/mod.rs Registers the new deregister command module.
crates/cli/src/commands/fetch.rs Passes discovery deadline into bootstrap_nodes and threads args for warming + caps.
crates/cli/src/commands/deregister.rs New command implementation for decdn node deregister with confirmation + JSON output and unit tests.
crates/cli/src/commands/bundle_pull.rs Bounds registry read with --timeout-ms via bootstrap_nodes(..., registry_cap) and updates tests for new Region typing.
contracts/test/CapacityBond.t.sol Adds tests for inactive declareMbps(0) tier release and for active operator rejection.
contracts/src/CapacityBond.sol Implements declareMbps(0) release path gated on inactivity; updates NatSpec accordingly.
contracts/.gas-snapshot Updates gas snapshot for new/changed CapacityBond tests.
Cargo.lock Adds serde_json dependency via protocol dev-deps.
adr/026-tokenomics.md Updates bond curve + full-exit narrative to include inactive-operator declareMbps(0) path.
adr/019-node-onboarding.md Updates onboarding/deregistration semantics to reflect inactive tier release path.
adr/012-client.md Updates retry-budget semantics and documents registry read bounding via --timeout-ms; removes unimplemented peer_cache_path key.
adr/003-payments.md Updates deregistration and reclaim semantics to match declareMbps(0) release for inactive operators.

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

Comment on lines +168 to +171
pub async fn run_then_cleanup<T, F: Future<Output = ()>>(
work: impl Future<Output = anyhow::Result<T>>,
cleanup: impl FnOnce() -> F,
) -> anyhow::Result<T> {

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.

Pushing back on this one — I don't think it's correct.

Future is in the Rust 2024 prelude (core::prelude::rust_2024 re-exports core::future::Future), and this workspace is edition 2024 (Cargo.toml: edition = "2024", inherited by decdn-incentive via edition.workspace = true). So the unqualified Future resolves without an import.

Verified rather than assumed: touch crates/incentive/src/tx.rs && cargo build -p decdn-incentive compiles clean, and CI on this PR has clippy (-D warnings), rustfmt, cargo doc, and doctest all green on the commit containing this code.

Happy to reconsider if you're seeing an actual compile error — if so, which toolchain/edition?

Comment thread crates/protocol/src/region.rs Outdated
let raw = String::deserialize(d)?;
Self::parse(&raw).ok_or_else(|| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Str(&raw),

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.

Fixed in 98735a5 — now Error::custom(InvalidRegion), so every fallible construction path carries the same input-free message.

Worth noting this is the path where it matters most, more than FromStr: Deserialize is what reads the peer cache, whose region strings originate from an on-chain regionHint that any operator can set to arbitrary bytes, and its decode error surfaces to the user through CacheRead::Unusable inside the ADR 012 bootstrap error.

The redaction test now covers both paths and is renamed construction_errors_do_not_echo_the_input. Mutation-checked: restoring the Unexpected::Str(&raw) form fails it.

@github-actions

github-actions Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 81.61% (was 81.61%, ● 0.00%) — 53777/65892 lines

File Coverage Lines Δ
crates/cli/src/commands/bundle_pull.rs 56.24% 545/969 ▼ 0.12%
crates/cli/src/commands/deregister.rs 59.41% 142/239 new
crates/cli/src/commands/fetch.rs 35.77% 289/808 ▼ 0.40%
crates/cli/src/commands/node.rs 82.54% 1078/1306 ▼ 0.98%
crates/cli/src/commands/setup.rs 48.20% 537/1114 ● 0.00%
crates/cli/src/commands/unbond.rs 73.53% 564/767 ▲ +2.08%
crates/client-pull/src/discovery.rs 96.38% 718/745 ▲ +4.40%
crates/common/src/cli/fetch.rs 100.00% 97/97 ● 0.00%
crates/common/src/cli/mod.rs 100.00% 3/3 ● 0.00%
crates/common/src/cli/node.rs 100.00% 5/5 ● 0.00%
crates/e2e/src/chain.rs 1.18% 11/934 ▼ 0.01%
crates/incentive/src/swap_balancer.rs 66.05% 142/215 ▼ 0.93%
crates/incentive/src/swap_uniswap.rs 65.57% 139/212 ▲ +1.51%
crates/incentive/src/tx.rs 88.39% 99/112 ▲ +16.05%
crates/protocol/src/region.rs 98.16% 160/163 ▼ 1.84%
History
Commit Total Δ vs base
a151571 81.61% ● 0.00%
98735a5 (HEAD) 81.61% ● 0.00%

#1348)

Review catch. `Deserialize` reported failures with
`Unexpected::Str(&raw)`, embedding the rejected value in the error, while
`FromStr` deliberately carries none — and the type's own doc claims
unvalidated bytes are kept out of log fields and metric labels.

The deserialize path is the one where it matters most: it reads the peer
cache, whose region strings originate from an on-chain `regionHint` that
any operator can set to arbitrary bytes, and its decode error reaches the
user through `CacheRead::Unusable` inside the ADR 012 bootstrap error.

Now `Error::custom(InvalidRegion)`, so every fallible construction path
carries the same input-free message. The redaction test covers both paths
and is renamed accordingly; mutation-checked — restoring the
`Unexpected::Str` form fails it.

Public-API snapshot unchanged (no surface change).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ADR 012 advertises a [cache] peer_cache_path key nothing reads

2 participants