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
5 changes: 5 additions & 0 deletions changelog.d/video-decode-transient.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### A video whose decoder fails once is decoded again, not refused

- When the video reader of GLM 5.3, MiMo V2.6, Qwen4 or Nemotron Super fails on a video that passed its metadata checks, the provider decodes the video once more with a new reader over the same bytes. A valid video that met one reader failure is now served with the same frames. Before, GLM refused it as `invalid_media` (400), and the coordinator did not send it to another provider.
- When the reader fails again with a decoder, hardware or interruption fault, the provider refuses the request as a retryable 503, and the coordinator can send it to another provider. Any other second failure, such as a truncated video, is still the deterministic `invalid_media` (400). A Qwen4 video whose reader fails twice without such a fault is now `invalid_media` (400) too; before, every Qwen4 reader failure was a retryable 503.
- Each failed reader pass logs a WARN `engine_health` event `video_reader_failed` with the reader status and the domain and code of its errors. It carries no media or prompt content.
18 changes: 18 additions & 0 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -2925,6 +2925,22 @@ errors instead of wrapping them as a retryable 503 construction refusal.
`maxMediaDecodedBytes` 25 MiB, `maxVideoDurationSeconds` 600,
`maxImagesPerRequest` 16, `maxVideosPerRequest` 8,
`maxRequestVideoFramePixels` 384 Mpx; `decodeOverheadFactor = 4`.
- **A failed video reader decodes again once.** An `AVAssetReader` can fail on a
valid video. When a reader pass of the GLM 5.3, MiMo V2.6, Qwen4 or Nemotron
Super decoder ends in a state other than `.completed`, the decoder keeps the
reader status and the domain and code of its error chain (`VideoReaderFailure`)
and decodes again with a new reader over the same in-memory asset
(`VideoReaderRetry`; the Super frame reader replaces its reader once and
decodes from the first frame again). A second success gives the same frames.
A second failure with an AVFoundation or VideoToolbox decoder, hardware or
interruption code (`VideoReaderFailure.isTransient`) refuses as a retryable
503 (failure code `capacity`), so the coordinator can send the request to
another provider. Any other second failure is the media's `invalid_media`
400. Each failed pass emits a WARN `engine_health` event, operation
`video_reader_failed`, with `retrying`, `transient`, `reader_status` and
`reader_error` (codes only)
(`libs/mlx-swift-lm/Libraries/MLXLMCommon/VideoReaderFailure.swift`,
`provider-swift/Sources/ProviderCore/Inference/Vision/VideoReaderFailureReport.swift`).
- Vision requests never stage SSD blocks and get no deadline projection; VLM
slots require a backend that honors span masks. The current paged cache
satisfies that structural gate; supported vision serving still requires its
Expand Down Expand Up @@ -3713,6 +3729,8 @@ evidence, not a change to the normal final-row contract or the near-tie rule
| 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` |
| `video_reader_failed` WARN event, `retrying: true`, and the request served | A video reader pass failed and the second pass decoded the video; `reader_error` names the reader's error codes | `libs/mlx-swift-lm/Libraries/MLXLMCommon/VideoReaderFailure.swift` (`VideoReaderRetry`), `VideoReaderFailureReport.swift` |
| Video refused after two `video_reader_failed` events (503 `capacity` or 400 `invalid_media`) | Both reader passes failed: 503 for a transient decoder, hardware or interruption code, 400 otherwise | `EngineV2VisionPrefill.swift` (`clientFault(for:)`), `EngineV2GLM5NextMediaPrefill.swift` (`glm5NextInputError`), `MiMoV26EncodedMediaIngress.swift` (`outwardFailure`), `NemotronSuperLocalImageHTTP.swift` (`SuperHTTPErrors.map`) |
| `missingUserQuery` (400) | Qwen 3.5/3.6/3.8 or Bonsai 2 history with no user turn beyond `<tool_response>` wrappers | `provider-swift/Sources/ProviderCore/Inference/Prompting/Qwen35TemplateFixes.swift` (`validateUserQuery`) |
| `Inference failure: invalid request (<reason>)` in `darkbloom logs` (400) | The sealed request, its body decode or the model's native controls refused it before the inference task, or a prompt policy or engine admission refused it while its prompt was prepared; the reason is the closed [refusal line](../provider/cli-reference.md#refusal-lines) | `provider-swift/Sources/ProviderCore/Inference/Engine/InferenceRefusalReason.swift` (`InferenceRefusalReason`, `init(promptRefusal:)`); `provider-swift/Sources/ProviderCore/Inference/Prompting/ProviderPromptContractPipeline.swift` (`nativeControlsRefusal`) |
| Load refused: `pagedUnavailable` (503) | Explicit `engine_v2_kv_backend = paged` and the paged pool/kernels failed | `EngineV2Factory+BackendPreparation.swift` — see [`prefix-cache.md`](prefix-cache.md) |
Expand Down
1 change: 1 addition & 0 deletions docs/provider/direct-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ envelope, the same on one Mac and on a [two-Mac cluster](./two-mac-cluster.md):
| `response_format` `json_object`/`json_schema` whose answer stopped at `max_tokens` before it was complete (a reasoning model can spend the whole budget thinking) | HTTP `422`: `The output was cut off by max_tokens before the structured (response_format) answer was complete. Raise max_tokens or lower the reasoning effort, and retry.` Invalid JSON at a natural stop keeps its `422` with the closed internal-failure message. GLM-5.3-Flash validates its withheld JSON answer itself (`GLM5NextResponseFormat`) and answers a truncated one with that closed `422` | `libs/mlx-swift-lm/Libraries/MLXLMServer/Runtime/MLXOpenAIService.swift` (`MLXOpenAIServiceError.responseFormatCutOffByMaxTokens`); `provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift` (`CORSResponder`); `provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift` (`validatedContent`) |
| GLM-5.3-Flash with images or video and `response_format` `json_object`/`json_schema` or a required or named `tool_choice` | HTTP `400` `Invalid inference request.` (failure code `invalid_request`) before any media decode: only the text path withholds and validates such an answer or call. Hidden reasoning (`reasoning.exclude: true`, `include_reasoning: false`, `thinking.display: "omitted"`) is served with media too, its reasoning withheld | `provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift` (`prepareCompletion`); `provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift` (`withholdsOutput`, `withholdsReasoning`) |
| An image or video the model's processor refuses: for Qwen 3.5 and 3.8 a side below `patch_size × merge_size` (32 pixels) or an aspect ratio above 200:1, which it does not upscale; a video without a decodable track; more images or videos than the processor takes | HTTP `400` `Invalid media input.` (failure code `invalid_media`), before the vision tower or any native reservation, never the retryable `503` | `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionPrefill.swift` (`clientFault(for:)`) |
| A video whose reader fails on GLM 5.3, MiMo V2.6, Qwen4 or Nemotron Super after its metadata checks passed | The provider decodes the video once more with a new reader. If that succeeds, the request is served. If it fails again with a decoder, hardware or interruption code, HTTP `503` (failure code `capacity`), which a coordinator retries on another provider; any other second failure is HTTP `400` `Invalid media input.` (failure code `invalid_media`). Each failed pass logs a WARN `engine_health` event `video_reader_failed` with the reader status and error codes only | `libs/mlx-swift-lm/Libraries/MLXLMCommon/VideoReaderFailure.swift` (`VideoReaderRetry`); `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionPrefill.swift` (`clientFault(for:)`); `provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift` (`SuperHTTPErrors.map`) |

## Responses continuation and retention

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,15 @@ enum EngineV2Translation {
/// before submit and production engines always run the contiguous
/// backend, so these rejections indicate a provider-side gating bug and
/// double as its loud signal.
///
/// Media preparation also refuses with this marker
/// (`EngineV2VisionPrefill.clientFault(for:)`), but a video decode is not
/// deterministic by itself: the video reader can fail on a valid clip. So
/// a failed reader pass runs once more with a new reader (`VideoReaderRetry`)
/// before any refusal, and a reader that fails again with a transient
/// decoder or hardware fault (`VideoReaderFailure.isTransient`) refuses as
/// a retryable 503 (`.requestRejected`). Only a reader that fails twice
/// without one reaches this marker.
static let multimodalRejectedPrefix = "multimodal_rejected"

/// Canonical marker for a cluster pair's refusal of a request it can
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,11 @@ actor NemotronSuperLocalImageBinding {
let parsed = try Self.parseEncodedBody(body, modelID: owner.modelID)
guard parsed.request.logprobs != true || logprobs != nil else { throw Failure.unsupportedCapability }
if let video = parsed.video {
try await Self.executeEncodedVideo(video, body: body, templateBytes: templateBytes,
request: parsed.request, owner: owner, gate: gate, mediaID: mediaID, requestID: id,
cacheScope: cacheScope, logprobs: logprobs, onEvent: onEvent)
try await VideoReaderFailureReport.reporting(to: { TelemetryClient.shared.emit($0) }) {
try await Self.executeEncodedVideo(video, body: body, templateBytes: templateBytes,
request: parsed.request, owner: owner, gate: gate, mediaID: mediaID, requestID: id,
cacheScope: cacheScope, logprobs: logprobs, onEvent: onEvent)
}
return
}
let plan = try Self.encodedPlan(parsed.images, contextLength: gate.contextLength)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -357,9 +357,12 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
// first-token or request budget: those start when the queue lets go.
let origin = acquired.queueExitedAt.map { exited in distributedRequestOrigin.map { max($0, exited) } ?? exited }
?? distributedRequestOrigin
return try await prepareAcquiredCompletion(
request: request, templateControls: templateControls, requestUsage: requestUsage,
distributedRequestOrigin: origin, acquired: acquired)
// Preparation, on this task or the lease's child task, decodes media.
return try await VideoReaderFailureReport.reporting(to: (engineV2Vision ?? .production).emitTelemetry) {
try await prepareAcquiredCompletion(
request: request, templateControls: templateControls, requestUsage: requestUsage,
distributedRequestOrigin: origin, acquired: acquired)
}
}

/// Keep registry/acquisition snapshots out of the parent preparation frame.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ extension EngineV2VisionPrefill {
}

/// Serving media preparation for a loaded GLM root and its processor.
/// Deterministic input faults map to `unsupportedMedia` (HTTP 400); tower
/// and MLX faults keep the retriable refusal mapping.
/// Deterministic input faults map to `unsupportedMedia` (HTTP 400); tower,
/// MLX and transient video decoder faults keep the retriable refusal mapping.
static func prepareGLM5NextMedia(
container: ModelContainer, request: OpenAIChatCompletionRequest,
templateControls: ChatTemplateControls
Expand Down Expand Up @@ -102,10 +102,16 @@ extension EngineV2VisionPrefill {

/// Processor refusals are properties of the request (geometry, counts,
/// budgets), identical on every provider. Their details are code literals.
/// A video whose reader failed on both passes is the media's fault unless
/// the reader reported a transient decoder fault, which leaves as the
/// `VideoReaderFailure` itself: a retriable refusal another provider can serve.
static func glm5NextInputError(_ error: GLM5NextVisionError) -> Error {
switch error {
case .invalidInput(let detail), .budgetExceeded(let detail), .unsupported(let detail):
return EngineV2VisionPrefillError.unsupportedMedia("GLM media input: \(detail)")
case .videoReader(let failure):
return failure.isTransient
? failure : EngineV2VisionPrefillError.unsupportedMedia("GLM media input: video decoding failed")
case .invalidWeights, .weightsNotLoaded:
return error
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -873,7 +873,8 @@ public enum EngineV2VisionPrefill {
///
/// PRIVACY: the human-readable `error` field is emitted ONLY for our own
/// `EngineV2VisionPrefillError` (content-safe by construction — see the
/// enum doc). Foreign throws (processor/MLX/media errors) carry
/// enum doc) and for a `VideoReaderFailure` (reader status and error
/// domains and codes only). Other throws (processor/MLX/media errors) carry
/// `error_class` only: `MediaError.invalidURL`, for one, embeds up to
/// 200 chars of the request's URI. The same throw now comes directly from
/// this preparer's single decode pass, so filtering by class is the
Expand All @@ -896,8 +897,8 @@ public enum EngineV2VisionPrefill {
"media_kind": .string(mediaKind.rawValue),
"error_class": .string(String(reflecting: type(of: error))),
]
if let visionError = error as? EngineV2VisionPrefillError {
fields["error"] = .string(String(describing: visionError))
if let detail = contentSafeDescription(of: error) {
fields["error"] = .string(detail)
}
event.fields = fields
return event
Expand All @@ -907,10 +908,19 @@ public enum EngineV2VisionPrefill {
/// errors are content-safe by construction; foreign errors contribute
/// their type name only (same stance as `refusalTelemetryEvent`).
static func refusalDetail(for error: Error) -> String {
contentSafeDescription(of: error) ?? String(reflecting: type(of: error))
}

/// Our own errors and a video reader's status and error codes; nil for any
/// other error, whose description may carry request content.
private static func contentSafeDescription(of error: Error) -> String? {
if let visionError = error as? EngineV2VisionPrefillError {
return String(describing: visionError)
}
return String(reflecting: type(of: error))
if let readerFailure = error as? VideoReaderFailure {
return String(describing: readerFailure)
}
return nil
}

/// The 400 for a media preparation throw that is the request's own fault.
Expand All @@ -919,10 +929,15 @@ public enum EngineV2VisionPrefill {
/// deterministic prefill shapes, and the processor refusing the media
/// itself (a geometry its resize cannot use, such as Qwen's side below
/// `patch_size × merge_size` or aspect ratio over 200:1; a video without a
/// decodable track; a media count the processor does not take). nil for
/// decodable track; a video whose reader failed twice without a transient
/// decoder fault; a media count the processor does not take). nil for
/// any other throw, which the caller refuses as a construction failure.
/// Processor text carries media dimensions, so the messages are fixed.
static func clientFault(for error: Error) -> MultiModelBatchSchedulerEngineError? {
if let readerFailure = error as? VideoReaderFailure {
return readerFailure.isTransient
? nil : .multimodalRejected("multimodal_rejected: the video could not be decoded")
}
if let visionError = error as? EngineV2VisionPrefillError {
switch visionError {
case .noProcessedMedia:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,14 @@ enum MiMoV26EncodedMediaIngress {
"video audio requires contiguous mono24k LPCM16/Float32 without edits")
}
}
// Both reader passes failed: a transient decoder fault can pass on another
// provider; any other failure is the media's.
if let failure = error as? VideoReaderFailure {
return failure.isTransient
? MultiModelBatchSchedulerEngineError.requestRejected(
"native media video decoder fault (\(failure)); retry on another provider")
: refusal()
}
if let failure = error as? MiMoV26EncodedVisualDecoder.Failure {
switch failure {
case .limit,.arithmeticOverflow:
Expand Down
Loading
Loading