Repository navigation
perf(node,cache): reduce TTFB on the cdn/client stream-open path (#1789) - #1871
Merged
Merged
Conversation
There was a problem hiding this comment.
Pull request overview
This PR reduces time-to-first-byte (TTFB) on the cdn/client/v1 stream-open path in the node by removing per-request disk fsyncs and redundant crypto work, eliminating hot-path locks, and overlapping independent admission checks. It touches the node handler, cache engine/probe, the lane/capability store, and the config surface to add a fault TTL for origin probing.
Changes:
- Buffer and dedup capability persistence in the lane store; add an in-process capability owner-recovery cache to avoid repeated
ecrecover. - Replace hot-path lane metrics refresh and cache eviction checks with atomic/lock-free structures (lane count atomic;
evictedviaArcSwap), and addserve_auditto fold store presence+size into one call. - Memoize origin-probe faults under a new
origin_probe_fault_ttl_secconfig knob and overlap origin presence probing with pool status reads during stream open.
Reviewed changes
Copilot reviewed 17 out of 17 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/handlers/client/mod.rs | Adds capability verification cache, buffers capability persistence, and switches lane gauge tracking to an atomic counter. |
| crates/node/src/handlers/client/dispatch.rs | Overlaps origin probe with pool status read and uses serve_audit to reduce store round-trips on cache hits. |
| crates/node/src/channel_store.rs | Buffers capability rows in the working set, flushes them with lane rows, and dedups identical capability rewrites. |
| crates/cache/src/engine.rs | Makes evicted lock-free via ArcSwap, memoizes origin-probe faults, and introduces serve_audit. |
| crates/cache/src/origin_probe.rs | Adds Fault presence state and a dedicated fault TTL in the probe memo. |
| crates/common/src/config/types.rs | Adds origin_probe_fault_ttl_sec to the cache config schema. |
| crates/common/src/config/resolved.rs | Adds resolved origin_probe_fault_ttl_sec field. |
| crates/common/src/config/mod.rs | Resolves and re-exports the new default for origin-probe fault TTL. |
| crates/config-types/src/defaults.rs | Introduces DEFAULT_ORIGIN_PROBE_FAULT_TTL_SEC. |
| crates/config-types/src/lib.rs | Re-exports the new default constant. |
| crates/node/src/runtime/mod.rs | Wires the new fault TTL into CacheEngine::set_origin_probe_config. |
| crates/node/src/runtime/reload.rs | Includes origin_probe_fault_ttl_sec in restart-required cache fields and test config. |
| crates/cli/src/commands/config.rs | Documents origin_probe_fault_ttl_sec in the default config template and validation tests. |
| crates/cli/tests/config_validate.rs | Updates resolved-config samples to include the new fault TTL field. |
| crates/node/tests/sighup_signal.rs | Updates resolved-config seed to include the new fault TTL field. |
| crates/node/tests/anvil_bringup_shutdown_e2e.rs | Updates e2e config builder to include the new fault TTL field. |
| crates/node/tests/client_loopback.rs | Updates tests for register_lane/capability intake signature changes (async→sync where applicable). |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Coverage reportTotal: 82.27% (was 82.11%, ▲ +0.16%) — 69251/84173 lines
History
|
#1789 item 6) A fault (transport error / timeout) is a backend outage for an entire namespace, not a per-hash absence. Previously faults were never memoized, so every probe re-HEADed a failing origin. Present, Absent, and Fault now each get their own TTL from cache.origin_probe_fault_ttl_sec (5s), between the negative and positive TTLs.
…tream open (#1789 item 7, part A) The open path serialized two independent network awaits back to back: the origin-only presence probe (a memoized HEAD/HeadObject, gated on the relay policy) and the cached getPool view read. Run them on tokio::join! so their latencies overlap on the happy path.
item 7, part B) Add CacheEngine::serve_audit, which reads presence, eviction, and size in a single BlobStatus call, and use it on the stream-open delivery path in place of the previous has() then inspect() pairing. A cache hit now touches the store actor once instead of twice; the miss path still inspects after a fill, and the size gate semantics are unchanged (range_pulled_size wins, then the audit's size, then a post-fill inspect).
…1789 item 2) The lock is held only for the IndexMap lookup/insert; the secp256k1 recovery runs outside it, so a burst of distinct capabilities at session open does not serialize on the cache mutex. Duplicate recovery under concurrent races is fine for a deterministic result.
thiras
force-pushed
the
perf/node-ttfb-open-path-1789
branch
from
August 30, 2026 18:40
9f761ee to
064dd7c
Compare
`NoopWarmingCreditSink::credit` takes `[u8; 32]` where `WarmingCreditSink` declares `Hash`, so `decdn-node` does not compile. Every downstream crate fails with it, and the whole workspace's clippy, test, doc, and doctest gates fail before they reach any other code. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Mfyosg52pVuL5t2XLwx1Vu
Withdraws item 7 part A and reworks the rest of the group where the review
found the change unsound, the documentation wrong, or the invariant only
asserted in prose.
Item 7 part A is withdrawn. The only wired `PoolView` is `PoolProjection`,
whose `status` is an `ArcSwap` load over an in-memory map, so the
`tokio::join!` overlapped a backend `HEAD` with a memory read and saved
nothing while making every declined request pay for a pool read it does not
use. The pool view is read after the origin-only gate again.
Correctness:
- `forget` drops the lane's capability row, and a drained key with no row
becomes a table DELETE in the same transaction. Registration material is
only ever asked for by `LaneKey`, and `forget_lane` runs only for a
reclaimed (Closed) pool, so the row is unreachable once its lane is gone.
Without this both the resident map and the table grew with the count of
distinct `(pool_id, signer)` pairs ever seen, and the signer half of that
pair is chosen by whoever funds the pool.
- `tune_lane_gauge` serializes the count read and the gauge publish. The
atomic fixes the count but not the publication order, so two concurrent
lane-lifecycle calls could leave `decdn_lanes_open` stuck on the staler
value until the next lifecycle event.
- `commit_snapshot` opens `CAPABILITY_TABLE` only when the snapshot carries
capability work, so a capability-side backend error cannot abort a commit
that carries only voucher watermarks.
- `resolve_cache_into` rejects `origin_probe_*` TTLs that break
`negative <= fault <= positive`. The ordering was stated in five doc
comments and enforced nowhere, so a long fault TTL could hide a recovered
origin — and keep refusing paying clients — for as long as an operator
set it.
Types carrying their own invariants:
- `ServeAudit` becomes `Serveable { size } | Unavailable { evicted }`. As
three public bools plus an `Option`, it could pair a wire size with a
refused blob (which `serve_audit` actually produced for an evicted blob),
and correctness rested on the caller's `if audit.present` guard.
- `MonotoneHashSet` holds the evicted set. Writers serialize, so the cap is
exact and `insert_if_absent` is linearizable, and the append-only contract
that makes the lock-free read sound is stated once instead of resting on
there happening to be one writer in a 9k-line file.
- `CapabilitySink::stage_capability` replaces `store_capability`: it names
what it does, and it is infallible, so the dead `Result` and its
unreachable "capability persist failed" warning are gone.
- `OriginProbePolicy` replaces four consecutive positional `Duration`
arguments on `OriginProbeMemo::new` and `set_origin_probe_config`, where
any transposition compiled and passed every test.
- `CapabilityVerifyCache` keeps recency in the value, so a hit is one hash
lookup rather than an `IndexMap` shift of up to 1023 entries under the
intake mutex.
Diagnostics:
- The capability drop log carries its cause again, and separates a
malformed signature (a client signing bug, `debug`) from a well-formed
one recovering to the wrong address (usually a transferred pool owner,
`warn`).
- A memoised origin fault warns once per hash per TTL, naming the window in
which this node refuses serves and answers probes with not-held. The memo
makes this strictly quieter than the per-request probe.
- A corrupt capability row names the signer as well as the pool; the pool
half alone does not identify the row that refuses the open.
- A failed flush reports how many lanes and how many capability rows are
left un-durable, and `flush_store_durable` no longer says "deferring
redeem" on the shutdown path that redeems anyway.
- `PoolStateStore::record` documents the non-blocking contract that calling
it inline on the open path now depends on.
Docs:
- `ServeAudit`, `ClientHandler` and `intake_capability` get their own doc
comments back; each had been left documenting a neighbour.
- The fault-TTL rationale is corrected in all five places. The memo is
keyed per hash, so it collapses one hash's repeats, not a namespace's
load: during an outage N distinct hashes still cost N live `HEAD`s per
window.
- `dht/publish.rs` no longer says faults are not memoised, and the size
gate no longer claims `has` just confirmed a blob present on the branch
reached only when it did not.
- Changelog voice removed throughout.
Tests:
- The concurrent-evict test runs eight writers over disjoint hashes and
asserts every one landed. With a single writer its assertion held under
any implementation, including one that loses updates outright, and a
starved reader made it assert nothing at all.
- The lane tests are multi-threaded, and a new one races sixteen
first-streams on ONE lane — the case the vacant-entry guard exists for.
- New coverage: a high-`s` capability dropped and cached `Invalid`; LRU
eviction order; `serve_audit` for a denied and for a zero-length blob; a
corrupt capability row refusing the open; capability GC across a reopen;
a flush carrying both lane and capability work; concurrent staging during
a flush; and the probe-TTL ordering accepting and rejecting.
- `capability_store_round_trips_and_missing_is_none` flushes and reopens,
so it tests the table again rather than the buffer in front of it.
- `flush_snapshot_sorts_into_table_key_order` observes the capability sort
it executes.
- The `..` added to the `CacheConfig` destructure is removed. All 32 fields
were still bound, so it only disabled the compile error that forces the
next cache knob into the `DEFAULT_CONFIG` template.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mfyosg52pVuL5t2XLwx1Vu
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.
Closes #1789 (Group B of the serve-path hot-path audit; siblings: #1788, #1787 doc drift). All items sit on the stream open path between
StreamRequestdecode and the firstChunkData, and are fixed together here.What
1. Buffer and dedup capability persistence
put_capabilityno longer awaits an inline redb fsync per request. Writes are staged into the working set and land in the same fsynced transaction as the lane frontier at the next flush, with the pre-redemptionflush_store_durableas the durability floor; repeat sends of an already-staged capability short-circuit the write. Rows are dropped when their lane is forgotten, so the table and the resident map do not grow with the count of distinct(pool_id, signer)pairs ever seen.2. Cache capability owner recovery
The capability owner ecrecover happens once per distinct
(signing_hash, signature)instead of per request; the recovered-owner comparison still runs per call, so an on-chain owner transfer takes effect immediately. Repeat sends skip ecrecover entirely.3 + 4. Atomic lane-count gauge and inline lane registration
refresh_lane_metrics's process-wide mutex plusDashMap::len()walk becomes an atomic counter bumped at register/forget.register_lane'sspawn_blocking(...).awaitround trip disappears — the store call is an in-memory buffered insert and is now called inline.5. Make the evicted set lock-free
engine.rsheld the last mutex inside the per-request deny check; its siblings (denied,chain_denied) were alreadyArcSwap. The evicted set moves behindMonotoneHashSet: anArcSwapread path with serialized writers, which is what makes the append-only contract the lock-free read depends on a property of the type rather than of there being one caller.6. Memoize origin-presence faults under a short TTL
Not-found results already got a negative TTL; faults did not, so a broken backend was re-probed on every request. Faults now get a distinct short TTL (
cache.origin_probe_fault_ttl_sec, default 5s), bounding repeat probes of the same hash under origin failure. The resolver rejects any TTL set that breaksnegative <= fault <= positive, since a long fault TTL keeps refusing paying clients after the origin recovers.7. Fold presence+size into one store contact
has+inspectare folded into a single store-actor call returningServeAudit, shaving a round trip off the pre-byte sequence on every cache hit.Not shipped: overlapping the presence probe with the pool-view read
An earlier revision of this PR ran the origin presence probe and the pool-view read on
tokio::join!(item 7 part A). It is withdrawn. The only wiredPoolViewisPoolProjection, whosestatusis anArcSwapload over an in-memory map — there is no RPC on that path and no latency to overlap, so the join saved nothing while making every declined request pay for a pool read it never uses.Notes
cache.origin_probe_fault_ttl_sec(restart-required, like itsorigin_probe_*siblings). No wire, postcard, ABI, or storage format changes.dispatch.rsdiff is largely re-indentation from amatch→ifconversion; behavior is preserved.crates/node/src/warming_allowance.rscarried a trait/impl signature mismatch from refactor(node): newtype warming source ids and hashes at the warming-allowance seam #1874 that stoppeddecdn-nodecompiling onmain. It is fixed in its own commit here so the rest of the branch can be built and tested at all.cargo clippy --workspace --all-targets,cargo fmt --check,cargo doc,cargo deny check,cargo test --doc, andcargo nextest run --workspace(3057 passing).