Repository navigation
fix(provider): cap VLM inline-media decode (decompression-bomb OOM) - #335
Conversation
Office Macs were OOM-crashing invisibly: the runtime KV admission was OS-memory-blind (counted only MLX's own memory against TOTAL physical RAM, ignoring everything else on a shared Mac), MLX had no memory ceiling (default is 1.5x working set, above physical RAM), and a jetsam SIGKILL leaves no in-process trace so the kills never reached telemetry. Provider OOM fix: - GlobalKVCacheBudget + tokenBudgetMax now clamp free RAM to min(physical - MLX.active - MLX.cache - reserve, SystemMemory.availableBytes()) — the same clamp the load gate already uses. Stops over-admission on shared boxes. - MLXMemoryGuard pins Memory.memoryLimit/cacheLimit below physical RAM once at load, so overshoot throttles instead of racing into a kernel kill. - MemoryPressureMonitor (DISPATCH_SOURCE_MEMORYPRESSURE): reclaim MLX cache on warning; on critical also drop an OOM marker + emit telemetry. OOM detection / observability: - New TelemetryKind=oom mirrored in Swift/Go/TS. - OOMDetector: on launch, consume any pre-death marker and scrape kernel JetsamEvent/EXC_RESOURCE crash reports for our process; emit oom telemetry. - Coordinator classifies abrupt read_error disconnects against the last heartbeat's memory pressure + in-flight count (ClassifyDisconnectReason); emits provider_oom_suspected_total + an oom telemetry event. - Telemetry field allowlists (Swift + Go) extended for the non-sensitive memory fields. Tests: GlobalKVCacheBudget OS-clamp, MLXMemoryGuard sizing/idempotency, OOMDetector parsers/marker/scan, memory-pressure policy, disconnect classifier. All provider + coordinator suites green.
Tighten/prune the comments added in the previous commit — keep the non-obvious why (OS-blind vs OS-aware admission, MLX's above-RAM default ceiling, jetsam SIGKILL invisibility), drop narration and redundancy. No code changes; builds + tests green.
Two valid findings from automated review: - Extract the pure .ips crash-report parsers + JSON helpers out of OOMDetector.swift into OOMDetector+CrashReports.swift (separates parsing from marker I/O + directory scanning; API unchanged, no test changes). - Replace GlobalKVCacheBudget's 4-tuple memory-snapshot closure with a named MemorySnapshot struct for readability. Behavior-preserving; 36 affected tests green. Other review findings declined (see PR discussion): hot-path/blocking-IO flags are per-request not per-step and caching would make the OOM guard stale; classifier is not duplicated.
Codex (chatgpt-codex-connector) found real logic bugs; fixed the valid ones: - MLX ceiling was set too late: ensureModelLoaded loads weights (first big allocation) before BatchScheduler.loadModel ran configureOnce. Now pinned in ProviderLoop.startMemoryProtection (before any load) and StandaloneServer.init; loadModel keeps it as a backstop. - Jetsam false-positive: a JetsamEvent lists the whole process table, so matching any 'darkbloom' entry flagged an OOM even when another process was killed. Now require a kill signal (per-entry reason or largestProcess) on our entry. - Wrong scan path: kernel JetsamEvent reports land in /Library/Logs/ DiagnosticReports (system), not just ~/Library. Scan both + their Retired dirs. - Double-count: marker + crash report both emitted for one death. detectOnLaunch now prefers the crash report and only surfaces the marker when none exists. - Survived marker: a critical-pressure event the provider survives left a marker that the next clean restart misreported as OOM. Cleared on graceful exit. - Watermark advanced before telemetry handoff; moved after the emit loop. - Coordinator: a drained going-away close could be flagged oom_suspected. Now require in-flight > 0 (graceful shutdown drains first; idle kills are caught by the crash-log scrape). New tests: jetsam kill-evidence requirement, detectOnLaunch marker/crash dedup. 39 affected Swift tests + coordinator suite green. Declined ethenotethan's findings (hot-path/blocking-IO are per-request, classifier not duplicated).
The VLM path decodes inline data: image/video before any KV/token/load admission. decodeImage -> CIImage(data:) eagerly rasterizes (W*H*4) with no size/dimension cap, and PNG has no scaled-decode, so a tiny highly-compressed bomb (a uniform 40000x40000 PNG, ~5 MB on the wire, under the 32 MiB WS frame cap) explodes on decode. Measured on an M5 Max: the real resample-to-448 provider path peaks at 1.78 GB for a 16000^2 input and 5.73 GB at 32000^2 — a single request OOM-kills a provider with a model already resident. This is the proactive complement to feat/oom-protection's reactive OOMDetector/MemoryPressureMonitor: reject the bomb from the image header, before the raster is ever allocated (CGImageSourceCopyPropertiesAtIndex is O(header): ~0 GB RSS even for a gigapixel input). - Per-image pixel cap (DARKBLOOM_MAX_IMAGE_MEGAPIXELS, default 100) - Request-wide aggregate cap (DARKBLOOM_MAX_REQUEST_IMAGE_MEGAPIXELS, default 384) bounds the pack-many-images amplification - Per-part decoded-byte cap (DARKBLOOM_MAX_MEDIA_MIB, default 25); also bounds the inline-video temp file + RAM - New MediaError.mediaTooLarge -> HTTP 400 (client fault) - docs/spikes/vlm-oom: the repro + watchdog harness + on-hardware measurements - Regression suite covers each cap, the header reader, and the defaults
Codex (gpt-5.5 xhigh) + an independent reviewer reviewed the image-cap commit. Both PASSed the core fix; this addresses their findings: - HIGH (codex): decodeVideo had no per-frame/duration cap — a <=25 MiB video still expands into multi-GB of frames. decodeVideo is now async and probes AVURLAsset track naturalSize + duration (no frame decode), rejecting mediaTooLarge before the model rasterizes. Per-frame reuses maxImagePixels; duration via DARKBLOOM_MAX_VIDEO_SECONDS (default 600). Rippled parts/buildUserInput/stream to async. - LOW (reviewer): closed the imagePixelCount-nil fallthrough with a post-decode extent backstop, so a format ImageIO can't size but CIImage can rasterize still can't carry an oversized raster downstream. - LOW (reviewer): aggregate pixel charge is now overflow-safe (shared safeExtentPixels helper), matching imagePixelCount. - LOW (codex): base64 byte preflight subtracts '=' padding so the cap boundary is exact (was conservative by up to 2 bytes). - Tests: percent-encoded byte cap, video byte cap, video frame reject/pass (real 64x64 mp4 fixture), real 200x150 image. 36 VLM tests pass on an M5 Max.
Final codex (gpt-5.5 xhigh) pass flagged the video guard still failed OPEN: it checked only the first track, suppressed metadata-read errors with try? (accepting a video whose size/duration couldn't be proven), treated non-finite duration as acceptable, and charged naturalSize (presentation) rather than the coded frame dimensions the decoder actually allocates. enforceVideoLimits now fails CLOSED: it rejects unless the duration AND every video track's coded frame dimensions (CMVideoFormatDescriptionGetDimensions, max of natural/coded) are readable and within cap. The model samples frames from these same properties via AVAssetImageGenerator (verified in mlx-swift-lm), so a video it can actually use is always probeable here — fail-closed never rejects a usable video, but a crafted/unprobeable one is refused (the 25 MiB byte cap does not bound decoded frame pixels or sampled frame count). Adds a fail-closed regression test (unprobeable bytes -> mediaTooLarge). 37 VLM tests pass on an M5 Max.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Found 1 test failure on Blacksmith runners: Failure
|
Second PR-335 review (codex gpt-5.5 xhigh) found two more issues: - HIGH: video limits were per-part only. The model (Gemma4 etc.) samples up to ~32 frames PER video, so many tiny valid MP4s in one request each pass the per-video checks but the aggregate frame/tensor work still explodes. Added request-wide video caps threaded through parts/buildUserInput (the video analog of the image aggregate): max video parts (DARKBLOOM_MAX_VIDEOS_PER_REQUEST, default 8) + summed per-frame pixels across videos (DARKBLOOM_MAX_REQUEST_VIDEO_FRAME_MEGAPIXELS, default 384). decodeVideo now returns its frame-pixel count so the caller can charge the request budget. - MEDIUM: percent-encoded data: URIs were capped only after full decode/alloc. Added a preflight (decoded length = len - 2*'%'count, exact for valid input) that rejects before allocating, mirroring the base64 path. Post-decode check kept as a backstop. Adds request-wide video count + frame-pixel regression tests. 39 VLM tests pass on an M5 Max.
|
@codex review this |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7893941763
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…ro to a test Addresses review feedback on the VLM inline-media decode cap: - Charge the request-image aggregate from the HEADER pixel count BEFORE CIImage(data:) decodes. Previously an over-aggregate request decoded the current image (the very allocation the cap guards against, with prior images still retained) before the 400. Split decodeImageData out of decodeImage so parts() reads the header, charges the aggregate, and only then allocates the raster; a nil-header image folds its realized extent into the aggregate. - resolveMaxPixels: clamp a huge megapixel env value to Int.max without Int(Double(Int.max)) — that round-trip rounds to 2^63 > Int.max and traps, so one bad DARKBLOOM_MAX_*_MEGAPIXELS crashed the provider at static init. - resolveMaxBytes: saturate the MiB->bytes multiply (multipliedReportingOverflow) instead of trapping on a large-but-parseable DARKBLOOM_MAX_MEDIA_MIB. - enforceVideoLimits: format the over-duration rejection via secondsString (no Int(Double)) so untrusted metadata declaring a duration > Int.max seconds returns a 400 instead of trapping while building the message. Replace the docs/spikes/vlm-oom manual repro (make_bomb.py / oom_probe.swift / run_guarded.sh / RUNBOOK.md) with VLMDecodeBombTests: an in-process streaming-zlib PNG bomb generator (tiny on-wire, huge declared raster) plus regressions proving the guard rejects from the header before the raster is allocated, accepts the same bomb under a higher cap, and rejects an over-aggregate bomb pre-decode. The on-hardware measurement table is preserved in the test file header. Adds env-clamp and secondsString regressions. swift test (VLM suites): 46/46 green.
|
@codex review this This commit (
Please confirm the aggregate is now charged pre-decode on every image path, and the env-clamp / duration-format edges no longer trap. |
|
This PR hardens the VLM media-decode path against provider-side DoS and decode-bomb attacks, and fixes a crash-on-startup integer conversion bug; no mitigations are weakened. Trust Boundaries Touched
Threat AssessmentT-007 (Provider serves manipulated model outputs / inference engine integrity) — ℹ️ Neutral on the weight-hash front, but the VLM decode path now validates media up-front before committing a streaming response. T-028 (Residual inference data in GPU memory) — ℹ️ Neutral. This PR doesn't add Metal buffer zeroing; the open finding remains. T-002 (Unbounded request body / OOM) — ✅ Strengthens an analogous control at the provider layer (not the coordinator). The new T-029 / T-016 (Resource exhaustion at provider) — ✅ Strengthens. The New Attack Surface / Observations
SEC-* Findings ResolvedNone explicitly resolved. The SummaryThe crash fix in 🔐 Threat model: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ed8e339369
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
DARKBLOOM_MLX_MEMORY_RESERVE_GB set to a huge finite value did 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/model load. Same Double->integer boundary-trap class as the VLM env clamps; saturate via a 2^64 threshold (uint64MaxAsDouble) so a value >= it returns UInt64.max instead of converting. Adds mlxGuardReserveEnvClampsHugeValueInsteadOfTrapping (huge/boundary saturate, normal value converts, 0 honored). swift test (MLXMemoryGuard + VLM): 52/52.
|
Thanks — triaged the two new-attack-surface items. Both concern OOM-detection code that landed independently via #330 (this branch was cut before that merged, so the bot diffs it all in); 1. OOM marker info side-channel — partially valid, low severity. The marker is written to 2.
|
|
@codex review this Latest commit
let scaled = gb * 1_073_741_824
return scaled >= uint64MaxAsDouble ? UInt64.max : UInt64(scaled)Added Please confirm this clamp can't trap at any boundary, and re-check the rest of the diff (VLM aggregate-before-decode, the other env clamps, |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 678a50f4b8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
The coordinator WebSocket path maps VLMRequestInference.MediaError via ProviderLoop.mapInferenceErrorToStatus (400 for client-fault media, 500 for the provider-side videoWriteFailed), but the local HTTP path's CORSResponder caught only MultiModelBatchSchedulerEngineError and MLXOpenAIServiceError — so an oversized/malformed inline-media request on 'darkbloom start --local' escaped as the framework's generic 500 instead of the 400 contract. Add the VLMRequestInference.MediaError catch to CORSResponder, reusing the same mapInferenceErrorToStatus mapping. Adds a direct CORSResponder regression (stub inner responder throwing MediaError) asserting 400 + the CORS header for oversized media and 500 for videoWriteFailed.
…-vlm-media-cap # Conflicts: # provider-swift/Sources/ProviderCore/Inference/MLXMemoryGuard.swift # provider-swift/Tests/ProviderCoreTests/MLXMemoryGuardTests.swift
|
@codex review this Head is now
37/37 affected Swift tests pass; coordinator |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c07a4d73e7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ), | ||
| message: error.localizedDescription | ||
| ) | ||
| } catch let error as VLMRequestInference.MediaError { |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…ream Follow-up to the CORSResponder catch: that only converts a MediaError to 400 if the error is THROWN through inner.respond. But on the streaming path (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 — after headers were sent. So an oversized inline-media streaming request still got a 200 with a truncated/error SSE body instead of a 400. 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 (non-streaming) HTTP, SSE (streaming) HTTP, and the coordinator WebSocket — and lands in the existing 4xx mappings (CORSResponder / mapInferenceErrorToStatus). validateMedia runs the same buildUserInput decode purely for its throwing side-effects (UserInput isn't Sendable, so it can't cross the stream task boundary — 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. Injectable caps mirror buildUserInput so tests stay fast. Adds validateMedia regressions (throws on oversize up front; passes within-cap). Affected Swift suites green.
|
@codex review this Head
Please confirm the preflight now covers the streaming path and there's no remaining path where oversized media yields a 200, plus re-check the rest. |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |

Summary
Caps VLM inline-media decode on the provider to close a decompression-bomb OOM. The VLM path decodes inline
data:image/video from a request before any KV/token/load admission runs, anddecodeImage→CIImage(data:)eagerly rasterizesW·H·4bytes with no size or dimension cap (PNG has no scaled-decode). A tiny, highly-compressed payload — a uniform40000×40000PNG is ~5 MB on the wire, well under the 32 MiB WS frame cap — explodes on decode.This is the proactive complement to this branch's reactive OOM work (
OOMDetector/MemoryPressureMonitor): reject the bomb from the media header before the raster is ever allocated, rather than detect the OOM after it happens.Measured on an M5 Max (128 GB, macOS 26.4.1)
A watchdog SIGKILLed each probe before it could threaten a co-resident 63 GB provider (0 swap) — no real OOM was triggered.
CIImage(data:))CIImage(data:)is not lazy for PNG (RSS scales linearly with pixels), the model's 448² downscale does not save the provider (CoreImage decodes the full-res source first), and ImageIO applies no dimension cap (decoded a 1-gigapixel PNG fine). The fix's header read is O(header) — ~0 GB even for a gigapixel input.The fix (
VLMRequestInference)All limits reject
MediaError.mediaTooLarge→ HTTP 400, are env-tunable, and have defaulted params for testability.CGImageSourceCopyPropertiesAtIndex) beforeCIImage(data:): per-image capDARKBLOOM_MAX_IMAGE_MEGAPIXELS(100) + a post-decodeCIImage.extentbackstop (closes the unsizable-format fallthrough), and a request-wide aggregateDARKBLOOM_MAX_REQUEST_IMAGE_MEGAPIXELS(384) that bounds the pack-many-images amplification.CMVideoFormatDescriptionGetDimensions, the larger of natural/coded) are readable and within cap, read fromAVURLAssettrack metadata with no frame decode. Per-frame reusesmaxImagePixels; duration capDARKBLOOM_MAX_VIDEO_SECONDS(600) bounds the sampled frame count. (A video the model can sample is always probeable, so fail-closed never rejects a usable video.) Plus request-wide caps —DARKBLOOM_MAX_VIDEOS_PER_REQUEST(8) and summed-per-frame-pixelDARKBLOOM_MAX_REQUEST_VIDEO_FRAME_MEGAPIXELS(384) — because the model samples ~32 frames per video, so a per-video cap alone doesn't bound a "many tiny MP4s" request.DARKBLOOM_MAX_MEDIA_MIB(25), also bounding the inline-video temp file + RAM; the base64 and percent-encoded paths both preflight the decoded size before allocating.Reviews (dual-gate + standing codex pass)
naturalSize-only metadata → then video limits were per-part only (many-tiny-MP4s) and the percent-encoded path capped only after allocating. All addressed; the final pass returned "No remaining findings."Test plan
swift test --filter VLMRequestInference— 39 tests, all pass on an M5 Max. Regression suite covers: per-image cap, post-decode backstop, request-wide image aggregate, byte caps (base64 + percent-encoded preflight), the header reader on a real multi-pixel image, video per-frame reject/pass (real 64×64 mp4 fixture), video byte cap, video fail-closed on unprobeable bytes, request-wide video count + frame-pixel caps, env resolution, and the documented defaults. Repro harness + on-hardware measurements:docs/spikes/vlm-oom/.Base
Stacks on
feat/oom-protection(its proactive input-validation piece).