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
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,23 @@ public enum MLXMemoryGuard {
) -> UInt64 {
if let explicit { return explicit }
if let raw = env["DARKBLOOM_MLX_MEMORY_RESERVE_GB"], let gb = Double(raw), gb >= 0, gb.isFinite {
return UInt64(min(gb * 1_073_741_824, Double(UInt64.max)))
// Saturate WITHOUT `UInt64(Double(UInt64.max))`: that round-trip rounds
// UInt64.max up to 2^64, which is outside UInt64, so `UInt64(...)` traps
// — a huge finite reserve override would crash the provider during
// configureOnce() at startup/model load. `uint64MaxAsDouble` is exactly
// 2^64; anything ≥ it saturates. Mirrors the VLM env clamps.
let scaled = gb * 1_073_741_824
return scaled >= uint64MaxAsDouble ? UInt64.max : UInt64(scaled)
}
return saturatingGiBToBytes(defaultReserveGB)
}

Comment thread
anupsv marked this conversation as resolved.
Resolved
/// `Double(UInt64.max)` rounded to the nearest representable Double — exactly
/// 2^64 (one more than `UInt64.max`). Used as the saturation threshold so a
/// `>= uint64MaxAsDouble` comparison catches every value that would trap on
/// `UInt64(_:)` conversion.
static let uint64MaxAsDouble = Double(UInt64.max)

private static func saturatingGiBToBytes(_ gib: UInt64) -> UInt64 {
let (bytes, overflow) = gib.multipliedReportingOverflow(by: 1_073_741_824)
return overflow ? UInt64.max : bytes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,19 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
// batched engine. For VLM models, serve them via the container's
// non-batched prepare/generate vision path.
if isVLM, let container, VLMRequestInference.hasMedia(request) {
// Decode + validate inline media SYNCHRONOUSLY, before returning the
// stream. A MediaError (oversized/malformed/non-`data:` payload) thrown
// here propagates through this `async throws` to the caller — so both
// the buffered (non-streaming) and the SSE (streaming) HTTP paths, and
// the coordinator WebSocket path, surface the correct 4xx instead of a
// 200 with a truncated/error stream body. (Deferring the decode into
// the generation task would let the HTTP layer commit a 200 first.)
do {
try await VLMRequestInference.validateMedia(request)
} catch {
await releaseBox.fire()
throw error
}
let vlmStream = VLMRequestInference.stream(
container: container, request: request, defaultMaxTokens: defaultMaxTokens)
return AsyncThrowingStream { continuation in
Expand Down
433 changes: 414 additions & 19 deletions provider-swift/Sources/ProviderCore/Inference/VLMRequestInference.swift

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ extension ProviderLoop {
.base64DecodeFailed,
.percentDecodeFailed,
.imageDecodeFailed,
.invalidURL:
.invalidURL,
.mediaTooLarge:
Comment thread
anupsv marked this conversation as resolved.
Resolved
return 400
case .videoWriteFailed:
return 500
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,20 @@ public struct CORSResponder<Inner: HTTPResponder>: HTTPResponder {
),
message: error.localizedDescription
)
} catch let error as VLMRequestInference.MediaError {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Surface VLM media errors before returning HTTP response

For the real local HTTP path, oversized/malformed inline media is not thrown by inner.respond: VLMRequestInference.stream returns an AsyncThrowingStream immediately and only calls buildUserInput inside the stream task, so the MediaError is produced while the response body is being iterated after the router has already returned its SSE Response. This catch therefore only fixes direct startup throws like the stub test, but /v1/chat/completions with an oversized data URI can still miss the intended 400/OpenAI envelope and instead produce a 200/truncated stream or framework body error. Move the media preflight to an async-throwing startup path before the response is returned, or wrap the body stream before headers are sent.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — you're right that the CORSResponder catch alone was insufficient for the streaming path. Fixed properly in 5070d29e.

The issue exactly as you described: on stream:true, the upstream router calls streamChatCompletionFrames + sseResponse and returns a 200 SSE Response immediately; the MediaError was only produced later inside VLMRequestInference.stream's generation task during body iteration (continuation.finish(throwing:)) — after headers were sent. So inner.respond never threw and my catch never saw it. (The non-streaming path was fine — collectChatOutput does for try await before returning, so it propagated synchronously.)

Fix: validate media up front. MultiModelBatchSchedulerEngine.streamChatCompletion now calls VLMRequestInference.validateMedia(request) and propagates its throw synchronously, before returning the stream. So the MediaError surfaces through the async throws chain on every path — buffered HTTP, SSE HTTP, and the coordinator WebSocket — and lands in the existing 4xx mappings.

validateMedia re-runs the same buildUserInput decode purely for its throwing side-effects (I couldn't thread the decoded UserInput across the stream-task boundary — it isn't Sendable, and prepare takes it consuming sending, so stream rebuilds it inside the task). The decode is bounded by the caps it enforces, so the up-front pass can't itself be a DoS. Kept the CORSResponder catch — it's now the correct landing point that turns the propagated throw into the OpenAI-shaped 400 on the local path.

Added validateMedia regressions (throws up front on oversize; passes within-cap). Affected Swift suites green.

// Local HTTP (`darkbloom start --local`) must give the same
// status contract as the coordinator WebSocket path: an
// oversized/malformed/non-`data:` inline-media payload is a client
// fault (400), not a provider 500. Without this catch a MediaError
// raised by the VLM media-cap path escapes as the framework's
// generic 500. Mapping reuses mapInferenceErrorToStatus (400 for
// every case except the provider-side videoWriteFailed → 500).
return Self.openAIErrorResponse(
status: HTTPResponse.Status(
code: Int(ProviderLoop.mapInferenceErrorToStatus(error))
),
message: error.localizedDescription
)
}
}

Expand Down
21 changes: 21 additions & 0 deletions provider-swift/Tests/ProviderCoreTests/MLXMemoryGuardTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,27 @@ private let gib = 1024 * 1024 * 1024
== MLXMemoryGuard.defaultReserveGB * 1_073_741_824)
}

