Repository navigation
fix: close the three #1518 review follow-ups — pre-spend deposit floor, observability, received-delta coverage - #1526
Conversation
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Free Run ID: 📒 Files selected for processing (17)
🚧 Files skipped from review as they are similar to previous changes (14)
WalkthroughThis change measures fee-on-transfer channel credits, adds pre-spend deposit refusal checks, centralizes request pricing across refusal responses, throttles deposit warnings, expands refusal metrics and diagnostics, and documents operational handling. ChangesDeposit accounting and refusal handling
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant ClientHandler
participant Cache
participant Upstream
Client->>ClientHandler: Send request with channel deposit
ClientHandler->>ClientHandler: Resolve rate and pre-spend floor
alt Insufficient headroom
ClientHandler-->>Client: Return InsufficientDeposit
else Floor satisfied
ClientHandler->>Cache: Check or fill content
Cache->>Upstream: Pull through on cache miss
Upstream-->>ClientHandler: Return content or refusal
ClientHandler-->>Client: Send priced response
end
Note 🎁 Summarized by CodeRabbit FreeYour 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 |
Gas snapshotNo gas changes vs base. |
Contracts coverageLine coverage: 90.03% (2520/2799 lines) |
Coverage reportTotal: 80.17% (was 80.24%, ▼ 0.07%) — 54333/67771 lines
History
|
There was a problem hiding this comment.
Pull request overview
This PR closes three follow-ups from #1518 by preventing pre-refusal spend on cache misses (deposit pre-spend floor), making insufficient-deposit refusals operationally observable (logs + alert + dashboard + runbook), and adding fee-on-transfer coverage to assert “received-delta” accounting in PaymentChannel and its Rust mirrors.
Changes:
- Hoist a cache-miss pre-spend deposit floor above all fill tiers and thread a single
rate_per_mbthrough refusal paths to avoid double-clamping/logging. - Add observability for insufficient-deposit refusals (throttled server
warn!+debug!, Prometheus alert, Grafana panel, runbook entry, and a buyer-side “unattributable refusal” metric). - Add fee-on-transfer mock + tests to assert
openChannel/topUpcredit the received balance delta, and update Rust buyer-channel tracking to record credited values.
Reviewed changes
Copilot reviewed 17 out of 17 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| monitoring/prometheus-alerts.yml | Adds an alert for sustained insufficient-deposit refusals. |
| monitoring/grafana-dashboard.json | Adds a stacked panel for payment-class NotFound-collapsed refusal counters. |
| docs/runbook.md | Documents symptoms, detection, and remediation for “refusing paying clients” due to insufficient deposit. |
| crates/node/src/handlers/client/mod.rs | Adds throttled logging state + helpers for insufficient-deposit refusals. |
| crates/node/src/handlers/client/dispatch.rs | Adds the pre-spend miss-floor guard and threads rate_per_mb through refusal paths. |
| crates/node/src/handlers/client/window.rs | Threads rate_per_mb in and logs deposit refusals at the window guard. |
| crates/node/src/handlers/client/wire.rs | Makes refusal responses take an explicit rate_per_mb to avoid implicit recomputation. |
| crates/node/src/node_origin.rs | Meters transient upstream refusals as “unattributable” for buyer-side visibility. |
| crates/node/src/metrics.rs | Adds/expands metrics docs and recorders for new refusal counter; updates metric export tests. |
| crates/node/tests/client_loopback.rs | Adds tests asserting underfunded/spent-out channels cannot trigger paid upstream pulls, plus clamp-once invariants. |
| crates/node/tests/node_origin_pull.rs | Adjusts a deposit value so the test continues to exercise the intended guard layer. |
| crates/client-pull/src/buyer_channel.rs | Records credited deposit on open/top-up, and decodes ChannelToppedUp with fallback reconciliation. |
| crates/cli/src/commands/fetch.rs | Improves NotFound hinting by attaching both “no binding” and “insufficient deposit” possible causes. |
| contracts/test/PaymentChannel.t.sol | Adds FeeOnTransferUSDC + a dedicated test contract covering received-delta crediting and zero-received guards. |
| contracts/.gas-snapshot | Updates snapshot with new fee-on-transfer tests. |
| CHANGELOG.md | Documents the pre-spend floor, buyer credited-deposit tracking, and related behavior notes. |
| adr/037-regional-proxy-warming.md | Updates ADR text to reflect the new two-layer pre-spend deposit protection and residuals. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
The #1516 deposit gate runs on the serve path, which a cache miss reaches only *after* the fill ladder. `try_range_pull_through` and `try_local_populate` front the operator's own origin egress, and `try_pull_through`'s `cache.populate` walks the paid `Peer` origin and fronts real upstream USDC — all three gated on channel ownership via `pull_authorized`, none on solvency. So a dust-deposit channel could name N absent hashes, make the operator pay for each, and be refused afterwards. The client gained nothing (#1516 closed the free-egress half) but the bill was real, and the rising `insufficient_deposit` counter read as "the guard is working" while meaning the opposite. Adds a pre-spend floor above every tier. The channel is already resolved above the ladder for the ADR-011 funder gate (`dispatch.rs`, whose own comment argues "resolving the channel early is a `HashMap` lookup, so the cost is nil") — the `Arc` was simply being dropped, so this holds it rather than taking the map lock again. **Placed in the miss arm, not at the funder gate.** The serve path's ceiling is `min(credit_window, aligned_span(..., total_bytes))`, and `total_bytes` is unknowable before a fill. A gate above the availability check would therefore have to drop the span cap, making it strictly stricter than the serve gate — which refuses funded requests. Two existing tests pin exactly that: a 256 KiB blob on a 5-unit channel, and a resumed tail on a 5-unit channel. The second matters most: `decdn fetch` treats a refused resume as a possibly-stale partial, rewinds to zero and re-pays for the whole blob, so mispricing a resume doubles a user's bill. **The floor is deliberately weak** — one credit window, "can this channel pay for anything at all" — so it catches insolvency without pre-judging a small request. `window.rs` keeps its stricter ceiling. The honest relationship, stated at the call site: `DEFAULT_PULL_AHEAD_BYTES` is exactly one interval, so at default settings the two compute the same number and the window guard is redundant; it earns its place only once `max_blob_size_bytes` is finite. Residual, documented in the ADR and CHANGELOG rather than papered over: a channel funded to exactly one window can still trigger a whole-blob buffered pull costing more than it can repay, because that tier is bounded by the cache engine's separate `max_blob_mb`, not by anything the handler prices. **`respond_error` now takes the request's price as a required argument.** The floor needs the rate and then falls through into the ladder, whose miss arms refuse — and `respond_error` used to compute the rate itself, so that fall-through would double-count `rate_bounds_clamped` and double-log: the #1518 bug one layer up. Rather than fix it by discipline across 21 call sites, the rate-recomputing wrapper is deleted and the explicit one promoted, so `serve_stream` holds the crate's only production `clamped_rate()` call and refusing without having priced the request exactly once is unrepresentable. `serve_via_window_pull_through` takes the rate as a parameter for the same reason — it was recomputing it, so that path double-counted on every refusal today. The pricing block sits *below* the binding block deliberately: the exits above it (stream-cap shed, cooperative close, malformed binding) never sign anything, and pricing them would meter a clamp for a request that never quoted a rate. Tests, both confirmed to fail under an injected mutant: - `underfunded_channel_never_reaches_the_paid_pull` — `hits == 0` is the acceptance criterion; the `cache_miss_total 0` assertion is what proves the refusal came from the floor rather than from the fill missing. - `funded_channel_still_reaches_the_paid_pull` — the boundary control. Without it, tightening the floor or flipping `<` to `<=` would break nothing. `window_pull_through_insufficient_deposit_refuses_before_pulling` had its deposit raised 1 -> 100. At 1 the new floor fires first and the test keeps passing while silently no longer covering `window.rs`'s guard; at 100 it clears the floor (10) but not the 64 MiB blob ceiling (640). Verified by disabling that guard and watching the test fail. Closes #1519 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The refusal emitted no log, and `grep monitoring/ docs/` for
`insufficient_deposit` returned nothing — no alert, no panel, no runbook entry.
"The metric is the signal" was the reasoning when the gate landed, and it does not
hold when nothing watches the metric: it meant "an operator who already suspects
this specific cause and knows the series name can query it by hand." Meanwhile the
wire code is deliberately lossy (`InsufficientDeposit` collapses to `NotFound`
with six other reasons so a prober cannot map channel balances), so a node could
refuse every paying client in silence.
**A throttled warn, not a per-refusal one and not a latch.** Warning per refusal is
farmable into log spam by exactly the abuse the gate guards against; a one-shot
latch — the only existing precedent (`log_per_source_poison`) — is wrong in the
other direction, because this fires legitimately and repeatedly, so a latched
warning is as invisible as none. So: one `warn!` per 5 minutes carrying the count
it suppressed, plus an unconditional `debug!` so a support ticket is answerable.
All three deposit guards emit it.
Unkeyed deliberately. A per-channel `governor` limiter was the obvious reach — it is
already a dependency and the vocabulary the request limiters speak — but keying it
means an unboundedly growing map, and the in-tree cost of owning one is
`retain_recent` sweeps, split single-flight prune guards, and two metrics per map.
That is a lot of machinery for a log line, and the aggregate is what answers the
triage question anyway. The window arithmetic is a pure function so it is tested
without sleeping, including the backwards-clock case (which suppresses rather than
spams — the safe direction for a log gate).
**The two causes are the point.** One unlabeled counter cannot separate a client
running dry (no action) from this node's chain watcher lagging an on-chain
`ChannelToppedUp` (funded clients being turned away, check RPC health). Opposite
remedies, identical signal. The log line, the alert description and the runbook all
say so, and the runbook gives the procedure that distinguishes them: compare
`decdn node channels` against `PaymentChannel.getChannel`.
**Buyer side.** `RefusalVerdict::Transient` bumped no counter at all, so a node
whose own deposit cannot buy anything saw every pull refused with nothing in its
telemetry — a seller refusing our channel signs `NotFound`, indistinguishable from
an honest miss. Adds `node_pull_refused_unattributable`; a rate approaching
`node_pull_refused` means "nobody will serve me", which is local.
**The CLI hint was pointing at the wrong fix.** `annotate_unbound_cache_miss`
hard-coded one cause for a `NotFound` ("set `blockchain.capacity_bond_address`"),
so an unbound fetch against an underfunded channel was told to set a config field
that would not help. It now checks the deposit case first, because that is the one
it can *prove* rather than guess: the signed refusal carries the node's quoted
rate, and the channel's own deposit and paid amount are in scope, so the shortfall
is arithmetic. It reasons only about our own channel from data the node already
sent, so the reject-reason collapse is untouched.
Two things found while doing this, worth flagging rather than burying:
- I nearly shipped a stale metric name. The first draft of the alert divided by
`decdn_serve_stream_requests_total`, which the exporter does not emit — the exact
bug #1513 is open about. There is no serve-attempt counter at all, so the alert
is a raw rate and says why.
- The *existing* `DecdnHighStreamErrorRate` alert is built on
`decdn_streams_failed_total` and `decdn_streams_completed_total`, neither of
which this exporter emits. That rule cannot fire. Left alone as #1513's scope,
but called out in a comment beside the new alert so nobody copies its denominator.
Also completes `serve_stream_rejected_counters_start_at_zero_and_increment_per_reason`,
which listed 10 of the 13 reject counters — the four missing ones had nothing
pinning that they export at zero, so a dashboard querying them read `(no data)`.
Closes #1520
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ransfer token `openChannel` and `topUp` credit a measured balance delta rather than the requested amount, and both carry a comment explaining that this is what stops a fee-on-transfer proxy over-stating a channel against the shared USDC pool. Nothing tested it: the suite had no fee-bearing token, so the delta arithmetic and both post-transfer `ZeroAmount` guards were unexercised on every path. Three comments asserting a protection with nothing behind them. Adds an inline `FeeOnTransferUSDC` (overriding OZ v5's `_update`, the same technique as `MaliciousERC20` in `TestnetFaucet.t.sol`) and a second test contract — `PaymentChannelTest` hard-codes `new MockUSDC()` and types its `usdc` field concretely, so there is no seam to inject a token through. Inline rather than `test/mocks/`, matching the 16-of-30 majority; `mocks/` holds cross-file interface stand-ins and the one token Rust needs as a standalone artifact. Five assertions. The valuable ones are not the reverts but the deltas: `ch.deposit == received` (**not** `== requested`) on open and top-up, and `ChannelOpened.deposit` carrying the same value, since off-chain buyers build their local row from that event. The 100%-burn cases reach the post-transfer `ZeroAmount` guards, which no test could previously reach at all — the pre-transfer guard cannot catch them because the requested amount is non-zero. The fixture arms the fee only AFTER funding and approving the client. Funding at a 100% burn leaves the client with nothing, and the revert under test becomes `ERC20InsufficientBalance` instead of the guard — which is exactly how the first draft failed. **Contract behaviour is unchanged.** A partial shave is credited as received, not reverted. That is now an asserted decision rather than an unexercised path. Reverting would hard-code "the settlement token must never be fee-bearing" into the contract — a policy call larger than the test gap that prompted this, and one that runs against the two commits that just deleted the on-chain minimum deposit. Also fixes the Rust mirror of the same accounting, which was wrong in both legs: `open_channel` recorded its `deposit` argument while already taking `channelId` and `expiresAt` from `ChannelOpened`, and `top_up` never decoded `ChannelToppedUp` at all. Under a fee-bearing token both would put the over-statement in the buyer's own row — vouchers climbing past the on-chain deposit, `_advanceClaimWatermark` reverting at settlement, the seller stranded with delivered bytes it cannot claim. Both now read the credited value; `top_up` falls back to the requested amount with a `warn!` if the event is missing, since the funds are already escrowed by then. The comment asserting "USDC is not fee-on-transfer, so the local `+= additional` matches" is gone, because the code no longer relies on it. Not reachable today: the USDC address is immutable at deployment and mainnet USDC is not fee-on-transfer. This is defensive depth. Closes #1521 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Four reviewers, and they converged on one theme: the mechanisms were sound, the justifications around them were not. Eight factual claims were wrong and three doc comments were attached to the wrong item. Two were genuine bugs. **Bugs** The floor priced a bounded range at a whole credit window even though `byte_len` is right there. At stock config that window is 8 MiB (`DEFAULT_CREDIT_WINDOW_BYTES` over a 4 MiB `DEFAULT_VOUCHER_INTERVAL_MB`), so a client funded for a 16 KiB range was served warm and refused cold — and `decdn fetch` reads a refused resume as a possibly-stale partial, rewinds to zero and re-pays for the whole blob. The floor now caps by `aligned_span` when the request bounds itself, which is exactly the argument used against hoisting it above the availability check in the first place. `decdn channel top-up` does not exist. `ChannelCommand` is `List | CoopClose | Close | Settle | Clean | Open`, so the new hint sent users to clap's "unrecognized subcommand" — worse than the opaque `NotFound` it replaced. And the CLI's estimate used the *protocol's* 1 MiB interval against the node's 8 MiB floor, so it under-detected by 8x and stayed silent across exactly the headroom band a stock node refuses in. Both fixed; the message is now a lower bound phrased as a possibility, and both causes attach instead of the first winning. **Wrong claims, all corrected** - "a merely small request is not pre-judged" and the CHANGELOG's "could not have completed the transfer either way" — false at stock config, where the floor is 8 MiB. The residual is now stated rather than denied. - "`DEFAULT_PULL_AHEAD_BYTES` is exactly one interval" — it is 1 MiB against a 4 MiB default interval. The conclusion held, but via `window.rs`'s `.max(credit_window(..))` term, not the stated premise. - "earns its place only once `max_blob_size_bytes` is finite" — `pull_ahead_bytes` is validated against `max_unrecouped_leech_bytes`, never the window, and a 1 MiB blob cap under an 8 MiB window makes that guard *weaker* than the floor. - "every exit above this point returns without signing anything" — the cooperative close signs an EIP-712 waiver. It carries no rate, which is what actually matters. - "`_advanceClaimWatermark` would revert at `withdraw`/`settleChannel`" — `settleChannel` never calls it, and the seller refuses off-chain via `stage_voucher` long before. The real harm is buyer-side: the inflated row suppresses auto-refill and compounds with every top-up. - "nothing pinned that they export at zero … read `(no data)`" — those four counters always exported; what was missing was the assertion. - "same technique as `MaliciousERC20`" — shared hook, not shared technique; that one is a reentrancy mock. - "a property the compiler checks" — it stops implicit recomputation; a caller can still pass a wrong value. Now says what it actually buys. - `blockchain.event_poll_interval_sec` → `_ms`; the panel described `cache_miss` as "not availability" while plotting it; `Overloaded` is peer backpressure, not the local problem the counter's doc implied. **Three orphaned doc comments.** New items were inserted between an existing doc block and the item it documented, so the block re-anchored and the original was left bare. `credit_window` — cited by three other comments and called by the new floor — ended up with no doc at all, its deadlock-freedom rationale heading a const. Nothing catches this: both readings compile and rustdoc sees every item as documented. **Four tests, each verified against an injected mutant** - `spent_out_channel_never_reaches_the_paid_pull` — the `last_amount` term. A mutant reading `headroom = deposit` passed the *entire* suite before this. A spent-out channel is the production shape; a dust channel is the adversarial one, and only the latter was covered. - `a_refused_request_clamps_the_rate_exactly_once` and `a_request_rejected_before_pricing_does_not_clamp_the_rate` — #1518's invariant, which nothing asserted. `rate_bounds_clamp_events` was referenced by no test, so the whole `respond_error` collapse rested on review attention. The second pins the *placement* of `clamped_rate()` below the binding block, previously prose only. - `deposit_refusal_warn_reports_exactly_what_it_swallowed` — the throttle's atomics. The suppressed count is the feature and every part of producing it was unverified. Also: `top_up`'s missing-event fallback now reads `getChannel` instead of guessing the requested amount — the funds are escrowed by then, so an `eth_call` is cheap, and the state that triggers it ("our ABI is wrong") is the worst one in which to guess. Its `log_decode` filters on the emitting address, since `topUp` transfers before it emits and this function's own premise is a token that misbehaves during transfer. `FeeOnTransferUSDC::setFeeBps` is bounded; the vacuous post-revert assert is replaced with one that can fail; the top-up leg gained the balance anchor the open leg had. Extracting `resolve_top_up_credit` and `log_top_up_outcome` keeps `top_up` under the complexity limit — the lint was right that the fallback deserved its own function. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three review comments, all correct. The first was worse than reported and the
other two exposed a pattern worth naming.
**The CLI hint printed literal whitespace runs.** The message was assembled with
single backslashes inside a generator heredoc, so the *generator* consumed them as
its own line continuations — stripping the newlines but leaving the indentation
inside the Rust string literal. The runtime output contained 18-space runs
("below the AT LEAST ~250000"). Rewritten with real Rust `\`
continuations and verified by reconstructing the collapsed literal: zero
double-space runs remain. The sibling message in the same function was already
correct because it used escaped backslashes, which is what made the bug invisible
to inspection.
Also dropped the "AT LEAST ~" construction the reviewer flagged as a grammatical
glitch; the lower-bound caveat now reads as a clause rather than shouted adjectives.
**Two CHANGELOG claims contradicted the code**, both flagged:
- "the one-clamp-per-request invariant something the compiler enforces" — it is
not. Taking the price as a parameter stops `respond_error` recomputing it
*implicitly*, which is the shape the bug took; a caller can still pass an inline
`clamped_rate()` or the wrong value. What holds it is the single call site plus
the two new tests. This is the same overstatement the review round corrected in
`wire.rs`'s doc — I fixed the code comment and left this copy standing.
- `top_up`'s fallback chain — it reconciles against `getChannel` first and only
credits the requested amount if that read *also* fails, at `error!` rather than
`warn!`. The entry described the pre-review behaviour.
**Three more of the same class the reviewer did not reach.** Every one is a claim I
corrected in a code comment during the review round while leaving the CHANGELOG
copy stale, which is the actual defect here — not the individual sentences:
- `_advanceClaimWatermark` reverting at `withdraw`/`settleChannel`. `settleChannel`
never calls it, and the seller refuses off-chain via `stage_voucher` long before.
The real harm is buyer-side: the inflated row makes the auto-refill fire late or
short, and the drift compounds with every top-up.
- "the USDC address is immutable at deployment and mainnet USDC is not
fee-on-transfer" conflated address with behaviour. Real USDC is an upgradeable
proxy — the immutable *address* is precisely why a behaviour change could not be
escaped, which is the point rather than an aside.
- the cache engine's "separate `max_blob_mb`" — not separate; engine and handler
both derive from `cache.max_blob_size_mb`, and what is true is only that the
engine is the one bounding that tier.
Verification: `cargo nextest run --workspace` 2666 passed, clippy `-D warnings`
clean, `cargo fmt --check` clean, `decdn-cli` 385 passed. One full-suite run hit
`probe_rate_limit_returns_rate_limited_close_code`; it passes 6/6 in isolation and
neither `probe_loopback.rs` nor any probe rate-limit source file is in this
branch's diff, so it is a pre-existing timing flake under parallelism rather than
a regression here.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
4ac019b to
c2cbad7
Compare
Closes #1519
Closes #1520
Closes #1521
The three follow-ups filed from #1518's multi-agent review. They share a root: the deposit gate #1516 added was narrower than its documentation claimed, and nothing made its refusals visible.
#1519 — an underfunded channel could still make the node spend (
bug,security,high)The #1516 gate runs on the serve path, which a cache miss reaches only after the fill ladder.
try_range_pull_throughandtry_local_populatefront the operator's own origin egress, andtry_pull_through'scache.populatewalks the paidPeerorigin and fronts real upstream USDC — all three gated on channel ownership viapull_authorized, none on solvency. So a dust-deposit channel could name N absent hashes, make the operator pay for each, and be refused afterwards. The client gained nothing (#1516 closed the free-egress half) but the bill was real, and the risinginsufficient_depositcounter read as "the guard is working" while meaning the opposite.A pre-spend floor now runs above every tier. The channel was already resolved above the ladder for the ADR-011 funder gate and the
Arcsimply dropped, so this holds it rather than taking the map lock again.Placed in the miss arm, not at the funder gate. The serve path's ceiling is
min(credit_window, aligned_span(..., total_bytes)), andtotal_bytesis unknowable before a fill. A gate above the availability check would have to drop the span cap, making it strictly stricter than the serve gate — which refuses funded requests. Two existing tests pin exactly that, and the resume one matters most:decdn fetchreads a refused resume as a possibly-stale partial, rewinds to zero and re-pays for the whole blob, so mispricing a resume doubles a user's bill.The floor caps by the chunk-group-aligned span when the request bounds itself, so a bounded range is priced at what it will actually be billed. For an unbounded request the window stands, and the residual that leaves is stated rather than denied: at stock config that window is 8 MiB, so a cold sub-window whole-blob fetch is priced at 8 MiB while the same blob served warm is priced at its actual span.
Collateral:
respond_errornow takes the request's priceThe floor needs the rate and then falls through into the ladder, whose miss arms refuse — and
respond_errorused to compute the rate itself, so that fall-through would double-countrate_bounds_clampedand double-log: #1518's bug one layer up. Rather than fix it by discipline across 21 sites, the rate-recomputing wrapper is deleted and the explicit one promoted, soserve_streamholds the crate's only productionclamped_rate()call.serve_via_window_pull_throughtakes the rate as a parameter for the same reason — that path double-counted on every refusal before this.#1520 — the refusal was unobservable
grep monitoring/ docs/forinsufficient_depositreturned nothing: no alert, no panel, no runbook entry. "The metric is the signal" was the reasoning in #1518 and it does not hold when nothing watches the metric.warn!(one per 5 min, carrying the count it suppressed) plus an unconditionaldebug!, at all three deposit guards. Not per-refusal (farmable into log spam by the abuse it guards against) and not a one-shot latch (this fires legitimately and repeatedly). Unkeyed deliberately — a per-channelgovernorlimiter needsretain_recentsweeps, split prune guards and two metrics per map, which is a lot of machinery for a log line.ChannelToppedUp(funded clients being turned away). Opposite remedies, identical signal — the log line, the alert, and the runbook all say so, and the runbook gives the procedure that distinguishes them.RefusalVerdict::Transientbumped no counter, so a node whose own deposit can't buy anything saw every pull refused with nothing in its telemetry. Addsnode_pull_refused_unattributable.annotate_unbound_cache_misshard-coded "setblockchain.capacity_bond_address". It now checks the deposit case too, from data the node already sent, and attaches both causes rather than letting the first win.#1521 — the received-delta accounting was untested
openChannelandtopUpcredit a measured balance delta, and both carry comments explaining that this is what stops a fee-on-transfer proxy over-stating a channel. Nothing tested it — the suite had no fee-bearing token, so the delta arithmetic and both post-transferZeroAmountguards were unexercised.Adds an inline
FeeOnTransferUSDCand a second test contract (5 tests). The valuable assertions are the deltas, not the reverts:ch.deposit == received(not== requested) on both legs, anchored to the real balance. Contract behaviour is unchanged — a partial shave is credited as received, now an asserted decision rather than an unexercised path.Also fixes the Rust mirror, wrong in both legs:
open_channelrecorded its argument while already takingchannelId/expiresAtfrom the event, andtop_upnever decodedChannelToppedUp. Both now read the credited value; the missing-event path readsgetChannelrather than guessing, since the funds are escrowed by then and "our ABI is wrong" is the worst state in which to guess.The review round
A four-agent review of these three commits found two bugs and eight wrong factual claims in my own comments, plus three doc comments attached to the wrong item. All fixed in the final commit, which lists them individually.
The pattern is worth naming: I verified the test harness constants (interval 1 MiB, credit window
None) and reasoned as if they were production defaults. They are 4 MiB and 8 MiB. That one wrong premise produced four of the eight wrong claims — including the bounded-range mispricing above, and a CLI estimate that under-detected by 8× and stayed silent across exactly the band a stock node refuses in.Three doc comments were orphaned by inserting new items between a doc block and the item it documented.
credit_window— cited by three other comments and called by the new floor — ended up undocumented, its deadlock-freedom rationale heading a const. Nothing catches this: both readings compile and rustdoc sees every item as documented.Verification (all local)
cargo nextest run --workspaceforge testforge build --sizes --deny warningscargo fmt --check/forge fmt --checkcargo clippy --workspace --all-targets -D warningsfail_on: medium) / solhintOverall gas change: 0)anvil e2e (settlement + bringup)anvil e2e (journeys)Seven mutants injected and killed, which is how each new test earned its place. Three are worth naming: disabling the floor fails the headline test; a mutant reading
headroom = deposit(ignoringlast_amount) passed the entire suite beforespent_out_channel_never_reaches_the_paid_pull; and restoring the rate-recomputingrespond_errornow failsa_refused_request_clamps_the_rate_exactly_once— #1518's invariant had no test at all.Rebased onto
mainafter #1518 merged (squash), replaying only these four commits — no conflicts.Residual, tracked not hidden
A channel funded for exactly one window can still trigger a whole-blob buffered node-to-node pull costing more than it can repay, because that tier's real bound is the cache engine's
max_blob_size_mbrather than anything the handler prices. Closing it needs the origin size probe to run before the floor — larger than #1519 asked for. Documented in ADR 037 and the CHANGELOG; worth its own issue.🤖 Generated with Claude Code
Summary by CodeRabbit