Repository navigation
feat(node): refuse-to-serve economics (ADR 041, closes #1755) - #1771
Merged
Merged
Conversation
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.
…imator decoupling
…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]>
There was a problem hiding this comment.
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 intoNodeOrigincandidate 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 + aSharesUpdatedwatcher 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.
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]>
Coverage reportTotal: 81.32% (was 81.35%, ▼ 0.03%) — 61370/75468 lines
History
|
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
ServeEconomicsPolicycomputes a per-MB buy ceiling; candidates quoting above it are skipped, and if none clears, the node returnsPullMiss::BelowMargin→ wireNotFound(client fails over via ADR 037/039).Two-regime ceiling (
max_buy):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).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 (
$5default), never the operational deposit.Inputs:
operator_bpsseeded fromFeeRouter.getShares()and refreshed via the #1747 multiplexed poller (no hardcoded split); heat from the ADR-040FrequencyEstimator(shared, now built formargintoo); 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)n_max.Config (
[cache.serve_economics])policy(off|margin, defaultmargin),discount(0.5),n_max(64),warming_budget($5),warming_refill(~$5/day).offreproduces 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 --checkclean.Follow-ups (deferred, non-blocking)
feeRouter()startup-read resilience (bounded retry / lazy route registration) — today it pinsoperator_bpsat the safe 4000 floor on a transient boot RPC failure.operator_sharesobservability accessor; decode→store is unit-tested).amortized_floorinvariantdebug_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