Repository navigation
Prefix cache: fix the hit-rate collapse (epoch churn, demand-gated writes, 1,024-token checkpoints, credit band, bounded fence, index sizing, sidecar parity) - #1207
Conversation
Production measurement of exact prefix-cache routing: 1.4–5.2% per-model hit rates with routing on at 100%, the opportunity funnel, holder lifecycle, donation economics, checkpoint geometry against prompt-length distribution, and ranked levers. Notes that the 10,000-entry demand index turns over in about a minute, so observed repeats are within-minute repeats.
…ples Adds the operator procedure for the post-fix activation: sidecar concurrency and memory before the plan QPS cap, then the coordinator holder TTL, then the two new allowlist tuples (derived with promptcontract.ContractID from the active registry versions; the same derivation reproduces the live gpt-oss tuple). Seeds new hosts with sidecar concurrency 16 and 2048 MiB.
Production (7 days, docs/reports/2026-09-26-prefix-cache-hit-rate-analysis.md) shows 3.04M gpt-oss and 1.42M Gemma routing evaluations with a valid, positively-credited cache holder that routed elsewhere (opportunity reason=holder_not_selected), against 118k/107k selected, while a selected holder hit 99.9% of the time. cacheServiceCost credits at most the request's prefill; queue/pending/backlog penalties stay intact, and any cache adjustment in the pool collapsed nearTieCostWindowMs to zero, so a holder still finishing the same tenant's previous turn (3,750 ms of queue+pending per concurrent request) lost to an idle cold peer, which then recomputed and wrote a duplicate checkpoint. The collapsed band also disabled the soft prefix affinity tie-breaker, the path that produced most of the observed hits. selectRoutingCandidateWithAffinity now keeps the 3 s band with or without cache adjustments. Inside the band, if any candidate carries a positive CacheDiscountMs and the band has more than one member, the cheapest credited holder wins (SelectionCacheCredit, "cache_credit"). Credited near-ties are totally ordered: adjusted cost, then larger credit, fresher evidence weight (new routingCandidate.cacheEvidenceWeight, set with the hint), lighter queue and pending load, then provider ID, so a reservation rescan over the same pool reproduces the winner. A candidate carrying a restore penalty (cacheEstimatedTTFTSavedMs < 0) is retained only at the exact minimum, so it never displaces a cheaper peer and never benefits from load spreading. With no credited candidate in the band, the existing least-busy tie-breaks apply and the prefix-affinity tie-breaker is no longer disabled by an out-of-band credit. The band is not scaled with the estimated saving: the credit is already subtracted from the cost, so a wider band would count it twice and double the extra pending load a holder could absorb. The commit-time rescan compare also checks CacheDiscountMs, since ranking now keys on it. CacheOpportunity.CreditWonNearTie records a credited winner that cost more than the pool minimum; CacheOpportunityReason reports it as "selected_near_tie" (bounded vocabulary; "selected" keeps its meaning for a credited strict minimum). routing.cache_selection_terminal tags are unchanged. No new environment knobs. Changed test expectations, each with the reason: - cache_service_cost_test.go TestCacheServiceCostBalancesQueueAndHardware: slower_cached_hardware moves from 500 to 400 tok/s so the holder is 4,880 ms above the cold peer (beyond the band) and still loses; a new slower_cached_hardware_near_tie case at 500 tok/s (1,928 ms above, 8 s of proven saving) now wins. large_queue (3,524 ms above) still loses. - cache_checkpoint_stage_cost_test.go: cases assert per-case NearTiePoolSize and SelectionPath. useful_hit_wins is now a 2-member band won via cache_credit. reservation_reprices_changed_rate: the cold peer carries a pending turn on another model (+750 ms) so the first scan's least-busy choice of the penalized holder is deterministic; after the commit reprices the holder at 1,000 tok/s the same file is a 3.2 s credit and the rescan selects the holder (want ssd, reason selected) instead of cold. The scans >= 2 and repriced-saving assertions remain. expensive_stage_loses (restore penalty excluded from the band), queue/decode/backlog cases (holder beyond the band), gate cases and only_expensive_holder_still_serves are unchanged. - cache_stage_measurement_test.go TestSSDMeasuredStageSurvivesReadyAndChangesRouting: fast_read_not_overpriced now wins via cache_credit with the cold peer in the band; slow_read_not_erased stays unique_min (penalty excluded). - routing_context_test.go: SelectionPath vocabulary gains cache_credit; cache_cost_minimum expects a 2-member band and cache_credit; cache_equal_random becomes cache_equal_deterministic (identical credited holders resolve by provider ID); discounted_minimum_keeps_cost_preference expects the band and cache_credit; new cases cover a credited holder beating a less busy cold peer, a credit beyond the band losing, a lone credited candidate staying unique_min, and a restore penalty never entering the band. - candidate_selection_test.go: the ranking oracle implements the new policy (fixed band, credited-first total order, penalty exclusion) and fuzzes penalized candidates and evidence weights. Unchanged: TestCacheServiceCostPenaltyPreservesNearTieRanking (penalty loses to a cheaper, busier cold peer), restore penalty increasing ThisReqMs, ambiguous dual-tier receiving no credit, and holder_no_positive_credit semantics. New registry-level coverage in cache_credit_selection_test.go, priced through the production scan and commit path: a holder with a pending turn ~2 s above the idle cold peer wins (selected_near_tie) and ~4 s above loses; two holders rank by adjusted cost (the larger credit wins at equal load, a busier holder with a larger credit does not); a pool without credit keeps tie_pending and random spreading; affinity still applies when the credited holder is beyond the band; a restore penalty never beats a cheaper cold peer; and a commit-time rescan matches a fresh scan of the same pool.
A prompt-chain proof mismatch used to fence the provider's advertised
capability until the capability changed, and dropped every holder that
provider had for the model. In production one mismatch discarded ~36 later
receipts (18% of all lookups were capability_fenced over 7 days), and with
per-file epoch rotation being removed on the provider the fence would have
become permanent.
Fence: rejectedV2 now stores a record with the capability, the window end and
a consecutive-strike count. The window starts at 60 s, doubles for each
consecutive mismatch on the same provider/model/tier capability and caps at
10 min. A fenced receipt never reaches rejectCapability, so it cannot extend
the window; a mismatch that raced an already open window leaves it unchanged.
capabilityRejected returns false once the window lifted and still clears on a
capability change. Strikes are forgotten when an accepted proof arrives after
the window lifted, when the capability changes, or when the record sits idle
for the retention (10 min); sweepLocked and the lifecycle status drop stale
records so the map stays bounded by live capabilities.
Invalidation: an anchor mismatch (prompt, matched, ready) carries the
attempt's verified plan out of the decision and drops only that provider's
holders at the plan's boundaries, in both tiers, keeping the replay watermark
and the provider's other prompts for the same model. An identity mismatch
keeps the whole provider/model drop because every holder under that
advertised identity is stale. The removal reason stays proof_mismatch and
prefixCacheRevision is still bumped so selection and reservation re-check.
Status: CacheRoutingLifecycleStatus gains fences_applied, fences_expired and
fenced_capabilities (aggregate counts only), projected through
/v1/cache/status, the exact_cache_fence{event} and
exact_cache_fenced_capabilities gauges and the matching Datadog gauges.
Receipt metric reasons are unchanged.
Tests: the tracker gets a test-only clock (SetCacheRoutingClockForTest,
atomic so the provider WebSocket goroutine can read it under -race).
Registry tests drive real receipts through the existing helpers: expiry at
60 s, doubling to the cap, strike reset, fenced receipts not extending,
racing mismatch, plan-scoped drops in both tiers, identity whole-model drop,
capability-change clearing, retention sweep and single-count lapse
accounting. An API test sends the mismatch, a fenced receipt and the
post-expiry receipt over a real provider WebSocket and asserts the
/v1/cache/status projection.
Existing tests: direct callers of disablePrefixCacheV2Model pass an empty
plan (whole-model drop, the pre-existing behaviour they assert) and
capabilityRejected takes the time; exactTestRegistry is parametrised by TTL
so fence tests can advance the clock past 60 s without TTL-expiring holders.
No test asserted the fence outlived a time bound, so none needed its
expectation reversed.
…ze the demand index for its TTL The demand tracker shared the 10,000-entry holder cap. At ~35 planned requests/s with ~5 geometric boundary keys per plan (~170 entries/s) it turned over in about a minute against the 10-minute TTL, so most real repeats looked novel. It now has its own cap (cacheDemandMaxEntries = 250,000; 300 entries/s x 600 s = 180,000 plus headroom, ~180 B/entry, ~45 MB full). Holder and attempt caps are unchanged. Prepared v2 attempts carry the plan's RepeatedPrefixTokens on the provider-bound frame as cache_repeated_prefix_tokens (*int, omitempty): absent for an older coordinator or an ungranted/revoked scope, 0 for a fleet-novel prompt, n > 0 for the longest repeated geometric boundary. It is an integer count only. Providers gate complete-checkpoint writes on it and report the new donation outcome skipped_novel (23 known buckets; 9 of 32 entries remain in reserve). Older coordinators drop only that entry.
… demand Every completed prompt above the checkpoint floor was written to SSD as a complete checkpoint (~50 KB/token on gpt-oss-20b), and because load spreading makes the same prefix novel on each provider, the provider's own tag history could not see fleet-wide repeats: over 72 h prod settled 2.16 M write_priority_limited against 2.47 M donated, and the disk budget churn evicted the evidence the coordinator routes on. The coordinator now forwards its demand observation on the sealed request as cache_repeated_prefix_tokens (decoded in Messages.swift, carried through the CoordinatorClient event, handleInferenceRequest, RemotePrefixCacheContext.donationDemand, MultiModelBatchSchedulerEngine and EngineV2Bridge.submitTokenized). The CBv2CompletePrefixCache.donate contract has no slot for it, so the bridge registers the hint per receipt ID on the store (SSDCheckpointDemandHints, bounded, cleared with staging/receipts) and prepareWriteJob consults it before any write budget is charged. Admission rule (SSDCheckpointDemand.admitsWrite): with a hint, write a not-yet-durable checkpoint only when repeatedPrefixTokens >= minEffectiveTokens OR the local tag history has seen the tag within the cache TTL; otherwise settle the new outcome skipped_novel (no bytes, no budget) while still recording the tag locally. Without a hint (older coordinator, standalone/local serving) every checkpoint is written as before. Durable duplicates bypass the gate and keep settling already_durable. The attention-block store is untouched.
… values The reference still said routing off at 1% and 1 plan/s; production has run mode on, 100% cohort, 40 plans/s, 10m TTL and 4 holders since the 0.9.x rollout (observed 2026-09-26). Documents the operator-owned allowlist and master key as intentionally absent.
…relay The relay projects an explicit allowlist of inference_request fields. The new demand count is an integer, never a key or boundary, so it is copied like the other counts; a literal 0 must survive.
Add three chat_completions cases to the shared prompt-contract corpus whose provider-bound bodies the sidecar and the Swift provider tokenize differently today, and regenerate production_vectors.json from the checked-in manifests with the current sidecar so ProductionPromptParityTests fails on every model: - tool_call_arguments_bridge: assistant tool-call arguments with keys in non-sorted order and integral JSON doubles (2.0, 1e3) - the provider's Jinja value bridge sorts keys and renders integral doubles as integers - tool_function_extra_keys: a tool whose function object carries strict, response and examples - OpenAITool.toolSpec() renders only name, description and parameters - assistant_output_text_part: an assistant turn with an output_text content part - OpenAIContentPart decodes it like text; the sidecar dropped it These are the shapes behind prod prompt_anchor_mismatch receipts (same_length_hash / provider_shorter / provider_longer).
…an retries Review follow-up to 831ae1b. Exact-tie spread. cacheCreditRanksAbove no longer ends in provider ID. Credited near-ties equal on adjusted cost, credit, evidence weight, effectiveQueue and totalPending (cacheCreditEquivalent) are now drawn uniformly, the same spread cold near-ties use. With an identity order, every request of a same-prefix burst over N identical holders (a warm-pool push that lands one checkpoint on N boxes, fresh providers on the fleet-median TPS fallback) chose the smallest ID; the first commit bumped its pending count, the rest failed the commit compare, rescanned, and all chose the next ID, K(K+1)/2 scans for a burst of K. The keyed affinity spread was not used here because it is stable per prefix and would concentrate a same-prefix burst the same way. Reproducibility is now: a rescan over the same pool selects from the same equivalent set. TestCacheCreditIdenticalHoldersSpreadConcurrentBurst holds three concurrent reservations at the scan barrier over three identical holders for 30 rounds and asserts distinct winners per round and fewer than 5 scans per round on average (identity order takes exactly 6). Plan retries. ReserveNextFromPlan prices and admits an alternate cold and never applied a cache hint, but left CacheSelectionSelected, CacheSelectionTier/DiscountMs/EstimatedTTFTSavedMs and the new CreditWonNearTie from the primary scan on the request, so a cache_credit winner that failed pre-content and retried on a cold alternate still reported selected_near_tie at its terminal. The plan commit now clears those fields; CacheSelectionMode (participation) and the scan's opportunity counts remain, so the terminal reason becomes holder_not_selected (TestCacheCreditPlanRetryClearsCacheSelection). The breaker-bypass branch in commitProviderReservation needs no change: it commits the bypass winner only when the normal re-scan found no pool, and selectBestCandidateScanLocked returns before touching CacheOpportunity in that case; when it does find a winner it rescans, which resets the fields. Timing. cache_checkpoint_stage_cost_test.go accepts the repriced saving down to 3,000 ms (about 3 s of age decay on the 60 s fixture TTL instead of 88 ms). TestCacheCreditReservationRescanMatchesFreshScan compares the time-independent base cost exactly and bounds the credit as a monotone decay within 10% of the committed one instead of allowing 1 ms of drift. Semantics stated precisely (unchanged from 831ae1b, understated there): before, any cache adjustment collapsed the near-tie band, so a restore-penalty candidate at the strict minimum won outright. Now every non-penalized candidate is in the 3 s band regardless of penalties in the pool, and a penalized exact-minimum candidate participates in the least-busy and random tie-breaks with the other band members, with no preference of its own; it is still never retained above the minimum. Test expectation changes: routing_context_test.go cache_equal_deterministic becomes cache_equal_spread (winner in the tied set, both seen over 60 draws) plus cache_credit_tie_breaks_before_spread (fresher evidence, then lighter load, decide before any draw); the ranking oracle permits any credited near-tie equal to the top on all five terms.
…n, 16 SSD anchors Bump libs/mlx-swift-lm to the checkpoint-geometry branch: historical (gpt-oss, gemma-4) checkpoints are captured at every 1,024-token multiple a computed range covers, including interior stripe positions, regardless of the chunk cap; up to K = 8 are retained per donor under a byte budget; adopters resume under ordinary scheduling; donors publish deepest first. Provider: `PrefixCacheReadyV2` keeps up to 16 anchors for every tier (the SSD checkpoint receipt previously clipped to the two shallowest, which would have dropped the deepest boundary and failed the coordinator's expected-savings check once a donor proved more than two). Protocol and evidence tests updated; a second gpt-oss live gate exercises a donor that prefills under batching and a repeat that restores the deepest boundary.
…ipped Exact prefix-cache receipts compare the provider's block chain over its tokenized prompt with the sidecar's chain over the same provider-bound body. Five provider-side steps that run before every chat template had no sidecar mirror, so the two chains diverged (prompt_anchor_mismatch: same_length_hash, provider_shorter, provider_longer) and fenced the provider/model: - Jinja.Value(any:) sorts every bridged dictionary with Swift String < (Unicode scalar order == UTF-8 byte order); the sidecar rendered wire order. Order every object of the lowered body the same way (sorted_object_keys) so template loops such as Harmony's properties.items() and Qwen's arguments|items agree. - decodeToolCallArguments -> JSONSerialization -> Value(any:) matches Int before Double, so integral JSON doubles in tool-call arguments render as integers on the provider (1.0 -> 1, 1e3 -> 1000); mirror that bridge for decoded arguments (provider_bridged_value). - OpenAITool.toolSpec() renders only name, description and parameters; the sidecar cloned the whole function object, so strict/response/examples reached Qwen's tojson and Gemma's response rendering (typed_function_definition). - sanitizeJinjaMessages strips raw Harmony channel framing from assistant content and reasoning_content for every model family (strip_harmony_channel_framing, an exact port of stripHarmonyChannelFraming). This also lets gpt-oss plan replayed Harmony output instead of failing the render. - OpenAIContentPart decodes output_text like text/input_text; message_text accepts it too. No prompt-contract version bump: every change mirrors existing provider behavior (the #874 precedent), so current providers keep their contracts and fences clear on their own. Unit tests cover each mirror; the shared corpus gains assistant_harmony_framing and production_vectors.json is regenerated from the checked-in manifests (only the four new cases' vectors change). Not mirrored, documented in prompt-contract-sidecar.md: swift-jinja's dictsort uses localizedCaseInsensitiveCompare (Gemma property/argument order for mixed-case, underscore-vs-digit and accented keys) and swift-transformers pre-tokenizes combining-mark scripts and CRLF differently from the tokenizers crate; those are provider-side and change the token count.
TestCacheCreditIdenticalHoldersSpreadConcurrentBurst bounded total scans at 5 per round, but with identity-ordered ties a round costs 5 or 6 scans depending on whether a loser rescans before or after the other loser's commit, so a negative control (the 831ae1b provider-ID rule) measured 153-156 scans over 30 rounds against the 150 bound: a scheduling-dependent margin. A request commits on its first scan exactly when its first pick was distinct within the burst, and the barrier makes every first scan see the same idle pool, so identity order yields exactly one first-scan commit per round whatever the schedule, while a uniform spread yields about 2.1 of 3. The test now requires more than 1.5 first-scan commits per round on average (measured 60-67 of 90 across five runs; the negative control gives exactly 30) and keeps the scan bound as a secondary check.
…alysis The compared anchor is the last complete 256-token boundary, not the token count, so same_length_hash covers most divergences; names the classes the follow-up investigation identified.
At the new 250,000-entry cap the first observe after a lull longer than the TTL expired the whole stale index in one pass under d.mu on the plan path. Each observe now expires at most 1,024 head entries and later calls finish the drain. Correctness never depended on the sweep: every match is validated against its own timestamp, so a stale entry that is still present cannot match, and the entry cap evicts from the same head. Also asserts eviction at exactly the cap (the previous check could not fail at a 108k fill) and fixes the inverted hint-registry comment: an evicted or leaked hint fails open (one extra write), never loses one.
…the next query Review follow-ups to the bounded proof fence. A capability change cleared the fence only when something next queried that model/tier (capabilityRejected), so a status scrape between a heartbeat that replaced the capability (for example a whole-root wipe rotating the epoch) and the next query counted the dead record in fenced_capabilities. UpdatePrefixCacheSnapshot now reconciles the provider's fence records per model/tier against the resulting capability maps (reconcileFences, cache_model_changes.go): a record whose capability was replaced is forgotten at once, with its lapse still counted once. A pair that is merely absent keeps its record, so a protocol toggle that re-advertises the identical capability still cannot clear quarantine, and another model's heartbeat never touches the fence. The routing-side holder/fence check in the scheduler and the attempt terminal timestamp now read the tracker clock, so SetCacheRoutingClockForTest governs every path its comment names; demand observation, activation sampling and TTFT calibration stay on the wall clock and the comment says so. Tests: TestProofFenceCapabilityChangeClearsAndResetsStrikes asserts the status count and the record are gone before any query; TestCacheSnapshotOtherModelCannotClearProofFence asserts the count survives an unrelated model's heartbeat; TestProofFenceSweepThroughNaturalEntries reaches the retention sweep through the lifecycle status, the bounded state counts and a receipt from another provider.
…r repeat hint # Conflicts: # coordinator/api/exact_cache_status_test.go
Every single-file removal minted a fresh cache epoch: `evictOldestEntry` per budget victim, TTL expiry and budget eviction through the whole-root maintainer (`performExternalDestructiveChange` and `performUnloadedDestructiveChange`), `reconcileExternalRemovals`, and `removeCorrupt`, in both `SSDHybridCheckpointStore` and the attention-block `SSDPrefixCache`. The coordinator drops every holder for that provider/model on any epoch change (`holder_removed.epoch_change`, 70% of prod holder removals) while the surviving files stay readable and keep serving hits the scheduler never routed for. Per-file removals now run under a per-store `removalLock` (`performIndexedRemoval`): unlink plus index/accounting update, serialized with other removals, refused once closed or once the store no longer owns its epoch. The epoch record is untouched, the capability stays published, and a removed anchor surfaces to the coordinator as an ordinary lookup miss (`miss_invalidation` removes only that holder; no fence). The maintainer's active-store path reconciles the index before the barrier lifts, so a reader queued on a removed file sees it gone at its post-acquire recheck. Its unloaded-root path only validates the record: no capability is advertised for an unloaded model, so the coordinator holds nothing a rotation could invalidate, and leaving `nextSequence` alone keeps sequences monotonic across the in-place model switch. Rotation is kept for whole-root rebuilds only: `SSDCacheEpochStore.init` on a schema/binding mismatch (wipe, then a fresh epoch) and the explicit `rotate()` primitive. `SSDPrefixCache.destructiveChangeInProgress`, its rotating `performDestructiveChange` and the DEBUG-only `holdDestructiveEpochForTesting` are removed because nothing sets them any more; the hybrid store's `destructiveChange` flag stays declared for the write path's `cacheMaintenanceBusy` gate but is never set. Tests that encoded "rotate on eviction" now assert the opposite: SSDCheckpointMaintenanceEpochTests (both), SSDHybridCheckpointStoreTests .sharedDiskBudget, SSDHybridCheckpointDuplicateTests, SSDHybridCheckpoint RecencyTests, SSDCheckpointWriteRecoveryTests (existing-file failure, budget eviction), SSDCacheEpochStoreTests.unloadedDeletionSerializesReopen and the SSDPrefixCacheTests eviction / whole-root tests. `queuedValidity` used to prove a queued read aborts under an empty destructive change; it now unlinks the queued file and proves the post-acquire index recheck yields `.missAbsent` on the unchanged epoch. The DEBUG capability-bracket test is replaced by tests that the capability and sequence issuance continue through eviction, TTL sweep and corrupt drops. New SSDEpochContinuityTests: eviction keeps the epoch and the other anchor still hits; whole-root TTL sweep through the active store; corrupt-read drop; sequence continuity across eviction and a simulated restart (persisted `nextSequence`); a crash between unlink and index update is reconciled by `scanOnDisk` on restart without a new epoch; a binding change still wipes, rotates and disowns the superseded store.
…ort last Review follow-up to 72b07a6. The provider's tokenization is the ground truth, so where the two runtimes cannot be shown to agree the planner now refuses the request (served cold) instead of planning a chain that fences the provider. - Non-NFC object keys are refused (render/input.rs visit). Swift String < orders keys by their composed scalars ("e\u{301}" sorts after "f"), the planner orders bytes, so a decomposed key could render in a different position without any colliding sibling. Applies to request objects and to decoded tool-call arguments. The test that kept distinct decomposed keys eligible is replaced by one that keeps composed keys and decomposed values eligible and one that refuses decomposed keys. - Harmony framing is stripped only when every control token is a whole extended grapheme cluster (require_whole_grapheme_tokens). Measured on the provider toolchain: contains/range(of:) reject a token followed by a combining mark, ZWJ, ZWNJ, variation selector, emoji modifier, halfwidth voiced mark, Thai SARA AM or a Devanagari vowel sign, or preceded by a prepended format character, and replacingOccurrences disagrees with them on four of those. The check also runs before each removal, because one removal can splice a new token next to an extender. strip_harmony_channel_framing now returns Result. Adds a direct dependency on unicode-segmentation 1.13.3, already in the lock through tokenizers (one line in Cargo.lock). - normalize sorts members once, at the end, over the final messages, tools and template context, so members inserted by tool-schema repair or legacy function-call lowering are ordered with the rest. This also removes the unused mut that failed clippy -D warnings in 72b07a6. - prompt-contract-sidecar.md: the three unmirrored provider-side classes still plan, mismatch and fence (they were described as cold-only); MiniJinja dictsort is UniCase, so case-only differences agree and the Gemma divergence is swift-jinja's localized collation of underscore, digits and accents; each class states its deciding experiment; wire order is described as it is: the prelude re-serializes every body today, but forwardBody forwards caller bytes when nothing is dirty and JSON inside strings is never re-serialized, so the planner's sort is load-bearing. Correction to 72b07a6, which said only the four new cases' vectors changed: that comparison ignored member order. In that commit endpoint_messages_tool_turn and gemma_tool_turn also had template_input members reordered on all seven models, with token_ids and plan unchanged. production_vectors.json is regenerated from the checked-in manifests. Against 72b07a6, token_ids and plan are identical for all 154 model/case pairs; template_input member order changes in all 22 cases on every model (the final sort); provider_body and request_body are unchanged. Against 78725b4, token_ids and plan are identical for all 126 pre-existing pairs. Prompt-contract IDs and the four contract versions are unchanged.
…on semantics Threat model T-041: the SSD at-rest and same-account timing-oracle window moves from 15 to 30 minutes (operator decision, 2026-09-26, SEC-035 re-accepted); default equals maximum so the environment override still only shortens. States that the cache epoch is a routing-evidence generation, not an at-rest purge primitive, so stopping per-file rotation leaves the mitigations unchanged. Reference and architecture pages: TTL 1800, eviction/TTL expiry/corrupt-file removal keep the epoch, epoch_change now means a whole-root rebuild. Rollout runbook: coordinator holder TTL 25m, inside the provider's 30-minute file TTL, only once the fleet majority runs the provider release. docs-impact rules: scheduler.go selection changes may be documented in routing.md; new rule maps the provider SSD prefix-cache sources to their reference and architecture pages.
…nd budget races Follow-up to the epoch-rotation fix. Per-file removals no longer run under the epoch store's record lock or behind an epoch change, which opened four gaps found in review. 1. Rebuild wipe vs. a superseded instance's removal. A removal that had already passed its ownership check could unlink a block the successor's `removeAllBlockFiles` had listed; `removeItemIfSafe` then returned false for the missing file, the wipe threw, init failed, and the factory left the SSD tier off for that load. `SSDCacheEpochStore.removeStaleBlock` treats an already-missing block as removed (as `evictOldestEntry` does) and still fails on an entry that is present but not an owned regular file. The `performIndexedRemoval` doc comments no longer overstate the guarantee: a same-binding successor republishes the same epoch, so an instance it supersedes is stopped only by `close()`. 2. A raced unlink was counted as corruption. The catch-alls in `SSDHybridCheckpointStore+Read.swift` and in `SSDPrefixCache` (stage block loop, window-sidecar read) turned a vanished file into `corruptDropped` and `.missCorrupt`. `SSDBlockStore.isAbsentBlockFailure` recognizes both shapes the miss takes: the typed `posixFailure(code: ENOENT)` from `openat`, and the untyped `ioFailure` that `readStreaming` raises at its regular-file pre-check when the unlink landed before the read started (the common case), confirmed by a live no-follow status of `.missing`. An absent file drops only its index entry (`forgetMissing`, rechecked under the removal lock) and reports `.missAbsent`; the attention-block store keeps the leading run it already read. Replaced or unreadable entries stay on the corruption path. 3. A disowned but unclosed store pinned phantom bytes. It refused both eviction and reconciliation, so `SSDDiskBudget` kept counting bytes a successor's wipe had removed and over-evicted healthy stores until `close()`. Index-only reconciliation (`reconcileExternalRemovals`, `forgetMissing`) touches no files and now bypasses the ownership guard; file-touching removals stay refused. 4. The three `destructiveChange` gates in `+Read.swift` are removed: nothing sets the flag. Its declaration stays because the write path's `cacheMaintenanceBusy` gate still reads it. Tests (each fails with its fix neutralized): SSDCheckpointRemovalRaceTests (unlink behind the index; eviction from inside a reader's import-plan callback, i.e. between its manifest read and its full read; concurrent readers vs. eviction; failure classification; disowned store and the box-wide budget), SSDCacheEpochStoreTests (wipe tolerance; a rebuild racing real concurrent unlinks), and SSDPrefixCacheLifecycleTests (absent block mid-run and leading; concurrent readers vs. eviction; crash between unlink and index update reconciled on restart; disowned cache reconciliation).
…r boundary With per-file eviction no longer rotating the provider's cache epoch, the coordinator learns that a checkpoint is gone only through lookups. A hit upserted the matched boundary and nothing else, so a provider that evicted its 4,096-token file but kept the 2,048 one answered every request with a valid hit at 2,048: no miss ever fired, the stale 4,096 holder lived until its TTL, outranked machines that really held 4,096, and priced the provider with a saving it would not deliver. An accepted hit now removes that provider's holders, in the receipt's tier only, at every boundary of the attempt's verified plan deeper than the matched anchor (supersedeDeeperHoldersLocked). Holder keys are content addressed, so a deeper holder on a different continuation of the same prefix is not in the plan and is left alone, as are other providers' holders at the same boundaries. The path never fences, never bumps the capability revision and never touches sequence watermarks; skipped_* outcomes do not trigger it. The removal is counted under a new reason, shorter_hit, not miss_invalidation. The provider can legitimately hit below a boundary it still stores: the attention-block store trims its longest run to the stage byte and time caps, the complete-checkpoint store skips a candidate over those caps, and the matched anchor follows what the engine adopted. The receipt cannot distinguish those from an eviction, holders are advisory, and a later ready or hit re-teaches the boundary. The reason joins CacheHolderRemovalReasons(), so /v1/cache/status and the exact_cache_holder_removed gauges carry it without further wiring. No scheduler change is needed for pricing: holder matches are walked deepest first and the first match per provider wins, so the next hint is the boundary the hit just proved, at its measured stage cost. Tests drive real receipts through the registry: the 2,048/4,096 scenario (holder gone for that provider only, the other machine preferred, hint and CacheEstimatedTTFTSavedMs at the shorter boundary, no fence, watermark intact and replay rejected), re-teaching by the same attempt's ready, tier isolation, no removal at the deepest held boundary or for a diverging continuation, and no removal on skipped or mismatched receipts. They fail with the supersede call removed. An API test sends the same exchange over a real provider WebSocket and asserts the /v1/cache/status projection; the wire harness moved into a shared helper that the fence wire test now uses.
`SSDPrefixCachePolicy.defaultTTLSeconds` and `maxTTLSeconds` 900 -> 1800. Default and maximum stay equal, so `DARKBLOOM_PREFIX_CACHE_SSD_TTL_SECONDS` can still only shorten the TTL: 1800 and below are accepted, anything above (or <= 0, or malformed) falls back to the default. The 15-minute cap dated from when every capacity eviction also rotated the cache epoch, so nothing on disk stayed routable for long anyway. With eviction no longer rotating, the TTL is what bounds reuse; the coordinator's own 10-minute holder TTL stays shorter. Everything else reads the policy accessor or `config.ttlSeconds`, so no other constant assumed 900: both stores' `scanOnDisk`, the hybrid store's `freshFileBytes` probe, `SSDPrefixCache.sweepExpiredEntries`, the whole-root maintainer, and `SSDCheckpointDemand(ttlSeconds:)` (a tag seen again within 30 minutes now counts as repeat demand). The crash-temp TTL (`crashTempTTLSeconds`, one hour) is independent and unchanged. Threat model: `docs/threat-model.yaml` T-041 requires a fresh SEC-035 sign-off for any TTL above 15 minutes. This value is the one relayed to this branch as signed off at 30 minutes and nothing longer; T-041 still states 15 minutes and must record that sign-off when this merges. Kept on its own branch, on top of the rotation fix, so it can merge second or be held without touching that fix.
A valid hit below a boundary recorded for that provider drops its deeper holders for that prompt in the receipt's tier. Explains why this is needed once per-file eviction no longer rotates the epoch, and that a stage cap can produce the same receipt.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6c8dda89e1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…in T-041 Two sentences still said 15 minutes after the 30-minute sign-off; SEC-035 now states one exposure window. Found by Codex review on #1207.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3229885155
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
clearRetired released holders, attempts, and the per-provider indexes but left the demand index populated. A prepared attempt keeps the retired tracker reachable through its owner until the request finishes, so a reconfigure could pin up to cacheDemandMaxEntries entries (~191 MiB at the 1,000,000 cap) in a generation that no longer serves lookups. Add cacheDemandTracker.clear and call it from clearRetired. Extend TestCacheProviderIndexIsClearedOnReconfigure to observe a plan on the old tracker and assert the demand index is empty after ConfigureCacheRouting; the assertion fails without the clear. Also correct the CHANGELOG demand-index figure to the shipped cacheDemandMaxEntries value (1,000,000). Addresses the Codex review threads on CHANGELOG.md:22 and cache_attempt_ownership.go:146.
…e-cleanup Conflicts were docs freshness stamps and the CHANGELOG head; keep both the Unreleased cleanup section and the v0.9.11 release-candidate section. master now carries v0.9.11, so the retired-backfill remedy no longer calls v0.9.10 the last release that runs them.
Prefix cache: fix the hit-rate collapse
Production ran exact prefix-cache routing at 100% and measured a 1.4–5.2% hit rate per model with 2–7% of prompt tokens saved. The analysis (
docs/reports/2026-09-26-prefix-cache-hit-rate-analysis.md) found the routing switch was not the problem: 85–90% of gpt-oss and Gemma routing evaluations repeated a recently seen prefix, but the coordinator held almost no evidence to route on, and the provider's write path threw away half of what it tried to keep.Root causes and fixes
cache_credit)functionkeys, Harmony framing in history,output_textparts)shorter_hit)Before and after, backed by what was measured
"Before" is production over the seven days ending 2026-09-27 00:30 UTC (Datadog
d_inference.routing.cache_model.*,/v1/cache/statuson the prod coordinator, prodrequest_profiles). "After" is what this PR changes, with the measurement that backs each row: live model runs on this branch, the two-provider end-to-end gate on the final tree, the coordinator benchmarks, or the test suites. Where the after value is a projection rather than a measurement it says so.Evidence the coordinator can route on
SSDEpochContinuityTests,SSDCheckpointRemovalRaceTests); in the end-to-end run each provider's epoch was constant across all nine casesTestProofFence*, wire test over a real provider socket). Sidecar mirrors remove the five mismatch classes that caused most fences: the pre-fix vectors fail the 7-model parity gate, the post-fix vectors passTestCacheDemand*)Selection
cache_credit_selection_test.go); in the end-to-end run the original holder won a two-candidate contest with a 3,832 ms creditWrites
skipped_novel); in the end-to-end run the other tenant's request carried a hint of 0 and reportedskipped_novel: 2with no file written, while the repeated tenant's requests wroteWhat a hit restores
sameText=true; end-to-end repeat restored 5,120 where the 09-07 record restored 4,096sameText=true; checkpoints now exist from 1,024 tokensParticipation (config, in the rollout runbook, not yet applied)
Hit rate
The end-to-end gate is functional, not a fleet measurement: two providers on one Mac, one request at a time. The production hit-rate rows above are what to compare against a week after the rollout steps, using the same Datadog series listed in the runbook.
Behavior
Colors: red = evidence lost or work wasted, green = evidence kept or a hit, amber = neutral outcome, grey = decision point.
Before: a repeated prompt (measured hit rate 1.4–5.2%)
flowchart LR classDef bad fill:#FEE2E2,stroke:#B91C1C,color:#7F1D1D classDef good fill:#DCFCE7,stroke:#15803D,color:#14532D classDef warn fill:#FEF3C7,stroke:#B45309,color:#78350F classDef neutral fill:#F1F5F9,stroke:#475569,color:#0F172A R["Repeat request arrives<br/>(85–90% of gpt-oss / Gemma traffic)"]:::neutral Q1{"Coordinator holds<br/>cache evidence?"}:::neutral L1["Usually no<br/>provider epoch rotated ~1/min<br/>fence never lifted<br/>10,000-holder cap"]:::bad Q2{"Holder is the strict<br/>cost minimum?"}:::neutral L2["No: any queued work on the<br/>holder beats the credit"]:::bad COLD["Cold provider prefills<br/>the whole prompt"]:::bad HIT["Hit, but only at the first<br/>chunk boundary (~2k of 4–7k tokens)"]:::warn W["Every prompt written to SSD<br/>at ~50 KB per token<br/>45% dropped at the write cap"]:::bad E["Eviction rotates the epoch:<br/>coordinator forgets this provider"]:::bad R --> Q1 Q1 -- "no (69–75%)" --> L1 --> COLD Q1 -- "yes" --> Q2 Q2 -- "no (8–16%)" --> L2 --> COLD Q2 -- "yes (0.6%)" --> HIT COLD --> W --> E E -. "next request" .-> Q1After
flowchart LR classDef bad fill:#FEE2E2,stroke:#B91C1C,color:#7F1D1D classDef good fill:#DCFCE7,stroke:#15803D,color:#14532D classDef warn fill:#FEF3C7,stroke:#B45309,color:#78350F classDef neutral fill:#F1F5F9,stroke:#475569,color:#0F172A R["Repeat request arrives"]:::neutral Q1{"Coordinator holds<br/>cache evidence?"}:::neutral K["Evidence survives<br/>eviction keeps the epoch<br/>fence lifts in 60 s to 10 min<br/>250,000 holders, 30-minute window"]:::good Q2{"Holder inside the<br/>3-second cost band?"}:::neutral SEL["Proven holder wins<br/>(cache_credit)"]:::good HIT["Hit at the deepest or the<br/>fork boundary (1,024-token stride)"]:::good COLD["Cold provider prefills"]:::warn Q3{"Coordinator repeat hint<br/>at or above 1,024 tokens?"}:::neutral SKIP["skipped_novel<br/>nothing written, no budget spent"]:::warn WR["Write first, fork target, deepest<br/>(2–3 files, capped per slot)"]:::good EV["Per-file eviction keeps the epoch<br/>coordinator learns of a removed file<br/>by a miss or a shorter hit"]:::good R --> Q1 Q1 -- "yes" --> K --> Q2 Q2 -- "yes" --> SEL --> HIT Q2 -- "no" --> COLD Q1 -- "no (fleet-novel)" --> COLD COLD --> Q3 Q3 -- "no" --> SKIP Q3 -- "yes" --> WR --> EV EV -. "next request" .-> Q1Lifecycle of one conversation
flowchart LR classDef bad fill:#FEE2E2,stroke:#B91C1C,color:#7F1D1D classDef good fill:#DCFCE7,stroke:#15803D,color:#14532D classDef warn fill:#FEF3C7,stroke:#B45309,color:#78350F subgraph BEFORE["Before"] direction LR B1["Turn 1: cold, written"]:::warn --> B2["Turn 2: evidence already<br/>wiped by an epoch rotation<br/>cold again, written again"]:::bad --> B3["Turn 3: same"]:::bad end subgraph AFTER["After"] direction LR A1["Turn 1: cold, skipped<br/>(fleet-novel)"]:::warn --> A2["Turn 2: repeat seen<br/>cold, written at 1,024 / fork / deepest"]:::warn --> A3["Turn 3 onward: hit at the<br/>previous turn's deepest boundary"]:::good endAn application whose system prompt exceeds 1,024 tokens skips the first step, because the shared prefix is already known to be repeated on turn one.
Code
Colors by layer: blue = coordinator (Go), amber = provider (Swift), purple = engine (
mlx-swift-lm), teal = prompt sidecar (Rust). Dashed grey boxes are the replaced behavior.flowchart TB classDef coord fill:#DBEAFE,stroke:#1D4ED8,color:#1E3A8A classDef prov fill:#FEF3C7,stroke:#B45309,color:#78350F classDef eng fill:#EDE9FE,stroke:#6D28D9,color:#4C1D95 classDef side fill:#CCFBF1,stroke:#0F766E,color:#134E4A classDef old fill:#F8FAFC,stroke:#94A3B8,color:#475569,stroke-dasharray:5 5 subgraph C["Coordinator (Go)"] direction LR C1["selectRoutingCandidateWithAffinity<br/>band collapsed to 0 with any credit"]:::old --> C2["3 s band kept<br/>cheapest credited holder wins<br/>SelectionCacheCredit"]:::coord C3["disablePrefixCacheV2Model<br/>fence until capability change<br/>drop every holder"]:::old --> C4["cache_proof_fence.go<br/>60 s → 10 min window<br/>invalidateProviderPlan"]:::coord C5["applyLookupV2Decision<br/>hit upserts only the match"]:::old --> C6["supersedeDeeperHoldersLocked<br/>shorter_hit"]:::coord C7["cacheRoutingTracker<br/>10,000 holders, full-scan sweep,<br/>power-of-two demand"]:::old --> C8["250,000 holders, expiry heaps,<br/>cache_provider_index.go,<br/>1,024-token demand stride"]:::coord C9["CacheAttemptSnapshot.ApplyTo<br/>scope + nonce only"]:::old --> C10["also cache_repeated_prefix_tokens"]:::coord end subgraph P["Provider (Swift)"] direction LR P1["evictOldestEntry / TTL sweep<br/>performOwnedDestructiveChange:<br/>new epoch per file"]:::old --> P2["performIndexedRemoval<br/>unlink + index, epoch kept"]:::prov P3["SSDHybridCheckpointStore+Write<br/>write every captured checkpoint"]:::old --> P4["SSDCheckpointDemand.admitsWrite<br/>skipped_novel below the hint floor"]:::prov P5["SSDPrefixCachePolicy<br/>TTL 900 s"]:::old --> P6["TTL 1,800 s<br/>(SEC-035 sign-off recorded)"]:::prov end subgraph E["Engine (mlx-swift-lm)"] direction LR E1["CBv2RecurrentCheckpointGeometry.record<br/>uniform chunk only, keep first + latest"]:::old --> E2["recordHistorical: 1,024-token stride<br/>CBv2HistoricalCheckpointRetention:<br/>first + fork target + latest<br/>CBv2HistoricalStagingCap: capacity / 8"]:::eng end subgraph S["Prompt sidecar (Rust)"] direction LR S1["normalize.rs<br/>diverged from the provider on<br/>5 prompt shapes"]:::old --> S2["mirrors: argument key order,<br/>integral doubles, typed function,<br/>Harmony framing, output_text"]:::side end C10 -. "wire: cache_repeated_prefix_tokens" .-> P4 P4 -. "hint → prefixCheckpointTargetTokens" .-> E2 S2 -. "matching proofs → fewer fences" .-> C4Compatibility
cache_repeated_prefix_tokensis optional; older providers ignore it and keep writing every checkpoint; older coordinators omit it and providers keep today's behavior. New donation outcomeskipped_noveland holder-removal reasonshorter_hit; unknown values are dropped entry-wise by older coordinators.Release
This PR prepares v0.9.11:
ProviderCore.versionand the coordinator'sLatestProviderVersionare aligned at 0.9.11 (scripts/check-release-version.shpasses), the changelog carries the v0.9.11 release-candidate section above the unshipped v0.9.10 candidate, and the provider-release runbook names 0.9.11 as the prepared version. The 0.9.10 rollout order applies unchanged because the new inference-request field is optional in both directions. No tag is created by this PR.Rollout
docs/operations/cache-routing-rollout.mdgains the post-fix procedure: sidecar concurrency and memory before the plan QPS cap (40 → 120), then the coordinator holder TTL (10m → 25m, only once the fleet majority runs the new provider release), then the Nemotron Lightning and Bonsai 2 allowlist tuples. The engine change is merged on themlx-swift-lmfork as Layr-Labs/mlx-swift-lm#168; this PR pinslibs/mlx-swift-lmto the fork'smainheadc9bcdc3e, whose tree is identical to the commit every verification below ran on.Verification
All on the integrated tree unless noted; every workstream was also independently reviewed before merge, with the reviewers' findings fixed on the branch.
gofmt,go vet ./...,go test ./...(all packages),go test -raceon registry, api, protocolgo test -short ./e2e/testbed/...)TestBenchmark_*ine2e/need a real provider and fail identically on master)cargo fmt --check,cargo clippy --locked --all-targets -- -D warnings,cargo test --lockedProductionPromptParityTests, 7 models, committed vectors)--no-parallel)libs/mlx-swift-lm) checkpoint, retention, geometry, packed-prefill, prefill-parity suitessameText=truethroughoutsameText=trueTestIntegrationConnectedCacheHTTP, gpt-oss-20b, ssd)Coordinator benchmarks at the new caps: routing lookup 57 µs at 250,000 holders (independent of index size); expiry sweep 6.5 µs against 47 ms for the old full scan; per-provider invalidation 36 µs against 15 ms; full holder plus demand indexes about 470 MiB on a 58 GB host that uses 1.3 GB today.
Numerical controls in the engine suites (
GPTOSSPrefillOutputTests,CBv2Gemma4ScheduledPrefillTests) pass with the default TF32 setting on this machine.End-to-end
TestIntegrationConnectedCacheHTTPon this Mac with two real gpt-oss-20b providers, the real supervised Rust sidecar and an in-memory coordinator with cache routing on, once inssdmode and once inoffmode, followed by the strict paired comparator (scripts/benchmarks/compare_connected_cache_http.py): both arms pass all nine applicable cases (vision is not applicable to this artifact), the comparator passes, and no test expectation had to change.[1024, 5120], two filesskipped_novel, no write[1024, 5120]Compared with the 2026-09-07 record on Qwen 3.8: the same 8 lookups, 4 hits and 4 misses; donations drop from three to two because the other tenant's fleet-novel request is now skipped; restores rise from 4,096 to 5,120 tokens because gpt-oss checkpoints now sit on the 1,024-token stride. Text and reasoning were identical across the cold, repeat and original-after-continuation cases and between arms; the tool call matched exactly; no fence,
shorter_hitor demand-cap counter moved.Two notes for whoever refreshes the frozen input package: the reviewed revision-2 tools fixture tokenizes to 135 tokens under gpt-oss, below the 256-token block, so it can never negotiate a cache scope (its gpt-oss cells were unrun at package freeze); the run above used a 372-token tools request. And
cold_donor_astill donates only because the harness pre-plans the fixture body, which primes the demand index; without that pre-plan the first case would be skipped and the second would donate.Follow-ups (not in this PR)
dictsortcollation, combining-mark scripts on the Qwen regex, CRLF): documented with deciding experiments; they also affect model quality independently of caching.🤖 Generated with Claude Code