From 2b4f9c96a4add732e88504ec806b0bf49d03e847 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:18:51 -0800 Subject: [PATCH 1/6] test(provider): a GPT-OSS answer under a final header with attributes reaches the client (red) GPT-OSS can open its answer with Harmony header attributes: <|channel|>final <|constrain|>json<|message|>. The SDK's Harmony reasoning parser routes only the exact header "final" to content and drops any other message, so such an answer reached the client as empty content. Adds the tests and a pass-through HarmonyFinalHeaderFilter, wired into the engine's forwarding body for GPT-OSS streams the Harmony parser splits. The filter does nothing yet, so the answer tests fail. Co-Authored-By: Claude Opus 5.5 --- .../MultiModelBatchSchedulerEngine.swift | 27 ++-- .../Streaming/HarmonyFinalHeaderFilter.swift | 35 +++++ .../HarmonyFinalHeaderFilterTests.swift | 130 ++++++++++++++++++ 3 files changed, 184 insertions(+), 8 deletions(-) create mode 100644 provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index e7ea281696..5119b17793 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -1199,7 +1199,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { .init(modelId: modelId, modelType: modelType)), answerStopFilter: answerStopFilter, answerFormat: jsonAnswer?.format, - withholdReasoning: withholdsReasoning + withholdReasoning: withholdsReasoning, + harmonyFinalHeaders: HarmonyFinalHeaderFilter.applies(to: request, modelId: modelId, modelType: modelType) ) } @@ -1568,7 +1569,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { absorbStrayThinkClose: Bool = false, answerStopFilter: FlintAnswerStopFilter? = nil, answerFormat: JSONAnswerFormat? = nil, - withholdReasoning: Bool = false + withholdReasoning: Bool = false, + harmonyFinalHeaders: Bool = false ) async throws -> AsyncThrowingStream { do { try checkFirstContentDeadline() @@ -1596,7 +1598,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { absorbStrayThinkClose: absorbStrayThinkClose, answerStopFilter: answerStopFilter, answerFormat: answerFormat, - withholdReasoning: withholdReasoning) + withholdReasoning: withholdReasoning, + harmonyFinalHeaders: harmonyFinalHeaders) try checkFirstContentDeadline() return stream } catch { @@ -1632,7 +1635,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { absorbStrayThinkClose: Bool = false, answerStopFilter: FlintAnswerStopFilter? = nil, answerFormat: JSONAnswerFormat? = nil, - withholdReasoning: Bool = false + withholdReasoning: Bool = false, + harmonyFinalHeaders: Bool = false ) throws -> AsyncThrowingStream { // One forwarding implementation preserves all parser/event bytes. The // native path changes only task ownership and cancellation handoff. @@ -1673,6 +1677,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { // Raw output passes this holdback before channel/tool parsing, // so a matched answer stop and its tail are never parsed. var answerStops = answerStopFilter + // GPT-OSS answers under `final <|constrain|>json` reach the Harmony parser as `final`. + var finalHeaders = harmonyFinalHeaders ? HarmonyFinalHeaderFilter() : nil // Exact Flint's prepared format, or the format a constrained // Qwen answer was compiled with. var formatOutput = (answerFormat ?? prepared.responseFormat).map(JSONAnswerOutput.init) @@ -1758,7 +1764,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { // Before any frame: generated output ends the // pre-content interval even while it is withheld. if recordsWithheldOutput, !generated.isEmpty { usageSignal.recordWithheldOutput() } - let text = answerStops?.ingest(generated) ?? generated + let stopped = answerStops?.ingest(generated) ?? generated + let text = finalHeaders?.ingest(stopped) ?? stopped if !text.isEmpty { do { let events = try router.process(text) @@ -1869,7 +1876,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { // defense in depth for every mode. do { var events: [MLXServerGenerationEvent] = [] - if let tail = answerStops?.finish(), !tail.isEmpty { + var tail = answerStops?.finish() ?? "" + if var filter = finalHeaders { tail = filter.ingest(tail) + filter.finish() } + if !tail.isEmpty { events += try router.process(tail) } events += try router.finishText() @@ -2055,13 +2064,15 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { recordsWithheldOutput: Bool = false, usageSignal: EngineV2RequestUsageSignal = EngineV2RequestUsageSignal(), answerStopFilter: FlintAnswerStopFilter? = nil, - answerFormat: JSONAnswerFormat? = nil + answerFormat: JSONAnswerFormat? = nil, + harmonyFinalHeaders: Bool = false ) throws -> AsyncThrowingStream { try makeEventStream(upstream: upstream, cancelUpstream: cancelUpstream, toolHandler: toolHandler, prepared: prepared, releaseBox: releaseBox, usageSignal: usageSignal, reasoningPrefix: reasoningPrefix, nativeReasoningPrefix: nativeReasoningPrefix, recordsWithheldOutput: recordsWithheldOutput, - answerStopFilter: answerStopFilter, answerFormat: answerFormat) + answerStopFilter: answerStopFilter, answerFormat: answerFormat, + harmonyFinalHeaders: harmonyFinalHeaders) } #endif diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift new file mode 100644 index 0000000000..8863dbaa9c --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift @@ -0,0 +1,35 @@ +// Copyright © 2026 Eigen Labs. + +import MLXLMServer + +/// Rewrites a GPT-OSS answer header that carries attributes, such as +/// `<|channel|>final <|constrain|>json<|message|>`, to the plain +/// `<|channel|>final<|message|>`. The Harmony reasoning parser routes only the +/// exact header `final` to content and drops every other message, so such an +/// answer reached the client as empty content. Other headers, and all text +/// outside headers, pass through byte for byte. +struct HarmonyFinalHeaderFilter: Sendable { + static let channelMarker = "<|channel|>" + static let messageMarker = "<|message|>" + /// A header is a few tokens; longer text after `<|channel|>` passes unchanged. + static let maximumHeaderBytes = 256 + + private var pending = "" + private var inHeader = false + + /// A GPT-OSS stream the Harmony reasoning parser splits (every coordinator + /// request, and local requests that name no other parser). + static func applies(to request: OpenAIChatCompletionRequest, modelId: String, modelType: String?) -> Bool { + request.reasoningParser == .harmony + && GPTOSSHarmonyTemplateFix.applies(to: ChatTemplateFixContext(modelId: modelId, modelType: modelType)) + } + + mutating func ingest(_ text: String) -> String { + text + } + + /// The text still held: an unfinished header or a partial `<|channel|>`. + mutating func finish() -> String { + "" + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift new file mode 100644 index 0000000000..fc08554a6f --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift @@ -0,0 +1,130 @@ +import Foundation +import MLXLMServer +import Testing +@testable import ProviderCore + +/// GPT-OSS answers under a `final` header with attributes reach the client as +/// content: the provider's filter, then the SDK's Harmony reasoning parser, as +/// `MLXOpenAIService` runs it on every coordinator stream. +struct HarmonyFinalHeaderFilterTests { + static let analysis = "<|channel|>analysis<|message|>Need JSON.<|end|><|start|>assistant" + static let answer = "{\"a\":1,\"b\":\"\"}" + + static func chunks(_ text: String, width: Int) -> [String] { + let characters = Array(text) + return stride(from: 0, to: characters.count, by: width).map { + String(characters[$0.. String { + var filter = HarmonyFinalHeaderFilter() + return chunks(text, width: width).map { filter.ingest($0) }.joined() + filter.finish() + } + + /// What a client receives: content and reasoning after the Harmony split. + static func received(_ text: String, width: Int) -> (content: String, reasoning: String) { + var parser = StreamingReasoningParser(format: .harmony) + var parsed = [ParsedReasoning]() + for chunk in chunks(filtered(text, width: width), width: width) { parsed += parser.parse(chunk) } + parsed += parser.finish() + return (parsed.map(\.content).joined(), parsed.compactMap(\.reasoningContent).joined()) + } + + static let widths = [1, 2, 3, 5, 11, 4096] + + @Test("an answer under `final <|constrain|>json` is content", arguments: widths) + func constrainedAnswerIsContent(width: Int) { + let output = Self.analysis + "<|channel|>final <|constrain|>json<|message|>" + Self.answer + "<|return|>" + let result = Self.received(output, width: width) + #expect(result.content == Self.answer) + #expect(result.reasoning == "Need JSON.") + } + + @Test("a bare content type or no space before the constraint is an answer too", arguments: widths) + func otherAttributeSpellingsAreContent(width: Int) { + for header in ["final json", "final<|constrain|>json", "final <|constrain|>JSON "] { + let output = Self.analysis + "<|channel|>\(header)<|message|>" + Self.answer + #expect(Self.received(output, width: width).content == Self.answer, "\(header)") + } + } + + @Test("every other header and all other text pass through byte for byte", arguments: widths) + func otherOutputIsUnchanged(width: Int) { + let outputs = [ + Self.analysis + "<|channel|>final<|message|>Plain answer.<|return|>", + "<|channel|>commentary to=functions.get_weather <|constrain|>json<|message|>{\"city\":\"Paris\"}<|call|>", + "<|channel|>commentary<|message|>Checking the weather.<|end|>", + "<|channel|>final to=functions.x<|message|>{}", + "<|channel|>finalize<|message|>x", + "No markers <|chan at all, a < and |>.", + "Unicode é 🙂 <|channel|>analysis<|message|>Ünïcode<|end|>", + ] + for output in outputs { + #expect(Self.filtered(output, width: width) == output) + } + } + + @Test("an unterminated or oversized header is passed on unchanged") + func unfinishedHeadersPassThrough() { + let unterminated = Self.analysis + "<|channel|>final <|constrain|>js" + #expect(Self.filtered(unterminated, width: 3) == unterminated) + let oversized = "<|channel|>final " + String(repeating: "a", count: 300) + "<|message|>{}" + #expect(Self.filtered(oversized, width: 7) == oversized) + var partial = HarmonyFinalHeaderFilter() + #expect(partial.ingest("text <|chan") == "text ") + #expect(partial.finish() == "<|chan") + } + + @Test("only a Harmony-parsed GPT-OSS stream is filtered") + func appliesOnlyToHarmonyParsedGPTOSS() throws { + func request(_ parser: String?) throws -> OpenAIChatCompletionRequest { + var body: [String: Any] = ["model": "gpt-oss-20b", "messages": [["role": "user", "content": "Hi"]], + "response_format": ["type": "json_object"]] + if let parser { body["reasoning_parser"] = parser } + return try JSONDecoder().decode(OpenAIChatCompletionRequest.self, + from: JSONSerialization.data(withJSONObject: body)) + } + #expect(HarmonyFinalHeaderFilter.applies(to: try request("harmony"), modelId: "gpt-oss-20b", modelType: "gpt_oss")) + #expect(!HarmonyFinalHeaderFilter.applies(to: try request("none"), modelId: "gpt-oss-20b", modelType: "gpt_oss")) + #expect(!HarmonyFinalHeaderFilter.applies(to: try request(nil), modelId: "gpt-oss-20b", modelType: "gpt_oss")) + #expect(!HarmonyFinalHeaderFilter.applies(to: try request("qwen3"), modelId: "Qwen3.5-9B", modelType: "qwen3_5")) + } + + #if DEBUG + @Test("the engine stream delivers a constrained GPT-OSS answer as content", arguments: [1, 4]) + func engineStreamDeliversConstrainedAnswer(width: Int) async throws { + let output = Self.analysis + "<|channel|>final <|constrain|>json<|message|>" + Self.answer + let pieces = Self.chunks(output, width: width) + let upstream = AsyncStream { continuation in + for piece in pieces { continuation.yield(.chunk(piece)) } + continuation.yield(.info(promptTokens: 12, completionTokens: pieces.count, tokensPerSecond: 1, + finishReason: "stop")) + continuation.finish() + } + let request = try JSONDecoder().decode(OpenAIChatCompletionRequest.self, from: JSONSerialization.data( + withJSONObject: ["model": "gpt-oss-20b", "messages": [["role": "user", "content": "JSON please"]], + "response_format": ["type": "json_object"]])) + let prepared = try ToolChoicePromptPolicy.prepare(request, modelType: "gpt_oss") + let scheduler = MultiModelBatchSchedulerEngine(registryProvider: { [:] }) + let events = try scheduler._testMakeEventStream(upstream: upstream, cancelUpstream: {}, prepared: prepared, + releaseBox: OneShotRelease(release: { _ in }, modelId: "fixture"), harmonyFinalHeaders: true) + var parser = StreamingReasoningParser(format: .harmony) + var content = "" + var reasoning = "" + for try await event in events { + guard case .content(let text) = event else { continue } + for parsed in parser.parse(text) { + content += parsed.content + reasoning += parsed.reasoningContent ?? "" + } + } + for parsed in parser.finish() { + content += parsed.content + reasoning += parsed.reasoningContent ?? "" + } + #expect(content == Self.answer) + #expect(reasoning == "Need JSON.") + } + #endif +} From 0c5c35f64d1ec49416c6521b07b7328150f43c41 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:27:27 -0800 Subject: [PATCH 2/6] fix(provider): a GPT-OSS answer under a final header with attributes reaches the client GPT-OSS can open its answer with Harmony header attributes, as in <|channel|>final <|constrain|>json<|message|>. The SDK's Harmony reasoning parser keeps only a message whose header is exactly "final", so the whole answer was dropped and the client got empty content: OpenRouter's GPT-OSS structured-output error rate (6.7-39.5 % a day, against peers' 1-6 %). HarmonyFinalHeaderFilter now rewrites a final header that carries attributes to <|channel|>final<|message|> in the raw stream, before tool parsing and the Harmony split. It holds back at most the header (a partial <|channel|> marker, or up to 256 bytes after it) and passes everything else byte for byte: analysis and commentary headers, call headers, a final header with a recipient, and all text outside headers. It runs for GPT-OSS streams the Harmony parser splits (every coordinator request). Co-Authored-By: Claude Opus 5.5 --- .../Streaming/HarmonyFinalHeaderFilter.swift | 49 ++++++++++++++++++- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift index 8863dbaa9c..82b97d7123 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift @@ -25,11 +25,56 @@ struct HarmonyFinalHeaderFilter: Sendable { } mutating func ingest(_ text: String) -> String { - text + pending += text + var output = "" + while true { + if inHeader { + guard let end = pending.range(of: Self.messageMarker) else { + if pending.utf8.count > Self.maximumHeaderBytes { + output += pending + pending = "" + inHeader = false + } + return output + } + output += Self.answerHeader(String(pending[..`. mutating func finish() -> String { - "" + defer { pending = ""; inHeader = false } + return pending + } + + /// `final` for an answer header with attributes; any other header as given. + /// A header with a recipient (`to=`) is a call, not an answer. + static func answerHeader(_ header: String) -> String { + let name = header.prefix { !$0.isWhitespace && $0 != "<" } + guard name == "final", header != "final", !header.contains("to=") else { return header } + return "final" + } + + /// Length of the longest suffix of `text` that is a proper prefix of `<|channel|>`. + private static func markerPrefixLength(_ text: String) -> Int { + let marker = Array(channelMarker.utf8) + let bytes = Array(text.utf8.suffix(marker.count - 1)) + for length in stride(from: bytes.count, through: 1, by: -1) + where marker.starts(with: bytes.suffix(length)) { + return String(decoding: bytes.suffix(length), as: UTF8.self).count + } + return 0 } } From 8c08c881b164e292d5c6e1e64d679dbcc6c5d1ba Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:28:13 -0800 Subject: [PATCH 3/6] docs(provider): GPT-OSS answer headers with attributes; changelog fragment Co-Authored-By: Claude Opus 5.5 --- changelog.d/gptoss-final-header-attributes.md | 4 ++++ docs/architecture/inference.md | 13 ++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 changelog.d/gptoss-final-header-attributes.md diff --git a/changelog.d/gptoss-final-header-attributes.md b/changelog.d/gptoss-final-header-attributes.md new file mode 100644 index 0000000000..f97fe04ac0 --- /dev/null +++ b/changelog.d/gptoss-final-header-attributes.md @@ -0,0 +1,4 @@ +### GPT-OSS answers under a `final` header with attributes reach the client + +- GPT-OSS can open its answer with Harmony header attributes, as in `<|channel|>final <|constrain|>json<|message|>`, typically for JSON answers. The provider's Harmony split kept only an exact `final` header, so such an answer was dropped and the client got empty `content`. It now arrives as `content`, as any other answer does. +- Nothing else in a GPT-OSS response changes: reasoning, tool calls, preambles and plain answers are byte-identical. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index a88327753d..5a3811493c 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` @@ -3300,6 +3300,17 @@ markers. It emits unclosed-frame payload incrementally and retains only a possible closing-marker suffix; it does not buffer an entire unfinished tool call (`provider-swift/Sources/ProviderCore/Inference/Streaming/NativeChannelSplitter.swift`). +GPT-OSS can open its answer with Harmony header attributes, as in +`<|channel|>final <|constrain|>json<|message|>`. The SDK's Harmony reasoning +parser routes only the exact header `final` to content and drops every other +message, so `MultiModelBatchSchedulerEngine.makeEventStream` first passes the +raw output of a GPT-OSS request on the `harmony` parser through +`HarmonyFinalHeaderFilter`. A `final` header that carries attributes and no +recipient becomes `<|channel|>final<|message|>`. Analysis, commentary and call +headers, and all text outside headers, pass byte for byte. The filter holds back +at most a partial `<|channel|>` marker or one header of up to 256 bytes +(`provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift`). + Only qualified Nemotron Lightning listings absorb a stray `` already in content state, leaving preceding text as content and tool arguments opaque. `ToolChoiceEnforcementPolicy.absorbsStrayThinkClose` gates the behavior by exact From 81fc75b51843b39d07186f8ca12601c6e9e9490f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:55:55 -0800 Subject: [PATCH 4/6] refactor(provider): tighten the GPT-OSS answer-header filter (refactor pass) From the dedicated refactor pass: the filter's constants and header rule are private, markerPrefixLength returns its ASCII length directly, the engine flag reads as a verb (rewriteHarmonyFinalHeaders) and the released text is named for what it is. Two behavior fixes the pass observed: - A header longer than 256 bytes now passes unchanged at every chunking: it was rewritten when its <|message|> arrived in the same chunk. - A header with leading whitespace (" final json") is rewritten too; the SDK parser trims that whitespace and then drops the attributes. Only surrounding whitespace (" final ") is still left as is. Co-Authored-By: Claude Opus 5.5 --- .../MultiModelBatchSchedulerEngine.swift | 18 +++++----- .../Streaming/HarmonyFinalHeaderFilter.swift | 34 +++++++++++-------- .../HarmonyFinalHeaderFilterTests.swift | 7 ++-- 3 files changed, 33 insertions(+), 26 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index 5119b17793..ab59bec3ef 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -1200,7 +1200,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { answerStopFilter: answerStopFilter, answerFormat: jsonAnswer?.format, withholdReasoning: withholdsReasoning, - harmonyFinalHeaders: HarmonyFinalHeaderFilter.applies(to: request, modelId: modelId, modelType: modelType) + rewriteHarmonyFinalHeaders: HarmonyFinalHeaderFilter.applies(to: request, modelId: modelId, modelType: modelType) ) } @@ -1570,7 +1570,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { answerStopFilter: FlintAnswerStopFilter? = nil, answerFormat: JSONAnswerFormat? = nil, withholdReasoning: Bool = false, - harmonyFinalHeaders: Bool = false + rewriteHarmonyFinalHeaders: Bool = false ) async throws -> AsyncThrowingStream { do { try checkFirstContentDeadline() @@ -1599,7 +1599,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { answerStopFilter: answerStopFilter, answerFormat: answerFormat, withholdReasoning: withholdReasoning, - harmonyFinalHeaders: harmonyFinalHeaders) + rewriteHarmonyFinalHeaders: rewriteHarmonyFinalHeaders) try checkFirstContentDeadline() return stream } catch { @@ -1636,7 +1636,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { answerStopFilter: FlintAnswerStopFilter? = nil, answerFormat: JSONAnswerFormat? = nil, withholdReasoning: Bool = false, - harmonyFinalHeaders: Bool = false + rewriteHarmonyFinalHeaders: Bool = false ) throws -> AsyncThrowingStream { // One forwarding implementation preserves all parser/event bytes. The // native path changes only task ownership and cancellation handoff. @@ -1678,7 +1678,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { // so a matched answer stop and its tail are never parsed. var answerStops = answerStopFilter // GPT-OSS answers under `final <|constrain|>json` reach the Harmony parser as `final`. - var finalHeaders = harmonyFinalHeaders ? HarmonyFinalHeaderFilter() : nil + var finalHeaders = rewriteHarmonyFinalHeaders ? HarmonyFinalHeaderFilter() : nil // Exact Flint's prepared format, or the format a constrained // Qwen answer was compiled with. var formatOutput = (answerFormat ?? prepared.responseFormat).map(JSONAnswerOutput.init) @@ -1764,8 +1764,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { // Before any frame: generated output ends the // pre-content interval even while it is withheld. if recordsWithheldOutput, !generated.isEmpty { usageSignal.recordWithheldOutput() } - let stopped = answerStops?.ingest(generated) ?? generated - let text = finalHeaders?.ingest(stopped) ?? stopped + let released = answerStops?.ingest(generated) ?? generated + let text = finalHeaders?.ingest(released) ?? released if !text.isEmpty { do { let events = try router.process(text) @@ -2065,14 +2065,14 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { usageSignal: EngineV2RequestUsageSignal = EngineV2RequestUsageSignal(), answerStopFilter: FlintAnswerStopFilter? = nil, answerFormat: JSONAnswerFormat? = nil, - harmonyFinalHeaders: Bool = false + rewriteHarmonyFinalHeaders: Bool = false ) throws -> AsyncThrowingStream { try makeEventStream(upstream: upstream, cancelUpstream: cancelUpstream, toolHandler: toolHandler, prepared: prepared, releaseBox: releaseBox, usageSignal: usageSignal, reasoningPrefix: reasoningPrefix, nativeReasoningPrefix: nativeReasoningPrefix, recordsWithheldOutput: recordsWithheldOutput, answerStopFilter: answerStopFilter, answerFormat: answerFormat, - harmonyFinalHeaders: harmonyFinalHeaders) + rewriteHarmonyFinalHeaders: rewriteHarmonyFinalHeaders) } #endif diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift index 82b97d7123..1b54e9a3b9 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift @@ -5,14 +5,14 @@ import MLXLMServer /// Rewrites a GPT-OSS answer header that carries attributes, such as /// `<|channel|>final <|constrain|>json<|message|>`, to the plain /// `<|channel|>final<|message|>`. The Harmony reasoning parser routes only the -/// exact header `final` to content and drops every other message, so such an -/// answer reached the client as empty content. Other headers, and all text -/// outside headers, pass through byte for byte. +/// exact header `final` to content and drops every other message, so without +/// this filter such an answer reaches the client as empty content. Other +/// headers, and all text outside headers, pass through byte for byte. struct HarmonyFinalHeaderFilter: Sendable { - static let channelMarker = "<|channel|>" - static let messageMarker = "<|message|>" + private static let channelMarker = "<|channel|>" + private static let messageMarker = "<|message|>" /// A header is a few tokens; longer text after `<|channel|>` passes unchanged. - static let maximumHeaderBytes = 256 + private static let maximumHeaderBytes = 256 private var pending = "" private var inHeader = false @@ -30,14 +30,17 @@ struct HarmonyFinalHeaderFilter: Sendable { while true { if inHeader { guard let end = pending.range(of: Self.messageMarker) else { - if pending.utf8.count > Self.maximumHeaderBytes { + // Past the limit plus a partial `<|message|>`: whatever ends it, the header is too long. + if pending.utf8.count > Self.maximumHeaderBytes + Self.messageMarker.utf8.count { output += pending pending = "" inHeader = false } return output } - output += Self.answerHeader(String(pending[.. Self.maximumHeaderBytes ? header : Self.answerHeader(header)) + + Self.messageMarker pending = String(pending[end.upperBound...]) inHeader = false } else if let start = pending.range(of: Self.channelMarker) { @@ -60,20 +63,23 @@ struct HarmonyFinalHeaderFilter: Sendable { } /// `final` for an answer header with attributes; any other header as given. - /// A header with a recipient (`to=`) is a call, not an answer. - static func answerHeader(_ header: String) -> String { - let name = header.prefix { !$0.isWhitespace && $0 != "<" } - guard name == "final", header != "final", !header.contains("to=") else { return header } + /// A header with a recipient (`to=`) is a call, not an answer. Surrounding + /// whitespace alone is left as is: the parser trims it. + private static func answerHeader(_ header: String) -> String { + let name = header.drop { $0.isWhitespace }.prefix { !$0.isWhitespace && $0 != "<" } + guard name == "final", !header.contains("to="), + header.trimmingCharacters(in: .whitespaces) != "final" else { return header } return "final" } - /// Length of the longest suffix of `text` that is a proper prefix of `<|channel|>`. + /// Length of the longest suffix of `text` that is a proper prefix of + /// `<|channel|>`. The marker is ASCII, so its bytes and characters count alike. private static func markerPrefixLength(_ text: String) -> Int { let marker = Array(channelMarker.utf8) let bytes = Array(text.utf8.suffix(marker.count - 1)) for length in stride(from: bytes.count, through: 1, by: -1) where marker.starts(with: bytes.suffix(length)) { - return String(decoding: bytes.suffix(length), as: UTF8.self).count + return length } return 0 } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift index fc08554a6f..bedd745475 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift @@ -43,7 +43,7 @@ struct HarmonyFinalHeaderFilterTests { @Test("a bare content type or no space before the constraint is an answer too", arguments: widths) func otherAttributeSpellingsAreContent(width: Int) { - for header in ["final json", "final<|constrain|>json", "final <|constrain|>JSON "] { + for header in ["final json", "final<|constrain|>json", "final <|constrain|>JSON ", " final json"] { let output = Self.analysis + "<|channel|>\(header)<|message|>" + Self.answer #expect(Self.received(output, width: width).content == Self.answer, "\(header)") } @@ -57,6 +57,7 @@ struct HarmonyFinalHeaderFilterTests { "<|channel|>commentary<|message|>Checking the weather.<|end|>", "<|channel|>final to=functions.x<|message|>{}", "<|channel|>finalize<|message|>x", + "<|channel|> final <|message|>Plain answer.", "No markers <|chan at all, a < and |>.", "Unicode é 🙂 <|channel|>analysis<|message|>Ünïcode<|end|>", ] @@ -70,7 +71,7 @@ struct HarmonyFinalHeaderFilterTests { let unterminated = Self.analysis + "<|channel|>final <|constrain|>js" #expect(Self.filtered(unterminated, width: 3) == unterminated) let oversized = "<|channel|>final " + String(repeating: "a", count: 300) + "<|message|>{}" - #expect(Self.filtered(oversized, width: 7) == oversized) + for width in Self.widths { #expect(Self.filtered(oversized, width: width) == oversized, "width \(width)") } var partial = HarmonyFinalHeaderFilter() #expect(partial.ingest("text <|chan") == "text ") #expect(partial.finish() == "<|chan") @@ -108,7 +109,7 @@ struct HarmonyFinalHeaderFilterTests { let prepared = try ToolChoicePromptPolicy.prepare(request, modelType: "gpt_oss") let scheduler = MultiModelBatchSchedulerEngine(registryProvider: { [:] }) let events = try scheduler._testMakeEventStream(upstream: upstream, cancelUpstream: {}, prepared: prepared, - releaseBox: OneShotRelease(release: { _ in }, modelId: "fixture"), harmonyFinalHeaders: true) + releaseBox: OneShotRelease(release: { _ in }, modelId: "fixture"), rewriteHarmonyFinalHeaders: true) var parser = StreamingReasoningParser(format: .harmony) var content = "" var reasoning = "" From bb36b0d9ba8d3e6390d86c60d53fc1801dcf2966 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:14:55 -0800 Subject: [PATCH 5/6] fix(provider): the GPT-OSS answer-header filter rewrites only well-formed answer headers (review) From the independent review (APPROVE WITH NITS): - A final header that holds another control marker (a header cut short, then a new message) is left as it is: rewriting it could turn the next message, say an analysis, into content. Only <|constrain|> may appear. - A whitespace-padded plain final becomes the exact one: the non-stream Harmony parser compares the raw header, so such an answer was dropped on the local non-stream path. - Tests: the cut-short header passes unchanged, the padded header, and the 256/257-byte limit at every chunking. - Docs and changelog say well-formed output is byte-identical (the filter does not track message bodies), give the exact hold bound, and point at the SDK parser as the long-term home. The filter imports Foundation and its held-suffix comment is exact. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gptoss-final-header-attributes.md | 2 +- docs/architecture/inference.md | 12 +++++++++--- .../Streaming/HarmonyFinalHeaderFilter.swift | 15 ++++++++++----- .../Streaming/HarmonyFinalHeaderFilterTests.swift | 15 ++++++++++++++- 4 files changed, 34 insertions(+), 10 deletions(-) diff --git a/changelog.d/gptoss-final-header-attributes.md b/changelog.d/gptoss-final-header-attributes.md index f97fe04ac0..3186916e37 100644 --- a/changelog.d/gptoss-final-header-attributes.md +++ b/changelog.d/gptoss-final-header-attributes.md @@ -1,4 +1,4 @@ ### GPT-OSS answers under a `final` header with attributes reach the client - GPT-OSS can open its answer with Harmony header attributes, as in `<|channel|>final <|constrain|>json<|message|>`, typically for JSON answers. The provider's Harmony split kept only an exact `final` header, so such an answer was dropped and the client got empty `content`. It now arrives as `content`, as any other answer does. -- Nothing else in a GPT-OSS response changes: reasoning, tool calls, preambles and plain answers are byte-identical. +- Nothing else in a well-formed GPT-OSS response changes: reasoning, tool calls, preambles and plain answers are byte-identical. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 5a3811493c..18cede1639 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3306,10 +3306,16 @@ parser routes only the exact header `final` to content and drops every other message, so `MultiModelBatchSchedulerEngine.makeEventStream` first passes the raw output of a GPT-OSS request on the `harmony` parser through `HarmonyFinalHeaderFilter`. A `final` header that carries attributes and no -recipient becomes `<|channel|>final<|message|>`. Analysis, commentary and call -headers, and all text outside headers, pass byte for byte. The filter holds back -at most a partial `<|channel|>` marker or one header of up to 256 bytes +recipient becomes `<|channel|>final<|message|>`, as does a whitespace-padded +`final`; a `final` header holding another control marker is left as it is. +Analysis, commentary and call headers, and the text of well-formed Harmony +messages, pass byte for byte (the filter does not track message bodies, so a +body that literally spells a `final` header is read as one). It holds back at +most a partial `<|channel|>` marker, or a header of up to 256 bytes and a partial +`<|message|>` (`provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift`). +The SDK parser is the better long-term home for this rule; until it routes by +channel name, the filter does. Only qualified Nemotron Lightning listings absorb a stray `` already in content state, leaving preceding text as content and tool arguments opaque. diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift index 1b54e9a3b9..726d073fe0 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift @@ -1,5 +1,6 @@ // Copyright © 2026 Eigen Labs. +import Foundation import MLXLMServer /// Rewrites a GPT-OSS answer header that carries attributes, such as @@ -11,6 +12,7 @@ import MLXLMServer struct HarmonyFinalHeaderFilter: Sendable { private static let channelMarker = "<|channel|>" private static let messageMarker = "<|message|>" + private static let constrainMarker = "<|constrain|>" /// A header is a few tokens; longer text after `<|channel|>` passes unchanged. private static let maximumHeaderBytes = 256 @@ -62,18 +64,21 @@ struct HarmonyFinalHeaderFilter: Sendable { return pending } - /// `final` for an answer header with attributes; any other header as given. - /// A header with a recipient (`to=`) is a call, not an answer. Surrounding - /// whitespace alone is left as is: the parser trims it. + /// `final` for an answer header: its first word is `final`, it names no + /// recipient (`to=` is a call) and it holds no control marker but + /// `<|constrain|>` (another one means the header was cut short and a new + /// message began). Any other header as given. private static func answerHeader(_ header: String) -> String { let name = header.drop { $0.isWhitespace }.prefix { !$0.isWhitespace && $0 != "<" } guard name == "final", !header.contains("to="), - header.trimmingCharacters(in: .whitespaces) != "final" else { return header } + !header.replacingOccurrences(of: constrainMarker, with: "").contains("<|") else { return header } return "final" } /// Length of the longest suffix of `text` that is a proper prefix of - /// `<|channel|>`. The marker is ASCII, so its bytes and characters count alike. + /// `<|channel|>`, in bytes. The caller holds that many Characters: the + /// suffix is ASCII, so this is the same text, or one cluster more when a + /// prepended mark joins its first byte. Text is held, never split. private static func markerPrefixLength(_ text: String) -> Int { let marker = Array(channelMarker.utf8) let bytes = Array(text.utf8.suffix(marker.count - 1)) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift index bedd745475..a36ada9804 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift @@ -57,7 +57,7 @@ struct HarmonyFinalHeaderFilterTests { "<|channel|>commentary<|message|>Checking the weather.<|end|>", "<|channel|>final to=functions.x<|message|>{}", "<|channel|>finalize<|message|>x", - "<|channel|> final <|message|>Plain answer.", + "<|channel|>final<|end|><|start|>assistant<|channel|>analysis<|message|>Reasoning.<|end|>", "No markers <|chan at all, a < and |>.", "Unicode é 🙂 <|channel|>analysis<|message|>Ünïcode<|end|>", ] @@ -66,12 +66,25 @@ struct HarmonyFinalHeaderFilterTests { } } + @Test("a padded plain final header becomes the exact one, for the non-stream parser too", arguments: widths) + func paddedFinalHeaderIsExact(width: Int) { + #expect(Self.filtered("<|channel|> final <|message|>Plain answer.", width: width) + == "<|channel|>final<|message|>Plain answer.") + } + @Test("an unterminated or oversized header is passed on unchanged") func unfinishedHeadersPassThrough() { let unterminated = Self.analysis + "<|channel|>final <|constrain|>js" #expect(Self.filtered(unterminated, width: 3) == unterminated) let oversized = "<|channel|>final " + String(repeating: "a", count: 300) + "<|message|>{}" for width in Self.widths { #expect(Self.filtered(oversized, width: width) == oversized, "width \(width)") } + // The limit is 256 header bytes at every chunking. + let atLimit = "<|channel|>final " + String(repeating: "a", count: 250) + "<|message|>{}" + let overLimit = "<|channel|>final " + String(repeating: "a", count: 251) + "<|message|>{}" + for width in Self.widths { + #expect(Self.filtered(atLimit, width: width) == "<|channel|>final<|message|>{}", "width \(width)") + #expect(Self.filtered(overLimit, width: width) == overLimit, "width \(width)") + } var partial = HarmonyFinalHeaderFilter() #expect(partial.ingest("text <|chan") == "text ") #expect(partial.finish() == "<|chan") From 6a4d20f1e11d1ee134700c13671f518a48f1f2b2 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:22:23 -0800 Subject: [PATCH 6/6] test(provider): the header filter's non-stream parser case and exact hold bound (delta review) From the delta review (APPROVE WITH NITS): - The non-stream Harmony parser (ReasoningParser.parse) now gets the answer for an attribute header and a padded final, asserted directly. - The hold bound is exact: at most 256 header bytes and a partial <|message|> (266 bytes) are held; the 267th releases the text. The check is >= so code and docs agree; a per-ingest test pins it. - The type comment covers padded headers and untracked bodies; the docs say "a control marker other than <|constrain|>" and drop a design note. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 5 ++--- .../Streaming/HarmonyFinalHeaderFilter.swift | 19 ++++++++++--------- .../HarmonyFinalHeaderFilterTests.swift | 14 ++++++++++++++ 3 files changed, 26 insertions(+), 12 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 18cede1639..8015872817 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3307,15 +3307,14 @@ message, so `MultiModelBatchSchedulerEngine.makeEventStream` first passes the raw output of a GPT-OSS request on the `harmony` parser through `HarmonyFinalHeaderFilter`. A `final` header that carries attributes and no recipient becomes `<|channel|>final<|message|>`, as does a whitespace-padded -`final`; a `final` header holding another control marker is left as it is. +`final`; a `final` header holding a control marker other than `<|constrain|>` is +left as it is. Analysis, commentary and call headers, and the text of well-formed Harmony messages, pass byte for byte (the filter does not track message bodies, so a body that literally spells a `final` header is read as one). It holds back at most a partial `<|channel|>` marker, or a header of up to 256 bytes and a partial `<|message|>` (`provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift`). -The SDK parser is the better long-term home for this rule; until it routes by -channel name, the filter does. Only qualified Nemotron Lightning listings absorb a stray `` already in content state, leaving preceding text as content and tool arguments opaque. diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift index 726d073fe0..6fffa6cd99 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift @@ -4,11 +4,12 @@ import Foundation import MLXLMServer /// Rewrites a GPT-OSS answer header that carries attributes, such as -/// `<|channel|>final <|constrain|>json<|message|>`, to the plain -/// `<|channel|>final<|message|>`. The Harmony reasoning parser routes only the -/// exact header `final` to content and drops every other message, so without +/// `<|channel|>final <|constrain|>json<|message|>`, or whitespace, to the plain +/// `<|channel|>final<|message|>`. The Harmony reasoning parsers route only the +/// exact header `final` to content and drop every other message, so without /// this filter such an answer reaches the client as empty content. Other -/// headers, and all text outside headers, pass through byte for byte. +/// headers and the messages of well-formed Harmony output pass byte for byte; +/// message bodies are not tracked. struct HarmonyFinalHeaderFilter: Sendable { private static let channelMarker = "<|channel|>" private static let messageMarker = "<|message|>" @@ -33,7 +34,7 @@ struct HarmonyFinalHeaderFilter: Sendable { if inHeader { guard let end = pending.range(of: Self.messageMarker) else { // Past the limit plus a partial `<|message|>`: whatever ends it, the header is too long. - if pending.utf8.count > Self.maximumHeaderBytes + Self.messageMarker.utf8.count { + if pending.utf8.count >= Self.maximumHeaderBytes + Self.messageMarker.utf8.count { output += pending pending = "" inHeader = false @@ -65,7 +66,7 @@ struct HarmonyFinalHeaderFilter: Sendable { } /// `final` for an answer header: its first word is `final`, it names no - /// recipient (`to=` is a call) and it holds no control marker but + /// recipient (`to=` is a call) and it holds no control marker other than /// `<|constrain|>` (another one means the header was cut short and a new /// message began). Any other header as given. private static func answerHeader(_ header: String) -> String { @@ -76,9 +77,9 @@ struct HarmonyFinalHeaderFilter: Sendable { } /// Length of the longest suffix of `text` that is a proper prefix of - /// `<|channel|>`, in bytes. The caller holds that many Characters: the - /// suffix is ASCII, so this is the same text, or one cluster more when a - /// prepended mark joins its first byte. Text is held, never split. + /// `<|channel|>`, in bytes. The suffix is ASCII, so the caller holds as many + /// Characters; when a prepend mark joins its first one, that mark is held + /// with it. Text is held, never split. private static func markerPrefixLength(_ text: String) -> Int { let marker = Array(channelMarker.utf8) let bytes = Array(text.utf8.suffix(marker.count - 1)) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift index a36ada9804..34bb1fec7f 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift @@ -49,6 +49,15 @@ struct HarmonyFinalHeaderFilterTests { } } + @Test("the non-stream Harmony parser gets the answer too") + func nonStreamParserGetsTheAnswer() { + let parser = ReasoningParser(format: .harmony) + for header in ["final <|constrain|>json", "final json", " final "] { + let output = Self.analysis + "<|channel|>\(header)<|message|>" + Self.answer + #expect(parser.parse(Self.filtered(output, width: 4096)).content == Self.answer, "\(header)") + } + } + @Test("every other header and all other text pass through byte for byte", arguments: widths) func otherOutputIsUnchanged(width: Int) { let outputs = [ @@ -88,6 +97,11 @@ struct HarmonyFinalHeaderFilterTests { var partial = HarmonyFinalHeaderFilter() #expect(partial.ingest("text <|chan") == "text ") #expect(partial.finish() == "<|chan") + // At most 256 header bytes and a partial `<|message|>` (266 bytes) are held. + var held = HarmonyFinalHeaderFilter() + let longHeader = String(repeating: "a", count: 266) + #expect(held.ingest("<|channel|>" + longHeader) == "<|channel|>") + #expect(held.ingest("a") == longHeader + "a") } @Test("only a Harmony-parsed GPT-OSS stream is filtered")