Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changelog.d/qwen38-reasoning-effort-400.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### Qwen3.8 unsupported reasoning effort is a client error

Qwen3.8-27B requests with thinking enabled and an effort its template does not
accept, such as `high` or `minimal`, now fail before rendering with the typed
HTTP 400 that Flash-Next already returns. Text requests previously surfaced as
a provider 500 `template_render` failure; media requests hit the same raise
inside vision preparation and were reported as a retryable 503
`capacity_busy`. Typed request errors from media preparation now keep their
own status.
12 changes: 12 additions & 0 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1115,6 +1115,17 @@ and the coordinator can refuse to route
(`provider-swift/Sources/ProviderCoreFoundation/TemplateRenderCheck.swift`,
`provider-swift/Sources/ProviderCore/Coordinator/CapacityQuoteEngine.swift`).

A template `raise_exception` at request time is classified `jinja_template`
and returned as HTTP 500, the provider-fault class, so a caller control that
a template is known to reject must be validated before rendering. The
Flash-Next and Qwen3.8-27B templates accept only `low`, `medium` and `xhigh`
while thinking is enabled; any other active effort, such as OpenAI's `high`
or `minimal`, is a typed HTTP 400 `client_error` and never reaches Jinja, on
text and media requests alike
(`provider-swift/Sources/ProviderCore/Inference/Qwen4SupportPolicy.swift`,
`validateReasoningContext`). Media preparation rethrows such typed request
errors instead of wrapping them as a retryable 503 construction refusal.

### Vision constraints

- **One image per tower pass.** `EngineV2VisionTowerRun` drives the Qwen
Expand Down Expand Up @@ -1503,6 +1514,7 @@ or change consumer/OpenRouter routing.
| `PreContentDeadlineFailure.deadlineUnreachable` | First-content budget spent before submit or during prefill projection | `CoordinatorClientTypes.swift`, `EngineV2Bridge+Submission.swift`, `EngineV2Bridge+Admission.swift` |
| Request cancelled by lease | No admission/prefill/decode progress within 120 s, or a step over 30 s | `EngineLoopV2.swift` |
| `advertisedContextExceeded` (400) | Candidate prompt plus resolved output reservation is invalid, overflowing or above its context limit | `provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift` (`submitTokenized`); `provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift` (`sanitizedInferenceFailure`) |
| `unsupportedReasoningEffort` (400) | Active effort outside `low`/`medium`/`xhigh` on a restricted-effort template (Flash-Next, Qwen3.8-27B) | `provider-swift/Sources/ProviderCore/Inference/Qwen4SupportPolicy.swift` (`validateReasoningContext`) |
| Model dropped from advertised set | Unsupported `model_type` | `EngineV2SupportedModels.swift` |
| Model advertised, capacity quotes rejected with reason `template` | Scan-time render check failed (`template_render_ok = false`) | `TemplateRenderCheck.swift`, `provider-swift/Sources/ProviderCore/Coordinator/CapacityQuoteEngine.swift` (`reject(.template)`) |
| Image rejected | Over `MediaIngest` caps or over the N² tower budget | `MediaIngest.swift`, `VisionTowerBudget.swift` |
Expand Down
8 changes: 5 additions & 3 deletions docs/reference/qwen4-next-support.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Qwen 3.8 Next (Flash-Next) native support reference

> Last updated: 2026-10-09
> Last updated: 2026-10-20

Reference for the native Qwen4 support candidate and its remaining qualification gates. These source defaults do not publish a model, approve a catalog entry, qualify a hardware tier or establish a production release. The composed SDK's `libs/mlx-swift-lm/docs/qwen4/composition.md` records source selection and excluded experiments.

Expand Down Expand Up @@ -76,8 +76,10 @@ does not model `reasoning.enabled`; do not substitute that extension for its
supported OFF form. Existing Chat Boolean precedence is preserved.
Unsupported active efforts such as `high` or `minimal` are rejected before
template rendering with a typed HTTP 400, not coerced to another effort.
Disabled thinking retains its existing precedence. Other artifact templates
are unaffected. Source: `provider-swift/Sources/ProviderCore/Inference/Qwen4SupportPolicy.swift`
Disabled thinking retains its existing precedence. Every concrete
Qwen3.8-27B build (`ModelRuntimeRequirements.qwen38ConcreteModelIDs`) ships a
template with the same effort raise, so it shares this boundary; other
artifact templates are unaffected. Source: `provider-swift/Sources/ProviderCore/Inference/Qwen4SupportPolicy.swift`
(`validateReasoningContext`) and `provider-swift/Sources/ProviderCore/Inference/Prompting/ProviderPromptContractPipeline.swift`
(`tokenize`). Hosted OpenRouter routing, adapter control mappings, exclusion,
reasoning-token budgets and opaque reasoning-history extensions require
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
if let failure = error as? PreContentDeadlineFailure { throw failure }
if error is CancellationError { throw CancellationError() }
if let mediaError = error as? MediaIngest.MediaError { throw mediaError }
if let engineError = error as? MultiModelBatchSchedulerEngineError { throw engineError }
if let visionError = error as? EngineV2VisionPrefillError {
switch visionError {
case .noProcessedMedia:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@ public enum MultiModelBatchSchedulerEngineError: Error, LocalizedError, Equatabl
/// histories do not trip model-specific Jinja assertions as provider
/// 500s.
case invalidToolPayload(String)
/// The owned native Flash-Next template does not support the resolved
/// thinking effort. Deterministic request error, before template rendering.
/// The owned native Flash-Next or Qwen3.8-27B template does not support
/// the resolved thinking effort. Deterministic request error, before
/// template rendering.
case unsupportedReasoningEffort
/// Native binary-thinking model received an unknown effort alias.
case unsupportedNativeReasoningEffort
Expand Down Expand Up @@ -110,7 +111,7 @@ public enum MultiModelBatchSchedulerEngineError: Error, LocalizedError, Equatabl
case .invalidToolPayload(let message):
return message
case .unsupportedReasoningEffort:
return "Qwen3.8-Flash-Next supports reasoning effort low, medium, or xhigh when thinking is enabled"
return "This model supports reasoning effort low, medium, or xhigh when thinking is enabled"
case .unsupportedNativeReasoningEffort:
return "DiffusionGemma supports binary reasoning: none/off/0 or minimal/low/medium/high/xhigh"
case .toolChoiceViolation(let message):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,16 @@ enum Qwen4SupportPolicy {

/// Validate this owned artifact's template contract after the existing
/// boolean/effort precedence has resolved. Other Qwen4 artifacts may ship
/// different templates, so architecture identity alone is insufficient.
/// different templates, so architecture identity alone is insufficient;
/// the concrete Qwen3.8-27B builds ship the same effort contract.
/// Never coerce an unsupported effort or change disabled-thinking behavior.
static func validateReasoningContext(
modelID: String,
modelType: String?,
additionalContext: [String: any Sendable]?
) throws {
guard isOwnedModelID(modelID), isQwen4ModelType(modelType),
guard (isOwnedModelID(modelID) && isQwen4ModelType(modelType))
|| ModelRuntimeRequirements.qwen38ConcreteModelIDs.contains(modelID),
additionalContext?["enable_thinking"] as? Bool != false,
let effort = additionalContext?["reasoning_effort"] as? String
else { return }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,10 +280,8 @@ public enum MediaIngest {
tools, context: .init(modelId: request.model, modelType: modelType))
let additionalContext = MultiModelBatchSchedulerEngine.templateAdditionalContext(
for: request, controls: templateControls, modelType: modelType, hasMedia: true)
if preserveTemplateFields {
try Qwen4SupportPolicy.validateReasoningContext(
modelID: request.model, modelType: modelType, additionalContext: additionalContext)
}
try Qwen4SupportPolicy.validateReasoningContext(
modelID: request.model, modelType: modelType, additionalContext: additionalContext)
var chatMessages: [Chat.Message] = []
let retainToolMedia = preserveTemplateFields && modelType == "diffusion_gemma"
var totalPixels = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1129,6 +1129,20 @@ struct EngineV2VisionRoutingTests {
#expect(outstanding == 0)
}

@Test("typed client errors from preparation keep their 400, not a retryable 503")
func typedClientErrorKeepsItsMapping() async throws {
let engine = VisionScriptedEngine(script: .stream([]))
let plumbing = EngineV2VisionPlumbing(
prepare: { _, _, _ in throw MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort },
emitTelemetry: VisionTelemetrySink().callback())
let router = makeRoutingEngine(
container: makeStubContainer(), bridge: makeBridge(engine: engine), plumbing: plumbing)
await #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort) {
_ = try await collectContent(try await router.streamChatCompletion(request: imageRequest()))
}
#expect(engine.submitted.isEmpty)
}

@Test("construction failure REFUSES loudly: ERROR telemetry + 503, no legacy fallback",
arguments: [false, true])
func constructionFailureRefusesLoudly(typedVisionFailure: Bool) async throws {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,15 @@ struct NativeMediaToolPreparationTests {
#expect(result["name"] as? String == "viewer")
}

@Test func nativeMediaRejectsUnsupportedEffortBeforeDecodingPixels() async throws {
/// Qwen3.8-27B media requests run without preserved template fields or a
/// native model type, exactly as `EngineV2VisionPrefill` builds them.
@Test(arguments: [("DarkBloom/Qwen3.8-Flash-Next-Q4-mtp", true, "qwen4_exp"),
("EigenLabs/Qwen3.8-27B-4bit-mtp", false, nil)] as [(String, Bool, String?)])
func nativeMediaRejectsUnsupportedEffortBeforeDecodingPixels(
model: String, preserveTemplateFields: Bool, modelType: String?
) async throws {
let body = #"""
{"model":"DarkBloom/Qwen3.8-Flash-Next-Q4-mtp",
{"model":"\#(model)",
"reasoning":{"enabled":true,"effort":"high"},
"messages":[{"role":"user","content":[
{"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}},
Expand All @@ -84,7 +90,7 @@ struct NativeMediaToolPreparationTests {
OpenAIChatCompletionRequest.self, from: Data(body.utf8))
do {
_ = try await MediaIngest.buildUserInput(
from: decoded, preserveTemplateFields: true, modelType: "qwen4_exp")
from: decoded, preserveTemplateFields: preserveTemplateFields, modelType: modelType)
Issue.record("unsupported native effort unexpectedly reached pixel decoding")
} catch MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort {
// The invalid image must not be decoded before the control error.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import MLXLMServer
import Testing
@testable import ProviderCore

@Suite("Owned Flash-Next reasoning effort request validation")
@Suite("Restricted-effort template request validation")
struct Qwen4ReasoningEffortValidationTests {
private let owned = Qwen4SupportPolicy.ownedModelID

Expand Down Expand Up @@ -74,6 +74,7 @@ struct Qwen4ReasoningEffortValidationTests {
let combinations: [(String, String?)] = [
("another-qwen4", "qwen4_exp"), (owned + "-alias", "qwen4_exp_text"),
(owned, "qwen3_5"), (owned, nil),
("Qwen3.5-9B", "qwen3_5"), ("eigenlabs/qwen3.8-27b-4bit-mtp", "qwen3_5"),
]
for (modelID, modelType) in combinations {
try Qwen4SupportPolicy.validateReasoningContext(modelID: modelID, modelType: modelType,
Expand Down Expand Up @@ -114,10 +115,30 @@ struct Qwen4ReasoningEffortValidationTests {
#expect(!String(decoding: wire, as: UTF8.self).contains("jinja"))
}

@Test(arguments: ModelRuntimeRequirements.qwen38ConcreteModelIDs.sorted())
func qwen38BuildsShareTheRestrictedEffortContract(model: String) throws {
let hi: [OpenAIChatMessage] = [.init(role: .user, content: .text("hi"))]
for effort: String? in [nil, "low", "medium", "xhigh"] {
_ = try tokenize(.init(model: model, messages: hi, reasoning: .init(enabled: true, effort: effort)),
controls: .init(), tokenizer: ReasoningContextTokenizer(), modelType: "qwen3_5")
}
// Raw-body `reasoning_effort`, the shape OpenRouter traffic arrives in.
for effort in ["high", "minimal"] {
let tokenizer = ReasoningContextTokenizer()
#expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort) {
try tokenize(.init(model: model, messages: hi), controls: .init(reasoningEffort: effort),
tokenizer: tokenizer, modelType: "qwen3_5")
}
#expect(tokenizer.calls == 0)
}
_ = try tokenize(.init(model: model, messages: hi), controls: .init(reasoningEffort: "high", enableThinking: false),
tokenizer: ReasoningContextTokenizer(), modelType: "qwen3_5")
}

private func tokenize(_ request: OpenAIChatCompletionRequest, controls: ChatTemplateControls,
tokenizer: ReasoningContextTokenizer) throws -> [Int] {
tokenizer: ReasoningContextTokenizer, modelType: String = "qwen4_exp") throws -> [Int] {
try ProviderPromptContractPipeline.tokenize(prepared: ToolChoicePromptPolicy.prepare(request),
request: request, tokenizer: tokenizer, modelType: "qwen4_exp", templateControls: controls)
request: request, tokenizer: tokenizer, modelType: modelType, templateControls: controls)
}
}

Expand Down
Loading