Repository navigation
fix(glm): GLM-5.3-Flash OpenRouter readiness: VFR video, strict tools and returned reasoning - #1561
Conversation
… 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.
…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.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Threat model review — advisoryReviewed head Review not completed for this head. Previous findings are superseded, not confirmed resolved. Reviewers: anthropic/claude-sonnet-5.5: first pass completed; anthropic/claude-opus-5.5: selected depth completed (43 batches); openai/gpt-6.1-sol: selected depth completed (35 batches) LOW: Weight-hash verification cache keyed on stat metadata with no stated integrity protectiondocs/reference/configuration.md:371 · A-004, ADV-001, T-012, T-027 The new `DARKBLOOM_VERIFIED_WEIGHTS_FILE` (`~/.darkbloom/verified-weights.json`) lets startup registration reuse a recorded weight hash instead of re-hashing when the stored device/inode/size/mtime/ctime match. The documented protection is only 'owner-only'. The owner is the provider operator (ADV-001), so the operator can hand-write a record for substituted weights, or edit the weights and restore their stat metadata under a manipulated clock or inode reuse. The provider would then register and advertise the previously verified hash without re-reading the bytes. This narrows the existing weight-substitution control (T-012/T-027) and adds a new operator-writable trust input. The same docs say a managed GLM load now publishes its own per-file SHA-256 verification 'instead of bracketing passes', which drops the pre/post-load comparison. The threat model should record that this cache is self-attested local state, not an integrity proof, and that coordinator-side hash checks must not treat it as stronger evidence. If the cache is intended as a security control, it should be MAC-bound to the Secure Enclave-rooted KEK or limited to non-security fast paths. Raised by: anthropic/claude-sonnet-5.5 LOW: Default reclaimable policy now credits all file-backed and purgeable pages as available memory, loosening the load/KV admission clampprovider-swift/Sources/ProviderCore/Inference/Memory/SystemMemory.swift:62 · new attack surface On the default `reclaimable` policy, `availableBytes` now returns max(free+inactive, free−speculative+external_page_count+purgeable_count) (SystemMemory.swift lines 60-62, 83-86). `external_page_count` covers every pageable file-backed page, including actively mapped pages that other processes or this process are still using, plus dirty pages that need writeback. The code comment claims reclaiming this memory never compresses or swaps process memory. That holds only for unmapped clean cache. Active mapped pages must be refaulted, and dirty pages need writeback first. The value feeds `ModelLoadAdmission.freeForLoadGb`/`maxLoadableWeightGb`, which clamp the load gate and the advertised loadable weight. Heavy file-cache or mapped-file use on a shared host can therefore inflate the headroom, so the provider admits a load or KV growth that pushes the machine into swap or OOM pressure and degrades availability. The cost is lost availability and over-advertised capacity. Mitigation: credit only a conservative fraction of `external_page_count`, or only inactive file pages, or keep the stricter policy on shared hosts. The existing `free-only` option remains available. Raised by: anthropic/claude-sonnet-5.5 MEDIUM: Operator-writable verified-weight cache may let forged records bypass startup weight re-hashingdocs/reference/configuration.md:371 · A-004, ADV-001, T-012, T-027, T-041, TB-003 configuration.md head line 371 documents a new DARKBLOOM_VERIFIED_WEIGHTS_FILE (~/.darkbloom/verified-weights.json). It holds owner-only records of verified weight hashes, bound only to file metadata (device, inode, size, mtime, ctime). Startup registration reuses a matching record instead of re-hashing. Under TB-003 the operator (ADV-001) owns this file. The operator can also read every metadata field of a substituted weight file, ctime included. Unless records are MAC'd or signed under an SE-rooted or process-held key, an operator could write a record that pairs the substituted files' metadata with the expected aggregate hash. The genuine signed binary would then report that hash at registration without hashing the bytes. This would weaken the T-012/T-027 weight-substitution detection on A-004. Today an attested binary computes the hash itself; with a forged record it would advertise a hash for weights it never measured. The env override also lets the path point to any file the operator writes. Fix: authenticate each record, e.g. HMAC under a KEK-derived key (as KVCacheSSD does), and bind it to the binary or version. Also keep fresh hashing on load before a verified weightHash is published or used as the T-041 SSD binding. Then update T-012/T-027 to describe this cache. The implementation (VerifiedWeightHashStore.swift) was not supplied, so the missing integrity control is inferred from the documentation. Raised by: anthropic/claude-opus-5.5 LOW: Registration weight hash can come from an unauthenticated, operator-writable cache fileprovider-swift/Sources/ProviderCore/Service/VerifiedWeightHashStore.swift:84 · A-004, ADV-001, T-012, T-027, TB-003 VerifiedWeightHashStore (lines 47-54, 79-86, 110-116) returns a stored aggregate SHA-256 as a verified hash when stat() identities match. The JSON at installDirectory/verified-weights.json, or any path named by DARKBLOOM_VERIFIED_WEIGHTS_FILE, has no MAC or signature. An operator (ADV-001) can write a record whose file identities match tampered weights and whose aggregateSHA256 is the catalog value. Device, inode, size, mtime and ctime are all read from the operator-controlled filesystem. A startup registration path that consults this store would then report a manifest-matching weight hash without reading the bytes. Before this PR, the attested process had to hash the weights itself to produce that claim (T-012/T-027/T-034). The doc comment (lines 12-15) says the managed GLM load re-verifies before serving, so the expected impact is a false registration and routing claim plus load-time failure, not unverified bytes in service. That guarantee depends on callers outside this batch. Plausible trigger: edit verified-weights.json or set the env override, then restart. Fix: authenticate records with a key derived from the SE-rooted KEK, ignore the environment override in release builds, or never surface stored hashes as attested registration evidence. Also update T-027/T-012 to describe the cached claim. Raised by: anthropic/claude-opus-5.5 Scan incomplete: 1 file(s) could not be fully read as text. Binary, Git LFS and submodule changes require manual review. Models: budgeted Sonnet / selective Opus / selective Sol 6.1. Findings require human validation; this review never requests changes or blocks merging. Human review required: CI did not complete the security review. A maintainer must review the saved findings and remaining scope. A green advisory job is not security clearance; do not manually rerun the paid scan. Coverage: 373/373 source units; cross-file integration complete. 0 selected depth batch(es) pending. All threat definitions indexed; relevant full definitions selected. Unchanged callers are not scanned. Cost this run: $0.0000 reported, $0.0000 reserved with unknown cost; 0 paid request(s), 147 reused batch(es), 0 provider cache-hit tokens. Saved findings and earlier report · Historical findings are not confirmed resolved. Bedrock: 7 request(s), 242423 uncached + 0 cache-read + 64267 cache-write input / 7303 output tokens; 0 request(s) with unknown usage. OpenRouter backup used 0 time(s). Dollar amounts above cover OpenRouter only; AWS billing is reconciled separately. |
… 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.
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.
…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.
… OpenRouter PR
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.
…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.
…penRouter PR Brings f663fe2, a811ae2 and 43d5512 from fix/provider-load-time-memory: GLM startup reads its weights twice instead of five times (the load publishes its own SHA-256 verification as the weight hash; a verified-hash record keyed by device/inode/size/mtime/ctime serves restarts), and bulk hash/verify reads drop their cached pages afterwards. Owner-approved. Resolves a semantic merge hazard: both sides added <think>/</think> to the synthetic GLM fixture vocabulary (4/5 here, 154841/154842 there), which would crash at runtime on a duplicate dictionary-literal key. Keeps the real GLM-5.3-Flash IDs 154841/154842 pinned in fixtures/models/glm53-flash/architecture.json.
GLM startup timing on M5 Ultra #1:
|
| Binary | Source | darkbloom SHA-256 |
mlx.metallib |
|---|---|---|---|
| BEFORE | master cf3c45107 (SDK 7bed8216) |
db94f6099b9f48d8892bb1f24aff92dfb56b2977f61206b77a8d80deb2e5beed |
156f2624… |
| AFTER | fix/provider-load-time-memory a811ae21a (= cf3c45107 + 4f04e6bd0, 57e3fb2ad, f663fe2ef, a811ae21a; SDK 7bed8216) |
f251c5dc094377fef378df6ef7dfa7b937d61df9c0a3b542bc2676e794bbcd95 |
156f2624… |
Release, dev install identity, same build recipe as above (Xcode 27.1, Swift 6.4, SDK 27.0).
Standalone (glm_load_timeline.sh: start --local, GLM startup preload, production [backend] settings)
Offsets are seconds from process start (seconds spent).
| Phase | tl-before-1 BEFORE |
tl-after-1 AFTER |
tl-after-2 AFTER |
|---|---|---|---|
Pre-load WeightHasher pass |
6.0 (25.0) | none | none |
| Loader: auxiliary verify / core SHA-256 verify / tensor reads + construction | 31–95 (64, not split in the log) | 5.7: 0.1 / 15.3 / 48.0 (64.3 total) | 5.5: 0.1 / 15.3 / 47.3 (63.5 total) |
Post-load WeightHasher pass |
95.0 (25.0) | none | none |
| Shape warmup | 121.5 (0.5, skipped: warm shader cache) | 70.8 (17.2, cold shader cache for the new binary) | 70.5 (0.5, skipped: warm shader cache) |
| Ready (listening) | 122.0 | 88.0 | 71.0 |
| Full 182 GB reads | 4 | 2 | 2 |
tl-before-1 vs tl-after-2 is like for like, both with a warm shader cache: −51.0 s. With a cold shader cache, AFTER takes 88.0 s (tl-after-1). The BEFORE cold-shader-cache starts on this Mac took 142 s (glm-before, 20:07 today, 20.1 s warmup), so the cold-cache comparison is 142 → 88 s. tl-after-2 is a standalone repeat. Standalone mode never registers, so it cannot exercise the verified-hash record; the coordinator-mode runs below do.
Coordinator mode (start --foreground --model glm-5.3-flash against the loopback proof coordinator from the comment above)
The production glm-5.3-flash revision directory was read-only. Ready = the provider's register + first heartbeat with glm-5.3-flash warm, as seen by the loopback coordinator.
| Phase | coord-before BEFORE |
coord-timing-1 AFTER, first start |
coord-timing-2 AFTER, restart |
|---|---|---|---|
Registration hash (attachWeightHashes) |
3.0 (25.0) | 3.0 (25.0), no record yet | 4.0: reused, "recorded by its last full verification; file identities unchanged, the load verifies again before serving" |
Pre-load WeightHasher pass |
31.0 (25.0) | none | none |
| Loader: aux / core SHA-256 / tensors + construction | 56–120 (64, not split) | 31.5: 0.1 / 15.3 / 47.2 (63.5 total) | 6.6: 0.1 / 15.3 / 47.1 (63.4 total) |
Post-load WeightHasher pass |
120.0 (25.0) | none | none |
| Shape warmup | 146.5 (0.5, warm cache) | 96.5 (0.5, warm cache) | 71.5 (0.5, warm cache) |
| Registered, warm | 157 | 107 | 83 |
| Full 182 GB reads | 5 | 3 | 2 |
| Plain request after warm | 200 "OK" | 200 "OK" | 200 "OK" |
All three runs spend about 10 s between the warmup and register, which this change does not touch. The verified-hash record went to the run's own file through DARKBLOOM_VERIFIED_WEIGHTS_FILE, not to ~/.darkbloom. It holds glm-5.3-flash → 3aae613f… with each file's device, inode, size, mtime and ctime. coord-timing-2 matched it after a purge, and its load still SHA-256-verified all 42 files before serving.
Wired limit (iogpu.wired_limit_mb, read with darkbloom doctor, no model loaded)
iogpu.wired_limit_mb |
doctor |
|---|---|
245760 (current, persisted by /Library/LaunchDaemons/com.layrlabs.glm53-wired-limits.plist) |
[PASS] metal gpu: Apple M5 Ultra, 240 GB working set |
| 0 (OS default), 21:00:36–21:00:50 only | [PASS] metal gpu: Apple M5 Ultra, 222 GB working set |
| restored to 245760 at 21:00:50 | sysctl iogpu.wired_limit_mb → 245760 (verified) |
Harness and raw logs
glm_load_timeline.sh / glm_load_timeline.py / TIMELINE.md (standalone runs); serve_coord.sh + loopback_coordinator.py (coordinator runs; VERIFIED_WEIGHTS_FILE keeps the record between the two AFTER runs). AFTER GLM load log lines, verbatim:
tl-after-1 2026-10-22T21:04:12-0700 GLM load EigenLabs/GLM-5.3-Flash-MLX-NVFP4-mtp: all 42 manifest files SHA-256 verified before serving; auxiliary verification 0.1 s, core verification 15.3 s, tensors and construction 48.0 s, total 64.3 s
tl-after-2 2026-10-22T21:05:57-0700 GLM load EigenLabs/GLM-5.3-Flash-MLX-NVFP4-mtp: all 42 manifest files SHA-256 verified before serving; auxiliary verification 0.1 s, core verification 15.3 s, tensors and construction 47.3 s, total 63.5 s
coord-timing-1 2026-10-22T21:08:03-0700 GLM load glm-5.3-flash: all 42 manifest files SHA-256 verified before serving; auxiliary verification 0.1 s, core verification 15.3 s, tensors and construction 47.2 s, total 63.5 s
coord-timing-2 2026-10-22T21:08:48-0700 Weight hash for glm-5.3-flash: 3aae613ff188bb0f (recorded by its last full verification; file identities unchanged, the load verifies again before serving)
coord-timing-2 2026-10-22T21:09:54-0700 GLM load glm-5.3-flash: all 42 manifest files SHA-256 verified before serving; auxiliary verification 0.1 s, core verification 15.3 s, tensors and construction 47.1 s, total 63.4 s
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.
…e GLM wired-limit notice
GLM-5.3-Flash real-checkpoint logprobs qualification on M5 Ultra #1: FAIL
Reading: the first divergence is a greedy argmax flip at a near-tie at step 3 ( Production: M5 #1 was drained at 21:41:19 PDT and |
|
Merge order for review (for Gaj)
Logprobs are included but stay off. The GLM logprobs code in this PR doesn't serve traffic until the build's catalog |
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.
|
Re-pin pushed: CI is rerunning on |
|
Disclosure for review: one stale gated test, which CI doesn't run.
So the test's expectation is out of date; the behavior isn't wrong. To avoid another push here during review, the fix goes in the logprobs follow-up draft (#1564). No CI result on this PR is affected. |
Summary
OpenRouter's
reasoning-content-returnreadiness task fails onglm-5.3-flashwith 400invalid inference request(three runs on 2026-10-22, provider request IDlb52omhg0hnt). The same task passes on MiMo (mimo-v2.6-flash-mopd) and Nemotron Super.The exact request payload was not observable. The OpenRouter dashboard shows status and the error body only: no request JSON, no provider request ID per run. This fix is built from the evidence below, not from a captured request.
CapabilityGate.Reject, which fires only whentoolsis present). Today it reaches the provider and getsinvalid_request.reasoning,reasoning-effort-low/high/max,multi-turn,multi-system-prompt,max-tokens, image and video URL.toolresult, with tools declared.I pushed 50 candidate shapes of that turn through each family's real decode → policy path (GLM also through the pinned template). Using MiMo and Super as the benchmark, GLM refused six shapes that both of them serve:
strict tool decoding is not qualified"strict": trueon a function: what OpenRouter's tool tests send (captured in platformincident_fixtures.go)autocall is already checked against its declared schema before it is exposed (ToolConstraintValidation.validate), so a non-conforming call still fails the request. The template omitsstrict"arguments": ""on a returned call{}, as vLLM, MiMo and Super doreasoning: null,include_reasoning: nullthinking: {"type":"enabled","clear_thinking":false}(GLM's own API spelling) or a Booleanclear_thinking(lowest precedence)strict: trueis the most likely trigger: it is the only tool-specific GLM-only refusal, and OpenRouter's captured tool requests use it. The other three are fixed as well because the payload is unknown.The fix also corrects a silent rendering gap. Reasoning returned as OpenRouter's
reasoningstring orreasoning_detailstext was dropped by the SDK message type, so GLM rendered an empty<think></think>for that turn. It now renders exactly asreasoning_content. Summary and encrypted details are skipped.clear_thinkingsemantics are unchanged.Also, as Nemotron Super already does: null
reasoningmembers are unset, andreasoning.summary/generate_summarylevels (auto,concise,detailed) are no-ops.Still refused: forced (
required/named) tool choice, contradictory thinking switches, unknownreasoningmembers,preserve_thinking, hidden reasoning (reasoning.exclude: true/include_reasoning: false, same fixed message), forged schema markers and history whose tool results don't match their calls. Either MiMo or Super refuses each of these too, so none can be the passing task's shape.Before
After
Code flow (
provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift):Proven against captured OpenRouter tool payloads
OpenRouter's GLM capability tests fail with the same 400
invalid inference request, three runs each:tool-call-step-1,tool-call-step-5,tool-choice-autoandtool-choice-none. The platform conformance fixtures hold OpenRouter's real captured tool-test bodies (orIncidentOmitted,orIncidentAutoincoordinator/tests/internal/conformance/incident_fixtures.go): the Boston weather prompt withget_current_weather,"strict": true,additionalProperties: false,reasoning: {"enabled": false}andstream: true;tool_choiceis omitted in one and"auto"in the other.Commit
c7bfab158adds tests that replay those bodies byte for byte. Each is SHA-256-checked against the platform fixture's provenance hashesf0f8f60c…/d63598aa…; only the routedmodelis added, as the platform fixture wrapper does. The cases are tool choice omitted,auto, and theautobody with"tool_choice": "none", plus a five-step conversation built from the samestricttool (user, then five rounds of assistanttool_callsandtoolresult; two rounds returnreasoning), thetool-call-step-5shape. Each runs through GLM's real coordinator and local decode → controls →ToolChoicePromptPolicy.prepare→ToolStreamPreparation.makeHandler→GLM5NextPromptPolicy→ shipped template path.Before (
GLM5NextPromptPolicy.swiftatorigin/master, same tests):invalidToolPayloadmaps to failure codeinvalid_request(ProviderLoop+ErrorMapping.swift), and the coordinator renders that as exactly OpenRouter's{"error":{"code":"invalid_request_error","message":"invalid inference request"}}.After (this PR):
The rendered prompts keep the declaration unchanged (closed schema included;
strictis omitted by the template), close thinking forreasoning: {"enabled": false}, and fornonedrop the tools and add the no-call instruction. Focused reruns atc7bfab158:GLM5NextPromptPolicyTests29/29,GLM5Next112/0,LocalChatRequestTests6/0,InboundDecodeTests32/0,InboundChatRequestDecodeTests4/0,MultiModelBatchSchedulerEngineTests30/0,ToolChoicePromptPolicy19/0,ToolConstraint75/0,ProductionPromptParityTests2/0,NemotronSuperPromptContract|NemotronSuperRequestPlanXCTest 15/0,MiMoV26TemplateFixTests18/0.make docs-check,docs-impact-check.py --base origin/masterandchangelog.py checkpass.So the
strictgate is proven to be the 400 for OpenRouter's tool tests.reasoning-content-return's exact payload is still unobserved. It carries tools (the 2026-10-15 tool-capability 503) and fails with the same error, and OpenRouter's tool tests declare thisstricttool, so it very likely hits the same gate. Its other plausible extras (returnedreasoning/reasoning_details, null fields, GLM'sthinkingobject,""arguments) are covered by the matrix below.Out of scope here:
response-format-json-objectandstructured-outputare refused byGLM5NextPromptPolicy.normalizedTextInput's guardrequest.responseFormat?.requiresJSONOutput != true("JSON output mode and constrained JSON schemas are not qualified" →invalid_request; verified locally forjson_objectand a strictjson_schema).tool-choice-requiredandtool-choice-functionstop at the coordinator. Neither is changed by this PR.Evidence
Candidate matrix: the same tool-call turn (
get_weather, returned call,toolresult) with one variation per row. Each family ran its production decode and policy path in a temporary probe test (not committed): GLMdecodeInboundChatRequest→validateNativeControls→prepare→ToolStreamPreparation.makeHandler→normalizedInput→ shipped template; MiMovalidateRawControls→ … →normalizedInput; SuperNemotronSuperRequestPlan→messages→makeHandler.All 50 shapes: GLM before / after, MiMo, Nemotron Super
Shapes returning
invalid_requeston GLM before and served after: S1, S2, H6, K3, K4, K5, K7, K8, K10. Of these, S1, S2, H6, K3, K7, K8 and K10 are served by both MiMo and Super. Every other GLM refusal is shared with MiMo or Super.Committed regression tests (
GLM5NextPromptPolicyTests), run on master source then on this branch:Focused suites on this branch (
swift test --skip-build --disable-xctest --filter …; counts are Swift Testing tests passed / failed):GLM5NextPromptPolicyTestsGLM5NextLocalChatRequestTests,InboundDecodeTests,InboundChatRequestDecodeTestsMultiModelBatchSchedulerEngineTests,ToolChoicePromptPolicy,ToolConstraintFlint,NemotronSuper,PromptTokenCache,Qwen4Reasoning,LocalResponseMiMoV26TemplateFixTests(XCTest)StandaloneServerstandaloneServerStopAndWaitReleaseResidentBridgeAndSSDResources(exit test), fails identically with this PR's source change reverted, so it predates this PRmake docs-check,docs-impact-check.py --base origin/masterandchangelog.py checkpass. MiMo fixture XCTests that needMIMO_PROMPT_ARTIFACT_DIRECTORYor payload fixtures were not configured locally; they reportfixtureRequired.Unchanged and still asserted: template SHA
46b2e213…, golden renders, thinking-off closing</think>, the fixed exclusion refusal message and its 400invalid_request/client_errorwire mapping.Merge Danger
Door: two-way. This is a provider policy change with no protocol, persistence or model-artifact change; reverting restores the old refusals.
Blast Radius: GLM-only. Only
GLM5NextPromptPolicybehavior changes; the model-blind capture records returned reasoning for every request but only GLM reads it.strict: trueis now served by validation, not constrained decoding. A model call that breaks the schema fails the request (generation failure) instead of being refused up front.reasoning/reasoning_details: the earlier turn now replays its reasoning whileclear_thinkingis false, asreasoning_contentalready did. This changes those prompts' tokens and prefix-cache keys.coordinator/promptsidecar/src/glm5_next.rsstill refusesstrict, top-levelthinking, nullreasoning/include_reasoningand summary levels, and does not mapreasoning/reasoning_detailsor""arguments. The coordinator does not reject on that: such requests plan cold, so cache-aware routing and the first-content estimate fall back to the heuristic.docs/reference/api-contracts.mdthere still says the provider refuses these. A small companion platform PR should mirror this contract.reasoning-content-returnafter a provider release that includes this change.Test plan
cd provider-swift && swift build --build-tests && swift test --skip-build --disable-xctest --filter GLM5NextPromptPolicyTests(master source: fails as above; branch: 27/27)make docs-check,python3 scripts/docs-impact-check.py --base origin/master,python3 scripts/changelog.py checkComponents touched
Protocol / interface changes
docs/reference/protocol-messages.md#glm-native-prompt-contract); the platform sidecar mirror is a follow-up (above).Documentation impact
docs/reference/protocol-messages.md(GLM native prompt contract),docs/architecture/inference.md,docs/developer/test.mdChangelog
changelog.d/glm-openrouter-returned-reasoning.md;python3 scripts/changelog.py checkpasses.Refactor Pass
Not run.
AGENTS.mdrequires a dedicated refactor subagent before review, and this worker has no delegation tool. The coordinating session owns this gate. Suggested scope:GLM5NextPromptPolicy.swift(RawControls.capture,ReturnedReasoning,returnedReasoning(_:request:prepared:)), keepingGLM5NextPromptPolicyTestsgreen.Refactor pass (reasoning/strict part)
A dedicated refactor subagent reviewed
59893e574andc7bfab158(git diff cf3c45107 c7bfab158). For that part, this replaces the "Not run" note above. The #1559 VFR part had its own pass and was not reviewed here.Outcome: no source change. Small test and doc cleanups in
5c73e5e91.GLM5NextPromptPolicy.swiftwas reviewed and left unchanged:RawControls.capture,ReturnedReasoningandreturnedReasoning(_:request:prepared:)are cohesive.noneeither appends its instruction to a leading system turn or inserts one at index 0, so the 0…1 offset is correct.strict.ToolConstraintValidation.validatechecks everyautocall against its schema before exposure.normalizedTextInputwas deliberately left alone so the stacked JSON-mode / forced-tool-choice branch merges cleanly.Cleanups in
5c73e5e91:docs/developer/test.mdcited a test that does not exist,openRouterReasoningContentReturnRequestsAreServed. It now citesopenRouterReasoningContentReturnRequestIsServed. It also now says the captured requests are held byte for byte and hash-checked; the replay re-serializes them with the routedmodeladded, so "replay byte for byte" was imprecise.docs/architecture/inference.mdnow citesGLM5NextPromptPolicy.RawControls.returnedReasoninginstead of the ambiguous pairRawControls,returnedReasoning.changelog.d/glm-openrouter-returned-reasoning.mdnow liststhinking: nullamong the unset values. That behavior was already implemented and tested.GLM5NextPromptPolicyTests.swift:fields, because callers also passtool_callsandcontent, not only reasoning.controlsbinding inrenderedThinkingOffToolRequest.decodeOpenAIRequestcall thatremoteAndLocalInputsalready makes.All invariants hold:
strictis accepted, and everyautocall is still schema-validated before exposure.{}.reasoning,include_reasoningandthinkingmean unset.thinkingBoolean or object is accepted.reasoning_content.Validation (head
5c73e5e91, SDK6aef0a5d, isolatedDARKBLOOM_STATE_FILE/DARKBLOOM_LOADED_MODELS_FILE):mlx.metallib/default.metallibcopies, ranswift build --build-tests(Build complete), then../scripts/stage-test-metallib.sh <bin>.../scripts/run-nested-suite.sh 'GLM5NextPromptPolicyTests|GLM5Next|ToolChoicePromptPolicy|ToolConstraint|ProductionPromptParityTests' --no-parallel:@Tests before and after this pass. This includes all seven returned-reasoning/strict tests and their 13 + 3 parameterized cases.DARKBLOOM_TEST_GLM5_PROTECTED_FACTORY,DARKBLOOM_TEST_GLM5_MANAGED_SYNTHETICandGLM53_RAW_HEADER_FIXTURE_DIR. None of them is in a file this pass touched.make docs-check: 192 files OK.make changelog-check: 3 valid fragments.make changelog-preview: ran successfully.make docs-impact-check BASE=origin/master: 10 changed files, coverage OK.Refactor pass (GLM JSON / forced tool_choice)
A dedicated refactor subagent reviewed
2d65e068b(JSON mode / structured outputs),e771f9615(forcedtool_choice),1d011ce1f(native output-control evidence) and17d1f6214(JSON-mode returned reasoning) on the merged head7b801ad9a. The platform mirror is reviewed in darkbloom-platform #411.Outcome: one CI fix and a small behavior-preserving cleanup.
CI fix,
96c510158(test(glm): align the capability tests with served GLM logprobs)The merged logprobs commit
f02327abechanged two things:capturesLogprobsargument toEngineV2Bridge.nativeOutputControlRefusal.GLM5NextOpenRouterCapabilityTestsstill called the old three-argument form, so the provider test products did not build on7b801ad9a. Its control test also asserted that GLM refuses a logprobs row, which is no longer true. The fix keeps the evidence non-vacuous:ServedResponse.nativeRefusalsis still GLM's decision (capturesLogprobs: true). Every JSON and forced assertion that it is[nil]is unchanged.nonCapturingNativeRefusalsholds the same check for a native engine that cannot capture logprobs (MiMo).nativeEngineEvidenceAdmitsGLMLogprobsButRefusesNonCapturingEngines. It asserts that GLM admits the logprobs row and that the non-capturing engine refuses it withEngineV2Translation.unsupportedOutputControlPrefix.swift build --build-testsfound no other caller of the old signature.Cleanup,
68593b595(refactor(glm): name the withheld GLM output modes once)GLM5NextPromptPolicy.withholdsOutput(_:modelType:)names the requests whose output GLM withholds until it validates: a JSONresponse_format, or a required/named call.MultiModelBatchSchedulerEngineused to spell that set twice, once for the GLM media refusal and once for the text path's typed reasoning channel and withheld-output recording. Both now read the one predicate, so they cannot drift.returnedReasoningrenames its index toinstructionIndexand says why the inserted turn is the last leading system turn.docs/developer/test.mdnow describes the new control.Reviewed and left unchanged:
GLM5NextResponseFormat/GLM5NextResponseFormatOutput.emitwithholding.ToolChoiceEnforcementPolicy:forcedStrategy,validateParserandadvertisesCapability.compileResponseSchemaexplicit-type check.EngineV2RequestUsageSignal.recordWithheldOutput.protocol-messages.md,inference.mdand the fixture README.inference.mdis still accurate after served GLM logprobs: JSON and forced rows request no logprobs and install no constraint.All invariants hold:
json_object/json_schemaare served through the instruction plus withheld validation. One validated, fence-free answer is exposed. Prose, a schema violation or truncation is a 422 with nothing exposed.glm-5.3-flashand the local qualification ID.Validation (SDK
baca4acf, isolatedDARKBLOOM_STATE_FILE/DARKBLOOM_LOADED_MODELS_FILE)mlx.metallib/default.metallibcopies. Then ranswift build --build-tests(Build complete) and../scripts/stage-test-metallib.sh <bin>.7b801ad9a:GLM5NextOpenRouterCapabilityTests.swift:90: missing argument for parameter 'capturesLogprobs' in call.96c510158alone:run-nested-suite.sh 'GLM5NextOpenRouterCapability|NativeOutputControlRefusal|GLM5NextLogprobs|GLM5NextPromptPolicy' --no-parallelran 43 tests in 4 suites, all passed. The renamed control passed. The only skip isprotectedNativeEngineServesRelayLogprobs, which is gated onDARKBLOOM_TEST_GLM5_MANAGED_SYNTHETICand is not in this pass's files.68593b595:run-nested-suite.sh 'GLM5NextOpenRouterCapability|GLM5NextPromptPolicy|ToolChoice|ToolConstraint|NativeOutputControlRefusal|GLM5Next|GLM5ToolFailure' --no-parallel:NativeOutputControlRefusalTests.DARKBLOOM_TEST_GLM5_*,DARKBLOOM_TEST_GLM_RESIDENCY_INTEGRATION,GLM53_RAW_HEADER_FIXTURE_DIR). None of them is in a file this pass touched.make docs-check: 192 files OK.make docs-impact-check BASE=origin/master: 30 changed files, coverage OK.make changelog-check: 5 valid fragments.make changelog-preview: renders the GLM JSON / forced fragment.Refactor pass (logprobs P0 part)
A dedicated refactor subagent reviewed the merged native-engine logprobs code without changing behavior:
b25ee3212: the fixture's<think>tokens.82acc4885: the typed P0 refusal.f02327abe: GLM logprobs are served; the 400 now covers only MiMo logprobs and token constraints on native engines.baca4acf(mlx-swift-lm fix(coordinator): schedule the read-cache purge janitor #340).Outcome: one small source cleanup,
574096eb4. The rest is merges with the moving remote:a8619365d,6e717ac19and053a69147(the head of the pushed range98210d6e0..053a69147).In
EngineV2Bridge+Submission.swift, the non-throwingsubmitTokenizedwrapper had two identical catch bodies. Each turned a typed refusal (tokenBudgetExhausted,unsupportedOutputControl) back into its in-band marker. They are now one multi-pattern catch. Both throws finalize their prefix-cache lookup first, andfromSchedulerMessagemaps each marker back to its error, so nothing changes for callers.I dropped an earlier edit that derived
nativeTrackedfrom the bridge's existingtracksNativeShutdown. Afterf02327abe,nativeOutputControlRefusalbinds the engine once for bothnativeShutdownExecutionContractIDandacceptsLogprobRows, so reusingtracksNativeShutdownno longer simplifies it.Reviewed and kept as is:
nativeOutputControlRefusal, both the instance and the static versionunsupportedOutputControlPrefixand itsfromSchedulerMessagecaseProviderLoop+ErrorMappingcasesNativeOutputControlRefusalTestsandGLM5NextLogprobsTestsNo test, assertion or public contract changed.
GLM5NextOpenRouterCapabilityTestsbelongs to the GLM-features refactor agent, and I did not edit it. Its fix96c510158came in through a merge.The invariants hold, and the runs below check them:
invalid_request(client_error) before any reservation, on both submit paths. These never count toward the error cooldown.proposedTokens == 0);EngineLoopV2.mtpBasicEligiblerejects it, and without target-only media in the cohort,mtpRowsCanSpeculatekeeps the whole GLM step target-only.Observations I did not act on:
protectedPagedEngineServesALogprobRowBesideAPlainRowusesmaxSpeculativeBatch: 1. With two rows, the batch gate alone already blocks speculation, so no test pins "the batch decodes without MTP while a logprob row decodes"; the code enforces it structurally. Pinning it would need a harness withmaxSpeculativeBatchof at least 2.Validation
Provider runs used head
053a69147, SDKbaca4acf, and isolatedDARKBLOOM_STATE_FILE/DARKBLOOM_LOADED_MODELS_FILE:I deleted the bundled
mlx.metallib/default.metallibcopies, ranswift build --build-tests(Build complete), then../scripts/stage-test-metallib.sh <bin>.With
DARKBLOOM_TEST_GLM5_MANAGED_SYNTHETIC=1, I ran../scripts/run-nested-suite.sh '…' --no-parallelover these suites:NativeOutputControlRefusal,GLM5NextLogprobs,MultimodalErrorMapping,InferenceFailure,ErrorMappingEngineDeadlineRetirementBridgeTests, which covers the folded catch'stokenBudgetExhaustedpathEngineV2LogprobsPassthroughTests,EngineV2LogprobsChannelCapTests,EngineV2TranslationTests,EngineV2EventFramingTests,EngineV2HardeningTests,EngineV2LookupReceiptCoverageTests,EngineV2CancellationTestsmultiModelEngine*,multiModelDeadline*,fromSchedulerMessage*,platformTerminal*,*MapsToBadRequestGLM5NextOpenRouterCapabilityTestsResult: 87 tests in 13 suites plus the scheduler's free-function tests passed, with exit 0 and no skips. They include
protectedNativeEngineServesRelayLogprobsandrefusalIsATypedClientErrorOnBothSubmitPaths.Before
f02327abe, a temporary probe that was never committed drove the folded catch'sunsupportedOutputControlpath through the real protected GLM bridge's non-throwing submit. It produced one in-band marker, which maps to 400invalid_request/client_error, with no native fault, and the engine kept serving.In the SDK, after
swift build --build-testsand staging:MLX_ENABLE_TF32=0 ../../scripts/run-nested-suite.sh 'GLM5NextMTPTests/protectedPagedEngine' --no-parallel: 4 tests passed. They includeprotectedPagedEngineCapturesLogprobRowsOffSpeculation, for serial and rectangular verification, andprotectedPagedEngineServesALogprobRowBesideAPlainRow.'CBv2LogprobsTests|CBv2MTPEngineMixedTests': 4 XCTest and 13 Swift Testing tests passed.scripts/prepare-mimo-provider-fixtures.pyandMIMO_V26_SERIAL_NATIVE_TESTS=1,CBv2NativeRequestRetirementTests/testZeroWorkIsAcknowledgedAndColdRefusalNeverRegisterspassed. It confirms that a tracked MiMo engine still refuses a logprob row at submit.make docs-check: 192 files OK.make changelog-check: 6 valid fragments.make changelog-preview: OK.make docs-impact-check BASE=origin/master: 38 files, coverage OK.GitHub shows all four new commits as Verified.
Page-cache admission
Merged from
fix/provider-load-time-memory(4f04e6bd0,57e3fb2ad) in98210d6e0.Problem.
SystemMemory.availableBytescounted free + inactive pages only, so clean file page cache on the active queue counted as used. macOS drops that cache without compressing or swapping any process memory. After weight download, staging and hashing, a 256 GB M5 Ultra held about 250 GB of page cache (vm_stat: free 2.4 GB, active 55.7 GB, inactive 208.7 GB). It reported 170.8 GB usable and refused GLM-5.3-Flash's 185.4 GB cold load (178.9 GB model + 6.5 GB serving reserve) untilsudo purge.Fix. Under the default
reclaimablepolicy, available = max(free + inactive, free − speculative + file-backed (external_page_count) + purgeable).DARKBLOOM_MEMORY_AVAILABILITY=free-onlyis unchanged.darkbloom statusanddarkbloom doctorall readSystemMemory.availableBytes.Unit tests (
SystemMemoryTests):hostOnePageCacheNoLongerBlocksTheGLMColdLoadreplays the incident'svm_statsample. Usable rises from 171.0 GiB to 211.5 GiB against 185.4 needed, and the load is admitted.busySharedMacIsNeverStricterThanBeforekeeps a shared M3 Ultra (mostly anonymous inactive memory) at its free + inactive figure, 93.0 GB.anonymousMemoryStillRefusesTheGLMColdLoadandcompressedAndWiredMemoryEarnNoCreditgive anonymous, compressed and wired pages no page-cache credit. The GLM load stays refused when the same pages are process memory.M5 Ultra proof (256 GB, real GLM-5.3-Flash weights, page cache filled to the incident's shape, no purge before start):
mastercf3c45107)darkbloom doctorStartup preload: 0 model(s) loadedStartup preload: 1 model(s) loadedFull M5 evidence (fill procedure,
vm_statsamples, logs and binary hashes): M5 Ultra #1 before/after comment.Before (page-cache admission)
After (page-cache admission)
Refactor pass (page-cache admission)
A dedicated refactor subagent reviewed
4f04e6bd0and57e3fb2ad(git diff 4f04e6bd0~1 57e3fb2ad) on head98210d6e0.Outcome: a small behavior-preserving cleanup,
ced5723d9(refactor(memory): share the live Mach sample and drop the dead saturating sum), merged into the branch by signed non-force merge94808688f.SystemMemory.vmStatistics()owns the live MachHOST_VM_INFO64sample.availableBytes()reads it, andlivePageCountsKeepTheMachPartitionnow checks the partition on that same sample instead of its own copy of the unsafe-pointer sampler.saturatingSum. Each measure adds at most three 32-bit Mach counters, which cannot overflowUInt64. The byte conversion still saturates (reclaimable) or fails closed to 0 (free-only).docs/architecture/hardware-support.mdnow name free + inactive directly instead of as "the former" or "before" measure.freeForLoadGbparameter doc now citesSystemMemory.availableBytesfor the policy. It used to say "free pages plus reclaimable page cache", which is wrong forfree-onlyand for the free + inactive term.hostOneSample(anonymousFileCache:)is nowhostOneSample(asAnonymousMemory:). The flag means the same pages are process memory rather than page cache.Reviewed and left unchanged:
availableBytes(stats:pageSize:policy:): the policy switch, nil (reclaimable) / zero (free-only) on sampling failure, and byte-overflow handling.freeAndPageCachePages.SystemMemory.availableBytes.docs/reference/configuration.mdanddocs/provider/cli-reference.md. The two reference docs are accurate, andfix/provider-load-time-memoryalso edits them.All invariants hold:
reclaimable= max(free + inactive, free − speculative +external_page_count+ purgeable).free-onlyis unchanged.hostOnePageCacheNoLongerBlocksTheGLMColdLoad,busySharedMacIsNeverStricterThanBefore, the anonymous/compressed tests,reclaimableIsTheLargerMeasureAndNeverMoreandlivePageCountsKeepTheMachPartitionkeep their assertions.Validation (SDK
baca4acf, isolatedDARKBLOOM_STATE_FILE/DARKBLOOM_LOADED_MODELS_FILE)mlx.metallib/default.metallibcopies. Then ranswift build --build-tests(Build complete) and../scripts/stage-test-metallib.sh <bin>(mlx.metallib156f2624…).../scripts/run-nested-suite.sh 'SystemMemory|GlobalKVCacheBudget|ModelLoadAdmission|ModelFit|UnifiedMemoryCap' --no-parallelran onced5723d9and again on the merged head94808688f:free-onlytestscohostReclaimablePagesCannotSatisfyFreeOnlyReserve,freeOnlySamplerFailsClosed,freeOnlyAtomicLoadClaimRejectsForeignReclaimCredit,freeOnlyRuntimeClaimCannotSpendReclaimableHeadroomandprocessBudgetFreeOnlyPolicyRejectsSharedHostLoadAndRechecks.SystemMemoryTests,SystemMemoryAdmissionTestsandGlobalKVCacheBudgetProcessTests: 12 / 3 / 9 tests and 43 / 11 / 66#expect/#requirecalls.053a69147, the logprobs refactor pass). Merge94808688fadds onlyEngineV2Bridge+Submission.swiftto this pass's tree. The rebuild and the focused suites above were rerun on it.make docs-check: 192 files OK.make docs-impact-check BASE=origin/master: 38 changed files, coverage OK.make changelog-check: 6 valid fragments.make changelog-preview: renders the page-cache fragment.57e3fb2ad. This pass changes no behavior.GPU wired-limit guidance
From
68267f0ae(feat(provider): give the macOS GPU wired-limit fix for GLM-5.3-Flash).What it does. GLM-5.3-Flash'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 Metal command buffers past it fail with "Insufficient Memory" (kIOGPUCommandBufferCallbackErrorOutOfMemory). The provider now tells the operator the fix the production hosts run. Recommended values:iogpu.wired_limit_mb= physical memory less 16 GiB =245760, and both user wire limits = 95% of physical memory =261134011596.Doctor WARN detail line (
glm wired limit, at macOS defaults):Fix command:
The
GLM-5.3-FLASH GPU WIRED-MEMORY LIMIT — ACTION RECOMMENDEDblock after the detailed checks also prints the current values and a copy-paste LaunchDaemon install (/Library/LaunchDaemons/com.layrlabs.glm53-wired-limits.plist, the production plist) that reapplies the values at boot. Once the values are set, the check is PASS and shows them. The check is doctor-only and is not inbuildDoctorChecks, sodarkbloom verifydoes not fail on it. No command runssudofor you.Where else it appears.
startprints the one-line fix as awarning:when it would serve GLM below the values.statusadds→ fix:under a GLM load error that reports the Metal out-of-memory text. When a GLM load, startup preload (new injectableStartupPreloaderonFailurehook), self-test or coordinator request fails with that text, the daemon logs the fix once per process to stderr, plus a fixed public line in the unified log. The error text is only matched, never logged. The provider's own lower-case "Insufficient memory for …" refusals never match.Scope. GLM-5.3-Flash only, on 256 GB M5 Macs only. The check applies when GLM is downloaded, selected in
[backend]or served. Other chips and sizes show nothing: at 512 GB the same rule would put the user wire limits below the GPU limit, which no host has run.No capacity change. This is advice only. Admission, KV grants and capacity never read it.
Known limitation. GLM's native engine can report its in-SDK GPU out-of-memory failures without the MLX text (readback faults show up only as
nativeWorkFailed), so the failure-time notice cannot match them.doctorandstartcheck the live limits beforehand, so they still flag the problem before any failure.Tests:
GLM5NextWiredLimitTests(derivation, default vs production limits, byte-exact plist, OOM matching vs provider refusals, notice mapping),GLMWiredLimitAdviceTests(doctor WARN/PASS/skip, GLM-in-use detection, start and status notices) and aStartupPreloadTestscase foronFailure.Refactor pass (wired-limit notice)
A dedicated refactor subagent reviewed
68267f0aeon headaad442436.Outcome: no change (justified). The diff is already small and well bounded:
GLM5NextWiredLimit(ProviderCore) owns the derivation, the sysctl/plist text and the OOM matcher.GLM5NextWiredLimitNoticeowns the once-per-process gate.GLMWiredLimitAdvice(CLI) owns the doctor, start and status presentation.ProviderLoop+InferenceHandler.swift, one inProviderLoop+Trust.swift), plus the defaultedonFailuredependency inStartupPreloaderand oneProviderOperationalMessagecase.Reviewed and kept:
reportedpre-check and the GLM model check inGLM5NextWiredLimitNotice.report. They look redundant withnotice(...), but they keep non-GLM failures and later failures from probing sysctl or Metal.Limits.live()is evaluated eagerly in doctor, start and status. Each runs once per command, and a lazy variant would only add API surface.#"…"#line-array plist builder. It reads clearly, and a test pins it byte-for-byte to the production plist.Invariants hold:
sudo.245760, and it is not inverify.Validation (fresh detached worktree at
aad442436, staged metallibs deleted before the build, isolatedDARKBLOOM_STATE_FILE/DARKBLOOM_LOADED_MODELS_FILE):swift build --build-tests: Build complete. Then../scripts/stage-test-metallib.sh <bin>(mlx.metallib156f2624…).../scripts/run-nested-suite.sh 'GLM5NextWiredLimit|GLMWiredLimitAdvice|StartupPreload|ProviderLogger|Doctor|Status' --no-parallelexited 0 with no skips. It ran 74 + 1 + 87 tests (Swift Testing + XCTest), including both wired-limit suites andStartupPreloader.StartupPreloadfilter also matches two MiMo strict-quote startup tests. They needMIMO_V26_SERIAL_LOAD_FIXTURES, so the fixtures were first prepared withscripts/prepare-mimo-provider-fixtures.py, as CI does. Without them, those two tests fail onXCTUnwrap. That failure is unrelated to this commit.aad442436.make docs-check: 192 files OK.make docs-impact-check BASE=origin/master: 78 changed files, coverage OK.make changelog-check: 8 valid fragments.Need help on this PR? Tag
@codesmith-botwith what you need.