@Test func mlxGuardReserveEnvClampsHugeValueInsteadOfTrapping() {
// A huge-but-finite GB override would, naively, do
// `UInt64(min(gb * 1GiB, Double(UInt64.max)))` — but `Double(UInt64.max)`
// rounds up to 2^64, which is outside UInt64, so `UInt64(...)` traps and
// crashes the provider in configureOnce() at startup. The fix saturates.
#expect(MLXMemoryGuard.resolvedReserveBytes(
explicit: nil, env: ["DARKBLOOM_MLX_MEMORY_RESERVE_GB": "1e308"]) == UInt64.max)
// A value whose ×1GiB lands exactly at the 2^64 boundary also saturates,
// not traps.
let boundaryGB = String(MLXMemoryGuard.uint64MaxAsDouble / 1_073_741_824)
#expect(MLXMemoryGuard.resolvedReserveBytes(
explicit: nil, env: ["DARKBLOOM_MLX_MEMORY_RESERVE_GB": boundaryGB]) == UInt64.max)
// A normal large-but-representable value still converts correctly.
#expect(MLXMemoryGuard.resolvedReserveBytes(
explicit: nil, env: ["DARKBLOOM_MLX_MEMORY_RESERVE_GB": "64"])
== UInt64(64) * 1_073_741_824)
// Zero is honored (operator's accepted DoS knob; must not trap or fall back).
#expect(MLXMemoryGuard.resolvedReserveBytes(
explicit: nil, env: ["DARKBLOOM_MLX_MEMORY_RESERVE_GB": "0"]) == 0)
}

@Test func mlxGuardConfigureOnceAppliesExactlyOnce() {
MLXMemoryGuard._resetForTest()
var applied: [MLXMemoryGuard.Limits] = []
Expand Down
48 changes: 48 additions & 0 deletions provider-swift/Tests/ProviderCoreTests/StandaloneServerTests.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import Hummingbird
import HummingbirdTesting
import Logging
import NIOEmbedded
import Testing
@testable import ProviderCore

Expand Down Expand Up @@ -212,6 +214,52 @@ import Testing
}
}

// MARK: - CORSResponder: VLM media-error mapping (local HTTP path)

/// Inner responder stub that always throws a fixed error, so we can drive
/// `CORSResponder.respond` directly and assert how it renders that error —
/// without standing up the whole engine/model stack.
private struct ThrowingResponder<E: Error>: HTTPResponder {
typealias Context = BasicRequestContext
let error: E
func respond(to request: Request, context: Context) async throws -> Response {
throw error
}
}

@Test func corsResponderMapsVLMMediaErrorTo400OnLocalPath() async throws {
// Regression: the coordinator WebSocket path maps VLMRequestInference.MediaError
// to a 400 (ProviderLoop.mapInferenceErrorToStatus), but the local HTTP path's
// CORSResponder previously caught only MultiModelBatchSchedulerEngineError /
// MLXOpenAIServiceError, so a MediaError from the VLM media-cap escaped as the
// framework's generic 500. CORSResponder now catches it too. Drive the
// responder directly with a stub that throws the oversize-media error.
let mediaErr = VLMRequestInference.MediaError.mediaTooLarge(
"image is 1600000000 px; per-image cap is 100000000 px")
let responder = CORSResponder(inner: ThrowingResponder(error: mediaErr))

let request = Request(
head: .init(method: .post, scheme: "http", authority: "localhost", path: "/v1/chat/completions"),
body: .init(buffer: ByteBuffer()))
let context = BasicRequestContext(
source: ApplicationRequestContextSource(
channel: EmbeddedChannel(),
logger: Logger(label: #function)))

let response = try await responder.respond(to: request, context: context)

#expect(response.status == .badRequest,
"oversized inline media on the local path must map to 400, not a generic 500")
#expect(response.headers[.accessControlAllowOrigin] == "*",
"CORS allow-origin must be set on the rendered error response")
// Client-fault video write IO failure stays a 500.
let writeFail = CORSResponder(
inner: ThrowingResponder(error: VLMRequestInference.MediaError.videoWriteFailed("disk full")))
let writeResp = try await writeFail.respond(to: request, context: context)
#expect(writeResp.status == .internalServerError,
"provider-side videoWriteFailed must stay a 500")
}

private func standaloneTestServer(models: [ModelInfo] = []) -> StandaloneServer {
StandaloneServer(
models: models
Expand Down
Loading
Loading