Skip to content

feat(node): refuse-to-serve economics (ADR 041, closes #1755) - #1771

Merged
alpergundogdu merged 15 commits into
mainfrom
claude/intelligent-payne-875a56
Aug 20, 2026
Merged

alpergundogdu merged 15 commits into
mainfrom
claude/intelligent-payne-875a56

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

Refuse-to-serve economics (ADR 041, closes #1755)

Adds a buy-side economic gate so a node relays a foreign-namespace cache miss only when it can profitably resell — the economic sibling of the ADR-040 admission/eviction work. Node-local, config-selectable, no wire surface.

What it does

On a miss the node buys bytes from a peer to relay. A ServeEconomicsPolicy computes a per-MB buy ceiling; candidates quoting above it are skipped, and if none clears, the node returns PullMiss::BelowMargin → wire NotFound (client fails over via ADR 037/039).

Two-regime ceiling (max_buy):

  • While the source has warming allowance: max(P_sell, amortized) — buys at market so a flat-price mesh still warms (the primer's amortized-only floor deadlocks warming; see ADR §buy-ceiling).
  • Once spent: amortized = (operator_bps/10_000)·N̂·P_sell — grief-proof profit-guarantee floor. N̂ = clamp(round(discount·heat), 1, n_max).

Per-source serve-vindicated warming allowance (signed net-P&L ledger, keyed on the bonded seller node, not the client): debit the full buy cost on a speculative pull, credit realized serve-margin on each serve, forget the tag on eviction (all removal paths). Bounds at-market dud-flood grief to a small per-source budget ($5 default), never the operational deposit.

Inputs: operator_bps seeded from FeeRouter.getShares() and refreshed via the #1747 multiplexed poller (no hardcoded split); heat from the ADR-040 FrequencyEstimator (shared, now built for margin too); candidate prices from the existing probe cache (no new fan-out). Own-namespace serves never hit the gate.

Security model (see ADR §8, tests in node_origin_pull.rs / client_loopback.rs)

  • Attack A (over-market sole source): refused; heat only rises on paid serves (HC-1); bait-and-switch aborts at pull-commit (HC-2); over-market loss bounded by n_max.
  • Attack B (at-market dud flood): bounded to the per-source allowance, then the source is cut off; a second source is independent; the deposit is never the target.

Config ([cache.serve_economics])

policy (off|margin, default margin), discount (0.5), n_max (64), warming_budget ($5), warming_refill (~$5/day). off reproduces static-ceiling-only behavior.

Commits

Config → policy → FeeRouter binding/cell → watcher route → runtime wiring + estimator decoupling → PullMiss::BelowMargin → warming allowance → gate integration + serve/evict hooks → adversarial tests → forget-on-all-evict-paths fix → ADR 041.

Testing

cargo nextest run --workspace → 2784/2784; workspace build + clippy -D warnings + fmt --check clean.

Follow-ups (deferred, non-blocking)

  • feeRouter() startup-read resilience (bounded retry / lazy route registration) — today it pins operator_bps at the safe 4000 floor on a transient boot RPC failure.
  • anvil-e2e live fee-refresh test (needs an operator_shares observability accessor; decode→store is unit-tested).
  • Minor: an amortized_floor invariant debug_assert; has_frequency_estimator() gating; a Solidity-constant mirror note; small test-coverage/style nits.

Sibling design issues already filed: #1758 (egress-aware sourcing), #1759 (foreign-namespace relay opt-out).

🤖 Generated with Claude Code

alpergundogdu and others added 13 commits August 20, 2026 12:45
Adds the refuse-to-serve economics config block (ADR 041): policy
("off"/"margin"), discount (converted to basis points), n_max, and
per-source warming_budget/warming_refill, mirroring the existing
[cache.tinylfu] pattern (raw type, resolved type, defaults + resolve +
load-time validation). Updates every hand-built ResolvedCache fixture
and exhaustive CacheConfig destructure across cli/node to carry the
new field, and adds it to the operator-facing config template.
Registers a Route for FeeRouter.SharesUpdated into the existing
multiplexed getLogs poller, mirroring rate_bounds_watcher.rs: decodes
each event into the shared OperatorShares cell (narrowed via
operator_bps_from_shares), with a periodic authoritative getShares()
re-read as a safety net against a missed log. Adds matching
fee_shares_watcher_{last_tick_timestamp_seconds,task_panicked}
metrics fields/recorders alongside the rate-bounds watcher's.
…used metric

Adds the PullMiss::BelowMargin variant, its miss_answer arm (wire-identical
to Clean's NotFound, so the serve-economics buy ceiling never leaks to the
client), and a dedicated decdn_serve_economics_refused_total counter. Task 8
wires the buy-loop gate that actually produces this variant and increments
the metric.
Adds below_margin_never_masks_or_is_masked_by_a_local_fault, asserting both
argument orders for LocalFault-over-BelowMargin and BelowMargin-over-Clean in
the walk fold. Extends the or() doc comment to explain why BelowMargin
outranks Clean in the fold.
… loop (ADR 041)

Wire the ADR 041 buy-side profitability gate into the node-to-node cache-miss
buy loop. A new `economic_ceiling` helper derives this node's sell rate and the
policy's two-regime buy cap per ranked candidate: a quote above the cap is
refused (metered `serve_economics_refused`, folded into the walk as
`PullMiss::BelowMargin`), and a quote merely above the amortized profit floor is
bought but flagged speculative. The cap is folded into the effective stream
ceiling so a bait-and-switch above it aborts mid-pull. On a clean speculative
pull each of the three buy paths (buffered `pull_from_candidate`, progressive
`NodeProgressivePull::finish`, gap-driven `run_pull_leg`) debits the source's
per-source `WarmingAllowance` by the full buy cost.

Adds the shared `warming: Arc<WarmingAllowance>` field to `NodeOriginConfig`,
constructed once in runtime bring-up and threaded through `ChainHandlers`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
… 041)

Complete the ADR 041 warming-allowance loop's serve and eviction sides. The
client handler now holds the shared `WarmingAllowance` and the live operator
fee-share cell; on each clean serve (`serve_leg` and `delivery`, beside the ADR
040 `observe_hit` sighting) it credits the realized operator margin —
`(operator_bps / 10_000) · P_sell · MB(served)` — back to the source that
speculatively warmed the blob. `credit_serve` is a no-op for an untagged hash, so
own-namespace / non-speculative serves cost one map lookup.

The eviction driver forgets an evicted hash's source tag on a successful
`release_for_eviction`, so a reused cache slot can never credit a stale source.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Adds node-loopback coverage for the ADR 041 buy-side gate: a bait-and-switch
abort (HC-2, probe quote clears the gate then the real StreamResponse quote
exceeds the composed ceiling), Attack A (a malicious upstream quoting exactly
at the amortized ceiling with heat pinned to n_max, bounding the buyer's
measured loss against one realized resale), Attack B (a per-source dud-flood
that drains a source's warming allowance after one dud, refuses further
at-market cold buys from that source, leaves an independent source untouched,
and confirms serve-vindication on a re-served blob), and an own-namespace test
proving the gate is never consulted on the local-origin serve path even under
the most restrictive possible settings.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
… 041)

WarmingAllowance::forget only ran from the eviction-driver sweep, leaving the
hash->source provenance tag in place when a blob left the cache via the
blacklist takedown watcher or the admin `decdn node evict` RPC. Thread the
shared WarmingAllowance Arc into both production removal paths and forget the
tag on a successful evict, so a re-admitted hash can never spuriously credit a
stale source's allowance.
Records the buy-side ServeEconomicsPolicy gate: two-regime buy ceiling
max(P_sell, amortized), per-source serve-vindicated warming allowance,
and the Attack A / Attack B adversarial reasoning implemented in this
branch. Adds 041 to the ADR book list and the architecture reading order.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Copilot AI lite review requested due to automatic review settings August 20, 2026 15:22

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

Implements ADR 041 “refuse-to-serve economics” in the node crate by adding a buy-side profitability gate for cache-miss relay legs, including a per-source warming allowance ledger, plus a chain watcher to keep the operator fee-share input current. This fits into the node’s existing miss-pull path (NodeOrigin) and shared chain-event poller wiring, without adding any wire/protocol surface.

Changes:

  • Add ServeEconomicsPolicy (off/margin) and integrate its buy-ceiling + enforcement into NodeOrigin candidate selection and pull-commit ceilings.
  • Add per-source serve-vindicated warming allowance (WarmingAllowance) with forget-on-evict hooks across eviction/admin/blacklist paths and serve-side crediting.
  • Add live operator fee-share (FeeRouter.getShares()) seeding + a SharesUpdated watcher route, plus config plumbing and tests.

Reviewed changes

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

Show a summary per file
File Description
crates/node/tests/sighup_signal.rs Updates resolved-config test fixture for new blockchain/cache fields.
crates/node/tests/node_origin_pull.rs Adds extensive ADR 041 coverage for gate behavior, bait-and-switch, and adversarial bounds.
crates/node/tests/client_loopback.rs Verifies own-namespace origin fills bypass serve-economics gating.
crates/node/tests/anvil_bringup_shutdown_e2e.rs Updates e2e config fixture for new resolved config fields.
crates/node/src/warming_allowance.rs Introduces per-source warming allowance ledger with debit/credit/forget and unit tests.
crates/node/src/serve_economics.rs Introduces ServeEconomicsPolicy trait plus margin policy implementation and selector.
crates/node/src/runtime/reload.rs Adds defaults + restart-required detection for cache.serve_economics and new poll interval.
crates/node/src/runtime/mod.rs Wires policy selection, shared estimator decoupling, operator fee-share seeding, watcher route registration, and shared warming handle threading.
crates/node/src/runtime/eviction.rs Ensures eviction sweep forgets warming provenance tags on removal.
crates/node/src/node_origin/pull_leg.rs Integrates economic ceiling decisions into pull-leg target setup and speculative-debit on success.
crates/node/src/node_origin/mod.rs Adds new config inputs, implements economic gate helpers, new miss classification (BelowMargin), and speculative debit for buffered/progressive paths.
crates/node/src/metrics.rs Adds ADR 041 refusal metric and fee-shares watcher liveness/panic metrics.
crates/node/src/lib.rs Exposes new modules: fee shares, fee-shares watcher, serve economics, warming allowance.
crates/node/src/handlers/client/serve_leg.rs Credits warming allowance on clean serve completion (serve_leg path).
crates/node/src/handlers/client/mod.rs Threads warming allowance + operator shares into client handler deps and implements credit logic.
crates/node/src/handlers/client/delivery.rs Credits warming allowance on clean serve completion (delivery path).
crates/node/src/fee_shares.rs Adds shared atomic cell for live operator fee-share and narrowing helper.
crates/node/src/fee_shares_watcher.rs Adds SharesUpdated watcher route and periodic authoritative getShares() re-read.
crates/node/src/blacklist_watcher.rs Ensures governance takedowns forget warming provenance tags when evicting.
crates/node/src/admin.rs Ensures admin evict forgets warming provenance tags when evicting.
crates/incentive/src/payment_pool.rs Adds FeeRouter RPC/event bindings to support fee-shares watcher.
crates/common/src/config/types.rs Adds new config knobs for fee-shares polling and serve-economics configuration.
crates/common/src/config/resolved.rs Adds resolved forms of new blockchain/cache config fields.
crates/common/src/config/mod.rs Adds defaults + resolver validation for new fields and serve-economics config.
crates/cli/tests/config_validate.rs Updates CLI resolved-config test fixture for new fields.
crates/cli/src/commands/config.rs Prints new resolved field and documents new config tables in the default config template.
crates/cache/src/engine.rs Adds has_frequency_estimator() introspection for wiring tests.
adr/Makefile Adds ADR 041 to the ADR book build.
adr/architecture.md Links ADR 041 in the architecture chapter index.
adr/041-refuse-to-serve.md Adds ADR 041 design/acceptance criteria document.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread crates/common/src/config/mod.rs Resolved
Comment thread adr/041-refuse-to-serve.md Resolved
Resolves conflicts with load-shedding (#1756) and origin-only relay
(#1759), which both extend ClientHandlerDeps/ClientHandler and the config
re-exports: kept all fields from both sides (warming + operator_shares +
relay_foreign_namespaces; ResolvedServeEconomics + ResolvedLoadShed).

Also corrects the warming-budget doc comment and ADR 041 to match the
shipped ledger: the allowance is debited the full upstream buy cost and
credited the realized serve margin (a one-hit nets ~0.4·P_sell), not
"debited by the speculative gap" (review feedback on PR #1771).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 81.32% (was 81.35%, ▼ 0.03%) — 61370/75468 lines

File Coverage Lines Δ
crates/cache/src/engine.rs 91.86% 3936/4285 ▲ +0.01%
crates/cli/src/commands/config.rs 86.53% 546/631 ▲ +0.06%
crates/common/src/config/mod.rs 97.11% 6865/7069 ▲ +0.03%
crates/common/src/config/resolved.rs 100.00% 42/42 ● 0.00%
crates/incentive/src/payment_pool.rs 98.75% 79/80 ● 0.00%
crates/node/src/admin.rs 93.13% 976/1048 ▼ 1.51%
crates/node/src/blacklist_watcher.rs 75.02% 928/1237 ▼ 0.02%
crates/node/src/fee_shares.rs 88.10% 37/42 new
crates/node/src/fee_shares_watcher.rs 84.91% 135/159 new
crates/node/src/handlers/client/delivery.rs 95.95% 237/247 ▲ +0.02%
crates/node/src/handlers/client/mod.rs 92.27% 1205/1306 ▲ +0.08%
crates/node/src/handlers/client/serve_leg.rs 85.98% 141/164 ▲ +0.09%
crates/node/src/metrics.rs 94.46% 852/902 ● 0.00%
crates/node/src/node_origin/mod.rs 91.27% 1129/1237 ▲ +0.26%
crates/node/src/node_origin/pull_leg.rs 85.07% 570/670 ▼ 0.60%
crates/node/src/runtime/eviction.rs 79.66% 372/467 ▲ +0.53%
crates/node/src/runtime/mod.rs 48.24% 1153/2390 ▲ +0.34%
crates/node/src/runtime/reload.rs 96.53% 1532/1587 ▲ +0.04%
crates/node/src/serve_economics.rs 100.00% 91/91 new
crates/node/src/warming_allowance.rs 95.45% 84/88 new
History
Commit Total Δ vs base
7782661 81.40% ▲ +0.05%
8cb81ab (HEAD) 81.32% ▼ 0.03%

Resolves conflicts with the G-NODE-01 onboarding work (#1030/#1768) on
AdminState and the admin-server builder chain: kept both the ADR 041
`warming` handle (for admin-evict forget) and the new `staker_set` handle.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alpergundogdu
alpergundogdu merged commit aa434a5 into main Aug 20, 2026
25 checks passed
@alpergundogdu
alpergundogdu deleted the claude/intelligent-payne-875a56 branch August 20, 2026 16:45
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.

Refuse-to-serve / stop-serving policy (economic, margin-based)

2 participants