Repository navigation
Fix cache prompt parity and telemetry correctness - #874
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Found 1 test failure on Blacksmith runners: Failure
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 58d5fabeca
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a87a5e788f
ℹ️ 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".
| if n.fract() == 0.0 && n >= i64::MIN as f64 && n < -(i64::MIN as f64) { | ||
| Value::from(n as i64) |
There was a problem hiding this comment.
Reject lossy integral doubles before encoding
When a schema contains an integral decimal beyond exact f64 range but below the current 1e16 eligibility cutoff (for example, 9007199254740993.0), serde_json has already rounded it to 9007199254740992 before this cast, while the provider's Int-first Swift decoder preserves 9007199254740993. Unlike the previously discussed out-of-range unsigned case, prevalidation accepts this decimal form, so the planner and provider inject different schema instructions and valid cache receipts are rejected and fenced for prompt-anchor mismatch; reject these lossy forms or preserve their lexical integer value.
Useful? React with 👍 / 👎.
* docs(reports): prefix cache hit-rate analysis and levers (2026-09-26)
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.
* ops(cache-routing): plan-gate widening runbook and Nemotron/Bonsai tuples
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.
* feat(registry): prefer a proven cache holder inside the near-tie band
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.
* fix(cache): bound the proof fence and narrow mismatch invalidation
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.
* feat(coordinator): forward observed repeat demand to providers and size 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.
* feat(provider): gate complete-checkpoint donations on observed repeat 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.
* deploy: sync the sanitized prod env reference with live cache-routing 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.
* test(e2e): observe cache_repeated_prefix_tokens in the provider wire 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.
* test(prompt-parity): reproduce sidecar/provider prompt-chain mismatches
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).
* fix(registry): spread tied cache holders, clear cache selection on plan retries
Review follow-up to 831ae1b78.
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 831ae1b78, 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.
* feat(prefix-cache): stride-aligned historical checkpoints, K retention, 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.
* fix(promptsidecar): mirror provider prompt preparation the planner skipped
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.
* test(registry): discriminate the tied-holder burst by first-scan commits
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 831ae1b78 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.
* docs(reports): correct the mismatch-detail reading in the hit-rate analysis
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.
* fix(registry): bound the demand-index TTL sweep per observe
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.
* fix(cache): lift a replaced capability's fence at the heartbeat, not 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.
* fix(provider): stop rotating the SSD cache epoch on per-file removals
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.
* docs: cache routing credit band, bounded proof fence, demand-gated donation
* fix(promptsidecar): refuse inputs the provider renders differently; sort last
Review follow-up to 72b07a63e. 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 72b07a63e.
- 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 72b07a63e, 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 72b07a63e, 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
78725b45b, token_ids and plan are identical for all 126 pre-existing pairs.
Prompt-contract IDs and the four contract versions are unchanged.
* docs: record the 30-minute SSD cache TTL sign-off and per-file eviction 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.
* fix(provider): harden per-file SSD removals against rebuild, reader and 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).
* fix(cache): drop a provider's deeper holders when it hits at a shorter 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.
* feat(provider): raise the SSD prefix-cache TTL from 15 to 30 minutes
`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.
* docs: shorter_hit holder removal
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.
* fix(provider): expire files under a disowned store's root; drop the dead maintenance gate
Whole-root maintenance and a disowned store. `SSDDiskBudget
.performActiveDestructiveChange` took the first registered store matching
a model root. A store that a different-binding successor has disowned,
and that its owner has not closed yet, refuses every file removal, so the
whole-root maintainer skipped that root's TTL expiry and budget eviction
until the store closed and files could outlive the at-rest TTL the threat
model states (T-041). The budget now considers only stores that still own
their root (`SSDEvictableStore.ownsEvictionRoot`: open, and still the
owner of the published epoch) and returns nil without running the body
when none does, so the maintainer falls through to the unloaded-root path
and expiry still happens. With an owner and a disowned store registered
for the same root, the owner brackets the removal and reconciles its index
inside the barrier. Both stores' `performIndexedRemoval` guards now read
the same property.
Cleanup of what the epoch-rotation change left dead in the write path:
the `destructiveChange` flag and its `cacheMaintenanceBusy` gate in
`SSDHybridCheckpointStore+Write.swift` are removed (nothing set the flag),
and two comments there no longer claim that removing an endpoint rotates
the epoch. The wire value `cache_maintenance_busy` stays in
`Protocol/Messages.swift`, `ProtocolTests` and the coordinator for older
providers; current providers no longer emit it. The demand gate is
untouched and still runs before the write rate limiter and before
`writing.insert`.
Tests: `maintenanceRefusalCanRecover` set the flag directly and asserted
the busy outcome; it is replaced by `donationDuringMaintenanceIsWritten`,
which holds the store inside a maintenance removal and proves a concurrent
donation is written. New: a disowned, unclosed store (hybrid) and cache
(attention-block) plus a TTL-expired file under the root, removed by one
maintainer pass; the owner is preferred over a disowned store on the same
root, and the budget declines without running the body when only a
disowned store remains. All three fail under the old first-match lookup.
* feat(prefix-cache): demand-targeted checkpoint retention and review fixes
Bump libs/mlx-swift-lm: a historical donor keeps at most the first
boundary, the fork target named by the coordinator's repeated-prefix hint
and its deepest boundary, instead of up to eight; historical adopters stay
out of packed prefill.
Provider:
- The bridge sets CBv2Request.prefixCheckpointTargetTokens from the same
cache_repeated_prefix_tokens hint that gates the write, so the engine
stages the fork boundary the coordinator observed.
- A ready receipt with more than 16 anchors keeps the deepest 16 and is
sent; the sequencer used to withhold it and the message kept the
shallowest.
Live gpt-oss gate: a growing conversation restores the previous turn's
deepest boundary, a forked prompt restores the hinted 2,048 boundary and
matches its cache-off text, the batched donor writes first and deepest
only, and a fleet-novel donor writes nothing. Each request logs
finish-to-DONE.
* feat(registry): size the cache indexes for a 30-minute TTL and bound the sweep
Holders now live their whole TTL, and the operator is raising it toward the
30 minutes providers keep cache files, so the two in-memory caps sized for
the old world become the next bottleneck.
- cacheRoutingMaxEntries 10,000 -> 250,000: 30 holders/s x 1,800 s = 54,000
with more than 4x headroom. Measured through the receipt path: 982 B per
donated holder, 1,126 B per holder recorded by a hit, about 270 MiB full.
- cacheDemandMaxEntries 250,000 -> 600,000: 300 entries/s x 1,800 s =
540,000. Measured 191 B per entry, about 110 MiB full.
- The holder and attempt order heaps are keyed by expiry instead of update
and creation time. Those orders differ: resident holders live
min(ttl, 30 s) while SSD holders live the ttl, and an attempt's deadline
is rewritten from two hours to two minutes when it turns terminal.
- sweepLocked pops expired heads instead of walking every holder and
attempt under the tracker lock, at most cacheRoutingMaxSweepRemovals =
1,024 of each per pass. A pass that spends its budget re-arms the sweep
for the next tracker operation. At 100,000 holders with ten expired the
pass costs 8 us instead of 17 ms.
- The caps evict the head of the same heap, the entry that expires first.
An expired head the sweep has not reached is counted as ttl, so
capacity_eviction counts only displaced live evidence.
- CacheRoutingStateCounts settles a mass expiry in bounded passes and
releases the lock between them.
(cherry picked from commit 01a4e08678493b1b3b88cc4edc4553e6ece0be2c)
* fixup: read the tracker caps under its lock in stateCounts
(cherry picked from commit 2a3eef8f78681e44da49b2ded78f05130ce5c130)
* docs: maintainer ownership rule and retired donation outcomes
Whole-root maintenance brackets removals only through a store that still owns
its root, so TTL expiry never waits for a disowned store. cache_entry_evicted
no longer implies an epoch change; cache_maintenance_busy is emitted only by
older providers.
* perf(registry): index cache holders and attempts by provider
invalidateProviderEvidence and invalidateProviderModels walked every holder
bucket and every attempt under the tracker lock: 14 to 24 ms at 250,000
holders, per disconnect or capability change, while the caller holds the
provider lock and the registry lock (ReplaceProviderModels the write lock).
- holdersByProvider and attemptsByProvider hold the order-heap entries
themselves and change only where the heaps push and remove, plus
clearRetired. Invalidation now visits that provider's entries. Model and
tier filtering, removal reasons, sequence watermarks and fences are
unchanged. The holder index costs 38 B per holder.
- The per-bucket maxHolders eviction counts an expired victim the sweep has
not reached as ttl, as the global cap does.
- Cap enforcement stops on an empty heap instead of indexing it.
- The sweep backlog flag is read from the heap heads, so a pass that ends
exactly on its budget does not re-arm for nothing.
- /v1/cache/status counts holders before it reads the lifecycle counters,
so holder_added minus the removals equals holders within one scrape.
- ConfigureCacheRouting warns when the TTL exceeds the 30 minutes the
indexes are sized for; it still starts.
- Lookup and ready receipts store the attempt through storeAttemptLocked.
- Invariant test: 8 seeds of 6,000 random operations check the heaps, the
by-key indexes and the per-provider indexes after every operation and
compare each invalidation with a brute-force census.
* feat(registry): observe cache demand on the 1,024-token checkpoint stride
The provider uses cache_repeated_prefix_tokens to choose where to keep a
checkpoint: the 1,024-aligned boundary at or below the observed shared
prefix. Observation at power-of-two block ordinals reported 4,096 for two
prompts sharing 7,000 tokens and 8,192 for a shared 12,000, so the fork
restored well short of what was shared.
- A plan observes its boundaries at every multiple of 1,024 tokens and its
final boundary, selected by token count. 256 and 512 are dropped: the
provider keeps no checkpoint below 1,024 tokens. Sharing 7,000 tokens now
reports 6,144 and sharing 12,000 reports 11,264.
- At most 64 stride boundaries per plan, the deepest ones, plus the final
boundary: 65 keyed digests and entries whatever the prompt length.
- The same anchors are read and recorded. A continuation reports the first
plan's final boundary when it lies on the stride and the stride boundary
below it otherwise, which is the checkpoint the provider chooses.
- cacheDemandMaxEntries 600,000 -> 1,000,000. Measured over the production
prompt lengths with every prompt distinct: 7.07 entries per plan for
gpt-oss-20b, 3.82 for gemma. 60 plans/s x 7.07 x 1,800 s = 763,000, so
the cap has 1.3x headroom. Measured 200 B per entry, 191 MiB full.
* docs(registry): describe the 1,024-token demand stride in code comments
Comment-only. The wire field cache_repeated_prefix_tokens and one wire test
still described the geometric observation; one sweep comment is rewrapped.
* test(registry): trim the race-time cost of the index sizing tests
Receipts are round-tripped through JSON only where memory is measured, and
the 29-minute plan retention fill lists each plan's observed boundaries
instead of every block. Under the race detector the two tests drop from
21 s and 11 s to 11 s and 3 s. No production code changes.
* feat(prefix-cache): cap staged checkpoint windows across the slot
Bump libs/mlx-swift-lm: staged historical windows of all donors on a slot
may hold at most 1/8 of its admission capacity, read at each capture.
Within a donor the claim order is rolling latest, fork target, first, and
a donor at the cap still rolls its latest. Four concurrent gemma-4 donors
on a 16 GB slot now stage at most 1.95 GB (nine checkpoints) instead of
3.46 GB, below the 2.60 GB the pre-change first/latest rule could reach.
* fix(prefix-cache): align the donor byte budget with the slot-wide cap's order
Bump libs/mlx-swift-lm: over its 1/16 budget a historical donor now gives
up its first, then its fork target, and always keeps its rolling latest,
the same order the slot-wide cap uses. On an 8 GB gemma-4 slot the donor
budget binds before the slot cap, so donors there kept a guessed first and
lost the boundary the coordinator had observed demand for. Without a
target the first/latest pair is kept as before.
* feat(registry): sticky affinity, shallow demand ladder, demand index status
- The affinity key is the deepest matched boundary that is a power-of-two
multiple of 1,024 tokens, falling back to the deepest match when no such
boundary matched. RepeatedPrefixTokens stays the deepest matched stride
or final boundary. A chat growing 400 tokens a turn keeps one key across
eleven turns until it crosses 8,192 (the stride key changed on every
stride crossed); an agent loop at 1,500 a turn changes it twice in nine.
- Plans longer than the 64-stride window also observe the power-of-two
multiples of 1,024 below it, at most ten. Two 100,000-token prompts
sharing 8,192 tokens now report 8,192 instead of 0, as does a 10,000 and
a 100,000-token prompt in either order. The per-plan bound is
cacheDemandMaxPlanBoundaries = 75: 65 up to 65,536 tokens, 71 under
131,072, 75 for the longest plan a receipt can name.
- CacheRoutingLifecycleStatus and /v1/cache/status carry demand_entries and
demand_cap_evictions; gauges exact_cache_demand_entries and
exact_cache_demand_cap_evictions, Datadog exact_cache.demand_entries and
exact_cache.demand_cap_evictions. Cap evictions count entries removed
inside their TTL; an expired head the bounded sweep left is an expiry.
- The measured plan mix moves to 7.11 and 3.85 entries per plan; the cap's
headroom is 1.30x.
- Comments: the stride rationale names the provider consumers, and the
status scrape comment no longer claims the lifecycle arithmetic is exact.
* test(promptsidecarloadproof): expect the 154-vector production corpus
The sidecar parity fix added four corpus cases across seven models (126 to
154 vectors); the load-proof inventory test pinned the old count.
* docs: index sizing, demand stride and observability
Holder cap 250,000 with expiry heaps and a bounded sweep, per-provider
invalidation index, demand observed at every 1,024 tokens with a power-of-two
ladder for long prompts, sticky affinity rung, demand-index status fields and
gauges, TTL sizing warning, eight removal reasons. Provider comments no longer
describe the repeat as geometric. Vector count 154.
* docs: demand index status fields and gauges
* fix(prefix-cache): count checkpoints in publication against the slot cap
Bump libs/mlx-swift-lm: a finished donor's checkpoints keep counting
against the slot-wide staged cap while its files are written, until the
publication batch closes, so donors finishing together cannot lift new
donors' staging above the cap. Discarded candidates leave the in-flight
tally immediately.
* docs: historical checkpoint geometry, retention and staging cap; changelog for the fix set
* registry: log the selection path on routing_decision
The connected end-to-end gate reads the routing_decision debug record, not
the profiler row, so a cache_credit win was not verifiable from it.
* chore(libs): pin mlx-swift-lm to main c9bcdc3e (#168 squash of the checkpoint-geometry branch)
Same tree as 03236c8, on which every verification ran.
* fix(provider): keep the demand hint across an abandoned stage
When a staged SSD read is abandoned because the shared-KV reservation failed,
the bridge retries the same receipt cold, so the completion still consults the
coordinator's repeat hint. abandonStaging no longer discards it; the capacity
error path, where the request ends, discards it explicitly. Regression: a
fleet-novel hint survives the abandon and the retried request reports
skipped_novel instead of writing unconditionally. Found by Codex review on #1207.
* chore(release): prepare v0.9.11 for the prefix-cache hit-rate set
ProviderCore.version and LatestProviderVersion at 0.9.11; the changelog's
prefix-cache section becomes the v0.9.11 release candidate above the unshipped
v0.9.10 candidate; the release runbook names 0.9.11 as the prepared version and
keeps the 0.9.10 rollout order, since the new inference-request field is
optional in both directions.
* fix(provider): make checkpoint publish-to-index atomic against removals
Every unlink (budget eviction, TTL sweep, corrupt drop, whole-root maintenance)
holds the store's removalLock, but performWrite indexed a freshly published
file outside it, so maintenance could unlink the file in that window and the
writer would insert a phantom entry and advertise READY for an absent
checkpoint. The writer now verifies the file under removalLock before
indexing it, and settles cache_entry_evicted with no ready endpoint otherwise.
Regression test reproduces the window through a debug-only hook. Found by
Codex review on #1207.
* docs(threat-model): reconcile the remaining 15-minute TTL statements 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.
* fix(registry): drop the retired tracker's demand index on reconfigure
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.
Structured-output requests can generate valid local cache usage but fail exact routing evidence: the provider service adds JSON response-format instructions, and Qwen/Harmony fold system turns, while the planner omitted these transformations. The old parity test tokenized the inbound body directly and therefore skipped the service behavior.
This PR mirrors the existing provider preparation in focused Rust modules and runs parity through the real, model-free
MLXOpenAIServiceentry point. It preserves the provider-bound request body, contract/artifact identity, exact receipt comparisons, replay checks and mismatch fences. New metrics supply matching prompt/saved-token denominators for provider usage, accepted lookups and selected-route terminals, plus bounded per-model rejection diagnostics.Before
After
Provider sampler teardown
A cancelled periodic sampler could already be queued on the bridge actor and emit after shutdown. A deterministic regression reproduces two events where only the opening event should remain. Periodic delivery now rechecks cancellation after the actor hop, and shutdown joins the cancelled sampler. Opening samples remain synchronous.
flowchart LR subgraph Before_sampler A[Timer checks cancellation] --> B[Actor hop queues sample] C[Shutdown cancels task without joining] --> D[Queued sample can emit after shutdown] B --> D end subgraph After_sampler E[Timer queues sample] --> F[Actor checks cancellation again] F -->|cancelled| G[No emission] H[Shutdown cancels and joins task] --> I[No sampler remains after return] endThe oversized-unsigned-number review suggestion is not applicable:
Planner::plan_synccallsrender::validate_request_inputbefore endpoint lowering, normalization or rendering. Values aboveInt64.maxuse the ordinary serving path without a cache plan. Explicit nestedresponse_format.json_schemaregression coverage includes9223372036854775809; no numeric coercion or eligibility expansion was added.Validation
DATABASE_URL); focused cache API/registry race tests pass. Added denominator, duplicate/parked-terminal, invalid/unreported, accepted-proof and privacy regression tests.The first Coordinator Tests run exposed a stale 98-vector inventory assertion after corpus expansion. Updated it to 126 plus explicit coverage of the four new cases per model, reproduced the failure, and reran the full Go race suite successfully before pushing 184a0e2. The current head includes the subsequent sampler fix and has been pushed for fresh CI.
The Threat Model Review job failed before analysis with an Anthropic
401 authentication_error/API key is invalid; this is not a completed security review.Rollout and limits
The cache prompt-preparation and coverage changes are coordinator-side. This PR also fixes provider slot-posture sampler teardown; that portion requires a provider release, alongside the separately merged disk-policy change. No MLX pin changes are required. No production deployment, release, config change or provider restart was performed.
The reproduced transformations explain a real false-fencing class; the historical aggregate mismatch counter does not establish how many live failures came from it. Existing fences are deliberately not cleared.
receiptandprompt_mismatchmetrics will distinguish future per-model reasons and equal-length hashes versus shorter/longer provider boundaries without recording hashes or prompt content. Coverage counters begin at deployment and cannot backfill historical percentages.More intermediate checkpoints and enabling resident-memory reuse by default remain separate performance qualifications: they must pass real-model output/cold parity, B=1/4/8 memory/TTFT and cancellation/shrink/refund checks before any release claim. This PR does not raise those defaults or relax trust checks.