Repository navigation
Bump the npm_and_yarn group across 2 directories with 2 updates - #4
Closed
dependabot[bot] wants to merge 1 commit into
Closed
dependabot[bot] wants to merge 1 commit into
dependabot[bot] wants to merge 1 commit into
Conversation
dependabot
Bot
force-pushed
the
dependabot/npm_and_yarn/settlement/npm_and_yarn-f1204c3a62
branch
from
April 1, 2026 21:03
f7e634d to
335407f
Compare
Bumps the npm_and_yarn group with 1 update in the /settlement directory: [picomatch](https://github.com/micromatch/picomatch). Bumps the npm_and_yarn group with 1 update in the /web directory: [next](https://github.com/vercel/next.js). Updates `picomatch` from 4.0.3 to 4.0.4 - [Release notes](https://github.com/micromatch/picomatch/releases) - [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md) - [Commits](micromatch/picomatch@4.0.3...4.0.4) 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: picomatch dependency-version: 4.0.4 dependency-type: indirect dependency-group: npm_and_yarn - 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
Bot
force-pushed
the
dependabot/npm_and_yarn/settlement/npm_and_yarn-f1204c3a62
branch
from
April 1, 2026 23:11
335407f to
58cb329
Compare
Contributor
Author
|
Looks like these dependencies are updatable in another way, so this is no longer needed. |
dependabot
Bot
deleted the
dependabot/npm_and_yarn/settlement/npm_and_yarn-f1204c3a62
branch
April 3, 2026 01:54
This was referenced Apr 24, 2026
3 of 6 tasks
anupsv
added a commit
that referenced
this pull request
May 29, 2026
… 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).
This was referenced May 30, 2026
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.
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…
anupsv
added a commit
that referenced
this pull request
Jun 15, 2026
Point the submodules at the merged commits carrying the Metal resource-COUNT crash fix: - libs/mlx-swift -> ac67822 (merged #4 Swift surface + #5 .gitmodules repoint to the Layr-Labs mlx/mlx-c forks + Cmlx pointer bump, i.e. the count-aware cache trim in MetalAllocator::malloc and the Memory.numResources / Memory.resourceLimit getters) - libs/mlx-swift-lm -> 404afee (merged #39 env-gated [rsrc] telemetry) This makes MLX.Memory.resourceLimit / .numResources resolve, so the live resource-count probes in ContinuousBatchingLiveTests compile. Verified locally: provider `swift build` and `swift build --build-tests` both complete clean (ContinuousBatchingLiveTests.swift compiles), with the nested Cmlx submodules resolving from the forks at the fix commits.
anupsv
added a commit
that referenced
this pull request
Jun 15, 2026
Point the submodules at the merged commits carrying the Metal resource-COUNT crash fix: - libs/mlx-swift -> ac67822 (merged #4 Swift surface + #5 .gitmodules repoint to the Layr-Labs mlx/mlx-c forks + Cmlx pointer bump, i.e. the count-aware cache trim in MetalAllocator::malloc and the Memory.numResources / Memory.resourceLimit getters) - libs/mlx-swift-lm -> 404afee (merged #39 env-gated [rsrc] telemetry) This makes MLX.Memory.resourceLimit / .numResources resolve, so the live resource-count probes in ContinuousBatchingLiveTests compile. Verified locally: provider `swift build` and `swift build --build-tests` both complete clean (ContinuousBatchingLiveTests.swift compiles), with the nested Cmlx submodules resolving from the forks at the fix commits.
Gajesh2007
added a commit
that referenced
this pull request
Jun 15, 2026
* Add live resource-count probes for the Metal resource-limit crash Two env-gated live tests characterise the `[metal::malloc] Resource limit (499000) exceeded` crash by driving batched decode and watching the Metal buffer COUNT (via the engine's [rsrc] telemetry): a small Qwen3-0.6B churn probe (varied prompt lengths across waves) and a sustained Gemma-4-26B high-concurrency probe. Both set a huge cacheLimit to mimic the big-RAM prod box where the byte-driven cache trim never fires, isolating pure count growth. Gated behind DARKBLOOM_LIVE_MLX_TESTS / _GEMMA / _MLX_RESOURCE_DEBUG so they never run in normal CI. * Add Metal resource-count fix handoff doc (fork-vs-vendor + merge order) * Bump mlx-swift + mlx-swift-lm to the resource-count fix Point the submodules at the merged commits carrying the Metal resource-COUNT crash fix: - libs/mlx-swift -> ac67822 (merged #4 Swift surface + #5 .gitmodules repoint to the Layr-Labs mlx/mlx-c forks + Cmlx pointer bump, i.e. the count-aware cache trim in MetalAllocator::malloc and the Memory.numResources / Memory.resourceLimit getters) - libs/mlx-swift-lm -> 404afee (merged #39 env-gated [rsrc] telemetry) This makes MLX.Memory.resourceLimit / .numResources resolve, so the live resource-count probes in ContinuousBatchingLiveTests compile. Verified locally: provider `swift build` and `swift build --build-tests` both complete clean (ContinuousBatchingLiveTests.swift compiles), with the nested Cmlx submodules resolving from the forks at the fix commits. * Address review: restore cacheLimit in probes; refresh handoff doc - Resource-count probes now snapshot MLX.Memory.cacheLimit and restore it in a defer (cacheLimit is process-global and Swift Testing shares the process, so the 80GB byte-trim-off setting would otherwise leak into other suites). Also switch to the non-deprecated Memory.cacheLimit property setter. - Handoff doc: the C++ fix is no longer local-only / in /tmp — point at the pushed fork commits + the darkbloom-metal-resource-count tags instead. * Address review: also lift memoryLimit in resource probes The byte-pressure reclaim in MetalAllocator::malloc fires on gc_limit_, which is derived from memoryLimit — NOT from cacheLimit. A prior live test can leave memoryLimit at 12–16GB via LiveInferenceFixtures.applyMemoryBudget (process- global; Swift Testing shares the process), so raising only cacheLimit still lets byte pressure free cached buffers and flatten the resource-count trajectory — a false negative for the count-limit bug. Both probes now raise AND restore memoryLimit alongside cacheLimit. --------- Co-authored-by: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
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
Jul 2, 2026
…probs 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).
Gajesh2007
added a commit
that referenced
this pull request
Jul 2, 2026
…probs 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).
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
Jul 9, 2026
…video+prefix on CBv2, KV re-slicing, fail-loud (#522) * chore(engine): bump mlx-swift-lm to 24c592c — vision prefill merged to main (+ Codex P2 fixes, fused-cache base) * feat(provider): vision requests through Engine V2 on Gemma 4 VLM slots (v0.7.4) Image requests on a v2-bridged Gemma 4 slot now prefill through the CBv2 engine instead of the legacy non-batched wrapper path — vision joins the continuous batch: - EngineV2VisionPrefill: decode media exactly as legacy (buildUserInput, same caps/errors), run the SAME Gemma4Processor.prepare (resize/ normalization/templating/placeholder expansion), run the wrapper's vision tower + projector via the new per-image seam and eval under container isolation (engine step loop never pays the tower cost), carve one CBv2ImageSpan per image out of the placeholder runs (ascending/non-overlapping/in-prompt by construction; adjacent images carve into adjacent spans the engine coalesces into one block). - MultiModelBatchSchedulerEngine: media branch attempts v2 when the slot has a bridge and the request has no video (hasVideo gate — video stays wholly on legacy, deliberately not half-supported); ANY construction failure -> WARN engine_v2_vision_fallback + unchanged legacy path (never a dropped request); CancellationError releases and rethrows instead (no WARN, no legacy re-serve). Vision reservation released once the bridge owns the request (its shared-budget gate covers prompt incl. soft tokens + max_tokens). Shared event-translation pump extracted (makeEventStream) and reused by both text-v2 and vision-v2 paths. Injectable EngineV2VisionPlumbing so unit tests drive the routing without weights. - EngineV2Bridge.submitTokenized(multimodal:) threads the spans + precomputed embeddings into CBv2Request; INFO engine_v2_vision telemetry per accepted vision request (filter-at-source). - Submit-time CBv2MultimodalError -> canonical multimodal_rejected: message -> .multimodalRejected -> HTTP 400 (deterministic rejections, never retry-signaled as capacity). - Telemetry: multimodal boolean field allowlisted in all three mirrors (Swift filter, Go coordinator, console-ui TS). Fallback WARN carries the human-readable error only for the content-safe EngineV2VisionPrefillError; foreign throws get error_class only. Unit tests (scripted CBv2Engine, stub container, injected preparer): span carving incl. adjacency/at-start/mismatches, bridge passthrough of spans+embeddings+telemetry, routing success, vision-reservation released exactly once (real GlobalKVCacheBudget), construction-failure fallback + WARN, non-bridged/video/text gates, multimodal_rejected->400. * test(provider): live vision-through-v2 suite on the prod Gemma 4 checkpoints New self-contained GemmaVLMVisionEngineV2LiveTests (deliberately independent of GemmaVLMEngineV2LiveTests — that file is owned by the concurrent 0.7.3 hotfix and is untouched here): - a real image request end-to-end through v2 (real vision-tower embeddings at real spans), asserted to actually take the v2 path (bridge admit count + zero fallback WARNs); - greedy determinism (same image + prompt twice => identical) and embedding steering (red vs blue image, same prompt => different completions — the key 'spans/embeddings actually reach the model' regression); - legacy-vs-v2 output for the same input logged, asserted only qualitatively (v0.7.2 RoPE-correctness divergence between extracted model and wrapper makes token-exactness a non-invariant, mirroring the parity-gate reasoning); - interleave hygiene: legacy-vision and v2-vision requests between v2 text decodes leave the text output bit-identical (mrope-class regression pattern); - structured teardown: unload/shutdown awaited on every exit path. * fix(provider): pre-stream cancellation reports the canonical 499, never a mapped 500 Codex quality-gate finding on the v0.7.4 range: a CancellationError thrown while STARTING the stream (consumer cancel during prompt templating or vision-feature construction — handleCancellation cancels the detached request task, and the vision seam rethrows instead of falling back to legacy) was caught by the generic pre-stream catch and mapped via mapInferenceErrorToStatus, which fell through to 500 — a client's own cancel counted as a provider .inferenceError and could trip the (provider, model) 5xx routing cooldown. - ProviderLoop+InferenceHandler: the pre-stream catch special-cases CancellationError / token.isCancelled and mirrors the established cancelled-with-nothing-delivered terminal exactly: 499 + "request cancelled" + the cancellations-before-output stat. - ProviderLoop+ErrorMapping: CancellationError -> 499 at the top of mapInferenceErrorToStatus as defense-in-depth for every other call site (the standalone --local HTTP path). - Test (routing harness): cancel during vision construction -> CancellationError propagates (no fallback WARN, engine untouched), model reservation released exactly once, vision KV reservation fully released, and the mapper reports 499. * release(provider): v0.7.4 — bump ProviderCore.version + LatestProviderVersion (0.7.3 is the shared-KV-gate hotfix release, shipped separately.) * fix(provider): correct stale v2 media-routing log — images route through v2 in 0.7.4, video stays legacy * docs(threat-model): T-041 — prefix cache on engine v2 is RAM-only PrefixCacheV2; salt scoping live * feat(engine-v2): enable PrefixCacheV2 — RAM-only, salt-scoped, budget carved from engine KV ceiling - PrefixCachePolicy (scheduler-free): DARKBLOOM_PREFIX_CACHE gate (default ON, 0/false/off/no opt-out), DARKBLOOM_PREFIX_CACHE_MAX_GB budget (default physical/8 — legacy numbers verbatim), and the carve that splits a slot's fleet-sized KV grant between engine admission ceiling and cache budget (1 GiB serviceable floor: live KV wins, the prefix budget shrinks; sub-one- block budgets degrade to off). Legacy gate/budget/stats resolvers delegate here — one source of truth until legacy deletion. - makeEngineV2BridgeForSlot is THE single carve point: the engine, its AdmissionV2 ledger, the bridge capacity snapshot, and the heartbeat activeTokenBudgetMax all read the REDUCED capacity (engine truth); fleet sizing and the heartbeat clamp subtract co-resident slots' TOTAL claims (engine ceiling + cache budget, EngineV2Bridge.slotKVBytesClaim) plus the slot's own cache budget, so the coordinator is never told about bytes the cache consumes. - makeProductionEngine(prefixCache:): non-nil ⇒ enablePrefixCache — TB-007 comment replaced with the updated T-041 posture; cacheScope → CBv2Request .cacheSalt plumbing is now live. - Per-request usage detail: bridge records engine prefixCacheHitTokens into EngineV2RequestUsageSignal (logprobs-channel pattern); the inference handler splices OpenAI-standard usage.prompt_tokens_details.cached_tokens into the trailing SSE usage chunk (injectCachedTokens, mirror of the reasoning_tokens splice). - Periodic stats: bridge-owned logger mirrors the legacy checkpoint-tier line with an engine=v2 tag (PrefixCacheV2.stats(): hits/misses/tokensSaved/ entries/bytes), DARKBLOOM_PREFIX_CACHE_STATS_INTERVAL_SECS cadence, cancelled on bridge shutdown. * test(engine-v2): prefix cache policy + wiring suites — gate, budget, carve, capacity agreement, salt plumbing, cached_tokens splice - PrefixCachePolicyTests: env-gate semantics (default ON, 0/false/off/no), MAX_GB budget override + physical/8 fallback, legacy-resolver delegation pins (no drift), carve conservation/floor-guard/one-block viability, makePrefixCache config (blockSize 256, model namespace, byte budget). - EngineV2PrefixCacheWiringTests: gate-off ⇒ raw grant + zero budget; gate-on ⇒ engine handed grant−budget; capacity-reduction AGREEMENT test (engine snapshot == bridge claim math == heartbeat activeTokenBudgetMax); co-residency test pinning that a later slot subtracts the earlier slot's TOTAL claim (engine ceiling + cache budget); cacheScope→cacheSalt bridge plumbing (distinct/stable/empty); EngineV2RequestUsageSignal terminal recording; injectCachedTokens splice/merge/passthrough. - slotFactoryUsesFleetResidency opts out of the (default-on) carve so it keeps pinning pure fleet sizing; heartbeatBudgetShrinksWhenSecondSlotLoads now runs WITH the carve — passing unchanged proves the own-budget clamp accounting. * test(engine-v2): EngineV2PrefixCacheLiveTests — live exactness/hit/batch-invariance on gpt-oss-20b + gemma-4-26b-qat Multi-turn conversation per model, turn-1 prefix sized past the model's own recompute bound (windowCount × maxWindow from cbv2LayerKinds — 1,536 for gpt-oss, 25,600 for gemma-4): (a) turn-2 greedy output byte-identical cache-on vs cache-off (two makeProductionEngine constructions, hybrid-window recompute exercised), (b) prefixCacheHitTokens > 0 with a shared-prefix-block lower bound, read through EngineV2RequestUsageSignal, (c) cached row + cold row batched together match their solo outputs. TTFT deltas logged. Gates: DARKBLOOM_LIVE_MLX_TESTS + _GPTOSS / _GEMMA; clean skip when weights absent. * fix(engine-v2): prefixCacheBudgetBytes is nonisolated — cross-module readers (heartbeat, tests) need no actor hop * chore(libs): pin mlx-swift-lm to cbv2/v075-engine — resizable KV capacity + Gemma4 video seam Local pin for the v0.7.5 integration branch; re-pointed to the merged mlx-swift-lm commit at ship time. * fix(test): size gemma live-prefix prompts by probe-extrapolation — 4x overshoot blew the engine's 120s request deadline The first sizing loop assumed ≥8 tokens/line and rendered 104k-token prompts (target 26.4k); every gemma request then died at the CBv2 loop's 120s per-request deadline. Probe 64 lines for the real per-line rate, extrapolate, top up by measured deficit (~2% slack). Also relax the shared-prefix assertion: turn 2 shares turn 1's prompt minus the template's generation suffix (4 tokens on gemma), which is irrelevant to whole-block chain matching — require shared ≥ the sized minimum instead. Result on M4 Max: turn1=27,936 tok, hit=2,304 (=109 shared blocks − 25,600 recompute bound, exact), byte-identical turn-2, batch invariance green, 129.7s total. * feat(provider): scheduler-free slot components + KV re-slice policy Scheduler-free homes for everything the v2 slot lifecycle used to parasitize from the always-constructed legacy BatchScheduler: - SlotSizingSnapshot: weight bytes + fp16 kvBytesPerToken derived from the model's own cbv2LayerKinds (engine truth — the long-context marginal rate of AdmissionV2.estimatedBytes; VLM checkpoints decode text_config with the same decoder the extraction uses) + context window + default max tokens. KVEstimation's config.json parse stays as the pre-load estimate/fallback only. - ModelEOSPolicy: BatchScheduler.effectiveEOSTokenIds re-homed unchanged (scheduler static now forwards). - KVHeadroomProbe: measuredLiveKVHeadroomBytes/hasServeableKVHeadroom re-homed (pure UnifiedMemoryCap math; scheduler members forward). - VisionMemoryGate: reserveVisionRequest/releaseVisionRequest re-homed as a per-slot value gating media-decode RAM + generation KV against the shared GlobalKVCacheBudget. - EngineV2SupportedModels: architecture-derived supported set (mirror of the makeProductionEngine switch keyed on config model_type: gpt_oss + gemma4*). - EngineV2KVSizing.resliceGrants: pure fair-share re-slice policy for multi-model co-residency — single model keeps the FULL fleet budget, >=2 share proportional to fp16 rate x min(context, 131072), equal split degenerate, sum(grants) <= budget invariant, and the 1 GiB serviceability floor check that refuses loads which would thrash every slot below serviceability. * feat(engine-v2): per-model prefix-cache funding gate — hybrid models whose adoption bound exceeds real prompt lengths keep their full KV grant The engine adopts a cached prefix only past windowCount × maxWindow matched tokens (cbv2RequiredRecompute; EngineV2.makeAdoption declines less). For gemma-4-26B that bound is 25 × 1024 = 25,600 tokens against a production p90 prompt of ~4k — hits are unreachable, yet the carve was still taking physical/8 (16 GiB on 128 GB; ~4.5 GB on 36 GB gemma boxes) out of the engine's live-KV ceiling for zero benefit, cutting gemma concurrency. - PrefixCachePolicy: adoptionBoundTokens(layerKinds:) (the exact bound term of the engine's recompute derivation), maxAdoptionBoundTokens env (DARKBLOOM_PREFIX_CACHE_MAX_ADOPTION_BOUND_TOKENS: absent/malformed => 4,096 default; 0 => never fund), shouldFund(adoptionBoundTokens:) — gpt-oss (1,536) funds, gemma-4 (25,600) does not; bound-unknown treated as 0/fund (pure-full-attention semantics; documented). Rationale in the file header. - Slot factory: model snapshot moved ahead of the carve; the gate resolves the bound from the loaded model (text slots, via the factory's family switch: EngineV2Factory.adoptionBoundTokens(model:)) or from the checkpoint's text_config alone for VLM slots (EngineV2VLMTextExtraction.adoptionBoundTokens(modelDirectory:) — no extraction run). Unfunded => requested budget 0 => carve passthrough: full grant to live KV, no cache instance, no stats logger; serving log names the unfunded reason (bound + cap). - Tests: policy units (bound derivation incl. prod shapes + mixed windows, threshold env semantics, funding matrix incl. boundary + never-fund), wiring (threshold-0 unfunded through the slot factory: raw grant, zero bridge budget, claim == capacity; unknown-family resolver => 0), live (gemma pins the UNFUNDED default verdict end-to-end — incl. config-only bound == loaded-model bound — then runs the funded hybrid-recompute scenario as the explicit operator override; gpt-oss pins funded-by- default). gpt-oss 15.9s (hit 768 exact, TTFT 2.78s->1.65s), gemma 147.8s (hit 2,304 exact under the override), full suite 1,391 green. * feat(provider): video-through-v2 — media prefill for image+video on engine_v2, fail-loud refusals Generalize EngineV2VisionPrefill from images-only to all media on a v2-bridged Gemma 4 VLM slot: - Span carving walks the prompt once, pairing placeholder runs of BOTH token ids (image + video) with per-kind tower features strictly in prompt order — one CBv2ImageSpan per image and per sampled video frame (perVideoFrameVisionFeatures, ≤32 uniformly sampled frames, per-frame data-driven soft-token counts). Frame-count/span-count mismatches throw in both directions; the defensive videoUnsupported throw is gone. - Routing: the hasVideo → legacy peel-off in MultiModelBatchSchedulerEngine is removed; video and mixed requests prefill through the engine like images. Byte/pixel/duration caps are unchanged (same validateMedia + buildUserInput path; inline-video temp files cleaned up inside prepare). - FAIL LOUD: v2 media construction failure no longer falls back to the legacy VLM path — it emits an engine_v2_vision_refusal ERROR (tagged media_kind image/video/mixed) and returns a retriable 503 (.requestRejected) so the coordinator's pre-content failover reroutes. CancellationError still propagates as 499; MediaError keeps its deterministic 4xx (400 / videoWriteFailed 500). The legacy wrapper path remains reachable only on slots without a v2 bridge. - Telemetry: engine_v2_vision success INFO + the new refusal ERROR both carry media_kind; the field is allowlisted in all three mirrors (Swift TelemetryFieldFilter, coordinator telemetry_handlers.go, console-ui telemetry-types.ts). Tests: EngineV2VisionRoutingTests extended (video routes to v2, mixed carving order, frame-count mismatch → refusal, construction failure → refusal with media-kind tag + budget release, MediaError keeps 4xx, garbage video still 400s pre-preparer); new GemmaVLMVideoEngineV2LiveTests generate deterministic solid-color H.264 clips via AVFoundation at test time (no committed binaries) and verify construction introspection, v2 serve + greedy determinism + steering, token parity vs the legacy VLMRequestInference.stream reference (token-exact on qat-4bit), the 32-frame sampling cap end-to-end, and TTFT logging. Vision live suite re-run green as regression. * fix(provider): review follow-ups — deterministic 400 for role-dropped media, media-kind tag alignment Independent-review findings on the video-through-v2 commit: - A media request whose parts all sit on non-user roles (buildUserInput drops them, so the processor yields no pixels) previously became a retriable 503 refusal that fails identically on every provider — pre-content failover would burn retries for nothing. noProcessedMedia now maps to .multimodalRejected (400, deterministic client fault, no refusal telemetry), mirroring the MediaError stance. - EngineV2VisionPrefill.mediaKind(of:) now scans user messages only, so refusal media_kind tags match the success path's lmInput-derived kind. - ProviderLoop+ErrorMapping.swift: the .multimodalRejected comment still claimed construction failures fall back to the legacy VLM path — rewritten for the fail-loud contract. - New tests: noProcessedMedia → 400 with no refusal event; refusal on a video request tags media_kind=video; mediaKind ignores non-user-role media. * feat(provider)!: v2-only slot lifecycle — KV re-slicing, fail-loud refusal, supported-set gate, v2-only heartbeat The one-engine core of v0.7.5. Every model slot serves through the CBv2 engine; the legacy BatchScheduler is no longer constructed anywhere in the ProviderLoop serving path (it remains only for the standalone 'darkbloom local' server, a separate workstream). KV re-slicing (root fix for the gemma postmortem layer 5): - ensureModelLoaded final sequence: loadContainer -> Metal/MLX guards (moved from scheduler.loadModel) -> SlotSizingSnapshot.build -> clearCache + KVHeadroomProbe (unload+503 on fail, v0.7.3 guard re-homed) -> reslice: SHRINK existing engines via their bridges' updateKVBytesCapacity -> makeBridge with the newcomer's grant (on throw: RESTORE previous grants exactly, unload, 503) -> register -> post-bridge headroom re-guard -> install slot + record model_load_time_ms on the bridge. - unloadModel: unregister -> bridge.shutdown -> clearCache -> reslice-GROW survivors (lone survivor gets the FULL budget back). - Serviceability floor: a slice leaving any slot under 1 GiB refuses the load (engine_v2_refusal reason=reslice_floor, 503) instead of thrashing all slots below serviceability. - The heartbeat clamp (liveEngineKVBytesBudget) stays as the between-reslice safety net and now reads each engine's CURRENT grant per heartbeat (engine capacity() reflects resizes). Fail loud, never fall back: - EngineV2Factory.makeBridgeIfSelected (nil-on-failure) -> throwing makeBridge; WARN engine_v2_fallback becomes ERROR engine_v2_refusal with a machine-classifiable reason (no_kv_headroom / unsupported_model / vlm_extraction_failed / reslice_floor / engine_init_failed). All fields already on the telemetry allowlist. - The selection gate dies: EngineV2Config.selection, the model allowlist, and DARKBLOOM_ENGINE_V2(_MODELS) consumption are deleted. The engine_v2 config key stays parsed-but-ignored; startup WARNs when it or the retired env vars are set. - Scan/advertise-time supported set (EngineV2SupportedModels — mirror of the makeProductionEngine switch keyed on config model_type: gpt_oss + gemma4*): unsupported families are dropped from the advertised set at ProviderLoop init (the single chokepoint feeding coordinator registration and the local /v1/models) and at prefetch-verify time. A stale-catalog load request 404s via the existing mapping; coordinator load_model pushes get load_model_status: failed. - Request-time backstop: a TEXT request reaching a registry entry with no engine at all is a hard 500 internal error. The media peel-off branch is untouched (video still runs the legacy VLM container path in this branch state — owned by the video workstream); its memory reservations now flow through the scheduler-free VisionMemoryGate. - ModelSlot: engineV2 non-optional, scheduler field DELETED, sizing snapshot + vision gate attached. Heartbeat/capacity + concurrency config + prefill: - updateAggregateCapacity: the legacy backendCapacity() fold is deleted; EngineV2Runtime.capacitySummary(fleetKV:) is the only slot source. Same BackendSlotCapacity wire shape, same state strings; no protocol changes. Fleet weights come from slot sizing snapshots. - model_load_time_ms moves to slot-level bookkeeping on the bridge (measured across the full load: weights + sizing + engine build). - productionMaxConcurrentRequests = 4 -> config: [backend] engine_v2_max_concurrent (default 4) + per-model map engine_v2_max_concurrent_by_model, clamped to [1, 8]; heartbeat max_concurrency reports the effective per-slot value. - observed_prefill_tps is now populated by the v2 bridge: prefill window = first-token time - submit, rate = prompt tokens / window, EWMA alpha 0.3, with PR #454's plausibility bounds (1 ms floor, raised 20k tok/s ceiling). This ABSORBS and supersedes #454's intent for the v2 engine — that PR's engine-side prefill-start marker was built for the legacy engine; the v2 bridge owns both timestamps natively, so no engine change is needed. Existing suites updated from legacy-fallback semantics to refusal semantics (EngineV2BridgeTests, EngineV2ProductionWiringTests) and to the bridge-required ModelSlot (LoadedModelsStoreTests, StartupPreloadTests, shared EngineV2TestStubs). * test(provider): re-slice policy, sizing drift, supported-set gate, prefill sampling suites - EngineV2ResliceTests: pure resliceGrants policy — proportional shares (rate x min(context, 131072)), single-model full budget, equal-split degenerate, context cap, sum<=budget invariant, 1 GiB serviceability floor, load/unload round trip. - SlotSizingDriftTests: pins the cbv2-layer-kinds fp16 rate against the KVEstimation config.json parse for BOTH prod families (gpt-oss 24,576 B/tok; gemma-4 qat 20,480 B/tok with K-eq-V full layers), proves estimatedKVBytes mirrors AdmissionV2.estimatedBytes exactly (engine oracle, window plateaus included), and re-checks against the REAL checkpoint config.json when present in the HF cache. - EngineV2SupportedSetGateTests: init drops CBv2-adapterless families from the advertised set; stale-id loads map to 404; reslice-floor errors map to 503; coordinator load_model push for an unsupported id emits load_model_status: failed. - EngineV2PrefillSamplingTests: classifier bounds (1 ms floor, 20k ceiling, PR #454's fast-cold band accepted) and the submit->first- token EWMA population on success / non-population on cancel. * test(provider): live two-model co-residency suite (gpt-oss + gemma-qat, real weights) The v0.7.5 §1.1 acceptance test, gated on DARKBLOOM_LIVE_MLX_TESTS + DARKBLOOM_LIVE_MLX_GEMMA with skip-if-absent per checkpoint: 1. load gpt-oss -> lone engine holds the FULL fleet KV budget (exact UnifiedMemoryCap figure); 2. worst-case admission probe (2.5M max_tokens ~ 61 GiB KV) ADMITS pre-shrink, then is cancelled; 3. a real greedy generation streams on gpt-oss WHILE gemma-qat loads: the stream completes untouched across the shrink; both slots hold live v2 bridges; grants equal the pure resliceGrants targets and sum <= the recomputed fleet budget; 4. the SAME probe is now REFUSED (token_budget_exhausted) — the next admission respects the shrunk ceiling; 5. both models serve a real decode through the production path (runStartupSelfTestDecode); unloading gemma grows gpt-oss back to the exact full budget and it still serves. Adds two read-only seams (slot sizing + slot bridge) and a bridge active-request-ids seam for the probe cancel. * test(provider): fixture model types satisfy the v0.7.5 advertise gate; self-scaling live probe - ModelPrefetchCoordinatorTests + StartupPreloadTests fixtures declare a supported model_type (gpt_oss / gemma4): the machinery under test (prefetch verify, hard swap, slot caps, preload gate) is orthogonal to the supported-set gate, which now drops adapterless families from the advertised set at init/verify time. - Live co-residency probe sizes itself dynamically between the expected post-shrink share (+15%) and the current full grant (−15%), under a test-scoped memory_reserve_gb that pins the cap at 64 GiB on a 128 GiB box — keeps the worst-case probe ~20 GiB so it is robust under concurrent-suite memory contention. * docs(provider): update stale fallback wording to refusal semantics in factory/extraction headers * test(provider): live co-residency probe hits the engine admission ledger directly The bridge-path probe reserved its worst case in the shared GlobalKVCacheBudget too, making the pre-shrink admit dependent on free system RAM — flaky when another suite holds tens of GiB on this box (observed: load gate refused at 14.2 GB free under a 64 GiB test reserve). The probe now submits straight to the engine (CBv2Engine.submit -> AdmissionV2.canEverFit): a pure grant-ledger verdict, drift-test-pinned to the same estimatedBytes arithmetic, immune to memory contention. The test reserve drops to a modest 8 GiB so the model LOAD gate breathes; the streaming request still exercises the full bridge + shared-budget path. PASSED on the M4 Max 128 GB (26.97 s): grantA0 = 100 GiB (gpt-oss alone, full budget) -> load gemma-qat while gpt-oss streams -> stream completed uninterrupted; grants re-sliced to 47 GiB (gpt-oss) + 39 GiB (gemma) = the 86 GiB fleet budget exactly; the ~53 GiB worst-case probe (2,355,631 tokens) admitted pre-shrink and REFUSED post-shrink; both models served real decodes; unload gemma -> gpt-oss back to 100 GiB exactly. * fix(provider): serialize unload-side regrow against the load re-slice (reviewer finding) Independent review found the one hole in the re-slice invariants: loads are serialized by isLoadingAny, but the idle monitor's unloadModel -> resliceGrowSurvivors runs from its own task and could interleave at the load path's suspension points — including the gap AFTER the newcomer's grant is carved out but BEFORE its slot is installed, where a regrow recomputes over the survivors alone and re-inflates them past the fleet budget (not an OOM — the shared GlobalKVCacheBudget still gates real reservations — but it broke the claimed 'sum(grants) <= budget at all times' and 'restore EXACTLY' invariants until the next re-slice). Fix: a re-slice gate (same waiter idiom as loadGateWaiters) serializes every grant-mutating section. ensureModelLoaded holds it across the WHOLE shrink -> build -> guard -> install-slot stretch (released on each failure path; the post-bridge-guard failure regrows survivors via the new resliceGrowSurvivorsLocked while still holding it); resliceGrowSurvivors (idle unload) is the gated wrapper. Deadlock-free: neither gated section calls the other — eviction unloads inside ensureModelLoaded run before the gated stretch begins. Regression test (fails without the fix, verified: sum(grants) 58.7 GB vs 29.6 GB budget): hold the gate as an in-flight load would, park a regrow behind it, install the newcomer, release — the regrow must mutate nothing while parked and must recompute over BOTH slots after. Also fixes the reviewer's doc nits: stale makeBridgeIfSelected/ selection-era headers in EngineV2Bridge.swift and EngineV2Factory+Production.swift. * fix(provider): release the failed newcomer's weights BEFORE restoring survivor KV grants (Codex finding) Codex review of the v0.7.5 re-slice found the failure-unwind ordering inverted: on a failed load of model B, ensureModelLoaded had already released the pending-load reservation (B's weights resident, counted only by live MLX usage), and the unwind then restored/regrew survivor grants while B's container was STILL retained by the load scope until the outer catch ran. Window: sum(engine grants) > the true fleet budget while B's weights were resident -> heartbeat/admission could transiently over-advertise capacity the shared GlobalKVCacheBudget would then reject (the gray-box class; never an OOM - the shared gate still bounded real reservations). Fix - both failure paths now unwind in this order, with the re-slice gate held across the entire sequence: shrink -> build fails -> RELEASE newcomer weights (EngineV2NewcomerBox) -> MLX clearCache -> restore/regrow survivor grants -> gate release - EngineV2NewcomerBox: ownership box for the loading container; ensureModelLoaded routes every access through it (borrow() is evaluated inline, never bound to a long-lived local) so release() provably drops the LAST strong reference to the weights. - resliceAndBuildEngineV2Slot takes the box; its catch releases + clears the cache BEFORE growing shrunk engines back to their exact previous grants. The pre-shrink floor refusal also releases promptly. - unwindBuiltSlotAndRegrow: the post-bridge-headroom failure path (unregister -> shutdown -> release weights -> clearCache -> regrow), shared by ensureModelLoaded and the test seam. - All existing cleanup semantics preserved: recordModelLoadError, loading-waiter wakeups, 404/503 mapping, load-gate release ordering, and the reslice-gate span through slot install (with a defensive gate release if the install-time container read could ever fail). Regression tests (EngineV2ResliceUnwindTests, verified FAILING on the old ordering - newcomerAlive was true at restore/regrow time - and passing on the new): a weak reference to B's container is checked at the exact instant each survivor-grant update lands on the engine; both the build-failure restore and the post-bridge-guard regrow must observe the newcomer's weights already dead, so the restored grants are <= the true fleet budget at every observable point of the unwind. Full suite: 1,386 tests / 127 suites green. * refactor(provider): extract shared v2 slot-factory + VLM-aware container loading Pulls the production bridge assembly (container EOS snapshot -> ModelEOSPolicy -> VLM text extraction -> makeProductionEngine -> fail-loud makeBridge + the kv_quant WARN) out of ProviderLoop's makeEngineV2BridgeForSlot into EngineV2SlotFactory.makeProductionBridge, and the VLM-aware checkpoint->container factory pick into ModelContainerLoading. Behavior-preserving: the ProviderLoop production branch now delegates to the factory (test-hooks branch unchanged), and the loop keeps registration + logging at its call site. Prepares the standalone server rewire (both slot owners construct through ONE path so assembly can never drift). * feat(provider)!: standalone server serves through engine v2 + 32 MiB local chat body ceiling (v0.7.5 §1.9) The last legacy BatchScheduler construction site outside tests is gone: darkbloom start --local now builds the SAME v2 slots the ProviderLoop does — sizing snapshot -> KV re-slice over the shared pure policy (EngineV2KVSizing.resliceGrants: single slot = full budget, >=2 share by rate x capped context, shrink-first / restore-on-throw / grow-after, serviceability-floor refusal) -> EngineV2SlotFactory.makeProductionBridge against the server's own GlobalKVCacheBudget. Grant mutations are serialized by the existing isLoadingAny load gate (standalone evictions only run from the load path, so no separate re-slice gate is needed). LRU eviction drains the bridge and regrows survivors; VLM checkpoints now load via the VLM factory so media requests work locally too. Fail loud: models without a CBv2 adapter are dropped from the catalog at construction (WARN) and the CLI prints a per-model error + exits non-zero when nothing serveable remains; engine construction failure surfaces as 503 (tokenBudgetExhausted shape) on the local endpoint; requests for dropped ids 404. engine_v2_max_concurrent (+ per-model map) now reaches standalone engines. The AcquiredModel/RegistryEntry scheduler leg is documented DEAD (removal belongs to the deletion pass). Also fixes the known 413 backlog item: the upstream router's BasicRequestContext pins Hummingbird's 2 MiB decode default with no config knob (protocol-witness default, not overridable retroactively), so the chat-completions POSTs are now served by LocalChatUploadResponder — collects the body under a 32 MiB ceiling (matches the coordinator WS path), decodes with the identical JSON configuration, and calls the same public MLXOpenAIService entry points with byte-identical response framing. Both --local and --local-endpoint get the fix; other routes keep the upstream decode path. Tests: v2-entry acquire (bridge populated, NO scheduler), catalog gate (construction + setModels + request-time 404), re-slice across loads + eviction regrow + restore-on-throw pinned against the pure policy, 3 MiB body clears the ceiling (404 unknown-model proves it reached the engine, streaming + buffered), >32 MiB -> 413 envelope, non-chat routes unchanged. * feat(provider): wedge self-recovery for v2 slots — drain, rebuild over the retained container, swap (v0.7.5 §1.10) Ports the legacy BatchScheduler+Liveness selfRestartForRecovery to the one-engine slot shape. The v2 engine detected wedges (WedgeMonitor + stepsExecuted flatline -> heartbeat 'crashed') but could not HEAL; the capacity-refresh tick now drives ProviderLoop+EngineV2Liveness: * CONFIRMED wedge (EngineV2Bridge+Liveness): >=1 hanging admit stalled >= 120s (the legacy BackendLivenessPolicy.defaultWedgeStallSeconds, one definition) AND the engine step counter frozen >= 120s — the flatline term keeps a starved-but-alive engine from triggering a rebuild (stricter than legacy .wedged; documented). * Recovery: legacy-shaped engine_health telemetry (engine_v2_self_restart ERROR / _complete INFO with duration_ms / _cooldown_unload / _failed, all allowlisted fields) -> old bridge reports 'reloading' (legacy isReloadingForRecovery precedence over 'crashed') -> drain (pump cancel + bounded engine drain) -> rebuild engine+bridge over the RETAINED container with the slot's CURRENT grant (NOT a re-slice — co-resident grants untouched, sum(grants) <= budget preserved) via the existing factory path (re-registers in EngineV2Runtime) -> atomic ModelSlot swap. * Serialization: the drain->rebuild->swap stretch holds the re-slice gate; a synthetic requestToModel pin keeps the idle monitor + every eviction filter off the recovering slot; explicit unloads win — every suspension point re-checks slot identity and aborts the swap. * 120s cooldown (legacy livenessRestartCooldown): a second confirmed wedge inside it UNLOADS the slot (fail loud — heartbeats drop it, coordinator routes around) instead of thrashing rebuilds; rebuild failure also unloads (refusal already fired). * Config/env parity: none to mirror — the legacy watchdog had no gate (always-on, 120s/120s); this port keeps that and adds no knobs. The legacy .pinned verdict is deliberately not ported (the collapsing-token-budget failure mode does not exist on re-sliced v2 byte grants). Tests (scripted engines, injectable clocks, no weights): verdict thresholds (stall + flatline both required; first token clears; moving steps never confirm), 'reloading' state precedence, full state machine (drain -> rebuild with the EXACT prior grant -> re-register -> swap -> serving again with a real streamed token), the two-model grant regression (recovering slot keeps ITS grant, co-resident engine sees zero capacity updates, sum <= budget), cooldown unload + re-wedge after cooldown recovers again, rebuild-failure unload, and shutdown/unloading skips. * test(provider): retarget standalone live tests to CBv2-supported checkpoints The standalone live tests served tiny Qwen models, which have no CBv2 adapter — under one-engine v0.7.5 the standalone server (correctly) refuses them, so the tests are re-pointed at the production pair: * two-models-through-one-process now serves gpt-oss + gemma-qat (the EngineV2CoResidencyLiveTests fixtures; additionally gated on DARKBLOOM_LIVE_MLX_GEMMA) and doubles as the standalone co-residency check (both slots hold live engine KV grants); * socket-disconnect cleanup runs on gpt-oss with the bridge-level debug surface (debugActiveRequestCount / debugSlotReservationCount replacing the legacy SchedulerCapacity shape) and gpt-oss-sized timeouts. liveModelInfo gains modelType/estimatedMemoryGb parameters (defaults preserve the remaining legacy call sites, which the deletion pass owns — the tiny-qwen ProviderLoop live tests have been unservable since the v2-only slot lifecycle landed and are on the §1.11 prune list). * feat(engine-v2): prefix cache ships DORMANT — opt-in via DARKBLOOM_PREFIX_CACHE=1; resident RAM stays with live serving v0.7.5 ship decision: no resident RAM prefix cache by default — every byte a resident cache retains is KV concurrency the box cannot serve. The successor design (encrypted SSD offload: write-behind donation on completion, read-through adoption, HMAC-keyed prefix hashes) caches without occupying serving RAM and will be reviewed under T-041 before it ships. All gate/budget/funding-gate/carve/salt/usage machinery stays fully wired as that foundation and for explicitly opted-in experiment boxes. - PrefixCachePolicy.isEnabled flips to OPT-IN: only 1/true/yes/on enables; absent/0/false/off/no/garbage stays dormant (fail-safe direction is OFF — a typo can never opt a box into the SEC-035 channel). The shared gate governs the legacy engine too (its live suites already setenv =1), so v0.7.5 ships with no resident prefix cache anywhere by default. Header rationale updated; legacy call-site log lines updated (DORMANT default / explicit opt-in banner). - Tests: envGate rewritten for opt-in semantics; new default-dormant wiring test (env ABSENT => no carve, raw grant to the engine, zero bridge budget, claim == capacity, makePrefixCache nil); explicit-0 test kept; funded-path tests now model an opted-in box (carveEnv defaults DARKBLOOM_PREFIX_CACHE=1); live suites pin the dormant default verdict before running their scenarios as the documented opt-in (+ adoption-bound override for gemma) paths. - Results: full suite 1,392 green; gpt-oss live 14.0s (hit 768 exact, TTFT 2.43s->1.56s); gemma live 135.4s (hit 2,304 exact under the override, TTFT 35.2s->31.4s). * docs(threat-model): T-041 — v0.7.5 ships the v2 prefix cache DORMANT (opt-in); SSD offload successor reviewed under this finding Title and description note the dormant default: DARKBLOOM_PREFIX_CACHE reverts to opt-in (=1 enables; absent/anything else off, both engines via the shared PrefixCachePolicy gate), so the fleet baseline exposure of the cross-tenant channel is zero — it exists only on explicitly opted-in boxes, where the posture is unchanged (RAM-only on v2, salt-scoped, SEC-035 for the residual TTFT oracle, now scoped to opted-in deployments). The opt-out-switch mitigation becomes the opt-in-gate mitigation; detection_hint adds two tripwires: flipping the dormant default back to enabled-by-default needs a fresh SEC-035 sign-off, and the encrypted SSD offload tier (write-behind/read-through, HMAC-keyed hashes) must be reviewed under this finding before shipping (it reintroduces the at-rest artifact class). * fix(provider): review follow-ups — malformed-JSON 400 parity, batch-route ceiling, recovery-pin hardening Independent-review findings on the §1.9/§1.10 diff: * P2: a malformed chat body on the intercepted routes escaped as a body-less 500 — the stock Hummingbird decode converts DecodingError to a 400 INSIDE the router responder, which this interceptor sits outside of, so a thrown HTTPError is never rendered. Decode failures are now RENDERED in place (OpenAI-shaped 400 envelope with the same error classification); regression test pins type-mismatch and truncated-JSON bodies at 400. * /v1/chat/completions/batch now rides the same 32 MiB ceiling (it decodes the same media-capable payload type; mirror of the upstream batch handler) + test. * Recovery abort path unregisters from EngineV2Runtime BEFORE releasing the re-slice gate, so the id-keyed unregister can never strip a successor load's fresh registration. * cancelAllInflight preserves the wedge-recovery requestToModel pins (namespaced prefix) — a disconnect-driven mass cancel must not expose a mid-rebuild slot to eviction/idle-unload. * engine_v2_max_concurrent standalone plumbing now has a test (per-model override + box-wide value on the bridge capacity). * Stale comments fixed (registry engineV2Bridge doc, --local slot cache wording). * test(provider): pin the recovery-window request semantics (drained bridge → 429, never 500) Codex review flagged requests admitted between the recovery drain and the slot swap as potential 500 provider faults. Against the real engine contract they are not: EngineV2.submit rejects post-shutdown with the (needed:1, available:0) capacityExhausted sentinel, which the bridge maps to the canonical 'token_budget_exhausted: request queue full' message → .queueFull → 429 + Retry-After — retryable capacity that the coordinator's pre-content failover reroutes invisibly. The requests already in flight at drain are the wedged ones (zero content for >=120s); they get teardown terminals exactly as the legacy restart's abort gave them, with their consumers long since rerouted. Pins the full chain with a test (drained engine → bridge error event → fromSchedulerMessage → 429), teaches the scripted engine the real post-shutdown reject sentinel, and documents the window semantics on the recovery driver. * test(provider): recovery of a carved slot reproduces grant + carve (T-041 x liveness invariant) * refactor(benchmark): port ThroughputSweep + SchedulerPrefillBenchmark to the production CBv2 engine The perf-gate harness now constructs its engines through the PUBLIC EngineV2Factory.makeProductionEngine — the same one-engine entry point every serving slot uses — instead of the legacy v1 BatchedEngine/Scheduler (deleted with the legacy engine). Decode rows submit CBv2Requests (greedy, per-row rotated prompts, first-token clock start, exact token counts off .delta events); prefill TTFT is measured to the first engine event with maxTokens=1 on a fresh engine per iteration. The legacy fixed-chunk/adaptive prefill strategy machinery is gone (CBv2 chunks prefill engine-internally): --prefill-strategies is removed and the report's strategy label is always 'cbv2'. Smoke-verified on real gpt-oss-20b weights (sweep + prefill JSON reports). * refactor(provider)!: extract MediaIngest from VLMRequestInference; delete the legacy VLM wrapper stream MediaIngest (Sources/ProviderCore/Inference/MediaIngest.swift) now owns everything shared with the v2 media path: MediaError, hasMedia/hasVideo, validateMedia, buildUserInput, the decompression-bomb caps + env overrides, projectedDecodeBytes/projectedKVTokens, and the inline-media decoders (CIImage, AVFoundation temp files, data-URI parsing). Deleted with the legacy engine: VLMRequestInference.stream (the non-batched prepare→generate wrapper path), generateParameters, and openAIFinishReason. The bridge-less media leg in MultiModelBatchSchedulerEngine.streamChatCompletion is now the same fail-loud internal error as the text path's — every slot serves through a v2 bridge as of v0.7.5, so it is structurally unreachable insurance. Tests: VLMRequestInferenceTests renamed to MediaIngestTests (they were all ingest/caps/error-mapping tests); the two legacy generateParameters tests deleted; remaining references renamed. * test(provider): non-bridged media slot pins the fail-loud backstop (legacy wrapper gone) * refactor(provider): KVEstimation moves to its own file as the pre-load estimate namespace BatchScheduler+KVEstimation.swift becomes KVEstimation.swift: the pure config.json architecture parse + per-token KV arithmetic, now carrying resolvedKVBytesPerToken directly on the KVEstimation enum (previously a BatchScheduler static shim). SlotSizingSnapshot and the KV-quant gate runner call the new home; the trivial resolvedMaxTokens shim is inlined at its one call site. Header documents the v0.7.5 role: pre-load gate estimate only — post-load sizing reads engine truth (cbv2LayerKinds), with SlotSizingDriftTests pinning the two. * refactor(provider)!: delete the legacy engine — BatchScheduler, checkpoint/disk KV tier, adaptive prefill, KV-quant, legacy compiled decode (v0.7.5 §1.11) One logical unit: everything that served inference outside ContinuousBatchingV2 is gone (~9.5k lines of provider source + the legacy test surface), and the mlx-swift-lm pin moves to cbv2/v075-engine @ 5c22907 (v1 engine deleted there; CBv2QuantizedSequenceKV + shared quant kernels guarded). Deleted (provider sources): - BatchScheduler.swift + 15 extensions + BatchSchedulerTypes (~5.5k lines), BatchQueuePlanner, CheckpointCapturePipeline, LegacyCompiledDecodeGate (+ its ProviderLoop+Serve foreground call), AdaptivePrefill/ (5 files), KVQuant/ (2 files), the dead entry.scheduler leg + scheduler fields in MultiModelBatchSchedulerEngine(+Registry) — a request on a bridge-less entry is now the same fail-loud 500 as the text path's backstop. - Legacy KVCache/ persistence: PrefixCacheManager, EncryptedKVStore, EncryptedPrefixCachePersistence, KVCacheSerializer, PrefixCacheIndex/RAM/ Strategy/PastWindow, PrefixDigest, GlobalDiskAccountant. - Executables: ProviderBenchmarkKVQuant, kv-quant-gate, kv-attn-selftest, kv-se-harness (Package.swift targets + sources). PRESERVED (and where): - KVCacheKEK + KeyWrappingService + SecureEnclaveKeyWrappingService + WrappedKEKStorage stay as the standalone KEK cluster in Sources/ProviderCore/KVCache/ — the Secure-Enclave KEK derivation (ECIES against the persistent SE identity + Keychain-wrapped storage) is the foundation the encrypted SSD-offload successor design builds on. - KVEstimation (own file; quantScheme stripped — fp16-only), and the shared value types GenerationEvent / ModelArchitecture / TokenizerHandle re-homed into Inference/InferenceTypes.swift. - WedgeMonitor, KVPoolReclaimer, MLXMemoryGuard, ModelEOSPolicy, KVHeadroomProbe, VisionMemoryGate: kept (v2 consumers). - LegacyKVCacheSweeper (new): one-shot startup sweep of the retired ~/Library/Caches/darkbloom/kv tier, replacing GlobalDiskAccountant's crash-hygiene sweep and shedding the old ciphertext on ≤0.7.4 upgrades. Tests: ~45 legacy-only suites deleted (Batching*, B1GreedyFastPath, HybridCheckpoint*Live, KVQuant*, CheckpointCapture*, AdaptivePrefill*, PerformanceLive, RowSamplers, BackendLivenessSelfRestartHeartbeat, KVCache legacy suites); shared suites pruned to v2-only semantics; live fixtures re-homed onto EngineV2SlotFactory.makeProductionBridge (LiveInferenceFixtures.loadBridge) with caller-side chat templating, mirroring the production request path. Kept: GlobalKVCacheBudget*, UnifiedMemoryCap*, KVPoolReclaimer*, KVCacheKEK/KeyWrapping tests. Full provider suite: 990 swift-testing tests / 108 suites (+XCTest) green. Submodule suite: 383 tests / 55 suites green. * chore(provider)!: retire the legacy engine's env vars and config keys (v0.7.5 §1.12) Env: EngineV2Config.retiredEnvironmentKeys now covers every knob the one-engine release retired — DARKBLOOM_ENGINE_V2(+_MODELS) (kept as the startup deprecation WARN for one release), DARKBLOOM_COMPILED_DECODE, DARKBLOOM_GEMMA_B1_FAST_PATH, DARKBLOOM_B1_GREEDY_FAST_PATH, DARKBLOOM_KV_GPTOSS_KERNEL, DARKBLOOM_ADAPTIVE_PREFILL_ALLOW_8192, DARKBLOOM_KV_CAPTURE_MAX_INFLIGHT, and the legacy SSD prefix-tier sizing envs (_DISK_GB, _MIN_PERSIST_TOKENS, _ALLOW_EPHEMERAL). One WARN per set key at startup. KEPT live: DARKBLOOM_PREFIX_CACHE* RAM-tier envs (dormant default), DARKBLOOM_MEM_CAP_FRACTION, DARKBLOOM_ACTIVATION_RESERVE_GB, DARKBLOOM_ENGINE_V2_VLM_PARITY_CHECK. Config ([backend]): engine_v2, continuous_batching, adaptive_prefill, legacy_compiled_decode are REMOVED from BackendSettings — old provider.toml files still parse cleanly (presence-only scan) and each found key gets a parsed-and-WARNed-as-retired startup line via the new retiredKeysPresent surface. kv_quant stays a field but is REJECTED-with-WARN (startup WARN + the existing per-load telemetry WARN) — never silently ignored, because a CBv2-native KV-quant fast-follow is planned; the beta-feature entry's copy now says exactly that. The adaptive-prefill beta feature is deregistered; StatusCommand drops the continuous-batching line; StandaloneServerConfig drops adaptivePrefill. Tests: retired-key surfacing + round-trip shedding pinned in ConfigTests; BetaFeatures registry expectations updated. 160 tests / 24 suites green on the affected filters. * docs(provider): v0.7.5 one-engine release notes; renumber vision vintage comments; overflow-safe runtime claim math - ProviderCore.swift release-notes block now carries the full one-engine summary (deletion inventory, replacements, retired knobs, rollback posture, wire-compat note). - The ~16 vision doc comments claiming a v0.7.4 ship vintage renumber to v0.7.5 (the vision branch was renumbered before shipping; prod 0.7.4 was the fused-MoE release). - EngineV2Runtime.capacitySummary adds claims overflow-safely (saturate, like slotKVBytesClaim). - EngineV2KVSizing.engineKVBytesCapacity documented as retained solely for the heartbeat live-budget clamp (slot-lifecycle deviation #5). * revert(provider): preserve EncryptedKVStore for the v0.7.5 encrypted SSD KV-offload tier Scope addition to the legacy deletion (Gaj decision): the encrypted SSD KV-offload tier ships IN v0.7.5 (feat/v075-ssd, merging after this integration) and reuses the chunked AES-GCM store verbatim. Restore Sources/ProviderCore/KVCache/EncryptedKVStore.swift (+ its 20-test suite) — it is self-contained (atomic tmp+rename writes, HKDF/nonce derivation, header parsing, JSON canonicalization all inline; only CryptoKit/Foundation/os imports), so nothing else comes back with it. The KEK cluster (KVCacheKEK, KeyWrappingService, SecureEnclaveKeyWrappingService, WrappedKEKStorage) was already preserved. The checkpoint-shaped consumers (PrefixCacheManager, EncryptedPrefixCachePersistence, CheckpointCapturePipeline) stay deleted as planned. * feat(kv-ssd): encrypted SSD KV-offload prefix cache — write-behind donation, read-through staging, HMAC-keyed names The v0.7.5 tier that replaces resident-RAM prefix caching: donated KV is extracted to host buffers on the engine's donation queue, deduped by HMAC lookup tag, encrypted (DBK2: per-file DEK wrapped by the SE-rooted KEK, AES-256-GCM chunks with metadata-as-AAD, HKDF nonces dbkv-chunk-v2), and written per-block content-addressed under kv/<modelKey>/cbv2 by a bounded serial pipeline — RAM stays entirely with live serving (zero resident block bytes at steady state). Adoption is read-through: a pre-submit hook in EngineV2Bridge probes the RAM index, applies the benefit gate (min-effective 1024, stage-bytes/time caps), reserves staged bytes in GlobalKVCacheBudget (refuse => silent recompute), reads+decrypts off the engine threads, and parks the rebuilt arrays in a staging map so the engine's synchronous lookup() hits; endAdoption releases (bridge backstops every terminal path incl. cancel/submit-failure). - New module Sources/ProviderCore/KVCacheSSD/: SSDPrefixCache (CBv2PrefixCache conformer), SSDBlockStore (DBK2 codec), SSDLookupKeys (K_lookup = HKDF(KEK, dbkv2-lookup-v1); tags fold the length-prefixed cacheSalt — raw chain hashes never on disk, closes T-041 leak #2), SSDBlockIndex + box-wide SSDDiskBudget, SSDWriteBehind (150 GB/day token bucket, low-disk guard, ENOSPC cooldown), SSDPrefixCachePolicy (knobs), SSDPrefixCacheFactory. - Tier selection (PrefixCachePolicy.mode): SSD DEFAULT-ON for funded models (gpt-oss funded, gemma-4 unfunded => writes nothing); DARKBLOOM_PREFIX_CACHE=0 kills everything, _SSD=0 kills the SSD tier; RAM tier stays opt-in; both active => SSD wins with WARN. - TTL 15 minutes MAX, sliding on hit (file-mtime backed so recency survives restart); disk budget 20 GiB box-wide default (DARKBLOOM_PREFIX_CACHE_DISK_GB, min free/2), LRU unlink eviction. - NO memory carve in SSD mode: the engine keeps its full slot grant (requestedBudgetBytes = 0); makeProductionEngine prefixCache param widens to (any CBv2PrefixCache)? — zero mlx-swift-lm changes. - Invalidation: weightHash + layoutEpoch bindings fail closed (delete-on-sight); GCM auth failure => delete + recompute; startup scan is the recovery protocol (no index sidecar); accountant init sweep now PRESERVES cbv2 subtrees (durable restart warmth). - Stats: tier=ssd engine=v2 log line (writes, bytes, hits, staged bytes, evictions, TTL sweeps). * test(kv-ssd): unit + live suites for the SSD offload tier - SSDPrefixCacheTests (24 tests, live-isolated: real files, real MLX arrays, real crypto, throwaway temp dirs): keyed+salt-scoped HMAC name derivation, DBK2 round-trip + AAD tamper fail-closed, layout epoch binding, tier mode-selection matrix (SSD default / kill switches / RAM opt-in / both => SSD wins), NO-memory-carve invariant, 20 GiB-shape disk-budget resolver + 15-min TTL cap knobs, donation write+dedupe+RAM-freed, restart-warmth scan+stage+byte-exact adopt, salt isolation on disk, corrupt-block delete+recompute fallback, TTL sweep + sliding-on-hit, box-wide LRU eviction, endurance write-cap drop, and staging reservation hygiene on success / backstop / cancel / pressure-refusal / close paths. - EngineV2SSDPrefixCacheLiveTests (gpt-oss-20b, weight-gated): 3.5k-tok turn-1 donates 13 encrypted blocks (163 MB) with ZERO resident bytes; turn-2 adopts FROM DISK (hit >= 1792 tok) byte-identical to cache-off; cross-engine-restart warmth (teardown closes the cache, fresh instance re-scans the dir and adopts byte-identical — no wipe); TTL expiry drops entries at scan and never adopts. Measured TTFT: warm 1.68s / restart-warm 1.86s vs cache-off 3.79s. - EngineV2PrefixCacheWiringTests: carve tests pin the RAM tier explicitly now that the SSD tier is default-on (SSD kill switch in the hook env). * docs(threat-model): T-041 — the encrypted SSD offload tier ships in v0.7.5, leak #2 HMAC mitigation implemented At-rest artifacts return with the SSD tier, reviewed under this finding: (a) names/index/metadata carry only HMAC-SHA256 tags under the SE-rooted per-install K_lookup — the long-open leak #2 mitigation flips to IMPLEMENTED with the tier that re-opened it; (b) the 15-minute sliding TTL + 20 GiB box-wide LRU budget bound the at-rest window; (c) file crypto is the reviewed legacy AES-GCM DEK/KEK scheme unchanged (DBK2, dbkv-chunk-v2 nonces); (d) salt scoping is preserved on disk (folded into chain hash AND tag input). Residual metadata (sizes, count, timestamps, model identity) documented as accepted. SEC-035 TTFT-oracle stays the accepted risk, extended across restarts within the TTL window. affected_files refreshed (KVCacheSSD/*, bridge, slot wiring); detection_hint rewritten — a persistence tier now exists, so TTL/budget/name-derivation/metadata/purge/reservation-release changes all trigger review. * fix(benchmark): sweep + prefill harness serve VLM checkpoints through the production text extraction The perf-gate run showed gemma-4 (a VLM checkpoint) measuring 0 tok/s on BOTH trees: the harness loaded it via LLMModelFactory and handed the raw wrapper to makeProductionEngine, which refused (unsupportedModel — no CBv2 adapter). Now: config.json vision_config detection → VLMModelFactory load → EngineV2Factory.benchmarkServingModel (new public seam over the weight-sharing EngineV2VLMTextExtraction, the exact slot-build path) → engine construction. gpt-oss (non-VLM) path unchanged. * fix(kv-ssd): review follow-ups — durable-subtree guard on unowned eviction, donate-side mtime recency, values shape guard, deterministic LRU test - GlobalDiskAccountant.evictUnownedEntries no longer rmdirs a model dir that still holds the durable cbv2/ subtree (the init-sweep invariant now holds on the ceiling-eviction path too). - donate() bumps file mtimes for REUSED blocks (best-effort), so donation-only warmth survives a restart — the startup scan seeds lastAccess from mtime and would otherwise TTL-drop actively re-donated blocks. - donate() validates the values tensor shape symmetrically with keys (defensive against a future backend whose snapshots are asymmetric — skip, never trap). - LRU eviction test: evict the ENTIRE older prefix (its blocks share one lastAccess; partial eviction left an arbitrary — sometimes prefix-contiguous, stageable — survivor set, flaking ~25%). * docs(provider): review advisories — T-041 post-deletion accuracy, policy comment staleness, standalone unwind divergence documented Independent-review advisories: T-041's affected_files no longer lists the deleted legacy tier files (EncryptedKVStore noted as preserved for the SSD successor) and its on-disk description is marked historical (the legacy deletion shipped in this release); PrefixCachePolicy drops the 'until the legacy deletion pass' clauses; StandaloneServer's re-slice doc now states the deliberate unwind-ordering divergence from ProviderLoop (caller-frame release, local-only exposure) instead of claiming identical sequencing. * fix(provider): capacity monitor SIGABRT under -O — non-generic Task.sleep + single-hop tick; retarget E2E testbed to CBv2 checkpoints Release-blocker found by the E2E gate: the serve-path capacity monitor aborted ~2 s after startup ('freed pointer was not the last allocation', swift_task_dealloc LIFO violation inside the inlined generic Task.sleep(for:tolerance:clock:)) on RELEASE builds only (Swift 6.3, macOS 26). Bisect: clean at dc03a0ce, crashes from a0067897 (standalone commit — a code-layout perturbation, not a logical cause; debug builds never crash). Fix: the monitor sleeps via the non-generic Task.sleep(nanoseconds:) overload (different codegen path, empirically stable across 3 E2E runs) and the tick body is hoisted into one actor method (capacityRefreshTick — capacity snapshot, wedge self-recovery, daemon state). Revisit on a toolchain bump; the comment documents it. E2E testbed retarget (one-engine collateral): the harness served tiny-Qwen checkpoints, which v0.7.5 correctly refuses to advertise (no CBv2 adapter) — every inference test failed. The default fixture is now gpt-oss-20b (DefaultTestModelID, env-overridable via DARKBLOOM_TESTBED_MODEL; runner needs it in the HF cache), the full-network smoke defaults to the production pair, and KnownModelSizes carries the CBv2 checkpoints. Suite startup already tolerates the 12 GB load (3-minute registration wait). * fix(provider): route every sleep through taskSleep(nanoseconds:) — Swift 6.3 -O task-allocator aborts at multiple sites The capacity-monitor fix was not enough: the identical 'freed pointer was not the last allocation' swift_task_dealloc abort (inlined generic Task.sleep(for:tolerance:clock:), release builds only) reproduced next inside CoordinatorClient.sessionLoop closure #4 during the first real E2E inference. The bug is systemic to the toolchain (Swift 6.3 / macOS 26), so ProviderCore now has ONE shim — taskSleep(_ duration:) over the non-generic Task.sleep(nanoseconds:) — and all 21 Task.sleep(for:) call sites route through it (same CancellationError semantics). E2E NonStreamingInference passes twice against the release binary with real gpt-oss inference. Revisit on a toolchain bump; TaskSleep.swift documents the trigger. * test(e2e): encryption-correctness budget fits the reasoning fixture gpt-oss-20b (the CBv2 default fixture) spends a 20-token cap entirely in the Harmony analysis channel, leaving message.content empty before the final channel starts — and this is the one test asserting on decrypted CONTENT. 256 tokens lets it reason and answer. Full E2E: 13/13 green (1 env-gated full-network SKIP by design). * feat(kv-ssd): per-donation gating replaces the SSD tier's per-model funding rule — gemma long-context tail now cached SSDPrefixCache.donate persists only when the donated whole-block prefix exceeds the model's adoption bound + the 1,024-token benefit floor: - gpt-oss (bound 1,536): sub-2,560-token donations — which adoption could never clear — are skipped before any extraction (pure disk-wear win; adoptable traffic unchanged). - gemma-4 (bound 25,600): the >26,624-token long-context tail persists and adopts (the old per-model rule excluded gemma entirely). The adoption/staging side needed no change: the benefit gate passes (effective = matched − 25,600 >= 1,024) and a ~27k-token run stages ~560 MB, under the 1 GiB byte cap and the 1 s time estimate. - Unknown/saturated bound: the gate can never pass — the only 'never cached' case left. The per-model funding gate (shouldFund / DARKBLOOM_PREFIX_CACHE_MAX_ADOPTION_BOUND_TOKENS) retires from SSD gating and now governs ONLY the opt-in RAM tier's carve (documented on shouldFund; cleaner than overloading the env var as a donation-gate ceiling). VLM-slot skip lifted: SSD construction for VLM slots derives layer kinds from config.json's text_config alone (new EngineV2VLMTextExtraction.cbv2LayerKinds, shared with the existing config-only adoptionBoundTokens; the live test pins config-derived kinds == extracted-model truth). Economics guards for the bigger donations: - Persisted-run byte cap: blocks whose cumulative plaintext exceeds maxStageBytes are never written (the stage trim loop could never use them) — leading blocks only, so the run stays prefix-contiguous. - Write-behind queue byte cap raised to max(512 MiB, maxStageBytes + 256 MiB) so ONE full max-size donation (the ~592 MB gemma tail measured live) is always admitted; a second concurrent large donation drops with a counter — never a stall (oversize jobs reject deterministically). Tests: donation-gate matrix on both models' real constants + saturated bound + byte-cap trim + 600 MB admission (unit); live gemma-qat DEFAULT config — typical prompt writes NOTHING and serves normally; >29k-token long context donates 113 blocks (592.6 MB), turn-2 adopts 3,328 tokens FROM DISK byte-identical to cache-off, TTFT 34.34s warm vs 37.27s off (Δ 2.93s — the win is bounded by gemma's 25.6k recompute span, as designed); gpt-oss suite stays green (warm 1.65s vs 3.52s off). Threat model T-041: per-donation wording — at-rest exposure unchanged in kind (HMAC names, 15-min TTL, same crypto), extended to gemma's long-context traffic; loosening the gate triggers review. * fix(kv-ssd): own on-disk root darkbloom/kv2 — immune to the legacy upgrade sweeper; policy header states the SSD tier ships in v0.7.5 Integration advisory (release/v075): the integration pass deleted GlobalDiskAccountant and replaced the startup wipe with a LegacyKVCacheSweeper that sheds retired-tier ciphertext under ~/Library/Caches/darkbloom/kv on upgrade — which would have wiped the SSD tier's kv/<modelKey>/cbv2 subtree every boot. Resolution (option a, fully self-contained, zero merge coupling): - SSDPrefixCacheFactory.cacheDirectory moves to its OWN root: ~/Library/Caches/darkbloom/kv2/<modelKey> — a SIBLING of the legacy kv/ root, never inside it. No exclusion contract with any sweeper is needed and none can regress this tier's durable restart warmth. - The GlobalDiskAccountant modifications (init-sweep cbv2 preservation, unowned-eviction durable-subtree guard) are REVERTED to the base — they are unnecessary with a separate root and the file is deleted on the integrated head (avoids a modify/delete merge conflict). - Tests: cacheDirectory pinned under darkbloom/kv2 and NEVER under darkbloom/kv; a simulated legacy sweep (rm -rf of the entire kv/ root) leaves SSD entries intact, re-scannable, and adoptable. - PrefixCachePolicy header + gate docstrings rewritten: the SSD tier SHIPS in v0.7.5 default-on with the per-donation gate (no longer 'successor/forthcoming'); the RAM tier is the opt-in experimental tier; threat-model detection hint names the kv2 root as review- triggering. gpt-oss live suite re-run green after the move. * fix(kv-ssd): post-merge review fixes — Codex SSD round - threat-model T-041: rescope the SEC-035 accepted-risk bullet to the v0.7.5 default-on SSD posture (the acceptance covers the fleet baseline again, with the strictly narrower channel enumerated); completes the Codex Medium (the two mitigation bullets were already rescoped in the merge commit). - SSDPrefixCache.stage: when a corrupt block SHORTENS the staged run, the shared-KV reservation and the staging accounting (StagedEntry.deviceBytes, stagedBytesInUse) now shrink to the bytes actually staged — release + re-reserve; a raced refusal degrades to silent recompute …
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.
8 of 9 tasks
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>
12 of 21 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Bumps the npm_and_yarn group with 1 update in the /settlement directory: picomatch.
Bumps the npm_and_yarn group with 1 update in the /web directory: next.
Updates
picomatchfrom 4.0.3 to 4.0.4Release notes
Sourced from picomatch's releases.
Commits
e5474fcPublish 4.0.44516eb5Merge commit from fork5eceecdMerge commit from fork0db7dd7Run benchmark again against latest minimatch version (#161)9500377docs: clarify what brace expansion syntax is and isn't supported (#134)2661f23fix typo in globstars.js test name (#138)1798b07docs: fixmakeReexample (#143)9d76bc5chore: undocument removed options (#146)e4d718bRemove unused time-require (#160)38dffebchore(deps): pin dependencies (#158)Updates
picomatchfrom 4.0.3 to 4.0.4Release notes
Sourced from picomatch's releases.
Commits
e5474fcPublish 4.0.44516eb5Merge commit from fork5eceecdMerge commit from fork0db7dd7Run benchmark again against latest minimatch version (#161)9500377docs: clarify what brace expansion syntax is and isn't supported (#134)2661f23fix typo in globstars.js test name (#138)1798b07docs: fixmakeReexample (#143)9d76bc5chore: undocument removed options (#146)e4d718bRemove unused time-require (#160)38dffebchore(deps): pin dependencies (#158)Updates
nextfrom 15.3.9 to 15.5.14Release notes
Sourced from next's releases.
Commits
d7b012dv15.5.142b05251[backport] feat(next/image): add lru disk cache and `images.maximumDiskCacheS...f88cee9Backport: Fix(pages-router): restore Content-Length and ETag for /_next/data/...cfd5f53v15.5.1315f2891[backport]: fix: patch http-proxy to prevent request smuggling in rewrites (#...d23f41cv15.5.128e75765fix unlock in publish-native6cef992[backport] normalize CRLF line endings in jscodeshift tests on Windows (#8800...7a94645Apply needs for publishReleasebbfd4e3v15.5.11