Repository navigation
perf(node,cache): shard stream-end bookkeeping off global mutexes - #1803
Conversation
Three per-serve-completion touches on process-wide mutexes that background scans hold for O(N), so completion latency tracked cache size and warming policy activity. - `access_times` becomes a `DashMap`. `record_access` is one shard touch; `eviction_candidates` and `access_times_snapshot` walk shard by shard instead of holding one guard across the whole map. The filter ordering in `eviction_candidates` (held before the deny carve-out) is unchanged, and the poison-recovery split the map used to carry disappears with the mutex. - The TinyLFU count-min sketch becomes `ShardedCountMinSketch`: 16 independently locked pieces routed by a key slice the row indices do not read. Total counter budget, per-row collision rate, and aging window are all held constant, so no admission or eviction decision moves; the halving now ages one shard at a time instead of the whole array under one lock. `ProbationAdmission::admit` no longer shares a lock with the serve path. - The warming serve credit goes over a bounded channel to a background aggregator, mirroring the receipt sink: `WarmingCreditSink`, a channel impl for the runtime, and an inline `DirectWarmingCreditSink` for tests. The stream task no longer waits on the ledger lock the buy loop and the eviction driver hold. Two contention tests pin the contract: a completion record must land while a scan holds another shard, and a serve credit must land while the ledger is held. Both time out against the pre-change single-lock forms. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Coverage reportTotal: 82.08% (was 82.00%, ▲ +0.08%) — 68889/83925 lines
History
|
There was a problem hiding this comment.
Pull request overview
This PR implements Group F of the serve-path hot-path audit (#1793), removing the three process-wide mutex touches that occur once per completed serve and that background scans hold for O(N). Each terminal-bookkeeping step is sharded or offloaded so a stream completion no longer contends with cache-size-dependent scans, keeping completion latency independent of cached-blob count and traffic. This fits the project's scaling goal where the busiest, fullest nodes are exactly where these per-serve global-lock touches hurt most.
Changes:
- Convert the cache engine's
access_timesLRU map fromMutex<HashMap>toDashMap, sorecord_accessis a single shard touch and the eviction/snapshot scans walk shard-by-shard. - Shard the TinyLFU count-min sketch into 16 independently locked sub-sketches (
ShardedCountMinSketch), preserving total budget, collision rate, and aging cadence while removing the process-wide sketch mutex. - Move warming serve-credit behind a non-blocking
WarmingCreditSinkseam (channel-backed background aggregator in production, inlineDirectWarmingCreditSinkfor tests), mirroring theReceiptSinkpattern.
Reviewed changes
Copilot reviewed 9 out of 10 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
crates/cache/src/engine.rs |
access_times → DashMap; scans/record/evict paths and poison/inspect docs updated; adds a shard-contention test |
crates/cache/src/policy/sketch.rs |
Adds ShardedCountMinSketch + word_at helper and shard-routing constants; new sharded-sketch tests |
crates/cache/src/policy/tinylfu.rs |
TinyLfuEstimator uses the sharded sketch; drops the outer Mutex/PoisonError |
crates/cache/Cargo.toml, Cargo.lock |
Adds dashmap (already a workspace dep) to the cache crate |
crates/node/src/warming_allowance.rs |
Adds WarmingCreditSink trait, channel/direct impls, spawn_warming_creditor aggregator, and tests |
crates/node/src/handlers/client/mod.rs |
ClientHandlerDeps/ClientHandler hold warming_credit sink; credit_warming_serve enqueues instead of locking the ledger |
crates/node/src/runtime/mod.rs |
Wires the production channel sink via spawn_warming_creditor over the shared allowance |
crates/node/tests/*.rs |
Updates test wiring to inject DirectWarmingCreditSink |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
… credits Review of #1803 found two correctness changes the PR described as behaviour-preserving, plus the receipt-sink safety features its warming aggregator was missing. - The sharded sketch clocked halving per shard, so each shard aged at a rate set by its own traffic. Both readers compare estimates on one scale — `ProbationAdmission` against a node-wide threshold, `TinyLfuEviction` by ranking candidates from different shards — so counters from shards at different aging phases stopped being comparable. Under a skewed load that inverted 44% of ranked pairs against a single wide sketch, evicting hotter blobs than it kept. `CountMinSketch` now carries no clock of its own; `ShardedCountMinSketch` owns one node-wide observation counter and each shard halves lazily by the windows elapsed since it last caught up. Halving work stays sharded, the cadence is global. - The equivalence test could not fail: `Hash::from([b; 32])` makes the shard word and all four row words the same `u32`, so shard and column choice are correlated, every row indexes one column, and neither halving nor collisions occur. It compared two exact counters. Sharded tests move to full-entropy keys and drive a skewed load past several aging windows; the pair of them reports 199/200 keys diverged and 31% of ranked pairs inverted against the per-shard clock. - `ChannelWarmingCreditSink` resolved `source_of[hash]` at apply time, so an eviction and a re-warm between enqueue and drain redirected the credit to the new source. The tags move out of the bucket mutex into a `DashMap`, the sink resolves the source itself and enqueues `(source, units)`, and the ledger's poison paths recover instead of failing closed. - `spawn_warming_creditor` now matches `spawn_receipt_writer`: it takes `Arc<Metrics>` and a `CancellationToken`, returns its `JoinHandle`, counts every dropped credit in `decdn_warming_credits_dropped_total`, and warns once on a closed queue. Shutdown cancels it after the router drains, awaits the flush, and aborts it if the deadline overruns. The remaining fixes are documentation that no longer matched the code: three sites claiming the client handler shares the allowance `Arc`, the trait doc asserting an O(N) ledger hold that no method performs, and the snapshot doc calling a shard-by-shard walk point-in-time. ADR 040 gains the sharding and aging-clock paragraphs. New coverage: the aggregator's `Full`, `Closed`, untagged and shutdown-flush paths; the forget/re-tag ordering; one end-to-end paid fetch through the real channel sink (it fails if the runtime wiring is dropped); a sketch contention test; the `cols <= SHARDS` degenerate shape; and that a concurrent record never makes the eviction sweep lose a pre-existing candidate. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Contracts coverageLine coverage: 89.69% (2575/2871 lines) |
Gas snapshotNo gas changes vs base. |
thiras
left a comment
There was a problem hiding this comment.
Review of the sharding changes (DashMap access_times, sharded TinyLFU sketch, background warming-credit aggregator). The key correctness claims check out: DashMap's iter holds each shard's read guard during that shard's traversal (so a_scan_never_loses_a_candidate_to_a_concurrent_record is sound), the shard-routing slice (bytes 16..20) is disjoint from the four row slices (bytes 0..16), and the global aging clock with lazy per-shard catch-up is internally consistent. One minor behavioral change worth noting below.
thiras
left a comment
There was a problem hiding this comment.
Review of the sharding changes (DashMap access_times, sharded TinyLFU sketch, background warming-credit aggregator). The key correctness claims check out: DashMap's iter holds each shard's read guard during that shard's traversal (so a_scan_never_loses_a_candidate_to_a_concurrent_record is sound), the shard-routing slice (bytes 16..20) is disjoint from the four row slices (bytes 0..16), and the global aging clock with lazy per-shard catch-up is internally consistent. One minor behavioral change worth noting below.
| .saturating_sub(units) | ||
| .max(self.budget.saturating_neg()); | ||
| } | ||
| self.source_of.insert(hash, source); |
There was a problem hiding this comment.
(Low) The source_of tag insert moved outside the bucket lock.
Previously debit_speculative inserted the hash→source tag under the same state lock as the debit, so credit_serve (which read the tag under that lock) could never observe a debit without its tag. Now the tag is written to the DashMap after the lock is released (line 145), opening a window where the debit is committed but source_for(hash) still returns None, so a concurrent credit_serve would drop the credit.
The consequence is conservative — the source stays more negative than reality, and the time refill forgives it — and the window is between the buy-loop debit and the tag insert, microseconds, well before any serve of that hash can complete. So this is not a realistic failure, but it is a genuine loss of the atomicity the original had. If you want to preserve it, insert the tag before releasing the lock (or accept the window and note it).
There was a problem hiding this comment.
Fixed in 6306712 — with one change to the proposed remedy.
Confirmed the regression: on main, source_of lived inside State, so the debit and the tag were published under one critical section and credit_serve read the tag under that same lock.
Inserting the tag before releasing the lock would not restore that, though: source_for is now a lock-free DashMap read and takes no part in the state mutex, so holding the lock across the insert only shortens the window rather than closing it.
What does close it is ordering the tag first:
self.source_of.insert(hash, source);
let mut state = self.state.lock()...;
// debit
The two writes still are not one atomic step, but this makes the only observable interleaving the harmless one — a serve that resolves the tag between them sees the source and credits it, which is what the accounting wants. The dropped-credit interleaving you identified is gone. Comment on debit_speculative spells out the ordering and why.
debit_speculative writes the hash-to-source tag and the bucket debit under two different locks. Ordering the tag first makes the only observable interleaving the harmless one: a serve that resolves the tag in between sees the source and credits it. The reverse order lets a serve see a committed debit with no tag yet and drop its credit. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
#1803 review) Eight doc sites justified the warming-credit seam by claiming the eviction driver contends on the bucket ledger. It does not: eviction's only contact with the allowance is `forget`, which touches the tag map alone. The lock is taken by the buy loop and by the aggregator, and the seam's purpose is that a serve's last step must not wait on it while the stream still holds its lane slot and floor reservation. One of those sites also claimed whole-pass holds, which the module's own "nothing iterates under the lock" contradicts. Two more described the DashMap tag map as lock-free; it is sharded RwLocks. Two aging claims promised more than the code delivers. An estimator loads the clock before taking the shard lock, so the epoch it applies is stale by whatever lands in between — it under-ages, never over-ages, and nothing bounds that gap in principle. A ranking pass carries one halving of skew per window boundary it crosses, not one in total, and candidates read on opposite sides of a boundary can misorder when their estimates are within a factor of two. ADR 040 claimed such a halving cannot reorder blobs of different true frequency; it can. `cache.tinylfu.sketch_bytes` was resolved with no floor while the estimator clamped it silently to 64 columns — four per shard. It is rejected at load now, at a floor derived from an over-report target rather than a round per-shard number, and ADR 040 records both the floor and that the block is validated whatever the policy selectors say. The sketch's row stride was a bare literal in four places, untied to the shard slice offset, so moving it could put a row index on the shard slice with every test still green. A SLICE_BYTES constant ties them; setting it to 8 is now a build failure. `source_for` and `credit_source` were public, which let any caller vindicate a source with no serve behind it. `credit_serve` resolves and applies in one step, which is what the shipped path must not do, so it carries the test-support gate of its only callers. Tests: a shard idle across many aging windows was never exercised, so catching up by a single halving passed the whole suite; exact assertions at one, two and eight windows reject that and the off-by-one. The eviction-scan test's overlap witness was satisfied by a record that landed before the walk, and cross-round residue made its retry decorative; it now accepts only keys written inside the walk. Also pins that every credit into a closed queue counts, not just the one that warns. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
#1803 review) Eight doc sites justified the warming-credit seam by claiming the eviction driver contends on the bucket ledger. It does not: eviction's only contact with the allowance is `forget`, which touches the tag map alone. The lock is taken by the buy loop and by the aggregator, and the seam's purpose is that a serve's last step must not wait on it while the stream still holds its lane slot and floor reservation. One of those sites also claimed whole-pass holds, which the module's own "nothing iterates under the lock" contradicts. Two more described the DashMap tag map as lock-free; it is sharded RwLocks. Two aging claims promised more than the code delivers. An estimator loads the clock before taking the shard lock, so the epoch it applies is stale by whatever lands in between — it under-ages, never over-ages, and nothing bounds that gap in principle. A ranking pass carries one halving of skew per window boundary it crosses, not one in total, and candidates read on opposite sides of a boundary can misorder when their estimates are within a factor of two. ADR 040 claimed such a halving cannot reorder blobs of different true frequency; it can. `cache.tinylfu.sketch_bytes` was resolved with no floor while the estimator clamped it silently to 64 columns — four per shard. It is rejected at load now, at a floor derived from an over-report target rather than a round per-shard number, and ADR 040 records both the floor and that the block is validated whatever the policy selectors say. The sketch's row stride was a bare literal in four places, untied to the shard slice offset, so moving it could put a row index on the shard slice with every test still green. A SLICE_BYTES constant ties them; setting it to 8 is now a build failure. `source_for` and `credit_source` were public, which let any caller vindicate a source with no serve behind it. `credit_serve` resolves and applies in one step, which is what the shipped path must not do, so it carries the test-support gate of its only callers. Tests: a shard idle across many aging windows was never exercised, so catching up by a single halving passed the whole suite; exact assertions at one, two and eight windows reject that and the off-by-one. The eviction-scan test's overlap witness was satisfied by a record that landed before the walk, and cross-round residue made its retry decorative; it now accepts only keys written inside the walk. Also pins that every credit into a closed queue counts, not just the one that warns. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…1803 review) (#1855) * fix(node,cache): correct the warming-seam docs, guard the sketch floor (#1803 review) Eight doc sites justified the warming-credit seam by claiming the eviction driver contends on the bucket ledger. It does not: eviction's only contact with the allowance is `forget`, which touches the tag map alone. The lock is taken by the buy loop and by the aggregator, and the seam's purpose is that a serve's last step must not wait on it while the stream still holds its lane slot and floor reservation. One of those sites also claimed whole-pass holds, which the module's own "nothing iterates under the lock" contradicts. Two more described the DashMap tag map as lock-free; it is sharded RwLocks. Two aging claims promised more than the code delivers. An estimator loads the clock before taking the shard lock, so the epoch it applies is stale by whatever lands in between — it under-ages, never over-ages, and nothing bounds that gap in principle. A ranking pass carries one halving of skew per window boundary it crosses, not one in total, and candidates read on opposite sides of a boundary can misorder when their estimates are within a factor of two. ADR 040 claimed such a halving cannot reorder blobs of different true frequency; it can. `cache.tinylfu.sketch_bytes` was resolved with no floor while the estimator clamped it silently to 64 columns — four per shard. It is rejected at load now, at a floor derived from an over-report target rather than a round per-shard number, and ADR 040 records both the floor and that the block is validated whatever the policy selectors say. The sketch's row stride was a bare literal in four places, untied to the shard slice offset, so moving it could put a row index on the shard slice with every test still green. A SLICE_BYTES constant ties them; setting it to 8 is now a build failure. `source_for` and `credit_source` were public, which let any caller vindicate a source with no serve behind it. `credit_serve` resolves and applies in one step, which is what the shipped path must not do, so it carries the test-support gate of its only callers. Tests: a shard idle across many aging windows was never exercised, so catching up by a single halving passed the whole suite; exact assertions at one, two and eight windows reject that and the off-by-one. The eviction-scan test's overlap witness was satisfied by a record that landed before the walk, and cross-round residue made its retry decorative; it now accepts only keys written inside the walk. Also pins that every credit into a closed queue counts, not just the one that warns. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(cache,node): correct the sketch collision math, close the deps-wiring class Review response on #1855. Three defects in the branch's own content, plus the structural gap its docstring admitted. The `sketch_bytes` floor rationale proved the wrong proposition. It claimed a sketch over-reports "only when another blob collides with it in every row" — sufficient, not necessary. Over-report needs every row polluted by some key, and the polluting keys need not be the same one across rows. The arithmetic that followed was internally correct and answered a question nobody asked: `1.5e-11` per pair is the all-rows twin-collision rate, while the real rate at that width and 10000 blobs is ~69%. Replaced with `(1 - e^(-N / cols))^4`, checked against simulation at four operating points. Two conclusions invert: sharding cancels out of the expression rather than inflating it by `SHARDS^(ROWS-1)`, and width scales linearly with the blob count rather than as its fourth root. The floor holds ~1500 blobs under a 1% over-report rate and the default ~25000, replacing the "10000 blobs, fewer than 1e-3 false-hot pairs" claim and the "100000 blobs wants the default" recommendation. `[cache.tinylfu]` is not inert when no selector names `tinylfu`. The default `cache.serve_economics.policy = "margin"` builds the same estimator, so `sketch_bytes` sizes a live sketch on a node running `lru`/`always`, and ADR 041 reads it for the heat input to its price gate. Six sites said otherwise, one of them a line this branch edited. The unconditional validation now rests on that fact rather than on a hypothetical later selector switch. `a_scan_never_loses_a_candidate_to_a_concurrent_record` reused one key range across all 16 rounds, and nothing evicts a round's keys from `access_times`. From round two the witness matched keys that were already present before the walk began, so a run where the walk never overlapped the writer still reported success. Each round now owns a `ROUND_STRIDE`-wide range, asserted wide enough for its writes, and the witness skips the one index that may predate the walk. `build_chain_and_handlers` claimed a single deps literal (#1254) while the code had drifted to `new()` plus fifteen setters, so dropping a wiring line left a live node on the inert default. Restored the exhaustive 33-field literal: a dropped `warming_credit` or `operator_shares` is now a missing-field compile error. `decdn_warming_credits_applied_total` covers the runtime half — an unwired sink enqueues nothing and so drops nothing, which made a zero drop count unreadable on its own. Also: CHANGELOG entry for the config-breaking floor; both warming-credit counters registered in appendix-observability; the rejected-design counterfactual at `warming_allowance.rs` stated in the subjunctive; `credit_warming_serve`'s cost documented per sink rather than unconditionally; the older sketch test's stale window copy read off the sketch. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_014Chu2v9AUcfr36pUVRLwwx --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: Ant Somers <[email protected]>
Group F of the serve-path hot-path audit: the three per-completed-serve touches on process-wide mutexes that background scans hold for O(N). Each is fixed with the primary approach the issue names.
1.
access_times→DashMapcrates/cache/src/engine.rs.record_access(the terminal bookkeeping of every completed serve, viaobserve_hit) is now one shard touch.eviction_candidatesandaccess_times_snapshotwalk shard by shard instead of holding one guard across the whole map, so a completion contends only when it lands on the shard a scan is inside at that moment.heldstill short-circuits before the deny carve-out, in that order, with its comment intact.access_times' mixed handling "a gap, not a design", and theinspectdoc that listed it as aMutex<HashMap>, are updated to describe what is there now.dashmapis added tocrates/cache(already a workspace dependency and already used bycrates/node;cargo deny checkis clean).2. Sharded TinyLFU sketch
crates/cache/src/policy/sketch.rs,tinylfu.rs.ShardedCountMinSketchsplits the counter array into 16 independently lockedCountMinSketches, routed by the 4-byte key slice at offset 16 — past the 16 bytes the row indices consume, so shard choice and column choice are independent functions of a uniform hash. Halving is per shard: it ages 1/16 of the counters under one shard's lock.TinyLfuEstimatorholds no outer mutex, soProbationAdmission::admitno longer shares one with the serve path.Nothing observable moves. Total counter budget is preserved (per-shard width rounds up), the per-row collision rate stays
1 / cols(same shard and same column within it), and each shard's aging window is its own width x 10, which with keys spread evenly is the single sketch'scols * 10node-wide. The shard count is a pure concurrency knob — no new tuning constant changes policy.3. Warming credit → background aggregator
crates/node/src/warming_allowance.rs. Copies the receipt-sink pattern: aWarmingCreditSinktrait, a bounded-channel impl behindspawn_warming_creditor, and an inlineDirectWarmingCreditSink(#[doc(hidden)]) that tests and loopback use to keep the credit synchronously observable. The handler holds the sink instead of the ledger, so a serve's final step is onetry_sendand never waits behind the buy loop or the eviction driver.A
Fullqueue drops the credit and logs it; the drop is conservative — an un-applied credit leaves the source's ledger more negative than reality, and the time refill forgives that. The aggregator ends when the last sink drops (router teardown), so it needs no separate stop signal: the allowance is in-memory bookkeeping a restart rebuilds anyway.Call sites checked:
handlers/client/delivery.rsandhandlers/client/serve_leg.rsboth reach the new path throughcredit_warming_serve;observe_hitis unchanged at both.Tests
Behaviour-preserving (pass before and after):
sharded_estimates_match_the_single_sketchasserts the sharded sketch reports exactly what one wide sketch of the same total width reports for the same load;sharded_estimate_rises_with_increments,sharded_aging_bounds_counters,shards_hold_disjoint_keys,channel_sink_credits_through_the_background_aggregator, plus every existing eviction-candidate and TinyLFU plan test untouched.Contention contract (fails before, passes after) — both use a held lock plus a bounded wait on another thread, so the failure is a timeout rather than a timing race:
record_access_does_not_wait_on_a_scan_of_another_shard— pins a scan inside one shard and records a completion for a hash elsewhere. AgainstMutex<HashMap>(where the scan's guard is the whole map's guard) it fails:Error: a serve completion's access record waited on a scan of another shardafter 10s. It passes on the sharded map in 0.11s.credit_does_not_wait_on_the_ledger_lock— holds the ledger the way a buy-loop pass does and credits a serve. With the inline sink (the pre-change path) it fails after 10s; with the channel sink it passes in 0.03s.Gates
cargo fmt -- --checkcleancargo clippy --workspace --all-targets -- -D warningsclean (also--all-features)cargo nextest run -p decdn-cache -p decdn-node --no-fail-fast— 1373 passed, 0 failed (full workspace: 2966 passed)cargo deny check— advisories ok, bans ok, licenses ok, sources okcargo doc --workspace --no-depscleanCloses #1793
🤖 Generated with Claude Code