From a400ded3c95fbc865025f7e6301853586ba9bf04 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:17:39 -0800 Subject: [PATCH 01/26] test(provider): `parallel_tool_calls: false` keeps the first call instead of failing (red) With `parallel_tool_calls: false`, a model that makes a second call fails the response: on the streamed `auto` path the first call has already left when `NativeToolStreamRouter.admitCall` throws `toolChoiceViolation` ("parallel tool calls are disabled for this request"), so the client sees a stream that errors mid-response; on the complete-call paths (and Nemotron Super's owner) the response is a 422. Nothing in the prompt asks the model for a single call. OpenAI returns at most one call and vLLM keeps the first (`maybe_filter_parallel_tool_calls`). These tests expect the first call to be returned and every later call to be dropped (valid, off-schema under `strict`, or undeclared), with no error. They fail on dev 6bc14de2c2; the Super HTTP case replaces the old 422 expectation. Co-Authored-By: Claude Opus 5.5 --- .../Streaming/StreamedToolCallTests.swift | 49 +++++++++++++++---- .../NemotronSuperMediaControlsHTTPTests.swift | 7 +-- 2 files changed, 43 insertions(+), 13 deletions(-) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift index 1f342836d9..837706d6f2 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift @@ -199,17 +199,46 @@ struct StreamedToolCallTests { #expect(call.completed?.function.name == "delete_everything") } - @Test func secondCallIsRefusedWhenParallelCallsAreDisabled() throws { - var router = try Self.router(Self.request(parallel: false)) - let first = Self.gemmaCall(#"location:<|"|>Paris<|"|>"#) - var exposed: [ServerToolCallDelta] = [] - for character in Self.characters(first) { exposed += Self.deltas(try router.process(character)) } - #expect(exposed.last?.completed != nil) - var thrown: Error? - for character in Self.characters(first) { - do { _ = try router.process(character) } catch { thrown = error; break } + /// `parallel_tool_calls: false` returns the first call, as OpenAI and vLLM + /// do. The calls the model makes after it, valid or not, are consumed and + /// dropped; none fails the stream after the first call already left. + @Test func laterCallsAreDroppedWhenParallelCallsAreDisabled() throws { + for strict in [false, true] { + let request = try Self.request(parallel: false, strict: strict) + var router = try Self.router(request) + let text = Self.gemmaCall(#"location:<|"|>Paris<|"|>"#) + + Self.gemmaCall(#"location:<|"|>Rome<|"|>,days:3"#) + + Self.gemmaCall(#"path:<|"|>a.py<|"|>,content:<|"|>x<|"|>"#, name: "write_file") + // Off the schema: `strict` would refuse it if it were returned. + + Self.gemmaCall(#"location:<|"|>Oslo<|"|>,unit:<|"|>kelvin<|"|>"#) + var events: [MLXServerGenerationEvent] = [] + for character in Self.characters(text) { events += try router.process(character) } + events += try router.finishText() + events += try router.finishToolCalls(truncated: false) + let deltas = Self.deltas(events) + #expect(events.count == deltas.count, "strict \(strict): no visible text from a dropped frame") + #expect(deltas.allSatisfy { $0.index == 0 }, "strict \(strict)") + #expect(deltas.compactMap(\.name) == ["get_weather"], "strict \(strict)") + #expect(deltas.compactMap(\.completed).map(\.function.arguments) == [["location": .string("Paris")]], + "strict \(strict)") + #expect(router.completedToolCalls.map(\.function.arguments) == [["location": .string("Paris")]]) + try ToolConstraintValidation.validate(router.completedToolCalls, + prepared: ToolChoicePromptPolicy.prepare(request, modelType: "gemma4")) } - #expect(thrown is MultiModelBatchSchedulerEngineError) + } + + /// A later call that completes without being exposed (a name the request + /// did not declare) is dropped too, before validation could refuse it. + @Test func laterUnexposedCallIsDroppedUnvalidated() throws { + var router = try Self.router(Self.request(parallel: false, strict: true), modelType: "qwen3_5") + let text = "\n\n\nParis\n\n\n\n" + + "\n\n\n/\n\n\n" + var events: [MLXServerGenerationEvent] = [] + for character in Self.characters(text) { events += try router.process(character) } + events += try router.finishText() + events += try router.finishToolCalls(truncated: false) + #expect(Self.deltas(events).compactMap(\.completed).map(\.function.name) == ["get_weather"]) + #expect(router.completedToolCalls.map(\.function.name) == ["get_weather"]) } /// The second partial holds a `}`, so Gemma's lenient EOS parse reads a diff --git a/provider-swift/Tests/ProviderCoreTests/Server/NemotronSuperMediaControlsHTTPTests.swift b/provider-swift/Tests/ProviderCoreTests/Server/NemotronSuperMediaControlsHTTPTests.swift index 52db79d382..19397a8aac 100644 --- a/provider-swift/Tests/ProviderCoreTests/Server/NemotronSuperMediaControlsHTTPTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Server/NemotronSuperMediaControlsHTTPTests.swift @@ -162,9 +162,10 @@ struct NemotronSuperMediaControlsHTTPTests { #expect(none.content == "Sunny." && none.toolCalls.isEmpty, "\(name)") #expect(!script.prompt.contains("get_weather") && script.prompt.contains("Do not call any tool."), "\(name)") - // `parallel_tool_calls: false` with two calls: the model broke the contract (422). - _ = try await send(body(media, Self.twoCalls, stream: false, - ["tools": [Self.weather], "parallel_tool_calls": false]), status: .unprocessableContent) + // `parallel_tool_calls: false` with two calls: the first is returned, as OpenAI and vLLM do. + let single = try SuperJSON(try await send(body(media, Self.twoCalls, stream: false, + ["tools": [Self.weather], "parallel_tool_calls": false]))) + #expect(single.toolCalls.map(\.arguments) == [#"{"city":"Paris"}"#], "\(name)") // Media in a tool result, which `native_media_tools` advertises. let result = try SuperJSON(try await send(toolResultBody(media, ["", "Sunny."]))) #expect(result.content == "Sunny.", "\(name)") From eb763093dac8b15136727241d7301517e7fabb16 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:18:33 -0800 Subject: [PATCH 02/26] test(provider): a stray in GLM output is text, not a 500 (red) GLM's tool parser withholds a response from its first `` to EOS and parses that suffix as one call batch. On the legacy text path it also reads the reasoning, so a `` the model only mentioned or drafted in its thought, or a text answer that mentions the tag, fails the batch, and `NativeToolStreamRouter.checkNativeToolFailure` turns that into generationFailed("native GLM tool output is invalid"): a 500 for the whole response. Production (OpenRouter, 72 h): 80 GLM tool requests ended this way, 55 cut mid-stream and 25 as HTTP 500 after 4-10 attempts. These tests pin the reference behaviour (vLLM's and SGLang's GLM parsers return unmatched markers as text): on an `auto` request the calls are the frames from the earliest `` whose rest parses to the end of the response, everything before them is text, and a suffix with no such rest is all text; a required call still fails closed (422); no call is completed, salvaged from a malformed final frame or split out of an output cut at the token limit. The conformance replay's shapes (a call drafted in the thought, a tag mentioned in the thought, a text answer that mentions it, clean calls) run through the production event stream, at 1- and 4096-character chunks. Red on dev 6bc14de2c2: the stray/unparsed `auto` cases fail with the 500. Co-Authored-By: Claude Opus 5.5 --- .../Streaming/GLM5ToolFailureTests.swift | 166 +++++++++++++++--- 1 file changed, 140 insertions(+), 26 deletions(-) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift index f231b7b081..25c90312d1 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift @@ -9,25 +9,119 @@ import Testing struct GLM5ToolFailureTests { private let valid = "echotextSAFE" + /// A malformed suffix commits no call. A required call fails (422); an + /// `auto` response returns the suffix as text instead of failing. @Test(arguments: [false, true], [1, 7, 4096]) func malformedSuffixNeverCommitsEarlierCall(forced: Bool, width: Int) async throws { - try await check(output: valid + "PRIVATE_STRAY", forced: forced, width: width, invalid: true) + let output = valid + "PRIVATE_STRAY" + let result = try await run(output, forced: forced, width: width) + try expectUnparsed(result, output: output, forced: forced) } @Test(arguments: [false, true]) func truncatedSecondCallNeverCommitsEarlierCall(forced: Bool) async throws { - try await check(output: valid + "echotext", forced: forced, width: 1, invalid: true) + let output = valid + "echotext" + let result = try await run(output, forced: forced, width: 1) + try expectUnparsed(result, output: output, forced: forced) } @Test(arguments: [false, true]) func validCallSurvives(forced: Bool) async throws { - try await check(output: valid, forced: forced, width: 1, invalid: false) + let result = try await run(valid, forced: forced, width: 1) + #expect(result.failure == nil) + #expect(result.calls.map(\.function.name) == ["echo"]) + #expect(result.visible.isEmpty) } @Test(arguments: [false, true]) func oversizedFrameFailsBeforeFallback(forced: Bool) async throws { - try await check(output: "echo" + String(repeating: "x", count: (1 << 20) + 1), - forced: forced, width: 65536, invalid: true) + let output = "echo" + String(repeating: "x", count: (1 << 20) + 1) + let result = try await run(output, forced: forced, width: 65536) + try expectUnparsed(result, output: output, forced: forced) + } + + /// The model's raw output after the prompt's open `` (the legacy + /// text path: the tool parser also reads the reasoning), the calls an + /// `auto` response returns, and its visible text, which the service's + /// reasoning parser then splits at ``. Shapes from the + /// conformance replay: a tag mentioned or a call drafted in the thought, a + /// text answer that mentions the tag, clean calls. + static let strayCases: [(name: String, output: String, calls: [String], visible: String)] = { + let call = "echotextSAFE" + let other = "echotextMORE" + let draft = "echotextDRAFT" + return [ + ("call", "Need it." + call, ["SAFE"], "Need it."), + ("call drafted in the thought", "I'll do " + draft + " maybe." + call, ["SAFE"], + "I'll do " + draft + " maybe."), + ("tag mentioned in the thought", "Wrap it in tags." + call, ["SAFE"], + "Wrap it in tags."), + ("tag mentioned in the thought, text answer", + "The tool would need syntax, but I can answer.Zürich is cool.", [], + "The tool would need syntax, but I can answer.Zürich is cool."), + ("text answer mentions the tag", "Simple.To call a tool, GLM writes first.", [], + "Simple.To call a tool, GLM writes first."), + ("answer quotes a frame, then calls", + "Simple.The format is … . Calling: " + call, ["SAFE"], + "Simple.The format is … . Calling: "), + ("two calls", "Two." + call + "\n" + other, ["SAFE", "MORE"], "Two."), + ("call from an unclosed thought", "Need it." + call, ["SAFE"], "Need it."), + ("call drafted in the thought, no call", "I'd do " + draft + "", [], + "I'd do " + draft + ""), + ("tag mentioned before two calls", "Use ." + call + " " + other + "\n", + ["SAFE", "MORE"], "Use ."), + ] + }() + + @Test(arguments: GLM5ToolFailureTests.strayCases.indices, [1, 4096]) + func strayToolTagsAreTextAndTheFinalCallsParse(index: Int, width: Int) async throws { + let shape = Self.strayCases[index] + let result = try await run(shape.output, forced: false, width: width) + #expect(result.failure == nil, "\(shape.name)") + #expect(result.calls.count == shape.calls.count, "\(shape.name)") + #expect(result.calls.compactMap { $0.function.arguments["text"]?.anyValue as? String } == shape.calls, + "\(shape.name)") + #expect(result.visible == shape.visible, "\(shape.name)") + } + + /// A required call keeps failing closed when its suffix does not parse. + @Test func forcedChoiceStillRefusesAStraySuffix() async throws { + let result = try await run("Wrap it in tags." + valid, forced: true, width: 1) + #expect(result.calls.isEmpty && result.visible.isEmpty) + #expect(result.failure == .toolChoiceViolation("native GLM tool output is invalid")) + } + + /// The delimiters quoted inside a JSON argument are data: the calls start + /// at the real frame, not at a quoted tag. + @Test func quotedDelimitersStayArgumentData() async throws { + let tool = #"{"type":"function","function":{"name":"store","parameters":{"type":"object","properties":{"doc":{"type":"object"}},"required":["doc"]}}}"# + let output = "See here.storedoc" + + #"{"x":"store"}"# + let result = try await run(output, forced: false, width: 3, tool: tool) + #expect(result.failure == nil) + #expect(result.calls.count == 1) + #expect(result.calls.first?.function.arguments["doc"] == .object(["x": .string("store")])) + #expect(result.visible == "See here.") + } + + /// An undeclared or malformed final call is not salvaged: the response is + /// text, as are its earlier calls. + @Test func malformedFinalCallIsText() async throws { + let output = "Use ." + valid + + "nopetexta" + let result = try await run(output, forced: false, width: 5) + #expect(result.failure == nil) + #expect(result.calls.isEmpty) + #expect(result.visible == output) + } + + /// Calls are never split out of an output the token limit cut off. + @Test func truncatedOutputIsNotSplit() async throws { + let output = "Wrap it in tags." + valid + let result = try await run(output, forced: false, width: 4, finishReason: "length") + #expect(result.failure == nil) + #expect(result.calls.isEmpty) + #expect(result.visible == output) } /// Forced choice is served by structured post-validation: the production @@ -49,8 +143,37 @@ struct GLM5ToolFailureTests { } } - private func check(output: String, forced: Bool, width: Int, invalid: Bool) async throws { - let request = try MiMoConsumerFixture.request(choice: forced ? #""required""# : #""auto""#) + private struct Result { + var calls: [ToolCall] = [] + var visible = "" + var failure: MultiModelBatchSchedulerEngineError? + } + + /// A required call fails closed (422); an `auto` response returns the + /// unparsed suffix as text, with no call and no failure. + private func expectUnparsed(_ result: Result, output: String, forced: Bool) throws { + #expect(result.calls.isEmpty) + if forced { + #expect(result.visible.isEmpty) + #expect(result.failure == .toolChoiceViolation("native GLM tool output is invalid")) + if let failure = result.failure { #expect(ProviderLoop.mapInferenceErrorToStatus(failure) == 422) } + } else { + #expect(result.failure == nil) + #expect(result.visible == output) + } + } + + /// The production event stream on the legacy text path (no native + /// channel), fed `width` characters at a time. + private func run(_ output: String, forced: Bool, width: Int, finishReason: String? = nil, + tool: String? = nil) async throws -> Result { + var request = try MiMoConsumerFixture.request(choice: forced ? #""required""# : #""auto""#) + if let tool { + var body = try #require(JSONSerialization.jsonObject(with: MiMoConsumerFixture.body( + choice: #""auto""#)) as? [String: Any]) + body["tools"] = [try JSONSerialization.jsonObject(with: Data(tool.utf8))] + request = try ProviderLoop.decodeOpenAIRequest(JSONSerialization.data(withJSONObject: body)) + } let prepared = try ToolChoicePromptPolicy.prepare(request, modelType: "glm5_next") let handler = try #require(try ToolStreamPreparation.makeHandler( request: request, prepared: prepared, modelType: "glm5_next")) @@ -60,36 +183,27 @@ struct GLM5ToolFailureTests { for start in stride(from: 0, to: chars.count, by: width) { continuation.yield(.chunk(String(chars[start.. Date: Thu, 12 Nov 2026 21:24:28 -0800 Subject: [PATCH 03/26] test(provider): Qwen3.5-9B keeps the card's presence penalty; a rollback switch (red) 9B-MIDFAIL (11-12): with provider 0.10.12 the catalog Qwen3.5-9B lost the model card's presence_penalty 1.5 (#1961). In production, in the same 10-minute windows as 0.10.11 Macs, its JSON response_format answers ran to max_tokens and failed about twice as often (51 % against 23 % on the 4,096-token workload; Mantel-Haenszel odds ratio 3.1), and answers with a max_tokens of 8,192 or more hit it 6.1 % of the time against 1.5 %. A registry presence_penalty 1.5 (2026-11-12 19:17Z) brought both back. Those JSON rows never speculate (a token constraint), so neither MTP acceptance nor the template differs for them between the two releases: the penalty is the difference. Red on dev: - qwen35CatalogBuildsUseTheirModelCardDefaults and qwen35OmittedPresencePenaltyFollowsEachBuildsGate expect 1.5 on the 9B. - qwen35NineBPresencePenaltyRollbackSwitch: DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0/off/false restores 0.10.12's no-penalty default on the 9B alone; anything else keeps the card's. - qwen35NineBPenaltySwitchReachesTheDaemon: `darkbloom start` passes it to the launchd daemon. Only the API surface the tests name is added (the key constant and an environment parameter, unused); behaviour is unchanged. --- .../Engine/EngineV2SamplingDefaults.swift | 4 +- .../EngineV2SamplingDefaultsTests.swift | 78 ++++++++++++++----- 2 files changed, 63 insertions(+), 19 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift index 5f977d1730..d37790f7f2 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift @@ -82,6 +82,7 @@ public struct EngineV2SamplingDefaults: Sendable, Equatable { static let qwen35NineBCardDefaults = EngineV2SamplingDefaults( temperature: 1.0, topP: 0.95, topK: 20) static let qwen35NineBModelID = "Qwen3.5-9B" + static let qwen35NineBPenaltyEnvironmentKey = "DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY" static let qwen35CardModelTypes = [ "Qwen3.5-9B": "qwen3_5", "qwen3.5-35b-a3b": "qwen3_5_moe", @@ -112,7 +113,8 @@ public struct EngineV2SamplingDefaults: Sendable, Equatable { /// the checkpoint directory is unknown, the file is absent or /// unreadable, or the artifact declares `do_sample: false`. static func resolve( - modelId: String, modelType: String?, modelDirectory: URL? + modelId: String, modelType: String?, modelDirectory: URL?, + environment: [String: String] = ProcessInfo.processInfo.environment ) -> EngineV2SamplingDefaults { if let type = qwen35CardModelTypes[modelId], type == modelType { return modelId == qwen35NineBModelID ? qwen35NineBCardDefaults : qwen35CardDefaults diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift index 4d4e8836fc..90e5e30c25 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift @@ -83,18 +83,18 @@ struct EngineV2SamplingDefaultsTests { } /// The catalog Qwen 3.5/3.6 builds have no generation_config.json: omitted - /// knobs take the model cards' thinking-mode values, explicit ones win. + /// knobs take the model cards' thinking-mode values, the presence penalty + /// 1.5 included, on every build; explicit ones win. @Test func qwen35CatalogBuildsUseTheirModelCardDefaults() throws { for (id, type) in EngineV2SamplingDefaults.qwen35CardModelTypes { - #expect(EngineV2SamplingDefaults.resolve(modelId: id, modelType: type, modelDirectory: nil) - == (id == "Qwen3.5-9B" ? EngineV2SamplingDefaults(temperature: 1.0, topP: 0.95, topK: 20) - : EngineV2SamplingDefaults.qwen35CardDefaults)) + #expect(EngineV2SamplingDefaults.resolve(modelId: id, modelType: type, modelDirectory: nil, environment: [:]) + == EngineV2SamplingDefaults(temperature: 1.0, topP: 0.95, topK: 20, presencePenalty: 1.5), "\(id)") } let defaults = EngineV2SamplingDefaults.resolve( - modelId: "Qwen3.5-9B", modelType: "qwen3_5", modelDirectory: nil) + modelId: "Qwen3.5-9B", modelType: "qwen3_5", modelDirectory: nil, environment: [:]) let omitted = EngineV2Translation.samplingParams(from: try request(bareRequest), defaults: defaults) #expect(omitted.temperature == 1 && omitted.topP == 0.95 && omitted.topK == 20) - #expect(omitted.presencePenalty == 0 && omitted.repetitionPenalty == 1) + #expect(omitted.presencePenalty == 1.5 && omitted.repetitionPenalty == 1) let explicit = EngineV2Translation.samplingParams( from: try request(#"{"model":"m","messages":[],"temperature":0,"presence_penalty":0}"#), defaults: defaults) @@ -104,27 +104,27 @@ struct EngineV2SamplingDefaultsTests { } } - /// The 0.10.12 gate on the signed 0.10.11 (temperature 1, top_p 0.95, - /// top_k 20) decided each build's omitted presence penalty. Without the - /// cards' 1.5, qwen3.5-35b-a3b looped under both MTP acceptance rules, so - /// the two 35B builds (one architecture) keep it. Qwen3.5-9B looped only - /// under typical acceptance and not under exact (13 against 0 of 31 draws - /// with MTP running), so it has no default penalty (its rows can speculate - /// and stage prefix checkpoints) and takes exact acceptance - /// (MTPAcceptancePolicy). The coordinator's body adds the registry's - /// temperature, top_p and top_k, and no penalty unless the registry sets - /// one. A request's own presence_penalty wins on every build. + /// Every catalog Qwen 3.5/3.6 build keeps the cards' 1.5 for a request + /// that omits the penalty. Without it qwen3.5-35b-a3b looped under both MTP + /// acceptance rules in the 0.10.12 gate. Qwen3.5-9B passed that gate under + /// exact acceptance (0 of 31 draws), so 0.10.12 dropped its penalty; in + /// production its answers then ran to `max_tokens` about three times as + /// often, and its JSON `response_format` answers (rows that never + /// speculate) ran out about twice as often as on 0.10.11 in the same hour + /// (9B-MIDFAIL). The coordinator's body adds the registry's temperature, + /// top_p and top_k, and the penalty only where the registry sets one. A + /// request's own presence_penalty wins on every build. @Test func qwen35OmittedPresencePenaltyFollowsEachBuildsGate() throws { let coordinatorBody = #"{"model":"m","messages":[{"role":"user","content":"hi"}],"temperature":1,"top_p":0.95,"top_k":20}"# let builds: [(id: String, type: String, penalty: Float)] = [ - ("Qwen3.5-9B", "qwen3_5", 0), + ("Qwen3.5-9B", "qwen3_5", 1.5), ("qwen3.5-35b-a3b", "qwen3_5_moe", 1.5), ("qwen3.6-35b-a3b-vl-mtp-mxfp8", "qwen3_5_moe", 1.5), ] for build in builds { let defaults = EngineV2SamplingDefaults.resolve( - modelId: build.id, modelType: build.type, modelDirectory: nil) + modelId: build.id, modelType: build.type, modelDirectory: nil, environment: [:]) for body in [bareRequest, coordinatorBody] { let sampling = EngineV2Translation.samplingParams(from: try request(body), defaults: defaults) #expect(sampling.temperature == 1 && sampling.topP == 0.95 && sampling.topK == 20, "\(build.id)") @@ -140,6 +140,48 @@ struct EngineV2SamplingDefaultsTests { } } + /// `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` (or `off`, `false`) restores + /// 0.10.12's no-penalty default on Qwen3.5-9B alone; anything else keeps + /// the card's 1.5, and the 35B builds ignore it. A request's own value + /// still wins under the rollback. + @Test func qwen35NineBPresencePenaltyRollbackSwitch() throws { + let key = EngineV2SamplingDefaults.qwen35NineBPenaltyEnvironmentKey + #expect(key == "DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY") + func nineB(_ environment: [String: String]) -> EngineV2SamplingDefaults { + EngineV2SamplingDefaults.resolve( + modelId: "Qwen3.5-9B", modelType: "qwen3_5", modelDirectory: nil, environment: environment) + } + let card = EngineV2SamplingDefaults(temperature: 1.0, topP: 0.95, topK: 20, presencePenalty: 1.5) + let noPenalty = EngineV2SamplingDefaults(temperature: 1.0, topP: 0.95, topK: 20) + for value in ["0", "off", "false", " OFF\n", "False"] { + #expect(nineB([key: value]) == noPenalty, "\(value)") + } + for value in ["", "1", "on", "true", "1.5", "card", "no"] { + #expect(nineB([key: value]) == card, "\(value)") + } + #expect(nineB([:]) == card) + let rolledBack = EngineV2Translation.samplingParams(from: try request(bareRequest), defaults: nineB([key: "0"])) + #expect(rolledBack.presencePenalty == 0 && rolledBack.temperature == 1) + let ownUnderRollback = EngineV2Translation.samplingParams( + from: try request(#"{"model":"m","messages":[],"presence_penalty":1.5}"#), defaults: nineB([key: "0"])) + #expect(ownUnderRollback.presencePenalty == 1.5) + for (id, type) in [("qwen3.5-35b-a3b", "qwen3_5_moe"), ("qwen3.6-35b-a3b-vl-mtp-mxfp8", "qwen3_5_moe")] { + #expect(EngineV2SamplingDefaults.resolve( + modelId: id, modelType: type, modelDirectory: nil, environment: [key: "0"]) == card, "\(id)") + } + // Other families never read it. + #expect(EngineV2SamplingDefaults.resolve( + modelId: "mlx-community/Qwen3.5-397B", modelType: "qwen3_5", modelDirectory: nil, + environment: [key: "on"]) == .legacy) + } + + @Test("darkbloom start passes the 9B penalty rollback switch to the launchd daemon") + func qwen35NineBPenaltySwitchReachesTheDaemon() { + let key = EngineV2SamplingDefaults.qwen35NineBPenaltyEnvironmentKey + #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(key)) + #expect(LaunchAgent.passthroughEnvironment(from: [key: "0"])[key] == "0") + } + /// The exact locally qualified GLM artifact declares temperature 1.0 and /// top_p 0.95 without `do_sample`; other GLM IDs or types stay legacy. @Test func gateAdmitsOnlyTheQualifiedGLMArtifact() throws { From 37f0e6277ac994b4c4f1ef39cbeef75bb61ade1e Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:28:43 -0800 Subject: [PATCH 04/26] fix(provider): Qwen3.5-9B keeps the model card's presence penalty; a rollback switch The 0.10.12 regression in 9B-MIDFAIL: #1961 dropped the catalog Qwen3.5-9B's default presence_penalty (the model card's 1.5) on the strength of a 31-draw gate. In production the 9B's answers then ran to max_tokens about three times as often, and its JSON response_format answers ran out about twice as often as on 0.10.11 in the same hour. Those JSON rows never speculate (a token constraint), and the 9B's template and JSON constraint are unchanged since 0.10.4. So the difference is the penalty itself, not MTP acceptance or the template. A registry presence_penalty 1.5 restored both from 2026-11-12 19:17Z. - EngineV2SamplingDefaults: every catalog Qwen 3.5/3.6 build, the 9B included, takes qwen35CardDefaults (T 1, top_p 0.95, top_k 20, presence penalty 1.5) for omitted knobs. A request's own value, the coordinator's registry default included, still wins. - DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY: 0/off/false/no restores 0.10.12's no-penalty default on the 9B alone (qwen35NineBNoPenaltyDefaults). It is read at slot construction from the factory's environment, and LaunchAgent.inferencePassthroughEnvKeys carries it to the launchd daemon. - MTPAcceptancePolicy: unchanged. The 9B's built-in rule stays exact for the rows that still draft (presence_penalty 0 or the rollback). - A penalty row does not speculate. It still donates prefix checkpoints (Qwen35CardDefaultDonationTests now serves the 9B on its own default). - The red test's rollback list gains "no", as the repo's other switches accept it. - Docs: inference.md (the sampling table, the Qwen defaults table, the acceptance rule), prefix-cache.md invariant 9, configuration.md (the new switch). Changelog fragment. --- .../qwen35-9b-card-presence-penalty.md | 5 ++ docs/architecture/inference.md | 40 +++++++------- docs/architecture/prefix-cache.md | 2 +- docs/reference/configuration.md | 1 + .../Engine/EngineV2SamplingDefaults.swift | 55 ++++++++++++++----- .../Engine/Factory/EngineV2SlotFactory.swift | 3 +- .../Inference/MTP/MTPAcceptancePolicy.swift | 6 +- .../ProviderCore/Service/LaunchAgent.swift | 3 + .../EngineV2SamplingDefaultsTests.swift | 6 +- .../Qwen35CardDefaultDonationTests.swift | 19 +++---- 10 files changed, 89 insertions(+), 51 deletions(-) create mode 100644 changelog.d/qwen35-9b-card-presence-penalty.md diff --git a/changelog.d/qwen35-9b-card-presence-penalty.md b/changelog.d/qwen35-9b-card-presence-penalty.md new file mode 100644 index 0000000000..8ecb4ef6fb --- /dev/null +++ b/changelog.d/qwen35-9b-card-presence-penalty.md @@ -0,0 +1,5 @@ +### Qwen 3.5 9B keeps its model card's presence penalty + +- Provider 0.10.12 dropped the default `presence_penalty` of 1.5 from the catalog `Qwen3.5-9B` for requests that send none. In production its answers then ran to `max_tokens` about three times as often, and JSON `response_format` answers that ran out failed about twice as often. 0.10.13 restores the model card's 1.5 for those requests, as on the other catalog Qwen 3.5/3.6 builds. +- A request that sends its own `presence_penalty` is unchanged. With `presence_penalty` 0 the 9B still speculates under exact MTP acceptance. A penalty row does not speculate but still donates prefix-cache checkpoints. +- `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` (or `off`) restores 0.10.12's default. `darkbloom start` passes it to the launchd job. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index a88327753d..9c20afafd0 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -2958,7 +2958,9 @@ When neither a global nor a per-model acceptance value is configured, serving defaults to typical acceptance for eligible sampled target-prefix rows, except on the builds whose built-in rule is exact (`MTPAcceptancePolicy.builtInIsExact`): the owned Bonsai 9B candidate; the catalog `Qwen3.5-9B`, which looped under -typical acceptance in the 0.10.12 gate (see the Qwen 3.5/3.6 defaults below); +typical acceptance in the 0.10.12 gate (its default carries the card's presence +penalty again, so only its rows with `presence_penalty` 0 draft; see the Qwen +3.5/3.6 defaults below); the catalog `gemma-4-26b-qat-4bit`, which drafted every answer of OpenRouter's 10-31 GPQA run, 30 % of which ended at the 32,768-token cap; and every Qwen 3.8 27B build (`EigenLabs/Qwen3.8-27B-4bit-mtp` and its head-less target, @@ -3095,7 +3097,7 @@ production assembly and encrypted store. | `top_p` | `topP` | artifact default, else `1.0` | | `top_k` | `topK` | artifact default, else `0` | | `repetition_penalty` | `repetitionPenalty` | artifact default, else `1.0` | -| `frequency_penalty` / `presence_penalty` | `frequencyPenalty` / `presencePenalty` | `0`; `presence_penalty` takes a model-card default on the catalog 35B Qwen 3.5/3.6 builds (`Qwen3.5-9B` has none) | +| `frequency_penalty` / `presence_penalty` | `frequencyPenalty` / `presencePenalty` | `0`; `presence_penalty` takes the model card's 1.5 on the catalog Qwen 3.5/3.6 builds (`DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` drops it on `Qwen3.5-9B`) | | `seed` | `seed`; also keys a stable engine request id | nil | | `logit_bias` | `logitBias` — string keys parsed to non-negative `Int`; invalid keys dropped and counted | `[:]` | | `logprobs` + `top_logprobs` | `topLogprobs = logprobs ? min(20, max(1, top_logprobs ?? 0)) : 0` | `0` | @@ -3153,29 +3155,27 @@ The catalog `Qwen3.5-9B`, `qwen3.5-35b-a3b` and `qwen3.6-35b-a3b-vl-mtp-mxfp8` builds (`EngineV2SamplingDefaults.qwen35CardModelTypes`, each bound to its `model_type`) take their model cards' thinking-mode values for omitted knobs: `temperature 1.0`, `top_p 0.95`, `top_k 20`. Greedy decoding made them repeat -themselves until `max_tokens` (#1530). The cards' `presence_penalty 1.5` is a -per-build default, set by the 0.10.12 gate on the signed 0.10.11 (temperature 1 -/ 0.95 / 20; #1652's four loopers and five tool transcripts at 32,768 tokens and -nineteen everyday prompts at 8,192, three seeds each; the Studio M3 Ultra for -the 9B, an M5 Ultra for the 35B): +themselves until `max_tokens` (#1530). Every build also takes the cards' +`presence_penalty 1.5` for a request that omits one (`qwen35CardDefaults`): -| Build | Omitted `presence_penalty` | Built-in MTP acceptance | The gate without the penalty | +| Build | Omitted `presence_penalty` | Built-in MTP acceptance | Without the penalty | |---|---|---|---| -| `qwen3.5-35b-a3b`, `qwen3.6-35b-a3b-vl-mtp-mxfp8` (`qwen35CardDefaults`) | 1.5 | typical | `qwen3.5-35b-a3b` ran away under typical acceptance (5 of 19 everyday prompts, 8 of 12 loopers to 32,768, MTP running at concurrency 1) and under exact (2 of 12 loopers); the 3.6 build shares its architecture | -| `Qwen3.5-9B` (`qwen35NineBCardDefaults`) | none | **exact** (`MTPAcceptancePolicy.builtInIsExact`) | ran away on 13 of 31 draws under typical acceptance and on 0 of 31 under exact, MTP running; the penalty-free body cached 8,192 tokens on the second send, the penalty body none | +| `qwen3.5-35b-a3b`, `qwen3.6-35b-a3b-vl-mtp-mxfp8` | 1.5 | typical | The 0.10.12 gate on the signed 0.10.11 (temperature 1 / 0.95 / 20; #1652's four loopers and five tool transcripts at 32,768 tokens, nineteen everyday prompts at 8,192, three seeds each; an M5 Ultra): `qwen3.5-35b-a3b` ran away under typical acceptance (5 of 19 everyday prompts, 8 of 12 loopers to 32,768, MTP running at concurrency 1) and under exact (2 of 12 loopers); the 3.6 build shares its architecture | +| `Qwen3.5-9B` | 1.5; none under `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` (`qwen35NineBNoPenaltyDefaults`, 0.10.12's default) | **exact** (`MTPAcceptancePolicy.builtInIsExact`) | The same gate (the Studio M3 Ultra) saw it run away on 13 of 31 draws under typical acceptance and on 0 of 31 under exact, so 0.10.12 shipped it without the penalty. In production that was a regression. On 2026-11-12, on 0.10.12 Macs against 0.10.11 Macs (the penalty, MTP off) in the same 10-minute windows, answers with `max_tokens` ≥ 8,192 hit the cap on 6.1 % against 1.5 %. On the 4,096-token JSON `response_format` workload, answers ran out and failed in 51 % of requests against 23 %. Those rows never speculate (a token constraint) and their template is unchanged since 0.10.4, so the penalty alone made the difference. A registry `presence_penalty` 1.5 brought both back within the hour | A row with a penalty does not speculate (`EngineLoopV2.mtpBasicEligible`), so -the 35B builds' requests that omit the penalty stay without MTP, the cost the -gate accepted for loop safety; they still stage prefix checkpoints +these builds' requests that omit the penalty stay without MTP, the cost taken +for loop safety. They still stage prefix checkpoints ([prefix caching](prefix-cache.md#invariants), invariant 9). A request's own -`presence_penalty` always wins: `0` on a 35B build speculates under typical -acceptance and donates checkpoints (the configuration that looped in the gate, -now the caller's choice); a nonzero value on the 9B turns its MTP off for that -request (it still donates checkpoints). The coordinator forwards a build's -registry runtime defaults for the fields a request omits -([`requestRuntimeDefaultKeys`](https://github.com/Layr-Labs/darkbloom-platform/blob/c69380d91fd3f9e4ef3ff1e3775690d80adbbe57/coordinator/api/inference/request/model_runtime_defaults.go)); -on 2026-11-10 the registry set `temperature`, `top_p` and `top_k` for these -builds and no `presence_penalty`, so the provider default above decides it. +`presence_penalty` always wins: `0` speculates (typical acceptance on the 35B +builds, the configuration that looped in the gate; exact on the 9B) and donates +checkpoints. The coordinator forwards a build's registry runtime defaults for +the fields a request omits +([`requestRuntimeDefaultKeys`](https://github.com/Layr-Labs/darkbloom-platform/blob/a9c111db3e235fa979a914d6a46bf93cba8e4268/coordinator/api/inference/request/model_runtime_defaults.go), +`presence_penalty` included). Since 2026-11-12 19:17Z the registry sets +`presence_penalty` 1.5 on `Qwen3.5-9B`, which reaches 0.10.12 Macs too; to +the provider it is the request's own value, so `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` +changes nothing while the registry sets it. Other model identities keep the legacy defaults in the table byte-for-byte. `do_sample: false` or an absent/unreadable file is legacy. The sampler is not part of prompt or cache identity, so prefix-cache and SSD diff --git a/docs/architecture/prefix-cache.md b/docs/architecture/prefix-cache.md index f8fa6dd092..42e9a44592 100644 --- a/docs/architecture/prefix-cache.md +++ b/docs/architecture/prefix-cache.md @@ -964,7 +964,7 @@ rules applied to these signals. text request that cannot speculate (a token constraint, logprobs, `logit_bias`, a repetition, frequency or presence penalty, a `stop` string: `EngineLoopV2.mtpBasicEligible`), including a Qwen request with the card's - presence penalty (the 35B builds' default), records the head's history over + presence penalty (every catalog Qwen 3.5/3.6 build's default), records the head's history over its prompt chunks. It therefore stages the same resident and SSD checkpoints a speculating request stages, byte for byte. It never drafts, verifies or seeds a carry, and its history is released once its prompt diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 6bf4cd8d16..3970fa8dbd 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -560,6 +560,7 @@ and rollback are defined in the [provider configuration reference](../provider/c | `DARKBLOOM_PREFILL_DEADLINE_MODE` | exactly `off` disables; any other value enforces | `enforce` | `provider-swift/Sources/ProviderCore/Inference/Engine/PrefillDeadlineMode.swift` (`PrefillDeadlineMode.resolve`) | Prefill-deadline admission on the provider. Read only when `[backend] prefill_deadline_mode` is absent from `provider.toml`; that key takes precedence. | | `DARKBLOOM_TTFT_ADMISSION_FIXES` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`DeadlineAdmissionFixes`) | Deadline-admission estimator corrections: per-batch decode charging, anchored isolated-prefill rate, newest-observation freshness, a probe that re-measures stale isolated-prefill evidence after three refusals it explains. Off restores the previous estimators and turns that probe off too. Forwarded to the launchd provider job. | | `DARKBLOOM_TTFT_REFUSAL_PROBE` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`DeadlineRefusalProbe`) | The refusal streak's idle probe alone ([deadlines](../architecture/inference.md#deadlines)): off, refusals neither count nor start a probe, and the estimator corrections stay on. Forwarded to the launchd provider job. | +| `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY` | trimmed, case-insensitive `0`, `false`, `no`, `off` drop the default; any other value keeps it | on: the model card's 1.5 | `provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift` (`qwen35NineBKeepsCardPenalty`) | The catalog `Qwen3.5-9B`'s `presence_penalty` for a request that omits one (0.10.13; 0.10.12 had none, and its answers ran to `max_tokens` about three times as often). `0` restores 0.10.12's no-penalty default. A request's own value, the coordinator's registry default included, always wins. `darkbloom start` passes it to the launchd job. | | `DARKBLOOM_TTFT_SHAPE_WARMUP` | trimmed, case-insensitive `0`, `false`, `no`, `off` disable; `always` skips the probe | unset: probe-gated warmup | `provider-swift/Sources/ProviderCore/Inference/Performance/ModelCalibrationPolicy.swift` (`shapeWarmupMode`) | Excluded load-time [shape warmup](../architecture/inference.md#model-startup-calibration) for ordinary `EngineV2` slots: a 128-token shader-cache probe runs twice and only a cold cache runs the shape cells, within 20 seconds per engine. Trains no rate or counter. Forwarded to the LaunchAgent. | | `DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL` | integer layers | projected from `provider.toml` (`18`) | `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift` | Gemma-4 prefill chunk-eval layers; the provider sets it for the engine, `scripts/install.sh` sets `18` for the smoke test. | | `DARKBLOOM_TTFT_GDN_BLOCKED` | `0`, `false`, `no`, `off` keep the stock kernel; `packed` or `rows` force that kernel; unset or any other value probes. Case-insensitive; surrounding whitespace is ignored | probe | `libs/mlx-swift-lm/Libraries/MLXLMCommon/GatedDelta.swift` (`GatedDeltaPrefill.mode`, `GatedDeltaPrefill.kernel`) | Selects the Gated DeltaNet prompt-window kernel of `qwen3_5`, `qwen3_5_moe` and `prism_hadamard_qwen35` models ([mechanism](../architecture/inference.md#context)). The default probe keeps a four-row kernel only where it reproduces `gated_delta_step` bit for bit on the GPU; it does not compare speed, so `0` is the rollback where a kept kernel is slower. Forced kernels skip that check and are for A/B measurement only. Decode, MTP verification and masked updates always use the stock kernel. Read once per process. Forwarded to the LaunchAgent. | diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift index d37790f7f2..c7f07baf16 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift @@ -23,10 +23,11 @@ // identities (catalog `glm-5.3-flash` and the local qualification download) // honor their artifact defaults. // The catalog Qwen 3.5/3.6 builds take their model cards' thinking-mode -// values instead of the greedy decoding that looped to `max_tokens`. The -// 35B builds keep the cards' presence penalty (`qwen35CardDefaults`); -// Qwen3.5-9B has none (`qwen35NineBCardDefaults`), as the 0.10.12 gate -// decided per build. +// values instead of the greedy decoding that looped to `max_tokens`, +// including the cards' presence penalty 1.5 (`qwen35CardDefaults`). +// 0.10.12 dropped it on Qwen3.5-9B, whose answers then ran to +// `max_tokens` about three times as often in production; 0.10.13 gives it +// back (`DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` is the rollback). // Every other model keeps the legacy defaults byte-for-byte. // * `do_sample: false` in the file means greedy (legacy), matching HF // semantics; an absent or unreadable file is legacy. @@ -70,19 +71,41 @@ public struct EngineV2SamplingDefaults: Sendable, Equatable { public static let legacy = EngineV2SamplingDefaults() /// The model cards' thinking-mode values (the template default), shared by - /// these exact catalog builds and their `model_type`. The 35B builds keep - /// the cards' presence penalty: without it qwen3.5-35b-a3b looped under - /// typical and exact MTP acceptance alike. + /// these exact catalog builds and their `model_type`, with the cards' + /// presence penalty. Without it qwen3.5-35b-a3b looped under typical and + /// exact MTP acceptance alike, and Qwen3.5-9B's answers ran on to + /// `max_tokens` (`qwen35NineBNoPenaltyDefaults`). A penalty row does not + /// speculate; it still stages the prefix checkpoints a speculating row + /// stages. static let qwen35CardDefaults = EngineV2SamplingDefaults( temperature: 1.0, topP: 0.95, topK: 20, presencePenalty: 1.5) - /// Qwen3.5-9B's: the same values without the penalty. Without it the 9B - /// looped only under typical MTP acceptance, and its built-in rule is exact - /// (`MTPAcceptancePolicy`); a penalty would keep its rows from speculating - /// (they would still stage prefix checkpoints). - static let qwen35NineBCardDefaults = EngineV2SamplingDefaults( + /// Qwen3.5-9B under `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0`: the card's + /// values without the penalty, 0.10.12's default. Its 31-draw gate saw no + /// loop under exact acceptance. In production (0.10.12 against 0.10.11 in + /// the same hour) its answers ran to `max_tokens` about three times as + /// often, and its JSON `response_format` answers, rows that never + /// speculate (a token constraint), ran out about twice as often: the + /// penalty alone made that difference. The registry's `presence_penalty` + /// 1.5 restored it on 2026-11-12. + static let qwen35NineBNoPenaltyDefaults = EngineV2SamplingDefaults( temperature: 1.0, topP: 0.95, topK: 20) static let qwen35NineBModelID = "Qwen3.5-9B" + + /// `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY`: unset (or `1`, `on`, `true`) + /// keeps the card's 1.5 for Qwen3.5-9B requests that omit a presence + /// penalty; `0`, `off`, `false` or `no` restores 0.10.12's no-penalty + /// default. + /// Any other value keeps the card's. Only the 9B reads it. A request's own + /// `presence_penalty`, the coordinator's registry default included, always + /// wins. static let qwen35NineBPenaltyEnvironmentKey = "DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY" + + static func qwen35NineBKeepsCardPenalty(environment: [String: String]) -> Bool { + guard let raw = environment[qwen35NineBPenaltyEnvironmentKey]? + .trimmingCharacters(in: .whitespacesAndNewlines).lowercased(), !raw.isEmpty + else { return true } + return !["0", "off", "false", "no"].contains(raw) + } static let qwen35CardModelTypes = [ "Qwen3.5-9B": "qwen3_5", "qwen3.5-35b-a3b": "qwen3_5_moe", @@ -111,13 +134,17 @@ public struct EngineV2SamplingDefaults: Sendable, Equatable { /// Resolve once at slot construction. `.legacy` when the gate is off, /// the checkpoint directory is unknown, the file is absent or - /// unreadable, or the artifact declares `do_sample: false`. + /// unreadable, or the artifact declares `do_sample: false`. `environment` + /// is read for `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY` alone. static func resolve( modelId: String, modelType: String?, modelDirectory: URL?, environment: [String: String] = ProcessInfo.processInfo.environment ) -> EngineV2SamplingDefaults { if let type = qwen35CardModelTypes[modelId], type == modelType { - return modelId == qwen35NineBModelID ? qwen35NineBCardDefaults : qwen35CardDefaults + if modelId == qwen35NineBModelID, !qwen35NineBKeepsCardPenalty(environment: environment) { + return qwen35NineBNoPenaltyDefaults + } + return qwen35CardDefaults } guard honorsArtifactDefaults(modelId: modelId, modelType: modelType), let modelDirectory diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift index ab4626a57b..41db0e0949 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift @@ -328,7 +328,8 @@ enum EngineV2SlotFactory { let samplingDefaults = EngineV2SamplingDefaults.resolve( modelId: modelId, modelType: modelType, - modelDirectory: modelDirectory) + modelDirectory: modelDirectory, + environment: environment) // SSD offload never carves the live KV grant. let engineKVBytesCapacity = kvBytesCapacity diff --git a/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift b/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift index 8b3b72d45b..ce1ae42a9d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift @@ -48,8 +48,10 @@ public enum MTPAcceptancePolicy { /// The built-in rule is exact for: /// - the owned Bonsai 9B candidate; - /// - the catalog Qwen3.5-9B: with no default presence penalty its rows - /// speculate, and at temperature 1 typical acceptance made them loop to + /// - the catalog Qwen3.5-9B: its default carries the card's presence + /// penalty again (a penalty row does not speculate), but a request with + /// `presence_penalty` 0, or a Mac on the no-penalty rollback, drafts, and + /// at temperature 1 typical acceptance made such rows loop to /// `max_tokens` where exact acceptance did not; /// - the catalog Gemma 4 26B QAT, whose assistant drafts most of its rows: /// on OpenRouter's GPQA run of 10-31 every answer drafted under typical diff --git a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift index 72f7edd7ff..252c07416c 100644 --- a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift +++ b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift @@ -421,6 +421,8 @@ public enum LaunchAgent: Sendable { /// `DARKBLOOM_LOOP_GUARD` / `DARKBLOOM_LOOP_EXIT_THINKING`: the loop guard /// and its exit from a repeating Gemma 4 thought are on by default; `0` /// turns each off, a list of `model_type`s replaces its default list. + /// `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY`: Qwen3.5-9B keeps the card's + /// presence penalty by default; its `0` rollback must reach the job. static let inferencePassthroughEnvKeys = [ EngineV2Factory.maxPartialPrefillsKey, EngineV2Factory.prefillChunkKey, @@ -453,6 +455,7 @@ public enum LaunchAgent: Sendable { "DARKBLOOM_GEMMA4_NAX_ROW_MAP", GenerationLoopGuardPolicy.environmentKey, GenerationLoopExitThinkingPolicy.environmentKey, + EngineV2SamplingDefaults.qwen35NineBPenaltyEnvironmentKey, ] + MiMoV26DecodeDefaults.environmentKeys + MiMoV26DecodeDefaults.verifyEnvironmentKeys static let passthroughEnvKeys = [ diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift index 90e5e30c25..d0b75157f6 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift @@ -140,7 +140,7 @@ struct EngineV2SamplingDefaultsTests { } } - /// `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` (or `off`, `false`) restores + /// `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` (or `off`, `false`, `no`) restores /// 0.10.12's no-penalty default on Qwen3.5-9B alone; anything else keeps /// the card's 1.5, and the 35B builds ignore it. A request's own value /// still wins under the rollback. @@ -153,10 +153,10 @@ struct EngineV2SamplingDefaultsTests { } let card = EngineV2SamplingDefaults(temperature: 1.0, topP: 0.95, topK: 20, presencePenalty: 1.5) let noPenalty = EngineV2SamplingDefaults(temperature: 1.0, topP: 0.95, topK: 20) - for value in ["0", "off", "false", " OFF\n", "False"] { + for value in ["0", "off", "false", "no", " OFF\n", "False"] { #expect(nineB([key: value]) == noPenalty, "\(value)") } - for value in ["", "1", "on", "true", "1.5", "card", "no"] { + for value in ["", "1", "on", "true", "1.5", "card", "yes"] { #expect(nineB([key: value]) == card, "\(value)") } #expect(nineB([:]) == card) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/PrefixCache/Qwen35CardDefaultDonationTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/PrefixCache/Qwen35CardDefaultDonationTests.swift index 4be370cd3e..6e3022653e 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/PrefixCache/Qwen35CardDefaultDonationTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/PrefixCache/Qwen35CardDefaultDonationTests.swift @@ -9,9 +9,9 @@ import Testing @testable import ProviderCore /// A Qwen 3.5/3.6 request with the model card's presence penalty (1.5) cannot speculate: on -/// `qwen3.5-35b-a3b` that is the provider's default for a request that sends no sampling field -/// (`EngineV2SamplingDefaults.qwen35CardDefaults`); on `Qwen3.5-9B` the request sends it, since -/// the 9B's default may carry no penalty. On the production paged assembly, with the inline MTP +/// `qwen3.5-35b-a3b` and `Qwen3.5-9B` alike that is the provider's default for a request that +/// sends no sampling field (`EngineV2SamplingDefaults.qwen35CardDefaults`; 0.10.12 had none on +/// the 9B). On the production paged assembly, with the inline MTP /// assistant and the encrypted complete-checkpoint store, such a request must still donate its /// prompt's checkpoints, answer exactly as it does with the cache off, and let the next /// identical request restore them and answer exactly as its cold run. Synthetic weights, no @@ -182,7 +182,8 @@ struct Qwen35CardDefaultDonationTests { let bridge = EngineV2Bridge( engine: build.engine, modelId: self.build.rawValue, tokenizer: TokenizerHandle(tokenizer), eosTokenIds: [], samplingDefaults: EngineV2SamplingDefaults.resolve( - modelId: self.build.rawValue, modelType: self.build.modelType, modelDirectory: nil), + modelId: self.build.rawValue, modelType: self.build.modelType, modelDirectory: nil, + environment: [:]), maxConcurrentRequests: 1, prefillDeadlineMode: .off, fixedRequestBytes: build.fixedRequestBytes, ssdHybridCheckpointStore: store, kvBackendKind: .paged) @@ -212,7 +213,7 @@ struct Qwen35CardDefaultDonationTests { static func request(_ build: Build, _ extra: Extra) -> ChatCompletionRequest { ChatCompletionRequest( model: build.rawValue, messages: [ChatMessage(role: "user", content: "pre-tokenized")], - max_tokens: maxTokens, presence_penalty: build == .dense ? 1.5 : nil, + max_tokens: maxTokens, stop: extra == .stop ? .single("") : nil, seed: 77, logprobs: extra == .logprobs ? true : nil, top_logprobs: extra == .logprobs ? 5 : nil) @@ -275,11 +276,9 @@ struct Qwen35CardDefaultDonationTests { let defaults = await coldBridge.samplingDefaults #expect(defaults.temperature == 1 && defaults.topP == 0.95 && defaults.topK == 20, "the card's sampling defaults apply") - if build == .moe { - #expect(defaults == EngineV2SamplingDefaults.qwen35CardDefaults, - "the 35B build keeps the card's presence penalty by default") - #expect(defaults.presencePenalty == 1.5) - } + #expect(defaults == EngineV2SamplingDefaults.qwen35CardDefaults, + "every catalog build keeps the card's presence penalty by default") + #expect(defaults.presencePenalty == 1.5) let cold = try await Self.serve(coldBridge, request, id: "cold") #expect(cold.finish == "length") #expect(cold.hit == 0) From ca52aa772fc870c1287397f5cd53d9e9e84438bd Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:18:35 -0800 Subject: [PATCH 05/26] fix(provider): `parallel_tool_calls: false` returns the first call instead of failing mid-stream OpenAI returns at most one call with `parallel_tool_calls: false`, and vLLM keeps the first (`maybe_filter_parallel_tool_calls`). We failed the response instead: the streamed `auto` path threw `toolChoiceViolation` after the first call had already left (a mid-stream error), and the complete-call paths returned a 422, although nothing in the prompt asks for a single call. - `NativeToolStreamRouter` exposes the first call only; a later frame, exposed-name or not, valid or not, is consumed and dropped without being validated (`admitsCall` / `droppingCall`). - `ToolConstraintValidation.admitted` keeps the first call on the complete-call paths: the scheduler's terminal flush (native channel families, required/named, one-piece surfaces) and Nemotron Super's owner output. `validate` keeps its cardinality check as defense in depth. - The prompt is unchanged (no template reads the flag), so the coordinator sidecar's prompt mirror is unaffected; GLM pairs keep their single-call instruction. Tests: StreamedToolCallTests (later calls dropped, strict and not; an unexposed later call dropped unvalidated, now a Harmony frame: Qwen's parser returns an undeclared frame as text, so its red-commit version never reached that path; the complete-call helper), NemotronSuperMediaControlsHTTPTests (two calls -> the first, was 422). Docs: inference.md, direct-mode.md. Changelog fragment parallel-tool-calls-false-first-call.md. Co-Authored-By: Claude Opus 5.5 --- .../parallel-tool-calls-false-first-call.md | 4 +++ docs/architecture/inference.md | 12 ++++--- docs/provider/direct-mode.md | 4 +-- .../MultiModelBatchSchedulerEngine.swift | 2 +- .../Prompting/ToolChoicePromptPolicy.swift | 5 +-- .../Streaming/NativeToolStreamRouter.swift | 30 +++++++++++++----- .../Streaming/NemotronSuperLocalOutput.swift | 2 +- .../Tools/ToolConstraintValidation.swift | 9 ++++++ .../Streaming/StreamedToolCallTests.swift | 31 ++++++++++++++++--- 9 files changed, 77 insertions(+), 22 deletions(-) create mode 100644 changelog.d/parallel-tool-calls-false-first-call.md diff --git a/changelog.d/parallel-tool-calls-false-first-call.md b/changelog.d/parallel-tool-calls-false-first-call.md new file mode 100644 index 0000000000..85c975608f --- /dev/null +++ b/changelog.d/parallel-tool-calls-false-first-call.md @@ -0,0 +1,4 @@ +### `parallel_tool_calls: false` returns the first tool call instead of failing the response + +- With `parallel_tool_calls: false`, a model that made a second call failed the whole response: a streamed answer ended in an error after its first call had already been sent, and a complete answer was a 422. Nothing in the prompt asks the model for a single call, so this was the provider failing a valid request. +- The response now carries the first call, as OpenAI and vLLM return it, and the calls the model makes after it are dropped. This holds for every model and path, Nemotron Super's included, streamed or not. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index a88327753d..8c4598c9aa 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-11-12 +> Last updated: 2026-11-13 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -3543,8 +3543,12 @@ read bare scalars and composites as raw strings. When the frame closes, the complete parse must agree with everything already exposed (`libs/mlx-swift-lm/Libraries/MLXLMCommon/Tool/ToolCallStreaming.swift`). `NativeToolStreamRouter` admits `parallel_tool_calls` cardinality at the first -fragment and, when the request is `strict` (below), validates name and schema -at frame close; the service renders OpenAI fragments (`index`, `id`, `type` +fragment: with `parallel_tool_calls: false` it exposes the first call only and +consumes every later frame without exposing or validating it, as OpenAI +returns one call and vLLM keeps the first (the complete-call paths, Nemotron +Super's included, keep the first through `ToolConstraintValidation.admitted`). +When the request is `strict` (below), it validates name and schema at frame +close; the service renders OpenAI fragments (`index`, `id`, `type` and `function.name` first, then `function.arguments` pieces). A response that begins with a call therefore reaches its first content frame at the function name instead of the engine terminal, which also ends the frame loop's @@ -3557,7 +3561,7 @@ function and arguments off the declared schema are returned instead of failing a response whose reasoning has already streamed. The request stays validated when any declared function sets `strict: true`, when it declares no tools (a call is then never returned), and for `required`, named and `none` -choices; `parallel_tool_calls: false` holds either way, and a call parsed from +choices; `parallel_tool_calls: false` returns the first call either way, and a call parsed from a frame that `max_tokens` cut off is still validated (it may be missing arguments). Strict `auto` checks each call against the caller's schema as sent diff --git a/docs/provider/direct-mode.md b/docs/provider/direct-mode.md index 68d6eaad23..5404c2282d 100644 --- a/docs/provider/direct-mode.md +++ b/docs/provider/direct-mode.md @@ -1,6 +1,6 @@ # The local API: an OpenAI-compatible server on your Mac -> Last updated: 2026-11-12 +> Last updated: 2026-11-13 Your Mac's models as an OpenAI-compatible HTTP server for your own tools, served two ways: **Both**, the default (`darkbloom start`: beside the Darkbloom @@ -660,7 +660,7 @@ frame-timestamp label. | `enable_thinking` absent or `true` | Template default; `reasoning_content` streams until `` | | `enable_thinking: false` | All output is `content`, including literal markers | | `chat_template_kwargs.force_nonempty_content` | Unterminated reasoning becomes `content`: moved in a complete response; a stream sends it as reasoning, then repeats it as `content` at the end | -| `tools`, `tool_choice`, `parallel_tool_calls` (text, image or video) | `` frames become validated `tool_calls`; violations return 422, or end a stream with an error event | +| `tools`, `tool_choice`, `parallel_tool_calls` (text, image or video) | `` frames become validated `tool_calls` (with `parallel_tool_calls: false`, the first one only); violations return 422, or end a stream with an error event | | `response_format` `json_object`/`json_schema` (text, image or video) | Content is withheld and validated; invalid JSON returns 422, or ends a stream with an error event. With `tools`, calls return as `tool_calls` and only an answer without calls must be JSON | | `logprobs: true`, `top_logprobs` 0 to 20 (text, image or video) | `choices[0].logprobs.content`, streamed and complete: one entry per generated token in generation order, covering reasoning, answer and tool-call tokens (as vLLM and SGLang return them), each with at least one alternative. Joined, the entry tokens spell the reasoning, the `` marker and then the answer, not the answer alone. Reasoning chunks carry their tokens' entries, and a response that ends while reasoning still carries them. A complete response carries the stream's entries. Tool-call tokens lack entries only in the rare case that nothing follows the call. The request does not speculate; others keep speculating ([logprob rows](../architecture/inference.md#nemotron-super-logprobs)) | | Contradictory controls, `top_logprobs` outside 0 to 20, `logit_bias`, `min_p` other than 0, `n > 1`, `prompt_cache_key` (text, image or video) | 400 `Invalid inference request.` before generation | diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index e7ea281696..f226702ef5 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -1917,7 +1917,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { continuation.finish() return } - let toolCalls = toolHandler?.finish() ?? [] + let toolCalls = ToolConstraintValidation.admitted(toolHandler?.finish() ?? [], prepared: prepared) do { try router.checkNativeToolFailure() } catch { diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift index f018df79fe..3813884f81 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift @@ -20,7 +20,8 @@ enum ToolChoicePromptPolicy { /// choice, JSON output and withheld reasoning are served alike on /// every GLM slot; a pair also asks for at most one call when /// automatic choice has `parallel_tool_calls: false` - /// (`singleCallInstruction`), which the validator holds it to. + /// (`singleCallInstruction`); a response keeps only its first call + /// (`ToolConstraintValidation.admitted`). var glm5PairPostValidation = false /// The caller's declarations as sent, before ingress normalization /// (`ToolSchemaNormalization`) filled in render types. Validation of @@ -57,7 +58,7 @@ enum ToolChoicePromptPolicy { var choice = try prepareToolChoice( request, modelType: modelType, allowInternalSchemaMetadata: allowInternalSchemaMetadata) // GLM on a pair: `parallel_tool_calls: false` with automatic choice - // asks for at most one call, which the validator then holds it to. + // asks for at most one call; the response keeps only its first. if glm5PairPostValidation, choice.mode == .auto, !choice.allowsParallelCalls, choice.tools?.isEmpty == false { choice = Prepared(messages: appendingToLastUser(singleCallInstruction, in: choice.messages), diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift index 6d6382d476..547fd23ad3 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift @@ -23,6 +23,9 @@ struct NativeToolStreamRouter { private var exposedCallCount = 0 private var openCallIndex: Int? private var openCallName: String? + /// The open frame is a call made after the one `parallel_tool_calls: + /// false` allows: it is consumed and nothing of it is exposed. + private var droppingCall = false /// Every call exposed so far whose frame parsed, each already accepted by /// `ToolConstraintValidation` (which returns `auto` calls as generated /// unless the request is `strict`). @@ -208,7 +211,11 @@ struct NativeToolStreamRouter { case .text(let text): return text.isEmpty ? [] : [visibleEvent(text)] case .callStarted(let name): - let index = try admitCall(prepared) + guard admitsCall(prepared) else { + droppingCall = true + return [] + } + let index = admitCall() openCallIndex = index openCallName = name return [.toolCallDelta(.init(index: index, name: name))] @@ -216,6 +223,7 @@ struct NativeToolStreamRouter { guard let index = openCallIndex, !fragment.isEmpty else { return [] } return [.toolCallDelta(.init(index: index, arguments: fragment))] case .callCompleted(let call, let remainder): + droppingCall = false guard let index = openCallIndex else { return [] } openCallIndex = nil try ToolConstraintValidation.validate([call], prepared: prepared, truncated: truncated) @@ -223,6 +231,10 @@ struct NativeToolStreamRouter { return [.toolCallDelta(.init(index: index, arguments: remainder, completed: call))] case .callFailed(let failure): defer { openCallIndex = nil } + if droppingCall { + droppingCall = false + return [] + } guard prepared.returnsAutoCallsAsGenerated, let index = openCallIndex, let name = openCallName else { throw MultiModelBatchSchedulerEngineError.toolChoiceViolation( @@ -237,8 +249,9 @@ struct NativeToolStreamRouter { completed: ToolCall(function: .init(name: name, arguments: [String: MLXLMCommon.JSONValue]()))))] case .call(let call): // Never exposed (e.g. an undeclared name): validate before showing. + guard admitsCall(prepared) else { return [] } try ToolConstraintValidation.validate([call], prepared: prepared, truncated: truncated) - let index = try admitCall(prepared) + let index = admitCall() completedToolCalls.append(call) let arguments = String( decoding: try JSONEncoder.openAIServer.encode(call.function.arguments), as: UTF8.self) @@ -247,11 +260,14 @@ struct NativeToolStreamRouter { } } - private mutating func admitCall(_ prepared: ToolChoicePromptPolicy.Prepared) throws -> Int { - if !prepared.allowsParallelCalls, exposedCallCount > 0 { - throw MultiModelBatchSchedulerEngineError.toolChoiceViolation( - ToolNoncomplianceCheck.parallelViolation) - } + /// With `parallel_tool_calls: false` only the first call is exposed, as + /// OpenAI and vLLM return it (`ToolConstraintValidation.admitted`); later + /// calls are dropped, never a failure after the first already streamed. + private func admitsCall(_ prepared: ToolChoicePromptPolicy.Prepared) -> Bool { + prepared.allowsParallelCalls || exposedCallCount == 0 + } + + private mutating func admitCall() -> Int { defer { exposedCallCount += 1 } return exposedCallCount } diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NemotronSuperLocalOutput.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NemotronSuperLocalOutput.swift index c06d614e42..5e98611b1b 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NemotronSuperLocalOutput.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NemotronSuperLocalOutput.swift @@ -79,7 +79,7 @@ struct NemotronSuperLocalOutput { reasoning = split.reasoning ?? "" _ = try route([.init(content: split.content ?? "", reasoningContent: nil)]) } - let calls = handler?.finish() ?? [] + let calls = ToolConstraintValidation.admitted(handler?.finish() ?? [], prepared: plan.toolPolicy) let residual = handler?.takeResidualText() ?? "" let forced = plan.toolPolicy.requiresToolCall // route refuses mid-stream parse failures, so any failure here is the diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintValidation.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintValidation.swift index 16eaaf0adf..af0ec9c1e1 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintValidation.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintValidation.swift @@ -111,6 +111,15 @@ enum ToolConstraintValidation { } } + /// The calls a response returns. With `parallel_tool_calls: false` that is + /// the first call only, as OpenAI and vLLM return it: calls the model makes + /// after it are dropped instead of failing the response. Callers pass + /// their calls through here before `validate`, whose cardinality check + /// stays as defense in depth. + static func admitted(_ calls: [ToolCall], prepared: ToolChoicePromptPolicy.Prepared) -> [ToolCall] { + prepared.allowsParallelCalls ? calls : Array(calls.prefix(1)) + } + /// Reserved-metadata forgery guard for untrusted payloads. The /// `originalBooleanSchemaKey` marker is injected by our own normalizer, so /// a client that sends it is forging internal state. diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift index 837706d6f2..0b951f1307 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift @@ -227,12 +227,15 @@ struct StreamedToolCallTests { } } - /// A later call that completes without being exposed (a name the request - /// did not declare) is dropped too, before validation could refuse it. + /// A later call that completes without being exposed (Harmony parses an + /// undeclared name, which `strict` refuses) is dropped too, before + /// validation could refuse it. @Test func laterUnexposedCallIsDroppedUnvalidated() throws { - var router = try Self.router(Self.request(parallel: false, strict: true), modelType: "qwen3_5") - let text = "\n\n\nParis\n\n\n\n" - + "\n\n\n/\n\n\n" + var router = try Self.router(Self.request(parallel: false, strict: true), modelType: "gpt_oss") + let text = "<|start|>assistant to=functions.get_weather<|channel|>commentary json" + + #"<|message|>{"location":"Paris"}<|call|>"# + + "<|start|>assistant to=functions.delete_everything<|channel|>commentary json" + + #"<|message|>{"path":"/"}<|call|>"# var events: [MLXServerGenerationEvent] = [] for character in Self.characters(text) { events += try router.process(character) } events += try router.finishText() @@ -241,6 +244,24 @@ struct StreamedToolCallTests { #expect(router.completedToolCalls.map(\.function.name) == ["get_weather"]) } + /// The complete-call paths (native channel families, required/named, + /// surfaces that take calls in one piece, Nemotron Super's owner) keep + /// the first call the same way. + @Test func completeCallPathsKeepTheFirstCall() throws { + let first = ToolCall(function: .init(name: "get_weather", arguments: ["location": "Paris"])) + let second = ToolCall(function: .init(name: "get_weather", arguments: ["location": "Rome"])) + for choice in [nil, OpenAIToolChoice.mode(.required), .function(name: "get_weather")] { + let single = try ToolChoicePromptPolicy.prepare(Self.request(choice, parallel: false), modelType: "gemma4") + let admitted = ToolConstraintValidation.admitted([first, second], prepared: single) + #expect(admitted == [first]) + try ToolConstraintValidation.validate(admitted, prepared: single) + let parallel = try ToolChoicePromptPolicy.prepare(Self.request(choice), modelType: "gemma4") + #expect(ToolConstraintValidation.admitted([first, second], prepared: parallel) == [first, second]) + } + let none = try ToolChoicePromptPolicy.prepare(Self.request(parallel: false), modelType: "gemma4") + #expect(ToolConstraintValidation.admitted([], prepared: none).isEmpty) + } + /// The second partial holds a `}`, so Gemma's lenient EOS parse reads a /// garbled call that contradicts the exposed arguments. @Test(arguments: [ From bf4eac880ed729a067f83bb1a3843cbbf20563f7 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:25:32 -0800 Subject: [PATCH 06/26] fix(provider): a stray in GLM output is text, not a 500 GLM's SDK tool stream (`GLM5ToolStream`) withholds a response from its first `` to EOS and parses that suffix as one call batch; on GLM `auto` requests (the legacy text path) the suffix also holds the reasoning. A tag the model only mentioned or a call it drafted in its thought, or a text answer that mentions the tag, failed the batch, and `checkNativeToolFailure` turned it into generationFailed -> a 500 for the whole response (80 OpenRouter GLM tool requests in the 72 h to 11-13 05:10Z; 13-34/day, ~74/day at the 11-13 tool rate). As vLLM's and SGLang's GLM parsers return unmatched markers as text: - `GLM5ToolSuffix.split` (new): when the SDK's whole-suffix parse fails, the calls are the frames from the earliest `` whose rest parses as calls to the end of the response (the SDK's public `GLM5ToolCallParser`, unchanged strictness); everything before them is text. A suffix with no such rest (a malformed or cut-off final frame, text after the calls) is all text, so a later malformed frame still never commits an earlier call. At most 64 starts are tried. - `NativeToolStreamRouter.finishCompleteCalls(truncated:)` applies it at the complete-call terminal (the scheduler calls it instead of the handler's `finish()` + `takeResidualText()`); an output cut at the token limit is never split. - `checkNativeToolFailure`: an `auto` GLM parse failure is no longer thrown; its text leaves through the existing residual path, which the service's reasoning parser splits at ``. Required/named calls still fail closed (422); MiMo, Flint and the streamed-call path are unchanged. - `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the 500 (no split); it is on `LaunchAgent.inferencePassthroughEnvKeys`. Tests: the red suite passes, plus the rollback and the 64-start bound. Docs: inference.md (GLM5Next implementation boundary), configuration.md. Changelog: glm-stray-tool-call-text.md. Co-Authored-By: Claude Opus 5.5 --- changelog.d/glm-stray-tool-call-text.md | 5 ++ docs/architecture/inference.md | 13 +++++ docs/reference/configuration.md | 1 + .../MultiModelBatchSchedulerEngine.swift | 8 ++- .../Inference/Streaming/GLM5ToolSuffix.swift | 41 ++++++++++++++++ .../Streaming/NativeToolStreamRouter.swift | 32 +++++++++++- .../ProviderCore/Service/LaunchAgent.swift | 3 ++ .../Streaming/GLM5ToolFailureTests.swift | 49 +++++++++++++++++-- 8 files changed, 141 insertions(+), 11 deletions(-) create mode 100644 changelog.d/glm-stray-tool-call-text.md create mode 100644 provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift diff --git a/changelog.d/glm-stray-tool-call-text.md b/changelog.d/glm-stray-tool-call-text.md new file mode 100644 index 0000000000..ceb1aec642 --- /dev/null +++ b/changelog.d/glm-stray-tool-call-text.md @@ -0,0 +1,5 @@ +### A stray `` no longer fails a GLM-5.3-Flash response + +- GLM's tool parser reads a response from its first `` to the end as one batch of calls, and on `auto` tool requests that includes the model's reasoning. A tag the model only mentioned or a call it drafted in its thought, or a text answer that mentions the tag, failed the whole response with a 500 (`native GLM tool output is invalid`). +- Such output is now returned the way vLLM's and SGLang's GLM parsers return unmatched markers: as text. The calls are the frames that parse to the end of the response; everything before them is text, so the reasoning still splits at ``. Output with no such calls (a malformed or cut-off final call, text after the calls, an output cut at `max_tokens`) is all text. No call is completed or salvaged. +- Required and named `tool_choice` still fail closed (422). `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the 500; `darkbloom start` passes it to the launchd provider. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index a88327753d..26099b838b 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1781,6 +1781,19 @@ commit a partial call batch. Its retained suffix is capped at 1 MiB; rejection returns the original text through the existing parser-failure path. Ambiguous string unions and unsupported indirect schemas are not inferred. This parser does not implement constrained decoding or advertise function calling. +The suffix starts at the response's first ``, and GLM `auto` tool +requests do not split reasoning off first, so it also holds a tag the model only +mentioned or a call it drafted in its thought, or a tag its answer mentions. +Such a suffix does not parse as one batch. On an `auto` request it is returned +as reference GLM parsers (vLLM, SGLang) return unmatched markers: as text, never +a failure (`NativeToolStreamRouter.finishCompleteCalls`, `GLM5ToolSuffix`). The +calls are the frames from the earliest `` whose rest parses as calls +to the end of the response, and everything before them is text, which the +service's reasoning parser then splits at ``. A suffix with no such rest +(a malformed or cut-off final frame, text after the calls), an output cut at the +token limit, and calls after more than 64 tags are all text; no frame is +completed or salvaged. A required or named call still fails closed (422). +`DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure (500). The request-local [GLM prompt contract](../reference/protocol-messages.md#glm-native-prompt-contract) also preserves original schema values only after a trusted loaded-model check. It renders reasoning that OpenRouter returns on earlier assistant turns diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 6bf4cd8d16..f581f45ae6 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -565,6 +565,7 @@ and rollback are defined in the [provider configuration reference](../provider/c | `DARKBLOOM_TTFT_GDN_BLOCKED` | `0`, `false`, `no`, `off` keep the stock kernel; `packed` or `rows` force that kernel; unset or any other value probes. Case-insensitive; surrounding whitespace is ignored | probe | `libs/mlx-swift-lm/Libraries/MLXLMCommon/GatedDelta.swift` (`GatedDeltaPrefill.mode`, `GatedDeltaPrefill.kernel`) | Selects the Gated DeltaNet prompt-window kernel of `qwen3_5`, `qwen3_5_moe` and `prism_hadamard_qwen35` models ([mechanism](../architecture/inference.md#context)). The default probe keeps a four-row kernel only where it reproduces `gated_delta_step` bit for bit on the GPU; it does not compare speed, so `0` is the rollback where a kept kernel is slower. Forced kernels skip that check and are for A/B measurement only. Decode, MTP verification and masked updates always use the stock kernel. Read once per process. Forwarded to the LaunchAgent. | | `DARKBLOOM_ENGINE_V2_VLM_PARITY_CHECK` | `0` skips | on | `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VLMTextExtraction.swift` | VLM text-extraction parity check. | | `DARKBLOOM_TTFT_STREAM_TOOL_CALLS` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/ToolStreamPreparation.swift` (`streamsToolCallsByDefault`) | Chat streams send `tool_choice` `auto` calls in the Gemma, Qwen 3.5, Harmony and framed-JSON formats as OpenAI `tool_calls` fragments while they are generated; each call is still validated when its frame closes. Required/named calls and other formats are unchanged. `0` restores complete calls at the engine terminal. See [streamed auto tool calls](../architecture/inference.md#streamed-auto-tool-calls). Forwarded to the LaunchAgent. | +| `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift` (`returnsUnparsedOutputAsTextByDefault`) | GLM-5.3-Flash `auto` tool output whose tool suffix does not parse as one call batch (a `` mentioned or drafted in the thought, or mentioned in the answer) is returned as text, with the frames that parse to the end of the response as its calls. Required/named calls still fail closed. `0` restores the 500 for any such response. See [GLM5Next implementation boundary](../architecture/inference.md#glm5next-implementation-boundary). Forwarded to the LaunchAgent. | | `DARKBLOOM_TTFT_THINK_CONTENT_SEED` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningPromptProbe.swift` (`seedsPlainTailContentByDefault`) | Qwen3-VL (`qwen3_vl_moe`, `plainTailContentModelTypes`) requests on the `qwen3` reasoning parser whose prompt tail has no think marker start in content state, so the answer streams instead of waiting for a tag or the end of generation. Other model types, including close-only Qwen reasoners, keep undecided parsing. `0` restores undecided parsing. Forwarded to the LaunchAgent. | ### Managed Nemotron Super slot diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index e7ea281696..e6c81dcf83 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -1917,7 +1917,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { continuation.finish() return } - let toolCalls = toolHandler?.finish() ?? [] + let finished = router.finishCompleteCalls(truncated: stopReason == "length") + let toolCalls = finished.calls do { try router.checkNativeToolFailure() } catch { @@ -1925,10 +1926,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { continuation.finish(throwing: error) return } - if prepared.mode == .auto, - let residual = toolHandler?.takeResidualText(), - !residual.isEmpty - { + if prepared.mode == .auto, let residual = finished.residual, !residual.isEmpty { emit(router.visibleEvent(residual)) } if prepared.mode == .auto, (toolHandler?.parseFailureCount ?? 0) > 0 { diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift new file mode 100644 index 0000000000..6fb374ba38 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift @@ -0,0 +1,41 @@ +import Foundation +import MLXLMCommon + +/// The calls in a GLM tool suffix that does not parse as one batch. +/// +/// The SDK's `GLM5ToolStream` withholds a response from its first +/// `` to EOS and parses that suffix as one call batch. On the legacy +/// text path the suffix also holds reasoning, so a `` the model only +/// mentioned or drafted in its thought, or one its answer mentions, fails the +/// batch. Reference GLM parsers (vLLM, SGLang) return such unmatched markers as +/// text. Here the calls are the frames from the earliest `` whose +/// rest parses as calls to the end of the response; everything before them is +/// text, and a suffix with no such rest is all text. A frame is never completed +/// or salvaged, and a call followed by anything but more calls commits nothing, +/// so a malformed final frame leaves the whole suffix as text. +enum GLM5ToolSuffix { + /// `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure: + /// an `auto` response whose suffix does not parse fails with a 500. + static let environmentKey = "DARKBLOOM_GLM_TOOL_TEXT_FALLBACK" + static let returnsUnparsedOutputAsTextByDefault = + ProcessInfo.processInfo.environment[environmentKey] != "0" + + /// `` positions tried as the calls' first frame. Each attempt + /// parses the rest of the suffix (at most `GLM5ToolCallParser`'s 1 MiB), so + /// this bounds the work; calls after more mentions than this stay text. + static let maximumStarts = 64 + + private static let opening = "" + + static func split(_ suffix: String, tools: [[String: any Sendable]]?) -> (text: String, calls: [ToolCall]) { + let parser = GLM5ToolCallParser() + var searchStart = suffix.startIndex + for _ in 0 ..< maximumStarts { + guard let start = suffix.range(of: opening, range: searchStart ..< suffix.endIndex) else { break } + let calls = parser.parseEOS(String(suffix[start.lowerBound...]), tools: tools) + if !calls.isEmpty { return (String(suffix[.. 0 else { return } + if returnsUnparsedGLMOutputAsText { return } let model = handler?.format == .glm5 ? "GLM" : handler?.format == .flint ? "Flint" : "MiMo" let message = "native \(model) tool output is invalid" if requiresToolCall || nativeMiMoRequiresConstraint { @@ -148,6 +157,25 @@ struct NativeToolStreamRouter { throw MultiModelBatchSchedulerEngineError.generationFailed(message) } + /// End of generation on the complete-call path: the handler's calls and + /// its residual text. An `auto` GLM suffix that did not parse as one batch + /// is split into text and its final calls (`GLM5ToolSuffix`); an output the + /// token limit cut off stays text. + func finishCompleteCalls(truncated: Bool) -> (calls: [ToolCall], residual: String?) { + guard let handler else { return ([], nil) } + let calls = handler.finish() + let residual = handler.takeResidualText() + guard returnsUnparsedGLMOutputAsText, !truncated, calls.isEmpty, let residual else { + return (calls, residual) + } + let split = GLM5ToolSuffix.split(residual, tools: tools) + return (split.calls, split.text) + } + + private var returnsUnparsedGLMOutputAsText: Bool { + handler?.format == .glm5 && glmUnparsedOutputIsText && !requiresToolCall + } + private mutating func route(_ pieces: [ParsedReasoning]) throws -> [MLXServerGenerationEvent] { var events: [MLXServerGenerationEvent] = [] for piece in pieces { diff --git a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift index 72f7edd7ff..7bdebada63 100644 --- a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift +++ b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift @@ -421,6 +421,8 @@ public enum LaunchAgent: Sendable { /// `DARKBLOOM_LOOP_GUARD` / `DARKBLOOM_LOOP_EXIT_THINKING`: the loop guard /// and its exit from a repeating Gemma 4 thought are on by default; `0` /// turns each off, a list of `model_type`s replaces its default list. + /// `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK`: unparsed `auto` GLM tool output is + /// text by default; exact `0` restores the 500. static let inferencePassthroughEnvKeys = [ EngineV2Factory.maxPartialPrefillsKey, EngineV2Factory.prefillChunkKey, @@ -453,6 +455,7 @@ public enum LaunchAgent: Sendable { "DARKBLOOM_GEMMA4_NAX_ROW_MAP", GenerationLoopGuardPolicy.environmentKey, GenerationLoopExitThinkingPolicy.environmentKey, + GLM5ToolSuffix.environmentKey, ] + MiMoV26DecodeDefaults.environmentKeys + MiMoV26DecodeDefaults.verifyEnvironmentKeys static let passthroughEnvKeys = [ diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift index 25c90312d1..9611711871 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift @@ -84,11 +84,16 @@ struct GLM5ToolFailureTests { #expect(result.visible == shape.visible, "\(shape.name)") } - /// A required call keeps failing closed when its suffix does not parse. + /// A required call keeps failing closed when its suffix does not parse: the + /// parser's own refusal, or the visible-text check when text precedes it. @Test func forcedChoiceStillRefusesAStraySuffix() async throws { - let result = try await run("Wrap it in tags." + valid, forced: true, width: 1) - #expect(result.calls.isEmpty && result.visible.isEmpty) - #expect(result.failure == .toolChoiceViolation("native GLM tool output is invalid")) + let stray = try await run("." + valid, forced: true, width: 1) + #expect(stray.calls.isEmpty && stray.visible.isEmpty) + #expect(stray.failure == .toolChoiceViolation("native GLM tool output is invalid")) + let mentioned = try await run("Wrap it in tags." + valid, forced: true, width: 1) + #expect(mentioned.calls.isEmpty && mentioned.visible.isEmpty) + let failure = try #require(mentioned.failure) + #expect(ProviderLoop.mapInferenceErrorToStatus(failure) == 422) } /// The delimiters quoted inside a JSON argument are data: the calls start @@ -124,6 +129,42 @@ struct GLM5ToolFailureTests { #expect(result.visible == output) } + /// The search for the calls' first frame is bounded. + @Test func callsAfterTooManyTagsStayText() async throws { + let mentions = String(repeating: " ", count: GLM5ToolSuffix.maximumStarts) + let within = try await run(String(mentions.dropFirst(12)) + valid, forced: false, width: 4096) + #expect(within.calls.count == 1 && within.failure == nil) + let beyond = try await run(mentions + valid, forced: false, width: 4096) + #expect(beyond.calls.isEmpty && beyond.failure == nil) + #expect(beyond.visible == mentions + valid) + } + + /// `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure. + @Test func rollbackRestoresTheSuffixFailure() throws { + let request = try MiMoConsumerFixture.request(choice: #""auto""#) + let prepared = try ToolChoicePromptPolicy.prepare(request, modelType: "glm5_next") + for textFallback in [true, false] { + let handler = try #require(try ToolStreamPreparation.makeHandler( + request: request, prepared: prepared, modelType: "glm5_next")) + var router = NativeToolStreamRouter(handler: handler, requiresToolCall: false, nativePrefix: nil, + tools: prepared.tools?.map { $0.toolSpec() }, glmUnparsedOutputIsText: textFallback) + _ = try router.process("Wrap it in tags." + valid) + _ = try router.finishText() + let finished = router.finishCompleteCalls(truncated: false) + if textFallback { + try router.checkNativeToolFailure() + #expect(finished.calls.count == 1) + #expect(finished.residual == " tags.") + } else { + #expect(finished.calls.isEmpty) + #expect(throws: MultiModelBatchSchedulerEngineError.generationFailed( + "native GLM tool output is invalid")) { try router.checkNativeToolFailure() } + } + } + #expect(GLM5ToolSuffix.environmentKey == "DARKBLOOM_GLM_TOOL_TEXT_FALLBACK") + #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(GLM5ToolSuffix.environmentKey)) + } + /// Forced choice is served by structured post-validation: the production /// handler is the native GLM parser, which withholds calls until EOS. @Test func publicForcedGLMUsesTheWithheldNativeParser() throws { From 221f1b40c0b82a2412a74ea16f1a400e88a37dff Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:33:12 -0800 Subject: [PATCH 07/26] refactor(provider): refactor pass on the GLM tool suffix fix From the dedicated refactor-pass subagent (behaviour-preserving): - the scheduler destructures `finishCompleteCalls` into `(toolCalls, residual)`; - the test suite's result type is `Outcome` (it shadowed `Swift.Result`), `expectUnparsed` no longer throws, and a custom tool body keeps the request's tool choice; - the 64-start bound is worded exactly: calls after 64 or more tags stay text. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 2 +- .../MultiModelBatchSchedulerEngine.swift | 5 ++--- .../Inference/Streaming/GLM5ToolSuffix.swift | 2 +- .../Streaming/GLM5ToolFailureTests.swift | 19 ++++++++++--------- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 26099b838b..d5c1d58da7 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1791,7 +1791,7 @@ calls are the frames from the earliest `` whose rest parses as calls to the end of the response, and everything before them is text, which the service's reasoning parser then splits at ``. A suffix with no such rest (a malformed or cut-off final frame, text after the calls), an output cut at the -token limit, and calls after more than 64 tags are all text; no frame is +token limit, and calls after 64 or more tags are all text; no frame is completed or salvaged. A required or named call still fails closed (422). `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure (500). The request-local [GLM prompt contract](../reference/protocol-messages.md#glm-native-prompt-contract) diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index e6c81dcf83..967169c7c9 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -1917,8 +1917,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { continuation.finish() return } - let finished = router.finishCompleteCalls(truncated: stopReason == "length") - let toolCalls = finished.calls + let (toolCalls, residual) = router.finishCompleteCalls(truncated: stopReason == "length") do { try router.checkNativeToolFailure() } catch { @@ -1926,7 +1925,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { continuation.finish(throwing: error) return } - if prepared.mode == .auto, let residual = finished.residual, !residual.isEmpty { + if prepared.mode == .auto, let residual, !residual.isEmpty { emit(router.visibleEvent(residual)) } if prepared.mode == .auto, (toolHandler?.parseFailureCount ?? 0) > 0 { diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift index 6fb374ba38..971cafc8a4 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift @@ -22,7 +22,7 @@ enum GLM5ToolSuffix { /// `` positions tried as the calls' first frame. Each attempt /// parses the rest of the suffix (at most `GLM5ToolCallParser`'s 1 MiB), so - /// this bounds the work; calls after more mentions than this stay text. + /// this bounds the work; calls after this many or more tags stay text. static let maximumStarts = 64 private static let opening = "" diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift index 9611711871..ea936a8d46 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift @@ -15,14 +15,14 @@ struct GLM5ToolFailureTests { func malformedSuffixNeverCommitsEarlierCall(forced: Bool, width: Int) async throws { let output = valid + "PRIVATE_STRAY" let result = try await run(output, forced: forced, width: width) - try expectUnparsed(result, output: output, forced: forced) + expectUnparsed(result, output: output, forced: forced) } @Test(arguments: [false, true]) func truncatedSecondCallNeverCommitsEarlierCall(forced: Bool) async throws { let output = valid + "echotext" let result = try await run(output, forced: forced, width: 1) - try expectUnparsed(result, output: output, forced: forced) + expectUnparsed(result, output: output, forced: forced) } @Test(arguments: [false, true]) @@ -37,7 +37,7 @@ struct GLM5ToolFailureTests { func oversizedFrameFailsBeforeFallback(forced: Bool) async throws { let output = "echo" + String(repeating: "x", count: (1 << 20) + 1) let result = try await run(output, forced: forced, width: 65536) - try expectUnparsed(result, output: output, forced: forced) + expectUnparsed(result, output: output, forced: forced) } /// The model's raw output after the prompt's open `` (the legacy @@ -184,7 +184,7 @@ struct GLM5ToolFailureTests { } } - private struct Result { + private struct Outcome { var calls: [ToolCall] = [] var visible = "" var failure: MultiModelBatchSchedulerEngineError? @@ -192,7 +192,7 @@ struct GLM5ToolFailureTests { /// A required call fails closed (422); an `auto` response returns the /// unparsed suffix as text, with no call and no failure. - private func expectUnparsed(_ result: Result, output: String, forced: Bool) throws { + private func expectUnparsed(_ result: Outcome, output: String, forced: Bool) { #expect(result.calls.isEmpty) if forced { #expect(result.visible.isEmpty) @@ -207,11 +207,12 @@ struct GLM5ToolFailureTests { /// The production event stream on the legacy text path (no native /// channel), fed `width` characters at a time. private func run(_ output: String, forced: Bool, width: Int, finishReason: String? = nil, - tool: String? = nil) async throws -> Result { - var request = try MiMoConsumerFixture.request(choice: forced ? #""required""# : #""auto""#) + tool: String? = nil) async throws -> Outcome { + let choice = forced ? #""required""# : #""auto""# + var request = try MiMoConsumerFixture.request(choice: choice) if let tool { var body = try #require(JSONSerialization.jsonObject(with: MiMoConsumerFixture.body( - choice: #""auto""#)) as? [String: Any]) + choice: choice)) as? [String: Any]) body["tools"] = [try JSONSerialization.jsonObject(with: Data(tool.utf8))] request = try ProviderLoop.decodeOpenAIRequest(JSONSerialization.data(withJSONObject: body)) } @@ -233,7 +234,7 @@ struct GLM5ToolFailureTests { let stream = try scheduler._testMakeEventStream(upstream: upstream, cancelUpstream: {}, prepared: prepared, releaseBox: OneShotRelease(release: { _ in }, modelId: "fixture"), toolHandler: handler) - var result = Result() + var result = Outcome() do { for try await event in stream { switch event { From 7fb1f8dd57a6349491463fb1bdbbbf0fb0ad78f5 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:35:39 -0800 Subject: [PATCH 08/26] test(provider): named choice and a clean call at the token limit; exact wording From the refactor pass's assessment (no further cleanup warranted): - the forced refusal test runs named as well as required choice; - a suffix that parses keeps its calls at `length` (unchanged), next to the stray suffix that is not split there; - docs, changelog and the router comment say exactly that: only a suffix that did not parse stays text in an output the token limit cut off. Co-Authored-By: Claude Opus 5.5 --- changelog.d/glm-stray-tool-call-text.md | 2 +- docs/architecture/inference.md | 7 ++++--- .../Streaming/NativeToolStreamRouter.swift | 4 ++-- .../Streaming/GLM5ToolFailureTests.swift | 17 +++++++++++------ 4 files changed, 18 insertions(+), 12 deletions(-) diff --git a/changelog.d/glm-stray-tool-call-text.md b/changelog.d/glm-stray-tool-call-text.md index ceb1aec642..a31b35a5b8 100644 --- a/changelog.d/glm-stray-tool-call-text.md +++ b/changelog.d/glm-stray-tool-call-text.md @@ -1,5 +1,5 @@ ### A stray `` no longer fails a GLM-5.3-Flash response - GLM's tool parser reads a response from its first `` to the end as one batch of calls, and on `auto` tool requests that includes the model's reasoning. A tag the model only mentioned or a call it drafted in its thought, or a text answer that mentions the tag, failed the whole response with a 500 (`native GLM tool output is invalid`). -- Such output is now returned the way vLLM's and SGLang's GLM parsers return unmatched markers: as text. The calls are the frames that parse to the end of the response; everything before them is text, so the reasoning still splits at ``. Output with no such calls (a malformed or cut-off final call, text after the calls, an output cut at `max_tokens`) is all text. No call is completed or salvaged. +- Such output is now returned the way vLLM's and SGLang's GLM parsers return unmatched markers: as text. The calls are the frames that parse to the end of the response; everything before them is text, so the reasoning still splits at ``. Output with no such calls (a malformed or cut-off final call, text after the calls) is all text, and so is output cut off at `max_tokens` whose tool suffix does not parse. No call is completed or salvaged. - Required and named `tool_choice` still fail closed (422). `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the 500; `darkbloom start` passes it to the launchd provider. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index d5c1d58da7..fc1e872700 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1790,9 +1790,10 @@ a failure (`NativeToolStreamRouter.finishCompleteCalls`, `GLM5ToolSuffix`). The calls are the frames from the earliest `` whose rest parses as calls to the end of the response, and everything before them is text, which the service's reasoning parser then splits at ``. A suffix with no such rest -(a malformed or cut-off final frame, text after the calls), an output cut at the -token limit, and calls after 64 or more tags are all text; no frame is -completed or salvaged. A required or named call still fails closed (422). +(a malformed or cut-off final frame, text after the calls) is all text, and so is +a suffix that did not parse in an output cut at the token limit, or whose calls +follow 64 or more tags; no frame is completed or salvaged. A suffix that parses +keeps its calls as before. A required or named call still fails closed (422). `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure (500). The request-local [GLM prompt contract](../reference/protocol-messages.md#glm-native-prompt-contract) also preserves original schema values only after a trusted loaded-model check. diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift index 2c64afd2a6..796d2a1fc9 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift @@ -159,8 +159,8 @@ struct NativeToolStreamRouter { /// End of generation on the complete-call path: the handler's calls and /// its residual text. An `auto` GLM suffix that did not parse as one batch - /// is split into text and its final calls (`GLM5ToolSuffix`); an output the - /// token limit cut off stays text. + /// is split into text and its final calls (`GLM5ToolSuffix`), except in an + /// output the token limit cut off, where it stays text. func finishCompleteCalls(truncated: Bool) -> (calls: [ToolCall], residual: String?) { guard let handler else { return ([], nil) } let calls = handler.finish() diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift index ea936a8d46..27625f9a3a 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift @@ -86,11 +86,13 @@ struct GLM5ToolFailureTests { /// A required call keeps failing closed when its suffix does not parse: the /// parser's own refusal, or the visible-text check when text precedes it. - @Test func forcedChoiceStillRefusesAStraySuffix() async throws { - let stray = try await run("." + valid, forced: true, width: 1) + @Test(arguments: [#""required""#, #"{"type":"function","function":{"name":"echo"}}"#]) + func forcedChoiceStillRefusesAStraySuffix(choice: String) async throws { + let stray = try await run("." + valid, forced: true, width: 1, choice: choice) #expect(stray.calls.isEmpty && stray.visible.isEmpty) #expect(stray.failure == .toolChoiceViolation("native GLM tool output is invalid")) - let mentioned = try await run("Wrap it in tags." + valid, forced: true, width: 1) + let mentioned = try await run("Wrap it in tags." + valid, forced: true, width: 1, + choice: choice) #expect(mentioned.calls.isEmpty && mentioned.visible.isEmpty) let failure = try #require(mentioned.failure) #expect(ProviderLoop.mapInferenceErrorToStatus(failure) == 422) @@ -120,13 +122,16 @@ struct GLM5ToolFailureTests { #expect(result.visible == output) } - /// Calls are never split out of an output the token limit cut off. + /// Calls are never split out of a suffix that did not parse in an output + /// the token limit cut off; a suffix that parses keeps its calls, as before. @Test func truncatedOutputIsNotSplit() async throws { let output = "Wrap it in tags." + valid let result = try await run(output, forced: false, width: 4, finishReason: "length") #expect(result.failure == nil) #expect(result.calls.isEmpty) #expect(result.visible == output) + let clean = try await run("Need it." + valid, forced: false, width: 4, finishReason: "length") + #expect(clean.failure == nil && clean.calls.count == 1 && clean.visible == "Need it.") } /// The search for the calls' first frame is bounded. @@ -207,8 +212,8 @@ struct GLM5ToolFailureTests { /// The production event stream on the legacy text path (no native /// channel), fed `width` characters at a time. private func run(_ output: String, forced: Bool, width: Int, finishReason: String? = nil, - tool: String? = nil) async throws -> Outcome { - let choice = forced ? #""required""# : #""auto""# + tool: String? = nil, choice forcedChoice: String = #""required""#) async throws -> Outcome { + let choice = forced ? forcedChoice : #""auto""# var request = try MiMoConsumerFixture.request(choice: choice) if let tool { var body = try #require(JSONSerialization.jsonObject(with: MiMoConsumerFixture.body( From faf818caea2951d9253e4bf5011c6daf9f489863 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:47:53 -0800 Subject: [PATCH 09/26] fix(provider): GLM suffix calls come only from top-level frames (review) From the independent review of 7fb1f8dd57 (REQUEST CHANGES): 1. BLOCKER: retrying every literal `` could promote a frame that sits inside an unfinished argument (a JSON string, or a raw string value) into an executable call. `GLM5ToolSuffix` now reads the suffix's frame structure as the SDK's parser does (`Lexer`): a frame that has started its arguments owns everything up to its ``; a string-typed value runs raw to ``, any other value is JSON whose quoted delimiters are data. The calls are the trailing run of top-level frames, separated only by whitespace and ending the response, from just after the run's last frame that does not parse (each frame parses on its own), and the SDK's `parseEOS` must agree on them; anything else is all text. 2. A think marker inside a released frame would reach the service's reasoning parser as a channel boundary: such a suffix keeps failing, as before (`Split.ambiguous`; `finishCompleteCalls` now throws it). 3. Work is linear in the suffix: one structural pass, each run frame parsed once on its own (from the end) and the run once by `parseEOS`; the 64-start bound is gone. 4. Docs, changelog and comments describe a stricter provider rule inspired by the reference parsers' no-failure fallback, and its deliberate divergences (a call followed by text or a malformed frame commits nothing; a call drafted in a closed thought stays reasoning). Tests: both review witnesses (JSON and raw nesting, with `stop` and `length`, at three chunk widths) and a frame after an argument stay text with no call; think markers inside a released draft keep the 500; 20,000 mentions before a call parse it. Co-Authored-By: Claude Opus 5.5 --- changelog.d/glm-stray-tool-call-text.md | 2 +- docs/architecture/inference.md | 29 ++- docs/reference/configuration.md | 2 +- .../MultiModelBatchSchedulerEngine.swift | 6 +- .../Inference/Streaming/GLM5ToolSuffix.swift | 228 ++++++++++++++++-- .../Streaming/NativeToolStreamRouter.swift | 14 +- .../Streaming/GLM5ToolFailureTests.swift | 50 +++- 7 files changed, 279 insertions(+), 52 deletions(-) diff --git a/changelog.d/glm-stray-tool-call-text.md b/changelog.d/glm-stray-tool-call-text.md index a31b35a5b8..9f50fc2c55 100644 --- a/changelog.d/glm-stray-tool-call-text.md +++ b/changelog.d/glm-stray-tool-call-text.md @@ -1,5 +1,5 @@ ### A stray `` no longer fails a GLM-5.3-Flash response - GLM's tool parser reads a response from its first `` to the end as one batch of calls, and on `auto` tool requests that includes the model's reasoning. A tag the model only mentioned or a call it drafted in its thought, or a text answer that mentions the tag, failed the whole response with a 500 (`native GLM tool output is invalid`). -- Such output is now returned the way vLLM's and SGLang's GLM parsers return unmatched markers: as text. The calls are the frames that parse to the end of the response; everything before them is text, so the reasoning still splits at ``. Output with no such calls (a malformed or cut-off final call, text after the calls) is all text, and so is output cut off at `max_tokens` whose tool suffix does not parse. No call is completed or salvaged. +- Such output is now text instead of a failure, as vLLM's and SGLang's GLM parsers never fail a response on tool syntax, with a stricter rule for what is still a call: the calls are the well-formed frames that end the response; everything before them is text, so the reasoning still splits at ``. A frame inside or after another frame's arguments is never a call. Output with no such calls (a malformed or cut-off final call, text after the calls) is all text, and so is output cut off at `max_tokens` whose tool suffix does not parse. No call is completed or salvaged. - Required and named `tool_choice` still fail closed (422). `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the 500; `darkbloom start` passes it to the launchd provider. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index fc1e872700..a5103b9b44 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1784,17 +1784,24 @@ does not implement constrained decoding or advertise function calling. The suffix starts at the response's first ``, and GLM `auto` tool requests do not split reasoning off first, so it also holds a tag the model only mentioned or a call it drafted in its thought, or a tag its answer mentions. -Such a suffix does not parse as one batch. On an `auto` request it is returned -as reference GLM parsers (vLLM, SGLang) return unmatched markers: as text, never -a failure (`NativeToolStreamRouter.finishCompleteCalls`, `GLM5ToolSuffix`). The -calls are the frames from the earliest `` whose rest parses as calls -to the end of the response, and everything before them is text, which the -service's reasoning parser then splits at ``. A suffix with no such rest -(a malformed or cut-off final frame, text after the calls) is all text, and so is -a suffix that did not parse in an output cut at the token limit, or whose calls -follow 64 or more tags; no frame is completed or salvaged. A suffix that parses -keeps its calls as before. A required or named call still fails closed (422). -`DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure (500). +Such a suffix does not parse as one batch. On an `auto` request it is no longer a +failure: like the reference GLM parsers (vLLM, SGLang), which never fail a +response on tool syntax, the provider returns it as text, under its own stricter +rule for what still counts as a call (`NativeToolStreamRouter.finishCompleteCalls`, +`GLM5ToolSuffix`). The calls are the trailing run of top-level frames, separated +only by whitespace and ending the response, from just after the last frame of the +run that does not parse; everything before them is text, which the service's +reasoning parser then splits at ``. A frame that has started its +arguments owns everything up to its ``, so a frame inside or after an +argument is data, never a call. A suffix with no such run (a malformed or cut-off +final frame, text after the calls) is all text, and so is a suffix that did not +parse in an output cut at the token limit; no frame is completed or salvaged. A +suffix whose release would put a think marker from inside a frame before the +reasoning parser keeps failing, as does a required or named call (422). Unlike +vLLM and SGLang, a call followed by text or by a malformed frame commits nothing, +and a call drafted inside a closed thought stays reasoning. A suffix that parses +keeps its calls as before. `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the +whole-suffix failure (500). The request-local [GLM prompt contract](../reference/protocol-messages.md#glm-native-prompt-contract) also preserves original schema values only after a trusted loaded-model check. It renders reasoning that OpenRouter returns on earlier assistant turns diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index f581f45ae6..11e1c4bd35 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -565,7 +565,7 @@ and rollback are defined in the [provider configuration reference](../provider/c | `DARKBLOOM_TTFT_GDN_BLOCKED` | `0`, `false`, `no`, `off` keep the stock kernel; `packed` or `rows` force that kernel; unset or any other value probes. Case-insensitive; surrounding whitespace is ignored | probe | `libs/mlx-swift-lm/Libraries/MLXLMCommon/GatedDelta.swift` (`GatedDeltaPrefill.mode`, `GatedDeltaPrefill.kernel`) | Selects the Gated DeltaNet prompt-window kernel of `qwen3_5`, `qwen3_5_moe` and `prism_hadamard_qwen35` models ([mechanism](../architecture/inference.md#context)). The default probe keeps a four-row kernel only where it reproduces `gated_delta_step` bit for bit on the GPU; it does not compare speed, so `0` is the rollback where a kept kernel is slower. Forced kernels skip that check and are for A/B measurement only. Decode, MTP verification and masked updates always use the stock kernel. Read once per process. Forwarded to the LaunchAgent. | | `DARKBLOOM_ENGINE_V2_VLM_PARITY_CHECK` | `0` skips | on | `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VLMTextExtraction.swift` | VLM text-extraction parity check. | | `DARKBLOOM_TTFT_STREAM_TOOL_CALLS` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/ToolStreamPreparation.swift` (`streamsToolCallsByDefault`) | Chat streams send `tool_choice` `auto` calls in the Gemma, Qwen 3.5, Harmony and framed-JSON formats as OpenAI `tool_calls` fragments while they are generated; each call is still validated when its frame closes. Required/named calls and other formats are unchanged. `0` restores complete calls at the engine terminal. See [streamed auto tool calls](../architecture/inference.md#streamed-auto-tool-calls). Forwarded to the LaunchAgent. | -| `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift` (`returnsUnparsedOutputAsTextByDefault`) | GLM-5.3-Flash `auto` tool output whose tool suffix does not parse as one call batch (a `` mentioned or drafted in the thought, or mentioned in the answer) is returned as text, with the frames that parse to the end of the response as its calls. Required/named calls still fail closed. `0` restores the 500 for any such response. See [GLM5Next implementation boundary](../architecture/inference.md#glm5next-implementation-boundary). Forwarded to the LaunchAgent. | +| `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift` (`returnsUnparsedOutputAsTextByDefault`) | GLM-5.3-Flash `auto` tool output whose tool suffix does not parse as one call batch (a `` mentioned or drafted in the thought, or mentioned in the answer) is returned as text, with the well-formed frames that end the response as its calls (`GLM5ToolSuffix`). Required/named calls still fail closed. `0` restores the 500 for any such response. See [GLM5Next implementation boundary](../architecture/inference.md#glm5next-implementation-boundary). Forwarded to the LaunchAgent. | | `DARKBLOOM_TTFT_THINK_CONTENT_SEED` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningPromptProbe.swift` (`seedsPlainTailContentByDefault`) | Qwen3-VL (`qwen3_vl_moe`, `plainTailContentModelTypes`) requests on the `qwen3` reasoning parser whose prompt tail has no think marker start in content state, so the answer streams instead of waiting for a tag or the end of generation. Other model types, including close-only Qwen reasoners, keep undecided parsing. `0` restores undecided parsing. Forwarded to the LaunchAgent. | ### Managed Nemotron Super slot diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index 967169c7c9..d0380c53a7 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -1917,15 +1917,17 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { continuation.finish() return } - let (toolCalls, residual) = router.finishCompleteCalls(truncated: stopReason == "length") + let finished: (calls: [ToolCall], residual: String?) do { + finished = try router.finishCompleteCalls(truncated: stopReason == "length") try router.checkNativeToolFailure() } catch { await releaseBox.fire() continuation.finish(throwing: error) return } - if prepared.mode == .auto, let residual, !residual.isEmpty { + let toolCalls = finished.calls + if prepared.mode == .auto, let residual = finished.residual, !residual.isEmpty { emit(router.visibleEvent(residual)) } if prepared.mode == .auto, (toolHandler?.parseFailureCount ?? 0) > 0 { diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift index 971cafc8a4..ab96964029 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift @@ -7,12 +7,17 @@ import MLXLMCommon /// `` to EOS and parses that suffix as one call batch. On the legacy /// text path the suffix also holds reasoning, so a `` the model only /// mentioned or drafted in its thought, or one its answer mentions, fails the -/// batch. Reference GLM parsers (vLLM, SGLang) return such unmatched markers as -/// text. Here the calls are the frames from the earliest `` whose -/// rest parses as calls to the end of the response; everything before them is -/// text, and a suffix with no such rest is all text. A frame is never completed -/// or salvaged, and a call followed by anything but more calls commits nothing, -/// so a malformed final frame leaves the whole suffix as text. +/// batch. Like reference GLM parsers (vLLM, SGLang), which never fail a +/// response on tool syntax, such a suffix is text here, but with a stricter, +/// provider-specific rule for what still counts as a call: the calls are the +/// trailing run of top-level frames, separated only by whitespace and ending +/// the response, from just after the last frame of that run that does not +/// parse. Everything before them is text; a suffix with no such run (a cut-off +/// or malformed final frame, text after the calls) is all text. +/// +/// A frame that has started its arguments owns everything up to its own +/// ``: a `` inside an argument, or after one, is data, +/// never a call (`Lexer`). A frame is never completed or salvaged. enum GLM5ToolSuffix { /// `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure: /// an `auto` response whose suffix does not parse fails with a 500. @@ -20,22 +25,203 @@ enum GLM5ToolSuffix { static let returnsUnparsedOutputAsTextByDefault = ProcessInfo.processInfo.environment[environmentKey] != "0" - /// `` positions tried as the calls' first frame. Each attempt - /// parses the rest of the suffix (at most `GLM5ToolCallParser`'s 1 MiB), so - /// this bounds the work; calls after this many or more tags stay text. - static let maximumStarts = 64 - - private static let opening = "" + enum Split: Equatable { + /// `text` precedes `calls`, which may be empty. + case text(String, calls: [ToolCall]) + /// Released text would put a think marker from inside a tool frame + /// before the service's reasoning parser, which reads it as a channel + /// boundary. Such a suffix keeps failing, as before. + case ambiguous + } - static func split(_ suffix: String, tools: [[String: any Sendable]]?) -> (text: String, calls: [ToolCall]) { + static func split(_ suffix: String, tools: [[String: any Sendable]]?) -> Split { + let bytes = Array(suffix.utf8) + var lexer = Lexer(bytes: bytes, tools: tools) + lexer.run() + // The run of whitespace-separated frames that ends the response. + var run: [Lexer.Frame] = [] + var end = bytes.count + if !lexer.openAtEnd { + for frame in lexer.frames.reversed() { + guard Lexer.isWhitespace(bytes[frame.range.upperBound ..< end]) else { break } + run.insert(frame, at: 0) + end = frame.range.lowerBound + } + } let parser = GLM5ToolCallParser() - var searchStart = suffix.startIndex - for _ in 0 ..< maximumStarts { - guard let start = suffix.range(of: opening, range: searchStart ..< suffix.endIndex) else { break } - let calls = parser.parseEOS(String(suffix[start.lowerBound...]), tools: tools) - if !calls.isEmpty { return (String(suffix[..`/`` pairs to ``. A + /// `` not followed by a name and `` or `` + /// is a mention and stays text. Once a frame has an argument it owns + /// everything up to its ``; a string-typed value runs to + /// `` (the template writes strings raw), any other value is + /// JSON, whose quoted delimiters are data. + struct Lexer { + struct Frame { + let range: Range + /// A think marker inside the frame's arguments. + let holdsThinkMarker: Bool + } + + let bytes: [UInt8] + let tools: [[String: any Sendable]]? + private(set) var frames: [Frame] = [] + /// A frame's arguments were still open at the end of the response. + private(set) var openAtEnd = false + private var openFrameHoldsThinkMarker = false + private var index = 0 + + init(bytes: [UInt8], tools: [[String: any Sendable]]?) { + self.bytes = bytes + self.tools = tools + } + + mutating func run() { + while let start = find("", from: index) { + index = start + 11 + guard let tag = find("<", from: index) else { return } + let name = Self.string(bytes, index ..< tag).trimmingCharacters(in: CharacterSet(charactersIn: " \t\r\n")) + if starts("", at: tag) { + index = tag + 12 + frames.append(Frame(range: start ..< index, holdsThinkMarker: false)) + } else if starts("", at: tag) { + index = tag + guard let frame = arguments(start: start, name: name) else { return } + frames.append(frame) + } else { + index = tag + } + } + } + + /// Whether text released up to `end` holds a think marker inside a frame. + func releasesThinkMarker(before end: Int) -> Bool { + frames.contains { $0.holdsThinkMarker && $0.range.lowerBound < end } + || (openAtEnd && openFrameHoldsThinkMarker) + } + + /// The frame from `start`, whose arguments begin at `index`; nil when + /// it is still open at the end of the response. + private mutating func arguments(start: Int, name: String) -> Frame? { + var key: String? + var thinkMarker = false + while let tag = find("<", from: index) { + if starts("", at: tag) { + index = tag + 12 + return Frame(range: start ..< index, holdsThinkMarker: thinkMarker) + } + if starts("", at: tag) { + guard let close = find("", from: tag + 9) else { break } + key = Self.string(bytes, tag + 9 ..< close) + index = close + 10 + } else if starts("", at: tag) { + let value = tag + 11 + guard let end = isString(name: name, key: key) + ? find("", from: value) : jsonEnd(from: value) + else { break } + thinkMarker = thinkMarker || containsThinkMarker(value ..< end) + index = end + key = nil + } else { + thinkMarker = thinkMarker || starts("", at: tag) || starts("", at: tag) + index = tag + 1 + } + } + openAtEnd = true + openFrameHoldsThinkMarker = thinkMarker || containsThinkMarker(index ..< bytes.count) + return nil + } + + /// The end of a JSON value: after its closing bracket or string, or at + /// a `<` outside any string (malformed JSON ends there); nil when it + /// is still open at the end of the response. + private func jsonEnd(from start: Int) -> Int? { + var index = start + var depth = 0 + var inString = false + while index < bytes.count { + let byte = bytes[index] + index += 1 + if inString { + if byte == 92 { index += 1 } else if byte == 34 { + inString = false + if depth == 0 { return index } + } + continue + } + switch byte { + case 34: inString = true + case 123, 91: depth += 1 + case 125, 93: + depth -= 1 + if depth <= 0 { return index } + case 60: return index - 1 + default: break + } + } + return nil + } + + /// The template writes a string value raw and any other value as JSON; + /// the SDK reads it the same way, by the declared type. + private func isString(name: String, key: String?) -> Bool { + guard let key, let tools else { return false } + let functions = tools.map { ($0["function"] as? [String: any Sendable]) ?? $0 } + .filter { $0["name"] as? String == name } + guard functions.count == 1, let parameters = functions[0]["parameters"] as? [String: any Sendable] + else { return false } + let schema = (parameters["properties"] as? [String: any Sendable])?[key] ?? parameters["additionalProperties"] + // A union with `string` is written raw too; the SDK then refuses the frame. + let type = (schema as? [String: any Sendable])?["type"] + return type as? String == "string" || (type as? [String])?.contains("string") == true + } + + private func containsThinkMarker(_ range: Range) -> Bool { + var index = range.lowerBound + while let tag = find("<", from: index), tag < range.upperBound { + if starts("", at: tag) || starts("", at: tag) { return true } + index = tag + 1 + } + return false + } + + private func find(_ literal: String, from start: Int) -> Int? { + let marker = Array(literal.utf8) + var index = start + while index + marker.count <= bytes.count { + if bytes[index] == marker[0], starts(literal, at: index) { return index } + index += 1 + } + return nil + } + + private func starts(_ literal: String, at index: Int) -> Bool { + let marker = literal.utf8 + return index + marker.count <= bytes.count && bytes[index ..< index + marker.count].elementsEqual(marker) + } + + static func isWhitespace(_ bytes: ArraySlice) -> Bool { + bytes.allSatisfy { [9, 10, 13, 32].contains($0) } + } + + static func string(_ bytes: [UInt8], _ range: Range) -> String { + String(decoding: bytes[range], as: UTF8.self) + } } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift index 796d2a1fc9..05eeb70b9b 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift @@ -160,16 +160,18 @@ struct NativeToolStreamRouter { /// End of generation on the complete-call path: the handler's calls and /// its residual text. An `auto` GLM suffix that did not parse as one batch /// is split into text and its final calls (`GLM5ToolSuffix`), except in an - /// output the token limit cut off, where it stays text. - func finishCompleteCalls(truncated: Bool) -> (calls: [ToolCall], residual: String?) { + /// output the token limit cut off, where it stays text. A suffix whose + /// release would expose a think marker from inside a tool frame keeps + /// failing, as before. + func finishCompleteCalls(truncated: Bool) throws -> (calls: [ToolCall], residual: String?) { guard let handler else { return ([], nil) } let calls = handler.finish() let residual = handler.takeResidualText() - guard returnsUnparsedGLMOutputAsText, !truncated, calls.isEmpty, let residual else { - return (calls, residual) + guard returnsUnparsedGLMOutputAsText, calls.isEmpty, let residual else { return (calls, residual) } + switch GLM5ToolSuffix.split(residual, tools: tools) { + case .text(let text, calls: let found): return truncated ? ([], residual) : (found, text) + case .ambiguous: throw MultiModelBatchSchedulerEngineError.generationFailed("native GLM tool output is invalid") } - let split = GLM5ToolSuffix.split(residual, tools: tools) - return (split.calls, split.text) } private var returnsUnparsedGLMOutputAsText: Bool { diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift index 27625f9a3a..aa56956191 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift @@ -98,10 +98,12 @@ struct GLM5ToolFailureTests { #expect(ProviderLoop.mapInferenceErrorToStatus(failure) == 422) } + static let storeTool = #"{"type":"function","function":{"name":"store","parameters":{"type":"object","properties":{"doc":{"type":"object"}},"required":["doc"]}}}"# + /// The delimiters quoted inside a JSON argument are data: the calls start /// at the real frame, not at a quoted tag. @Test func quotedDelimitersStayArgumentData() async throws { - let tool = #"{"type":"function","function":{"name":"store","parameters":{"type":"object","properties":{"doc":{"type":"object"}},"required":["doc"]}}}"# + let tool = Self.storeTool let output = "See here.storedoc" + #"{"x":"store"}"# let result = try await run(output, forced: false, width: 3, tool: tool) @@ -134,14 +136,42 @@ struct GLM5ToolFailureTests { #expect(clean.failure == nil && clean.calls.count == 1 && clean.visible == "Need it.") } - /// The search for the calls' first frame is bounded. - @Test func callsAfterTooManyTagsStayText() async throws { - let mentions = String(repeating: " ", count: GLM5ToolSuffix.maximumStarts) - let within = try await run(String(mentions.dropFirst(12)) + valid, forced: false, width: 4096) - #expect(within.calls.count == 1 && within.failure == nil) - let beyond = try await run(mentions + valid, forced: false, width: 4096) - #expect(beyond.calls.isEmpty && beyond.failure == nil) - #expect(beyond.visible == mentions + valid) + /// A frame that has started its arguments owns everything up to its own + /// ``: a frame inside an argument, or after one, is data and + /// never becomes a call, whether the outer frame is cut off or closed. + @Test(arguments: [nil, "length"], [1, 7, 4096]) + func framesInsideAFrameAreNeverCalls(finishReason: String?, width: Int) async throws { + let nested = "storedoc{}" + let cases: [(output: String, tool: String?)] = [ + ("storedoc{\"x\":\"" + nested, Self.storeTool), + ("echotextdraft " + valid, nil), + ("Use .echotextajunk" + valid, nil), + ] + for shape in cases { + let result = try await run(shape.output, forced: false, width: width, finishReason: finishReason, + tool: shape.tool) + #expect(result.failure == nil && result.calls.isEmpty, "\(shape.output)") + #expect(result.visible == shape.output, "\(shape.output)") + } + } + + /// Released text would hand a think marker from inside a drafted call to + /// the service's reasoning parser as a channel boundary: that response keeps + /// failing, as before. + @Test func thinkMarkerInsideAReleasedFrameStillFails() async throws { + let draft = "Draft echotext" + for output in [draft + "PRIVATEAnswer", draft + " more." + valid] { + let result = try await run(output, forced: false, width: 5) + #expect(result.calls.isEmpty && result.visible == "Draft ") + #expect(result.failure == .generationFailed("native GLM tool output is invalid")) + } + } + + /// Finding the calls is linear in the suffix: many mentions before them. + @Test func manyMentionsBeforeTheCalls() async throws { + let mentions = String(repeating: " ", count: 20_000) + let result = try await run(mentions + valid, forced: false, width: 65536) + #expect(result.failure == nil && result.calls.count == 1 && result.visible == mentions) } /// `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure. @@ -155,7 +185,7 @@ struct GLM5ToolFailureTests { tools: prepared.tools?.map { $0.toolSpec() }, glmUnparsedOutputIsText: textFallback) _ = try router.process("Wrap it in tags." + valid) _ = try router.finishText() - let finished = router.finishCompleteCalls(truncated: false) + let finished = try router.finishCompleteCalls(truncated: false) if textFallback { try router.checkNativeToolFailure() #expect(finished.calls.count == 1) From 0d73e281142e83817c31e116ba42a34c930a4658 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:52:12 -0800 Subject: [PATCH 10/26] refactor(provider): one ParallelToolCallPolicy; the router drops later frames before routing them Same behavior as the previous commit, fewer lines shared with the other 0.10.13 tool-output PRs (#2053 changes the same `routeToolSegment` cases and adds `validateWithheld` where `admitted` was): - `ParallelToolCallPolicy` (new file) holds `admitted` (withheld calls: the first) and `LaterCallFilter` (streamed segments of every call after the first are consumed: `.callStarted` opens a dropped frame, its arguments and its completion or failure are swallowed, and an unexposed `.call` after an exposed one is dropped before validation). - `NativeToolStreamRouter`: one stored filter and one line at the top of `routeToolSegment`; the case bodies and `admitCall` are back to `dev` (its parallel throw is unreachable now, kept as defense in depth). - `ToolConstraintValidation` is back to `dev`; the scheduler's terminal flush and Nemotron Super's output call `ParallelToolCallPolicy.admitted`. - inference.md: the "holds either way" sentence is back to `dev` (still true: one call); the streamed-calls paragraph names the policy. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 10 ++--- .../MultiModelBatchSchedulerEngine.swift | 2 +- .../Prompting/ToolChoicePromptPolicy.swift | 2 +- .../Streaming/NativeToolStreamRouter.swift | 33 +++++--------- .../Streaming/NemotronSuperLocalOutput.swift | 2 +- .../Tools/ParallelToolCallPolicy.swift | 44 +++++++++++++++++++ .../Tools/ToolConstraintValidation.swift | 9 ---- .../Streaming/StreamedToolCallTests.swift | 6 +-- 8 files changed, 65 insertions(+), 43 deletions(-) create mode 100644 provider-swift/Sources/ProviderCore/Inference/Tools/ParallelToolCallPolicy.swift diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 8c4598c9aa..6e307a047c 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3545,10 +3545,10 @@ complete parse must agree with everything already exposed `NativeToolStreamRouter` admits `parallel_tool_calls` cardinality at the first fragment: with `parallel_tool_calls: false` it exposes the first call only and consumes every later frame without exposing or validating it, as OpenAI -returns one call and vLLM keeps the first (the complete-call paths, Nemotron -Super's included, keep the first through `ToolConstraintValidation.admitted`). -When the request is `strict` (below), it validates name and schema at frame -close; the service renders OpenAI fragments (`index`, `id`, `type` +returns one call and vLLM keeps the first; the complete-call paths, Nemotron +Super's included, keep the first the same way (`ParallelToolCallPolicy`). When +the request is `strict` (below), it validates name and schema at frame close; +the service renders OpenAI fragments (`index`, `id`, `type` and `function.name` first, then `function.arguments` pieces). A response that begins with a call therefore reaches its first content frame at the function name instead of the engine terminal, which also ends the frame loop's @@ -3561,7 +3561,7 @@ function and arguments off the declared schema are returned instead of failing a response whose reasoning has already streamed. The request stays validated when any declared function sets `strict: true`, when it declares no tools (a call is then never returned), and for `required`, named and `none` -choices; `parallel_tool_calls: false` returns the first call either way, and a call parsed from +choices; `parallel_tool_calls: false` holds either way, and a call parsed from a frame that `max_tokens` cut off is still validated (it may be missing arguments). Strict `auto` checks each call against the caller's schema as sent diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index f226702ef5..74548901e8 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -1917,7 +1917,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { continuation.finish() return } - let toolCalls = ToolConstraintValidation.admitted(toolHandler?.finish() ?? [], prepared: prepared) + let toolCalls = ParallelToolCallPolicy.admitted(toolHandler?.finish() ?? [], prepared: prepared) do { try router.checkNativeToolFailure() } catch { diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift index 3813884f81..bdcf4580d3 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift @@ -21,7 +21,7 @@ enum ToolChoicePromptPolicy { /// every GLM slot; a pair also asks for at most one call when /// automatic choice has `parallel_tool_calls: false` /// (`singleCallInstruction`); a response keeps only its first call - /// (`ToolConstraintValidation.admitted`). + /// (`ParallelToolCallPolicy.admitted`). var glm5PairPostValidation = false /// The caller's declarations as sent, before ingress normalization /// (`ToolSchemaNormalization`) filled in render types. Validation of diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift index 547fd23ad3..29c2f1d305 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift @@ -23,9 +23,8 @@ struct NativeToolStreamRouter { private var exposedCallCount = 0 private var openCallIndex: Int? private var openCallName: String? - /// The open frame is a call made after the one `parallel_tool_calls: - /// false` allows: it is consumed and nothing of it is exposed. - private var droppingCall = false + /// `parallel_tool_calls: false`: the frames of calls after the first. + private var laterCalls = ParallelToolCallPolicy.LaterCallFilter() /// Every call exposed so far whose frame parsed, each already accepted by /// `ToolConstraintValidation` (which returns `auto` calls as generated /// unless the request is `strict`). @@ -207,15 +206,12 @@ struct NativeToolStreamRouter { private mutating func routeToolSegment( _ segment: ToolCallStreamSegment, prepared: ToolChoicePromptPolicy.Prepared, truncated: Bool = false ) throws -> [MLXServerGenerationEvent] { + if laterCalls.drops(segment, exposedCalls: exposedCallCount, prepared: prepared) { return [] } switch segment { case .text(let text): return text.isEmpty ? [] : [visibleEvent(text)] case .callStarted(let name): - guard admitsCall(prepared) else { - droppingCall = true - return [] - } - let index = admitCall() + let index = try admitCall(prepared) openCallIndex = index openCallName = name return [.toolCallDelta(.init(index: index, name: name))] @@ -223,7 +219,6 @@ struct NativeToolStreamRouter { guard let index = openCallIndex, !fragment.isEmpty else { return [] } return [.toolCallDelta(.init(index: index, arguments: fragment))] case .callCompleted(let call, let remainder): - droppingCall = false guard let index = openCallIndex else { return [] } openCallIndex = nil try ToolConstraintValidation.validate([call], prepared: prepared, truncated: truncated) @@ -231,10 +226,6 @@ struct NativeToolStreamRouter { return [.toolCallDelta(.init(index: index, arguments: remainder, completed: call))] case .callFailed(let failure): defer { openCallIndex = nil } - if droppingCall { - droppingCall = false - return [] - } guard prepared.returnsAutoCallsAsGenerated, let index = openCallIndex, let name = openCallName else { throw MultiModelBatchSchedulerEngineError.toolChoiceViolation( @@ -249,9 +240,8 @@ struct NativeToolStreamRouter { completed: ToolCall(function: .init(name: name, arguments: [String: MLXLMCommon.JSONValue]()))))] case .call(let call): // Never exposed (e.g. an undeclared name): validate before showing. - guard admitsCall(prepared) else { return [] } try ToolConstraintValidation.validate([call], prepared: prepared, truncated: truncated) - let index = admitCall() + let index = try admitCall(prepared) completedToolCalls.append(call) let arguments = String( decoding: try JSONEncoder.openAIServer.encode(call.function.arguments), as: UTF8.self) @@ -260,14 +250,11 @@ struct NativeToolStreamRouter { } } - /// With `parallel_tool_calls: false` only the first call is exposed, as - /// OpenAI and vLLM return it (`ToolConstraintValidation.admitted`); later - /// calls are dropped, never a failure after the first already streamed. - private func admitsCall(_ prepared: ToolChoicePromptPolicy.Prepared) -> Bool { - prepared.allowsParallelCalls || exposedCallCount == 0 - } - - private mutating func admitCall() -> Int { + private mutating func admitCall(_ prepared: ToolChoicePromptPolicy.Prepared) throws -> Int { + if !prepared.allowsParallelCalls, exposedCallCount > 0 { + throw MultiModelBatchSchedulerEngineError.toolChoiceViolation( + ToolNoncomplianceCheck.parallelViolation) + } defer { exposedCallCount += 1 } return exposedCallCount } diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NemotronSuperLocalOutput.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NemotronSuperLocalOutput.swift index 5e98611b1b..17f8842cbf 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NemotronSuperLocalOutput.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NemotronSuperLocalOutput.swift @@ -79,7 +79,7 @@ struct NemotronSuperLocalOutput { reasoning = split.reasoning ?? "" _ = try route([.init(content: split.content ?? "", reasoningContent: nil)]) } - let calls = ToolConstraintValidation.admitted(handler?.finish() ?? [], prepared: plan.toolPolicy) + let calls = ParallelToolCallPolicy.admitted(handler?.finish() ?? [], prepared: plan.toolPolicy) let residual = handler?.takeResidualText() ?? "" let forced = plan.toolPolicy.requiresToolCall // route refuses mid-stream parse failures, so any failure here is the diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/ParallelToolCallPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/ParallelToolCallPolicy.swift new file mode 100644 index 0000000000..09ca65ae19 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/ParallelToolCallPolicy.swift @@ -0,0 +1,44 @@ +// Copyright © 2026 Eigen Labs. + +import MLXLMCommon + +/// `parallel_tool_calls: false`: a response carries one call, the first. OpenAI +/// returns at most one, and vLLM keeps the first +/// (`maybe_filter_parallel_tool_calls`). The calls a model makes after it are +/// dropped instead of failing a response that may already have streamed the +/// first; no template reads the flag, so nothing in the prompt asked for one +/// call. `ToolConstraintValidation.validate` keeps its cardinality check as +/// defense in depth. +enum ParallelToolCallPolicy { + /// The calls a response returns from those withheld until the end. + static func admitted(_ calls: [ToolCall], prepared: ToolChoicePromptPolicy.Prepared) -> [ToolCall] { + prepared.allowsParallelCalls ? calls : Array(calls.prefix(1)) + } + + /// Drops the streamed segments of every call after the first: a dropped + /// frame is consumed, never exposed or validated. + struct LaterCallFilter { + private var droppingFrame = false + + /// `exposedCalls`: calls of this response already exposed. + mutating func drops( + _ segment: ToolCallStreamSegment, exposedCalls: Int, prepared: ToolChoicePromptPolicy.Prepared + ) -> Bool { + guard !prepared.allowsParallelCalls else { return false } + switch segment { + case .text: + return false + case .callStarted: + droppingFrame = exposedCalls > 0 + return droppingFrame + case .callArguments: + return droppingFrame + case .callCompleted, .callFailed: + defer { droppingFrame = false } + return droppingFrame + case .call: + return exposedCalls > 0 + } + } + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintValidation.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintValidation.swift index af0ec9c1e1..16eaaf0adf 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintValidation.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintValidation.swift @@ -111,15 +111,6 @@ enum ToolConstraintValidation { } } - /// The calls a response returns. With `parallel_tool_calls: false` that is - /// the first call only, as OpenAI and vLLM return it: calls the model makes - /// after it are dropped instead of failing the response. Callers pass - /// their calls through here before `validate`, whose cardinality check - /// stays as defense in depth. - static func admitted(_ calls: [ToolCall], prepared: ToolChoicePromptPolicy.Prepared) -> [ToolCall] { - prepared.allowsParallelCalls ? calls : Array(calls.prefix(1)) - } - /// Reserved-metadata forgery guard for untrusted payloads. The /// `originalBooleanSchemaKey` marker is injected by our own normalizer, so /// a client that sends it is forging internal state. diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift index 0b951f1307..df25574e59 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift @@ -252,14 +252,14 @@ struct StreamedToolCallTests { let second = ToolCall(function: .init(name: "get_weather", arguments: ["location": "Rome"])) for choice in [nil, OpenAIToolChoice.mode(.required), .function(name: "get_weather")] { let single = try ToolChoicePromptPolicy.prepare(Self.request(choice, parallel: false), modelType: "gemma4") - let admitted = ToolConstraintValidation.admitted([first, second], prepared: single) + let admitted = ParallelToolCallPolicy.admitted([first, second], prepared: single) #expect(admitted == [first]) try ToolConstraintValidation.validate(admitted, prepared: single) let parallel = try ToolChoicePromptPolicy.prepare(Self.request(choice), modelType: "gemma4") - #expect(ToolConstraintValidation.admitted([first, second], prepared: parallel) == [first, second]) + #expect(ParallelToolCallPolicy.admitted([first, second], prepared: parallel) == [first, second]) } let none = try ToolChoicePromptPolicy.prepare(Self.request(parallel: false), modelType: "gemma4") - #expect(ToolConstraintValidation.admitted([], prepared: none).isEmpty) + #expect(ParallelToolCallPolicy.admitted([], prepared: none).isEmpty) } /// The second partial holds a `}`, so Gemma's lenient EOS parse reads a From 78febeb0181ca82f0ab70ae066d217580c8cf4c6 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:57:45 -0800 Subject: [PATCH 11/26] test(provider): review findings on #2049: the stale Super test, failed later frames, the engine terminal The independent review of 0d73e28114 (CHANGES REQUESTED): - B1: `NemotronSuperLocalOutputTests.testToolPolicyViolationsFailClosed` still expected two calls under `parallel_tool_calls: false` to throw; CI run 43374842176 failed exactly there. The case moves to its own test, which expects the first call (streamed and complete) and both calls without the flag. - Nothing covered the filter's `.callFailed` / `.callCompleted` branches: `failedLaterFramesAreDroppedToo` drops a later Gemma frame that closes against what it streamed, one cut by the end of generation (unterminated, diverged) and one ended by the stop token, strict or not, at the token limit or not. Without those branches the dropped frame's failure reaches `routeToolSegment` and fails the stream. - Nothing covered the scheduler's complete-call terminal: `completeCallTerminalReturnsTheFirstCall` serves a forced Gemma choice with two calls through the service and the engine's event stream. - `StructuredForcedToolAdmissionTests.serve` mirrors the engine terminal again (`ParallelToolCallPolicy.admitted`), and its forced `parallel_tool_calls: false` case expects the first call (Qwen 3.5, 3.6, MiMo) instead of the old violation. All of these fail on dev 6bc14de2c2, where a second call throws. Co-Authored-By: Claude Opus 5.5 --- .../Streaming/StreamedToolCallTests.swift | 55 +++++++++++++++++++ .../StructuredForcedToolAdmissionTests.swift | 18 +++--- .../NemotronSuperLocalOutputTests.swift | 20 ++++++- 3 files changed, 80 insertions(+), 13 deletions(-) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift index df25574e59..24e8e96e15 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/StreamedToolCallTests.swift @@ -262,6 +262,61 @@ struct StreamedToolCallTests { #expect(ParallelToolCallPolicy.admitted([], prepared: none).isEmpty) } + /// A later frame that fails is dropped as quietly as one that parses: one + /// that closes against what it streamed (a repeated key), one cut by the + /// end of generation (unterminated or diverged), and one whose end tag is + /// the stop token, at the token limit or not. + @Test(arguments: [ + #"<|tool_call>call:get_weather{location:<|"|>Rome<|"|>,location:<|"|>Oslo<|"|>}"#, + #"<|tool_call>call:write_file{path:<|"|>a.py<|"|>,content:<|"|>print("#, + #"<|tool_call>call:write_file{path:<|"|>a.py<|"|>,content:<|"|>def f(): return {"a": 1}"#, + #"<|tool_call>call:get_weather{location:<|"|>Rome<|"|>}"#, + ]) + func failedLaterFramesAreDroppedToo(later: String) throws { + for strict in [false, true] { + for truncated in [false, true] { + var router = try Self.router(Self.request(parallel: false, strict: strict)) + var events: [MLXServerGenerationEvent] = [] + for character in Self.characters(Self.gemmaCall(#"location:<|"|>Paris<|"|>"#) + later) { + events += try router.process(character) + } + events += try router.finishText() + events += try router.finishToolCalls(truncated: truncated) + let deltas = Self.deltas(events) + #expect(events.count == deltas.count, "strict \(strict) truncated \(truncated)") + #expect(deltas.allSatisfy { $0.index == 0 }, "strict \(strict) truncated \(truncated)") + #expect(deltas.compactMap(\.name) == ["get_weather"], "strict \(strict) truncated \(truncated)") + #expect(router.completedToolCalls.map(\.function.arguments) == [["location": .string("Paris")]], + "strict \(strict) truncated \(truncated)") + } + } + } + + /// The engine's complete-call terminal (here a forced choice, whose calls + /// are withheld until generation ends) returns the first call as well. + @Test func completeCallTerminalReturnsTheFirstCall() async throws { + let upstream = AsyncStream.makeStream() + let text = Self.gemmaCall(#"location:<|"|>Paris<|"|>"#) + Self.gemmaCall(#"location:<|"|>Rome<|"|>"#) + for chunk in Self.characters(text) { upstream.continuation.yield(.chunk(chunk)) } + upstream.continuation.yield(.info(promptTokens: 9, completionTokens: 30, tokensPerSecond: 0, + finishReason: nil)) + upstream.continuation.finish() + var frames: [String] = [] + for try await frame in try await MLXOpenAIService( + engine: RoutedEngine(upstream: upstream.stream, modelType: "gemma4") + ).streamChatCompletionFrames(request: try Self.request(.mode(.required), parallel: false)) { + frames.append(frame) + } + let parsed = frames.compactMap(ProviderLoop.parseStreamChunk) + let deltas = parsed.flatMap { $0.toolCallsDelta ?? [] } + #expect(deltas.allSatisfy { $0.index == 0 }) + #expect(deltas.compactMap { $0.function?.name } == ["get_weather"]) + let arguments = deltas.compactMap { $0.function?.arguments }.joined() + #expect(try JSONDecoder().decode([String: MLXLMCommon.JSONValue].self, from: Data(arguments.utf8)) + == ["location": .string("Paris")]) + #expect(parsed.contains { $0.finishReason == "tool_calls" }) + } + /// The second partial holds a `}`, so Gemma's lenient EOS parse reads a /// garbled call that contradicts the exposed arguments. @Test(arguments: [ diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/StructuredForcedToolAdmissionTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/StructuredForcedToolAdmissionTests.swift index a7accc2686..f67bc8951c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/StructuredForcedToolAdmissionTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/StructuredForcedToolAdmissionTests.swift @@ -160,6 +160,13 @@ struct StructuredForcedToolAdmissionTests { let parallel = try serve(build, request, prepared, output: parallelOutput, width: width) #expect(parallel.map(\.function.name) == ["get_weather", "get_time"], "\(build.id) width \(width)") } + // parallel_tool_calls=false returns the first call, as OpenAI and vLLM do. + let single = try self.request(build, choice: Self.required, parallel: false) + let singlePrepared = try ToolChoicePromptPolicy.prepare(single, modelType: build.modelType) + for width in [1, 5, Int.max] { + let first = try serve(build, single, singlePrepared, output: parallelOutput, width: width) + #expect(first.map(\.function.name) == ["get_weather"], "\(build.id) width \(width)") + } } } @@ -224,15 +231,6 @@ struct StructuredForcedToolAdmissionTests { output: answer(build, frame(build, "delete_files", ["path": "/"]))) } - // parallel_tool_calls=false admits exactly one call. - let single = try self.request(build, choice: Self.required, parallel: false) - let singlePrepared = try ToolChoicePromptPolicy.prepare(single, modelType: build.modelType) - try expectViolation(build) { - _ = try serve(build, single, singlePrepared, output: answer(build, - frame(build, "get_weather", ["city": "Paris"]) + "\n" - + frame(build, "get_weather", ["city": "Rome"]))) - } - // Malformed policies are client errors before any generation. let undeclared = try self.request(build, choice: ["type": "function", "function": ["name": "get_stock_price"]] as [String: Any]) @@ -320,7 +318,7 @@ struct StructuredForcedToolAdmissionTests { continue } } - let calls = handler.finish() + let calls = ParallelToolCallPolicy.admitted(handler.finish(), prepared: prepared) try router.checkNativeToolFailure() try ToolConstraintValidation.validate(calls, prepared: prepared) return calls diff --git a/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift b/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift index d05051133d..dadccdcc44 100644 --- a/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift @@ -244,9 +244,6 @@ final class NemotronSuperLocalOutputTests: XCTestCase { _ = try none.append("" + one) XCTAssertThrowsError(try none.finish(), tools) } - var parallel = try output(Self.weather + #","parallel_tool_calls":false"#) - _ = try parallel.append("" + one + one) - XCTAssertThrowsError(try parallel.finish()) var required = try output(Self.weather + #","tool_choice":"required""#) XCTAssertThrowsError(try required.append("Sure, here it is.")) var requiredMissing = try output(Self.weather + #","tool_choice":"required""#) @@ -257,6 +254,23 @@ final class NemotronSuperLocalOutputTests: XCTestCase { ["R:plan", #"F:get_weather{"city":"A"}"#]) } + /// `parallel_tool_calls: false` returns the first call, as OpenAI and + /// vLLM do, instead of failing a response that made a second one. + func testParallelCallsDisabledKeepTheFirstCall() throws { + let one = "\n\n\nA\n\n\n" + let two = one.replacingOccurrences(of: "\nA\n", with: "\nB\n") + for streaming in [true, false] { + var parallel = try output(Self.weather + #","parallel_tool_calls":false"#, streaming: streaming) + _ = try parallel.append("" + one + two) + let finished = try parallel.finish() + XCTAssertEqual(finished.result.calls.map(\.function.arguments), [["city": .string("A")]]) + XCTAssertEqual(try trace(finished.events).filter { $0.hasPrefix("F:") }, [#"F:get_weather{"city":"A"}"#]) + } + var parallel = try output(Self.weather) + _ = try parallel.append("" + one + two) + XCTAssertEqual(try parallel.finish().result.calls.count, 2) + } + func testStructuredOutputIsWithheldValidatedAndNormalized() throws { var object = try output(#""response_format":{"type":"json_object"}"#) XCTAssertEqual(try object.append("Short plan."), [.parsed(.init(content: "", reasoningContent: "Short plan."))]) From 15f7d676e9ad60d650f2eed8879fa0faebaf975a Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:57:45 -0800 Subject: [PATCH 12/26] docs(provider): #2049's wording after review: the prompt, malformed later frames - The prompt does ask for one call in two cases (a GLM pair's automatic choice, and forced choices with `parallel_tool_calls: false`), so the changelog and `ParallelToolCallPolicy` now say "under automatic choice" and "only a GLM pair's prompt does". - A later frame keeps its family's malformed-output rule: GLM, MiMo, Flint and Nemotron Super still fail a response on any frame that does not parse, and a frame a parser returns as text (an undeclared name on Qwen or Gemma) stays text (changelog, inference.md, the policy's doc). The "holds either way" sentence in inference.md is left as is: #2053 rewrites that sentence, and its fold resolution already carries this PR. Co-Authored-By: Claude Opus 5.5 --- changelog.d/parallel-tool-calls-false-first-call.md | 4 ++-- docs/architecture/inference.md | 9 ++++++--- .../Inference/Tools/ParallelToolCallPolicy.swift | 7 ++++--- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/changelog.d/parallel-tool-calls-false-first-call.md b/changelog.d/parallel-tool-calls-false-first-call.md index 85c975608f..37b799e7f5 100644 --- a/changelog.d/parallel-tool-calls-false-first-call.md +++ b/changelog.d/parallel-tool-calls-false-first-call.md @@ -1,4 +1,4 @@ ### `parallel_tool_calls: false` returns the first tool call instead of failing the response -- With `parallel_tool_calls: false`, a model that made a second call failed the whole response: a streamed answer ended in an error after its first call had already been sent, and a complete answer was a 422. Nothing in the prompt asks the model for a single call, so this was the provider failing a valid request. -- The response now carries the first call, as OpenAI and vLLM return it, and the calls the model makes after it are dropped. This holds for every model and path, Nemotron Super's included, streamed or not. +- With `parallel_tool_calls: false`, a model that made a second call failed the whole response: a streamed answer ended in an error after its first call had already been sent, and a complete answer was a 422. Under automatic tool choice the prompt does not ask for a single call (only a GLM pair's prompt does), so these were requests the provider should have served. +- The response now carries the first call, as OpenAI and vLLM return it, and the calls the model makes after it are dropped, streamed or not, on every model, Nemotron Super's path included. A later frame that does not parse keeps the existing rule for malformed output: GLM, MiMo, Flint and Nemotron Super fail the response, as for any malformed frame, and a frame that never reads as a call (an undeclared name on Qwen or Gemma) stays text. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 6e307a047c..0aba69ac4e 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3544,9 +3544,12 @@ complete parse must agree with everything already exposed (`libs/mlx-swift-lm/Libraries/MLXLMCommon/Tool/ToolCallStreaming.swift`). `NativeToolStreamRouter` admits `parallel_tool_calls` cardinality at the first fragment: with `parallel_tool_calls: false` it exposes the first call only and -consumes every later frame without exposing or validating it, as OpenAI -returns one call and vLLM keeps the first; the complete-call paths, Nemotron -Super's included, keep the first the same way (`ParallelToolCallPolicy`). When +drops every later call frame, unexposed and unvalidated, as OpenAI returns one +call and vLLM keeps the first; the complete-call paths, Nemotron Super's +included, keep the first the same way (`ParallelToolCallPolicy`). A later +frame keeps its family's malformed-output rule: one the parser returns as +text (an undeclared name it cannot read) stays visible text, and one that does +not parse still fails a GLM, MiMo, Flint or Nemotron Super response. When the request is `strict` (below), it validates name and schema at frame close; the service renders OpenAI fragments (`index`, `id`, `type` and `function.name` first, then `function.arguments` pieces). A response that diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/ParallelToolCallPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/ParallelToolCallPolicy.swift index 09ca65ae19..6e81e9b4fe 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Tools/ParallelToolCallPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/ParallelToolCallPolicy.swift @@ -6,9 +6,10 @@ import MLXLMCommon /// returns at most one, and vLLM keeps the first /// (`maybe_filter_parallel_tool_calls`). The calls a model makes after it are /// dropped instead of failing a response that may already have streamed the -/// first; no template reads the flag, so nothing in the prompt asked for one -/// call. `ToolConstraintValidation.validate` keeps its cardinality check as -/// defense in depth. +/// first; under automatic choice the prompt does not ask for one call (only a +/// GLM pair's does). A later frame that does not parse keeps its family's +/// malformed-output rule. `ToolConstraintValidation.validate` keeps its +/// cardinality check as defense in depth. enum ParallelToolCallPolicy { /// The calls a response returns from those withheld until the end. static func admitted(_ calls: [ToolCall], prepared: ToolChoicePromptPolicy.Prepared) -> [ToolCall] { From 98a9cded8ca6c86b94c77708566211f86bdbd30c Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:03:54 -0800 Subject: [PATCH 13/26] refactor(provider): the 9B penalty fix's wording and names (review-2051, refactor pass) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Behaviour unchanged: the same defaults, switch values, passthrough and assertions. From the independent review of 37f0e6277a (APPROVE; should-fix 1-3, nit 5), applied by the AGENTS.md refactor pass: - The registry shadows the kill switch. While the coordinator's registry sets presence_penalty for the 9B, routed requests carry it, so DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0 affects only local requests. A routed rollback also needs the registry value removed or set to 0. Said in configuration.md, the changelog and the key's doc comment. - The root cause is worded as the evidence allows: "constrained JSON rows" (a schema outside the subset is served prompt-only), and "the difference we can establish" (32.7 % vs 13.6 % with nothing else running), not "the penalty alone". - One number pair everywhere. "About three times" is 5.5 % vs 1.7 % of answers with max_tokens >= 8,192 over the same period (9B-MIDFAIL §4.5). "The same 10-minute windows" goes with the JSON workload's 51 % vs 23 % only (§4.1). inference.md had attached 6.1 % vs 1.5 % to the 10-minute windows. - Tests: - qwen35OmittedPresencePenaltyFollowsEachBuildsGate is renamed qwen35OmittedPresencePenaltyIsTheCardsOnEveryBuild, and its vestigial per-build penalty column is dropped (same assertions). - The launchd test now uses the file's unnamed @Test style. --- .../qwen35-9b-card-presence-penalty.md | 4 +-- docs/architecture/inference.md | 2 +- docs/reference/configuration.md | 2 +- .../Engine/EngineV2SamplingDefaults.swift | 34 +++++++++++-------- .../EngineV2SamplingDefaultsTests.swift | 34 +++++++++++-------- .../Qwen35CardDefaultDonationTests.swift | 4 +-- 6 files changed, 44 insertions(+), 36 deletions(-) diff --git a/changelog.d/qwen35-9b-card-presence-penalty.md b/changelog.d/qwen35-9b-card-presence-penalty.md index 8ecb4ef6fb..e757beaf70 100644 --- a/changelog.d/qwen35-9b-card-presence-penalty.md +++ b/changelog.d/qwen35-9b-card-presence-penalty.md @@ -1,5 +1,5 @@ ### Qwen 3.5 9B keeps its model card's presence penalty -- Provider 0.10.12 dropped the default `presence_penalty` of 1.5 from the catalog `Qwen3.5-9B` for requests that send none. In production its answers then ran to `max_tokens` about three times as often, and JSON `response_format` answers that ran out failed about twice as often. 0.10.13 restores the model card's 1.5 for those requests, as on the other catalog Qwen 3.5/3.6 builds. +- Provider 0.10.12 dropped the default `presence_penalty` of 1.5 from the catalog `Qwen3.5-9B` for requests that send none. In production its answers with `max_tokens` of 8,192 or more then ran to the limit about three times as often (5.5 % against 1.7 % on 0.10.11), and JSON `response_format` answers ran out and failed about twice as often (51 % against 23 % in the same 10-minute windows). 0.10.13 restores the model card's 1.5 for those requests, as on the other catalog Qwen 3.5/3.6 builds. - A request that sends its own `presence_penalty` is unchanged. With `presence_penalty` 0 the 9B still speculates under exact MTP acceptance. A penalty row does not speculate but still donates prefix-cache checkpoints. -- `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` (or `off`) restores 0.10.12's default. `darkbloom start` passes it to the launchd job. +- `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` (or `off`) restores 0.10.12's default. `darkbloom start` passes it to the launchd job. A coordinator registry `presence_penalty` arrives as the request's own value and wins, so while the registry sets one for the 9B the switch changes only local requests; rolling routed traffic back also needs the registry value removed or set to 0. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 9c20afafd0..2b43900f38 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3161,7 +3161,7 @@ themselves until `max_tokens` (#1530). Every build also takes the cards' | Build | Omitted `presence_penalty` | Built-in MTP acceptance | Without the penalty | |---|---|---|---| | `qwen3.5-35b-a3b`, `qwen3.6-35b-a3b-vl-mtp-mxfp8` | 1.5 | typical | The 0.10.12 gate on the signed 0.10.11 (temperature 1 / 0.95 / 20; #1652's four loopers and five tool transcripts at 32,768 tokens, nineteen everyday prompts at 8,192, three seeds each; an M5 Ultra): `qwen3.5-35b-a3b` ran away under typical acceptance (5 of 19 everyday prompts, 8 of 12 loopers to 32,768, MTP running at concurrency 1) and under exact (2 of 12 loopers); the 3.6 build shares its architecture | -| `Qwen3.5-9B` | 1.5; none under `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` (`qwen35NineBNoPenaltyDefaults`, 0.10.12's default) | **exact** (`MTPAcceptancePolicy.builtInIsExact`) | The same gate (the Studio M3 Ultra) saw it run away on 13 of 31 draws under typical acceptance and on 0 of 31 under exact, so 0.10.12 shipped it without the penalty. In production that was a regression. On 2026-11-12, on 0.10.12 Macs against 0.10.11 Macs (the penalty, MTP off) in the same 10-minute windows, answers with `max_tokens` ≥ 8,192 hit the cap on 6.1 % against 1.5 %. On the 4,096-token JSON `response_format` workload, answers ran out and failed in 51 % of requests against 23 %. Those rows never speculate (a token constraint) and their template is unchanged since 0.10.4, so the penalty alone made the difference. A registry `presence_penalty` 1.5 brought both back within the hour | +| `Qwen3.5-9B` | 1.5; none under `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` (`qwen35NineBNoPenaltyDefaults`, 0.10.12's default) | **exact** (`MTPAcceptancePolicy.builtInIsExact`) | The same gate (the Studio M3 Ultra) saw it run away on 13 of 31 draws under typical acceptance and on 0 of 31 under exact, so 0.10.12 shipped it without the penalty. In production that was a regression. On 2026-11-12, on 0.10.12 Macs against 0.10.11 Macs (the penalty, MTP off) over the same period, answers with `max_tokens` ≥ 8,192 hit the cap on 5.5 % against 1.7 %, about three times as often. On the 4,096-token JSON `response_format` workload, in the same 10-minute windows, answers ran out and failed in 51 % of requests against 23 %. Its constrained JSON rows never speculate and their template is unchanged since 0.10.4, so the penalty is the difference we can establish: with nothing else running they failed 32.7 % against 13.6 %. A registry `presence_penalty` 1.5 brought both back within the hour | A row with a penalty does not speculate (`EngineLoopV2.mtpBasicEligible`), so these builds' requests that omit the penalty stay without MTP, the cost taken diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 3970fa8dbd..013f20e08f 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -560,7 +560,7 @@ and rollback are defined in the [provider configuration reference](../provider/c | `DARKBLOOM_PREFILL_DEADLINE_MODE` | exactly `off` disables; any other value enforces | `enforce` | `provider-swift/Sources/ProviderCore/Inference/Engine/PrefillDeadlineMode.swift` (`PrefillDeadlineMode.resolve`) | Prefill-deadline admission on the provider. Read only when `[backend] prefill_deadline_mode` is absent from `provider.toml`; that key takes precedence. | | `DARKBLOOM_TTFT_ADMISSION_FIXES` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`DeadlineAdmissionFixes`) | Deadline-admission estimator corrections: per-batch decode charging, anchored isolated-prefill rate, newest-observation freshness, a probe that re-measures stale isolated-prefill evidence after three refusals it explains. Off restores the previous estimators and turns that probe off too. Forwarded to the launchd provider job. | | `DARKBLOOM_TTFT_REFUSAL_PROBE` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`DeadlineRefusalProbe`) | The refusal streak's idle probe alone ([deadlines](../architecture/inference.md#deadlines)): off, refusals neither count nor start a probe, and the estimator corrections stay on. Forwarded to the launchd provider job. | -| `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY` | trimmed, case-insensitive `0`, `false`, `no`, `off` drop the default; any other value keeps it | on: the model card's 1.5 | `provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift` (`qwen35NineBKeepsCardPenalty`) | The catalog `Qwen3.5-9B`'s `presence_penalty` for a request that omits one (0.10.13; 0.10.12 had none, and its answers ran to `max_tokens` about three times as often). `0` restores 0.10.12's no-penalty default. A request's own value, the coordinator's registry default included, always wins. `darkbloom start` passes it to the launchd job. | +| `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY` | trimmed, case-insensitive `0`, `false`, `no`, `off` drop the default; any other value keeps it | on: the model card's 1.5 | `provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift` (`qwen35NineBKeepsCardPenalty`) | The catalog `Qwen3.5-9B`'s `presence_penalty` for a request that omits one (0.10.13; 0.10.12 had none, and its answers with `max_tokens` ≥ 8,192 ran to the limit about three times as often: 5.5 % against 1.7 %). `0` restores 0.10.12's no-penalty default. A request's own value, the coordinator's registry default included, always wins: while the registry sets `presence_penalty` for `Qwen3.5-9B`, routed requests carry it and `0` affects only local requests, so rolling routed traffic back also needs the registry value removed or set to `0`. `darkbloom start` passes it to the launchd job. | | `DARKBLOOM_TTFT_SHAPE_WARMUP` | trimmed, case-insensitive `0`, `false`, `no`, `off` disable; `always` skips the probe | unset: probe-gated warmup | `provider-swift/Sources/ProviderCore/Inference/Performance/ModelCalibrationPolicy.swift` (`shapeWarmupMode`) | Excluded load-time [shape warmup](../architecture/inference.md#model-startup-calibration) for ordinary `EngineV2` slots: a 128-token shader-cache probe runs twice and only a cold cache runs the shape cells, within 20 seconds per engine. Trains no rate or counter. Forwarded to the LaunchAgent. | | `DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL` | integer layers | projected from `provider.toml` (`18`) | `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift` | Gemma-4 prefill chunk-eval layers; the provider sets it for the engine, `scripts/install.sh` sets `18` for the smoke test. | | `DARKBLOOM_TTFT_GDN_BLOCKED` | `0`, `false`, `no`, `off` keep the stock kernel; `packed` or `rows` force that kernel; unset or any other value probes. Case-insensitive; surrounding whitespace is ignored | probe | `libs/mlx-swift-lm/Libraries/MLXLMCommon/GatedDelta.swift` (`GatedDeltaPrefill.mode`, `GatedDeltaPrefill.kernel`) | Selects the Gated DeltaNet prompt-window kernel of `qwen3_5`, `qwen3_5_moe` and `prism_hadamard_qwen35` models ([mechanism](../architecture/inference.md#context)). The default probe keeps a four-row kernel only where it reproduces `gated_delta_step` bit for bit on the GPU; it does not compare speed, so `0` is the rollback where a kept kernel is slower. Forced kernels skip that check and are for A/B measurement only. Decode, MTP verification and masked updates always use the stock kernel. Read once per process. Forwarded to the LaunchAgent. | diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift index c7f07baf16..4287ab057d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift @@ -25,9 +25,10 @@ // The catalog Qwen 3.5/3.6 builds take their model cards' thinking-mode // values instead of the greedy decoding that looped to `max_tokens`, // including the cards' presence penalty 1.5 (`qwen35CardDefaults`). -// 0.10.12 dropped it on Qwen3.5-9B, whose answers then ran to -// `max_tokens` about three times as often in production; 0.10.13 gives it -// back (`DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` is the rollback). +// 0.10.12 dropped it on Qwen3.5-9B, whose long answers then ran to +// `max_tokens` about three times as often in production (5.5 % against +// 1.7 %); 0.10.13 gives it back (`DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` +// is the rollback). // Every other model keeps the legacy defaults byte-for-byte. // * `do_sample: false` in the file means greedy (legacy), matching HF // semantics; an absent or unreadable file is legacy. @@ -81,23 +82,25 @@ public struct EngineV2SamplingDefaults: Sendable, Equatable { temperature: 1.0, topP: 0.95, topK: 20, presencePenalty: 1.5) /// Qwen3.5-9B under `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0`: the card's /// values without the penalty, 0.10.12's default. Its 31-draw gate saw no - /// loop under exact acceptance. In production (0.10.12 against 0.10.11 in - /// the same hour) its answers ran to `max_tokens` about three times as - /// often, and its JSON `response_format` answers, rows that never - /// speculate (a token constraint), ran out about twice as often: the - /// penalty alone made that difference. The registry's `presence_penalty` - /// 1.5 restored it on 2026-11-12. + /// loop under exact acceptance. In production, 0.10.12 against 0.10.11 + /// Macs over the same period, its answers with `max_tokens` ≥ 8,192 ran + /// to the limit about three times as often (5.5 % against 1.7 %), and + /// its constrained JSON `response_format` rows, which never speculate, + /// ran out and failed about twice as often (51 % against 23 % in the same + /// 10-minute windows). The penalty is the difference we can establish: + /// with nothing else running those rows failed 32.7 % against 13.6 %. + /// The registry's `presence_penalty` 1.5 restored it on 2026-11-12. static let qwen35NineBNoPenaltyDefaults = EngineV2SamplingDefaults( temperature: 1.0, topP: 0.95, topK: 20) static let qwen35NineBModelID = "Qwen3.5-9B" - /// `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY`: unset (or `1`, `on`, `true`) - /// keeps the card's 1.5 for Qwen3.5-9B requests that omit a presence - /// penalty; `0`, `off`, `false` or `no` restores 0.10.12's no-penalty - /// default. - /// Any other value keeps the card's. Only the 9B reads it. A request's own + /// `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY`: `0`, `off`, `false` or `no` + /// (trimmed, case-insensitive) restores 0.10.12's no-penalty default for + /// Qwen3.5-9B requests that omit a presence penalty; unset or any other + /// value keeps the card's 1.5. Only the 9B reads it. A request's own /// `presence_penalty`, the coordinator's registry default included, always - /// wins. + /// wins, so while the registry sets one the switch does not reach routed + /// traffic. static let qwen35NineBPenaltyEnvironmentKey = "DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY" static func qwen35NineBKeepsCardPenalty(environment: [String: String]) -> Bool { @@ -106,6 +109,7 @@ public struct EngineV2SamplingDefaults: Sendable, Equatable { else { return true } return !["0", "off", "false", "no"].contains(raw) } + static let qwen35CardModelTypes = [ "Qwen3.5-9B": "qwen3_5", "qwen3.5-35b-a3b": "qwen3_5_moe", diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift index d0b75157f6..d5067ffc8f 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift @@ -107,20 +107,24 @@ struct EngineV2SamplingDefaultsTests { /// Every catalog Qwen 3.5/3.6 build keeps the cards' 1.5 for a request /// that omits the penalty. Without it qwen3.5-35b-a3b looped under both MTP /// acceptance rules in the 0.10.12 gate. Qwen3.5-9B passed that gate under - /// exact acceptance (0 of 31 draws), so 0.10.12 dropped its penalty; in - /// production its answers then ran to `max_tokens` about three times as - /// often, and its JSON `response_format` answers (rows that never - /// speculate) ran out about twice as often as on 0.10.11 in the same hour - /// (9B-MIDFAIL). The coordinator's body adds the registry's temperature, - /// top_p and top_k, and the penalty only where the registry sets one. A - /// request's own presence_penalty wins on every build. - @Test func qwen35OmittedPresencePenaltyFollowsEachBuildsGate() throws { + /// exact acceptance (0 of 31 draws), so 0.10.12 dropped its penalty. In + /// production, against 0.10.11 Macs over the same period, its answers with + /// `max_tokens` ≥ 8,192 then ran to the limit about three times as often + /// (5.5 % against 1.7 %), and its constrained JSON `response_format` rows, + /// which never speculate, ran out and failed about twice as often (51 % + /// against 23 % in the same 10-minute windows). The penalty is the + /// difference we can establish: with nothing else running those rows + /// failed 32.7 % against 13.6 % (9B-MIDFAIL). The coordinator's body adds + /// the registry's temperature, top_p and top_k, and the penalty only where + /// the registry sets one. A request's own presence_penalty wins on every + /// build. + @Test func qwen35OmittedPresencePenaltyIsTheCardsOnEveryBuild() throws { let coordinatorBody = #"{"model":"m","messages":[{"role":"user","content":"hi"}],"temperature":1,"top_p":0.95,"top_k":20}"# - let builds: [(id: String, type: String, penalty: Float)] = [ - ("Qwen3.5-9B", "qwen3_5", 1.5), - ("qwen3.5-35b-a3b", "qwen3_5_moe", 1.5), - ("qwen3.6-35b-a3b-vl-mtp-mxfp8", "qwen3_5_moe", 1.5), + let builds: [(id: String, type: String)] = [ + ("Qwen3.5-9B", "qwen3_5"), + ("qwen3.5-35b-a3b", "qwen3_5_moe"), + ("qwen3.6-35b-a3b-vl-mtp-mxfp8", "qwen3_5_moe"), ] for build in builds { let defaults = EngineV2SamplingDefaults.resolve( @@ -128,7 +132,7 @@ struct EngineV2SamplingDefaultsTests { for body in [bareRequest, coordinatorBody] { let sampling = EngineV2Translation.samplingParams(from: try request(body), defaults: defaults) #expect(sampling.temperature == 1 && sampling.topP == 0.95 && sampling.topK == 20, "\(build.id)") - #expect(sampling.presencePenalty == build.penalty, "\(build.id): \(body)") + #expect(sampling.presencePenalty == 1.5, "\(build.id): \(body)") #expect(sampling.frequencyPenalty == 0 && sampling.repetitionPenalty == 1, "\(build.id)") } for own in ["0", "1.5"] { @@ -175,8 +179,8 @@ struct EngineV2SamplingDefaultsTests { environment: [key: "on"]) == .legacy) } - @Test("darkbloom start passes the 9B penalty rollback switch to the launchd daemon") - func qwen35NineBPenaltySwitchReachesTheDaemon() { + /// `darkbloom start` passes the 9B penalty rollback switch to the launchd daemon. + @Test func qwen35NineBPenaltySwitchReachesTheDaemon() { let key = EngineV2SamplingDefaults.qwen35NineBPenaltyEnvironmentKey #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(key)) #expect(LaunchAgent.passthroughEnvironment(from: [key: "0"])[key] == "0") diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/PrefixCache/Qwen35CardDefaultDonationTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/PrefixCache/Qwen35CardDefaultDonationTests.swift index 6e3022653e..e8edc8e3c1 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/PrefixCache/Qwen35CardDefaultDonationTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/PrefixCache/Qwen35CardDefaultDonationTests.swift @@ -11,8 +11,8 @@ import Testing /// A Qwen 3.5/3.6 request with the model card's presence penalty (1.5) cannot speculate: on /// `qwen3.5-35b-a3b` and `Qwen3.5-9B` alike that is the provider's default for a request that /// sends no sampling field (`EngineV2SamplingDefaults.qwen35CardDefaults`; 0.10.12 had none on -/// the 9B). On the production paged assembly, with the inline MTP -/// assistant and the encrypted complete-checkpoint store, such a request must still donate its +/// the 9B). On the production paged assembly, with the inline MTP assistant and the encrypted +/// complete-checkpoint store, such a request must still donate its /// prompt's checkpoints, answer exactly as it does with the cache off, and let the next /// identical request restore them and answer exactly as its cold run. Synthetic weights, no /// model load. From 531ddffb6b1ebe85d5a76164d9cf7dbd95a1f683 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:04:25 -0800 Subject: [PATCH 14/26] test(provider): the second review's findings on #2052 (red) The independent review of faf818caea (REQUEST CHANGES, glm-stray-evidence/review/REVIEW-2.md) as tests, before the fix: 1. Malformed JSON let the lexer resume reading frames, so a frame quoted in a JSON string the malformed value opened became a call (store(doc: {})): `]` or `` where a value belongs. Also a name followed by ``, `` or `` (not ``) was read as a mention, so a complete frame after it became a call. Expected: no call, all text, at `stop` and `length`, three chunk widths. 2. A think marker in an argument key was not checked: the released text handed it to the reasoning parser. Expected: the response keeps failing. Same after a frame whose JSON breaks the grammar (it owns the rest). 3. At `length` the router released the whole suffix after checking only the prefix of a split it then discarded: a marker inside the selected call was released. Expected: keeps failing. 4. An oversized suffix the SDK refuses while streaming was released through the visible-text path, before any EOS check: `auto` now fails again, as on dev, in pieces or in one delivery (the auto expectation of oversizedFrameFailsBeforeFallback goes back to dev's). 5. Many adjacent frames after a mention (40,000; the run was built by front insertion): a functional check, not a timing one, so not red. Plus a regression guard: a think marker inside the final call's own argument stays its data. Red on faf818caea: 1 (stop), 2, 3, 4 and the oversized auto case. Co-Authored-By: Claude Opus 5.5 --- .../Streaming/GLM5ToolFailureTests.swift | 89 ++++++++++++++++++- 1 file changed, 88 insertions(+), 1 deletion(-) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift index aa56956191..48c5daef33 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift @@ -33,11 +33,27 @@ struct GLM5ToolFailureTests { #expect(result.visible.isEmpty) } + /// The SDK refuses an oversized suffix while it streams, before EOS: that + /// still fails the response, `auto` included, before any of it is released. @Test(arguments: [false, true]) func oversizedFrameFailsBeforeFallback(forced: Bool) async throws { let output = "echo" + String(repeating: "x", count: (1 << 20) + 1) let result = try await run(output, forced: forced, width: 65536) - expectUnparsed(result, output: output, forced: forced) + #expect(result.calls.isEmpty && result.visible.isEmpty) + #expect(result.failure == (forced ? .toolChoiceViolation("native GLM tool output is invalid") + : .generationFailed("native GLM tool output is invalid"))) + } + + /// An oversized suffix never bypasses the EOS checks: a think marker inside + /// a drafted call is not released, whether the suffix arrives in pieces or + /// in one delivery. + @Test(arguments: [65536, 1 << 22]) + func oversizedSuffixIsNeverReleased(width: Int) async throws { + let draft = "echotext" + let output = "Draft " + draft + "PRIVATEAnswer" + String(repeating: "x", count: 1 << 20) + let result = try await run(output, forced: false, width: width) + #expect(result.calls.isEmpty && !result.visible.contains("PRIVATE")) + #expect(result.failure == .generationFailed("native GLM tool output is invalid")) } /// The model's raw output after the prompt's open `` (the legacy @@ -155,6 +171,31 @@ struct GLM5ToolFailureTests { } } + /// Arguments that break the SDK's grammar end the lexer's reading of + /// frames: a frame after them (here quoted in a JSON string the malformed + /// value opened) stays data and never becomes a call, whether the output + /// stops or is cut off. So does one after a name followed by anything but + /// `` or `` that belongs to a frame. + @Test(arguments: ["stop", "length"], [1, 7, 4096]) + func framesAfterMalformedArgumentsAreNeverCalls(finishReason: String, width: Int) async throws { + let inner = "storedoc{}" + let open = "storedoc" + let outputs = [ + open + #"{"x": ],"y":""# + "" + inner, + open + #"{"x": ,"y":""# + "" + inner, + open + #"{"x": 1 "y":""# + "" + inner, + "store" + inner, + "store" + inner, + "store" + inner, + ] + for output in outputs { + let result = try await run(output, forced: false, width: width, finishReason: finishReason, + tool: Self.storeTool) + #expect(result.failure == nil && result.calls.isEmpty, "\(output)") + #expect(result.visible == output, "\(output)") + } + } + /// Released text would hand a think marker from inside a drafted call to /// the service's reasoning parser as a channel boundary: that response keeps /// failing, as before. @@ -167,6 +208,38 @@ struct GLM5ToolFailureTests { } } + /// The same holds for a think marker in a key, after a frame whose + /// arguments break the grammar (which owns the rest of the response), and + /// in an output cut off at the token limit, whose whole suffix would be + /// released. + @Test(arguments: [1, 5, 4096]) + func thinkMarkerAnywhereInAReleasedFrameStillFails(width: Int) async throws { + let cases: [(output: String, finishReason: String, tool: String?)] = [ + ("Draft echo0PRIVATEAnswer", + "stop", nil), + ("Draft storedoc{bad}PRIVATEAnswer", + "stop", Self.storeTool), + ("Draft . echotextPRIVATE", + "length", nil), + ] + for shape in cases { + let result = try await run(shape.output, forced: false, width: width, finishReason: shape.finishReason, + tool: shape.tool) + #expect(result.calls.isEmpty && result.visible == "Draft ", "\(shape.output)") + #expect(result.failure == .generationFailed("native GLM tool output is invalid"), "\(shape.output)") + } + } + + /// A think marker inside the final call's own argument is that call's + /// data: the call parses and nothing of it is released. + @Test func thinkMarkerInsideTheFinalCallStaysItsArgument() async throws { + let call = "echotextstrip tags" + let result = try await run("Use ." + call, forced: false, width: 3, finishReason: "stop") + #expect(result.failure == nil) + #expect(result.calls.compactMap { $0.function.arguments["text"]?.anyValue as? String } == ["strip tags"]) + #expect(result.visible == "Use .") + } + /// Finding the calls is linear in the suffix: many mentions before them. @Test func manyMentionsBeforeTheCalls() async throws { let mentions = String(repeating: " ", count: 20_000) @@ -174,6 +247,20 @@ struct GLM5ToolFailureTests { #expect(result.failure == nil && result.calls.count == 1 && result.visible == mentions) } + /// And many adjacent frames after a mention: the run that ends the + /// response is collected in one pass. + @Test func manyFramesAfterAMention() throws { + let tools: [[String: any Sendable]] = [["type": "function", "function": ["name": "a"] as [String: any Sendable]]] + let suffix = "." + String(repeating: "a", count: 40_000) + let split = GLM5ToolSuffix.split(suffix, tools: tools) + guard case .text(let text, let calls) = split else { + Issue.record("expected text and calls, got \(split)") + return + } + #expect(text == "." && calls.count == 40_000) + #expect(calls.allSatisfy { $0.function.name == "a" && $0.function.arguments.isEmpty }) + } + /// `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure. @Test func rollbackRestoresTheSuffixFailure() throws { let request = try MiMoConsumerFixture.request(choice: #""auto""#) From 3779320d8a83cc8d0ee3da9a4665149c13f22b95 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:10:58 -0800 Subject: [PATCH 15/26] fix(provider): the second review's findings on #2052 From the independent review of faf818caea (REQUEST CHANGES, REVIEW-2.md), finishing the author's last, uncompiled draft (05:56Z) and extending it: 1. BLOCKER: `GLM5ToolSuffix.Lexer` reads a frame's JSON values as the SDK does, structurally (strings, objects, arrays, literals, number bytes) instead of counting brackets, and never resumes reading frames inside arguments that break the grammar: such a frame, or one still open at the end, owns the rest of the response, so no frame after it is a call (all text). A name followed by ``, `` or `` is a malformed frame too, not a mention. A value whose declared type is a union of `string` with `object` or `array` (the template could have written it raw or as JSON, ending in different places) owns the rest as well; a declared type is taken from the key that matches byte for byte, as the SDK takes it. 2. The think-marker check covers whole frames (name, keys, values) and everything after a frame that owns the rest. 3. `split(_:tools:truncated:)` decides the release first: at the token limit the whole suffix is text and the check runs on all of it. 4. `checkNativeToolFailure` lets a GLM parse failure through only after `finishCompleteCalls` released the EOS suffix: a suffix the SDK refuses as oversized while streaming fails before it is released, as on dev. 5. The run that ends the response is collected by appending and reversing once (it was built by front insertion: quadratic in adjacent frames). 6. Docs and changelog: the cases that still fail (think marker inside a frame, oversized suffix), the grammar rule. The red tests of 531ddffb6b pass with this; the rest of the suite is unchanged. Co-Authored-By: Claude Opus 5.5 --- changelog.d/glm-stray-tool-call-text.md | 4 +- docs/architecture/inference.md | 27 +- docs/reference/configuration.md | 2 +- .../Inference/Streaming/GLM5ToolSuffix.swift | 325 +++++++++++------- .../Streaming/NativeToolStreamRouter.swift | 31 +- 5 files changed, 233 insertions(+), 156 deletions(-) diff --git a/changelog.d/glm-stray-tool-call-text.md b/changelog.d/glm-stray-tool-call-text.md index 9f50fc2c55..6e6dd26683 100644 --- a/changelog.d/glm-stray-tool-call-text.md +++ b/changelog.d/glm-stray-tool-call-text.md @@ -1,5 +1,5 @@ ### A stray `` no longer fails a GLM-5.3-Flash response - GLM's tool parser reads a response from its first `` to the end as one batch of calls, and on `auto` tool requests that includes the model's reasoning. A tag the model only mentioned or a call it drafted in its thought, or a text answer that mentions the tag, failed the whole response with a 500 (`native GLM tool output is invalid`). -- Such output is now text instead of a failure, as vLLM's and SGLang's GLM parsers never fail a response on tool syntax, with a stricter rule for what is still a call: the calls are the well-formed frames that end the response; everything before them is text, so the reasoning still splits at ``. A frame inside or after another frame's arguments is never a call. Output with no such calls (a malformed or cut-off final call, text after the calls) is all text, and so is output cut off at `max_tokens` whose tool suffix does not parse. No call is completed or salvaged. -- Required and named `tool_choice` still fail closed (422). `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the 500; `darkbloom start` passes it to the launchd provider. +- Such output is now text instead of a failure, as vLLM's and SGLang's GLM parsers never fail a response on tool syntax, with a stricter rule for what is still a call: the calls are the well-formed frames that end the response; everything before them is text, which the service's reasoning parser splits at ``. A frame inside or after another frame's arguments, or after arguments that break the parser's grammar, is never a call. Output with no such calls (a malformed or cut-off final call, text after the calls) is all text, and so is output cut off at `max_tokens` whose tool suffix does not parse. No call is completed or salvaged. +- Still a 500, as before: output whose released text would hold a think marker from inside a tool frame (the reasoning parser would read it as the end of the thought), and a tool suffix over the parser's 1 MiB bound. Required and named `tool_choice` still fail closed (422). `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the 500 for every unparsed suffix; `darkbloom start` passes it to the launchd provider. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index a5103b9b44..db60acbbfd 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1792,16 +1792,23 @@ rule for what still counts as a call (`NativeToolStreamRouter.finishCompleteCall only by whitespace and ending the response, from just after the last frame of the run that does not parse; everything before them is text, which the service's reasoning parser then splits at ``. A frame that has started its -arguments owns everything up to its ``, so a frame inside or after an -argument is data, never a call. A suffix with no such run (a malformed or cut-off -final frame, text after the calls) is all text, and so is a suffix that did not -parse in an output cut at the token limit; no frame is completed or salvaged. A -suffix whose release would put a think marker from inside a frame before the -reasoning parser keeps failing, as does a required or named call (422). Unlike -vLLM and SGLang, a call followed by text or by a malformed frame commits nothing, -and a call drafted inside a closed thought stays reasoning. A suffix that parses -keeps its calls as before. `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the -whole-suffix failure (500). +arguments must follow the SDK parser's grammar to its own `` (a +string-typed value raw to ``, any other value structurally valid +JSON, whose quoted delimiters are data). One that does not (malformed JSON, its +own tags out of order after its name, a value whose declared type is a union of +`string` with `object` or `array`, which the template could have written either +way) or that is still open at the end owns the rest of the response: no frame +inside or after its arguments is ever a call. A suffix with no such run (a +malformed or cut-off final frame, text after the calls) is all text, and so is a +suffix that did not parse in an output cut at the token limit; no frame is +completed or salvaged. A suffix whose release would put a think marker from +inside a frame (its name, a key or a value, or anything after a frame that owns +the rest) before the reasoning parser keeps failing (500), at a stop or at the +token limit, as does a suffix the SDK refuses as oversized while it streams, and +a required or named call (422). Unlike vLLM and SGLang, a call followed by text +or by a malformed frame commits nothing, and a call drafted inside a closed +thought stays reasoning. A suffix that parses keeps its calls as before. +`DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure (500). The request-local [GLM prompt contract](../reference/protocol-messages.md#glm-native-prompt-contract) also preserves original schema values only after a trusted loaded-model check. It renders reasoning that OpenRouter returns on earlier assistant turns diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 11e1c4bd35..dd2c2ba4dc 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -565,7 +565,7 @@ and rollback are defined in the [provider configuration reference](../provider/c | `DARKBLOOM_TTFT_GDN_BLOCKED` | `0`, `false`, `no`, `off` keep the stock kernel; `packed` or `rows` force that kernel; unset or any other value probes. Case-insensitive; surrounding whitespace is ignored | probe | `libs/mlx-swift-lm/Libraries/MLXLMCommon/GatedDelta.swift` (`GatedDeltaPrefill.mode`, `GatedDeltaPrefill.kernel`) | Selects the Gated DeltaNet prompt-window kernel of `qwen3_5`, `qwen3_5_moe` and `prism_hadamard_qwen35` models ([mechanism](../architecture/inference.md#context)). The default probe keeps a four-row kernel only where it reproduces `gated_delta_step` bit for bit on the GPU; it does not compare speed, so `0` is the rollback where a kept kernel is slower. Forced kernels skip that check and are for A/B measurement only. Decode, MTP verification and masked updates always use the stock kernel. Read once per process. Forwarded to the LaunchAgent. | | `DARKBLOOM_ENGINE_V2_VLM_PARITY_CHECK` | `0` skips | on | `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VLMTextExtraction.swift` | VLM text-extraction parity check. | | `DARKBLOOM_TTFT_STREAM_TOOL_CALLS` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/ToolStreamPreparation.swift` (`streamsToolCallsByDefault`) | Chat streams send `tool_choice` `auto` calls in the Gemma, Qwen 3.5, Harmony and framed-JSON formats as OpenAI `tool_calls` fragments while they are generated; each call is still validated when its frame closes. Required/named calls and other formats are unchanged. `0` restores complete calls at the engine terminal. See [streamed auto tool calls](../architecture/inference.md#streamed-auto-tool-calls). Forwarded to the LaunchAgent. | -| `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift` (`returnsUnparsedOutputAsTextByDefault`) | GLM-5.3-Flash `auto` tool output whose tool suffix does not parse as one call batch (a `` mentioned or drafted in the thought, or mentioned in the answer) is returned as text, with the well-formed frames that end the response as its calls (`GLM5ToolSuffix`). Required/named calls still fail closed. `0` restores the 500 for any such response. See [GLM5Next implementation boundary](../architecture/inference.md#glm5next-implementation-boundary). Forwarded to the LaunchAgent. | +| `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift` (`returnsUnparsedOutputAsTextByDefault`) | GLM-5.3-Flash `auto` tool output whose tool suffix does not parse as one call batch (a `` mentioned or drafted in the thought, or mentioned in the answer) is returned as text, with the well-formed frames that end the response as its calls (`GLM5ToolSuffix`). Output whose released text would hold a think marker from inside a tool frame, and a suffix over the parser's 1 MiB bound, still fail (500); required/named calls still fail closed (422). `0` restores the 500 for any such response. See [GLM5Next implementation boundary](../architecture/inference.md#glm5next-implementation-boundary). Forwarded to the LaunchAgent. | | `DARKBLOOM_TTFT_THINK_CONTENT_SEED` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningPromptProbe.swift` (`seedsPlainTailContentByDefault`) | Qwen3-VL (`qwen3_vl_moe`, `plainTailContentModelTypes`) requests on the `qwen3` reasoning parser whose prompt tail has no think marker start in content state, so the answer streams instead of waiting for a tag or the end of generation. Other model types, including close-only Qwen reasoners, keep undecided parsing. `0` restores undecided parsing. Forwarded to the LaunchAgent. | ### Managed Nemotron Super slot diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift index ab96964029..cdce225e3c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift @@ -7,17 +7,17 @@ import MLXLMCommon /// `` to EOS and parses that suffix as one call batch. On the legacy /// text path the suffix also holds reasoning, so a `` the model only /// mentioned or drafted in its thought, or one its answer mentions, fails the -/// batch. Like reference GLM parsers (vLLM, SGLang), which never fail a -/// response on tool syntax, such a suffix is text here, but with a stricter, -/// provider-specific rule for what still counts as a call: the calls are the -/// trailing run of top-level frames, separated only by whitespace and ending -/// the response, from just after the last frame of that run that does not -/// parse. Everything before them is text; a suffix with no such run (a cut-off -/// or malformed final frame, text after the calls) is all text. +/// batch. Reference GLM parsers (vLLM, SGLang) never fail a response on tool +/// syntax; here such a suffix is text too, under a stricter, provider-specific +/// rule for what is still a call: the trailing run of top-level frames, +/// separated only by whitespace and ending the response, from just after the +/// run's last frame that does not parse. Everything before them is text. /// -/// A frame that has started its arguments owns everything up to its own -/// ``: a `` inside an argument, or after one, is data, -/// never a call (`Lexer`). A frame is never completed or salvaged. +/// Only text the lexer can place outside every frame's arguments starts a +/// frame. A frame that has started its arguments must follow the SDK's grammar +/// to its own ``; one that does not, or is still open at the end, +/// owns the rest of the response, so a `` inside or after an +/// argument is never a call. A frame is never completed or salvaged. enum GLM5ToolSuffix { /// `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure: /// an `auto` response whose suffix does not parse fails with a 500. @@ -28,168 +28,214 @@ enum GLM5ToolSuffix { enum Split: Equatable { /// `text` precedes `calls`, which may be empty. case text(String, calls: [ToolCall]) - /// Released text would put a think marker from inside a tool frame - /// before the service's reasoning parser, which reads it as a channel - /// boundary. Such a suffix keeps failing, as before. + /// The text to release holds a think marker inside a tool frame, which + /// the service's reasoning parser would read as a channel boundary. + /// Such a suffix keeps failing, as before. case ambiguous } - static func split(_ suffix: String, tools: [[String: any Sendable]]?) -> Split { + /// `truncated`: the token limit cut the output off; its suffix is text. + static func split(_ suffix: String, tools: [[String: any Sendable]]?, truncated: Bool = false) -> Split { let bytes = Array(suffix.utf8) var lexer = Lexer(bytes: bytes, tools: tools) lexer.run() - // The run of whitespace-separated frames that ends the response. - var run: [Lexer.Frame] = [] - var end = bytes.count - if !lexer.openAtEnd { + var start = bytes.count + var calls: [ToolCall] = [] + if !truncated, lexer.unclosed == nil { + // The run of whitespace-separated frames that ends the response. + var run: [Range] = [] + var end = bytes.count for frame in lexer.frames.reversed() { - guard Lexer.isWhitespace(bytes[frame.range.upperBound ..< end]) else { break } - run.insert(frame, at: 0) - end = frame.range.lowerBound + guard Lexer.isWhitespace(bytes[frame.upperBound ..< end]) else { break } + run.append(frame) + end = frame.lowerBound } - } - let parser = GLM5ToolCallParser() - let text = { (start: Int) in String(decoding: bytes[..`/`` pairs to ``. A - /// `` not followed by a name and `` or `` - /// is a mention and stays text. Once a frame has an argument it owns - /// everything up to its ``; a string-typed value runs to - /// `` (the template writes strings raw), any other value is - /// JSON, whose quoted delimiters are data. + /// Top-level GLM frames, read by the SDK parser's grammar: a name up to `<`, + /// then ``, or `` pairs. A `` followed by + /// anything but those or another frame tag is a mention and stays text. A + /// string-typed value runs raw to `` (the template writes + /// strings raw); any other value is JSON, structurally checked as the SDK + /// reads it, so quoted delimiters are data. An argument whose declared type + /// is unknown is JSON if it opens like JSON, raw otherwise. struct Lexer { - struct Frame { - let range: Range - /// A think marker inside the frame's arguments. - let holdsThinkMarker: Bool - } - let bytes: [UInt8] - let tools: [[String: any Sendable]]? - private(set) var frames: [Frame] = [] - /// A frame's arguments were still open at the end of the response. - private(set) var openAtEnd = false - private var openFrameHoldsThinkMarker = false + private let parameters: [String: [String: any Sendable]] + /// Closed top-level frames, in order. + private(set) var frames: [Range] = [] + /// Start of a frame whose arguments break the grammar or are still open + /// at the end; it owns the rest of the response. + private(set) var unclosed: Int? private var index = 0 init(bytes: [UInt8], tools: [[String: any Sendable]]?) { self.bytes = bytes - self.tools = tools + var parameters: [String: [String: any Sendable]] = [:] + var duplicates: Set = [] + for tool in tools ?? [] { + let function = (tool["function"] as? [String: any Sendable]) ?? tool + guard let name = function["name"] as? String else { continue } + if parameters[name] != nil { duplicates.insert(name) } + parameters[name] = (function["parameters"] as? [String: any Sendable]) ?? [:] + } + for name in duplicates { parameters[name] = nil } + self.parameters = parameters } mutating func run() { while let start = find("", from: index) { - index = start + 11 - guard let tag = find("<", from: index) else { return } - let name = Self.string(bytes, index ..< tag).trimmingCharacters(in: CharacterSet(charactersIn: " \t\r\n")) + guard let tag = find("<", from: start + 11) else { return } if starts("", at: tag) { index = tag + 12 - frames.append(Frame(range: start ..< index, holdsThinkMarker: false)) + frames.append(start ..< index) } else if starts("", at: tag) { - index = tag - guard let frame = arguments(start: start, name: name) else { return } - frames.append(frame) + let name = String(decoding: bytes[start + 11 ..< tag], as: UTF8.self) + .trimmingCharacters(in: CharacterSet(charactersIn: " \t\r\n")) + guard let end = arguments(from: tag, name: name) else { + unclosed = start + return + } + index = end + frames.append(start ..< end) + } else if ["", "", ""].contains(where: { starts($0, at: tag) }) { + // A frame's own tags out of order: a malformed frame, not a mention. + unclosed = start + return } else { index = tag } } } - /// Whether text released up to `end` holds a think marker inside a frame. - func releasesThinkMarker(before end: Int) -> Bool { - frames.contains { $0.holdsThinkMarker && $0.range.lowerBound < end } - || (openAtEnd && openFrameHoldsThinkMarker) + /// Whether text released before `end` holds a think marker inside a frame. + func holdsThinkMarker(before end: Int) -> Bool { + frames.contains { $0.lowerBound < end && containsThinkMarker($0) } + || unclosed.map { $0 < end && containsThinkMarker($0 ..< bytes.count) } == true } - /// The frame from `start`, whose arguments begin at `index`; nil when - /// it is still open at the end of the response. - private mutating func arguments(start: Int, name: String) -> Frame? { - var key: String? - var thinkMarker = false - while let tag = find("<", from: index) { - if starts("", at: tag) { - index = tag + 12 - return Frame(range: start ..< index, holdsThinkMarker: thinkMarker) - } - if starts("", at: tag) { - guard let close = find("", from: tag + 9) else { break } - key = Self.string(bytes, tag + 9 ..< close) - index = close + 10 - } else if starts("", at: tag) { - let value = tag + 11 - guard let end = isString(name: name, key: key) - ? find("", from: value) : jsonEnd(from: value) - else { break } - thinkMarker = thinkMarker || containsThinkMarker(value ..< end) - index = end - key = nil + /// The end of the frame whose first `` is at `start`, read as + /// the SDK reads it; nil when it breaks that grammar or is open at the end. + private func arguments(from start: Int, name: String) -> Int? { + var index = start + while true { + index = skipWhitespace(from: index) + if starts("", at: index) { return index + 12 } + guard starts("", at: index), let close = find("", from: index + 9), + close > index + 9, !bytes[index + 9 ..< close].contains(60) + else { return nil } + let key = String(decoding: bytes[index + 9 ..< close], as: UTF8.self) + index = close + 10 + guard starts("", at: index) else { return nil } + index += 11 + guard let raw = readsRaw(name: name, key: key, value: index) else { return nil } + if raw { + guard let end = find("", from: index) else { return nil } + index = end + 12 } else { - thinkMarker = thinkMarker || starts("", at: tag) || starts("", at: tag) - index = tag + 1 + guard jsonValue(&index, depth: 0) else { return nil } + index = skipWhitespace(from: index) + guard starts("", at: index) else { return nil } + index += 12 } } - openAtEnd = true - openFrameHoldsThinkMarker = thinkMarker || containsThinkMarker(index ..< bytes.count) - return nil } - /// The end of a JSON value: after its closing bracket or string, or at - /// a `<` outside any string (malformed JSON ends there); nil when it - /// is still open at the end of the response. - private func jsonEnd(from start: Int) -> Int? { - var index = start - var depth = 0 - var inString = false - while index < bytes.count { - let byte = bytes[index] - index += 1 - if inString { - if byte == 92 { index += 1 } else if byte == 34 { - inString = false - if depth == 0 { return index } + /// The SDK reads a value raw only when its declared type is `string` + /// (the declared key byte for byte, as the SDK matches it). A union of + /// `string` with `object` or `array` could have been written either way, + /// ending in different places: nil, the frame owns the rest. A union + /// with bare literals ends where its raw reading does (the SDK refuses + /// any union with `string`). + private func readsRaw(name: String, key: String, value: Int) -> Bool? { + if let parameters = parameters[name] { + let properties = parameters["properties"] as? [String: any Sendable] + let schema = properties?.first(where: { $0.key.utf8.elementsEqual(key.utf8) })?.value + ?? parameters["additionalProperties"] + if let type = (schema as? [String: any Sendable])?["type"] { + if let type = type as? String { return type == "string" } + if let types = type as? [String], types.contains("string") { + return types.contains("object") || types.contains("array") ? nil : true } - continue + return false } - switch byte { - case 34: inString = true - case 123, 91: depth += 1 - case 125, 93: - depth -= 1 - if depth <= 0 { return index } - case 60: return index - 1 - default: break + } + let first = skipWhitespace(from: value) + return first >= bytes.count || ![34, 91, 123].contains(bytes[first]) + } + + /// One JSON value from `index`, structurally as the SDK's reader takes + /// it (strings, objects, arrays, literals, number characters). + private func jsonValue(_ index: inout Int, depth: Int) -> Bool { + guard depth <= 64 else { return false } + index = skipWhitespace(from: index) + guard index < bytes.count else { return false } + switch bytes[index] { + case 34: + return jsonString(&index) + case 123: + index = skipWhitespace(from: index + 1) + if consume("}", &index) { return true } + while true { + guard jsonString(&index) else { return false } + index = skipWhitespace(from: index) + guard consume(":", &index), jsonValue(&index, depth: depth + 1) else { return false } + index = skipWhitespace(from: index) + if consume("}", &index) { return true } + guard consume(",", &index) else { return false } + index = skipWhitespace(from: index) } + case 91: + index = skipWhitespace(from: index + 1) + if consume("]", &index) { return true } + while true { + guard jsonValue(&index, depth: depth + 1) else { return false } + index = skipWhitespace(from: index) + if consume("]", &index) { return true } + guard consume(",", &index) else { return false } + } + case 116: return consume("true", &index) + case 102: return consume("false", &index) + case 110: return consume("null", &index) + default: + let start = index + while index < bytes.count, Self.isNumberByte(bytes[index]) { index += 1 } + return index > start } - return nil } - /// The template writes a string value raw and any other value as JSON; - /// the SDK reads it the same way, by the declared type. - private func isString(name: String, key: String?) -> Bool { - guard let key, let tools else { return false } - let functions = tools.map { ($0["function"] as? [String: any Sendable]) ?? $0 } - .filter { $0["name"] as? String == name } - guard functions.count == 1, let parameters = functions[0]["parameters"] as? [String: any Sendable] - else { return false } - let schema = (parameters["properties"] as? [String: any Sendable])?[key] ?? parameters["additionalProperties"] - // A union with `string` is written raw too; the SDK then refuses the frame. - let type = (schema as? [String: any Sendable])?["type"] - return type as? String == "string" || (type as? [String])?.contains("string") == true + private func jsonString(_ index: inout Int) -> Bool { + guard index < bytes.count, bytes[index] == 34 else { return false } + index += 1 + while index < bytes.count { + let byte = bytes[index] + index += 1 + if byte < 32 { return false } + if byte == 34 { return true } + if byte == 92 { index += 1 } + } + return false } private func containsThinkMarker(_ range: Range) -> Bool { @@ -201,6 +247,18 @@ enum GLM5ToolSuffix { return false } + private func consume(_ literal: String, _ index: inout Int) -> Bool { + guard starts(literal, at: index) else { return false } + index += literal.utf8.count + return true + } + + private func skipWhitespace(from start: Int) -> Int { + var index = start + while index < bytes.count, Self.isWhitespaceByte(bytes[index]) { index += 1 } + return index + } + private func find(_ literal: String, from start: Int) -> Int? { let marker = Array(literal.utf8) var index = start @@ -217,11 +275,16 @@ enum GLM5ToolSuffix { } static func isWhitespace(_ bytes: ArraySlice) -> Bool { - bytes.allSatisfy { [9, 10, 13, 32].contains($0) } + bytes.allSatisfy(isWhitespaceByte) + } + + private static func isWhitespaceByte(_ byte: UInt8) -> Bool { + byte == 9 || byte == 10 || byte == 13 || byte == 32 } - static func string(_ bytes: [UInt8], _ range: Range) -> String { - String(decoding: bytes[range], as: UTF8.self) + /// The bytes the SDK's JSON number reader takes: digits, `+ - . E e`. + private static func isNumberByte(_ byte: UInt8) -> Bool { + (48 ... 57).contains(byte) || byte == 43 || byte == 45 || byte == 46 || byte == 69 || byte == 101 } } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift index 05eeb70b9b..ba66a5dc6a 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift @@ -18,8 +18,12 @@ struct NativeToolStreamRouter { private let withholdReasoning: Bool private var withheldReasoning = "" private let tools: [[String: any Sendable]]? - /// An `auto` GLM tool suffix that does not parse is text (`GLM5ToolSuffix`). + /// An `auto` GLM tool suffix that does not parse at EOS is text + /// (`GLM5ToolSuffix`). private let glmUnparsedOutputIsText: Bool + /// `finishCompleteCalls` has released the EOS suffix that way, which + /// answers its parse failure. + private var glmSuffixSplit = false /// Validation contract for calls exposed while generated; nil keeps the /// complete-call path (calls flushed at the engine terminal). private let streamedCallPolicy: ToolChoicePromptPolicy.Prepared? @@ -143,12 +147,13 @@ struct NativeToolStreamRouter { /// Also called after the SDK EOS flush, before residual text or any call /// is published. GLM validates the entire retained suffix only at EOS; on - /// an `auto` request a suffix that does not parse is text - /// (`finishCompleteCalls`), not a failure. + /// an `auto` request a suffix that does not parse there is text + /// (`finishCompleteCalls`), not a failure. A suffix the SDK rejects as + /// oversized while streaming still fails. func checkNativeToolFailure() throws { guard nativeMiMoChannels || handler?.format == .glm5 || handler?.format == .flint, (handler?.parseFailureCount ?? 0) > 0 else { return } - if returnsUnparsedGLMOutputAsText { return } + if glmSuffixSplit { return } let model = handler?.format == .glm5 ? "GLM" : handler?.format == .flint ? "Flint" : "MiMo" let message = "native \(model) tool output is invalid" if requiresToolCall || nativeMiMoRequiresConstraint { @@ -159,18 +164,20 @@ struct NativeToolStreamRouter { /// End of generation on the complete-call path: the handler's calls and /// its residual text. An `auto` GLM suffix that did not parse as one batch - /// is split into text and its final calls (`GLM5ToolSuffix`), except in an - /// output the token limit cut off, where it stays text. A suffix whose - /// release would expose a think marker from inside a tool frame keeps - /// failing, as before. - func finishCompleteCalls(truncated: Bool) throws -> (calls: [ToolCall], residual: String?) { + /// is split into text and its final calls (`GLM5ToolSuffix`; an output the + /// token limit cut off is all text). A suffix whose release would expose a + /// think marker from inside a tool frame keeps failing, as before. + mutating func finishCompleteCalls(truncated: Bool) throws -> (calls: [ToolCall], residual: String?) { guard let handler else { return ([], nil) } let calls = handler.finish() let residual = handler.takeResidualText() guard returnsUnparsedGLMOutputAsText, calls.isEmpty, let residual else { return (calls, residual) } - switch GLM5ToolSuffix.split(residual, tools: tools) { - case .text(let text, calls: let found): return truncated ? ([], residual) : (found, text) - case .ambiguous: throw MultiModelBatchSchedulerEngineError.generationFailed("native GLM tool output is invalid") + switch GLM5ToolSuffix.split(residual, tools: tools, truncated: truncated) { + case .text(let text, calls: let found): + glmSuffixSplit = true + return (found, text) + case .ambiguous: + throw MultiModelBatchSchedulerEngineError.generationFailed("native GLM tool output is invalid") } } From 46a47ef3639013603b478070af3221ba9ec77002 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:58:14 -0800 Subject: [PATCH 16/26] test(provider): the third review's findings on #2052 (red) The independent review of 3779320d8a (REQUEST CHANGES, glm-stray-evidence/review/REVIEW-3.md) as tests, before the fix: 1. A raw (string-typed) value holding the SDK's frame tags, which the SDK refuses, let the lexer borrow a nested frame's closing tags as its own: the second of two frames drafted inside it became a call. 2. A name followed by an unexpected tag (``) was read as a mention even when argument tags followed it, so a frame inside its JSON argument became a call, and a think marker inside its value was released (stop and `length`). 3. A key that only canonically equals a declared one (the SDK refuses it) fell through to `additionalProperties`, read raw, and let the frame end inside an unclosed JSON string: the next frame became a call. Expected for 1-3: no call; all text, or the failure for a released think marker. Plus guards: a byte-exact declared key and an additional property still type the final call, and 5,000 additional keys against a 5,000-key schema (review finding 4: a full map scan per key) parse, functionally. Red on 3779320d8a: 1-3 at `stop`, 2's think marker at `length` too. Co-Authored-By: Claude Opus 5.5 --- .../Streaming/GLM5ToolFailureTests.swift | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift index 48c5daef33..a617a33ba2 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift @@ -221,6 +221,10 @@ struct GLM5ToolFailureTests { "stop", Self.storeTool), ("Draft . echotextPRIVATE", "length", nil), + ("Draft echotextPRIVATEAnswer", + "stop", nil), + ("Draft echotextPRIVATEAnswer", + "length", nil), ] for shape in cases { let result = try await run(shape.output, forced: false, width: width, finishReason: shape.finishReason, @@ -230,6 +234,49 @@ struct GLM5ToolFailureTests { } } + /// `store` with a declared object key `é` (U+00E9) and string-typed + /// additional properties. + static let accentTool = #"{"type":"function","function":{"name":"store","parameters":{"type":"object","properties":{"\u00e9":{"type":"object"}},"additionalProperties":{"type":"string"}}}}"# + + /// A frame never borrows a later frame's closing tags: a raw value holding + /// the SDK's frame tags (which the SDK refuses), a malformed header that + /// leads into arguments, and a key the SDK refuses because it only + /// canonically equals a declared one each make the frame own the rest, so + /// no frame after it is a call, at a stop or the token limit. + @Test(arguments: ["stop", "length"], [1, 7, 4096]) + func framesNeverBorrowALaterFramesClose(finishReason: String, width: Int) async throws { + let echo = { (text: String) in "echotext\(text)" } + let inner = "storedoc{}" + let cases: [(output: String, tool: String?)] = [ + ("echotextdraft " + echo("ONE") + echo("TWO"), nil), + ("storedoc{\"x\":\"" + inner, Self.storeTool), + ("storee\u{301}{\"x\":\"store", + Self.accentTool), + ] + for shape in cases { + let result = try await run(shape.output, forced: false, width: width, finishReason: finishReason, + tool: shape.tool) + #expect(result.failure == nil && result.calls.isEmpty, "\(shape.output)") + #expect(result.visible == shape.output, "\(shape.output)") + } + } + + /// Declared keys (byte for byte) and additional properties keep their + /// types after a mention: the final call parses. + @Test func declaredAndAdditionalKeysStillParse() async throws { + for (frame, key, value) in [ + ("store\u{e9}{}", "\u{e9}", + JSONValue.object([:])), + ("storenoteplain {text}", "note", + JSONValue.string("plain {text}")), + ] { + let result = try await run("Use ." + frame, forced: false, width: 3, finishReason: "stop", + tool: Self.accentTool) + #expect(result.failure == nil && result.visible == "Use .", "\(frame)") + #expect(result.calls.map { $0.function.arguments } == [[key: value]], "\(frame)") + } + } + /// A think marker inside the final call's own argument is that call's /// data: the call parses and nothing of it is released. @Test func thinkMarkerInsideTheFinalCallStaysItsArgument() async throws { @@ -261,6 +308,24 @@ struct GLM5ToolFailureTests { #expect(calls.allSatisfy { $0.function.name == "a" && $0.function.arguments.isEmpty }) } + /// And many additional properties against a large declared schema: each + /// key's type is one lookup. + @Test func manyAdditionalKeysAgainstALargeSchema() throws { + var properties: [String: any Sendable] = [:] + for index in 0 ..< 5_000 { properties["p\(index)"] = ["type": "string"] as [String: any Sendable] } + let parameters: [String: any Sendable] = ["type": "object", "properties": properties, + "additionalProperties": ["type": "string"] as [String: any Sendable]] + let tools: [[String: any Sendable]] = [["type": "function", + "function": ["name": "f", "parameters": parameters] as [String: any Sendable]]] + let arguments = (0 ..< 5_000).map { "x\($0)v" }.joined() + let split = GLM5ToolSuffix.split(".f" + arguments + "", tools: tools) + guard case .text(let text, let calls) = split else { + Issue.record("expected text and calls, got \(split)") + return + } + #expect(text == "." && calls.count == 1 && calls.first?.function.arguments.count == 5_000) + } + /// `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure. @Test func rollbackRestoresTheSuffixFailure() throws { let request = try MiMoConsumerFixture.request(choice: #""auto""#) From c62caaf05e51b7cf98e5544ee48ca57fc739afd1 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:02:42 -0800 Subject: [PATCH 17/26] fix(provider): the third review's findings on #2052 From the independent review of 3779320d8a (REQUEST CHANGES, REVIEW-3.md): 1. A raw value is checked for the frame tags the SDK refuses there (``, ``, ``, ``, ``): a value holding one makes its frame own the rest, instead of ending at a nested frame's `` and resuming after it. 2. A `` whose name is followed by anything but `` or `` is a mention only when no frame tag follows it before the next ``; otherwise it is a malformed frame that owns the rest (this replaces the three-tag special case of 3779320d8a). Its think markers are then inside a frame, and released text holding them still fails. 3. A declared key's type is taken as the SDK takes it: a dictionary lookup, then the declared key's bytes; a key that only canonically equals a declared one owns the rest (the SDK refuses it) instead of falling through to `additionalProperties`. 4. That lookup is one hash lookup, not a scan of the declared properties per argument. Also: only a declaration the SDK accepts (one per name, an object schema without indirect types) and a key schema without indirect types type an argument; otherwise the value is read as JSON if it opens like JSON (never ending before its raw reading would), raw otherwise. Docs: the ownership triggers and the mention rule. The red tests of 46a47ef363 pass with this. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 13 ++- .../Inference/Streaming/GLM5ToolSuffix.swift | 101 +++++++++++++----- 2 files changed, 83 insertions(+), 31 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index db60acbbfd..48000fda5a 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1794,11 +1794,14 @@ run that does not parse; everything before them is text, which the service's reasoning parser then splits at ``. A frame that has started its arguments must follow the SDK parser's grammar to its own `` (a string-typed value raw to ``, any other value structurally valid -JSON, whose quoted delimiters are data). One that does not (malformed JSON, its -own tags out of order after its name, a value whose declared type is a union of -`string` with `object` or `array`, which the template could have written either -way) or that is still open at the end owns the rest of the response: no frame -inside or after its arguments is ever a call. A suffix with no such run (a +JSON, whose quoted delimiters are data). One that does not (malformed JSON, a raw +value holding frame tags, which the SDK refuses, its own tags after a malformed +header, a key that only canonically equals a declared one, a value whose declared +type is a union of `string` with `object` or `array`, which the template could +have written either way) or that is still open at the end owns the rest of the +response: no frame inside or after its arguments is ever a call. A `` +followed by anything else, with no frame tags before the next ``, is a +mention. A suffix with no such run (a malformed or cut-off final frame, text after the calls) is all text, and so is a suffix that did not parse in an output cut at the token limit; no frame is completed or salvaged. A suffix whose release would put a think marker from diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift index cdce225e3c..f48935dea3 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift @@ -75,11 +75,13 @@ enum GLM5ToolSuffix { /// Top-level GLM frames, read by the SDK parser's grammar: a name up to `<`, /// then ``, or `` pairs. A `` followed by - /// anything but those or another frame tag is a mention and stays text. A - /// string-typed value runs raw to `` (the template writes - /// strings raw); any other value is JSON, structurally checked as the SDK - /// reads it, so quoted delimiters are data. An argument whose declared type - /// is unknown is JSON if it opens like JSON, raw otherwise. + /// anything else is a mention and stays text, unless a frame's own tags + /// follow it before the next ``. A string-typed value runs raw + /// to `` (the template writes strings raw) and may not hold the + /// frame tags the SDK refuses there; any other value is JSON, structurally + /// checked as the SDK reads it, so quoted delimiters are data. An argument + /// whose declared type is unknown is JSON if it opens like JSON, raw + /// otherwise. struct Lexer { let bytes: [UInt8] private let parameters: [String: [String: any Sendable]] @@ -92,13 +94,25 @@ enum GLM5ToolSuffix { init(bytes: [UInt8], tools: [[String: any Sendable]]?) { self.bytes = bytes + // Only a declaration the SDK's parser accepts types arguments: one + // per name, an object schema without indirect types. var parameters: [String: [String: any Sendable]] = [:] + var seen: Set = [] var duplicates: Set = [] for tool in tools ?? [] { let function = (tool["function"] as? [String: any Sendable]) ?? tool guard let name = function["name"] as? String else { continue } - if parameters[name] != nil { duplicates.insert(name) } - parameters[name] = (function["parameters"] as? [String: any Sendable]) ?? [:] + if !seen.insert(name).inserted { duplicates.insert(name) } + guard let declared = function["parameters"] else { + parameters[name] = [:] + continue + } + guard let schema = declared as? [String: any Sendable], + schema["type"] == nil || schema["type"] as? String == "object", + !Self.hasIndirectType(schema), + schema["properties"].map({ $0 is [String: any Sendable] }) ?? true + else { continue } + parameters[name] = schema } for name in duplicates { parameters[name] = nil } self.parameters = parameters @@ -119,16 +133,25 @@ enum GLM5ToolSuffix { } index = end frames.append(start ..< end) - } else if ["", "", ""].contains(where: { starts($0, at: tag) }) { - // A frame's own tags out of order: a malformed frame, not a mention. - unclosed = start - return } else { - index = tag + // Anything else after the name is a mention, unless a + // frame's own tags follow before the next ``: + // then it is a malformed frame, which owns the rest. + let next = find("", from: tag) ?? bytes.count + if holdsAny(Self.frameTags, in: tag ..< next) { + unclosed = start + return + } + index = next } } } + /// The tags of a frame after its ``. + private static let frameTags = ["", "", "", "", ""] + /// The tags the SDK refuses inside a raw value. + private static let rawValueCollisions = ["", "", "", "", ""] + /// Whether text released before `end` holds a think marker inside a frame. func holdsThinkMarker(before end: Int) -> Bool { frames.contains { $0.lowerBound < end && containsThinkMarker($0) } @@ -151,7 +174,11 @@ enum GLM5ToolSuffix { index += 11 guard let raw = readsRaw(name: name, key: key, value: index) else { return nil } if raw { - guard let end = find("", from: index) else { return nil } + // A raw value holding frame tags is refused by the SDK; its + // `` may be a nested frame's. + guard let end = find("", from: index), + !holdsAny(Self.rawValueCollisions, in: index ..< end) + else { return nil } index = end + 12 } else { guard jsonValue(&index, depth: 0) else { return nil } @@ -162,18 +189,31 @@ enum GLM5ToolSuffix { } } - /// The SDK reads a value raw only when its declared type is `string` - /// (the declared key byte for byte, as the SDK matches it). A union of - /// `string` with `object` or `array` could have been written either way, - /// ending in different places: nil, the frame owns the rest. A union - /// with bare literals ends where its raw reading does (the SDK refuses - /// any union with `string`). + /// The SDK reads a value raw only when its declared type is `string`. + /// It takes the type of a declared key only from the key as declared, + /// byte for byte, and refuses one that only canonically equals it (nil: + /// the frame owns the rest); an undeclared key takes + /// `additionalProperties`. A union of `string` with `object` or `array` + /// could have been written either way, ending in different places: nil + /// too. A union with bare literals ends where its raw reading does (the + /// SDK refuses any union with `string`). Without a type the SDK accepts, + /// a value that opens like JSON is read as JSON, which never ends before + /// its raw reading would; any other value is raw (a JSON literal has no + /// delimiters to end early on). private func readsRaw(name: String, key: String, value: Int) -> Bool? { if let parameters = parameters[name] { - let properties = parameters["properties"] as? [String: any Sendable] - let schema = properties?.first(where: { $0.key.utf8.elementsEqual(key.utf8) })?.value - ?? parameters["additionalProperties"] - if let type = (schema as? [String: any Sendable])?["type"] { + let schema: (any Sendable)? + if let properties = parameters["properties"] as? [String: any Sendable], + let declared = properties.index(forKey: key) + { + guard properties[declared].key.utf8.elementsEqual(key.utf8) else { return nil } + schema = properties[declared].value + } else { + schema = parameters["additionalProperties"] + } + if let schema = schema as? [String: any Sendable], !Self.hasIndirectType(schema), + let type = schema["type"] + { if let type = type as? String { return type == "string" } if let types = type as? [String], types.contains("string") { return types.contains("object") || types.contains("array") ? nil : true @@ -239,10 +279,15 @@ enum GLM5ToolSuffix { } private func containsThinkMarker(_ range: Range) -> Bool { + holdsAny(["", ""], in: range) + } + + /// Whether one of `tags` (each opening with `<`) starts in `range`. + private func holdsAny(_ tags: [String], in range: Range) -> Bool { var index = range.lowerBound - while let tag = find("<", from: index), tag < range.upperBound { - if starts("", at: tag) || starts("", at: tag) { return true } - index = tag + 1 + while index < range.upperBound { + if bytes[index] == 60, tags.contains(where: { starts($0, at: index) }) { return true } + index += 1 } return false } @@ -274,6 +319,10 @@ enum GLM5ToolSuffix { return index + marker.count <= bytes.count && bytes[index ..< index + marker.count].elementsEqual(marker) } + private static func hasIndirectType(_ schema: [String: any Sendable]) -> Bool { + ["$ref", "$dynamicRef", "anyOf", "oneOf", "allOf", "not", "if", "then", "else"].contains { schema[$0] != nil } + } + static func isWhitespace(_ bytes: ArraySlice) -> Bool { bytes.allSatisfy(isWhitespaceByte) } From e7c14d073dc243ba09527374988f10ad841cd5cb Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:11:24 -0800 Subject: [PATCH 18/26] refactor(provider): refactor pass on the final GLM tool suffix fix The dedicated refactor-pass subagent (AGENTS.md) on c62caaf05e (glm-stray-evidence/refactor/ASSESSMENT-3.md): no code change warranted; one comment correction: `finishCompleteCalls` says that only a suffix that did not parse is all text at the token limit, and one that parses keeps its calls (as `truncatedOutputIsNotSplit` asserts). Co-Authored-By: Claude Opus 5.5 --- .../Inference/Streaming/NativeToolStreamRouter.swift | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift index ba66a5dc6a..ad68bf67c1 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift @@ -164,9 +164,10 @@ struct NativeToolStreamRouter { /// End of generation on the complete-call path: the handler's calls and /// its residual text. An `auto` GLM suffix that did not parse as one batch - /// is split into text and its final calls (`GLM5ToolSuffix`; an output the - /// token limit cut off is all text). A suffix whose release would expose a - /// think marker from inside a tool frame keeps failing, as before. + /// is split into text and its final calls (`GLM5ToolSuffix`; such a suffix + /// in an output the token limit cut off is all text, while one that parses + /// keeps its calls). A suffix whose release would expose a think marker + /// from inside a tool frame keeps failing, as before. mutating func finishCompleteCalls(truncated: Bool) throws -> (calls: [ToolCall], residual: String?) { guard let handler else { return ([], nil) } let calls = handler.finish() From e33365d24a1646412fc8013ad1627e654e20d6ab Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:19:00 -0800 Subject: [PATCH 19/26] test(provider): the fourth reviews' findings on #2052 (red) Two fresh-context reviews of c62caaf05e (REVIEW-4.md and REVIEW-4b.md, both REQUEST CHANGES) as tests, before the fix: 1. A frame the SDK refuses kept a boundary a different reading would move: a raw guess for a schema the SDK refuses (an object property with `anyOf`, or an undeclared tool) ended the frame at an `` that a JSON string it opened may run past, and a JSON reading of an array-typed value that opens with a string ran past a raw string's end, swallowing the next frame's opening. The frames after it (data, in another reading) became calls, and a think marker after it was released. 2. A frame's tags in top-level text escaped the malformed-header check when a closed frame came between the header and its arguments: a frame inside that header's JSON argument became a call, and its think marker was released. Expected: no call, all text, or the failure for a released think marker, at `stop` and `length`. Plus a functional case for the review's long-name cost (the name was hashed once per argument): a 200,000-byte name with 5,000 arguments. The run helper takes a JSON array of tools too. Red on c62caaf05e: 1 and 2 at `stop`; the think-marker cases at `length` too. Co-Authored-By: Claude Opus 5.5 --- .../Streaming/GLM5ToolFailureTests.swift | 65 ++++++++++++++++++- 1 file changed, 63 insertions(+), 2 deletions(-) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift index a617a33ba2..6da8576bf9 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift @@ -261,6 +261,56 @@ struct GLM5ToolFailureTests { } } + /// A frame the SDK refuses keeps its boundary only when no reading could + /// move it: a `"` in it may open a JSON string that runs past its + /// `` (a raw guess for a schema the SDK refuses), or a raw + /// string a JSON reading runs past (swallowing the next frame's opening). + /// Such a frame owns the rest. And a frame's tags in top-level text, here + /// after a closed frame that follows a malformed header, own the rest too. + /// No call either way, at a stop or the token limit. + @Test(arguments: ["stop", "length"], [1, 7, 4096]) + func refusedFramesWithAMovableBoundaryOwnTheRest(finishReason: String, width: Int) async throws { + let refusedObject = #"{"type":"function","function":{"name":"f","parameters":{"type":"object","properties":{"x":{"type":"object","anyOf":[{"type":"object"}]}}}}}"# + let arrayTools = #"[{"type":"function","function":{"name":"put","parameters":{"type":"object","properties":{"m":{"type":"array"}}}}},{"type":"function","function":{"name":"g","parameters":{"type":"object","properties":{}}}},{"type":"function","function":{"name":"h","parameters":{"type":"object","properties":{"z":{"type":"string"}}}}}]"# + let headerTools = #"[{"type":"function","function":{"name":"store","parameters":{"type":"object","properties":{"doc":{"type":"object"}}}}},{"type":"function","function":{"name":"x"}},{"type":"function","function":{"name":"g","parameters":{"type":"object","properties":{}}}}]"# + let cases: [(output: String, tool: String)] = [ + (#"fx]{"y":"f"#, + refusedObject), + (#"gx]{"y":"f"#, + refusedObject), + (#"putm"xputm["ghz"]"#, + arrayTools), + (#"storexdoc{"x":"g"#, + headerTools), + ] + for shape in cases { + let result = try await run(shape.output, forced: false, width: width, finishReason: finishReason, + tool: shape.tool) + #expect(result.failure == nil && result.calls.isEmpty, "\(shape.output)") + #expect(result.visible == shape.output, "\(shape.output)") + } + } + + /// Their think markers are then inside a frame: released text holding one + /// still fails, at a stop or the token limit. + @Test(arguments: ["stop", "length"], [1, 5, 4096]) + func thinkMarkersAfterAMovableBoundaryStillFail(finishReason: String, width: Int) async throws { + let refusedObject = #"{"type":"function","function":{"name":"f","parameters":{"type":"object","properties":{"x":{"type":"object","anyOf":[{"type":"object"}]}}}}}"# + let headerTools = #"[{"type":"function","function":{"name":"echo","parameters":{"type":"object","properties":{"text":{"type":"string"}}}}},{"type":"function","function":{"name":"x"}}]"# + let cases: [(output: String, tool: String)] = [ + (#"fx]{"y":"PRIVATEAnswer"#, + refusedObject), + ("echoxtextPRIVATEAnswer", + headerTools), + ] + for shape in cases { + let result = try await run(shape.output, forced: false, width: width, finishReason: finishReason, + tool: shape.tool) + #expect(result.calls.isEmpty && result.visible.isEmpty, "\(shape.output)") + #expect(result.failure == .generationFailed("native GLM tool output is invalid"), "\(shape.output)") + } + } + /// Declared keys (byte for byte) and additional properties keep their /// types after a mention: the final call parses. @Test func declaredAndAdditionalKeysStillParse() async throws { @@ -326,6 +376,15 @@ struct GLM5ToolFailureTests { #expect(text == "." && calls.count == 1 && calls.first?.function.arguments.count == 5_000) } + /// And a long generated name with many arguments: the name is looked up + /// once per frame, not once per argument. + @Test func longNameWithManyArguments() throws { + let tools: [[String: any Sendable]] = [["type": "function", "function": ["name": "echo"] as [String: any Sendable]]] + let suffix = "" + String(repeating: "a", count: 200_000) + + String(repeating: "xv", count: 5_000) + "" + #expect(GLM5ToolSuffix.split(suffix, tools: tools) == .text(suffix, calls: [])) + } + /// `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure. @Test func rollbackRestoresTheSuffixFailure() throws { let request = try MiMoConsumerFixture.request(choice: #""auto""#) @@ -392,7 +451,8 @@ struct GLM5ToolFailureTests { } /// The production event stream on the legacy text path (no native - /// channel), fed `width` characters at a time. + /// channel), fed `width` characters at a time. `tool` is one tool or a + /// JSON array of tools. private func run(_ output: String, forced: Bool, width: Int, finishReason: String? = nil, tool: String? = nil, choice forcedChoice: String = #""required""#) async throws -> Outcome { let choice = forced ? forcedChoice : #""auto""# @@ -400,7 +460,8 @@ struct GLM5ToolFailureTests { if let tool { var body = try #require(JSONSerialization.jsonObject(with: MiMoConsumerFixture.body( choice: choice)) as? [String: Any]) - body["tools"] = [try JSONSerialization.jsonObject(with: Data(tool.utf8))] + let tools = try JSONSerialization.jsonObject(with: Data(tool.utf8)) + body["tools"] = (tools as? [Any]) ?? [tools] request = try ProviderLoop.decodeOpenAIRequest(JSONSerialization.data(withJSONObject: body)) } let prepared = try ToolChoicePromptPolicy.prepare(request, modelType: "glm5_next") From e0922a96a00209ffccc84d8581f3afd43bcdccc6 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:21:45 -0800 Subject: [PATCH 20/26] fix(provider): the fourth reviews' findings on #2052 From two fresh-context reviews of c62caaf05e (REVIEW-4.md, REVIEW-4b.md): 1. BLOCKER (both): a frame the SDK refuses kept an end that another reading would move. `GLM5ToolSuffix.Lexer` now asks the SDK's parser about each closed frame as it records it: an accepted frame is the SDK's own reading and keeps its boundary; a refused frame keeps it only without a `"`, which could open a JSON string a raw reading ends inside (a raw guess for a schema the SDK refuses) or end a raw string a JSON reading runs past (swallowing the next frame's opening). Otherwise it owns the rest. The run reuses these verdicts instead of parsing its frames again. 2. A frame's tag (``, ``, ``, ``, ``) in top-level text, outside every frame, owns the rest: the malformed-header check no longer stops at an interposed closed frame. 3. A frame's declaration is looked up once per frame, and only for a name the SDK accepts (1-64 ASCII letters, digits, `-`, `_`), not once per argument. Docs: the refused-frame and top-level-tag rules, that a thought spelling out the tags in order owns the rest (and fails as before when its `` follows), and that the rule follows the `glm5` parser format. The red tests of e33365d24a pass with this. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 21 ++-- .../Inference/Streaming/GLM5ToolSuffix.swift | 97 +++++++++++++------ 2 files changed, 83 insertions(+), 35 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 48000fda5a..4e9cf0af2d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1799,19 +1799,26 @@ value holding frame tags, which the SDK refuses, its own tags after a malformed header, a key that only canonically equals a declared one, a value whose declared type is a union of `string` with `object` or `array`, which the template could have written either way) or that is still open at the end owns the rest of the -response: no frame inside or after its arguments is ever a call. A `` +response: no frame inside or after its arguments is ever a call. Where the SDK +accepts a frame on its own, the lexer reads it as the SDK does; a frame the SDK +refuses keeps its end only without a `"` (one may open a JSON string that a raw +reading ends inside, or end a raw string that a JSON reading runs past), else it +owns the rest too, as does a frame's tag in top-level text. A `` followed by anything else, with no frame tags before the next ``, is a -mention. A suffix with no such run (a -malformed or cut-off final frame, text after the calls) is all text, and so is a -suffix that did not parse in an output cut at the token limit; no frame is -completed or salvaged. A suffix whose release would put a think marker from +mention; a thought that spells out the tags in order (`` … ``) +therefore owns the rest, and fails as before when its `` follows. A suffix +with no such run (a malformed or cut-off final frame, text after the calls) is +all text, and so is a suffix that did not parse in an output cut at the token +limit; no frame is completed or salvaged. A suffix whose release would put a think marker from inside a frame (its name, a key or a value, or anything after a frame that owns the rest) before the reasoning parser keeps failing (500), at a stop or at the token limit, as does a suffix the SDK refuses as oversized while it streams, and a required or named call (422). Unlike vLLM and SGLang, a call followed by text or by a malformed frame commits nothing, and a call drafted inside a closed -thought stays reasoning. A suffix that parses keeps its calls as before. -`DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure (500). +thought stays reasoning. A suffix that parses keeps its calls as before. The +rule follows the handler's `glm5` parser format, so a request that selects that +parser for another family gets it too. `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` +restores the whole-suffix failure (500). The request-local [GLM prompt contract](../reference/protocol-messages.md#glm-native-prompt-contract) also preserves original schema values only after a trusted loaded-model check. It renders reasoning that OpenRouter returns on earlier assistant turns diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift index f48935dea3..5bb391a9ba 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift @@ -43,26 +43,25 @@ enum GLM5ToolSuffix { var calls: [ToolCall] = [] if !truncated, lexer.unclosed == nil { // The run of whitespace-separated frames that ends the response. - var run: [Range] = [] + var run: [Int] = [] var end = bytes.count - for frame in lexer.frames.reversed() { + for frameIndex in lexer.frames.indices.reversed() { + let frame = lexer.frames[frameIndex] guard Lexer.isWhitespace(bytes[frame.upperBound ..< end]) else { break } - run.append(frame) + run.append(frameIndex) end = frame.lowerBound } run.reverse() // Each frame parses on its own, so the starts that parse to the // end are exactly those after the run's last frame that does not. - let parser = GLM5ToolCallParser() - let first = run.lastIndex { - parser.parse(content: String(decoding: bytes[$0], as: UTF8.self), tools: tools) == nil - }.map { $0 + 1 } ?? 0 + let first = run.lastIndex { !lexer.accepted[$0] }.map { $0 + 1 } ?? 0 if first < run.count { - let parsed = parser.parseEOS( - String(decoding: bytes[run[first].lowerBound...], as: UTF8.self), tools: tools) + let from = lexer.frames[run[first]].lowerBound + let parsed = GLM5ToolCallParser().parseEOS( + String(decoding: bytes[from...], as: UTF8.self), tools: tools) // The SDK reads the same frames; anything else stays text. if parsed.count == run.count - first { - start = run[first].lowerBound + start = from calls = parsed } } @@ -81,19 +80,26 @@ enum GLM5ToolSuffix { /// frame tags the SDK refuses there; any other value is JSON, structurally /// checked as the SDK reads it, so quoted delimiters are data. An argument /// whose declared type is unknown is JSON if it opens like JSON, raw - /// otherwise. + /// otherwise. Where the SDK accepts a frame, this is its own reading; a + /// frame it refuses keeps its boundary only when no other reading could + /// move it. struct Lexer { let bytes: [UInt8] + private let tools: [[String: any Sendable]]? private let parameters: [String: [String: any Sendable]] /// Closed top-level frames, in order. private(set) var frames: [Range] = [] - /// Start of a frame whose arguments break the grammar or are still open - /// at the end; it owns the rest of the response. + /// Whether the SDK's parser accepts each frame on its own. + private(set) var accepted: [Bool] = [] + /// Start of a frame whose arguments break the grammar, are still open + /// at the end or end where another reading would not; it owns the + /// rest of the response. Also a frame's tag in top-level text. private(set) var unclosed: Int? private var index = 0 init(bytes: [UInt8], tools: [[String: any Sendable]]?) { self.bytes = bytes + self.tools = tools // Only a declaration the SDK's parser accepts types arguments: one // per name, an object schema without indirect types. var parameters: [String: [String: any Sendable]] = [:] @@ -119,34 +125,58 @@ enum GLM5ToolSuffix { } mutating func run() { - while let start = find("", from: index) { - guard let tag = find("<", from: start + 11) else { return } + while true { + let next = find("", from: index) + // A frame's tag in top-level text belongs to no frame: what + // follows it may be that frame's arguments. + if let stray = first(of: Self.frameTags, in: index ..< (next ?? bytes.count)) { + unclosed = stray + return + } + guard let start = next, let tag = find("<", from: start + 11) else { return } if starts("", at: tag) { index = tag + 12 - frames.append(start ..< index) + guard record(start ..< index) else { return } } else if starts("", at: tag) { let name = String(decoding: bytes[start + 11 ..< tag], as: UTF8.self) .trimmingCharacters(in: CharacterSet(charactersIn: " \t\r\n")) - guard let end = arguments(from: tag, name: name) else { + let declared = Self.isFunctionName(name) ? parameters[name] : nil + guard let end = arguments(from: tag, parameters: declared) else { unclosed = start return } index = end - frames.append(start ..< end) + guard record(start ..< end) else { return } } else { // Anything else after the name is a mention, unless a // frame's own tags follow before the next ``: // then it is a malformed frame, which owns the rest. - let next = find("", from: tag) ?? bytes.count - if holdsAny(Self.frameTags, in: tag ..< next) { + let following = find("", from: tag) ?? bytes.count + if holdsAny(Self.frameTags, in: tag ..< following) { unclosed = start return } - index = next + index = following } } } + /// Records a closed frame and whether the SDK accepts it on its own. A + /// frame the SDK refuses keeps its boundary only without a `"`: one may + /// open a JSON string that a raw reading ends inside, or end a raw + /// string that a JSON reading runs past. False when it owns the rest. + private mutating func record(_ frame: Range) -> Bool { + let accepts = GLM5ToolCallParser().parse( + content: String(decoding: bytes[frame], as: UTF8.self), tools: tools) != nil + if !accepts, bytes[frame].contains(34) { + unclosed = frame.lowerBound + return false + } + frames.append(frame) + accepted.append(accepts) + return true + } + /// The tags of a frame after its ``. private static let frameTags = ["", "", "", "", ""] /// The tags the SDK refuses inside a raw value. @@ -160,7 +190,7 @@ enum GLM5ToolSuffix { /// The end of the frame whose first `` is at `start`, read as /// the SDK reads it; nil when it breaks that grammar or is open at the end. - private func arguments(from start: Int, name: String) -> Int? { + private func arguments(from start: Int, parameters: [String: any Sendable]?) -> Int? { var index = start while true { index = skipWhitespace(from: index) @@ -172,7 +202,7 @@ enum GLM5ToolSuffix { index = close + 10 guard starts("", at: index) else { return nil } index += 11 - guard let raw = readsRaw(name: name, key: key, value: index) else { return nil } + guard let raw = readsRaw(parameters: parameters, key: key, value: index) else { return nil } if raw { // A raw value holding frame tags is refused by the SDK; its // `` may be a nested frame's. @@ -200,8 +230,8 @@ enum GLM5ToolSuffix { /// a value that opens like JSON is read as JSON, which never ends before /// its raw reading would; any other value is raw (a JSON literal has no /// delimiters to end early on). - private func readsRaw(name: String, key: String, value: Int) -> Bool? { - if let parameters = parameters[name] { + private func readsRaw(parameters: [String: any Sendable]?, key: String, value: Int) -> Bool? { + if let parameters { let schema: (any Sendable)? if let properties = parameters["properties"] as? [String: any Sendable], let declared = properties.index(forKey: key) @@ -282,14 +312,18 @@ enum GLM5ToolSuffix { holdsAny(["", ""], in: range) } - /// Whether one of `tags` (each opening with `<`) starts in `range`. private func holdsAny(_ tags: [String], in range: Range) -> Bool { + first(of: tags, in: range) != nil + } + + /// Where one of `tags` (each opening with `<`) first starts in `range`. + private func first(of tags: [String], in range: Range) -> Int? { var index = range.lowerBound while index < range.upperBound { - if bytes[index] == 60, tags.contains(where: { starts($0, at: index) }) { return true } + if bytes[index] == 60, tags.contains(where: { starts($0, at: index) }) { return index } index += 1 } - return false + return nil } private func consume(_ literal: String, _ index: inout Int) -> Bool { @@ -319,6 +353,13 @@ enum GLM5ToolSuffix { return index + marker.count <= bytes.count && bytes[index ..< index + marker.count].elementsEqual(marker) } + /// The SDK's function-name rule: 1-64 ASCII letters, digits, `-`, `_`. + private static func isFunctionName(_ name: String) -> Bool { + (1 ... 64).contains(name.utf8.count) && name.utf8.allSatisfy { + (48 ... 57).contains($0) || (65 ... 90).contains($0) || (97 ... 122).contains($0) || $0 == 45 || $0 == 95 + } + } + private static func hasIndirectType(_ schema: [String: any Sendable]) -> Bool { ["$ref", "$dynamicRef", "anyOf", "oneOf", "allOf", "not", "if", "then", "else"].contains { schema[$0] != nil } } From 43be515df2bae2b96500bd0cf498482e6d8d2f6d Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:31:10 -0800 Subject: [PATCH 21/26] test(provider): the fifth review's findings on #2052 (red) A fresh-context review of e0922a96a0 (REVIEW-5.md, REQUEST CHANGES, two SHOULD-FIX) as tests, before the fix: 1. A frame's tag in top-level text made the rest owned only from that tag: a malformed header read as a mention before an interposed closed frame kept its think marker outside, and released it (either direction, `` or `` after a real thought close). Expected: the response keeps failing, at `stop` and `length`. 2. Every closed frame was parsed by the SDK while lexing, even a quote-free one discarded before the end, and the SDK scans every declared tool per frame: 20,000 discarded frames against 500 tools, functionally (not a timing test, so not red). Red on e0922a96a0: 1. Co-Authored-By: Claude Opus 5.5 --- .../Streaming/GLM5ToolFailureTests.swift | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift index 6da8576bf9..812c87a074 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift @@ -311,6 +311,24 @@ struct GLM5ToolFailureTests { } } + /// A frame's tag in top-level text also takes back the malformed header + /// read as a mention before it: a think marker in that header's region, + /// either way, still fails. + @Test(arguments: ["stop", "length"], [1, 5, 4096]) + func orphanTagsTakeBackAnEarlierMention(finishReason: String, width: Int) async throws { + let headerTools = #"[{"type":"function","function":{"name":"echo","parameters":{"type":"object","properties":{"text":{"type":"string"}}}}},{"type":"function","function":{"name":"x"}}]"# + let orphan = "xtextv" + for (output, visible) in [ + ("echoPRIVATE" + orphan, ""), + ("Done.echoPRIVATE" + orphan, "Done."), + ] { + let result = try await run(output, forced: false, width: width, finishReason: finishReason, + tool: headerTools) + #expect(result.calls.isEmpty && result.visible == visible, "\(output)") + #expect(result.failure == .generationFailed("native GLM tool output is invalid"), "\(output)") + } + } + /// Declared keys (byte for byte) and additional properties keep their /// types after a mention: the final call parses. @Test func declaredAndAdditionalKeysStillParse() async throws { @@ -376,6 +394,17 @@ struct GLM5ToolFailureTests { #expect(text == "." && calls.count == 1 && calls.first?.function.arguments.count == 5_000) } + /// And many quote-free frames discarded before the end against many + /// tools: only frames whose boundary needs it, and the final run, are + /// checked by the SDK's parser. + @Test func manyDiscardedFramesAgainstManyTools() throws { + let tools: [[String: any Sendable]] = (0 ..< 500).map { + ["type": "function", "function": ["name": "f\($0)"] as [String: any Sendable]] + } + let suffix = "." + String(repeating: "f0.", count: 20_000) + #expect(GLM5ToolSuffix.split(suffix, tools: tools) == .text(suffix, calls: [])) + } + /// And a long generated name with many arguments: the name is looked up /// once per frame, not once per argument. @Test func longNameWithManyArguments() throws { From bd0bdd2520dffd10d0ddb9a65b6394c42756d0ae Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:34:41 -0800 Subject: [PATCH 22/26] test(provider): the second fifth review's findings on #2052 (red) A second fresh-context review of e0922a96a0 (REVIEW-5b.md, APPROVE WITH FIXES) as tests, before the fix: 1. A trailing run with a member the SDK refuses (an undeclared name, a missing required argument) ran the members after it: part of a batch the model emitted as one unit, against the SDK's own rule that a malformed member invalidates the batch. Expected: no call, all text. 2. The fallback was gated on `!requiresToolCall`, not on `auto`: with a prepared `none` (the Flint response format forces it while a client-selected GLM parser keeps its handler) the suffix was split and its failure answered, though no residual is published for `none`. Expected: the suffix still fails. (Its NITs 2 and 4 are REVIEW-5's two findings, in 43be515df2.) Red on e0922a96a0: 1 and 2. Co-Authored-By: Claude Opus 5.5 --- .../Streaming/GLM5ToolFailureTests.swift | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift index 812c87a074..33e4c5240c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift @@ -329,6 +329,22 @@ struct GLM5ToolFailureTests { } } + /// A trailing run with a member the SDK refuses is not a batch to take + /// part of: no member of it runs, as the SDK's own batch rule says (an + /// undeclared name, a missing required argument). + @Test(arguments: [1, 7, 4096]) + func aRefusedMemberCancelsTheWholeRun(width: Int) async throws { + let london = "echotextLondon" + for output in [ + "Checking.echtextParis\n" + london, + "Checking.echo\n" + london, + ] { + let result = try await run(output, forced: false, width: width, finishReason: "stop") + #expect(result.failure == nil && result.calls.isEmpty, "\(output)") + #expect(result.visible == output, "\(output)") + } + } + /// Declared keys (byte for byte) and additional properties keep their /// types after a mention: the final call parses. @Test func declaredAndAdditionalKeysStillParse() async throws { @@ -440,6 +456,35 @@ struct GLM5ToolFailureTests { #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(GLM5ToolSuffix.environmentKey)) } + /// Only an `auto` request returns an unparsed GLM suffix as text. With any + /// other prepared choice (here `none`, which the Flint response format + /// forces while a client-selected parser keeps its handler) no residual + /// is published, so the suffix still fails. + @Test func onlyAutoChoiceReturnsTheSuffixAsText() throws { + let auto = try MiMoConsumerFixture.request(choice: #""auto""#) + let autoPrepared = try ToolChoicePromptPolicy.prepare(auto, modelType: "glm5_next") + let nonePrepared = try ToolChoicePromptPolicy.prepare( + try MiMoConsumerFixture.request(choice: #""none""#), modelType: "glm5_next") + #expect(nonePrepared.mode == .none) + for (prepared, fallsBack) in [(autoPrepared, true), (nonePrepared, false)] { + let handler = try #require(try ToolStreamPreparation.makeHandler( + request: auto, prepared: autoPrepared, modelType: "glm5_next")) + var router = NativeToolStreamRouter(handler: handler, requiresToolCall: false, nativePrefix: nil, + tools: autoPrepared.tools?.map { $0.toolSpec() }, streamedCalls: prepared) + _ = try router.process("Wrap it in tags." + valid) + _ = try router.finishText() + let finished = try router.finishCompleteCalls(truncated: false) + if fallsBack { + try router.checkNativeToolFailure() + #expect(finished.calls.count == 1) + } else { + #expect(finished.calls.isEmpty) + #expect(throws: MultiModelBatchSchedulerEngineError.generationFailed( + "native GLM tool output is invalid")) { try router.checkNativeToolFailure() } + } + } + } + /// Forced choice is served by structured post-validation: the production /// handler is the native GLM parser, which withholds calls until EOS. @Test func publicForcedGLMUsesTheWithheldNativeParser() throws { From 9415d3439bb4510c61c6294a77d679775be821a4 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:35:47 -0800 Subject: [PATCH 23/26] fix(provider): the fifth reviews' findings on #2052 From two fresh-context reviews of e0922a96a0 (REVIEW-5.md: two SHOULD-FIX; REVIEW-5b.md: APPROVE WITH FIXES): 1. A frame's tag in top-level text owns the rest from the first `` read as a mention before it (the malformed header it may belong to), not from the tag, so a think marker in that header's region is inside the owned text (REVIEW-5 #1, 5b NIT 2). 2. The SDK's parser is asked about a frame while lexing only when the frame holds a `"` (the boundary check needs it), and about the final run when it is chosen, instead of about every closed frame: quote-free frames discarded before the end cost no tool-table scan (REVIEW-5 #2, 5b NIT 4). A name the SDK would refuse before reading arguments (invalid, or not an accepted declaration) is refused without asking it. 3. The trailing run is taken whole or not at all, as the SDK takes a batch: a member it refuses (an undeclared name, a missing required argument) no longer lets the members after it run (5b #1). 4. The fallback is gated on `auto` (the prepared choice the scheduler passes the router), not on `!requiresToolCall`: under `none` no residual is published, so the suffix keeps failing (5b NIT 3). Docs and changelog: the whole-batch rule, the mention anchor. The red tests of 43be515df2 and bd0bdd2520 pass with this. Co-Authored-By: Claude Opus 5.5 --- changelog.d/glm-stray-tool-call-text.md | 2 +- docs/architecture/inference.md | 13 ++-- docs/reference/configuration.md | 2 +- .../Inference/Streaming/GLM5ToolSuffix.swift | 68 ++++++++++++------- .../Streaming/NativeToolStreamRouter.swift | 7 +- 5 files changed, 60 insertions(+), 32 deletions(-) diff --git a/changelog.d/glm-stray-tool-call-text.md b/changelog.d/glm-stray-tool-call-text.md index 6e6dd26683..8347502473 100644 --- a/changelog.d/glm-stray-tool-call-text.md +++ b/changelog.d/glm-stray-tool-call-text.md @@ -1,5 +1,5 @@ ### A stray `` no longer fails a GLM-5.3-Flash response - GLM's tool parser reads a response from its first `` to the end as one batch of calls, and on `auto` tool requests that includes the model's reasoning. A tag the model only mentioned or a call it drafted in its thought, or a text answer that mentions the tag, failed the whole response with a 500 (`native GLM tool output is invalid`). -- Such output is now text instead of a failure, as vLLM's and SGLang's GLM parsers never fail a response on tool syntax, with a stricter rule for what is still a call: the calls are the well-formed frames that end the response; everything before them is text, which the service's reasoning parser splits at ``. A frame inside or after another frame's arguments, or after arguments that break the parser's grammar, is never a call. Output with no such calls (a malformed or cut-off final call, text after the calls) is all text, and so is output cut off at `max_tokens` whose tool suffix does not parse. No call is completed or salvaged. +- Such output is now text instead of a failure, as vLLM's and SGLang's GLM parsers never fail a response on tool syntax, with a stricter rule for what is still a call: the calls are the frames that end the response, when all of them are well-formed; everything before them is text, which the service's reasoning parser splits at ``. A frame inside or after another frame's arguments, or after arguments that break the parser's grammar, is never a call. Output with no such calls (a malformed or cut-off final call, a malformed call among the final ones, text after the calls) is all text, and so is output cut off at `max_tokens` whose tool suffix does not parse. No call is completed or salvaged. - Still a 500, as before: output whose released text would hold a think marker from inside a tool frame (the reasoning parser would read it as the end of the thought), and a tool suffix over the parser's 1 MiB bound. Required and named `tool_choice` still fail closed (422). `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the 500 for every unparsed suffix; `darkbloom start` passes it to the launchd provider. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 4e9cf0af2d..de5f8354a5 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1789,9 +1789,9 @@ failure: like the reference GLM parsers (vLLM, SGLang), which never fail a response on tool syntax, the provider returns it as text, under its own stricter rule for what still counts as a call (`NativeToolStreamRouter.finishCompleteCalls`, `GLM5ToolSuffix`). The calls are the trailing run of top-level frames, separated -only by whitespace and ending the response, from just after the last frame of the -run that does not parse; everything before them is text, which the service's -reasoning parser then splits at ``. A frame that has started its +only by whitespace and ending the response, when the SDK parser accepts every one +of them (like the SDK, the batch is taken whole or not at all); everything before +them is text, which the service's reasoning parser then splits at ``. A frame that has started its arguments must follow the SDK parser's grammar to its own `` (a string-typed value raw to ``, any other value structurally valid JSON, whose quoted delimiters are data). One that does not (malformed JSON, a raw @@ -1803,7 +1803,8 @@ response: no frame inside or after its arguments is ever a call. Where the SDK accepts a frame on its own, the lexer reads it as the SDK does; a frame the SDK refuses keeps its end only without a `"` (one may open a JSON string that a raw reading ends inside, or end a raw string that a JSON reading runs past), else it -owns the rest too, as does a frame's tag in top-level text. A `` +owns the rest too, as does a frame's tag in top-level text (from the first +`` read as a mention before it). A `` followed by anything else, with no frame tags before the next ``, is a mention; a thought that spells out the tags in order (`` … ``) therefore owns the rest, and fails as before when its `` follows. A suffix @@ -1814,8 +1815,8 @@ inside a frame (its name, a key or a value, or anything after a frame that owns the rest) before the reasoning parser keeps failing (500), at a stop or at the token limit, as does a suffix the SDK refuses as oversized while it streams, and a required or named call (422). Unlike vLLM and SGLang, a call followed by text -or by a malformed frame commits nothing, and a call drafted inside a closed -thought stays reasoning. A suffix that parses keeps its calls as before. The +or by a malformed frame, or next to one in the final run, commits nothing, and a +call drafted inside a closed thought stays reasoning. A suffix that parses keeps its calls as before. The rule follows the handler's `glm5` parser format, so a request that selects that parser for another family gets it too. `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure (500). diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index dd2c2ba4dc..87cbd9e3f4 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -565,7 +565,7 @@ and rollback are defined in the [provider configuration reference](../provider/c | `DARKBLOOM_TTFT_GDN_BLOCKED` | `0`, `false`, `no`, `off` keep the stock kernel; `packed` or `rows` force that kernel; unset or any other value probes. Case-insensitive; surrounding whitespace is ignored | probe | `libs/mlx-swift-lm/Libraries/MLXLMCommon/GatedDelta.swift` (`GatedDeltaPrefill.mode`, `GatedDeltaPrefill.kernel`) | Selects the Gated DeltaNet prompt-window kernel of `qwen3_5`, `qwen3_5_moe` and `prism_hadamard_qwen35` models ([mechanism](../architecture/inference.md#context)). The default probe keeps a four-row kernel only where it reproduces `gated_delta_step` bit for bit on the GPU; it does not compare speed, so `0` is the rollback where a kept kernel is slower. Forced kernels skip that check and are for A/B measurement only. Decode, MTP verification and masked updates always use the stock kernel. Read once per process. Forwarded to the LaunchAgent. | | `DARKBLOOM_ENGINE_V2_VLM_PARITY_CHECK` | `0` skips | on | `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VLMTextExtraction.swift` | VLM text-extraction parity check. | | `DARKBLOOM_TTFT_STREAM_TOOL_CALLS` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/ToolStreamPreparation.swift` (`streamsToolCallsByDefault`) | Chat streams send `tool_choice` `auto` calls in the Gemma, Qwen 3.5, Harmony and framed-JSON formats as OpenAI `tool_calls` fragments while they are generated; each call is still validated when its frame closes. Required/named calls and other formats are unchanged. `0` restores complete calls at the engine terminal. See [streamed auto tool calls](../architecture/inference.md#streamed-auto-tool-calls). Forwarded to the LaunchAgent. | -| `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift` (`returnsUnparsedOutputAsTextByDefault`) | GLM-5.3-Flash `auto` tool output whose tool suffix does not parse as one call batch (a `` mentioned or drafted in the thought, or mentioned in the answer) is returned as text, with the well-formed frames that end the response as its calls (`GLM5ToolSuffix`). Output whose released text would hold a think marker from inside a tool frame, and a suffix over the parser's 1 MiB bound, still fail (500); required/named calls still fail closed (422). `0` restores the 500 for any such response. See [GLM5Next implementation boundary](../architecture/inference.md#glm5next-implementation-boundary). Forwarded to the LaunchAgent. | +| `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift` (`returnsUnparsedOutputAsTextByDefault`) | GLM-5.3-Flash `auto` tool output whose tool suffix does not parse as one call batch (a `` mentioned or drafted in the thought, or mentioned in the answer) is returned as text, with the frames that end the response as its calls when all of them are well-formed (`GLM5ToolSuffix`). Output whose released text would hold a think marker from inside a tool frame, and a suffix over the parser's 1 MiB bound, still fail (500); required/named calls still fail closed (422). `0` restores the 500 for any such response. See [GLM5Next implementation boundary](../architecture/inference.md#glm5next-implementation-boundary). Forwarded to the LaunchAgent. | | `DARKBLOOM_TTFT_THINK_CONTENT_SEED` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningPromptProbe.swift` (`seedsPlainTailContentByDefault`) | Qwen3-VL (`qwen3_vl_moe`, `plainTailContentModelTypes`) requests on the `qwen3` reasoning parser whose prompt tail has no think marker start in content state, so the answer streams instead of waiting for a tag or the end of generation. Other model types, including close-only Qwen reasoners, keep undecided parsing. `0` restores undecided parsing. Forwarded to the LaunchAgent. | ### Managed Nemotron Super slot diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift index 5bb391a9ba..e1870c29d4 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift @@ -10,8 +10,8 @@ import MLXLMCommon /// batch. Reference GLM parsers (vLLM, SGLang) never fail a response on tool /// syntax; here such a suffix is text too, under a stricter, provider-specific /// rule for what is still a call: the trailing run of top-level frames, -/// separated only by whitespace and ending the response, from just after the -/// run's last frame that does not parse. Everything before them is text. +/// separated only by whitespace and ending the response, when every frame of +/// it parses. Everything before them is text. /// /// Only text the lexer can place outside every frame's arguments starts a /// frame. A frame that has started its arguments must follow the SDK's grammar @@ -52,15 +52,14 @@ enum GLM5ToolSuffix { end = frame.lowerBound } run.reverse() - // Each frame parses on its own, so the starts that parse to the - // end are exactly those after the run's last frame that does not. - let first = run.lastIndex { !lexer.accepted[$0] }.map { $0 + 1 } ?? 0 - if first < run.count { - let from = lexer.frames[run[first]].lowerBound + // The run is the response's call batch: like the SDK, take all of + // it or none, so a member the SDK refuses runs no other member. + if let head = run.first, run.allSatisfy({ lexer.verdicts[$0] ?? lexer.accepts(lexer.frames[$0]) }) { + let from = lexer.frames[head].lowerBound let parsed = GLM5ToolCallParser().parseEOS( String(decoding: bytes[from...], as: UTF8.self), tools: tools) // The SDK reads the same frames; anything else stays text. - if parsed.count == run.count - first { + if parsed.count == run.count { start = from calls = parsed } @@ -89,12 +88,16 @@ enum GLM5ToolSuffix { private let parameters: [String: [String: any Sendable]] /// Closed top-level frames, in order. private(set) var frames: [Range] = [] - /// Whether the SDK's parser accepts each frame on its own. - private(set) var accepted: [Bool] = [] + /// Whether the SDK's parser accepts each frame on its own, where that + /// was needed while lexing (a frame with a `"`); nil: not asked yet. + private(set) var verdicts: [Bool?] = [] /// Start of a frame whose arguments break the grammar, are still open /// at the end or end where another reading would not; it owns the - /// rest of the response. Also a frame's tag in top-level text. + /// rest of the response. For a frame's tag in top-level text, the + /// first mention before it, or the tag. private(set) var unclosed: Int? + /// The first `` read as a mention. + private var firstMention: Int? private var index = 0 init(bytes: [UInt8], tools: [[String: any Sendable]]?) { @@ -128,9 +131,10 @@ enum GLM5ToolSuffix { while true { let next = find("", from: index) // A frame's tag in top-level text belongs to no frame: what - // follows it may be that frame's arguments. + // follows it may be that frame's arguments, and a header read + // as a mention before it may be that frame's. if let stray = first(of: Self.frameTags, in: index ..< (next ?? bytes.count)) { - unclosed = stray + unclosed = firstMention ?? stray return } guard let start = next, let tag = find("<", from: start + 11) else { return } @@ -138,8 +142,7 @@ enum GLM5ToolSuffix { index = tag + 12 guard record(start ..< index) else { return } } else if starts("", at: tag) { - let name = String(decoding: bytes[start + 11 ..< tag], as: UTF8.self) - .trimmingCharacters(in: CharacterSet(charactersIn: " \t\r\n")) + let name = frameName(start ..< tag) let declared = Self.isFunctionName(name) ? parameters[name] : nil guard let end = arguments(from: tag, parameters: declared) else { unclosed = start @@ -156,27 +159,46 @@ enum GLM5ToolSuffix { unclosed = start return } + firstMention = firstMention ?? start index = following } } } - /// Records a closed frame and whether the SDK accepts it on its own. A - /// frame the SDK refuses keeps its boundary only without a `"`: one may - /// open a JSON string that a raw reading ends inside, or end a raw - /// string that a JSON reading runs past. False when it owns the rest. + /// Records a closed frame. A frame the SDK refuses keeps its boundary + /// only without a `"`: one may open a JSON string that a raw reading + /// ends inside, or end a raw string that a JSON reading runs past. Only + /// such a frame is checked here; false when it owns the rest. private mutating func record(_ frame: Range) -> Bool { - let accepts = GLM5ToolCallParser().parse( - content: String(decoding: bytes[frame], as: UTF8.self), tools: tools) != nil - if !accepts, bytes[frame].contains(34) { + guard bytes[frame].contains(34) else { + frames.append(frame) + verdicts.append(nil) + return true + } + guard accepts(frame) else { unclosed = frame.lowerBound return false } frames.append(frame) - accepted.append(accepts) + verdicts.append(true) return true } + /// Whether the SDK's parser accepts `frame` on its own. A name it + /// would refuse before reading arguments is refused without asking it. + func accepts(_ frame: Range) -> Bool { + guard let tag = find("<", from: frame.lowerBound + 11) else { return false } + let name = frameName(frame.lowerBound ..< tag) + guard Self.isFunctionName(name), parameters[name] != nil else { return false } + return GLM5ToolCallParser().parse(content: String(decoding: bytes[frame], as: UTF8.self), tools: tools) != nil + } + + /// The name of the frame opening at `header.lowerBound`, up to its first `<`. + private func frameName(_ header: Range) -> String { + String(decoding: bytes[header.lowerBound + 11 ..< header.upperBound], as: UTF8.self) + .trimmingCharacters(in: CharacterSet(charactersIn: " \t\r\n")) + } + /// The tags of a frame after its ``. private static let frameTags = ["", "", "", "", ""] /// The tags the SDK refuses inside a raw value. diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift index ad68bf67c1..d17bc647b2 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift @@ -21,6 +21,9 @@ struct NativeToolStreamRouter { /// An `auto` GLM tool suffix that does not parse at EOS is text /// (`GLM5ToolSuffix`). private let glmUnparsedOutputIsText: Bool + /// The request's tool choice is `auto`: the only mode whose residual text + /// the caller publishes. + private let autoToolChoice: Bool /// `finishCompleteCalls` has released the EOS suffix that way, which /// answers its parse failure. private var glmSuffixSplit = false @@ -55,6 +58,8 @@ struct NativeToolStreamRouter { self.nativeMiMoRequiresConstraint = nativeMiMoRequiresConstraint self.rejectMiMoThought = nativeMiMoChannels && !nativeMiMoThinkingEnabled self.streamedCallPolicy = handler?.streamsCalls == true ? streamedCalls : nil + // The scheduler passes the prepared choice here on every path. + self.autoToolChoice = streamedCalls.map { $0.mode == .auto } ?? !requiresToolCall if nativeGemmaChannels { gemmaParser = DiffusionGemmaChannelSplitter() } else if let nativePrefix { @@ -183,7 +188,7 @@ struct NativeToolStreamRouter { } private var returnsUnparsedGLMOutputAsText: Bool { - handler?.format == .glm5 && glmUnparsedOutputIsText && !requiresToolCall + handler?.format == .glm5 && glmUnparsedOutputIsText && autoToolChoice } private mutating func route(_ pieces: [ParsedReasoning]) throws -> [MLXServerGenerationEvent] { From afa6697a617e4ac60fd95dbcdaf9a1c57b93b78f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:45:57 -0800 Subject: [PATCH 24/26] refactor(provider): refactor pass on 9415d3439b; the sixth reviews' NITs Behaviour-preserving: - The dedicated refactor-pass subagent (AGENTS.md) on 9415d3439b (glm-stray-evidence/refactor/ASSESSMENT-4.md): the trailing run is a range of frame indices (it is always a suffix of the frames) instead of a reversed array and a second lookup of its start. - REVIEW-6 NIT 1 / REVIEW-6b NIT 1: when the lexer asks the SDK's parser about a frame with a `"`, it passes that name's one accepted declaration instead of the whole tool list, which the SDK scans per frame; the SDK resolves the name the same way from either (the lexer keeps only names with exactly one accepted declaration, and refuses every name when an entry's `function` is not an object, as the SDK does). The final `parseEOS` still uses the whole list. Functional case: 12,000 such frames discarded before the end, against 500 tools. - REVIEW-6 NIT 2: the changelog says that output the parser cannot read safely (a thought spelling out the tags, a refused call with quotes before the final calls) recovers no call. Co-Authored-By: Claude Opus 5.5 --- changelog.d/glm-stray-tool-call-text.md | 2 +- .../Inference/Streaming/GLM5ToolSuffix.swift | 71 ++++++++++++------- .../Streaming/GLM5ToolFailureTests.swift | 14 ++++ 3 files changed, 60 insertions(+), 27 deletions(-) diff --git a/changelog.d/glm-stray-tool-call-text.md b/changelog.d/glm-stray-tool-call-text.md index 8347502473..b72b23f66e 100644 --- a/changelog.d/glm-stray-tool-call-text.md +++ b/changelog.d/glm-stray-tool-call-text.md @@ -2,4 +2,4 @@ - GLM's tool parser reads a response from its first `` to the end as one batch of calls, and on `auto` tool requests that includes the model's reasoning. A tag the model only mentioned or a call it drafted in its thought, or a text answer that mentions the tag, failed the whole response with a 500 (`native GLM tool output is invalid`). - Such output is now text instead of a failure, as vLLM's and SGLang's GLM parsers never fail a response on tool syntax, with a stricter rule for what is still a call: the calls are the frames that end the response, when all of them are well-formed; everything before them is text, which the service's reasoning parser splits at ``. A frame inside or after another frame's arguments, or after arguments that break the parser's grammar, is never a call. Output with no such calls (a malformed or cut-off final call, a malformed call among the final ones, text after the calls) is all text, and so is output cut off at `max_tokens` whose tool suffix does not parse. No call is completed or salvaged. -- Still a 500, as before: output whose released text would hold a think marker from inside a tool frame (the reasoning parser would read it as the end of the thought), and a tool suffix over the parser's 1 MiB bound. Required and named `tool_choice` still fail closed (422). `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the 500 for every unparsed suffix; `darkbloom start` passes it to the launchd provider. +- Still a 500, as before: output whose released text would hold a think marker from inside a tool frame (the reasoning parser would read it as the end of the thought), and a tool suffix over the parser's 1 MiB bound. Output the parser cannot read safely, such as a thought that spells out the tags in order (``, ``, ``) or a refused call with quotes before the final calls, recovers no call: it is text, or still a 500 when the thought's `` comes after it. Required and named `tool_choice` still fail closed (422). `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the 500 for every unparsed suffix; `darkbloom start` passes it to the launchd provider. diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift index e1870c29d4..3a02e4de05 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift @@ -43,19 +43,16 @@ enum GLM5ToolSuffix { var calls: [ToolCall] = [] if !truncated, lexer.unclosed == nil { // The run of whitespace-separated frames that ends the response. - var run: [Int] = [] - var end = bytes.count - for frameIndex in lexer.frames.indices.reversed() { - let frame = lexer.frames[frameIndex] - guard Lexer.isWhitespace(bytes[frame.upperBound ..< end]) else { break } - run.append(frameIndex) - end = frame.lowerBound + var head = lexer.frames.endIndex + var from = bytes.count + while head > 0, Lexer.isWhitespace(bytes[lexer.frames[head - 1].upperBound ..< from]) { + head -= 1 + from = lexer.frames[head].lowerBound } - run.reverse() + let run = head ..< lexer.frames.endIndex // The run is the response's call batch: like the SDK, take all of // it or none, so a member the SDK refuses runs no other member. - if let head = run.first, run.allSatisfy({ lexer.verdicts[$0] ?? lexer.accepts(lexer.frames[$0]) }) { - let from = lexer.frames[head].lowerBound + if !run.isEmpty, run.allSatisfy({ lexer.verdicts[$0] ?? lexer.accepts(lexer.frames[$0]) }) { let parsed = GLM5ToolCallParser().parseEOS( String(decoding: bytes[from...], as: UTF8.self), tools: tools) // The SDK reads the same frames; anything else stays text. @@ -84,7 +81,8 @@ enum GLM5ToolSuffix { /// move it. struct Lexer { let bytes: [UInt8] - private let tools: [[String: any Sendable]]? + /// Each declaration the SDK's parser accepts, by name, and its schema. + private let declarations: [String: [String: any Sendable]] private let parameters: [String: [String: any Sendable]] /// Closed top-level frames, in order. private(set) var frames: [Range] = [] @@ -102,28 +100,46 @@ enum GLM5ToolSuffix { init(bytes: [UInt8], tools: [[String: any Sendable]]?) { self.bytes = bytes - self.tools = tools // Only a declaration the SDK's parser accepts types arguments: one - // per name, an object schema without indirect types. + // per name, an object schema without indirect types. A `function` + // that is not an object makes it refuse every name. + var declarations: [String: [String: any Sendable]] = [:] var parameters: [String: [String: any Sendable]] = [:] var seen: Set = [] var duplicates: Set = [] for tool in tools ?? [] { - let function = (tool["function"] as? [String: any Sendable]) ?? tool + let function: [String: any Sendable] + if let wrapped = tool["function"] { + guard let object = wrapped as? [String: any Sendable] else { + declarations = [:] + parameters = [:] + break + } + function = object + } else { + function = tool + } guard let name = function["name"] as? String else { continue } if !seen.insert(name).inserted { duplicates.insert(name) } - guard let declared = function["parameters"] else { - parameters[name] = [:] - continue + let schema: [String: any Sendable] + if let declared = function["parameters"] { + guard let object = declared as? [String: any Sendable], + object["type"] == nil || object["type"] as? String == "object", + !Self.hasIndirectType(object), + object["properties"].map({ $0 is [String: any Sendable] }) ?? true + else { continue } + schema = object + } else { + schema = [:] } - guard let schema = declared as? [String: any Sendable], - schema["type"] == nil || schema["type"] as? String == "object", - !Self.hasIndirectType(schema), - schema["properties"].map({ $0 is [String: any Sendable] }) ?? true - else { continue } + declarations[name] = tool parameters[name] = schema } - for name in duplicates { parameters[name] = nil } + for name in duplicates { + declarations[name] = nil + parameters[name] = nil + } + self.declarations = declarations self.parameters = parameters } @@ -185,12 +201,15 @@ enum GLM5ToolSuffix { } /// Whether the SDK's parser accepts `frame` on its own. A name it - /// would refuse before reading arguments is refused without asking it. + /// would refuse before reading arguments is refused without asking it; + /// otherwise it is asked with that name's one declaration, which it + /// resolves the same way as from the whole list, without scanning it. func accepts(_ frame: Range) -> Bool { guard let tag = find("<", from: frame.lowerBound + 11) else { return false } let name = frameName(frame.lowerBound ..< tag) - guard Self.isFunctionName(name), parameters[name] != nil else { return false } - return GLM5ToolCallParser().parse(content: String(decoding: bytes[frame], as: UTF8.self), tools: tools) != nil + guard Self.isFunctionName(name), let declaration = declarations[name] else { return false } + return GLM5ToolCallParser().parse( + content: String(decoding: bytes[frame], as: UTF8.self), tools: [declaration]) != nil } /// The name of the frame opening at `header.lowerBound`, up to its first `<`. diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift index 33e4c5240c..a75b05b9b5 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift @@ -421,6 +421,20 @@ struct GLM5ToolFailureTests { #expect(GLM5ToolSuffix.split(suffix, tools: tools) == .text(suffix, calls: [])) } + /// And many discarded frames that the SDK must check (they hold a `"`) + /// against many tools: each check resolves the frame's one declaration. + @Test func manyQuotedDiscardedFramesAgainstManyTools() throws { + var tools: [[String: any Sendable]] = (1 ..< 500).map { + ["type": "function", "function": ["name": "f\($0)"] as [String: any Sendable]] + } + tools.insert(["type": "function", "function": ["name": "f0", "parameters": ["type": "object", + "properties": ["x": ["type": "string"] as [String: any Sendable]] as [String: any Sendable]] + as [String: any Sendable]] as [String: any Sendable]], at: 0) + let frame = #"f0x"."# + let suffix = "." + String(repeating: frame, count: 12_000) + #expect(GLM5ToolSuffix.split(suffix, tools: tools) == .text(suffix, calls: [])) + } + /// And a long generated name with many arguments: the name is looked up /// once per frame, not once per argument. @Test func longNameWithManyArguments() throws { From f64d2fee90211084843e9593cc15de3e097aefdd Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:46:12 -0800 Subject: [PATCH 25/26] test(provider): the sixth review's finding on #2052 (red) The second fresh-context review of 9415d3439b (REVIEW-6b.md, APPROVE WITH FIXES, one SHOULD-FIX) as a test, before the fix: a frame's tag in top-level text after a closed frame (no mention before it) owned the rest only from the tag, but the closed frame's raw value may run on through it (the template writes strings raw and unescaped), so a think marker between the frame and the orphan tag was released (either direction). Expected: the response keeps failing, at `stop` and `length`. Red on afa6697a61. Co-Authored-By: Claude Opus 5.5 --- .../Streaming/GLM5ToolFailureTests.swift | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift index a75b05b9b5..9f62dae47c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift @@ -329,6 +329,22 @@ struct GLM5ToolFailureTests { } } + /// And a closed frame before it: its value may run on, unescaped, through + /// the orphan tags (the template writes strings raw), so a think marker + /// between them, either way, still fails. + @Test(arguments: ["stop", "length"], [1, 5, 4096]) + func orphanTagsTakeBackAnEarlierFrame(finishReason: String, width: Int) async throws { + let echo = "echotextx" + for (output, visible) in [ + (echo + "PRIVATE", ""), + ("Done." + echo + "HIDDEN", "Done."), + ] { + let result = try await run(output, forced: false, width: width, finishReason: finishReason) + #expect(result.calls.isEmpty && result.visible == visible, "\(output)") + #expect(result.failure == .generationFailed("native GLM tool output is invalid"), "\(output)") + } + } + /// A trailing run with a member the SDK refuses is not a batch to take /// part of: no member of it runs, as the SDK's own batch rule says (an /// undeclared name, a missing required argument). From 91ae6525ecaf0259c74b1798d2cb63a64929147d Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:48:49 -0800 Subject: [PATCH 26/26] fix(provider): the sixth review's finding on #2052 From the second fresh-context review of 9415d3439b (REVIEW-6b.md, APPROVE WITH FIXES): a frame's tag in top-level text owns the rest from the first frame or mention before it, not only from a mention: a closed frame's raw value may run on, unescaped, through the orphan tags, so a think marker between them is inside the owned text and still fails. When such a tag is there no call is recovered anyway; only think markers move back to the 500 they were on dev. Not taken: REVIEW-6b NIT 2 (check a refused frame for `"` only after its name). A Hermes-style draft whose JSON "name" region opens a string could then end the frame early and let a frame inside that string run. The red test of f64d2fee90 passes with this. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 2 +- .../ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index de5f8354a5..61a5254cae 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1804,7 +1804,7 @@ accepts a frame on its own, the lexer reads it as the SDK does; a frame the SDK refuses keeps its end only without a `"` (one may open a JSON string that a raw reading ends inside, or end a raw string that a JSON reading runs past), else it owns the rest too, as does a frame's tag in top-level text (from the first -`` read as a mention before it). A `` +frame or `` read as a mention before it). A `` followed by anything else, with no frame tags before the next ``, is a mention; a thought that spells out the tags in order (`` … ``) therefore owns the rest, and fails as before when its `` follows. A suffix diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift index 3a02e4de05..0440c8b362 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift @@ -92,7 +92,7 @@ enum GLM5ToolSuffix { /// Start of a frame whose arguments break the grammar, are still open /// at the end or end where another reading would not; it owns the /// rest of the response. For a frame's tag in top-level text, the - /// first mention before it, or the tag. + /// first frame or mention before it, or the tag. private(set) var unclosed: Int? /// The first `` read as a mention. private var firstMention: Int? @@ -148,9 +148,10 @@ enum GLM5ToolSuffix { let next = find("", from: index) // A frame's tag in top-level text belongs to no frame: what // follows it may be that frame's arguments, and a header read - // as a mention before it may be that frame's. + // as a mention before it, or a closed frame whose raw value + // runs on through it, may be that frame's. Own from the first. if let stray = first(of: Self.frameTags, in: index ..< (next ?? bytes.count)) { - unclosed = firstMention ?? stray + unclosed = min(stray, firstMention ?? stray, frames.first?.lowerBound ?? stray) return } guard let start = next, let tag = find("<", from: start + 11) else { return }