Skip to content

Add speech-to-text support with continuous batching - #5

Merged
Gajesh2007 merged 4 commits into
masterfrom
worktree-stt-integration
Mar 28, 2026
Merged

Gajesh2007 merged 4 commits into
masterfrom
worktree-stt-integration

Conversation

@Gajesh2007

Copy link
Copy Markdown
Member

Summary

  • Adds full STT pipeline: coordinator API endpoint, provider proxy, continuous-batching Python server, and frontend UI
  • Integrates Cohere Transcribe 2B model via mlx-audio on Apple Silicon
  • Same architecture as vllm-mlx: Python subprocess handles GPU batching, Rust provider proxies concurrent requests
  • Frontend gets mic recording, audio file upload, and inline audio player in chat

Architecture

Browser (record/upload audio)
  → Next.js /api/transcribe (proxy)
    → Coordinator POST /v1/audio/transcriptions (routes to provider)
      → Provider (Rust, WebSocket) → proxy to local STT server
        → stt_server.py (continuous batching on GPU)
          → Cohere Transcribe model via mlx-audio

Performance

Scenario Result
Single 30s clip 0.35s
Batch of 4 0.88s (4.5 req/s)
Batch of 8 1.64s (4.9 req/s)
Full 22min file 10.4s at 409 TPS
10 concurrent vs sequential 1.82x speedup

Changes

Protocol (Rust + Go, kept in sync): TranscriptionRequest, TranscriptionComplete, segments, usage types

Coordinator (Go): OpenAI-compatible POST /v1/audio/transcriptions multipart endpoint

Provider (Rust): handle_transcription_request(), STT server lifecycle, model advertisement

STT Server (Python): stt_server.py with BatchScheduler — collects concurrent requests within configurable window, batches on GPU

Frontend (Next.js): Mic recording (MediaRecorder API), file upload, audio player, /api/transcribe route, auto-detect STT models

How to use

# Provider
export DGINF_STT_MODEL="CohereLabs/cohere-transcribe-03-2026"
dginf-provider serve

# Consumer
curl -X POST https://inference-test.openinnovation.dev/v1/audio/transcriptions \
  -H "Authorization: Bearer $KEY" \
  -F "file=@recording.mp3" \
  -F "model=CohereLabs/cohere-transcribe-03-2026"

Test plan

  • Cohere model loads and transcribes via mlx-audio (30s clip + 22min file)
  • Continuous batching server handles concurrent requests (batch sizes up to 8)
  • Protocol JSON roundtrips between Rust and Go (unit tests)
  • All 108 Rust provider tests pass
  • All Go coordinator tests pass
  • Next.js frontend builds clean
  • Full end-to-end: browser → coordinator → provider → STT server
  • Browser audio recording via MediaRecorder
  • Deploy to production coordinator + provider

🤖 Generated with Claude Code

Gajesh2007 and others added 4 commits March 28, 2026 13:53
Integrate Cohere Transcribe model via mlx-audio for speech-to-text
inference through the decentralized network. Follows the same architecture
as vllm-mlx for LLM inference: a Python server subprocess handles
continuous batching on GPU while the Rust provider proxies requests.

Protocol (Rust + Go, kept in sync):
- TranscriptionRequest/TranscriptionComplete message types
- TranscriptionSegment, TranscriptionUsage structs
- Base64-encoded audio over WebSocket

Coordinator (Go):
- POST /v1/audio/transcriptions — OpenAI-compatible multipart endpoint
- Routes to STT-capable providers, returns text + segments
- TranscriptionCh on PendingRequest for async result delivery

Provider (Rust):
- handle_transcription_request() in proxy.rs — multipart POST to STT backend
- TranscriptionRequest event dispatch in coordinator.rs
- STT server lifecycle management (DGINF_STT_MODEL env var)
- Advertises STT models with model_type: "stt"

STT Server (Python):
- stt_server.py — FastAPI with BatchScheduler for continuous batching
- Collects concurrent requests, batches on GPU via model.transcribe()
- Batch of 8: 1.64s total (0.21s/req, 4.9 req/s)
- /health, /v1/models, /v1/audio/transcriptions, /v1/stats endpoints

Frontend (Next.js):
- Microphone recording via MediaRecorder API
- Audio file upload via file input
- Inline audio player in chat messages
- /api/transcribe proxy route
- Auto-detects STT models in model selector

Tested: Cohere Transcribe 2B on Apple Silicon — 22min audio in 10.4s
at 409 TPS. Concurrent batching verified with 10 simultaneous requests.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Audio data (someone's voice) is at least as sensitive as text prompts.
Apply the same NaCl Box encryption used for inference requests:
coordinator encrypts with provider's X25519 public key, only the
hardened provider process can decrypt with its private key.

- Coordinator: encrypt TranscriptionRequestBody when provider has public key
- Provider: decrypt encrypted_body in TranscriptionRequest same as inference
- Protocol: add encrypted_body field to TranscriptionRequest on both sides
- Tests: add encrypted transcription request deserialization test

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Providers without a public key are not eligible to receive transcription
requests. Audio data must always be encrypted — no plaintext fallback.
If encryption setup fails for any reason, the request is rejected with
a clear error rather than silently sending unencrypted audio.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Providers without a public key are not eligible to receive any consumer
data. Both chat completions and audio transcriptions now reject with
encryption_required if no encrypted provider is available. No plaintext
fallback — consumer prompts and audio must never travel unencrypted.

Updated tests to register providers with public keys.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@Gajesh2007
Gajesh2007 merged commit 31274ad into master Mar 28, 2026
@Gajesh2007
Gajesh2007 deleted the worktree-stt-integration branch March 28, 2026 21:39
Gajesh2007 added a commit that referenced this pull request Apr 21, 2026
SSRF (pentest #6): Server-side proxy routes no longer accept
x-coordinator-url from client requests. Coordinator URL is resolved
exclusively from NEXT_PUBLIC_COORDINATOR_URL env var. Removes the
attack vector where an attacker-controlled header redirected requests
(including API keys) to arbitrary URLs.

API key self-replication (pentest #5): Key creation (POST /v1/auth/keys)
and device approval (POST /v1/device/approve) now require Privy JWT
session auth via new requirePrivyAuth middleware — API keys are rejected.
A leaked key can no longer create derivative keys or self-approve device
links. Added DELETE /v1/auth/keys for key revocation.

Session poisoning (pentest #8): Logout now clears darkbloom_api_key and
darkbloom_coordinator_url from localStorage. Login resets coordinator URL
to prevent pre-auth poisoning.

CORS (pentest #17): Replaced wildcard Access-Control-Allow-Origin: *
with configurable origin via CORS_ORIGIN env var, defaulting to
https://console.darkbloom.dev.
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
…poch, late-SecurityInfo caching, MDM-config gate, 10m window, security docs

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

coordinator/: gofmt clean, go build ./... ok, go test ./... all pass (postgres
tests skipped w/o DATABASE_URL), -race clean on api + registry.
Gajesh2007 added a commit that referenced this pull request 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 …
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant