Skip to content

perf(node,cache): reduce TTFB on the cdn/client stream-open path (#1789) - #1871

Merged
thiras merged 10 commits into
mainfrom
perf/node-ttfb-open-path-1789
Aug 30, 2026
Merged

thiras merged 10 commits into
mainfrom
perf/node-ttfb-open-path-1789

Conversation

@thiras

@thiras thiras commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

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 StreamRequest decode and the first ChunkData, and are fixed together here.

What

1. Buffer and dedup capability persistence

put_capability no 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-redemption flush_store_durable as 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 plus DashMap::len() walk becomes an atomic counter bumped at register/forget. register_lane's spawn_blocking(...).await round trip disappears — the store call is an in-memory buffered insert and is now called inline.

5. Make the evicted set lock-free

engine.rs held the last mutex inside the per-request deny check; its siblings (denied, chain_denied) were already ArcSwap. The evicted set moves behind MonotoneHashSet: an ArcSwap read 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 breaks negative <= fault <= positive, since a long fault TTL keeps refusing paying clients after the origin recovers.

7. Fold presence+size into one store contact

has+inspect are folded into a single store-actor call returning ServeAudit, 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 wired PoolView is PoolProjection, whose status is an ArcSwap load 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

  • New config knob cache.origin_probe_fault_ttl_sec (restart-required, like its origin_probe_* siblings). No wire, postcard, ABI, or storage format changes.
  • The dispatch.rs diff is largely re-indentation from a match→if conversion; behavior is preserved.
  • crates/node/src/warming_allowance.rs carried a trait/impl signature mismatch from refactor(node): newtype warming source ids and hashes at the warming-allowance seam #1874 that stopped decdn-node compiling on main. It is fixed in its own commit here so the rest of the branch can be built and tested at all.
  • Verified with cargo clippy --workspace --all-targets, cargo fmt --check, cargo doc, cargo deny check, cargo test --doc, and cargo nextest run --workspace (3057 passing).

Copilot AI lite review requested due to automatic review settings August 30, 2026 03:23

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 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; evicted via ArcSwap), and add serve_audit to fold store presence+size into one call.
  • Memoize origin-probe faults under a new origin_probe_fault_ttl_sec config 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.

Comment thread crates/node/src/handlers/client/mod.rs Resolved
@github-actions

github-actions Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 82.27% (was 82.11%, ▲ +0.16%) — 69251/84173 lines

File Coverage Lines Δ
crates/cache/src/engine.rs 92.31% 4513/4889 ▲ +0.09%
crates/cache/src/lib.rs 100.00% 28/28 ● 0.00%
crates/cache/src/origin_probe.rs 98.57% 207/210 ▼ 1.43%
crates/cli/src/commands/config.rs 87.00% 776/892 ▲ +0.07%
crates/common/src/config/mod.rs 97.10% 6891/7097 ▲ +0.02%
crates/common/src/config/resolved.rs 100.00% 42/42 ● 0.00%
crates/incentive/src/store.rs 92.45% 245/265 ● 0.00%
crates/node/src/channel_store.rs 87.84% 1668/1899 ▲ +1.65%
crates/node/src/dht/publish.rs 91.41% 1032/1129 ● 0.00%
crates/node/src/handlers/client/dispatch.rs 85.93% 464/540 ▲ +0.16%
crates/node/src/handlers/client/mod.rs 93.81% 1865/1988 ▲ +1.07%
crates/node/src/payment_settlement.rs 51.49% 621/1206 ▼ 0.26%
crates/node/src/runtime/mod.rs 47.79% 1158/2423 ▲ +0.09%
crates/node/src/runtime/reload.rs 96.55% 1540/1595 ▲ +0.01%
crates/node/src/warming_allowance.rs 98.17% 322/328 ▲ +0.14%
History
Commit Total Δ vs base
b3af664 82.18% ▲ +0.10%
9f761ee 82.17% ▲ +0.09%
f33f069 (HEAD) 82.27% ▲ +0.16%

thiras added 8 commits August 30, 2026 21:35
#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
thiras force-pushed the perf/node-ttfb-open-path-1789 branch from 9f761ee to 064dd7c Compare August 30, 2026 18:40
thiras and others added 2 commits August 30, 2026 22:40
`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
@thiras
thiras merged commit 06b29d6 into main Aug 30, 2026
48 of 50 checks passed
@thiras
thiras deleted the perf/node-ttfb-open-path-1789 branch August 30, 2026 20:07
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.

perf(node): TTFB — stream open pays 3 secp256k1 ops, an inline redb fsync, and a global metrics refresh before first byte

2 participants