Repository navigation
fix(node,cache): correct the sharding docs, guard the sketch floor (#1803 review) - #1855
Conversation
Coverage reportTotal: 82.56% (was 82.55%, ● 0.00%) — 70516/85416 lines
History
|
A self-review of the correction patch found it had introduced four claims of the same kind it was fixing. The eviction-driver rewrite missed a site. runtime/mod.rs, where the seam is wired and the first place a reader looks, still said the buy loop and the eviction path both take the bucket lock. ADR 040 said one halving does not reorder blobs of different true frequency. It does: a candidate read before a window boundary and one read after can swap whenever their estimates are within a factor of two, which is the normal operating range for saturating byte counters. The ADR now states what holds — an evenly applied halving only creates ties, and a boundary crossed mid-pass can misorder adjacent candidates until the next sweep. The sketch's new build-time guard asserted `SHARD_SLICE_START >= ROWS * 4` against a constant defined as `ROWS * 4`, so it could never fire, and the comment above it promised protection the definition already provided. The row stride was still a bare literal in four places, and moving it — not ROWS — was what could put a row index on the shard slice with every test green. A SLICE_BYTES constant closes that; setting it to 8 is now a build failure. The poisoning note listed `forget` among the paths that take the ledger lock, contradicting the module doc sixty lines above it. Both new tests proved less than they claimed. The scan test's overlap witness was satisfied by a record that landed before the walk began, and cross-round residue made the retry loop decorative; it now accepts only keys written inside the walk, and fails when the writer is stubbed out. The catch-up test passed against `halve(elapsed - 1)`; exact assertions at one, two, and eight windows reject that and `halve(1)`. The sketch_bytes floor keeps its value but drops its reasoning, which had the collision argument backwards — sharding leaves the per-row rate at 1/cols and inflates the whole-sketch rate. 16384 now follows from an over-report target, and ADR 040 records both the floor and that the block is validated whatever the policy selectors say. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Pushed The corrections that were themselves wrongThe eviction-driver rewrite missed a site. ADR 040 stated a false safety property. "one halving does not reorder blobs of different true frequency" — it does. Candidate X (true 7) read before a window boundary reads 7; Y (true 10) read after reads 5, so Y ranks colder and is evicted first though it is hotter. Any pair within a factor of two can invert, and on saturating byte counters with The new build-time guard was a tautology. The same hunk changed The poisoning note contradicted the module doc added in the same commit. It listed Both new tests proved less than they claimedThe scan test's concurrency witness was vacuous, twice over. The catch-up test passed against The floor keeps its value, loses its reasoningThe doc said "the per-shard width — not the total width — is what governs the collision rate". Also: two fabricated Gate: |
f3736fc to
974a6c8
Compare
|
Rebased onto Why it conflicted: How it was resolved. The two commits were squashed to one (content-identical), then rebased. Nine of the twelve files merged clean and carried the bulk of the value — the sketch Re-verified the premise against
The false claims survived on Dropped from this PR: my One change forced by the rebase: narrowing All four injected-bug proofs re-run green after the rebase: Gate: |
…ring 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
#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]>
…ring 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
ce66117 to
5b80b4f
Compare
Post-merge follow-up to #1803. A five-agent review of the merged diff found no correctness bug in the sharding itself — routing, epoch monotonicity, DashMap guard semantics, lock ordering, and aggregator shutdown all check out. What it did find was docs that promise more than the code delivers, one unvalidated config knob, one encapsulation regression, and a test gap that let a real bug through.
Docs that were wrong
Five sites justified the warming-credit seam by claiming the eviction driver contends on
WarmingAllowance::state. It does not. Eviction's only contact with the allowance isforget(), and #1803 moved that onto thesource_ofDashMap. Verified across all three eviction callers —blacklist_watcher.rs:974,admin.rs:533,runtime/eviction.rs:179— each callsforget()and nothing else.state.lock()is taken by exactly two things: the buy loop (available+debit_speculativeon the cache-miss path) and the aggregator (credit_source). The seam's actual purpose is that a serve completion's last step must not wait on that lock while the stream still holds its lane slot and floor reservation. The docs say that now.One test doc also claimed those callers hold the lock "for whole passes of their own bookkeeping", contradicting the module's own "every operation on it is O(1) — nothing iterates under the lock". Reconciled.
Two overclaims about the aging clock, both bounded and conservative, now stated as bounds rather than guarantees:
estimateloadsobservationsbefore taking the shard lock, so it can catch a shard up to an epoch one window stale. It under-ages by at most one halving and never over-ages.TinyLfuEviction::planreads each candidate separately, so a pass crossing a window boundary spans one halving.Also: four CLAUDE.md present-tense-canon violations; ADR 041 still described serve credits as unconditional after they became lossy; two operator-facing docs (one shipping in
decdn configoutput) described thesample/sample_maxreset this PR's parent deleted.Config floor
cache.tinylfu.sketch_bytesresolved with nobag.check_withwhilepromotion_thresholdtwelve lines below carries "Reject it at load, never clamp".TinyLfuEstimator::newthen clamped silently to 64 columns — over 16 shards that is four columns per shard, a width at which the estimates stop separating blobs at all. Rejected at load now, with a floor of 16384 bytes; the 64-column clamp reads as the backstop it is.Encapsulation
credit_sourceandsource_forwerepub, so any caller could vindicate an arbitrary source with no serve behind it — bypassing the ADR 041 grief cap that was type-owned before the deferred sink split the two halves. Both have in-module callers only, so droppingpubcosts nothing.ClientHandlerDeps::newalso defaultedwarming_credittoDirectWarmingCreditSink, the type whose docs say it must never be wired onto the serve path. NowNoopWarmingCreditSink.Tests
The real one:
catch_upwas never called withelapsed >= 2.aging_is_driven_by_node_wide_traffic_not_the_shard_s_owndrives exactly one window (640 observations) and asserts onlyestimate < before; the equivalence tests keep every shard busy. Replacinghalve(elapsed)withhalve(1)passed the entire suite. In production that is a node with low key cardinality leaving most shards idle across epochs, so a blob routing into a long-cold shard reads counters that should have drained — a cold key outranking a warm one, silently. The new test brackets it: one window must leave the counter non-zero, eight must drain it. Verified it fails against the injected bug before wiring the assertion.a_scan_never_loses_a_candidate_to_a_concurrent_recordspawned a writer then scanned ~512 entries immediately — microseconds of work against a thread spawn, so it usually finished before the writer ran. It now waits for the writer and requires a round whose result carries writer-produced hashes.Plus: every credit into a closed queue must count, not just the one that warns (moving the metric inside the
closed_loggedlatch would cap the counter at one); and the untagged-hash test asserts an empty ledger rather than relying on a drop counter that reads zero either way.Filed separately (pre-existing)
#1851
[u8; 32]for both hashes and source ids · #1852 gateDirect*Sinkbehind a test-support feature · #1853 pair shutdown token with its JoinHandle · #1854 degenerate[b; 32]keys in the tinylfu testsVerification
cargo fmt --check,cargo clippy --workspace --all-targets -- -D warnings,cargo doc --workspace --no-depsall clean.cargo nextest run --workspace --no-fail-fast: 3070 passed.Review round 2 (
ce66117e)A review of the first commit found three defects in its own content, plus the structural gap its docstring admitted. All fixed here.
The floor rationale proved the wrong proposition
The commit justified the 16384-byte floor with: "the sketch reports a blob hotter than it is only when another blob collides with it in every row." That is sufficient, not necessary. A count-min sketch over-reports when every row carries mass from some other key — the polluting keys need not be the same one across rows. The arithmetic that followed (
SHARDS^(ROWS-1) / cols^ROWS=1.5e-11per pair;C(10000,2)of them under1e-3) was internally correct and answered a question nobody asked.The real rate is
(1 - e^(-N / cols))^4, confirmed by simulation at four operating points:Two conclusions invert. Sharding cancels out — a shard divides the columns and the keys in the same proportion — rather than inflating the rate by
SHARDS^(ROWS-1); simulated at SHARDS ∈ {1, 4, 16, 64}, all ≈1 %. And width scales linearly with the blob count, not as its fourth root:0.38 * colslive blobs holds the rate under 1 %, so the floor is good for ~1,500 and the default for ~25,000. Corrected in ADR 040, theMIN_TINYLFU_SKETCH_BYTESdoc, and the pre-existing module-doc source atsketch.rsthe text was inherited from.[cache.tinylfu]is not inert on a default nodeSix sites — including a line the first commit edited — said the block is unused unless a selector names
tinylfu. Butwant_estimatoralso fires oncache.serve_economics.policy == "margin", which is the default, andheat_offeeds that estimate into ADR 041's price gate. Sosketch_bytessizes a live sketch that gates real spending on a node runninglru/always. The unconditional validation now rests on that fact rather than on a hypothetical later selector switch, which also makes it a much stronger argument.The reworked concurrency test's witness was vacuous
a_scan_never_loses_a_candidate_to_a_concurrent_recordreused oneWRITER_BASEacross all 16 rounds, and nothing evicts a round's keys fromaccess_times. From round two theduringset matched keys already present before the walk began, so a run where the walk never overlapped the writer still reported success — degrading the retry loop to a one-shot exactly when it was needed. Each round now owns aROUND_STRIDE-wide range, asserted wide enough for its own writes, and the witness skips the one index that may predate the walk (the writer inserts, then bumps its counter).Closed the wiring class, not just the instance
runtime/mod.rsalready claimed "a single deps literal (#1254)" while the code had drifted toClientHandlerDeps::new()plus fifteen setter assignments — so the coverage gap the first commit documented forwarming_creditwas one of fourteen identical silent-degradation sites (operator_sharessilently → zero share is the same shape). Restored the exhaustive 33-field literal: dropping a wiring line is now a missing-field compile error rather than a live node quietly running the inert default.decdn_warming_credits_applied_totalcovers the runtime half. An unwired sink enqueues nothing and therefore drops nothing, which is precisely why the first commit's docstring had to say "with the drop counter still reading zero" — the two counters now read together tell "no credits lost" apart from "no credits at all". Both are registered inappendix-observability.md.Also
CHANGELOG.mdentry for the config-breaking floor (naming the field and its selector-independence); the rejected-design counterfactual inwarming_allowance.rsstated in the subjunctive rather than the indicative;credit_warming_serve's cost documented per wired sink rather than as an unconditional guarantee; the older sketch test's stalewindowcopy now read off the sketch, which is the very hazard the new test's own comment warns about.Verification
cargo fmt --check,cargo clippy --workspace --all-targets,cargo doc --workspace --no-deps --document-private-itemswith-D warnings, andpre-commit run --all-filesall clean.cargo nextest runacrossdecdn-node,decdn-cache,decdn-common,decdn-cli: 2327 passed, 0 failed. The reworked concurrency test stressed 20× post-change. The corrected probability model was validated against a Monte-Carlo simulation before the docs were rewritten.🤖 Generated with Claude Code