From d5251a4637efedaf8a66cd8ba3f0b6ca35b2a4ee Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Sat, 25 Jul 2026 11:47:24 -0700
Subject: [PATCH 01/23] chore(deps): bump mlx-swift-lm to query-block prefill
attention (#85)
abd1985 lands q=128 query sub-blocking in AttentionV1: prompt chunks
attend in blocks, slicing K/V to each block's own visible span. Sliding
executed/useful collapses from 1.499x to 1.062x at q=128, and the
composed-path score tensor becomes O(1) in chunk length (2.04 GB ->
0.51 GB at 124k context on a full-attention layer).
Blocked call sites are updateAndAttendRow and borrowAndAttendRow.
Decode, last-query prefill, and span-bearing vision chunks keep the
single-call path. DARKBLOOM_CBV2_ATTN_QUERY_BLOCK overrides the width;
0 restores the previous behavior.
Verified: provider swift build clean; coordinator go build/test clean.
provider swift test 1639 tests, 2 pre-existing SelfUpdaterTests
failures from a missing local mlx.metallib fixture (environmental,
unrelated to this bump).
---
libs/mlx-swift-lm | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index b177c35b72..abd1985637 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit b177c35b72976010d3e0b4d814a0854cbfd0c4fd
+Subproject commit abd1985637d68292f440122fbb390c583ce37a60
From 2b943b667e7a2ab973376345dab6a273401c9e7e Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Sat, 25 Jul 2026 11:47:32 -0700
Subject: [PATCH 02/23] docs(reports): paged-KV migration plan rev 2, verified
against abd1985
Rev 1 was written against submodule b177c35. Re-verified every claim
against e65b5bbc1 / abd1985 and corrected 26 items (log in section 22).
Four findings changed the plan's shape:
1. #85 already shipped Track A (query sub-blocking), so that track is
deleted -- and paged does NOT inherit the win. PagedLayerCache
.prefillAttend still issues one SDPA over the full [L, kL] rectangle
and adds a gathered K/V copy, so the migration now regresses prefill
activation memory unless new item 0.2p lands first.
2. B=8 is NOT reachable by provider config. The coordinator quality cap
(concurrency_cap.go:272-299) takes MIN(reported, ceil(1.2 * floor((
solo/15 - 1)/0.27))); gemma-4's 10-18 tok/s solo yields an effective
cap of 2 at both B=4 and B=8, pinned by concurrency_cap_test.go
:140-147. Gate G0 as written would have measured nothing. Split into
G0a/G0b, added section 8 (nine coordinator files, four of them
capacity-feedback loops that can eject a B=8 box), tripled Track E.
3. The wire cannot distinguish a paged provider from a contiguous one
-- BackendSlotCapacity has no backend discriminator, so a mixed
canary is unobservable. Added as Gate G5.
4. CI runs no paged correctness test; four suites are compiled and
discarded, and all three named silent-corruption classes have zero
fireable assertions. New sections 19 (test/CI) and 20 (benchmark).
Also corrected: WS-3.4's justification was false in the dangerous
direction (rectangular MTP verification is live in production, so the
first paged MTP slot is a process abort, not a fallback); the
activation-reserve mirror is servability.go:50, not scheduler.go:1301;
the DARKBLOOM_CBV2_PAGED_KV kill switch is unreachable under today's
default; Track T should extend CBv2KVSharingParityTests rather than
start over. Rev 1's 27,136 donation floor was right and the findings
doc's 26,624 was wrong.
Also commits the two companion reports the plan cites, so its
cross-references resolve in-tree.
---
...25-paged-attention-for-prefill-decision.md | 182 ++
.../2026-07-25-paged-kv-migration-plan.md | 1542 +++++++++++++++++
...-prefill-and-fleet-performance-findings.md | 461 +++++
3 files changed, 2185 insertions(+)
create mode 100644 docs/reports/2026-07-25-paged-attention-for-prefill-decision.md
create mode 100644 docs/reports/2026-07-25-paged-kv-migration-plan.md
create mode 100644 docs/reports/2026-07-25-prefill-and-fleet-performance-findings.md
diff --git a/docs/reports/2026-07-25-paged-attention-for-prefill-decision.md b/docs/reports/2026-07-25-paged-attention-for-prefill-decision.md
new file mode 100644
index 0000000000..183f72d293
--- /dev/null
+++ b/docs/reports/2026-07-25-paged-attention-for-prefill-decision.md
@@ -0,0 +1,182 @@
+# Should we move to Paged Attention instead of optimizing AttentionV1?
+
+**Decision: No — not for the prefill problem.** Paged attention is a
+decode-side KV-memory optimization. Its prefill path is the *same* composed
+fallback we already run, plus an extra materialized mask, and adopting it would
+disable two features we shipped in v0.7.15.
+
+Companion to `2026-07-25-prefill-and-fleet-performance-findings.md`, which has
+the full roofline and fleet analysis.
+
+---
+
+## The question
+
+We are planning ~60 lines of query sub-blocking in `AttentionV1.swift` (the
+contiguous backend's attention dispatch) to cut wasted sliding-window attention
+work and cap the score tensor. A paged backend already exists in the tree.
+Why not just switch to it instead of investing in "V1"?
+
+A naming clarification first: **`AttentionV1` is not a legacy version we are
+propping up.** It is the production attention dispatch for the contiguous KV
+backend. Paged is the experimental alternative (`AGENTS.md`: paged is explicit/
+experimental, `.auto` resolves to contiguous, VLM and kv-quant slots are vetoed
+from it). "V1" refers to the first *backend implementation*, not an old API.
+
+---
+
+## Evidence 1 — the paged Metal kernel is decode-only
+
+`Paged/pagedattention.metal:3`:
+
+```
+// CBv2 paged-attention decode kernels (ContinuousBatchingV2, WS-C).
+```
+
+It is a two-pass split-K **decode** kernel: pass A computes partials per
+(sequence, query-head), pass B merges them. It is built around one query per
+sequence, and it is genuinely good at that — KV bytes are read once per head
+group rather than once per query head.
+
+**There is no paged prefill kernel.**
+
+## Evidence 2 — paged prefill runs the identical composed fallback
+
+`Paged/PagedLayerCache.swift:341-343`:
+
+```swift
+return MLXFast.scaledDotProductAttention(
+ queries: queries, keys: k, values: v, scale: scale,
+ mask: .array(mask), sinks: sinks?.asType(queries.dtype))
+```
+
+That is the **same `MLXFast` entry point the contiguous path calls**. The
+composed fallback is selected by *head dimension*, not by cache backend
+(`libs/mlx/mlx/backend/metal/scaled_dot_product_attention.cpp:625-626`):
+
+```cpp
+sdpa_full_supported_head_dim = query_head_dim == value_head_dim &&
+ (query_head_dim == 64 || query_head_dim == 80 || query_head_dim == 128);
+```
+
+Gemma 4 uses head_dim **256** (sliding) and **512** (full). Neither backend can
+reach the fused kernel. Switching storage layout changes nothing about this.
+
+## Evidence 3 — paged prefill is strictly *worse* here
+
+`Paged/PagedLayerCache.swift:322-329` materializes an explicit `[qL, kL]`
+boolean mask on every prefill chunk:
+
+```swift
+let qpos = MLXArray(Int32(qStart) ..< Int32(end)).expandedDimensions(axis: 1)
+let kpos = MLXArray(Int32(kStart) ..< Int32(end)).expandedDimensions(axis: 0)
+var mask = kpos .<= qpos
+if case .slidingWindow(let window) = kind.attention {
+ mask = mask & (kpos .> (qpos - Int32(window)))
+}
+```
+
+The contiguous path uses the *symbolic* `.causal` mask mode wherever it can
+(`AttentionV1.maskMode`) and only materializes an array mask when the window
+actually binds. So paged adds a full-size tensor allocation the current path
+avoids — on top of the same score tensor.
+
+---
+
+## Paged solves a problem we do not have
+
+Paged attention's real value is KV memory management: pages instead of
+contiguous per-sequence buffers, eliminating fragmentation and enabling high
+concurrency.
+
+Our KV is small. At 124k context the **entire KV cache is 2.76 GB**, because:
+
+- `attention_k_eq_v` means the 5 full layers skip `v_proj` entirely,
+- those layers carry only 2 KV heads (`num_global_key_value_heads`), and
+- the 1024-token sliding window caps the other 25 layers at **0.21 GB total,
+ regardless of context length**.
+
+For comparison, the *transient attention score tensor* at that context is
+**2.04 GB at C=512** and would be 8.18 GB at C=2048. The thing that actually
+pressures memory is an activation, not the cache — and paged does not touch
+activations.
+
+---
+
+## What paged would cost us
+
+| Capability | Gate | Effect |
+|---|---|---|
+| Rectangular packed prefill | `LayerCacheBankV2.swift:121-123` — `supportsPackedPrefill` requires every cache to be `CBv2LayerCache` | **Disabled.** This is the feature we shipped and measured in v0.7.15. |
+| Vision / multimodal | `LayerCacheBankV2.swift:112-114` — `supportsMultimodalSpans` requires `CBv2SpanMaskBinding`; `PagedLayerCache` does **not** conform | **Cannot serve vision requests at all.** |
+| Prefix cache | paged slabs are recyclable, so `requiresMaterializedSnapshots` applies | Extra constraint on donation/adoption. |
+
+So the trade is: lose packed prefill and multimodal, gain nothing on the prefill
+path, and keep an attention kernel that only helps decode.
+
+---
+
+## Attention is not where prefill time goes anyway
+
+From the calibrated cost model (P=512):
+
+| Component | Share of prefill time |
+|---|---:|
+| MoE experts | 41.8% |
+| Attention projections | 21.5% |
+| Fixed per-request overhead | 14.3% |
+| Dense MLP | 10.4% |
+| Elementwise / gather | 6.1% |
+| **Attention matmuls** | **4.1%** |
+| Score-tensor traffic | 1.1% |
+
+Attention *matmuls* are 4.1% at P=512 and 9.9% at P=2048. Even a perfect
+attention kernel is a modest prefill win. The two big terms — MoE tile padding
+and the projections — are untouched by any attention work, paged or otherwise.
+
+Sub-blocking is worth doing not because attention dominates, but because it is
+cheap (~60 lines in the path we already run) and because it makes the score
+tensor **O(1) in chunk size**, which is the precondition for chunk growth
+(1.16x combined). See the findings doc, section 9.
+
+---
+
+## Where paged *would* earn its place
+
+This is not "paged is bad". It is well-built and its decode kernel is the right
+design. The case for adopting it would be:
+
+- **Much higher concurrency.** If we wanted `maxConcurrentRequests` well above
+ 4, contiguous per-sequence KV would fragment and strand memory. Paged fixes
+ exactly that.
+- **Very long contexts at scale**, where KV genuinely becomes the dominant
+ resident cost — not our situation while the sliding window holds 25/30 layers
+ flat.
+
+Today neither applies. Decode is **bandwidth-bound** at ~259 GB/s (47% of the
+546 GB/s pin rate), and the B=4 ceiling is 2.11x — set by 66% batch-invariant
+bytes and 91%-distinct expert draws, not by KV capacity or fragmentation. Adding
+concurrency would not convert into throughput, so the problem paged solves is
+not currently binding.
+
+**Revisit if:** we raise concurrency substantially, KV becomes the resident
+bottleneck, or someone writes a *paged prefill* kernel that is window-aware and
+avoids score materialization. The third would be a real advance — but that is
+flash attention with paged storage, which is a much larger project than
+sub-blocking and would still need head_dim 256/512 support that MLX lacks.
+
+---
+
+## Verdict
+
+| | Sub-blocking in AttentionV1 | Migrate to paged |
+|---|---|---|
+| Fixes wasted sliding-window FLOPs (1.499x -> 1.062x) | Yes | No |
+| Caps score tensor (2.04 GB -> 0.51 GB) | Yes | No |
+| Unlocks chunk growth (1.16x combined) | Yes | No |
+| Helps decode | No | Yes (but decode is bandwidth-bound) |
+| Keeps packed prefill | Yes | **No** |
+| Keeps vision support | Yes | **No** |
+| Effort | ~60 lines Swift + parity tests | backend migration |
+
+Proceed with sub-blocking. Keep paged as the experimental backend it is.
diff --git a/docs/reports/2026-07-25-paged-kv-migration-plan.md b/docs/reports/2026-07-25-paged-kv-migration-plan.md
new file mode 100644
index 0000000000..82bc7108a5
--- /dev/null
+++ b/docs/reports/2026-07-25-paged-kv-migration-plan.md
@@ -0,0 +1,1542 @@
+# Migration Plan: Contiguous → Paged KV, and B=4 → B=8
+
+Status: **proposed**, not started. Supersedes the "no" verdict in
+`2026-07-25-paged-attention-for-prefill-decision.md` (see §21 for what changed
+and which of that document's arguments were wrong).
+
+Companion to `2026-07-25-prefill-and-fleet-performance-findings.md`.
+
+Everything here is either measured, read out of the source, or derived from a
+model that is validated against a measurement. Derived numbers say so.
+
+**Revision 2 (2026-07-25).** Rev 1 was written against submodule `b177c35`;
+this revision is verified against **`abd1985`** (`Layr-Labs/mlx-swift-lm` #85)
+on superproject `e65b5bbc1`. Four findings changed the plan's shape:
+
+| # | Finding | Effect |
+|---|---|---|
+| 1 | **#85 already shipped query sub-blocking.** Track A / WS-0.2 is done. | Removes a track. Also makes paged **worse**: the win is contiguous-only (§7.2). |
+| 2 | **B=8 is NOT reachable by provider config.** The coordinator's quality cap clamps gemma-4 to **2** regardless of what the provider reports. | Rewrites §3, §5-G0 and Track E. Gate G0 as written would have measured nothing. |
+| 3 | **The wire cannot distinguish a paged provider from a contiguous one.** | Promotes WS-7 from "nice" to a hard rollout blocker (§18). |
+| 4 | **CI runs no paged correctness test.** Four suites are compiled and discarded. | New §19. An 11-track parallel migration with no numerical gate is not executable. |
+
+A full correction log against Rev 1 is in §22.
+
+---
+
+## 1. Why
+
+Two goals, in priority order:
+
+1. **Batching.** Decode is bandwidth-bound and MoE batches unusually well. B=4
+ → B=8 is a modelled **1.26x** aggregate decode throughput at p50 context
+ (**measured 1.30x**, §3.2), with per-request ITL at ~25 tok/s (floor is
+ `EIGENINFERENCE_MIN_DECODE_TPS=15`, `deploy/environments/prod.env:27`).
+2. **Removing a model-architecture bet.** Contiguous is competitive only
+ because 25 of gemma-4's 30 layers are sliding-window and therefore already
+ fixed-size rings. Add one large full-attention long-context model and the
+ fragmentation math flips. Paging buys out of that dependency.
+
+Paged is **not** faster today. It is 13% slower at B=1 on GPT-OSS
+(88.5 vs 101.8 tok/s, `libs/mlx-swift-lm/benchmarks/reports/*-paged-gate-2026-07-09.md`)
+and marginally *faster* at B=4 (38.5 vs 37.3 gpt-oss; 39.0 vs 38.0 gemma). The
+migration is a bet on B, on context length, and on the model set — not a
+performance win on the current operating point. Any justification that promises
+otherwise will be contradicted by the first benchmark after the flip.
+
+**New in Rev 2:** since #85, paged is also *behind* on prefill memory. Query
+sub-blocking bounds the score tensor to O(1) in chunk length on the contiguous
+path only; `PagedLayerCache.prefillAttend` still materialises the full
+`[L, kL]` rectangle **and** pays a gathered K/V copy contiguous does not
+(§7.2). That is a new, first-order cost of the migration.
+
+---
+
+## 2. Target state
+
+| Dimension | Today | Target | Measured by |
+|---|---|---|---|
+| Engine concurrency | B=4 | **B=8** | heartbeat `max_concurrency` |
+| **Coordinator-effective concurrency (gemma-4)** | **2** | **8** | `effectiveMaxConcurrencyForModelRateLocked` |
+| Aggregate decode throughput | 1.0x | **1.26x** modelled / **1.30x** measured | tok/s at fixed ITL floor |
+| Per-request ITL @ target B | 51 tok/s | **~25 tok/s** (measured 24.7) | `observed_decode_tps` |
+| KV per sequence @ ctx 5k | 348 MB | **312 MB (-10%)** | `bytesInUse / B` |
+| KV per sequence, distribution-weighted | 348 MB | **257 MB (-26%)** | `bytesInUse / B` |
+| gemma-4 prefix donation floor | 27,136 tok | **1,024 tok** | `SSDPrefixCache.config` |
+| gemma-4 donatable traffic | 2.3% | **~37%** | donation settle counters |
+| Per-slot KV-backend on the wire | **absent** | **present** | `BackendSlotCapacity` |
+| Paged correctness on CI | **none** | **gated** | CI job |
+| MTP | token-exact | **token-exact** (non-negotiable) | parity suite |
+| Vision, packed prefill | working | **working** | e2e |
+
+**Non-goals:** beating contiguous at B=1; preserving compiled decode (§14);
+B > 8 (§3).
+
+---
+
+## 3. Why B=8 and not higher
+
+8 is the sanctioned engine ceiling, encoded in three places:
+
+```swift
+// provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift:90-96
+/// Box-wide concurrent-request cap per v2 engine slot
+/// (`engine_v2_max_concurrent` under `[backend]`). Default 4 — the
+/// CBv2 product target. Clamped to [1, 8] at use: the engine's KV
+/// byte-ledger admission binds long before count does, and caps past 8
+/// recreate the batch-collapse regime the one-engine release exists to
+/// kill.
+```
+
+```swift
+// provider-swift/Sources/ProviderCore/ProviderLoop.swift:690-692
+internal static func clampEngineV2Concurrency(_ raw: UInt64) -> Int {
+ Int(min(max(raw, 1), 8))
+}
+```
+
+`CBv2SchedulerConfig.maxConcurrentRequests` defaults to 4
+(`CBv2Contracts.swift:594`), whose own doc reads "product target: 4, max 8" —
+B=8 is the top of the supported range, not an overrun.
+
+### 3.1 The batching model
+
+Decode bytes per step, gemma-4-26b-qat-4bit:
+
+```
+bytes(B, ctx) = invariant + experts(B) + B * kv(ctx)
+
+invariant = 1,608 MB (dense MLP 23.3% + attn weights 25.5% + LM head 17.0%)
+experts(B) = 100.25 MB * 128 * (1 - (1 - 8/128)^B)
+kv(ctx) = 209.7 MB + 0.0205 MB * ctx
+ ^ 25 sliding layers, FLAT ^ 5 full layers, 20,480 B/tok
+```
+
+**Model validation:** at ctx=1000, B=4 this predicts **1.94x** vs B=1. The
+measured value is **1.92x** (findings doc §7). It also independently reproduces
+the findings doc's "entire KV at 124k = 2.76 GB" (`kv(124000)` = 2,752 MB).
+
+At ctx=1000 (near p50 of 979):
+
+| B | unique experts | throughput vs B=1 | vs B=4 | per-request TPS |
+|---|---:|---:|---:|---:|
+| 1 | 8.0 | 1.00x | 0.52x | 106 |
+| **4 (today)** | 29.1 | 1.94x | — | **51** |
+| **8 (target)** | 51.6 | **2.45x** | **1.26x** | **32.5** |
+| 16 | 82.4 | 3.12x | 1.61x | 20.7 |
+| 32 | 111.8 | 4.19x | 2.16x | 13.9 |
+
+MoE batches well because at B=1 you draw 8 of 128 experts and at B=8 you draw
+~52 — once most experts are being read anyway, extra sequences are cheap on
+that term. It still flattens because `B * kv(ctx)` grows linearly: at B=8,
+ctx=5000, KV is ~27% of bytes read.
+
+B=16 would give another 1.28x, but 20.7 tok/s leaves little margin over the
+15 tok/s floor, and past 8 the clamp comment warns of a regime the one-engine
+release was built to eliminate. **B=8 first; revisit 16 only with measurements
+in hand.**
+
+### 3.2 B=8 has already been measured — use it
+
+`libs/mlx-swift-lm/benchmarks/reports/gemma4-26b-qat4bit-paged-gate-2026-07-09.md`
+already contains the B=8 row. Eager v2, gemma-4-26B, M4 Max:
+
+| B | decode TPS/req | decode-only aggregate (B × TPS) | step gain |
+|---|---:|---:|---:|
+| 1 | 101.8 | 101.8 | — |
+| 2 | 59.6 | 119.2 | 1.17x |
+| 4 | 38.0 | 152.0 | 1.28x |
+| **8** | **24.7** | **197.6** | **1.30x** |
+
+**Measured B=4 → B=8 is 1.30x against a modelled 1.26x.** The batching premise
+is validated at the target operating point.
+
+Two caveats that must travel with this number:
+
+1. **The workload shape changes between rows.** `promptMix(batch:)`
+ (`BenchCBv2RealModel.swift:293-299`) is hardcoded: B=4 is `100/500/1500/500`
+ (mean 650) and B=8 is `8 × 500` (mean 500). The B=4 → B=8 comparison is
+ therefore **not apples-to-apples**. Treat 1.30x as indicative, not as the
+ gate result.
+2. **The model over-predicts the absolute level.** Measured B=1 → B=4 is
+ **1.49x** against a modelled 1.94x, so the whole per-request curve sits
+ ~25% below the model even though the 4 → 8 *slope* matches. That is why the
+ plan targets ~25 tok/s per request, not the 32.5 the model implies.
+
+### 3.3 B=8 is **not** reachable by provider config alone
+
+Rev 1 claimed "no code change is required to test the batching hypothesis."
+**That is wrong, and it invalidated Gate G0 as originally written.**
+
+The provider-reported `max_concurrency` is only the `base` operand of a MIN
+against a coordinator-computed quality cap:
+
+```go
+// coordinator/registry/concurrency_cap.go:272-299
+base := p.maxConcurrencyForModelLocked(model)
+qc := qualityConcurrency(rate.tps, r.qualityCapFloorTPS, effectiveTPSLoadFactor, base, r.qualityCapFallback)
+capped := int(math.Ceil(float64(qc) * r.qualityCapOvercommitForModelLocked(model)))
+if capped < base { return capped }
+```
+
+```go
+// coordinator/registry/warm_pool_target.go:84-107
+// b = floor((solo/floor - 1) / k); 1 if solo <= floor
+```
+
+At production settings — floor `15` (`prod.env:27`), `k = 0.27`
+(`scheduler.go:57-65`), overcommit forced to `1.2` because
+`EIGENINFERENCE_QUALITY_CONCURRENCY_OVERCOMMIT` is unset
+(`concurrency_cap.go:103-105`) — the base only binds above a solo-TPS
+threshold:
+
+| target B | requires solo decode TPS ≥ |
+|---:|---:|
+| 4 | **27.2 tok/s** |
+| 8 | **39.3 tok/s** |
+
+gemma-4's solo median is **10–18 tok/s** → `qc = 1` → **effective cap 2, at
+both B=4 and B=8.** This is not a theory; it is pinned by tests:
+`concurrency_cap_test.go:140-147` asserts "provider-reported 8 is looser than
+quality 2 → quality binds", and `solo_tps_test.go:521-522` pins the cold-start
+gemma cap at 2. `QualityCap.Enabled` defaults true (`config.go:157`) and is
+unset in `prod.env`, so this is live.
+
+```mermaid
+flowchart LR
+ A["provider
engine_v2_max_concurrent = 8"] --> B["heartbeat
max_concurrency: 8"]
+ B --> C["clampBackendCapacity
ceiling 24 — 8 passes clean"]
+ C --> D["maxConcurrencyForModelLocked
base = 8"]
+ D --> E{{"MIN(base, ceil(qc x 1.2))
concurrency_cap.go:296"}}
+ F["solo TPS 10-18
floor 15, k 0.27"] --> G["qualityConcurrency = 1"]
+ G --> E
+ E --> H["effective cap = 2
UNCHANGED by B=8"]
+```
+
+**Consequence table at prod settings:**
+
+| model / rate source | cap at B=4 | cap at B=8 | change? |
+|---|---:|---:|---|
+| gemma-4-26b (solo 10–18) | 2 | 2 | **none** |
+| gpt-oss-20b on seed 30 | 4 | 4 | **none** |
+| gpt-oss-20b on registration bench | 4 | 8 | lands |
+
+So B=8 delivers concurrency only to benchmarked fast-model pairs. **Track E
+must ship a coordinator co-change in the same change-set** — see §8.0 — or G0
+measures nothing.
+
+### 3.4 The load factor `k = 0.27` is stale
+
+```go
+// coordinator/registry/scheduler.go:57-65
+// Measured on M4 Max (Qwen2.5-7B-4bit) at N=1/2/4/8 concurrent decodes:
+// per-request TPS = 92.8 / 69.5 / 35.9 / 29.6 ... effectiveTPSLoadFactor = 0.27
+```
+
+[DERIVED] `rate(8) = solo / (1 + 0.27 × 8) = solo / 3.16`. With gemma solo
+medians of 10–18 that predicts **3.2–5.7 tok/s** at B=8. The measured value is
+**24.7**. The coefficient is roughly **16x too aggressive** for the CBv2
+engine — it was fitted on a legacy engine and a dense 7B model.
+
+`k` is the single shared coefficient behind four systems:
+
+| consumer | site |
+|---|---|
+| admission quality cap | `concurrency_cap.go:293` |
+| effective decode TPS | `scheduler.go:1720` |
+| projected per-request TPS at batch | `scheduler.go:1954-1972` |
+| warm-pool target | `warm_pool_controller.go:423` |
+
+**Re-fitting `k` against the B=8 harness is a prerequisite for B=8, not a
+follow-up.** It is item 0.0 in §7.
+
+---
+
+## 4. Before / after
+
+```mermaid
+flowchart LR
+ subgraph Before
+ A1[request] --> B1["AdmissionV2: charge min(ctx, window)"]
+ B1 --> C1["ContiguousKVBackend
full: grow-by-doubling
windowed: full-window ring on first write"]
+ C1 --> D1["AttentionV1: q=128 blocks (#85)
score tensor 0.51 GB
span chunks: single call, 2.04 GB"]
+ D1 --> E1["engine B=4 / coordinator cap 2
prefix reuse via frozenFullReplay R=25,600"]
+ E1 --> F1["gemma donate floor 27,136
2.3% eligible"]
+ end
+ subgraph After
+ A2[request] --> B2["AdmissionV2: charge window
+ parametric activation reserve"]
+ B2 --> C2["PagedKVPool
pool = B x perSeqWorstCase
ring = window + spec span"]
+ C2 --> D2["PagedLayerCache: still single-call
+ gathered K/V copy (REGRESSION)"]
+ D2 --> E2["engine B=8 / coordinator cap 8
prefix reuse via installShared, R=0"]
+ E2 --> F2["gemma donate floor 1,024
~37% eligible"]
+ end
+```
+
+---
+
+## 5. Phase gates
+
+Six stop-or-continue decisions (G0 split; G5 added).
+
+| Gate | Question | Exit criterion |
+|---|---|---|
+| **G0a** | Does the coordinator actually dispatch 8? | `effectiveMaxConcurrencyForModelRateLocked` returns 8 for gemma-4 on a canary; `slot.NumRunning` observed at 8 |
+| **G0b** | Does batching pay end to end? | agg throughput ≥ 1.07x of B=4 at matched prompt mix; per-request decode ≥ 22 tok/s |
+| **G1** | Is paged sized correctly? | **per-sequence** paged KV ≤ contiguous at ctx {1k, 10k, 100k}; pool footprint fits 36 GB boxes |
+| **G2** | Is parity green? | MTP token-exact, vision serving, packed prefill active, prefix reuse ≥ contiguous |
+| **G3** | Does gpt-oss canary hold? | 24h at parity or better on TTFT p50/p90, decode TPS, 503 rate |
+| **G4** | Does gemma-4 hold? | same, plus donation rate materially above 2.3% |
+| **G5** | Is the canary observable? | coordinator can segment TTFT/TPS/error-rate by KV backend (§18) |
+
+Three changes from Rev 1, all forced by measurement:
+
+- **G0 is split.** G0a is the coordinator co-change; without it G0b is
+ unmeasurable. Rev 1 collapsed them and would have reported "no gain."
+- **G0's ITL bar moved 25 → 22 tok/s.** The already-measured B=8 values are
+ 24.7 (gemma) and 21.9 (gpt-oss); a 25 bar fails on data the plan already had.
+ 22 keeps a real margin over the 15 floor without being pre-falsified.
+- **G1 says "per-sequence."** The 07-09 reports' `gpuPeak` for paged
+ (30.5–32.5 GiB) is dominated by the `--kv-gb 16` pool reservation, not by
+ KV/seq, and `gpuActive` is inert (13.48 GiB on every row — weights only).
+ As emitted, those columns do not answer G1.
+
+Gates map to **waves**, not to elapsed weeks — see §6.
+
+---
+
+## 6. Execution model — tracks and waves
+
+The whole plan is executed in one pass, in parallel. The binding constraint is
+not total effort; it is **file ownership** and **verification capacity**.
+
+### 6.1 The real constraint
+
+Mapping every work item to the files it touches shows four contended files:
+
+| File | Work items wanting it |
+|---|---:|
+| `Paged/PagedLayerCache.swift` | 5 (poison-page pad, exact-ring gather, packed prefill, spans, last-query) |
+| `Paged/PagedKVPool.swift` | 5 (poison page, guards, ring formula, lazy reservation, spec headroom) |
+| `Paged/PagedSequenceKV.swift` | 3 (fixed ring table, spec transaction, `installShared`) |
+| `EngineV2Factory+Production.swift` | 4 (merge configs, pool sizing, B=8, slot vetoes) |
+
+**Therefore: partition by file, not by workstream.** Once ownership is
+exclusive, most of the plan is genuinely independent.
+
+### 6.2 Tracks
+
+Each track owns its files exclusively. No two tracks edit the same file.
+
+| Track | Owns (exclusive) | Work items |
+|---|---|---|
+| **T — oracle** | `Tests/CBv2Paged*`, `CBv2KVSharingParityTests`, differential harness | the parity oracle (§6.3) |
+| **E — memory + coordinator** | `AdmissionV2.swift`, `UnifiedMemoryCap.swift`, `ModelLoadAdmission.swift`, coordinator `registry/{concurrency_cap,warm_pool_target,servability,scheduler,pooled_admission,budget_clamp,health_ejection,capacity_rate,solo_tps}.go` | 0.0, 0.1, 0.3, §8 |
+| ~~**A — attention**~~ | ~~`AttentionV1.swift`~~ | **DONE — shipped as #85 (`abd1985`)** |
+| **F — telemetry + wire** | `coordinator/protocol/{telemetry,messages}.go`, Swift `Telemetry/` + `Protocol/Types.swift`, `console-ui/src/lib/telemetry-types.ts`, `console-ui/src/app/providers/types.ts`, `api/telemetry_handlers.go`, `docs/reference/telemetry-schema.md` | §18 |
+| **P — pool** | `PagedKVPool.swift`, `PagedAttentionKernel.swift` | 0.5, 0.6, 1.2 (formula), 1.3, 3.1, 6.4 |
+| **R — row** | `PagedSequenceKV.swift`, `PrefixReusePlan.swift` | 1.3 (row side), 3.2, 3.3, 4.1 |
+| **L — layer** | `PagedLayerCache.swift`, `LayerCacheBankV2.swift` | 0.5 (pad site), 1.2 (gather++chunk), **0.2p (paged sub-blocking)**, 2.1–2.5 |
+| **X — factory** | `EngineV2Factory+Production.swift`, `ProviderConfig.swift`, `EngineV2SlotFactory.swift`, `EngineV2Bridge*.swift`, `EngineV2Config.swift` | 0.4, 1.1, 2.6, 6.1–6.3, 6.5 |
+| **M — MTP seams** | `MTP/EngineLoopV2+MTP*.swift`, `EngineV2.swift` (mode selection) | 3.4, 3.5 |
+| **D — SSD tier** | `provider-swift/.../KVCacheSSD/*`, `PrefixCachePolicy.swift` | 4.2 |
+| **G — compiled** | `Compiled/*` and its hooks in `FullSequenceKV`/`WindowedSequenceKV`/`EngineLoopV2` | §14 |
+| **C — CI + benchmark** | `.github/workflows/ci.yml`, `Makefile`, `scripts/gemma_contbatch/*`, `Sources/ProviderBenchmark/*`, `Sources/BenchCBv2/*`, `e2e/testbed/*` | §19, §20 |
+
+Repo split: **L, P, R, M, G, T** are PRs to `Layr-Labs/mlx-swift-lm`.
+**D, X, C** and the provider half of **E**/**F** are PRs to `d-inference`. The
+submodule bump is the integration point and must be a single commit that takes
+every engine track at once.
+
+Two changes from Rev 1: **Track A is deleted** (shipped), and **Track E roughly
+triples** — Rev 1 gave it `registry/scheduler.go` alone, which is the wrong
+file for every coordinator item (§8).
+
+### 6.3 Track T ships first — and it does not start from zero
+
+Rev 1 said to build the differential harness from scratch, patterned on
+`CBv2MTPKVStagingTests.swift`. **A two-arm differential already exists:**
+
+```swift
+// libs/mlx-swift-lm/Tests/MLXLMTests/CBv2KVSharingParityTests.swift:76-78
+enum BackendKind { case contiguous; case paged }
+```
+
+with a shared `runChunkedBorrowingParity` body driven through both arms
+(`:165`, `:169`) and a hardware skip. A real-weights provider-side oracle also
+exists — `EngineV2PagedParityLiveTests.swift`, whose own header says it "gates
+explicit paged canaries before any future default reconsideration," i.e.
+exactly this plan.
+
+Track T's genuinely new work is therefore narrower and sharper:
+
+1. **A contiguous-backend arm for `CBv2PagedKernelTests`.** Today every
+ reference in that file is an in-file fp32 recomputation over a *mirror of
+ the same writes*, so a bug in the shared write path (the poison page,
+ §7.5) corrupts mirror and pool identically and parity still holds.
+2. **Adopt-vs-cold greedy parity** — the only oracle for the residency/plan
+ mismatch (§17). `adoptPrefixRoundtrip` (`CBv2PagedBackendTests.swift:264-300`)
+ is happy-path only.
+3. **A slab canary** for the poison page. No existing test writes a canary into
+ a neighbouring page and re-reads it after a short bulk write.
+4. **A CI step that actually schedules any of it** (§19).
+
+**T is not a testing chore appended to the end; it is the first deliverable.**
+
+### 6.4 The interface contract gates P, R, and L
+
+`PagedKVPool` ↔ `PagedSequenceKV` ↔ `PagedLayerCache` are the three hottest
+files and they call each other. Before those tracks start, freeze the seam:
+
+```
+pool: allocatePage / freePage / retainPage / refCount / ringPages
+ / reserve(pages) / writeTokens / gather / drainDeferredFrees
+row: installShared / restoreWindow / windowSnapshot / attendableViews
+ / decodeAttendRange / decodeTableLength / speculativeHeadroom
+layer: updateAndAttend(B,L) / attendBorrowing / bindSpanContext
+```
+
+~30 lines of protocol, one day of design. **This is the single decision that
+determines whether the three hottest files parallelize or collide.** It is not
+delegable — it should be written and reviewed by a human before Wave 1.
+
+Note: `beginSpeculativeWrite()` / `commitSpeculativeWrite()` are **already**
+protocol requirements (`CBv2Contracts.swift:297`, `:304`) with default no-ops,
+and the contiguous windowed ring already implements real staging
+(`WindowedSequenceKV.swift:183-195`). Only `speculativeHeadroom` is new.
+
+### 6.5 Waves
+
+| Wave | Runs in parallel | Entry condition |
+|---|---|---|
+| **0** | **T, E(0.0/0.1), F, C** + the §6.4 contract | none — start immediately |
+| **1** | **P, R, L, X, M, G, D**, E(0.3) | contract merged; T's harness green on contiguous; C's CI step live |
+| **2** | integration, submodule bump, benchmark matrix, adversarial review | Wave 1 merged |
+| **3** | G0a → G0b → gpt-oss canary (G3) → gemma-4 canary (G4) | Wave 2 green, G5 green |
+
+Within a track, items stay sequential — Track R does fixed ring table → spec
+transaction → `installShared` in that order, because they are the same file.
+
+Every track runs in its own git worktree so a mistake in the ownership map
+produces a merge conflict rather than silent clobbering.
+
+### 6.6 What does not compress
+
+Parallelism reduces wall clock, not total work. Rev 1 listed four hard floors;
+two of them were overstated and are corrected here.
+
+1. **G0 needs real traffic and a coordinator change.** No longer config-only
+ (§3.3). Bug A plus the quality-cap co-change must land first. ~1 wk.
+2. **Benchmarks need hardware — but less than Rev 1 claimed.** The B axis and
+ the engine axis are **free**: `BenchCBv2` already sweeps
+ `{v2, v2-compiled, v2-paged} × B{1,2,4,8}` in one process on one loaded
+ model and emits `gpuActive`/`gpuPeak` per cell automatically
+ (`BenchCBv2RealModel.swift:784-785`, `:978-982`). The 07-09 reports are one
+ command. **The context axis is the real gap** — `promptMix(batch:)` is
+ hardcoded and caps at 1,500 tokens, and the bench's paged pool hardcodes
+ `nominalMaxSequenceLength: 4096`, so G1's ctx {10k, 100k} is unreachable
+ without two source edits (Track C).
+3. **Canary gates are wall-clock.** G3 and G4 are 24h soaks each.
+4. **The three silent-corruption risks need adversarial review** — shared-page
+ writes, residency/plan mismatch, `spanChunkMask` offsets. All produce wrong
+ output with no crash and no telemetry. Each should be reviewed by someone
+ other than its author.
+
+### 6.7 Wall clock
+
+| Wave | Elapsed |
+|---|---|
+| 0 (4 tracks + contract) | ~1 wk |
+| 1 (7 tracks) | ~1–2 wk |
+| 2 (integration + hardware, serialized) | ~1 wk |
+| 3 (gates, wall-clock bound) | ~1–1.5 wk |
+| **Total** | **~4–5.5 weeks** |
+
+Against ~20–24 engineer-weeks of content (Track A's ~1 wk is now free).
+
+---
+
+## 7. WS-0 — Memory model · Tracks E, L, P, X
+
+None of this needs paged. All of it is needed *by* paged, and most of it
+independently unblocks B=8.
+
+### 0.0 Re-fit the coordinator load factor · **Track E** — NEW, gates everything
+
+`effectiveTPSLoadFactor = 0.27` (`scheduler.go:57-65`) is fitted on legacy-engine
+Qwen2.5-7B data and mispredicts CBv2 gemma-4 at B=8 by ~16x (§3.4). Re-fit
+against the B-sweep from Track C, and thread the new value through all four
+consumers. Without this, the quality cap (0.0b) cannot be raised safely,
+because the same coefficient sets the warm-pool target and the TTFT backlog.
+
+### 0.0b Let the quality cap reach 8 · **Track E** — NEW, gates G0
+
+Pick one, in ascending order of blast radius:
+
+| Option | Change | Blast radius |
+|---|---|---|
+| (a) per-model overcommit | `EIGENINFERENCE_QUALITY_CONCURRENCY_OVERCOMMIT_BY_MODEL` for gemma-4 | config only; `qualityCapOvercommitByModel` already parsed at `concurrency_cap.go:112` |
+| (b) re-fit `k` (0.0) | raises `qualityConcurrency` for every model | `concurrency_cap_test.go`, `solo_tps_test.go`, warm-pool tests |
+| (c) lower the decode floor | changes routing *and* admission (they share the 15) | `main.go:194-199` couples them — highest risk |
+
+**Recommend (a) for the canary, (b) as the durable fix.** Do not touch (c):
+`EIGENINFERENCE_MIN_DECODE_TPS` is simultaneously the routing floor and the
+quality-cap floor.
+
+Also set `EIGENINFERENCE_MODEL_SOLO_TPS_SEED` before B=8 ships. It is absent
+from `prod.env`, and higher B **starves the solo-TPS sampler** that feeds the
+cap — `soloSampleEligible` requires the whole box to have ≤1 running-or-waiting
+request (`solo_tps.go:140-152`). Without a seed the fallback is the
+provider-level registration benchmark, which is the exact cross-model
+contamination that file exists to prevent.
+
+### 0.1 Fix the admission/allocation mismatch · **Track E** — small, do this first
+
+Admission charges actual tokens capped at the window:
+
+```swift
+// libs/mlx-swift-lm/.../AdmissionV2.swift:206
+case .slidingWindow(let window): retained = min(tokens, window)
+```
+
+Allocation takes the whole window on first write:
+
+```swift
+// SequenceKV/WindowedSequenceKV.swift:516-522
+guard keys == nil else { return } // lazy…
+keys = MLXArray.zeros([1, kvHeads, window, keyTemplate.dim(3)], ...) // …but full-size
+```
+
+A 500-token request is charged ~102 MB of sliding KV and allocates 209.7 MB.
+
+| B | hidden overshoot |
+|---:|---:|
+| 4 | 0.4 GB (invisible today) |
+| **8** | **0.9 GB** |
+| 16 | 1.7 GB |
+
+On a 36 GB box with ~14 GB of KV headroom this is a 6% overshoot at B=8
+against a gate that believes it has margin. On unified memory the failure mode
+is swap pressure, not a clean rejection. **This must land before G0.**
+
+Three corrections to Rev 1:
+
+- Allocation is **lazy on first write**, full-*size* — not eager at admission.
+- **The fix already exists.** `AdmissionV2.fixedWindowBytesShortfall(afterReservingTokens:)`
+ (`:222-227`) computes exactly the missing bytes; its only caller is the
+ prefix-cache adoption path (`EngineV2.swift:493`). This is a call-site
+ addition, not new accounting.
+- The contiguous backend's own ledger is **correct** —
+ `ContiguousKVBackend.swift:343-352` charges windowed layers their full ring.
+ The leak is confined to the `AdmissionV2` layer.
+
+Also note B and paged pool size are already coupled:
+`PagedKVPhysicalCapacityPolicyTests.machineSizingMatrix` will **fail
+arithmetically** at B=8 — `usefulDemand = min(maxContext, 32768) × B × rate`
+goes 6 GiB → 12 GiB, `machineCap` (8 GiB) displaces it as the binding
+constraint, and the 128/256 GiB rows move 6 → 8 GiB.
+
+### 0.2 Query sub-blocking q=128 · ~~Track A~~ — **SHIPPED (#85, `abd1985`)**
+
+Landed upstream. `attendQueryBlocks` (`AttentionV1.swift:460-495`), width from
+`DARKBLOOM_CBV2_ATTN_QUERY_BLOCK` (default 128, `0` = kill switch, `:35-42`),
+applied at both prompt-attention call sites — `updateAndAttendRow:252` and
+`borrowAndAttendRow:394`. `attendSerialQueries` is now
+`attendQueryBlocks(blockSize: 1)` and is bit-identical to the loop it replaced.
+Score tensor 2.04 GB → 0.51 GB at 124k context. Max abs diff vs the single-call
+path 2.384e-07 (~2 ulp).
+
+**Two things Rev 1's trap warning becomes.** The `spanChunkMask` absolute-
+coordinate hazard was not fixed — it was **structurally avoided**:
+
+```swift
+// AttentionV1.swift:243-251
+if let spanContext, L > 1 {
+ // Vision spans carry a bidirectional overlay across the WHOLE
+ // chunk, so a query block cannot be sliced to a causal-only
+ // visible span. Span chunks keep the single-call path.
+ return attendSpanChunk(...)
+}
+```
+
+Therefore:
+
+- **The score-tensor bound does NOT hold for vision requests.** They still
+ materialise the full `[L, kL]` rectangle plus a `[L, kL]` bool mask per image
+ block. Vision chunks are also the only path whose `L` can exceed
+ `prefillChunkSize` (scheduler snap-over, `SchedulerV2.swift:135-140`) — so
+ they are simultaneously the largest-`L` and the only unblocked prefill path.
+ **WS-0.3 cannot be justified from the blocked bound** (see below).
+- The trap re-arms the moment anyone sub-blocks span chunks, which WS-2's
+ vision work will want. Keep the warning; move it to §9.
+
+Coverage note: `CBv2QueryBlockAttentionTests.swift` is strong (parity vs two
+independent references, causality by perturbation, window boundaries from both
+sides, `blockSize == 1` bit-equality, kill-switch truth table) but
+`attendQueryBlocks` is `private`, so **only one block width is exercised per
+run**, and the file does not run on CI (§19).
+
+### 0.2p Sub-block the paged prefill path · **Track L** — NEW
+
+**Paged gets none of #85's win.** `PagedLayerCache.prefillAttend`
+(`:309-344`) gathers the whole retained tail, builds one full `[l, retained]`
+mask, and issues a single `MLXFast.scaledDotProductAttention`. There is no
+`queryBlockSize` reference anywhere under `Paged/`.
+
+So as of `abd1985` the migration would **regress** prefill activation memory:
+contiguous 0.51 GB vs paged 2.04 GB at 124k, and paged additionally pays a
+gathered contiguous K/V copy that `PagedKVPool.gather` documents as a
+materialised copy (`:521-522`).
+
+This is now a **migration blocker**, not an optimisation. Port the blocking
+loop into `prefillAttend` before G1.
+
+### 0.3 Parametric activation reserve · **Track E**
+
+```swift
+// provider-swift/Sources/ProviderCore/Inference/UnifiedMemoryCap.swift:45
+static let defaultActivationReserveBytes: UInt64 = 3 * 1024 * 1024 * 1024 // 3 GiB
+```
+
+Flat. Its own doc calls it "a conservative SAFETY FLOOR, not a per-batch
+estimate," justified by a measurement taken **at 4-concurrent**. Nothing in it
+scales with B.
+
+The prefill score tensor is `[concurrent_prefills, heads, C, kL]`, fp32 in the
+composed fallback (gemma-4 head_dim 256/512 never reaches MLX's fused kernel —
+`sdpa_full_supported_head_dim` is {64, 80, 128}).
+
+| concurrent prefills | ctx 10k | ctx 100k |
+|---:|---:|---:|
+| 4 (today, budget-capped) | 0.66 GB | **6.6 GB — exceeds reserve** |
+| 8 (after §13.2) | 1.3 GB | 13.1 GB |
+
+Already broken at B=4 for long contexts. #85 fixes this **for text only** —
+vision chunks remain unblocked (0.2), so the parametric reserve must be
+`f(maxBatchedTokensPerStep, maxContext, heads, subBlockSize, spanChunkMaxL)`
+with the span path costed at full `L`.
+
+> **Rev 1 pointed at the wrong coordinator file.** It said to thread this
+> through `freeMemoryAdmits` (`registry/scheduler.go:1301`). That function is
+> **reserve-blind by design** — it charges flat tokens against the
+> provider-reported `active_token_budget_max` and on the cold path defers
+> wholesale to the provider-reported `free_for_load_gb`.
+>
+> The real mirror is **`coordinator/registry/servability.go:50`**:
+> ```go
+> // servabilityActivationReserveGB mirrors the provider's activation reserve
+> // kept aside on top of weights before KV cache (UnifiedMemoryCap ~3 GiB).
+> servabilityActivationReserveGB = 3.0
+> ```
+> used at `:98` in `coldTokenBudgetEstimate` to predict a cold provider's
+> post-load budget before any heartbeat exists.
+
+**Exact parallel-edit set** (9 sites, two of them hardcoded goldens):
+
+1. `registry/servability.go:44-50` — the two constants
+2. `registry/servability.go:93-111` — `coldTokenBudgetEstimate`
+3. `registry/servability.go:119-132` — `snapshotStructuralBudget` call site
+4. `registry/servability_test.go:7-12` — the constant-pinning doc comment
+5. `registry/servability_test.go:18-19` — `const wantRoomy = int64(110565)` **will break**
+6. `registry/servability_test.go:28,35-59` — tiny-node + kvpt-fallback equalities
+7. `registry/servability_test.go:90,95` — `wantCold` recomputations
+8. `registry/servability_provider_fit_test.go:57-75` — the gemma 28GB-on-48GB shape
+9. `registry/servability_provider_fit_test.go:113-121` — `coldTokenBudgetEstimate(48, 28, 0)`
+
+Do **not** conflate `scheduler.go:1272 coldLoadCatalogGBToMemGiB` — that is the
+weight-padding conversion.
+
+### 0.4 Merge the duplicate scheduler config · **Track X**
+
+`EngineV2Factory+Production.swift:356` (feeds paged pool sizing) and `:485`
+(handed to `EngineV2`; also passes `enablePrefixCache`). They agree on
+`prefillChunkSize` **only because both accept the memberwise default 512**
+(`CBv2Contracts.swift:594-595`) — nothing links them, and they live in
+different static funcs.
+
+The LOCKSTEP comment at `:410-415` wires the paged ring's `maxPrefillChunk` to
+instance #1, but the engine runs on instance #2. Divergence trips:
+
+```swift
+// PagedSequenceKV.swift:149-153
+precondition(n <= pool.config.maxPrefillChunk,
+ "windowed update of \(n) tokens exceeds maxPrefillChunk ...")
+```
+
+A `precondition` — process kill, not an error. `CBv2PagedSafetyTests`
+covers the *overflow* path (`maxPrefillChunk: Int.max` must throw) but **not**
+the divergence case.
+
+### 0.5 Poison page · **Tracks P + L** — ship independently
+
+`PagedLayerCache.swift:296` pads `deviceTables` with `0`, and page 0 is **not**
+a sentinel: `PagedKVPool.swift:184` builds the free list reversed and `:192`
+pops with `removeLast()`, so page 0 is the first page handed to the first
+tenant. Reserve one permanently-zeroed page per group and pad with it.
+
+> **Rev 1 overstated this.** It called this "a live cross-request leak on the
+> paged path today." It is a genuine **fail-open** design, but no reachable
+> trigger exists: `PagedSequenceKV.swift:256-258` states the protecting
+> invariant ("every position the decode actually attends was written, so its
+> ring slot is allocated"), upheld by `ensurePage` growing the table and
+> `decodeAttendRange` clamping to `[baseOffset, absoluteOffset)`.
+>
+> **A worse latent variant exists**, and Rev 1 missed it: the kernel's modulo
+> divisor is `decodeTableLength` (= `ringPages`, e.g. **97**) while the tables
+> array width is `max(8, max table.count)`. If the invariant breaks, the read
+> runs past the row's table row **into the next row's table** — worse than
+> page 0.
+>
+> **And item 1.2 tightens exactly that invariant.** 0.5, 1.2 and WS-3 are
+> coupled, not independently schedulable.
+
+There is a second pad-with-a-real-slot site at `PagedKVPool.swift:501-509`
+(`while padded.count < 8 { padded.append(slots[slots.count - 1]) }`) whose
+safety argument is also a code comment. No test would catch either (§19).
+
+### 0.6 Construction guards · **Track P**
+
+`blockSize % pageSize == 0` (256 % 16, `BlockHasher.swift:31` and
+`PagedKVPool.swift:82`) and `maxPrefillChunk + pageSize >= blockSize`. Both
+currently hold by coincidence across two files with zero cross-reference — the
+only page-modulo guards in the stack are PTOK-based
+(`PagedKVPool.swift:275`, `PagedAttentionKernel.swift:407`). Both are
+load-bearing for WS-4's windowed-sharing residency proof.
+
+---
+
+## 8. Coordinator surface — Track E · **NEW SECTION**
+
+Rev 1 gave Track E `registry/scheduler.go`. That is the wrong file for every
+item in this section. Raising B to 8 touches nine coordinator files, and four
+of them are **capacity-feedback loops that can cancel the throughput win**.
+
+### 8.1 The shed paths B=8 actually opens
+
+**`EIGENINFERENCE_MIN_DECODE_TPS` is not one of them.** It is soft
+(`scheduler.go:792-798`) and never rejects; `projectedPerRequestDecodeTPSAtBatch`
+unwinds the observed rate at `backendRunning` and reapplies at +1
+(`:1954-1986`), so a self-consistent observation survives the floor. What it
+*does* is narrow the candidate pool, so filled boxes lose to idle peers — a
+throughput cancellation, not an outage.
+
+The real risks are capacity-shaped:
+
+| # | Mechanism | Site | Effect at B=8 |
+|---|---|---|---|
+| 8.1a | **Live TTFT backlog → hard reject** | `scheduler.go:1537-1540` `backlogMs = tokensAhead / effectiveTPS × 1000`; drop at `:722-724` | `activeTokenBudgetUsed` ~doubles → `backlogMs` ~doubles → candidates cross the 9 s deadline (`prod.env:38`) → **429 `ttft_too_slow`**. `EIGENINFERENCE_TTFT_HARD_REJECT=true` in prod. |
+| 8.1b | **Budget clamp** | `budget_clamp.go:257-261`, default on | ONE capacity-503 zeroes the pair's live headroom for up to 5 min. Release needs a strictly-later heartbeat with ≥1024 free tokens **and** an accept. |
+| 8.1c | **Capacity-rate derater** | `capacity_rate.go:63-68`, `:190` | >25% reject rate over 8 samples → +15 s cost penalty. **No accept-triggered reset by design.** |
+| 8.1d | **Health ejection** | `health_ejection.go:59-61` | 10 consecutive capacity-shaped 5xx with zero interleaved successes → node quarantined 60 s–10 min. |
+
+These compose: a B=8 box that over-commits KV rejects a burst → clamp arms →
+capacity rate rises → cost penalty → fewer accepts → more consecutive rejects →
+ejection. **Track E must add a canary abort condition on 8.1b–8.1d.**
+
+Latent, not active: `ttftOccupancyMs` at `alpha=50` (`prod.env:39`) would
+compute ~18,000 ms at occ=8 vs a 9,000 ms deadline, but the term is provably
+**out** of the live decision (`scheduler.go:2346-2365` documents this as a
+safety invariant, `TTFT_ADMISSION_MODE=shadow`). Flipping that mode to enforce
+after B=8 would shed every 8-batched box instantly. **Add to the risk
+register, §17.**
+
+### 8.2 KV-byte accounting drift under paged
+
+Coordinator consumers split into two classes:
+
+| class | sites |
+|---|---|
+| rate-aware | `scheduler.go:1229`/`:2239` (`snap.kvBytesPerToken`); `pooled_admission.go:183-286`; `servability.go:102-105` when reported |
+| **rate-blind** | `scheduler.go:1381` (fixed `kvCacheBytesPerToken = 400_000`); `pooled_admission.go:106-109` (`max(400k, maxResident)`); `servability.go:104` fallback |
+
+As WS-1 lowers the real per-token rate **below** 400k, the rate-blind sites
+over-charge relative to the rate-aware ones by a factor that **grows as paged
+improves** — cold requests priced at 400k against a pool sized at the true
+lower rate. Net effect: `pooledBudgetAdmits` and `PredictServable` get
+progressively more pessimistic exactly as the engine gets better.
+
+The ceiling clamp (`maxKVBytesPerToken = 1 << 24`) never binds — paged lowers
+the rate. But the **floor** is a hazard: `clampKVBytesPerToken` maps a negative
+rate to 0, and 0 means "absent", which flips `knownZeroTokenBudget` from
+"known-full, reject" to "unknown, **fail open**". Pin the wire contract so a
+fully-committed paged ring can never emit 0.
+
+Worse, `kv_bytes_per_token` is **already wrong on paged slots**: it is reported
+unconditionally from contiguous-shaped sizing
+(`EngineV2Bridge+Capacity.swift:154` ← `ProviderLoop+EngineV2.swift:560`), but
+paged never reserves per-token (`EngineV2Bridge.swift:495`) — its true capacity
+is the immutable physical pool (`:711-713`, `kvBackendPoolBytes()` at `:729`),
+which is never on the wire.
+
+### 8.3 What does NOT change
+
+Three numerical decoys. State them so nobody "fixes" them:
+
+- `registry.go:4212 DefaultMaxConcurrent = 4` — the fallback for providers that
+ report **no** `BackendCapacity`. Leaving it at 4 while providers serve 8 is
+ correct (conservative for silent providers). Pinned by
+ `registry_capacity_test.go:17-18`.
+- `promptcontract/config.go:40 MaxConcurrency` — the prompt-planning sidecar's
+ own semaphore. Unrelated to inference batch size.
+- `registry.go:1197-1200` returns a flat **24** for any token-budget provider —
+ B is not the binding constraint on those slots at all.
+
+Also clean, verified: value 8 survives every clamp untouched
+(`registry.go:2699-2706`, ceiling 24; pinned by `clamp_test.go:121-133`), the
+protocol round-trips it, and no token-budget site assumes any concurrency.
+
+### 8.4 Observability regressions at higher B
+
+Two detectors go blind as B rises, both by design and both silently:
+
+- **Throughput-anomaly detector**: `api/throughput_anomaly.go:140-142` samples
+ only slots with `NumRunning <= 1`. At steady-state B=8 the sample supply
+ falls below `DefaultAnomalyMinSamples = 3`. This is the detector that would
+ notice a paged decode regression.
+- **Solo-TPS sampler**: `solo_tps.go:140-152` requires the whole box to be
+ near-idle. Feeds the quality cap (§3.3), so the cap's input degrades exactly
+ when the cap matters most. Mitigate with `EIGENINFERENCE_MODEL_SOLO_TPS_SEED`.
+
+Finally, `api/me_handlers.go:622` shows providers the **provider-level**
+`MaxConcurrency` (the hardcoded 24), not the per-model effective cap of 2. A
+provider who sets B=8 will see "24" and no change either way.
+
+---
+
+## 9. WS-1 — Paged sized correctly · Tracks X, P, R, L → **G1**
+
+The 2.3x memory gap measured in the paged gate reports is a sizing bug plus an
+over-provision, not a property of paging.
+
+Calibration on that "2.3x": it is the **B=1 GPT-OSS `gpuPeak`** ratio
+(28.21/12.44). At the fleet-relevant batch sizes it is ~2.13x (gpt-oss B=4/8)
+and **1.75x** (gemma B=8). `gpuActive` is *identical* across all engines
+(13.48 GiB gemma / 11.25 GiB gpt-oss) — the gap is entirely peak, which is
+consistent with eager slab materialisation.
+
+| # | Item | Effect |
+|---|---|---|
+| 1.1 | `poolCapacity = min(kvBytesCapacity, B * perSeqWorstCase * safety)` | Paged **eagerly materialises** its physical pool (`materializeSlabs()`, `EngineV2Factory+Production.swift:424`) while contiguous treats its grant as a **lazily-enforced ceiling** (`ContiguousKVBackend.swift:81`, `:285-287`). 28 GB → ~2 GB at B=4. |
+| 1.2 | Ring = `ceil(window/pageSize) + ceil(maxSpeculativeSpan/pageSize)` | Today `window + maxPrefillChunk` = 1,552 tok for a 1,024 window. A **1.52x penalty on 25 of 30 layers** — this is why paged currently loses on memory. Attend `gather(ring) ++ chunk` as contiguous does. |
+| 1.3 | Lazy reservation: charge `min(ctx, window)` | `pageDemand` is capped only by worst-case `maxLength` (prompt + maxTokens), so any request with `maxLength ≥ 1552` charges the full ring. `E[min(ctx, 1024)] ≈ 757` vs 1,024 over the production distribution. |
+
+Rev 1 said 1.1 gives paged "the entire remaining KV grant." Corrected:
+`PagedKVPhysicalCapacityPolicy.swift:104-108` caps it five ways —
+`min(logicalGrantBytes, usefulDemand, machineCap, liveLimit, maxBufferLength×2)`
+— and the in-code comment at `:421-423` reads "Commit only the
+independently-capped PHYSICAL pool." The eager-vs-ceiling contrast is real; the
+"entire grant" framing is not.
+
+The ring arithmetic reproduces exactly:
+
+```swift
+// PagedKVPool.swift:420-423
+let tokens = window + config.maxPrefillChunk // 1024 + 512 = 1536
+return (tokens + config.pageSize - 1) / config.pageSize + 1 // 96 + 1 = 97
+```
+
+97 pages × 16 = **1,552 tokens** = **1.5156x**. Note 1,536 is already a multiple
+of 16, so the entire 16-token excess comes from the unconditional `+1` slack
+page.
+
+Projected KV per sequence:
+
+| | sliding | full | total |
+|---|---:|---:|---:|
+| contiguous @ ctx 5k (eager window + doubling) | 209.7 MB | 138 MB | **348 MB** |
+| paged today @ ctx 5k (1.52x ring) | 317.9 MB | 102.4 MB | 420 MB |
+| **paged fixed** @ ctx 5k | 209.7 MB | 102.4 MB | **312 MB** |
+| paged fixed, *expected over the traffic distribution* | 155 MB | — | — |
+
+Rev 1's table put the distribution-expected 155 MB (= `E[min(ctx,1024)] = 757`
+tokens) in a column labelled ctx 5,000, where the window is in fact full. Both
+numbers are now shown with their meaning. At B=8 and ctx 5k: contiguous 2.8 GB,
+paged fixed 2.5 GB.
+
+**1.2 is coupled to WS-3 and to 0.5.** Shrinking the ring removes the accidental
+headroom MTP staging depends on, and tightens the invariant the poison-page pad
+relies on. The `+maxSpeculativeSpan` term is mandatory.
+
+**No existing test constrains this.** `CBv2PagedBackendTests.swift:198-201`
+re-derives its expectation from the same formula and thereafter asserts only
+`table.count <= ring` — an under-provision bound. Shrinking *or* growing the
+ring fails nothing. Track T must add an upper-bound assertion.
+
+---
+
+## 10. WS-2 — Capability parity · Tracks L, X
+
+| Capability | Gap | Work | Est |
+|---|---|---|---:|
+| **Packed prefill** | `precondition(b == 1, ...)` at `PagedLayerCache.swift:142` (twin at `:175`) | Replace with the per-row loop `AttentionV1.updateAndAttend` already uses for `B>1, L>1` (`:127` → `updateAndAttendRow:235`). Nothing in it is storage-specific — `row.update(...)` then `attend(...)`, both `CBv2SequenceKV` protocol surface. | **3 d** |
+| **Vision / spans** | No `CBv2SpanMaskBinding` conformance | Compose the span overlay onto the mask `prefillAttend` already builds in absolute coordinates. Paged is *better* positioned than contiguous, which must abandon symbolic `.causal`. **Carries the `spanChunkMask` trap forward** — see below. | 1.5 wk |
+| **Capability protocol** | `supportsPackedPrefill = caches.allSatisfy { $0 is CBv2LayerCache }` (`LayerCacheBankV2.swift:121-123`) | A type check makes every future backend second-class by construction. Convert to an affirmative protocol. | 3 d |
+| Last-query prefill | No `CBv2LastQueryPrefillLayerCache` conformance | Days — and **dead on gemma-4-26B anyway**: `gemma4SupportsLastQueryPrefill` (`Gemma4Text.swift:80-84`) requires `!layerUsesSharedKV(numHiddenLayers-1)`, but `numKvSharedLayers` defaults to 20 (`:156`, `:252`) and `layerUsesSharedKV` (`:330`) always returns true for the last layer when it is > 0. `DARKBLOOM_GEMMA4_PREFILL_LAST_QUERY=0` is a no-op kill switch. | 2 d |
+| `uniformAttentionSoftcap` | Bank only inspects `CBv2LayerCache` (`:99`) → nil → fail-safe compiled veto (`EngineV2.swift:205-215`) | Report it for paged caches. **Not sufficient alone** — `EngineV2.swift:225` carries an independent `backendVeto = !producesCompiledDecodeEligibleRows` OR'd on the same line. Moot if §14 deletes compiled decode. | 2 d |
+| Slot vetoes | VLM and kv-quant forced to contiguous (`EngineV2SlotFactory.swift:182-185`) | Lift the VLM veto once spans land. **Note:** the vetoes are currently load-bearing for *test* correctness — `LiveInferenceFixtures` defaults `kvBackendConfig: "auto"`, so a default flip repoints ~10 live suites at paged and the VLM veto bounces them back. | 1 d |
+
+**The `spanChunkMask` trap, relocated from Rev 1's §0.2.** `AttentionV1.swift:559-577`
+is the only absolute-coordinate mask site in the file:
+
+```swift
+let chunkEnd = context.chunkEnd
+let qAbs = MLXArray(Int32(chunkEnd - L) ..< Int32(chunkEnd))...
+let kAbs = MLXArray(Int32(chunkEnd - kL) ..< Int32(chunkEnd))...
+```
+
+#85 avoided it by keeping span chunks on the single-call path. Any work that
+sub-blocks spans — which the vision item above will want, for the memory reason
+in §7.0.2p — re-arms it. Under sub-blocking, `L` becomes the sub-block size
+while `chunkEnd` stays the whole-chunk end, so `qAbs` slides to the wrong
+absolute window. **Silent wrong output on multimodal, no crash, no telemetry.**
+
+---
+
+## 11. WS-3 — MTP parity · Tracks P, R, M
+
+**The staging blocker is largely illusory.** The comment at
+`PagedSequenceKV.swift:107-114` claims the ring aliases within the window. It
+does not:
+
+```swift
+// PagedKVPool.swift:420-423
+let tokens = window + config.maxPrefillChunk // +512, not +0
+```
+
+Aliasing distance is `ringPages * pageSize`. Gemma-4: ring 1,552 tokens vs
+window 1,024 → **528 tokens of headroom against a max speculative span of 8, a
+66x margin.** The safety condition is `R >= W + s`; it holds by 520 tokens. The
+Metal shader asserts exactly this (`pagedattention.metal:105-107`: "Windowed
+rings cannot alias"). **The shader is right and the Swift comment is wrong** —
+the comment also contradicts its own file header 97 lines above (`:14-16`).
+
+**Framing correction to Rev 1.** Staging is not blocked *by aliasing*. It is
+blocked by an unconditional gate whose *justification* is the false comment:
+
+```swift
+// PagedSequenceKV.swift:115
+public var supportsSpeculativeWrites: Bool { windowSize == nil }
+```
+
+The contiguous windowed ring implements real staging
+(`WindowedSequenceKV.swift:183-195`), so this is an implementation gap, not an
+architectural one.
+
+| # | Item |
+|---|---|
+| 3.1 | Explicit `maxSpeculativeSpan` term in `ringPageCount` + construction guard — converts an accident into an enforced invariant. The term appears **nowhere** in source today. |
+| 3.2 | Bookkeeping-only transaction: `speculativeBase`, tightened rollback precondition, deferred page frees, `lastUpdateTokens` restoration |
+| 3.3 | Derive `supportsSpeculativeWrites` from headroom; delete the false comment |
+| 3.4 | **Force serial verification for paged banks.** See the correction below. |
+| 3.5 | **Materialize MTP captures before rounds.** Contiguous gets snapshot freezing free from MLX array versioning; paged slabs are mutated in place, and `PagedKVPool.gather`'s own doc (`:523-526`) warns "a stale unevaluated gather could observe pages after they were recycled." |
+
+> **3.4 was mis-justified in Rev 1, and it matters.** Two defects:
+>
+> - The cited path `MTP/MTPTargetVerification.swift` **does not exist**. The
+> real file is `MTP/EngineLoopV2+MTPTargetVerification.swift`; the
+> `preconditionFailure("MTP rectangular verification requires CBv2 layer
+> caches")` is at `:49-54`.
+> - "Unreachable today only because the rectangular envelope defaults to 0" is
+> **false in production.** That 0 is the library struct default
+> (`MTPContractsV2.swift:226`). Production overrides it:
+> `EngineV2SlotFactory.swift:224-230` passes
+> `MTPAutomaticVerificationPolicy.maxRectangularTokens()`, which returns **8
+> on M3/M4/M5** and 4 on M1/M2 — never 0.
+>
+> **Rectangular verification is live in production.** The precondition is
+> unreachable only because paged rows never reach an MTP-enabled slot — a
+> guarantee **this migration removes**. The first paged MTP slot is a *process
+> abort*, not a graceful fallback. `DARKBLOOM_MTP_VERIFICATION_MODE=rectangular`
+> also bypasses the envelope check entirely. **3.4 is a hard blocker, not
+> hygiene.**
+
+**Zero Metal changes.** Conditional +2–3 wk for paged rectangular verification,
+gated on measuring how much of MTP's 1.24–1.79x survives serial-only.
+
+MTP context: the drafter **is published** —
+`mlx-community/gemma-4-26B-A4B-it-qat-assistant-4bit`, rev `bb94eae1`, 236 MB,
+`spec_dec` metadata on `gemma-4-26b-qat-4bit` only, full digest chain verified
+against `models.darkbloom.ai`. It is gated behind `[backend] mtp`, default
+`false` (`ProviderConfig.swift:257`).
+
+---
+
+## 12. WS-4 — Prefix reuse · Tracks R, D — **hard migration blocker**
+
+**Paged today gives gemma-4 zero prefix reuse.**
+`PrefixReusePlan.swift:127-141` sees `hasOwningFullAfterWindow` for gemma's
+`sliding ×4 → full` pattern and returns
+`unsupported(.pagedHybridRequiresDualCursor)` for `.pagedFP16`. "Zero" is
+literal, not rhetorical: `unsupported` sets `strategy: nil` (`:293-305`) and
+`isSupported` requires non-nil (`:47-49`). `PagedKVBackend.swift:156-158`
+**throws** `backendIneligible` on `.frozenFullReplay`.
+
+**Flipping gemma-4 to paged without this is a 2.3% → 0% regression** — an
+elimination, not a degradation.
+
+Where the 27,136 comes from — all computed, none hardcoded:
+
+```
+R = windowCount × maxWindow = 25 × 1024 = 25,600 (PrefixReusePlan.swift:117-118)
+floor = adoptionBoundTokens + minEffectiveTokens
+ = 25,600 + 1,536 = 27,136 (SSDPrefixCache.swift:783-785)
+```
+
+`minEffectiveTokens` is 1,536, not the generic 1,024 default — the long-hybrid
+override at `PrefixCachePolicy.swift:151-155` fires when
+`conservativeReplayBoundTokens >= 25_600`. (The findings doc's 26,624 used the
+generic default and is wrong; live tests pin `bound == 25_600` and
+`benefitFloor == 1_536`.) The gate is a strict `>`, so the true minimum
+donatable prompt is **27,137** tokens.
+
+| # | Item | Est |
+|---|---|---:|
+| 4.1 | `installShared` / `restoreWindow` / `windowSnapshot` on `PagedSequenceKV`; fixed-length ring table with sentinel; `CBv2PrefixResidencyClass` threaded through `derive`/`plan` | 1.5 wk |
+| 4.2 | SSD windowed sidecar blocks | 2.5 wk |
+
+The single semantic change that deletes 25,600 tokens of replay:
+**`baseOffset = M - W` instead of `M`.** With R=0 there is no second cursor, so
+`pagedHybridRequiresDualCursor` evaporates rather than being solved.
+
+Two facts make windowed sharing work, both currently unasserted (hence 0.6):
+
+- Ring slot is `(p / pageSize) % ringPages` over the **absolute** position
+ (`PagedSequenceKV.swift:187-193`, stated in the file header at `:10-11`), so
+ donor and adopter share identical slots with no re-indexing.
+- `blockSize 256 % pageSize 16 == 0`, so every matched boundary is
+ page-aligned and post-adoption writes start at slot 0 — COW is a pointer
+ swap, never a byte copy.
+
+Sidecar economics (gemma-4): **3.25x disk and write-wear, +9.4 MB stage read,
++6 ms** against a 1,000 ms budget (write-always, read-terminal-four). Buys
+**27,136 → 1,024** and **2.3% → ~37%** donatable traffic.
+
+**Open question the plan does not resolve.** The 2.3% → 37% win comes from
+4.2, the SSD windowed sidecar — persisting the sliding window so it need not be
+replayed. That is a *cache format* change. Paging makes adoption a pointer swap
+instead of a ≤210 MB memcpy, but nothing here establishes that a windowed
+sidecar is impossible on contiguous. [INFERENCE] If it is not, the migration's
+largest single justification is separable from the migration. **Resolve this
+before Wave 1** — it is a one-day spike against `WindowedSequenceKV`'s ring and
+`SSDPrefixCache`'s block format, and it can save 20 engineer-weeks.
+
+**Deferred: refcounted COW page sharing (3 wk).** Production installs only
+`SSDPrefixCache`, never `PrefixCacheV2` — in-memory sharing ships zero
+production value until a resident tier exists. Revisit after B=8.
+
+Cross-repo hazard: `adoptionBoundTokens` hardcodes
+`backend: .contiguousUnquantized` (`PrefixCachePolicy.swift:135-140`) while its
+own selection-aware sibling at `:120-126` branches on `.paged`. **There are
+three such hardcodes, not one** — the other two are
+`EngineV2SSDPrefixCacheLiveTests.swift:158-159` and
+`FrozenReplayRealModelTests.swift:143-144`. All must become residency- and
+backend-aware or the floors will silently disagree.
+
+Prior-art note: the measured gemma replay benefit is *small and noisy* just
+above 25,600 — one sample in `2026-07-19-frozen-full-prefix-cache-proof.md` was
+**32.2% slower**. The floor fix matters precisely because it moves the win into
+the region where the saved fraction is large.
+
+---
+
+## 13. WS-6 — Scale to B=8 · Tracks X, P, E
+
+| # | Item |
+|---|---|
+| 6.0 | **Coordinator co-change (§7.0.0b).** Without it, 6.1 is invisible in production. |
+| 6.1 | `engine_v2_max_concurrent = 8`, ramped per model via `engine_v2_max_concurrent_by_model` |
+| 6.2 | `maxBatchedTokensPerStep` 2048 → 4096. At B=8 the current budget affords ~4 prefill chunks per step, so 8 prefilling rows each get a chunk every other step. Requires 0.3 first (activation memory doubles). Note raising it alone does **not** exercise sub-blocking — per-call `L` is capped by `prefillChunkSize` (still 512), not by the step budget. |
+| 6.3 | **Enable `DARKBLOOM_CBV2_MIXED_PREFILL_CAP`** (`Int?`, nil = OFF, `EngineV2.swift:295-302`). It bounds prompt tokens on steps that **also carry decode work**; pure-prefill steps stay uncapped (`SchedulerV2.swift:307-318`), and even `cap == 0` cannot deadlock (`:194-197`). At B=8 a single 512-token prefill chunk makes 7 decoding rows wait out the whole step. This is the ITL protection that makes higher B tolerable rather than janky. |
+| 6.4 | Adaptive `PTOK`/split sizing — fixes paged's B=1 deficit (~16 threadgroups on a 40-core GPU at short context) |
+| 6.5 | Hardware-aware chunk sizing: `chunk = clamp(target_step_ms * measured_tok_per_ms, 512, 4096)` from the existing `observed_prefill_tps` EWMA. Note `EngineV2Config.swift` holds **zero live knobs** — it is a retired-env warner; this belongs in the factory. |
+
+**There are four independent `4`s for concurrency across two repos**, and Rev 1
+assigned only the first to Track X:
+
+| site | role |
+|---|---|
+| `EngineV2Factory+Production.swift:78` | `productionMaxConcurrentRequests` |
+| `EngineV2Bridge.swift:235` | bridge default |
+| `EngineV2Config.swift:133` | config default |
+| `CBv2Contracts.swift:594` | scheduler default |
+
+Plus `ProviderConfig.swift:172`/`:241` and `StandaloneServer.swift:95` for the
+TOML surface. Track X owns all of them; the justification comment at
+`ProviderConfig.swift:91-95` must be updated in the same commit or it will
+contradict the new default.
+
+---
+
+## 14. WS-5 — Retire compiled decode · Track G
+
+Incompatible, and proven: `PagedKVPool.gather` returns a fresh variable-length
+**copy** (`:521-522`, `:550-554`), so a paged row can never satisfy the
+requirement for a live, stable, fixed-shape `[1, kvHeads, capacity, headDim]`
+array that *is* the row's storage (`FullSequenceKV.swift:187-192`, enforced by
+`precondition` at `CompiledLayerCacheV2.swift:95-96`).
+
+**But it is worth negative.** Same-run A/B, GPT-OSS-20B decode TPS:
+
+| B | v2 eager | v2 compiled | Δ |
+|---:|---:|---:|---:|
+| 1 | **101.8** | 96.7 | **-5.0%** |
+| 2 | **59.8** | 56.0 | **-6.4%** |
+| 4 | **37.3** | 35.3 | **-5.4%** |
+| **8** | **21.9** | **21.6** | **compiled falls back entirely** |
+
+Compiled attention masks the entire padded 4,096-slot buffer every step
+(`kvCapacity = 4096`, `CompiledLayerCacheV2.swift:216`/`:229`) while eager
+attends `.. PINNED contiguous: this drill asserts the LEDGER shrink/serve/regrow
+> arithmetic... Under paged-by-default, gpt-oss's lone-slot grant would be
+> physically committed as slabs (~the full fleet budget on this box) and the
+> later gemma load correctly FAILS CLOSED at the post-load headroom guard — the
+> designed v1 paged co-residency behavior, but not what this test measures.
+> Meaningful paged co-residency at these scales needs the **pool-resize
+> follow-up**.
+
+Providers hold up to `maxModelSlots` (default 3) models simultaneously, and the
+fleet is 94 mixed boxes (findings §4). **Paged-by-default makes every
+multi-slot box hit this.** The "pool-resize follow-up" is referenced nowhere in
+this plan's 11 tracks. Either schedule it as a Wave-1 item under Track X/P, or
+scope the rollout to single-model boxes and say so in §18.
+
+Related, and currently correct-by-refusal:
+`EngineV2ProductionWiringTests.mixedPagedContiguousResliceIsLedgerOnly`
+(`:687-801`) pins that the paged pool is construction-fixed and re-slices move
+ledgers only. Its central contrast is a **mixed** fleet
+(`kvBackendKindByModel: ["gemma-4-26b-qat-4bit": .paged]` with slot B
+contiguous); under a paged default both slots are paged and the test's
+asymmetry collapses. It needs restructuring, not re-pinning.
+
+---
+
+## 16. WS-7 — Rollout · Track F + ops
+
+**Telemetry first — you cannot roll out what you cannot see.**
+
+### 16.1 The canary discriminator is a rollout blocker
+
+**The wire cannot distinguish a paged provider from a contiguous one.**
+`BackendSlotCapacity` (`coordinator/protocol/messages.go:267-300`) has 20 fields
+and no KV-backend field; the Swift mirror (`Protocol/Types.swift:437-503`) is
+identical.
+
+Consequence during a mixed canary: the coordinator **cannot** A/B TTFT/TPS/error
+rate by backend, **cannot** exclude paged slots from routing on regression, and
+**cannot** attribute a fleet-wide regression to the rollout. This is Gate G5.
+
+Two near-misses that will be mistaken for coverage:
+
+- `PrefixCacheModelStatus.Backend` (`messages.go:164`) does carry the real
+ serving kind, but it is **fleet-aggregate only**
+ (`cache_status.go:53 ByBackend[...]++`), **conditional** on the provider
+ sending `prefix_cache_statuses` at all (`api/provider.go:472-474`), and
+ unread by console-ui.
+- The `engine_v2_kv_backend` INFO telemetry event
+ (`EngineV2Config.swift:236-246`) fires **once per engine construction** on a
+ best-effort sink that **drops on full** (`telemetry_sink.go:14-17`) behind a
+ 100/min rate limit. A once-per-load droppable event is not a fleet inventory.
+
+**Decision required: telemetry fields for diagnostics, heartbeat field for
+anything the canary gates on.** They are different plumbing with different edit
+sets, and Rev 1 conflated them.
+
+### 16.2 The real edit sets
+
+**Telemetry-field path — six artifacts, not four.** `coordinator/protocol/telemetry.go`
+is a **non-edit**: `Fields map[string]any` (`:126`) is generic.
+
+| # | Artifact | Anchor |
+|---|---|---|
+| 1 | Go allowlist | `api/telemetry_handlers.go:48-147` (applied `:417`) |
+| 2 | Swift client filter | `Telemetry/TelemetryEvent.swift:238-283` |
+| 3 | TS set | `console-ui/src/lib/telemetry-types.ts:58-143` |
+| 4 | Schema doc | `docs/reference/telemetry-schema.md` (anchors at `:106` are stale) |
+| 5 | Ops doc | `docs/architecture/operations/telemetry.md:29-31` (all three anchors stale) |
+| 6 | **A real 3-way parity test** | does not exist — see below |
+
+Copy the prefix-replay cohort (`prefix_reuse_strategy`, `prefix_matched_tokens`,
+…) — eight fields appended as a commented block in all three layers, Go `:132-142`,
+Swift `:280-283`, TS `:135-142`.
+
+**Heartbeat path — five artifacts.** `protocol/messages.go` +
+`messages_backend_capacity_test.go` + `Protocol/Types.swift` (four sites:
+property, CodingKey, decode `:569-579`, encode `:595-605`) +
+`console-ui/src/app/providers/types.ts:33-45` (an undocumented **5th mirror**
+carrying 8 of 20 fields) + its test.
+
+### 16.3 No test enforces allowlist parity
+
+Add a field to Go only and CI stays green while the Swift client filter strips
+it before transmission. Four supposed guards, all miss:
+
+| guard | what it actually pins |
+|---|---|
+| `protocol/telemetry_symmetry_test.go:15` | event **shape** only — never `fields` keys |
+| `TelemetrySymmetryTests.swift:63-77` | the **kind** set/count |
+| `api/telemetry_handlers_test.go:200-205` | seven hardcoded keys, **Go-side existence only** |
+| `console-ui/__tests__/telemetry.test.ts:66-85` | asserts `_bufferSize() == 1` — never inspects the filtered output |
+
+The drift is **already live**: the Swift filter lacks `network_reachable`,
+`coordinator_url`, `url`, `user_agent`, `route`; the TS set lacks the first two.
+**A real parity test is a WS-7 deliverable, not a nice-to-have.**
+
+### 16.4 Fields to add
+
+MTP appears **nowhere on the wire** (control-checked zero across
+`coordinator/protocol/`, `coordinator/api/`, provider `Protocol/` and
+`Telemetry/`, and `console-ui/src/lib/`). Add `mtp_enabled`, `mtp_active`,
+`mtp_inactive_reason`, acceptance rate — and note the routing hazard: MTP
+inflates `observed_decode_tps` with no discriminator, so a partial-MTP fleet
+biases routing toward MTP boxes on a metric the coordinator believes is
+homogeneous.
+
+Paged pool metrics (`pages_pinned`, `cow_events`, `pool_utilization`) are
+greenfield — zero naming collisions.
+
+Beware `backend` as a field key: it already carries **two contradictory
+meanings** — `"engine_v2"` at `EngineV2Config.swift:243` and
+`paged|contiguous` at `EngineV2Bridge+PrefixCache.swift:197`/`:252`. Any
+`group by backend` dashboard mis-buckets. Rename or pin the meaning.
+
+Verify the pipeline flows first — `telemetry_events` has been stale since
+2026-05-28.
+
+### 16.5 Local observability
+
+An operator on a canary box has **no way to confirm the active backend**.
+`StatusCommand.swift:24-51` and `DoctorCommand.swift:118-235` expose neither KV
+backend, nor concurrency, nor pool bytes. (`api/install.sh:74-77` greps the
+binary's string table — that proves paged is *compiled in*, never that it is
+*active*.) Add a `darkbloom doctor` KV-backend/pool check.
+
+### 16.6 The flip
+
+One line:
+
+```swift
+// EngineV2Factory+Production.swift:346
+case .auto: resolvedKind = .contiguous // → .paged
+```
+
+Everything else is preparation. Rollout mechanics that already exist:
+
+- Per-model backend override: `engine_v2_kv_backend_by_model`
+ (`ProviderLoop+EngineV2.swift:603`)
+- Per-slot vetoes: `EngineV2KVBackendPolicy.applySlotVetoes`
+- Fleet kill switch: `DARKBLOOM_CBV2_PAGED_KV=0`
+ (`EngineV2Factory+Production.swift:349-354`) — **but note it is unreachable
+ under today's default**, because the guard is `if resolvedKind == .paged` and
+ `.auto` already resolved to `.contiguous` three lines earlier. It becomes a
+ real net only *after* the flip. Rev 1 presented it as an active safety net
+ today; it is not.
+
+The flip is **not** a one-line diff in practice. In the same commit:
+`EngineV2KVBackendGateTests.swift:125-141` (two `auto == .contiguous`
+assertions plus the file header), `EngineV2BridgeTests.swift:1375-1408`
+(telemetry `reason == "contiguous"`), and
+`EngineV2ProductionWiringTests.swift:687-801` (restructure). These are the
+intended tripwires and they work — the plan must schedule them.
+
+**Order:** gpt-oss first (no vision, single KV group, shorter 1,536-token replay
+bound makes the sharing win easy to measure) → gemma-4 only after WS-4 lands.
+
+---
+
+## 17. Risk register
+
+| Risk | Severity | Mitigation |
+|---|---|---|
+| **In-place write to a shared page** | Silent cross-request corruption | Single choke point (`ensurePage`), three independent assertions, **net-new** slab-canary test (§19: nothing today would fire) |
+| **Residency/plan mismatch** | Silently truncated window for the first W tokens — no crash, mildly wrong output | `residency` as a field on the plan; refuse `.direct` without it; **net-new** adopt-vs-cold greedy parity in CI. Today's protection is refusal (`CBv2InvariantSuiteTests.swift:332`), which WS-4 removes |
+| **Ring residency broken by config drift** | Pinned pages already overwritten | Construction assert **and** per-pin runtime check |
+| **Free-list underflow** | **Process abort under load** | `available = pageCount - pagesReserved - pagesPinned` |
+| **Paged MTP slot reached** | **Process abort** (§11 item 3.4) | Force serial verification before any MTP+paged slot can exist |
+| **B=8 capacity feedback loop** | Provider ejected 60 s–10 min; win cancelled | §8.1b–d: canary abort on budget-clamp / capacity-rate / ejection counters |
+| **B=8 TTFT backlog shed** | 429 `ttft_too_slow` | §8.1a: watch `ttft_429` rate on the canary; `TTFT_HARD_REJECT` is on in prod |
+| **`TTFT_ADMISSION_MODE` flipped to enforce after B=8** | Every 8-batched box shed instantly | Latent: `alpha=50` × occ 8 ≈ 18 s vs a 9 s deadline. Do not change that env var while B=8 is rolling |
+| **Paged prefill activation regression** | Lost the #85 win, 0.51 → 2.04 GB | §7.0.2p is a blocker, not an optimisation |
+| Sub-blocking spans misses `spanChunkMask` | Silent vision corruption | Span parity tests before merge (§10) |
+| Serial-only MTP loses the speedup | Scope +2–3 wk | Measure at G0 |
+| Pool footprint disqualifies fleet | Migration blocked | G1 exit criterion |
+| Multi-model co-residency fails closed | Every mixed box degrades | §15 — currently unscheduled |
+
+---
+
+## 18. Content volume per track
+
+Sizing is content volume, **not** a schedule. Wall clock is §6.7.
+
+| Track | Items | Content | Notes |
+|---|---|---:|---|
+| **T** oracle | harness | M | ships first; extends `CBv2KVSharingParityTests`, does not start over |
+| **E** memory + coordinator | 0.0, 0.0b, 0.1, 0.3, §8 | **L** | **tripled vs Rev 1.** 0.1 is small and gates G0 — land it standalone, first |
+| ~~**A** attention~~ | — | — | **done (#85)** |
+| **F** telemetry + wire | §16 | M | 6 artifacts + a parity test + a heartbeat field; must precede rollout |
+| **P** pool | 0.5, 0.6, 1.2, 1.3, 3.1, 6.4 | **L** | heaviest engine track |
+| **R** row | 1.3, 3.2, 3.3, 4.1 | **L** | strictly sequential internally |
+| **L** layer | 0.2p, 0.5, 1.2, 2.1–2.5 | **L** | 6 items, one file; 0.2p is new and blocking |
+| **X** factory | 0.4, 1.1, 2.6, 6.1–6.3, 6.5 | M | config surface; owns all four concurrency `4`s |
+| **M** MTP seams | 3.4, 3.5 | S | 3.4 is a hard blocker, not hygiene |
+| **D** SSD tier | 4.2 | **L** | separate repo; needs R's `windowSnapshot` shape only |
+| **G** compiled | §14 | M | mostly deletion; measure at long context before deleting |
+| **C** CI + bench | §19, §20 | M | **new**; gates Wave 1 |
+
+**P, R, L are the three heavy tracks and they are the three contended files.**
+That is not a coincidence — it is why §6.4 exists.
+
+Load-balancing note: if a track must be split, split **P** by concern
+(`PagedKVPool` sizing/ring vs refcounts/free-list) rather than **R**, whose
+items genuinely serialize.
+
+---
+
+## 19. Test and CI coverage — **NEW SECTION, Track C**
+
+**CI runs no paged correctness test.** This is the largest process gap in the
+plan: eleven parallel tracks, four of which mutate `PagedKVPool`/
+`PagedLayerCache`, with no automated numerical gate.
+
+```yaml
+# .github/workflows/ci.yml:169-181 — the ONLY engine-submodule test step
+swift test --skip-build --filter CBv2PagedSafetyTests
+swift test --skip-build --filter CBv2PrefixCacheHasherTests
+```
+
+`CBv2PagedSafetyTests` scopes itself, in its own header, to "missing/corrupt
+SwiftPM resources, Metal maxBufferLength violations, and hostile size
+arithmetic" — **zero numerical assertions**.
+
+Compiled by `swift build --build-tests` and then **never executed**:
+`CBv2PagedKernelTests` (fp32 decode parity, bitwise batch-composition
+invariance, 200-step greedy token match), `CBv2PagedBackendTests`,
+`CBv2PagedEligibilityTests`, `CBv2KVSharingParityTests`. Also never run
+anywhere: `EngineV2PagedParityLiveTests`, the real-weights oracle whose header
+says it "gates explicit paged canaries before any future default
+reconsideration" — no `DARKBLOOM_LIVE_MLX_TESTS` in any workflow and no
+checkpoint fetched.
+
+### 19.1 The three silent-corruption classes have zero fireable assertions
+
+Verified at source, one by one:
+
+| Class | Why nothing fires |
+|---|---|
+| **Poison page** | `PagedKVPool.swift:501-509` pads by duplicating a real slot id; the safety argument is a comment. No test writes a canary into a neighbouring page and re-reads it after a short bulk write. |
+| **Ring over-provision** | `CBv2PagedBackendTests.swift:198-201` re-derives its expectation from the same formula, then asserts only `table.count <= ring` — an *under*-provision bound. Shrinking or growing the ring fails nothing. |
+| **Residency/plan mismatch** | `adoptPrefixRoundtrip` is happy-path only; there is no adopted-vs-cold comparison. Today's real protection is *refusal* (`CBv2InvariantSuiteTests.swift:332`), which WS-4 removes. |
+
+### 19.2 e2e is blind to all of it
+
+`e2e/testbed/suite.go:474-487` launches the provider with five env vars, none of
+them CBv2 — no `engine_v2_kv_backend`, no `engine_v2_max_concurrent`, no
+provider.toml `[backend]`. So (a) e2e **cannot** exercise paged today, and (b)
+the moment `.auto` resolves `.paged`, all 14 integration tests silently switch
+backend with no test edit and no signal.
+
+`TestIntegration_ConcurrentRequests` is the only concurrency test: 5 requests,
+and it passes if **one** succeeds (`integration_test.go:559`). Nothing in e2e
+would need updating for B=8 — which is exactly the problem. No e2e test would
+detect a paged numerical regression: the two content-checking tests
+(`_E2EEncryptionCorrectness`, `_StreamingContentValidation`) check envelope and
+stream shape, not token-exactness, so a paged drift produces different-but-
+plausible text and passes.
+
+### 19.3 The mixed-version gate is red
+
+`e2e/mixed_version_test.go:23-26` requires SIP and **fails rather than skips**
+on a runner reporting `SIP status: disabled` — the anti-silent-skip design
+works, and the gate is currently non-functional. The reverse lane
+(`integration.yml:107-125`) runs only 2 of 14 tests and neither asserts token
+content.
+
+Paged-by-default changes heartbeat `max_concurrency` and the
+`engine_v2_kv_backend` telemetry field — **precisely the wire surface this gate
+exists to protect. Repair it before the flip, not after.**
+
+### 19.4 Track C deliverables
+
+1. A CI step that runs `CBv2PagedKernelTests`, `CBv2PagedBackendTests`,
+ `CBv2KVSharingParityTests` and Track T's new differential. Budget note: the
+ `cache-swift` lane is `if: github.event_name == 'push'`, so PRs restore but
+ do not save, and a cold nested build already eats the 35-minute budget.
+2. A `--kv-backend` knob in `e2e/testbed` plus a paged-pinned lane.
+3. Parameterise `CBv2QueryBlockAttentionTests` over ≥2 block widths (today only
+ one width runs per invocation, and it never runs on CI).
+4. Parameterise the churn-storm invariance test (`CBv2InvarianceTests.swift:206-207`,
+ `:249-250`) over B ∈ {4, 8}. It is the engine's strongest batch-composition
+ oracle and it would otherwise keep testing a configuration the fleet no
+ longer serves.
+5. Repair the mixed-version gate.
+
+Tests that **must change**, enumerated so no track is surprised:
+
+| Test | Why | Owner |
+|---|---|---|
+| `EngineV2KVBackendGateTests.swift:125-141` | two `auto == .contiguous` + header | flip |
+| `EngineV2BridgeTests.swift:1375-1408` | telemetry `reason == "contiguous"` | F |
+| `EngineV2BridgeTests.swift:1495,1528` | `engineV2MaxConcurrent == 4` | X |
+| `EngineV2ProductionWiringTests.swift:687-801` | mixed-fleet contrast collapses | X + E |
+| `EngineV2CoResidencyLiveTests.swift:66-79` | documents paged-by-default failure | §15 |
+| `PagedKVPhysicalCapacityPolicyTests.machineSizingMatrix` | **breaks arithmetically** at B=8 | E |
+| `PrefixCachePolicyTests.swift:60-98,119-155` | WS-4 makes paged hybrids reusable | R + D |
+| `servability_test.go`, `servability_provider_fit_test.go` | hardcoded goldens (§7.0.3) | E |
+| `concurrency_cap_test.go`, `solo_tps_test.go` | any cap/floor/`k` change | E |
+
+Explicitly clean, so nobody chases them: no Go test asserts a KV backend;
+console-ui already uses `max_concurrency: 8` in fixtures and renders it
+generically (`ConcurrencyDots.tsx`, `MAX_DOTS = 16`); `ProtocolTests.swift`
+round-trips whatever integer it is given; `release-swift.yml` correctly verifies
+the paged artifacts ship.
+
+---
+
+## 20. Benchmark harness — **NEW SECTION, Track C**
+
+Two disjoint stacks, split by repo, with no shared driver — and the automated
+one **cannot measure paged**.
+
+### 20.1 What exists
+
+**Provider stack** (automated, statistically careful, **contiguous-only**):
+
+```bash
+make benchmark-gemma-contbatch \
+ GEMMA_BENCHMARK_ARGS="--max-batch 8 --iterations 5 --decode-prompt-tokens 512 --label g0-b8"
+```
+
+Builds a release binary + metallib, runs the decode curve, medians it, validates
+matrix completeness (fails closed), and pins git commit + binary sha + env +
+thermal. `environment.py:34` already captures the `DARKBLOOM_CBV2_` prefix, so
+both `DARKBLOOM_CBV2_ATTN_QUERY_BLOCK` and `DARKBLOOM_CBV2_PAGED_KV` land in
+every report unmodified.
+
+**Submodule stack** (measures paged, zero automation):
+
+```bash
+cd libs/mlx-swift-lm && swift run -c release BenchCBv2 \
+ --model --mode all \
+ --engines v2,v2-compiled,v2-paged --batches 1,2,4,8 --steps 128 --kv-gb 16 \
+ --out benchmarks/reports/.md
+```
+
+This produced the 07-09 reports. It already sweeps three backends × four batch
+sizes in one process on one loaded model and emits `gpuActive`/`gpuPeak` per
+cell with a per-cell peak reset (`:336`, `:978-982`).
+
+### 20.2 What is missing
+
+| # | Gap | Site |
+|---|---|---|
+| C1 | **`darkbloom benchmark` can never construct a paged engine.** `ThroughputSweep.swift:288-292` calls `makeProductionEngine` with no `kvBackend:` → `.auto` → contiguous. There is no `--kv-backend` flag, and `DARKBLOOM_CBV2_PAGED_KV` is **negative-polarity only** — it can force paged off, never on. | Track X owns `EngineV2Factory+Production.swift`; thread an option through |
+| C2 | **The sweep bypasses the production ceiling.** Same call passes `maxConcurrentRequests: max(batchSize, 1)`, so a green B=8 sweep does **not** demonstrate that `productionMaxConcurrentRequests` was raised. | G0a must be measured on a real canary, not here |
+| C3 | **No ITL, no p90.** `summary.py:59-84` emits only elapsed / per-request TPS / aggregate TPS. G0's ITL criterion has no producer in the provider harness; only `BenchCBv2` computes `itlP50Ms`. | Track C |
+| C4 | **No GPU memory anywhere in the provider harness.** `ThroughputSweepReport.swift:16-26` has only static hardware facts. Bug A's over-admission at B=8 will not be caught by that run. | Track C |
+| C5 | **The context axis does not exist.** `--decode-prompt-tokens` is a scalar; `promptMix(batch:)` is hardcoded and caps at 1,500 tokens; the bench's paged pool hardcodes `nominalMaxSequenceLength: 4096`. G1's ctx {10k, 100k} needs two source edits. | Track C — **the binding gap for G1** |
+| C6 | **Arrival invariance is pinned at 4 rows.** `EXPECTED_ARRIVAL_PATTERNS` (4 entries × 4 delays) and `ArrivalInvarianceBenchmark.swift:108-113`; `:189` derives concurrency *from* the pattern width. Raising B leaves arrival invariance unmeasured at the new operating point. | Track C |
+| C7 | **`BenchCBv2` bypasses the production paged construction.** `BenchCBv2RealModel.swift:130-137` builds `PagedKVBackend` directly, skipping `PagedKernelPreflight.run`, `PagedKVPhysicalCapacityPolicy.decide` and `materializeSlabs()`. **G1 as measured today validates a different paged construction than the one that ships.** | Track C + Track X |
+| C8 | `--max-batch 8` runs B=1..8 dense, not `{1,2,4,8}` (`BenchmarkCommand+Sweep.swift:28`). Doubles G0 wall time for no information. | Track C, cheap |
+| C9 | `BenchCBv2` records no invocation, git commit, or submodule sha in its report header. | Track C |
+| C10 | **No benchmark sweeps `DARKBLOOM_CBV2_ATTN_QUERY_BLOCK`.** The 0.51 GB claim is unmeasured end to end — `BenchCBv2`'s longest prompt is 1,500 tokens, well under the L where q=128 pays. | Track C |
+
+**Net:** G0 is ~90% automated; G1's engine and batch axes are free but its
+context axis and its construction fidelity are not. Rev 1's "3 contexts × 4
+batch sizes × 2 models is machine-hours" overstated the batch/engine cost and
+understated the context problem.
+
+---
+
+## 21. What changed since the "no" verdict
+
+`2026-07-25-paged-attention-for-prefill-decision.md` recommended against paged.
+Its conclusion was right for the question it asked ("should we migrate *instead
+of* optimizing prefill?"), but three of its supporting arguments do not hold:
+
+| Claim | Reality |
+|---|---|
+| "Paged adds a materialized mask the contiguous path avoids via symbolic `.causal`" | `.causal` is only symbolic if MLX takes the fused path, and at head_dim 256/512 it does not. The fallback builds an equivalent mask itself (`libs/mlx/mlx/fast.cpp:738-747`). **No extra mask for gemma-4.** |
+| "Rectangular packed prefill — **Disabled**" | Not implemented, not disabled. A `b == 1` precondition; contiguous handles it with a per-row loop that has no storage dependency. **3 days.** |
+| "Cannot serve vision requests at all" | Not implemented. Paged's always-materialized absolute-coordinate mask composes with the span overlay *more* directly than contiguous's symbolic mode. |
+
+What survives from that document, and remains true: **there is no paged prefill
+kernel** (`pagedattention.metal` defines only `paged_attention_part_impl`,
+`paged_attention_merge_impl`, and a bulk `paged_kv_write_impl` scatter), so
+paged cannot improve the prefill phase; and paged's decode kernel addresses KV
+bandwidth, which is only 8.6% of decode bytes at p50 context.
+
+**And one of its arguments got stronger after #85.** That document warned that
+adopting paged would cost the prefill work then in flight. Sub-blocking has
+since shipped, and paged does not inherit it (§7.0.2p) — so the migration now
+regresses prefill activation memory 0.51 → 2.04 GB unless 0.2p lands first.
+
+The reframe that justifies the migration is unchanged: **paged is a batching
+enabler and an architecture hedge, not a prefill or single-stream decode
+optimization.** But note §3.3 — the batching enablement is gated on a
+coordinator change, not on paging.
+
+---
+
+## 22. Correction log — Rev 1 → Rev 2
+
+Every item below was verified against `e65b5bbc1` / `abd1985`.
+
+| # | Rev 1 claim | Correction |
+|---|---|---|
+| 1 | Track A (sub-blocking) is Wave-0 work | **Shipped** as #85 (`abd1985`). Track deleted. |
+| 2 | "No code change is required to test the batching hypothesis" | **False.** The coordinator quality cap clamps gemma-4 to 2 at both B=4 and B=8 (§3.3). G0 split into G0a/G0b. |
+| 3 | Track E owns `registry/scheduler.go` | Wrong file for every item. Nine coordinator files, four of them capacity-feedback loops (§8). |
+| 4 | Thread the activation reserve through `freeMemoryAdmits` (`scheduler.go:1301`) | That function is reserve-blind. The mirror is `registry/servability.go:50`; 9-site parallel edit (§7.0.3). |
+| 5 | Poison page is "a live cross-request leak today" | Fail-open, but no reachable trigger — invariant at `PagedSequenceKV.swift:256-258`. A worse latent variant exists (`table_len` 97 > row width 8). |
+| 6 | WS-3.4 unreachable "because the envelope defaults to 0" | **False in production** — `MTPAutomaticVerificationPolicy` returns 8 on M4. Cited file path also does not exist. 3.4 is a hard blocker. |
+| 7 | Paged "receives the entire remaining KV grant" | Capped five ways (`PagedKVPhysicalCapacityPolicy.swift:104-108`). Real contrast is eager materialisation vs lazily-enforced ceiling. |
+| 8 | Bug A: allocation is "unconditional" | Lazy on first write, full-size. And `fixedWindowBytesShortfall` already exists — the fix is a call site. |
+| 9 | MTP staging blocked by ring aliasing | Blocked by an unconditional gate (`PagedSequenceKV.swift:115`) whose justification comment is false. `begin/commitSpeculativeWrite` already exist. |
+| 10 | `pageDemand` charges the full ring | `min(ceil(maxLength/pageSize), ringPageCount)`, capped by worst-case `maxLength`. Conclusion stands. |
+| 11 | `attendSerialQueries` "generalizes directly" | Loop bounds do; the mask does not (`L:1, window:nil` → `.none`). Moot — #85 shipped. |
+| 12 | `DARKBLOOM_CBV2_PAGED_KV` is an active fleet kill switch | **Unreachable** under today's default — `.auto` resolves contiguous before the switch is consulted. |
+| 13 | gemma donation floor 27,136 | **Correct** (25,600 + 1,536). The findings doc's 26,624 is the wrong one. Strict `>`, so the true floor is 27,137. |
+| 14 | "2.3x memory gap" | B=1 gpt-oss `gpuPeak`. ~2.13x at B=4/8; **1.75x** on gemma at B=8. `gpuActive` identical across engines. |
+| 15 | Paged "roughly par at B=4" | Slightly **faster**: 38.5 vs 37.3 (gpt-oss), 39.0 vs 38.0 (gemma). Conservative against itself. |
+| 16 | `forward.build` 40.9% → 12.1% | Reproduces exactly, but from a report self-flagged **HOST CONTENDED**. |
+| 17 | Compiled decode A/B at B=1/2/4 | Add B=8: compiled **falls back entirely** (`batch_8_exceeds_ladder`). Strengthens §14. |
+| 18 | `uniformAttentionSoftcap` fix re-enables compiled for paged | Insufficient — `EngineV2.swift:225` has an independent `backendVeto`. |
+| 19 | Track T builds a differential harness from scratch | `CBv2KVSharingParityTests.swift:76-171` already has the two-arm structure; `EngineV2PagedParityLiveTests` is a real-weights oracle. Extend, don't restart. |
+| 20 | §6.6 "benchmarks are machine-hours" | B and engine axes are free; the **context axis** and construction fidelity are the real gaps (§20). |
+| 21 | WS-7 is a four-file telemetry change | Six artifacts, and `protocol/telemetry.go` is a **non-edit**. Plus a heartbeat field on a different five-file path. |
+| 22 | — (absent) | **New:** the wire cannot distinguish paged from contiguous. Rollout blocker, Gate G5 (§16.1). |
+| 23 | — (absent) | **New:** CI runs no paged correctness test; three silent-corruption classes have zero fireable assertions (§19). |
+| 24 | — (absent) | **New:** paged prefill gets none of #85's memory win and adds a gathered copy (§7.0.2p). |
+| 25 | — (absent) | **New:** multi-model co-residency under paged is known-broken and unscheduled (§15). |
+| 26 | — (absent) | **New:** `effectiveTPSLoadFactor = 0.27` mispredicts CBv2 B=8 by ~16x and drives four systems (§3.4). |
diff --git a/docs/reports/2026-07-25-prefill-and-fleet-performance-findings.md b/docs/reports/2026-07-25-prefill-and-fleet-performance-findings.md
new file mode 100644
index 0000000000..006214874d
--- /dev/null
+++ b/docs/reports/2026-07-25-prefill-and-fleet-performance-findings.md
@@ -0,0 +1,461 @@
+# Prefill and Fleet Performance — Findings, 2026-07-25
+
+Working notes from the session that shipped provider **v0.7.15** (CBv2 prefill
+stack) and then measured the production system to decide what to do next.
+
+Everything here is either measured or read out of the source. Where a number is
+inferred rather than observed, it says so. Several widely-assumed things turned
+out to be wrong; those are called out explicitly, because re-deriving them is
+expensive.
+
+---
+
+## 1. What shipped in v0.7.15
+
+Merged: `d-inference` #573, #574, #576, #577, #578; `mlx-swift-lm` #84
+(`b177c35`). Tagged `v0.7.15`, registered with the coordinator at 07:12 UTC.
+
+| Change | Mechanism |
+|---|---|
+| Prompt-output narrowing | Prompt chunks no longer build `[B, L, 262144]` logits for positions the engine never reads. Intermediate chunks project nothing; the frontier projects one row. |
+| Final-layer tail pruning + last-query | The last decoder layer keeps full attention and every K/V write but evaluates only the frontier row. |
+| Rectangular packed prefill | Equal-length text chunks run as ONE layer-major `[B, L]` forward instead of B separate ones. |
+| Mixed-step prefill quota | `DARKBLOOM_CBV2_MIXED_PREFILL_CAP`, opt-in, default OFF. |
+
+**Kill switches** (no rebuild): `DARKBLOOM_GEMMA4_PREFILL_TAIL_ROWS=0`,
+`DARKBLOOM_GEMMA4_PREFILL_LAST_QUERY=0`, `DARKBLOOM_CBV2_MIXED_PREFILL_CAP=`.
+Prompt-output narrowing and packed prefill have **no env gate** — backing those
+out means reverting the submodule bump.
+
+### Measured impact (production, not benchmark)
+
+Regressing `TTFT = intercept + slope x prompt_tokens` on gemma-4 routes
+separates fixed cost from per-token prefill cost and controls for prompt size:
+
+| Version | n | Fixed cost | Per-token | Implied | r2 |
+|---|---:|---:|---:|---:|---:|
+| 0.7.15 | 881 | **1,626 ms** | **0.9075 ms/tok** | 1,102 tok/s | 0.815 |
+| 0.7.14 | 12,513 | 2,120 ms | 0.9464 ms/tok | 1,057 tok/s | 0.800 |
+
+Fixed cost **-23%**, per-token **-4.1%**. Worked through real prompt sizes:
+128 tok **-22%**, 979 (p50) **-17%**, 10,000 (p90) **-8%**.
+
+This corroborates the synthetic benchmark (-15/-20/-19%) on independent traffic.
+Residual confound: 0.7.15 machines ran slightly lighter at measurement time, so
+some of the intercept gain may be reduced co-tenancy rather than code.
+
+---
+
+## 2. Instrumentation traps — read this before querying
+
+These cost real time this session. Every one of them produced a confident wrong
+conclusion first.
+
+| Field / table | Reality |
+|---|---|
+| `providers.id` | **Churns per registration.** 5,381 rows in 24h = 348 distinct machines; one serial had 685 rows. **Always dedupe by `serial_number`** (`distinct on (serial_number) ... order by serial_number, last_seen desc`). |
+| `actual_ttft_ms` | `FirstContentAt - DispatchedAt` (`coordinator/api/route_outcome.go:428`). **Provider-side only** — already excludes coordinator overhead and queue wait. Do not "subtract queueing" from it. |
+| `queue_ms`, `pending_ms`, `backlog_ms`, `this_req_ms`, `cost_ms`, `health_ms` | **Router scoring penalties, not milliseconds.** Summed into a routing decision (`registry/scheduler_test.go:67`). Values like 2,452,501 are scores. |
+| `queue_wait_ms` | Real, but populated only for the ~10% of requests that actually queued. |
+| `dispatch_to_first_chunk_ms` | Byte-identical to `dispatch_ms`; it is DispatchedAt -> first *byte* (role preamble), not first content. **Not a prefill metric.** |
+| `cache_affinity_key` | **Dead.** A DB trigger `clear_legacy_cache_affinity_key` blanks it on every INSERT/UPDATE (`coordinator/store/postgres.go:100-119`). It is always non-NULL but always the same empty value. |
+| `telemetry_events` | **Stale since 2026-05-28.** 148k rows, none newer. |
+| `inference_routes` | Huge. **Always bound `created_at > now() - interval '...'`** or you get a full scan that hangs. |
+| `providers.last_seen` | Mutated in place — historical liveness cannot be reconstructed from it. Use `provider_sessions` connect/disconnect intervals instead. |
+
+**The DB in `coordinator/.env` is the PRODUCTION PRIMARY** (`pg_is_in_recovery()`
+= false), not a replica. Read-only recipe, needed in every shell call because
+env does not persist:
+
+```bash
+export DBURL=$(grep -E '^EIGENINFERENCE_DATABASE_URL=' coordinator/.env | cut -d= -f2- | tr -d '"')
+export PGOPTIONS='-c default_transaction_read_only=on -c statement_timeout=30000'
+psql "$DBURL" -qAc "SELECT ..."
+```
+
+`default_transaction_read_only=on` is a per-connection libqp startup option; it
+makes the **server** reject writes and cannot leak into the coordinator's own
+sessions.
+
+**Repo trap:** the main checkout `/Users/gaj/Documents/Builds/d-inference` has a
+**stale submodule** at `libs/mlx-swift-lm` = `dc2cd55`. Master expects
+`b177c35`. Analyze engine code in a worktree synced to master, or you will
+conclude that shipped features do not exist.
+
+---
+
+## 3. Production shape (2026-07-25, ~07:00-07:30 UTC)
+
+- **348 machines** total (deduped by serial); ~150 serving at any moment.
+- TTFT: **p50 3,042 ms, p90 12,439 ms, p99 42,097 ms**.
+- Prompt tokens: **p50 979, p90 9,993, p95 16,919, p999 74,473, max 124,754**.
+- Two models: `gpt-oss-20b` (~58-61% of traffic) and `gemma-4-26b-qat-4bit`.
+- Fleet-wide 503 rate ~1.3%.
+- Regression across all traffic: **TTFT = 1,663 ms + 0.9914 ms/prompt_token**,
+ r2 = 0.80. 97% of the prompt-proportional term is provider-side prefill.
+
+---
+
+## 4. Finding: half the fleet is idle — fleet partitioning, not churn
+
+**~50% of live machines serve nothing while gemma-4 requests queue 22.9%.**
+
+Not upgrade churn. Using `provider_sessions` (not `last_seen`), the idle rate is
+a standing condition: **52.9% today, 52.9% yesterday, 55.4% two days ago, 64.1%
+a week ago.** v0.7.15 machines were *less* idle (40.9%) than 0.7.14 (50.6%).
+
+### Root cause
+
+`EIGENINFERENCE_DEDICATED_MODELS` defaults to `"gemma-4"`
+(`registry/dedicated_models.go:10`). `providerExcludedByDedicatedRuleLocked`
+(`:96`) says a gemma-4 request may only route to a box whose **entire advertised
+catalog** is gemma-4. It is a catalog-composition exclusion, not a capacity test.
+
+| Partition | Machines | Hardware-trusted, >=36 GB |
+|---|---:|---:|
+| A — gemma-only (eligible) | 67 | 46 |
+| B — mixed, **blocked for gemma** | 94 | **71** |
+| C — no gemma | 131 | 39 |
+
+| Model | Routes/hr | % queued | avg candidates |
+|---|---:|---:|---:|
+| gemma-4-26b-qat-4bit | 15,327 | **22.9%** | **4.3** |
+| gpt-oss-20b | 21,416 | **0.0%** | 41.7 |
+
+42% of demand is confined to ~23% of the fleet, while the gpt-oss partition has
+literally zero queueing. **71 hardware-trusted >=36 GB machines with gemma-4
+already on disk are barred purely because gpt-oss is also installed.**
+
+Dominant shed is `ttft_too_slow`, 1,798/hr, `could_have_served=true`, average
+best TTFT **78 seconds**.
+
+### Fixes, cheapest first
+
+1. **No code change** — remove `gpt-oss-20b` from disk on some of the 94 mixed
+ boxes; they become dedicated gemma boxes immediately. gpt-oss has 0% queueing
+ and can absorb it.
+2. **Make the rule demand-aware** — allow mixed boxes when the dedicated pool is
+ shedding. The memory-isolation guarantee it exists to provide is *already*
+ enforced independently by `freeMemoryAdmits` (`registry/scheduler.go:1301`)
+ and the provider's `UnifiedMemoryCap`. The catalog exclusion is redundant.
+3. **Demote to a routing cost penalty** so dedicated boxes win when available but
+ mixed boxes serve rather than 429.
+
+### Secondary idle causes
+
+- **50 idle at `trust_level='self_signed'`** (96% idle). `registry/persistence.go:75`
+ never restores trust above self-signed on reconnect, so a restart demotes a box
+ until MDA re-attestation. ~35 self-promote; **~17 genuinely stuck**, 6 for >24h.
+- **24 idle at <=24 GB** with a **0% success rate** (0/312 over 6h, 169 provider
+ 503s). `freeMemoryAdmits` over-admits that tier; `capacity_cooldown` only
+ catches it after burning user-visible requests. **This is a real defect.**
+
+---
+
+## 5. Finding: prefix caching is OFF, and structurally cannot help gemma-4
+
+Live `GET /v1/cache/status`: `routing_mode: "off"`, `ssd_lookups: 0`,
+`ssd_hits: 0`, `ssd_donations: 0`. `exact_cache_plan_total{outcome="off"}`
+= 938,241. **Zero lookups have ever been attempted.**
+
+Set by `EIGENINFERENCE_CACHE_ROUTING_MODE=off` (`deploy/environments/prod.env:58`).
+**This was a deliberate operator decision** after cache-hit problems in an
+earlier enablement — not an oversight.
+
+Even flipping it back would barely register, because four more gates multiply:
+
+| Gate | Coverage |
+|---|---|
+| Sampling | 10% live (`prod.env` says 1%) |
+| Protocol v2 providers | 34 of 255 = **13%** |
+| Healthy cache models | 35 ready vs **105 `cache_init_failed`** = 25% |
+| Donations that ever wrote a block | **0** (`no_complete_block: 1579`) |
+
+~**0.3% effective coverage**, on a write path that has never persisted a block.
+Dominant init failure is `promptContractID == nil`
+(`EngineV2SlotFactory.swift:337-347`) with only 3 prompt contracts loaded.
+
+### The structural blocker for gemma-4
+
+`SSDPrefixCache.swift:783-788` sets `donationFloor = adoptionBoundTokens +
+minEffectiveTokens`:
+
+| Model | Floor | Requests that can ever donate |
+|---|---:|---:|
+| gpt-oss-20b | 2,560 | 38.4% |
+| gemma-4-26b-qat-4bit | **26,624** | **2.3%** |
+
+The 25,600-token `frozenFullReplay` bound (`PrefixCachePolicy.swift:151-154`)
+exceeds typical gemma prompts by ~18x. **39% of traffic is excluded by policy,
+permanently**, regardless of hit rate.
+
+Ceiling with a *perfect* cache: gpt-oss p90 **-38%**; gemma-4 **~0%**; all
+traffic p50 -12%, p90 -24%.
+
+**Counters live only in coordinator RAM and reset on restart** — which is why
+nobody had measured this. Persist them regardless of what else is decided.
+
+---
+
+## 6. Finding: head-of-line blocking is NOT the tail driver
+
+Hypothesis was that 124k-token prompts block everything behind them. **The data
+says giant prompts cause ~0% of the p90/p99 tail.** Blocking costs ~640 ms of
+p50 (21%) and essentially nothing at the tail.
+
+Counterfactual (remove all co-tenancy): p50 3,024 -> 2,385 (**-21%**);
+p90 12,171 -> 12,287 (**0%**); p99 40,089 -> 40,242 (**0%**).
+
+**Why:** `4 rows x 512 tokens = 2,048` = exactly `maxBatchedTokensPerStep`. Every
+running prefill row gets its full 512-token chunk *every step*
+(`SchedulerV2.swift:287`, `:374-377`). A 124k prompt occupies 244 steps but never
+denies the other three rows their chunk. A giant neighbor is a **longer-lived**
+blocker, not a harder one. Confirmed: victim TTFT scales with the *count* of
+co-prefilling rows and is flat in their size.
+
+The tail is **own prompt size**: above p99, 74.8% of routes are >20k prompts
+(2.3% of traffic). A sub-2k prompt essentially never reaches global p90
+(19 of 11,228).
+
+**Therefore SJF / size-aware admission is low value** — its entire ceiling is the
+639 ms of p50, and it adds starvation risk for the >20k class.
+
+### What IS worth doing from that analysis
+
+**Hardware-aware routing.** Prefill throughput spans **2.9x** across the fleet
+for >=8k prompts (M1 Ultra ~440 -> M5 Pro ~1,260 tok/s), and **39.2% of
+big-prompt traffic lands on sub-800 tok/s chips.** Routing big prompts to fast
+hardware: **p90 -16%, p99 -34%.** `hardware_chip`/tier are already in the
+registry and on every route row.
+
+Also: coordinator overhead is 23 ms at p50 but **6,234 ms at p99** (15% of
+end-to-end). Bug-shaped, worth separate investigation.
+
+---
+
+## 7. Roofline — Gemma 4 26B-A4B QAT 4-bit on M4 Max (40c, 128 GB)
+
+Hardware verified: 546 GB/s memory bandwidth, ~16.2 TFLOPS FP32 FMA peak, **no
+matrix accelerator**, NAX unavailable (needs GPU gen >=17; M4 is gen 16).
+
+Model: 30 layers = 25 sliding (window 1024, head_dim 256, 8 kv heads) + 5 full
+(head_dim 512, 2 kv heads, `attention_k_eq_v` so no `v_proj`). Dense MLP **and**
+MoE run in *parallel* branches every layer. 128 experts, top-8, 4-bit.
+
+### Per-token FLOP budget (prefill, P=512)
+
+| Component | GFLOP/tok | Share |
+|---|---:|---:|
+| MoE experts | 2.8547 | **45.2%** |
+| Attention projections | 2.2204 | 35.2% |
+| Dense MLP | 1.0705 | 17.0% |
+| Attention scores | 0.1471 | 2.3% |
+| Router | 0.0216 | 0.3% |
+| LM head (once per prompt) | 1.4764 | — |
+
+### Prefill
+
+Runs at **~9.6 TFLOPS useful against ~13 TFLOPS achievable = 74% efficiency**.
+Floor is `6.32 GFLOP/tok / 13 TFLOPS` = 0.486 ms/tok ~ **2,060 tok/s**; we are at
+~1,350-1,400. **Total headroom 1.47x; ~1.30x realistically reachable.**
+
+Time split at P=512: MoE 41.8%, attn projections 21.5%, **fixed per-request
+overhead 14.3% (~54-64 ms)**, dense MLP 10.4%, elementwise 6.1%, attn matmuls 4.1%.
+
+### Decode
+
+Bandwidth-bound: **2,444 MB read per token**, of which experts 32.8%, dense MLP
+23.3%, attention weights 25.5%, LM head 17.0%, KV <1%.
+Roof at 546 GB/s = 223 tok/s; measured B=1 is 106 tok/s = **259 GB/s effective,
+47% of pin rate**.
+
+Batch scaling is fully explained: **66% of decode bytes are batch-invariant**,
+and expert draws are **91% distinct at B=4** (`E[unique] = 128(1-(1-8/128)^B)`).
+Amdahl predicts 2.11x at B=4; measured 1.92x. **B=4 will never approach 4x.**
+
+Only large decode lever is **MTP / speculative decoding** (infrastructure already
+exists): 1.24-1.79x depending on depth and acceptance.
+
+### CORRECTION: the "MoE runs at 3 TFLOPS" claim was wrong
+
+Widely repeated, **arithmetically impossible**: at 3.0 TFLOPS the MoE stage alone
+would take 487 ms, but the entire measured 512-token TTFT is 380 ms. Experts
+actually run at **~9.2 TFLOPS useful** (two independent derivations agree within
+7%). The whole remaining MoE win is ~1.11x, not 4x.
+
+The gap is **tile padding**, exactly: `gather_qmm_rhs` hardcodes `bm=16,bn=32`
+(`quantized.cpp:1279`), and the kernel runs one full `16xBNxK` matmul per
+distinct expert inside each 16-row tile (`kernels/quantized.h:2334-2345`).
+
+**Closed form: `inflation(R) = 1 + 16*E/R` where `R = tokens x topK`, `E = 128`
+=> `inflation(C) = 1 + 256/C`.** Predicts 1.500 at C=512 (measured 1.465) and
+1.125 at C=2048 (measured 1.116).
+
+### CORRECTION: packing and chunk growth are the same thing to MoE
+
+`Gemma4Experts.callAsFunction` (`Gemma4Text.swift:871-874`) flattens **B and S
+together**. A `[4,512]` packed chunk and a `[1,2048]` chunk are the *same* call to
+`SwitchGLU`. Both sort (`doSort = indices.size >= 64`) and both reach
+`gather_qmm_rhs` (needs `B/E >= 4`, i.e. >=64 tokens). **Packing did not change
+which kernel runs — it changed `R`.**
+
+Consequence: packing captured the MoE win **only for concurrent bursts**. Most
+production chunks run `B=1` and never got it. Raising `C` is the cheap way to
+give single requests the same regime.
+
+### THE major structural finding: we never use fused attention
+
+```
+sdpa_full_supported_head_dim = {64, 80, 128} <- prefill
+sdpa_vector_supported_head_dim = {64, 96, 128, 256} <- decode
+```
+(`scaled_dot_product_attention.cpp:621-626`)
+
+Gemma 4 uses head_dim **256** (sliding) and **512** (full). So **all 30 layers
+fall back to the composed path in prefill**: `matmul -> mask -> softmax ->
+matmul`, materializing a `[C, kL]` score tensor with **no causal block skipping**.
+
+Not a bug and not a regression — MLX simply never implemented a `bd=256` full
+kernel. **GPT-OSS uses head_dim 64 and is entirely unaffected.** Gemma decode is
+mostly fine too: the 25 sliding layers hit the fused *vector* kernel; only the 5
+full layers (512) fall back, and at `qL=1` their scores are trivial.
+
+Sliding executed/useful ratio is `(1023+C)/1024`: **1.499x at C=512, 2.0x at
+C=1024, 2.67x at C=2048.**
+
+---
+
+## 8. Memory: the score tensor, and why the reserve is the real limit
+
+Score tensor is `[batch, heads, C, kL]` — a **transient activation, not KV**.
+
+| Config | One full-attn layer @124k ctx |
+|---|---:|
+| C=512 (today) | **2.04 GB** |
+| C=2048 | **8.18 GB** |
+| Any C, 128-row sub-blocking | **0.51 GB** |
+
+For comparison, the **entire KV cache at 124k is only 2.76 GB** — `attention_k_eq_v`
+means full layers skip `v_proj`, they have 2 KV heads, and the sliding window caps
+25 of 30 layers at 0.21 GB total.
+
+**Why we would OOM despite having a memory model:** `UnifiedMemoryCap` reserves a
+**flat constant** for activations —
+`defaultActivationReserveBytes = 3 GiB`
+(`provider-swift/Sources/ProviderCore/Inference/UnifiedMemoryCap.swift:45`). It
+does not scale with chunk size, context length, or concurrency. 2.04 GB fits
+inside it; 8.18 GB does not, and nothing in admission would notice. It is also a
+**load-time** gate, not per-request, so it cannot react to a 124k prompt arriving.
+On unified memory the failure mode is swap/pressure, not a clean rejection.
+
+**Sub-blocking makes the score tensor O(1) in C, which keeps the flat reserve
+true.** That is why it is a hard prerequisite for chunk growth — the alternative
+is re-deriving the reserve as a function of `C x max_context x heads` and
+threading it through the load gate, `GlobalKVCacheBudget`, and the coordinator's
+`freeMemoryAdmits` mirror.
+
+**KV quantization is the wrong tool** (KV is 2.76 GB, the problem is 8-24 GB of
+activations; it also costs quality and disables prefix caching).
+**Paged attention is the wrong tool** (it manages KV allocation, not score
+materialization) — and worse, our paged backend reports
+`supportsPackedPrefill = false`, so enabling it would **disable the packed
+prefill we just shipped**.
+
+---
+
+## 9. Engine plan — sequence and expected gains
+
+Speedup vs shipped v0.7.15, on total prefill wall clock:
+
+| Configuration | P=979 (p50) | P=10,000 (p90) | Weighted |
+|---|---:|---:|---:|
+| Chunk 512->2048 **alone** | 1.04x | **0.95x (REGRESSION)** | — |
+| Query sub-blocking **alone** | 1.03x | 1.05x | 1.046x |
+| **Both together** | 1.12x | **1.17x** | **1.158x** |
+| + kill fixed per-request cost | 1.24x | 1.18x | 1.173x |
+| + adaptive expert tail bodies | 1.30x | 1.20x | 1.196x |
+| + fused SDPA hd256 (everything) | 1.35x | 1.28x | 1.266x |
+
+**Chunk growth alone regresses p90** because sliding executed KV goes as `W-1+C`.
+Sub-blocking alone does not monetize the MoE side. They are worth 1.16x together
+and little apart. **1.196x of the available 1.27x needs no `libs/mlx` changes.**
+
+### Recommended sequence
+
+1. **Profile the ~54-64 ms fixed cost** (1 day). `CBV2_STEP_PROFILE=1` +
+ `CBv2StepProfiler.summaryTable()` already exist. Suspects: first-chunk Metal
+ pipeline specialization for unwarmed `align_M/N/K` variants, host-side setup,
+ first-token readback sync.
+2. **Query sub-blocking, q=128** (2-3 days) in `AttentionV1.swift` —
+ `updateAndAttendRow:209-227`, `borrowAndAttendRow:342-363`, generalizing
+ `attendSerialQueries:386-408`. Do **both** sliding and full layers (full layers
+ are the memory case). `maskMode` needs no change. Last-ulp numerics.
+3. **Chunk growth** (2-3 days): `prefillChunkSize` 512 -> 2048,
+ `mixedStepPrefillTokenCap = 512`, `maxBatchedTokensPerStep` 2048 -> 4096.
+ Note `EngineV2Factory+Production.swift:415` ties the paged ring's
+ `maxPrefillChunk` to the same field — lockstep by construction.
+4. **Fixed-cost fix** from step 1.
+5. **RE-MEASURE, then** adaptive expert tail bodies `BM 32/16/8` in `libs/mlx`.
+ Value drops from 1.064x to a marginal ~1.02x once chunk growth lands.
+
+**Do NOT port `tmp/patches/w3-r1-expert-qmm-nested-mlx.patch` as-is.** Its
+descriptor kernel opens with `if (gid != 0) return;` — a single GPU thread
+serially binary-searching 128 expert segments. Its only real benefit came from
+the `<=16-row` tail body. It also changes `qmm_t_impl`'s `M` from
+`const constant int&` to `const int`, which demotes the value out of constant
+address space for **every** quantized kernel and costs ~1% decode.
+
+**Do NOT do fused SDPA (hd 256) now:** marginal 1.06x for 2-4 weeks of Metal work
+at the 32 KB threadgroup-memory boundary, and it does not touch the `head_dim 512`
+full layers that dominate at p90.
+
+### Chunk growth should not be uniform across the fleet
+
+`prefillChunkSize` is a per-engine config (default 512, never overridden in
+production — `EngineV2Factory+Production.swift:356`), and `EngineV2Config.swift`
+has **zero hardware awareness**. The MoE benefit is machine-independent, but a
+2048-token chunk takes ~1.6 s on an M5 Pro and **~4.7 s on an M1 Ultra**, and
+co-running decode waits out the whole step. Better design: bound step *time*, not
+step *tokens*, using the existing per-provider prefill EWMA
+(`observed_prefill_tps` in `EngineV2Bridge`):
+`chunk = clamp(target_step_ms x measured_tokens_per_ms, 512, 4096)`.
+
+---
+
+## 10. Priority list
+
+| # | Lever | Value | Type |
+|---|---|---|---|
+| **1** | Unblock the gemma pool — 71 trusted >=36 GB machines barred by the dedicated-catalog rule | 22.9% queueing -> ~0; kills 78 s shed TTFTs | **Config** |
+| **2** | Hardware-route big prompts — 2.9x fleet spread, 39% land on slow chips | p90 -16%, p99 -34% | Coordinator |
+| **3** | Fix gemma's 26,624-token cache floor, then `cache_init_failed` + donations | unlocks 39% of traffic; gpt-oss p90 -38% | Engine + config |
+| **4** | Engine: sub-blocking -> chunk growth -> fixed cost -> tail bodies | ~1.30x ceiling | Kernel/Swift |
+| 5 | Coordinator p99 overhead (23 ms p50 vs 6,234 ms p99) | 15% of e2e at p99 | Bug-shaped |
+| 6 | 24 GB boxes admitted for gpt-oss fail 100% (0/312) | correctness | Bug |
+| 7 | MTP / speculative decoding | decode 1.24-1.79x | Engine |
+
+**Items 1-3 are each worth more than the entire remaining engine ceiling, and two
+of them are configuration rather than code.**
+
+---
+
+## 11. Open items
+
+- **Verify live coordinator config** via IAP into `darkbloom-coordinator`
+ (`us-east4-a`, `darkbloom-mainnet`) — confirm `EIGENINFERENCE_DEDICATED_MODELS`
+ is actually set/unset, and diff live env against
+ `deploy/environments/prod.env`. An investigation was dispatched but not
+ completed.
+- **Reconstruct the prefix-cache incident** from Datadog (`DD_API_KEY`,
+ `DD_APP_KEY`, `DD_SITE` in `coordinator/.env`) — the owner disabled it after
+ cache-hit problems; the specific failure was never identified this session.
+- **`TestIntegrationMixedVersionReleasedV0712Provider` fails** with
+ "SIP status: disabled" on the CI runner — appears environmental (the test
+ refuses to skip silently), but was never confirmed, and it means the
+ mixed-version compatibility gate did not actually run for v0.7.15.
+- **Check `gpu_memory_peak_gb` vs prompt size** in `inference_routes` to see
+ whether the 2 GB score tensor already causes pressure at C=512.
+- **W3 expert-kernel patches** live at `tmp/patches/w3-r1-expert-qmm-*.patch`
+ plus two `git stash` entries in `libs/mlx-swift` and its nested mlx. **`tmp/`
+ is gitignored** — that work is not in version control and will be lost on a
+ clean.
From 0cc5fc9c974b9b68039a6c9887b49f0bf28f8926 Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Sun, 9 Aug 2026 21:04:12 -0700
Subject: [PATCH 03/23] =?UTF-8?q?perf(provider):=20Gemma=204=2026B=20v0.8.?=
=?UTF-8?q?2=20=E2=80=94=20retained=20optimization=20cutover,=20config-bac?=
=?UTF-8?q?ked=20controls,=20source-matched=20metallib?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Production integration of the retained v0.8.2 Gemma 4 slices; pins
libs/mlx-swift-lm (53e8ccd) and libs/mlx-swift (db9b77d, nested 9dd10bef).
- Shared-tower cutover: production/benchmark resolution unwraps the outer
MLXVLM.Gemma4 once and threads its owned textModel through engine,
cache, sizing, media, prefix/frozen-replay, and MTP paths.
EngineV2VLMTextExtraction and its parity-probe plumbing are deleted.
- Config authority: GemmaOptimizationEnvironment/Settings resolve the
retained layer-18 and coupled weighted-unsort + safe-R1 requests once
per process before any MLX device access (launchd/foreground/local/
benchmark), with requested/effective reporting; raw env sampling stays
experimental-only.
- Version surfaces: ProviderCore.version 0.8.2; coordinator
LatestProviderVersion fallback 0.8.2 in sync.
- Source-matched metallib: fetch-metallib builds from
libs/mlx-swift/Source/Cmlx/mlx (JIT off), refuses artifacts missing
NAX/GEMV/the R1 builder/tile symbols; ci/integration/release workflows
replace PyPI metallibs and purge cache-restored ones; Makefile
provider-build/test stages the metallib for runner and xctest bundles;
PackagedRuntimeSmoke/darkbloom runtime-smoke cover it.
- e2e/testbed + scripts/gemma_contbatch: benchmark harness environment
threading; docs (beta-features, cli-reference, installation,
quickstart) and READMEs updated.
Measured effect (gemma-4-26B-A4B-it-qat-4bit, M4 Max, immutable pre-edit
vs retained weighted+R1 profile, median/geomean): arrival TTFT +44.8%,
arrival end-to-end TPS +19.6%, single-shot TTFT +15.2% (2048-tok
1715ms -> ~1389ms), decode aggregate TPS +1.3%, prefill TPS +2.4%,
peak memory unchanged. Dropped: expert gate/up packing, dense gate/up
packing, standalone weighted-unsort, standalone R1, historical accepted
R1 control (noisy/negative). R1 kernel armed but recorded zero
production hits; retained opt-in under the coupled gate. Benchmark
artifacts predate the final kernel-body source edit; rebuild and
re-verify before release claims.
---
.github/workflows/ci.yml | 75 ++--
.github/workflows/integration.yml | 52 ++-
.github/workflows/release-swift.yml | 160 ++++----
Makefile | 31 +-
README.md | 9 +
coordinator/api/server.go | 2 +-
docs/provider/beta-features.md | 76 +++-
docs/provider/cli-reference.md | 15 +-
docs/provider/installation.md | 8 +
docs/provider/quickstart.md | 13 +
e2e/testbed/provider.go | 116 ++++--
libs/mlx-swift | 2 +-
libs/mlx-swift-lm | 2 +-
provider-swift/README.md | 36 +-
.../ArrivalInvarianceBenchmark.swift | 5 +-
.../MTPProductionSession.swift | 9 +-
.../SchedulerPrefillBenchmark.swift | 15 +-
.../ProviderBenchmark/ThroughputSweep.swift | 28 +-
.../ProviderCore/Config/BetaFeatures.swift | 44 ++-
.../Config/GemmaOptimizationEnvironment.swift | 89 +++++
.../Config/GemmaOptimizationSettings.swift | 36 ++
.../ProviderCore/Config/ProviderConfig.swift | 17 +-
.../Inference/EngineV2Config.swift | 5 -
.../Inference/EngineV2Factory+Benchmark.swift | 27 +-
.../EngineV2Factory+Production.swift | 24 +-
.../Inference/EngineV2SlotFactory+MTP.swift | 37 +-
.../Inference/EngineV2SlotFactory.swift | 173 +++++++-
.../Inference/EngineV2SupportedModels.swift | 5 +-
.../Inference/EngineV2VLMTextExtraction.swift | 369 ------------------
.../Inference/EngineV2VisionPrefill.swift | 6 +-
.../Inference/ModelContainerLoading.swift | 5 +-
.../MultiModelBatchSchedulerEngine.swift | 23 +-
.../Inference/PackagedRuntimeSmoke.swift | 115 ++++++
.../Inference/SlotSizingSnapshot.swift | 45 +--
.../ProviderCore/Process/BoundedProcess.swift | 48 ++-
.../Sources/ProviderCore/ProviderCore.swift | 29 +-
.../ProviderCore/ProviderLoop+EngineV2.swift | 28 +-
.../ProviderLoop+EngineV2Liveness.swift | 1 -
.../ProviderLoop+ModelLoading.swift | 12 +-
.../Sources/ProviderCore/ProviderLoop.swift | 4 +-
.../Server/StandaloneServer.swift | 16 +-
.../ProviderCore/Service/LaunchAgent.swift | 73 ++--
.../ProviderCore/Update/SelfUpdater.swift | 10 +-
.../Sources/darkbloom/BetaCommand.swift | 16 +-
.../darkbloom/RuntimeSmokeCommand.swift | 2 +
.../darkbloom/StartCommand+Daemon.swift | 4 +-
.../Sources/darkbloom/StartCommand.swift | 41 +-
.../DarkbloomCLITests/StartCommandTests.swift | 109 ++++++
.../ProviderCoreTests/BetaFeaturesTests.swift | 70 +++-
.../EngineV2BridgeTests.swift | 3 -
.../EngineV2LivenessRecoveryTests.swift | 4 +-
.../EngineV2ProductionWiringTests.swift | 40 +-
.../EngineV2SSDPrefixCacheLiveTests.swift | 24 +-
.../FrozenReplayRealModelTests.swift | 14 +-
.../GemmaMTPProductionLiveTests.swift | 1 -
.../GemmaOptimizationConfigTests.swift | 240 ++++++++++++
.../GemmaOptimizationReportingTests.swift | 126 ++++++
.../GemmaVLMEngineV2LiveTests.swift | 154 +++-----
.../GemmaVLMParityProbeMemoryLiveTests.swift | 281 -------------
.../GemmaVLMSharedTowerMemoryLiveTests.swift | 224 +++++++++++
.../GemmaVLMVideoEngineV2LiveTests.swift | 20 +-
.../GemmaVLMVisionEngineV2LiveTests.swift | 19 +-
.../LaunchAgentRestartTests.swift | 42 +-
.../LiveInferenceFixtures.swift | 81 ++--
.../ProviderCoreTests/MTPConfigTests.swift | 9 +-
.../ProviderMTPFactoryTests.swift | 102 ++++-
.../ProviderCoreTests/SelfUpdaterTests.swift | 4 +-
.../SlotSizingDriftTests.swift | 7 +-
scripts/fetch-metallib.sh | 272 ++++++++++---
scripts/gemma_contbatch/environment.py | 1 +
70 files changed, 2378 insertions(+), 1427 deletions(-)
create mode 100644 provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift
create mode 100644 provider-swift/Sources/ProviderCore/Config/GemmaOptimizationSettings.swift
delete mode 100644 provider-swift/Sources/ProviderCore/Inference/EngineV2VLMTextExtraction.swift
create mode 100644 provider-swift/Tests/DarkbloomCLITests/StartCommandTests.swift
create mode 100644 provider-swift/Tests/ProviderCoreTests/GemmaOptimizationConfigTests.swift
create mode 100644 provider-swift/Tests/ProviderCoreTests/GemmaOptimizationReportingTests.swift
delete mode 100644 provider-swift/Tests/ProviderCoreTests/GemmaVLMParityProbeMemoryLiveTests.swift
create mode 100644 provider-swift/Tests/ProviderCoreTests/GemmaVLMSharedTowerMemoryLiveTests.swift
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 815df82287..2c459d2a23 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -116,9 +116,14 @@ jobs:
~/Library/org.swift.swiftpm
provider-swift/.build
libs/mlx-swift-lm/.build
- key: spm-v2-${{ runner.os }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }}
+ key: spm-v3-${{ runner.os }}-${{ github.sha }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }}
restore-keys: |
- spm-v2-${{ runner.os }}-
+ spm-v3-${{ runner.os }}-
+ - name: Discard metallibs restored by the generic SwiftPM cache
+ run: |
+ for root in provider-swift/.build libs/mlx-swift-lm/.build; do
+ [ ! -d "$root" ] || find "$root" -type f -name mlx.metallib -delete
+ done
- name: Install pinned Rust toolchain for production prompt parity
run: |
rustup toolchain install 1.88.0 --profile minimal
@@ -132,28 +137,29 @@ jobs:
# The root helper is a separately packaged executable product and is
# not guaranteed to be linked merely because the test bundle builds.
swift build --product darkbloom-fan-helper
- - name: Extract mlx.metallib
- working-directory: provider-swift
+ - name: Build and stage source-matched mlx.metallib
run: |
- python3 -m venv /tmp/mlxvenv
- /tmp/mlxvenv/bin/pip install 'mlx==0.31.2'
- metallib="/tmp/mlxvenv/lib/python$(/tmp/mlxvenv/bin/python -c 'import sys;print(f"{sys.version_info.major}.{sys.version_info.minor}")')/site-packages/mlx/lib/mlx.metallib"
- # MLX's C++ loader (device.cpp load_default_library) searches for the
- # metallib COLOCATED WITH THE RUNNING BINARY. Under `swift test` the
- # running binary is the xctest runner INSIDE the .xctest bundle, so a
- # copy in .build/debug alone is not found — it must sit next to the
- # runner. Place it in both locations to cover `swift run`/built-binary
- # paths and the test runner. Fail loudly if the source isn't there.
- test -f "$metallib" || { echo "::error::mlx.metallib not found at $metallib"; exit 1; }
- cp "$metallib" "$RUNNER_TEMP/mlx.metallib"
- cp "$metallib" .build/debug/mlx.metallib
- for bundle in .build/debug/*PackageTests.xctest; do
- macos="$bundle/Contents/MacOS"
- if [ -d "$macos" ]; then
- cp "$metallib" "$macos/mlx.metallib"
- echo "placed metallib in $macos"
- fi
+ set -euo pipefail
+ command -v cmake >/dev/null 2>&1 || brew install cmake
+ METALLIB_CACHE_DIR="$RUNNER_TEMP/metallib-cache" \
+ ./scripts/fetch-metallib.sh "$RUNNER_TEMP"
+ metallib="$RUNNER_TEMP/mlx.metallib"
+ test -s "$metallib" || { echo "::error::source-matched mlx.metallib was not produced"; exit 1; }
+
+ # MLX loads the metallib from beside the running executable. Stage the
+ # helper-authorized artifact into every provider binary and XCTest
+ # location that the preceding build created.
+ provider_bin=$(cd provider-swift && swift build -c debug --show-bin-path)
+ for destination in provider-swift/.build/debug "$provider_bin"; do
+ mkdir -p "$destination"
+ cp "$metallib" "$destination/mlx.metallib"
done
+ while IFS= read -r macos; do
+ cp "$metallib" "$macos/mlx.metallib"
+ echo "placed source-matched metallib in $macos"
+ done < <(
+ find provider-swift/.build -type d -path '*.xctest/Contents/MacOS' -print
+ )
- name: Run Swift tests
working-directory: provider-swift
# NOTE: do NOT pass --build-tests-relinking flags; the bundle is already
@@ -167,7 +173,12 @@ jobs:
# 12-vcpu runner); warm runs restore libs/mlx-swift-lm/.build from
# the SwiftPM cache and finish in ~1 min.
timeout-minutes: 35
- run: swift build --build-tests
+ run: |
+ # This standalone package otherwise resolves its remote mlx-swift
+ # branch while loading the root helper's local-source metallib.
+ swift package unedit --force mlx-swift >/dev/null 2>&1 || true
+ swift package edit --path ../mlx-swift mlx-swift
+ swift build --build-tests
- name: Run nested paged and prompt-hash tests directly
working-directory: libs/mlx-swift-lm
timeout-minutes: 10
@@ -202,9 +213,14 @@ jobs:
~/Library/org.swift.swiftpm
provider-swift/.build
libs/mlx-swift-lm/.build
- key: spm-v2-${{ runner.os }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }}
+ key: spm-v3-${{ runner.os }}-${{ github.sha }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }}
restore-keys: |
- spm-v2-${{ runner.os }}-
+ spm-v3-${{ runner.os }}-
+ - name: Discard metallibs restored by the generic SwiftPM cache
+ run: |
+ for root in provider-swift/.build libs/mlx-swift-lm/.build; do
+ [ ! -d "$root" ] || find "$root" -type f -name mlx.metallib -delete
+ done
- name: Build provider-swift
working-directory: provider-swift
run: |
@@ -215,7 +231,12 @@ jobs:
# The test-provider job runs CBv2PagedSafetyTests from this nested
# .build; saving it here keeps that lane warm across PRs.
timeout-minutes: 35
- run: swift build --build-tests
+ run: |
+ # Keep the warmed nested workspace on the same local MLX source used
+ # by provider builds and scripts/fetch-metallib.sh.
+ swift package unedit --force mlx-swift >/dev/null 2>&1 || true
+ swift package edit --path ../mlx-swift mlx-swift
+ swift build --build-tests
- name: Save SwiftPM cache
uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0
with:
@@ -224,7 +245,7 @@ jobs:
~/Library/org.swift.swiftpm
provider-swift/.build
libs/mlx-swift-lm/.build
- key: spm-v2-${{ runner.os }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }}
+ key: spm-v3-${{ runner.os }}-${{ github.sha }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }}
lint-console:
name: Console UI Lint & Build
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index 156715dca6..3776c5ed37 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -37,12 +37,24 @@ jobs:
- name: Build prompt-contract sidecar
run: cargo build --manifest-path coordinator/promptsidecar/Cargo.toml --release
- - name: Extract mlx.metallib
+ - name: Build and stage source-matched mlx.metallib
run: |
- python3 -m venv /tmp/mlxvenv
- /tmp/mlxvenv/bin/pip install 'mlx==0.31.2'
- cp /tmp/mlxvenv/lib/python*/site-packages/mlx/lib/mlx.metallib \
- provider-swift/.build/debug/mlx.metallib
+ set -euo pipefail
+ command -v cmake >/dev/null 2>&1 || brew install cmake
+ METALLIB_CACHE_DIR="$RUNNER_TEMP/metallib-cache" \
+ ./scripts/fetch-metallib.sh "$RUNNER_TEMP"
+ metallib="$RUNNER_TEMP/mlx.metallib"
+ provider_bin=$(cd provider-swift && swift build -c debug --show-bin-path)
+ for destination in provider-swift/.build/debug "$provider_bin"; do
+ mkdir -p "$destination"
+ cp "$metallib" "$destination/mlx.metallib"
+ done
+ while IFS= read -r macos; do
+ cp "$metallib" "$macos/mlx.metallib"
+ done < <(
+ find provider-swift/.build libs/mlx-swift-lm/.build \
+ -type d -path '*.xctest/Contents/MacOS' -print 2>/dev/null
+ )
- name: Install Hugging Face client
# v0.7.5 one-engine: the testbed default is the smallest
@@ -51,7 +63,9 @@ jobs:
# register). Exact-cache routing additionally uses the small Gemma 4
# checkpoint because GPT-OSS's dynamic-date template is cold-only.
# A warm HF cache makes these downloads no-ops.
- run: /tmp/mlxvenv/bin/pip install huggingface_hub
+ run: |
+ python3 -m venv /tmp/mlxvenv
+ /tmp/mlxvenv/bin/pip install huggingface_hub
- name: Download model (protected read-only auth)
if: github.event_name == 'push'
@@ -156,18 +170,32 @@ jobs:
cd provider-swift
swift build -c debug
- - name: Extract mlx.metallib
+ - name: Build and stage source-matched mlx.metallib
run: |
- python3 -m venv /tmp/mlxvenv
- /tmp/mlxvenv/bin/pip install 'mlx==0.31.2'
- cp /tmp/mlxvenv/lib/python*/site-packages/mlx/lib/mlx.metallib \
- provider-swift/.build/debug/mlx.metallib
+ set -euo pipefail
+ command -v cmake >/dev/null 2>&1 || brew install cmake
+ METALLIB_CACHE_DIR="$RUNNER_TEMP/metallib-cache" \
+ ./scripts/fetch-metallib.sh "$RUNNER_TEMP"
+ metallib="$RUNNER_TEMP/mlx.metallib"
+ provider_bin=$(cd provider-swift && swift build -c debug --show-bin-path)
+ for destination in provider-swift/.build/debug "$provider_bin"; do
+ mkdir -p "$destination"
+ cp "$metallib" "$destination/mlx.metallib"
+ done
+ while IFS= read -r macos; do
+ cp "$metallib" "$macos/mlx.metallib"
+ done < <(
+ find provider-swift/.build libs/mlx-swift-lm/.build \
+ -type d -path '*.xctest/Contents/MacOS' -print 2>/dev/null
+ )
- name: Install Hugging Face client
# Benchmarks serve the CBv2 default (gpt-oss-20b, ~12 GB) plus the
# secondary multi-model checkpoint (gemma-4-26B QAT, ~14.5 GB) for
# TestBenchmark_MultiModelMultiProvider. Warm HF cache ⇒ no-op.
- run: /tmp/mlxvenv/bin/pip install huggingface_hub
+ run: |
+ python3 -m venv /tmp/mlxvenv
+ /tmp/mlxvenv/bin/pip install huggingface_hub
- name: Download public models (pull request)
run: |
diff --git a/.github/workflows/release-swift.yml b/.github/workflows/release-swift.yml
index c373110582..7dbb856718 100644
--- a/.github/workflows/release-swift.yml
+++ b/.github/workflows/release-swift.yml
@@ -236,9 +236,14 @@ jobs:
~/Library/org.swift.swiftpm
provider-swift/.build
libs/mlx-swift-lm/.build
- key: spm-v2-${{ runner.os }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }}
+ key: spm-v3-${{ runner.os }}-${{ github.sha }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }}
restore-keys: |
- spm-v2-${{ runner.os }}-
+ spm-v3-${{ runner.os }}-
+ - name: Discard metallibs restored by the generic SwiftPM cache
+ run: |
+ for root in provider-swift/.build libs/mlx-swift-lm/.build; do
+ [ ! -d "$root" ] || find "$root" -type f -name mlx.metallib -delete
+ done
- name: Verify production prompt parity
run: |
@@ -246,90 +251,62 @@ jobs:
rustup override set 1.88.0
./scripts/verify-prompt-parity.sh
- # ----------------------------------------------------------------------
- # Build mlx.metallib (compiled Metal GPU kernels) FROM SOURCE.
- #
- # mlx-swift's Cmlx target does not compile .metal kernels via SwiftPM, so
- # we build them here with cmake from the exact fork commit at
- # libs/mlx-swift/Source/Cmlx/mlx (the same source the host C++ links
- # against). This guarantees the kernels match — including the _nax kernels
- # — and needs no published mlx wheel. The result is cached on the mlx
- # commit + toolchain, so it only rebuilds when the submodule or Xcode
- # changes (~1 min on a cold build, instant on a cache hit).
- # ----------------------------------------------------------------------
-
- - name: Resolve metallib cache key
+ # The root helper is the sole metallib builder. The Actions cache stores
+ # its private cache directory; the helper still runs on every release and
+ # authorizes the exact source/toolchain/deployment/JIT contract itself.
+ - name: Resolve source-matched metallib cache namespace
id: mlxkey
run: |
set -euo pipefail
MLX_SRC="libs/mlx-swift/Source/Cmlx/mlx"
test -f "$MLX_SRC/mlx/version.h" || { echo "::error::mlx submodule not checked out at $MLX_SRC"; exit 1; }
+ SOURCE_STATUS=$(git -C "$MLX_SRC" status --porcelain=v1 --untracked-files=all)
+ if [ -n "$SOURCE_STATUS" ]; then
+ echo "::error::release metallib source checkout is dirty"
+ printf '%s\n' "$SOURCE_STATUS"
+ exit 1
+ fi
MLX_SHA=$(git -C "$MLX_SRC" rev-parse HEAD)
+ HELPER_SHA=$(shasum -a 256 scripts/fetch-metallib.sh | cut -d' ' -f1)
SDK=$(xcrun --sdk macosx --show-sdk-version)
- XCODE=$(xcodebuild -version | head -1 | tr -d ' ')
- KEY="metallib-v1-${MLX_SHA}-${XCODE}-sdk${SDK}-dt${MLX_METALLIB_DEPLOYMENT_TARGET}-jitoff"
- echo "mlx_src=$MLX_SRC" >> "$GITHUB_OUTPUT"
- echo "mlx_sha=$MLX_SHA" >> "$GITHUB_OUTPUT"
- echo "mlx_sha_short=${MLX_SHA:0:12}" >> "$GITHUB_OUTPUT"
+ XCODE=$(xcodebuild -version | tr -cs '[:alnum:].' '-')
+ KEY="metallib-helper-v1-${MLX_SHA}-${HELPER_SHA}-${XCODE}-sdk${SDK}-dt${MLX_METALLIB_DEPLOYMENT_TARGET}-jitoff"
echo "key=$KEY" >> "$GITHUB_OUTPUT"
- echo "Metallib cache key: $KEY"
+ echo "mlx_sha_short=${MLX_SHA:0:12}" >> "$GITHUB_OUTPUT"
+ echo "Metallib cache namespace: $KEY"
- - name: Restore metallib cache
+ - name: Restore source-matched metallib cache
id: metallib-cache
uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0
with:
- path: ${{ runner.temp }}/metallib/mlx.metallib
+ path: ${{ runner.temp }}/metallib-cache
key: ${{ steps.mlxkey.outputs.key }}
- - name: Build mlx.metallib from source
- if: steps.metallib-cache.outputs.cache-hit != 'true'
+ - name: Build source-matched mlx.metallib through root helper
+ id: metallib
+ env:
+ METALLIB_CACHE_DIR: ${{ runner.temp }}/metallib-cache
run: |
set -euo pipefail
command -v cmake >/dev/null 2>&1 || brew install cmake
- SRC="${{ steps.mlxkey.outputs.mlx_src }}"
- BUILD="$RUNNER_TEMP/metallib-build"
- OUT="$RUNNER_TEMP/metallib"
- rm -rf "$BUILD"; mkdir -p "$OUT"
- # JIT=OFF compiles the full kernel set into the metallib. Deployment
- # target >= 26.2 + SDK >= 26.2 + Metal >= 4.0 is what gates the _nax
- # kernels (mlx/backend/metal/kernels/CMakeLists.txt).
- cmake -S "$SRC" -B "$BUILD" \
- -DCMAKE_BUILD_TYPE=Release \
- -DCMAKE_OSX_DEPLOYMENT_TARGET="$MLX_METALLIB_DEPLOYMENT_TARGET" \
- -DMLX_METAL_JIT=OFF \
- -DMLX_BUILD_TESTS=OFF -DMLX_BUILD_EXAMPLES=OFF \
- -DMLX_BUILD_BENCHMARKS=OFF -DMLX_BUILD_PYTHON_BINDINGS=OFF
- cmake --build "$BUILD" --target mlx-metallib -j"$(sysctl -n hw.ncpu)"
- cp "$BUILD/mlx/backend/metal/kernels/mlx.metallib" "$OUT/mlx.metallib"
- ls -lh "$OUT/mlx.metallib"
-
- - name: Save metallib cache
+ MLX_SRC="libs/mlx-swift/Source/Cmlx/mlx"
+ test -z "$(git -C "$MLX_SRC" status --porcelain=v1 --untracked-files=all)"
+ ./scripts/fetch-metallib.sh "$RUNNER_TEMP/metallib"
+ test -z "$(git -C "$MLX_SRC" status --porcelain=v1 --untracked-files=all)" || {
+ echo "::error::metallib helper modified the release source checkout"
+ exit 1
+ }
+ MLIB="$RUNNER_TEMP/metallib/mlx.metallib"
+ test -s "$MLIB" || { echo "::error::metallib missing at $MLIB"; exit 1; }
+ echo "metallib=$MLIB" >> "$GITHUB_OUTPUT"
+
+ - name: Save source-matched metallib cache
if: steps.metallib-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0
with:
- path: ${{ runner.temp }}/metallib/mlx.metallib
+ path: ${{ runner.temp }}/metallib-cache
key: ${{ steps.mlxkey.outputs.key }}
- - name: Verify metallib completeness (nax + gemv)
- id: metallib
- run: |
- set -euo pipefail
- MLIB="$RUNNER_TEMP/metallib/mlx.metallib"
- test -s "$MLIB" || { echo "::error::metallib missing at $MLIB"; exit 1; }
- # Count with `grep -c` (not `grep -q`): grep -q closes the pipe on the
- # first match, which makes `strings` on this 150 MB+ file exit via
- # SIGPIPE and trip `set -o pipefail` — a false negative.
- NAX=$(strings "$MLIB" | grep -c "_nax" || true)
- GEMV=$(strings "$MLIB" | grep -c "gemv" || true)
- # _nax kernels are required for the M5 Neural Accelerator path. Their
- # absence means the build used the wrong SDK/deployment target (see the
- # gate in kernels/CMakeLists.txt). gemv guards against an incomplete
- # (JIT) build. Fail loudly rather than ship a broken bundle.
- [ "$NAX" -gt 0 ] || { echo "::error::metallib has no _nax kernels (SDK/deployment target < 26.2?)"; exit 1; }
- [ "$GEMV" -gt 0 ] || { echo "::error::metallib missing gemv kernels (incomplete build?)"; exit 1; }
- echo "metallib=$MLIB" >> "$GITHUB_OUTPUT"
- echo "Metallib OK: size=$(ls -lh "$MLIB" | awk '{print $5}') nax_refs=$NAX gemv_refs=$GEMV"
-
# ----------------------------------------------------------------------
# Build (tests run by CI, not the release workflow).
# ----------------------------------------------------------------------
@@ -359,7 +336,7 @@ jobs:
~/Library/org.swift.swiftpm
provider-swift/.build
libs/mlx-swift-lm/.build
- key: spm-v2-${{ runner.os }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }}
+ key: spm-v3-${{ runner.os }}-${{ github.sha }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }}
# Unit tests are run by CI (ci.yml + integration.yml) on push to
# master. Skipped here to avoid flaky live MLX inference tests
@@ -515,13 +492,17 @@ jobs:
scripts/stage-swiftpm-resource-bundles.sh \
"$BIN_DIR" "$APP" "$RESOURCE_MANIFEST"
- # Package-real runtime gate. This invokes the staged executable,
- # resolves the resource from the installed app layout, then
- # JIT-compiles and executes GPT-OSS bulk-write, decode-part, and
- # decode-merge variants. The v0.7.6 artifact fails here because
- # its bundle is absent.
- DARKBLOOM_NO_UPDATE_CHECK=1 \
- "$APP/Contents/MacOS/$CLI_NAME" runtime-smoke
+ # Package-real runtime gate. Before its first GPU access the staged
+ # child decodes the retained Gemma config, proves authoritative
+ # overwrite of all three low-level controls, snapshots the early R1
+ # latch/AOT capability without arming counters, then runs the
+ # existing GPT-OSS paged-kernel shapes. The v0.7.6 artifact still
+ # fails here because its resource bundle is absent.
+ PRE_SIGN_SMOKE_OUTPUT=$(DARKBLOOM_NO_UPDATE_CHECK=1 \
+ "$APP/Contents/MacOS/$CLI_NAME" runtime-smoke)
+ printf '%s\n' "$PRE_SIGN_SMOKE_OUTPUT"
+ printf '%s\n' "$PRE_SIGN_SMOKE_OUTPUT" \
+ | grep -Fqx 'gemma-optimizations-runtime-smoke: ok'
# Hardened-runtime sign each binary and resource, then the bundle.
# mlx.metallib must be signed before the bundle or codesign rejects
@@ -686,6 +667,7 @@ jobs:
# with the coordinator and verified by provider self-update.
cmp "$STAGE/bin/$CLI_NAME" "$APP/Contents/MacOS/$CLI_NAME"
cmp "$STAGE/bin/$ENCLAVE_NAME" "$APP/Contents/MacOS/$ENCLAVE_NAME"
+ cmp "$STAGE/bin/mlx.metallib" "$APP/Contents/MacOS/mlx.metallib"
tar czf /tmp/darkbloom-bundle-macos-arm64.tar.gz -C "${{ steps.bundle.outputs.stage }}" .
tar tzf /tmp/darkbloom-bundle-macos-arm64.tar.gz | sort | tee /tmp/darkbloom-bundle-files.txt
@@ -721,6 +703,29 @@ jobs:
rm -rf "$SMOKE_ROOT"
mkdir -p "$SMOKE_ROOT"
tar xzf /tmp/darkbloom-bundle-macos-arm64.tar.gz -C "$SMOKE_ROOT"
+ FINAL_APP_METALLIB="$SMOKE_ROOT/Darkbloom.app/Contents/MacOS/mlx.metallib"
+ FINAL_FLAT_METALLIB="$SMOKE_ROOT/bin/mlx.metallib"
+ test -s "$FINAL_APP_METALLIB"
+ test -s "$FINAL_FLAT_METALLIB"
+ cmp "$FINAL_FLAT_METALLIB" "$FINAL_APP_METALLIB"
+ # Repeat the helper's exact four-part completeness contract against
+ # the final extracted, signed bytes rather than the pre-signing input.
+ NAX_SYMBOL="_nax"
+ GEMV_SYMBOL="gemv"
+ R1_BUILDER_SYMBOL="build_gemma4_sorted_expert_tiles_bm32"
+ R1_KERNEL_SYMBOL="affine_gather_qmm_gemma4_expert_tiles_bfloat16_t_gs_64_b_4_alN_true_bm_32_bn_32_bk_32"
+ for symbol in \
+ "$NAX_SYMBOL" \
+ "$GEMV_SYMBOL" \
+ "$R1_BUILDER_SYMBOL" \
+ "$R1_KERNEL_SYMBOL"
+ do
+ MATCHES=$(strings "$FINAL_FLAT_METALLIB" | grep -F -c "$symbol" || true)
+ if [ "$MATCHES" -eq 0 ]; then
+ echo "::error::final signed metallib is missing required symbol: $symbol"
+ exit 1
+ fi
+ done
FINAL_FAN_HELPER="$SMOKE_ROOT/Darkbloom.app/Contents/Helpers/$FAN_HELPER_NAME"
FINAL_FAN_MARKER="$SMOKE_ROOT/Darkbloom.app/Contents/Resources/darkbloom-runtime-capabilities/fan-helper-v1"
test -f "$FINAL_FAN_HELPER"
@@ -737,8 +742,11 @@ jobs:
"-R=$FAN_HELPER_REQUIREMENT" "$FINAL_FAN_HELPER"
codesign --verify --deep --strict --verbose=2 \
"$SMOKE_ROOT/Darkbloom.app"
- DARKBLOOM_NO_UPDATE_CHECK=1 \
- "$SMOKE_ROOT/Darkbloom.app/Contents/MacOS/$CLI_NAME" runtime-smoke
+ FINAL_SMOKE_OUTPUT=$(DARKBLOOM_NO_UPDATE_CHECK=1 \
+ "$SMOKE_ROOT/Darkbloom.app/Contents/MacOS/$CLI_NAME" runtime-smoke)
+ printf '%s\n' "$FINAL_SMOKE_OUTPUT"
+ printf '%s\n' "$FINAL_SMOKE_OUTPUT" \
+ | grep -Fqx 'gemma-optimizations-runtime-smoke: ok'
REPORTED=$("$SMOKE_ROOT/Darkbloom.app/Contents/MacOS/$CLI_NAME" --version)
./scripts/check-release-version.sh "$VERSION" "$REPORTED"
test "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleVersion' \
@@ -746,9 +754,9 @@ jobs:
test "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' \
"$SMOKE_ROOT/Darkbloom.app/Contents/Info.plist")" = "$VERSION"
- BINARY_HASH=$(shasum -a 256 "${{ steps.bundle.outputs.stage }}/bin/$CLI_NAME" | cut -d' ' -f1)
+ BINARY_HASH=$(shasum -a 256 "$SMOKE_ROOT/bin/$CLI_NAME" | cut -d' ' -f1)
BUNDLE_HASH=$(shasum -a 256 /tmp/darkbloom-bundle-macos-arm64.tar.gz | cut -d' ' -f1)
- METALLIB_HASH=$(shasum -a 256 "${{ steps.bundle.outputs.stage }}/bin/mlx.metallib" | cut -d' ' -f1)
+ METALLIB_HASH=$(shasum -a 256 "$FINAL_FLAT_METALLIB" | cut -d' ' -f1)
echo "BINARY_HASH=$BINARY_HASH" >> "$GITHUB_ENV"
echo "BUNDLE_HASH=$BUNDLE_HASH" >> "$GITHUB_ENV"
echo "METALLIB_HASH=$METALLIB_HASH" >> "$GITHUB_ENV"
diff --git a/Makefile b/Makefile
index 5dc4fcc4de..a40782804c 100644
--- a/Makefile
+++ b/Makefile
@@ -44,11 +44,34 @@ prompt-sidecar: prompt-sidecar-format prompt-sidecar-check prompt-sidecar-test p
# ---- Provider (Swift, Apple Silicon) --------------------------------------
-provider-build: ## swift build for the Swift provider CLI
+provider-build: ## Build the Swift provider CLI with its source-matched metallib
cd provider-swift && swift build
-
-provider-test: ## swift test for the Swift provider CLI
- cd provider-swift && swift test
+ @set -eu; \
+ bin_path="$$(cd provider-swift && swift build --show-bin-path)"; \
+ ./scripts/fetch-metallib.sh "$$bin_path"
+
+provider-test: ## Build and run Swift provider tests with source-matched metallibs
+ cd provider-swift && swift build --build-tests
+ @set -eu; \
+ bin_path="$$(cd provider-swift && swift build --show-bin-path)"; \
+ ./scripts/fetch-metallib.sh "$$bin_path"; \
+ runner_tmp=""; \
+ trap 'test -z "$$runner_tmp" || rm -f "$$runner_tmp"' EXIT; \
+ trap 'exit 143' HUP INT TERM; \
+ found=0; \
+ for bundle in "$$bin_path"/*PackageTests.xctest; do \
+ [ -d "$$bundle" ] || continue; \
+ runner_dir="$$bundle/Contents/MacOS"; \
+ mkdir -p "$$runner_dir"; \
+ runner_tmp="$$runner_dir/.mlx.metallib.$$$$"; \
+ cp "$$bin_path/mlx.metallib" "$$runner_tmp"; \
+ mv -f "$$runner_tmp" "$$runner_dir/mlx.metallib"; \
+ runner_tmp=""; \
+ found=1; \
+ done; \
+ [ "$$found" -eq 1 ] || { echo "provider test runner bundle not found in $$bin_path" >&2; exit 1; }; \
+ trap - EXIT HUP INT TERM
+ cd provider-swift && swift test --skip-build
provider: provider-build provider-test ## Build + test provider
diff --git a/README.md b/README.md
index 382436b1bd..1453ee635d 100644
--- a/README.md
+++ b/README.md
@@ -271,6 +271,10 @@ idle_timeout_mins = 60 # unload an idle model after N minutes (0 = never)
max_model_slots = 3 # max models resident at once
continuous_batching = true
+[gemma_optimizations]
+prefill_layer18 = true # default ON; 18-layer prefill submissions
+weighted_r1 = true # default ON; coupled weighted-unsort + safe R1
+
[coordinator]
url = "wss://api.darkbloom.dev/ws/provider"
heartbeat_interval_secs = 5
@@ -286,6 +290,11 @@ start = "22:00"
end = "08:00"
```
+`[gemma_optimizations]` is authoritative for production provider processes.
+Both selected controls default to `true` even when an older config omits the
+section. To roll back either optimization, set its key to `false` and run
+`darkbloom restart`; restart is the activation boundary.
+
## Self-route & direct mode
Running a node also makes your **own** inference free.
diff --git a/coordinator/api/server.go b/coordinator/api/server.go
index 105b9d61c0..610a3357eb 100644
--- a/coordinator/api/server.go
+++ b/coordinator/api/server.go
@@ -145,7 +145,7 @@ func keyLimitResetFromContext(ctx context.Context) string {
// 0.6.0 is the APNs code-identity / VLM-routing / graceful-update release.
// Keep this fallback in sync with ProviderCore.version so dev/in-memory
// coordinators advertise the same floor as the Swift binary they expect.
-var LatestProviderVersion = "0.7.15"
+var LatestProviderVersion = "0.8.2"
// minProviderVersionForDesiredModels is the first provider version whose Swift
// runtime understands the desired_models message. The coordinator must NOT send
diff --git a/docs/provider/beta-features.md b/docs/provider/beta-features.md
index 2d306ca7e8..86b97ffdf3 100644
--- a/docs/provider/beta-features.md
+++ b/docs/provider/beta-features.md
@@ -1,19 +1,18 @@
# Beta Features
-Beta features are experimental provider capabilities that are **off by default**.
-They are validated enough to try in production but may change, carry caveats, or
-only apply to specific model families. Enable them per provider when you want to
-opt in.
+Beta features are experimental provider capabilities with feature-specific
+defaults. The benchmark-selected Gemma stack is **on by default**, including for
+existing configs that omit its section; reserved and opt-in features remain off
+until enabled. Every feature can be changed per provider.
## How beta features are toggled
-Beta features are **config-backed**, not environment-variable backed. Each one is
-a field in your provider TOML config (`~/.config/darkbloom/provider.toml`). This
-matters: the launchd daemon started by `darkbloom start` only inherits a tiny
-allowlist of `DARKBLOOM_*` environment variables
-(`provider-swift/Sources/ProviderCore/Daemon/LaunchAgent.swift`), so an env-var
-toggle would silently have no effect on the running daemon. A TOML field is always
-read by every serve path (daemon, `--foreground`, and `--local`).
+Beta features are **config-backed**. Each one is a field in your provider TOML
+config (`~/.config/darkbloom/provider.toml`), and that config is authoritative
+for daemon, `--foreground`, and `--local` processes. Low-level environment
+variables are implementation details, not an independent production control
+surface. Process-wide optimization state is resolved at startup, so restart
+after changing a restart-required feature.
The registry of available features lives in
`provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift`.
@@ -28,19 +27,64 @@ darkbloom beta disable # turn a feature off
```
`enable`/`disable` perform a read-modify-write of the TOML config and print
-whether a restart is required. Most beta features take effect on the next backend
-start:
+whether a restart is required. For example, to roll back the default-on coupled
+Gemma expert optimization:
```bash
-darkbloom beta enable kv-quant
+darkbloom beta disable gemma-weighted-r1
darkbloom restart
```
-You can also see which beta features are active in `darkbloom status` (the
-`Beta features:` line), or edit the TOML directly.
+The restart is the activation boundary. Re-enable and restart to restore the
+selected default. You can also see which beta features are active in
+`darkbloom status` (the `Beta features:` line), or edit the TOML directly.
## Available features
+### `gemma-prefill-layer18` — layer-18 prefill submission
+
+This optimization submits queued Gemma prefill work every 18 transformer
+layers instead of waiting for one final submission. It defaults ON for both new
+and pre-existing provider configs.
+
+```toml
+[gemma_optimizations]
+prefill_layer18 = true
+```
+
+Rollback is config-backed and restart-required:
+
+```bash
+darkbloom beta disable gemma-prefill-layer18
+darkbloom restart
+```
+
+Setting the key to `false` (or using the command above) restores the legacy
+one-final-submission behavior after restart.
+
+### `gemma-weighted-r1` — coupled weighted unsort + safe R1
+
+This optimization defaults ON and is deliberately one atomic production
+control. It enables both the direct weighted expert reduction and the safe
+exact-shape R1 QMM path. There is no supported config or beta combination that
+enables one without the other.
+
+```toml
+[gemma_optimizations]
+weighted_r1 = true
+```
+
+To roll back both paths together:
+
+```bash
+darkbloom beta disable gemma-weighted-r1
+darkbloom restart
+```
+
+Missing `[gemma_optimizations]` sections and missing keys decode as `true`, so
+old configs receive the selected v0.8.2 stack. An explicit `false` plus restart
+is the durable rollback.
+
### `kv-quant` — reserved KV-cache quantization toggle
v0.7.5 serves fp16-only KV through ContinuousBatchingV2. The configuration
diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md
index 3f3795bff3..aa84f0b02a 100644
--- a/docs/provider/cli-reference.md
+++ b/docs/provider/cli-reference.md
@@ -208,9 +208,9 @@ This toggles `provider.auto_update` in `provider.toml`.
## `darkbloom beta`
-Manage opt-in beta features. Beta features are off by default and config-backed
-(a TOML field), so they apply to the launchd daemon too — unlike environment
-variables, which the daemon does not inherit.
+Manage configurable beta features. Defaults are feature-specific: the selected
+Gemma optimizations default on, while reserved/opt-in features default off.
+Provider TOML is authoritative for every serve mode.
```bash
darkbloom beta list # all features + on/off (default subcommand)
@@ -221,13 +221,16 @@ darkbloom beta disable # turn off
| Feature | Effect |
|---------|--------|
+| `gemma-prefill-layer18` | Default-on layer-18 prefill submission; disable and restart for legacy submission behavior |
+| `gemma-weighted-r1` | Default-on atomic weighted-unsort + safe-R1 pair; disable and restart to roll back both |
| `kv-quant` | Forward-compatibility toggle; v0.7.5 warns and continues with fp16 KV |
| `mtp` | Default-off Gemma 4 MTP code path; requires a separately published and verified `spec_dec` artifact, which production does not currently have |
`enable`/`disable` read-modify-write the TOML config and report whether a restart
-is required. See [Beta Features](beta-features.md) for the full guide. `darkbloom
-beta list` also accepts `--json`. Installing a provider release does not enable
-MTP, and local parity results are not a blanket M1–M3/unknown-chip certification.
+is required. Restart is the activation boundary for process-wide optimization
+state. See [Beta Features](beta-features.md) for the full guide. `darkbloom beta
+list` also accepts `--json`. Installing a provider release does not enable MTP,
+and local parity results are not a blanket M1–M3/unknown-chip certification.
## `darkbloom fan` (experimental)
diff --git a/docs/provider/installation.md b/docs/provider/installation.md
index 3ba9993d86..880f1b0d43 100644
--- a/docs/provider/installation.md
+++ b/docs/provider/installation.md
@@ -92,11 +92,19 @@ enabled_models = []
idle_timeout_mins = 60
max_model_slots = 3
+[gemma_optimizations]
+prefill_layer18 = true
+weighted_r1 = true
+
[coordinator]
url = "wss://api.darkbloom.dev/ws/provider"
private_only = false
```
+Both Gemma controls default ON when the section or either key is absent, so
+older configs receive the selected stack. Provider TOML is authoritative; set
+a key to `false` and run `darkbloom restart` for a durable rollback.
+
## Updating the provider
```bash
diff --git a/docs/provider/quickstart.md b/docs/provider/quickstart.md
index bec70b8b95..74b64afa4e 100644
--- a/docs/provider/quickstart.md
+++ b/docs/provider/quickstart.md
@@ -119,6 +119,10 @@ idle_timeout_mins = 60
max_model_slots = 3
kv_quant = false
+[gemma_optimizations]
+prefill_layer18 = true
+weighted_r1 = true
+
[coordinator]
url = "wss://api.darkbloom.dev/ws/provider"
heartbeat_interval_secs = 5
@@ -130,6 +134,15 @@ start = "22:00"
end = "08:00"
```
+- `gemma_optimizations.prefill_layer18` — default ON, including when an older
+ config omits the section or key. Set to `false` and restart to restore legacy
+ one-final-submission Gemma prefill.
+- `gemma_optimizations.weighted_r1` — default ON, including when omitted. This
+ is one atomic production control for weighted unsort and safe R1; the two
+ paths cannot be configured independently.
+- Provider TOML is authoritative for both controls. Changes take effect at
+ process restart; after setting either key to `false`, run `darkbloom restart`
+ to activate the rollback.
- `backend.enabled_models` — if non-empty, only these models are advertised.
- `backend.idle_timeout_mins` — minutes of inactivity before an idle model is
unloaded (default 60; 0 disables eviction).
diff --git a/e2e/testbed/provider.go b/e2e/testbed/provider.go
index cad2602fc8..09768ba99c 100644
--- a/e2e/testbed/provider.go
+++ b/e2e/testbed/provider.go
@@ -1,6 +1,7 @@
package testbed
import (
+ "bytes"
"context"
"fmt"
"log/slog"
@@ -8,6 +9,8 @@ import (
"os/exec"
"path/filepath"
"strings"
+ "syscall"
+ "time"
)
func providerBuildConfig() string {
@@ -44,34 +47,37 @@ func BuildProvider(ctx context.Context, logger *slog.Logger) (string, error) {
providerDir := filepath.Join(repoRoot, "provider-swift")
cfg := providerBuildConfig()
- binaryPath := providerDir + "/.build/" + cfg + "/darkbloom"
- if _, err := os.Stat(binaryPath); err == nil {
- metallibPath := providerDir + "/.build/" + cfg + "/mlx.metallib"
- if _, err2 := os.Stat(metallibPath); err2 == nil {
- logger.Info("using cached provider binary", "path", binaryPath)
- return binaryPath, nil
- }
+ showBinPath := exec.CommandContext(ctx, "swift", "build", "-c", cfg, "--show-bin-path")
+ showBinPath.Dir = providerDir
+ binPathOutput, err := showBinPath.Output()
+ if err != nil {
+ return "", fmt.Errorf("resolve provider build path: %w", err)
}
+ binPath := strings.TrimSpace(string(binPathOutput))
+ if binPath == "" {
+ return "", fmt.Errorf("resolve provider build path: swift returned an empty path")
+ }
+ binaryPath := filepath.Join(binPath, "darkbloom")
logger.Info("building provider binary", "dir", providerDir, "config", cfg)
-
cmd := exec.CommandContext(ctx, "swift", "build", "-c", cfg)
cmd.Dir = providerDir
-
- out, err := cmd.CombinedOutput()
- if err != nil {
- return "", fmt.Errorf("swift build provider: %w: %s", err, string(out))
+ out, buildErr := cmd.CombinedOutput()
+ if buildErr != nil {
+ return "", fmt.Errorf("swift build provider: %w: %s", buildErr, string(out))
}
-
- if _, err := os.Stat(binaryPath); err != nil {
+ if info, statErr := os.Stat(binaryPath); statErr != nil || info.IsDir() || info.Mode()&0o111 == 0 {
return "", fmt.Errorf("provider binary not found after build: %s", binaryPath)
}
- if err := ensureMetallib(providerDir, logger); err != nil {
+ // Candidate binaries always receive a freshly staged metallib from the
+ // exact nested MLX source. An existing colocated file is not evidence that
+ // it matches the host code.
+ if err := ensureMetallib(ctx, repoRoot, binPath, logger); err != nil {
return "", fmt.Errorf("metallib setup: %w", err)
}
- logger.Info("provider binary built", "path", binaryPath)
+ logger.Info("provider binary ready", "path", binaryPath)
return binaryPath, nil
}
@@ -94,37 +100,69 @@ func findRepositoryRoot(start string) (string, error) {
}
}
-func ensureMetallib(providerDir string, logger *slog.Logger) error {
- cfg := providerBuildConfig()
- metallibPath := providerDir + "/.build/" + cfg + "/mlx.metallib"
- if _, err := os.Stat(metallibPath); err == nil {
- return nil
+func ensureMetallib(
+ ctx context.Context,
+ repoRoot string,
+ binPath string,
+ logger *slog.Logger,
+) error {
+ helper := filepath.Join(repoRoot, "scripts", "fetch-metallib.sh")
+ info, err := os.Stat(helper)
+ if err != nil || info.IsDir() || info.Mode()&0o111 == 0 {
+ return fmt.Errorf("source metallib helper is not executable: %s", helper)
}
- if envPath := os.Getenv("MLX_METALLIB_PATH"); envPath != "" {
- if _, err := os.Stat(envPath); err == nil {
- return copyFile(envPath, metallibPath)
- }
+ cmd := exec.Command(helper, binPath)
+ cmd.Dir = repoRoot
+ out, err := runProcessGroup(ctx, cmd)
+ if len(out) != 0 {
+ (&logWriter{logger: logger, prefix: "metallib helper"}).Write(out)
}
-
- siteDirs, _ := filepath.Glob("/tmp/mlxvenv/lib/python*/site-packages/mlx/lib")
- for _, dir := range siteDirs {
- src := filepath.Join(dir, "mlx.metallib")
- if _, err := os.Stat(src); err == nil {
- logger.Info("copying mlx.metallib from Python wheel", "src", src)
- return copyFile(src, metallibPath)
- }
+ if err != nil {
+ return fmt.Errorf("build source-matched metallib: %w", err)
}
- return fmt.Errorf("mlx.metallib not found; install mlx==0.31.2 Python wheel and copy to %s or set MLX_METALLIB_PATH", metallibPath)
+ metallibPath := filepath.Join(binPath, "mlx.metallib")
+ metallib, err := os.Stat(metallibPath)
+ if err != nil || metallib.IsDir() || metallib.Size() == 0 {
+ return fmt.Errorf("source metallib helper did not stage %s", metallibPath)
+ }
+ return nil
}
-func copyFile(src, dst string) error {
- data, err := os.ReadFile(src)
- if err != nil {
- return err
+func runProcessGroup(ctx context.Context, cmd *exec.Cmd) ([]byte, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+
+ var output bytes.Buffer
+ cmd.Stdout = &output
+ cmd.Stderr = &output
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ if err := cmd.Start(); err != nil {
+ return output.Bytes(), err
+ }
+
+ done := make(chan error, 1)
+ go func() {
+ done <- cmd.Wait()
+ }()
+
+ select {
+ case err := <-done:
+ return output.Bytes(), err
+ case <-ctx.Done():
+ // Let the helper shell handle TERM and run its EXIT cleanup. If CMake
+ // or a compiler child does not exit promptly, kill the entire group.
+ _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
+ <-done
+ }
+ return output.Bytes(), ctx.Err()
}
- return os.WriteFile(dst, data, 0644)
}
func findProviderBinary() string {
diff --git a/libs/mlx-swift b/libs/mlx-swift
index df1fdc5f78..db9b77da44 160000
--- a/libs/mlx-swift
+++ b/libs/mlx-swift
@@ -1 +1 @@
-Subproject commit df1fdc5f7821a1fabe921fdefbc42ac74dcfb6bc
+Subproject commit db9b77da44735dd94e2f8737355c3056464b56ca
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index abd1985637..53e8ccd4e1 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit abd1985637d68292f440122fbb390c583ce37a60
+Subproject commit 53e8ccd4e1ba5f51da6ad3254115b59547151e1b
diff --git a/provider-swift/README.md b/provider-swift/README.md
index acb6ce67e4..d7ee50f927 100644
--- a/provider-swift/README.md
+++ b/provider-swift/README.md
@@ -12,11 +12,15 @@ This package is **CLI-only**: no SwiftUI app, no `.app` bundle, no DMG.
## Build & test
```bash
-swift test
-swift build -c release
-# Outputs:
-# .build/release/darkbloom
-# .build/release/darkbloom-enclave
+# From the repository root. These targets build first, stage the matching
+# source-built metallib at every runtime path, and then run tests skip-build.
+make provider-test
+make provider-build
+
+# Optimized local binary:
+cd provider-swift && swift build -c release && cd ..
+./scripts/fetch-metallib.sh release
+# Outputs include provider-swift/.build/release/{darkbloom,mlx.metallib}.
```
The package depends on local submodules at `../libs/mlx-swift` and `../libs/mlx-swift-lm`. Make sure they are checked out:
@@ -30,19 +34,23 @@ git submodule update --init --recursive
`mlx-swift`'s `Cmlx` target does **not** auto-compile its Metal kernels through SwiftPM. The runtime needs an `mlx.metallib` file colocated with the binary (or inside the binary's resource bundle), or it crashes on the first MLX call with `Failed to load the default metallib`.
-Until we land a SwiftPM build-tool plugin for this, the workaround is to ship the matching `mlx.metallib` from the MLX Python wheel that pins the same C++ ABI as the fork (currently `mlx==0.31.2`). For local dev, the simplest setup is:
+The canonical helper builds the metallib from the exact nested MLX source used
+by `Cmlx` (`libs/mlx-swift/Source/Cmlx/mlx`), with Metal JIT disabled and the
+required deployment target and kernel completeness checks. It never extracts a
+Python wheel:
```bash
-python3 -m venv /tmp/mlxvenv
-/tmp/mlxvenv/bin/pip install 'mlx==0.31.2'
-cp /tmp/mlxvenv/lib/python*/site-packages/mlx/lib/mlx.metallib \
- .build/release/mlx.metallib
+# From the repository root, after the corresponding Swift build:
+./scripts/fetch-metallib.sh debug
+./scripts/fetch-metallib.sh release
-# Then:
-.build/release/darkbloom serve --foreground
+provider-swift/.build/release/darkbloom serve --foreground
```
-`release-swift.yml` in CI does the same thing automatically and bakes the metallib into the released bundle next to `darkbloom`.
+The helper also accepts an absolute destination directory and
+`METALLIB_CACHE_DIR`; local, integration, CI, and release paths use this same
+source-matched builder. Release packaging colocates the resulting metallib with
+`darkbloom`.
## Layout
@@ -110,6 +118,6 @@ Done in v0.5.0:
Still pending:
- [ ] Phase 4b: true continuous batching (deferrable past cutover; today's `BatchScheduler` does prefill-serial + decode-concurrent on a single ModelContainer).
-- [ ] Phase 0: SwiftPM build-tool plugin to produce `mlx.metallib` directly from `libs/mlx-swift/Source/Cmlx/mlx-generated/metal/`. Today's local-dev workflow uses `scripts/fetch-metallib.sh` and CI uses the wheel-extraction step in `release-swift.yml`.
+- [ ] Phase 0: SwiftPM build-tool plugin to produce `mlx.metallib` directly from `libs/mlx-swift/Source/Cmlx/mlx`. Until then, local development and CI use the canonical source builder at `scripts/fetch-metallib.sh`.
- [ ] First-class `metallib_hash` field on `protocol.RegisterMessage` and `protocol.AttestationResponseMessage` (today it rides as a key inside `template_hashes`, which the coordinator stores but does not enforce).
- [ ] Build-time injection of `ProviderCore.version` from a git tag (today it is a hand-bumped constant; CI consumes it as-is).
diff --git a/provider-swift/Sources/ProviderBenchmark/ArrivalInvarianceBenchmark.swift b/provider-swift/Sources/ProviderBenchmark/ArrivalInvarianceBenchmark.swift
index 79d1d54520..209a91e521 100644
--- a/provider-swift/Sources/ProviderBenchmark/ArrivalInvarianceBenchmark.swift
+++ b/provider-swift/Sources/ProviderBenchmark/ArrivalInvarianceBenchmark.swift
@@ -183,7 +183,6 @@ public enum ArrivalInvarianceBenchmark {
let engine = try await makeEngine(
container: container,
- modelDirectory: modelDirectory,
isVLM: isVLM,
weightBytes: facts.weightBytes,
maxConcurrentRequests: patterns.map(\.delaysMs.count).max() ?? 1
@@ -477,7 +476,6 @@ public enum ArrivalInvarianceBenchmark {
private static func makeEngine(
container: ModelContainer,
- modelDirectory: URL,
isVLM: Bool,
weightBytes: Int,
maxConcurrentRequests: Int
@@ -493,8 +491,7 @@ public enum ArrivalInvarianceBenchmark {
let parts = try await container.perform { context -> EngineParts in
let servingModel = try EngineV2Factory.benchmarkServingModel(
model: context.model,
- isVLM: isVLM,
- modelDirectory: modelDirectory
+ isVLM: isVLM
)
return EngineParts(engine: try EngineV2Factory.makeProductionEngine(
model: servingModel,
diff --git a/provider-swift/Sources/ProviderBenchmark/MTPProductionSession.swift b/provider-swift/Sources/ProviderBenchmark/MTPProductionSession.swift
index 33e4c609c2..072f0dbb50 100644
--- a/provider-swift/Sources/ProviderBenchmark/MTPProductionSession.swift
+++ b/provider-swift/Sources/ProviderBenchmark/MTPProductionSession.swift
@@ -5,9 +5,9 @@ import MLXVLM
import ProviderCore
/// Cache-only model bundle for MTP validation. It loads the target through the
-/// same model factories as serving, resolves the exact VLM text model through
-/// ProviderCore's production extraction seam, and loads/binds the real Gemma 4
-/// assistant. It never downloads and never contains a decoder implementation.
+/// same model factories as serving, resolves the exact VLM-owned text tower,
+/// and loads/binds the real Gemma 4 assistant. It never downloads and never
+/// contains a decoder implementation.
public final class MTPProductionModelBundle: @unchecked Sendable {
public let targetID: String
public let assistantID: String
@@ -106,8 +106,7 @@ public final class MTPProductionModelBundle: @unchecked Sendable {
convertTokenToID: { snapshot.tokenizer.convertTokenToId($0) })
let servingModel = try EngineV2Factory.benchmarkServingModel(
model: snapshot.model,
- isVLM: isVLM,
- modelDirectory: targetDirectory)
+ isVLM: isVLM)
guard let target = servingModel as? any Gemma4MTPTarget else {
throw MTPBenchmarkError.mtpRequestedButInactive(
"target model \(type(of: servingModel)) is not Gemma4MTPTarget")
diff --git a/provider-swift/Sources/ProviderBenchmark/SchedulerPrefillBenchmark.swift b/provider-swift/Sources/ProviderBenchmark/SchedulerPrefillBenchmark.swift
index 7629519fac..e4c8c75f8c 100644
--- a/provider-swift/Sources/ProviderBenchmark/SchedulerPrefillBenchmark.swift
+++ b/provider-swift/Sources/ProviderBenchmark/SchedulerPrefillBenchmark.swift
@@ -54,8 +54,8 @@ public enum SchedulerPrefillBenchmark {
log("loading model \(modelID)")
log(" path: \(modelDirectory.path)")
- // VLM checkpoints load via the VLM factory and measure through the
- // weight-sharing extracted text model (production serving path).
+ // VLM checkpoints load via the VLM factory and measure the exact
+ // text tower owned by the wrapper (the production serving path).
let isVLM = ThroughputSweep.readHasVisionConfig(modelDirectory: modelDirectory)
let container: ModelContainer
if isVLM {
@@ -83,8 +83,7 @@ public enum SchedulerPrefillBenchmark {
promptTokens: min(lengths.first ?? 128, 128),
iteration: 0,
weightBytes: facts.weightBytes,
- isVLM: isVLM,
- modelDirectory: modelDirectory
+ isVLM: isVLM
)
var samples: [SchedulerPrefillBenchmarkReport.Sample] = []
@@ -96,8 +95,7 @@ public enum SchedulerPrefillBenchmark {
promptTokens: length,
iteration: iteration,
weightBytes: facts.weightBytes,
- isVLM: isVLM,
- modelDirectory: modelDirectory
+ isVLM: isVLM
)
log(" \(strategyLabel) L=\(length) i=\(iteration): \(String(format: "%.3f", sample.msPerPrefillToken)) ms/t (\(String(format: "%.1f", sample.ttftMs)) ms)")
samples.append(sample)
@@ -120,8 +118,7 @@ public enum SchedulerPrefillBenchmark {
promptTokens: Int,
iteration: Int,
weightBytes: Int,
- isVLM: Bool,
- modelDirectory: URL?
+ isVLM: Bool
) async throws -> SchedulerPrefillBenchmarkReport.Sample {
// Same KV-ceiling derivation as a single-model serving slot; far
// above what one row needs, so admission never binds.
@@ -133,7 +130,7 @@ public enum SchedulerPrefillBenchmark {
UInt64(Int.max)))
let engine = try await container.perform { ctx -> any CBv2Engine in
let servingModel = try EngineV2Factory.benchmarkServingModel(
- model: ctx.model, isVLM: isVLM, modelDirectory: modelDirectory)
+ model: ctx.model, isVLM: isVLM)
return try EngineV2Factory.makeProductionEngine(
model: servingModel,
tokenizer: ctx.tokenizer,
diff --git a/provider-swift/Sources/ProviderBenchmark/ThroughputSweep.swift b/provider-swift/Sources/ProviderBenchmark/ThroughputSweep.swift
index 1f18b41b93..2d85465d21 100644
--- a/provider-swift/Sources/ProviderBenchmark/ThroughputSweep.swift
+++ b/provider-swift/Sources/ProviderBenchmark/ThroughputSweep.swift
@@ -59,9 +59,8 @@ public enum ThroughputSweep {
log("loading model \(modelID)")
log(" path: \(modelDirectory.path)")
- // VLM checkpoints (config declares `vision_config`) load through the
- // VLM factory and serve through the weight-sharing extracted text
- // model — the same construction every production slot performs.
+ // VLM checkpoints load through the VLM factory and serve through the
+ // exact text tower owned by that wrapper, matching production.
let isVLM = readHasVisionConfig(modelDirectory: modelDirectory)
let container: ModelContainer
if isVLM {
@@ -99,8 +98,7 @@ public enum ThroughputSweep {
decodePromptTokens: decodePromptTokens,
iterations: decodeIterations,
weightBytes: facts.weightBytes,
- isVLM: isVLM,
- modelDirectory: modelDirectory
+ isVLM: isVLM
)
// One median sample per batch size: the B=1 implied read and the
@@ -207,8 +205,7 @@ public enum ThroughputSweep {
decodePromptTokens: Int,
iterations: Int,
weightBytes: Int,
- isVLM: Bool,
- modelDirectory: URL?
+ isVLM: Bool
) async -> [ThroughputSweepReport.DecodeSample] {
let sizes = batchSizes.filter { $0 > 0 }.sorted()
guard !sizes.isEmpty else { return [] }
@@ -222,7 +219,7 @@ public enum ThroughputSweep {
await runDecodeBatch(
container: container, modelID: modelID, baseTokens: baseTokens,
batchSize: 1, decodeTokens: 4, promptLen: promptLen, weightBytes: weightBytes,
- isVLM: isVLM, modelDirectory: modelDirectory)
+ isVLM: isVLM)
var samples: [ThroughputSweepReport.DecodeSample] = []
for iteration in 1 ... repetitions {
@@ -230,7 +227,7 @@ public enum ThroughputSweep {
let (totalTokens, maxElapsed) = await runDecodeBatch(
container: container, modelID: modelID, baseTokens: baseTokens,
batchSize: batchSize, decodeTokens: genTokens, promptLen: promptLen,
- weightBytes: weightBytes, isVLM: isVLM, modelDirectory: modelDirectory)
+ weightBytes: weightBytes, isVLM: isVLM)
let secs = seconds(maxElapsed)
let aggregate = secs > 0 ? Double(totalTokens) / secs : 0
let perSeq = aggregate / Double(batchSize)
@@ -261,8 +258,7 @@ public enum ThroughputSweep {
decodeTokens: Int,
promptLen: Int,
weightBytes: Int,
- isVLM: Bool,
- modelDirectory: URL?
+ isVLM: Bool
) async -> (totalTokens: Int, maxElapsed: Duration) {
// The engine's KV admission ceiling: the same unified-memory budget a
// single-model provider slot would be granted. Far above what these
@@ -280,10 +276,10 @@ public enum ThroughputSweep {
let parts: EngineParts
do {
parts = try await container.perform { ctx -> EngineParts in
- // Serving-model resolution: VLM checkpoints run the
- // weight-sharing text extraction, exactly like a slot build.
+ // Serving-model resolution matches production: VLM checkpoints
+ // use the exact text tower owned by the loaded wrapper.
let servingModel = try EngineV2Factory.benchmarkServingModel(
- model: ctx.model, isVLM: isVLM, modelDirectory: modelDirectory)
+ model: ctx.model, isVLM: isVLM)
return EngineParts(
engine: try EngineV2Factory.makeProductionEngine(
model: servingModel,
@@ -415,8 +411,8 @@ public enum ThroughputSweep {
return (sorted[middle - 1] + sorted[middle]) / 2
}
- /// Whether the checkpoint's config.json declares a `vision_config`
- /// (VLM — load via the VLM factory, serve via the text extraction).
+ /// Whether config.json declares `vision_config` (load through VLMModelFactory
+ /// and serve through the wrapper-owned text tower).
static func readHasVisionConfig(modelDirectory: URL) -> Bool {
let url = modelDirectory.appendingPathComponent("config.json")
guard let data = try? Data(contentsOf: url),
diff --git a/provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift b/provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift
index 828a7852dc..1d00f48b01 100644
--- a/provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift
+++ b/provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift
@@ -1,6 +1,6 @@
import Foundation
-/// A user-facing opt-in *beta* feature.
+/// A user-facing configurable *beta* feature.
///
/// Beta features are intentionally **config-backed**, not environment-variable
/// backed: the launchd daemon started by `darkbloom start` only inherits a tiny
@@ -55,13 +55,49 @@ public struct BetaFeature: Sendable, Identifiable {
}
}
-/// The registry of opt-in beta features.
+/// The registry of configurable beta features.
///
/// Adding a beta toggle = adding one ``BetaFeature`` entry here (and its backing
-/// `ProviderConfig` field). The `darkbloom beta` command and `darkbloom status`
-/// are driven entirely off this list, so they need no per-feature code.
+/// `ProviderConfig` field). Features declare their own defaults; the
+/// `darkbloom beta` command and `darkbloom status` are driven entirely off this
+/// list, so they need no per-feature code.
public enum BetaFeatures {
public static let all: [BetaFeature] = [
+ BetaFeature(
+ id: "gemma-prefill-layer18",
+ title: "Gemma layer-18 prefill submission",
+ summary: "Default ON. Submit prefill work every 18 layers; disable for legacy submission behavior.",
+ details: """
+ Default ON for existing and new configs. Writes prefill_layer18 \
+ under [gemma_optimizations]; provider config is authoritative over \
+ the low-level process environment. Restart after changing it. \
+ Disable and restart to restore the legacy one-final-submission \
+ prefill behavior.
+ """,
+ requiresRestart: true,
+ read: { $0.gemmaOptimizations.prefillLayer18 },
+ write: { enabled, config in
+ config.gemmaOptimizations.prefillLayer18 = enabled
+ }
+ ),
+ BetaFeature(
+ id: "gemma-weighted-r1",
+ title: "Gemma weighted unsort + safe R1",
+ summary: "Default ON. Coupled weighted-unsort and safe-R1 expert paths with one rollback.",
+ details: """
+ Default ON for existing and new configs. Writes weighted_r1 under \
+ [gemma_optimizations]. This single production control keeps direct \
+ weighted expert reduction coupled to the safe exact-shape R1 QMM \
+ path; neither half can be selected independently. Provider config \
+ is authoritative over the low-level process environment. Disable \
+ and restart to restore both legacy paths together.
+ """,
+ requiresRestart: true,
+ read: { $0.gemmaOptimizations.weightedR1 },
+ write: { enabled, config in
+ config.gemmaOptimizations.weightedR1 = enabled
+ }
+ ),
BetaFeature(
id: "kv-quant",
title: "KV-cache quantization",
diff --git a/provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift b/provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift
new file mode 100644
index 0000000000..6d2ec02bdd
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift
@@ -0,0 +1,89 @@
+import Darwin
+
+/// Projects the config-backed Gemma controls into the low-level environment
+/// consumed while MLX and MLX-LM initialize process-wide optimization state.
+public enum GemmaOptimizationEnvironment {
+ public static let prefillLayer18Key = "DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL"
+ public static let weightedUnsortKey = "MLX_GEMMA4_FUSED_WEIGHTED_UNSORT"
+ public static let safeR1Key = "MLX_GATHER_QMM_EXPERT_SLICES"
+
+ /// Return the complete production projection for `settings`.
+ ///
+ /// Weighted unsort and safe R1 always receive the same value: production
+ /// never exposes either half of the benchmark-selected pair independently.
+ public static func projection(
+ for settings: GemmaOptimizationSettings
+ ) -> [String: String] {
+ let weightedR1 = settings.weightedR1 ? "1" : "0"
+ return [
+ prefillLayer18Key: settings.prefillLayer18 ? "18" : "0",
+ weightedUnsortKey: weightedR1,
+ safeR1Key: weightedR1,
+ ]
+ }
+
+ /// Raised when the process refuses one or more projected controls.
+ ///
+ /// Weighted unsort and safe R1 are process-start latches, so a projection
+ /// that only partially applied leaves the coupled pair in a state no
+ /// benchmark ever measured. Callers must abort startup instead of
+ /// continuing on the surviving half.
+ public struct ApplicationFailure: Error, Equatable, CustomStringConvertible {
+ /// Rejected keys, sorted, so the message is stable across runs.
+ public let keys: [String]
+ /// `errno` reported by the first rejected key.
+ public let code: Int32
+
+ public init(keys: [String], code: Int32) {
+ self.keys = keys
+ self.code = code
+ }
+
+ public var description: String {
+ let reason = strerror(code).map { String(cString: $0) }
+ ?? "errno \(code)"
+ return """
+ failed to apply Gemma optimization controls \
+ [\(keys.joined(separator: ", "))]: \(reason)
+ """
+ }
+ }
+
+ /// Apply the complete projection to the current process.
+ ///
+ /// Config is authoritative, so every key is overwritten even when the
+ /// launching shell supplied a conflicting low-level value. Throws
+ /// `ApplicationFailure` if the environment rejects any key.
+ public static func apply(_ settings: GemmaOptimizationSettings) throws {
+ try apply(settings) { name, value, overwrite in
+ errno = 0
+ guard setenv(name, value, overwrite) == 0 else {
+ return errno == 0 ? EINVAL : errno
+ }
+ return 0
+ }
+ }
+
+ /// Apply every projected key, then report all rejections at once.
+ ///
+ /// - Parameter set: applies one key and returns `0` on success or the
+ /// failing `errno` otherwise.
+ static func apply(
+ _ settings: GemmaOptimizationSettings,
+ set: (_ name: String, _ value: String, _ overwrite: Int32) -> Int32
+ ) throws {
+ var rejected: [String] = []
+ var code: Int32 = 0
+ // Sorted so a failure reports the same keys regardless of the
+ // dictionary's per-process hash ordering.
+ for (name, value) in projection(for: settings).sorted(by: { $0.key < $1.key }) {
+ let status = set(name, value, 1)
+ guard status != 0 else { continue }
+ rejected.append(name)
+ if code == 0 { code = status }
+ }
+ guard rejected.isEmpty else {
+ throw ApplicationFailure(keys: rejected, code: code)
+ }
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/Config/GemmaOptimizationSettings.swift b/provider-swift/Sources/ProviderCore/Config/GemmaOptimizationSettings.swift
new file mode 100644
index 0000000000..52957b8c77
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/Config/GemmaOptimizationSettings.swift
@@ -0,0 +1,36 @@
+/// Production controls for the benchmark-selected Gemma optimization stack.
+///
+/// Both controls default on so provider configs written before these keys were
+/// introduced receive the selected stack. Operators can roll either part back
+/// in `provider.toml`; the change takes effect after the provider restarts.
+public struct GemmaOptimizationSettings: Sendable, Equatable, Codable {
+ /// Submit prefill work every 18 Gemma transformer layers.
+ public var prefillLayer18: Bool
+
+ /// Enable the coupled weighted-unsort and safe-R1 expert paths.
+ ///
+ /// These paths intentionally share one production control. Exposing them
+ /// independently could select a combination that was not benchmarked.
+ public var weightedR1: Bool
+
+ public init(
+ prefillLayer18: Bool = true,
+ weightedR1: Bool = true
+ ) {
+ self.prefillLayer18 = prefillLayer18
+ self.weightedR1 = weightedR1
+ }
+
+ enum CodingKeys: String, CodingKey {
+ case prefillLayer18 = "prefill_layer18"
+ case weightedR1 = "weighted_r1"
+ }
+
+ public init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ self.prefillLayer18 = try container.decodeIfPresent(
+ Bool.self, forKey: .prefillLayer18) ?? true
+ self.weightedR1 = try container.decodeIfPresent(
+ Bool.self, forKey: .weightedR1) ?? true
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift b/provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift
index b648e9c7a6..995b179c1b 100644
--- a/provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift
+++ b/provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift
@@ -10,6 +10,7 @@
/// - Backend settings (port, model, continuous batching, idle timeout)
/// - Coordinator connection settings (URL, heartbeat interval)
/// - Scheduling windows
+/// - Config-backed Gemma optimization controls
///
/// A default config is generated based on detected hardware when the provider
/// is first initialized. CLI flags can override config values at runtime.
@@ -298,17 +299,28 @@ public struct ProviderConfig: Sendable, Equatable, Codable {
public var backend: BackendSettings
public var coordinator: CoordinatorSettings
public var schedule: ScheduleConfig?
+ public var gemmaOptimizations: GemmaOptimizationSettings
public init(
provider: ProviderSettings,
backend: BackendSettings = BackendSettings(),
coordinator: CoordinatorSettings = CoordinatorSettings(),
- schedule: ScheduleConfig? = nil
+ schedule: ScheduleConfig? = nil,
+ gemmaOptimizations: GemmaOptimizationSettings = GemmaOptimizationSettings()
) {
self.provider = provider
self.backend = backend
self.coordinator = coordinator
self.schedule = schedule
+ self.gemmaOptimizations = gemmaOptimizations
+ }
+
+ enum CodingKeys: String, CodingKey {
+ case provider
+ case backend
+ case coordinator
+ case schedule
+ case gemmaOptimizations = "gemma_optimizations"
}
public init(from decoder: Decoder) throws {
@@ -317,6 +329,9 @@ public struct ProviderConfig: Sendable, Equatable, Codable {
self.backend = try container.decodeIfPresent(BackendSettings.self, forKey: .backend) ?? BackendSettings()
self.coordinator = try container.decodeIfPresent(CoordinatorSettings.self, forKey: .coordinator) ?? CoordinatorSettings()
self.schedule = try container.decodeIfPresent(ScheduleConfig.self, forKey: .schedule)
+ self.gemmaOptimizations = try container.decodeIfPresent(
+ GemmaOptimizationSettings.self, forKey: .gemmaOptimizations
+ ) ?? GemmaOptimizationSettings()
}
/// Generate a default config based on detected hardware.
diff --git a/provider-swift/Sources/ProviderCore/Inference/EngineV2Config.swift b/provider-swift/Sources/ProviderCore/Inference/EngineV2Config.swift
index ad56f5813f..99bb66007d 100644
--- a/provider-swift/Sources/ProviderCore/Inference/EngineV2Config.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/EngineV2Config.swift
@@ -82,9 +82,6 @@ public enum EngineV2RefusalReason: String, Sendable {
/// (`EngineV2ProductionError.unsupportedModel`) — should be unreachable
/// behind the scan-time supported-set gate; kept as loud insurance.
case unsupportedModel = "unsupported_model"
- /// The Gemma 4 VLM text-model extraction failed (config decode, weight
- /// re-key, verify, or the forward-parity gate).
- case vlmExtractionFailed = "vlm_extraction_failed"
/// A load-time KV re-slice would push some co-resident slot below the
/// minimum serviceable grant (`EngineV2KVSizing` floor).
case resliceFloor = "reslice_floor"
@@ -98,8 +95,6 @@ public enum EngineV2RefusalReason: String, Sendable {
return .noKVHeadroom
case EngineV2ProductionError.unsupportedModel:
return .unsupportedModel
- case is EngineV2VLMTextExtractionError:
- return .vlmExtractionFailed
default:
return .engineInitFailed
}
diff --git a/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Benchmark.swift b/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Benchmark.swift
index 3f29226cb4..4c80e0fc8e 100644
--- a/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Benchmark.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Benchmark.swift
@@ -1,33 +1,20 @@
// Copyright © 2026 Eigen Labs.
//
-// Benchmark-facing seam: the perf-gate harness (`ProviderBenchmark`'s
-// ThroughputSweep / SchedulerPrefillBenchmark) must measure the SERVING
-// model — for Gemma 4 VLM checkpoints that is the weight-sharing
-// CBv2-adapted text model produced by `EngineV2VLMTextExtraction`, exactly
-// as `EngineV2SlotFactory.makeProductionBridge` builds it. Without this the
-// sweep would hand the raw VLM wrapper to `makeProductionEngine` and refuse
-// (`unsupportedModel`), measuring nothing.
+// Benchmark-facing seam: perf harnesses must measure the exact module served
+// in production. Gemma 4 VLM checkpoints expose their directly owned
+// `Gemma4TextModel`; no extraction, re-keying, or second module is involved.
-import Foundation
import MLXLMCommon
extension EngineV2Factory {
/// Resolve the CBv2-serving model for a loaded checkpoint: the model
- /// itself for text checkpoints, the weight-sharing extracted text model
- /// for VLM checkpoints (zero extra weight memory; load-time parity gate
- /// included — throws on any extraction/verify failure).
+ /// itself for text checkpoints, or the exact VLM-owned text tower for
+ /// Gemma 4 VLM checkpoints.
public static func benchmarkServingModel(
model: any LanguageModel,
- isVLM: Bool,
- modelDirectory: URL?
+ isVLM: Bool
) throws -> any LanguageModel {
- guard isVLM else { return model }
- guard let modelDirectory else {
- throw EngineV2VLMTextExtractionError.missingModelDirectory
- }
- return try EngineV2VLMTextExtraction.extractTextModel(
- from: model, modelDirectory: modelDirectory
- ).model
+ try directServingModel(model: model, isVLM: isVLM)
}
}
diff --git a/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Production.swift b/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Production.swift
index b5c1756efb..1256ae940e 100644
--- a/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Production.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Production.swift
@@ -32,14 +32,14 @@ import Foundation
import MLX
import MLXLLM
import MLXLMCommon
+import MLXVLM
/// Failure modes of production v2-engine construction. Each maps to the
/// factory's REFUSAL path (ERROR `engine_v2_refusal` telemetry + throw).
enum EngineV2ProductionError: Error, CustomStringConvertible {
/// The loaded module is not a CBv2-adapted family (an unexpected
- /// architecture). Allowlisted Gemma 4 VLM wrappers do NOT land here —
- /// the slot factory extracts their CBv2-adapted text model first
- /// (`EngineV2VLMTextExtraction`) and hands THAT to this factory.
+ /// architecture). Gemma 4 VLM wrappers are resolved to their directly
+ /// owned text tower before engine construction.
case unsupportedModel(String)
/// No KV byte budget is left under the unified-memory cap — an engine
/// admitted with a zero ceiling would reject every request, so the
@@ -57,6 +57,20 @@ enum EngineV2ProductionError: Error, CustomStringConvertible {
}
extension EngineV2Factory {
+ /// Resolve the exact module instance served by CBv2. Gemma 4 VLM owns
+ /// its `Gemma4TextModel`; direct VLM forwards and CBv2 therefore share
+ /// one language tower, one parameter tree, and one residency footprint.
+ static func directServingModel(
+ model: any LanguageModel, isVLM: Bool
+ ) throws -> any LanguageModel {
+ guard isVLM else { return model }
+ guard let gemma4 = model as? MLXVLM.Gemma4 else {
+ throw EngineV2ProductionError.unsupportedModel(
+ String(describing: type(of: model)))
+ }
+ return gemma4.textModel
+ }
+
/// Clamp a KV admission ceiling to physical unified memory. A ceiling
/// above physical RAM can only come from a mis-derivation upstream; the
@@ -129,8 +143,8 @@ extension EngineV2Factory {
/// Build the real `EngineV2` over a loaded model.
///
/// - Parameters:
- /// - model: the loaded language module (the SAME instance the legacy
- /// engine serves — weights are shared, never duplicated).
+ /// - model: the loaded serving language module; for Gemma 4 VLM this
+ /// is the exact text tower owned by the wrapper.
/// - tokenizer: the model's tokenizer, for incremental detokenization.
/// - kvBytesCapacity: admission ceiling for live sequence KV, in bytes
/// (derive from `UnifiedMemoryCap.kvBudgetBytes`).
diff --git a/provider-swift/Sources/ProviderCore/Inference/EngineV2SlotFactory+MTP.swift b/provider-swift/Sources/ProviderCore/Inference/EngineV2SlotFactory+MTP.swift
index ecd3a7484f..e5c7d1ee01 100644
--- a/provider-swift/Sources/ProviderCore/Inference/EngineV2SlotFactory+MTP.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/EngineV2SlotFactory+MTP.swift
@@ -1,4 +1,3 @@
-import Foundation
import MLXLMCommon
/// Model handle + EOS config snapshot pulled out of `ModelContainer.perform`.
@@ -9,8 +8,8 @@ struct EngineV2ModelSnapshot: @unchecked Sendable {
let extraEOSTokens: [String]
}
-/// Target extraction plus fail-open assistant preparation, completed before KV
-/// re-slicing so final sizing uses retained assistant bytes.
+/// Direct serving-target resolution plus fail-open assistant preparation,
+/// completed before KV re-slicing so sizing uses retained assistant bytes.
struct EngineV2PreparedModel: @unchecked Sendable {
let snapshot: EngineV2ModelSnapshot
let servingModel: any LanguageModel
@@ -45,45 +44,31 @@ extension EngineV2SlotFactory {
private static func servingModel(
modelId: String,
isVLM: Bool,
- modelDirectory: URL?,
snapshot: EngineV2ModelSnapshot,
emitTelemetry: (@Sendable (TelemetryEvent) -> Void)?,
logInfo: @escaping @Sendable (String) -> Void
) throws -> any LanguageModel {
guard isVLM else { return snapshot.model }
- guard let modelDirectory else {
- let error = EngineV2VLMTextExtractionError.missingModelDirectory
- EngineV2Factory.emitRefusalTelemetry(
- modelId: modelId,
- reason: .vlmExtractionFailed,
- error: error,
- emitTelemetry: emitTelemetry)
- throw error
- }
- let extraction: EngineV2VLMTextExtraction.Extraction
do {
- extraction = try EngineV2VLMTextExtraction.extractTextModel(
- from: snapshot.model, modelDirectory: modelDirectory)
+ let target = try EngineV2Factory.directServingModel(
+ model: snapshot.model, isVLM: true)
+ logInfo(
+ "engine_v2: \(modelId) using the Gemma 4 VLM-owned text tower "
+ + "directly (shared identity and residency)")
+ return target
} catch {
EngineV2Factory.emitRefusalTelemetry(
modelId: modelId,
- reason: .vlmExtractionFailed,
+ reason: EngineV2RefusalReason.classify(error),
error: error,
emitTelemetry: emitTelemetry)
throw error
}
- if let parityDiff = extraction.parityMaxAbsLogitDiff {
- logInfo(
- "engine_v2: \(modelId) VLM text-model extraction passed the "
- + "load-time forward parity gate (max |Δlogit| \(parityDiff))")
- }
- return extraction.model
}
static func prepareProductionModel(
modelId: String,
isVLM: Bool,
- modelDirectory: URL?,
container: ModelContainer,
specDecPreparation: SpecDecPreparation,
assistantLoader: any ProviderMTPAssistantLoading = Gemma4ProviderMTPAssistantLoader(),
@@ -95,7 +80,6 @@ extension EngineV2SlotFactory {
let servingModel = try servingModel(
modelId: modelId,
isVLM: isVLM,
- modelDirectory: modelDirectory,
snapshot: snapshot,
emitTelemetry: emitTelemetry,
logInfo: logInfo)
@@ -153,7 +137,6 @@ extension EngineV2SlotFactory {
static func prepareRecoveryModel(
modelId: String,
isVLM: Bool,
- modelDirectory: URL?,
container: ModelContainer,
previousArtifact: SpecDecArtifact?,
previousStatus: MTPActivationStatus,
@@ -192,7 +175,6 @@ extension EngineV2SlotFactory {
let target = try servingModel(
modelId: modelId,
isVLM: isVLM,
- modelDirectory: modelDirectory,
snapshot: snapshot,
emitTelemetry: emitTelemetry,
logInfo: logInfo)
@@ -208,7 +190,6 @@ extension EngineV2SlotFactory {
let target = try servingModel(
modelId: modelId,
isVLM: isVLM,
- modelDirectory: modelDirectory,
snapshot: snapshot,
emitTelemetry: emitTelemetry,
logInfo: logInfo)
diff --git a/provider-swift/Sources/ProviderCore/Inference/EngineV2SlotFactory.swift b/provider-swift/Sources/ProviderCore/Inference/EngineV2SlotFactory.swift
index 9387f767e6..4d6594a1e4 100644
--- a/provider-swift/Sources/ProviderCore/Inference/EngineV2SlotFactory.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/EngineV2SlotFactory.swift
@@ -7,12 +7,11 @@
// slots through THIS one path so the assembly can never drift between
// them: snapshot the loaded module's EOS config out of the container,
// apply the model-specific EOS policy (`ModelEOSPolicy`), build the
-// production CBv2 engine over the loaded module (with the weight-sharing
-// VLM text extraction for Gemma 4 VLM checkpoints), and wrap it in an
-// `EngineV2Bridge` via the fail-loud `EngineV2Factory.makeBridge` (any
-// construction failure emits the ERROR `engine_v2_refusal` telemetry and
-// throws — the caller unloads and maps to a 503; there is no legacy
-// fallback).
+// production CBv2 engine over the loaded module (using the Gemma 4 VLM's
+// directly owned text tower), and wrap it in an `EngineV2Bridge` via the
+// fail-loud `EngineV2Factory.makeBridge` (any construction failure emits the
+// ERROR `engine_v2_refusal` telemetry and throws — the caller unloads and
+// maps to a 503; there is no legacy fallback).
//
// Call-site differences stay at the call sites: the ProviderLoop
// registers the bridge with `EngineV2Runtime` (heartbeat/cancel fan-out)
@@ -21,10 +20,124 @@
// are limited to `makeEngineOverride` (scripted engines, no weights).
import Foundation
+import MLX
import MLXLLM
import MLXLMCommon
import ProviderCoreFoundation
+enum GemmaOptimizationReason: String, Sendable, Equatable {
+ case disabled
+ case modelIneligible = "model_ineligible"
+ case aotUnavailable = "aot_unavailable"
+ case naxPrecedence = "nax_precedence"
+ case effective
+}
+
+struct GemmaOptimizationState: Sendable, Equatable {
+ let name: String
+ let requested: Bool
+ let effective: Bool
+ let reason: GemmaOptimizationReason
+
+ var compactDescription: String {
+ "\(name)(requested=\(requested),effective=\(effective),reason=\(reason.rawValue))"
+ }
+}
+
+/// Pure requested/effective resolution for the three retained Gemma controls.
+/// Safe R1 is inferred from one unarmed device snapshot; this type never
+/// resets, arms, or samples route counters.
+struct GemmaOptimizationReport: Sendable, Equatable {
+ let layer18: GemmaOptimizationState
+ let weightedUnsort: GemmaOptimizationState
+ let safeR1: GemmaOptimizationState
+
+ init(
+ layer18Requested: Bool,
+ layer18Effective: Bool,
+ weightedUnsortRequested: Bool,
+ weightedUnsortEffective: Bool,
+ safeR1Requested: Bool,
+ safeR1GeometryEligible: Bool,
+ safeR1AOTAvailable: Bool,
+ safeR1NAXAvailable: Bool
+ ) {
+ layer18 = Self.resolve(
+ name: "layer18",
+ requested: layer18Requested,
+ modelEligible: layer18Effective)
+ weightedUnsort = Self.resolve(
+ name: "weighted_unsort",
+ requested: weightedUnsortRequested,
+ modelEligible: weightedUnsortEffective)
+ safeR1 = Self.resolve(
+ name: "safe_r1",
+ requested: safeR1Requested,
+ modelEligible: safeR1GeometryEligible,
+ aotAvailable: safeR1AOTAvailable,
+ naxAvailable: safeR1NAXAvailable)
+ }
+
+ var states: [GemmaOptimizationState] {
+ [layer18, weightedUnsort, safeR1]
+ }
+
+ func logLine(modelId: String) -> String {
+ "engine_v2: \(modelId) gemma optimizations "
+ + states.map(\.compactDescription).joined(separator: " ")
+ }
+
+ func telemetryEvents(modelId: String) -> [TelemetryEvent] {
+ states.map { state in
+ var event = TelemetryEvent(
+ source: .provider,
+ severity: .info,
+ kind: .engineHealth,
+ message: "engine_v2: gemma optimization "
+ + state.compactDescription)
+ event.fields = TelemetryFieldFilter.filter([
+ "component": .string("engine"),
+ "operation": .string("gemma_optimization_\(state.name)"),
+ "backend": .string("engine_v2"),
+ "model": .string(modelId),
+ // Existing allowlisted field, carrying the bounded 2-bit
+ // requested/effective state without a telemetry schema change.
+ "target": .string(
+ "requested_\(state.requested ? 1 : 0)_effective_"
+ + "\(state.effective ? 1 : 0)"),
+ "reason": .string(state.reason.rawValue),
+ ])
+ return event
+ }
+ }
+
+ private static func resolve(
+ name: String,
+ requested: Bool,
+ modelEligible: Bool,
+ aotAvailable: Bool? = nil,
+ naxAvailable: Bool = false
+ ) -> GemmaOptimizationState {
+ let reason: GemmaOptimizationReason
+ if !requested {
+ reason = .disabled
+ } else if !modelEligible {
+ reason = .modelIneligible
+ } else if aotAvailable == false {
+ reason = .aotUnavailable
+ } else if naxAvailable {
+ reason = .naxPrecedence
+ } else {
+ reason = .effective
+ }
+ return GemmaOptimizationState(
+ name: name,
+ requested: requested,
+ effective: reason == .effective,
+ reason: reason)
+ }
+}
+
enum EngineV2SlotFactory {
/// Narrow assembly seams for production-order regression tests. Normal
@@ -62,10 +175,9 @@ enum EngineV2SlotFactory {
/// - Parameters:
/// - modelId: catalog id the slot serves under.
/// - modelType: `model_type` from config.json (EOS policy input).
- /// - isVLM: config declares `vision_config` — the engine is built
- /// over `EngineV2VLMTextExtraction`'s weight-sharing text model.
- /// - modelDirectory: checkpoint dir (required for VLM extraction).
- /// - container: the just-loaded model container.
+ /// - isVLM: config declares `vision_config` — the engine directly uses
+ /// the `Gemma4TextModel` owned by the loaded VLM wrapper.
+ /// - modelDirectory: checkpoint dir (prompt-contract identity input).
/// - tokenizer: the container's tokenizer handle.
/// - sizing: scheduler-free sizing snapshot (fp16 KV rate, context,
/// default max tokens).
@@ -88,7 +200,7 @@ enum EngineV2SlotFactory {
/// `ProviderLoop.EngineV2SlotHooks`); nil ⇒ the real
/// `EngineV2Factory.makeProductionEngine`. SSD cache instances and
/// stats logging exist only on the production path.
- /// - logInfo: sink for the VLM parity-gate + cache-state info lines.
+ /// - logInfo: sink for shared-tower + cache-state info lines.
/// - logWarning: sink for the both-tiers-requested WARN line.
static func makeProductionBridge(
modelId: String,
@@ -138,8 +250,7 @@ enum EngineV2SlotFactory {
}
/// Production bundle assembly. Assistant preparation is deliberately
- /// fail-open; target extraction/engine construction retain their existing
- /// fail-loud semantics.
+ /// fail-open; direct target resolution and engine construction fail loud.
static func makeProductionBundle(
modelId: String,
modelType: String?,
@@ -197,7 +308,6 @@ enum EngineV2SlotFactory {
prepared = try await prepareProductionModel(
modelId: modelId,
isVLM: isVLM,
- modelDirectory: modelDirectory,
container: container,
specDecPreparation: SpecDecPreparation(
artifact: nil, status: specDecPreparation.status),
@@ -209,7 +319,6 @@ enum EngineV2SlotFactory {
prepared = try await prepareProductionModel(
modelId: modelId,
isVLM: isVLM,
- modelDirectory: modelDirectory,
container: container,
specDecPreparation: specDecPreparation,
assistantLoader: assistantLoader,
@@ -280,12 +389,9 @@ enum EngineV2SlotFactory {
// only RAM claims are per-request staging reservations in the
// shared `GlobalKVCacheBudget` (refused ⇒ silent recompute).
//
- // VLM slots derive layer kinds from config.json's text_config
- // alone (`EngineV2VLMTextExtraction.cbv2LayerKinds` — drift tests
- // pin config-derived shape == engine truth); the weight-sharing
- // extraction itself still runs inside engine construction. A
- // family with no derivable kinds gets no cache (it would throw
- // unsupportedModel at engine build anyway).
+ // VLM slots use the layer kinds of the exact text tower already
+ // resolved from the loaded wrapper. A family with no adapted serving
+ // model gets no prepared backend and is refused before cache creation.
var ssdPrefixCache: SSDPrefixCache?
var cacheCapability: CBv2PrefixReuseCapability?
var cacheConstructionStatus = PrefixCacheConstructionStatus.configDisabled
@@ -443,6 +549,31 @@ enum EngineV2SlotFactory {
await bridge.startSSDPrefixCacheStatsLogger(cache: ssdPrefixCache)
}
await bridge.configureMTPStatus(mtpStatus)
+ if let gemmaModel = servingModel as? Gemma4TextModel {
+ // One load-time snapshot only. Never arm the benchmark counters in
+ // production: the QMM hot path remains free of counter atomics.
+ let r1 = GPU.gemma4ExpertQMMDiagnostics()
+ let layerInterval = gemmaModel.cbv2PrefillChunkEvalInterval
+ let report = GemmaOptimizationReport(
+ layer18Requested: layerInterval > 0,
+ layer18Effective:
+ layerInterval > 0
+ && gemmaModel.cbv2LayerKinds.count >= layerInterval,
+ weightedUnsortRequested: gemmaModel.weightedExpertUnsortRequested,
+ weightedUnsortEffective: gemmaModel.weightedExpertUnsortEffective,
+ safeR1Requested: r1.requested,
+ safeR1GeometryEligible: gemmaModel.expertQMMGeometryEligible,
+ safeR1AOTAvailable: r1.aotAvailable,
+ safeR1NAXAvailable: r1.naxAvailable)
+ logInfo(report.logLine(modelId: modelId))
+ for event in report.telemetryEvents(modelId: modelId) {
+ if let emitTelemetry {
+ emitTelemetry(event)
+ } else {
+ TelemetryClient.shared.emit(event)
+ }
+ }
+ }
logInfo(
"engine_v2: \(modelId) prefix cache "
+ prefixCacheStateDescription(
diff --git a/provider-swift/Sources/ProviderCore/Inference/EngineV2SupportedModels.swift b/provider-swift/Sources/ProviderCore/Inference/EngineV2SupportedModels.swift
index 2daf109663..91e28fd280 100644
--- a/provider-swift/Sources/ProviderCore/Inference/EngineV2SupportedModels.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/EngineV2SupportedModels.swift
@@ -10,10 +10,9 @@
// declares (the value `ModelScanner.parseModelInfo` stamps on `ModelInfo`):
//
// * `gpt_oss` — GPT-OSS (GPTOSSModel)
-// * `gemma4` — Gemma 4 VLM wrapper
+// * `gemma4` — Gemma 4 VLM wrapper, serving through its directly
+// owned text tower plus vision prefill
// * `gemma4_text` — Gemma 4 text target
-// wrapper (`gemma4`, served via the weight-sharing
-// text-model extraction + vision prefill)
//
// Everything else (gemma3, qwen*, llama, …) has no CBv2 adapter: it is
// dropped from the advertised set at startup and at prefetch-verify time
diff --git a/provider-swift/Sources/ProviderCore/Inference/EngineV2VLMTextExtraction.swift b/provider-swift/Sources/ProviderCore/Inference/EngineV2VLMTextExtraction.swift
deleted file mode 100644
index 16a661f0ff..0000000000
--- a/provider-swift/Sources/ProviderCore/Inference/EngineV2VLMTextExtraction.swift
+++ /dev/null
@@ -1,369 +0,0 @@
-// Copyright © 2026 Eigen Labs.
-//
-// ContinuousBatchingV2 — weight-sharing text-model extraction for VLM slots.
-//
-// Every production Gemma 4 checkpoint ships a vision tower, so the provider
-// loads it through `VLMModelFactory` and the resident module is MLXVLM's
-// `Gemma4` wrapper — whose language model is a PRIVATE inline duplicate of
-// the text architecture ("MLXVLM can't import MLXLLM") with none of the
-// CBv2 hooks (`cbv2LayerKinds` / `newCacheV2`). The v2 engine therefore
-// could never serve a VLM slot directly, and before v0.7.2 the per-slot
-// `isVLM` gate excluded 100% of prod Gemma traffic from engine v2.
-//
-// This file builds the CBv2-adapted MLXLLM `Gemma4TextModel` OVER THE SAME
-// WEIGHT ARRAYS the wrapper already holds:
-//
-// 1. decode the checkpoint's `config.json` `text_config` with MLXLLM's
-// `Gemma4TextConfiguration` decoder and construct a lazy skeleton
-// (nothing is materialized — MLXArray init is lazy until eval);
-// 2. re-apply the checkpoint's quantization STRUCTURE to the skeleton the
-// exact way `loadWeights` did for the wrapper (scales-presence gate +
-// the same per-layer table from `BaseConfiguration`, whose keys live in
-// the checkpoint's `language_model.`-prefixed key space);
-// 3. re-key the wrapper's live parameter tree (`language_model.model.X` →
-// `model.X`, `language_model.lm_head.X` → `lm_head.X`), run it through
-// `Gemma4TextModel.sanitize` (drops shared-KV k/v duplicates the
-// wrapper allocates but the MLXLLM model does not), and
-// `update(parameters:verify:[.all])` — missing/extra/mis-shaped keys
-// all THROW, which the engine factory catches as the standard
-// `engine_v2_refusal` ERROR + load failure (never silent wrongness);
-// 4. run a tiny forward through BOTH the wrapper's text path and the
-// extracted model and require cross-containment of each side's greedy
-// argmax in the other side's top-5, plus a bounded max |Δlogit| — a
-// load-time backstop against catastrophic extraction bugs (see
-// `assertForwardParity` for why bit-parity is structurally
-// unattainable; env `DARKBLOOM_ENGINE_V2_VLM_PARITY_CHECK=0` skips).
-//
-// The result is a SEPARATE module instance (own norms/rope/layer objects)
-// sharing only the immutable parameter arrays — zero extra weight memory,
-// and no module-level mutable state shared with the wrapper, which is what
-// makes the Qwen3.5-mrope class of cross-path state corruption structurally
-// impossible here. Concurrency: the legacy vision forward (wrapper) and v2
-// text forward (extracted model) may interleave on the same arrays; both
-// are read-only over the parameters (forward passes never mutate weights)
-// and each path owns its private KV caches.
-
-import Foundation
-import MLX
-import MLXLLM
-import MLXLMCommon
-import MLXNN
-import MLXVLM
-
-/// Failure modes of VLM text-model extraction. Every case lands in
-/// `EngineV2Factory.makeBridge`'s catch → ERROR `engine_v2_refusal`
-/// telemetry + legacy serving. The messages are operator-facing (they ride
-/// the telemetry `error` field), so they say exactly what to look at.
-enum EngineV2VLMTextExtractionError: Error, CustomStringConvertible {
- /// The loaded module is not a VLM wrapper this extraction understands.
- case unsupportedWrapper(String)
- /// The slot factory could not hand us the model directory (needed for
- /// `config.json`).
- case missingModelDirectory
- /// `config.json` was unreadable or had no decodable `text_config`.
- case invalidConfig(String)
- /// The checkpoint has quantized weights but no `quantization` block in
- /// `config.json` to derive the skeleton's quantization structure from.
- case missingQuantizationConfig
- /// The load-time forward parity gate failed: the extracted text model
- /// disagrees with the wrapper's own text path on the same weights.
- case parityMismatch(String)
-
- var description: String {
- switch self {
- case .unsupportedWrapper(let type):
- return "engine_v2 vlm extraction: unsupported VLM wrapper \(type)"
- case .missingModelDirectory:
- return "engine_v2 vlm extraction: model directory unavailable for config.json"
- case .invalidConfig(let detail):
- return "engine_v2 vlm extraction: config.json unusable (\(detail))"
- case .missingQuantizationConfig:
- return "engine_v2 vlm extraction: quantized weights but no quantization block in config.json"
- case .parityMismatch(let detail):
- return "engine_v2 vlm extraction: wrapper/extracted forward parity failed (\(detail))"
- }
- }
-}
-
-/// Weight-sharing extraction of the CBv2-adapted MLXLLM text model from a
-/// loaded MLXVLM wrapper. Pure functions; no state.
-enum EngineV2VLMTextExtraction {
-
- /// Env kill switch for the load-time forward parity gate ("0"/"false"/
- /// "no"/"off" disables). Default ON — the check is one tiny prefill at
- /// model-load time and is the backstop against silent architecture
- /// drift between MLXVLM's inline text model and MLXLLM's.
- static let parityCheckFlag = "DARKBLOOM_ENGINE_V2_VLM_PARITY_CHECK"
-
- /// Checkpoint key-space prefix of the wrapper's language model. Both the
- /// parameter tree and the per-layer quantization table use it.
- private static let languageModelPrefix = "language_model."
-
- /// Result of one extraction: the CBv2-adapted text model (sharing the
- /// wrapper's weight arrays) plus the parity probe's max |Δlogit| for the
- /// slot factory's log line (nil when the parity gate was disabled).
- struct Extraction {
- let model: Gemma4TextModel
- let parityMaxAbsLogitDiff: Float?
- }
-
- /// Build an MLXLLM `Gemma4TextModel` over the weight arrays of a loaded
- /// MLXVLM `Gemma4` wrapper. See the file header for the full mechanism.
- ///
- /// - Parameters:
- /// - model: the slot's loaded module (must be `MLXVLM.Gemma4`).
- /// - modelDirectory: the checkpoint directory (for `config.json`).
- /// - environment: env snapshot (parity-gate kill switch).
- static func extractTextModel(
- from model: any LanguageModel,
- modelDirectory: URL,
- environment: [String: String] = ProcessInfo.processInfo.environment
- ) throws -> Extraction {
- guard let wrapper = model as? MLXVLM.Gemma4 else {
- throw EngineV2VLMTextExtractionError.unsupportedWrapper(
- String(describing: type(of: model)))
- }
-
- // 1. Text config: decode the checkpoint's `text_config` with the SAME
- // decoder `LLMModelFactory` would use for a text-only checkpoint.
- let configURL = modelDirectory.appendingPathComponent("config.json")
- let configData: Data
- do {
- configData = try Data(contentsOf: configURL)
- } catch {
- throw EngineV2VLMTextExtractionError.invalidConfig(
- "read \(configURL.path): \(error)")
- }
- let textConfig = try decodeTextConfiguration(configData: configData)
-
- // Quantization table: `BaseConfiguration` holds the checkpoint-wide
- // default plus the per-layer overrides, keyed in the checkpoint's
- // `language_model.`-prefixed key space.
- let baseConfig = try? JSONDecoder.json5().decode(BaseConfiguration.self, from: configData)
-
- // 2-3. Lazy skeleton → quantization structure → weight-sharing update.
- let skeleton = Gemma4TextModel(textConfig)
- let textWeights = reKeyedTextWeights(wrapper: wrapper, sanitizer: skeleton)
- try applyQuantizationStructure(
- skeleton: skeleton, weights: textWeights,
- perLayerQuantization: baseConfig?.perLayerQuantization)
- // verify: [.all] — a missing model key, an unused weight key, or a
- // shape mismatch all throw here. That is the design: any drift
- // between the wrapper's parameter tree and the MLXLLM architecture
- // must fail LOUDLY at load (→ engine_v2_refusal ERROR + 503),
- // never produce a silently wrong serving model.
- try skeleton.update(
- parameters: ModuleParameters.unflattened(textWeights), verify: [.all])
-
- // 4. Load-time forward parity gate (env-gated, default on).
- var parityDiff: Float? = nil
- if parityCheckEnabled(environment: environment) {
- // Return the probe's transient buffers to the OS before the load
- // path's post-build admission/headroom reads. The probe's two
- // forwards leave ~GiBs of intermediates in the MLX pool; fence
- // async GPU completion first (M4 IOKit guard), and clean up on
- // the parity-failure throw path too.
- defer {
- MLX.Stream().synchronize()
- MLX.Memory.clearCache()
- }
- parityDiff = try assertForwardParity(
- wrapper: wrapper, extracted: skeleton, vocabSize: textConfig.vocabSize)
- }
-
- return Extraction(model: skeleton, parityMaxAbsLogitDiff: parityDiff)
- }
-
- /// A VLM checkpoint's CBv2 layer kinds from `config.json`'s
- /// `text_config` ALONE — identical to what the extracted text model
- /// reports (the drift tests pin config-derived shape == engine truth).
- /// Used by the slot factory to construct the SSD prefix cache for VLM
- /// slots (layout-epoch + adoption-bound binding) BEFORE the extraction
- /// runs inside engine construction. nil when the config is
- /// unreadable/undecodable — no cache is built (the extraction will
- /// throw on the same config moments later).
- static func cbv2LayerKinds(modelDirectory: URL) -> [CBv2LayerKind]? {
- let configURL = modelDirectory.appendingPathComponent("config.json")
- guard let configData = try? Data(contentsOf: configURL),
- let textConfig = try? decodeTextConfiguration(configData: configData)
- else { return nil }
- return textConfig.cbv2LayerKinds
- }
-
- // MARK: - Steps
-
- /// Decode MLXLLM's `Gemma4TextConfiguration` from the VLM checkpoint's
- /// `text_config` block. The top-level `quantization` block is merged in
- /// so the configuration's informational `quantizationBits`/`GroupSize`
- /// fields reflect the checkpoint (they do not drive the skeleton's
- /// quantization — `applyQuantizationStructure` does).
- static func decodeTextConfiguration(configData: Data) throws -> Gemma4TextConfiguration {
- let root: [String: Any]
- do {
- guard
- let parsed = try JSONSerialization.jsonObject(with: configData)
- as? [String: Any]
- else {
- throw EngineV2VLMTextExtractionError.invalidConfig("config.json is not an object")
- }
- root = parsed
- } catch let error as EngineV2VLMTextExtractionError {
- throw error
- } catch {
- throw EngineV2VLMTextExtractionError.invalidConfig("parse config.json: \(error)")
- }
- guard var textConfigJSON = root["text_config"] as? [String: Any] else {
- throw EngineV2VLMTextExtractionError.invalidConfig("no text_config object")
- }
- if textConfigJSON["quantization"] == nil, let quantization = root["quantization"] {
- textConfigJSON["quantization"] = quantization
- }
- do {
- let textConfigData = try JSONSerialization.data(withJSONObject: textConfigJSON)
- return try JSONDecoder.json5().decode(Gemma4TextConfiguration.self, from: textConfigData)
- } catch {
- throw EngineV2VLMTextExtractionError.invalidConfig("decode text_config: \(error)")
- }
- }
-
- /// Re-key the wrapper's live parameter tree into the text model's key
- /// space and drop everything outside the language model (vision tower,
- /// multimodal embedder). The result then passes through the text
- /// model's own `sanitize`, which drops the k/v-projection duplicates
- /// the wrapper allocates for KV-shared layers (MLXLLM does not allocate
- /// those modules) and leaves everything else untouched.
- private static func reKeyedTextWeights(
- wrapper: MLXVLM.Gemma4, sanitizer: Gemma4TextModel
- ) -> [String: MLXArray] {
- var textWeights: [String: MLXArray] = [:]
- for (key, value) in wrapper.parameters().flattened() {
- guard key.hasPrefix(languageModelPrefix) else { continue }
- textWeights[String(key.dropFirst(languageModelPrefix.count))] = value
- }
- return sanitizer.sanitize(weights: textWeights)
- }
-
- /// Mirror `loadWeights`' quantization pass onto the skeleton: a module is
- /// quantized iff the (re-keyed, live) weights carry `.scales`, with
- /// (groupSize, bits, mode) resolved from the checkpoint's per-layer table
- /// under the module's `language_model.`-prefixed checkpoint key — the
- /// exact lookup the wrapper's own load performed, so the two module trees
- /// can never disagree on quantization structure. All arrays involved stay
- /// lazy; `update(parameters:)` replaces them before anything evaluates.
- private static func applyQuantizationStructure(
- skeleton: Gemma4TextModel,
- weights: [String: MLXArray],
- perLayerQuantization: BaseConfiguration.PerLayerQuantization?
- ) throws {
- let hasQuantizedWeights = weights.keys.contains { $0.hasSuffix(".scales") }
- guard hasQuantizedWeights else { return }
- guard let perLayerQuantization else {
- throw EngineV2VLMTextExtractionError.missingQuantizationConfig
- }
- quantize(model: skeleton) { path, _ in
- guard weights["\(path).scales"] != nil else { return nil }
- return perLayerQuantization
- .quantization(layer: languageModelPrefix + path)?.asTuple
- }
- }
-
- // MARK: - Parity gate
-
- static func parityCheckEnabled(environment: [String: String]) -> Bool {
- guard
- let raw = environment[parityCheckFlag]?
- .trimmingCharacters(in: .whitespaces).lowercased(), !raw.isEmpty
- else { return true }
- return !["0", "false", "no", "off"].contains(raw)
- }
-
- /// Top-k window for the bidirectional argmax-containment check.
- static let parityTopK = 5
- /// Ceiling on max |Δlogit| across the probe. Final logits are
- /// softcapped to ±`final_logit_softcapping` (30 on every Gemma 4
- /// checkpoint), so unrelated distributions differ by up to ~60;
- /// same-weights implementation noise measured ≤ ~8 (see below).
- static let parityMaxAbsLogitDiff: Float = 20
-
- /// One tiny forward through the wrapper's text path and the extracted
- /// model on identical tokens — a CATASTROPHIC-EXTRACTION detector, not
- /// a bit-parity check.
- ///
- /// Token-exact parity between the two is structurally unattainable
- /// (measured on gemma-4-26B-A4B qat-4bit, 2026-07):
- ///
- /// * the two implementations have different bf16 kernel/fusion
- /// orderings, giving ~0.5 max |Δlogit| even at position 0 (where
- /// RoPE is the identity), which flips near-tie top-8-of-128 MoE
- /// expert selections at later positions (~8 max |Δlogit|);
- /// * MLXVLM's wrapper mis-implements the checkpoint's declared
- /// `rope_type: "proportional"` for full-attention layers as an
- /// HF-style truncated-dims partial RoPE (freqs /128, partner +64),
- /// while MLXLLM's `ProportionalRoPE` implements the declared type
- /// (freqs /512 over the full head, partner +256 — verified against
- /// the mlx_lm Python reference). The extracted model keeps the
- /// CORRECT scheme; the wrapper discrepancy is flagged upstream.
- ///
- /// What a correct extraction guarantees — and what this gate enforces —
- /// is that both models compute the same function up to implementation
- /// noise: each side's greedy argmax must sit inside the other side's
- /// top-`parityTopK` at EVERY position, and max |Δlogit| must stay under
- /// `parityMaxAbsLogitDiff`. A mis-extracted model (wrong keys, wrong
- /// quantization structure, wrong config) produces unrelated
- /// distributions and fails both with overwhelming probability. The
- /// probe is fixed and both models are deterministic, so for a given
- /// (checkpoint, binary) the gate either always passes or always fails —
- /// no per-load flakiness.
- private static func assertForwardParity(
- wrapper: MLXVLM.Gemma4, extracted: Gemma4TextModel, vocabSize: Int
- ) throws -> Float {
- // Fixed probe: small ids well inside every Gemma vocab; length stays
- // far under the sliding window so the check exercises both layer
- // types without materializing meaningful KV.
- let probeTokens = [2, 651, 6134, 1024, 578, 108, 2364].map {
- min($0, max(0, vocabSize - 1))
- }
- let inputs = MLXArray(probeTokens.map(Int32.init)).expandedDimensions(axis: 0)
-
- let wrapperLogits = wrapper(inputs, cache: nil).asType(.float32)
- let extractedLogits = extracted(inputs, cache: nil).asType(.float32)
-
- let k = parityTopK
- // Top-k token ids per position, [1, L, k] (unordered within k).
- let wrapperTopK = argPartition(-wrapperLogits, kth: k - 1, axis: -1)[.ellipsis, .. ProviderConfig {
+ try TOMLDecoder().decode(
+ ProviderConfig.self, from: retainedConfigurationTOML)
+ }
+
+ static func validateRetainedProjection(
+ _ projection: [String: String]
+ ) throws {
+ let expected = [
+ GemmaOptimizationEnvironment.prefillLayer18Key: "18",
+ GemmaOptimizationEnvironment.weightedUnsortKey: "1",
+ GemmaOptimizationEnvironment.safeR1Key: "1",
+ ]
+ guard projection == expected else {
+ throw VerificationError.unexpectedProjection(projection)
+ }
+ }
+
+ static func rejectedEnvironmentKeys(
+ projection: [String: String],
+ environment: [String: String]
+ ) -> [String] {
+ projection.compactMap { key, value in
+ environment[key] == value ? nil : key
+ }.sorted()
+ }
+
+ static func validateSafeR1(
+ requested: Bool,
+ aotAvailable: Bool,
+ countersArmed: Bool
+ ) throws {
+ guard requested else { throw VerificationError.safeR1NotRequested }
+ guard aotAvailable else { throw VerificationError.safeR1AOTUnavailable }
+ guard !countersArmed else { throw VerificationError.safeR1CountersArmed }
+ }
+
+ static func containsGemmaOptimizationSuccessMarker(_ output: Data) -> Bool {
+ guard let text = String(data: output, encoding: .utf8) else { return false }
+ return text.split(whereSeparator: \.isNewline).contains {
+ $0 == Substring(gemmaOptimizationSuccessMarker)
+ }
+ }
public static func runPagedKernel(
shapes: [PagedAttentionKernelSmokeShape] =
diff --git a/provider-swift/Sources/ProviderCore/Inference/SlotSizingSnapshot.swift b/provider-swift/Sources/ProviderCore/Inference/SlotSizingSnapshot.swift
index 41fc582d9a..1d3602a682 100644
--- a/provider-swift/Sources/ProviderCore/Inference/SlotSizingSnapshot.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/SlotSizingSnapshot.swift
@@ -116,7 +116,6 @@ public struct SlotSizingSnapshot: Sendable, Equatable {
struct ModuleFacts: @unchecked Sendable {
let bytes: Int
let moduleKVRate: Int?
- let isGemma4VLMWrapper: Bool
}
let facts = await container.perform { ctx -> ModuleFacts in
let bytes = ctx.model.parameters().flattened().reduce(0) { $0 + $1.1.nbytes }
@@ -124,27 +123,24 @@ public struct SlotSizingSnapshot: Sendable, Equatable {
// layer kinds (GPT-OSS derives them from the LOADED trunk, so
// they are congruent with the actual layers even when config.json
// omits `layer_types`).
- var rate: Int? = nil
- var isWrapper = false
+ let rate: Int?
switch ctx.model {
case let gemma as Gemma4TextModel:
rate = fp16KVBytesPerToken(layerKinds: gemma.cbv2LayerKinds)
case let gptoss as GPTOSSModel:
rate = fp16KVBytesPerToken(layerKinds: gptoss.cbv2LayerKinds)
- case is MLXVLM.Gemma4:
- // The VLM wrapper has no CBv2 hooks; its extracted text model
- // does. Derive from the checkpoint's text_config below (the
- // SAME decoder the extraction uses, so the kinds equal what
- // the extracted model will report).
- isWrapper = true
+ case let gemma as MLXVLM.Gemma4:
+ // Direct ownership makes the loaded tower engine truth with
+ // no config re-decode or second topology that can drift.
+ rate = fp16KVBytesPerToken(layerKinds: gemma.textModel.cbv2LayerKinds)
default:
- break
+ rate = nil
}
- return ModuleFacts(bytes: bytes, moduleKVRate: rate, isGemma4VLMWrapper: isWrapper)
+ return ModuleFacts(bytes: bytes, moduleKVRate: rate)
}
- // Architecture metadata (context window + the config-parse fallback
- // rate) from config.json — the same parse the load-gate estimate uses.
+ // Architecture metadata (context window + non-CBv2 fallback rate)
+ // comes from the same config parse the load-gate estimate uses.
let architecture: ModelArchitecture
if let modelPath {
architecture = KVEstimation.parseModelArchitecture(
@@ -154,15 +150,10 @@ public struct SlotSizingSnapshot: Sendable, Equatable {
}
var kvRate = facts.moduleKVRate ?? 0
- if kvRate <= 0, facts.isGemma4VLMWrapper, let modelPath {
- kvRate = gemma4VLMTextKVRate(modelDirectory: modelPath) ?? 0
- }
if kvRate <= 0 {
- // Non-CBv2 module (or a wrapper whose text_config failed to
- // decode): fall back to the config-parse figure so callers that
- // only need a rough rate (vision reservations in tests) still
- // get one. Such a model cannot build a v2 engine and is refused
- // at load — this value never sizes a real engine grant.
+ // Non-CBv2 module: fall back to the config-parse figure so
+ // callers that only need a rough rate still get one. Such a
+ // model cannot build a v2 engine and is refused at load.
kvRate = KVEstimation.resolvedKVBytesPerToken(
architecture: architecture, weightBytes: facts.bytes)
}
@@ -216,16 +207,4 @@ public struct SlotSizingSnapshot: Sendable, Equatable {
return total
}
- /// CBv2 layer kinds for a Gemma 4 VLM checkpoint's TEXT model, decoded
- /// from `config.json`'s `text_config` with the same decoder the
- /// weight-sharing extraction uses (`EngineV2VLMTextExtraction`), so the
- /// kinds equal what the extracted `Gemma4TextModel` will report.
- static func gemma4VLMTextKVRate(modelDirectory: URL) -> Int? {
- let configURL = modelDirectory.appendingPathComponent("config.json")
- guard let configData = try? Data(contentsOf: configURL),
- let textConfig = try? EngineV2VLMTextExtraction.decodeTextConfiguration(
- configData: configData)
- else { return nil }
- return fp16KVBytesPerToken(layerKinds: textConfig.cbv2LayerKinds)
- }
}
diff --git a/provider-swift/Sources/ProviderCore/Process/BoundedProcess.swift b/provider-swift/Sources/ProviderCore/Process/BoundedProcess.swift
index 1cdf0a7613..b16962cc67 100644
--- a/provider-swift/Sources/ProviderCore/Process/BoundedProcess.swift
+++ b/provider-swift/Sources/ProviderCore/Process/BoundedProcess.swift
@@ -31,6 +31,52 @@ enum BoundedProcess {
arguments: [String],
environment: [String: String]? = nil,
timeout: TimeInterval
+ ) throws {
+ try runProcess(
+ executable,
+ arguments: arguments,
+ environment: environment,
+ standardOutput: FileHandle.nullDevice,
+ timeout: timeout)
+ }
+
+ /// Run a bounded child while retaining stdout for signed-artifact
+ /// assertions. A temporary file avoids the pipe backpressure deadlock that
+ /// would otherwise let a verbose child fill its pipe before termination.
+ static func runCapturingStandardOutput(
+ _ executable: URL,
+ arguments: [String],
+ environment: [String: String]? = nil,
+ timeout: TimeInterval
+ ) throws -> Data {
+ let outputURL = FileManager.default.temporaryDirectory
+ .appendingPathComponent("darkbloom-child-\(UUID().uuidString).stdout")
+ guard FileManager.default.createFile(
+ atPath: outputURL.path, contents: nil)
+ else {
+ throw CocoaError(.fileWriteUnknown)
+ }
+ defer { try? FileManager.default.removeItem(at: outputURL) }
+
+ let output = try FileHandle(forWritingTo: outputURL)
+ defer { try? output.close() }
+ try runProcess(
+ executable,
+ arguments: arguments,
+ environment: environment,
+ standardOutput: output,
+ timeout: timeout)
+ try output.synchronize()
+ try output.close()
+ return try Data(contentsOf: outputURL)
+ }
+
+ private static func runProcess(
+ _ executable: URL,
+ arguments: [String],
+ environment: [String: String]?,
+ standardOutput: Any,
+ timeout: TimeInterval
) throws {
let process = Process()
process.executableURL = executable
@@ -40,7 +86,7 @@ enum BoundedProcess {
environment,
uniquingKeysWith: { _, override in override })
}
- process.standardOutput = FileHandle.nullDevice
+ process.standardOutput = standardOutput
process.standardError = FileHandle.nullDevice
try process.run()
diff --git a/provider-swift/Sources/ProviderCore/ProviderCore.swift b/provider-swift/Sources/ProviderCore/ProviderCore.swift
index 3c1b1ead58..3b89ddc992 100644
--- a/provider-swift/Sources/ProviderCore/ProviderCore.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderCore.swift
@@ -75,26 +75,13 @@ public enum ProviderCore {
// jinja_null_bridge / jinja_template / model_load), so durable telemetry can
// tell the two indistinguishable gpt-oss 500 modes apart. Wire-compatible:
// `error_reason` is an optional inference-error field, omitted when nil.
- // 0.7.2 lets engine_v2 (continuous batching) serve TEXT requests on
- // allowlisted VLM-loaded Gemma 4 slots. Every prod Gemma 4 checkpoint
- // ships a vision tower, so it loads via VLMModelFactory and the per-slot
- // isVLM gate previously kept 100% of Gemma traffic on the legacy engine.
- // The slot factory now extracts the CBv2-adapted MLXLLM text model over
- // the SAME weight arrays (zero extra weight memory) and serves text
- // through v2; image/video requests keep the legacy VLM path. No protocol
- // change — capability is behavioral, gated by the existing engine_v2
- // allowlist + flag.
- // 0.7.3 fixes the v0.7.2 black-hole incident: the VLM text extraction's
- // two module trees each lazily built their own multi-GiB SwitchGLU fused
- // gate+up expert cache at the load-time parity probe (~15 GiB × 2 on
- // gemma-4-26b-8bit), pushing 64 GB (8-bit) and 36 GB (qat-4bit) boxes
- // past the 90% unified-memory cap so the shared KV gate rejected every
- // request forever. The trees now share ONE fused cache
- // (SwitchGLU.shareFusedGateUpCache); the load path re-checks serveable
- // KV headroom AFTER the engine build and unloads instead of advertising
- // a dead model; and GlobalKVCacheBudget audits + drops stale
- // reservations under sustained full-rejection (defense in depth). No
- // protocol changes.
+ // 0.7.2 first enabled CBv2 for VLM-loaded Gemma 4 by reconstructing a
+ // separate MLXLLM text module over shared arrays. That convention was the
+ // source of the historical multi-tree memory/parity complexity.
+ // Gemma 4 VLM now owns the canonical `Gemma4TextModel` directly: direct
+ // VLM, CBv2, media prefill, and MTP all retain the same module identity.
+ // The post-build serveable-headroom guard and stale-reservation cleanup
+ // remain defense in depth; no protocol change is required.
// 0.7.5 is the ONE-ENGINE release: every request — text, image, video,
// mixed — on every slot serves through ContinuousBatchingV2, and the
// legacy BatchScheduler engine is DELETED from the binary (~15k lines
@@ -169,5 +156,5 @@ public enum ProviderCore {
// DARKBLOOM_GEMMA4_PREFILL_TAIL_ROWS=0 and
// DARKBLOOM_GEMMA4_PREFILL_LAST_QUERY=0; the opt-in mixed-step prefill
// quota is DARKBLOOM_CBV2_MIXED_PREFILL_CAP.
- public static let version = "0.7.15"
+ public static let version = "0.8.2"
}
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2.swift
index a569ff39e7..a9e74b457a 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2.swift
@@ -224,11 +224,11 @@ extension ProviderLoop {
/// Re-slice KV grants for the newcomer + existing slots, shrink
/// existing engines, and build the newcomer's bridge. On ANY throw —
- /// re-slice floor, extraction failure, engine construction — the
- /// newcomer's weights are RELEASED (box + clearCache) and only THEN is
- /// every existing engine's grant RESTORED exactly (Codex-review
- /// ordering: restoring first would let Σ(grants) exceed the true fleet
- /// budget while the failed newcomer's weights are still resident).
+ /// direct serving-model resolution, re-slice floor, or engine construction
+ /// — the newcomer's weights are RELEASED (box + clearCache) and only THEN
+ /// every existing engine's grant is RESTORED exactly (restoring first
+ /// would let Σ(grants) exceed the true fleet budget while the failed
+ /// newcomer's weights are still resident).
/// Returns the bridge, already registered with `engineV2Runtime`.
/// CALLER HOLDS the re-slice gate (see `acquireResliceGate`), spanning
/// through slot installation, so a concurrent idle-timeout unload's
@@ -259,9 +259,9 @@ extension ProviderLoop {
return build.bundle.bridge
}
- /// MTP-aware load funnel. Target extraction and assistant load/bind complete
- /// before final sizing and re-slicing, so fallback removes the prospective
- /// assistant charge and active MTP adds it exactly once.
+ /// MTP-aware load funnel. Direct target resolution and assistant load/bind
+ /// complete before final sizing and re-slicing, so fallback removes the
+ /// prospective assistant charge and active MTP adds it exactly once.
internal func resliceAndBuildEngineV2Bundle(
modelId: String,
modelType: String?,
@@ -279,7 +279,6 @@ extension ProviderLoop {
prepared = try await EngineV2SlotFactory.prepareProductionModel(
modelId: modelId,
isVLM: isVLM,
- modelDirectory: modelDirectory,
container: newcomerBox.borrow(),
specDecPreparation: specDecPreparation,
assistantLoader: engineV2SlotHooks?.assistantLoader
@@ -487,12 +486,11 @@ extension ProviderLoop {
/// caller unloads and maps to 503. There is no legacy path.
///
/// VLM slots: every production Gemma 4 checkpoint ships a vision tower,
- /// so the loaded module is MLXVLM's wrapper — which has no CBv2 hooks.
- /// The engine is built over `EngineV2VLMTextExtraction`'s weight-sharing
- /// MLXLLM text model: TEXT requests serve through v2, and ALL media —
- /// image, video, mixed — prefills through v2 via `EngineV2VisionPrefill`
- /// (v0.7.5; media construction failures REFUSE loudly, 503 — see
- /// `MultiModelBatchSchedulerEngine.streamChatCompletion`).
+ /// so the loaded MLXVLM wrapper directly exposes its owned MLXLLM text
+ /// tower to CBv2. Text, image, video, mixed, and MTP requests therefore
+ /// share one language-model identity; media prefills use
+ /// `EngineV2VisionPrefill` (construction failures refuse loudly with 503;
+ /// see `MultiModelBatchSchedulerEngine.streamChatCompletion`).
///
/// On success the bridge is registered with `engineV2Runtime` BEFORE the
/// caller installs the slot, so a request routed the instant the slot
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2Liveness.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2Liveness.swift
index aa49343926..e41e18bacd 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2Liveness.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2Liveness.swift
@@ -187,7 +187,6 @@ extension ProviderLoop {
var prepared = try await EngineV2SlotFactory.prepareRecoveryModel(
modelId: modelId,
isVLM: slot.isVLM,
- modelDirectory: modelDirectory,
container: slot.container,
previousArtifact: slot.engineBundle.mtpArtifact,
previousStatus: slot.engineBundle.mtpStatus,
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ModelLoading.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ModelLoading.swift
index aa0cb06b0c..bb6a841f86 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop+ModelLoading.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ModelLoading.swift
@@ -555,13 +555,11 @@ extension ProviderLoop {
var sizing = slotBuild.sizing
var engineV2Bridge = engineBundle.bridge
- // Post-BRIDGE measured-headroom re-guard (v0.7.3, kept): the
- // engine build (and, for VLM slots, the text-model extraction +
- // parity probe) can retain additional load-time memory beyond
- // the weights the check above measured. Re-measure so a box
- // whose full load-time footprint leaves no serveable KV unloads
- // and 503s instead of advertising a model whose every request
- // the shared KV gate rejects — the v0.7.2 black-hole shape.
+ // Post-BRIDGE measured-headroom re-guard (v0.7.3, kept): engine
+ // construction/JIT may retain load-time memory beyond the weights
+ // measured above. Re-measure so a box with no serveable KV unloads
+ // and 503s instead of advertising a model whose every request the
+ // shared KV gate rejects.
// BACKEND-AWARE: a PAGED slot commits its independently-capped
// physical pool at construction. The guard requires BOTH a
// serveable pool and residual whole-machine headroom; this
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift
index bf8d5380fa..cb5635ab20 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift
@@ -580,8 +580,8 @@ public actor ProviderLoop {
/// the slot never exists (`ensureModelLoaded` unloads + 503s).
let engineBundle: ProviderEngineBundle
var engineV2: EngineV2Bridge { engineBundle.bridge }
- /// Retained for VLM vision preprocessing (the tower shares weights
- /// with the extracted text model) and for liveness rebuilds.
+ /// Retained for VLM vision preprocessing and liveness rebuilds; the
+ /// wrapper owns the exact text tower retained by the engine.
let container: MLXLMCommon.ModelContainer
let tokenizer: TokenizerHandle
/// Scheduler-free sizing facts (weights, fp16 KV rate, context) —
diff --git a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift
index c698577874..f5fb0e709f 100644
--- a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift
+++ b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift
@@ -121,10 +121,9 @@ private let standaloneLogger = Logger(
public actor StandaloneServer {
- /// One resident model: its v2 bridge (the serving engine), the loaded
- /// container (retained for the VLM media path — the vision tower shares
- /// weights with the extracted text model), and the sizing facts the KV
- /// re-slice needs. Mirrors `ProviderLoop.ModelSlot`.
+ /// One resident model: its v2 bridge, loaded container (the VLM owns both
+ /// vision and the exact text tower served by the bridge), and KV sizing
+ /// facts. Mirrors `ProviderLoop.ModelSlot`.
struct CachedSlot {
let bundle: ProviderEngineBundle
var bridge: EngineV2Bridge { bundle.bridge }
@@ -715,7 +714,6 @@ public actor StandaloneServer {
prepared = try await EngineV2SlotFactory.prepareProductionModel(
modelId: modelId,
isVLM: isVLM,
- modelDirectory: modelDirectory,
container: newcomerBox.borrow(),
specDecPreparation: specDecPreparation,
assistantLoader: v2TestHooks?.assistantLoader
@@ -1375,11 +1373,9 @@ public actor StandaloneServer {
var bridge = bundle.bridge
// Post-BRIDGE measured-headroom re-guard (mirrors ProviderLoop):
- // the engine build (and, for VLM slots, the text-model
- // extraction + parity probe) can retain additional load-time
- // memory beyond the weights. Re-measure so a box whose full
- // load-time footprint leaves no serveable KV tears down instead
- // of publishing a model whose every request the KV gate rejects.
+ // engine construction/JIT may retain load-time memory beyond the
+ // weights. Re-measure so a box with no serveable KV tears down
+ // instead of publishing a model whose every request is rejected.
// BACKEND-AWARE: a PAGED slot commits only its conservative
// physical plan. Require both a useful pool and residual
// whole-machine headroom after the build.
diff --git a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift
index 297d15bb5c..4738680397 100644
--- a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift
+++ b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift
@@ -107,6 +107,7 @@ public enum LaunchAgent: Sendable {
coordinatorURL: String,
models: [String] = [],
idleTimeout: UInt64? = nil,
+ configPath: URL? = nil,
localEndpoint: LocalEndpointOptions = LocalEndpointOptions()
) throws {
// Determine the binary path (current executable)
@@ -126,6 +127,7 @@ public enum LaunchAgent: Sendable {
coordinatorURL: coordinatorURL,
models: models,
idleTimeout: idleTimeout,
+ configPath: configPath,
localEndpoint: localEndpoint
)
try loadService()
@@ -294,6 +296,7 @@ public enum LaunchAgent: Sendable {
coordinatorURL: String,
models: [String],
idleTimeout: UInt64?,
+ configPath: URL?,
localEndpoint: LocalEndpointOptions = LocalEndpointOptions()
) throws {
let plist = plistPath()
@@ -305,30 +308,14 @@ public enum LaunchAgent: Sendable {
let log = logPath().path
- // Build the ProgramArguments array.
- var programArguments: [String] = [
- binaryPath,
- "start",
- "--foreground",
- "--coordinator-url",
- coordinatorURL,
- ]
- for model in models {
- programArguments.append("--model")
- programArguments.append(model)
- }
- if let timeout = idleTimeout {
- programArguments.append("--idle-timeout")
- programArguments.append("\(timeout)")
- }
- if localEndpoint.enabled {
- programArguments.append("--local-endpoint")
- programArguments.append(contentsOf: ["--port", "\(localEndpoint.port)"])
- programArguments.append(contentsOf: ["--bind", localEndpoint.bind])
- if localEndpoint.noAuth {
- programArguments.append("--no-auth")
- }
- }
+ let programArguments = serviceProgramArguments(
+ binaryPath: binaryPath,
+ coordinatorURL: coordinatorURL,
+ models: models,
+ idleTimeout: idleTimeout,
+ configPath: configPath,
+ localEndpoint: localEndpoint
+ )
let plistDict = makeServicePlist(
label: label,
@@ -345,6 +332,44 @@ public enum LaunchAgent: Sendable {
try data.write(to: plist, options: .atomic)
}
+ /// Build the child argv without touching launchd or the filesystem.
+ /// A custom config is explicit so every relaunch reads the same TOML;
+ /// the canonical default remains implicit and follows normal migration.
+ static func serviceProgramArguments(
+ binaryPath: String,
+ coordinatorURL: String,
+ models: [String],
+ idleTimeout: UInt64?,
+ configPath: URL?,
+ localEndpoint: LocalEndpointOptions = LocalEndpointOptions()
+ ) -> [String] {
+ var arguments = [
+ binaryPath,
+ "start",
+ "--foreground",
+ "--coordinator-url",
+ coordinatorURL,
+ ]
+ if let configPath {
+ arguments.append(contentsOf: ["--config", configPath.standardizedFileURL.path])
+ }
+ for model in models {
+ arguments.append(contentsOf: ["--model", model])
+ }
+ if let idleTimeout {
+ arguments.append(contentsOf: ["--idle-timeout", "\(idleTimeout)"])
+ }
+ if localEndpoint.enabled {
+ arguments.append("--local-endpoint")
+ arguments.append(contentsOf: ["--port", "\(localEndpoint.port)"])
+ arguments.append(contentsOf: ["--bind", localEndpoint.bind])
+ if localEndpoint.noAuth {
+ arguments.append("--no-auth")
+ }
+ }
+ return arguments
+ }
+
/// Build the launchd plist dictionary for the provider service. Pure (no I/O)
/// so the auto-start and environment-passthrough behavior is unit-testable.
///
diff --git a/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift b/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift
index 29fff8ed53..f89e3943d8 100644
--- a/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift
+++ b/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift
@@ -1150,11 +1150,19 @@ public struct SelfUpdater: Sendable {
+ "\(PackagedRuntimeSmoke.mlxLMCommonBundleName)/pagedattention.metal "
+ "(found \(bundles.count))")
}
- try BoundedProcess.run(
+ // The signed child must prove the production TOML projection,
+ // overwrite precedence, early safe-R1 latch, and packaged AOT before
+ // it reaches the existing paged-kernel GPU smoke.
+ let smokeOutput = try BoundedProcess.runCapturingStandardOutput(
executable,
arguments: ["runtime-smoke"],
environment: ["DARKBLOOM_NO_UPDATE_CHECK": "1"],
timeout: Self.artifactVerificationTimeout)
+ guard PackagedRuntimeSmoke.containsGemmaOptimizationSuccessMarker(smokeOutput)
+ else {
+ throw UpdateError.replaceFailed(
+ "packaged runtime smoke omitted the retained Gemma optimization marker")
+ }
}
private func verifyCodeSignature(
diff --git a/provider-swift/Sources/darkbloom/BetaCommand.swift b/provider-swift/Sources/darkbloom/BetaCommand.swift
index 0b1fdf220f..c89694414e 100644
--- a/provider-swift/Sources/darkbloom/BetaCommand.swift
+++ b/provider-swift/Sources/darkbloom/BetaCommand.swift
@@ -5,12 +5,11 @@ import ProviderCore
struct Beta: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "beta",
- abstract: "Manage opt-in beta features.",
+ abstract: "Manage configurable beta features.",
discussion: """
- Beta features are experimental and off by default. Toggling one writes a
- field in your provider TOML config, so the change also applies to the
- launchd daemon (unlike environment variables, which the daemon does not
- inherit).
+ Beta features are experimental and have feature-specific defaults.
+ Toggling one writes a field in your provider TOML config, which is the
+ authority for daemon, `--foreground`, and `--local` processes.
Subcommands:
list Show all beta features and whether each is on (default).
@@ -18,8 +17,9 @@ struct Beta: AsyncParsableCommand {
disable Turn a beta feature off.
status [feature] Show details for all features, or one.
- Most changes require a restart to take effect:
- darkbloom beta enable kv-quant
+ Changes that affect process-wide optimization state require a restart.
+ To roll back a default-on feature:
+ darkbloom beta disable gemma-weighted-r1
darkbloom restart
""",
subcommands: [List.self, Enable.self, Disable.self, Status.self],
@@ -79,7 +79,7 @@ extension Beta {
}
}
print("")
- print("Enable with: darkbloom beta enable (then: darkbloom restart)")
+ print("Change with: darkbloom beta enable|disable (then: darkbloom restart)")
print("Details with: darkbloom beta status ")
}
}
diff --git a/provider-swift/Sources/darkbloom/RuntimeSmokeCommand.swift b/provider-swift/Sources/darkbloom/RuntimeSmokeCommand.swift
index 9086d637ba..769529b913 100644
--- a/provider-swift/Sources/darkbloom/RuntimeSmokeCommand.swift
+++ b/provider-swift/Sources/darkbloom/RuntimeSmokeCommand.swift
@@ -13,6 +13,8 @@ struct RuntimeSmoke: ParsableCommand {
var shapes: [String] = []
mutating func run() throws {
+ try PackagedRuntimeSmoke.verifyGemmaOptimizations()
+ print(PackagedRuntimeSmoke.gemmaOptimizationSuccessMarker)
try PackagedRuntimeSmoke.runPagedKernel(arguments: shapes)
print("paged-kernel-runtime-smoke: ok")
}
diff --git a/provider-swift/Sources/darkbloom/StartCommand+Daemon.swift b/provider-swift/Sources/darkbloom/StartCommand+Daemon.swift
index 98e0ed3a5e..334cbd6bb8 100644
--- a/provider-swift/Sources/darkbloom/StartCommand+Daemon.swift
+++ b/provider-swift/Sources/darkbloom/StartCommand+Daemon.swift
@@ -13,7 +13,8 @@ extension Start {
internal mutating func launchDaemon(
snapshot: RuntimeSnapshot,
config: ProviderConfig,
- coordinatorURL: String
+ coordinatorURL: String,
+ configPath: URL?
) async throws {
// Run critical checks before downloading models or prompting.
try runPreflightChecks(snapshot: snapshot)
@@ -44,6 +45,7 @@ extension Start {
coordinatorURL: coordinatorURL,
models: selectedModelIDs,
idleTimeout: idleTimeout ?? (config.backend.idleTimeoutMins > 0 ? config.backend.idleTimeoutMins : nil),
+ configPath: configPath,
localEndpoint: LaunchAgent.LocalEndpointOptions(
enabled: localEndpoint, port: port, bind: bind, noAuth: noAuth
)
diff --git a/provider-swift/Sources/darkbloom/StartCommand.swift b/provider-swift/Sources/darkbloom/StartCommand.swift
index 7a6118c99f..b9746b8f1a 100644
--- a/provider-swift/Sources/darkbloom/StartCommand.swift
+++ b/provider-swift/Sources/darkbloom/StartCommand.swift
@@ -62,7 +62,6 @@ struct Start: AsyncParsableCommand {
mutating func run() async throws {
Darkbloom.ensureLogging()
-
if !foreground {
printTermsNotice()
}
@@ -75,15 +74,6 @@ struct Start: AsyncParsableCommand {
throw ExitCode.failure
}
- // GPU is required. Reject CPU fallback up-front so we never
- // come up reporting healthy and then silently churn at 0.5 tok/s.
- do {
- _ = try GPUEnforcement.requireMetal()
- } catch {
- printError("\(error)")
- throw ExitCode.failure
- }
-
let snapshot = try loadRuntimeSnapshot(configOptions: configOptions)
let effectiveCoordinator = coordinatorURL ?? snapshot.config.coordinator.url
var effectiveConfig = snapshot.config
@@ -91,6 +81,15 @@ struct Start: AsyncParsableCommand {
effectiveConfig.backend.idleTimeoutMins = idleTimeout
}
+ // These controls are process-start latches in MLX/MLXLM. Project the
+ // authoritative TOML before requireMetal() performs the first MLX touch.
+ do {
+ try Self.prepareServeRuntime(settings: snapshot.config.gemmaOptimizations)
+ } catch {
+ printError("Cannot start: \(error)")
+ throw ExitCode.failure
+ }
+
guard let hardware = snapshot.hardware else {
printError("Cannot start: hardware detection failed (\(snapshot.hardwareError?.localizedDescription ?? "unknown"))")
throw ExitCode.failure
@@ -113,9 +112,29 @@ struct Start: AsyncParsableCommand {
try await launchDaemon(
snapshot: snapshot,
config: effectiveConfig,
- coordinatorURL: effectiveCoordinator
+ coordinatorURL: effectiveCoordinator,
+ configPath: configOptions.config == nil ? nil : snapshot.configPath
)
}
}
+ /// Testable ordering seam for process-start environment projection. The
+ /// default closures are the production path; tests replace only the Metal
+ /// probe so they can assert ordering without constructing an MLX device.
+ ///
+ /// A rejected projection throws before `requireMetal()`, so a half-applied
+ /// weighted-unsort/safe-R1 pair can never reach engine construction.
+ internal static func prepareServeRuntime(
+ settings: GemmaOptimizationSettings,
+ apply: (GemmaOptimizationSettings) throws -> Void = {
+ try GemmaOptimizationEnvironment.apply($0)
+ },
+ requireMetal: () throws -> Void = {
+ _ = try GPUEnforcement.requireMetal()
+ }
+ ) throws {
+ try apply(settings)
+ try requireMetal()
+ }
+
}
diff --git a/provider-swift/Tests/DarkbloomCLITests/StartCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/StartCommandTests.swift
new file mode 100644
index 0000000000..0b746853a1
--- /dev/null
+++ b/provider-swift/Tests/DarkbloomCLITests/StartCommandTests.swift
@@ -0,0 +1,109 @@
+import ArgumentParser
+import Darwin
+import ProviderCore
+import Testing
+
+@testable import darkbloom
+
+@Suite("Start command runtime preparation")
+struct StartCommandTests {
+ @Test("TOML projection precedes the first MLX touch")
+ func projectionPrecedesMetal() throws {
+ let settings = GemmaOptimizationSettings(
+ prefillLayer18: false,
+ weightedR1: false
+ )
+ var events: [String] = []
+
+ try Start.prepareServeRuntime(
+ settings: settings,
+ apply: { received in
+ #expect(received.prefillLayer18 == false)
+ #expect(received.weightedR1 == false)
+ events.append("projection")
+ },
+ requireMetal: {
+ events.append("metal")
+ }
+ )
+
+ #expect(events == ["projection", "metal"])
+ }
+
+ @Test("a rejected projection aborts before the first MLX touch")
+ func rejectedProjectionSkipsMetal() {
+ var events: [String] = []
+ let failure = GemmaOptimizationEnvironment.ApplicationFailure(
+ keys: [
+ GemmaOptimizationEnvironment.safeR1Key,
+ GemmaOptimizationEnvironment.weightedUnsortKey,
+ ],
+ code: ENOMEM
+ )
+
+ // The coupled weighted-unsort/safe-R1 pair is a process-start latch:
+ // a half-applied projection must never reach engine construction.
+ do {
+ try Start.prepareServeRuntime(
+ settings: GemmaOptimizationSettings(),
+ apply: { _ in
+ events.append("projection")
+ throw failure
+ },
+ requireMetal: {
+ events.append("metal")
+ }
+ )
+ Issue.record("a rejected projection must abort serve preparation")
+ } catch let error as GemmaOptimizationEnvironment.ApplicationFailure {
+ #expect(error == failure)
+ #expect("\(error)" == failure.description)
+ } catch {
+ Issue.record("expected ApplicationFailure, got \(error)")
+ }
+
+ #expect(events == ["projection"])
+ }
+
+ @Test("the default projection path is the environment apply boundary")
+ func defaultApplyProjectsSettings() throws {
+ let settings = GemmaOptimizationSettings(
+ prefillLayer18: false,
+ weightedR1: true
+ )
+ let projection = GemmaOptimizationEnvironment.projection(for: settings)
+ let saved = projection.keys.reduce(into: [String: String?]()) { out, key in
+ out[key] = key.withCString { getenv($0).map { String(cString: $0) } }
+ }
+ defer {
+ for (key, value) in saved {
+ if let value {
+ _ = setenv(key, value, 1)
+ } else {
+ _ = unsetenv(key)
+ }
+ }
+ }
+ var metalProbed = false
+
+ try Start.prepareServeRuntime(
+ settings: settings,
+ requireMetal: { metalProbed = true }
+ )
+
+ for (key, value) in projection {
+ let observed = key.withCString { getenv($0).map { String(cString: $0) } }
+ #expect(observed == value)
+ }
+ #expect(metalProbed)
+ }
+
+ @Test("start accepts an explicit custom config")
+ func customConfigParses() throws {
+ let parsed = try Darkbloom.parseAsRoot([
+ "start", "--config", "/tmp/custom provider.toml", "--foreground",
+ ])
+ let command = try #require(parsed as? Start)
+ #expect(command.configOptions.config == "/tmp/custom provider.toml")
+ }
+}
diff --git a/provider-swift/Tests/ProviderCoreTests/BetaFeaturesTests.swift b/provider-swift/Tests/ProviderCoreTests/BetaFeaturesTests.swift
index 4ab8baeeac..5652473888 100644
--- a/provider-swift/Tests/ProviderCoreTests/BetaFeaturesTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/BetaFeaturesTests.swift
@@ -12,18 +12,26 @@ struct BetaFeaturesTests {
)
}
- @Test("registry exposes beta features")
+ @Test("registry exposes only retained Gemma controls")
func registryContainsExpectedFeatures() {
+ #expect(BetaFeatures.all.contains { $0.id == "gemma-prefill-layer18" })
+ #expect(BetaFeatures.all.contains { $0.id == "gemma-weighted-r1" })
#expect(BetaFeatures.all.contains { $0.id == "kv-quant" })
- // adaptive-prefill was retired with the legacy engine (v0.7.5).
+ #expect(!BetaFeatures.all.contains { $0.id == "gemma-expert-packing" })
+ #expect(!BetaFeatures.all.contains { $0.id == "gemma-dense-packing" })
#expect(!BetaFeatures.all.contains { $0.id == "adaptive-prefill" })
}
@Test("feature lookup is case-insensitive and nil for unknown ids")
func featureLookup() {
+ #expect(
+ BetaFeatures.feature(id: "GEMMA-PREFILL-LAYER18")?.id
+ == "gemma-prefill-layer18"
+ )
+ #expect(BetaFeatures.feature(id: "Gemma-Weighted-R1")?.id == "gemma-weighted-r1")
#expect(BetaFeatures.feature(id: "kv-quant")?.id == "kv-quant")
#expect(BetaFeatures.feature(id: "KV-QUANT")?.id == "kv-quant")
- #expect(BetaFeatures.feature(id: "ADAPTIVE-PREFILL") == nil) // retired v0.7.5
+ #expect(BetaFeatures.feature(id: "ADAPTIVE-PREFILL") == nil)
#expect(BetaFeatures.feature(id: "does-not-exist") == nil)
}
@@ -34,6 +42,35 @@ struct BetaFeaturesTests {
#expect(feature.requiresRestart == true)
}
+ @Test("retained Gemma controls default on and require restart")
+ func gemmaControlsDefaultOn() {
+ let config = freshConfig()
+ for id in ["gemma-prefill-layer18", "gemma-weighted-r1"] {
+ let feature = BetaFeatures.feature(id: id)!
+ #expect(feature.isEnabled(in: config))
+ #expect(feature.requiresRestart)
+ }
+ }
+
+ @Test("each retained Gemma row mutates exactly one setting")
+ func gemmaRowsAreScoped() {
+ let layer = BetaFeatures.feature(id: "gemma-prefill-layer18")!
+ let weighted = BetaFeatures.feature(id: "gemma-weighted-r1")!
+ var config = freshConfig()
+
+ layer.apply(false, to: &config)
+ #expect(!config.gemmaOptimizations.prefillLayer18)
+ #expect(config.gemmaOptimizations.weightedR1)
+
+ weighted.apply(false, to: &config)
+ #expect(!config.gemmaOptimizations.prefillLayer18)
+ #expect(!config.gemmaOptimizations.weightedR1)
+
+ weighted.apply(true, to: &config)
+ #expect(!config.gemmaOptimizations.prefillLayer18)
+ #expect(config.gemmaOptimizations.weightedR1)
+ }
+
@Test("apply toggles the backing config field both ways")
func applyTogglesField() {
let feature = BetaFeatures.feature(id: "kv-quant")!
@@ -64,15 +101,21 @@ struct BetaFeaturesTests {
#expect(config.backend.enabledModels == before.backend.enabledModels)
#expect(config.provider == before.provider)
#expect(config.coordinator == before.coordinator)
+ #expect(config.gemmaOptimizations == before.gemmaOptimizations)
}
- @Test("enabledIDs reflects the current config")
+ @Test("enabledIDs reflects default-on and explicit beta settings")
func enabledIDsReflectsConfig() {
var config = freshConfig()
- #expect(BetaFeatures.enabledIDs(in: config).isEmpty)
+ #expect(BetaFeatures.enabledIDs(in: config) == [
+ "gemma-prefill-layer18", "gemma-weighted-r1",
+ ])
+ BetaFeatures.feature(id: "gemma-weighted-r1")!.apply(false, to: &config)
BetaFeatures.feature(id: "kv-quant")!.apply(true, to: &config)
- #expect(BetaFeatures.enabledIDs(in: config) == ["kv-quant"])
+ #expect(BetaFeatures.enabledIDs(in: config) == [
+ "gemma-prefill-layer18", "kv-quant",
+ ])
}
@Test("toggling kv-quant survives a TOML round-trip")
@@ -88,4 +131,19 @@ struct BetaFeaturesTests {
#expect(feature.isEnabled(in: decoded) == true)
}
+ @Test("retained Gemma beta toggles survive a TOML round trip")
+ func gemmaRowsRoundTripThroughTOML() {
+ var config = freshConfig()
+ BetaFeatures.feature(id: "gemma-prefill-layer18")!.apply(false, to: &config)
+ BetaFeatures.feature(id: "gemma-weighted-r1")!.apply(false, to: &config)
+
+ let toml = ConfigManager.serialize(config)
+ let decoded = ConfigManager.parse(toml)
+
+ #expect(toml.contains("prefill_layer18"))
+ #expect(toml.contains("weighted_r1"))
+ #expect(!decoded.gemmaOptimizations.prefillLayer18)
+ #expect(!decoded.gemmaOptimizations.weightedR1)
+ }
+
}
diff --git a/provider-swift/Tests/ProviderCoreTests/EngineV2BridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/EngineV2BridgeTests.swift
index 7cf74b7ad1..a104d9a6f0 100644
--- a/provider-swift/Tests/ProviderCoreTests/EngineV2BridgeTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/EngineV2BridgeTests.swift
@@ -1357,8 +1357,6 @@ struct EngineV2FailLoudFactoryTests {
EngineV2ProductionError.noKVHeadroom) == .noKVHeadroom)
#expect(EngineV2RefusalReason.classify(
EngineV2ProductionError.unsupportedModel("Qwen3Model")) == .unsupportedModel)
- #expect(EngineV2RefusalReason.classify(
- EngineV2VLMTextExtractionError.parityMismatch("x")) == .vlmExtractionFailed)
#expect(EngineV2RefusalReason.classify(SomeError()) == .engineInitFailed)
}
@@ -1442,7 +1440,6 @@ struct EngineV2FailLoudFactoryTests {
let cases: [(any Error, String)] = [
(EngineV2ProductionError.noKVHeadroom, "no_kv_headroom"),
(EngineV2ProductionError.unsupportedModel("StubModel"), "unsupported_model"),
- (EngineV2VLMTextExtractionError.parityMismatch("probe"), "vlm_extraction_failed"),
]
for (error, expectedReason) in cases {
let telemetry = TelemetrySink()
diff --git a/provider-swift/Tests/ProviderCoreTests/EngineV2LivenessRecoveryTests.swift b/provider-swift/Tests/ProviderCoreTests/EngineV2LivenessRecoveryTests.swift
index 827e126859..d018bcd742 100644
--- a/provider-swift/Tests/ProviderCoreTests/EngineV2LivenessRecoveryTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/EngineV2LivenessRecoveryTests.swift
@@ -350,8 +350,8 @@ struct EngineV2LivenessRecoveryTests {
init() {
// unloadModel / updateAggregateCapacity read MLX GPU counters — the
- // mlx.metallib must be colocated with the test runner (CI extracts
- // it; locally run `./scripts/fetch-metallib.sh debug` once).
+ // mlx.metallib must be colocated with the test runner (CI stages
+ // the source-built result; locally run `./scripts/fetch-metallib.sh debug` once).
_ = LiveInferenceFixtures.ensureMetallibColocated()
}
diff --git a/provider-swift/Tests/ProviderCoreTests/EngineV2ProductionWiringTests.swift b/provider-swift/Tests/ProviderCoreTests/EngineV2ProductionWiringTests.swift
index 085fc69f70..4090c031b6 100644
--- a/provider-swift/Tests/ProviderCoreTests/EngineV2ProductionWiringTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/EngineV2ProductionWiringTests.swift
@@ -422,40 +422,6 @@ struct EngineV2SlotBuildTests {
#expect(events.first?.fields?["error_class"]?.description.contains("InitFailure") == true)
}
- @Test("VLM slot: extraction failure surfaces as vlm_extraction_failed refusal")
- func vlmExtractionFailureRefusesLoudly() async throws {
- let loop = try makeWiringLoop()
- let runtime = EngineV2Runtime()
- let telemetry = WiringTelemetrySink()
- await loop.setEngineV2RuntimeForTesting(runtime)
- await loop.setEngineV2SlotHooksForTesting(
- ProviderLoop.EngineV2SlotHooks(
- emitTelemetry: telemetry.callback(),
- physicalMemoryBytes: wiringPhysicalBytes,
- makeEngine: { _, _ in
- // Stands in for any extraction failure (config decode,
- // verify [.all] mismatch, forward-parity gate).
- throw EngineV2VLMTextExtractionError.parityMismatch("scripted")
- }))
-
- await #expect(throws: EngineV2VLMTextExtractionError.self) {
- _ = try await loop.resliceAndBuildEngineV2SlotForTesting(
- modelId: "gemma-4-26b-qat-4bit",
- modelType: "gemma4",
- isVLM: true,
- container: makeStubContainer(),
- tokenizer: TokenizerHandle(WiringStubTokenizer()),
- sizing: makeSizing(weightsGiB: 15)
- )
- }
- #expect(await runtime.bridge(forModel: "gemma-4-26b-qat-4bit") == nil)
- let refusal = telemetry.events.first {
- $0.fields?["operation"]?.description == "engine_v2_refusal"
- }
- #expect(refusal != nil)
- #expect(refusal?.severity == .error)
- #expect(refusal?.fields?["reason"]?.description == "vlm_extraction_failed")
- }
@Test("production factory: unsupported model class throws (→ refusal)")
func productionFactoryRejectsUnsupportedModel() {
@@ -1573,9 +1539,9 @@ struct EngineV2RequestRoutingTests {
/// These tests drive the REAL `updateAggregateCapacity` / `unloadModel`
/// paths, which read MLX GPU counters — so the mlx.metallib must be
-/// colocated with the test runner. CI places it under `.build` (see
-/// ci.yml "Extract mlx.metallib"); locally run `./scripts/fetch-metallib.sh
-/// debug` once. Mirrors the `LiveInferenceFixtures` pattern.
+/// colocated with the test runner. CI uses the canonical source builder and
+/// stages its result under `.build`; locally run
+/// `./scripts/fetch-metallib.sh debug` once. Mirrors the `LiveInferenceFixtures` pattern.
@Suite("EngineV2 production wiring: runtime guards", .serialized)
struct EngineV2RuntimeGuardTests {
diff --git a/provider-swift/Tests/ProviderCoreTests/EngineV2SSDPrefixCacheLiveTests.swift b/provider-swift/Tests/ProviderCoreTests/EngineV2SSDPrefixCacheLiveTests.swift
index 3a52a85975..75b86ab5c5 100644
--- a/provider-swift/Tests/ProviderCoreTests/EngineV2SSDPrefixCacheLiveTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/EngineV2SSDPrefixCacheLiveTests.swift
@@ -93,11 +93,9 @@ struct EngineV2SSDPrefixCacheLiveTests {
static let gemmaQatModelID = "mlx-community/gemma-4-26B-A4B-it-qat-4bit"
- /// Prod gemma-4 checkpoints are VLM builds: load through the VLM
- /// factory and extract the CBv2-adapted text model over the SAME
- /// weight arrays — the identical path the slot factory takes. Layer
- /// kinds ALSO derived config-only (the production SSD construction
- /// path for VLM slots) and pinned equal to engine truth.
+ /// Production Gemma 4 checkpoints are VLM builds. Their loaded wrapper
+ /// owns and exposes the exact CBv2-adapted text tower; SSD topology comes
+ /// from that same live module with no config re-decode or extraction.
private func loadGemmaQat() async throws -> LiveModel {
guard LiveInferenceFixtures.ensureMetallibColocated() != nil else {
throw LiveFixtureSkip.missingMetallib
@@ -118,20 +116,18 @@ struct EngineV2SSDPrefixCacheLiveTests {
let tokenizer: TokenizerHandle = await container.perform { ctx in
TokenizerHandle(ctx.tokenizer)
}
- let extraction = try EngineV2VLMTextExtraction.extractTextModel(
- from: snapshot.model, modelDirectory: directory)
- // The config-only derivation (what the slot factory hands the SSD
- // cache for a VLM slot) must match engine truth.
- let configKinds = EngineV2VLMTextExtraction.cbv2LayerKinds(modelDirectory: directory)
- #expect(configKinds == extraction.model.cbv2LayerKinds,
- "config-only layer kinds drifted from the extracted model's")
+ let wrapper = try #require(snapshot.model as? MLXVLM.Gemma4)
+ let textModel = wrapper.textModel
+ let direct = try EngineV2Factory.directServingModel(
+ model: wrapper, isVLM: true)
+ #expect(ObjectIdentifier(direct) == ObjectIdentifier(textModel))
return LiveModel(
modelID: "gemma-4-26b-qat-4bit",
container: container,
- model: extraction.model,
+ model: textModel,
tokenizer: tokenizer,
eosTokenIds: snapshot.eosTokenIds,
- layerKinds: extraction.model.cbv2LayerKinds,
+ layerKinds: textModel.cbv2LayerKinds,
modelDirectory: directory)
}
diff --git a/provider-swift/Tests/ProviderCoreTests/FrozenReplayRealModelTests.swift b/provider-swift/Tests/ProviderCoreTests/FrozenReplayRealModelTests.swift
index cba461a155..9250529ee2 100644
--- a/provider-swift/Tests/ProviderCoreTests/FrozenReplayRealModelTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/FrozenReplayRealModelTests.swift
@@ -69,14 +69,16 @@ struct FrozenReplayRealModelTests {
eosTokenIds: context.configuration.eosTokenIds,
extraEOSTokens: context.configuration.extraEOSTokens.sorted())
}
- let extraction = try EngineV2VLMTextExtraction.extractTextModel(
- from: snapshot.model,
- modelDirectory: directory)
+ let wrapper = try #require(snapshot.model as? MLXVLM.Gemma4)
+ let textModel = wrapper.textModel
+ let direct = try EngineV2Factory.directServingModel(
+ model: wrapper, isVLM: true)
+ #expect(ObjectIdentifier(direct) == ObjectIdentifier(textModel))
return Loaded(
container: container,
- model: extraction.model,
- layerKinds: extraction.model.cbv2LayerKinds,
- vocabularySize: extraction.model.vocabularySize)
+ model: textModel,
+ layerKinds: textModel.cbv2LayerKinds,
+ vocabularySize: textModel.vocabularySize)
}
private func makeBank(_ loaded: Loaded) -> CBv2LayerCacheBank {
diff --git a/provider-swift/Tests/ProviderCoreTests/GemmaMTPProductionLiveTests.swift b/provider-swift/Tests/ProviderCoreTests/GemmaMTPProductionLiveTests.swift
index 4d280d556b..d8b7f78c27 100644
--- a/provider-swift/Tests/ProviderCoreTests/GemmaMTPProductionLiveTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/GemmaMTPProductionLiveTests.swift
@@ -100,7 +100,6 @@ struct GemmaMTPProductionLiveTests {
let prepared = try await EngineV2SlotFactory.prepareProductionModel(
modelId: MTPProductionLiveFixtures.targetID,
isVLM: true,
- modelDirectory: targetDirectory,
container: container,
specDecPreparation: preparation,
assistantLoader: AlwaysFailMTPAssistantLoader())
diff --git a/provider-swift/Tests/ProviderCoreTests/GemmaOptimizationConfigTests.swift b/provider-swift/Tests/ProviderCoreTests/GemmaOptimizationConfigTests.swift
new file mode 100644
index 0000000000..3ed7f67997
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/GemmaOptimizationConfigTests.swift
@@ -0,0 +1,240 @@
+import Darwin
+import Testing
+@testable import ProviderCore
+
+@Suite("Gemma optimization config")
+struct GemmaOptimizationConfigTests {
+ @Test("missing optimization section enables the selected stack")
+ func missingSectionDefaultsOn() {
+ let config = ConfigManager.parse("""
+ [provider]
+ name = "test-provider"
+ """)
+
+ #expect(config.gemmaOptimizations == GemmaOptimizationSettings())
+ #expect(config.gemmaOptimizations.prefillLayer18)
+ #expect(config.gemmaOptimizations.weightedR1)
+ }
+
+ @Test("partial optimization section defaults each missing key on")
+ func partialSectionDefaultsMissingKeysOn() {
+ let layerOnly = ConfigManager.parse("""
+ [provider]
+ name = "test-provider"
+
+ [gemma_optimizations]
+ prefill_layer18 = false
+ """)
+ #expect(!layerOnly.gemmaOptimizations.prefillLayer18)
+ #expect(layerOnly.gemmaOptimizations.weightedR1)
+
+ let weightedOnly = ConfigManager.parse("""
+ [provider]
+ name = "test-provider"
+
+ [gemma_optimizations]
+ weighted_r1 = false
+ """)
+ #expect(weightedOnly.gemmaOptimizations.prefillLayer18)
+ #expect(!weightedOnly.gemmaOptimizations.weightedR1)
+ }
+
+ @Test("explicit optimization values are honored")
+ func explicitValues() {
+ let config = ConfigManager.parse("""
+ [provider]
+ name = "test-provider"
+
+ [gemma_optimizations]
+ prefill_layer18 = false
+ weighted_r1 = false
+ """)
+
+ #expect(!config.gemmaOptimizations.prefillLayer18)
+ #expect(!config.gemmaOptimizations.weightedR1)
+ }
+
+ @Test("optimization settings round trip with snake-case TOML keys")
+ func snakeCaseRoundTrip() {
+ let original = ProviderConfig(
+ provider: ProviderSettings(name: "test-provider"),
+ gemmaOptimizations: GemmaOptimizationSettings(
+ prefillLayer18: false,
+ weightedR1: true
+ )
+ )
+
+ let toml = ConfigManager.serialize(original)
+ let decoded = ConfigManager.parse(toml)
+
+ #expect(toml.contains("[gemma_optimizations]"))
+ #expect(toml.contains("prefill_layer18 = false"))
+ #expect(toml.contains("weighted_r1 = true"))
+ #expect(!toml.contains("gemmaOptimizations"))
+ #expect(!toml.contains("prefillLayer18"))
+ #expect(!toml.contains("weightedR1"))
+ #expect(decoded == original)
+ }
+}
+
+@Suite("Gemma optimization environment")
+struct GemmaOptimizationEnvironmentTests {
+ private let expectedKeys: Set = [
+ "DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL",
+ "MLX_GEMMA4_FUSED_WEIGHTED_UNSORT",
+ "MLX_GATHER_QMM_EXPERT_SLICES",
+ ]
+
+ @Test("projection emits exactly the three selected controls")
+ func exactProjection() {
+ let enabled = GemmaOptimizationEnvironment.projection(
+ for: GemmaOptimizationSettings()
+ )
+ #expect(enabled == [
+ "DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL": "18",
+ "MLX_GEMMA4_FUSED_WEIGHTED_UNSORT": "1",
+ "MLX_GATHER_QMM_EXPERT_SLICES": "1",
+ ])
+
+ let disabled = GemmaOptimizationEnvironment.projection(
+ for: GemmaOptimizationSettings(
+ prefillLayer18: false,
+ weightedR1: false
+ )
+ )
+ #expect(disabled == [
+ "DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL": "0",
+ "MLX_GEMMA4_FUSED_WEIGHTED_UNSORT": "0",
+ "MLX_GATHER_QMM_EXPERT_SLICES": "0",
+ ])
+ }
+
+ @Test("weighted unsort and safe R1 are atomic in every projection")
+ func weightedR1IsAtomic() {
+ for enabled in [false, true] {
+ let projection = GemmaOptimizationEnvironment.projection(
+ for: GemmaOptimizationSettings(weightedR1: enabled)
+ )
+ #expect(
+ projection[GemmaOptimizationEnvironment.weightedUnsortKey]
+ == projection[GemmaOptimizationEnvironment.safeR1Key]
+ )
+ #expect(Set(projection.keys) == expectedKeys)
+ }
+ }
+
+ @Test("apply overwrites every projected value")
+ func applyUsesOverwrite() throws {
+ var values: [String: String] = [:]
+ var overwrites: [String: Int32] = [:]
+ let settings = GemmaOptimizationSettings(
+ prefillLayer18: false,
+ weightedR1: true
+ )
+
+ try GemmaOptimizationEnvironment.apply(settings) { name, value, overwrite in
+ values[name] = value
+ overwrites[name] = overwrite
+ return 0
+ }
+
+ #expect(values == [
+ "DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL": "0",
+ "MLX_GEMMA4_FUSED_WEIGHTED_UNSORT": "1",
+ "MLX_GATHER_QMM_EXPERT_SLICES": "1",
+ ])
+ // The application boundary must hand the environment exactly what
+ // projection() reports, or the release matrix describes a dispatch
+ // that never happened.
+ #expect(values == GemmaOptimizationEnvironment.projection(for: settings))
+ #expect(Set(overwrites.keys) == expectedKeys)
+ #expect(overwrites.values.allSatisfy { $0 == 1 })
+ }
+
+ @Test("a rejected key fails the whole application with its errno")
+ func applyRejectsPartialLatch() {
+ var attempted: [String: String] = [:]
+ let settings = GemmaOptimizationSettings()
+
+ do {
+ try GemmaOptimizationEnvironment.apply(settings) { name, value, _ in
+ attempted[name] = value
+ return name == GemmaOptimizationEnvironment.safeR1Key ? ENOMEM : 0
+ }
+ Issue.record("a rejected key must fail the whole application")
+ } catch let error as GemmaOptimizationEnvironment.ApplicationFailure {
+ #expect(error == GemmaOptimizationEnvironment.ApplicationFailure(
+ keys: [GemmaOptimizationEnvironment.safeR1Key],
+ code: ENOMEM
+ ))
+ } catch {
+ Issue.record("expected ApplicationFailure, got \(error)")
+ }
+
+ // A rejected key never truncates the attempt, and the values offered
+ // stay exactly the projection.
+ #expect(attempted == GemmaOptimizationEnvironment.projection(for: settings))
+ }
+
+ @Test("every rejected key is reported, ordered, with the first errno")
+ func applyReportsAllRejectedKeys() {
+ var order: [String] = []
+
+ do {
+ try GemmaOptimizationEnvironment.apply(GemmaOptimizationSettings()) {
+ name, _, _ in
+ order.append(name)
+ switch name {
+ case GemmaOptimizationEnvironment.safeR1Key: return EINVAL
+ case GemmaOptimizationEnvironment.weightedUnsortKey: return EPERM
+ default: return 0
+ }
+ }
+ Issue.record("rejected keys must fail the whole application")
+ } catch let error as GemmaOptimizationEnvironment.ApplicationFailure {
+ #expect(error == GemmaOptimizationEnvironment.ApplicationFailure(
+ keys: [
+ GemmaOptimizationEnvironment.safeR1Key,
+ GemmaOptimizationEnvironment.weightedUnsortKey,
+ ],
+ code: EINVAL
+ ))
+ } catch {
+ Issue.record("expected ApplicationFailure, got \(error)")
+ }
+
+ // Sorted application keeps the reported failure identical across runs
+ // despite per-process dictionary hash ordering.
+ #expect(order == expectedKeys.sorted())
+ }
+
+ @Test("failure description names the rejected keys and the errno")
+ func failureDescriptionIsPrecise() {
+ let failure = GemmaOptimizationEnvironment.ApplicationFailure(
+ keys: [
+ GemmaOptimizationEnvironment.weightedUnsortKey,
+ GemmaOptimizationEnvironment.safeR1Key,
+ ],
+ code: ENOMEM
+ )
+
+ #expect(failure.description.contains(
+ GemmaOptimizationEnvironment.weightedUnsortKey))
+ #expect(failure.description.contains(
+ GemmaOptimizationEnvironment.safeR1Key))
+ #expect(failure.description.contains(String(cString: strerror(ENOMEM))))
+ }
+
+ @Test("projection excludes dropped packing and prefill controls")
+ func droppedControlsAreAbsent() {
+ let keys = Set(GemmaOptimizationEnvironment.projection(
+ for: GemmaOptimizationSettings()
+ ).keys)
+
+ #expect(!keys.contains("MLX_GEMMA4_FUSED_EXPERT_GATE_UP"))
+ #expect(!keys.contains("MLX_GEMMA4_FUSED_DENSE_GATE_UP"))
+ #expect(!keys.contains("DARKBLOOM_GEMMA4_PREFILL_TAIL_ROWS"))
+ #expect(!keys.contains("DARKBLOOM_GEMMA4_PREFILL_LAST_QUERY"))
+ #expect(keys == expectedKeys)
+ }
+}
diff --git a/provider-swift/Tests/ProviderCoreTests/GemmaOptimizationReportingTests.swift b/provider-swift/Tests/ProviderCoreTests/GemmaOptimizationReportingTests.swift
new file mode 100644
index 0000000000..57ab62cdf3
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/GemmaOptimizationReportingTests.swift
@@ -0,0 +1,126 @@
+import Foundation
+import Testing
+@testable import ProviderCore
+
+@Suite("Gemma optimization reporting")
+struct GemmaOptimizationReportingTests {
+ @Test("reason precedence covers disabled, model eligibility, and AOT")
+ func reasonPrecedence() {
+ let report = GemmaOptimizationReport(
+ layer18Requested: false,
+ layer18Effective: false,
+ weightedUnsortRequested: true,
+ weightedUnsortEffective: false,
+ safeR1Requested: true,
+ safeR1GeometryEligible: true,
+ safeR1AOTAvailable: false,
+ safeR1NAXAvailable: true)
+
+ #expect(report.layer18.reason == .disabled)
+ #expect(report.weightedUnsort.reason == .modelIneligible)
+ #expect(report.safeR1.reason == .aotUnavailable)
+ #expect(!report.layer18.effective)
+ #expect(!report.weightedUnsort.effective)
+ #expect(!report.safeR1.effective)
+ }
+
+ @Test("NAX precedence and effective state render centrally")
+ func naxAndEffectiveRendering() {
+ let nax = GemmaOptimizationReport(
+ layer18Requested: true,
+ layer18Effective: true,
+ weightedUnsortRequested: true,
+ weightedUnsortEffective: true,
+ safeR1Requested: true,
+ safeR1GeometryEligible: true,
+ safeR1AOTAvailable: true,
+ safeR1NAXAvailable: true)
+ #expect(nax.safeR1.reason == .naxPrecedence)
+ #expect(!nax.safeR1.effective)
+
+ let effective = GemmaOptimizationReport(
+ layer18Requested: true,
+ layer18Effective: true,
+ weightedUnsortRequested: true,
+ weightedUnsortEffective: true,
+ safeR1Requested: true,
+ safeR1GeometryEligible: true,
+ safeR1AOTAvailable: true,
+ safeR1NAXAvailable: false)
+ let rendered = effective.logLine(modelId: "gemma-4-production")
+ #expect(effective.states.allSatisfy(\.effective))
+ #expect(rendered.contains("layer18(requested=true,effective=true,reason=effective)"))
+ #expect(rendered.contains("weighted_unsort(requested=true,effective=true,reason=effective)"))
+ #expect(rendered.contains("safe_r1(requested=true,effective=true,reason=effective)"))
+
+ let events = effective.telemetryEvents(modelId: "gemma-4-production")
+ #expect(events.count == 3)
+ #expect(events.allSatisfy { $0.kind == .engineHealth })
+ #expect(events.allSatisfy { $0.fields?["model"]?.description == "gemma-4-production" })
+ #expect(events.allSatisfy { $0.fields?["target"]?.description == "requested_1_effective_1" })
+ #expect(events.allSatisfy { $0.fields?["reason"]?.description == "effective" })
+ let allowedKeys = Set([
+ "component", "operation", "backend", "model", "target", "reason",
+ ])
+ #expect(events.allSatisfy { Set($0.fields?.keys.map { $0 } ?? []) == allowedKeys })
+ }
+}
+
+@Suite("Packaged retained-Gemma smoke")
+struct PackagedRetainedGemmaSmokeTests {
+ private let expectedProjection = [
+ GemmaOptimizationEnvironment.prefillLayer18Key: "18",
+ GemmaOptimizationEnvironment.weightedUnsortKey: "1",
+ GemmaOptimizationEnvironment.safeR1Key: "1",
+ ]
+
+ @Test("synthetic retained config has an exact three-key projection")
+ func exactProjectionAndNoRejectedKeys() throws {
+ let config = try PackagedRuntimeSmoke.retainedConfiguration()
+ let decodedProjection = GemmaOptimizationEnvironment.projection(
+ for: config.gemmaOptimizations)
+ #expect(decodedProjection == expectedProjection)
+ try PackagedRuntimeSmoke.validateRetainedProjection(decodedProjection)
+ #expect(
+ PackagedRuntimeSmoke.rejectedEnvironmentKeys(
+ projection: expectedProjection,
+ environment: expectedProjection).isEmpty)
+
+ var poisoned = expectedProjection
+ poisoned[GemmaOptimizationEnvironment.safeR1Key] = "poisoned"
+ #expect(
+ PackagedRuntimeSmoke.rejectedEnvironmentKeys(
+ projection: expectedProjection,
+ environment: poisoned)
+ == [GemmaOptimizationEnvironment.safeR1Key])
+ }
+
+ @Test("safe R1 gate requires requested packaged AOT and unarmed counters")
+ func safeR1Requirements() throws {
+ try PackagedRuntimeSmoke.validateSafeR1(
+ requested: true, aotAvailable: true, countersArmed: false)
+
+ #expect(throws: PackagedRuntimeSmoke.VerificationError.safeR1NotRequested) {
+ try PackagedRuntimeSmoke.validateSafeR1(
+ requested: false, aotAvailable: true, countersArmed: false)
+ }
+ #expect(throws: PackagedRuntimeSmoke.VerificationError.safeR1AOTUnavailable) {
+ try PackagedRuntimeSmoke.validateSafeR1(
+ requested: true, aotAvailable: false, countersArmed: false)
+ }
+ #expect(throws: PackagedRuntimeSmoke.VerificationError.safeR1CountersArmed) {
+ try PackagedRuntimeSmoke.validateSafeR1(
+ requested: true, aotAvailable: true, countersArmed: true)
+ }
+ }
+
+ @Test("signed-child marker is an exact output line")
+ func signedChildMarker() {
+ let exact = Data(
+ "noise\n\(PackagedRuntimeSmoke.gemmaOptimizationSuccessMarker)\npaged-kernel-runtime-smoke: ok\n".utf8)
+ let embedded = Data(
+ "prefix-\(PackagedRuntimeSmoke.gemmaOptimizationSuccessMarker)-suffix\n".utf8)
+ #expect(PackagedRuntimeSmoke.containsGemmaOptimizationSuccessMarker(exact))
+ #expect(!PackagedRuntimeSmoke.containsGemmaOptimizationSuccessMarker(embedded))
+ }
+}
diff --git a/provider-swift/Tests/ProviderCoreTests/GemmaVLMEngineV2LiveTests.swift b/provider-swift/Tests/ProviderCoreTests/GemmaVLMEngineV2LiveTests.swift
index e9c084c885..4f7d596707 100644
--- a/provider-swift/Tests/ProviderCoreTests/GemmaVLMEngineV2LiveTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/GemmaVLMEngineV2LiveTests.swift
@@ -1,35 +1,17 @@
// Copyright © 2026 Eigen Labs.
//
-// Live (weight-gated) validation of the v0.7.2 Gemma 4 VLM → engine_v2
-// text-model extraction, on the EXACT checkpoints production serves
-// (gemma-4-26b-qat-4bit / gemma-4-26b-8bit — both ship a vision tower, so
-// the provider loads them through VLMModelFactory exactly like
-// `ProviderLoop.loadModelContainer`). Two stages, mirroring the prod
-// serving path (updated for the v0.7.5 ONE-ENGINE release):
+// Live (weight-gated) validation of direct Gemma 4 VLM text-tower ownership
+// on the exact qat-4bit / 8bit checkpoints production serves. Both load via
+// `VLMModelFactory`, exactly like `ProviderLoop.loadModelContainer`.
//
-// (a) EXTRACTION + PARITY — extract the CBv2-adapted MLXLLM
-// `Gemma4TextModel` over the wrapper's weight arrays; the extraction
-// must not duplicate weights (MLX active memory grows by ~nothing),
-// and the built-in load-time parity gate must pass (each side's greedy
-// argmax sits in the other's top-5 at every probe position, max
-// |Δlogit| bounded — see EngineV2VLMTextExtraction for why token-exact
-// WRAPPER parity is structurally unattainable).
+// (a) DIRECT OWNERSHIP + MEMORY — resolving the CBv2 serving model returns
+// the wrapper's exact `textModel` object and does not construct or
+// materialize a second tower.
+// (b) V2 SERVE — that owned model serves a text request through the real
+// production bridge/routing seam with deterministic greedy output.
//
-// (b) V2 SERVE — the extracted model must serve a text request through
-// the REAL production seam (`EngineV2Bridge` +
-// `MultiModelBatchSchedulerEngine.streamChatCompletion`, the exact
-// engine construction the slot factory performs after its own
-// extraction): non-empty greedy output, byte-identical across two
-// identical submissions.
-//
-// DELETED with the legacy engine (v0.7.5 one-engine): the "v2 == legacy
-// greedy" stage (its reference — a legacy `BatchScheduler` run over the
-// same extracted module — no longer exists; the engine-repo v2-vs-legacy
-// invariant it verified died with the legacy engine) and the legacy-vision
-// interleave stage (media on a slot without a v2 bridge now throws the
-// fail-loud "no serving engine for media" error instead of serving via the
-// wrapper; vision-through-v2 interleave hygiene is pinned by
-// GemmaVLMVisionEngineV2LiveTests).
+// Vision-through-v2 image/video behavior and interleave hygiene remain pinned
+// by GemmaVLMVisionEngineV2LiveTests and GemmaVLMVideoEngineV2LiveTests.
//
// Gated like the other multi-GB Gemma tests: DARKBLOOM_LIVE_MLX_TESTS +
// DARKBLOOM_LIVE_MLX_GEMMA, and each checkpoint is skipped cleanly when not
@@ -45,7 +27,7 @@ import Testing
@testable import ProviderCore
-@Suite("Gemma 4 VLM engine_v2 extraction (live)", .serialized)
+@Suite("Gemma 4 VLM direct text tower (live)", .serialized)
struct GemmaVLMEngineV2LiveTests {
/// The two production Gemma 4 checkpoints (coordinator catalog ids
@@ -57,19 +39,14 @@ struct GemmaVLMEngineV2LiveTests {
private struct LoadedVLMSlot {
let modelID: String
- let directory: URL
let container: ModelContainer
let tokenizer: TokenizerHandle
let model: any LanguageModel
let eosTokenIds: Set
}
- /// Load a checkpoint EXACTLY the way the provider does for a VLM slot:
- /// `VLMModelFactory` (the container the vision tower lives in). Loaded
- /// BY HAND rather than through `LiveInferenceFixtures.loadBridge`
- /// because stage (a) must run the extraction ITSELF, on the raw wrapper
- /// handle, with clean before/after memory readings — the fixture's
- /// production bridge would run the extraction internally first.
+ /// Load a checkpoint exactly as the provider does for a VLM slot:
+ /// `VLMModelFactory`, retaining the wrapper that owns both towers.
private func loadVLMSlot(modelID: String, budgetBytes: Int) async throws -> LoadedVLMSlot {
guard LiveInferenceFixtures.ensureMetallibColocated() != nil else {
throw LiveFixtureSkip.missingMetallib
@@ -95,7 +72,6 @@ struct GemmaVLMEngineV2LiveTests {
}
return LoadedVLMSlot(
modelID: modelID,
- directory: directory,
container: container,
tokenizer: tokenizer,
model: snapshot.model,
@@ -122,48 +98,36 @@ struct GemmaVLMEngineV2LiveTests {
MLX.Memory.clearCache()
}
- /// Stage (a): weight-sharing extraction + the load-time parity gate.
- ///
- /// Two concerns, measured separately:
- /// * WEIGHT-SHARING — extract with the parity gate OFF and require MLX
- /// active memory to grow by no more than a small tolerance. Skeleton
- /// construction is lazy; `update(parameters:)` re-points at the
- /// wrapper's arrays; nothing multi-GiB may be retained (the removed
- /// SwitchGLU fused gate+up cache was the v0.7.2 black hole — a
- /// second weight copy would show up as ≥ the model size).
- /// * PARITY GATE — extract again with the gate ON (production default)
- /// and require it to pass and report a bounded max |Δlogit|. Both
- /// extractions share the same wrapper arrays, so this is not a second
- /// copy either; the returned model is the one stage (b) serves.
- private func runExtractionStage(
+ /// Resolve the production serving model and prove it is the wrapper-owned
+ /// object. Merely exposing/resolving the tower must not add meaningful MLX
+ /// residency; a second checkpoint tower would exceed this allowance by
+ /// many GiB.
+ private func runDirectTowerStage(
_ slot: LoadedVLMSlot
- ) throws -> EngineV2VLMTextExtraction.Extraction {
- // Weight-sharing invariant (parity gate off).
+ ) throws -> Gemma4TextModel {
+ let wrapper = try #require(
+ slot.model as? MLXVLM.Gemma4,
+ "production Gemma VLM checkpoint must load as MLXVLM.Gemma4")
MLX.Memory.clearCache()
let activeBefore = MLX.GPU.activeMemory
- let noParity = try EngineV2VLMTextExtraction.extractTextModel(
- from: slot.model, modelDirectory: slot.directory,
- environment: ["DARKBLOOM_ENGINE_V2_VLM_PARITY_CHECK": "0"])
- #expect(noParity.parityMaxAbsLogitDiff == nil)
+ let owned = wrapper.textModel
+ let serving = try EngineV2Factory.directServingModel(
+ model: wrapper, isVLM: true)
+ let textModel = try #require(serving as? Gemma4TextModel)
+
+ #expect(ObjectIdentifier(owned) == ObjectIdentifier(textModel))
+ #expect(wrapper.textModel === owned)
let growth = max(0, MLX.GPU.activeMemory - activeBefore)
- let allowance = 1_536 * 1024 * 1024
+ let allowance = 64 * 1024 * 1024
#expect(
growth < allowance,
Comment(
- rawValue: "extraction grew MLX active memory by \(growth) bytes "
- + "(> 1.5 GiB) — weights or a module cache were duplicated "
- + "instead of shared"))
-
- // Parity gate (production default env). Returns the model stage
- // (b) runs on.
- let extraction = try EngineV2VLMTextExtraction.extractTextModel(
- from: slot.model, modelDirectory: slot.directory)
- let diff = try #require(
- extraction.parityMaxAbsLogitDiff, "parity gate did not run under the default env")
+ rawValue: "direct tower resolution grew MLX active memory by "
+ + "\(growth) bytes (> 64 MiB), suggesting duplicate residency"))
print(
- "[gemma-vlm-v2] \(slot.modelID) parity max |Δlogit| = \(diff), "
- + "weight-share growth = \(growth) bytes")
- return extraction
+ "[gemma-vlm-v2] \(slot.modelID) direct tower identity passed; "
+ + "resolution growth = \(growth) bytes")
+ return textModel
}
/// Drive one OpenAI-shaped text request through the production routing
@@ -208,15 +172,13 @@ struct GemmaVLMEngineV2LiveTests {
return content
}
- /// Build the REAL production v2 engine + bridge over the extracted text
- /// model — the same construction `EngineV2SlotFactory.makeProductionBridge`
- /// performs right after ITS extraction, so stage (b) serves through the
- /// exact one-engine seam production uses.
+ /// Build the real production v2 engine + bridge over the VLM-owned text
+ /// model, matching `EngineV2SlotFactory.makeProductionBridge`.
private func makeBridge(
- slot: LoadedVLMSlot, extracted: Gemma4TextModel
+ slot: LoadedVLMSlot, textModel: Gemma4TextModel
) throws -> EngineV2Bridge {
let engine = try EngineV2Factory.makeProductionEngine(
- model: extracted,
+ model: textModel,
tokenizer: slot.tokenizer.inner,
kvBytesCapacity: 4 * 1024 * 1024 * 1024
)
@@ -231,10 +193,10 @@ struct GemmaVLMEngineV2LiveTests {
/// Structured bridge lifecycle: `shutdown()` (engine drain + pump
/// teardown) awaited on every exit path.
private func withBridge(
- slot: LoadedVLMSlot, extracted: Gemma4TextModel,
+ slot: LoadedVLMSlot, textModel: Gemma4TextModel,
_ body: (EngineV2Bridge) async throws -> Void
) async throws {
- let bridge = try makeBridge(slot: slot, extracted: extracted)
+ let bridge = try makeBridge(slot: slot, textModel: textModel)
do {
try await body(bridge)
} catch {
@@ -244,22 +206,16 @@ struct GemmaVLMEngineV2LiveTests {
await bridge.shutdown()
}
- /// Stages (a)+(b) for one checkpoint: measured extraction + parity
- /// gate, then greedy serve determinism through the production seam.
- private func runExtractionAndV2Serve(_ slot: LoadedVLMSlot) async throws {
- // (a) extraction + load-time parity gate + weight-sharing invariant.
- let extraction = try runExtractionStage(slot)
+ /// Direct identity/memory proof followed by deterministic production serve.
+ private func runDirectTowerAndV2Serve(_ slot: LoadedVLMSlot) async throws {
+ let textModel = try runDirectTowerStage(slot)
- // (b) v2 serve: the extracted model, behind the real EngineV2
- // bridge, must produce non-empty greedy output through the
- // production routing seam — and byte-identical output for two
- // identical submissions (greedy decode is deterministic).
- try await withBridge(slot: slot, extracted: extraction.model) { bridge in
+ try await withBridge(slot: slot, textModel: textModel) { bridge in
let prompt = OpenAIMessageContent.text(
"Count from one to five as digits separated by commas.")
let v2Text = try await streamText(
slot: slot, bridge: bridge, userContent: prompt, maxTokens: 32)
- #expect(!v2Text.isEmpty, "v2 text serve over the extracted model produced no content")
+ #expect(!v2Text.isEmpty, "v2 text serve over the VLM-owned model produced no content")
let v2TextAgain = try await streamText(
slot: slot, bridge: bridge, userContent: prompt, maxTokens: 32)
@@ -267,37 +223,37 @@ struct GemmaVLMEngineV2LiveTests {
#expect(
v2TextAgain == v2Text,
Comment(
- rawValue: "v2 greedy decode over the extracted model is "
+ rawValue: "v2 greedy decode over the VLM-owned model is "
+ "non-deterministic: \(v2Text.debugDescription) vs "
+ "\(v2TextAgain.debugDescription)"))
}
}
- // MARK: - qat-4bit: extraction parity + v2 serve
+ // MARK: - qat-4bit: direct ownership + v2 serve
@Test(
- "qat-4bit: extraction parity and v2 serve determinism",
+ "qat-4bit: direct tower identity, memory, and v2 serve determinism",
.enabled(if: LiveInferenceFixtures.gemmaTestsEnabled)
)
- func qat4bitExtractionAndV2Serve() async throws {
+ func qat4bitDirectTowerAndV2Serve() async throws {
try await withLoadedVLMSlot(
modelID: Self.qat4bitModelID, budgetBytes: 48 * 1024 * 1024 * 1024
) { slot in
- try await runExtractionAndV2Serve(slot)
+ try await runDirectTowerAndV2Serve(slot)
}
}
- // MARK: - 8bit: extraction parity + v2 serve
+ // MARK: - 8bit: direct ownership + v2 serve
@Test(
- "8bit: extraction parity and v2 serve determinism",
+ "8bit: direct tower identity, memory, and v2 serve determinism",
.enabled(if: LiveInferenceFixtures.gemmaTestsEnabled)
)
- func eightBitExtractionAndV2Serve() async throws {
+ func eightBitDirectTowerAndV2Serve() async throws {
try await withLoadedVLMSlot(
modelID: Self.eightBitModelID, budgetBytes: 64 * 1024 * 1024 * 1024
) { slot in
- try await runExtractionAndV2Serve(slot)
+ try await runDirectTowerAndV2Serve(slot)
}
}
}
diff --git a/provider-swift/Tests/ProviderCoreTests/GemmaVLMParityProbeMemoryLiveTests.swift b/provider-swift/Tests/ProviderCoreTests/GemmaVLMParityProbeMemoryLiveTests.swift
deleted file mode 100644
index d5223942f7..0000000000
--- a/provider-swift/Tests/ProviderCoreTests/GemmaVLMParityProbeMemoryLiveTests.swift
+++ /dev/null
@@ -1,281 +0,0 @@
-// Copyright © 2026 Eigen Labs.
-//
-// Live (weight-gated) regression for the v0.7.2 black-hole incident
-// (7×64 GB gemma-4-26b-8bit + 1×36 GB qat-4bit boxes rejecting 100% of
-// requests with the shared-KV capacity string from their first request,
-// permanently).
-//
-// ROOT CAUSE (measured on the real 8-bit checkpoint, 2026-07-03):
-// `MLXLMCommon.SwitchGLU` used to lazily concatenate a fused gate+up copy
-// of its quantized expert weights on FIRST FORWARD and retain it on the
-// module (~540 MB per MoE layer, ~15 GiB model-wide on gemma-4-26b-8bit).
-// The v0.7.2 VLM text extraction created a SECOND SwitchGLU tree over the
-// same weights, and the load-time parity probe ran one forward through
-// EACH tree — materializing TWO ~15 GiB fused copies before the first
-// request and pushing the box past the 90% unified-memory cap forever.
-//
-// The fused cache has since been DELETED from SwitchGLU (benchmarks showed
-// ~0% decode win at its only active shape, B=1 solo decode, for 8–15 GiB
-// of always-resident memory). The regression therefore tightens: the
-// extraction + parity probe must retain (almost) NOTHING beyond the
-// already-resident weights. This test asserts, on the real checkpoint:
-//
-// 1. GROWTH BOUND — extraction WITH the parity probe (production default)
-// grows MLX active memory by no more than a small tolerance (rope
-// tables / compiled-graph constants) — no multi-GiB retained state.
-// 2. STEADY STATE AT LOAD — re-running both probe forwards afterwards
-// grows active memory by ~nothing: no lazy build is waiting to fire
-// mid-serving.
-// 3. ADMISSION — a `GlobalKVCacheBudget` viewing the post-extraction MLX
-// state through a simulated 64 GB profile admits a typical worst-case
-// request reservation (the incident's first-request rejection,
-// inverted).
-// 4. CAPACITY CONSISTENCY — the weights-derived v2 static ceiling equals
-// the shared gate's live headroom on the same profile: with no
-// engine-retained overhead there is nothing to net out, and the
-// heartbeat max and the gate agree by construction.
-//
-// Gated like the other multi-GB Gemma tests: DARKBLOOM_LIVE_MLX_TESTS +
-// DARKBLOOM_LIVE_MLX_GEMMA; skipped cleanly when no checkpoint is cached.
-
-import Foundation
-import MLX
-import MLXLMCommon
-import MLXNN
-import MLXVLM
-import Testing
-
-@testable import ProviderCore
-
-@Suite("Gemma 4 VLM parity-probe memory hygiene (live)", .serialized)
-struct GemmaVLMParityProbeMemoryLiveTests {
-
- /// The incident checkpoint (catalog id `gemma-4-26b-8bit`); falls back to
- /// the qat-4bit build when only that one is cached — the no-retained-
- /// growth invariant is checkpoint-independent.
- private static let preferredModelIDs = [
- LiveInferenceFixtures.gemmaModelID,
- "mlx-community/gemma-4-26B-A4B-it-qat-4bit",
- ]
-
- private struct LoadedVLMSlot {
- let modelID: String
- let directory: URL
- let container: ModelContainer
- let model: any LanguageModel
- /// Scheduler-free sizing snapshot (v0.7.5 one-engine): the fp16 KV
- /// rate + weight bytes production feeds the load gate, the re-slice,
- /// and `makeEngineV2BridgeForSlot` (the legacy `BatchScheduler`
- /// surfaces this test used to read are deleted).
- let sizing: SlotSizingSnapshot
- }
-
- private func loadFirstCachedVLMSlot() async throws -> LoadedVLMSlot {
- guard LiveInferenceFixtures.ensureMetallibColocated() != nil else {
- throw LiveFixtureSkip.missingMetallib
- }
- var located: (String, URL)? = nil
- for modelID in Self.preferredModelIDs {
- if case .found(let directory) = LiveInferenceFixtures.locate(modelID) {
- located = (modelID, directory)
- break
- }
- }
- guard let (modelID, directory) = located else {
- throw LiveFixtureSkip.modelNotInCache(Self.preferredModelIDs[0])
- }
- #expect(ProviderLoop.modelIsVLM(at: directory))
- LiveInferenceFixtures.applyMemoryBudget(maxBytes: 64 * 1024 * 1024 * 1024)
-
- let container = try await VLMModelFactory.shared.loadContainer(
- from: directory, using: LocalTokenizerLoader())
- // Same post-load sizing pass production runs (ProviderLoop+
- // ModelLoading): weight walk + engine-truth fp16 KV rate. Pure
- // reads — nothing here may allocate MLX state, so it cannot
- // perturb the growth baselines below.
- let sizing = await SlotSizingSnapshot.build(
- container: container,
- modelPath: directory,
- fallbackDefaultMaxTokens: 256)
- let snapshot = await container.perform { ctx in
- EngineV2ModelSnapshot(
- model: ctx.model,
- eosTokenIds: ctx.configuration.eosTokenIds,
- extraEOSTokens: [])
- }
- return LoadedVLMSlot(
- modelID: modelID,
- directory: directory,
- container: container,
- model: snapshot.model,
- sizing: sizing
- )
- }
-
- private static func gib(_ bytes: Int) -> String {
- String(format: "%.2f GiB", Double(bytes) / (1024 * 1024 * 1024))
- }
-
- @Test(
- "extraction + parity probe leave the shared KV budget serveable (64 GB profile)",
- .enabled(if: LiveInferenceFixtures.gemmaTestsEnabled)
- )
- func parityProbeMemoryHygieneAndBudgetAdmission() async throws {
- let slot = try await loadFirstCachedVLMSlot()
- // No unload hop anymore: the multi-GB residency dies with `slot` at
- // scope exit (the container is the only retainer); trim the probe's
- // pool garbage on every exit path so the next serialized live suite
- // starts from a clean pool.
- defer { MLX.Memory.clearCache() }
- try await runBody(slot)
- }
-
- private func runBody(_ slot: LoadedVLMSlot) async throws {
- // Mirror the production sequence: the load path's post-load headroom
- // check trims the cold-load pool BEFORE the bridge build, so the
- // pre-extraction baseline starts from a clean pool exactly like prod.
- MLX.Stream().synchronize()
- MLX.Memory.clearCache()
- let activeBefore = MLX.GPU.activeMemory
- let sysBefore = SystemMemory.availableBytes() ?? 0
- print(
- "[parity-mem] pre-extraction: active=\(Self.gib(activeBefore)) "
- + "cache=\(Self.gib(MLX.GPU.cacheMemory)) sysAvail=\(Self.gib(Int(sysBefore)))")
-
- // REAL extraction with the parity gate ON (production default env).
- let extraction = try EngineV2VLMTextExtraction.extractTextModel(
- from: slot.model, modelDirectory: slot.directory)
- #expect(extraction.parityMaxAbsLogitDiff != nil)
-
- let activeAfter = MLX.GPU.activeMemory
- let cacheAfter = MLX.GPU.cacheMemory
- let activeGrowth = max(0, activeAfter - activeBefore)
- print(
- "[parity-mem] post-extraction: active=\(Self.gib(activeAfter)) "
- + "cache=\(Self.gib(cacheAfter)) activeGrowth=\(Self.gib(activeGrowth))")
-
- // 1. GROWTH BOUND: the extraction shares the wrapper's weight arrays
- // and retains no engine-side caches, so the only legitimate
- // growth is small one-time state (rope tables, compiled-graph
- // constants, probe stragglers). Pre-v0.7.3 this measured ~30 GiB
- // (two fused copies); with the fused cache deleted outright the
- // bar is a flat 2 GiB.
- let tolerance = 2 * 1024 * 1024 * 1024
- #expect(
- activeGrowth < tolerance,
- Comment(
- rawValue: "extraction + parity probe retained \(Self.gib(activeGrowth)) "
- + "(> 2 GiB) — a weight or cache copy is being built "
- + "(the v0.7.2 black-hole shape)"))
- // The pool must also come back trimmed (post-probe clearCache).
- #expect(
- cacheAfter < 1 * 1024 * 1024 * 1024,
- Comment(
- rawValue: "probe left \(Self.gib(cacheAfter)) in the MLX pool — "
- + "the post-probe clearCache is missing"))
-
- // 2. STEADY STATE AT LOAD: re-running both probe forwards must not
- // materialize anything new — no lazy multi-GiB build can be
- // waiting to fire on the first real request.
- guard let wrapper = slot.model as? MLXVLM.Gemma4 else {
- Issue.record("prod Gemma 4 slot did not load the MLXVLM.Gemma4 wrapper")
- return
- }
- let probeTokens = MLXArray([2, 651, 6134, 1024, 578, 108, 2364].map(Int32.init))
- .expandedDimensions(axis: 0)
- eval(wrapper(probeTokens, cache: nil))
- eval(extraction.model(probeTokens, cache: nil))
- MLX.Stream().synchronize()
- MLX.Memory.clearCache()
- let activeSteady = MLX.GPU.activeMemory
- let steadyGrowth = max(0, activeSteady - activeAfter)
- print("[parity-mem] steady-state re-forward growth=\(Self.gib(steadyGrowth))")
- #expect(
- steadyGrowth < 512 * 1024 * 1024,
- Comment(
- rawValue: "serving forwards after load grew active memory by "
- + "\(Self.gib(steadyGrowth)) — a lazy per-tree cache still fires at "
- + "request time"))
-
- // 3. ADMISSION on the incident profile: view the REAL post-extraction
- // MLX counters through a synthetic 64 GB box (the incident
- // hardware). The budget must admit one typical worst-case request
- // (2 KiB prompt + 4096 max tokens at the slot's fp16 KV rate) —
- // pre-fix this is exactly the reservation that failed 100% of the
- // time from the first request.
- let fp16Rate = slot.sizing.fp16KVBytesPerToken
- let totalBytes: UInt64 = 64 * 1024 * 1024 * 1024
- let budget = GlobalKVCacheBudget(
- memorySnapshot: {
- let active = UInt64(max(0, MLX.GPU.activeMemory))
- let cache = UInt64(max(0, MLX.GPU.cacheMemory))
- let used = active + cache
- // Simulated OS view of the 64 GB box: whatever the provider
- // isn't holding, minus a 4 GiB OS/wired allowance.
- let osAllowance: UInt64 = 4 * 1024 * 1024 * 1024
- let free = totalBytes > used + osAllowance ? totalBytes - used - osAllowance : 0
- return .init(
- total: totalBytes, active: active, cache: cache, systemAvailable: free)
- }
- )
- let worstCaseTokens = 2048 + 4096
- let admitted = await budget.reserve(
- requestID: "incident-probe", kvBytesPerToken: fp16Rate, tokenCount: worstCaseTokens)
- print(
- "[parity-mem] 64GB-profile admission: fp16KVBytesPerToken=\(fp16Rate) "
- + "worstCaseTokens=\(worstCaseTokens) admitted=\(admitted)")
- #expect(
- admitted,
- Comment(
- rawValue: "the shared KV budget rejected a typical request on the simulated "
- + "64 GB profile after the parity probe — the v0.7.2 black-hole signature"))
- await budget.release(requestID: "incident-probe")
- #expect(await budget.reservationIDsForTesting().isEmpty)
-
- // 4. CAPACITY CONSISTENCY: the v2 static ceiling is sized from the
- // SIZING SNAPSHOT's weight figure (the exact input production
- // makeEngineV2BridgeForSlot passes — ProviderLoop+EngineV2 reads
- // `sizing.weightsBytes`), NOT from live MLX usage, so this
- // genuinely catches the over-advertising shape: if
- // extraction/probe retained any non-weight state, the
- // weights-derived ceiling would exceed the gate's live headroom
- // by exactly that retained amount. With the fused cache deleted,
- // the divergence must fit inside the same 2 GiB retained-state
- // bar as step 1 (rope tables, compiled-graph constants), and can
- // never be negative beyond rounding (live use cannot be below
- // the resident weights).
- MLX.Stream().synchronize()
- MLX.Memory.clearCache()
- let snapshotWeightBytes = slot.sizing.weightsBytes
- let mlxUsedNow =
- UInt64(max(0, MLX.GPU.activeMemory)) + UInt64(max(0, MLX.GPU.cacheMemory))
- let ceiling = EngineV2KVSizing.engineKVBytesCapacity(
- newModelWeightBytes: snapshotWeightBytes,
- coResidentWeightBytes: 0,
- existingEngineKVCapacities: [],
- physicalBytes: totalBytes)
- let gateHeadroom = UnifiedMemoryCap.liveKVHeadroomBytes(
- physicalBytes: totalBytes,
- mlxUsedBytes: mlxUsedNow,
- systemAvailableBytes: .max)
- let retainedOverhead = Int64(ceiling) - Int64(clamping: gateHeadroom)
- print(
- "[parity-mem] 64GB-profile capacity: ceiling=\(Self.gib(ceiling)) "
- + "gateHeadroom=\(Self.gib(Int(gateHeadroom))) "
- + "retainedOverhead=\(Self.gib(Int(retainedOverhead)))")
- #expect(
- retainedOverhead <= Int64(tolerance),
- Comment(
- rawValue: "weights-derived v2 ceiling \(Self.gib(ceiling)) exceeds the "
- + "shared-gate live headroom \(Self.gib(Int(gateHeadroom))) by more than "
- + "the retained-state bar — extraction/probe is holding non-weight "
- + "memory the heartbeat would over-advertise (the finding-2 "
- + "over-routing shape)"))
- #expect(
- retainedOverhead >= -(64 * 1024 * 1024),
- Comment(
- rawValue: "shared-gate headroom exceeds the weights-derived ceiling — "
- + "live MLX usage measured below the snapshot's resident weights, "
- + "which means the weight figure itself is inflated"))
- }
-}
diff --git a/provider-swift/Tests/ProviderCoreTests/GemmaVLMSharedTowerMemoryLiveTests.swift b/provider-swift/Tests/ProviderCoreTests/GemmaVLMSharedTowerMemoryLiveTests.swift
new file mode 100644
index 0000000000..4315b98173
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/GemmaVLMSharedTowerMemoryLiveTests.swift
@@ -0,0 +1,224 @@
+// Copyright © 2026 Eigen Labs.
+//
+// Live (weight-gated) regression for Gemma 4 VLM shared-tower residency.
+// The loaded MLXVLM wrapper must expose its already-owned text tower to
+// CBv2 without constructing a second module or retaining a second checkpoint
+// worth of state. On a real production checkpoint this suite proves:
+//
+// 1. DIRECT RESOLUTION — production model resolution returns the wrapper's
+// exact `textModel` object with negligible active-memory growth.
+// 2. STEADY STATE — direct VLM and CBv2 forwards over that one object do not
+// trigger a second lazy multi-GiB module cache.
+// 3. ADMISSION — the post-forward shared KV budget remains serveable on the
+// incident 64 GB profile.
+// 4. CAPACITY CONSISTENCY — weights-derived capacity and live headroom stay
+// aligned because no separately reconstructed tower is resident.
+//
+// Gated by DARKBLOOM_LIVE_MLX_TESTS + DARKBLOOM_LIVE_MLX_GEMMA and skipped
+// cleanly when no checkpoint is cached.
+
+import Foundation
+import MLX
+import MLXLLM
+import MLXLMCommon
+import MLXNN
+import MLXVLM
+import Testing
+
+@testable import ProviderCore
+
+@Suite("Gemma 4 VLM shared-tower memory hygiene (live)", .serialized)
+struct GemmaVLMSharedTowerMemoryLiveTests {
+
+ /// The incident checkpoint (catalog id `gemma-4-26b-8bit`); falls back to
+ /// the qat-4bit build when only that one is cached — the no-retained-
+ /// growth invariant is checkpoint-independent.
+ private static let preferredModelIDs = [
+ LiveInferenceFixtures.gemmaModelID,
+ "mlx-community/gemma-4-26B-A4B-it-qat-4bit",
+ ]
+
+ private struct LoadedVLMSlot {
+ let modelID: String
+ let container: ModelContainer
+ let model: any LanguageModel
+ /// Scheduler-free sizing snapshot (v0.7.5 one-engine): the fp16 KV
+ /// rate + weight bytes production feeds the load gate, the re-slice,
+ /// and `makeEngineV2BridgeForSlot` (the legacy `BatchScheduler`
+ /// surfaces this test used to read are deleted).
+ let sizing: SlotSizingSnapshot
+ }
+
+ private func loadFirstCachedVLMSlot() async throws -> LoadedVLMSlot {
+ guard LiveInferenceFixtures.ensureMetallibColocated() != nil else {
+ throw LiveFixtureSkip.missingMetallib
+ }
+ var located: (String, URL)? = nil
+ for modelID in Self.preferredModelIDs {
+ if case .found(let directory) = LiveInferenceFixtures.locate(modelID) {
+ located = (modelID, directory)
+ break
+ }
+ }
+ guard let (modelID, directory) = located else {
+ throw LiveFixtureSkip.modelNotInCache(Self.preferredModelIDs[0])
+ }
+ #expect(ProviderLoop.modelIsVLM(at: directory))
+ LiveInferenceFixtures.applyMemoryBudget(maxBytes: 64 * 1024 * 1024 * 1024)
+
+ let container = try await VLMModelFactory.shared.loadContainer(
+ from: directory, using: LocalTokenizerLoader())
+ // Same post-load sizing pass production runs (ProviderLoop+
+ // ModelLoading): weight walk + engine-truth fp16 KV rate. Pure
+ // reads — nothing here may allocate MLX state, so it cannot
+ // perturb the growth baselines below.
+ let sizing = await SlotSizingSnapshot.build(
+ container: container,
+ modelPath: directory,
+ fallbackDefaultMaxTokens: 256)
+ let snapshot = await container.perform { ctx in
+ EngineV2ModelSnapshot(
+ model: ctx.model,
+ eosTokenIds: ctx.configuration.eosTokenIds,
+ extraEOSTokens: [])
+ }
+ return LoadedVLMSlot(
+ modelID: modelID,
+ container: container,
+ model: snapshot.model,
+ sizing: sizing
+ )
+ }
+
+ private static func gib(_ bytes: Int) -> String {
+ String(format: "%.2f GiB", Double(bytes) / (1024 * 1024 * 1024))
+ }
+
+ @Test(
+ "direct shared tower leaves the KV budget serveable (64 GB profile)",
+ .enabled(if: LiveInferenceFixtures.gemmaTestsEnabled)
+ )
+ func sharedTowerMemoryHygieneAndBudgetAdmission() async throws {
+ let slot = try await loadFirstCachedVLMSlot()
+ // The multi-GB residency dies with `slot` at scope exit; trim forward
+ // buffers so the next serialized live suite starts from a clean pool.
+ defer { MLX.Memory.clearCache() }
+ try await runBody(slot)
+ }
+
+ private func runBody(_ slot: LoadedVLMSlot) async throws {
+ // Mirror production: trim cold-load pool state before direct serving
+ // model resolution and take the residency baseline.
+ MLX.Stream().synchronize()
+ MLX.Memory.clearCache()
+ let activeBefore = MLX.GPU.activeMemory
+ let sysBefore = SystemMemory.availableBytes() ?? 0
+ print(
+ "[shared-tower-mem] pre-resolution: active=\(Self.gib(activeBefore)) "
+ + "cache=\(Self.gib(MLX.GPU.cacheMemory)) sysAvail=\(Self.gib(Int(sysBefore)))")
+
+ let wrapper = try #require(
+ slot.model as? MLXVLM.Gemma4,
+ "production Gemma 4 slot must load the MLXVLM.Gemma4 wrapper")
+ let owned = wrapper.textModel
+ let serving = try EngineV2Factory.directServingModel(
+ model: wrapper, isVLM: true)
+ let textModel = try #require(serving as? MLXLLM.Gemma4TextModel)
+ #expect(ObjectIdentifier(owned) == ObjectIdentifier(textModel))
+
+ let activeAfter = MLX.GPU.activeMemory
+ let activeGrowth = max(0, activeAfter - activeBefore)
+ print(
+ "[shared-tower-mem] post-resolution: active=\(Self.gib(activeAfter)) "
+ + "activeGrowth=\(Self.gib(activeGrowth))")
+ let tolerance = 64 * 1024 * 1024
+ #expect(
+ activeGrowth < tolerance,
+ Comment(
+ rawValue: "direct tower resolution retained \(Self.gib(activeGrowth)) "
+ + "(> 64 MiB), suggesting a second module or weight copy"))
+
+ // Direct VLM and CBv2 paths call the same object. A second forward must
+ // not materialize a second per-tree cache.
+ let probeTokens = MLXArray([2, 65, 61, 24, 57, 10, 23].map(Int32.init))
+ .expandedDimensions(axis: 0)
+ eval(wrapper(probeTokens, cache: nil))
+ eval(textModel(probeTokens, cache: nil))
+ MLX.Stream().synchronize()
+ MLX.Memory.clearCache()
+ let activeSteady = MLX.GPU.activeMemory
+ let steadyGrowth = max(0, activeSteady - activeAfter)
+ print(
+ "[shared-tower-mem] steady-state re-forward growth=\(Self.gib(steadyGrowth))")
+ #expect(
+ steadyGrowth < 512 * 1024 * 1024,
+ Comment(
+ rawValue: "shared-tower forwards grew active memory by "
+ + "\(Self.gib(steadyGrowth)); a lazy duplicate cache fired"))
+ // Admission on the incident 64 GB profile: the live post-forward
+ // counters must admit a typical worst-case request.
+ let fp16Rate = slot.sizing.fp16KVBytesPerToken
+ let totalBytes: UInt64 = 64 * 1024 * 1024 * 1024
+ let budget = GlobalKVCacheBudget(
+ memorySnapshot: {
+ let active = UInt64(max(0, MLX.GPU.activeMemory))
+ let cache = UInt64(max(0, MLX.GPU.cacheMemory))
+ let used = active + cache
+ // Simulated OS view of the 64 GB box: whatever the provider
+ // isn't holding, minus a 4 GiB OS/wired allowance.
+ let osAllowance: UInt64 = 4 * 1024 * 1024 * 1024
+ let free = totalBytes > used + osAllowance ? totalBytes - used - osAllowance : 0
+ return .init(
+ total: totalBytes, active: active, cache: cache, systemAvailable: free)
+ }
+ )
+ let worstCaseTokens = 2048 + 4096
+ let admitted = await budget.reserve(
+ requestID: "incident-probe", kvBytesPerToken: fp16Rate, tokenCount: worstCaseTokens)
+ print(
+ "[shared-tower-mem] 64GB-profile admission: fp16KVBytesPerToken=\(fp16Rate) "
+ + "worstCaseTokens=\(worstCaseTokens) admitted=\(admitted)")
+ #expect(
+ admitted,
+ Comment(
+ rawValue: "the shared KV budget rejected a typical request on the "
+ + "64 GB profile after direct shared-tower resolution"))
+ await budget.release(requestID: "incident-probe")
+ #expect(await budget.reservationIDsForTesting().isEmpty)
+
+ // Capacity consistency: direct ownership leaves no separately
+ // reconstructed model state for the weights-derived ceiling to miss.
+ MLX.Stream().synchronize()
+ MLX.Memory.clearCache()
+ let snapshotWeightBytes = slot.sizing.weightsBytes
+ let mlxUsedNow =
+ UInt64(max(0, MLX.GPU.activeMemory)) + UInt64(max(0, MLX.GPU.cacheMemory))
+ let ceiling = EngineV2KVSizing.engineKVBytesCapacity(
+ newModelWeightBytes: snapshotWeightBytes,
+ coResidentWeightBytes: 0,
+ existingEngineKVCapacities: [],
+ physicalBytes: totalBytes)
+ let gateHeadroom = UnifiedMemoryCap.liveKVHeadroomBytes(
+ physicalBytes: totalBytes,
+ mlxUsedBytes: mlxUsedNow,
+ systemAvailableBytes: .max)
+ let retainedOverhead = Int64(ceiling) - Int64(clamping: gateHeadroom)
+ print(
+ "[shared-tower-mem] 64GB-profile capacity: ceiling=\(Self.gib(ceiling)) "
+ + "gateHeadroom=\(Self.gib(Int(gateHeadroom))) "
+ + "retainedOverhead=\(Self.gib(Int(retainedOverhead)))")
+ let capacityTolerance = 2 * 1024 * 1024 * 1024
+ #expect(
+ retainedOverhead <= Int64(capacityTolerance),
+ Comment(
+ rawValue: "weights-derived v2 ceiling \(Self.gib(ceiling)) exceeds the "
+ + "shared-gate live headroom \(Self.gib(Int(gateHeadroom))) by more "
+ + "than the retained-state bar, indicating unaccounted residency"))
+ #expect(
+ retainedOverhead >= -(64 * 1024 * 1024),
+ Comment(
+ rawValue: "shared-gate headroom exceeds the weights-derived ceiling — "
+ + "live MLX usage measured below the snapshot's resident weights, "
+ + "which means the weight figure itself is inflated"))
+ }
+}
diff --git a/provider-swift/Tests/ProviderCoreTests/GemmaVLMVideoEngineV2LiveTests.swift b/provider-swift/Tests/ProviderCoreTests/GemmaVLMVideoEngineV2LiveTests.swift
index 01efcac407..566d640a45 100644
--- a/provider-swift/Tests/ProviderCoreTests/GemmaVLMVideoEngineV2LiveTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/GemmaVLMVideoEngineV2LiveTests.swift
@@ -4,10 +4,8 @@
// production Gemma 4 checkpoint (`gemma-4-26b-qat-4bit`). Self-contained
// harness — deliberately independent of `GemmaVLMVisionEngineV2LiveTests`
// (same precedent that file set vs the 0.7.3 suites; nothing here touches
-// it). Slots are built through `LiveInferenceFixtures.loadBridge` — the
-// production `EngineV2SlotFactory.makeProductionBridge` construction
-// (weight-sharing text extraction + parity gate), i.e. the ONE engine
-// every slot serves with since v0.7.5. Stages:
+// it). Slots use `LiveInferenceFixtures.loadBridge`, which follows production
+// direct shared-tower construction: one engine serves every slot request.
//
// (a) CONSTRUCTION INTROSPECTION — `EngineV2VisionPrefill.prepare` on a
// real 4-distinct-frame clip: one span per sampled frame, spans ==
@@ -29,16 +27,10 @@
// measured and logged (informational — the vision tower runs
// pre-submit).
//
-// DELETED with the legacy engine (v0.7.5 one-engine): the wrapper
-// parity reference. Media on a slot WITHOUT a v2 bridge no longer
-// serves at all — `MultiModelBatchSchedulerEngine` throws the
-// fail-loud "no serving engine for media (no v2 bridge)" internal
-// error (pinned by the non-live routing tests) — so there is no
-// legacy output to log. (Token-exact wrapper parity was never
-// asserted anyway: the extracted model implements the checkpoint's
-// declared `rope_type: "proportional"` correctly while the wrapper
-// deviated, plus bf16 kernel-order noise — see
-// EngineV2VLMTextExtraction.)
+// The removed legacy comparison is no longer needed for tower parity:
+// direct VLM and CBv2 now invoke the same `Gemma4TextModel` instance.
+// Media without a v2 bridge still fails loudly, as pinned by non-live
+// routing tests.
//
// (c) 32-FRAME SAMPLING CAP — a 40-second, 40-frame clip: the processor
// samples uniformly and caps at 32; construction must carve ≤ 32
diff --git a/provider-swift/Tests/ProviderCoreTests/GemmaVLMVisionEngineV2LiveTests.swift b/provider-swift/Tests/ProviderCoreTests/GemmaVLMVisionEngineV2LiveTests.swift
index 042f4ee801..6918730b4f 100644
--- a/provider-swift/Tests/ProviderCoreTests/GemmaVLMVisionEngineV2LiveTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/GemmaVLMVisionEngineV2LiveTests.swift
@@ -25,15 +25,9 @@
// masks / spliced embeddings must leave no residue in the engine's
// caches — the Qwen3.5-mrope-class regression pattern).
//
-// DELETED with the legacy engine (v0.7.5): the wrapper-path greedy
-// comparison and the text/legacy-vision/text interleave. Media on a slot
-// WITHOUT a v2 bridge no longer serves at all — it throws the fail-loud
-// "no serving engine for media (no v2 bridge)" internal error, pinned by
-// the non-live routing tests — so there is no legacy output to compare
-// against. (Wrapper-vs-extracted token-exactness was never asserted anyway:
-// the extracted model implements the checkpoint's declared `rope_type:
-// "proportional"` correctly while the wrapper deviates, plus bf16
-// kernel-order noise — see EngineV2VLMTextExtraction.)
+// The removed legacy comparison is no longer needed for tower parity: direct
+// VLM and CBv2 now invoke the same `Gemma4TextModel` instance. Media without
+// a v2 bridge still fails loudly, as pinned by non-live routing tests.
//
// Teardown here is structured (bridge shutdown awaited on every exit path)
// so this suite never overlaps residency with other serialized live runs.
@@ -82,10 +76,9 @@ struct GemmaVLMVisionEngineV2LiveTests {
// MARK: - Harness (the provider's one-engine VLM slot shape)
- /// One loaded v2 VLM slot: the PRODUCTION bridge (built through
- /// `EngineV2SlotFactory.makeProductionBridge`, weight-sharing text
- /// extraction + parity gate included), the retained VLM container the
- /// vision tower runs in, and the tokenizer for the registry entry.
+ /// One loaded v2 VLM slot: the production bridge over the wrapper-owned
+ /// text tower, the retained VLM container that runs vision, and the
+ /// tokenizer for the registry entry.
private struct LoadedV2VLMSlot {
let modelID: String
let bridge: EngineV2Bridge
diff --git a/provider-swift/Tests/ProviderCoreTests/LaunchAgentRestartTests.swift b/provider-swift/Tests/ProviderCoreTests/LaunchAgentRestartTests.swift
index 84abcb8ebd..cccf8de7b4 100644
--- a/provider-swift/Tests/ProviderCoreTests/LaunchAgentRestartTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/LaunchAgentRestartTests.swift
@@ -1,3 +1,4 @@
+import Foundation
import Testing
@testable import ProviderCore
@@ -81,6 +82,16 @@ struct LaunchAgentEnvironmentTests {
from: ["DARKBLOOM_MTP_MAX_RECTANGULAR_TOKENS": "4", "PATH": "/usr/bin"])
#expect(out == ["DARKBLOOM_MTP_MAX_RECTANGULAR_TOKENS": "4"])
}
+
+ @Test func excludesConfigBackedGemmaControlsFromDaemonEnvironment() {
+ let out = LaunchAgent.passthroughEnvironment(from: [
+ "DARKBLOOM_PREFIX_CACHE": "0",
+ GemmaOptimizationEnvironment.prefillLayer18Key: "poison",
+ GemmaOptimizationEnvironment.weightedUnsortKey: "poison",
+ GemmaOptimizationEnvironment.safeR1Key: "poison",
+ ])
+ #expect(out == ["DARKBLOOM_PREFIX_CACHE": "0"])
+ }
}
@Suite("LaunchAgent service plist")
@@ -90,7 +101,13 @@ struct LaunchAgentServicePlistTests {
label: "io.darkbloom.provider",
programArguments: ["/usr/local/bin/darkbloom", "start", "--foreground"],
logPath: "/tmp/p.log",
- environment: ["DARKBLOOM_PREFIX_CACHE": "0", "PATH": "/usr/bin"]
+ environment: [
+ "DARKBLOOM_PREFIX_CACHE": "0",
+ GemmaOptimizationEnvironment.prefillLayer18Key: "poison",
+ GemmaOptimizationEnvironment.weightedUnsortKey: "poison",
+ GemmaOptimizationEnvironment.safeR1Key: "poison",
+ "PATH": "/usr/bin",
+ ]
)
// RunAtLoad=true so a rebooted / auto-login box restarts (and re-attests via
// APNs) with no human; KeepAlive stays false to avoid racing the self-updater.
@@ -109,4 +126,27 @@ struct LaunchAgentServicePlistTests {
#expect(plist["EnvironmentVariables"] == nil)
#expect(plist["RunAtLoad"] as? Bool == true)
}
+
+ @Test func customConfigFlagAndAbsolutePathStayAdjacent() throws {
+ let arguments = LaunchAgent.serviceProgramArguments(
+ binaryPath: "/usr/local/bin/darkbloom",
+ coordinatorURL: "wss://api.darkbloom.dev/ws/provider",
+ models: ["org/model"],
+ idleTimeout: 15,
+ configPath: URL(fileURLWithPath: "/tmp/custom provider.toml")
+ )
+ let flagIndex = try #require(arguments.firstIndex(of: "--config"))
+ #expect(arguments[flagIndex + 1] == "/tmp/custom provider.toml")
+ }
+
+ @Test func defaultConfigPathRemainsImplicit() {
+ let arguments = LaunchAgent.serviceProgramArguments(
+ binaryPath: "/usr/local/bin/darkbloom",
+ coordinatorURL: "wss://api.darkbloom.dev/ws/provider",
+ models: [],
+ idleTimeout: nil,
+ configPath: nil
+ )
+ #expect(!arguments.contains("--config"))
+ }
}
diff --git a/provider-swift/Tests/ProviderCoreTests/LiveInferenceFixtures.swift b/provider-swift/Tests/ProviderCoreTests/LiveInferenceFixtures.swift
index 83c7cc8a60..a5690f48c5 100644
--- a/provider-swift/Tests/ProviderCoreTests/LiveInferenceFixtures.swift
+++ b/provider-swift/Tests/ProviderCoreTests/LiveInferenceFixtures.swift
@@ -7,6 +7,7 @@ import MLXLMCommon
// MARK: - Tiny, fast model used for the bulk of live tests.
enum LiveInferenceFixtures {
+ private static let metallibColocationLock = NSLock()
/// Default tiny MLX-community model: ~600M params, ~1 GB on disk in 8-bit.
/// Loads in seconds and finishes a 16-token generation in well under 1s
@@ -78,17 +79,18 @@ enum LiveInferenceFixtures {
///
/// `.build//debug/PackageTests.xctest/Contents/MacOS/`
///
- /// `scripts/fetch-metallib.sh` only places the metallib at
- /// `.build/debug/mlx.metallib`, which is *not* where MLX looks. This
- /// helper finds the metallib in any well-known location (incl. the
- /// fetch script's drop site) and copies it next to the test runner
- /// so MLX's `current_binary_dir() / "mlx.metallib"` lookup succeeds
- /// on the first GPU call. Idempotent.
+ /// The canonical source helper stages a metallib in the Swift build
+ /// directory. This helper finds that source and always replaces the copy
+ /// beside the test runner so a stale pre-existing file cannot survive into
+ /// the current test invocation.
///
- /// Returns the path to the colocated metallib on success, or `nil` if
- /// no source metallib could be found anywhere -- in which case the
- /// caller should skip the test rather than crashing in the GPU init.
+ /// Returns the path to the colocated metallib on success, or `nil` if no
+ /// source metallib could be found -- in which case the caller should skip
+ /// the test rather than crashing in GPU initialization.
static func ensureMetallibColocated() -> URL? {
+ metallibColocationLock.lock()
+ defer { metallibColocationLock.unlock() }
+
let fm = FileManager.default
// 1. Find the test bundle's MacOS dir. Bundle(for:) reliably points
@@ -99,28 +101,32 @@ enum LiveInferenceFixtures {
}
let destination = testBundleMacOSDir.appendingPathComponent("mlx.metallib")
- if fm.fileExists(atPath: destination.path) {
- return destination
- }
-
- // 2. Find a source metallib to copy.
+ // 2. Resolve the authoritative staged source before considering the
+ // runner copy. Existence alone does not prove source compatibility.
guard let source = findSourceMetallib() else {
return nil
}
do {
- try fm.copyItem(at: source, to: destination)
+ // Copy beside the destination, then atomically replace the runner
+ // file without loading the 150 MB+ metallib into process memory.
+ let temporary = testBundleMacOSDir
+ .appendingPathComponent(".mlx.metallib.\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: temporary) }
+ try fm.copyItem(at: source, to: temporary)
+ if fm.fileExists(atPath: destination.path) {
+ _ = try fm.replaceItemAt(destination, withItemAt: temporary)
+ } else {
+ try fm.moveItem(at: temporary, to: destination)
+ }
// Mirror to MLX_METALLIB_PATH so our own `locateMetallib()`
// (which trusts _NSGetExecutablePath, i.e. the xctest host
// path) can find it too if anyone else queries.
setenv("MLX_METALLIB_PATH", destination.path, 1)
return destination
} catch {
- // Last resort: still set MLX_METALLIB_PATH so any code that
- // queries `locateMetallib()` succeeds, even though the MLX
- // C++ runtime won't honor it and tests will crash on first
- // GPU call. Better to let the test report the failure than
- // to silently skip.
+ // The C++ runtime does not honor MLX_METALLIB_PATH, so failure to
+ // replace its runner-local copy must remain a fixture failure.
setenv("MLX_METALLIB_PATH", source.path, 1)
return nil
}
@@ -146,29 +152,33 @@ enum LiveInferenceFixtures {
return nil
}
- /// Look for a metallib at the spots `scripts/fetch-metallib.sh` and the
- /// release pipeline drop one. We anchor at the test bundle (which is
- /// inside `.build//debug/...`) and walk up to the package root.
+ /// Look for a metallib at the canonical helper's drop sites. We anchor at
+ /// the test bundle (`.build///...`) and accept only
+ /// the configuration which contains the running test bundle.
private static func findSourceMetallib() -> URL? {
let fm = FileManager.default
- if let env = ProcessInfo.processInfo.environment["MLX_METALLIB_SOURCE"],
- !env.isEmpty,
- fm.fileExists(atPath: env) {
- return URL(fileURLWithPath: env)
- }
-
// Anchor at the test bundle path -- much more reliable than
// _NSGetExecutablePath under `swift test`.
let bundle = Bundle(for: BundleSentinel.self)
+ let components = bundle.bundleURL.pathComponents
+ let configuration: String
+ if let buildIndex = components.lastIndex(of: ".build"),
+ let activeConfiguration = components[components.index(after: buildIndex)...]
+ .first(where: { $0 == "debug" || $0 == "release" }) {
+ configuration = activeConfiguration
+ } else {
+ configuration = "debug"
+ }
+
var cursor = bundle.bundleURL
for _ in 0..<12 {
if cursor.lastPathComponent == ".build" {
let candidates: [URL] = [
- cursor.appendingPathComponent("debug/mlx.metallib"),
- cursor.appendingPathComponent("release/mlx.metallib"),
- cursor.appendingPathComponent("arm64-apple-macosx/debug/mlx.metallib"),
- cursor.appendingPathComponent("arm64-apple-macosx/release/mlx.metallib"),
+ cursor.appendingPathComponent("\(configuration)/mlx.metallib"),
+ cursor.appendingPathComponent(
+ "arm64-apple-macosx/\(configuration)/mlx.metallib"
+ ),
]
for candidate in candidates {
if fm.fileExists(atPath: candidate.path) {
@@ -215,9 +225,8 @@ enum LiveInferenceFixtures {
let sizing: SlotSizingSnapshot
}
- /// Load a model and build its production v2 bridge (VLM-aware — the
- /// same `ModelContainerLoading` + weight-sharing text extraction the
- /// serve path uses).
+ /// Load a model and build its production v2 bridge, including direct use
+ /// of a VLM wrapper's owned text tower.
///
/// - Throws: `LiveFixtureSkip` if the model isn't on disk, or if the
/// metallib isn't available.
diff --git a/provider-swift/Tests/ProviderCoreTests/MTPConfigTests.swift b/provider-swift/Tests/ProviderCoreTests/MTPConfigTests.swift
index a9a25730b5..8d25ffeef6 100644
--- a/provider-swift/Tests/ProviderCoreTests/MTPConfigTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/MTPConfigTests.swift
@@ -174,12 +174,16 @@ struct MTPBetaFeatureTests {
feature.apply(true, to: &config)
#expect(config.backend.mtp == true)
#expect(feature.isEnabled(in: config) == true)
- #expect(BetaFeatures.enabledIDs(in: config) == ["mtp"])
+ #expect(BetaFeatures.enabledIDs(in: config) == [
+ "gemma-prefill-layer18", "gemma-weighted-r1", "mtp",
+ ])
feature.apply(false, to: &config)
#expect(config.backend.mtp == false)
#expect(feature.isEnabled(in: config) == false)
- #expect(BetaFeatures.enabledIDs(in: config).isEmpty)
+ #expect(BetaFeatures.enabledIDs(in: config) == [
+ "gemma-prefill-layer18", "gemma-weighted-r1",
+ ])
}
@Test("apply only mutates its mapped field")
@@ -195,6 +199,7 @@ struct MTPBetaFeatureTests {
#expect(config.backend.port == before.backend.port)
#expect(config.provider == before.provider)
#expect(config.coordinator == before.coordinator)
+ #expect(config.gemmaOptimizations == before.gemmaOptimizations)
}
// `darkbloom beta enable mtp` = apply(true) + ConfigManager.save; the
diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderMTPFactoryTests.swift b/provider-swift/Tests/ProviderCoreTests/ProviderMTPFactoryTests.swift
index 6dfdd2685c..811913a775 100644
--- a/provider-swift/Tests/ProviderCoreTests/ProviderMTPFactoryTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/ProviderMTPFactoryTests.swift
@@ -1,8 +1,10 @@
import Foundation
import Crypto
import MLX
+import MLXLLM
import MLXLMCommon
import MLXNN
+import MLXVLM
import Testing
@testable import ProviderCore
import ProviderCoreFoundation
@@ -33,7 +35,9 @@ private struct MTPFactoryProcessor: UserInputProcessor {
func prepare(input: UserInput) async throws -> LMInput { throw CancellationError() }
}
-private func mtpFactoryContainer(_ target: MTPFactoryTarget = MTPFactoryTarget()) -> ModelContainer {
+private func mtpFactoryContainer(
+ _ target: any LanguageModel = MTPFactoryTarget()
+) -> ModelContainer {
ModelContainer(context: ModelContext(
configuration: ModelConfiguration(id: "test/mtp-factory"),
model: target,
@@ -41,6 +45,48 @@ private func mtpFactoryContainer(_ target: MTPFactoryTarget = MTPFactoryTarget()
tokenizer: MTPFactoryTokenizer()))
}
+private func mtpFactoryVLM() throws -> MLXVLM.Gemma4 {
+ let data = Data(
+ """
+ {
+ "model_type": "gemma4",
+ "text_config": {
+ "hidden_size": 32,
+ "num_hidden_layers": 2,
+ "num_attention_heads": 2,
+ "num_key_value_heads": 1,
+ "head_dim": 8,
+ "global_head_dim": 8,
+ "intermediate_size": 64,
+ "vocab_size": 128,
+ "sliding_window": 16,
+ "layer_types": ["sliding_attention", "full_attention"],
+ "tie_word_embeddings": true,
+ "hidden_size_per_layer_input": 0,
+ "vocab_size_per_layer_input": 0,
+ "num_kv_shared_layers": 0,
+ "use_double_wide_mlp": false,
+ "enable_moe_block": false,
+ "use_bidirectional_attention": "vision"
+ },
+ "vision_config": {
+ "hidden_size": 16,
+ "intermediate_size": 32,
+ "num_hidden_layers": 1,
+ "num_attention_heads": 2,
+ "num_key_value_heads": 2,
+ "head_dim": 8,
+ "patch_size": 8,
+ "position_embedding_size": 64,
+ "default_output_length": 4,
+ "pooling_kernel_size": 2
+ }
+ }
+ """.utf8)
+ return MLXVLM.Gemma4(
+ try JSONDecoder().decode(MLXVLM.Gemma4Configuration.self, from: data))
+}
+
private func mtpFactoryArtifact() throws -> SpecDecArtifact {
let directory = FileManager.default.temporaryDirectory
.appendingPathComponent("provider-mtp-test-\(UUID().uuidString)", isDirectory: true)
@@ -207,7 +253,6 @@ struct ProviderMTPFactoryTests {
let prepared = try await EngineV2SlotFactory.prepareProductionModel(
modelId: model.id,
isVLM: false,
- modelDirectory: nil,
container: mtpFactoryContainer(),
specDecPreparation: preparation,
assistantLoader: MTPFactoryRecordingLoader(recorder: recorder, failure: nil))
@@ -227,7 +272,6 @@ struct ProviderMTPFactoryTests {
let prepared = try await EngineV2SlotFactory.prepareProductionModel(
modelId: "gemma-4-test",
isVLM: false,
- modelDirectory: nil,
container: mtpFactoryContainer(target),
specDecPreparation: .init(
artifact: artifact, status: .candidate(artifact)),
@@ -240,6 +284,51 @@ struct ProviderMTPFactoryTests {
#expect(prepared.assistantBytes == artifact.residentBytes)
}
+ @Test("Gemma 4 VLM hands its owned text tower directly to CBv2 and MTP")
+ func vlmOwnedTargetIdentity() async throws {
+ let vlm = try mtpFactoryVLM()
+ let container = mtpFactoryContainer(vlm)
+ let recorder = MTPFactoryIdentityRecorder()
+ let artifact = try mtpFactoryArtifact()
+ defer { try? FileManager.default.removeItem(at: artifact.directory) }
+
+ let prepared = try await EngineV2SlotFactory.prepareProductionModel(
+ modelId: "gemma-4-vlm-test",
+ isVLM: true,
+ container: container,
+ specDecPreparation: .init(
+ artifact: artifact, status: .candidate(artifact)),
+ assistantLoader: MTPFactoryRecordingLoader(
+ recorder: recorder, failure: nil))
+
+ let ownedID = ObjectIdentifier(vlm.textModel)
+ #expect(ObjectIdentifier(prepared.servingModel) == ownedID)
+ #expect(recorder.snapshot.0 == ownedID)
+ #expect(recorder.snapshot.1 == 1)
+ #expect(prepared.mtpStatus.active)
+
+ let recovered = try await EngineV2SlotFactory.prepareRecoveryModel(
+ modelId: "gemma-4-vlm-test",
+ isVLM: true,
+ container: container,
+ previousArtifact: prepared.mtpArtifact,
+ previousStatus: prepared.mtpStatus,
+ assistant: prepared.assistant)
+ #expect(ObjectIdentifier(recovered.servingModel) == ownedID)
+ let recoveredAssistant = try #require(recovered.assistant)
+ let preparedAssistant = try #require(prepared.assistant)
+ #expect(recoveredAssistant === preparedAssistant)
+ #expect(recovered.mtpStatus.active)
+ }
+
+ @Test("VLM resolution fails loud for an unsupported wrapper")
+ func unsupportedVLMWrapperRefuses() {
+ #expect(throws: EngineV2ProductionError.self) {
+ _ = try EngineV2Factory.directServingModel(
+ model: MTPFactoryTarget(), isVLM: true)
+ }
+ }
+
@Test("assistant load and bind failures are stable target-only fallbacks")
func loadAndBindFallbacks() async throws {
for failure in [
@@ -252,7 +341,6 @@ struct ProviderMTPFactoryTests {
let prepared = try await EngineV2SlotFactory.prepareProductionModel(
modelId: "gemma-4-test",
isVLM: false,
- modelDirectory: nil,
container: mtpFactoryContainer(),
specDecPreparation: .init(
artifact: artifact, status: .candidate(artifact)),
@@ -272,7 +360,6 @@ struct ProviderMTPFactoryTests {
let first = try await EngineV2SlotFactory.prepareProductionModel(
modelId: "gemma-4-test",
isVLM: false,
- modelDirectory: nil,
container: mtpFactoryContainer(),
specDecPreparation: .init(
artifact: artifact, status: .candidate(artifact)),
@@ -291,7 +378,6 @@ struct ProviderMTPFactoryTests {
let rebuilt = try await EngineV2SlotFactory.prepareProductionModel(
modelId: "gemma-4-test",
isVLM: false,
- modelDirectory: nil,
container: mtpFactoryContainer(),
specDecPreparation: .init(
artifact: artifact, status: .candidate(artifact)),
@@ -317,7 +403,6 @@ struct ProviderMTPFactoryTests {
let prepared = try await EngineV2SlotFactory.prepareProductionModel(
modelId: "gemma-4-test",
isVLM: false,
- modelDirectory: nil,
container: mtpFactoryContainer(),
specDecPreparation: .init(
artifact: artifact, status: .candidate(artifact)),
@@ -342,7 +427,6 @@ struct ProviderMTPFactoryTests {
let prepared = try await EngineV2SlotFactory.prepareProductionModel(
modelId: "gemma-4-test",
isVLM: false,
- modelDirectory: nil,
container: mtpFactoryContainer(),
specDecPreparation: .init(
artifact: artifact, status: .candidate(artifact)),
@@ -361,7 +445,6 @@ struct ProviderMTPFactoryTests {
let prepared = try await EngineV2SlotFactory.prepareProductionModel(
modelId: "gemma-4-test",
isVLM: false,
- modelDirectory: nil,
container: mtpFactoryContainer(),
specDecPreparation: .init(
artifact: artifact, status: .candidate(artifact)))
@@ -375,7 +458,6 @@ struct ProviderMTPFactoryTests {
let prepared = try await EngineV2SlotFactory.prepareProductionModel(
modelId: "gemma-4-test",
isVLM: false,
- modelDirectory: nil,
container: mtpFactoryContainer(),
specDecPreparation: .init(
artifact: nil,
diff --git a/provider-swift/Tests/ProviderCoreTests/SelfUpdaterTests.swift b/provider-swift/Tests/ProviderCoreTests/SelfUpdaterTests.swift
index b32363143a..2942ad0276 100644
--- a/provider-swift/Tests/ProviderCoreTests/SelfUpdaterTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/SelfUpdaterTests.swift
@@ -514,7 +514,7 @@ struct SelfUpdaterTests {
return (tarball, release, install)
}
- @Test("signed extracted app runs real packaged verification before staging succeeds")
+ @Test("signed extracted child proves retained Gemma marker before staging succeeds")
func signedAppRunsRealVerification() throws {
_ = LiveInferenceFixtures.ensureMetallibColocated()
let root = FileManager.default.temporaryDirectory
@@ -532,7 +532,7 @@ struct SelfUpdaterTests {
release: validRelease,
installDir: install)
else {
- Issue.record("real signed/runtime-verified staging failed")
+ Issue.record("real signed/runtime marker verification failed")
return
}
staged.discard()
diff --git a/provider-swift/Tests/ProviderCoreTests/SlotSizingDriftTests.swift b/provider-swift/Tests/ProviderCoreTests/SlotSizingDriftTests.swift
index 5cfa6b95b5..bc44a90eed 100644
--- a/provider-swift/Tests/ProviderCoreTests/SlotSizingDriftTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/SlotSizingDriftTests.swift
@@ -191,8 +191,11 @@ struct SlotSizingDriftTests {
// Engine truth from the REAL file.
let engineRate: Int
if checkpoint.textConfigWrapped {
- let textConfig = try EngineV2VLMTextExtraction.decodeTextConfiguration(
- configData: configData)
+ let root = try JSONSerialization.jsonObject(with: configData) as! [String: Any]
+ let textConfigData = try JSONSerialization.data(
+ withJSONObject: root["text_config"] as! [String: Any])
+ let textConfig = try JSONDecoder().decode(
+ Gemma4TextConfiguration.self, from: textConfigData)
engineRate = SlotSizingSnapshot.fp16KVBytesPerToken(
layerKinds: textConfig.cbv2LayerKinds)
} else {
diff --git a/scripts/fetch-metallib.sh b/scripts/fetch-metallib.sh
index 70bb13786a..5df8ed2d95 100755
--- a/scripts/fetch-metallib.sh
+++ b/scripts/fetch-metallib.sh
@@ -1,12 +1,10 @@
#!/bin/bash
# fetch-metallib.sh -- build the matching mlx.metallib for local Swift builds.
#
-# NOTE: despite the name, this now BUILDS the .metallib from source rather than
-# fetching it from a PyPI wheel. Building from our own fork guarantees the GPU
-# kernels match the exact MLX commit the host C++ links against — including the
-# resource-count trim and the M5 `_nax` kernels — and needs no published wheel
-# (there is no mlx==0.32.0 on PyPI). This mirrors the release-swift.yml
-# "Build mlx.metallib from source" step.
+# NOTE: despite the name, this BUILDS the metallib from source rather than
+# fetching a PyPI wheel. The kernels match the exact MLX source that the host
+# C++ links against. This is the canonical metallib path for local,
+# integration, CI, and release builds.
#
# mlx-swift's Cmlx target does NOT compile its Metal kernels through SwiftPM, so
# we compile them here with cmake from libs/mlx-swift/Source/Cmlx/mlx (the same
@@ -21,11 +19,20 @@ set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SWIFT_PROVIDER_DIR="${SWIFT_PROVIDER_DIR:-$REPO_ROOT/provider-swift}"
-# Source of truth: the mlx submodule the Cmlx target actually compiles against.
-MLX_SRC="${MLX_SRC:-$REPO_ROOT/libs/mlx-swift/Source/Cmlx/mlx}"
+# Source of truth: exactly the mlx tree the Cmlx target compiles against.
+MLX_SRC="$REPO_ROOT/libs/mlx-swift/Source/Cmlx/mlx"
# The _nax kernels are only compiled when SDK >= 26.2 AND deployment target
# >= 26.2 AND Metal >= 4.0 (mlx/backend/metal/kernels/CMakeLists.txt).
DEPLOYMENT_TARGET="${MLX_METALLIB_DEPLOYMENT_TARGET:-26.2}"
+JIT_MODE="OFF"
+NAX_SYMBOL="_nax"
+GEMV_SYMBOL="gemv"
+R1_BUILDER_SYMBOL="build_gemma4_sorted_expert_tiles_bm32"
+R1_KERNEL_SYMBOL="affine_gather_qmm_gemma4_expert_tiles_bfloat16_t_gs_64_b_4_alN_true_bm_32_bn_32_bk_32"
+COMPLETENESS_CONTRACT="$(
+ printf '%s\n' "$NAX_SYMBOL" "$GEMV_SYMBOL" "$R1_BUILDER_SYMBOL" "$R1_KERNEL_SYMBOL" \
+ | shasum -a 256 | cut -d' ' -f1
+)"
TARGET_ARG="${1:-debug}"
case "$TARGET_ARG" in
@@ -37,6 +44,8 @@ esac
mkdir -p "$DEST_DIR"
command -v cmake >/dev/null 2>&1 || { echo "✗ cmake not found (brew install cmake)"; exit 1; }
+command -v xcodebuild >/dev/null 2>&1 || { echo "✗ xcodebuild not found"; exit 1; }
+command -v xcrun >/dev/null 2>&1 || { echo "✗ xcrun not found"; exit 1; }
test -f "$MLX_SRC/mlx/version.h" || {
echo "✗ mlx submodule missing at $MLX_SRC"
echo " run: git submodule update --init --recursive"
@@ -54,38 +63,51 @@ test -f "$MLX_SRC/mlx/version.h" || {
# change the hash instead of collapsing to "Binary files differ",
# --no-ext-diff so a user's difftool cannot alter the key, and --no-color so
# terminal settings cannot either.
-if git -C "$MLX_SRC" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
- MLX_SHA="$(git -C "$MLX_SRC" rev-parse HEAD 2>/dev/null || echo nogit)"
- MLX_TREE_HASH="$({
- git -C "$MLX_SRC" diff HEAD --binary --no-ext-diff --no-color -- 2>/dev/null || true
- {
- git -C "$MLX_SRC" ls-files --others --exclude-standard 2>/dev/null || true
- } | while IFS= read -r f; do
- printf '%s\n' "$f"
- cat "$MLX_SRC/$f" 2>/dev/null || true
- done
- } | shasum -a 256 | cut -d' ' -f1)"
-else
- # Not a git checkout (source tarball, vendored copy). There is no commit
- # and no diff to read, so hashing nothing would mark ANY local edit as
- # "clean" and reintroduce exactly the bug this key is meant to prevent.
- # Hash the source contents instead.
- MLX_SHA="nogit"
- MLX_TREE_HASH="$(
- find "$MLX_SRC/mlx" -type f \( -name '*.h' -o -name '*.metal' -o -name '*.cpp' \) -print0 2>/dev/null \
- | sort -z | xargs -0 shasum -a 256 2>/dev/null | shasum -a 256 | cut -d' ' -f1
- )"
+compute_mlx_identity() {
+ if git -C "$MLX_SRC" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
+ MLX_SHA="$(git -C "$MLX_SRC" rev-parse HEAD 2>/dev/null || echo nogit)"
+ MLX_TREE_HASH="$({
+ git -C "$MLX_SRC" diff HEAD --binary --no-ext-diff --no-color -- 2>/dev/null || true
+ {
+ git -C "$MLX_SRC" ls-files --others --exclude-standard 2>/dev/null || true
+ } | while IFS= read -r f; do
+ printf '%s\n' "$f"
+ cat "$MLX_SRC/$f" 2>/dev/null || true
+ done
+ } | shasum -a 256 | cut -d' ' -f1)"
+ else
+ # Hash the entire source tree (including CMake inputs and generated
+ # manifests), not just kernel extensions.
+ MLX_SHA="nogit"
+ MLX_TREE_HASH="$(
+ find "$MLX_SRC" -type f ! -path '*/.git/*' -print0 2>/dev/null \
+ | sort -z | xargs -0 shasum -a 256 2>/dev/null | shasum -a 256 | cut -d' ' -f1
+ )"
+ fi
+}
+
+compute_mlx_identity
+INITIAL_MLX_SHA="$MLX_SHA"
+INITIAL_MLX_TREE_HASH="$MLX_TREE_HASH"
+if [ "$MLX_SHA" = "nogit" ]; then
echo "→ mlx source is not a git checkout; keying metallib on file contents (${MLX_TREE_HASH:0:12})"
fi
+assert_mlx_source_unchanged() {
+ compute_mlx_identity
+ if [ "$MLX_SHA" != "$INITIAL_MLX_SHA" ] \
+ || [ "$MLX_TREE_HASH" != "$INITIAL_MLX_TREE_HASH" ]
+ then
+ echo "✗ MLX source changed while preparing metallib; refusing stale cache publication"
+ return 1
+ fi
+}
# Hash of empty input == a clean git tree.
MLX_CLEAN_HASH="$(printf '' | shasum -a 256 | cut -d' ' -f1)"
if [ "$MLX_SHA" != "nogit" ] && [ "$MLX_TREE_HASH" = "$MLX_CLEAN_HASH" ]; then
- # Clean tree. The key is versioned (-c2) rather than bare: entries written
- # by the PREVIOUS version of this script used the bare name and could have
- # been built from a DIRTY tree, so reusing them would resurrect the very
- # mismatch this change exists to prevent. The suffix retires them.
- MLX_TREE_SUFFIX="-c2"
+ # Keep a visible clean-tree epoch; the helper and completeness contract are
+ # independently folded into the toolchain hash below.
+ MLX_TREE_SUFFIX="-c4"
else
MLX_TREE_SUFFIX="-w${MLX_TREE_HASH:0:12}"
if [ "$MLX_SHA" != "nogit" ]; then
@@ -93,40 +115,178 @@ else
fi
fi
-# Cache the built metallib by mlx commit + working-tree contents + deployment
-# target so repeat runs are instant (the build is ~1 min). Override with
-# METALLIB_CACHE_DIR.
+# Cache identity covers every input which can change generated Metal code or
+# the helper's acceptance contract. In particular, a cache from another Xcode
+# or SDK must never be reused merely because the source commit is identical.
+XCODE_VERSION="$(xcodebuild -version | tr '\n' ';')"
+SDK_VERSION="$(xcrun --sdk macosx --show-sdk-version)"
+SDK_BUILD_VERSION="$(xcrun --sdk macosx --show-sdk-build-version)"
+HELPER_CONTRACT_HASH="$(shasum -a 256 "$0" | cut -d' ' -f1)"
+TOOLCHAIN_HASH="$(
+ printf '%s\n' \
+ "$XCODE_VERSION" \
+ "$SDK_VERSION" \
+ "$SDK_BUILD_VERSION" \
+ "deployment=$DEPLOYMENT_TARGET" \
+ "jit=$JIT_MODE" \
+ "helper=$HELPER_CONTRACT_HASH" \
+ "completeness=$COMPLETENESS_CONTRACT" \
+ | shasum -a 256 | cut -d' ' -f1
+)"
+
CACHE_DIR="${METALLIB_CACHE_DIR:-/tmp/mlx-metallib-cache}"
-CACHE_KEY="mlx-${MLX_SHA}${MLX_TREE_SUFFIX}-dt${DEPLOYMENT_TARGET}"
+CACHE_KEY="mlx-${MLX_SHA}${MLX_TREE_SUFFIX}-tc${TOOLCHAIN_HASH:0:16}-dt${DEPLOYMENT_TARGET}-jitoff-c${COMPLETENESS_CONTRACT:0:12}"
CACHED="$CACHE_DIR/${CACHE_KEY}.metallib"
+verify_metallib() {
+ local metallib="$1"
+ local symbol matches
+
+ if [ ! -s "$metallib" ]; then
+ echo "✗ metallib missing or empty: $metallib"
+ return 1
+ fi
+
+ for symbol in \
+ "$NAX_SYMBOL" \
+ "$GEMV_SYMBOL" \
+ "$R1_BUILDER_SYMBOL" \
+ "$R1_KERNEL_SYMBOL"
+ do
+ # Use grep -c rather than grep -q: grep -q closes the pipe after its
+ # first match, causing strings to receive SIGPIPE under pipefail.
+ matches="$(strings "$metallib" | grep -F -c "$symbol" || true)"
+ if [ "$matches" -eq 0 ]; then
+ echo "✗ metallib missing required symbol string: $symbol"
+ return 1
+ fi
+ done
+}
+
+mkdir -p "$CACHE_DIR"
+
+# Serialize validation and publication for a cache key. A symlink is the
+# atomic owner-bearing primitive: it never exposes a lock without PID/start
+# identity. The unique target directory also provides an atomic reaper claim.
+CACHE_LOCK="$CACHE_DIR/.${CACHE_KEY}.lock"
+PROCESS_START_HASH="$(
+ LC_ALL=C TZ=UTC ps -p $$ -o lstart= | shasum -a 256 | cut -d' ' -f1
+)"
+LOCK_STATE_NAME=".${CACHE_KEY}.owner-$$-$PROCESS_START_HASH"
+LOCK_STATE="$CACHE_DIR/$LOCK_STATE_NAME"
+mkdir "$LOCK_STATE"
+LOCK_HELD=0
+LOCK_ATTEMPTS=0
+
+while :; do
+ if ln -s "$LOCK_STATE_NAME" "$CACHE_LOCK" 2>/dev/null; then
+ LOCK_HELD=1
+ break
+ fi
+
+ lock_target="$(readlink "$CACHE_LOCK" 2>/dev/null || true)"
+ case "$lock_target" in
+ ".${CACHE_KEY}.owner-"*)
+ owner_meta="${lock_target#".${CACHE_KEY}.owner-"}"
+ owner_pid="${owner_meta%%-*}"
+ owner_start_hash="${owner_meta#*-}"
+ current_start_hash=""
+ if kill -0 "$owner_pid" 2>/dev/null; then
+ current_start_hash="$(
+ LC_ALL=C TZ=UTC ps -p "$owner_pid" -o lstart= 2>/dev/null \
+ | shasum -a 256 | cut -d' ' -f1
+ )"
+ fi
+ if [ "$current_start_hash" != "$owner_start_hash" ]; then
+ stale_state="$CACHE_DIR/$lock_target"
+ # Recreate a missing target left by an interrupted release.
+ if [ ! -d "$stale_state" ]; then
+ mkdir "$stale_state" 2>/dev/null || true
+ fi
+ if mkdir "$stale_state/reaper" 2>/dev/null; then
+ if [ "$(readlink "$CACHE_LOCK" 2>/dev/null || true)" = "$lock_target" ]; then
+ rm -f "$CACHE_LOCK"
+ fi
+ rmdir "$stale_state/reaper"
+ rmdir "$stale_state"
+ rm -rf "$CACHE_DIR"/.build-"$CACHE_KEY"."$owner_pid".*
+ rm -f "$CACHE_DIR/.${CACHE_KEY}.${owner_pid}"
+ continue
+ fi
+ fi
+ ;;
+ esac
+
+ if [ "$LOCK_ATTEMPTS" -eq 0 ]; then
+ echo "→ Waiting for concurrent metallib build $CACHE_KEY"
+ fi
+ LOCK_ATTEMPTS=$((LOCK_ATTEMPTS + 1))
+ if [ "$LOCK_ATTEMPTS" -ge 6000 ]; then
+ echo "✗ timed out waiting for metallib cache lock: $CACHE_LOCK"
+ exit 1
+ fi
+ sleep 0.1
+done
+
+BUILD_DIR=""
+CACHE_TMP=""
+DEST_TMP=""
+release_cache_lock() {
+ if [ "$LOCK_HELD" -eq 1 ]; then
+ if [ "$(readlink "$CACHE_LOCK" 2>/dev/null || true)" = "$LOCK_STATE_NAME" ]; then
+ rm -f "$CACHE_LOCK"
+ fi
+ LOCK_HELD=0
+ fi
+ rmdir "$LOCK_STATE" 2>/dev/null || true
+}
+cleanup() {
+ [ -z "$BUILD_DIR" ] || rm -rf "$BUILD_DIR"
+ [ -z "$CACHE_TMP" ] || rm -f "$CACHE_TMP"
+ [ -z "$DEST_TMP" ] || rm -f "$DEST_TMP"
+ release_cache_lock
+}
+trap cleanup EXIT
+trap 'exit 143' HUP INT TERM
+
+if [ -s "$CACHED" ]; then
+ if verify_metallib "$CACHED"; then
+ echo "→ Using cached metallib $CACHE_KEY"
+ else
+ echo "→ Discarding incomplete cached metallib $CACHE_KEY"
+ rm -f "$CACHED"
+ fi
+fi
+
if [ ! -s "$CACHED" ]; then
echo "→ Building mlx.metallib from $MLX_SRC @ $CACHE_KEY"
- BUILD_DIR="$(mktemp -d)"
+ BUILD_DIR="$(mktemp -d "$CACHE_DIR/.build-${CACHE_KEY}.$$.XXXXXX")"
+ CACHE_TMP="$CACHE_DIR/.${CACHE_KEY}.$$"
+
cmake -S "$MLX_SRC" -B "$BUILD_DIR" \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_OSX_DEPLOYMENT_TARGET="$DEPLOYMENT_TARGET" \
- -DMLX_METAL_JIT=OFF \
+ -DMLX_METAL_JIT="$JIT_MODE" \
-DMLX_BUILD_TESTS=OFF -DMLX_BUILD_EXAMPLES=OFF \
-DMLX_BUILD_BENCHMARKS=OFF -DMLX_BUILD_PYTHON_BINDINGS=OFF >/dev/null
cmake --build "$BUILD_DIR" --target mlx-metallib -j"$(sysctl -n hw.ncpu 2>/dev/null || echo 4)"
- mkdir -p "$CACHE_DIR"
- cp "$BUILD_DIR/mlx/backend/metal/kernels/mlx.metallib" "$CACHED"
+ cp "$BUILD_DIR/mlx/backend/metal/kernels/mlx.metallib" "$CACHE_TMP"
+ verify_metallib "$CACHE_TMP"
+ assert_mlx_source_unchanged
+ mv -f "$CACHE_TMP" "$CACHED"
+ CACHE_TMP=""
rm -rf "$BUILD_DIR"
-else
- echo "→ Using cached metallib $CACHE_KEY"
-fi
-
-# Sanity: the _nax kernels must be present, otherwise the build silently used an
-# SDK/deployment target < 26.2 and we'd ship a nax-less metallib. Use `grep -c`
-# (not `grep -q`): grep -q closes the pipe on first match, which makes `strings`
-# on this 150 MB+ file exit via SIGPIPE and trips `set -o pipefail` — a false
-# negative.
-NAX_KERNELS="$(strings "$CACHED" | grep -c "_nax" || true)"
-if [ "$NAX_KERNELS" -eq 0 ]; then
- echo "✗ built metallib has no _nax kernels — is your Xcode SDK / deployment target >= 26.2?"
- exit 1
+ BUILD_DIR=""
fi
-cp "$CACHED" "$DEST_DIR/mlx.metallib"
+# Always replace the destination, even on a cache hit. A merely existing file
+# may have been built from different host sources and can hang the GPU.
+DEST_TMP="$DEST_DIR/.mlx.metallib.$$"
+assert_mlx_source_unchanged
+cp "$CACHED" "$DEST_TMP"
+mv -f "$DEST_TMP" "$DEST_DIR/mlx.metallib"
+DEST_TMP=""
echo "✓ wrote $DEST_DIR/mlx.metallib ($(shasum -a 256 "$DEST_DIR/mlx.metallib" | cut -d' ' -f1))"
+
+release_cache_lock
+trap - EXIT HUP INT TERM
diff --git a/scripts/gemma_contbatch/environment.py b/scripts/gemma_contbatch/environment.py
index efc804544d..1f08714260 100644
--- a/scripts/gemma_contbatch/environment.py
+++ b/scripts/gemma_contbatch/environment.py
@@ -58,6 +58,7 @@
"MLX_COMPILED_DECODE",
"MLX_DISABLE_COMPILE",
"MLX_GATHER_QMM_EXPERT_SLICES",
+ "MLX_GEMMA4_FUSED_WEIGHTED_UNSORT",
"MLX_METALLIB_PATH",
}
)
From 7fdf0e10013c7bc9d3956aa0972ea99e2e5b2698 Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Sun, 9 Aug 2026 21:43:10 -0700
Subject: [PATCH 04/23] docs(changelog): v0.8.2 candidate entry for the Gemma 4
optimization stack
---
CHANGELOG.md | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9ef9355f0e..43f7a3e974 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Changelog
+## Unreleased (v0.8.2 candidate — provider)
+
+### Provider (Swift)
+
+#### Performance
+
+- **Gemma 4 26B-A4B v0.8.2 optimization stack** — Layer-18 lazy prefill submission; coupled weighted-expert-unsort + safe-R1 expert-QMM gate (both default-on via `[gemma_optimizations]`); direct shared VLM text tower (deletes the duplicate extraction tower); packed multimodal prefill inside q=128 query blocks; source-matched metallib enforced across CI/release/packaged smoke. Measured on `gemma-4-26B-A4B-it-qat-4bit` vs the v0.7.15 baseline: 2K-prompt TTFT 1.23x (1715 -> 1390 ms), TTFT under concurrent load 1.39-1.76x, arrival end-to-end throughput +18-25%, decode +1.3-2.3%, peak memory unchanged. Dropped after measurement: expert gate/up packing, dense gate/up packing, standalone weighted-unsort, standalone R1. `0cc5fc9c9`
+
+---
+
## Unreleased (Apr 26 - May 25, 2026)
26 commits since `aa74499`.
From 9d5c7ae212aec1ce2349220f1019a6b82ad672b3 Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Sun, 9 Aug 2026 21:45:28 -0700
Subject: [PATCH 05/23] test(provider): use closure form in
GemmaOptimizationReportingTests #expect
allSatisfy(\.effective) trips the macro's throwing-call detection;
closure form is identical and compiles.
---
.../ProviderCoreTests/GemmaOptimizationReportingTests.swift | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/provider-swift/Tests/ProviderCoreTests/GemmaOptimizationReportingTests.swift b/provider-swift/Tests/ProviderCoreTests/GemmaOptimizationReportingTests.swift
index 57ab62cdf3..858b257fd7 100644
--- a/provider-swift/Tests/ProviderCoreTests/GemmaOptimizationReportingTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/GemmaOptimizationReportingTests.swift
@@ -48,7 +48,7 @@ struct GemmaOptimizationReportingTests {
safeR1AOTAvailable: true,
safeR1NAXAvailable: false)
let rendered = effective.logLine(modelId: "gemma-4-production")
- #expect(effective.states.allSatisfy(\.effective))
+ #expect(effective.states.allSatisfy { $0.effective })
#expect(rendered.contains("layer18(requested=true,effective=true,reason=effective)"))
#expect(rendered.contains("weighted_unsort(requested=true,effective=true,reason=effective)"))
#expect(rendered.contains("safe_r1(requested=true,effective=true,reason=effective)"))
From 06442b50e1fed3e7fb5a844c2f8dbe75ad771d7f Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Sun, 9 Aug 2026 22:44:41 -0700
Subject: [PATCH 06/23] fix(provider): apply Gemma config before first
benchmark MLX access; cite canonical code in beta docs; bump pins
- BenchmarkCommand now loads the runtime snapshot, then routes through
the same Start.prepareServeRuntime seam as the serve path: the
provider.toml Gemma projection applies before GPUEnforcement's first
MLX device access, so a rollback A/B benchmark can no longer measure
the default-enabled stack against an operator-disabled config
(Codex P1 on Layr-Labs/d-inference#607).
- docs/provider/beta-features.md gains canonical file:line references
for every behavioral claim (docs/AGENTS.md code-wins rule): settings
defaults, startup projection seam, projection/apply authority, the
coupled weighted+R1 control (Codex docs P1).
- Pins libs/mlx-swift-lm 1d46abc (four shared-tower semantics fixes +
contract suite) and libs/mlx-swift cdb7bcd (C-mode MLX_API fallback
for the R1 facade; Codex P1 on Layr-Labs/mlx-swift#11).
make provider-test: 1666 swift-testing + 82 XCTest pass on this tree.
---
docs/provider/beta-features.md | 21 ++++++++++++++++++-
libs/mlx-swift | 2 +-
libs/mlx-swift-lm | 2 +-
.../Sources/darkbloom/BenchmarkCommand.swift | 12 ++++++++---
4 files changed, 31 insertions(+), 6 deletions(-)
diff --git a/docs/provider/beta-features.md b/docs/provider/beta-features.md
index 86b97ffdf3..cc4e4e3044 100644
--- a/docs/provider/beta-features.md
+++ b/docs/provider/beta-features.md
@@ -15,7 +15,26 @@ surface. Process-wide optimization state is resolved at startup, so restart
after changing a restart-required feature.
The registry of available features lives in
-`provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift`.
+`provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift:58-65`.
+
+### Canonical implementation references
+
+- Default-on decoding for omitted config sections:
+ `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationSettings.swift:16-20`
+ (both fields default to `true`) and
+ `provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift:332-334`
+ (`decodeIfPresent` with the defaulted struct as fallback).
+- Startup projection before the first MLX device access (daemon, foreground,
+ `--local`, and `benchmark` processes):
+ `provider-swift/Sources/darkbloom/StartCommand.swift:87` and the ordering
+ seam at `provider-swift/Sources/darkbloom/StartCommand.swift:127-140`;
+ the benchmark path shares it at
+ `provider-swift/Sources/darkbloom/BenchmarkCommand.swift:76-85`.
+- The config→environment projection and its overwrite authority:
+ `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift:14-25`
+ (`projection(for:)`) and `:57` (`apply(_:)`).
+- The `benchmark`-selected coupling of weighted unsort with safe R1 as one
+ control: `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationSettings.swift:11-14`.
## The `darkbloom beta` command
diff --git a/libs/mlx-swift b/libs/mlx-swift
index db9b77da44..cdb7bcd807 160000
--- a/libs/mlx-swift
+++ b/libs/mlx-swift
@@ -1 +1 @@
-Subproject commit db9b77da44735dd94e2f8737355c3056464b56ca
+Subproject commit cdb7bcd807d8d70a864b09c14f938068b4e0c22d
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index 53e8ccd4e1..1d46abc2df 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit 53e8ccd4e1ba5f51da6ad3254115b59547151e1b
+Subproject commit 1d46abc2df6adcc9032c6a7dde350f17b47a9099
diff --git a/provider-swift/Sources/darkbloom/BenchmarkCommand.swift b/provider-swift/Sources/darkbloom/BenchmarkCommand.swift
index a0a8ad4929..cee8c0ab77 100644
--- a/provider-swift/Sources/darkbloom/BenchmarkCommand.swift
+++ b/provider-swift/Sources/darkbloom/BenchmarkCommand.swift
@@ -73,15 +73,21 @@ struct Benchmark: AsyncParsableCommand {
var arrivalIterations = 3
mutating func run() async throws {
+ let snapshot = try loadRuntimeSnapshot(configOptions: configOptions)
+
+ // The low-level Gemma controls are process-start latches, so
+ // `provider.toml` must be projected BEFORE the first MLX device
+ // access — exactly like the serve path (`Start.prepareServeRuntime`).
+ // Otherwise a rollback A/B benchmark silently measures the
+ // default-enabled stack instead of the configured serving stack. A
+ // rejected projection aborts before engine construction.
do {
- _ = try GPUEnforcement.requireMetal()
+ try Start.prepareServeRuntime(settings: snapshot.config.gemmaOptimizations)
} catch {
printError("\(error)")
throw ExitCode.failure
}
- let snapshot = try loadRuntimeSnapshot(configOptions: configOptions)
-
guard let hardware = snapshot.hardware else {
printError("hardware detection failed: \(snapshot.hardwareError?.localizedDescription ?? "unknown")")
throw ExitCode.failure
From 2627e132acac57bf157a38da0326071b6308b530 Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Sun, 9 Aug 2026 23:23:07 -0700
Subject: [PATCH 07/23] fix(provider): harden config loading surface +
benchmark/CLI integrity follow-ups
Review follow-ups on the v0.8.2 Gemma 4 optimization stack (#607):
- R1 (HIGH, silent rollback defeat): the lenient ConfigManager.parse
(whole-config defaults on ANY decode error) stays only as the
test-facing API; production file loads route through the new strict
ConfigManager.parseValidating via ConfigManager.load(from:), throwing
ConfigError.parseFailed with the decode detail. A malformed
[gemma_optimizations] entry (weighted_r1 = 0, prefill_layer18 = "false")
previously re-armed the whole default-on stack with zero log; every
snapshot-based command (start/benchmark/beta/status/...) now refuses at
load. Missing files keep defaulting one layer up
(loadDefault/loadRuntimeSnapshot), and missing sections/keys keep their
per-key default-on decode.
- R2 (HIGH, benchmark A/B integrity): darkbloom benchmark now reads the
three low-level env keys before applying the projection and FAILS
(stderr naming key, shell value, config value + ExitCode.failure) when a
shell preset conflicts, instead of silently overwriting it and
invalidating the runner.py os.environ artifact metadata; on success it
prints one line with the effective controls. Benchmark A/B is explicitly
config-driven (docs/provider/beta-features.md updated with the new
citations/line numbers).
- R3 (MED, seam placement): the ordering seam moved from
Start.prepareServeRuntime into the new
ServeRuntimePreparer.prepareRuntime (config projection strictly BEFORE
the first MLX touch; a rejected projection aborts before engine
construction). Start.prepareServeRuntime remains as a forwarding shim
for compatibility (StartCommand.run + one shim test); BenchmarkCommand
and StartCommandTests now target ServeRuntimePreparer directly.
- R4 (LOW): darkbloom beta enable/disable no longer no-ops when the key
(or its [section]) is ABSENT but the decode default matches the target:
the value is materially written (BetaFeature.configAddress +
tomlKeyPresent), pinning operator intent against future default flips.
A key already pinned at the target is still a true no-op (no rewrite).
- R5 (LOW): CHANGELOG stat fixes vs the committed-tree tree benchmark
artifact: arrival TTFT speedups 1.411/1.385/1.470/1.762 -> "1.38-1.76x"
(was "1.39-1.76x"); "peak memory unchanged" replaced with the retention
memory control numbers (B1/B2/B4 peaks 14.0/14.64/15.05 GiB vs default
14.06/14.70/15.11; tmp/benchmarks/v0-8-2-retention-comparison.json).
- R6 (LOW): the beta load->modify->save window is serialized by an
exclusive flock(2) on a stable provider.toml.lock SIDECAR file, with the
config re-loaded inside the lock (lost-update RMW race). Sidecar chosen
over locking the config file itself: ConfigManager.save writes
atomically via temp-file+rename, so the config inode changes on every
save and concurrent writers holding different inodes would NOT exclude
each other; the sidecar path is never renamed, giving every contender
the same inode. fd close releases the lock even across a throw.
R7 (note only, semantics unchanged): GemmaOptimizationEnvironment holds
no armed/latched global state -- projection() is pure and apply() only
setenv()s the three latches at process start. The POSIX process
environment is global and getenv/setenv are not thread-safe, which stays
correct because both call sites (start, benchmark) apply before MLX init
and before any worker concurrency; a future call site that applies
mid-run would need its own serialization.
Tests: 1692 swift-testing tests + 82 XCTest, all passing (make
provider-test). New: ConfigValidationTests (11), BetaCommandTests (10),
RuntimeSnapshotConfigTests (2), StartCommandTests +4 (env-conflict guard +
shim forwarding; pre-existing Start seam tests retargeted).
---
CHANGELOG.md | 2 +-
docs/provider/beta-features.md | 19 +-
.../ProviderCore/Config/BetaFeatures.swift | 13 +
.../ProviderCore/Config/ProviderConfig.swift | 32 ++-
.../Sources/darkbloom/BenchmarkCommand.swift | 25 +-
.../Sources/darkbloom/BetaCommand.swift | 119 +++++++--
.../darkbloom/ServeRuntimePreparer.swift | 80 ++++++
.../Sources/darkbloom/StartCommand.swift | 19 +-
.../DarkbloomCLITests/BetaCommandTests.swift | 235 ++++++++++++++++++
.../RuntimeSnapshotConfigTests.swift | 54 ++++
.../DarkbloomCLITests/StartCommandTests.swift | 76 +++++-
.../ConfigValidationTests.swift | 159 ++++++++++++
12 files changed, 792 insertions(+), 41 deletions(-)
create mode 100644 provider-swift/Sources/darkbloom/ServeRuntimePreparer.swift
create mode 100644 provider-swift/Tests/DarkbloomCLITests/BetaCommandTests.swift
create mode 100644 provider-swift/Tests/DarkbloomCLITests/RuntimeSnapshotConfigTests.swift
create mode 100644 provider-swift/Tests/ProviderCoreTests/ConfigValidationTests.swift
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 43f7a3e974..aac170c8ff 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,7 @@
#### Performance
-- **Gemma 4 26B-A4B v0.8.2 optimization stack** — Layer-18 lazy prefill submission; coupled weighted-expert-unsort + safe-R1 expert-QMM gate (both default-on via `[gemma_optimizations]`); direct shared VLM text tower (deletes the duplicate extraction tower); packed multimodal prefill inside q=128 query blocks; source-matched metallib enforced across CI/release/packaged smoke. Measured on `gemma-4-26B-A4B-it-qat-4bit` vs the v0.7.15 baseline: 2K-prompt TTFT 1.23x (1715 -> 1390 ms), TTFT under concurrent load 1.39-1.76x, arrival end-to-end throughput +18-25%, decode +1.3-2.3%, peak memory unchanged. Dropped after measurement: expert gate/up packing, dense gate/up packing, standalone weighted-unsort, standalone R1. `0cc5fc9c9`
+- **Gemma 4 26B-A4B v0.8.2 optimization stack** — Layer-18 lazy prefill submission; coupled weighted-expert-unsort + safe-R1 expert-QMM gate (both default-on via `[gemma_optimizations]`); direct shared VLM text tower (deletes the duplicate extraction tower); packed multimodal prefill inside q=128 query blocks; source-matched metallib enforced across CI/release/packaged smoke. Measured on `gemma-4-26B-A4B-it-qat-4bit` vs the v0.7.15 baseline: 2K-prompt TTFT 1.23x (1715 -> 1390 ms), TTFT under concurrent load 1.38-1.76x, arrival end-to-end throughput +18-25%, decode +1.3-2.3%, retention memory control within 0.06 GiB of default (B1/B2/B4 peaks 14.0/14.64/15.05 GiB vs 14.06/14.70/15.11; tmp/benchmarks/v0-8-2-retention-comparison.json). Dropped after measurement: expert gate/up packing, dense gate/up packing, standalone weighted-unsort, standalone R1. `0cc5fc9c9`
---
diff --git a/docs/provider/beta-features.md b/docs/provider/beta-features.md
index cc4e4e3044..5d7cdf037e 100644
--- a/docs/provider/beta-features.md
+++ b/docs/provider/beta-features.md
@@ -15,7 +15,7 @@ surface. Process-wide optimization state is resolved at startup, so restart
after changing a restart-required feature.
The registry of available features lives in
-`provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift:58-65`.
+`provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift:73-80`.
### Canonical implementation references
@@ -25,11 +25,18 @@ The registry of available features lives in
`provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift:332-334`
(`decodeIfPresent` with the defaulted struct as fallback).
- Startup projection before the first MLX device access (daemon, foreground,
- `--local`, and `benchmark` processes):
- `provider-swift/Sources/darkbloom/StartCommand.swift:87` and the ordering
- seam at `provider-swift/Sources/darkbloom/StartCommand.swift:127-140`;
- the benchmark path shares it at
- `provider-swift/Sources/darkbloom/BenchmarkCommand.swift:76-85`.
+ `--local`, and `benchmark` processes): the shared ordering seam is
+ `provider-swift/Sources/darkbloom/ServeRuntimePreparer.swift:24-35`
+ (`ServeRuntimePreparer.prepareRuntime`); the serve path calls it through
+ `Start`'s forwarding shim at
+ `provider-swift/Sources/darkbloom/StartCommand.swift:87`, and the benchmark
+ path calls it directly at
+ `provider-swift/Sources/darkbloom/BenchmarkCommand.swift:105`.
+ Benchmark A/B is config-driven — a shell-preset low-level key that
+ conflicts with the config projection is rejected rather than overwritten,
+ and the effective controls are printed before measuring
+ (`provider-swift/Sources/darkbloom/BenchmarkCommand.swift:91-110`, guard
+ helper `provider-swift/Sources/darkbloom/ServeRuntimePreparer.swift:58-79`).
- The config→environment projection and its overwrite authority:
`provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift:14-25`
(`projection(for:)`) and `:57` (`apply(_:)`).
diff --git a/provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift b/provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift
index 1d00f48b01..765ceaacdd 100644
--- a/provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift
+++ b/provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift
@@ -22,6 +22,13 @@ public struct BetaFeature: Sendable, Identifiable {
public let details: String
/// Whether `darkbloom restart` is required for a change to take effect.
public let requiresRestart: Bool
+ /// Where the backing field lives in `provider.toml`
+ /// (`[section]` + `key =`), so the CLI can tell "already at the requested
+ /// value AND pinned in the file" apart from "same value via decode
+ /// default". An absent key must be WRITTEN on an explicit toggle: the
+ /// operator asked for the value durably, not for today's decode default
+ /// (a future default flip would otherwise silently move their provider).
+ public let configAddress: (section: String, key: String)?
private let read: @Sendable (ProviderConfig) -> Bool
private let write: @Sendable (Bool, inout ProviderConfig) -> Void
@@ -32,6 +39,7 @@ public struct BetaFeature: Sendable, Identifiable {
summary: String,
details: String,
requiresRestart: Bool,
+ configAddress: (section: String, key: String)? = nil,
read: @escaping @Sendable (ProviderConfig) -> Bool,
write: @escaping @Sendable (Bool, inout ProviderConfig) -> Void
) {
@@ -40,6 +48,7 @@ public struct BetaFeature: Sendable, Identifiable {
self.summary = summary
self.details = details
self.requiresRestart = requiresRestart
+ self.configAddress = configAddress
self.read = read
self.write = write
}
@@ -75,6 +84,7 @@ public enum BetaFeatures {
prefill behavior.
""",
requiresRestart: true,
+ configAddress: (section: "gemma_optimizations", key: "prefill_layer18"),
read: { $0.gemmaOptimizations.prefillLayer18 },
write: { enabled, config in
config.gemmaOptimizations.prefillLayer18 = enabled
@@ -93,6 +103,7 @@ public enum BetaFeatures {
and restart to restore both legacy paths together.
""",
requiresRestart: true,
+ configAddress: (section: "gemma_optimizations", key: "weighted_r1"),
read: { $0.gemmaOptimizations.weightedR1 },
write: { enabled, config in
config.gemmaOptimizations.weightedR1 = enabled
@@ -110,6 +121,7 @@ public enum BetaFeatures {
leaving this enabled opts you in when it ships.
""",
requiresRestart: true,
+ configAddress: (section: "backend", key: "kv_quant"),
read: { $0.backend.kvQuant },
write: { enabled, config in config.backend.kvQuant = enabled }
),
@@ -126,6 +138,7 @@ public enum BetaFeatures {
mtp_drafter_path under [backend] to a local drafter directory.
""",
requiresRestart: true,
+ configAddress: (section: "backend", key: "mtp"),
read: { $0.backend.mtp },
write: { enabled, config in config.backend.mtp = enabled }
),
diff --git a/provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift b/provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift
index 995b179c1b..eaab451558 100644
--- a/provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift
+++ b/provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift
@@ -430,6 +430,13 @@ public enum ConfigManager: Sendable {
}
/// Load config from a file path.
+ ///
+ /// This is the production file-loading boundary: a file that EXISTS but
+ /// cannot decode throws `ConfigError.parseFailed` (see
+ /// ``parseValidating(_:)``) instead of silently falling back to defaults.
+ /// Callers that want missing-file leniency check `fileExists` first; only
+ /// a NONEXISTENT path defaults (`readFailed` is thrown here, and the
+ /// snapshot/`loadDefault` layers substitute defaults in that case).
public static func load(from path: URL) throws -> ProviderConfig {
let content: String
do {
@@ -437,7 +444,7 @@ public enum ConfigManager: Sendable {
} catch {
throw ConfigError.readFailed(path: path.path, underlying: error)
}
- return parse(content)
+ return try parseValidating(content)
}
/// Load config from the default path. Returns default config if file doesn't exist.
@@ -485,6 +492,13 @@ public enum ConfigManager: Sendable {
// MARK: - TOML parsing
/// Parse a TOML string into a ProviderConfig.
+ ///
+ /// LENIENT, test-facing entry point: ANY decode failure falls back to a
+ /// whole-config default, exactly matching historical behavior. Production
+ /// file loads must NOT use this — a malformed `[gemma_optimizations]`
+ /// entry (e.g. `weighted_r1 = 0` as an integer) would otherwise silently
+ /// re-enable the whole default-on optimization stack with zero log. Use
+ /// ``parseValidating(_:)`` (via ``load(from:)``) on that path.
public static func parse(_ content: String) -> ProviderConfig {
do {
return try TOMLDecoder().decode(ProviderConfig.self, from: content)
@@ -498,6 +512,22 @@ public enum ConfigManager: Sendable {
}
}
+ /// Parse a TOML string into a ProviderConfig, failing loudly.
+ ///
+ /// Unlike ``parse(_:)``, any decode failure throws
+ /// `ConfigError.parseFailed` carrying the decoder's description, so an
+ /// operator who fat-fingers `provider.toml` is told at startup instead of
+ /// unknowingly serving on whole-config defaults. Missing / partial content
+ /// still decodes with per-key defaults (default-on Gemma stack) — only an
+ /// undecodable FILE is rejected.
+ public static func parseValidating(_ content: String) throws -> ProviderConfig {
+ do {
+ return try TOMLDecoder().decode(ProviderConfig.self, from: content)
+ } catch {
+ throw ConfigError.parseFailed(detail: "\(error)")
+ }
+ }
+
/// Serialize a ProviderConfig to the provider's TOML config format.
public static func serialize(_ config: ProviderConfig) -> String {
do {
diff --git a/provider-swift/Sources/darkbloom/BenchmarkCommand.swift b/provider-swift/Sources/darkbloom/BenchmarkCommand.swift
index cee8c0ab77..18a6764bdf 100644
--- a/provider-swift/Sources/darkbloom/BenchmarkCommand.swift
+++ b/provider-swift/Sources/darkbloom/BenchmarkCommand.swift
@@ -77,16 +77,37 @@ struct Benchmark: AsyncParsableCommand {
// The low-level Gemma controls are process-start latches, so
// `provider.toml` must be projected BEFORE the first MLX device
- // access — exactly like the serve path (`Start.prepareServeRuntime`).
+ // access — exactly like the serve path (the shared seam is
+ // `ServeRuntimePreparer.prepareRuntime`; `Start` forwards to it).
// Otherwise a rollback A/B benchmark silently measures the
// default-enabled stack instead of the configured serving stack. A
// rejected projection aborts before engine construction.
+ //
+ // A/B integrity: benchmark artifacts record the process environment
+ // (scripts/gemma_contbatch/runner.py logs os.environ). A shell-preset
+ // low-level key that CONFLICTS with the config projection would be
+ // silently overwritten by apply(), so the artifact metadata would
+ // then disagree with what was actually measured — refuse to run.
+ let gemmaSettings = snapshot.config.gemmaOptimizations
+ if let conflict = ServeRuntimePreparer.conflictingEnvironmentOverride(
+ settings: gemmaSettings
+ ) {
+ printError("""
+ benchmark is config-driven: refusing to run with \
+ \(conflict.key)=\(conflict.shellValue) set in this shell while \
+ provider.toml projects \(conflict.configValue). Toggle with \
+ `darkbloom beta` or edit [gemma_optimizations] in provider.toml, \
+ then re-run benchmark without the low-level override.
+ """)
+ throw ExitCode.failure
+ }
do {
- try Start.prepareServeRuntime(settings: snapshot.config.gemmaOptimizations)
+ try ServeRuntimePreparer.prepareRuntime(settings: gemmaSettings)
} catch {
printError("\(error)")
throw ExitCode.failure
}
+ print("gemma optimizations: prefill_layer18=\(gemmaSettings.prefillLayer18 ? "on" : "off") weighted_r1=\(gemmaSettings.weightedR1 ? "on" : "off")")
guard let hardware = snapshot.hardware else {
printError("hardware detection failed: \(snapshot.hardwareError?.localizedDescription ?? "unknown")")
diff --git a/provider-swift/Sources/darkbloom/BetaCommand.swift b/provider-swift/Sources/darkbloom/BetaCommand.swift
index c89694414e..3308677900 100644
--- a/provider-swift/Sources/darkbloom/BetaCommand.swift
+++ b/provider-swift/Sources/darkbloom/BetaCommand.swift
@@ -1,6 +1,9 @@
import Foundation
import ArgumentParser
import ProviderCore
+#if canImport(Darwin)
+import Darwin
+#endif
struct Beta: AsyncParsableCommand {
static let configuration = CommandConfiguration(
@@ -139,7 +142,7 @@ extension Beta {
var feature: String
mutating func run() async throws {
- try setBetaFeature(feature, enabled: true, configOptions: configOptions)
+ try setBetaFeature(feature, enabled: true, configPath: configOptions.config)
}
}
@@ -154,7 +157,7 @@ extension Beta {
var feature: String
mutating func run() async throws {
- try setBetaFeature(feature, enabled: false, configOptions: configOptions)
+ try setBetaFeature(feature, enabled: false, configPath: configOptions.config)
}
}
}
@@ -168,17 +171,19 @@ private func unknownFeatureError(_ id: String) -> ValidationError {
}
/// Read-modify-write a single beta feature's config field and persist it.
-private func setBetaFeature(
+///
+/// Internal (not `private`) so `DarkbloomCLITests` can drive it with temp
+/// config fixtures via `configPath`.
+func setBetaFeature(
_ id: String,
enabled: Bool,
- configOptions: ConfigOptions
+ configPath: String?
) throws {
guard let feature = BetaFeatures.feature(id: id) else {
throw unknownFeatureError(id)
}
- let snapshot = try loadRuntimeSnapshot(configOptions: configOptions)
- var config = snapshot.config
+ let snapshot = try loadRuntimeSnapshot(configPath: configPath)
// Persist to the path the daemon will actually read. With no explicit
// --config, loadRuntimeSnapshot may have just migrated a legacy config to
@@ -187,26 +192,102 @@ private func setBetaFeature(
// the (legacy) snapshot.configPath would leave the restarted daemon on the
// stale value. Re-resolving the default returns the post-migration canonical.
let savePath: URL
- if configOptions.config != nil {
+ if configPath != nil {
savePath = snapshot.configPath
} else {
savePath = try ConfigManager.defaultConfigPath()
}
- // Already in the desired state and the target file exists — no-op.
- if feature.isEnabled(in: config) == enabled
- && FileManager.default.fileExists(atPath: savePath.path) {
- print("\(feature.title) (\(feature.id)) is already \(enabled ? "enabled" : "disabled").")
- return
+ // Serialize the load → modify → save window with an exclusive flock, and
+ // RELOAD inside the lock: the snapshot above and any concurrent `beta`
+ // process's write can interleave, and using the pre-lock snapshot would be
+ // a classic lost-update RMW race.
+ try withExclusiveConfigLock(at: savePath) {
+ var config: ProviderConfig
+ if FileManager.default.fileExists(atPath: savePath.path) {
+ config = try ConfigManager.load(from: savePath)
+ } else {
+ config = snapshot.config
+ }
+
+ // No-op only when the file already PINS the requested value. An absent
+ // key (or absent [section]) can decode to the same effective value via
+ // the default, but an explicit enable/disable means "make it so,
+ // durably" — materialize the key so a future default flip cannot
+ // silently move this provider.
+ if feature.isEnabled(in: config) == enabled,
+ let address = feature.configAddress,
+ let content = try? String(contentsOf: savePath, encoding: .utf8),
+ tomlKeyPresent(content, section: address.section, key: address.key) {
+ print("\(feature.title) (\(feature.id)) is already \(enabled ? "enabled" : "disabled").")
+ return
+ }
+
+ feature.apply(enabled, to: &config)
+ try ConfigManager.save(config, to: savePath)
+
+ print("\(enabled ? "Enabled" : "Disabled") beta feature: \(feature.title) (\(feature.id))")
+ print(" \(feature.details)")
+ if feature.requiresRestart {
+ print(" Restart to apply: darkbloom restart")
+ }
+ print(" Config: \(savePath.path)")
}
+}
- feature.apply(enabled, to: &config)
- try ConfigManager.save(config, to: savePath)
+/// Guards one config-file mutation window with an exclusive `flock(2)` on a
+/// stable `.lock` sidecar next to the config file. The lock must
+/// NOT be taken out on provider.toml itself: `ConfigManager.save` writes
+/// atomically via temp-file + rename, so the config file's inode changes on
+/// every save and concurrent writers would be locking DIFFERENT inodes (no
+/// mutual exclusion). The sidecar path is never renamed, so every contending
+/// process locks the same inode. Closing the fd (the defer) also releases the
+/// kernel lock if the explicit LOCK_UN is ever skipped by a throw.
+@discardableResult
+func withExclusiveConfigLock(at configPath: URL, _ body: () throws -> T) throws -> T {
+ let directory = configPath.deletingLastPathComponent()
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let lockURL = directory.appendingPathComponent(configPath.lastPathComponent + ".lock")
+
+ let fd = open(lockURL.path, O_RDWR | O_CREAT, 0o644)
+ guard fd >= 0 else {
+ throw ConfigError.writeFailed(
+ path: lockURL.path,
+ underlying: NSError(domain: NSPOSIXErrorDomain, code: Int(errno))
+ )
+ }
+ defer { close(fd) }
+
+ guard flock(fd, LOCK_EX) == 0 else {
+ throw ConfigError.writeFailed(
+ path: lockURL.path,
+ underlying: NSError(domain: NSPOSIXErrorDomain, code: Int(errno))
+ )
+ }
+ defer { _ = flock(fd, LOCK_UN) }
- print("\(enabled ? "Enabled" : "Disabled") beta feature: \(feature.title) (\(feature.id))")
- print(" \(feature.details)")
- if feature.requiresRestart {
- print(" Restart to apply: darkbloom restart")
+ return try body()
+}
+
+/// Whether TOML `content` materially sets `key` inside `[section]`.
+///
+/// Line-oriented: tracks the current table header and matches `key = ...`
+/// assignments. Only needs to be correct for the flat
+/// `[section]\nkey = value` shape `ConfigManager.save` serializes (and that
+/// operators hand-edit). A miss here is fail-safe for the caller: unsure
+/// means WRITE the key, which is idempotent.
+func tomlKeyPresent(_ content: String, section: String, key: String) -> Bool {
+ var inSection = false
+ for rawLine in content.split(separator: "\n", omittingEmptySubsequences: false) {
+ let line = rawLine.trimmingCharacters(in: .whitespaces)
+ if line.hasPrefix("[") {
+ inSection = line == "[\(section)]"
+ continue
+ }
+ guard inSection, !line.hasPrefix("#"),
+ let eqIndex = line.firstIndex(of: "=") else { continue }
+ let name = line[.. Void = {
+ try GemmaOptimizationEnvironment.apply($0)
+ },
+ requireMetal: () throws -> Void = {
+ _ = try GPUEnforcement.requireMetal()
+ }
+ ) throws {
+ try apply(settings)
+ try requireMetal()
+ }
+
+ /// One pre-set low-level environment key that CONFLICTS with the config
+ /// projection a command is about to apply.
+ struct EnvironmentConflict: Equatable {
+ /// The low-level environment key (e.g. `MLX_GATHER_QMM_EXPERT_SLICES`).
+ let key: String
+ /// The value the operator's shell exported.
+ let shellValue: String
+ /// The value `provider.toml` projects (and would overwrite with).
+ let configValue: String
+ }
+
+ /// Returns the first pre-existing low-level key whose value DISAGREES with
+ /// the config projection; nil when every key is unset or already matches.
+ ///
+ /// `apply(_:)` overwrites unconditionally (config is authoritative), which
+ /// is correct for serving — but a benchmark run whose artifact metadata
+ /// records `os.environ` (scripts/gemma_contbatch/runner.py) would then
+ /// disagree with what was actually measured. Benchmark-style callers check
+ /// this first and refuse to run on a conflict instead of silently
+ /// rewriting the operator's shell. Sorted scan keeps the reported key
+ /// stable across runs.
+ internal static func conflictingEnvironmentOverride(
+ settings: GemmaOptimizationSettings,
+ getenv: (String) -> String? = {
+ $0.withCString { Darwin.getenv($0) }.map { String(cString: $0) }
+ }
+ ) -> EnvironmentConflict? {
+ let projection = GemmaOptimizationEnvironment.projection(for: settings)
+ for key in [
+ GemmaOptimizationEnvironment.prefillLayer18Key,
+ GemmaOptimizationEnvironment.weightedUnsortKey,
+ GemmaOptimizationEnvironment.safeR1Key,
+ ].sorted() {
+ guard let shellValue = getenv(key),
+ shellValue != projection[key] else { continue }
+ return EnvironmentConflict(
+ key: key,
+ shellValue: shellValue,
+ configValue: projection[key] ?? ""
+ )
+ }
+ return nil
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/StartCommand.swift b/provider-swift/Sources/darkbloom/StartCommand.swift
index b9746b8f1a..e4e5c2d687 100644
--- a/provider-swift/Sources/darkbloom/StartCommand.swift
+++ b/provider-swift/Sources/darkbloom/StartCommand.swift
@@ -118,12 +118,12 @@ struct Start: AsyncParsableCommand {
}
}
- /// Testable ordering seam for process-start environment projection. The
- /// default closures are the production path; tests replace only the Metal
- /// probe so they can assert ordering without constructing an MLX device.
- ///
- /// A rejected projection throws before `requireMetal()`, so a half-applied
- /// weighted-unsort/safe-R1 pair can never reach engine construction.
+ /// Backward-compatible forwarding shim for the process-start environment
+ /// projection. The real seam (and its ordering contract: config projection
+ /// strictly BEFORE the first MLX touch; a rejected projection throws
+ /// before `requireMetal()`) lives in `ServeRuntimePreparer.prepareRuntime`
+ /// so `benchmark` mirrors the serve path without referencing `Start`.
+ /// Tests target `ServeRuntimePreparer` directly.
internal static func prepareServeRuntime(
settings: GemmaOptimizationSettings,
apply: (GemmaOptimizationSettings) throws -> Void = {
@@ -133,8 +133,11 @@ struct Start: AsyncParsableCommand {
_ = try GPUEnforcement.requireMetal()
}
) throws {
- try apply(settings)
- try requireMetal()
+ try ServeRuntimePreparer.prepareRuntime(
+ settings: settings,
+ apply: apply,
+ requireMetal: requireMetal
+ )
}
}
diff --git a/provider-swift/Tests/DarkbloomCLITests/BetaCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/BetaCommandTests.swift
new file mode 100644
index 0000000000..f0e54b79f7
--- /dev/null
+++ b/provider-swift/Tests/DarkbloomCLITests/BetaCommandTests.swift
@@ -0,0 +1,235 @@
+import Darwin
+import Foundation
+import ProviderCore
+import Testing
+
+@testable import darkbloom
+
+@Suite("Beta command config mutation")
+struct BetaCommandTests {
+
+ /// Write `toml` (when non-nil) into a unique temp `provider.toml` and
+ /// return its URL. `~/.config/darkbloom/provider.toml` is guarded around
+ /// every toggle call: a non-canonical config path triggers
+ /// loadRuntimeSnapshot's legacy→canonical copy when the canonical file is
+ /// ABSENT, which would otherwise plant test fixtures in the operator's
+ /// real config on a fresh machine.
+ private func makeTempConfig(_ toml: String?) throws -> URL {
+ let directory = FileManager.default.temporaryDirectory
+ .appendingPathComponent("beta-cfg-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(
+ at: directory, withIntermediateDirectories: true)
+ let url = directory.appendingPathComponent("provider.toml")
+ if let toml {
+ try toml.write(to: url, atomically: true, encoding: .utf8)
+ }
+ return url
+ }
+
+ private func withGuardedCanonicalConfig(
+ _ body: () throws -> Void
+ ) rethrows {
+ let canonical = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".config/darkbloom/provider.toml")
+ let existedBefore = FileManager.default.fileExists(atPath: canonical.path)
+ defer {
+ if !existedBefore,
+ FileManager.default.fileExists(atPath: canonical.path) {
+ try? FileManager.default.removeItem(at: canonical)
+ }
+ }
+ try body()
+ }
+
+ @Test("enable with an absent section writes the key despite the matching default")
+ func enableMaterializesAbsentKey() throws {
+ let url = try makeTempConfig("""
+ [provider]
+ name = "beta-test"
+ """)
+ defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }
+
+ // weightedR1 already decodes to true via the default; the old code
+ // no-oped ("already enabled") without pinning anything.
+ try withGuardedCanonicalConfig {
+ try setBetaFeature("gemma-weighted-r1", enabled: true, configPath: url.path)
+ }
+
+ let written = try String(contentsOf: url, encoding: .utf8)
+ #expect(written.contains("[gemma_optimizations]"))
+ #expect(written.contains("weighted_r1 = true"))
+ let reloaded = try ConfigManager.load(from: url)
+ #expect(reloaded.gemmaOptimizations.weightedR1)
+ }
+
+ @Test("enable after the materializing write is a true no-op")
+ func secondEnableDoesNotRewrite() throws {
+ let url = try makeTempConfig("""
+ [provider]
+ name = "beta-test"
+ """)
+ defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }
+
+ try withGuardedCanonicalConfig {
+ try setBetaFeature("gemma-weighted-r1", enabled: true, configPath: url.path)
+ let pinned = try String(contentsOf: url, encoding: .utf8)
+
+ try setBetaFeature("gemma-weighted-r1", enabled: true, configPath: url.path)
+ let after = try String(contentsOf: url, encoding: .utf8)
+
+ #expect(after == pinned)
+ }
+ }
+
+ @Test("a key pinned at the target value is a no-op without a rewrite")
+ func pinnedKeyIsNoOp() throws {
+ let url = try makeTempConfig("""
+ [provider]
+ name = "beta-test"
+
+ [gemma_optimizations]
+ weighted_r1 = true
+ """)
+ defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }
+ let before = try String(contentsOf: url, encoding: .utf8)
+
+ try withGuardedCanonicalConfig {
+ try setBetaFeature("gemma-weighted-r1", enabled: true, configPath: url.path)
+ }
+
+ let after = try String(contentsOf: url, encoding: .utf8)
+ #expect(after == before)
+ }
+
+ @Test("disable with an absent key still writes a default-off feature")
+ func disableMaterializesAbsentKey() throws {
+ // kv-quant defaults off: disabling an absent key used to no-op without
+ // persisting the operator's intent.
+ let url = try makeTempConfig("""
+ [provider]
+ name = "beta-test"
+ """)
+ defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }
+
+ try withGuardedCanonicalConfig {
+ try setBetaFeature("kv-quant", enabled: false, configPath: url.path)
+ }
+
+ let written = try String(contentsOf: url, encoding: .utf8)
+ #expect(written.contains("kv_quant = false"))
+ #expect(tomlKeyPresent(written, section: "backend", key: "kv_quant"))
+ }
+
+ @Test("disable flips a pinned key and keeps its neighbour")
+ func disableFlipsPinnedKey() throws {
+ let url = try makeTempConfig("""
+ [provider]
+ name = "beta-test"
+
+ [gemma_optimizations]
+ prefill_layer18 = false
+ """)
+ defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }
+
+ try withGuardedCanonicalConfig {
+ try setBetaFeature("gemma-weighted-r1", enabled: false, configPath: url.path)
+ }
+
+ let reloaded = try ConfigManager.load(from: url)
+ #expect(!reloaded.gemmaOptimizations.weightedR1)
+ #expect(!reloaded.gemmaOptimizations.prefillLayer18)
+ let written = try String(contentsOf: url, encoding: .utf8)
+ #expect(written.contains("weighted_r1 = false"))
+ #expect(written.contains("prefill_layer18 = false"))
+ }
+
+ @Test("an unknown feature id is rejected before touching the file")
+ func unknownFeatureThrows() throws {
+ let url = try makeTempConfig("""
+ [provider]
+ name = "beta-test"
+ """)
+ defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }
+ let before = try String(contentsOf: url, encoding: .utf8)
+
+ do {
+ try setBetaFeature("gemma-expert-packing", enabled: true, configPath: url.path)
+ Issue.record("gemma-expert-packing is not a beta feature in this build")
+ } catch {
+ // ValidationError naming the known feature ids.
+ }
+
+ let after = try String(contentsOf: url, encoding: .utf8)
+ #expect(after == before)
+ }
+
+ @Test("enabling into a missing config file creates it with the key")
+ func missingFileIsWritten() throws {
+ let url = try makeTempConfig(nil)
+ defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }
+
+ try withGuardedCanonicalConfig {
+ try setBetaFeature("gemma-prefill-layer18", enabled: false, configPath: url.path)
+ }
+
+ let written = try String(contentsOf: url, encoding: .utf8)
+ #expect(written.contains("prefill_layer18 = false"))
+ }
+
+ // MARK: - tomlKeyPresent
+
+ @Test("tomlKeyPresent matches keys inside their own section only")
+ func tomlKeyPresentSectioning() {
+ let content = """
+ [provider]
+ name = "x"
+
+ [gemma_optimizations]
+ weighted_r1 = false
+
+ [backend]
+ kv_quant = true
+ """
+
+ #expect(tomlKeyPresent(content, section: "gemma_optimizations", key: "weighted_r1"))
+ #expect(tomlKeyPresent(content, section: "backend", key: "kv_quant"))
+ #expect(!tomlKeyPresent(content, section: "backend", key: "weighted_r1"))
+ #expect(!tomlKeyPresent(content, section: "gemma_optimizations", key: "kv_quant"))
+ #expect(!tomlKeyPresent(content, section: "gemma_optimizations", key: "prefill_layer18"))
+ }
+
+ @Test("tomlKeyPresent ignores commented-out keys")
+ func tomlKeyPresentIgnoresComments() {
+ let content = """
+ [gemma_optimizations]
+ # weighted_r1 = false
+ """
+ #expect(!tomlKeyPresent(content, section: "gemma_optimizations", key: "weighted_r1"))
+ }
+
+ // MARK: - config flock
+
+ @Test("the config lock excludes a second exclusive flock on the sidecar")
+ func configLockMutualExclusion() throws {
+ let url = try makeTempConfig(nil)
+ defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }
+
+ let lockPath = url.path + ".lock"
+ try withExclusiveConfigLock(at: url) {
+ let fd = open(lockPath, O_RDWR | O_CREAT, 0o644)
+ #expect(fd >= 0)
+ defer { close(fd) }
+ // flock is per open-file-description: a second descriptor to the
+ // same sidecar must fail LOCK_EX|LOCK_NB while the guard holds it.
+ #expect(flock(fd, LOCK_EX | LOCK_NB) != 0)
+ #expect(errno == EWOULDBLOCK)
+ }
+
+ // After the guard released it, an exclusive lock succeeds again.
+ let fd = open(lockPath, O_RDWR | O_CREAT, 0o644)
+ #expect(fd >= 0)
+ defer { close(fd) }
+ #expect(flock(fd, LOCK_EX | LOCK_NB) == 0)
+ _ = flock(fd, LOCK_UN)
+ }
+}
diff --git a/provider-swift/Tests/DarkbloomCLITests/RuntimeSnapshotConfigTests.swift b/provider-swift/Tests/DarkbloomCLITests/RuntimeSnapshotConfigTests.swift
new file mode 100644
index 0000000000..f611db8cf6
--- /dev/null
+++ b/provider-swift/Tests/DarkbloomCLITests/RuntimeSnapshotConfigTests.swift
@@ -0,0 +1,54 @@
+import Foundation
+import ProviderCore
+import Testing
+
+@testable import darkbloom
+
+/// Operator-facing pin for the v0.8.2 config-loading contract: every
+/// snapshot-based command (`start`, `benchmark`, `beta`, ...) loads its config
+/// through `loadRuntimeSnapshot`. A MISSING file must keep defaulting
+/// leniently; an EXISTING but malformed file must fail loudly instead of
+/// silently re-enabling whole-config defaults (e.g. re-arming the default-on
+/// Gemma stack after a botched rollback edit).
+@Suite("Runtime snapshot config loading")
+struct RuntimeSnapshotConfigTests {
+
+ private func tempConfigURL() -> URL {
+ FileManager.default.temporaryDirectory
+ .appendingPathComponent("snapshot-cfg-\(UUID().uuidString).toml")
+ }
+
+ @Test("a missing config file keeps the lenient default path")
+ func missingConfigYieldsDefaults() throws {
+ let missing = tempConfigURL()
+
+ let snapshot = try loadRuntimeSnapshot(configPath: missing.path)
+
+ #expect(!snapshot.configFileExists)
+ // Missing section/keys decode defaulted: the optimisation stack stays
+ // on; hardware-derived name when detection succeeds, "darkbloom" else.
+ #expect(snapshot.config.gemmaOptimizations == GemmaOptimizationSettings())
+ #expect(snapshot.config.gemmaOptimizations.prefillLayer18)
+ #expect(snapshot.config.gemmaOptimizations.weightedR1)
+ }
+
+ @Test("a malformed config file fails the load loudly")
+ func malformedConfigThrows() throws {
+ let url = tempConfigURL()
+ try """
+ [provider]
+ name = "snapshot-test"
+
+ [gemma_optimizations]
+ weighted_r1 = 0
+ """.write(to: url, atomically: true, encoding: .utf8)
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ do {
+ _ = try loadRuntimeSnapshot(configPath: url.path)
+ Issue.record("a malformed provider.toml must abort, not silently default")
+ } catch ConfigError.parseFailed(let detail) {
+ #expect(!detail.isEmpty)
+ }
+ }
+}
diff --git a/provider-swift/Tests/DarkbloomCLITests/StartCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/StartCommandTests.swift
index 0b746853a1..294bfbe80f 100644
--- a/provider-swift/Tests/DarkbloomCLITests/StartCommandTests.swift
+++ b/provider-swift/Tests/DarkbloomCLITests/StartCommandTests.swift
@@ -5,7 +5,7 @@ import Testing
@testable import darkbloom
-@Suite("Start command runtime preparation")
+@Suite("Serve runtime preparation (shared Start/Benchmark seam)")
struct StartCommandTests {
@Test("TOML projection precedes the first MLX touch")
func projectionPrecedesMetal() throws {
@@ -15,7 +15,7 @@ struct StartCommandTests {
)
var events: [String] = []
- try Start.prepareServeRuntime(
+ try ServeRuntimePreparer.prepareRuntime(
settings: settings,
apply: { received in
#expect(received.prefillLayer18 == false)
@@ -44,7 +44,7 @@ struct StartCommandTests {
// The coupled weighted-unsort/safe-R1 pair is a process-start latch:
// a half-applied projection must never reach engine construction.
do {
- try Start.prepareServeRuntime(
+ try ServeRuntimePreparer.prepareRuntime(
settings: GemmaOptimizationSettings(),
apply: { _ in
events.append("projection")
@@ -86,7 +86,7 @@ struct StartCommandTests {
}
var metalProbed = false
- try Start.prepareServeRuntime(
+ try ServeRuntimePreparer.prepareRuntime(
settings: settings,
requireMetal: { metalProbed = true }
)
@@ -98,6 +98,74 @@ struct StartCommandTests {
#expect(metalProbed)
}
+ @Test("the Start compatibility shim forwards to the shared seam")
+ func startShimForwards() throws {
+ var events: [String] = []
+ try Start.prepareServeRuntime(
+ settings: GemmaOptimizationSettings(),
+ apply: { _ in events.append("projection") },
+ requireMetal: { events.append("metal") }
+ )
+ #expect(events == ["projection", "metal"])
+ }
+
+ @Test("benchmark env guard: a conflicting shell preset is rejected")
+ func conflictingEnvironmentOverrideReportsConflict() throws {
+ let settings = GemmaOptimizationSettings(
+ prefillLayer18: true,
+ weightedR1: true
+ )
+ let conflict = ServeRuntimePreparer.conflictingEnvironmentOverride(
+ settings: settings
+ ) { key in
+ // Operator rolled back via the shell, config still selects on.
+ key == GemmaOptimizationEnvironment.safeR1Key ? "0" : nil
+ }
+
+ let found = try #require(conflict)
+ #expect(found.key == GemmaOptimizationEnvironment.safeR1Key)
+ #expect(found.shellValue == "0")
+ #expect(found.configValue == "1")
+ }
+
+ @Test("benchmark env guard: the paired weighted-unsort key is checked too")
+ func conflictingEnvironmentOverrideChecksWeightedKey() {
+ let settings = GemmaOptimizationSettings(
+ prefillLayer18: false,
+ weightedR1: false
+ )
+ let conflict = ServeRuntimePreparer.conflictingEnvironmentOverride(
+ settings: settings
+ ) { key in
+ key == GemmaOptimizationEnvironment.weightedUnsortKey ? "1" : nil
+ }
+
+ #expect(conflict?.key == GemmaOptimizationEnvironment.weightedUnsortKey)
+ #expect(conflict?.shellValue == "1")
+ #expect(conflict?.configValue == "0")
+ }
+
+ @Test("benchmark env guard: matching or unset shell values are not flagged")
+ func conflictingEnvironmentOverrideAllowsConsistent() {
+ let settings = GemmaOptimizationSettings(
+ prefillLayer18: true,
+ weightedR1: false
+ )
+ let projection = GemmaOptimizationEnvironment.projection(for: settings)
+
+ // Every preset value EQUALS the projection — consistent, proceed.
+ let consistent = ServeRuntimePreparer.conflictingEnvironmentOverride(
+ settings: settings
+ ) { projection[$0] }
+ #expect(consistent == nil)
+
+ // Nothing preset at all — proceed.
+ let unset = ServeRuntimePreparer.conflictingEnvironmentOverride(
+ settings: settings
+ ) { _ in nil }
+ #expect(unset == nil)
+ }
+
@Test("start accepts an explicit custom config")
func customConfigParses() throws {
let parsed = try Darkbloom.parseAsRoot([
diff --git a/provider-swift/Tests/ProviderCoreTests/ConfigValidationTests.swift b/provider-swift/Tests/ProviderCoreTests/ConfigValidationTests.swift
new file mode 100644
index 0000000000..2c4a840f92
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/ConfigValidationTests.swift
@@ -0,0 +1,159 @@
+import Foundation
+import Testing
+@testable import ProviderCore
+
+/// v0.8.2 config-loading hardening: the lenient `ConfigManager.parse` stays
+/// for tests only. The production FILE path (`load(from:)` →
+/// `parseValidating`) must fail loudly — a malformed `[gemma_optimizations]`
+/// entry previously decoded to whole-config defaults and silently re-enabled
+/// the default-on stack (and silently applied any other default) with no log.
+@Suite("Config strict loading")
+struct ConfigValidationTests {
+
+ private func writeTempConfig(_ toml: String) throws -> URL {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("config-validation-\(UUID().uuidString).toml")
+ try toml.write(to: url, atomically: true, encoding: .utf8)
+ return url
+ }
+
+ // MARK: - parseValidating
+
+ @Test("parseValidating decodes a well-formed config")
+ func parseValidatingDecodesValid() throws {
+ let config = try ConfigManager.parseValidating("""
+ [provider]
+ name = "strict-provider"
+
+ [gemma_optimizations]
+ prefill_layer18 = false
+ weighted_r1 = false
+ """)
+
+ #expect(config.provider.name == "strict-provider")
+ #expect(!config.gemmaOptimizations.prefillLayer18)
+ #expect(!config.gemmaOptimizations.weightedR1)
+ }
+
+ @Test("parseValidating still defaults a missing optimisation section on")
+ func parseValidatingDefaultsMissingSectionOn() throws {
+ let config = try ConfigManager.parseValidating("""
+ [provider]
+ name = "strict-provider"
+ """)
+
+ #expect(config.gemmaOptimizations == GemmaOptimizationSettings())
+ #expect(config.gemmaOptimizations.prefillLayer18)
+ #expect(config.gemmaOptimizations.weightedR1)
+ }
+
+ @Test("parseValidating keys off per-key defaults for a partial section")
+ func parseValidatingDefaultsMissingKeysOn() throws {
+ let config = try ConfigManager.parseValidating("""
+ [gemma_optimizations]
+ weighted_r1 = false
+ """)
+
+ #expect(config.gemmaOptimizations.prefillLayer18)
+ #expect(!config.gemmaOptimizations.weightedR1)
+ }
+
+ @Test("parseValidating rejects a mis-typed rollback key")
+ func parseValidatingRejectsIntegerBool() throws {
+ do {
+ _ = try ConfigManager.parseValidating("""
+ [gemma_optimizations]
+ weighted_r1 = 0
+ """)
+ Issue.record("weighted_r1 = 0 is not a Bool and must not decode")
+ } catch ConfigError.parseFailed(let detail) {
+ #expect(!detail.isEmpty)
+ }
+ }
+
+ @Test("parseValidating rejects a quoted rollback key")
+ func parseValidatingRejectsQuotedBool() throws {
+ do {
+ _ = try ConfigManager.parseValidating("""
+ [gemma_optimizations]
+ prefill_layer18 = "false"
+ """)
+ Issue.record("prefill_layer18 = \"false\" is not a Bool and must not decode")
+ } catch ConfigError.parseFailed(let detail) {
+ #expect(!detail.isEmpty)
+ }
+ }
+
+ @Test("parseValidating rejects syntactically broken TOML")
+ func parseValidatingRejectsBrokenSyntax() throws {
+ do {
+ _ = try ConfigManager.parseValidating("[gemma_optimizations\nbroken")
+ Issue.record("syntactically broken TOML must not decode")
+ } catch ConfigError.parseFailed(let detail) {
+ #expect(!detail.isEmpty)
+ }
+ }
+
+ // MARK: - file-loading boundary
+
+ @Test("a malformed existing config file fails loading loudly")
+ func malformedFileThrowsOnLoad() throws {
+ let url = try writeTempConfig("""
+ [provider]
+ name = "strict-provider"
+
+ [gemma_optimizations]
+ weighted_r1 = 0
+ """)
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ do {
+ _ = try ConfigManager.load(from: url)
+ Issue.record("loading a malformed config file must throw, not default")
+ } catch ConfigError.parseFailed(let detail) {
+ #expect(!detail.isEmpty)
+ }
+ }
+
+ @Test("a well-formed existing config file still loads")
+ func wellFormedFileLoads() throws {
+ let url = try writeTempConfig("""
+ [provider]
+ name = "strict-provider"
+
+ [gemma_optimizations]
+ prefill_layer18 = false
+ """)
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ let config = try ConfigManager.load(from: url)
+ #expect(config.provider.name == "strict-provider")
+ #expect(!config.gemmaOptimizations.prefillLayer18)
+ #expect(config.gemmaOptimizations.weightedR1)
+ }
+
+ @Test("a missing config file reports a read failure, not a parse failure")
+ func missingFileIsReadFailure() throws {
+ let missing = FileManager.default.temporaryDirectory
+ .appendingPathComponent("config-validation-missing-\(UUID().uuidString).toml")
+
+ do {
+ _ = try ConfigManager.load(from: missing)
+ Issue.record("loading a missing file must throw")
+ } catch ConfigError.readFailed {
+ // Expected: missing-file LENIENCY lives one layer up
+ // (loadDefault / loadRuntimeSnapshot substitute defaults there),
+ // never a silent whole-config default from this boundary.
+ }
+ }
+
+ @Test("the lenient test-facing parse keeps its historical contract")
+ func lenientParseStillDefaultsOnMalformed() {
+ let config = ConfigManager.parse("""
+ [gemma_optimizations]
+ weighted_r1 = 0
+ """)
+
+ #expect(config.gemmaOptimizations == GemmaOptimizationSettings())
+ }
+}
From c8045ce633f9836c5244c194d09b4d7ba42911c5 Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 10:15:13 -0700
Subject: [PATCH 08/23] chore(deps): pin mlx-swift-lm f00c9bd + mlx-swift
746d7c5 (review-fix cascade); fix benchmark stdout hygiene
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- mlx-swift-lm f00c9bd: completes the global-KV-head rule across the
CBv2 layer-kind derivation and MTP validation, re-forges the vacuous
fp16 overflow proof at norm gains, normalizes short/empty
layer_types, pins rank-1 at both entries and the canonical
ProportionalRoPE construction.
- mlx-swift 746d7c5 (with nested 8d538a08): fail-safe sortedness check
in the R1 tile builder (host re-routes to legacy on violation),
shared route predicate, hit-only bias normalization, atomic armed_;
mirrors/facades byte-synced; xcodeproj generator now preserves the
C-mode MLX_API fallback; facade ABI pinned with _Static_asserts;
ON-path test invocation documented.
- SlotSizingDriftTests: track the gemma4LayerKinds signature change.
- BenchmarkCommand: project the effective settings echo to stderr —
benchmark subcommands emit machine-parsed JSON on stdout (a stdout
line broke the gemma-contbatch harness).
---
libs/mlx-swift | 2 +-
libs/mlx-swift-lm | 2 +-
provider-swift/Sources/darkbloom/BenchmarkCommand.swift | 7 ++++++-
.../Tests/ProviderCoreTests/SlotSizingDriftTests.swift | 3 +--
4 files changed, 9 insertions(+), 5 deletions(-)
diff --git a/libs/mlx-swift b/libs/mlx-swift
index cdb7bcd807..746d7c5c67 160000
--- a/libs/mlx-swift
+++ b/libs/mlx-swift
@@ -1 +1 @@
-Subproject commit cdb7bcd807d8d70a864b09c14f938068b4e0c22d
+Subproject commit 746d7c5c671a52c0d8d7ddb60e916455e3161186
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index 1d46abc2df..f00c9bdcfa 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit 1d46abc2df6adcc9032c6a7dde350f17b47a9099
+Subproject commit f00c9bdcfa3c432379a1329a0d80562a224310bd
diff --git a/provider-swift/Sources/darkbloom/BenchmarkCommand.swift b/provider-swift/Sources/darkbloom/BenchmarkCommand.swift
index 18a6764bdf..39978b2b89 100644
--- a/provider-swift/Sources/darkbloom/BenchmarkCommand.swift
+++ b/provider-swift/Sources/darkbloom/BenchmarkCommand.swift
@@ -1,4 +1,5 @@
import ArgumentParser
+import Foundation
import ProviderCore
import ProviderBenchmark
@@ -107,7 +108,11 @@ struct Benchmark: AsyncParsableCommand {
printError("\(error)")
throw ExitCode.failure
}
- print("gemma optimizations: prefill_layer18=\(gemmaSettings.prefillLayer18 ? "on" : "off") weighted_r1=\(gemmaSettings.weightedR1 ? "on" : "off")")
+ // stderr, not stdout — benchmark subcommands emit machine-parsed JSON
+ // on stdout (any stray line breaks `darkbloom benchmark`'s consumers).
+ FileHandle.standardError.write(Data(
+ "gemma optimizations: prefill_layer18=\(gemmaSettings.prefillLayer18 ? "on" : "off") weighted_r1=\(gemmaSettings.weightedR1 ? "on" : "off")\n"
+ .utf8))
guard let hardware = snapshot.hardware else {
printError("hardware detection failed: \(snapshot.hardwareError?.localizedDescription ?? "unknown")")
diff --git a/provider-swift/Tests/ProviderCoreTests/SlotSizingDriftTests.swift b/provider-swift/Tests/ProviderCoreTests/SlotSizingDriftTests.swift
index bc44a90eed..0097fd17c4 100644
--- a/provider-swift/Tests/ProviderCoreTests/SlotSizingDriftTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/SlotSizingDriftTests.swift
@@ -94,8 +94,7 @@ private func gemma4Kinds(from config: [String: Any]) -> [CBv2LayerKind] {
globalHeadDim: config["global_head_dim"] as! Int,
numAttentionHeads: config["num_attention_heads"] as! Int,
numKeyValueHeads: config["num_key_value_heads"] as! Int,
- numGlobalKeyValueHeads: config["num_global_key_value_heads"] as? Int,
- attentionKeqV: config["attention_k_eq_v"] as! Bool)
+ numGlobalKeyValueHeads: config["num_global_key_value_heads"] as? Int)
}
// MARK: - Tests
From b0fa08af6daf7c7e9f090943ab681b1b627604c3 Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 10:57:06 -0700
Subject: [PATCH 09/23] fix(provider): scope UpdateCommand config fallback to
missing files; widen preload-gate margin under parallel load; bump pins
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- UpdateCommand: only ConfigError.readFailed falls back to defaults — an
existing-but-malformed provider.toml now fails loudly instead of
silently resetting every setting and aiming the update check at the
wrong coordinator (final root-verifier residual item; watchdog's
deliberate fail-open posture unchanged).
- StartupPreloadTests: wall-clock margin 2.8s -> 4.5s; the semantic
signal is the .timedOut outcome + background continuation, and the
tight margin flaked at 2.8-3.5s under full-suite parallelism on
loaded machines (1692-test runs, twice, on this box).
- Pins: libs/mlx-swift-lm 06046c3 (last k_eq_v-gated head rule gone
from validateAttentionProducts), libs/mlx-swift 38eaa93 (nested
9b0d1b4c: sound adjacent-pair sortedness oracle + dedicated
fallback_sortedness_retracted counter, ABI 88, generator post-
condition; mirrors/facades byte-synced).
---
libs/mlx-swift | 2 +-
libs/mlx-swift-lm | 2 +-
provider-swift/Sources/darkbloom/UpdateCommand.swift | 6 +++++-
.../Tests/ProviderCoreTests/StartupPreloadTests.swift | 7 +++++--
4 files changed, 12 insertions(+), 5 deletions(-)
diff --git a/libs/mlx-swift b/libs/mlx-swift
index 746d7c5c67..38eaa93a75 160000
--- a/libs/mlx-swift
+++ b/libs/mlx-swift
@@ -1 +1 @@
-Subproject commit 746d7c5c671a52c0d8d7ddb60e916455e3161186
+Subproject commit 38eaa93a75ae85257b1df27aa4a7537cbba65881
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index f00c9bdcfa..06046c3f5d 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit f00c9bdcfa3c432379a1329a0d80562a224310bd
+Subproject commit 06046c3f5d442a14653a9a2cba09a1abe757c590
diff --git a/provider-swift/Sources/darkbloom/UpdateCommand.swift b/provider-swift/Sources/darkbloom/UpdateCommand.swift
index 9bb3b03a7b..5b46e891d0 100644
--- a/provider-swift/Sources/darkbloom/UpdateCommand.swift
+++ b/provider-swift/Sources/darkbloom/UpdateCommand.swift
@@ -26,7 +26,11 @@ struct Update: AsyncParsableCommand {
do {
let snapshot = try loadRuntimeSnapshot(configOptions: configOptions)
config = snapshot.config
- } catch {
+ } catch ConfigError.readFailed {
+ // Missing/unreadable config files legitimately fall back to
+ // defaults; a file that exists but doesn't parse must fail loudly
+ // instead of silently resetting (and quietly aiming an update
+ // check at the wrong coordinator).
config = ConfigManager.loadDefault()
}
diff --git a/provider-swift/Tests/ProviderCoreTests/StartupPreloadTests.swift b/provider-swift/Tests/ProviderCoreTests/StartupPreloadTests.swift
index 76ea5140f1..ae52ef7afe 100644
--- a/provider-swift/Tests/ProviderCoreTests/StartupPreloadTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/StartupPreloadTests.swift
@@ -461,9 +461,12 @@ struct StartupPreloadGateTests {
let gateElapsed = clock.now - start
// Availability beats perfection: the gate released at ~1s even though
- // ~2s of loading remained.
+ // ~2s of loading remained. The wall-clock margin must absorb parallel-
+ // suite scheduling stalls on loaded machines (observed 3.5s); the
+ // semantic signal is the .timedOut outcome + background continuation,
+ // not the sub-second margin.
#expect(outcome == .timedOut)
- #expect(gateElapsed < .milliseconds(2800))
+ #expect(gateElapsed < .milliseconds(4500))
#expect(recorder.loads.isEmpty)
// The driver keeps warming in the background after the gate released.
From 009b6b5ff5064b00a997908ee8ec17d13eb11682 Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 12:16:32 -0700
Subject: [PATCH 10/23] chore(deps): pin upstream-integrated mlx-swift-lm
---
libs/mlx-swift-lm | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index 06046c3f5d..c489f2d534 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit 06046c3f5d442a14653a9a2cba09a1abe757c590
+Subproject commit c489f2d534547b831c04224cad3ce45f9554263f
From d42a423ff408c713dd715de784c0f00438f5b171 Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 12:37:18 -0700
Subject: [PATCH 11/23] chore(deps): pin final Gemma review fixes
---
libs/mlx-swift-lm | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index c489f2d534..8ab2f9b4ca 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit c489f2d534547b831c04224cad3ce45f9554263f
+Subproject commit 8ab2f9b4ca9efab2c8d2c1cf41a3350dde19346a
From e651273d503ea0eecf5c1590dc4bad266fd1e7bb Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 13:01:10 -0700
Subject: [PATCH 12/23] test(provider): synchronize metallib environment
mutations
---
.../Helpers/MLXMetallibEnvironment.swift | 45 +++++++++++
.../LiveInferenceFixtures.swift | 77 +++++++++---------
.../ProviderCoreTests/MetallibHashTests.swift | 78 +++++++++++--------
3 files changed, 128 insertions(+), 72 deletions(-)
create mode 100644 provider-swift/Tests/ProviderCoreTests/Helpers/MLXMetallibEnvironment.swift
diff --git a/provider-swift/Tests/ProviderCoreTests/Helpers/MLXMetallibEnvironment.swift b/provider-swift/Tests/ProviderCoreTests/Helpers/MLXMetallibEnvironment.swift
new file mode 100644
index 0000000000..5d88a93fba
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/Helpers/MLXMetallibEnvironment.swift
@@ -0,0 +1,45 @@
+import Foundation
+
+enum MLXMetallibEnvironment {
+ private static let key = "MLX_METALLIB_PATH"
+ private static let lock = NSRecursiveLock()
+
+ static func withExclusiveAccess(
+ _ operation: () throws -> Result
+ ) rethrows -> Result {
+ lock.lock()
+ defer { lock.unlock() }
+ return try operation()
+ }
+
+ static func setPath(_ path: String?) {
+ withExclusiveAccess {
+ updatePath(path)
+ }
+ }
+
+ static func withPath(
+ _ path: String?,
+ operation: () throws -> Result
+ ) rethrows -> Result {
+ try withExclusiveAccess {
+ let previousPath = currentPath()
+ updatePath(path)
+ defer { updatePath(previousPath) }
+ return try operation()
+ }
+ }
+
+ private static func currentPath() -> String? {
+ guard let value = getenv(key) else { return nil }
+ return String(cString: value)
+ }
+
+ private static func updatePath(_ path: String?) {
+ if let path {
+ setenv(key, path, 1)
+ } else {
+ unsetenv(key)
+ }
+ }
+}
diff --git a/provider-swift/Tests/ProviderCoreTests/LiveInferenceFixtures.swift b/provider-swift/Tests/ProviderCoreTests/LiveInferenceFixtures.swift
index ce293314bd..75a2c254f8 100644
--- a/provider-swift/Tests/ProviderCoreTests/LiveInferenceFixtures.swift
+++ b/provider-swift/Tests/ProviderCoreTests/LiveInferenceFixtures.swift
@@ -7,8 +7,6 @@ import MLXLMCommon
// MARK: - Tiny, fast model used for the bulk of live tests.
enum LiveInferenceFixtures {
- private static let metallibColocationLock = NSLock()
-
/// Default tiny MLX-community model: ~600M params, ~1 GB on disk in 8-bit.
/// Loads in seconds and finishes a 16-token generation in well under 1s
/// on Apple Silicon. Has a chat template; no tool-calling weirdness.
@@ -88,47 +86,46 @@ enum LiveInferenceFixtures {
/// source metallib could be found -- in which case the caller should skip
/// the test rather than crashing in GPU initialization.
static func ensureMetallibColocated() -> URL? {
- metallibColocationLock.lock()
- defer { metallibColocationLock.unlock() }
-
- let fm = FileManager.default
-
- // 1. Find the test bundle's MacOS dir. Bundle(for:) reliably points
- // at the .xctest bundle even when launched via the system
- // `xctest` host (where _NSGetExecutablePath returns the host).
- guard let testBundleMacOSDir = testBundleExecutableDir() else {
- return nil
- }
- let destination = testBundleMacOSDir.appendingPathComponent("mlx.metallib")
+ MLXMetallibEnvironment.withExclusiveAccess {
+ let fm = FileManager.default
+
+ // 1. Find the test bundle's MacOS dir. Bundle(for:) reliably points
+ // at the .xctest bundle even when launched via the system
+ // `xctest` host (where _NSGetExecutablePath returns the host).
+ guard let testBundleMacOSDir = testBundleExecutableDir() else {
+ return nil
+ }
+ let destination = testBundleMacOSDir.appendingPathComponent("mlx.metallib")
- // 2. Resolve the authoritative staged source before considering the
- // runner copy. Existence alone does not prove source compatibility.
- guard let source = findSourceMetallib() else {
- return nil
- }
+ // 2. Resolve the authoritative staged source before considering the
+ // runner copy. Existence alone does not prove source compatibility.
+ guard let source = findSourceMetallib() else {
+ return nil
+ }
- do {
- // Copy beside the destination, then atomically replace the runner
- // file without loading the 150 MB+ metallib into process memory.
- let temporary = testBundleMacOSDir
- .appendingPathComponent(".mlx.metallib.\(UUID().uuidString)")
- defer { try? fm.removeItem(at: temporary) }
- try fm.copyItem(at: source, to: temporary)
- if fm.fileExists(atPath: destination.path) {
- _ = try fm.replaceItemAt(destination, withItemAt: temporary)
- } else {
- try fm.moveItem(at: temporary, to: destination)
+ do {
+ // Copy beside the destination, then atomically replace the runner
+ // file without loading the 150 MB+ metallib into process memory.
+ let temporary = testBundleMacOSDir
+ .appendingPathComponent(".mlx.metallib.\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: temporary) }
+ try fm.copyItem(at: source, to: temporary)
+ if fm.fileExists(atPath: destination.path) {
+ _ = try fm.replaceItemAt(destination, withItemAt: temporary)
+ } else {
+ try fm.moveItem(at: temporary, to: destination)
+ }
+ // Mirror to MLX_METALLIB_PATH so our own `locateMetallib()`
+ // (which trusts _NSGetExecutablePath, i.e. the xctest host
+ // path) can find it too if anyone else queries.
+ MLXMetallibEnvironment.setPath(destination.path)
+ return destination
+ } catch {
+ // The C++ runtime does not honor MLX_METALLIB_PATH, so failure to
+ // replace its runner-local copy must remain a fixture failure.
+ MLXMetallibEnvironment.setPath(source.path)
+ return nil
}
- // Mirror to MLX_METALLIB_PATH so our own `locateMetallib()`
- // (which trusts _NSGetExecutablePath, i.e. the xctest host
- // path) can find it too if anyone else queries.
- setenv("MLX_METALLIB_PATH", destination.path, 1)
- return destination
- } catch {
- // The C++ runtime does not honor MLX_METALLIB_PATH, so failure to
- // replace its runner-local copy must remain a fixture failure.
- setenv("MLX_METALLIB_PATH", source.path, 1)
- return nil
}
}
diff --git a/provider-swift/Tests/ProviderCoreTests/MetallibHashTests.swift b/provider-swift/Tests/ProviderCoreTests/MetallibHashTests.swift
index a6a46df344..d5e5755368 100644
--- a/provider-swift/Tests/ProviderCoreTests/MetallibHashTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/MetallibHashTests.swift
@@ -2,10 +2,8 @@ import Foundation
import Testing
@testable import ProviderCore
-/// Marked `.serialized` because every test in this suite mutates the
-/// process-wide MLX_METALLIB_PATH environment variable. Swift Testing's
-/// default parallel execution would race them and produce flakes like
-/// "metallibHash returned nil because another test just unset the env".
+/// Marked `.serialized` to avoid needless contention within this suite. The
+/// shared environment guard also excludes mutations from live-test fixtures.
@Suite("metallib hash + locator", .serialized)
struct MetallibHashTests {
@@ -16,11 +14,10 @@ struct MetallibHashTests {
defer { try? FileManager.default.removeItem(at: tmp) }
try Data("not really a metallib but exists".utf8).write(to: tmp)
- setenv("MLX_METALLIB_PATH", tmp.path, 1)
- defer { unsetenv("MLX_METALLIB_PATH") }
-
- let located = locateMetallib()
- #expect(located?.path == tmp.path)
+ MLXMetallibEnvironment.withPath(tmp.path) {
+ let located = locateMetallib()
+ #expect(located?.path == tmp.path)
+ }
}
@Test("metallibHash returns a 64-character hex string when located")
@@ -30,16 +27,15 @@ struct MetallibHashTests {
defer { try? FileManager.default.removeItem(at: tmp) }
try Data(repeating: 0x42, count: 1024).write(to: tmp)
- setenv("MLX_METALLIB_PATH", tmp.path, 1)
- defer { unsetenv("MLX_METALLIB_PATH") }
-
- guard let hash = metallibHash() else {
- Issue.record("metallibHash returned nil for an existing file at \(tmp.path)")
- return
+ MLXMetallibEnvironment.withPath(tmp.path) {
+ guard let hash = metallibHash() else {
+ Issue.record("metallibHash returned nil for an existing file at \(tmp.path)")
+ return
+ }
+ #expect(hash.count == 64)
+ let hex = Set("0123456789abcdef")
+ #expect(hash.allSatisfy { hex.contains($0) })
}
- #expect(hash.count == 64)
- let hex = Set("0123456789abcdef")
- #expect(hash.allSatisfy { hex.contains($0) })
}
@Test("metallibHash is stable across calls for the same file")
@@ -49,13 +45,32 @@ struct MetallibHashTests {
defer { try? FileManager.default.removeItem(at: tmp) }
try Data("hello mlx".utf8).write(to: tmp)
- setenv("MLX_METALLIB_PATH", tmp.path, 1)
- defer { unsetenv("MLX_METALLIB_PATH") }
+ let competing = URL(fileURLWithPath: NSTemporaryDirectory())
+ .appendingPathComponent("competing-mlx-\(UUID().uuidString).metallib")
+ defer { try? FileManager.default.removeItem(at: competing) }
+ try Data("different metallib".utf8).write(to: competing)
+
+ let mutationAttempted = DispatchSemaphore(value: 0)
+ let mutationCompleted = DispatchSemaphore(value: 0)
+
+ MLXMetallibEnvironment.withPath(tmp.path) {
+ let firstHash = metallibHash()
+ let mutationThread = Thread {
+ mutationAttempted.signal()
+ MLXMetallibEnvironment.withPath(competing.path) {}
+ mutationCompleted.signal()
+ }
+ mutationThread.start()
- let a = metallibHash()
- let b = metallibHash()
- #expect(a != nil)
- #expect(a == b)
+ #expect(mutationAttempted.wait(timeout: .now() + 5) == .success)
+ #expect(mutationCompleted.wait(timeout: .now() + 0.05) == .timedOut)
+
+ let secondHash = metallibHash()
+ #expect(firstHash != nil)
+ #expect(firstHash == secondHash)
+ }
+
+ #expect(mutationCompleted.wait(timeout: .now() + 5) == .success)
}
@Test("locateMetallib returns nil when nothing is found and no env override")
@@ -64,13 +79,12 @@ struct MetallibHashTests {
// through to the binary-adjacent search and may or may not find one
// (it could find one in the test bundle's .build path). We assert
// on the env override semantics only.
- setenv("MLX_METALLIB_PATH", "/var/empty/definitely-not-here.metallib", 1)
- defer { unsetenv("MLX_METALLIB_PATH") }
-
- // Env override misses → falls back to binary-adjacent search. The
- // test binary may or may not have a colocated metallib; we don't
- // assert one way or the other, just that the function returns
- // without crashing.
- _ = locateMetallib()
+ MLXMetallibEnvironment.withPath("/var/empty/definitely-not-here.metallib") {
+ // Env override misses → falls back to binary-adjacent search. The
+ // test binary may or may not have a colocated metallib; we don't
+ // assert one way or the other, just that the function returns
+ // without crashing.
+ _ = locateMetallib()
+ }
}
}
From e7be02abad49ed9a9e7a487276acca0025c047f5 Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 13:02:12 -0700
Subject: [PATCH 13/23] fix(bench): harden Gemma baseline verification
---
CHANGELOG.md | 2 +-
docs/provider/beta-features.md | 49 ++++---
docs/provider/cli-reference.md | 12 +-
docs/provider/quickstart.md | 11 +-
.../BackendParityHarness.swift | 2 +-
.../EngineV2Factory+Production.swift | 9 +-
.../Sources/ProviderCore/ProviderCore.swift | 6 +-
.../ProviderLoop+ModelLoading.swift | 14 +-
.../BenchmarkSweepExitTests.swift | 8 +-
.../EngineV2KVBackendGateTests.swift | 6 +-
.../EngineV2PagedParityLiveTests.swift | 14 +-
.../GemmaMTPProductionLiveTests.swift | 2 +-
scripts/gemma_contbatch/backend.py | 9 +-
scripts/gemma_contbatch/baseline.py | 7 +-
scripts/gemma_contbatch/config.py | 19 ++-
.../tests/test_gemma_optimizations.py | 126 +++++++++++++-----
16 files changed, 184 insertions(+), 112 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aac170c8ff..40990ba593 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,7 @@
#### Performance
-- **Gemma 4 26B-A4B v0.8.2 optimization stack** — Layer-18 lazy prefill submission; coupled weighted-expert-unsort + safe-R1 expert-QMM gate (both default-on via `[gemma_optimizations]`); direct shared VLM text tower (deletes the duplicate extraction tower); packed multimodal prefill inside q=128 query blocks; source-matched metallib enforced across CI/release/packaged smoke. Measured on `gemma-4-26B-A4B-it-qat-4bit` vs the v0.7.15 baseline: 2K-prompt TTFT 1.23x (1715 -> 1390 ms), TTFT under concurrent load 1.38-1.76x, arrival end-to-end throughput +18-25%, decode +1.3-2.3%, retention memory control within 0.06 GiB of default (B1/B2/B4 peaks 14.0/14.64/15.05 GiB vs 14.06/14.70/15.11; tmp/benchmarks/v0-8-2-retention-comparison.json). Dropped after measurement: expert gate/up packing, dense gate/up packing, standalone weighted-unsort, standalone R1. `0cc5fc9c9`
+- **Gemma 4 26B-A4B v0.8.2 optimization stack** — Layer-18 lazy prefill submission; coupled weighted-expert-unsort + safe-R1 expert-QMM gate (both default-on via `[gemma_optimizations]`); the VLM wrapper's directly shared text tower; packed multimodal prefill inside q=128 query blocks; source-matched metallib enforced across CI/release/packaged smoke. Final performance and retention deltas are pending a same-tree A/B measurement on the reviewed release tree. Earlier gitignored measurements predated the final kernel edits and are not release evidence. Dropped before the final cut: expert gate/up packing, dense gate/up packing, standalone weighted-unsort, standalone R1. `0cc5fc9c9`
---
diff --git a/docs/provider/beta-features.md b/docs/provider/beta-features.md
index 4c9ebde00f..a3ef584463 100644
--- a/docs/provider/beta-features.md
+++ b/docs/provider/beta-features.md
@@ -15,33 +15,34 @@ surface. Process-wide optimization state is resolved at startup, so restart
after changing a restart-required feature.
The registry of available features lives in
-`provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift:73-80`.
+`BetaFeatures.all` in
+`provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift:73-133`.
### Canonical implementation references
-- Default-on decoding for omitted config sections:
- `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationSettings.swift:16-20`
- (both fields default to `true`) and
- `provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift:332-334`
- (`decodeIfPresent` with the defaulted struct as fallback).
+- Default-on decoding for omitted keys is implemented by
+ `GemmaOptimizationSettings.init(from:)` in
+ `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationSettings.swift:29-35`.
+ The missing-section fallback is `ProviderConfig.init(from:)` in
+ `provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift:391-400`.
- Startup projection before the first MLX device access (daemon, foreground,
`--local`, and `benchmark` processes): the shared ordering seam is
`provider-swift/Sources/darkbloom/ServeRuntimePreparer.swift:24-35`
(`ServeRuntimePreparer.prepareRuntime`); the serve path calls it through
- `Start`'s forwarding shim at
- `provider-swift/Sources/darkbloom/StartCommand.swift:87`, and the benchmark
- path calls it directly at
- `provider-swift/Sources/darkbloom/BenchmarkCommand.swift:105`.
- Benchmark A/B is config-driven — a shell-preset low-level key that
- conflicts with the config projection is rejected rather than overwritten,
- and the effective controls are printed before measuring
- (`provider-swift/Sources/darkbloom/BenchmarkCommand.swift:91-110`, guard
- helper `provider-swift/Sources/darkbloom/ServeRuntimePreparer.swift:58-79`).
+ `Start.prepareServeRuntime` at
+ `provider-swift/Sources/darkbloom/StartCommand.swift:84-91,128-147`.
+ `Benchmark.run` rejects a conflicting shell override at
+ `provider-swift/Sources/darkbloom/BenchmarkCommand.swift:147-159`, prepares
+ the runtime at `:160-165`, and reports the effective controls at `:166-170`.
+ The guard helper is `ServeRuntimePreparer.conflictingEnvironmentOverride`
+ in `provider-swift/Sources/darkbloom/ServeRuntimePreparer.swift:48-79`.
- The config→environment projection and its overwrite authority:
- `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift:14-25`
- (`projection(for:)`) and `:57` (`apply(_:)`).
+ `GemmaOptimizationEnvironment.projection(for:)` in
+ `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift:10-23`
+ and `GemmaOptimizationEnvironment.apply(_:)` at `:52-64`.
- The `benchmark`-selected coupling of weighted unsort with safe R1 as one
- control: `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationSettings.swift:11-14`.
+ control: `GemmaOptimizationSettings.weightedR1` in
+ `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationSettings.swift:10-14`.
## The `darkbloom beta` command
@@ -121,10 +122,14 @@ darkbloom beta enable mtp
darkbloom restart
```
-Activation additionally requires a verified `spec_dec` assistant artifact in
-the model catalog. Production publishes that artifact for
-`gemma-4-26b-qat-4bit`; other models and providers without the explicit beta
-setting continue with target-only decoding.
+Without a valid local `[backend] mtp_drafter_path` override, activation also
+requires a verified `spec_dec` assistant artifact in the model catalog. The
+current public production catalog publishes `metadata.spec_dec` for
+`gemma-4-26b-qat-4bit` ([live catalog](https://api.darkbloom.dev/v1/models/catalog?type=text));
+other catalog models and providers without the explicit beta setting continue
+with target-only decoding. Artifact resolution and target-only fallback are in
+`ProviderLoop.specDecPreparation` at
+`provider-swift/Sources/ProviderCore/ProviderLoop+MTP.swift:35-54`.
The implementation has target-authoritative verification and focused parity
coverage. That is not a universal certification of token-identical behavior on
diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md
index 10f3f8461d..e3c8a25acf 100644
--- a/docs/provider/cli-reference.md
+++ b/docs/provider/cli-reference.md
@@ -154,9 +154,10 @@ Two of the detailed checks cover the KV-backend rollout:
| `kv backend posture` | An EXPLICIT `paged` or `contiguous` request was not honoured: refused (no engine built, the box serves nothing for that model) or silently degraded to another backend. |
`auto` never fails this check — it promises nothing, so whichever backend it
-lands on is honoured by definition. It resolves paged as of v0.8.0 and
-degrades to contiguous on a box that cannot serve paged, so an `auto` slot
-reporting contiguous is expected output, not a finding. When
+lands on is honoured by definition. It resolves contiguous as of v0.8.1, so an
+`auto` slot reporting contiguous is expected output, not a finding. Explicit
+`paged` remains available and refuses a load it cannot serve instead of
+silently changing backends. When
the state file is past the wedge bar the backend verdict is WITHHELD rather
than asserted from a snapshot that may predate a reload.
@@ -279,7 +280,7 @@ darkbloom beta disable # turn off
|---------|--------|
| `gemma-prefill-layer18` | Default-on layer-18 prefill submission; disable and restart for legacy submission behavior |
| `gemma-weighted-r1` | Default-on atomic weighted-unsort + safe-R1 pair; disable and restart to roll back both |
-| `mtp` | Default-off Gemma 4 MTP code path; requires a separately published and verified `spec_dec` artifact, which production does not currently have |
+| `mtp` | Default-off Gemma 4 MTP code path; uses a valid local `mtp_drafter_path` or a verified catalog `spec_dec` artifact. The current production catalog publishes one for `gemma-4-26b-qat-4bit` |
`enable`/`disable` read-modify-write the TOML config and report whether a restart
is required. Restart is the activation boundary for process-wide optimization
@@ -288,6 +289,9 @@ state. The durable locked write and restart instruction are implemented in
[Beta Features](beta-features.md) for the full guide. `darkbloom beta list` also
accepts `--json`. Installing a provider release does not enable MTP, and local
parity results are not a blanket M1-M3/unknown-chip certification.
+The published assistant metadata is visible in the
+[public production catalog](https://api.darkbloom.dev/v1/models/catalog?type=text)
+under `gemma-4-26b-qat-4bit.metadata.spec_dec`.
`kv-quant` was removed in v0.8.0 and is no longer a valid feature id.
## `darkbloom fan` (experimental)
diff --git a/docs/provider/quickstart.md b/docs/provider/quickstart.md
index 778b650f81..373a7aeeb4 100644
--- a/docs/provider/quickstart.md
+++ b/docs/provider/quickstart.md
@@ -199,14 +199,15 @@ end = "08:00"
cache is not constructed there.
Vision (VLM) models are NOT forced to contiguous. The
VLM veto in `EngineV2KVBackendPolicy.applySlotVetoes`
- (`guard isVLM, !pagedHonorsSpanMasks`, `provider-swift/Sources/ProviderCore/Inference/EngineV2KVBackendPolicy.swift:162`)
+ (`guard isVLM, !pagedHonorsSpanMasks`, `provider-swift/Sources/ProviderCore/Inference/EngineV2KVBackendPolicy.swift:202-210`)
fires only when the paged cache does not affirm multimodal span masks, and
`PagedLayerCache.honorsSpanMaskContextsByConstruction` is `true`
- (`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedLayerCache.swift:982`),
+ (`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedLayerCache.swift:994`),
which is what the slot factory passes
- (`provider-swift/Sources/ProviderCore/Inference/EngineV2SlotFactory.swift:190`),
- so the veto is inert: a VLM slot gets paged under `"auto"` like any
- other model.
+ (`provider-swift/Sources/ProviderCore/Inference/EngineV2SlotFactory.swift:301-304`),
+ so the veto is inert: an explicitly paged VLM slot can use paged like any
+ other model. Under `"auto"`, every slot resolves contiguous as described
+ above.
The concurrency cap above matters: paged only
overtakes contiguous above ~5 concurrent rows, so pairing
`engine_v2_kv_backend = "paged"` with a low `engine_v2_max_concurrent`
diff --git a/provider-swift/Sources/ProviderBenchmark/BackendParityHarness.swift b/provider-swift/Sources/ProviderBenchmark/BackendParityHarness.swift
index 9d03743e3a..5b6a2c1850 100644
--- a/provider-swift/Sources/ProviderBenchmark/BackendParityHarness.swift
+++ b/provider-swift/Sources/ProviderBenchmark/BackendParityHarness.swift
@@ -1168,7 +1168,7 @@ public enum BackendParityHarness {
+ "EngineV2SlotFactory). Every verdict here is a BACKEND result, not a "
+ "statement about how production routes a slot to that backend."
+ (isVLM ? " This checkpoint IS a VLM and is served here through the "
- + "text-extraction seam." : ""))
+ + "wrapper's directly owned shared text tower." : ""))
notes.append(
"token comparisons are over RAW SAMPLED TOKEN IDS with temperature 0; text "
+ "equality is a strictly weaker oracle and is not used.")
diff --git a/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Production.swift b/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Production.swift
index c6c3184d88..a9b6caad3b 100644
--- a/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Production.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Production.swift
@@ -66,10 +66,11 @@ enum EngineV2ProductionError: Error, CustomStringConvertible {
/// (`EngineV2Factory.pagedPoolDType(environment:)`) and surfaced as a
/// REFUSAL only for an EXPLICIT `.paged` selection — the measurement
/// posture the knob exists for, where silently serving fp16 under an
- /// fp32 label would fake a control arm. Under `.auto` (the fleet
- /// default since v0.8.0) the factory catches it and DEGRADES to
- /// contiguous with `fallbackReason = "invalid_dtype: …"` instead: one
- /// typo'd env var must not 503 every slot on the fleet.
+ /// fp32 label would fake a control arm. If `.auto` resolves paged, the
+ /// factory catches this and DEGRADES to contiguous with
+ /// `fallbackReason = "invalid_dtype: …"` instead. That path is dormant
+ /// while `.auto` resolves contiguous as of v0.8.1, but remains the safety
+ /// contract for any future paged default.
case invalidPagedPoolDType(String)
var description: String {
diff --git a/provider-swift/Sources/ProviderCore/ProviderCore.swift b/provider-swift/Sources/ProviderCore/ProviderCore.swift
index fa95919cf0..1f1ae0ce15 100644
--- a/provider-swift/Sources/ProviderCore/ProviderCore.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderCore.swift
@@ -197,8 +197,10 @@ public enum ProviderCore {
// staged, matched or adopted where adoption diverges. Paged code, the
// DARKBLOOM_CBV2_PAGED_KV kill switch, the crash-loop guard and the
// blocking paged CI lane all stay; `engine_v2_kv_backend = "paged"`
- // still resolves paged. `engine_v2_max_concurrent = 8` is NOT coupled
- // to paged and stays at 8.
+ // still resolves paged. The box-wide concurrency default returns to 4
+ // with contiguous. The v0.8.1 migration preserves an existing 8 only for
+ // an explicitly paged config, and 8 remains the supported upper bound for
+ // operator and per-model overrides.
//
// 0.8.2 adds the benchmark-retained Gemma 4 optimization stack: layer-18
// lazy prefill submission plus the coupled weighted-unsort/safe-R1 path,
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ModelLoading.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ModelLoading.swift
index be23fc5890..570c4d07fc 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop+ModelLoading.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ModelLoading.swift
@@ -555,13 +555,13 @@ extension ProviderLoop {
var sizing = slotBuild.sizing
var engineV2Bridge = engineBundle.bridge
- // Post-BRIDGE measured-headroom re-guard (v0.7.3, kept): the
- // engine build (and, for VLM slots, the text-model extraction +
- // parity probe) can retain additional load-time memory beyond
- // the weights the check above measured. Re-measure so a box
- // whose full load-time footprint leaves no serveable KV unloads
- // and 503s instead of advertising a model whose every request
- // the shared KV gate rejects — the v0.7.2 black-hole shape.
+ // Post-BRIDGE measured-headroom re-guard (v0.7.3, kept): engine
+ // construction can retain additional load-time memory beyond the
+ // weights the check above measured. VLM slots reuse the wrapper's
+ // directly owned text tower; no extraction copy is built. Re-measure
+ // so a box whose full load-time footprint leaves no serveable KV
+ // unloads and 503s instead of advertising a model whose every
+ // request the shared KV gate rejects — the v0.7.2 black-hole shape.
// BACKEND-AWARE: a PAGED slot's slabs are committed lazily at
// the pool's FIRST ADMISSION (`.atFirstAdmission`, the D1 fix),
// NOT at construction — so the measured headroom taken here
diff --git a/provider-swift/Tests/DarkbloomCLITests/BenchmarkSweepExitTests.swift b/provider-swift/Tests/DarkbloomCLITests/BenchmarkSweepExitTests.swift
index c8c618f5f9..4af107b318 100644
--- a/provider-swift/Tests/DarkbloomCLITests/BenchmarkSweepExitTests.swift
+++ b/provider-swift/Tests/DarkbloomCLITests/BenchmarkSweepExitTests.swift
@@ -129,10 +129,10 @@ struct BenchmarkSweepExitTests {
// Under `auto` the operator named no backend, so a cell that could
// not build one is an ordinary bad run, not a broken promise — the
// same asymmetry `EngineV2KVBackendPolicy.degradesPagedFailure`
- // encodes for the engine. `auto` resolves paged but DEGRADES on a
- // paged failure rather than refusing, so a paged capacity refusal is
- // still not reachable here; what is reachable is an ordinary
- // construction error, and it keeps its exit status.
+ // encodes for the engine. `auto` resolves contiguous as of v0.8.1,
+ // so a paged capacity refusal is not reachable here; what is reachable
+ // is an ordinary construction error, and it keeps its exit status. The
+ // degrade rule remains for any future release that resolves auto paged.
// Nil message ⇒ `runThroughputSweep` returns normally ⇒ 0.
#expect(Benchmark.sweepFailureMessage(
backend: .auto, failure: nil, coverage: coverage()) == nil)
diff --git a/provider-swift/Tests/ProviderCoreTests/EngineV2KVBackendGateTests.swift b/provider-swift/Tests/ProviderCoreTests/EngineV2KVBackendGateTests.swift
index f967b34c37..7d4e8c207e 100644
--- a/provider-swift/Tests/ProviderCoreTests/EngineV2KVBackendGateTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/EngineV2KVBackendGateTests.swift
@@ -1005,9 +1005,9 @@ struct EngineV2KVBackendGateTests {
/// resolved, so the next capability cannot land with the same invisible
/// gap.
///
- /// `preparedModel` is supplied so the VLM text extraction (which needs a
- /// checkpoint directory) is skipped: the subject here is the ROUTING for
- /// `isVLM: true`, not the extraction.
+ /// `preparedModel` is supplied so real VLM wrapper resolution is skipped:
+ /// the subject here is the ROUTING for `isVLM: true`, not selection of the
+ /// wrapper's directly owned text tower.
@Test("slot factory routes a VLM slot to paged now that the cache vouches")
func slotFactoryRoutesVLMToPagedWhenTheCacheVouches() async throws {
#expect(
diff --git a/provider-swift/Tests/ProviderCoreTests/EngineV2PagedParityLiveTests.swift b/provider-swift/Tests/ProviderCoreTests/EngineV2PagedParityLiveTests.swift
index b5f6b7520e..ec4e599275 100644
--- a/provider-swift/Tests/ProviderCoreTests/EngineV2PagedParityLiveTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/EngineV2PagedParityLiveTests.swift
@@ -158,10 +158,10 @@ struct EngineV2PagedParityLiveTests {
/// "Insufficient memory (X GB free, need Y GB) …" message. Everything
/// else reaching this catch IS a load-path regression the loop gates
/// exist to expose — explicit-paged refusal (the policy REFUSES instead
- /// of degrading for an explicit `.paged` selection), VLM extraction or
- /// engine-construction breakage, an invalid model directory, the
- /// post-bridge headroom guard unloading a fresh paged slot — and must
- /// fail the test, not return green.
+ /// of degrading for an explicit `.paged` selection), VLM serving-model
+ /// resolution or engine-construction breakage, an invalid model
+ /// directory, the post-bridge headroom guard unloading a fresh paged slot
+ /// — and must fail the test, not return green.
private func triageLoopGateLoadFailure(_ error: Error, arm: String) {
if case InferenceError.modelLoadFailed(let message) = error,
message.hasPrefix("Insufficient memory (")
@@ -521,9 +521,9 @@ struct EngineV2PagedParityLiveTests {
try await loop.ensureModelLoaded(modelId: Self.gemmaModelID)
} catch {
// Same triage as the gpt-oss arm: only the pre-load free-memory
- // refusal skips; explicit-paged refusal, VLM extraction failure,
- // engine-construction breakage, an invalid model dir, and the
- // post-bridge headroom guard all FAIL. See
+ // refusal skips; explicit-paged refusal, VLM serving-model
+ // resolution or engine-construction breakage, an invalid model
+ // dir, and the post-bridge headroom guard all FAIL. See
// triageLoopGateLoadFailure.
triageLoopGateLoadFailure(error, arm: "gemma-paged-loop")
return
diff --git a/provider-swift/Tests/ProviderCoreTests/GemmaMTPProductionLiveTests.swift b/provider-swift/Tests/ProviderCoreTests/GemmaMTPProductionLiveTests.swift
index af1baa99b8..309f7696da 100644
--- a/provider-swift/Tests/ProviderCoreTests/GemmaMTPProductionLiveTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/GemmaMTPProductionLiveTests.swift
@@ -154,7 +154,7 @@ struct GemmaMTPProductionLiveTests {
}
@Test(
- "VLM extraction and tool-templated decode retain greedy parity",
+ "shared VLM text tower and tool-templated decode retain greedy parity",
.enabled(
if: MTPProductionLiveFixtures.enabled,
MTPProductionLiveFixtures.disabledReason))
diff --git a/scripts/gemma_contbatch/backend.py b/scripts/gemma_contbatch/backend.py
index 1c6513e562..46f39225de 100644
--- a/scripts/gemma_contbatch/backend.py
+++ b/scripts/gemma_contbatch/backend.py
@@ -2,10 +2,11 @@
A decode curve is only comparable to another decode curve if both were
produced by the same KV backend. Nothing else in this harness can establish
-that: `--kv-backend auto` is a *selection*. It resolves paged as of v0.8.0
-(see the provider's `EngineV2Factory.prepareProductionBackend`) but degrades
-to contiguous on a box that cannot serve paged, and an explicit `paged` can
-still be vetoed by the fleet kill switch. A run that
+that: `--kv-backend auto` is a *selection* and resolves contiguous as of
+v0.8.1 (see the provider's `EngineV2Factory.prepareProductionBackend`). The
+wrapper requests `paged` explicitly; that selection refuses when paged cannot
+be built, while the fleet kill switch can deliberately degrade it to
+contiguous. A run that
did not build the backend it names measures the fallback while every other
check in this wrapper stays green, and a percentage delta against a baseline
recorded on the other backend is a backend change wearing a performance
diff --git a/scripts/gemma_contbatch/baseline.py b/scripts/gemma_contbatch/baseline.py
index 2d7581570c..7aa6c52a7b 100644
--- a/scripts/gemma_contbatch/baseline.py
+++ b/scripts/gemma_contbatch/baseline.py
@@ -15,6 +15,7 @@
from .config import SCHEMA_VERSION
from .environment import baseline_environment
+from .gemma_optimizations import validate_gemma_optimizations
NO_COMPARE_HINT = "omit --baseline to run without a comparison"
@@ -111,6 +112,8 @@ def validate_configuration_pin(
if not isinstance(baseline_configuration, dict):
raise RuntimeError("baseline does not record a configuration; " + NO_COMPARE_HINT)
expected = {
+ "iterations": args.iterations,
+ "decodeIterations": args.iterations,
"decodePromptTokens": args.decode_prompt_tokens,
"decodeTokens": args.decode_tokens,
"arrivalPromptTokens": args.arrival_prompt_tokens,
@@ -130,7 +133,9 @@ def validate_configuration_pin(
+ "; " + NO_COMPARE_HINT
)
- baseline_gemma = baseline_configuration.get("gemmaOptimizations")
+ baseline_gemma = validate_gemma_optimizations(
+ baseline_configuration.get("gemmaOptimizations"), "baseline configuration"
+ )
if comparison_axis == "code":
if baseline_gemma != gemma_optimizations:
raise RuntimeError(
diff --git a/scripts/gemma_contbatch/config.py b/scripts/gemma_contbatch/config.py
index 401ba917a8..e206487371 100644
--- a/scripts/gemma_contbatch/config.py
+++ b/scripts/gemma_contbatch/config.py
@@ -29,17 +29,14 @@
# The canonical posture this release is measured under. Both defaults are
# load-bearing:
#
-# paged — `auto` resolves PAGED as of v0.8.0, but it degrades
-# SILENTLY (kill switch, kernel preflight, pool capacity)
-# while an explicit `paged` REFUSES. Naming the backend is
-# the only way this wrapper can promise it measured what it
-# reports, so it is requested by name even though `auto`
-# would usually land on the same engine.
-# 1,2,4,8 — paged-vs-contiguous aggregate decode crosses over at ~B=5
-# (measured on gemma-4 / M4 Max: 0.92x at B=1, 0.98x at B=4,
-# 1.17x at B=8). A curve that stops at 4 structurally cannot
-# observe the win and reads as a regression. B=8 is also the
-# raised production concurrency ceiling. The list is sparse on
+# paged — `auto` resolves CONTIGUOUS as of v0.8.1. Naming `paged` is
+# therefore the only way this wrapper can promise it measured
+# the paged arm; an explicit request refuses when paged cannot
+# be built, except that the fleet kill switch deliberately
+# degrades to contiguous and is caught by the posture checks.
+# 1,2,4,8 — the current production concurrency default is B=4 under the
+# contiguous `auto` posture, while B=8 remains supported and is
+# the explicit-paged measurement point. The list is sparse on
# purpose: a dense 1..8 ladder doubles wall time for cells no
# gate reads.
DEFAULT_KV_BACKEND = "paged"
diff --git a/scripts/gemma_contbatch/tests/test_gemma_optimizations.py b/scripts/gemma_contbatch/tests/test_gemma_optimizations.py
index 33eadc0c8d..1c2f986137 100644
--- a/scripts/gemma_contbatch/tests/test_gemma_optimizations.py
+++ b/scripts/gemma_contbatch/tests/test_gemma_optimizations.py
@@ -2,8 +2,9 @@
from __future__ import annotations
-import unittest
+import copy
import tempfile
+import unittest
from pathlib import Path
from .. import runner
@@ -22,6 +23,27 @@ def raw_outputs() -> dict[str, dict]:
}
+def baseline_configuration(args) -> dict:
+ return {
+ "iterations": args.iterations,
+ "decodeIterations": args.iterations,
+ "decodePromptTokens": args.decode_prompt_tokens,
+ "decodeTokens": args.decode_tokens,
+ "arrivalPromptTokens": args.arrival_prompt_tokens,
+ "arrivalDecodeTokens": args.arrival_decode_tokens,
+ "batchSizes": args.batch_sizes,
+ "prefillLengths": args.prefill_lengths,
+ "gemmaOptimizations": copy.deepcopy(fixtures.GEMMA_OPTIMIZATIONS),
+ }
+
+
+def opposite_gemma_optimizations() -> dict:
+ settings = copy.deepcopy(fixtures.GEMMA_OPTIMIZATIONS)
+ settings["prefillLayer18"] = False
+ settings["environment"]["DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL"] = "0"
+ return settings
+
+
class GemmaOptimizationProvenanceTests(unittest.TestCase):
def test_matching_effective_settings_are_resolved(self):
self.assertEqual(
@@ -94,36 +116,15 @@ def test_missing_explicit_config_is_refused(self):
def test_baseline_with_different_effective_settings_is_refused(self):
args = make_args()
- baseline = {
- "configuration": {
- "decodePromptTokens": args.decode_prompt_tokens,
- "decodeTokens": args.decode_tokens,
- "arrivalPromptTokens": args.arrival_prompt_tokens,
- "arrivalDecodeTokens": args.arrival_decode_tokens,
- "batchSizes": args.batch_sizes,
- "prefillLengths": args.prefill_lengths,
- "gemmaOptimizations": {
- **fixtures.GEMMA_OPTIMIZATIONS,
- "prefillLayer18": False,
- },
- }
- }
+ configuration = baseline_configuration(args)
+ configuration["gemmaOptimizations"] = opposite_gemma_optimizations()
+ baseline = {"configuration": configuration}
with self.assertRaisesRegex(RuntimeError, "gemmaOptimizations"):
validate_configuration_pin(args, baseline, fixtures.GEMMA_OPTIMIZATIONS)
def test_gemma_axis_requires_different_settings(self):
args = make_args(comparison_axis="gemma-optimizations")
- baseline = {
- "configuration": {
- "decodePromptTokens": args.decode_prompt_tokens,
- "decodeTokens": args.decode_tokens,
- "arrivalPromptTokens": args.arrival_prompt_tokens,
- "arrivalDecodeTokens": args.arrival_decode_tokens,
- "batchSizes": args.batch_sizes,
- "prefillLengths": args.prefill_lengths,
- "gemmaOptimizations": fixtures.GEMMA_OPTIMIZATIONS,
- }
- }
+ baseline = {"configuration": baseline_configuration(args)}
with self.assertRaisesRegex(RuntimeError, "requires different"):
validate_configuration_pin(
args,
@@ -132,18 +133,73 @@ def test_gemma_axis_requires_different_settings(self):
comparison_axis=args.comparison_axis,
)
- off = {
- **fixtures.GEMMA_OPTIMIZATIONS,
- "prefillLayer18": False,
- "environment": {
- **fixtures.GEMMA_OPTIMIZATIONS["environment"],
- "DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL": "0",
- },
- }
validate_configuration_pin(
- args, baseline, off, comparison_axis=args.comparison_axis
+ args,
+ baseline,
+ opposite_gemma_optimizations(),
+ comparison_axis=args.comparison_axis,
)
+ def test_gemma_axis_refuses_absent_baseline_provenance(self):
+ args = make_args(comparison_axis="gemma-optimizations")
+ configuration = baseline_configuration(args)
+ del configuration["gemmaOptimizations"]
+ with self.assertRaisesRegex(
+ RuntimeError, "baseline configuration did not report effective"
+ ):
+ validate_configuration_pin(
+ args,
+ {"configuration": configuration},
+ opposite_gemma_optimizations(),
+ comparison_axis=args.comparison_axis,
+ )
+
+ def test_gemma_axis_refuses_malformed_baseline_provenance(self):
+ args = make_args(comparison_axis="gemma-optimizations")
+ configuration = baseline_configuration(args)
+ configuration["gemmaOptimizations"]["weightedR1"] = "on"
+ with self.assertRaisesRegex(
+ RuntimeError, "baseline configuration reported malformed"
+ ):
+ validate_configuration_pin(
+ args,
+ {"configuration": configuration},
+ opposite_gemma_optimizations(),
+ comparison_axis=args.comparison_axis,
+ )
+
+ def test_gemma_axis_refuses_partial_baseline_provenance(self):
+ args = make_args(comparison_axis="gemma-optimizations")
+ configuration = baseline_configuration(args)
+ del configuration["gemmaOptimizations"]["environment"][
+ "MLX_GATHER_QMM_EXPERT_SLICES"
+ ]
+ with self.assertRaisesRegex(RuntimeError, "environment projection"):
+ validate_configuration_pin(
+ args,
+ {"configuration": configuration},
+ opposite_gemma_optimizations(),
+ comparison_axis=args.comparison_axis,
+ )
+
+ def test_baseline_iterations_mismatch_is_refused(self):
+ args = make_args()
+ configuration = baseline_configuration(args)
+ configuration["iterations"] += 1
+ with self.assertRaisesRegex(RuntimeError, "iterations"):
+ validate_configuration_pin(
+ args, {"configuration": configuration}, fixtures.GEMMA_OPTIMIZATIONS
+ )
+
+ def test_baseline_decode_iterations_mismatch_is_refused(self):
+ args = make_args()
+ configuration = baseline_configuration(args)
+ configuration["decodeIterations"] += 1
+ with self.assertRaisesRegex(RuntimeError, "decodeIterations"):
+ validate_configuration_pin(
+ args, {"configuration": configuration}, fixtures.GEMMA_OPTIMIZATIONS
+ )
+
def test_gemma_axis_requires_identical_binary_and_metallib(self):
baseline = {
"metadata": {"binarySha256": "binary-a", "metallibSha256": "metal"}
From 75dab283bdb1e4da4d4b484ffcb82450fc4a7c7c Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 13:13:11 -0700
Subject: [PATCH 14/23] docs(provider): align preflight and KV citations
---
docs/provider/cli-reference.md | 6 +++--
docs/provider/hardware-requirements.md | 4 +--
docs/provider/installation.md | 2 +-
docs/provider/quickstart.md | 14 +++++-----
docs/provider/troubleshooting.md | 6 +++--
.../EngineV2KVBackendGateTests.swift | 27 +++++++++----------
6 files changed, 31 insertions(+), 28 deletions(-)
diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md
index e3c8a25acf..cfc2cf342b 100644
--- a/docs/provider/cli-reference.md
+++ b/docs/provider/cli-reference.md
@@ -37,8 +37,10 @@ darkbloom start [flags]
| `--bind ` | Bind address for local modes (default 127.0.0.1) |
| `--no-auth` | Disable local API-key auth (trusted/airgapped only) |
-Preflight checks (SIP, debugger, GPU, memory) run before the model picker
-(`provider-swift/Sources/darkbloom/StartCommand.swift:429-448`).
+Preflight checks for boot security, debugger attachment, and memory run before
+the model picker (`provider-swift/Sources/darkbloom/StartCommand+Preflight.swift:9-27`);
+the Metal requirement is enforced by `Start.prepareServeRuntime`
+(`provider-swift/Sources/darkbloom/StartCommand.swift:128-147`).
Examples:
diff --git a/docs/provider/hardware-requirements.md b/docs/provider/hardware-requirements.md
index 8df3afe33f..f17a2b45af 100644
--- a/docs/provider/hardware-requirements.md
+++ b/docs/provider/hardware-requirements.md
@@ -9,8 +9,8 @@ the models you want to serve.
| Component | Minimum | Notes |
|-----------|---------|-------|
| **CPU** | Apple M1 (or later) | Apple Silicon required; Intel Macs are not supported |
-| **RAM** | 8 GB | Start path rejects `< 8 GB` (`provider-swift/Sources/darkbloom/StartCommand.swift:444-447`) |
-| **GPU** | Apple Silicon integrated GPU | CPU-only execution is rejected (`provider-swift/Sources/darkbloom/StartCommand.swift:80-85`) |
+| **RAM** | 8 GB | Start path rejects `< 8 GB` (`provider-swift/Sources/darkbloom/StartCommand+Preflight.swift:23-27`) |
+| **GPU** | Apple Silicon integrated GPU | CPU-only execution is rejected (`provider-swift/Sources/darkbloom/StartCommand.swift:128-147`) |
| **Storage** | 50 GB free | SSD required; model weights are large |
| **macOS** | 14 (Sonoma) | Newer is better; install script enforces Darwin + arm64 |
| **Network** | Outbound HTTPS to coordinator | No inbound port is required |
diff --git a/docs/provider/installation.md b/docs/provider/installation.md
index 0209e9c2ff..c9e6ec7087 100644
--- a/docs/provider/installation.md
+++ b/docs/provider/installation.md
@@ -109,7 +109,7 @@ and missing-key decode are canonical in
with the missing-section fallback in
`provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift:397-400`.
Startup applies that config before Metal initialization
-(`provider-swift/Sources/darkbloom/StartCommand.swift:82-88` and
+(`provider-swift/Sources/darkbloom/StartCommand.swift:84-91` and
`provider-swift/Sources/darkbloom/ServeRuntimePreparer.swift:24-35`), and the
beta command's locked read-modify-write plus restart instruction is implemented
at `provider-swift/Sources/darkbloom/BetaCommand.swift:201-235`.
diff --git a/docs/provider/quickstart.md b/docs/provider/quickstart.md
index 373a7aeeb4..15cf40ef03 100644
--- a/docs/provider/quickstart.md
+++ b/docs/provider/quickstart.md
@@ -15,10 +15,10 @@ serving the public fleet, or use the same node for your own free inference via
| **Network** | Outbound HTTPS (port 443) | Low-latency path to `api.darkbloom.dev` |
The installer enforces macOS + Apple Silicon up front
-(`scripts/install.sh:41-48`). The start path rejects CPU-only execution via
-`GPUEnforcement.requireMetal()` (`provider-swift/Sources/darkbloom/StartCommand.swift:80-85`)
-and rejects machines with less than 8 GB RAM
-(`provider-swift/Sources/darkbloom/StartCommand.swift:444-447`).
+(`scripts/install.sh:41-48`). The start path rejects CPU-only execution through
+`Start.prepareServeRuntime` (`provider-swift/Sources/darkbloom/StartCommand.swift:128-147`)
+and rejects machines with less than 8 GB RAM in `Start.runPreflightChecks`
+(`provider-swift/Sources/darkbloom/StartCommand+Preflight.swift:14-27`).
## Install
@@ -153,7 +153,7 @@ end = "08:00"
- Provider TOML is authoritative for both controls. Changes take effect at
process restart; after setting either key to `false`, run `darkbloom restart`
to activate the rollback. The start path projects config before Metal access
- (`provider-swift/Sources/darkbloom/StartCommand.swift:82-88` and
+ (`provider-swift/Sources/darkbloom/StartCommand.swift:84-91` and
`provider-swift/Sources/darkbloom/ServeRuntimePreparer.swift:24-35`), while
`darkbloom beta` durably locks, reloads, and saves the selected value before
printing the restart boundary
@@ -217,14 +217,14 @@ end = "08:00"
under an explicit `"paged"` the model REFUSES to load instead, with the
underlying reason attached:
`EngineV2KVBackendPolicy.degradesPagedFailure`
- (`selection != .paged`, `provider-swift/Sources/ProviderCore/Inference/EngineV2KVBackendPolicy.swift:183`)
+ (`selection != .paged`, `provider-swift/Sources/ProviderCore/Inference/EngineV2KVBackendPolicy.swift:229-233`)
returns `false` for — and only for — an explicit `.paged` selection, so a
paged fleet can never silently serve contiguous. That refusal surfaces as
a 503 and the coordinator reroutes: the engine-construction catch wraps it
as `InferenceError.modelLoadFailed`
(`provider-swift/Sources/ProviderCore/ProviderLoop+ModelLoading.swift:543-549`),
`loadErrorStatusCode` maps that case to 503
- (`same file:975-983`), and the coordinator counts a 503 as
+ (`same file:979-1007`), and the coordinator counts a 503 as
`capacityRejection` — no reputation strike — then cools the load-rejecting
pair so retries skip it (`coordinator/api/provider.go:2332`, cool-down at
`:2343-2351`).
diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md
index 047325f308..a5b7148308 100644
--- a/docs/provider/troubleshooting.md
+++ b/docs/provider/troubleshooting.md
@@ -34,8 +34,10 @@ is stale. Re-download from the coordinator and verify again.
### `darkbloom start` fails immediately
-Preflight checks are in
-`provider-swift/Sources/darkbloom/StartCommand.swift:429-448`.
+Boot-security, debugger, and memory preflight checks are in
+`provider-swift/Sources/darkbloom/StartCommand+Preflight.swift:9-27`; Metal
+enforcement is in `Start.prepareServeRuntime`
+(`provider-swift/Sources/darkbloom/StartCommand.swift:128-147`).
| Error | Fix |
|-------|-----|
diff --git a/provider-swift/Tests/ProviderCoreTests/EngineV2KVBackendGateTests.swift b/provider-swift/Tests/ProviderCoreTests/EngineV2KVBackendGateTests.swift
index 7d4e8c207e..5e37a05ad9 100644
--- a/provider-swift/Tests/ProviderCoreTests/EngineV2KVBackendGateTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/EngineV2KVBackendGateTests.swift
@@ -138,9 +138,9 @@ private let gateTestCapacity = 8 << 20 // 8 MiB pool — tiny but constructible
/// Hermetic default for every construction in this suite: point the
/// crash-loop guard store at a file that can never decode. Without it a
/// developer box whose REAL provider tripped the guard on the checked-out
-/// version would fail every `.auto`-resolves-paged assertion here — the
-/// same reason tests inject `environment:` instead of inheriting the
-/// shell's kill switch. A caller's explicit value wins.
+/// version would fail every explicit-paged assertion here — the same reason
+/// tests inject `environment:` instead of inheriting the shell's kill switch.
+/// A caller's explicit value wins.
private let hermeticGuardEnvironment = [KVBackendGuardStore.pathEnvKey: "/dev/null"]
private func gateEnvironment(_ overrides: [String: String] = [:]) -> [String: String] {
@@ -158,8 +158,9 @@ private func makeBuild(
model: model,
tokenizer: StubBridgeTokenizer(),
kvBytesCapacity: gateTestCapacity,
- // Deliberately 2, not the production 8: these gates assert BACKEND
- // SELECTION, and a small pool keeps construction cheap.
+ // Deliberately 2: these gates assert BACKEND SELECTION, and a small
+ // pool keeps construction cheap. Production defaults to B=4 while
+ // still supporting explicit overrides through B=8.
maxConcurrentRequests: 2,
prefixCache: nil,
kvBackend: kvBackend,
@@ -345,15 +346,13 @@ struct EngineV2KVBackendGateTests {
#expect(reason?.hasPrefix("physical_capacity:") == true)
}
- @Test("`.auto` still degrades when paged cannot be served")
- func autoDegradesOnPagedFailure() async throws {
- // Layer 5's degrade half, as a predicate. Since v0.8.0 `.auto`
- // RESOLVES PAGED, so the real construction path reaches this branch
- // on every paged-ineligible box in the fleet — it is the COMMON
- // path, not a hypothetical. The predicate stays pinned here; the
- // three construction tests below drive the same answer through the
- // real factory, one per failure stage (preflight, capacity
- // planning, pool construction).
+ @Test("non-explicit selections permit paged-failure degradation")
+ func nonExplicitSelectionsPermitPagedFailureDegradation() async throws {
+ // Layer 5's degrade half, pinned as a policy predicate. `.auto`
+ // resolves contiguous as of v0.8.1 and therefore does not currently
+ // enter a paged-failure branch. The predicate remains the fail-open
+ // contract if a future release selects paged automatically; an
+ // explicit `.paged` request must continue to refuse instead.
#expect(EngineV2KVBackendPolicy.degradesPagedFailure(selection: .auto))
#expect(EngineV2KVBackendPolicy.degradesPagedFailure(selection: .contiguous))
#expect(!EngineV2KVBackendPolicy.degradesPagedFailure(selection: .paged))
From 8b3671d5be6021270cbf66cd479444c1fc85589f Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 13:19:19 -0700
Subject: [PATCH 15/23] fix(bench): enforce fixed decode token budgets
---
.../Sources/ProviderBenchmark/ThroughputSweep.swift | 11 +++++++----
.../ProviderCoreTests/ThroughputSweepTests.swift | 5 +++++
2 files changed, 12 insertions(+), 4 deletions(-)
diff --git a/provider-swift/Sources/ProviderBenchmark/ThroughputSweep.swift b/provider-swift/Sources/ProviderBenchmark/ThroughputSweep.swift
index 4d324b57c2..ec4acf410c 100644
--- a/provider-swift/Sources/ProviderBenchmark/ThroughputSweep.swift
+++ b/provider-swift/Sources/ProviderBenchmark/ThroughputSweep.swift
@@ -31,6 +31,12 @@ public enum ThroughputSweep {
public static let defaultDecodePromptTokens = 64
public static let defaultDecodeIterations = 1
+ /// Throughput cells must generate the requested budget for every row.
+ /// Honoring model EOS would compare different token counts and lets one
+ /// early-stopping row corrupt a batch aggregate; arrival invariance uses
+ /// the same fixed-budget contract.
+ static let fixedBudgetStopTokens: Set = []
+
/// Snapshot of model facts read once, off-actor, inside `perform`.
private struct ModelFacts: Sendable {
let weightBytes: Int
@@ -428,7 +434,6 @@ public enum ThroughputSweep {
UInt64(Int.max)))
struct EngineParts: @unchecked Sendable {
let engine: any CBv2Engine
- let eosTokenIds: Set
/// The backend the factory resolved to, with any fallback reason.
let resolvedBackend: String
}
@@ -451,7 +456,6 @@ public enum ThroughputSweep {
kvBackend: kvBackend)
return EngineParts(
engine: build.engine,
- eosTokenIds: ctx.configuration.eosTokenIds,
resolvedBackend: build.resolvedKVBackendDescriptor)
}
} catch {
@@ -463,7 +467,6 @@ public enum ThroughputSweep {
return (0, .zero, nil, "\(error)", nil)
}
let engine = parts.engine
- let eosTokenIds = parts.eosTokenIds
let result = await withTaskGroup(of: RowMeasure.self) {
group -> (Int, Duration, String?) in
@@ -480,7 +483,7 @@ public enum ThroughputSweep {
promptTokens: prompt,
sampling: CBv2SamplingParams(temperature: 0.0),
maxTokens: decodeTokens + 1,
- stopTokens: eosTokenIds
+ stopTokens: Self.fixedBudgetStopTokens
))
} catch {
Self.log(" submit failed: \(error)")
diff --git a/provider-swift/Tests/ProviderCoreTests/ThroughputSweepTests.swift b/provider-swift/Tests/ProviderCoreTests/ThroughputSweepTests.swift
index 15ad86f073..634b4a786a 100644
--- a/provider-swift/Tests/ProviderCoreTests/ThroughputSweepTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/ThroughputSweepTests.swift
@@ -103,6 +103,11 @@ struct DecodeBandwidthModelTests {
@Suite("throughput sweep: row aggregation")
struct ThroughputSweepRowAggregationTests {
+ @Test("decode sweep ignores EOS to preserve a fixed token budget")
+ func fixedDecodeBudget() {
+ #expect(ThroughputSweep.fixedBudgetStopTokens.isEmpty)
+ }
+
@Test("clean rows aggregate tokens and the slowest row's elapsed")
func cleanRowsAggregate() {
let cell = ThroughputSweep.aggregateRows([
From 6aa321a719e3c3e35c28f85679d8706b4e67161f Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 13:34:37 -0700
Subject: [PATCH 16/23] chore(deps): pin CBv2-scoped weighted expert path
---
libs/mlx-swift-lm | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index 8ab2f9b4ca..29ff95bc84 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit 8ab2f9b4ca9efab2c8d2c1cf41a3350dde19346a
+Subproject commit 29ff95bc84f86d58ce28c3db2e50c02eaf0f727b
From 04a0b303084c6225c9a6b92f7a7b92ddd3cf4c98 Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 14:52:12 -0700
Subject: [PATCH 17/23] fix(ci): remove unused schema helper
---
coordinator/api/toolschema.go | 30 ------------------------------
1 file changed, 30 deletions(-)
diff --git a/coordinator/api/toolschema.go b/coordinator/api/toolschema.go
index 07aeff3a8c..8dc8441c5f 100644
--- a/coordinator/api/toolschema.go
+++ b/coordinator/api/toolschema.go
@@ -711,36 +711,6 @@ func assertionFamilyTypes(dict map[string]any) map[string]struct{} {
return families
}
-// typelessAssertionFamiliesAmbiguous reports whether a typeless node's
-// assertions cannot determine a single renderable type: either its assertion
-// keywords span more than one type family (e.g. `{"minimum":5,"minLength":2}`)
-// or its only assertion is `not` (e.g. `{"not":{"type":"string"}}`, which
-// accepts every non-string — no injected type can preserve that, and the
-// string default would make the schema unsatisfiable). Callers reject these
-// before normalization; nodes with structural, union, or finite-value
-// evidence are typed by those higher-priority rules instead.
-func typelessAssertionFamiliesAmbiguous(dict map[string]any) bool {
- for _, key := range []string{
- "properties", "patternProperties", "additionalProperties",
- "items", "prefixItems",
- } {
- if _, ok := dict[key]; ok {
- return false
- }
- }
- if _, ok := unionMemberType(dict); ok {
- return false
- }
- families := assertionFamilyTypes(dict)
- if len(families) > 1 {
- return true
- }
- if _, negated := dict["not"]; negated && len(families) == 0 {
- return true
- }
- return false
-}
-
// finiteValueTypes reports the JSON type names of a node's const/enum values:
// the set of concrete (non-null) member types plus whether null appears.
// ok is false when the node carries no const and no non-empty enum array.
From 3ee0a9129778f579172ce9b1e81f5d308713cbce Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 14:52:13 -0700
Subject: [PATCH 18/23] chore(deps): pin merged Gemma safety fixes
---
libs/mlx-swift | 2 +-
libs/mlx-swift-lm | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/libs/mlx-swift b/libs/mlx-swift
index 38eaa93a75..97b3c92162 160000
--- a/libs/mlx-swift
+++ b/libs/mlx-swift
@@ -1 +1 @@
-Subproject commit 38eaa93a75ae85257b1df27aa4a7537cbba65881
+Subproject commit 97b3c92162afab0ad7868ce364a40a2382c219a5
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index 29ff95bc84..1ddb070f74 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit 29ff95bc84f86d58ce28c3db2e50c02eaf0f727b
+Subproject commit 1ddb070f74dccd3ae1e8cdd7b69ff5b47bb716f7
From 716beda20056bd7def82a25d0f0dc5f82773c1e7 Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 14:52:13 -0700
Subject: [PATCH 19/23] fix(bench): default Gemma runs to contiguous KV
---
scripts/gemma_contbatch/config.py | 16 +++++++---------
scripts/gemma_contbatch/runner.py | 6 +++---
scripts/gemma_contbatch/tests/test_kv_backend.py | 8 ++++----
3 files changed, 14 insertions(+), 16 deletions(-)
diff --git a/scripts/gemma_contbatch/config.py b/scripts/gemma_contbatch/config.py
index e206487371..92d1489257 100644
--- a/scripts/gemma_contbatch/config.py
+++ b/scripts/gemma_contbatch/config.py
@@ -29,17 +29,15 @@
# The canonical posture this release is measured under. Both defaults are
# load-bearing:
#
-# paged — `auto` resolves CONTIGUOUS as of v0.8.1. Naming `paged` is
-# therefore the only way this wrapper can promise it measured
-# the paged arm; an explicit request refuses when paged cannot
-# be built, except that the fleet kill switch deliberately
-# degrades to contiguous and is caught by the posture checks.
+# contiguous — `auto` resolves contiguous as of v0.8.1, but naming the
+# backend keeps every phase's release posture explicit and
+# prevents a future default flip from changing the benchmark.
# 1,2,4,8 — the current production concurrency default is B=4 under the
-# contiguous `auto` posture, while B=8 remains supported and is
-# the explicit-paged measurement point. The list is sparse on
+# contiguous `auto` posture, while B=8 remains a supported
+# stress point. The list is sparse on
# purpose: a dense 1..8 ladder doubles wall time for cells no
# gate reads.
-DEFAULT_KV_BACKEND = "paged"
+DEFAULT_KV_BACKEND = "contiguous"
DEFAULT_BATCH_SIZES = [1, 2, 4, 8]
KV_BACKENDS = ("auto", "contiguous", "paged")
EXPECTED_ARRIVAL_PATTERNS = {
@@ -101,7 +99,7 @@ def parse_args() -> argparse.Namespace:
choices=KV_BACKENDS,
default=DEFAULT_KV_BACKEND,
help=(
- "KV backend the decode sweep is built with "
+ "KV backend every benchmark phase is built with "
f"(default {DEFAULT_KV_BACKEND}; 'auto' may silently resolve "
"either backend, so it cannot pin a measurement)"
),
diff --git a/scripts/gemma_contbatch/runner.py b/scripts/gemma_contbatch/runner.py
index 515e03f3c7..3a8991f96b 100644
--- a/scripts/gemma_contbatch/runner.py
+++ b/scripts/gemma_contbatch/runner.py
@@ -312,9 +312,9 @@ def main() -> int:
comparison_axis=args.comparison_axis,
metadata=metadata,
)
- # The pin this release turns on. A paged-versus-contiguous difference
- # would otherwise show up as a double-digit aggregate delta with no
- # trace of its cause anywhere in the report.
+ # Keep the release's contiguous posture fixed across comparisons. A
+ # paged-versus-contiguous difference would otherwise read as a code or
+ # Gemma-optimization delta with no trace of its cause in the summary.
validate_kv_backend_pin(baseline, kv_backend)
report["comparison"] = compare(summary, baseline)
diff --git a/scripts/gemma_contbatch/tests/test_kv_backend.py b/scripts/gemma_contbatch/tests/test_kv_backend.py
index 44709e0909..f93fbb2986 100644
--- a/scripts/gemma_contbatch/tests/test_kv_backend.py
+++ b/scripts/gemma_contbatch/tests/test_kv_backend.py
@@ -210,14 +210,14 @@ def test_a_deliberate_auto_run_forwards_auto_everywhere(self):
class DefaultPostureTests(unittest.TestCase):
- def test_defaults_are_paged_and_reach_eight(self):
+ def test_defaults_are_contiguous_and_reach_eight(self):
with mock.patch.object(sys, "argv", ["benchmark-gemma-contbatch.py"]):
args = parse_args()
- self.assertEqual(args.kv_backend, "paged")
+ self.assertEqual(args.kv_backend, "contiguous")
self.assertEqual(args.kv_backend, DEFAULT_KV_BACKEND)
self.assertEqual(args.batch_sizes, list(DEFAULT_BATCH_SIZES))
- # The claim this release makes (1.17x aggregate) lives at B=8; a curve
- # that stops earlier cannot observe it.
+ # B=8 remains a useful stress point even though stock serving caps at
+ # B=4 under the contiguous release posture.
self.assertEqual(max(args.batch_sizes), 8)
def test_auto_is_still_reachable_for_a_deliberate_run(self):
From 9e7199ef47f8375c27def31ee312ef6cf8f5f042 Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 15:04:20 -0700
Subject: [PATCH 20/23] fix(provider): reject all-mode Gemma CBv2
---
libs/mlx-swift-lm | 2 +-
.../Inference/EngineV2Factory+Production.swift | 12 ++++++------
.../FrozenReplayRealModelTests.swift | 2 +-
3 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index 1ddb070f74..3c3ce9ffe4 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit 1ddb070f74dccd3ae1e8cdd7b69ff5b47bb716f7
+Subproject commit 3c3ce9ffe4899a2818a4871f97a5158f3d9e3448
diff --git a/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Production.swift b/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Production.swift
index a9b6caad3b..1c1a835475 100644
--- a/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Production.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/EngineV2Factory+Production.swift
@@ -547,11 +547,11 @@ extension EngineV2Factory {
let layerKinds: [CBv2LayerKind]
let newCaches:
((Int, CBv2LayerKind) -> any CBv2AttendingLayerCache)
- -> [any CBv2AttendingLayerCache]
+ throws -> [any CBv2AttendingLayerCache]
switch model {
case let gemma as Gemma4TextModel:
layerKinds = gemma.cbv2LayerKinds
- newCaches = { make in gemma.newCacheV2(makeLayerCache: make) }
+ newCaches = { make in try gemma.newCacheV2(makeLayerCache: make) }
case let gptoss as GPTOSSModel:
layerKinds = gptoss.cbv2LayerKinds
newCaches = { make in gptoss.newCacheV2(makeLayerCache: make) }
@@ -764,10 +764,10 @@ extension EngineV2Factory {
let schedulerConfig = CBv2SchedulerConfig(
maxConcurrentRequests: max(1, maxConcurrentRequests))
- func contiguousPreparation() -> ProductionBackendPreparation {
+ func contiguousPreparation() throws -> ProductionBackendPreparation {
let backend = CBv2ContiguousKVBackend(
config: CBv2ContiguousBackendConfig(bytesCapacity: cappedCapacity))
- let caches = newCaches { index, kind in
+ let caches = try newCaches { index, kind in
CBv2LayerCache(layerIndex: index, kind: kind)
}
return ProductionBackendPreparation(
@@ -848,7 +848,7 @@ extension EngineV2Factory {
// exists, so no admitted page is ever unbacked.
slabCommitment: plan.commitment)
let pagedCaches = paged.makeLayerCaches()
- let caches = newCaches { index, _ in pagedCaches[index] }
+ let caches = try newCaches { index, _ in pagedCaches[index] }
return ProductionBackendPreparation(
model: model,
maxConcurrentRequests: maxConcurrentRequests,
@@ -881,7 +881,7 @@ extension EngineV2Factory {
}
}
}
- return contiguousPreparation()
+ return try contiguousPreparation()
}
/// Emergency rollback kill-switch for the monotonic deadline leases. Set
diff --git a/provider-swift/Tests/ProviderCoreTests/FrozenReplayRealModelTests.swift b/provider-swift/Tests/ProviderCoreTests/FrozenReplayRealModelTests.swift
index 9250529ee2..a39560ccbb 100644
--- a/provider-swift/Tests/ProviderCoreTests/FrozenReplayRealModelTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/FrozenReplayRealModelTests.swift
@@ -88,7 +88,7 @@ struct FrozenReplayRealModelTests {
CBv2LayerCache(layerIndex: index, kind: kind)
})
case let gemma as Gemma4TextModel:
- return CBv2LayerCacheBank(caches: gemma.newCacheV2 { index, kind in
+ return CBv2LayerCacheBank(caches: try! gemma.newCacheV2 { index, kind in
CBv2LayerCache(layerIndex: index, kind: kind)
})
default:
From 4451701f06c7db520c17138bbd988e593e5537e1 Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 15:17:21 -0700
Subject: [PATCH 21/23] fix(provider): preserve update config read failures
---
libs/mlx-swift-lm | 2 +-
.../Sources/darkbloom/UpdateCommand.swift | 31 ++++++++++++-------
.../RuntimeSnapshotConfigTests.swift | 14 +++++++++
3 files changed, 35 insertions(+), 12 deletions(-)
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index 3c3ce9ffe4..b677d81f43 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit 3c3ce9ffe4899a2818a4871f97a5158f3d9e3448
+Subproject commit b677d81f43b1829709712993ec186004a44db4c1
diff --git a/provider-swift/Sources/darkbloom/UpdateCommand.swift b/provider-swift/Sources/darkbloom/UpdateCommand.swift
index 5b46e891d0..4c568c2aab 100644
--- a/provider-swift/Sources/darkbloom/UpdateCommand.swift
+++ b/provider-swift/Sources/darkbloom/UpdateCommand.swift
@@ -1,6 +1,25 @@
import ArgumentParser
+import Foundation
import ProviderCore
+private func updateConfigReadFailureIsMissing(_ error: Error) -> Bool {
+ let nsError = error as NSError
+ return (nsError.domain == NSCocoaErrorDomain
+ && nsError.code == CocoaError.Code.fileNoSuchFile.rawValue)
+ || (nsError.domain == NSPOSIXErrorDomain
+ && nsError.code == Int(POSIXErrorCode.ENOENT.rawValue))
+}
+
+func loadUpdateConfig(configPath: String?) throws -> ProviderConfig {
+ do {
+ return try loadRuntimeSnapshot(configPath: configPath).config
+ } catch ConfigError.readFailed(_, let underlying)
+ where updateConfigReadFailureIsMissing(underlying)
+ {
+ return ConfigManager.loadDefault()
+ }
+}
+
struct Update: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "update",
@@ -22,17 +41,7 @@ struct Update: AsyncParsableCommand {
var overrideQuarantine = false
mutating func run() async throws {
- let config: ProviderConfig
- do {
- let snapshot = try loadRuntimeSnapshot(configOptions: configOptions)
- config = snapshot.config
- } catch ConfigError.readFailed {
- // Missing/unreadable config files legitimately fall back to
- // defaults; a file that exists but doesn't parse must fail loudly
- // instead of silently resetting (and quietly aiming an update
- // check at the wrong coordinator).
- config = ConfigManager.loadDefault()
- }
+ let config = try loadUpdateConfig(configPath: configOptions.config)
print("darkbloom update")
print("Current version: \(ProviderCore.version)")
diff --git a/provider-swift/Tests/DarkbloomCLITests/RuntimeSnapshotConfigTests.swift b/provider-swift/Tests/DarkbloomCLITests/RuntimeSnapshotConfigTests.swift
index 348adbdafa..448a0234d4 100644
--- a/provider-swift/Tests/DarkbloomCLITests/RuntimeSnapshotConfigTests.swift
+++ b/provider-swift/Tests/DarkbloomCLITests/RuntimeSnapshotConfigTests.swift
@@ -79,4 +79,18 @@ struct RuntimeSnapshotConfigTests {
#expect(!snapshot.config.gemmaOptimizations.weightedR1)
#expect(try String(contentsOf: url, encoding: .utf8) == original)
}
+
+ @Test("update propagates existing-path read failures")
+ func updateRejectsUnreadableExistingPath() throws {
+ let url = tempConfigURL()
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false)
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ do {
+ _ = try loadUpdateConfig(configPath: url.path)
+ Issue.record("an existing path that cannot be read as TOML must not default")
+ } catch ConfigError.readFailed(let path, _) {
+ #expect(path == url.path)
+ }
+ }
}
From b56d09e07a400af5731c925abd85ee5024448c7c Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 15:32:15 -0700
Subject: [PATCH 22/23] chore(deps): pin final Gemma compatibility fixes
---
libs/mlx-swift-lm | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index b677d81f43..c5c5338461 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit b677d81f43b1829709712993ec186004a44db4c1
+Subproject commit c5c5338461320d46c660b4531066d38a0a8fb59e
From 1963230d8996c5345d3838028584f6bca8e3c57b Mon Sep 17 00:00:00 2001
From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Date: Mon, 10 Aug 2026 18:08:42 -0700
Subject: [PATCH 23/23] chore(deps): pin merged mlx-swift-lm main
---
libs/mlx-swift-lm | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm
index c5c5338461..ed55bee83b 160000
--- a/libs/mlx-swift-lm
+++ b/libs/mlx-swift-lm
@@ -1 +1 @@
-Subproject commit c5c5338461320d46c660b4531066d38a0a8fb59e
+Subproject commit ed55bee83beb0623152f4c2e70f0cf99ad379e35