Skip to content

Bump next from 15.3.9 to 15.5.14 in /web in the npm_and_yarn group across 1 directory - #3

Closed
dependabot[bot] wants to merge 1 commit into
masterfrom
dependabot/npm_and_yarn/web/npm_and_yarn-edc2f2fe5d
Closed

dependabot[bot] wants to merge 1 commit into
masterfrom
dependabot/npm_and_yarn/web/npm_and_yarn-edc2f2fe5d

Conversation

@dependabot

@dependabot dependabot Bot commented on behalf of github Mar 24, 2026

Copy link
Copy Markdown
Contributor

Bumps the npm_and_yarn group with 1 update in the /web directory: next.

Updates next from 15.3.9 to 15.5.14

Release notes

Sourced from next's releases.

v15.5.14

[!NOTE] This release is backporting bug fixes. It does not include all pending features/changes on canary.

Core Changes

  • feat(next/image): add lru disk cache and images.maximumDiskCacheSize (#91660)
  • Fix(pages-router): restore Content-Length and ETag for /_next/data/ JSON responses (#90304)

Credits

Huge thanks to @​styfle and @​lllomh for helping!

v15.5.13

[!NOTE] This release is backporting bug fixes. It does not include all pending features/changes on canary.

Core Changes

  • fix: patch http-proxy to prevent request smuggling in rewrites (See: CVE-2026-29057)

Credits

Huge thanks to @​ztanner for helping!

v15.5.12

[!NOTE] This release is backporting bug fixes. It does not include all pending features/changes on canary.

  • fix unlock in publish-native

This is a re-release of v15.5.11 applying the turbopack changes.

v15.5.11

[!NOTE] This release is backporting bug fixes. It does not include all pending features/changes on canary.

Core Changes

  • Tracing: Fix memory leak in span map (#85529)
  • fix: ensure LRU cache items have minimum size of 1 to prevent unbounded growth (#89134)
  • Turbopack: fix NFT tracing of sharp 0.34 (#82340)
  • Turbopack: support pattern into exports field (#82757)
  • NFT tracing fixes (#84155 and #85323)
  • Turbopack: validate CSS without computing all paths (#83810)
  • feat: implement LRU cache with invocation ID scoping for minimal mode response cache (#89129)

Credits

Huge thanks to @​timneutkens, @​mischnic, @​ztanner, and @​wyattjoh for helping!

Commits
  • d7b012d v15.5.14
  • 2b05251 [backport] feat(next/image): add lru disk cache and `images.maximumDiskCacheS...
  • f88cee9 Backport: Fix(pages-router): restore Content-Length and ETag for /_next/data/...
  • cfd5f53 v15.5.13
  • 15f2891 [backport]: fix: patch http-proxy to prevent request smuggling in rewrites (#...
  • d23f41c v15.5.12
  • 8e75765 fix unlock in publish-native
  • 6cef992 [backport] normalize CRLF line endings in jscodeshift tests on Windows (#8800...
  • 7a94645 Apply needs for publishRelease
  • bbfd4e3 v15.5.11
  • Additional commits viewable in compare view

Dependabot compatibility score

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


Dependabot commands and options

You can trigger Dependabot actions by commenting on this PR:

  • @dependabot rebase will rebase this PR
  • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
  • @dependabot show <dependency name> ignore conditions will show all of the ignore conditions of the specified dependency
  • @dependabot ignore <dependency name> major version will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself)
  • @dependabot ignore <dependency name> minor version will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself)
  • @dependabot ignore <dependency name> will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself)
  • @dependabot unignore <dependency name> will remove all of the ignore conditions of the specified dependency
  • @dependabot unignore <dependency name> <ignore condition> will remove the ignore condition of the specified dependency and ignore conditions
    You can disable automated security fix PRs for this repo from the Security Alerts page.

Bumps the npm_and_yarn group with 1 update in the /web directory: [next](https://github.com/vercel/next.js).


Updates `next` from 15.3.9 to 15.5.14
- [Release notes](https://github.com/vercel/next.js/releases)
- [Changelog](https://github.com/vercel/next.js/blob/canary/release.js)
- [Commits](vercel/next.js@v15.3.9...v15.5.14)

---
updated-dependencies:
- dependency-name: next
  dependency-version: 15.5.14
  dependency-type: direct:production
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
@dependabot dependabot Bot added dependencies Pull requests that update a dependency file javascript Pull requests that update javascript code labels Mar 24, 2026
@dependabot @github

dependabot Bot commented on behalf of github Mar 26, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #4.

@dependabot dependabot Bot closed this Mar 26, 2026
@dependabot
dependabot Bot deleted the dependabot/npm_and_yarn/web/npm_and_yarn-edc2f2fe5d branch March 26, 2026 16:02
anupsv added a commit that referenced this pull request May 29, 2026
…P2s)

Addresses 3 Codex P2 findings on the encrypted SSD KV cache (all only
matter when DARKBLOOM_PREFIX_CACHE is enabled, default off):

- Weight-hash binding (#1): the cache dir key and metadata modelHash were
  derived from the mutable modelId. A re-download under the same id with
  different weights left old encrypted KV that still passed the
  model/shape guards and could seed generation with stale-weight KV,
  corrupting output. Now bound to ModelInfo.weightHash when available
  (falls back to modelId) for both the directory and the MB-1 binding, so
  a weight change yields a fresh dir + binding and old KV is invalidated.

- Memory budget (#2): the engine block cache used a fixed maxBlocks=4096
  (4096*256 tokens of KV held OUTSIDE the scheduler kvBudget) -> tens to
  hundreds of GB on large models -> OOM even though admission thinks
  requests fit. maxBlocks is now derived from a memory budget
  (DARKBLOOM_PREFIX_CACHE_MAX_GB, default 1/8 physical RAM) and the
  model's per-token KV bytes; the cache disables itself if even one block
  would not fit.

- Disk eviction (#3): EncryptedPrefixCachePersistence wrote a file per
  evicted block and never cleaned up, growing until the volume filled
  (breaking later cache writes and model downloads). Added an LRU
  byte-budget sweep (DARKBLOOM_PREFIX_CACHE_DISK_GB, default 10 GB; 0 =
  unlimited), amortized so the directory scan does not run on every block.

Tests: prefixCacheBindingId / prefixCacheMaxBlocks helpers (weight binding
+ memory scaling/clamp); disk-budget eviction keeps usage within budget
while evicting oldest. 101 KV + 10 BatchScheduler tests green.
Gajesh2007 added a commit that referenced this pull request May 30, 2026
…nt prices, decimal active-params)

Resolves the four P2 Codex findings on this PR.

#2 (most important): the default platform fee was 5% (payments/pricing.go), so
providers actually received 95% despite the README/landing advertising "100%
during the public alpha". Set the alpha default to 0% so the code matches the
copy; per-account overrides via PUT /v1/admin/users/platform-fee still apply.
Updated the pricing tests. NOTE: the referral program pays out a share of the
platform fee, so referral payouts are dormant while the default fee is 0.

#1: /v1/pricing serves a public GET plus authenticated PUT/DELETE, but the new
public-CORS rule matched by path only and returned GET-only, no-credentials
headers for every method — which would reject a browser preflight for the
authenticated pricing mutations. Gate the wildcard CORS on the effective GET
method (preflight-aware via Access-Control-Request-Method) and add PUT to the
credentialed Allow-Methods. Extended the CORS test.

#3: the landing live price formatter and the earnings calculator's currency
reformatter rounded to 2 decimals, showing $0.015 -> $0.01 and $0.165 -> $0.17.
Allow up to 4 fraction digits so sub-cent model prices render exactly.

#4: the earnings calculator's active-parameter estimate ignored decimal counts
and only read id/architecture ("MoE"), under-counting GPT-OSS active params
(3 vs ~3.6) and inflating projected earnings after the live refresh. Parse the
model description and accept decimals (mirrored in the console earn page).
Gajesh2007 added a commit that referenced this pull request May 31, 2026
…log, persist platform pricing (#259)

* fix: correct model lineup + remove legacy catalog + persist pricing on restart

Addresses the stale model lineup (#257) and its backend root cause, plus a
critical billing bug found along the way.

Pricing (critical): the model_prices startup cleanup deleted the synthetic
"platform" account rows on every boot (platform != a users row), silently
reverting billing to the fallback $0.05/$0.20. Exclude "platform" and gate the
one-time cleanup behind a schema_migrations marker so it never runs again.

Backend: remove the legacy supported_models catalog -- the bare
GET/POST/DELETE /v1/admin/models endpoints, the store CRUD + table (now
DROP TABLE), the empty-registry fallbacks, the IsRetiredProviderModel filter,
and the dead seedModelCatalog. The manifest-backed model_registry is the single
source of truth. The SupportedModel struct stays as the in-memory shape derived
from the registry. The registry admin path and PUT /v1/admin/pricing are
untouched.

Frontend/docs: the landing pricing table and earnings calculator now source the
lineup live from /v1/models/catalog + /v1/pricing (static fallback = the two
served models). Public read endpoints (/v1/models/catalog, /v1/pricing) get
permissive CORS so the marketing site can read them cross-origin. README,
console-ui and benchmark scripts updated to Gemma 4 26B + GPT-OSS 20B; README
revenue split made consistent (100% during the public alpha).

Refs #257, #256

* fix: price Gemma 4 26B + GPT-OSS 20B at 50% of OpenRouter

The README, landing pricing table / earnings calculator, and the console models
comparison were showing the $0.05/$0.20 platform fallback. Set them to the
intended ~50%-of-OpenRouter rates:

- Gemma 4 26B: $0.03 in / $0.165 out  (OpenRouter google/gemma-4-26b-a4b-it: $0.06/$0.33)
- GPT-OSS 20B: $0.015 in / $0.07 out  (OpenRouter openai/gpt-oss-20b: $0.03/$0.14)

console baselinePricing now holds the real OpenRouter output rates (330000 /
140000 micro-USD) so the "50% lower" comparison reads correctly. Live platform
pricing must still be set in the coordinator (PUT /v1/admin/pricing or the
register-model workflow) to match these docs; values now persist across restarts
after the model_prices cleanup fix.

* chore(ui): drop OpenRouter branding from the pricing comparison

The price comparison shouldn't name OpenRouter as the baseline.

- console models page: baseline label "OpenRouter" -> "typical APIs"; the
  per-card line now reads "X% cheaper vs typical APIs"; footnote reworded to
  "typical hosted-API list rates".
- README pricing note: drop the OpenRouter naming and the OpenRouter
  slug-style references; keep our model ids (gemma-4-26b, gpt-oss-20b) and a
  generic "typical hosted-API list rates" framing.

Model ids shown are already our ids everywhere -- the /v1/models and
/v1/models/openrouter `id` field is our model id; the OpenRouter marketplace
`slug` is a separate, optional field. Left the API-compatibility references
(the /v1/models/openrouter feed docs + provider-schema code comments) intact
since they describe a real integration, not a pricing claim.

* fix: address Codex review (alpha 0% fee, GET-only public CORS, sub-cent prices, decimal active-params)

Resolves the four P2 Codex findings on this PR.

#2 (most important): the default platform fee was 5% (payments/pricing.go), so
providers actually received 95% despite the README/landing advertising "100%
during the public alpha". Set the alpha default to 0% so the code matches the
copy; per-account overrides via PUT /v1/admin/users/platform-fee still apply.
Updated the pricing tests. NOTE: the referral program pays out a share of the
platform fee, so referral payouts are dormant while the default fee is 0.

#1: /v1/pricing serves a public GET plus authenticated PUT/DELETE, but the new
public-CORS rule matched by path only and returned GET-only, no-credentials
headers for every method — which would reject a browser preflight for the
authenticated pricing mutations. Gate the wildcard CORS on the effective GET
method (preflight-aware via Access-Control-Request-Method) and add PUT to the
credentialed Allow-Methods. Extended the CORS test.

#3: the landing live price formatter and the earnings calculator's currency
reformatter rounded to 2 decimals, showing $0.015 -> $0.01 and $0.165 -> $0.17.
Allow up to 4 fraction digits so sub-cent model prices render exactly.

#4: the earnings calculator's active-parameter estimate ignored decimal counts
and only read id/architecture ("MoE"), under-counting GPT-OSS active params
(3 vs ~3.6) and inflating projected earnings after the live refresh. Parse the
model description and accept decimals (mirrored in the console earn page).

* test(e2e): fix payout-split & referral tests for 0% alpha default fee

The platform fee now defaults to 0% (providers keep 100% during the alpha), so TestIntegration_ProviderPayoutSplit (asserted a non-zero fee) and TestIntegration_ReferralRewardDistribution (rewards are funded from the platform fee) failed in CI. Give each test's consumer an explicit 5% per-account fee override (CreateUser with PlatformFeePercent) so they exercise the payout-split and referral mechanics end-to-end regardless of the global default; compute the split expectation via the *WithPercent helpers.
anupsv added a commit that referenced this pull request Jun 3, 2026
admissionRamFirstThenPromotesOnSecondUse validates Phase-1 RAM-first + 2nd-use promotion on real weights:
- req #1: capture writes NO SSD file (RAM-only)
- req #2: shared prefix RAM-hit triggers detached promotion -> SSD file appears
- req #3: after clearRAM, SSD restore produces valid output

Test uses 64-token boundary + ~70-token prompt for fast execution on M5.
Polls for file appearance (no fixed sleep).
Gajesh2007 added a commit that referenced this pull request Jun 8, 2026
…d flag-gated engine integration (#237)

* fix: APN reliability for MDM — network assertions, 90s timeout, late-arrival path

Provider (Swift):
- Add NetworkPowerAssertion: IOKit assertions for NetworkClientActive
  and BackgroundTask, acquired for the entire provider session
- Keeps the macOS network stack alive during sleep so APN pushes
  (courier.push.apple.com:5223) can be delivered for MDM commands
- No root required — uses IOPMAssertionCreateWithName API

Coordinator:
- Increase SecurityInfo timeout from 30s to 90s to cover Power Nap
  cycles (every ~15 minutes on AC power)
- Add OnLateSecurityInfoCallback: when a SecurityInfo webhook arrives
  after the 90s timeout, retroactively upgrade the self_signed provider
  to hardware trust instead of silently dropping the response
- Wire up the callback in main.go alongside the existing SetOnMDA
  callback, using the same ForEachProvider + serial match pattern

* docs(threat-model): update SE key from ephemeral to persistent keychain-backed

Reflects commit 4a0dae5e (PersistentEnclaveKey.swift). Key changes:

- TB-003 how_it_works: document Security framework persistent key, access group
  SLDQ2GJ6TL.io.darkbloom.provider, kSecAttrIsPermanent, and the
  errSecMissingEntitlement fallback behaviour on patched binaries
- TB-003 current_limitations: add two new limitations — team-scoped cross-binary
  keychain access, and silent ephemeral fallback that defers rejection to the
  coordinator rather than failing at the process boundary
- TB-009 how_it_works: rewrite SE key lifecycle section to reflect persistent
  identity across restarts; rotation now requires explicit keychain deletion
- T-013 (binary tampering) mitigations: add keychain access group enforcement as
  a fourth, implemented mitigation; update detection_hint
- T-033 (attestation replay) affected_files: add PersistentEnclaveKey.swift and
  AttestationSigner.swift; update mitigation wording
- T-035 (repudiation after rotation) description, mitigations, detection_hint:
  reframe rotation as an explicit operator action rather than automatic per
  launch; note kSecAttrIsPermanent as a positive mitigation; add open finding
  that coordinator cannot detect opportunistic keychain delete + re-registration

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(kv-cache): P0 — encrypted-at-rest KV cache primitives

First phase of SSD KV cache per docs/ssd-kv-cache-design.md. P0
delivers the cryptographic plumbing only; no integration with
BatchScheduler yet (that's P3).

Adds:

  - `KVCache/KeyWrappingService` — protocol abstracting wrap/unwrap
    of the KEK at rest. Two impls: `InMemoryKeyWrappingService`
    (tests) and `SecureEnclaveKeyWrappingService` (prod; ECIES
    via the existing persistent SE identity using
    `.eciesEncryptionStandardX963SHA256AESGCM`).

  - `KVCache/WrappedKEKStorage` — protocol abstracting the at-rest
    persistence layer. `KeychainWrappedKEKStorage` for prod (data-
    protection Keychain with `kSecAttrAccessibleAfterFirstUnlock-
    ThisDeviceOnly`), `InMemoryWrappedKEKStorage` for tests. Two
    layers (wrap + storage) so the entitlement-gated Keychain path
    is independently swappable from the SE-bound wrap path; both
    are individually exercised in tests.

  - `KVCache/KVCacheKEK` — actor that generates/persists the KEK
    on first run, holds the unwrapped key in actor-isolated state,
    and exposes per-file DEK wrap/unwrap with AAD binding.

  - `KVCache/EncryptedKVStore` — on-disk format codec for the
    `.darkbloom-kv` file. Layout: magic ‖ version ‖ flags ‖
    file_IV ‖ wrapped_DEK ‖ metadata-JSON ‖ encrypted chunks. Per-
    chunk nonces derived via HKDF-SHA256 from (DEK, file_IV,
    chunk_index) — no nonce reuse, no nonce storage. Metadata
    bytes are bound as AAD on every chunk seal AND on the DEK
    wrap, so tampering with any field surfaces as an authentication
    failure on the first chunk decrypt (and on DEK unwrap too,
    via belt-and-suspenders).

  - `Security/PersistentEnclaveKey+ECIES.swift` — adds
    `eciesEncrypt/eciesDecrypt` to the existing SE identity. The
    only modification to existing code is bumping `privateKey` from
    `private` to `internal` so the extension can reach it; the SE
    still owns the key material.

Threat model + format details: docs/ssd-kv-cache-design.md.

Tests:
  - KeyWrappingServiceTests — 7 cases: wrap roundtrip, unique
    ciphertexts per call, tamper detection (ct + tag), wrong key,
    malformed input, empty plaintext.
  - KVCacheKEKTests — 10 cases including SE-roundtrip
    + Keychain-storage roundtrip (both skip on missing
    entitlement, same pattern as existing PersistentEnclaveKey
    tests).
  - EncryptedKVStoreTests — 13 cases covering single/multi-chunk
    roundtrip, metadata-only read, tamper at magic / version /
    metadata / chunk-ct levels, truncation, wrong-KEK,
    chunk-count/size mismatch, and the HKDF nonce derivation
    determinism + diversity properties.

All 32 tests pass (2 skip on missing keychain-access-groups
entitlement in unsigned debug builds; same pattern as
PersistentEnclaveKeyTests).

* docs(kv-cache): add MB-1 model-binding invariant + read-path diagram

Corrects a misleading claim in the SSD KV cache design: §5.1
previously stated that `model_hash` in the metadata AAD "binds the
cache to a specific model file — reloading after a model upgrade fails
closed." That overstated what the crypto does.

The AES-GCM layer uses the file's OWN metadata (read back from disk) as
AAD on both the DEK unwrap and every chunk seal. This proves the bytes
weren't altered since write (tamper-evidence) but does NOT verify the
file belongs to the currently-loaded model: a structurally valid cache
file authored for model A decrypts cleanly while model B is loaded,
because both supply the file's embedded metadata as AAD. The cipher
cannot distinguish "right model" from "wrong model."

Adds:
  - §5.1 rewritten to spell out what the AAD does (tamper-evidence)
    vs does NOT (model-binding).
  - §8.1.1 new section defining invariant MB-1: PrefixCacheManager
    MUST check meta.modelHash == currentLoadedModelHash (and an
    architectural-shape guard for 12-char hash-prefix collisions)
    BEFORE unwrapping the DEK or decrypting. Includes the guard
    pseudocode and three P3 regression tests that must fail if the
    guard is removed.
  - §10 two new failure-mode rows (cross-model file, shape mismatch),
    each noting they're caught by MB-1, not the crypto.
  - §14 P3 phase now explicitly includes MB-1 + its rejection tests.
  - docs/ssd-kv-cache-model-binding.{mmd,svg} — read-path flowchart
    showing where MB-1 sits (between metadata-read and decrypt) and a
    callout box on what the AES-GCM layer does vs doesn't guarantee.
    Animated SVG (draws on in a browser; renders static when embedded).

No code change — P0 crypto is unaffected; MB-1 is an application-layer
guard that lands with the P3 BatchScheduler integration.

* test(kv-cache): prove rotating-cache snapshot/restore for sliding-window models

Empirically resolves the open correctness question gating prefix cache
for sliding-window models (GPT-OSS-20B, Gemma-4 26B-A4B MoE). Two
review agents disagreed on whether RotatingKVCache survives
snapshot -> restore -> resume; an adversarial lens claimed
temporalOrder() scrambles token order on restore + multi-token prefill.

These tests settle it from runtime behaviour. Each token t is encoded
as K=t, V=t+100 so the returned (keys,values) reveal exact token order;
any scrambling shows as a content mismatch vs a never-reset reference.

RotatingKVCacheRestoreTests (single-stream, the circular-buffer case):
  - multi-token prefill after restore matches reference (the adversary's
    exact scenario — wrap the buffer, snapshot, restore, prefill)
  - single-token decode after restore matches
  - pre-wrap restore matches
  - omitting metaState on restore DOES corrupt order — proving idx/offset
    serialization is load-bearing (the failure mode is real but only
    under misuse: state without metaState)

BatchRotatingExtractRoundtripTests (the batched path our design uses):
  - extract(row) isolates the correct row (no cross-row leakage)
  - extract(row) -> snapshot -> restore -> resume matches extract ->
    resume, for both multi-token and single-token continuations

Verdict: rotating-cache restore is CORRECT when state AND metaState are
restored together (the loadPromptCache contract). BatchRotatingKVCache
keeps a linear front-trimmed buffer (no circular wrap), and its
extract(idx) returns a single-stream RotatingKVCache with a fully
populated metaState (keep,maxCacheSize,step,offset,idx) — so our
design path (extract row -> single-stream -> serialize) sidesteps the
batched cache's own incomplete metaState. The metaState-sync
requirement is now a guarded invariant.

All 7 tests pass. No production code changed.

* docs(kv-cache): exact-checkpoint model + verified per-model support

Rewrites §4.4 and adds §4.5 to reflect what was verified against the
actual mlx-swift-lm source + the empirical rotating-restore tests.

Corrections to the earlier draft:
  - "slice the first N columns" was wrong: caches are 4-D
    [B,kvHeads,seq,headDim], sliced on axis 2, and the snapshot is taken
    by extractBatched(row) from the live batched caches — not naive
    slicing.
  - Arbitrary longest-prefix match (old O2) is DROPPED for the models we
    serve. Recurrent (Mamba/GatedDeltaNet) and sliding-window layers
    cannot be sliced to a shorter prefix, so reuse is EXACT-CHECKPOINT
    only: hit when the incoming prompt's prefix is byte-identical to a
    cached checkpoint boundary (e.g. end of a system prompt). Covers the
    dominant shared-system-prompt case.

New §4.5 — verified per-model cacheability (cache type detected at LOAD
time, never hardcoded; MoE is irrelevant — it only changes the FFN):
  - Qwen3.5 MoE / Qwen3-Next: hybrid MambaCache + KVCacheSimple →
    exact-checkpoint (recurrent state restorable at boundary, not
    sliceable).
  - Gemma-4 26B-A4B MoE: sliding RotatingKVCache(512) + full; only 15
    non-shared caches to snapshot (20 layers KV-share, auto-reconstructed).
  - GPT-OSS-20B MoE: sliding RotatingKVCache(128) + full; attention
    sinks are learned weights, not KV state → no snapshot impact.
  - Unsupported cache types (Chunked/Quantized/CacheList/DeepseekV4
    pooling) gated out at load time → cold path, no error.

Invariant MS-1 (metaState-sync): extracted caches must persist
metaState in sync with state (RotatingKVCache's idx/offset drive
temporalOrder). EncryptedKVStoreMetadata already has the metaState
field; regression-guarded by omittingMetaStateOnRestoreCorruptsOrder.

Also: status line updated (P0 landed + cacheability verified), O2 marked
dropped, per-request flow diagram shows exact-checkpoint + MB-1 guard,
§15 records what verification resolved + adds [Q8].

* feat(kv-cache): P1 — PrefixCacheRAM (in-process LRU RAM tier)

The decrypted RAM tier of the SSD KV cache (design §4.1). Holds
recently-used prefix KV snapshots as live [any KVCache] (one extracted
single-stream cache per layer) so a repeat request whose prompt prefix
is byte-identical to a cached checkpoint hits RAM instead of decrypting
from SSD or running a cold prefill.

Scope: RAM only — no SSD, no encryption, no BatchScheduler wiring (those
are P2-P4). Plain final class (non-Sendable: holds MLXArrays), to be
owned by the PrefixCacheManager actor in P3; tests run single-threaded.

Design points:
  - Keyed by (modelHash, prefixDigest). modelHash is the locally-computed
    weight hash, so a lookup for model B structurally cannot return model
    A's entry — the RAM-tier half of MB-1.
  - get() returns copy() of each stored cache (upstream's blessed clone,
    state.map { $0[.ellipsis] }), so a consumer can seed a batch row and
    decode into the returned caches without corrupting the stored
    snapshot. This is the load-bearing invariant.
  - LRU eviction by a monotonic use-counter (not wall-clock — keeps it
    deterministic, avoids Date.now()), bounded by BOTH an entry count and
    a byte budget (measured via MLXArray.nbytes over each cache's state).
  - clear(modelHash:) for model unload; entriesForFlush(modelHash:)
    returns copies for the P4 SSD-flush path without removing.

Tests (9, all pass):
  - hit/miss + tokenCount round-trip
  - MB-1: lookup keyed by modelHash (no cross-model bleed)
  - distinct digests are distinct entries
  - getReturnsIndependentCopy: mutate a returned copy (append 5 tokens),
    assert the stored snapshot stays at its original offset — proves
    copy()-on-get protects the snapshot
  - LRU eviction by entry count (recently-used survives, LRU evicted)
  - eviction by byte budget
  - clear(modelHash:) drops only that model
  - put replaces an existing key without leaking byte accounting
  - entriesForFlush returns per-model copies without removing

* feat(kv-cache): P2 — PrefixDigest + JSON-backed PrefixCacheIndex

The exact-checkpoint lookup layer (design §4.4, §7; [Q3] resolved to
JSON, not SQLite). No SSD I/O of cache payloads and no BatchScheduler
wiring yet — that's P3 (held for review).

PrefixDigest — checkpoint keys:
  - Checkpoints at the O9 boundaries (256/512/1024/2048/4096/8192).
  - For a prompt's token array, computes SHA-256 of the first c tokens
    at each checkpoint c <= count, in a SINGLE pass by snapshotting the
    rolling hash at each boundary. Proven (checkpointDigestEquals-
    IndependentPrefixHash) to equal an independent hash of the first c
    tokens — so a longer cached prefix is findable from a shorter shared
    one, and two prompts sharing a system prompt agree on every
    checkpoint digest within the shared region.
  - Tokens hashed as little-endian Int64 after a domain-separation tag;
    stable across machines, can't collide with other SHA uses.

PrefixCacheIndex — JSON-persisted, in-RAM:
  - Maps (modelHash, digestHex) -> {relativePath, tokenCount, fileBytes,
    createdAt, lastHitAt, hitCount}.
  - findLongestCheckpoint(modelHash:tokens:): computes the prompt's
    checkpoint digests and returns the entry for the LONGEST checkpoint
    present for that model — the exact-checkpoint match. Partitioned by
    modelHash (MB-1: model B can't match model A's entries).
  - record / touch / remove / removeModel / entriesLRUFirst (eviction
    order for P6) / rebuild(from:) (recover when JSON missing/corrupt).
  - Atomic JSON write-back on save(); dirty-tracked. A corrupt index
    file is treated as empty (logged), not fatal — SSD files are self-
    describing and the index rebuilds from them.
  - Timestamps passed in by the caller (now: Int64), keeping the type
    deterministic and clock-free for tests.

Tests (16, all pass): digest determinism + prefix-sensitivity,
single-pass == independent-hash equivalence, shared-prefix agreement,
boundary/token-count handling; index exact + longest-checkpoint match,
divergent-prefix miss, MB-1 model scoping, touch metadata, remove/
removeModel, LRU ordering, JSON persistence round-trip, corrupt-file
recovery, rebuild.

* fix(kv-cache): address P0-P2 adversarial review findings

A 5-dimension adversarial review (findings verified by refutation)
found 0 critical, 0 high, 6 medium, 9 low. Fixes for the cheap/
clearly-correct ones; the two genuinely-P3 items (PCR-1 sending-returns
across the actor boundary, XC-3 MB-1 guard + tests) are deferred to P3
where the PrefixCacheManager actor lands. KV-3 (redundant magic field)
is won't-fix.

Crypto / format:
  - KV-1, XC-2: fix 3-way doc drift on per-chunk nonce derivation. The
    code uses HKDF-Expand-only (Extract skipped — DEK is already a
    uniform 256-bit key, RFC 5869 §3.3) with file_IV folded into `info`,
    NOT file_IV as an HKDF salt. Header + byte-layout comments now match
    the implementation and the function doc. (No crypto change — write
    and read already shared deriveChunkNonce, so round-trip was correct.)
  - KV-2: fsync the containing directory (F_FULLFSYNC, fsync fallback)
    after the atomic rename in EncryptedKVStore.write, so a just-renamed
    cache file is durable across power loss. Best-effort: a miss only
    costs a cold prefill.
  - KV-4: SecureEnclaveKeyWrappingService.unwrap classifies auth
    failures by structured OSStatus (errSecDecode/errSecAuthFailed/
    errSecParam) instead of substring-matching a locale-dependent
    error string.

RAM tier:
  - PCR-2: PrefixCacheRAM.put refuses (and counts) an entry whose own
    size exceeds maxBytes instead of storing-then-self-evicting into a
    silent no-op. put now returns Bool (@discardableResult).
  - PCR-3: byte accounting uses innerState() (physical, step-allocated
    buffers) instead of state() (trimmed logical view), so maxBytes
    bounds true resident RAM.

Index / digest:
  - PCI-1: PrefixCacheIndex.save writes via Data.write(.atomic) directly
    (Foundation does aux-file + rename) instead of a manual tmp-<uuid> +
    replaceItemAt, which could leak a UUID-named orphan on a crash
    between write and replace with no sweep.
  - PCI-3, XC-4: entriesLRUFirst adds a deterministic secondary key
    (digestHex) so equal-lastHitAt entries order stably.
  - PD-1: PrefixDigest.checkpoints dedups boundaries so a duplicated
    caller-supplied boundary isn't double-emitted.

Tests:
  - XC-1: new batchRotatingExtractMatchesIndependentSingleStreamReference
    — builds the reference WITHOUT extract() (an independent single-
    stream RotatingKVCache fed row 0's tokens) and compares resume,
    proving extract() is semantically equivalent, not merely idempotent.
  - new: ramRejectsEntryLargerThanByteBudget (PCR-2),
    indexLRUTieBreakIsDeterministic (PCI-3).
  - ramPutReplacesExistingKeyWithoutLeakingBytes rewritten to assert the
    real no-leak invariant under physical byte accounting (PCR-3).

All KV cache tests pass (46 in the affected set; full P0-P2 suite green).

* feat(kv-cache): P3-foundation — KVCacheSerializer ([KVCache] <-> bytes)

The missing primitive the SSD tier needs: convert an extracted
[any KVCache] (one single-stream cache per layer, from
BatchedCache.extractBatched) into raw byte chunks + a layout
descriptor, and back. Chunks feed straight into EncryptedKVStore so
plaintext KV NEVER touches disk — we deliberately do NOT route through
upstream savePromptCache (it writes a plaintext .safetensors and its
reconstruction helper is private). Byte round-trip via
MLXArray.asData(.copy) / MLXArray(data:shape:dtype:) is dtype-agnostic,
so bf16 round-trips exactly.

Reconstruction uses each cache type's PUBLIC state + metaState setters.

Scope — SSD-serializable: KVCacheSimple + RotatingKVCache (the
attention + sliding-window caches Gemma-4 26B-A4B and GPT-OSS-20B use,
plus all pure-attention models).

NOT SSD-serializable: MambaCache / ArraysCache (recurrent). Their
metaState setter deliberately traps (assertionFailure) and the real
reconstruction path (ArraysCache.restoreFromMetaState) is `internal` to
MLXLMCommon — unreachable from ProviderCore. Rebuilding recurrent state
via the partial public API can't be verified correct without running
the model, and a wrong recurrent state silently emits garbage tokens,
so the serializer REFUSES recurrent caches (and any hybrid stack
containing one) rather than guess. Consequence: hybrid models
(Qwen3.5/Next) get the RAM tier only — which uses copy(), no
serialization — not SSD persistence. SSD-for-Mamba is a documented
follow-up gated on upstream exposing a public reconstruction.
(This constraint was found by the test suite: an earlier attempt to set
MambaCache.metaState tripped the upstream assertionFailure — caught
before it could become a latent bug.)

Also unsupported: ChunkedKVCache, QuantizedKVCache, CacheList. serialize
throws on any unsupported layer; the P3 manager's load-time capability
gate keeps them out first.

Tests (7, all pass): KVCacheSimple state round-trip; bf16 exact
fidelity; resume-equivalence for KVCacheSimple AND wrapped
RotatingKVCache (reconstructed cache continues generation identically);
Mamba rejected (RAM-only); Chunked rejected + attention/sliding stack
accepted; full end-to-end serialize -> EncryptedKVStore.write (layout in
metaState) -> read -> deserialize.

* feat(kv-cache): P3 — PrefixCacheManager orchestration actor

The three-tier orchestration layer (design §4), one manager per loaded
model. Standalone and fully tested; the BatchScheduler wiring is the
NEXT step and is deliberately not in this commit (review checkpoint
before touching live inference).

Closes the two review findings deferred from P0-P2:
  - XC-3: the MB-1 model-binding guard now EXISTS and is enforced on the
    SSD load path — readMetadataOnly first, verify metadata.modelHash ==
    binding.modelHash AND the architectural shape (numLayers/kvHeads/
    headDim) BEFORE unwrap/decrypt, drop the index entry + count the
    mismatch on failure. This catches a wrong-model file the crypto
    cannot (a valid file from another model decrypts cleanly because the
    AAD is its own metadata).
  - PCR-1: the non-Sendable [any KVCache] crosses the actor boundary via
    documented @unchecked Sendable transfer types (PrefixLookupResult
    out, SendableKVCaches in). `sending` is unusable here because values
    produced through the actor-isolated PrefixCacheRAM are inferred into
    the actor's region; the boxes are sound because the caches are always
    fresh (RAM hits copy(), SSD hits freshly deserialized) and single-
    owner — matching the codebase's existing UncheckedSendable idiom.

Behavior:
  - lookup(tokens:): exact-checkpoint match, RAM tier (longest checkpoint
    first) then SSD tier (MB-1-guarded read -> deserialize -> promote to
    RAM). Returns fresh caller-owned caches + tokenCount + tier.
  - store(tokens:checkpointLength:caches:): write-back to RAM only.
  - flushToSSD(): serialize RAM entries not already on SSD -> encrypt via
    EncryptedKVStore (layout JSON in metaState) -> record + save index.
    Skips non-serializable stacks defensively.
  - capability gate: ssdEnabled requires index+kek+cacheDir; a model
    whose caches aren't KVCacheSerializer-supported (Mamba hybrids) runs
    RAM-only. Timestamps injected (now:) for determinism.

Tests (8): RAM hit + longest-checkpoint-wins; full SSD round-trip
(store -> flush -> clearRAM -> SSD hit -> promote-to-RAM); restart
persistence across manager instances; MB-1 rejects a cross-model file
even when the index points B at A's file (the symlink/collision case) —
asserts modelMismatches counted; SSD-disabled-without-backing; miss on
sub-checkpoint prompt.

Full KV cache suite green: 98 tests.

* feat(kv-cache): P3 wiring (1/2) — EncryptedPrefixCachePersistence

The encrypted SSD backend for the engine's in-GPU block prefix cache
(Path 2). Conforms to MLXLMCommon.PrefixCachePersistence (added to the
submodule): the engine calls saveBlock on LRU eviction and loadBlock on
a block-hash miss, so evicted blocks are AES-GCM-encrypted to disk
(surviving eviction AND restart) instead of dropped + re-prefilled.

Reuses our crypto primitives — EncryptedKVStore + KVCacheSerializer +
the KEK — keyed by the engine's content-addressed block hash. (Note:
this block-level integration supersedes the checkpoint-level
PrefixCacheManager/Index/Digest/RAM for the live path — the engine
already owns lookup/LRU/indexing; those layers remain for any non-engine
use but aren't on this path.)

EncryptedKVStore: refactored the body-build / header-assemble / atomic-
write / chunk-decrypt into shared sync helpers, and added writeSync /
readSync taking a SymmetricKey KEK directly. The engine step loop is
synchronous and can't await the KVCacheKEK actor, so the persistence
holds an already-unwrapped KEK and does synchronous crypto + I/O. The
async write/read now delegate to the same helpers — format is identical
(the 15 EncryptedKVStore tests still pass).

EncryptedPrefixCachePersistence: sync saveBlock/loadBlock; MB-1 guard on
load (metadata.modelHash + shape before decrypt); KVCacheSimple-only
(matches the engine's prefix cache); best-effort save (never throws).

SECURITY (TB-007): this adds encryption-at-rest (disk-theft defense) but
does NOT close the in-process cross-tenant sharing / TTFT side-channel —
the provider can't see tenant identity. Default-off flag + explicit
threat-model sign-off required (the BatchScheduler flag is the next
commit). Documented in the type header.

Tests (5): save/load round-trip; on-disk bytes are encrypted (DBKV magic
present, no plaintext); MB-1 rejects wrong model; wrong KEK -> nil (no
crash); and END-TO-END through the real upstream PrefixCache — maxBlocks=1
forces eviction (saveBlock) then fetch reloads from encrypted SSD
(loadBlock). EncryptedKVStore async suite still green.

* feat(kv-cache): P3 wiring (2/2) — default-off BatchScheduler flag

Wires the encrypted prefix cache into live inference behind the
DARKBLOOM_PREFIX_CACHE env flag (default OFF — unset = exact current
behavior, prefixCache nil).

When set, makeBatchedEngine builds an EncryptedPrefixCachePersistence
and passes it as the engine's Scheduler.prefixCache, so the engine's
in-GPU block cache is backed by AES-GCM-encrypted SSD storage (evicted
blocks persist + survive restart; fetch misses reload from disk).

Guards before enabling:
  - architecture must expose numLayers/kvHeads/headDim (from the
    config.json already parsed in snapshotContainer) — else disabled.
  - KEK must be Secure-Enclave-wrapped + Keychain-persisted (so files
    survive restart). If unavailable (no SE / entitlement) we REFUSE to
    enable rather than fall back to an ephemeral key that would silently
    break restart-reuse.
  - per-model dir keyed by sha256(modelId)[:12] under the OS cache dir.

SECURITY (TB-007): enabling re-opens the cross-tenant data-leak / TTFT
side-channel that was deliberately gated — the provider cannot see
tenant identity, so the cache is shared across consumers. This commit
adds encryption-at-rest (disk-theft defense) but does NOT close the
in-process channel. Ships ONLY behind the default-off flag with an
explicit operator threat-model sign-off. Loud warning logged on enable.

modelId is used as the model-binding key; weight-hash binding (to
invalidate on a weight change under the same id) is a documented
follow-up.

Full KV cache suite green: 103 tests. End-to-end live behavior on real
hardware still needs the 2-Mac smoke test (cannot run in CI).

* chore(submodule): bump mlx-swift-lm to PrefixCachePersistence hook

Points libs/mlx-swift-lm at the additive PrefixCachePersistence change
(branch feat/encrypted-prefix-cache-persistence, 6f79f04) that the
encrypted prefix-cache wiring depends on. The submodule change is
default-nil (no behavior change unless darkbloom passes a persistence
backend), so this bump is safe with the flag off.

NOTE: the submodule change lives on a branch, not yet merged to the
submodule's main. The corresponding submodule PR must merge before this
parent change can land on master.

* test(kv-cache): live model-backed prefix-cache integration test

Opt-in integration test (gated by DARKBLOOM_MODEL_TEST_DIR, so CI /
plain `swift test` skip it) that drives the REAL engine with a REAL
model through our encrypted prefix-cache path. Builds the BatchedEngine
with an EncryptedPrefixCachePersistence (injected in-memory KEK), then:

  - generates a prompt with cache OFF (reference),
  - generates the same prompt twice with cache ON,
  - asserts the cache-ON greedy (temp 0) output is byte-IDENTICAL to the
    reference — i.e. prefix KV reuse does not corrupt generation,
  - asserts the cache engaged (hits > 0, tokens_saved > 0).

Validated on a real M5 Max with mlx-community/Llama-3.2-1B-Instruct-bf16:
output matched the uncached reference exactly and the cache saved 256
prefill tokens (one full block) on the repeat request.

* test(kv-cache): transient-SE harness + makeTransient for unsigned SE validation

Adds PersistentEnclaveKey.makeTransient() — a non-persisted Secure
Enclave key (kSecAttrIsPermanent=false, no keychain access group). Since
it never touches a keychain access group it needs NO
keychain-access-groups entitlement, so SE crypto (sign / ECIES) can be
exercised on real hardware from unsigned builds. (loadOrCreate, which
persists under the team access group, still requires a signed build —
that's the same SecItem path the production attestation key uses.)

Adds kv-se-harness — a TEST-ONLY standalone executable (not a product,
not shipped) that uses a transient SE key to validate the encrypted
KV-cache key path on real hardware without code signing:
  - ECIES wrap (public) + unwrap (SE-private) via the new
    PersistentEnclaveKey+ECIES / SecureEnclaveKeyWrappingService code,
  - KVCacheKEK generate -> SE-wrap -> store -> read -> SE-unwrap,
    recovering identical key material,
  - DEK wrap/unwrap under the recovered KEK,
  - tamper rejection (flipped wrapped-DEK byte fails auth).

Validated on a real M5 Max (unsigned): all five checks PASS, closing the
SE-crypto validation gap. The only piece still requiring a signed build
is keychain PERSISTENCE of the key (production-proven attestation path),
not any code this branch introduced.

* security(kv-cache): #if DEBUG-gate makeTransient (threat-review hardening)

Addresses the threat-model-review finding that PersistentEnclaveKey.
makeTransient() — the entitlement-free transient-SE-key factory — was
public and ungated, so it shipped in release builds.

Independent verification confirmed the factual claim (public, no guard)
but found the exploit risk overstated: only the test-only kv-se-harness
calls it (production uses loadOrCreate), and a transient key can't pass
coordinator-side attestation anyway (SIP/SecureBoot/MDA gates). Still,
compiling a test-only entitlement-free SE-key path out of release builds
is correct defense-in-depth, so it's now #if DEBUG.

Verified: debug build (harness) still compiles with makeTransient;
release ProviderCore compiles without it (nothing else references it).

* fix(kv-cache): bind SSD prefix loads to requested hash; create-safe atomic write

Address Codex review on PR #237 (3 inline findings).

- EncryptedKVStore.atomicWrite: replace the replace-only
  FileManager.replaceItemAt with an atomic create-or-replace (rename when
  the destination is absent — the first-write case — replaceItemAt only
  to swap an existing file). replaceItemAt happens to create on
  macOS/APFS (the round-trip tests prove first writes already worked, so
  the cache was NOT nonfunctional), but the rename form is portable and
  unambiguous.
- EncryptedPrefixCachePersistence.loadBlock and
  PrefixCacheManager.loadFromSSD: each verified the file's model+shape
  (MB-1) but not that its tokenPrefixHash equals the REQUESTED prefix.
  Since the file authenticates under its own metadata, a renamed/swapped
  same-model file or a stale/corrupt index entry would decrypt cleanly
  and return KV for a DIFFERENT prompt prefix → wrong generations. Add a
  prefix-hash equality guard to both paths (new prefixHashMismatches
  stat); reject and cold-prefill on mismatch.

Regression tests: writeCreatesBrandNewFile (first write must CREATE the
file), loadBlockRefusesFileHoldingDifferentPrefix, and
managerRejectsStaleIndexPrefixHashMismatch. 91 KV tests green.

* fix(kv-cache): bind KV shape to model, validate metaState, harden SSD path

Follow-up review (adversarial multi-lens sweep) of the encrypted KV cache
surface for remaining instances of the 'serve an on-disk file/index entry
without verifying it is the RIGHT one' class. Three fixes + the submodule
bump (libs/mlx-swift-lm: cachedTokens length-accounting fix).

- Shape binding (G1): the load-path MB-1 guard only compared metadata
  *integers* (numLayers/kvHeads/headDim); the tensors that seed attention
  come from layout.layers[].arrays[].shape, never cross-checked. A
  self-consistent file whose layout disagrees with the live model (weights
  changed under the same id, or a foreign file) would deserialize and seed
  wrong-shaped KV → corruption or an MLX trap. Add
  KVCacheSerializer.validateLayout(_:kvHeads:headDim:) and call it in both
  loadFromSSD and loadBlock before deserialize (binds dims 1 and 3).

- metaState validation (G2): reconstruct() handed unvalidated strings to
  the engine's KVCacheSimple/RotatingKVCache metaState setters, which
  fatalError on bad count / non-integer fields / maxSize=='None'. A single
  malformed (stale/foreign) RotatingKVCache file would crash the whole
  provider — uncatchable by the load-path do/catch. Pre-validate and throw
  (recoverable cold miss) instead.

- SSD path safety (B): loadFromSSD joined the unauthenticated index's
  entry.relativePath to cacheDir (a '../' could escape the per-model dir,
  an out-of-sandbox read). Reconstruct the path deterministically from the
  trusted binding + index digest (matching how flushToSSD writes it and
  the content-addressed engine tier); the stored relativePath is ignored.

- G3 (loadBlock prefix-hash check): documented that it detects on-disk
  rename; the substantive content binding is the GCM AAD plus the new
  shape validation.

Tests: validateLayout accept/reject, deserialize rejects malformed
metaState (3 cases) instead of crashing, manager ignores a malicious
relativePath; MB-1 and prefix-hash manager tests rewritten to exercise
the residual threats (model-dir-prefix collision; same-dir on-disk swap)
now that the path is reconstructed. 97 KV tests + 11 submodule tests green.

* fix(kv-cache): close two residual uncatchable-crash gaps in deserialize

A second review pass (crypto-security-auditor) on the G1/G2 fixes found
two more instances of the same uncatchable-crash class still reachable in
the foreign/tampered-file threat model — both defeat G2's invariant that a
malformed file becomes a recoverable cold miss, never a process crash:

- State-setter array count: validateMetaState checks metaState but NOT the
  per-layer state-array count. reconstruct's "c.state = arrays" runs the
  KVCacheSimple/RotatingKVCache state setter, which fatalErrors unless
  given exactly 2 arrays. deserialize only checked the AGGREGATE chunk
  count, so a foreign file with 1 or 3 arrays in a layer crashed the
  provider. Now require 0 or 2 arrays per layer (throw otherwise).

- MLXArray init precondition: validateLayout binds dims [1]/[3] but not
  that shape.product*dtype.size == chunk byte length, nor that dims are
  non-negative / non-overflowing. MLXArray(data:shape:dtype:) hard-traps
  (shapePrecondition) on a mismatch, and shape.reduce(1,*) traps on a
  negative dim or Int overflow. deserialize now computes an overflow-safe
  expected byte count and rejects any descriptor whose chunk length
  disagrees, before constructing the MLXArray.

Both throw KVCacheSerializerError.reconstructionFailed -> cold miss.
Tests: deserializeRejects{WrongStateArrayCount,ShapeByteLengthMismatch,
NegativeDimShape} -- each would crash the test process pre-fix. 100 KV
tests green.

* docs(kv-cache): add as-built How-It-Works reference

New docs/ssd-kv-cache.md documents the encrypted SSD KV cache as it
actually runs: the two tiers (wired engine block cache + the built-but-
unwired checkpoint manager), the store/evict/load data path, the DBKV file
format, the SE-wrapped-KEK / per-file-DEK envelope, KVCacheSerializer, the
DARKBLOOM_PREFIX_CACHE flag + prerequisites, the load-path verification
ladder (model/shape/prefix-hash/path/tensor-shape/decode-safety, all fail
closed to a cold miss), exact-checkpoint matching, failure modes, on-disk
layout, the TB-007 security model, and a code/test map. Cross-linked from
the design doc, which remains the rationale/threat-model/phased plan.

* fix(kv-cache): bind cache to weight hash, bound memory + disk (Codex P2s)

Addresses 3 Codex P2 findings on the encrypted SSD KV cache (all only
matter when DARKBLOOM_PREFIX_CACHE is enabled, default off):

- Weight-hash binding (#1): the cache dir key and metadata modelHash were
  derived from the mutable modelId. A re-download under the same id with
  different weights left old encrypted KV that still passed the
  model/shape guards and could seed generation with stale-weight KV,
  corrupting output. Now bound to ModelInfo.weightHash when available
  (falls back to modelId) for both the directory and the MB-1 binding, so
  a weight change yields a fresh dir + binding and old KV is invalidated.

- Memory budget (#2): the engine block cache used a fixed maxBlocks=4096
  (4096*256 tokens of KV held OUTSIDE the scheduler kvBudget) -> tens to
  hundreds of GB on large models -> OOM even though admission thinks
  requests fit. maxBlocks is now derived from a memory budget
  (DARKBLOOM_PREFIX_CACHE_MAX_GB, default 1/8 physical RAM) and the
  model's per-token KV bytes; the cache disables itself if even one block
  would not fit.

- Disk eviction (#3): EncryptedPrefixCachePersistence wrote a file per
  evicted block and never cleaned up, growing until the volume filled
  (breaking later cache writes and model downloads). Added an LRU
  byte-budget sweep (DARKBLOOM_PREFIX_CACHE_DISK_GB, default 10 GB; 0 =
  unlimited), amortized so the directory scan does not run on every block.

Tests: prefixCacheBindingId / prefixCacheMaxBlocks helpers (weight binding
+ memory scaling/clamp); disk-budget eviction keeps usage within budget
while evicting oldest. 101 KV + 10 BatchScheduler tests green.

* docs(kv-cache): correct threat-model SE-key entry + sync how-it-works doc

- threat-model.yaml (#4): the SE-key block was stale relative to the code
  it documents as the KV-cache security sign-off record. Corrected the
  label v1 -> v2 (current defaultLabel; legacy v1 is migrated on load) and
  documented that the same persistent SE key now performs ECIES
  unwrap/decryption for the KV-cache KEK, not only ECDSA signing -- so the
  decryption capability granted to entitled same-team binaries and the
  actual keychain item to audit are both visible.

- ssd-kv-cache.md: synced to the weight-hash binding, memory-bounded
  maxBlocks, and disk-eviction behavior, plus the two new budget env vars
  (DARKBLOOM_PREFIX_CACHE_MAX_GB / _DISK_GB).

* fix(kv-cache): default disk budget to 50% of free volume space

The on-disk prefix-cache budget defaulted to a flat 10 GB regardless of
the actual disk. Make the default 50% of the cache volume's free capacity,
measured live at model load (volumeAvailableCapacityForImportantUsage,
falling back to raw available capacity). The DARKBLOOM_PREFIX_CACHE_DISK_GB
env override still wins (0 = unlimited); a near-full disk yields a tiny
positive budget (evict-almost-everything) rather than the env's
0-means-unlimited; if free space can't be read, falls back to 10 GB.

Split into a pure, testable policy (resolveDiskBudget) + a free-space
probe (volumeFreeBytes). Tests: 50%-of-free, env override, env-0-unlimited,
near-full -> tiny positive, unknown -> 10 GB fallback, and a live
free-capacity read. 113 KV + BatchScheduler tests green.

* fix(kv-cache): harden budget env parsing, stop orphaning dirs, skip oversized writes

Address the adversarial review of the budget/binding changes.

- Env crash (medium, x2): prefixCacheBudgetBytes (MAX_GB) and
  resolveDiskBudget (DISK_GB) did Int(gb * 2^30) guarded only by a sign
  check. Double("inf")/"1e400"/huge values pass and Int(Double) TRAPS on
  non-finite/overflow (uncatchable) -> provider crash on model load. MAX_GB
  is read unconditionally to size maxBlocks, so it crashed even with the
  cache OFF. Now reject non-finite / out-of-range values back to the
  default. Extracted a pure resolveMemoryBudget mirror for testability.

- Orphaned directories (low): keying the cache dir by weightHash (the prior
  weight-binding fix) created a fresh, never-swept directory on every
  re-download. Key the dir by the MODEL id instead (stable) and keep the
  MB-1 binding on the weight hash: stale-weight files are rejected AND
  deleted by loadBlock on access and aged out by the sweep — invalidation
  without leaking dirs.

- Write-then-delete treadmill (low): when a single block exceeds the disk
  budget (tiny env value / near-full disk) saveBlock wrote then immediately
  evicted it. Skip the write up front instead.

Tests: resolveMemoryBudget + resolveDiskBudget now cover inf/NaN/overflow
(would have trapped pre-fix); write-skip-when-oversized; delete-on-MB1-
mismatch. Docs: corrected the sample log line, the dir-key scheme, and an
explicit per-model (not global), measured-once disk-bounding note. 116 KV +
BatchScheduler tests green.

* feat(kv-cache): hybrid-model foundation — strategy classifier + window boundaries + mixed round-trip proof

Groundwork to make the SSD KV cache benefit Gemma-4 and GPT-OSS (hybrid
sliding-window models), which the engine block tier excludes because it is
KVCacheSimple-only. ZERO runtime effect — nothing here is wired into the
serve path yet; it is the verified base for the wiring to come.

Design: docs/ssd-kv-cache-hybrid-models.md (why block-caching a rotating
window is unsound; the whole-cache exact-checkpoint approach via the
already-built PrefixCacheManager; the window>=checkpoint constraint;
isolation guarantees; the numeric-equivalence verification gate).

- PrefixCacheStrategy.classify([KVCache]) → .engine | .checkpoint | .none:
  the single point that keeps the two tiers mutually exclusive. all-simple
  → engine (today's path, unchanged); simple+rotating → checkpoint
  (Gemma-4/GPT-OSS); any Mamba/recurrent/unsupported → none (Qwen stays
  uncached). Named PrefixCacheStrategy to avoid the existing
  PrefixCacheTier telemetry enum.
- PrefixDigest.checkpoints(forSlidingWindow:): derive checkpoint boundaries
  ≤ the sliding window so a snapshot never claims tokens the window has
  discarded. Gemma-4(512)→[256,512]; GPT-OSS(128)→[64,128]; unknown→defaults.
- Foundational correctness proof: a mixed [Rotating,Rotating,Simple,
  Rotating,Simple] cache survives serialize→encrypt→decrypt→deserialize→
  restore and matches a never-snapshotted reference layer-for-layer after a
  continue-prefill (serializerMixedHybridLayersEndToEndThroughEncryptedStore).

16 new unit tests; 114 KV tests green. No engine/scheduler change.

* feat(kv-cache): minSlidingWindow helper + verified hybrid integration map

Step 1 (zero-runtime) continued, plus the source-audited integration plan.

- PrefixCacheStrategy.minSlidingWindow([KVCache]): smallest RotatingKVCache
  window across a model's layers (read from live cache instances, since
  ModelArchitecture has no sliding-window integer). Feeds
  PrefixDigest.checkpoints(forSlidingWindow:) so checkpoint boundaries never
  exceed the window (Gemma-4 512 -> [256,512]; GPT-OSS 128 -> [64,128]).
- Tests: minSlidingWindow (min across layers, ignores non-rotating, nil when
  none) + classify→boundaries end-to-end for Gemma-4/GPT-OSS shapes.
- docs/ssd-kv-cache-hybrid-models.md §7: the verified integration map from a
  submodule source audit — capture point (before generate()'s in-init decode
  slides the window), the missing mixed-cache restore path (doExternalPrefill
  + BatchKVCache.merge are KVCacheSimple-only; a new B==1 restore path is
  required, NOT relaxing the engine guard), the cacheFactories restore
  scaffold, async/sync boundary handling, decisions taken, and the
  risk→catching-test matrix.

116 KV tests green. No engine/scheduler change yet (steps 2-5 pending).

* test(kv-cache): prove fromSingleRow restore + bump submodule

- Bump libs/mlx-swift-lm to f00c1a7 (BatchRotatingKVCache.fromSingleRow).
- BatchRotatingExtractRoundtripTests: fromSingleRow resume matches an
  independent single-stream reference (wrapped + pre-wrap) — the
  restore-side correctness proof for the hybrid checkpoint tier.

22 batched-cache tests green; additive, no regression to extract/merge.

* test(kv-cache): boundary-align planner tests + bump submodule (capture hook)

- Bump libs/mlx-swift-lm to 62bf9f2 (CheckpointPrefillPlanner + Scheduler
  capture hook, default-off/isolated).
- CheckpointPrefillPlannerTests: 7 cases proving the chunk is capped to land
  on a boundary, never grows, never overshoots remaining, captures only at
  reachable boundaries, always >= 1.

Capture-only step; no restore yet, so no model output changes. 23 submodule
CB tests + 4 capture tests + planner suite green.

* docs(kv-cache): mark restore primitive + capture hook done in hybrid plan

* chore(kv-cache): bump submodule — checkpoint restore-admit path (d76279d)

Adds Request.restoredCheckpoint + the B==1 mixed-cache restore-admit path to
the scheduler. Numeric-equivalence gated (restore == cold), isolated
(default-off), reviewed. Provider-side wiring (BatchScheduler → manager
lookup/store) is the next step.

* feat(kv-cache): wire checkpoint tier into BatchScheduler (Step 4)

Connects the engine-side capture+restore (submodule) to the encrypted
PrefixCacheManager for hybrid sliding-window models (Gemma-4, GPT-OSS).
Default-off (DARKBLOOM_PREFIX_CACHE); fully isolated for other models.

- makeBatchedEngine classifies the loaded model via
  PrefixCacheStrategy.classify(model.newCache()) and builds the matching
  tier: .engine → in-GPU block PrefixCache (unchanged); .checkpoint →
  PrefixCacheManager + scheduler.onCheckpointCapture + boundaries (from the
  min sliding window); .none → neither. Returns EngineBuild(engine,
  checkpointManager?, boundaries); loadModel stores them on the actor.
- Shared PrefixCacheBacking (KEK actor + unwrapped key + dir + MB-1 binding
  + disk budget) reused by both tiers — one Keychain key, no double-unwrap.
- maybeRestoreCheckpoint(req,promptTokens) in both submit paths: on a
  manager hit (1 <= tokenCount < promptLen) sets req.restoredCheckpoint so
  the engine decodes only the suffix. nil manager ⇒ cheap no-op.
- Capture closure stores to RAM then flushToSSD (off the engine queue via
  Task) so checkpoints survive restart — fixes a review finding that the
  SSD/at-rest half was otherwise dead.
- RAM tier respects DARKBLOOM_PREFIX_CACHE_MAX_GB (was default 8 GB).
- Epoch-race bail + stopCurrentEngine clear checkpointManager so a stale
  manager never serves a superseded model.

Bumps submodule to 8c2e2ce (per-position layer-type validation hardening).
Reviewed for isolation; 138 KV+scheduler tests green. Live logit-equivalence
on real Gemma-4/GPT-OSS (Step 5) is the remaining merge gate.

* test(kv-cache): live Gemma-4/GPT-OSS checkpoint equivalence gate (Step 5)

HybridCheckpointLiveTests: on REAL weights, continuing generation from a
restored checkpoint at length L (serialize prefix cache → deserialize →
rebuild B==1 batched → prefill suffix → greedy) must produce the SAME tokens
as a cold full-prompt greedy run. Exercises real bf16 KV, head dims, sliding
windows, and layer counts through the actual KVCacheSerializer +
fromSingleRow/merge path — the correctness that synthetic models can't
cover.

Capability-gated (only runs for .checkpoint models) and env-gated
(DARKBLOOM_LIVE_MLX_TESTS + _GEMMA / _GPTOSS); skips cleanly with no weights
in CI. Marks the hybrid feature complete behind the default-off flag; design
doc §7.4 updated.

130 KV+scheduler tests green; live suite compiles + skips.

* fix(kv-cache): bound checkpoint-tier disk + sweep orphan temps (partner-stability audit)

Deep pre-integration stability audit (75 agents, 68 findings, 62 refuted).
Fixes the confirmed production-reachable resource leaks; the refutations
independently confirmed no crash/race/corruption in the feature.

HIGH — checkpoint tier had NO disk budget (findings 1-3, same root cause):
PrefixCacheManager.flushToSSD wrote a .darkbloom-kv file + permanent
index.json entry per unique prefix with no cap, so sustained diverse
partner traffic on Gemma-4/GPT-OSS could fill the volume (breaking model
downloads, logging, all writes). Only the engine block tier was bounded.
Fix: thread diskBudgetBytes (same 50%-of-free default) into
PrefixCacheManager and enforce it in flushToSSD via LRU eviction
(index.entriesLRUFirst), deleting file + index entry together — bounds both
the KV dir AND index.json. New stat diskEvictions; test
managerEnforcesDiskBudgetWithLRUEviction.

MEDIUM — orphan atomic-write temp files: a process KILL between createFile
and rename leaves a <name>.tmp-<UUID> with no cleanup. Added
EncryptedKVStore.sweepStaleTempFiles, called at cache setup; test
sweepStaleTempFilesRemovesOrphansKeepsRealFiles.

LOW — loadFromSSD on decrypt/KEK-unwrap failure now deletes the unusable
file (not just the index entry) so it can't linger and be re-read.

LOW — orphaned per-model dirs across model churn: documented as a known
limitation (each dir is bounded; no cross-model GC yet).

132 KV+scheduler tests green.

* fix(kv-cache): de-race + de-amplify concurrent flushToSSD (reentrancy review)

Follow-up review of the disk-budget fix found the checkpoint capture hook
fires one detached Task{ store; flushToSSD } per checkpoint, so many
flushToSSD run concurrently on the PrefixCacheManager actor and interleave
at the mid-loop "await EncryptedKVStore.write". No crash/corruption (index
is a dict, atomic writes don't tear, eviction terminates -- 22 of 26
findings refuted), but two real perf/waste issues for a busy partner:

- MEDIUM (perf): index.save() re-encodes the WHOLE index + atomic write +
  fsync on EVERY flush, synchronously inside the actor region -- head-of-
  line-blocks lookup() on the hot path, amplified K-fold by K concurrent
  flushes. Now COALESCED: save once per 8 writes; flushIndexNow() forces a
  save on teardown (wired into stopCurrentEngine) so coalesced entries
  survive restart.

- LOW (reentrancy): two concurrent flushes of the same digest both passed
  the "already persisted?" check before either recorded it, redundantly
  serialize+encrypt+fsync-ing the same large blob. Added an actor-isolated
  inFlightWrites set (check+insert before the await is atomic on the actor;
  removed after, on both success and catch paths).

Tests: managerCoalescesIndexSavesButFlushIndexNowForces (save deferred
below threshold, forced by flushIndexNow); restart-style tests now call
flushIndexNow as production does on teardown. 133 KV+scheduler tests green.

* fix(kv-cache): startup index<->disk reconciliation closes coalescing leak (round-4 audit)

Fourth-round partner-stability audit (49 agents, 43 findings, 26 refuted).
15 of the 17 confirmed shared one root cause: the index save-coalescing
added earlier THIS session weakened durability, and crucially orphaned
.darkbloom-kv files (written but not yet in a coalesced index.save) ESCAPED
the disk budget (enforceDiskBudget only sums indexed bytes) and were never
reclaimed -- a real regression that partially defeated round-3's disk cap on
unclean shutdown (crash/OOM/SIGKILL/SIGTERM during a partner deploy).

Keystone fix -- reconcileWithDisk(), run once at model load before any
request is admitted:
- files present but NOT indexed (crash-window orphans, or a corrupt/missing
  index.json) are re-indexed from their plaintext metadata header (no
  decrypt) after validating model + shape + prefix-hash binding -- so they
  count toward the budget AND are reusable instead of leaking;
- index entries whose file vanished are dropped;
- foreign / mislabeled / unreadable files are deleted.
This makes coalescing crash-safe (orphans reclaimed next load), keeping its
perf win without the disk leak or lost-cache-across-restart. Also self-heals
a corrupt index.json (finding 4).

Smaller fixes: only reset unsavedWrites on a SUCCESSFUL index.save (both the
flushToSSD threshold path and flushIndexNow), so a transient ENOSPC/EACCES
retries rather than silently dropping durability tracking (findings 10/13).

The remaining confirmed findings were all bounded variants of the same
coalescing/orphan theme, resolved by the reconcile; none were
crash/hang/corruption/wrong-output (26 refuted, incl. all crypto
nonce-reuse, AAD-binding, integration-boundary, and output-equivalence
checks -- the at-rest crypto and partner-facing behavior verified sound).

Test: managerReconcileReindexesOrphanFilesAndDropsMissing (orphan re-indexed
and serves; missing-file entry dropped to a clean miss). 134 KV+scheduler
tests green.

* docs(kv-cache): mark checkpoint tier as wired/implemented (correct stale status)

The checkpoint tier was described as 'NOT wired into the serve path (only
tests)' and 'design — not yet implemented', both stale: Steps 3-4 wired
PrefixCacheManager into BatchScheduler for .checkpoint models and Step 5
added the live gate. Corrected both so the docs match the code; remaining
items are process gates (submodule PR merge, TB-007 sign-off, live-weights
run), not implementation.

* fix(kv-cache): per-layer shape validation for heterogeneous models (Gemma-4)

REAL bug caught by testing on the M5 Max with actual weights: a live shape
probe shows Gemma-4 has HETEROGENEOUS per-layer KV — sliding layers
[kvHeads=8, headDim=256] interleaved with full layers [kvHeads=2,
headDim=512] (25 + 5 of 30). But validateLayout checked every layer against
a SINGLE binding.kvHeads/headDim, so loadFromSSD would reject the model's
OWN freshly-written checkpoint files -> the encrypted SSD cache silently
never loads for Gemma-4 in production. The equivalence test missed it
because it bypasses the manager/validateLayout. (GPT-OSS is uniform
[8,·,64], unaffected -- only per-model real testing surfaces this.)

Fix:
- KVCacheSerializer.validateLayout(_:layerShapes:) — validates each layer
  against its OWN expected [kvHeads, headDim] + requires matching layer
  count. Scalar overload kept for uniform models / tests.
- PrefixCacheModelBinding gains optional layerShapes; loadFromSSD uses the
  per-layer guard when present, else the scalar one.
- BatchScheduler.probeLayerShapes(model:) derives per-layer [kvHeads,
  headDim] ground truth via a 1-token probe prefill, and the .checkpoint
  binding carries it.

Tests: validateLayoutPerLayer{AcceptsHeterogeneousModel,RejectsMismatchAndCount}
(the heterogeneous case proves the old scalar guard wrongly rejected it);
new live gemma4SSDLoadMatchesCold drives the FULL encrypted-SSD path
(store -> flush -> fresh manager -> reconcile -> loadFromSSD -> decrypt ->
per-layer validate -> serve) == cold, the path the bypass test didn't cover.
18 serializer/validate unit tests green.

* test(kv-cache): share KEK across writer/reader in live SSD-load test

The new gemma4SSDLoadMatchesCold test built a fresh InMemoryKeyWrappingService
+ storage per manager, minting a RANDOM KEK each time, so the reader couldn't
unwrap the writer's DEK -> 'DEK unwrap failed: authenticationFailure' -> SSD
lookup MISS. That was a test-harness artifact: production shares ONE
SE-wrapped/Keychain-persisted KEK (backing.kek) between flush and load and
across restart. Fix: share a fixed wrapping key + a single storage instance
so writer and reader resolve the same persisted KEK, matching production.
(Diagnosed on the M5 Max via NSLog of the actual throw.)

* test(kv-cache): live load/stress gates on real Gemma-4 KV

Adversarial live tests (gated DARKBLOOM_LIVE_MLX_TESTS+_GEMMA) driving the
dimensions equivalence tests don't cover, with REAL ~tens-of-MB Gemma-4 KV:
- diskBudgetBoundsRealKVUnderSustainedStores: 12 distinct-prompt stores
  under a ~3-file budget; asserts on-disk bytes stay within budget, eviction
  ran, most-recent survives.
- concurrentFlushesStayWithinBudgetAndDontCrash: 16 CONCURRENT flushToSSD
  Tasks (the production capture-hook pattern); asserts no read/decrypt
  errors, no duplicate files, budget respected, survivors reload+decrypt.
- ramByteBudgetBoundsMemoryUnderLargeCheckpoints: 10 real checkpoints into a
  ~2.5-checkpoint RAM budget; asserts bytes bounded + LRU eviction ran.

* test(kv-cache): end-to-end serve-loop + TTFT live gates (real Gemma-4)

The path a partner actually hits — BatchScheduler.submitTokenized → lookup →
addRequest → admit (capture/restore) → decode → stream — which no other
live test exercised. Gated DARKBLOOM_LIVE_MLX_TESTS+_GEMMA:
- flagOnOutputMatchesFlagOff: flag-on cold AND warm/restored output ==
  flag-off baseline (cache must be transparent).
- sharedPrefixRestoresAndIsNotSlower: warm-up request captures (stores>=1);
  a 2nd same-prefix request RESTORES (ramHits/ssdHits delta>=1); warm TTFT
  not pathologically worse than a no-prefix cold request.
- cacheMissDoesNotRegressVsFlagOff: a unique-prompt miss with flag on
  produces identical output and TTFT not pathologically worse than flag-off
  (lookup overhead on the miss path is bounded).

* test(kv-cache): e2e restore via test seam + chaos/failure live gates

E2E finding: with the flag ON on an unsigned swift-test binary, the
checkpoint manager is NOT wired — PersistentEnclaveKey.loadOrCreate fails
(errSecMissingEntitlement), so makePrefixCacheBackingIfEnabled correctly
returns nil (the deliberate 'refuse rather than ephemeral KEK' guard). NOT a
product bug; the SE path needs a signed binary. To still exercise the real
submit→lookup→admit→capture serve path, add an internal test seam
_installCheckpointManagerForTest that injects a manager with an in-memory
KEK + the model's real per-layer shapes, wiring the same capture hook
makeBatchedEngine does.

- HybridCheckpointE2ELiveTests.sharedPrefixRestoresAndIsNotSlower: warm-up
  captures (stores>=1), shared-prefix 2nd request RESTORES (hit delta>=1),
  warm TTFT not pathologically worse than cold. (transparency + miss-path
  tests already pass and need no manager.)
- HybridCheckpointChaosLiveTests: truncated file / wrong KEK degrade to a
  clean cold miss (no crash); SIGKILL-orphan re-indexed+served by reconcile;
  garbage file deleted — all on real Gemma-4 KV.

* fix(kv-cache): delete unusable file on ALL loadFromSSD reject paths

Chaos test (truncatedFileDegradesToColdMiss) on real Gemma-4 caught it: a
truncated/corrupt file correctly degraded to a cold miss (no crash, safety
held), but only the INDEX entry was dropped — the file lingered on disk,
leaking and escaping the disk budget (it's no longer indexed, so
enforceDiskBudget can't see it). The decrypt-failure path already deleted
the file; the earlier readMetadataOnly-failure + MB-1/shape/prefix-hash
mismatch paths did not. Now all reject paths in loadFromSSD remove the file
too (the path is reconstructed from this model's binding, so a mismatch is a
genuinely stale/wrong file for this model). 13 manager tests green.

* docs(kv-cache): link global-disk-budget follow-up (#266) + low-churn rollout guidance

Per-model disk budget is sufficient for a low-churn/few-model rollout with
an explicit DARKBLOOM_PREFIX_CACHE_DISK_GB; the global cross-model accountant
needed before high-churn multi-model fleets is tracked in #266.

* fix(kv-cache): default disk budget to a fixed 10GB/model, not 50%-of-free

The unset DARKBLOOM_PREFIX_CACHE_DISK_GB default was 50%-of-free PER MODEL,
which is the unbounded-aggregate behavior of #266: N models each take ~half
the disk and collectively fill it. Make the out-of-box default safe for a
low-churn rollout — a fixed 10 GB per model, clamped down to 50% of free on
a tight volume. 'just set DARKBLOOM_PREFIX_CACHE=1' now caps each model at
10 GB (≈ models × 10 GB aggregate) instead of risking the whole disk;
operators raise it explicitly when they have headroom. Env override + 0=
unlimited + non-finite-rejection unchanged. Docs + tests updated; #266
(global cross-model accountant) still tracks the high-churn fix. 138 tests green.

* test(kv-cache): document live suites must run one-at-a-time (model contention)

Running all Hybrid*LiveTests in one swift-test invocation parallelizes
across suites (.serialized only orders within a suite), loading several 26B
models concurrently → memory contention → spurious request errors + TTFT
failures. The substantive checks pass; only the timing-sensitive E2E
transparency/miss-path asserts are affected. Documented: run the E2E suite
alone. Verified 3/3 E2E green in isolation against 3089c798 on the M5.

* test(kv-cache): multi-sample TTFT benchmark (real Gemma-4, charting data)

N cold (distinct 512-tok prefix → full prefill) vs N warm (shared 512-tok
prefix → checkpoint restore + 6-tok suffix) TTFT samples, with a warm-up to
absorb Metal compile. Emits raw per-sample ms as 'BENCH,cond,i,ms' lines for
charting, plus a median-speedup summary. Run alone; gated on live+gemma.

* docs(kv-cache): add real-M5 TTFT benchmark chart + raw data

Chart and raw samples from HybridCheckpointBenchLiveTests on M5 Max
(128GB) over real Gemma-4 26B weights, n=12/condition, 512-tok shared
prefix: cold median 485ms vs warm-restore 283ms = 1.71x faster TTFT,
12/12 warm hits. Right panel summarizes the verified resource bounds
(disk 165/192MB w/ 45 evictions, RAM 110/137MB w/ 8 evictions) and
concurrency/integrity results from the stress + chaos suites. CSV holds
the raw per-sample TTFT; PNG is the GitHub-embeddable render of the SVG.

* test(kv-cache): parameterize TTFT bench for GPT-OSS-20B too

The TTFT benchmark was Gemma-4-only. Factor the cold-vs-warm loop into
runBench(modelID:prefixLen:tag:) and add a GPT-OSS-20B case (sliding
window 128 → checkpoint @ 96, within window) gated by
DARKBLOOM_LIVE_MLX_GPTOSS. Each model is gated independently and emits
tagged BENCH lines (BENCH,<tag>,cold/warm,i,ms) so a box with only one
weight set still produces chartable data and both can share one log.

* docs(kv-cache): add GPT-OSS-20B to the real-M5 TTFT chart

Benchmarked GPT-OSS-20B (mlx-community/gpt-oss-20b-MXFP4-Q8) the same
way as Gemma-4 on the M5 Max — n=12/condition, 96-tok shared prefix
(within its 128 sliding window), 12/12 warm hits: cold median 174ms vs
warm-restore 67ms = 2.60x faster TTFT. GPT-OSS's smaller window means a
larger fraction of prefill is saved, so its relative win exceeds
Gemma-4's (1.71x). Chart now groups both models; CSV holds both raw
sample sets.

* test(kv-cache): add prefill-length TTFT sweep

Factor the cold-vs-warm measurement into measureColdVsWarm(...) and add
gemma4PrefillSweep, which holds Gemma-4 loaded and measures cold/warm
TTFT at prefix lengths {64,128,256,384,512} (all <= window 512). This
shows directly that the cache's TTFT win is a PREFILL effect: cold rises
with prefix length (more tokens to prefill) while warm stays ~flat (only
the 6-token suffix is ever prefilled), so the speedup scales with how
much prefill the checkpoint restore skips. Emits SWEEP,<model>,L,cold,
warm,speedup lines for charting.

* docs(kv-cache): add prefill-length sweep chart (real M5 Gemma-4)

Visualizes the gemma4PrefillSweep result: cold TTFT rises ~0.34ms/token
with shared-prefix length (341ms@64 -> 493ms@512) while warm stays ~flat
(270->286ms, only the 6-tok suffix is prefilled), so the speedup grows
1.26x->1.72x with the cached prefix. Confirms the TTFT win is a prefill
effect. SVG + GitHub-embeddable PNG + raw CSV.

* test(kv-cache): add large-prefill (up to 100k) scaling probe

Answers "what about a 100k prefill?". Hybrid sliding-window models cap a
restorable checkpoint at the sliding window (a rotating window discards
older KV), so the cache can only remove the first `window` tokens of any
prefill. gemma4LargePrefillScaling reports the runtime sliding window and
measures cold prefill TTFT at 1k..100k tokens, then expresses what a
window-sized checkpoint removes as a fraction of the 100k prefill — making
the large-context ceiling explicit. Raises the test memory budget to 100GB
for the big prompts (M5 Max 128GB).

* test(kv-cache): probe past-window restore equivalence + fix 100k scaling

Two corrections prompted by review:

1. The sliding window is NOT a fundamental cap on reusable prefix length.
   A hybrid prefix needs full KV for full-attention layers + only the last
   `window` KV for sliding layers; our serializer already snapshots exactly
   that (RotatingKVCache.state returns the wrapped ring buffer). The only
   thing capping reuse at L<=window is PrefixDigest.checkpoints(forSliding
   Window:), a design choice. Add gemma4RestoreMatchesColdPastWindow
   (L=2048, 4096 vs the 1024 window) to measure whether serialize -> restore
   -> continue stays numerically exact once the ring buffer has wrapped —
   the experiment that decides whether the cap protects a real gap or is
   merely conservative.

2. Fix gemma4LargePrefillScaling: it crashed at 100k because the default 60s
   pending timeout expired before admission. Raise pendingTimeout to 300s
   (new loadScheduler param), drop reps for >=64k, and record non-completion
   as n/a instead of asserting a bogus negative. Corrected its comment: it
   measures avoided prefill cost, not a reuse ceiling.

* docs(kv-cache): correct the window-vs-reusable-prefix framing

An earlier draft (hybrid-models S3) claimed a checkpoint at L is only sound
when L <= sliding window — i.e. that the window caps reusable prefix length.
That is wrong. A hybrid prefix needs full KV for full-attention layers + only
the last `window` KV for sliding layers; full layers retain everything, so
they never limit reuse. The window bounds per-layer retention, not prefi…
@github-actions github-actions Bot mentioned this pull request Jun 14, 2026
6 of 12 tasks
Gajesh2007 added a commit that referenced this pull request Jun 17, 2026
…e (Codex #3)

coldSpillProviderEligibleLocked gated only on pendingCount, but TriggerModelSwaps
also rejects backend-busy providers (warmPoolBackendSlotBusyLocked). A provider
with empty coordinator-pending but a running/waiting backend slot passed cold-spill
eligibility, got a request enqueued, then the planner refused to load it — so the
request waited out the 120s queue timeout instead of failing fast. Now mirrors the
planner gate exactly.
Gajesh2007 added a commit that referenced this pull request Jun 17, 2026
P2 #3 — exclude non-evictable work from free_for_load_gb (provider). The
heartbeat computed max-loadable weight by treating ALL MLX usage as reclaimable,
but MLX memory is global (it also covers the local inference endpoint, whose
streams are tracked by localReservations, not modelSlots), so a model actively
serving a local request is NOT evictable. Gate the eviction add-back on
`hasInflightWork` (the comprehensive coordinator-inflight + local-streams
signal): assume idle models are evictable only when nothing is in flight;
otherwise reclaim nothing (conservative — never advertises a served model's
weights as free).

P2 #2 — gate the load planner with reported free capacity (coordinator).
modelLoadCandidatePendingLocked (warm-pool / queue-before-shed cold dispatch)
only checked static modelFitsHardware, so it could send a load_model the direct
freeMemoryAdmits gate would reject — leaving queued requests to time out. Mirror
the direct path: skip a candidate whose catalog weight exceeds the provider's
reported free_for_load_gb. Legacy providers (nil) fall through to the static gate.

P2 #1 (request KV not in the cold gate) is by design: free_for_load_gb
guarantees the model loads and can serve a modest request (provider reserves
min serveable KV); per-request KV is a runtime concern, and folding the
coordinator's generic KV estimate in would break edge-fit cold loads (the model
consumes the whole budget). Left as-is; the proper enhancement is a per-request
load budget from the provider (follow-up).

Test: planner respects free_for_load_gb (reject 14GB model at 9GB free, accept
at 20GB, legacy nil falls back). Go suite + Swift build green.
Gajesh2007 added a commit that referenced this pull request Jun 17, 2026
…d paths

Second Codex #390 pass — make the reported-capacity gate consistent everywhere
and apples-to-apples, via one shared helper so the paths can't drift.

- New reportedFreeForLoadAdmits() helper + coldLoadCatalogGBToMemGiB normalization
  (P2 #4): the provider's free_for_load_gb is padded GiB (ModelLoadAdmission uses
  estimatedMemoryGb = on-disk × 1.2 / 2^30), but the coordinator compared raw
  catalogSizeGB (TotalSizeBytes/1e9). A near-threshold model whose RAW size fit
  but whose PADDED estimate didn't was admitted then 503'd at load. Normalize
  catalog GB → padded GiB (×1.2×(1e9/2^30) ≈ 1.1176) before comparing, so the
  coordinator gate exactly mirrors the provider's canLoad.
- Apply the helper in all four cold-load decision paths so they stay in sync:
  direct admission (freeMemoryAdmits), the swap planner
  (modelLoadCandidatePendingLocked), the warm pool (warmPoolCandidateLocked, P2 #1)
  and the cold-spill predicate (coldSpillProviderEligibleLocked, P2 #2). Previously
  only the first two were gated, so the warm pool could issue a load_model the
  provider rejects, and cold-spill would queue a request the planner then refuses
  to load (sit until the 120s timeout).
- Provider (P2 #3): subtract outstanding KV reservations
  (kvBudget.outstandingReservedBytes()) from the heartbeat free_for_load_gb,
  exactly as availableMemoryGb does, so it can't advertise reserved-but-not-yet-
  allocated bytes as loadable. maxLoadableWeightGb gains an
  outstandingReservationBytes parameter.

Tests: near-threshold normalization (raw fits, padded rejects), planner gate,
outstanding-KV subtraction. Go suite (17 pkgs) + Swift build green; gofmt clean.
Gajesh2007 added a commit that referenced this pull request Jun 17, 2026
…poch, late-SecurityInfo caching, MDM-config gate, 10m window, security docs

FIX A (P1, durable hard-untrust — close the write-after-delete race; Codex
trust_reuse.go:366 + Threat-Model #6): the persisted reuse WRITE was still
fire-and-forget, so a hard untrust right after a grant could delete first and the
async write could land a stale `hardware` row that a restart reseeds → fast-skip
resurrects untrusted hardware. Added a per-provider hard-untrust EPOCH:
registry.Provider.untrustEpoch (atomic.Uint64) + HardUntrustEpoch(), bumped in
markUntrusted's HARD path BEFORE the delete hook fires. recordTrustReuse now
captures the epoch at grant time, persists SYNCHRONOUSLY (no saferun.Go), and
immediately before the upsert re-checks the provider is not hard-untrusted AND the
epoch is unchanged — else it skips the persist and drops the in-memory entry.
markUntrusted's invalidate stays synchronous. Deterministic tests (registry epoch
counter; record-after-untrust skips persist; durable-across-restart both
orderings).

FIX B (P2, cache late grants; Codex provider.go:2755): ApplyLateSecurityInfo now
mirrors the synchronous path with the same epoch-checked write-through, so a
self_signed→hardware upgrade from a late SecurityInfo also gets restart-survivable
fast-skip. Test added.

FIX C (P2, gate on MDM configured; Codex trust_reuse.go:438): tryTrustReuseFastSkip
returns false when s.mdmClient == nil — a no-MDM/misconfigured deploy must not
grant hardware from a (possibly stale) cache with no live MDM fallback. Test added.

FIX D (Threat-Model #3, window): default reuse window 30m→10m so hardware-trust
reuse cannot span a SIP-disable reboot cycle; still configurable via
EIGENINFERENCE_TRUST_REUSE_WINDOW. Comment updated.

FIX E (Threat-Model #5, table doc): annotated the provider_trust_reuse migration as
security-sensitive — a row grants a hardware fast-skip, so write access must be
guarded like the payment ledger; SeedTrustReuseCache trusts DB contents, bounded by
the always-run live SE challenge + future-date rejection. No schema change.

FIX F (Threat-Model SEC-004, doc): noted near recordTrustReuse/SeedTrustReuseCache
that a forged (localhost-bound, unauthenticated) MDM webhook driving a grant would
be durably persisted + reseeded → amplified across restarts; bounded by the
localhost-only webhook, full mitigation is authenticating the webhook (tracked
separately).

coordinator/: gofmt clean, go build ./... ok, go test ./... all pass (postgres
tests skipped w/o DATABASE_URL), -race clean on the new tests.
Gajesh2007 added a commit that referenced this pull request Jun 17, 2026
…on coordinator restart/swap) (#391)

* feat(attestation): DAR-326 Phase 0 — provider trust-reuse cache (skip MDM re-verify herd on restart)

A planned coordinator restart/blue-green swap reconnects the whole fleet at
once; today each provider's per-connection mdmVerificationLoop fires a live MDM
SecurityInfo round-trip (+ APNs push) almost immediately, so the fleet hammers
MicroMDM/APNs in a herd. This adds a coordinator-side, RDS-persisted
"trust-reuse" cache (mirroring the existing code-identity reuse cache) that lets
a reconnecting, recently-fully-verified provider be granted hardware from its
record once a FRESH live SE challenge re-proves identity + posture — skipping the
live MDM round-trip.

Store layer (mirrors code_attestations):
- store.ProviderTrustReuse + List/Upsert/Delete in interface.go, postgres.go
  (provider_trust_reuse table), memory.go.

Cache (api/trust_reuse.go, mirrors code_attest_throttle.go):
- trustReuseCache with reuseTrust / hasFreshRecord / recordTrust /
  invalidateReuse / seed; window via EIGENINFERENCE_TRUST_REUSE_WINDOW (default
  30m). Server wiring: SeedTrustReuseCache (seed + write-through + hard-untrust
  hook), recordTrustReuse, persistTrustReuse, invalidateTrustReuse,
  tryTrustReuseFastSkip, awaitTrustReuseGrant. Seeded at startup in main.go.

Write-through: verifyProviderViaMDM records a reuse entry after a live MDM pass +
hardware grant.

Read-path fast-skip: after the live SE challenge passes (verifyChallengeResponse),
grant hardware iff ALL gates hold: (a) SE-key+serial match, (b) fresh signed
binary_hash == cached, (c) fresh SIP+SecureBoot good && status fields signed,
(d) within window, (e) not hard-untrusted. Any miss falls through to the
unchanged full live MDM verify. The mdmVerificationLoop briefly defers to this
fast-skip only for candidates (hasFreshRecord), so the live round-trip is
actually skipped instead of racing ahead.

Invalidation: a registry hard-untrust hook (SetHardUntrustHook, fired in
markUntrusted only for non-recoverable deroutes) drops the record in-memory +
persisted, keeping "hard untrust always takes effect" durable across restarts.

Security invariants: the live SE challenge ALWAYS runs first; the skip is a gated
optimization, never a trust shortcut; first-ever verification (no record) always
does full live MDM; persisted rows are re-validated on every read.

Tests: cache gates + window + seed + env (mirrors code_attest_throttle_test),
store round-trip (mirrors code_attest_test), fast-skip grant + every
fall-through case, and the registry hard/transient untrust hook.

* fix(dar-326): address review findings — durable invalidation, clock-skew guard, fast-skip latency, test gaps, hook decoupling

FIX 1 (should-fix) — durable hard-untrust invalidation: invalidateTrustReuse now
does a synchronous in-memory invalidateReuse plus an INLINE bounded-retry
DeleteProviderTrustReuse (3 attempts, 5s timeout each, short backoff, log only
after the final failure) instead of a fire-and-forget saferun.Go. Safe because
the hard-untrust hook fires off all registry locks (registry.markUntrusted) and a
hard untrust is rare; this keeps "hard untrust always takes effect" durable across
a coordinator restart even through a transient DB blip. (Parity for
invalidatePersistedCodeAttestation deliberately NOT applied: it runs on the
WebSocket read loop via maybeRearmCodeAttest, where an inline blocking delete
would stall reads — only the trust-reuse hook is guaranteed off-locks.)

FIX 2 (nit) — clock-skew guard: reuseTrust/hasFreshRecord/seed now require age in
[-clockSkewTolerance, reuseWindow) (clockSkewTolerance = 2m), rejecting
implausibly future-dated (corrupt/forged) records that would otherwise stay
"fresh" indefinitely.

FIX 3 (nit) — fast-skip latency: added a per-connection buffered "challenge
settled without fast-skip grant" signal on registry.Provider
(SignalChallengeSettled/ChallengeSettledChan, created fresh per Register). It is
fired in verifyChallengeResponse right after tryTrustReuseFastSkip returns false,
and awaitTrustReuseGrant now selects on it — so a non-fast-skip candidate proceeds
to the full live MDM verify immediately instead of stalling up to 10s.

FIX 4 (nit) — tests: added serial-mismatch and SE-key-mismatch fall-through cases
to TestTrustReuseFastSkipFallsThrough.

FIX 5 (nit) — hook decoupling: SeedTrustReuseCache now wires the hard-untrust hook
UNCONDITIONALLY (independent of store presence); store write-through + startup
seeding stay behind the store check. Doc updated. (5b) a successful fast-skip
grant now clears any stashed pending-ACME result, mirroring a normal upgrade.

Tests: extended TestInvalidateTrustReuseDeletesPersisted (now asserts synchronous
delete) and added TestInvalidateTrustReuseRetriesPersistedDelete (flaky store,
retry-then-succeed) + TestInvalidateTrustReuseDurableAcrossRestart (record →
hard untrust → fresh cache seeded from same store finds nothing); future-dated
cases in the cache + seed tests; await-signal returns-promptly + returns-true-on-
hardware; hook-wired-without-store. gofmt clean, go build ./... ok, go test ./...
all pass (postgres tests skipped w/o DATABASE_URL), -race clean on new tests.

* fix(dar-326): address Codex + threat-model review — durable untrust epoch, late-SecurityInfo caching, MDM-config gate, 10m window, security docs

FIX A (P1, durable hard-untrust — close the write-after-delete race; Codex
trust_reuse.go:366 + Threat-Model #6): the persisted reuse WRITE was still
fire-and-forget, so a hard untrust right after a grant could delete first and the
async write could land a stale `hardware` row that a restart reseeds → fast-skip
resurrects untrusted hardware. Added a per-provider hard-untrust EPOCH:
registry.Provider.untrustEpoch (atomic.Uint64) + HardUntrustEpoch(), bumped in
markUntrusted's HARD path BEFORE the delete hook fires. recordTrustReuse now
captures the epoch at grant time, persists SYNCHRONOUSLY (no saferun.Go), and
immediately before the upsert re-checks the provider is not hard-untrusted AND the
epoch is unchanged — else it skips the persist and drops the in-memory entry.
markUntrusted's invalidate stays synchronous. Deterministic tests (registry epoch
counter; record-after-untrust skips persist; durable-across-restart both
orderings).

FIX B (P2, cache late grants; Codex provider.go:2755): ApplyLateSecurityInfo now
mirrors the synchronous path with the same epoch-checked write-through, so a
self_signed→hardware upgrade from a late SecurityInfo also gets restart-survivable
fast-skip. Test added.

FIX C (P2, gate on MDM configured; Codex trust_reuse.go:438): tryTrustReuseFastSkip
returns false when s.mdmClient == nil — a no-MDM/misconfigured deploy must not
grant hardware from a (possibly stale) cache with no live MDM fallback. Test added.

FIX D (Threat-Model #3, window): default reuse window 30m→10m so hardware-trust
reuse cannot span a SIP-disable reboot cycle; still configurable via
EIGENINFERENCE_TRUST_REUSE_WINDOW. Comment updated.

FIX E (Threat-Model #5, table doc): annotated the provider_trust_reuse migration as
security-sensitive — a row grants a hardware fast-skip, so write access must be
guarded like the payment ledger; SeedTrustReuseCache trusts DB contents, bounded by
the always-run live SE challenge + future-date rejection. No schema change.

FIX F (Threat-Model SEC-004, doc): noted near recordTrustReuse/SeedTrustReuseCache
that a forged (localhost-bound, unauthenticated) MDM webhook driving a grant would
be durably persisted + reseeded → amplified across restarts; bounded by the
localhost-only webhook, full mitigation is authenticating the webhook (tracked
separately).

coordinator/: gofmt clean, go build ./... ok, go test ./... all pass (postgres
tests skipped w/o DATABASE_URL), -race clean on the new tests.

* fix(dar-326): address review round 2 — empty-seKey guard, post-write untrust recheck, queue drain, ACME handling, MDA-freshness doc

FIX 1 (MUST — empty-seKey poisoning, a bug FIX B introduced): recordTrustReuse is
now a hard no-op for an empty seKey OR empty binaryHash (no in-memory entry, no
persisted row) — an unkeyed row would poison the cache/store and an empty binary
hash can never satisfy the read gate. ApplyLateSecurityInfo nil-guards the derived
values and skips recordTrustReuse when AttestationResult is absent or the SE
key / binary hash is empty.

FIX 2 (MUST — write-delete TOCTOU, Codex P1 trust_reuse.go:393): the pre-write
epoch check left a check-then-write window where a hard untrust landing between the
check and the upsert committing could resurrect a stale row. recordTrustReuse now
adds a POST-write epoch recheck: after a successful upsert, if the provider is
hard-untrusted or the epoch changed, it deletes the just-written row (bounded-retry
idempotent helper, now shared with invalidateTrustReuse) and drops the in-memory
entry. With markUntrusted's own synchronous delete this fully linearizes write vs
delete: untrust-before-precheck is dropped, untrust-during-write is compensated,
untrust-after is removed by its own delete.

FIX 3 (SHOULD — drain queue after fast-skip, Codex P2): on a fast-skip hardware
grant, verifyChallengeResponse now drains the provider's queued requests
(DrainQueuedRequestsForProvider, off the challenge goroutine) — mirroring the
code-attest / MDM grant path — so freshly-routable capacity picks up queued work
instead of waiting for the next heartbeat / 120s timeout.

FIX 4 (SHOULD — ACME interaction, Codex P2 + Threat Model):
(a) reconcileACMEAfterFastSkip — after an MDM-reuse grant, if a connect-time ACME
    cert is stashed but never bound, try the binding once; if it still doesn't bind,
    clear the optimistic ACMEVerified flag and discard the stale pending result so
    the attestation report never claims acme_verified for an unproven binding.
(b) on a fast-skip MISS, retryACMETrust runs BEFORE SignalChallengeSettled, and the
    settled signal is fired only if ACME did not promote to hardware — so a bound
    device cert can promote without forcing a live MDM round-trip.
(c) connection-scope the challengeSettled signal: Provider.ResetChallengeSettled()
    drains it, called from Register, so no stale buffered signal can carry into a new
    connection.

FIX 5 (DOC — Threat Model MDA freshness): documented in docs/threat-model.yaml
(T-036, ref TB-005) and in a code comment at the fast-skip grant that the fast-skip
skips live MDA cert-chain re-verification within the reuse window — an accepted
trade-off for the restart-herd problem, bounded by the short window, the always-run
live SE challenge, the hard-untrust epoch, and the MDM-configured gate.

coordinator/: gofmt clean, go build ./... ok, go test ./... all pass (postgres
tests skipped w/o DATABASE_URL), -race clean on api + registry.
Gajesh2007 added a commit that referenced this pull request Jun 22, 2026
…s (measurement only)

Extends the first-token-wedge instrumentation with three more NON-PRIVATE signals
and bumps the mlx-swift / mlx-swift-lm submodule pins to the commits that carry
the engine-side probes.

#1 Prefill-sampling health (provider only): counts why observed_prefill_tps stays
   0 — accepted / dropped-below-1ms-floor / dropped-above-8000-ceiling samples +
   the raw last sample rate. The bounds check is refactored into a pure,
   unit-tested `classifyPrefillSample` (accept path byte-for-byte unchanged).

#2 Eval-in-flight (mlx-swift EvalProbe, pin ac678221->f84a56d8): brackets the
   blocking mlx_eval inside evalLock so the provider reports how long the CURRENT
   eval has run — the direct wedge smoking gun. Heartbeat scalar eval_in_flight_ms
   + engine_health counts; coordinator emits provider.eval_in_flight_long.

#3 Idle-clear-in-flight (mlx-swift-lm EngineCore, pin 8a9bc7ce->3293f8ed): marks
   the M4-panic-race synchronize+clearCache so a clear that never exits pins
   candidate #1. Heartbeat scalar idle_clear_in_flight_ms + engine_health count.

Wire: 2 new BackendSlotCapacity scalars mirrored Swift<->Go + decoded into the
routing snapshot; 10 new engine_health field keys mirrored across the Go/Swift/TS
allowlists. Symmetry/round-trip/omitempty + classifier + EvalProbe-wiring tests
added. No routing/watchdog/eval behavior change (cheap timestamps; writes under
the eval lock or engine loop, lock-free reads — same pattern as stepsExecuted).

SUBMODULE NOTE: the two pins point to pushed feature branches
(Layr-Labs/mlx-swift#provider-wedge-instrumentation,
Layr-Labs/mlx-swift-lm#provider-wedge-instrumentation). Those submodule commits
must be merged (and ideally the pins re-pointed to the merge commits) for CI to
build a stable pin.

Co-authored-by: Cursor <cursoragent@cursor.com>
Gajesh2007 added a commit that referenced this pull request Jun 23, 2026
…e_health telemetry (measurement only) (#451)

* feat(provider): instrument the first-token wedge (measurement only)

Add NON-PRIVATE engine-health signals so the coordinator and the offline
telemetry trail can SEE the MLX/Metal first-token wedge from
docs/reports/2026-06-22-cancel-root-cause-and-fix.md §C: the provider emits
the CPU-only preamble, then the first blocking eval never returns, so token
production freezes while num_running stays 0 and the wedge is invisible today.

Provider (Swift):
- WedgeMonitor: pure per-load counters (admits, first-tokens, engine steps)
  and the ">=N admits / 0 first-tokens / >=T seconds" wedge primitive.
- Fold the signals into BackendSlotCapacity: steps_executed, admits,
  first_tokens_emitted, seconds_since_last_step, seconds_since_last_first_token,
  wedge_suspected (all omit-empty; admit at bridge start, first-token on first
  content -- independent of admittedAt, which a prefill wedge never sets).
- Emit engine_health telemetry events (model-load milestones, periodic engine
  snapshots, wedge-suspected transitions) via the existing TelemetryClient.

Coordinator (Go):
- Mirror the 6 BackendSlotCapacity fields and decode them into routingSnapshot.
- New engine_health telemetry kind; allowlist the new operational fields.
- Emit provider.first_token_wedge_suspected from heartbeats (fleet visibility).

Console UI (TS): mirror the engine_health kind + allowlist.

INSTRUMENTATION ONLY: no routing/watchdog behavior change. Protocol + telemetry
symmetry tests added/updated across Go/Swift/TS; WedgeMonitor logic + wire
round-trip/omit/backcompat tests included.

telemetry_events root cause: the coordinator no longer persists telemetry to
the DB (Datadog is the sole sink -- api/telemetry_handlers.go), so the dead
table is by design; provider internals were invisible because the provider
never emitted engine-internal events. Fixed by emitting engine_health events.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat: add eval-in-flight, idle-clear, and prefill-health wedge signals (measurement only)

Extends the first-token-wedge instrumentation with three more NON-PRIVATE signals
and bumps the mlx-swift / mlx-swift-lm submodule pins to the commits that carry
the engine-side probes.

#1 Prefill-sampling health (provider only): counts why observed_prefill_tps stays
   0 — accepted / dropped-below-1ms-floor / dropped-above-8000-ceiling samples +
   the raw last sample rate. The bounds check is refactored into a pure,
   unit-tested `classifyPrefillSample` (accept path byte-for-byte unchanged).

#2 Eval-in-flight (mlx-swift EvalProbe, pin ac678221->f84a56d8): brackets the
   blocking mlx_eval inside evalLock so the provider reports how long the CURRENT
   eval has run — the direct wedge smoking gun. Heartbeat scalar eval_in_flight_ms
   + engine_health counts; coordinator emits provider.eval_in_flight_long.

#3 Idle-clear-in-flight (mlx-swift-lm EngineCore, pin 8a9bc7ce->3293f8ed): marks
   the M4-panic-race synchronize+clearCache so a clear that never exits pins
   candidate #1. Heartbeat scalar idle_clear_in_flight_ms + engine_health count.

Wire: 2 new BackendSlotCapacity scalars mirrored Swift<->Go + decoded into the
routing snapshot; 10 new engine_health field keys mirrored across the Go/Swift/TS
allowlists. Symmetry/round-trip/omitempty + classifier + EvalProbe-wiring tests
added. No routing/watchdog/eval behavior change (cheap timestamps; writes under
the eval lock or engine loop, lock-free reads — same pattern as stepsExecuted).

SUBMODULE NOTE: the two pins point to pushed feature branches
(Layr-Labs/mlx-swift#provider-wedge-instrumentation,
Layr-Labs/mlx-swift-lm#provider-wedge-instrumentation). Those submodule commits
must be merged (and ideally the pins re-pointed to the merge commits) for CI to
build a stable pin.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: address 4 Codex-flagged false-positives in wedge/prefill instrumentation

All measurement-only / behavior-neutral; each fix has a regression test.

1. wedgeSuspected now requires the engine-step flatline too (WedgeMonitor.swift):
   was admits>=N && dryStreak>=T, which tripped on 3 legitimately slow prefills
   whose stepsExecuted kept advancing. Add `secondsSinceLastStep >= T` (the
   file's own documented 3-part signature); never-sampled reads 0 ⇒ won't trip.
   Test: notSuspectedWhenStepsAdvancing.

2. Clear the dry streak on a no-first-token terminal (WedgeMonitor +
   runBridge): only the first-token path cleared it, so client_gone cancels
   (which end before the first token) accumulated into a false wedge on healthy
   boxes. New WedgeMonitor.recordTerminalWithoutFirstToken() decrements the
   currently-hanging streak (floor 0, clears anchor at 0), called from both
   terminal exits when !sawFirstToken. Test: terminalWithoutFirstTokenClearsStreak.

3. eval_in_flight_long is provider-wide, not per-model (provider_wedge_telemetry.go):
   eval_in_flight_ms is the process-global EvalProbe value copied onto every
   slot, so the per-slot loop fired once per loaded model and tagged idle models
   as stalled. Emit once per heartbeat from the max across slots, untagged by
   model (keep first_token_wedge_suspected per-model). Test:
   TestProviderWideEvalInFlightLong (3×800ms ⇒ not long; max-based, not summed).

4. Reset prefillHealth on model swap (BatchScheduler.stopCurrentEngine): the
   EWMA it tracks IS reset there, but prefillHealth was not, so a new model
   inherited the prior model's accepted/dropped/last-sample counts. Add the
   reset next to the EWMA reset and correct the false "not reset per load"
   comment. Test: modelSwapResetsPrefillHealth.

No protocol/wire change; no submodule change; coordinator metric semantics:
provider.eval_in_flight_long is now provider-wide (see PR body).

Co-authored-by: Cursor <cursoragent@cursor.com>

* test: assert provider.eval_in_flight_long emits once provider-wide

Direct end-to-end regression for Fix 3 via the UDP statsd collector: 3 loaded
models all carrying the same process-global in-flight eval must emit
provider.eval_in_flight_long exactly once and without a model: tag. Fails (n==3)
without the provider-wide fix.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(submodule): bump mlx-swift pin to EvalProbe review fixes (c133e2e)

Re-points libs/mlx-swift f84a56d8 → c133e2ed (Layr-Labs/mlx-swift#6):
  - EvalProbe now brackets MLXArray.eval() so implicit realizations
    (item()/asArray()/asData()) are tracked too.
  - EvalProbe state moved behind OSAllocatedUnfairLock (was a torn-read data
    race on nonisolated(unsafe) scalars).

Measurement-only; provider `swift test` (1077/77) and `go test ./...` green
against the new pin. Merge-ordering still holds: merge mlx-swift#6 first, then
re-point this pin at the resulting main commit.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(submodule): re-point mlx-swift-lm pin to main (#48 merged)

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(submodule): bump mlx-swift pin to NSLock EvalProbe (3c50ad6)

Re-points libs/mlx-swift c133e2ed → 3c50ad69 (Layr-Labs/mlx-swift#6): EvalProbe
now uses a cross-platform Foundation NSLock instead of the Darwin-only
OSAllocatedUnfairLock, so mlx-swift builds on Linux (EvalProbe.swift is not in
the Linux excludes). Behavior-neutral on Darwin.

Provider `swift test` (1079/77) + coordinator `go test ./...` green against the
new pin. Merge-ordering still holds: merge mlx-swift#6 first, then re-point this
pin at the resulting main commit.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(wedge): anchor dry-streak to oldest hanging admit + epoch-gate callbacks

Two Codex P2 fixes on the wedge monitor (measurement-only, behavior-neutral):

B1 — dry-streak anchor could point at an ended admit (WedgeMonitor). After a
no-first-token terminal decremented a non-last hanging admit, the streak anchor
could still reference a request that already ended, so a mix of old+new admits
reported wedge_suspected before the newer admits had actually stalled 10s.
Replace the single anchor with a FIFO of hanging-admit timestamps: append on
admit, remove the front on a no-first-token terminal, clear all on a first token
(engine proven alive). dryStreakSeconds now measures from the OLDEST still-
hanging admit. consecutiveAdmitsWithoutFirstToken is derived from the FIFO.
Regression test: dryStreakAnchorsToOldestStillHangingAdmit (codex A/B/C/A-cancel/D
scenario ⇒ NOT wedge_suspected at t=10).

B3 — bridge callbacks didn't check the load generation, so a stale bridge
callback after stopCurrentEngine/reload could corrupt the fresh model's monitor.
Capture generationEpoch at bridge start and thread it through
recordWedgeAdmit/FirstToken/TerminalWithoutFirstToken; ignore the event when the
epoch no longer matches (mirrors engineStillCurrent). Regression test:
staleEpochWedgeCallbackIgnoredAfterReset.

B2 — EVALUATED, intentionally KEPT the bridge-start admit. Verified in code that
this engine emits a RequestOutput ONLY from the decode phase
(Scheduler.swift processGenResponses, lines 1262/1301) — there is no
prefill/admission-stage output — so a wedged first eval produces NO RequestOutput;
moving the admit to "first RequestOutput" would make the wedge invisible. The
step-flatline gate (wedgeSuspected requires frozen steps) prevents a merely-queued
request on a healthy engine from false-tripping. Documented the reasoning in the
runBridge admit comment.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Gajesh2007 added a commit that referenced this pull request Jul 2, 2026
…ant models

Two coupled memory-accounting gaps from PR #499 review (Codex P2 #2 + #3):

Fix #2 (shared-budget KV accounting): the v2 bridge bypassed the shared
GlobalKVCacheBudget, so model-load admission (availableMemoryGb minus
outstanding reservations) and the legacy live-KV gate under-counted when
a v2 slot was active alongside a legacy slot — a concurrent legacy load
could over-commit unified memory. The v2 engine runs its own optimistic +
preemption admission against a private byte ledger, so a per-request
GATING reservation would fight that design (and double-count against the
engine's ledger). Instead each in-flight v2 request records its worst-case
KV footprint (prompt + maxTokens, fp16 rate) in the shared ledger via a
new bookkeeping-only recordEngineKV (never rejects — the v2 engine stays
authoritative for v2 acceptance), released on every terminal/teardown path
in the pump. outstandingReservedBytes() now truthfully includes v2
in-flight KV; the v2 engine's own ledger is unchanged.

Fix #3 (kv_quant fp16 sizing): engine_v2 builds UNQUANTIZED CBv2LayerCache
regardless of kv_quant (makeProductionEngine never builds a quantized
cache), but the slot factory sized the bridge from the scheduler's live
kvBytesPerToken — the QUANTIZED rate when kv_quant=true — overstating v2
token budgets/heartbeats 2–4x and under-sizing the fix-#2 reservation.
EngineV2KVSizing.resolve now picks the fp16 rate (scheduler
fp16KVBytesPerToken) for v2 sizing and emits a WARN engine_health
telemetry (engine_v2_kv_quant_unsupported) once per load when kv_quant
actually engaged for the model.

Tests: sizing decision (both kv_quant configs), record+release invariant
(finish and no-terminal teardown), no-op when rate unknown, and the slot
factory's fp16 sizing + WARN end-to-end via a new BatchScheduler rate seam.
Gajesh2007 added a commit that referenced this pull request Jul 2, 2026
…ant models

Two coupled memory-accounting gaps from PR #499 review (Codex P2 #2 + #3):

Fix #2 (shared-budget KV accounting): the v2 bridge bypassed the shared
GlobalKVCacheBudget, so model-load admission (availableMemoryGb minus
outstanding reservations) and the legacy live-KV gate under-counted when
a v2 slot was active alongside a legacy slot — a concurrent legacy load
could over-commit unified memory. The v2 engine runs its own optimistic +
preemption admission against a private byte ledger, so a per-request
GATING reservation would fight that design (and double-count against the
engine's ledger). Instead each in-flight v2 request records its worst-case
KV footprint (prompt + maxTokens, fp16 rate) in the shared ledger via a
new bookkeeping-only recordEngineKV (never rejects — the v2 engine stays
authoritative for v2 acceptance), released on every terminal/teardown path
in the pump. outstandingReservedBytes() now truthfully includes v2
in-flight KV; the v2 engine's own ledger is unchanged.

Fix #3 (kv_quant fp16 sizing): engine_v2 builds UNQUANTIZED CBv2LayerCache
regardless of kv_quant (makeProductionEngine never builds a quantized
cache), but the slot factory sized the bridge from the scheduler's live
kvBytesPerToken — the QUANTIZED rate when kv_quant=true — overstating v2
token budgets/heartbeats 2–4x and under-sizing the fix-#2 reservation.
EngineV2KVSizing.resolve now picks the fp16 rate (scheduler
fp16KVBytesPerToken) for v2 sizing and emits a WARN engine_health
telemetry (engine_v2_kv_quant_unsupported) once per load when kv_quant
actually engaged for the model.

Tests: sizing decision (both kv_quant configs), record+release invariant
(finish and no-terminal teardown), no-op when rate unknown, and the slot
factory's fp16 sizing + WARN end-to-end via a new BatchScheduler rate seam.
Gajesh2007 added a commit that referenced this pull request Jul 3, 2026
…ma 4 + GPT-OSS 20B) (#499)

* feat(engine-v2): provider bridge for ContinuousBatchingV2 behind DARKBLOOM_ENGINE_V2

- EngineV2Config: env DARKBLOOM_ENGINE_V2 / [backend] engine_v2 key selection,
  gemma-4*/gpt-oss* per-model allowlist (DARKBLOOM_ENGINE_V2_MODELS override),
  EngineV2Factory with safe legacy fallback + WARN engine_health telemetry
  (operation=engine_v2_fallback) on v2 init failure
- EngineV2Bridge: adapts CBv2Engine to the existing GenerationEvent surface;
  event framing mirrors BatchScheduler+EngineBridge (chunk/info/error, abort
  usage-before-error, teardown sentinel); billing-zero max() defense and the
  legacy decode-TPS methodology/EWMA
- EngineV2Bridge+Translation: pure ChatRequest -> CBv2Request translation
  (temperature ?? 0.0 legacy default, logit_bias string-key id parsing,
  logprobs/top_logprobs mapping, seed passthrough, buildStopTokenIds-semantics
  stop resolution, max_tokens defaulting); CBv2KVError.capacityExhausted ->
  canonical token_budget_exhausted: string (429/503 classification unchanged)
- EngineV2Bridge+Capacity: CBv2CapacitySnapshot -> existing BackendSlotCapacity
  fields (no protocol change), truthful bytes-derived token budgets, WedgeMonitor
  reuse + engine_v2 step_wedge transition telemetry
- EngineV2Runtime: process-wide bridge registry; ProviderLoop capacity heartbeat
  folds v2 slots, handleCancellation fans request-id out to CBv2Engine.cancel;
  both no-ops when the flag is off
- ChatCompletionRequest: additive optional logit_bias/logprobs/top_logprobs
  (v2 path only; legacy ignores them)
- docs/engine-v2/CONTRACT-ISSUES-H-provider.md: contract gaps + chosen shapes
- submodule: pin libs/mlx-swift-lm at the CBv2 contracts commit (fe60e17)

* test(engine-v2): bridge unit suite — scripted CBv2Engine stub, no models/network

34 tests in 7 suites (swift test --filter EngineV2):
- translation: field-by-field CBv2Request mapping, legacy greedy defaults,
  logit_bias string-key parsing, logprobs/top_logprobs mapping,
  buildStopTokenIds-semantics stop resolution + construction-time stamping
- event framing: fixture-compare against the recorded legacy
  BatchScheduler+EngineBridge stream shape (chunks -> single info -> finish;
  abort usage-before-error; teardown sentinel; billing-zero max() defense;
  tokenize failure short-circuits before the engine)
- error mapping: capacityExhausted -> token_budget_exhausted (retryable
  .tokenBudgetExhausted class), backendIneligible/unknown -> generationFailed
- cancellation: provider id -> minted CBv2RequestID, unknown-id no-op,
  EngineV2Runtime fan-out (ProviderLoop hook path)
- capacity: snapshot -> BackendSlotCapacity (bytes-derived budgets, idle/
  running states, wedge counters), runtime aggregate summary
- config gating: env/config flag matrix, allowlist + env override, factory
  legacy selection without invoking the builder, init-failure fallback with
  engine_v2_fallback telemetry, engine_v2 TOML key decode

* fix(engine-v2): duplicate request-id guard + deterministic fan-out test

- EngineV2Bridge.submitTokenized: reject a second submit under an active
  request id with the legacy planner's canonical message
  ('token_budget_exhausted: duplicate request ID' -> .requestRejected, 400)
  before minting an engine id, so two pumps can never share bookkeeping
- test: duplicate-id rejection classification + engine isolation
- test: runtimeFanOut holds the submitted stream alive for the whole test;
  dropping it fired onTermination(.cancelled) and raced a second
  (idempotent) engine cancel into the count assertions

* feat(engine-v2): wire ContinuousBatchingV2 into production serving paths

Closes the P1 integration gap: the EngineV2 bridge (DARKBLOOM_ENGINE_V2 /
engine_v2) was implemented and tested but never instantiated outside tests
— model loading always built only the legacy BatchScheduler, both request
paths captured slot.scheduler directly, and the EngineV2Runtime registry
stayed permanently empty.

- Model load (ProviderLoop+ModelLoading -> new ProviderLoop+EngineV2):
  when EngineV2Config selects v2 for a (non-VLM) model, assemble the real
  CBv2 engine over the already-loaded container via the new
  EngineV2Factory.makeProductionEngine (Gemma4/GPT-OSS cbv2LayerKinds +
  newCacheV2, contiguous KV backend sized from the unified-memory KV
  budget, text detokenizer over the model tokenizer), register the bridge
  with EngineV2Runtime, and store it on ModelSlot alongside (never
  replacing) the legacy scheduler.
- Routing: MultiModelBatchSchedulerEngine registry entries and
  AcquiredModel carry the optional bridge; streamChatCompletion submits
  the same tokenized prompt through it when present (translated sampling/
  stop params — v2 additionally honors penalties + stop strings the
  legacy submit drops) and cancels through the owning engine. The
  coordinator inference handler and the unified local endpoint both pass
  slot.engineV2; standalone --local mode intentionally stays legacy.
- Zero-overhead flag-off: capacity heartbeats and cancellation fan-out
  consult the runtime only when at least one v2 slot exists (previously
  an unconditional empty-registry actor hop). A v2-served slot reports
  capacity through its bridge ONLY (the dormant legacy scheduler is
  skipped so the model is never advertised twice). unloadModel
  unregisters and drains the bridge.
- Failure semantics now exercised in production: v2 init throw -> WARN
  engine_health (engine_v2_fallback) + legacy fallback; VLM slots skip
  selection silently (no per-load WARN for permanently-unsupported
  shapes).
- Pin libs/mlx-swift-lm to b2b6d53 (integrated CBv2 engine) — the public
  EngineV2 assembly the production factory constructs did not exist at
  the previously pinned SHA.

Tests (EngineV2ProductionWiringTests, live-isolated, no weights/network):
slot-factory flag-off/allowlist/VLM-gate/init-failure + runtime
registration, both request-routing shapes through a scripted CBv2Engine,
cancellation propagation to the engine-minted id, runtime-guard
zero-consult, heartbeat fold-in with the no-double-report regression,
unload retirement, and the production factory throw paths. 50 EngineV2
tests green; full suite 1214 tests / 96 suites green.

* chore(submodule): bump mlx-swift-lm to engine-v2 final tip 8662159

Pulls the CBv2 contract updates the provider bridge adopts next:
- CBv2Engine is now Sendable (contract-issue H§1 fix)
- CBv2CapacitySnapshot.stepsExecuted monotonic step counter (H§3 fix)
- CBv2Event.delta logprobs populated when sampling.topLogprobs > 0 (E§1)
- CBv2Request.cacheSalt per-request prefix-cache scope (TB-007)
- prefix-cache donation skip for quantized KV; shutdown timeout hardening

* feat(engine-v2): adopt final CBv2 contract — drop engine box, real step counter, logprobs + cacheSalt plumbing

Follow-ups on the engine-v2 bridge against mlx-swift-lm tip 8662159:

- Drop EngineV2EngineBox: CBv2Engine is Sendable in the contract now, so
  the bridge actor holds and calls the engine directly (H§1 resolved).

- Wedge signal from the engine's own counter: WedgeMonitor now samples
  CBv2CapacitySnapshot.stepsExecuted (published every step) instead of
  the bridge's event-count proxy (H§3 resolved). New capacity test pins
  the passthrough plus the flatline-under-hanging-admits wedge verdict.

- Logprobs passthrough (coordinator path): engine delta logprobs are
  converted to the OpenAI streaming entry shape and ride out-of-band via
  a per-request EngineV2LogprobsChannel (bridge pump appends before the
  chunk yield); the inference handler splices them into the next
  content-bearing SSE chunk as choices[0].logprobs = {content: [...]}
  before encryption. The legacy engine NEVER emitted logprobs, so this
  is the OpenAI-standard shape, not a legacy match; the standalone
  --local path (frames served inside the upstream router) still emits
  none. logprobs/top_logprobs are decoded from the sealed body (the
  upstream request type does not model them) like reasoning_effort.

- cacheSalt forward plumbing (inert): the per-tenant cache scope
  (SHA256(prompt_cache_key)/SHA256(user), the same value the legacy
  scheduler threads into the checkpoint cache) now maps onto
  CBv2Request.cacheSalt; "" maps to nil (cache-level salt fallback).
  Production still constructs the v2 engine with prefixCache: nil.

Tests: scripted-stub coverage for channel ordering/conversion, SSE
splice shape + skip rules, extractLogprobsSpec, cacheSalt mapping on
both bridge entry points, and engine wiring threading scope+plumbing.

* chore(submodule): bump mlx-swift-lm to engine-v2 final tip a0ae73b (paged eligibility guard + bench driver)

* chore(submodule): bump mlx-swift-lm to engine-v2 composed tip 255b223 (compiled decode + kernel-opt + profiler)

* fix(engine-v2): thread sealed-body logit_bias + seed through the coordinator v2 translation

The upstream OpenAIChatCompletionRequest models neither logit_bias nor
seed, so the coordinator path's internal ChatCompletionRequest always
carried nil for both and EngineV2Translation silently dropped them
(PR #499 review, Codex P2 #1). Recover them the same way logprobs /
reasoning_effort / cache scope are recovered: decode straight from the
E2E-sealed body (ProviderLoop.extractSamplingOverrides, field-independent
probes) and overlay onto the v2 translation via a new
EngineV2SamplingOverrides plumbing struct. v2 engine path only — the
legacy engine never honored either knob and its submit call is
byte-identical; the --local path still drops both (no provider seam,
documented in the narrowed KNOWN DEVIATION).

Tests: sealed-body extraction (both fields, absence, malformed-field
independence), translate overlay → CBv2SamplingParams, and a
coordinator-path wiring test proving the parsed bias + seed reach the
stub CBv2Engine.

* fix(engine-v2): truthful shared-KV accounting + fp16 sizing for kv_quant models

Two coupled memory-accounting gaps from PR #499 review (Codex P2 #2 + #3):

Fix #2 (shared-budget KV accounting): the v2 bridge bypassed the shared
GlobalKVCacheBudget, so model-load admission (availableMemoryGb minus
outstanding reservations) and the legacy live-KV gate under-counted when
a v2 slot was active alongside a legacy slot — a concurrent legacy load
could over-commit unified memory. The v2 engine runs its own optimistic +
preemption admission against a private byte ledger, so a per-request
GATING reservation would fight that design (and double-count against the
engine's ledger). Instead each in-flight v2 request records its worst-case
KV footprint (prompt + maxTokens, fp16 rate) in the shared ledger via a
new bookkeeping-only recordEngineKV (never rejects — the v2 engine stays
authoritative for v2 acceptance), released on every terminal/teardown path
in the pump. outstandingReservedBytes() now truthfully includes v2
in-flight KV; the v2 engine's own ledger is unchanged.

Fix #3 (kv_quant fp16 sizing): engine_v2 builds UNQUANTIZED CBv2LayerCache
regardless of kv_quant (makeProductionEngine never builds a quantized
cache), but the slot factory sized the bridge from the scheduler's live
kvBytesPerToken — the QUANTIZED rate when kv_quant=true — overstating v2
token budgets/heartbeats 2–4x and under-sizing the fix-#2 reservation.
EngineV2KVSizing.resolve now picks the fp16 rate (scheduler
fp16KVBytesPerToken) for v2 sizing and emits a WARN engine_health
telemetry (engine_v2_kv_quant_unsupported) once per load when kv_quant
actually engaged for the model.

Tests: sizing decision (both kv_quant configs), record+release invariant
(finish and no-terminal teardown), no-op when rate unknown, and the slot
factory's fp16 sizing + WARN end-to-end via a new BatchScheduler rate seam.

* harden(engine-v2): request-id validation, pump lifecycle, bounded logprobs buffer, sanity guards

Security/hardening findings from PR #499 review (ethenotethan):

#4 request-id validation: a caller-supplied request-id is validated
(non-empty, ≤256 chars, no ASCII control chars) before it becomes a
dictionary key / cancel-correlation handle; nil/invalid ids normalize to
a fresh req-<uuid>. Static normalizedRequestId/isValidRequestId are pure
and unit-tested. This also subsumes #11 (duplicate-id): prod ids are
provider-minted UUIDs, and any malformed id is now normalized to a fresh
UUID before the existing duplicate guard, so an attacker cannot induce a
collision — no separate change needed.

#5 nextRawId overflow: += → &+= (wrapping) with a comment; 2^64 is
unreachable in practice, this makes the theoretical overflow explicitly
defined rather than a trap.

#6 engine.submit on the actor: verified O(1) non-blocking enqueue against
the CBv2Engine contract (admission check + register + enqueue, no forward
pass; tokenization already off-actor) and documented it at the call site.
No code change.

#7 pump task lifecycle: per-request pump Tasks are now tracked in
pumpTasks and cancelled by shutdown() (before the engine drain), so none
outlives the bridge; AsyncStream cancellation unwinds each pump through
its teardown path, releasing per-request KV. Tested: shutdown cancels a
live pump and its reservation returns to 0.

#8 bounded logprobs buffer: EngineV2LogprobsChannel caps at 4096 entries
with drop-oldest eviction + a droppedCount and a one-line WARN on first
drop, so a stalled/never-draining consumer can't grow it unboundedly.
Dropping logprobs never affects content/billing/hash (out-of-band).

#9 dropped logit_bias keys: parseLogitBiasCountingDropped returns the
count of dropped (non-numeric/negative) keys; samplingParams emits a
count-only WARN (never the keys — request content) instead of dropping
silently.

#10 kvBytesCapacity sanity: clampKVBytesCapacity caps the v2 admission
ceiling at physical RAM so a mis-derived budget degrades to all-of-memory
rather than an absurd ceiling.

Tests: id validation matrix + normalization-in-submit, wrapping id,
shutdown-cancels-live-pumps, logprobs cap drop-oldest + droppedCount,
dropped-key count, and the capacity clamp. Full suite green (1245).

* fix(engine-v2): record shared-KV reservation atomically with admission; truthful kv_quant WARN

Addresses both reviewers of the PR #499 fixes:

Codex (race): the shared-budget KV reservation was recorded in the
detached pump task, which runs AFTER submitTokenized returns — leaving a
window where a concurrent model-load gate could observe zero v2 KV
between engine admission and the pump starting. Make submit/submitTokenized
async (all call sites already await) and record the reservation
SYNCHRONOUSLY right after engine.submit succeeds, before returning the
stream. The pump now only releases. Tests assert the no-gap invariant
(reservation visible the instant submit returns, no polling).

Claude (truthfulness): move the engine_v2_kv_quant_unsupported WARN below
the makeBridgeIfSelected guard so it fires only when the v2 bridge
actually built. On a v2 init-failure fallback the model serves via
legacy, which DOES honor kv_quant, so warning there was untruthful.

Full suite green (1245).

* chore(submodule): bump mlx-swift-lm to engine-v2 tip e4158bc (PR#62 review fixes)

* fix(engine-v2): gate v2 admission on the shared KV budget before engine submission

The bridge now RESERVES each request's worst-case KV footprint in the
process-wide GlobalKVCacheBudget before engine.submit — atomically on the
budget actor (check + record in one hop) — and rejects with the canonical
token_budget_exhausted capacity error when the shared pool has no headroom,
exactly like the legacy scheduler's KV-reserve rejection. Engine rejections
after the gate release the reservation. The non-gating recordEngineKV is
removed (the gating reserve subsumes it). Degenerate maxTokens<=0 requests
skip the gate (the engine finishes them without allocating KV).

Round-2 PR#499 P2: with another slot's live KV reserved, record-after-accept
could overcommit unified memory on multi-slot providers.

* fix(engine-v2): report committed worst-case tokens in heartbeat budget fields

The coordinator's token-budget gate (activeTokenBudgetUsed +
queuedTokenBudget + requestTokens <= activeTokenBudgetMax) expects 'used' to
carry the committed worst-case reservation of accepted requests — the legacy
scheduler's Σ(prompt + maxTokens) — and never consults max_tokens_potential.
Feeding it materialized KV bytes let the coordinator over-route while
accepted long-max_tokens requests still had unprotected growth.

Mapping (existing wire fields only, documented in backendSlotCapacity):
activeTokens stays engine truth (real KV-resident tokens);
activeTokenBudgetUsed and maxTokensPotential carry Σ(prompt+maxTokens);
activeTokenBudgetMax is the engine byte capacity / fp16 rate (0 when the
rate is unknown, disengaging the gate).

Round-2 PR#499 P2.

* fix(engine-v2): stable (seed, prompt)-derived engine ids for reproducible seeded sampling

The v2 sampler keys its RNG on (seed, requestID.raw, stepIndex), so minting
a fresh monotonic id per submission made identical seeded requests sample
differently depending on prior traffic. Seeded submissions now derive their
engine id from a SplitMix64 chain over (seed, promptTokens), tagged with
bit 63 to stay disjoint from the monotonic family; the id is minted in the
same synchronous stretch as engine.submit so the liveness collision check
cannot race a concurrent identical submission. An identical seeded request
that is still live falls back to a fresh id (documented waiver); batching
reproducibility remains best-effort per the engine contract.

Test: stochastic sampler stub keyed exactly like SamplerV2 proves same-seed
+ same-prompt submissions reproduce identical output across interleaved
traffic, and diverge on different seed/prompt.

Round-2 PR#499 P2.

* fix(engine-v2): size v2 KV admission ceilings against fleet-wide residency

A v2 engine's kvBytesCapacity was derived as if only its own slot's weights
were resident, so multi-slot providers could grant Σ(ceilings) far past the
unified-memory KV budget. The slot factory now derives the ceiling with
EngineV2KVSizing.engineKVBytesCapacity: kvBudgetBytes over ALL resident
models' weights (co-resident slots + the new model) minus the
construction-fixed ceilings already granted to existing v2 engines. When
nothing remains the capacity is 0 and makeProductionEngine throws
noKVHeadroom, so the slot serves via the legacy scheduler (whose per-request
shared-budget gate — and now the v2 bridge's too — needs no static ceiling).

Test hooks now receive the computed capacity ((modelId, kvBytesCapacity))
so wiring tests assert the two-slot derivation end-to-end; pure sizing tests
pin the sum-within-budget invariant and degenerate clamps.

Round-2 PR#499 P2.

* docs(engine-v2): hardening-review rationales — pump-task bound, logprobs lock, cancel scan

- pumpTasks: bounded by the engine's own admission (maxConcurrent +
  maxWaiting, ~68 in production) — pump tasks exist only for
  engine-accepted requests and self-clear on terminal; cite the contract.
- EngineV2LogprobsChannel: why an uncontended NSLock beats actor isolation
  for a two-party bounded append/swap on the delta path.
- EngineV2Runtime.cancel: O(n) scan is over v2-served MODELS (<= slot cap,
  single digits), not requests; an id->bridge index would add hot-path
  register/unregister traffic to save a 3-entry scan on a rare event.

* fix(engine-v2): duplicate re-check across the gate suspension; scope KV release to the reserving request

The shared-budget reserve introduced the bridge's first suspension between
the duplicate-id guard and the bookkeeping install. A concurrent same-id
submission that SKIPS the gate (degenerate maxTokens / unknown rate) could
slip in across that gap and be overwritten; and the pump's unconditional
release could drop a same-keyed reservation owned by a different
submission. Now: re-check active[id] after the reserve (roll back + reject
as duplicate), and the pump releases only when its own submission reserved
(holdsSharedReservation). Degenerate maxTokens<=0 requests are covered by a
test proving they skip the gate even on an exhausted pool.

* chore(submodule): bump mlx-swift-lm to engine-v2 tip ef1ad12 (bench cells on top of e4158bc)

* chore(submodule): bump mlx-swift-lm to engine-v2 tip ec541f5 (PR#62 round-2 review fixes)

* feat(provider): config keys for startup preload + auto-update rollover jitter

New provider.toml keys (all additive; defaults chosen to be fleet-safe):

[backend]
- startup_preload (default true): preload models before coordinator
  registration on boot. A fresh install has no persisted serving set,
  so out-of-the-box behavior is unchanged until a model has been served.
- preload_models (default []): explicit preload list, operator order;
  empty means "the models served before the last restart".
- startup_preload_timeout_secs (default 120): upper bound on how long
  registration is deferred while the preload runs.
- startup_selftest (default true): 1-token greedy decode through the
  serving path after each preload.
- startup_selftest_fail_closed (default false): retire a model whose
  self-test failed instead of keeping it advertised (fail-open).

[provider]
- update_jitter_seconds (default 300): max random delay between staging
  a verified auto-update bundle and beginning the drain+restart.

* feat(provider): startup model preload + registration readiness gate

Fixes the v0.6.30-class cold-restart failure mode: after a release
restart the provider registered (and attracted routing) with NOTHING
loaded, so first requests paid the full ~26 GB weight load + engine
build inside a live request — and at a fleet rollover every box was
cold at once (first_chunk_timeout storm).

- LoadedModelsStore: persists the live serving set to
  ~/.darkbloom/loaded-models.json (data dir — survives auto-updates) on
  every load and every NON-shutdown unload (idle timeout, eviction,
  retirement). Shutdown teardown deliberately preserves it so a
  stop/update/restart remembers what was being served.
- StartupPreloader: sequential, deps-injected preload driver. Memory
  admission never evicts — a candidate that does not fit what is free
  is skipped with a WARN and left to the lazy-load path; failed loads
  and self-tests degrade, never crash.
- ProviderLoop.runStartupPreloadGate(): runs in run() BEFORE the
  coordinator client exists. Plan = preload_models (operator order) or
  the persisted set (biggest first), filtered to advertised models and
  capped at max_model_slots. Each preload is the full ensureModelLoaded
  (weights + legacy scheduler + v2 bridge/warmup when flagged).

  Readiness vs availability: registration is deferred until warm, at
  most startup_preload_timeout_secs (default 120s). On timeout the
  provider registers anyway — a lone provider for a model must still
  serve it cold, and the lazy-load path is unchanged as the fallback —
  while the remaining loads continue in the background. The heartbeat
  warm_models field (which the coordinator's warm-model bonus scores)
  stays truthful throughout: it is derived from live slots only.
- Startup self-test (startup_selftest, default on): after each preload,
  a 1-token greedy decode through the REAL serving path (v2 bridge when
  flagged, else legacy scheduler) forces end-to-end warmth (Metal JIT,
  compiled buckets, chat-template render). Failure emits WARN
  engine_health telemetry and is fail-open by default;
  startup_selftest_fail_closed retires the model from this run's
  advertised set (registration filters through advertisedModels).

Tests (live-isolated, scripted loaders — no weights, no network):
persistence round-trip incl. unload removal + the shutdown-preserve
guard; preloader ordering/admission-skip/failure-continuation/
fail-open/fail-closed/cancellation; plan order + unknown-id filter +
dedup + slot cap; gate defers-until-warm, proceeds-at-timeout with
background continuation, and fail-closed retirement.

* feat(provider): rollover jitter before background auto-update install

Behavior change at defaults (update_jitter_seconds = 300) — justified
as the fleet-rollover fix: providers discover a release on aligned
30-minute update ticks (ticks correlate after any previous synchronized
restart) and drained + restarted in near-unison, putting the entire
fleet cold at the same moment (first_chunk_timeout storm). A uniform
random 0-300s delay between staging the verified bundle and beginning
the drain decorrelates the restarts; combined with the startup preload
gate, warm boxes absorb traffic while each cold box re-warms.

Placement: the delay sits strictly AFTER download + signature
verification (no security-critical check is deferred; the bundle is
already verified and staged, and the provider keeps serving while it
waits) and BEFORE beginDraining. Forced/manual updates — the
darkbloom-update command and the startup update check — do not go
through AutoUpdateController and stay immediate. A 1-hour sanity cap
bounds a misconfigured value.

Tests: delay bounds with a seeded RNG, zero-max and forced bypasses,
the sanity cap, and controller sequencing (jitter strictly between
stage and drain; never invoked on up-to-date / check-failed /
stage-failed paths).

* fix(provider): review fixes — cancel-safe jitter, no-evict preload loads, retirement + persistence hygiene

Review round (Codex + Claude) on the startup-preload/jitter feature found
four real gaps; all fixed with regression tests:

1. Cancel-safe rollover jitter. The jitter closure slept with
   `try? await Task.sleep`, so a shutdown cancelling autoUpdateTask inside
   the (up to 300s) jitter window returned early and the controller
   proceeded to drain + commit + RESTART a shutting-down provider.
   AutoUpdateController now checks Task.isCancelled after
   waitBeforeInstall and aborts with a new .cancelled outcome
   (resumeServing discards the staged bundle; the next tick retries).

2. No-evict preload loads, enforced in the real load path. The
   preloader's freeMemoryGb pre-check was advisory only — the actual
   ensureModelLoaded could still slot-cap-evict or memory-evict an
   EARLIER preloaded (idle) model to fit a later candidate, and a
   local-endpoint load interleaving with the driver could make the
   pre-check stale. ensureModelLoaded/evictUntilAvailable now take
   allowEviction (default true = live-traffic behavior unchanged); the
   startup preload passes false, and the check runs inside the
   serialized isLoadingAny critical section so it cannot go stale.
   Tested against the production load path (fake HF snapshot + real
   admission gates): no-evict refuses at the slot cap and the memory
   gate while the default policy still evicts.

3. Post-registration fail-closed retirement now reaches the
   coordinator. When the gate times out, registration has already
   announced the model; a later self-test retirement only edited local
   state, so the coordinator kept routing it. Retirement now mirrors
   the hard-swap drop: unadvertise on the client store + forceReconnect
   (new provider-side CoordinatorClient method; a fresh register is the
   existing wire mechanism for advertised-set removals — models_update
   is additive, and NO protocol changes are introduced). End-to-end
   test: real CoordinatorClient against MockCoordinator observes the
   second register without the retired model.

4. Loaded-models persistence is inert until run() arms it. The
   persist-on-load/unload write points fired from ANY ProviderLoop —
   including unit tests that install/unload slots — clobbering the
   operator's real ~/.darkbloom/loaded-models.json (the next boot's
   preload plan). Persistence is now gated on loadedModelsPersistenceEnabled,
   set only by run() (and explicitly by the test seam with a temp path).

* fix(engine-v2): honor memory_reserve_gb in v2 KV sizing; clamp heartbeat budget max to live fleet residency (PR#499 r3 P2)

Two coupled capacity-truth fixes on the v2 path:

* memory_reserve_gb in v2 ceilings: UnifiedMemoryCap.kvBudgetBytes gains
  configReserveBytes (effective cap = min(hardCap, physical - reserve),
  the same max(configReserve, capImplied) hold-back the load gate and
  the shared KV gate apply); EngineV2KVSizing.engineKVBytesCapacity
  threads it and the slot factory passes the operator reserve. On
  16/32 GiB boxes (default 4 GiB reserve > cap-implied reserve) the
  bridge no longer advertises/privately admits capacity the shared
  gate rejects post-acceptance.

* Stale activeTokenBudgetMax after later loads: v2 admission ceilings
  are construction-fixed, so a model loaded later (especially a
  legacy/non-allowlisted slot) left existing bridges advertising a
  stale budget the coordinator kept routing against. The heartbeat now
  CLAMPS the reported max to the sizing function's current answer:
  ProviderLoop.updateAggregateCapacity snapshots live fleet residency
  (all slots' weights + operator reserve) into
  EngineV2Runtime.capacitySummary(fleetKV:), which recomputes each
  bridge's budget via EngineV2KVSizing.liveEngineKVBytesBudget
  (min(construction grant, current fleet answer)) and passes it to
  backendSlotCapacity(kvBytesBudgetClamp:). The engine's private
  ledger keeps its grant; only the coordinator-visible figure shrinks.
  Heartbeat cadence only - never the submit path.

Tests: kvBudgetBytes reserve regimes (binding / no-op / degenerate),
pure sizing with reserve both regimes, live-clamp pure math (later
legacy load shrinks by exactly its weights; co-resident v2 grants
subtract; never inflates past the grant; clamps to 0), and an
end-to-end wiring test: load a v2 slot, register a second slot's
weights, heartbeat max shrinks by exactly weights/rate while the
engine keeps its construction grant.

* fix(engine-v2): preserve queue-full classification on v2 admission rejections (PR#499 r3 P2)

EngineV2.submit surfaces BOTH byte-ledger capacity exhaustion and its
waiting-queue-full / draining-for-shutdown guards as
CBv2KVError.capacityExhausted; the bridge mapped every shape to the
generic token_budget_exhausted string, so v2 queue saturation surfaced
as a 503 token-budget failure instead of the legacy 429 + Retry-After
queue-full path.

The two families are distinguishable by shape: the slot-rejection
guards throw the sentinel (needed: 1, available: 0) (no byte estimate
exists), while byte-ledger rejections carry needed = a multiple of the
per-token KV cost (never 1) and available = admissibleBytesCapacity
(> 0 for any constructible engine). EngineV2Translation
.admissionErrorMessage now maps the sentinel to the exact legacy
queue-full string ('token_budget_exhausted: request queue full',
BatchSchedulerTypes.RejectionReason.queueFull), which
fromSchedulerMessage classifies as .queueFull -> 429. Shutdown-drain
riding the same sentinel lands on queue-full too, matching the legacy
handler's .queueFull("provider shutting down"). No new classification
strings, no wire changes.

Tests: sentinel -> queue-full string -> .queueFull -> 429; byte-figure
rejection stays .tokenBudgetExhausted -> 503; near-sentinel byte
figures (needed 2/available 0, needed 1/available 512) never classify
as queue-full. Also carries the bridge/runtime heartbeat-clamp tests
for the previous commit (same test file).

* fix(engine-v2): bound pending logprobs before the first content frame (PR#499 r3 P2)

The inference handler drains the capped EngineV2LogprobsChannel into a
local pendingLogprobs array every frame but only clears it when
injectLogprobs finds a content-bearing frame - so a stream with a long
reasoning-only/tool-only prefix (GPT-OSS reasoning) re-accumulated
everything the channel cap had just bounded, growing without limit and
eventually serializing thousands of entries into one huge first
content chunk.

EngineV2LogprobsChannel.capPending mirrors the channel's own policy on
the caller-held buffer: cap at maxEntries (4096), drop-OLDEST so the
freshest window (the entries nearest the content that eventually
renders) is kept, return the evicted count. The handler re-caps after
every drain, WARNs once on first drop and logs the request's total at
stream end (counts only - never token text; entries are response
content and stay inside the E2E stream).

Tests: drop-oldest at the real 4096 cap with count reporting and
no-op below the cap; frames-loop simulation where a capped window
survives reasoning-only frames and the first content chunk carries
exactly the retained entries.

* chore(submodule): bump mlx-swift-lm to engine-v2 tip 0c5d3a9 (round-3 review fixes)

* chore(submodule): pin mlx-swift-lm to main d63b1c8 (squash-merge of engine-v2 PR #62; content-identical to 0c5d3a9)

* fix(provider): startup self-test no longer poisons Qwen3.5 slots — stale VLM mrope position ids + e2e state isolation

Root cause of the CI e2e regression (test 1 passes, every later test's
provider dies on its first inference with
'[broadcast_shapes] Shapes (1,8,L,64) and (1,1,12,64) cannot be broadcast'):

1. Qwen3.5-0.8B declares a vision_config, so the provider loads it via
   VLMModelFactory. The MLXVLM Qwen35 LanguageModel cached the full-prompt
   mrope position ids (precomputedPositionIds) on the long-lived model
   module and reused them for ANY later forward at cache offset 0. The
   startup self-test decode ('Hi', 12 prompt tokens, maxTokens=1) was the
   first request in every preloading provider, so the first routed request
   with a longer prompt sliced the stale 12-position ids (MLX clamps the
   out-of-range slice), producing cos/sin frozen at (1,1,12,64) against
   the new request's (1,8,L,64) rotary block — process-fatal in the first
   full-attention layer. Fixed in the mlx-swift-lm submodule (d3b1ae9):
   always recompute position ids at sequence start, exactly like Qwen3VL
   and HF transformers; precomputedPositionIds removed. Also covers
   Qwen35MoE (subclass). NOT self-test-specific: ANY second, longer
   text-only request on one scheduler crashed the same way.

2. The e2e testbed launched providers with the real user HOME, so
   ~/.darkbloom/loaded-models.json leaked across testbed instances: test
   1's provider persisted its serving set, and test 2's freshly-booted
   provider startup-preloaded + self-tested it — the trigger that made
   every post-first test hit (1). Providers now get a per-instance temp
   state dir (DARKBLOOM_STATE_FILE + DARKBLOOM_LOADED_MODELS_FILE),
   removed on Stop.

Regression test: StartupSelfTestDecodeLiveTests (weight-gated,
DARKBLOOM_LIVE_MLX_TESTS) loads Qwen3.5-0.8B through the SAME
VLMModelFactory selection production uses and drives the self-test-shaped
request then a longer request through MultiModelBatchSchedulerEngine +
MLXOpenAIService — crashes with the exact production signature without
the submodule fix, passes with it. Validated end-to-end: 4 sequential
e2e integration tests green locally (previously test 2+ crashed 502).

* feat(provider): v0.7.0 engine posture — v2 default-on for exact prod checkpoints, legacy compiled decode opt-in, finish_reason 'length' threaded end-to-end

Three coordinated changes for the v0.7.0 release posture:

1. engine_v2 default TRUE, allowlist narrowed to the EXACT production
   checkpoint ids (mlx-community/gpt-oss-20b-MXFP4-Q8,
   mlx-community/gemma-4-26b-a4b-it-8bit) — default-on scope equals the
   real-model-validated scope; other quantizations/families keep legacy
   until widened via DARKBLOOM_ENGINE_V2_MODELS. DARKBLOOM_ENGINE_V2=0
   stays the absolute per-box kill switch (beats config, no release).
   The v2-init-failure fallback telemetry (engine_v2_fallback, WARN
   engine_health) now also carries the human-readable 'error' reason
   next to error_class + model — it is load-bearing now that v2 is the
   default. Exact-pattern allowlist matching compares last path
   components on both sides so bare ids match org-qualified patterns.
   Retirement (failed self-test) and hard-swap/idle/eviction paths were
   audited for default-on v2: every unload funnels through
   ProviderLoop.unloadModel, which unregisters the bridge from the
   runtime and drains it gracefully before scheduler teardown; the
   hard-swap dropAdvertisedBuild is a lazy advertised-set drop that
   leaves in-flight requests on the resident slot untouched.

2. Legacy compiled decode is now OPT-IN (new [backend] key
   legacy_compiled_decode, default false). The bumped mlx-swift-lm pin
   ships CompiledDecode default-ON; LegacyCompiledDecodeGate forces
   DARKBLOOM_COMPILED_DECODE=0 into the process env at both serve entry
   points (ProviderLoop.run, local standalone) BEFORE any engine/model
   code latches the library's static — unless the operator opted in via
   config or set the env var explicitly (explicit env always wins, both
   directions). Keeps release behavior identical to prod v0.6.30 (the
   compiled-decode rollback); single-stream speed ships via the v2
   canary instead.

3. finish_reason 'length' is threaded end-to-end instead of being
   flattened to 'stop'. GenerationEvent.info gains finishReason; the
   legacy engine bridge passes RequestOutput.finishReason through, the
   v2 bridge maps CBv2FinishReason.length/.stop, the B=1 greedy fast
   path infers length from a full-budget decode, and
   MultiModelBatchSchedulerEngine forwards it as
   ServerGenerationInfo.stopReason (tool_calls still wins). Clients now
   see finish_reason 'length' on max_tokens truncation from BOTH
   engines.

Tests: LegacyCompiledDecodeGateTests (gate matrix + real-env apply,
snapshot/restore), EngineV2 gating suite updated for the exact-id
allowlist + default-on selection matrix (kill switch beats default-on),
fallback telemetry asserts the new 'error' field, v2 bridge test for
.length/.stop/cancelled reason threading. Full provider suite green
(1327 tests); live engine-path tests green (weight-gated).

* docs(provider): review-nit comment fixes — GenerationEvent.info arity in docs, gate empty-env rationale
Gajesh2007 added a commit that referenced this pull request Aug 3, 2026
…on on return

Two of the four Codex review findings on #594 were real. This addresses both.

Rate limit (P2 #3). POST /v1/billing/stripe/dashboard was the only
Stripe-POST billing route without rateLimitFinancial — create-session has
it — so a valid Privy session could loop the route and burn the platform's
Stripe request capacity while minting live credentials. Chained INSIDE
requirePrivyAuth, not outside as the review suggested: rateLimitWithTier
keys on consumerKeyFromContext, which only the auth middleware populates,
so an outer limiter would collapse every caller into one empty-string
bucket. This matches all ten sibling financial routes and
rateLimitFinancial's own doc comment.

Stale destination (P2 #1). The dashboard opens in another tab, so the
original kept rendering the pre-change destination_last4 and — worse —
openWithdraw seeds withdrawMethod from the same stale instant_eligible.
stripe_withdraw.go admits instant when EITHER the fresh account or the
stored flag says eligible, so a card -> bank switch got an instant payout
accepted, rejected by Stripe, and the fee charged then refunded before
falling back to the daily sweep. A one-shot visibilitychange handler now
pulls refresh=1 on return (not the cached read: account.updated may not
have landed yet). It lives in an effect so it is torn down if the page
unmounts before the user comes back.

Not addressed, deliberately:

  P2 #2 (pending vs awaiting-verification) is correct — an account with
  details_submitted=true, payouts_enabled=false and no currently_due maps
  to "pending" and gets 409'd despite having a Stripe dashboard — but
  PayoutDestinationRow renders only in the ready branch, so no UI path
  reaches it. Adding a Stripe round-trip to unblock a dead path is not
  worth it.

  P2 #4 (dashboard-initiated payouts never reconcile) is real but
  pre-existing: live-mode Express holders already self-serve at
  connect.stripe.com/express_login with email + OTP, no platform link
  required, so reconcileUnmatchedPayout's !pe.Automatic early return
  already strands those rows today. Attributing non-automatic payouts to
  withdrawal rows is a separate change to the webhook state machine.

Tests: both fixes negative-controlled (reverted each, confirmed its test
fails, restored). gofmt/go vet clean; go test ./api/... ./billing/... pass;
eslint 0 errors; vitest 499 passed.
Gajesh2007 added a commit that referenced this pull request Aug 3, 2026
…ves (#594)

* feat(billing): let providers change their payout bank account themselves

Providers with a fully onboarded Stripe Express account had no way to
change the bank account their earnings land in. The onboarding link we
already expose only collects outstanding requirements, and a `ready`
account has none, so it bounces straight back to the return URL; Stripe
forbids `account_update` links for any account with a Stripe-hosted
dashboard, which every Express account has. The only remaining option
was unlinking and re-onboarding a brand new connected account, throwing
away completed KYC — so the request arrived as a support ticket instead.

Add the Express Dashboard login link, which is exactly the supported
path for this. `POST /v1/billing/stripe/dashboard` mints a single-use
URL and the ready-state payout card gains a "Change in Stripe" action
next to the destination chip.

Gated on requirePrivyAuth rather than requireAuth: the URL is a bearer
credential for a session that can redirect a user's earnings to another
bank account, so an inference API key must not be able to mint one.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(billing): harden the dashboard link after review

Two independent reviews of the previous commit found one must-fix and a
set of real edge cases.

The must-fix: nothing tested that the new route rejects API keys. Since
requireAuth also populates the user context for account-bound keys and
provider device tokens, the in-handler requirePrivyUser is not a second
line of defense — the route-level middleware is the only gate, and
swapping that one line would have left the whole suite green while
letting a leaked inference key mint a session that redirects a
provider's earnings. Now driven through the real mux, mirroring
TestStripeUnlinkRouteRejectsAPIKey.

Also:
- Reuse the existing error vocabulary (not_onboarded,
  stripe_account_gone) instead of coining parallel spellings the
  frontend classifier wouldn't have matched.
- Reject accounts that haven't submitted details. Stripe has no Express
  Dashboard for them, and the raw error told the user to retry something
  that can never work. Restricted and rejected accounts do have a
  dashboard, so they still get through.
- Return 500 rather than claiming an unlink when persisting it failed.
- Don't burn the single-use link when the pre-opened tab was closed, or
  when the response arrives without a url; navigate with replace() so the
  credential never enters session history.
- Extract PayoutDestinationRow, taking the card's cognitive complexity
  to 24 — below its pre-existing baseline of 30.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(billing): rate-limit the dashboard link and refresh the destination on return

Two of the four Codex review findings on #594 were real. This addresses both.

Rate limit (P2 #3). POST /v1/billing/stripe/dashboard was the only
Stripe-POST billing route without rateLimitFinancial — create-session has
it — so a valid Privy session could loop the route and burn the platform's
Stripe request capacity while minting live credentials. Chained INSIDE
requirePrivyAuth, not outside as the review suggested: rateLimitWithTier
keys on consumerKeyFromContext, which only the auth middleware populates,
so an outer limiter would collapse every caller into one empty-string
bucket. This matches all ten sibling financial routes and
rateLimitFinancial's own doc comment.

Stale destination (P2 #1). The dashboard opens in another tab, so the
original kept rendering the pre-change destination_last4 and — worse —
openWithdraw seeds withdrawMethod from the same stale instant_eligible.
stripe_withdraw.go admits instant when EITHER the fresh account or the
stored flag says eligible, so a card -> bank switch got an instant payout
accepted, rejected by Stripe, and the fee charged then refunded before
falling back to the daily sweep. A one-shot visibilitychange handler now
pulls refresh=1 on return (not the cached read: account.updated may not
have landed yet). It lives in an effect so it is torn down if the page
unmounts before the user comes back.

Not addressed, deliberately:

  P2 #2 (pending vs awaiting-verification) is correct — an account with
  details_submitted=true, payouts_enabled=false and no currently_due maps
  to "pending" and gets 409'd despite having a Stripe dashboard — but
  PayoutDestinationRow renders only in the ready branch, so no UI path
  reaches it. Adding a Stripe round-trip to unblock a dead path is not
  worth it.

  P2 #4 (dashboard-initiated payouts never reconcile) is real but
  pre-existing: live-mode Express holders already self-serve at
  connect.stripe.com/express_login with email + OTP, no platform link
  required, so reconcileUnmatchedPayout's !pe.Automatic early return
  already strands those rows today. Attributing non-automatic payouts to
  withdrawal rows is a separate change to the webhook state machine.

Tests: both fixes negative-controlled (reverted each, confirmed its test
fails, restored). gofmt/go vet clean; go test ./api/... ./billing/... pass;
eslint 0 errors; vitest 499 passed.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies Pull requests that update a dependency file javascript Pull requests that update javascript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants