Skip to content

perf(cbv2): capture GLM checkpoints beside decoding requests - #355

Closed
jonathan308 wants to merge 2 commits into
feat/glm5next-bf16-checkpointsfrom
perf/glm5next-capture-under-load
Closed

jonathan308 wants to merge 2 commits into
feat/glm5next-bf16-checkpointsfrom
perf/glm5next-capture-under-load

Conversation

@jonathan308

@jonathan308 jonathan308 commented Oct 24, 2026 •

Copy link
Copy Markdown

Summary

A GLM-5.3-Flash donor served beside a decoding request captured no complete checkpoint, and nothing counted the loss: one donor of six in the qualification's concurrent burst was cached. GLM captures under the chunk-agnostic recurrent rule (a checkpoint exists only at a prefill range end on the 256-token grid), and its prefill chunk shares one 2,048-token step budget with the decode rows of other requests, so with company every range is 2,044–2,047 tokens and no range end lands on the grid.

This adds an opt-in scheduler partition, CBv2SchedulerConfig.demandedCaptureBoundaryMinimumTokens: a request the store would write ends a range at its hinted fork target and at the deepest aligned boundary below its prompt end, whatever chunk its company left it. GLM adopters also stop holding a hit to the donor's chunk size, which made them wait and cold-restart after three waits under the same company.

It corrects the qualification's diagnosis (F4): GLM never went through the uniform complete-chunk rule (prepareHistoricalCheckpoints returns early for GLM); the shared step budget was the cause.

Stacking: one commit on #353's head after its refactor pass, 184b5a93 (git merge origin/feat/glm5next-bf16-checkpoints: already up to date); no file overlaps #353. The provider enables the partition for the GLM engine and store in Layr-Labs/d-inference#1589, whose libs/mlx-swift-lm pin is this head (2231b8fc).

Before

flowchart TB
    subgraph Before["Before: GLM beside a decoding request"]
        direction TB
        b1(["GLM donor, repeated prompt"]):::req --> b2["SchedulerV2: one 2,048-token step budget;<br/>decode rows take 1–4 tokens"]:::flow
        b2 --> b3["prefill ranges of 2,044–2,047 tokens"]:::flow
        b3 --> b4{"captureRecurrentCheckpoints:<br/>range end on the 256 grid?"}:::check
        b4 -- "never" --> b5["no checkpoint, no counter;<br/>next sighting prefills cold"]:::bad
        b6(["GLM hit"]):::req --> b7["adopter held to the donor's 2,048 chunk"]:::flow
        b7 --> b8["waits while decode rows shorten the budget;<br/>3 waits → preempted → cold prefill"]:::bad
    end
    classDef req fill:#dbeafe,stroke:#1d4ed8,color:#1e3a8a
    classDef flow fill:#f3f4f6,stroke:#4b5563,color:#111827
    classDef check fill:#fef3c7,stroke:#b45309,color:#78350f
    classDef bad fill:#fee2e2,stroke:#b91c1c,color:#7f1d1d
Loading

After

flowchart TB
    subgraph After["After: demandedCaptureBoundaryMinimumTokens set (provider: GLM engine + GLM store)"]
        direction TB
        a1(["GLM donor, repeated prompt"]):::req --> a2["SchedulerV2 proposes a range"]:::flow
        a2 --> a3{"demandedCaptureBoundaryRange:<br/>fork target or latest ahead?"}:::check
        a3 -- "inside the range" --> a4["end the range on the boundary"]:::good
        a3 -- "under 128 tokens past it" --> a5["end on the 128 query grid;<br/>the next range reaches the boundary"]:::good
        a3 -- "none, or a fleet-novel hint" --> a6["ordinary range"]:::flow
        a4 --> a7["aligned range end → capture"]:::good
        a8(["GLM hit"]):::req --> a9["adopter resumes under ordinary chunking;<br/>captures above its restore"]:::good
    end
    classDef req fill:#dbeafe,stroke:#1d4ed8,color:#1e3a8a
    classDef flow fill:#f3f4f6,stroke:#4b5563,color:#111827
    classDef check fill:#fef3c7,stroke:#b45309,color:#78350f
    classDef good fill:#dcfce7,stroke:#15803d,color:#14532d
Loading
CBv2SchedulerConfig.demandedCaptureBoundaryMinimumTokens   new opt-in (nil keeps today's geometry); the value is the store floor
demandedCheckpointRange → demandedCaptureBoundaryRange    target = floor256(hint), latest = floor256(prompt − 1); both ≥ floor
canScheduleDemandedShortCheckpoint                         also false for a shape-bound adopter (prefixReusePlan.recurrentChunkSize set)
EngineV2.completeCheckpointLookup (GLM)                    no recurrentChunkSize / recurrentPromptLength on the reuse plan

A hint below the floor marks a fleet-novel prompt the store will not write, so it keeps its geometry; no hint (legacy write-everything) cuts at the latest only. The scheduler and the first-token projection share the rule through demandedCheckpointRange.

Evidence

M5 Ultra #1, real GLM-5.3-Flash weights, provider dev builds from the stacked d-inference branch, loopback coordinator (isolated state; the signed install stayed stopped).

Measure Before After
Six distinct 8k donors sent together (after first sightings): captured 1/6 (qualification A/B), 2/6 (run 1) 6/6 in four runs (three experiment builds and the final heads)
Company donors' prefill ranges 2,044–2,047, no aligned end max 2,046/2,047, ends cut at 8,192
32,682-token donor publishes 2,048 + 30,720 2,048 + 32,512
Hit TTFT for that prompt (suffix 1,962 → 170 tokens) 3.96 s median 3.1–3.7 s
10,678-token hit (restores 8,192) beside two decoding requests forced 2,048 chunk: waits, cold restart after 3 hit, 3 ranges (max 2,046), 0 preemptions, captured its own 10,496

State equality, judged on the written checkpoints (per-tensor SHA-256 of all 96 tensors, plus per-layer diffs of plaintext dumps), not on text:

Comparison Result
Solo donor of one prompt: three runs, two scopes (@9,472) bit-identical
Solo donors @8,192 and @2,048 bit-identical
Donor beside decoding requests vs the solo reference rows [0, 2,044) of every DSA layer identical; first difference at row 2,044, the partial four-token KDA group at the end of the first 2,046-token range; KDA layers 0–3 identical, relative L2 7e-5 at layer 4 growing to ~0.1 by layer ~17; MTP state ~0.1–0.15
Two different company partitions differ from each other by the same order
First-token logprob, same prompt, cold, greedy Value
Ordinary 2,048 partition (no cut) −0.443859 (3 runs, identical)
Latest cut at 9,472 −0.350700 (4 runs, identical)
Beside decoding requests −0.458427

GLM's cold prefill depends on its partition (KDA's four-token groups, the attention history/current split, MoE routing amplifying both), exactly like the MoE Qwen in the 2026-09-27 chunk-partition parity report. Each partition is deterministic, and company already changes the partition today. A checkpoint is bit-exactly the state its own donor computed, and restore copies it exactly; the cut does not add a restore error. It does change the donor's own partition, one more of the partitions company already produces. Exact partition invariance is not reachable by alignment alone on GLM.

Tests

Scratch package: this branch + the provider's mlx-swift (M3 Ultra)
swift build -c release --build-tests -Xswiftc -enable-testing
swift test -c release --skip-build --no-parallel

XCTest: 82 executed, 0 failures, 12 suites
  CBv2DemandedCaptureBoundaryTests (new, 8): GLM geometry solo and beside a decoding neighbour; hint at, below and
    above the floor and nil; the 128-token pre-snap; adopters (shape-bound never cut); first-token projection
  CBv2CompleteCheckpointEngineTests (+1): a donor beside a decoding request captures nothing without the partition,
    its target and latest with it, and the latest restores to the donor's tokens
  unchanged: CBv2DemandedCheckpointContinuation/Partition, CBv2DemandedShortCheckpoint Capacity/Engine/Packed/
    Preemption/Range, CBv2FirstTokenDeadlineEngine, CBv2FirstTokenWorkProjection, CBv2FrozenReplayPlan

The provider PR runs the tiny synthetic GLM through the real protected factory with the partition on (GLM5NextProtectedFactoryTests, GLM5NextEncryptedCheckpointTests). swift-format lint is clean on the changed files.

Merge Danger

Door: two-way. demandedCaptureBoundaryMinimumTokens defaults to nil; only the provider's GLM engine sets it. Reverting restores today's geometry; checkpoint files and their format do not change.

Blast Radius: GLM scheduling and GLM adopters. canScheduleDemandedShortCheckpoint now also excludes shape-bound adopters for every model, but the existing short-checkpoint partition already requires !hasPrefixReuse, so its behavior is unchanged.

Limitations

  • Exact partition invariance is impossible for GLM (measured above). The accepted rationale is the MoE Qwen precedent: the capture equals the donor's own cold state.
  • GLM still admits one partial prefill at a time: a hit that arrives during another request's long cold prefill waits for it (measured TTFT 15.3 s behind a 32k prefill). Scheduler policy, not touched here.
  • Requests with logprobs and reasoning_effort: none were cut but never donated in these runs (no donation outcome). Probably their rows carry no MTP assistant state for the capture; not investigated here.

Refactor pass

Done, behavior-preserving: one signed commit, 723dbdaa. No library code changed. CBv2CheckpointHalfPrecision and the checkpoint paths that #354 uses are untouched.

Change Why
CBv2DemandedCaptureBoundaryTests moved from a top-level XCTest file to Tests/MLXLMTests/Unit/Scheduling/CBv2DemandedCaptureBoundaryTests.swift, as a Swift Testing suite in UnitTests. The eight cases and their assertions are the same CONTRIBUTING.md requires each new test to have one type. These tests run only SchedulerV2 bookkeeping and the pure first-token projection, so they are unit tests, like the other suites in Unit/Scheduling/. CI's no-GPU unit step now runs them
The doc comment of demandedCaptureBoundaryMinimumTokens now says that, when set, it replaces the short-checkpoint partition (demandedShortCheckpointMinimumTokens) for every request demandedCheckpointRange returns before the short-checkpoint path whenever the value is set, and the comment did not say so
The doc comment of demandedBoundaryAlignment now says what it returns It still held the inline comment it was extracted from ("Preserve both …")

Left as is, with reasons:

  • testDonorBesideADecodingRequestCapturesItsDemandedBoundaries stays in the XCTest suite CBv2CompleteCheckpointEngineTests. It reuses that suite's private engine, store and geometry-observer fixtures next to the related capture tests. Moving it to Integration/ would duplicate those fixtures.
  • demandedCaptureBoundaryRange, the GLM branch of completeCheckpointLookup and the shape-bound check in canScheduleDemandedShortCheckpoint are small, do one thing each, and their names say what they do.

This supersedes the 2231b8fc cited above: Layr-Labs/d-inference#1589 now pins 723dbdaa (0c3b31d85).

Validation on 723dbdaa (M3 Ultra, debug test build):

  • scripts/check-unit-test-files.sh passed. scripts/run-nested-suite.sh '\.UnitTests/', run with no Metal library in .build: 405 tests in 56 suites passed (397 in 55 at 184b5a93, plus the 8 moved cases), and 82 tests in 12 suites in the server target.
  • Checkpoint, demanded-partition and projection selection, with metallib 156f2624… (mlx-swift 67dc7528) staged. It covers half-precision, GLM complete checkpoint, paged storage/export/codec/adoption, native and asymmetric transfers, quantized, historical windows, Qwen 3.5/4, CBv2DemandedShortCheckpoint*, CBv2DemandedCheckpoint*, CBv2DemandedCaptureBoundaryTests, CBv2FirstTokenDeadline*, CBv2FirstTokenWorkProjection, CBv2FrozenReplayPlan, CBv2PrefixReusePlan, and CBv2CompleteCheckpointEngineTests with the new engine test:
    • XCTest: 154 executed, 18 skipped (the opt-in native lane), 0 failures.
    • Swift Testing: 88 tests in 16 suites passed.
    • DARKBLOOM_TEST_NATIVE_COMPLETE_PREFIX=1 CBv2NativeCompleteCheckpointTransferTests: 7 executed, 1 skipped, 0 failures.
  • swift format on every Swift file this PR changes: no changes. scripts/check_forkdiff.py: 1895 of 1895 files described.
  • No real-model run, because no runtime code changed. The GLM and SSD suites of d-inference#1589 pass with this head pinned.

GLM captures complete checkpoints under the chunk-agnostic recurrent
rule: a boundary is a prefill range end on the 256-token grid. Its
prefill chunk and its decode rows share one 2,048-token step budget, so
beside any decoding request every chunk is 2,048 minus the decode tokens
and no range end lands on the grid: a donor served with company captured
nothing (one of six in the qualification burst), silently.

Add an opt-in scheduler partition,
`CBv2SchedulerConfig.demandedCaptureBoundaryMinimumTokens`: a donor with
write demand ends a range on its hinted fork target and on the deepest
aligned boundary below its prompt end, whatever company shortened the
chunk. A range that would stop less than one query block short of a
boundary ends on the query grid instead, so the range that reaches the
boundary keeps the ordinary prefill kernels. Fleet-novel prompts (a hint
below the floor) keep their geometry. The scheduler and the first-token
projection share the rule through `demandedCheckpointRange`.

GLM adopters resume under ordinary chunking. They were held to the
donor's chunk size like the native historical codecs, so a shortened
step budget made them wait and, after three waits, cold-restart the hit.
A shape-bound adopter is never cut.

Tests: CBv2DemandedCaptureBoundaryTests (GLM geometry, solo and with a
decoding neighbour, demand, adopters, projection) and an engine test in
which a donor beside a decoding request captures nothing without the
partition and its target and latest with it, and the latest restores to
the donor's tokens.
CBv2DemandedCaptureBoundaryTests runs only SchedulerV2 bookkeeping and
the pure first-token projection, so under CONTRIBUTING.md's test types it
is a unit test. It moves to Tests/MLXLMTests/Unit/Scheduling/ as a Swift
Testing suite in UnitTests, beside the other scheduler unit suites, and
CI's no-GPU unit step now runs it. The eight cases and their assertions
are unchanged.

Document that demandedCaptureBoundaryMinimumTokens, when set, replaces
the short-checkpoint partition, and what demandedBoundaryAlignment
returns. No behavior change.
jonathan308 added a commit to Layr-Labs/d-inference that referenced this pull request Oct 24, 2026
…-swift-lm#355

libs/mlx-swift-lm moves 2231b8fc -> 723dbdaa. The refactor pass moves
CBv2DemandedCaptureBoundaryTests into the SDK's unit tests and documents
the capture-boundary partition's precedence and grid; no library behavior
changes.
@jonathan308

Copy link
Copy Markdown
Author

Superseded by #356; consolidated per owner request

Gajesh2007 added a commit to Layr-Labs/d-inference that referenced this pull request Oct 25, 2026
…nRouter reasoning fields (#1592)

* fix(provider): serve OpenRouter's variable-frame-rate readiness video on GLM

OpenRouter's provider-readiness test input-video-base64 failed on
glm-5.3-flash with 400 invalid_media. The clip is a variable-frame-rate
QuickTime movie (211 frames in 10.833 s), and GLM5NextProcessor refused it
with unsupported("variable-frame-rate video"), which the scheduler maps to
multimodal_rejected and then invalid_media.

- Bump mlx-swift-lm to the GLM5Next decoder fix: frames are indexed in
  presentation order and timed by the track's average rate, as in the
  reference loader (Layr-Labs/mlx-swift-lm#340).
- Admit data:video/mov (OpenRouter's documented QuickTime label) and
  data:video/x-m4v on the shared media ingest. MemoryBackedVideoAsset
  still identifies MP4 or QuickTime from the bytes.
- Scheduler-level regression test with the real OpenRouter fixtures and a
  label-alias ingest test; docs and changelog fragment.

* fix(provider): admit inlined Nemotron Super videos above 8 MiB

The Super media binding refused any encoded body over 8 MiB as invalid
input, so OpenRouter's input-video-url readiness test (a 6.9 MB MP4 the
coordinator inlines into a 9.3 MB body) failed with invalid_media.

Raise NemotronSuperServingPolicy.maximumEncodedBodyBytes to 40 MiB, which
holds one part at the shared 25 MiB inline-media cap as base64 and any body
the provider's transports deliver, and make encodedHeaderQuote use it as
its single bound. A body above it now fails as media_too_large. The media
charge quotes and the default prefix bank follow the larger bound.

Add NemotronSuperOpenRouterVideoTests: both OpenRouter readiness clips
pass ingress, inspection, the pinned template's prompt, the media plan and
every frame's decode, and serve on the tiny installed fixture.

* fix(glm): serve OpenRouter's returned-reasoning tool turn on GLM-5.3-Flash

OpenRouter's reasoning-content-return readiness task carries tools and
returns the model's reasoning on an assistant tool-call turn. GLM refused
it with 400 invalid_request while MiMo and Nemotron Super serve it.

Every GLM-only refusal of a shape both passing families accept is removed:

- strict tool declarations: served without constrained decoding; every
  auto call is already validated against its declared schema before it is
  exposed (ToolConstraintValidation.validate).
- empty-string history arguments read as {} (vLLM, MiMo and Super parity).
- reasoning: null, null reasoning members and include_reasoning: null are
  unset; reasoning.summary/generate_summary levels are no-ops.
- top-level thinking as a Boolean or GLM's API object
  {"type":"enabled"|"disabled","clear_thinking":Bool}.

Reasoning returned as OpenRouter's `reasoning` string or `reasoning_details`
text entries now renders as the template's reasoning_content instead of an
empty thinking block. Contradictions, unknown reasoning members,
preserve_thinking, forced tool choices and hidden reasoning stay refused.

* refactor: share the Super video test owner with the OpenRouter clip tests

NemotronSuperOpenRouterVideoTests copied NemotronSuperVideoBindingTests' tiny-fixture video owner (same tower, budget, load lease, context and teardown checks) and its generation-event recorder. Reuse videoOwner(contextLength:), VideoOwner.close() and SuperVideoEvents instead, and drop the unused MLXLMCommon import.

Correct two test comments: the inlined link makes a body of more than 9 MB here (9.39 MB once JSONSerialization escapes slashes, not 9.3), and only invalid input, not every other binding refusal, still leaves as invalid_media.

* test: drop the stale 8 MiB body case from the Super HTTP bounds test

The 40 MiB encoded-body bound made the 8 MiB case pass ingress; it was refused only by the context bound the next case already covers. Over local HTTP the body bound is unreachable because the 32 MiB upload limit answers 413 first (tested above), and the binding's over-cap refusal is covered by oversizeBodyIsMediaTooLarge.

* refactor(provider): pin the GLM decodeFrames cleanup and name MiMo in the changelog

Required refactor pass; no behavior change.

- Bump libs/mlx-swift-lm 54227bab -> 6aef0a5d (Layr-Labs/mlx-swift-lm#340),
  which removes decodeFrames' frame-rate parameter left unused by the
  variable-frame-rate fix and updates two comments that still described
  constant-frame-rate-only decoding.
- The shared inline-video path also serves MiMo V2.6:
  MiMoV26EncodedMediaIngress calls MediaIngest.decodeVideo directly, so it
  admits the new video/mov and video/x-m4v labels too. Say so in the
  changelog fragment.

* fix(provider): drop the inline video label aliases

Owner decision. OpenRouter sends data:video/quicktime;base64, which every
model already admits: Nemotron Super passed OpenRouter's base64 readiness
test with OpenRouter's label, and the recorded request size fits that
28-character header exactly. The aliases also made the shared ingest accept
labels that Nemotron Super, in the provider and the coordinator, still
refuses.

- MediaIngest.decodeVideo again admits only data:video/mp4;base64 and
  data:video/quicktime;base64; MediaIngest.swift, MediaIngestTests.swift and
  the T-050 threat-model wording match master.
- The routing test keeps the real video/quicktime and video/mp4 readiness
  cases and drops the video/mov variant.
- Docs and the changelog fragment keep only the variable-frame-rate fix.
  The SDK pin and the GLM regression test are unchanged.

* test(glm): replay OpenRouter's captured strict tool requests through the GLM path

The platform conformance fixtures hold OpenRouter's real tool-test bodies
(orIncidentOmitted, orIncidentAuto): the Boston weather prompt with a
strict, closed-schema get_current_weather tool and reasoning disabled.
Replay both byte for byte (hash-checked), the same body with tool_choice
none, and a five-step tool conversation built from them, through the
coordinator and local decode paths, the tool-stream handler, the GLM
policy and the shipped template. On master's policy every case fails with
"strict tool decoding is not qualified" (invalid_request); with the fix
they render.

* refactor(glm): tidy the returned-reasoning tests and docs

Behavior-preserving refactor pass over the reasoning/strict commits. Correct the stale test name in docs/developer/test.md and say the captured requests are held byte for byte and hash-checked, cite RawControls.returnedReasoning precisely, list thinking: null in the changelog, name the conversation helper's merged assistant fields, drop an unused controls binding and a decode that remoteAndLocalInputs already performs.

* feat(glm): serve JSON mode and structured outputs on GLM-5.3-Flash

OpenRouter's response-format-json-object and structured-output tests got
400 invalid_request: GLM's prompt policy refused every JSON
response_format. GLM's native engine refuses sampler token constraints,
so the Flint-style grammar is not available; GLM now follows the
prompt-plus-withheld-validation contract Nemotron Super uses:

- The service's response_format instruction renders through the shipped
  template; json_schema compiles to the shared fail-closed subset
  (compileResponseSchema now also requires explicit types, the check
  Flint already ran after it).
- GLM JSON requests route reasoning through the native channel splitter,
  so reasoning streams while the answer is withheld until generation
  ends. The answer is extracted (fences and surrounding prose removed),
  decoded, checked (root object, or ToolConstraintValidation.satisfies)
  and exposed once; anything else is a content-free 422.
- Withheld output records its generation time on the usage signal, so
  the relay's pre-content deadline and TTFT anchor see the first
  generated token, as they already do for withheld Flint reasoning.
- JSON with tools, unsupported schemas and JSON with image or video input
  stay 400s. No constraint is installed, so these rows keep MTP.

* feat(glm): serve forced tool_choice on GLM-5.3-Flash by structured post-validation

OpenRouter's tool-choice-required and tool-choice-function tests got 400
from the coordinator ("inference-enforced tool_choice (required/named) is
not supported for model glm-5.3-flash"): no provider listed GLM under
tool-constraint protocol v1, and the provider itself refused forced
choice in GLM's prompt policy and in ToolChoiceEnforcementPolicy.

GLM's native engine refuses sampler constraints, so forced choice uses
the structured post-validation strategy Qwen 3.5/3.8 and Nemotron use:

- ToolChoicePromptPolicy's forcing instruction renders through the
  shipped template; a named choice offers only the selected function.
- Forced GLM rows split reasoning on the native typed channel (as JSON
  mode does) and the native GLM parser withholds the call until end of
  stream; ToolConstraintValidation must accept it (function, schema,
  cardinality) before it is exposed. Visible text or a missing,
  malformed, truncated or schema-invalid call is a 422
  tool_noncompliance with nothing exposed.
- The forced strategy requires the native GLM parser.
- Providers advertise the managed GLM identities (glm-5.3-flash and the
  local qualification download) under tool-constraint protocol v1, so
  the coordinator's existing capability gate routes these requests to
  them without a coordinator change.
- Image or video input with a forced choice is refused with 400 before
  any media work, as JSON mode is. No constraint is installed, so these
  rows keep MTP.

* test(glm5next): give the managed fixture its <think> tokens

GLM5NextManagedLoad now wraps the loaded tokenizer in
GLM5NextThinkingTokenizer, which requires <think> and </think>. The
synthetic managed fixture never gained them, so every opt-in
DARKBLOOM_TEST_GLM5_MANAGED_SYNTHETIC suite that loads it failed with
"tokenizer lacks the <think> tokens" before building an engine. CI does
not run these suites, so the drift went unnoticed.

ordinaryFactoryRunsTextHTTPImageAndProtectedEmbeddedMTP passes again on
an M3 Ultra (17 s).

* fix(provider): refuse logprobs on native engines as a typed 400

GLM-5.3-Flash and MiMo V2.6 serve from native-tracked CBv2 engines.
EngineV2.validateRequest refuses a topLogprobs row or a token constraint
on them with an SDK-internal error, which the bridge reported as
"engine_v2 submit failed": a 500 generation_failure. The coordinator
counts 500s as provider sickness, so two logprobs requests cooled every
GLM provider for five minutes and its requests without tools were shed
as 429 "no provider for model ... is available right now", the failure
OpenRouter's top-logprobs test recorded.

EngineV2Bridge.nativeOutputControlRefusal refuses those requests first,
before any service or KV reservation, as the new
MultiModelBatchSchedulerEngineError.unsupportedOutputControl:
400 invalid_request with reason client_error, which never strikes the
breaker. The non-throwing submit path carries the same marker in-band.

GLM5NextLogprobsTests submits logprobs to the protected native GLM
bridge built from the synthetic managed fixture: 500 generation_failure
before, typed 400 after, and the engine keeps serving.

* fix(memory): count reclaimable page cache as available memory

Load admission, KV budgets, cold-load capacity and the doctor/status
"usable now" figure all read SystemMemory.availableBytes, which counted
Mach free + inactive pages. Active file-backed pages counted as used, so
on an M5 Ultra whose page cache held the just-downloaded and re-hashed
GLM weights (vm_stat free 2.4 GB, active 55.7 GB, inactive 208.7 GB) the
provider reported 170.8 GB usable and refused GLM-5.3-Flash's 185.4 GB
cold load until `sudo purge`.

The default `reclaimable` policy now counts free pages plus the
file-backed page cache (external_page_count) and volatile purgeable
pages. Speculative read-ahead pages sit inside both free_count and
external_page_count and are counted once. Anonymous pages, active or
inactive, and compressor pages are never counted. `free-only` is
unchanged.

Tests reproduce host #1's counters (171.0 GiB usable before, refused;
211.5 GiB after, admitted) and keep anonymous and compressed pressure
refused.

* fix(memory): never report less available memory than free + inactive

The reclaimable policy now takes the larger of the former free +
inactive measure and the page-cache measure (free − speculative +
file-backed + purgeable). The page-cache measure alone gave less on a
shared Mac with much inactive anonymous memory: on an M3 Ultra running
other builds, doctor reported 77.6 GB usable where the former measure
gave 93.0 GB. Taking the maximum keeps that case unchanged while active
page cache still never blocks a load (host #1: 171.0 GiB -> 211.5 GiB).

The page-cache measure itself still counts no anonymous or compressed
memory; tests assert it separately, that the combined figure is exactly
the larger measure, and the busy shared-Mac sample.

* test(glm): show JSON mode and forced tool_choice pass the native output-control refusal

#1561 now refuses logprobs and token constraints on native-tracked
engines before submit (EngineV2Bridge.nativeOutputControlRefusal), and
GLM's protected engine is native-tracked. GLM JSON mode and forced
tool_choice are prompt-steered and validated after generation, so they
must reach that engine with neither.

The capability tests now record every submission the scheduler makes
and evaluate the production refusal on it as GLM's native-tracked
engine: each served JSON and forced request carries no token constraint
and no logprobs, so it is admitted. A logprobs row threaded the way the
coordinator handler threads it is refused, so the check is not vacuous.

* fix(provider): serve Nemotron Super JSON response formats with tools

OpenRouter tests every capability on our Super endpoint (tools, all
tool_choice modes, json_object, strict json_schema, reasoning on and off).
Replaying each test shape, derived from the captured OpenRouter tool request,
through the owner's relay path (inbound decode, native controls, response
format preparation, request plan, pinned template, output parser) admits all
of them except a JSON response format combined with tools: the request plan
refused that pair with 400 (unsupportedControl).

Serve it. The plan no longer refuses the pair, and the output validates the
format only for an answer: a turn that calls tools returns its calls, with
any text unchanged, and an answer without calls must be JSON for the format
(422 otherwise). A required or named tool_choice still needs its call.

NemotronSuperOpenRouterCapabilityTests replays all 20 shapes (10 tests,
reasoning enabled and disabled) and validates a compliant response for each,
streamed and complete; the captured request's SHA-256 is pinned to the
platform conformance fixture. The live HTTP test now serves both a call and a
JSON answer for a JSON format with tools, and refuses prose with 422.

* fix(glm): render returned reasoning in JSON-mode requests

GLM aligns the reasoning OpenRouter returns on earlier assistant turns
(`reasoning`, `reasoning_details`) with the decoded messages by index.
For a JSON response_format, MLXOpenAIService first inserts its
instruction turn after the leading system turns, so the counts differed
by one and the capture was dropped: those turns rendered an empty
thinking block in every JSON-mode multi-turn request.

The alignment now skips that inserted turn, at the position the service
inserts it (`OpenAIResponseFormatSupport.preparedRequest`). The
capability tests serve a JSON-mode conversation through the service,
with and without a leading system turn: returned `reasoning` and
`reasoning_details` render byte for byte like `reasoning_content`.

* feat(provider): serve logprobs on GLM-5.3-Flash

Pin mlx-swift-lm to baca4acf (#340 head plus "capture logprobs on
GLM5-Next native engines"): the GLM page-bank contract now qualifies
logprob capture, and EngineV2.acceptsLogprobRows reports it.

EngineV2Bridge.nativeOutputControlRefusal keeps the typed 400 for a
native engine that does not capture logprobs (MiMo) and for token
constraints on any native engine, and lets GLM logprob rows through to
the engine. On the coordinator relay the existing channel and SSE
splice return them as OpenAI logprobs.content entries.

A GLM logprob row samples through the ordinary sampler and never drafts.
GLM has no request-scoped target-only fallback, so steps that include
it decode target-only, as they do beside a GLM image row; output stays
exact and other rows speculate again once it finishes.

GLM5NextLogprobsTests now asserts served logprobs on the protected
native bridge built from the synthetic managed fixture: one entry per
generated token with the requested alternatives, descending, chosen
token first under greedy decoding, no drafts for the logprob row, and a
later plain request that still speculates.

* refactor(provider): fold the bridge's in-band refusal catches into one

The non-throwing submitTokenized wrapper re-yields two typed refusals as
their content-free in-band markers: tokenBudgetExhausted (capacity) and
unsupportedOutputControl (a native engine's refused logprobs row or token
constraint). Both had identical catch bodies; fold them into one
multi-pattern catch. Both throws already finalized their prefix-cache
lookup, and fromSchedulerMessage maps each marker back to the same typed
error, so the 400 invalid_request (client_error) and capacity outcomes are
unchanged.

* test(glm): align the capability tests with served GLM logprobs

The merged logprobs support (f02327abe) gave
EngineV2Bridge.nativeOutputControlRefusal a capturesLogprobs argument and
made GLM's native engine serve logprob rows. The capability tests still
called the three-argument form, so the provider test products did not
build, and their control asserted that GLM refuses a logprobs row.

The scripted engine now evaluates the check for a given capture
capability. Each served response keeps GLM's decision (captures logprobs)
in nativeRefusals, which every JSON and forced row still asserts is nil,
and adds the decision of a native engine that cannot capture logprobs
(MiMo). The control, now
nativeEngineEvidenceAdmitsGLMLogprobsButRefusesNonCapturingEngines,
asserts GLM admits the logprobs row and the non-capturing engine refuses
it with the output-control prefix, so the evidence stays non-vacuous.

* perf(glm): publish the load's own verification instead of re-reading 182 GB

A GLM-5.3-Flash coordinator start read all 182 GB five times: the
startup registration hash, a pre-load WeightHasher pass, the native
loader's SHA-256 of every core file, the tensor reads and a post-load
WeightHasher pass (M5 Ultra: 25 s per hash pass, about 150 s to warm).
Standalone starts did four of them (141 s to listen on the M5).

The managed load already SHA-256-verifies every manifest file against
the catalog-pinned manifest before serving: core files in the native
reader before any header is parsed or payload read, the rest in
verifyAuxiliaryContents before the tokenizer loads, with file identities
rechecked through construction. It now records that result
(GLM5NextManagedLoad.verifiedArtifactSHA256, the manifest aggregate,
which is the value WeightHasher reports for those files) and both
ProviderLoop and StandaloneServer publish it instead of bracketing the
load with two more full passes. Integrity before serving is unchanged;
the dropped post-load pass only re-read disk, never the loaded bytes,
and any modification through the file system changes ctime, which the
load's identity checks refuse.

Coordinator-mode startup registration now reuses the last fully
verified hash of a managed-load model while every hashed file keeps its
device, inode, size and modification and status-change times
(VerifiedWeightHashStore, ~/.darkbloom/verified-weights.json, 0600).
The load verifies again before serving, so a stale or edited record can
misstate the registration claim but cannot serve unverified bytes. Any
changed file is hashed in full and re-recorded.

The load logs its phases (auxiliary verification, core verification,
tensors and construction). scripts/benchmarks/glm_load_timeline.py
turns a provider log into a timeline. The synthetic GLM fixtures gain
the <think>/</think> tokens the serving tokenizer has required since
#1516, so the gated managed and provider-loop suites run again.

* refactor(glm): name the withheld GLM output modes once

Refactor pass for GLM JSON mode, structured outputs and forced
tool_choice. Behavior is unchanged.

- GLM5NextPromptPolicy.withholdsOutput names the requests whose output
  GLM withholds until it validates: a JSON response_format or a
  required/named call. The scheduler's media refusal and its text-path
  channel split and withheld-output recording each spelled that set
  separately; both now read the one predicate, so they cannot drift.
- The JSON-mode returned-reasoning alignment names its index
  (instructionIndex) and says why it is the last leading system turn.
- docs/developer/test.md describes the capability tests' current
  control: GLM admits a logprobs row that the same output-control check
  refuses for a native engine without logprobs capture.

* perf(memory): drop cached weight pages after bulk hash and load reads

WeightHasher already reads every file through an aligned F_NOCACHE
descriptor, but F_NOCACHE only keeps a read from adding pages: pages
cached before the read stay resident and are read from the cache.
Downloads write every shard through the cache and then verify it twice
(per file, then the aggregate), so a GLM-5.3-Flash download left about
250 GB of page cache, some of it active, which the former
free + inactive admission figure counted as used.

PageCache.drop invalidates a file's resident pages with msync
MS_INVALIDATE over a read-only shared mapping (vmtouch's macOS
eviction; dirty pages are written back first, contents unchanged).
hashSingleFileUncached now drops the file's pages after reading it,
which covers startup registration hashes, download and prefetch
verification, the publish aggregate and revision checks. The managed GLM
load drops its shards' pages once loaded; its native reader also reads
around the cache.

On the M3 Ultra, with an 8.6 GB shard fully cached, the previous
build's `models list --hash` left all 8.6 GB resident and this build
leaves 0, with the same digest and time (3.9 s). PageCacheTests measure
residency with mincore before and after.

* refactor: tidy the Super JSON-format-with-tools output and tests

Behavior-preserving cleanup of the Nemotron Super JSON response format
with tools change:

- NemotronSuperLocalOutput.finish named the text a call turn passes through
  unchanged `answer`, which the comment above it says a call turn is not.
  Name it `text` and lay the conditional validation out on three lines.
- NemotronSuperOpenRouterCapabilityTests.check repeated compliantAnswer's
  "tool-call-step-5" name test; it now asserts the call when the shape was
  answered with the call, so the step-5 choice lives in one place.
- The live HTTP test declares its JSON-format-with-tools options once and
  reuses them for the 422 case.
- The shape corpus comment describes the shapes instead of what the owner
  used to refuse.

Same control flow, values and assertions.

* refactor(memory): share the live Mach sample and drop the dead saturating sum

- SystemMemory.vmStatistics() owns the HOST_VM_INFO64 sample. availableBytes()
  and livePageCountsKeepTheMachPartition read that one sampler instead of two
  copies of the unsafe-pointer code.
- Remove saturatingSum: each page measure adds at most three 32-bit Mach
  counters, which cannot overflow UInt64. The byte conversion still saturates
  (reclaimable) or fails closed to zero (free-only).
- Name free + inactive directly in comments and hardware-support.md instead of
  as the "former"/"before" measure. The freeForLoadGb parameter doc cites
  SystemMemory.availableBytes instead of restating only one of its measures.
- Rename the test helper flag hostOneSample(anonymousFileCache:) to
  asAnonymousMemory: the same pages held as process memory, not page cache.

Behavior is unchanged. No test was removed or weakened.

* refactor(glm): share the loaded-artifact check and tighten load-path comments

Behavior-preserving refactor pass over the GLM startup-read and
page-drop work.

- StandaloneServer requires the managed load's verified hash through
  ProviderLoop.requireGLM5NextLoadedArtifact, the rule ProviderLoop
  already applies, instead of a second inline copy. The comparison and
  the thrown identityMismatch are unchanged.
- GLM5NextManagedLoad.verifiedArtifactSHA256 says core files are
  verified before any header or payload is read, as the native reader
  does. The duration formatter is private.
- VerifiedWeightHashStore names both writers: a full startup
  registration hash and a managed load's manifest verification.
- verifiedGLM5NextWeightHash's comment no longer hardcodes 182 GB; the
  changelog fragment's word order is fixed.

* feat(provider): give the macOS GPU wired-limit fix for GLM-5.3-Flash

GLM's KV grant fills the 90% memory cap, so at full KV a 256 GB M5
Ultra plans about 247 GB of GPU memory. Under the macOS default
(iogpu.wired_limit_mb=0) the GPU may use only Metal's recommended
working set, about 222 GiB there, and command buffers past it fail with
"Insufficient Memory" (kIOGPUCommandBufferCallbackErrorOutOfMemory).
Capacity and admission stay as they are; the operator gets the exact
fix the production hosts run instead.

GLM5NextWiredLimit derives the recommendation from physical memory
(iogpu.wired_limit_mb = physical less 16 GiB = 245760, user wire
limits = 95% = 261134011596) and defines it only for 256 GB M5 Macs:
at 512 GB the same rule would put the user wire limits below the GPU
limit, which no host has run. It reads the three sysctls and Metal's
working set, builds the sysctl one-liner and the LaunchDaemon that
reapplies it at boot, and recognizes MLX's Metal out-of-memory text
without matching the provider's own "Insufficient memory" refusals.

- doctor adds `glm wired limit` when GLM is downloaded, selected or
  served on such a Mac: WARN with the planned GPU memory and the
  one-liner, plus an action block with the current values, the fix,
  `darkbloom restart` and the copy-paste LaunchDaemon install; PASS
  with the current values once set. It is not in buildDoctorChecks, so
  `verify` does not fail on it.
- start prints the same one-line fix as a warning when its selection
  would serve GLM below the values.
- status adds `→ fix:` under a GLM load error that reports the Metal
  out-of-memory error.
- A GLM load, startup preload, self-test or coordinator request that
  fails with that error logs the fix once per process to stderr
  (provider.log, or a foreground start's terminal) and a fixed public
  pointer to the unified log. Error text is only matched, never logged.
  StartupPreloader reports through a new injectable onFailure hook.

Failures that the native engine reports without the MLX text (its
readback faults surface only as nativeWorkFailed) cannot be matched;
doctor and start still flag the limit there.

* feat(provider): serve logprobs on Nemotron Super

Super refused logprobs and top_logprobs with 400: in
NemotronSuperRequestPlan.validateWireControls and in both bindings. It
now serves them on text, image and video requests, streamed and
complete, through the coordinator relay and the local endpoint.

- NemotronSuperRequestPlan.topLogprobs reads logprobs and top_logprobs
  from the raw body (EngineV2Translation.topLogprobs). The plan refuses
  top_logprobs outside 0...20.
- The owner's chat route (NemotronSuperLocalImageHTTP.engine,
  NemotronSuperSlotOwner.chatEngine) takes the caller's
  EngineV2LogprobsChannel. The text and image bindings pass it to
  EngineV2Bridge.submitTokenized and refuse a logprobs request without
  one.
- The coordinator relay passes the channel its frames loop already
  splices.
- LocalChatUploadResponder creates a channel for a local logprobs body
  sent to a raw-body owner: the qualification runner's hook or the
  managed local endpoint. It splices entries into content frames with
  ProviderLoop.injectLogprobs, and into a complete response's message
  without the token a stop finish ends on.

Pin mlx-swift-lm to 5cd9c81a (7bed8216 plus "keep MTP beside logprob
rows on request-scoped fallback targets"). A logprob row never drafts,
and on Super's fallback target the rows beside it keep speculating.

Tests:
- The plan admits logprobs and refuses top_logprobs 21 and -1.
- parseEncodedBody translates logprobs.
- The local hook serves streamed and complete logprobs on the tiny
  installed fixture.
- The managed slot serves them through the encrypted relay, with no
  drafted tokens, and through the unified local endpoint, streamed and
  complete.

* Add env-gated real-GLM logprobs qualification test

GLM5NextRealLogprobsQualificationTests loads the real checkpoint through
the production bundle and EngineV2Bridge relay channel and checks a
top_logprobs:5 greedy row against the MTP greedy tokens and a
teacher-forced log-softmax, a batched plain row's exact output and
renewed speculation, and the absence of native faults.

* WIP: check GLM logprobs along the served tokens, not MTP's

The M5 run of GLM5NextRealLogprobsQualificationTests failed because the
test assumed a logprob row reproduces the MTP greedy stream. A logprob
row never drafts, so it decodes one-token target steps; adaptive
rectangular verify windows round differently and the two streams parted
at step 3 (" History" vs " Roman", a near-tie: both within 0.1 nats in
the reference). The reference was then teacher-forced along the MTP
tokens, so every later step compared different contexts (252 failures,
15.75-nat "deltas"). Steps 0-3 matched within 0.05, so entries are
aligned with emitted tokens.

The test now takes the target path's token ids from the same logprob row
on the raw engine (the relay must reproduce its tokens, text and values
exactly), teacher-forces the reference along those ids, and accepts an
MTP or batched departure only at a reference near-tie. The co-batched
plain row uses another prompt and must emit the reference argmax up to a
near-tie. Per-step bounds are the larger of the tolerance and two bf16
spacings of the step's largest logit; 5e-2 alone is below one spacing
for logits of 8 or more.

Unverified: not compiled or run yet.

* test(provider): check Super logprobs against teacher forcing on the pinned checkpoint

Gated by DARKBLOOM_SUPER_MANAGED_LIVE=1 and NEMOTRON_SUPER_CHECKPOINT_DIR,
like the other managed-slot live cases.

Through the encrypted relay, a logprobs request drafts nothing, and the
same request without logprobs speculates to the same text. On the
engine, a greedy logprob row over the relay's rendered prompt carries
the relay's values. At every step the relay served, those values match
the last-position log-softmax of a cold prefill of the prompt and the
tokens before it: the same argmax at every step, worst deviation under
0.25 nats.

Pinned checkpoint on an M3 Ultra:
- 38 relay entries, relay vs engine 0.0
- teacher-forced median 0.0007 nats, worst 0.161 nats
- 0 argmax mismatches
- 0 drafted tokens for the logprob row, 13 rounds for the plain request

* chore(sdk): pin mlx-swift-lm to the merged #340 squash commit

Layr-Labs/mlx-swift-lm#340 was squash-merged to main as 6148b6da7eb8ed509ac56b74d7a69e8e73d8bf6c. Its tree is identical to the previously pinned PR head baca4acf8f7b4b91190de78a79e245f433875400, so only the gitlink changes: no SDK source differs.

* test(provider): judge Super's teacher-forced logprobs only up to the served end

pinnedCheckpointLogprobsMatchTeacherForcing now requires the relay to end at the end of turn inside its budget and stops the engine's greedy logprob row at the relay's last served position, so no step past the end of turn is scored. DARKBLOOM_SUPER_LIVE_MTP=off loads a plain owner for the numerics experiments; the speculation checks then require no MTP.

* test(provider): keep a GLM logprob row's entries beside a concurrent plain row

GLM5NextLogprobsTests/logprobRowKeepsItsEntriesBesideAConcurrentPlainRow serves a ten-step top-3 logprob row alone and then beside a twenty-step plain row on another prompt, on the protected synthetic bridge with two concurrent requests. The batched row carries one entry per token with the solo tokens, text, alternatives and values (within 1e-4); it never drafts; the plain row keeps its solo text and drafts again after the logprob row finishes.

* test(provider): bound a co-batched GLM logprob row's alternatives by batch-width numerics

On the real checkpoint (M3 Ultra) the solo logprob row matches the teacher-forced reference within 4e-6 nats, but beside a plain row its alternatives moved by up to 0.69 nats while its chosen values stayed within 0.048. Scoring the dense reference as two identical rows moves its top-8 by up to 0.56 nats from the one-row reference, so batch width alone produces that drift; every batched alternative stayed a reference top-8 token.

A co-batched row's alternatives are now bounded by DARKBLOOM_TEST_GLM5_REAL_LOGPROBS_BATCHED_TOLERANCE (default 1.0 nat); chosen values keep the per-step bf16-aware bound. The run records the paired-reference drift (pairedReferenceMaxDrift), the batched row's drift from its solo values and its comparison with the paired reference.

* docs: describe the GLM batched logprobs bound and the Super served-end check

* test(provider): expect GLM to serve required and named tool choice beside an image

ordinaryFactoryRunsTextHTTPImageAndProtectedEmbeddedMTP still expected a required tool_choice on GLM media input to throw. GLM now serves required and named tool choice: the forcing instruction leads the rendered prompt, the declared tool stays, and the call is withheld until it parses and matches its schema. Check that both choices normalize beside the image with the forcing system turn and the user's interleaved text and image parts.

* test(provider): serve GLM logprob and plain rows through one relay helper

GLM5NextLogprobsTests submitted and collected requests three ways: a plain helper, a logprobs helper and an inline loop in the relay test. One helper now serves both kinds of row and gives a logprobs request its relay channel. The assertions are unchanged.

* docs: describe the GLM concurrent logprob-row check

* feat(provider): return GLM and Super reasoning-token logprobs on the frames that carry them

Option B for the open thinking-only decision: vLLM-style logprobs. On
Nemotron Super (coordinator relay and local endpoint) and GLM-5.3-Flash
(relay), an entry now rides the reasoning or content frame that carries its
token, and a complete local response attaches entries to a message with
content or reasoning. logprobs.content therefore covers reasoning tokens,
and a response that ends while reasoning (max_tokens spent while thinking)
still returns one entry per token instead of none.

ProviderLoop.logprobsCoverReasoning selects GLM5-Next and the Super owner;
every other model keeps content-frame attachment. The coordinator already
concatenates logprobs from every chunk, so a non-streamed response with
content carries the same entries as before.

* provider(ssd-cache): queue up to six SSD prefix-cache writes

Both SSD prefix-cache write queues refused new donations as
write_queue_full at two jobs, so busy providers dropped prefixes they
could otherwise have reused. Raise SSDPrefixCachePolicy.writeQueueMaxJobs
from 2 to 6 and make the complete-checkpoint store use it instead of
literals: its writer gate admits six unsettled jobs, the one being
written included, and its pipeline buffer is as deep as that gate, so
the gate is the only queue refusal. Previously the one-job buffer could
refuse a job the gate had admitted after the writer settled one job and
before it took the next.

The memory bounds are unchanged. Attention-block jobs must still fit the
queued-byte cap (1,280 MiB at the default stage cap), and the job being
written still leaves both counts. A queued complete checkpoint holds only
donor state that stays charged to the engine admission ledger and I/O
scratch reserved before queueing. Because the engine delivers a donor's
terminal after its checkpoints settle, a write backlog now delays stream
end by up to five earlier writes per checkpoint instead of dropping it.

Tests: the attention cache queues six donations behind a blocked writer
and settles the seventh as write_queue_full; at the production limits the
queued-byte cap still refuses a job while a job slot is free; the fleet
demand test now fills the six-job bound; and queued complete writes keep
their host reservations, so the process ledger refuses before the job
bound. The SSD KV cache reference documents both queues, with a changelog
fragment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(provider): check GLM relay logprobs over reasoning through a shared scripted relay

ScriptedCoordinatorRelay drives one sealed request through the production
coordinator handler with a scripted engine; it is the Flint visibility
suite's relay harness, moved so other suites can use it, with a Progress
handle that lets a script wait for the chunks its deltas produced.

GLM5NextRelayLogprobsTests replays GLM-shaped tokens (the prompt ends inside
an open thought) through it: mixed and reasoning-only replies, requested
streamed and not, carry one entry per generated token in generation order,
reasoning tokens on the reasoning chunks and the marker and answer tokens on
the content chunks; no logprobs request carries none; another model type
keeps content-chunk attachment.

* test(provider): check Super logprobs over reasoning, including a thinking-only teacher-forced reply

Tiny fixtures: the Super relay serves a thinking-on mixed reply and a reply
that ends while reasoning with one entry per generated token on reasoning or
content chunks; the local endpoint does the same streamed and complete, and a
request without logprobs carries none.

pinnedCheckpointLogprobsMatchTeacherForcing now also runs with thinking on: a
48-token reply that ends inside reasoning must carry 48 entries on reasoning
chunks, equal the engine's, and match teacher forcing at every served
(reasoning) position. The real-GLM qualification records how many judged
positions are reasoning tokens and requires some.

* docs: state the vLLM-style logprobs contract for Super and GLM

logprobs.content has one entry per generated token in generation order,
reasoning tokens included: joined, the entry tokens spell the reasoning and
then the answer, not the answer alone. Reasoning chunks carry their tokens'
entries and a reply that ends while reasoning still returns them.

* provider(ssd-cache): pin the checkpoint writer buffer to the job gate

Refactor-pass follow-up to the six-job SSD write queue.

The complete-checkpoint pipeline buffer is as deep as the writer gate so
that a job the gate admits after the writer settles one job, but before
it dequeues the next, is buffered rather than dropped. No test held that
window open: the six-job fleet test still passes with a buffer one
shallower than the gate. Add one that blocks the first job's completion
callback, which runs after settle frees its writing entry, and checks
that the sixth admitted job is buffered and written.

Share the queued-donation helper that the six-job and host-ledger tests
each defined locally as SSDHybridCheckpointTestFixture.startDonation,
which the new test also uses. Name the gate and the window in the
pipeline comment, and note in the policy comment and the changelog that
a donor's stream end and KV release wait for all of its checkpoints, so
up to six waiting donors (was two) can hold KV memory at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(provider): judge real-GLM logprobs on reasoning tokens at the default effort

At low effort GLM-5.3-Flash closes the thought with its first token, so the
qualification judged answer tokens only (reasoningPositions 0 on the M3 Ultra).
The logprob prompt now uses the template-default effort, whose reply opens
with reasoning, and the run requires reasoning positions.

* feat(provider): route Nemotron Super prefix reuse through the coordinator

The managed Super owner's resident checkpoint bank now advertises a
protocol-v2 resident capability (prefix_cache_memory_models) bound to the
aggregate the provider published for the loaded checkpoint and the
checkpoint's PromptContractIdentity, the identity the prompt sidecar plans
with. Coordinator requests on the Super route submit under the request's
own usage signal, so lookup and ready receipts, prompt_tokens_details
cached_tokens and inference_complete cache usage now reach the coordinator
as on the generic engine, and the local endpoint reports the reused tokens.

Without a capability the coordinator never prepared a cache attempt for
Super, so no request carried a cache scope and the reserved bank served no
coordinator hit. A publication whose post-load artifact hash differs from
the advertised one closes the evidence; local reuse is unchanged.

* docs(provider): describe Nemotron Super prefix-cache routing evidence

Document the managed Super slot's resident capability, receipts and cached
token usage, the local endpoint's cached_tokens, and add the changelog
fragment.

* fix(glm): accept OpenRouter's reasoning.context and reasoning.mode on GLM-5.3-Flash

OpenRouter's reasoning-content-return readiness test now returns the
model's reasoning on a get_time tool call and asks for a secret word
chosen in that reasoning. A 123-variant matrix of that request family,
run through the coordinator-path handling (decodeInboundChatRequest,
validateNativeControls, the scheduler and the shipped template), shows
0.10.1 serves every reasoning carrier, reasoning_details field, strict
or empty-schema declaration, argument spelling and reasoning control the
test can send, and renders the returned reasoning. 0.10.0 refuses strict
tools, empty-string arguments and null reasoning members with 400
invalid_request, and drops returned reasoning.

The documented OpenRouter fields 0.10.1 still refused were the reasoning
object's context and mode members, rejected as unknown members:

- reasoning.context spells the template's clear_thinking: current_turn
  keeps only the reasoning returned after the last user turn (true),
  all_turns every turn's (false), and auto or null is unset. Other
  values, and a context that contradicts the effective clear_thinking,
  stay refused, never reconciled.
- reasoning.mode standard, OpenRouter's default, is a no-op. pro names a
  model variant GLM does not have and stays refused.

Tests: every golden renders byte for byte with its clear_thinking
replaced by the equivalent context; current_turn renders like
clear_thinking true with and without a later user turn; contradictions
are refused on the coordinator and local paths; the secret-word turn is
served through the scheduler with each reasoning carrier, the strict
declaration, empty-string arguments and the new controls. Each new test
fails on master's policy. Docs and a changelog fragment are updated.

* test(provider): accept Super teacher-forcing argmax swaps within twice the value bound

With thinking on, the 48 served reasoning tokens match teacher forcing within
0.293 nats, but at 3 steps the cold-prefill reference prefers another token
by at most 0.5 nats: decode-versus-prefill rounding, since one-token prefill
chunks make both cases bitwise equal (0 deviation, 0 swaps) on the pinned
checkpoint. The served value bound is 0.35 nats, and an argmax swap is
accepted only where the reference separates the two tokens by at most twice
that.

* refactor(glm): resolve clear_thinking and its reasoning.context in one place

The first version expressed the reasoning.context rule twice: validate()
refused a context that contradicts the raw clear_thinking, and
additionalContext() repeated the comparison against the typed controls'
value and then resolved explicit ?? context ?? false on its own.

RawControls.resolvedClearThinking(explicit:) now holds the whole rule:
the explicit Boolean, else the one reasoning.context spells, else false,
refusing a context that contradicts the explicit Boolean. validate() and
additionalContext() both call it, at the same points as before, so the
refusal order, message and rendered value are unchanged. The single-use
contradictoryReasoningContext constant is inlined.

Behavior-preserving: the GLM prompt-policy and OpenRouter capability
suites (42 tests, every golden render included) and the broader
GLM/prompt/request selection pass unchanged.

* refactor: tidy the option-B logprobs tests, comments and docs

Behavior-preserving refactor pass over the commits since e74c48250
(0425a8d8 through fc3dc260). No runtime change: the one Sources edit is a
comment.

- Super teacher forcing: the doc comment names the near-tie rule (each
  served value within `valueBound`, an argmax swap only where the
  reference prefers its argmax by at most twice that) and why
  decode-versus-prefill rounding explains it. The reference's value for
  the served token is now `referenceForServed`, so the gap no longer
  reads as `reference.logprob - referenceLogprob`.
- SuperSSE: drop a `delta` guard that the default empty delta made dead.
- GLM relay test: name the `</think>` token id (`thinkEnd`) instead of 3.
- Comments that still said entries attach to content frames only now
  name the reasoning case (`logprobsCoverReasoning`, `includingReasoning`).
- Changelog and direct-mode docs: the joined entry tokens include the
  `</think>` marker between reasoning and answer. test.md: the GLM relay
  test's mixed reply has no entry for its stop token.

* perf(glm): store GLM-5.3-Flash SSD checkpoints at BF16

Bump mlx-swift-lm to 39a12e1d (Layr-Labs/mlx-swift-lm#353): GLM complete
checkpoints write the latent keys, the index/gate/validity values row and
the KDA convolution history at their BF16 activation dtype and widen them
back to the identical FP32 bits on restore; the FP32 KDA recurrent state is
unchanged and any value BF16 cannot hold refuses the donation. The layout
becomes native-paged-glm5next-full-state-v2 (new namespace; v1 files expire
through the whole-root TTL sweep).

Measured on an M5 Ultra against the v0.10.1 build: checkpoints at
2,048 / 8,192 / 30,720 tokens shrink 18 / 33 / 42 %, bytes per token 48 %,
SSD bytes for an identical workload 30 %, and restore stage 25-29 %.
Document the v2 layout and sizes in the SSD reference and prefix-cache
architecture pages.

* perf(glm): validate GLM checkpoint validity flags by column

Bump mlx-swift-lm to 9abc8090 (Layr-Labs/mlx-swift-lm#353): the restore-time
validity check strides through the values row's validity column instead
of testing every element (one 30,720-token checkpoint: 51.3 ms -> 0.53 ms
on an M3 Ultra).

* feat(provider): keep Nemotron Super prefix reuse as durable SSD checkpoints

The managed Super slot's exact text prefix reuse is now complete encrypted
SSD checkpoints by default, as for the other cache-enabled models: the
builder prepares the paged backend, builds an SSDHybridCheckpointStore bound
to the published aggregate and the checkpoint's prompt contract, and
assembles the engine with it (native KV precision whatever the operator's
checkpoint quantization). The slot advertises prefix_cache_v2_models,
checkpoints survive restarts within the store TTL, and the coordinator's
repeat hint now reaches the Super route, so writes follow the same demand
gate and daily budget. The SDK bump adds the Super KV type declarations and
the assistant's durable history codec.

The resident bank is no longer reserved by default (its grant returns to
KV); DARKBLOOM_PREFIX_CACHE_MEMORY=1 selects it, and it remains the only
tier that reuses image turns. A load whose artifact hash changes during the
load is refused when it has a durable store.

* fix(provider): give a local Super complete response its stream's logprob entries

A local complete response attached every generated token's entry, including
the tool-call tokens that its stream and the relay drop when no text follows
the call (tiny fixture, thinking on: 9 entries complete, 1 streamed; with an
answer before the call, 11 and 4). The owner now also passes each chunk of a
complete response through a streaming split of the same request, and carries
the entries gathered so far only when that chunk shows reasoning or content,
as the stream's frames do (NemotronSuperCompleteLogprobs). The responder
attaches them as given, so its stop-token and message checks go.

Streams and the relay are unchanged. Text after a call still carries the
call's entries on every path, and Super's own call turns end with a newline
after </tool_call>; the docs and changelog say so.

* docs(glm): state the GLM checkpoint format once, in the SSD reference

Refactor pass. The SSD reference owns the GLM full-state v2 format; the
prefix-cache and inference explanations now name the identifiers and link
to it instead of restating its values (BF16, the payload ratio, the FP32
recurrent state). The reference cites the helper by its symbol and
tabulates the current v2 checkpoint sizes; the retired v1 comparison stays
in the changelog fragment and the PR evidence.

* refactor(glm): pin mlx-swift-lm at the refactor pass of Layr-Labs/mlx-swift-lm#353

Bumps libs/mlx-swift-lm 9abc8090 -> 184b5a93: the paged export walk is
shared by the native and narrowing branches, a wire dtype equal to the
page dtype is the native layout, the import sink drops its force unwraps,
and the half-precision tests are split into unit and kernel suites. The
checkpoint format and every GLM checkpoint byte are unchanged.

* docs: say Super's logprob entries cover tool-call tokens

Kept as decided: the relay, the local stream and the local complete
response carry the same entries, and Super's call turns end with a
newline after </tool_call>, whose chunk carries the call's entries. The
docs led with the exception ("a tool call's tokens carry entries only
when text follows the call"). They now state the contract first: one
entry per generated token in generation order, covering reasoning,
answer and tool-call tokens; tool-call tokens lack entries only in the
rare case that nothing follows the call.

The changelog fragment also covers GLM, whose template ends a call turn
with <|observation|> right after </tool_call>, so it calls that case
rare for Super only.

The refactor review of af5d701aa found no code to change.

* chore(provider): bump mlx-swift-lm to the formatted Super checkpoint codec

* perf(glm): capture GLM prefix checkpoints beside decoding requests

GLM-5.3-Flash captures a complete checkpoint only at a prefill range end
on the 256-token grid, and its prefill chunk shares one 2,048-token step
budget with the decode rows of other requests. Beside a decoding request
every range was 2,044-2,047 tokens, so a donor served with company
captured nothing, with no counter: one of six donors in the
qualification burst was cached.

Bump libs/mlx-swift-lm 184b5a93 -> 2231b8fc (Layr-Labs/mlx-swift-lm#355):
an opt-in scheduler partition ends a cacheable donor's range on its
demanded boundaries (fork target, deepest aligned boundary below the
prompt end), and GLM adopters resume under ordinary chunking instead of
waiting for a donor-sized chunk and cold-restarting after three waits.
The protected GLM engine with its GLM store enables the partition at the
store floor (EngineV2Factory.demandedCaptureBoundaryMinimumTokens).

With every donor capturing, donors that finish together overflowed the
store's single write slot: on an M5 Ultra two donors finishing in the
same millisecond lost both of one donor's files as write_queue_full. A
GLM store now holds eight donations behind its writer
(SSDPrefixCachePolicy.completeCheckpointWriteQueueJobs, set through
SSDHybridCheckpointStore.Config.writeQueueJobs); other layouts keep one.
A queued donation pins only its donor's pages and KDA copies, which stay
charged to the admission ledger until the write settles.

M5 Ultra #1, real weights: six concurrent 8k donors 6/6 captured and
written (was 1/6); a 32,682-token prompt publishes 32,512 instead of
30,720 (hit TTFT 3.1-3.7 s, was 3.96 s); a hit beside two decoding
requests restores with no preemption.

Tests: SSDCheckpointWriteQueueTests (depth by layout; four donations
queue behind a blocked writer and a fifth settles write_queue_full), the
partition stays GLM-only (Nemotron policy suite), and the GLM protected
factory asserts the partition floor and the queue depth.

* perf(glm): price measured restore time in complete-checkpoint ready receipts

A complete-checkpoint ready receipt priced a future restore as its file
bytes at the 1.5 GB/s planning rate. GLM-5.3-Flash restores take about
0.9 s more than that on an M5 Ultra, mostly the device's first work
after idling, so the receipt said 478 ms for a 716 MB checkpoint that
restored in 1.1-1.4 s and 125 ms for a 187 MB one that took 1.0-1.1 s.
The coordinator scores a holder with this value until a hit's measured
lookup replaces it, so it overstated the saving of short cached GLM
prompts.

SSDCheckpointStageCost adds to the byte price an exponentially weighted
average (newest weight 0.25) of how much longer this store's first-attempt
restores took than their byte price; a retried restore also paid for its
refused first attempt and is not recorded. The first restore replaces
the layout's prior: 935 ms for GLM5-Next, the median of the nine
qualification restores beyond their byte price; 0 for other layouts, so
their receipts are unchanged until they stage a file.

With this estimator (prior 900 ms in that build), 8,192-token GLM ready
receipts said 1,101 ms against 16 measured restores of 882-1,229 ms
(median 1,088 ms) on the M5 Ultra.

Tests: SSDCheckpointStageCostTests (layout priors and the exact GLM
estimate, replace-then-average updates, invalid samples, the protocol
ceiling, and a store's ready receipt after a first-attempt and a retried
restore on an injected stage clock).

* chore(provider): pin mlx-swift-lm at the refactor pass of Layr-Labs/mlx-swift-lm#354

44bdae77 -> 91bdc989: the Super adapter resolves its recurrent spec and its
complete-checkpoint KV types through one probe cache instead of two copies.
No behavior or checkpoint-format change.

* refactor(provider): tidy the Nemotron Super durable-checkpoint tests and docs

- NemotronSuperDurablePrefixCacheTests.ready polls through the evidence
  suite's `eventually` (the same 5 s bound) instead of a copy of it.
- The managed-slot durable test names the receipt boundary mode
  `boundaryMode` instead of shadowing its `mode: MTPMode` argument.
- The gated bank live test documents DARKBLOOM_PREFIX_CACHE_MEMORY=1 and
  checks it before loading: under the SSD default the slot keeps no bank,
  so without the switch the test could only fail after an 80 GB load.
- Rewraps the two docs paragraphs that the Phase A and B edits left with a
  stub line and over-long lines.

No runtime change.

* docs(glm): state the measured GLM write-queue overflow precisely

The two donors whose finishing lost both of one donor's files to the
single write slot finished within 27 ms of each other, not in the same
millisecond (M5 Ultra burst, harness wire log).

* docs(glm): cite the GLM capture partition's SDK sources by path

The GLM capture paragraph of prefix-cache.md named two SDK files by bare
file name, which docs-check cannot verify. Cite them by repository path
with their symbols (completeCheckpointLookup, demandedCaptureBoundaryRange),
as the neighbouring paragraphs and docs rule 4 do. No content change.

* refactor(glm): pin mlx-swift-lm at the refactor pass of Layr-Labs/mlx-swift-lm#355

libs/mlx-swift-lm moves 2231b8fc -> 723dbdaa. The refactor pass moves
CBv2DemandedCaptureBoundaryTests into the SDK's unit tests and documents
the capture-boundary partition's precedence and grid; no library behavior
changes.

* test(docs): keep Git auto-maintenance out of the historical-link fixtures

Docs Lint failed on #1592 in scripts/test-docs-check-historical-links.py,
before docs-check ran: test_a_frozen_directory_prefix_does_not_hide_a_
current_document passed its assertions, then its TemporaryDirectory
cleanup raised OSError [Errno 39] "Directory not empty: '.git'". The
fixture's commits let Git (2.55 on the runner) start detached
auto-maintenance, which can still be writing into the fixture's .git
while cleanup removes it. No docs or links were involved; the job's
docs-check step never ran.

The fixtures' Git environment now sets maintenance.auto=false and
gc.auto=0 (GIT_CONFIG_COUNT), so no background Git process outlives a
test. The checker under test is unchanged.

* fix(glm): serve OpenRouter hidden reasoning and Anthropic thinking controls

GLM-5.3-Flash refused several documented request controls with a typed 400
invalid_request, before acceptance and without a public log line, and the
coordinator counted each refusal as a failed job for the receiving provider:

- OpenRouter's hidden reasoning (reasoning.exclude: true,
  include_reasoning: false). The refusal's stated reason, that the provider
  had no seam to withhold reasoning it generates, no longer held: Flint
  already withholds reasoning through NativeToolStreamRouter.
- Anthropic's thinking object, which the coordinator's Messages lowering
  forwards unchanged (budget_tokens, type adaptive, display).
- A null reasoning_effort, which OpenAI documents as nullable.

GLM now serves them. The prompt is unchanged. When reasoning is withheld,
GLM's reasoning takes the native typed channel on text and media (as its JSON
and forced-call modes already do), the router withholds it, it still counts as
reasoning tokens and ends the pre-content interval, and
WithheldReasoningLogprobsFilter (renamed from FlintReasoningLogprobsFilter,
now shared) starts inside the prompt's open <think>, so no withheld entry
returns as logprobs. thinking.budget_tokens selects the effort as
reasoning.max_tokens does; adaptive enables thinking; display omitted hides
the reasoning. The unused reasoningExclusionUnsupported error and its local
HTTP message are removed.

Tests (fail on fb052c1e5, pass here):
- GLM5NextReasoningVisibilityTests: sealed requests through the production
  coordinator handler: withheld reasoning counted and excluded from the
  response hash, logprobs omit it, thinking-off with exclusion keeps the
  answer.
- GLM5NextMediaRoutingTests.hiddenReasoningWithMediaIsWithheldButCounted.
- GLM5NextPromptPolicyTests: exclusion renders the prompt byte-identical to
  the same request without it on both paths; Anthropic thinking and null
  reasoning_effort render like their unified spellings; the fail-closed list
  keeps invalid budgets, display values and thinking types.

* docs(provider): Super speculates for sampled requests and beside rows it cannot draft for

inference.md and a changelog fragment for the SDK change: sampled Super requests speculate through exact target-prefix acceptance, and a stop-string, penalty or logit-bias request decodes one ordinary token per step beside requests that speculate instead of turning speculation off for the step.

* fix(provider): never refuse a GLM load for the resident prefix-cache opt-in

DARKBLOOM_PREFIX_CACHE_MEMORY=1 builds a resident page-index config and a
recurrent-bank config for every slot. GLM's protected engine hosts neither,
and its backend preparation refuses both ("resident and hybrid prefixes are
unsupported"), so setting the flag fleet-wide refused every GLM load.

The slot factory now asks for resident tiers only from engines that host
them: a GLM slot logs that it ignores the opt-in and keeps its default
encrypted SSD checkpoints. Every other model still receives the opt-in
unchanged (Super's bank, attention models' resident L1), and the protected
backend's own refusal stays as a guard against a direct caller.

The real-construction test loads the tiny synthetic GLM with the flag set.
Before the fix it failed with the refusal above; it now binds the complete
store, builds no bank and serves an MTP request.

* fix(provider): replace an SSD cache KEK that no key can open again

The SSD prefix cache's key-encrypting key is stored in the Keychain sealed
(ECIES) to the provider's Secure Enclave identity. Two paths replace that
identity without touching the stored KEK: the attestation key's self-repair
(PersistentEnclaveKey.loadOrCreateVerified deletes and re-mints a key that
cannot sign) and `darkbloom unenroll` (LocalDataCleanup.purge deletes the
key). From then on every unwrap fails authentication, so every SSD store on
that Mac is refused as key_unavailable (cache_init_failed) on every load
until someone deletes the Keychain item by hand.

KVCacheKEK now treats an entry that fails authentication, is not a valid
ciphertext, or does not hold a 32-byte key as unusable and replaces it with
a fresh KEK sealed to the current identity. The files it protected were
already unreadable; each store's key-fingerprint binding wipes them when it
next starts. Backend failures (a locked keychain, an unavailable Secure
Enclave) are still reported and leave the entry untouched. Replacement runs
under one process-wide lock and re-reads the entry first, so concurrent
model loads converge on a single replacement.

* feat(provider): report why an SSD prefix cache did not start

80 of 1,568 loaded production slots report cache_init_failed, but the
heartbeat carries only that closed reason: the typed cause stayed in a
provider-local log line under com.darkbloom.provider, which `darkbloom logs`
does not read, and nothing in `status` or `doctor` showed it.

- The heartbeat's PrefixCacheModelStatus gains an optional `detail` with the
  typed cause behind an error state (SSDPrefixCacheConstructionFailure raw
  values, e.g. key_unavailable). It is omitted otherwise, so coordinators
  that predate it ignore it.
- Every store factory maps a refusal through one rule
  (PrefixCacheConstructionStatus(refusal:)): a refused complete-checkpoint
  store now reports unsafe_path as disk_unavailable, as attention-block
  stores already did, and a layout refusal as unsupported_layout. MiMo and
  the diffusion path now keep the typed cause instead of a bare nil.
- A closed store reports cache_closed and an attention-block store that
  lost its epoch reports epoch_unavailable, so slot teardown is no longer
  indistinguishable from a failed start.
- The daemon state file records each slot's prefix-cache state, reason and
  cause. `status` appends prefix_cache=… to every slot line with the cause
  and fix under a failed one; `doctor` (the desktop app's diagnostics) adds
  a prefix cache check. A load whose store failed logs a fixed public line
  for `darkbloom logs` and the model, cause and fix to provider.log.

* docs(provider): document prefix-cache failure causes, the KEK replacement and GLM's memory opt-in

- SSD KV cache reference: one refusal-to-status table for every store, the
  heartbeat `detail`, `cache_closed`, the status/doctor surfaces, that a
  refusal is never cached (each load retries), and that an unusable KEK is
  replaced.
- Protocol messages: PrefixCacheModelStatus's optional `detail` vocabulary.
- CLI reference: `prefix_cache=` on the slot posture lines and the doctor
  check.
- Encryption: a KEK sealed to a Secure Enclave key that no longer exists is
  replaced; a locked keychain leaves it untouched.
- Cache storage troubleshooting, prefix-cache architecture and inference
  architecture: the status rows and GLM ignoring the resident opt-in.
- Changelog fragment `prefix-cache-always-on`.

* feat(provider): log every refusal before the inference task with a fixed reason

A coordinator request refused before its inference task left no readable
log line, although coordinators count each refusal as a failed job: a
missing sender key or undecryptable body, unauthenticated tool-schema
metadata, a body that does not decode, unsupported audio, and native
controls the model refuses (the GLM, MiMo and Flint policies). The
console's Jobs card could not be matched in `darkbloom logs`.

Each refusal now writes one fixed public line naming a reason from the
closed InferenceRefusalReason set, for example
"Inference failure: invalid request (unsupported reasoning control)",
plus a private line with the request ID. The reason comes from the code
path that refused: the sealed request, the chat body's decode error (its
type and the request field its coding path starts at), the GLM capture
step that refused a tool declaration or control, or a contradiction. No
line carries request text. Logging only: every refusal decision and every
inference_error frame is unchanged.

- InferenceRefusalReason: the closed set and the decode classification.
- GLM5NextPromptPolicy.RawControls records its first refused step;
  refusalReason mirrors validate().
- ProviderPromptContractPipeline.nativeControlsRefusal names why
  validateNativeControls refuses; the handler uses it at both checks.
- InferenceFailureLogger.record(requestId:failure:refusal:) and the
  matching ProviderOperationalMessage cases.
- ProviderLoop takes a test …
Gajesh2007 added a commit to Layr-Labs/d-inference that referenced this pull request Oct 25, 2026
…laim memory (#1603)

* fix(provider): serve OpenRouter's variable-frame-rate readiness video on GLM

OpenRouter's provider-readiness test input-video-base64 failed on
glm-5.3-flash with 400 invalid_media. The clip is a variable-frame-rate
QuickTime movie (211 frames in 10.833 s), and GLM5NextProcessor refused it
with unsupported("variable-frame-rate video"), which the scheduler maps to
multimodal_rejected and then invalid_media.

- Bump mlx-swift-lm to the GLM5Next decoder fix: frames are indexed in
  presentation order and timed by the track's average rate, as in the
  reference loader (Layr-Labs/mlx-swift-lm#340).
- Admit data:video/mov (OpenRouter's documented QuickTime label) and
  data:video/x-m4v on the shared media ingest. MemoryBackedVideoAsset
  still identifies MP4 or QuickTime from the bytes.
- Scheduler-level regression test with the real OpenRouter fixtures and a
  label-alias ingest test; docs and changelog fragment.

* fix(provider): admit inlined Nemotron Super videos above 8 MiB

The Super media binding refused any encoded body over 8 MiB as invalid
input, so OpenRouter's input-video-url readiness test (a 6.9 MB MP4 the
coordinator inlines into a 9.3 MB body) failed with invalid_media.

Raise NemotronSuperServingPolicy.maximumEncodedBodyBytes to 40 MiB, which
holds one part at the shared 25 MiB inline-media cap as base64 and any body
the provider's transports deliver, and make encodedHeaderQuote use it as
its single bound. A body above it now fails as media_too_large. The media
charge quotes and the default prefix bank follow the larger bound.

Add NemotronSuperOpenRouterVideoTests: both OpenRouter readiness clips
pass ingress, inspection, the pinned template's prompt, the media plan and
every frame's decode, and serve on the tiny installed fixture.

* fix(glm): serve OpenRouter's returned-reasoning tool turn on GLM-5.3-Flash

OpenRouter's reasoning-content-return readiness task carries tools and
returns the model's reasoning on an assistant tool-call turn. GLM refused
it with 400 invalid_request while MiMo and Nemotron Super serve it.

Every GLM-only refusal of a shape both passing families accept is removed:

- strict tool declarations: served without constrained decoding; every
  auto call is already validated against its declared schema before it is
  exposed (ToolConstraintValidation.validate).
- empty-string history arguments read as {} (vLLM, MiMo and Super parity).
- reasoning: null, null reasoning members and include_reasoning: null are
  unset; reasoning.summary/generate_summary levels are no-ops.
- top-level thinking as a Boolean or GLM's API object
  {"type":"enabled"|"disabled","clear_thinking":Bool}.

Reasoning returned as OpenRouter's `reasoning` string or `reasoning_details`
text entries now renders as the template's reasoning_content instead of an
empty thinking block. Contradictions, unknown reasoning members,
preserve_thinking, forced tool choices and hidden reasoning stay refused.

* refactor: share the Super video test owner with the OpenRouter clip tests

NemotronSuperOpenRouterVideoTests copied NemotronSuperVideoBindingTests' tiny-fixture video owner (same tower, budget, load lease, context and teardown checks) and its generation-event recorder. Reuse videoOwner(contextLength:), VideoOwner.close() and SuperVideoEvents instead, and drop the unused MLXLMCommon import.

Correct two test comments: the inlined link makes a body of more than 9 MB here (9.39 MB once JSONSerialization escapes slashes, not 9.3), and only invalid input, not every other binding refusal, still leaves as invalid_media.

* test: drop the stale 8 MiB body case from the Super HTTP bounds test

The 40 MiB encoded-body bound made the 8 MiB case pass ingress; it was refused only by the context bound the next case already covers. Over local HTTP the body bound is unreachable because the 32 MiB upload limit answers 413 first (tested above), and the binding's over-cap refusal is covered by oversizeBodyIsMediaTooLarge.

* refactor(provider): pin the GLM decodeFrames cleanup and name MiMo in the changelog

Required refactor pass; no behavior change.

- Bump libs/mlx-swift-lm 54227bab -> 6aef0a5d (Layr-Labs/mlx-swift-lm#340),
  which removes decodeFrames' frame-rate parameter left unused by the
  variable-frame-rate fix and updates two comments that still described
  constant-frame-rate-only decoding.
- The shared inline-video path also serves MiMo V2.6:
  MiMoV26EncodedMediaIngress calls MediaIngest.decodeVideo directly, so it
  admits the new video/mov and video/x-m4v labels too. Say so in the
  changelog fragment.

* fix(provider): drop the inline video label aliases

Owner decision. OpenRouter sends data:video/quicktime;base64, which every
model already admits: Nemotron Super passed OpenRouter's base64 readiness
test with OpenRouter's label, and the recorded request size fits that
28-character header exactly. The aliases also made the shared ingest accept
labels that Nemotron Super, in the provider and the coordinator, still
refuses.

- MediaIngest.decodeVideo again admits only data:video/mp4;base64 and
  data:video/quicktime;base64; MediaIngest.swift, MediaIngestTests.swift and
  the T-050 threat-model wording match master.
- The routing test keeps the real video/quicktime and video/mp4 readiness
  cases and drops the video/mov variant.
- Docs and the changelog fragment keep only the variable-frame-rate fix.
  The SDK pin and the GLM regression test are unchanged.

* test(glm): replay OpenRouter's captured strict tool requests through the GLM path

The platform conformance fixtures hold OpenRouter's real tool-test bodies
(orIncidentOmitted, orIncidentAuto): the Boston weather prompt with a
strict, closed-schema get_current_weather tool and reasoning disabled.
Replay both byte for byte (hash-checked), the same body with tool_choice
none, and a five-step tool conversation built from them, through the
coordinator and local decode paths, the tool-stream handler, the GLM
policy and the shipped template. On master's policy every case fails with
"strict tool decoding is not qualified" (invalid_request); with the fix
they render.

* refactor(glm): tidy the returned-reasoning tests and docs

Behavior-preserving refactor pass over the reasoning/strict commits. Correct the stale test name in docs/developer/test.md and say the captured requests are held byte for byte and hash-checked, cite RawControls.returnedReasoning precisely, list thinking: null in the changelog, name the conversation helper's merged assistant fields, drop an unused controls binding and a decode that remoteAndLocalInputs already performs.

* feat(glm): serve JSON mode and structured outputs on GLM-5.3-Flash

OpenRouter's response-format-json-object and structured-output tests got
400 invalid_request: GLM's prompt policy refused every JSON
response_format. GLM's native engine refuses sampler token constraints,
so the Flint-style grammar is not available; GLM now follows the
prompt-plus-withheld-validation contract Nemotron Super uses:

- The service's response_format instruction renders through the shipped
  template; json_schema compiles to the shared fail-closed subset
  (compileResponseSchema now also requires explicit types, the check
  Flint already ran after it).
- GLM JSON requests route reasoning through the native channel splitter,
  so reasoning streams while the answer is withheld until generation
  ends. The answer is extracted (fences and surrounding prose removed),
  decoded, checked (root object, or ToolConstraintValidation.satisfies)
  and exposed once; anything else is a content-free 422.
- Withheld output records its generation time on the usage signal, so
  the relay's pre-content deadline and TTFT anchor see the first
  generated token, as they already do for withheld Flint reasoning.
- JSON with tools, unsupported schemas and JSON with image or video input
  stay 400s. No constraint is installed, so these rows keep MTP.

* feat(glm): serve forced tool_choice on GLM-5.3-Flash by structured post-validation

OpenRouter's tool-choice-required and tool-choice-function tests got 400
from the coordinator ("inference-enforced tool_choice (required/named) is
not supported for model glm-5.3-flash"): no provider listed GLM under
tool-constraint protocol v1, and the provider itself refused forced
choice in GLM's prompt policy and in ToolChoiceEnforcementPolicy.

GLM's native engine refuses sampler constraints, so forced choice uses
the structured post-validation strategy Qwen 3.5/3.8 and Nemotron use:

- ToolChoicePromptPolicy's forcing instruction renders through the
  shipped template; a named choice offers only the selected function.
- Forced GLM rows split reasoning on the native typed channel (as JSON
  mode does) and the native GLM parser withholds the call until end of
  stream; ToolConstraintValidation must accept it (function, schema,
  cardinality) before it is exposed. Visible text or a missing,
  malformed, truncated or schema-invalid call is a 422
  tool_noncompliance with nothing exposed.
- The forced strategy requires the native GLM parser.
- Providers advertise the managed GLM identities (glm-5.3-flash and the
  local qualification download) under tool-constraint protocol v1, so
  the coordinator's existing capability gate routes these requests to
  them without a coordinator change.
- Image or video input with a forced choice is refused with 400 before
  any media work, as JSON mode is. No constraint is installed, so these
  rows keep MTP.

* test(glm5next): give the managed fixture its <think> tokens

GLM5NextManagedLoad now wraps the loaded tokenizer in
GLM5NextThinkingTokenizer, which requires <think> and </think>. The
synthetic managed fixture never gained them, so every opt-in
DARKBLOOM_TEST_GLM5_MANAGED_SYNTHETIC suite that loads it failed with
"tokenizer lacks the <think> tokens" before building an engine. CI does
not run these suites, so the drift went unnoticed.

ordinaryFactoryRunsTextHTTPImageAndProtectedEmbeddedMTP passes again on
an M3 Ultra (17 s).

* fix(provider): refuse logprobs on native engines as a typed 400

GLM-5.3-Flash and MiMo V2.6 serve from native-tracked CBv2 engines.
EngineV2.validateRequest refuses a topLogprobs row or a token constraint
on them with an SDK-internal error, which the bridge reported as
"engine_v2 submit failed": a 500 generation_failure. The coordinator
counts 500s as provider sickness, so two logprobs requests cooled every
GLM provider for five minutes and its requests without tools were shed
as 429 "no provider for model ... is available right now", the failure
OpenRouter's top-logprobs test recorded.

EngineV2Bridge.nativeOutputControlRefusal refuses those requests first,
before any service or KV reservation, as the new
MultiModelBatchSchedulerEngineError.unsupportedOutputControl:
400 invalid_request with reason client_error, which never strikes the
breaker. The non-throwing submit path carries the same marker in-band.

GLM5NextLogprobsTests submits logprobs to the protected native GLM
bridge built from the synthetic managed fixture: 500 generation_failure
before, typed 400 after, and the engine keeps serving.

* fix(memory): count reclaimable page cache as available memory

Load admission, KV budgets, cold-load capacity and the doctor/status
"usable now" figure all read SystemMemory.availableBytes, which counted
Mach free + inactive pages. Active file-backed pages counted as used, so
on an M5 Ultra whose page cache held the just-downloaded and re-hashed
GLM weights (vm_stat free 2.4 GB, active 55.7 GB, inactive 208.7 GB) the
provider reported 170.8 GB usable and refused GLM-5.3-Flash's 185.4 GB
cold load until `sudo purge`.

The default `reclaimable` policy now counts free pages plus the
file-backed page cache (external_page_count) and volatile purgeable
pages. Speculative read-ahead pages sit inside both free_count and
external_page_count and are counted once. Anonymous pages, active or
inactive, and compressor pages are never counted. `free-only` is
unchanged.

Tests reproduce host #1's counters (171.0 GiB usable before, refused;
211.5 GiB after, admitted) and keep anonymous and compressed pressure
refused.

* fix(memory): never report less available memory than free + inactive

The reclaimable policy now takes the larger of the former free +
inactive measure and the page-cache measure (free − speculative +
file-backed + purgeable). The page-cache measure alone gave less on a
shared Mac with much inactive anonymous memory: on an M3 Ultra running
other builds, doctor reported 77.6 GB usable where the former measure
gave 93.0 GB. Taking the maximum keeps that case unchanged while active
page cache still never blocks a load (host #1: 171.0 GiB -> 211.5 GiB).

The page-cache measure itself still counts no anonymous or compressed
memory; tests assert it separately, that the combined figure is exactly
the larger measure, and the busy shared-Mac sample.

* test(glm): show JSON mode and forced tool_choice pass the native output-control refusal

#1561 now refuses logprobs and token constraints on native-tracked
engines before submit (EngineV2Bridge.nativeOutputControlRefusal), and
GLM's protected engine is native-tracked. GLM JSON mode and forced
tool_choice are prompt-steered and validated after generation, so they
must reach that engine with neither.

The capability tests now record every submission the scheduler makes
and evaluate the production refusal on it as GLM's native-tracked
engine: each served JSON and forced request carries no token constraint
and no logprobs, so it is admitted. A logprobs row threaded the way the
coordinator handler threads it is refused, so the check is not vacuous.

* fix(provider): serve Nemotron Super JSON response formats with tools

OpenRouter tests every capability on our Super endpoint (tools, all
tool_choice modes, json_object, strict json_schema, reasoning on and off).
Replaying each test shape, derived from the captured OpenRouter tool request,
through the owner's relay path (inbound decode, native controls, response
format preparation, request plan, pinned template, output parser) admits all
of them except a JSON response format combined with tools: the request plan
refused that pair with 400 (unsupportedControl).

Serve it. The plan no longer refuses the pair, and the output validates the
format only for an answer: a turn that calls tools returns its calls, with
any text unchanged, and an answer without calls must be JSON for the format
(422 otherwise). A required or named tool_choice still needs its call.

NemotronSuperOpenRouterCapabilityTests replays all 20 shapes (10 tests,
reasoning enabled and disabled) and validates a compliant response for each,
streamed and complete; the captured request's SHA-256 is pinned to the
platform conformance fixture. The live HTTP test now serves both a call and a
JSON answer for a JSON format with tools, and refuses prose with 422.

* fix(glm): render returned reasoning in JSON-mode requests

GLM aligns the reasoning OpenRouter returns on earlier assistant turns
(`reasoning`, `reasoning_details`) with the decoded messages by index.
For a JSON response_format, MLXOpenAIService first inserts its
instruction turn after the leading system turns, so the counts differed
by one and the capture was dropped: those turns rendered an empty
thinking block in every JSON-mode multi-turn request.

The alignment now skips that inserted turn, at the position the service
inserts it (`OpenAIResponseFormatSupport.preparedRequest`). The
capability tests serve a JSON-mode conversation through the service,
with and without a leading system turn: returned `reasoning` and
`reasoning_details` render byte for byte like `reasoning_content`.

* feat(provider): serve logprobs on GLM-5.3-Flash

Pin mlx-swift-lm to baca4acf (#340 head plus "capture logprobs on
GLM5-Next native engines"): the GLM page-bank contract now qualifies
logprob capture, and EngineV2.acceptsLogprobRows reports it.

EngineV2Bridge.nativeOutputControlRefusal keeps the typed 400 for a
native engine that does not capture logprobs (MiMo) and for token
constraints on any native engine, and lets GLM logprob rows through to
the engine. On the coordinator relay the existing channel and SSE
splice return them as OpenAI logprobs.content entries.

A GLM logprob row samples through the ordinary sampler and never drafts.
GLM has no request-scoped target-only fallback, so steps that include
it decode target-only, as they do beside a GLM image row; output stays
exact and other rows speculate again once it finishes.

GLM5NextLogprobsTests now asserts served logprobs on the protected
native bridge built from the synthetic managed fixture: one entry per
generated token with the requested alternatives, descending, chosen
token first under greedy decoding, no drafts for the logprob row, and a
later plain request that still speculates.

* refactor(provider): fold the bridge's in-band refusal catches into one

The non-throwing submitTokenized wrapper re-yields two typed refusals as
their content-free in-band markers: tokenBudgetExhausted (capacity) and
unsupportedOutputControl (a native engine's refused logprobs row or token
constraint). Both had identical catch bodies; fold them into one
multi-pattern catch. Both throws already finalized their prefix-cache
lookup, and fromSchedulerMessage maps each marker back to the same typed
error, so the 400 invalid_request (client_error) and capacity outcomes are
unchanged.

* test(glm): align the capability tests with served GLM logprobs

The merged logprobs support (f02327abe) gave
EngineV2Bridge.nativeOutputControlRefusal a capturesLogprobs argument and
made GLM's native engine serve logprob rows. The capability tests still
called the three-argument form, so the provider test products did not
build, and their control asserted that GLM refuses a logprobs row.

The scripted engine now evaluates the check for a given capture
capability. Each served response keeps GLM's decision (captures logprobs)
in nativeRefusals, which every JSON and forced row still asserts is nil,
and adds the decision of a native engine that cannot capture logprobs
(MiMo). The control, now
nativeEngineEvidenceAdmitsGLMLogprobsButRefusesNonCapturingEngines,
asserts GLM admits the logprobs row and the non-capturing engine refuses
it with the output-control prefix, so the evidence stays non-vacuous.

* perf(glm): publish the load's own verification instead of re-reading 182 GB

A GLM-5.3-Flash coordinator start read all 182 GB five times: the
startup registration hash, a pre-load WeightHasher pass, the native
loader's SHA-256 of every core file, the tensor reads and a post-load
WeightHasher pass (M5 Ultra: 25 s per hash pass, about 150 s to warm).
Standalone starts did four of them (141 s to listen on the M5).

The managed load already SHA-256-verifies every manifest file against
the catalog-pinned manifest before serving: core files in the native
reader before any header is parsed or payload read, the rest in
verifyAuxiliaryContents before the tokenizer loads, with file identities
rechecked through construction. It now records that result
(GLM5NextManagedLoad.verifiedArtifactSHA256, the manifest aggregate,
which is the value WeightHasher reports for those files) and both
ProviderLoop and StandaloneServer publish it instead of bracketing the
load with two more full passes. Integrity before serving is unchanged;
the dropped post-load pass only re-read disk, never the loaded bytes,
and any modification through the file system changes ctime, which the
load's identity checks refuse.

Coordinator-mode startup registration now reuses the last fully
verified hash of a managed-load model while every hashed file keeps its
device, inode, size and modification and status-change times
(VerifiedWeightHashStore, ~/.darkbloom/verified-weights.json, 0600).
The load verifies again before serving, so a stale or edited record can
misstate the registration claim but cannot serve unverified bytes. Any
changed file is hashed in full and re-recorded.

The load logs its phases (auxiliary verification, core verification,
tensors and construction). scripts/benchmarks/glm_load_timeline.py
turns a provider log into a timeline. The synthetic GLM fixtures gain
the <think>/</think> tokens the serving tokenizer has required since
#1516, so the gated managed and provider-loop suites run again.

* refactor(glm): name the withheld GLM output modes once

Refactor pass for GLM JSON mode, structured outputs and forced
tool_choice. Behavior is unchanged.

- GLM5NextPromptPolicy.withholdsOutput names the requests whose output
  GLM withholds until it validates: a JSON response_format or a
  required/named call. The scheduler's media refusal and its text-path
  channel split and withheld-output recording each spelled that set
  separately; both now read the one predicate, so they cannot drift.
- The JSON-mode returned-reasoning alignment names its index
  (instructionIndex) and says why it is the last leading system turn.
- docs/developer/test.md describes the capability tests' current
  control: GLM admits a logprobs row that the same output-control check
  refuses for a native engine without logprobs capture.

* perf(memory): drop cached weight pages after bulk hash and load reads

WeightHasher already reads every file through an aligned F_NOCACHE
descriptor, but F_NOCACHE only keeps a read from adding pages: pages
cached before the read stay resident and are read from the cache.
Downloads write every shard through the cache and then verify it twice
(per file, then the aggregate), so a GLM-5.3-Flash download left about
250 GB of page cache, some of it active, which the former
free + inactive admission figure counted as used.

PageCache.drop invalidates a file's resident pages with msync
MS_INVALIDATE over a read-only shared mapping (vmtouch's macOS
eviction; dirty pages are written back first, contents unchanged).
hashSingleFileUncached now drops the file's pages after reading it,
which covers startup registration hashes, download and prefetch
verification, the publish aggregate and revision checks. The managed GLM
load drops its shards' pages once loaded; its native reader also reads
around the cache.

On the M3 Ultra, with an 8.6 GB shard fully cached, the previous
build's `models list --hash` left all 8.6 GB resident and this build
leaves 0, with the same digest and time (3.9 s). PageCacheTests measure
residency with mincore before and after.

* refactor: tidy the Super JSON-format-with-tools output and tests

Behavior-preserving cleanup of the Nemotron Super JSON response format
with tools change:

- NemotronSuperLocalOutput.finish named the text a call turn passes through
  unchanged `answer`, which the comment above it says a call turn is not.
  Name it `text` and lay the conditional validation out on three lines.
- NemotronSuperOpenRouterCapabilityTests.check repeated compliantAnswer's
  "tool-call-step-5" name test; it now asserts the call when the shape was
  answered with the call, so the step-5 choice lives in one place.
- The live HTTP test declares its JSON-format-with-tools options once and
  reuses them for the 422 case.
- The shape corpus comment describes the shapes instead of what the owner
  used to refuse.

Same control flow, values and assertions.

* refactor(memory): share the live Mach sample and drop the dead saturating sum

- SystemMemory.vmStatistics() owns the HOST_VM_INFO64 sample. availableBytes()
  and livePageCountsKeepTheMachPartition read that one sampler instead of two
  copies of the unsafe-pointer code.
- Remove saturatingSum: each page measure adds at most three 32-bit Mach
  counters, which cannot overflow UInt64. The byte conversion still saturates
  (reclaimable) or fails closed to zero (free-only).
- Name free + inactive directly in comments and hardware-support.md instead of
  as the "former"/"before" measure. The freeForLoadGb parameter doc cites
  SystemMemory.availableBytes instead of restating only one of its measures.
- Rename the test helper flag hostOneSample(anonymousFileCache:) to
  asAnonymousMemory: the same pages held as process memory, not page cache.

Behavior is unchanged. No test was removed or weakened.

* refactor(glm): share the loaded-artifact check and tighten load-path comments

Behavior-preserving refactor pass over the GLM startup-read and
page-drop work.

- StandaloneServer requires the managed load's verified hash through
  ProviderLoop.requireGLM5NextLoadedArtifact, the rule ProviderLoop
  already applies, instead of a second inline copy. The comparison and
  the thrown identityMismatch are unchanged.
- GLM5NextManagedLoad.verifiedArtifactSHA256 says core files are
  verified before any header or payload is read, as the native reader
  does. The duration formatter is private.
- VerifiedWeightHashStore names both writers: a full startup
  registration hash and a managed load's manifest verification.
- verifiedGLM5NextWeightHash's comment no longer hardcodes 182 GB; the
  changelog fragment's word order is fixed.

* feat(provider): give the macOS GPU wired-limit fix for GLM-5.3-Flash

GLM's KV grant fills the 90% memory cap, so at full KV a 256 GB M5
Ultra plans about 247 GB of GPU memory. Under the macOS default
(iogpu.wired_limit_mb=0) the GPU may use only Metal's recommended
working set, about 222 GiB there, and command buffers past it fail with
"Insufficient Memory" (kIOGPUCommandBufferCallbackErrorOutOfMemory).
Capacity and admission stay as they are; the operator gets the exact
fix the production hosts run instead.

GLM5NextWiredLimit derives the recommendation from physical memory
(iogpu.wired_limit_mb = physical less 16 GiB = 245760, user wire
limits = 95% = 261134011596) and defines it only for 256 GB M5 Macs:
at 512 GB the same rule would put the user wire limits below the GPU
limit, which no host has run. It reads the three sysctls and Metal's
working set, builds the sysctl one-liner and the LaunchDaemon that
reapplies it at boot, and recognizes MLX's Metal out-of-memory text
without matching the provider's own "Insufficient memory" refusals.

- doctor adds `glm wired limit` when GLM is downloaded, selected or
  served on such a Mac: WARN with the planned GPU memory and the
  one-liner, plus an action block with the current values, the fix,
  `darkbloom restart` and the copy-paste LaunchDaemon install; PASS
  with the current values once set. It is not in buildDoctorChecks, so
  `verify` does not fail on it.
- start prints the same one-line fix as a warning when its selection
  would serve GLM below the values.
- status adds `→ fix:` under a GLM load error that reports the Metal
  out-of-memory error.
- A GLM load, startup preload, self-test or coordinator request that
  fails with that error logs the fix once per process to stderr
  (provider.log, or a foreground start's terminal) and a fixed public
  pointer to the unified log. Error text is only matched, never logged.
  StartupPreloader reports through a new injectable onFailure hook.

Failures that the native engine reports without the MLX text (its
readback faults surface only as nativeWorkFailed) cannot be matched;
doctor and start still flag the limit there.

* feat(provider): serve logprobs on Nemotron Super

Super refused logprobs and top_logprobs with 400: in
NemotronSuperRequestPlan.validateWireControls and in both bindings. It
now serves them on text, image and video requests, streamed and
complete, through the coordinator relay and the local endpoint.

- NemotronSuperRequestPlan.topLogprobs reads logprobs and top_logprobs
  from the raw body (EngineV2Translation.topLogprobs). The plan refuses
  top_logprobs outside 0...20.
- The owner's chat route (NemotronSuperLocalImageHTTP.engine,
  NemotronSuperSlotOwner.chatEngine) takes the caller's
  EngineV2LogprobsChannel. The text and image bindings pass it to
  EngineV2Bridge.submitTokenized and refuse a logprobs request without
  one.
- The coordinator relay passes the channel its frames loop already
  splices.
- LocalChatUploadResponder creates a channel for a local logprobs body
  sent to a raw-body owner: the qualification runner's hook or the
  managed local endpoint. It splices entries into content frames with
  ProviderLoop.injectLogprobs, and into a complete response's message
  without the token a stop finish ends on.

Pin mlx-swift-lm to 5cd9c81a (7bed8216 plus "keep MTP beside logprob
rows on request-scoped fallback targets"). A logprob row never drafts,
and on Super's fallback target the rows beside it keep speculating.

Tests:
- The plan admits logprobs and refuses top_logprobs 21 and -1.
- parseEncodedBody translates logprobs.
- The local hook serves streamed and complete logprobs on the tiny
  installed fixture.
- The managed slot serves them through the encrypted relay, with no
  drafted tokens, and through the unified local endpoint, streamed and
  complete.

* Add env-gated real-GLM logprobs qualification test

GLM5NextRealLogprobsQualificationTests loads the real checkpoint through
the production bundle and EngineV2Bridge relay channel and checks a
top_logprobs:5 greedy row against the MTP greedy tokens and a
teacher-forced log-softmax, a batched plain row's exact output and
renewed speculation, and the absence of native faults.

* WIP: check GLM logprobs along the served tokens, not MTP's

The M5 run of GLM5NextRealLogprobsQualificationTests failed because the
test assumed a logprob row reproduces the MTP greedy stream. A logprob
row never drafts, so it decodes one-token target steps; adaptive
rectangular verify windows round differently and the two streams parted
at step 3 (" History" vs " Roman", a near-tie: both within 0.1 nats in
the reference). The reference was then teacher-forced along the MTP
tokens, so every later step compared different contexts (252 failures,
15.75-nat "deltas"). Steps 0-3 matched within 0.05, so entries are
aligned with emitted tokens.

The test now takes the target path's token ids from the same logprob row
on the raw engine (the relay must reproduce its tokens, text and values
exactly), teacher-forces the reference along those ids, and accepts an
MTP or batched departure only at a reference near-tie. The co-batched
plain row uses another prompt and must emit the reference argmax up to a
near-tie. Per-step bounds are the larger of the tolerance and two bf16
spacings of the step's largest logit; 5e-2 alone is below one spacing
for logits of 8 or more.

Unverified: not compiled or run yet.

* test(provider): check Super logprobs against teacher forcing on the pinned checkpoint

Gated by DARKBLOOM_SUPER_MANAGED_LIVE=1 and NEMOTRON_SUPER_CHECKPOINT_DIR,
like the other managed-slot live cases.

Through the encrypted relay, a logprobs request drafts nothing, and the
same request without logprobs speculates to the same text. On the
engine, a greedy logprob row over the relay's rendered prompt carries
the relay's values. At every step the relay served, those values match
the last-position log-softmax of a cold prefill of the prompt and the
tokens before it: the same argmax at every step, worst deviation under
0.25 nats.

Pinned checkpoint on an M3 Ultra:
- 38 relay entries, relay vs engine 0.0
- teacher-forced median 0.0007 nats, worst 0.161 nats
- 0 argmax mismatches
- 0 drafted tokens for the logprob row, 13 rounds for the plain request

* chore(sdk): pin mlx-swift-lm to the merged #340 squash commit

Layr-Labs/mlx-swift-lm#340 was squash-merged to main as 6148b6da7eb8ed509ac56b74d7a69e8e73d8bf6c. Its tree is identical to the previously pinned PR head baca4acf8f7b4b91190de78a79e245f433875400, so only the gitlink changes: no SDK source differs.

* test(provider): judge Super's teacher-forced logprobs only up to the served end

pinnedCheckpointLogprobsMatchTeacherForcing now requires the relay to end at the end of turn inside its budget and stops the engine's greedy logprob row at the relay's last served position, so no step past the end of turn is scored. DARKBLOOM_SUPER_LIVE_MTP=off loads a plain owner for the numerics experiments; the speculation checks then require no MTP.

* test(provider): keep a GLM logprob row's entries beside a concurrent plain row

GLM5NextLogprobsTests/logprobRowKeepsItsEntriesBesideAConcurrentPlainRow serves a ten-step top-3 logprob row alone and then beside a twenty-step plain row on another prompt, on the protected synthetic bridge with two concurrent requests. The batched row carries one entry per token with the solo tokens, text, alternatives and values (within 1e-4); it never drafts; the plain row keeps its solo text and drafts again after the logprob row finishes.

* test(provider): bound a co-batched GLM logprob row's alternatives by batch-width numerics

On the real checkpoint (M3 Ultra) the solo logprob row matches the teacher-forced reference within 4e-6 nats, but beside a plain row its alternatives moved by up to 0.69 nats while its chosen values stayed within 0.048. Scoring the dense reference as two identical rows moves its top-8 by up to 0.56 nats from the one-row reference, so batch width alone produces that drift; every batched alternative stayed a reference top-8 token.

A co-batched row's alternatives are now bounded by DARKBLOOM_TEST_GLM5_REAL_LOGPROBS_BATCHED_TOLERANCE (default 1.0 nat); chosen values keep the per-step bf16-aware bound. The run records the paired-reference drift (pairedReferenceMaxDrift), the batched row's drift from its solo values and its comparison with the paired reference.

* docs: describe the GLM batched logprobs bound and the Super served-end check

* test(provider): expect GLM to serve required and named tool choice beside an image

ordinaryFactoryRunsTextHTTPImageAndProtectedEmbeddedMTP still expected a required tool_choice on GLM media input to throw. GLM now serves required and named tool choice: the forcing instruction leads the rendered prompt, the declared tool stays, and the call is withheld until it parses and matches its schema. Check that both choices normalize beside the image with the forcing system turn and the user's interleaved text and image parts.

* test(provider): serve GLM logprob and plain rows through one relay helper

GLM5NextLogprobsTests submitted and collected requests three ways: a plain helper, a logprobs helper and an inline loop in the relay test. One helper now serves both kinds of row and gives a logprobs request its relay channel. The assertions are unchanged.

* docs: describe the GLM concurrent logprob-row check

* feat(provider): return GLM and Super reasoning-token logprobs on the frames that carry them

Option B for the open thinking-only decision: vLLM-style logprobs. On
Nemotron Super (coordinator relay and local endpoint) and GLM-5.3-Flash
(relay), an entry now rides the reasoning or content frame that carries its
token, and a complete local response attaches entries to a message with
content or reasoning. logprobs.content therefore covers reasoning tokens,
and a response that ends while reasoning (max_tokens spent while thinking)
still returns one entry per token instead of none.

ProviderLoop.logprobsCoverReasoning selects GLM5-Next and the Super owner;
every other model keeps content-frame attachment. The coordinator already
concatenates logprobs from every chunk, so a non-streamed response with
content carries the same entries as before.

* provider(ssd-cache): queue up to six SSD prefix-cache writes

Both SSD prefix-cache write queues refused new donations as
write_queue_full at two jobs, so busy providers dropped prefixes they
could otherwise have reused. Raise SSDPrefixCachePolicy.writeQueueMaxJobs
from 2 to 6 and make the complete-checkpoint store use it instead of
literals: its writer gate admits six unsettled jobs, the one being
written included, and its pipeline buffer is as deep as that gate, so
the gate is the only queue refusal. Previously the one-job buffer could
refuse a job the gate had admitted after the writer settled one job and
before it took the next.

The memory bounds are unchanged. Attention-block jobs must still fit the
queued-byte cap (1,280 MiB at the default stage cap), and the job being
written still leaves both counts. A queued complete checkpoint holds only
donor state that stays charged to the engine admission ledger and I/O
scratch reserved before queueing. Because the engine delivers a donor's
terminal after its checkpoints settle, a write backlog now delays stream
end by up to five earlier writes per checkpoint instead of dropping it.

Tests: the attention cache queues six donations behind a blocked writer
and settles the seventh as write_queue_full; at the production limits the
queued-byte cap still refuses a job while a job slot is free; the fleet
demand test now fills the six-job bound; and queued complete writes keep
their host reservations, so the process ledger refuses before the job
bound. The SSD KV cache reference documents both queues, with a changelog
fragment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(provider): check GLM relay logprobs over reasoning through a shared scripted relay

ScriptedCoordinatorRelay drives one sealed request through the production
coordinator handler with a scripted engine; it is the Flint visibility
suite's relay harness, moved so other suites can use it, with a Progress
handle that lets a script wait for the chunks its deltas produced.

GLM5NextRelayLogprobsTests replays GLM-shaped tokens (the prompt ends inside
an open thought) through it: mixed and reasoning-only replies, requested
streamed and not, carry one entry per generated token in generation order,
reasoning tokens on the reasoning chunks and the marker and answer tokens on
the content chunks; no logprobs request carries none; another model type
keeps content-chunk attachment.

* test(provider): check Super logprobs over reasoning, including a thinking-only teacher-forced reply

Tiny fixtures: the Super relay serves a thinking-on mixed reply and a reply
that ends while reasoning with one entry per generated token on reasoning or
content chunks; the local endpoint does the same streamed and complete, and a
request without logprobs carries none.

pinnedCheckpointLogprobsMatchTeacherForcing now also runs with thinking on: a
48-token reply that ends inside reasoning must carry 48 entries on reasoning
chunks, equal the engine's, and match teacher forcing at every served
(reasoning) position. The real-GLM qualification records how many judged
positions are reasoning tokens and requires some.

* docs: state the vLLM-style logprobs contract for Super and GLM

logprobs.content has one entry per generated token in generation order,
reasoning tokens included: joined, the entry tokens spell the reasoning and
then the answer, not the answer alone. Reasoning chunks carry their tokens'
entries and a reply that ends while reasoning still returns them.

* provider(ssd-cache): pin the checkpoint writer buffer to the job gate

Refactor-pass follow-up to the six-job SSD write queue.

The complete-checkpoint pipeline buffer is as deep as the writer gate so
that a job the gate admits after the writer settles one job, but before
it dequeues the next, is buffered rather than dropped. No test held that
window open: the six-job fleet test still passes with a buffer one
shallower than the gate. Add one that blocks the first job's completion
callback, which runs after settle frees its writing entry, and checks
that the sixth admitted job is buffered and written.

Share the queued-donation helper that the six-job and host-ledger tests
each defined locally as SSDHybridCheckpointTestFixture.startDonation,
which the new test also uses. Name the gate and the window in the
pipeline comment, and note in the policy comment and the changelog that
a donor's stream end and KV release wait for all of its checkpoints, so
up to six waiting donors (was two) can hold KV memory at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(provider): judge real-GLM logprobs on reasoning tokens at the default effort

At low effort GLM-5.3-Flash closes the thought with its first token, so the
qualification judged answer tokens only (reasoningPositions 0 on the M3 Ultra).
The logprob prompt now uses the template-default effort, whose reply opens
with reasoning, and the run requires reasoning positions.

* feat(provider): route Nemotron Super prefix reuse through the coordinator

The managed Super owner's resident checkpoint bank now advertises a
protocol-v2 resident capability (prefix_cache_memory_models) bound to the
aggregate the provider published for the loaded checkpoint and the
checkpoint's PromptContractIdentity, the identity the prompt sidecar plans
with. Coordinator requests on the Super route submit under the request's
own usage signal, so lookup and ready receipts, prompt_tokens_details
cached_tokens and inference_complete cache usage now reach the coordinator
as on the generic engine, and the local endpoint reports the reused tokens.

Without a capability the coordinator never prepared a cache attempt for
Super, so no request carried a cache scope and the reserved bank served no
coordinator hit. A publication whose post-load artifact hash differs from
the advertised one closes the evidence; local reuse is unchanged.

* docs(provider): describe Nemotron Super prefix-cache routing evidence

Document the managed Super slot's resident capability, receipts and cached
token usage, the local endpoint's cached_tokens, and add the changelog
fragment.

* fix(glm): accept OpenRouter's reasoning.context and reasoning.mode on GLM-5.3-Flash

OpenRouter's reasoning-content-return readiness test now returns the
model's reasoning on a get_time tool call and asks for a secret word
chosen in that reasoning. A 123-variant matrix of that request family,
run through the coordinator-path handling (decodeInboundChatRequest,
validateNativeControls, the scheduler and the shipped template), shows
0.10.1 serves every reasoning carrier, reasoning_details field, strict
or empty-schema declaration, argument spelling and reasoning control the
test can send, and renders the returned reasoning. 0.10.0 refuses strict
tools, empty-string arguments and null reasoning members with 400
invalid_request, and drops returned reasoning.

The documented OpenRouter fields 0.10.1 still refused were the reasoning
object's context and mode members, rejected as unknown members:

- reasoning.context spells the template's clear_thinking: current_turn
  keeps only the reasoning returned after the last user turn (true),
  all_turns every turn's (false), and auto or null is unset. Other
  values, and a context that contradicts the effective clear_thinking,
  stay refused, never reconciled.
- reasoning.mode standard, OpenRouter's default, is a no-op. pro names a
  model variant GLM does not have and stays refused.

Tests: every golden renders byte for byte with its clear_thinking
replaced by the equivalent context; current_turn renders like
clear_thinking true with and without a later user turn; contradictions
are refused on the coordinator and local paths; the secret-word turn is
served through the scheduler with each reasoning carrier, the strict
declaration, empty-string arguments and the new controls. Each new test
fails on master's policy. Docs and a changelog fragment are updated.

* test(provider): accept Super teacher-forcing argmax swaps within twice the value bound

With thinking on, the 48 served reasoning tokens match teacher forcing within
0.293 nats, but at 3 steps the cold-prefill reference prefers another token
by at most 0.5 nats: decode-versus-prefill rounding, since one-token prefill
chunks make both cases bitwise equal (0 deviation, 0 swaps) on the pinned
checkpoint. The served value bound is 0.35 nats, and an argmax swap is
accepted only where the reference separates the two tokens by at most twice
that.

* refactor(glm): resolve clear_thinking and its reasoning.context in one place

The first version expressed the reasoning.context rule twice: validate()
refused a context that contradicts the raw clear_thinking, and
additionalContext() repeated the comparison against the typed controls'
value and then resolved explicit ?? context ?? false on its own.

RawControls.resolvedClearThinking(explicit:) now holds the whole rule:
the explicit Boolean, else the one reasoning.context spells, else false,
refusing a context that contradicts the explicit Boolean. validate() and
additionalContext() both call it, at the same points as before, so the
refusal order, message and rendered value are unchanged. The single-use
contradictoryReasoningContext constant is inlined.

Behavior-preserving: the GLM prompt-policy and OpenRouter capability
suites (42 tests, every golden render included) and the broader
GLM/prompt/request selection pass unchanged.

* refactor: tidy the option-B logprobs tests, comments and docs

Behavior-preserving refactor pass over the commits since e74c48250
(0425a8d8 through fc3dc260). No runtime change: the one Sources edit is a
comment.

- Super teacher forcing: the doc comment names the near-tie rule (each
  served value within `valueBound`, an argmax swap only where the
  reference prefers its argmax by at most twice that) and why
  decode-versus-prefill rounding explains it. The reference's value for
  the served token is now `referenceForServed`, so the gap no longer
  reads as `reference.logprob - referenceLogprob`.
- SuperSSE: drop a `delta` guard that the default empty delta made dead.
- GLM relay test: name the `</think>` token id (`thinkEnd`) instead of 3.
- Comments that still said entries attach to content frames only now
  name the reasoning case (`logprobsCoverReasoning`, `includingReasoning`).
- Changelog and direct-mode docs: the joined entry tokens include the
  `</think>` marker between reasoning and answer. test.md: the GLM relay
  test's mixed reply has no entry for its stop token.

* perf(glm): store GLM-5.3-Flash SSD checkpoints at BF16

Bump mlx-swift-lm to 39a12e1d (Layr-Labs/mlx-swift-lm#353): GLM complete
checkpoints write the latent keys, the index/gate/validity values row and
the KDA convolution history at their BF16 activation dtype and widen them
back to the identical FP32 bits on restore; the FP32 KDA recurrent state is
unchanged and any value BF16 cannot hold refuses the donation. The layout
becomes native-paged-glm5next-full-state-v2 (new namespace; v1 files expire
through the whole-root TTL sweep).

Measured on an M5 Ultra against the v0.10.1 build: checkpoints at
2,048 / 8,192 / 30,720 tokens shrink 18 / 33 / 42 %, bytes per token 48 %,
SSD bytes for an identical workload 30 %, and restore stage 25-29 %.
Document the v2 layout and sizes in the SSD reference and prefix-cache
architecture pages.

* perf(glm): validate GLM checkpoint validity flags by column

Bump mlx-swift-lm to 9abc8090 (Layr-Labs/mlx-swift-lm#353): the restore-time
validity check strides through the values row's validity column instead
of testing every element (one 30,720-token checkpoint: 51.3 ms -> 0.53 ms
on an M3 Ultra).

* feat(provider): keep Nemotron Super prefix reuse as durable SSD checkpoints

The managed Super slot's exact text prefix reuse is now complete encrypted
SSD checkpoints by default, as for the other cache-enabled models: the
builder prepares the paged backend, builds an SSDHybridCheckpointStore bound
to the published aggregate and the checkpoint's prompt contract, and
assembles the engine with it (native KV precision whatever the operator's
checkpoint quantization). The slot advertises prefix_cache_v2_models,
checkpoints survive restarts within the store TTL, and the coordinator's
repeat hint now reaches the Super route, so writes follow the same demand
gate and daily budget. The SDK bump adds the Super KV type declarations and
the assistant's durable history codec.

The resident bank is no longer reserved by default (its grant returns to
KV); DARKBLOOM_PREFIX_CACHE_MEMORY=1 selects it, and it remains the only
tier that reuses image turns. A load whose artifact hash changes during the
load is refused when it has a durable store.

* fix(provider): give a local Super complete response its stream's logprob entries

A local complete response attached every generated token's entry, including
the tool-call tokens that its stream and the relay drop when no text follows
the call (tiny fixture, thinking on: 9 entries complete, 1 streamed; with an
answer before the call, 11 and 4). The owner now also passes each chunk of a
complete response through a streaming split of the same request, and carries
the entries gathered so far only when that chunk shows reasoning or content,
as the stream's frames do (NemotronSuperCompleteLogprobs). The responder
attaches them as given, so its stop-token and message checks go.

Streams and the relay are unchanged. Text after a call still carries the
call's entries on every path, and Super's own call turns end with a newline
after </tool_call>; the docs and changelog say so.

* docs(glm): state the GLM checkpoint format once, in the SSD reference

Refactor pass. The SSD reference owns the GLM full-state v2 format; the
prefix-cache and inference explanations now name the identifiers and link
to it instead of restating its values (BF16, the payload ratio, the FP32
recurrent state). The reference cites the helper by its symbol and
tabulates the current v2 checkpoint sizes; the retired v1 comparison stays
in the changelog fragment and the PR evidence.

* refactor(glm): pin mlx-swift-lm at the refactor pass of Layr-Labs/mlx-swift-lm#353

Bumps libs/mlx-swift-lm 9abc8090 -> 184b5a93: the paged export walk is
shared by the native and narrowing branches, a wire dtype equal to the
page dtype is the native layout, the import sink drops its force unwraps,
and the half-precision tests are split into unit and kernel suites. The
checkpoint format and every GLM checkpoint byte are unchanged.

* docs: say Super's logprob entries cover tool-call tokens

Kept as decided: the relay, the local stream and the local complete
response carry the same entries, and Super's call turns end with a
newline after </tool_call>, whose chunk carries the call's entries. The
docs led with the exception ("a tool call's tokens carry entries only
when text follows the call"). They now state the contract first: one
entry per generated token in generation order, covering reasoning,
answer and tool-call tokens; tool-call tokens lack entries only in the
rare case that nothing follows the call.

The changelog fragment also covers GLM, whose template ends a call turn
with <|observation|> right after </tool_call>, so it calls that case
rare for Super only.

The refactor review of af5d701aa found no code to change.

* chore(provider): bump mlx-swift-lm to the formatted Super checkpoint codec

* perf(glm): capture GLM prefix checkpoints beside decoding requests

GLM-5.3-Flash captures a complete checkpoint only at a prefill range end
on the 256-token grid, and its prefill chunk shares one 2,048-token step
budget with the decode rows of other requests. Beside a decoding request
every range was 2,044-2,047 tokens, so a donor served with company
captured nothing, with no counter: one of six donors in the
qualification burst was cached.

Bump libs/mlx-swift-lm 184b5a93 -> 2231b8fc (Layr-Labs/mlx-swift-lm#355):
an opt-in scheduler partition ends a cacheable donor's range on its
demanded boundaries (fork target, deepest aligned boundary below the
prompt end), and GLM adopters resume under ordinary chunking instead of
waiting for a donor-sized chunk and cold-restarting after three waits.
The protected GLM engine with its GLM store enables the partition at the
store floor (EngineV2Factory.demandedCaptureBoundaryMinimumTokens).

With every donor capturing, donors that finish together overflowed the
store's single write slot: on an M5 Ultra two donors finishing in the
same millisecond lost both of one donor's files as write_queue_full. A
GLM store now holds eight donations behind its writer
(SSDPrefixCachePolicy.completeCheckpointWriteQueueJobs, set through
SSDHybridCheckpointStore.Config.writeQueueJobs); other layouts keep one.
A queued donation pins only its donor's pages and KDA copies, which stay
charged to the admission ledger until the write settles.

M5 Ultra #1, real weights: six concurrent 8k donors 6/6 captured and
written (was 1/6); a 32,682-token prompt publishes 32,512 instead of
30,720 (hit TTFT 3.1-3.7 s, was 3.96 s); a hit beside two decoding
requests restores with no preemption.

Tests: SSDCheckpointWriteQueueTests (depth by layout; four donations
queue behind a blocked writer and a fifth settles write_queue_full), the
partition stays GLM-only (Nemotron policy suite), and the GLM protected
factory asserts the partition floor and the queue depth.

* perf(glm): price measured restore time in complete-checkpoint ready receipts

A complete-checkpoint ready receipt priced a future restore as its file
bytes at the 1.5 GB/s planning rate. GLM-5.3-Flash restores take about
0.9 s more than that on an M5 Ultra, mostly the device's first work
after idling, so the receipt said 478 ms for a 716 MB checkpoint that
restored in 1.1-1.4 s and 125 ms for a 187 MB one that took 1.0-1.1 s.
The coordinator scores a holder with this value until a hit's measured
lookup replaces it, so it overstated the saving of short cached GLM
prompts.

SSDCheckpointStageCost adds to the byte price an exponentially weighted
average (newest weight 0.25) of how much longer this store's first-attempt
restores took than their byte price; a retried restore also paid for its
refused first attempt and is not recorded. The first restore replaces
the layout's prior: 935 ms for GLM5-Next, the median of the nine
qualification restores beyond their byte price; 0 for other layouts, so
their receipts are unchanged until they stage a file.

With this estimator (prior 900 ms in that build), 8,192-token GLM ready
receipts said 1,101 ms against 16 measured restores of 882-1,229 ms
(median 1,088 ms) on the M5 Ultra.

Tests: SSDCheckpointStageCostTests (layout priors and the exact GLM
estimate, replace-then-average updates, invalid samples, the protocol
ceiling, and a store's ready receipt after a first-attempt and a retried
restore on an injected stage clock).

* chore(provider): pin mlx-swift-lm at the refactor pass of Layr-Labs/mlx-swift-lm#354

44bdae77 -> 91bdc989: the Super adapter resolves its recurrent spec and its
complete-checkpoint KV types through one probe cache instead of two copies.
No behavior or checkpoint-format change.

* refactor(provider): tidy the Nemotron Super durable-checkpoint tests and docs

- NemotronSuperDurablePrefixCacheTests.ready polls through the evidence
  suite's `eventually` (the same 5 s bound) instead of a copy of it.
- The managed-slot durable test names the receipt boundary mode
  `boundaryMode` instead of shadowing its `mode: MTPMode` argument.
- The gated bank live test documents DARKBLOOM_PREFIX_CACHE_MEMORY=1 and
  checks it before loading: under the SSD default the slot keeps no bank,
  so without the switch the test could only fail after an 80 GB load.
- Rewraps the two docs paragraphs that the Phase A and B edits left with a
  stub line and over-long lines.

No runtime change.

* docs(glm): state the measured GLM write-queue overflow precisely

The two donors whose finishing lost both of one donor's files to the
single write slot finished within 27 ms of each other, not in the same
millisecond (M5 Ultra burst, harness wire log).

* docs(glm): cite the GLM capture partition's SDK sources by path

The GLM capture paragraph of prefix-cache.md named two SDK files by bare
file name, which docs-check cannot verify. Cite them by repository path
with their symbols (completeCheckpointLookup, demandedCaptureBoundaryRange),
as the neighbouring paragraphs and docs rule 4 do. No content change.

* refactor(glm): pin mlx-swift-lm at the refactor pass of Layr-Labs/mlx-swift-lm#355

libs/mlx-swift-lm moves 2231b8fc -> 723dbdaa. The refactor pass moves
CBv2DemandedCaptureBoundaryTests into the SDK's unit tests and documents
the capture-boundary partition's precedence and grid; no library behavior
changes.

* test(docs): keep Git auto-maintenance out of the historical-link fixtures

Docs Lint failed on #1592 in scripts/test-docs-check-historical-links.py,
before docs-check ran: test_a_frozen_directory_prefix_does_not_hide_a_
current_document passed its assertions, then its TemporaryDirectory
cleanup raised OSError [Errno 39] "Directory not empty: '.git'". The
fixture's commits let Git (2.55 on the runner) start detached
auto-maintenance, which can still be writing into the fixture's .git
while cleanup removes it. No docs or links were involved; the job's
docs-check step never ran.

The fixtures' Git environment now sets maintenance.auto=false and
gc.auto=0 (GIT_CONFIG_COUNT), so no background Git process outlives a
test. The checker under test is unchanged.

* fix(glm): serve OpenRouter hidden reasoning and Anthropic thinking controls

GLM-5.3-Flash refused several documented request controls with a typed 400
invalid_request, before acceptance and without a public log line, and the
coordinator counted each refusal as a failed job for the receiving provider:

- OpenRouter's hidden reasoning (reasoning.exclude: true,
  include_reasoning: false). The refusal's stated reason, that the provider
  had no seam to withhold reasoning it generates, no longer held: Flint
  already withholds reasoning through NativeToolStreamRouter.
- Anthropic's thinking object, which the coordinator's Messages lowering
  forwards unchanged (budget_tokens, type adaptive, display).
- A null reasoning_effort, which OpenAI documents as nullable.

GLM now serves them. The prompt is unchanged. When reasoning is withheld,
GLM's reasoning takes the native typed channel on text and media (as its JSON
and forced-call modes already do), the router withholds it, it still counts as
reasoning tokens and ends the pre-content interval, and
WithheldReasoningLogprobsFilter (renamed from FlintReasoningLogprobsFilter,
now shared) starts inside the prompt's open <think>, so no withheld entry
returns as logprobs. thinking.budget_tokens selects the effort as
reasoning.max_tokens does; adaptive enables thinking; display omitted hides
the reasoning. The unused reasoningExclusionUnsupported error and its local
HTTP message are removed.

Tests (fail on fb052c1e5, pass here):
- GLM5NextReasoningVisibilityTests: sealed requests through the production
  coordinator handler: withheld reasoning counted and excluded from the
  response hash, logprobs omit it, thinking-off with exclusion keeps the
  answer.
- GLM5NextMediaRoutingTests.hiddenReasoningWithMediaIsWithheldButCounted.
- GLM5NextPromptPolicyTests: exclusion renders the prompt byte-identical to
  the same request without it on both paths; Anthropic thinking and null
  reasoning_effort render like their unified spellings; the fail-closed list
  keeps invalid budgets, display values and thinking types.

* docs(provider): Super speculates for sampled requests and beside rows it cannot draft for

inference.md and a changelog fragment for the SDK change: sampled Super requests speculate through exact target-prefix acceptance, and a stop-string, penalty or logit-bias request decodes one ordinary token per step beside requests that speculate instead of turning speculation off for the step.

* fix(provider): never refuse a GLM load for the resident prefix-cache opt-in

DARKBLOOM_PREFIX_CACHE_MEMORY=1 builds a resident page-index config and a
recurrent-bank config for every slot. GLM's protected engine hosts neither,
and its backend preparation refuses both ("resident and hybrid prefixes are
unsupported"), so setting the flag fleet-wide refused every GLM load.

The slot factory now asks for resident tiers only from engines that host
them: a GLM slot logs that it ignores the opt-in and keeps its default
encrypted SSD checkpoints. Every other model still receives the opt-in
unchanged (Super's bank, attention models' resident L1), and the protected
backend's own refusal stays as a guard against a direct caller.

The real-construction test loads the tiny synthetic GLM with the flag set.
Before the fix it failed with the refusal above; it now binds the complete
store, builds no bank and serves an MTP request.

* fix(provider): replace an SSD cache KEK that no key can open again

The SSD prefix cache's key-encrypting key is stored in the Keychain sealed
(ECIES) to the provider's Secure Enclave identity. Two paths replace that
identity without touching the stored KEK: the attestation key's self-repair
(PersistentEnclaveKey.loadOrCreateVerified deletes and re-mints a key that
cannot sign) and `darkbloom unenroll` (LocalDataCleanup.purge deletes the
key). From then on every unwrap fails authentication, so every SSD store on
that Mac is refused as key_unavailable (cache_init_failed) on every load
until someone deletes the Keychain item by hand.

KVCacheKEK now treats an entry that fails authentication, is not a valid
ciphertext, or does not hold a 32-byte key as unusable and replaces it with
a fresh KEK sealed to the current identity. The files it protected were
already unreadable; each store's key-fingerprint binding wipes them when it
next starts. Backend failures (a locked keychain, an unavailable Secure
Enclave) are still reported and leave the entry untouched. Replacement runs
under one process-wide lock and re-reads the entry first, so concurrent
model loads converge on a single replacement.

* feat(provider): report why an SSD prefix cache did not start

80 of 1,568 loaded production slots report cache_init_failed, but the
heartbeat carries only that closed reason: the typed cause stayed in a
provider-local log line under com.darkbloom.provider, which `darkbloom logs`
does not read, and nothing in `status` or `doctor` showed it.

- The heartbeat's PrefixCacheModelStatus gains an optional `detail` with the
  typed cause behind an error state (SSDPrefixCacheConstructionFailure raw
  values, e.g. key_unavailable). It is omitted otherwise, so coordinators
  that predate it ignore it.
- Every store factory maps a refusal through one rule
  (PrefixCacheConstructionStatus(refusal:)): a refused complete-checkpoint
  store now reports unsafe_path as disk_unavailable, as attention-block
  stores already did, and a layout refusal as unsupported_layout. MiMo and
  the diffusion path now keep the typed cause instead of a bare nil.
- A closed store reports cache_closed and an attention-block store that
  lost its epoch reports epoch_unavailable, so slot teardown is no longer
  indistinguishable from a failed start.
- The daemon state file records each slot's prefix-cache state, reason and
  cause. `status` appends prefix_cache=… to every slot line with the cause
  and fix under a failed one; `doctor` (the desktop app's diagnostics) adds
  a prefix cache check. A load whose store failed logs a fixed public line
  for `darkbloom logs` and the model, cause and fix to provider.log.

* docs(provider): document prefix-cache failure causes, the KEK replacement and GLM's memory opt-in

- SSD KV cache reference: one refusal-to-status table for every store, the
  heartbeat `detail`, `cache_closed`, the status/doctor surfaces, that a
  refusal is never cached (each load retries), and that an unusable KEK is
  replaced.
- Protocol messages: PrefixCacheModelStatus's optional `detail` vocabulary.
- CLI reference: `prefix_cache=` on the slot posture lines and the doctor
  check.
- Encryption: a KEK sealed to a Secure Enclave key that no longer exists is
  replaced; a locked keychain leaves it untouched.
- Cache storage troubleshooting, prefix-cache architecture and inference
  architecture: the status rows and GLM ignoring the resident opt-in.
- Changelog fragment `prefix-cache-always-on`.

* feat(provider): log every refusal before the inference task with a fixed reason

A coordinator request refused before its inference task left no readable
log line, although coordinators count each refusal as a failed job: a
missing sender key or undecryptable body, unauthenticated tool-schema
metadata, a body that does not decode, unsupported audio, and native
controls the model refuses (the GLM, MiMo and Flint policies). The
console's Jobs card could not be matched in `darkbloom logs`.

Each refusal now writes one fixed public line naming a reason from the
closed InferenceRefusalReason set, for example
"Inference failure: invalid request (unsupported reasoning control)",
plus a private line with the request ID. The reason comes from the code
path that refused: the sealed request, the chat body's decode error (its
type and the request field its coding path starts at), the GLM capture
step that refused a tool declaration or control, or a contradiction. No
line carries request text. Logging only: every refusal decision and every
inference_error frame is unchanged.

- InferenceRefusalReason: the closed set and the decode classification.
- GLM5NextPromptPolicy.RawControls records its first refused step;
  refusalReason mirrors validate().
- ProviderPromptContractPipeline.nativeControlsRefusal names why
  validateNativeControls refuses; the handler uses it at both checks.
- InferenceFailureLogger.record(requestId:failure:refusal:) and the
  matching ProviderOperationalMessage cases.
- ProviderLoop takes a test log sink (log…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant