diff --git a/changelog.d/video-decode-transient.md b/changelog.d/video-decode-transient.md new file mode 100644 index 0000000000..0d7e404f86 --- /dev/null +++ b/changelog.d/video-decode-transient.md @@ -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. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 4773725ca5..ab443e697d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -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 @@ -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 `` wrappers | `provider-swift/Sources/ProviderCore/Inference/Prompting/Qwen35TemplateFixes.swift` (`validateUserQuery`) | | `Inference failure: invalid request ()` 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) | diff --git a/docs/provider/direct-mode.md b/docs/provider/direct-mode.md index e23d2e56ef..aa06da80c9 100644 --- a/docs/provider/direct-mode.md +++ b/docs/provider/direct-mode.md @@ -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 diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 62b29ecd96..2e499695c0 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 62b29ecd9600ca0070671b94a782319094e66c88 +Subproject commit 2e499695c08e4df402f64dcb0d6ec7ac0102e601 diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Translation.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Translation.swift index d9883d0b18..b1e5de3134 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Translation.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Translation.swift @@ -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 diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalImageBinding.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalImageBinding.swift index b96e8b3562..2b9ce23574 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalImageBinding.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalImageBinding.swift @@ -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) diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index e1e4b213b8..6f7cb96665 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -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. diff --git a/provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2GLM5NextMediaPrefill.swift b/provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2GLM5NextMediaPrefill.swift index 31b7fa7242..2cfad5b2e6 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2GLM5NextMediaPrefill.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2GLM5NextMediaPrefill.swift @@ -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 @@ -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 } diff --git a/provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionPrefill.swift b/provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionPrefill.swift index fb1d24418f..f7fff07958 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionPrefill.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionPrefill.swift @@ -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 @@ -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 @@ -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. @@ -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: diff --git a/provider-swift/Sources/ProviderCore/Inference/Vision/MiMo/MiMoV26EncodedMediaIngress.swift b/provider-swift/Sources/ProviderCore/Inference/Vision/MiMo/MiMoV26EncodedMediaIngress.swift index 15a67adb66..e1c9f09b56 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Vision/MiMo/MiMoV26EncodedMediaIngress.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Vision/MiMo/MiMoV26EncodedMediaIngress.swift @@ -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: diff --git a/provider-swift/Sources/ProviderCore/Inference/Vision/NemotronSuperVideoDecode.swift b/provider-swift/Sources/ProviderCore/Inference/Vision/NemotronSuperVideoDecode.swift index 09b093bbe1..4dab947b90 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Vision/NemotronSuperVideoDecode.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Vision/NemotronSuperVideoDecode.swift @@ -4,6 +4,7 @@ import CoreMedia import CoreVideo import Foundation +import MLXLMCommon import MLXVLM /// Inline MP4/QuickTime input of the Super video binding, sampled as NVIDIA's @@ -154,7 +155,9 @@ enum NemotronSuperVideoDecode { let (pixels, overflow) = coded.width.multipliedReportingOverflow(by: coded.height) guard !overflow, pixels <= pixelCap else { throw Failure.limit } let rotation = try Rotation(try await track.load(.preferredTransform)) - let timing = try await sampleTiming(movie, track: track, source: asset) + let timing = try await VideoReaderRetry.run { + try await sampleTiming(movie, track: track, source: asset) + } let indices = try NemotronSuperVideoPreprocessing.sampledFrameIndices( totalFrames: timing.frames, sourceFPS: timing.fps) let width = rotation.swapsAxes ? coded.height : coded.width @@ -175,11 +178,14 @@ enum NemotronSuperVideoDecode { } /// AVFoundation errors may describe the media; they leave as `invalidVideo`. + /// A `VideoReaderFailure` holds the reader's status and error codes only. fileprivate static func reading(_ body: () async throws -> Result) async throws -> Result { do { return try await body() } catch let error as Failure { throw error + } catch let error as VideoReaderFailure { + throw error } catch let error as NemotronSuperVideoPreprocessing.Failure { throw error } catch let error as NemotronSuperImagePreprocessing.Failure { @@ -198,6 +204,21 @@ enum NemotronSuperVideoDecode { return track } + /// A started BGRA reader of `track`; AVFoundation's refusal leaves as `invalidVideo`. + fileprivate static func decodedReader(_ movie: AVAsset, track: AVAssetTrack) throws + -> (AVAssetReader, AVAssetReaderOutput) { + let reader: AVAssetReader + do { reader = try AVAssetReader(asset: movie) } catch { throw Failure.invalidVideo } + let output = AVAssetReaderTrackOutput(track: track, outputSettings: [ + kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA, + ]) + output.alwaysCopiesSampleData = false + guard reader.canAdd(output) else { throw Failure.invalidVideo } + reader.add(output) + guard reader.startReading() else { throw Failure.invalidVideo } + return (reader, output) + } + /// The stream metadata vLLM's OpenCV loader reads from FFmpeg: the sample /// count, and the rate as that count over the summed sample durations /// (`avg_frame_rate`). One division of the exact rational keeps an @@ -240,7 +261,8 @@ enum NemotronSuperVideoDecode { } // Cancellation stops the reader early; it is not a malformed movie. try Task.checkCancellation() - guard samples.completed, frames > 0, duration.value > 0, duration.timescale > 0 else { + if let failure = samples.failure { throw failure } + guard frames > 0, duration.value > 0, duration.timescale > 0 else { throw Failure.invalidVideo } let fps = Double(frames) * Double(duration.timescale) / Double(duration.value) @@ -292,23 +314,15 @@ enum NemotronSuperVideoDecode { /// `NemotronSuperVideoDecode.decodeAllowance`. init(_ plan: Plan, decodeAllowance: Duration? = nil) async throws { let movie = plan.asset.retainedAsset - let (reader, output) = try await NemotronSuperVideoDecode.reading { - () async throws -> (AVAssetReader, AVAssetReaderTrackOutput) in - let track = try await NemotronSuperVideoDecode.videoTrack(movie) - let reader = try AVAssetReader(asset: movie) - let output = AVAssetReaderTrackOutput(track: track, outputSettings: [ - kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA, - ]) - output.alwaysCopiesSampleData = false - guard reader.canAdd(output) else { throw Failure.invalidVideo } - reader.add(output) - guard reader.startReading() else { throw Failure.invalidVideo } - return (reader, output) + let track = try await NemotronSuperVideoDecode.reading { + try await NemotronSuperVideoDecode.videoTrack(movie) } + let (reader, output) = try NemotronSuperVideoDecode.decodedReader(movie, track: track) self.plan = plan self.reader = SerialReader(reader, output: output, source: plan.asset, allowance: decodeAllowance ?? NemotronSuperVideoDecode.decodeAllowance(frames: plan.decodedFrames, - codedPixels: plan.codedPixels)) + codedPixels: plan.codedPixels), + reopen: { try NemotronSuperVideoDecode.decodedReader(movie, track: track) }) } /// Runs `body`, which pulls frames, with a pull waiting on the @@ -335,7 +349,15 @@ enum NemotronSuperVideoDecode { while true { try Task.checkCancellation() let frame = try autoreleasepool { () throws -> [Float]? in - guard let sample = reader.nextSample() else { throw reader.earlyEnd } + guard let sample = reader.nextSample() else { + // A failed reader is replaced once; frames before the + // next sampled one decode again and are dropped. + guard try reader.reopenAfterFailure() else { throw reader.earlyEnd } + index = 0 + markers = 0 + lastPresentation = nil + return nil + } let count = CMSampleBufferGetNumSamples(sample) guard count > 0 else { markers += 1 @@ -417,14 +439,20 @@ private final class SerialReader: @unchecked Sendable { var sample: CMSampleBuffer? } - private let reader: AVAssetReader - private let output: AVAssetReaderOutput + /// Read, cancelled and replaced only on `queue`. + private var reader: AVAssetReader + private var output: AVAssetReaderOutput + /// Opens a new reader of the same track, for `reopenAfterFailure()`. + private let reopen: (() throws -> (AVAssetReader, AVAssetReaderOutput))? + /// The pulling thread's: whether the reader was already replaced. + private var reopened = false /// The in-memory asset the reader loads through; its resource loader /// holds the delegate serving the bytes only weakly. private let source: NemotronSuperVideoAsset private let queue = DispatchQueue(label: "ai.darkbloom.super-video.reader", qos: .userInitiated, autoreleaseFrequency: .workItem) private let cancelledForTesting: (@Sendable (AVAssetReader) -> Void)? + private let beforeReadForTesting: (@Sendable (AVAssetReader) -> Void)? private let lock = NSLock() /// Nanoseconds of decoder wait left; nil without an allowance. private var remaining: UInt64? @@ -437,11 +465,14 @@ private final class SerialReader: @unchecked Sendable { private var expired = false init(_ reader: AVAssetReader, output: AVAssetReaderOutput, source: NemotronSuperVideoAsset, - allowance: Duration? = nil) { + allowance: Duration? = nil, reopen: (() throws -> (AVAssetReader, AVAssetReaderOutput))? = nil) { self.reader = reader self.output = output + self.reopen = reopen self.source = source cancelledForTesting = NemotronSuperVideoDecode.readerCancelledForTesting + // The reads run on `queue`, so the task's hook is read here. + beforeReadForTesting = VideoReaderRetry.beforeReadForTesting remaining = allowance.map(Self.nanoseconds) } @@ -513,6 +544,7 @@ private final class SerialReader: @unchecked Sendable { } guard let deadline else { return nil } queue.async { [self] in + beforeReadForTesting?(reader) let sample = autoreleasepool { output.copyNextSampleBuffer() } let delivered = lock.withLock { () -> Bool in guard !read.abandoned else { return false } @@ -534,12 +566,43 @@ private final class SerialReader: @unchecked Sendable { } } - /// Whether the reader read to its end, asked on its queue. - var completed: Bool { queue.sync { reader.status == .completed } } + /// How the reader failed, asked on its queue; nil once it read to its end. + var failure: VideoReaderFailure? { + queue.sync { reader.status == .completed ? nil : VideoReaderFailure(reader: reader) } + } + + /// After `nextSample()` returned nil early: when the reader failed on its + /// own, rather than being stopped, replaces it once with a new reader of + /// the same asset and returns true, and the caller reads from the first + /// frame again. A reader that fails after its replacement throws its + /// `VideoReaderFailure`. Each failure goes to `VideoReaderRetry`'s observer. + func reopenAfterFailure() throws -> Bool { + guard !Task.isCancelled, !lock.withLock({ stopped }), let failure else { return false } + guard let reopen, !reopened else { + VideoReaderRetry.report(failure, retrying: false) + throw failure + } + VideoReaderRetry.report(failure, retrying: true) + reopened = true + let (next, nextOutput) = try reopen() + queue.sync { + // A stop already queued cancels the failed reader; the new one never starts serving. + guard !lock.withLock({ stopped }) else { + next.cancelReading() + cancelledForTesting?(next) + return + } + reader.cancelReading() + cancelledForTesting?(reader) + reader = next + output = nextOutput + } + return true + } /// Why the reader returned no sample before the plan's last frame: the - /// task was cancelled, the allowance ran out, or the reader failed or - /// lost frames. + /// task was cancelled, the allowance ran out, or the reader ended early + /// without failing (a failed reader is `reopenAfterFailure()`'s). var earlyEnd: any Error { if Task.isCancelled { return CancellationError() } return lock.withLock { expired } diff --git a/provider-swift/Sources/ProviderCore/Inference/Vision/VideoReaderFailureReport.swift b/provider-swift/Sources/ProviderCore/Inference/Vision/VideoReaderFailureReport.swift new file mode 100644 index 0000000000..e1029277f9 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Vision/VideoReaderFailureReport.swift @@ -0,0 +1,42 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon + +/// Reports each failed `AVAssetReader` pass of a media decode (MLX-Swift-LM's +/// `VideoReaderRetry`, and the Super video reader) as one WARN `engine_health` +/// event and one provider log line. Both carry the reader status and the +/// domain and code of its errors only, never media bytes, frames or prompt +/// content. +enum VideoReaderFailureReport { + private static let logger = ProviderLogger( + subsystem: BuildEnvironment.current.serviceLogSubsystem, category: "video-reader") + + static func event(_ failure: VideoReaderFailure, retrying: Bool) -> TelemetryEvent { + TelemetryEvent( + source: .provider, severity: .warn, kind: .engineHealth, + message: retrying + ? "video reader pass failed; decoding again with a new reader" + : "video reader pass failed again; the video is refused" + ).withFields([ + "component": .string("engine"), + "operation": .string("video_reader_failed"), + "retrying": .bool(retrying), + "transient": .bool(failure.isTransient), + "reader_status": .int(failure.status), + "reader_error": .string(failure.description), + ]) + } + + /// Runs `operation` with every failed reader pass in it reported to `emit`. + static func reporting( + to emit: @escaping @Sendable (TelemetryEvent) -> Void, + isolation: isolated (any Actor)? = #isolation, + _ operation: () async throws -> Result + ) async rethrows -> Result { + try await VideoReaderRetry.$failedPassObserver.withValue({ failure, retrying in + logger.warning("video reader pass failed (retrying: \(retrying)): \(failure)") + emit(event(failure, retrying: retrying)) + }, operation: operation) + } +} diff --git a/provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift b/provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift index c3ff38307e..2a8d3fdfd2 100644 --- a/provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift +++ b/provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift @@ -237,7 +237,12 @@ enum SuperHTTPErrors { return MultiModelBatchSchedulerEngineError.generationFailed("native output handling failed") } } - if error is NemotronSuperVideoDecode.Failure || error is NemotronSuperVideoPreprocessing.Failure { + if let failure = error as? VideoReaderFailure, failure.isTransient { + return MultiModelBatchSchedulerEngineError.requestRejected( + "inline video decoder fault (\(failure)); retry on another provider") + } + if error is VideoReaderFailure || error is NemotronSuperVideoDecode.Failure + || error is NemotronSuperVideoPreprocessing.Failure { return MultiModelBatchSchedulerEngineError.multimodalRejected("unsupported or invalid inline video request") } if error is DecodingError || error is NemotronSuperImageDecode.Failure diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Vision/GLM5NextMediaRoutingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Vision/GLM5NextMediaRoutingTests.swift index 23d43b14a3..c824d21ce2 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Vision/GLM5NextMediaRoutingTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Vision/GLM5NextMediaRoutingTests.swift @@ -5,6 +5,7 @@ // preparer. No model weights. The native builder itself is exercised by // `GLM5NextManagedLoadTests` on synthetic GLM weights. +@preconcurrency import AVFoundation import CryptoKit import Foundation import MLX @@ -228,6 +229,94 @@ private func preparedSubmission() -> EngineV2VisionPrefill.PreparedSubmission { positionState: nil, mediaKind: .image) } +/// The scheduler's telemetry, for the reader-failure reports. Disarms `fault` +/// when a reader pass fails and a second pass follows, so that pass reads every byte. +private final class TelemetryCapture: @unchecked Sendable { + private let lock = NSLock() + private let fault: VideoDataRequestFault? + private var recorded: [TelemetryEvent] = [] + + init(disarming fault: VideoDataRequestFault? = nil) { self.fault = fault } + + func record(_ event: TelemetryEvent) { + lock.withLock { recorded.append(event) } + if event.fields?["operation"]?.value as? String == "video_reader_failed", + event.fields?["retrying"]?.value as? Bool == true { + fault?.disarm() + } + } + + private func events(_ operation: String) -> [[String: AnyCodableValue]] { + lock.withLock { recorded }.compactMap(\.fields).filter { + $0["operation"]?.value as? String == operation + } + } + + /// Each failed reader pass: whether a second pass followed, and the reader's codes. + var readerFailures: [(retrying: Bool, error: String)] { + events("video_reader_failed").map { + ($0["retrying"]?.value as? Bool ?? false, $0["reader_error"]?.value as? String ?? "") + } + } + + var refusalErrors: [String] { + events("engine_v2_vision_refusal").map { $0["error"]?.value as? String ?? "" } + } +} + +/// Grid rows and placement span lengths of the MP4 readiness clip. +private let readinessMP4Prepared = [[5, 52, 92], Array(repeating: 52 * 92 / 4, count: 5)] + +/// The MP4 readiness clip through the scheduler with GLM's request +/// normalization and processor, its in-memory asset created under `fault`. +private func readinessMP4(under fault: VideoDataRequestFault, telemetry: TelemetryCapture) + async throws -> (submitted: Int, prepared: [[Int]], failure: InferenceFailure?) +{ + let mp4 = try openRouterVideo( + "input-video-url.mp4", sha256: "dc11648bd3546cd0a37ecc1077ccc426d42c409fe4822ece0354eb250804431e") + let engine = GLMScriptedEngine() + let bridge = EngineV2Bridge( + engine: engine, modelId: "test/glm-stub", tokenizer: TokenizerHandle(GLMStubTokenizer()), + eosTokenIds: [2], kvBytesPerToken: 0) + let prepared = PreparedCapture() + let plumbing = EngineV2VisionPlumbing( + prepare: { _, request, controls in + let input = try await EngineV2VisionPrefill.glm5NextUserInput(request: request, controls: controls) + let processor = try GLM5NextProcessor(configuration: .init(), tokenizer: GLMMediaMarkerTokenizer()) + do { + let output = try await processor.prepareDetailed(input: input) + prepared.record( + (output.input.video?.frames ?? []).map { [$0.t, $0.h, $0.w] } + + [output.placements.map(\.tokenRange.count)]) + } catch let error as GLM5NextVisionError { + throw EngineV2VisionPrefill.glm5NextInputError(error) + } + return preparedSubmission() + }, emitTelemetry: { telemetry.record($0) }) + let request = imageRequest([ + .text("What's in this video?"), .videoURL("data:video/mp4;base64," + mp4.base64EncodedString()), + ]) + let failure = await VideoDataRequestFault.$current.withValue(fault) { () async -> InferenceFailure? in + do { + for try await _ in try await router(bridge: bridge, plumbing: plumbing) + .streamChatCompletion(request: request) {} + return nil + } catch { + return ProviderLoop.sanitizedInferenceFailure(from: error, phase: .streamStart) + } + } + return (engine.submitted.count, prepared.values, failure) +} + +/// The clip keeps `moov` after `mdat`, so its middle byte is sample data that +/// only a full reader pass requests. AVFoundation requests a failed range again, +/// so a reader pass fails only while the fault stays armed. +private func midMP4Fault(error: any Error & Sendable) throws -> VideoDataRequestFault { + let mp4 = try openRouterVideo( + "input-video-url.mp4", sha256: "dc11648bd3546cd0a37ecc1077ccc426d42c409fe4822ece0354eb250804431e") + return VideoDataRequestFault(offset: mp4.count / 2, error: error) +} + @Suite("GLM5Next media routing") struct GLM5NextMediaRoutingTests { @Test func imageReachesTheEngineAsCausalPositionFreeSpansFromTheOriginalRequest() async throws { @@ -374,9 +463,11 @@ struct GLM5NextMediaRoutingTests { } } - /// The readiness requests through the scheduler with GLM's actual request - /// normalization, shared ingest and processor at the published budgets. - /// The variable-frame-rate QuickTime clip was refused as `invalid_media`. + /// OpenRouter's two readiness videos through the scheduler with GLM's actual + /// request normalization, shared ingest and processor at the published + /// budgets: `input-video-base64.mov` (QuickTime, variable frame rate), once + /// refused as `invalid_media`, and `input-video-url.mp4` (MP4, constant + /// 24 fps), whose video reader once failed in CI (Layr-Labs/d-inference#1847). @Test func openRouterReadinessVideosReachTheEngineInsteadOfInvalidMedia() async throws { let mov = try openRouterVideo( "input-video-base64.mov", @@ -428,6 +519,53 @@ struct GLM5NextMediaRoutingTests { } } + /// Data requests fail partway through the MP4 until the first reader pass + /// fails: a second pass decodes the same frames, and the provider reports + /// the first pass with the reader's codes. + @Test func aReaderPassThatFailsPartwayThroughTheMP4IsDecodedAgain() async throws { + let fault = try midMP4Fault(error: MemoryBackedVideoAssetError.invalidRange) + let telemetry = TelemetryCapture(disarming: fault) + let run = try await readinessMP4(under: fault, telemetry: telemetry) + #expect(run.failure == nil, "\(String(describing: run.failure))") + #expect(run.submitted == 1) + #expect(run.prepared == readinessMP4Prepared) + #expect(fault.injected >= 1) + let failures = telemetry.readerFailures + #expect(failures.map { $0.retrying } == [true]) + #expect(failures.allSatisfy { $0.error.hasPrefix("video reader status 3: ") && !$0.error.hasSuffix("no error") }, + "\(failures)") + } + + /// A resource that ends partway (the loader refuses every range past it) is + /// the media's fault on both passes: the deterministic `invalid_media` 400. + @Test func aVideoTruncatedForBothPassesStaysInvalidMedia() async throws { + let fault = try midMP4Fault(error: MemoryBackedVideoAssetError.invalidRange) + let telemetry = TelemetryCapture() + let run = try await readinessMP4(under: fault, telemetry: telemetry) + #expect(run.submitted == 0) + #expect(run.failure?.code == .invalidMedia && run.failure?.statusCode == 400, + "\(String(describing: run.failure))") + #expect(telemetry.readerFailures.map { $0.retrying } == [true, false]) + #expect(telemetry.refusalErrors.isEmpty) + } + + /// An unavailable decoder on both passes is the machine's fault: a + /// retryable 503 that the coordinator sends to another provider. + @Test func aTransientDecoderFaultOnBothPassesIsARetryableRefusal() async throws { + let decoderUnavailable = NSError( + domain: AVFoundationErrorDomain, code: AVError.Code.decoderTemporarilyUnavailable.rawValue) + let fault = try midMP4Fault(error: decoderUnavailable) + let telemetry = TelemetryCapture() + let run = try await readinessMP4(under: fault, telemetry: telemetry) + #expect(run.submitted == 0) + #expect(run.failure?.code == .capacity && run.failure?.statusCode == 503, + "\(String(describing: run.failure)); \(telemetry.readerFailures)") + #expect(telemetry.readerFailures.map { $0.retrying } == [true, false]) + #expect(telemetry.refusalErrors.count == 1 + && telemetry.refusalErrors.allSatisfy { $0.contains("AVFoundationErrorDomain -11839") }, + "\(telemetry.refusalErrors)") + } + @Test func processorRefusalsAreDeterministicClientFaults() { for error in [ GLM5NextVisionError.invalidInput("media count does not match rendered prompt"), diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Vision/NemotronSuperVideoReaderRetryTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Vision/NemotronSuperVideoReaderRetryTests.swift new file mode 100644 index 0000000000..04269bdd5f --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Vision/NemotronSuperVideoReaderRetryTests.swift @@ -0,0 +1,136 @@ +// Copyright © 2026 Eigen Labs. + +@preconcurrency import AVFoundation +import CryptoKit +import Foundation +import MLXLMCommon +import Testing + +@testable import ProviderCore + +/// Every failed reader pass, in order. +private final class FailedPasses: @unchecked Sendable { + private let lock = NSLock() + private var recorded: [VideoReaderFailure] = [] + private var retries: [Bool] = [] + var retrying: [Bool] { lock.withLock { retries } } + var failures: [VideoReaderFailure] { lock.withLock { recorded } } + var observer: VideoReaderRetry.Observer { + { [self] failure, retrying in + lock.withLock { + recorded.append(failure) + retries.append(retrying) + } + } + } +} + +/// Cancels the readers in `ending` (1 is the first reader the task opens) +/// before their read number `read`, on the reader's queue between two reads, +/// as the reader's own stop does. Each then ends `.cancelled` without having +/// been stopped, as a reader that fails partway ends `.failed`. +private final class ReaderEnder: @unchecked Sendable { + private let lock = NSLock() + private let ending: Set + private let read: Int + private var order: [ObjectIdentifier: (ordinal: Int, reads: Int)] = [:] + private var endedCount = 0 + + init(ending: Set, atRead read: Int) { + self.ending = ending + self.read = read + } + + var ended: Int { lock.withLock { endedCount } } + + var hook: @Sendable (AVAssetReader) -> Void { + { [self] reader in + let end = lock.withLock { () -> Bool in + let id = ObjectIdentifier(reader) + var entry = order[id] ?? (ordinal: order.count + 1, reads: 0) + entry.reads += 1 + order[id] = entry + guard entry.reads == read, ending.contains(entry.ordinal) else { return false } + endedCount += 1 + return true + } + if end { reader.cancelReading() } + } + } +} + +/// The Super video reader over OpenRouter's MP4 readiness clip, with a reader +/// ended partway through `VideoReaderRetry`'s read hook: the timing pass, or +/// the frame reader that `Frames` replaces once. +struct NemotronSuperVideoReaderRetryTests { + private typealias Decode = NemotronSuperVideoDecode + + private static func clip() throws -> Data { + var root = URL(fileURLWithPath: #filePath) + for _ in 0..<6 { root.deleteLastPathComponent() } + let data = try Data(contentsOf: root.appendingPathComponent( + "libs/mlx-swift-lm/Tests/MLXLMTests/Resources/MiMoOpenRouter/input-video-url.mp4")) + #expect(SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + == "dc11648bd3546cd0a37ecc1077ccc426d42c409fe4822ece0354eb250804431e") + return data + } + + private static func inspect(_ data: Data) async throws -> Decode.Plan { + try await Decode.inspect(NemotronSuperVideoClips.uri(data)) + } + + private static func frames(_ plan: Decode.Plan) async throws -> [[Float]] { + let frames = try await Decode.Frames(plan) + return try await frames.withCancellableReader { + var all: [[Float]] = [] + while let frame = try frames.next() { all.append(frame) } + return all + } + } + + private static func ending(_ ender: ReaderEnder, observing passes: FailedPasses, + _ body: () async throws -> Result) async throws -> Result { + try await VideoReaderRetry.$failedPassObserver.withValue(passes.observer) { + try await VideoReaderRetry.$beforeReadForTesting.withValue(ender.hook, operation: body) + } + } + + @Test func aFailedTimingPassIsReadAgainWithTheSamePlan() async throws { + let data = try Self.clip() + let baseline = try await Self.inspect(data) + let ender = ReaderEnder(ending: [1], atRead: 40) + let passes = FailedPasses() + let plan = try await Self.ending(ender, observing: passes) { try await Self.inspect(data) } + #expect(ender.ended == 1) + #expect(passes.retrying == [true]) + #expect(passes.failures.map(\.status) == [AVAssetReader.Status.cancelled.rawValue]) + #expect(plan.sourceFrames == baseline.sourceFrames && plan.sourceFPS == baseline.sourceFPS) + #expect(plan.frameIndices == baseline.frameIndices && plan.labels == baseline.labels) + } + + /// The frame reader ends partway: a new reader decodes from the first + /// frame again and the sampled frames match an unfaulted decode. + @Test func aFailedFrameReaderIsReplacedOnceWithTheSameFrames() async throws { + let plan = try await Self.inspect(try Self.clip()) + let baseline = try await Self.frames(plan) + let ender = ReaderEnder(ending: [1], atRead: 40) + let passes = FailedPasses() + let frames = try await Self.ending(ender, observing: passes) { try await Self.frames(plan) } + #expect(ender.ended == 1) + #expect(passes.retrying == [true]) + #expect(passes.failures.map(\.status) == [AVAssetReader.Status.cancelled.rawValue]) + #expect(frames == baseline) + } + + @Test func aFrameReaderThatFailsAgainThrowsItsFailure() async throws { + let plan = try await Self.inspect(try Self.clip()) + let ender = ReaderEnder(ending: [1, 2], atRead: 40) + let passes = FailedPasses() + await #expect(throws: VideoReaderFailure.self) { + try await Self.ending(ender, observing: passes) { try await Self.frames(plan) } + } + #expect(ender.ended == 2) + #expect(passes.retrying == [true, false]) + #expect(passes.failures.allSatisfy { !$0.isTransient }) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Vision/VideoReaderFailureMappingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Vision/VideoReaderFailureMappingTests.swift new file mode 100644 index 0000000000..ad9da67501 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Vision/VideoReaderFailureMappingTests.swift @@ -0,0 +1,84 @@ +// Copyright © 2026 Eigen Labs. + +@preconcurrency import AVFoundation +import Foundation +import MLXLMCommon +import MLXVLM +import Testing + +@testable import ProviderCore + +/// Every refusal path classifies a video whose reader failed on both passes the +/// same way: a transient decoder fault is a retryable 503 (`capacity`), any +/// other reader failure is the media's 400 (`invalid_media`). +struct VideoReaderFailureMappingTests { + private let transient = VideoReaderFailure( + status: AVAssetReader.Status.failed.rawValue, + error: NSError(domain: AVFoundationErrorDomain, code: AVError.Code.decoderTemporarilyUnavailable.rawValue)) + private let media = VideoReaderFailure( + status: AVAssetReader.Status.failed.rawValue, + error: NSError(domain: AVFoundationErrorDomain, code: AVError.Code.decodeFailed.rawValue)) + + private func wire(_ error: Error) -> (InferenceFailureCode, UInt16) { + let failure = ProviderLoop.sanitizedInferenceFailure(from: error, phase: .streamStart) + return (failure.code, failure.statusCode) + } + + private func isRetryable(_ error: Error) -> Bool { + guard case .requestRejected(let message)? = error as? MultiModelBatchSchedulerEngineError else { return false } + return message.contains(transient.description) && wire(error) == (.capacity, 503) + } + + @Test func glmKeepsItsRefusalTextAndLetsTransientFaultsThrough() throws { + let refusal = EngineV2VisionPrefill.glm5NextInputError(.videoReader(media)) + guard case .unsupportedMedia(let detail)? = refusal as? EngineV2VisionPrefillError else { + Issue.record("a media reader failure is not a client fault: \(refusal)") + return + } + #expect(detail == "GLM media input: video decoding failed") + let clientFault = try #require(EngineV2VisionPrefill.clientFault(for: refusal)) + #expect(wire(clientFault) == (.invalidMedia, 400)) + let passedOn = EngineV2VisionPrefill.glm5NextInputError(.videoReader(transient)) + #expect(passedOn as? VideoReaderFailure == transient) + #expect(EngineV2VisionPrefill.clientFault(for: passedOn) == nil) + } + + /// Qwen4, and GLM's transient case, reach the shared media funnel as the + /// failure itself. A transient fault becomes the retryable construction + /// refusal, whose telemetry and message carry the reader's codes. + @Test func sharedMediaFunnel() throws { + let clientFault = try #require(EngineV2VisionPrefill.clientFault(for: media)) + #expect(clientFault == .multimodalRejected("multimodal_rejected: the video could not be decoded")) + #expect(wire(clientFault) == (.invalidMedia, 400)) + #expect(EngineV2VisionPrefill.clientFault(for: transient) == nil) + let event = EngineV2VisionPrefill.refusalTelemetryEvent(modelId: "m", mediaKind: .video, error: transient) + #expect(event.fields?["error"]?.value as? String == transient.description) + #expect(EngineV2VisionPrefill.refusalDetail(for: transient) == transient.description) + } + + @Test func mimoAndSuperFunnels() { + let mimo = MiMoV26EncodedMediaIngress.outwardFailure(media) + #expect(mimo as? MultiModelBatchSchedulerEngineError + == .multimodalRejected("native media input is unsupported or exceeds its bound")) + #expect(wire(mimo) == (.invalidMedia, 400)) + #expect(isRetryable(MiMoV26EncodedMediaIngress.outwardFailure(transient))) + + let superVideo = SuperHTTPErrors.map(media, media: true) + #expect(superVideo as? MultiModelBatchSchedulerEngineError + == .multimodalRejected("unsupported or invalid inline video request")) + #expect(wire(superVideo) == (.invalidMedia, 400)) + #expect(isRetryable(SuperHTTPErrors.map(transient, media: true))) + } + + @Test func reportCarriesTheReaderStatusAndCodesOnly() { + let event = VideoReaderFailureReport.event(transient, retrying: true) + #expect(event.severity == .warn && event.kind == .engineHealth) + let fields = event.fields ?? [:] + #expect(fields["operation"]?.value as? String == "video_reader_failed") + #expect(fields["retrying"]?.value as? Bool == true) + #expect(fields["transient"]?.value as? Bool == true) + #expect(fields["reader_status"]?.value as? Int == AVAssetReader.Status.failed.rawValue) + #expect(fields["reader_error"]?.value as? String == "video reader status 3: AVFoundationErrorDomain -11839") + #expect(VideoReaderFailureReport.event(media, retrying: false).fields?["transient"]?.value as? Bool == false) + } +}