Skip to content

fix(provider): cap VLM inline-media decode (decompression-bomb OOM) - #335

Merged
Gajesh2007 merged 13 commits into
masterfrom
feat/oom-protection-vlm-media-cap
Jun 14, 2026
Merged

Gajesh2007 merged 13 commits into
masterfrom
feat/oom-protection-vlm-media-cap

Conversation

@anupsv

@anupsv anupsv commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

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, and decodeImage → CIImage(data:) eagerly rasterizes W·H·4 bytes with no size or dimension cap (PNG has no scaled-decode). A tiny, highly-compressed payload — a uniform 40000×40000 PNG 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.

input mode on-wire decoded peak RSS
16000² decode-only (CIImage(data:)) 757 KiB 256 Mpx 0.96 GB
16000² real provider path (resample→448²) 757 KiB 256 Mpx 1.78 GB
32000² real provider path 3.0 MB 1024 Mpx 5.73 GB
40000² header read (the fix's probe) 4.7 MB 1600 Mpx 0 GB

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.

  • Images — pixel dimensions read from the format header (CGImageSourceCopyPropertiesAtIndex) before CIImage(data:): per-image cap DARKBLOOM_MAX_IMAGE_MEGAPIXELS (100) + a post-decode CIImage.extent backstop (closes the unsizable-format fallthrough), and a request-wide aggregate DARKBLOOM_MAX_REQUEST_IMAGE_MEGAPIXELS (384) that bounds the pack-many-images amplification.
  • Video — fails closed: rejects unless the duration and every track's coded frame dimensions (CMVideoFormatDescriptionGetDimensions, the larger of natural/coded) are readable and within cap, read from AVURLAsset track metadata with no frame decode. Per-frame reuses maxImagePixels; duration cap DARKBLOOM_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-pixel DARKBLOOM_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.
  • Both — per-part decoded-byte cap 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)

  • codex (GPT-5.5, xhigh) — several rounds, each verified on the M5 Max. Caught, in order: the video path was uncapped → then the video guard failed open on unreadable/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."
  • Independent reviewer — PASS on the image fix; its findings (nil-fallthrough backstop, overflow-safe aggregate, percent-encoded + video test gaps) are all addressed.

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).

Gajesh2007 and others added 7 commits June 13, 2026 13:00
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.
@vercel

vercel Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jun 14, 2026 10:40pm
d-inference-console-ui-dev Ready Ready Preview Jun 14, 2026 10:40pm
d-inference-landing Ready Ready Preview Jun 14, 2026 10:40pm

Request Review

ethenotethan

This comment was marked as outdated.

@blacksmith-sh

blacksmith-sh Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Found 1 test failure on Blacksmith runners:

Failure

Test View Logs
github.com/eigeninference/d-inference/coordinator/api/
TestProviderRegistrationRejectsInvalidConfiguredBinaryHash
View Logs

Fix with Codesmith
Need help on this PR? Tag /codesmith with what you need.

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.
ethenotethan

This comment was marked as outdated.

Comment thread docs/spikes/vlm-oom/make_bomb.py Resolved
@Gajesh2007

Copy link
Copy Markdown
Member

@codex review this

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Base automatically changed from feat/oom-protection to master June 14, 2026 18:17
…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.
@anupsv

anupsv commented Jun 14, 2026

Copy link
Copy Markdown
Contributor Author

@codex review this

This commit (ed8e3393) addresses your prior review (P2s) plus moves the spike repro to a test:

  • Aggregate-before-decode: parts() now charges the request-image aggregate from the header pixel count BEFORE CIImage(data:) (split decodeImageData out of decodeImage); a nil-header image folds its realized extent into the aggregate.
  • resolveMaxPixels: clamp huge env values to Int.max without Int(Double(Int.max)) (which rounds to 2^63 and traps at static init).
  • resolveMaxBytes: saturating multipliedReportingOverflow instead of a trapping MiB→bytes multiply.
  • enforceVideoLimits: format the over-duration 400 via secondsString (no Int(Double)), so untrusted duration > Int.max seconds returns 400 instead of trapping.
  • Replaced docs/spikes/vlm-oom/* with VLMDecodeBombTests.swift (in-process streaming-zlib PNG bomb; rejected from the header before raster allocation). 46/46 VLM tests pass.

Please confirm the aggregate is now charged pre-decode on every image path, and the env-clamp / duration-format edges no longer trap.

ethenotethan

This comment was marked as outdated.

@github-actions

github-actions Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

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

  • TB-003 — Provider operator vs. process (inference engine hardening)
  • TB-007 — Provider inference engine (VLM request handling, memory limits, streaming response lifecycle)

Threat Assessment

T-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 validateMedia path in VLMRequestInference.swift (lines ~100–130) enforces per-image pixel caps (maxImagePixels), aggregate pixel caps (maxRequestImagePixels), per-request video caps (maxVideosPerRequest), and video-frame pixel caps (maxRequestVideoFramePixels) before a streaming response is opened. Previously, an oversized or malformed data: payload would have committed a HTTP 200 and only errored mid-stream. Now a MediaError.mediaTooLarge throws before releaseBox is held unnecessarily and before the HTTP status is written.

T-029 / T-016 (Resource exhaustion at provider) — ✅ Strengthens. The MLXMemoryGuard.swift fix (scaled >= uint64MaxAsDouble ? UInt64.max : UInt64(scaled)) closes a latent crash: a provider operator (or env var injection) setting DARKBLOOM_MLX_MEMORY_RESERVE_GB to a value large enough that gb * 1_073_741_824 ≥ 2^64 would have trapped in the UInt64(Double(UInt64.max)) conversion at startup. The old path could be used to crash the provider process at configureOnce() with a single env var write — within reach of ADV-001. The fix saturates cleanly to UInt64.max instead.


New Attack Surface / Observations

  1. Double decode in validateMedia → stream (VLMRequestInference.swift lines ~126–135 and ~139–165): The PR comment acknowledges this correctly — buildUserInput is called twice (once in validateMedia, once inside the generation Task). The caps are re-enforced on the second pass identically, so there is no TOCTOU gap on the limits themselves. However, if a malformed data: URI passes validateMedia on the first decode (e.g., a race with a mutable request object — not possible here since OpenAIChatCompletionRequest is passed by value) the second pass would also fail. This appears structurally safe but is worth noting for future refactors that might make request reference-typed.

  2. Temp-file cleanup in validateMedia (VLMRequestInference.swift lines ~118–122): The defer { for url in tempFiles { try? FileManager.default.removeItem(at: url) } } in validateMedia silently swallows removal errors. This is consistent with existing stream behavior, so it's not a regression, but a provider operator could observe temp-file residue (containing decoded frame data) in a crash scenario. Given the open finding on GPU-buffer zeroing (T-028), the same concern applies at the CPU/disk tier.

  3. releaseBox.fire() on validation failure (MultiModelBatchSchedulerEngine.swift lines ~200–205): The early await releaseBox.fire() before rethrowing MediaError correctly releases the concurrency slot. If releaseBox.fire() itself throws or is idempotent-unsafe, a slot leak is possible — but this is an existing pattern in the codebase, not introduced here.

  4. AVFoundation / ImageIO added as imports (VLMRequestInference.swift lines 18–19): Both are Apple system frameworks with no network-calling surface in this context. No new attack surface.


SEC-* Findings Resolved

None explicitly resolved. The MLXMemoryGuard crash fix addresses a gap adjacent to T-016 (operator fills disk / crashes provider) but is not tracked as a named SEC finding. Consider opening one if this crash path was reachable from coordinator-supplied env config rather than only operator-local env.


Summary

The crash fix in MLXMemoryGuard.swift is the highest-priority change here — a known-large DARKBLOOM_MLX_MEMORY_RESERVE_GB value was a provider-crasher reachable by the operator (ADV-001) with no coordinator-side visibility. The VLM decode-bomb mitigations are solid: pixel caps, video caps, and early-rejection before HTTP 200 commit. No regressions against the threat model are present.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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.
@anupsv

anupsv commented Jun 14, 2026

Copy link
Copy Markdown
Contributor Author

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); OOMDetector.swift here is byte-identical to master. This PR's own delta is the VLM media caps in VLMRequestInference.swift.

1. OOM marker info side-channel — partially valid, low severity. The marker is written to ~/.darkbloom/oom_marker.json (provider user's home, not $TMPDIR/world-readable temp), so the path concern doesn't apply. The real sub-point stands: data.write(to:options:.atomic) sets no explicit mode, so the file inherits umask (often 0644) and exposes peakMemoryBytes/availableBytesAtEvent as a weak memory-size oracle to local processes. Worth a 0600 (FileProtectionType / explicit POSIX perms) hardening — tracked as a follow-up against master since it's #330 code, not this PR. The concurrency concern is a non-issue: the writeMarker closure reads MLX.Memory.peakMemory (a global, not actor-isolated state).

2. DARKBLOOM_MLX_MEMORY_RESERVE_GB operator DoS — agreed it's within ADV-001's accepted capabilities (an operator can already kill the process), so no code change for the DoS itself; will document it as an accepted operator knob. However, reviewing that exact line surfaced a real reliability bug Codex also flagged: UInt64(min(gb * 1GiB, Double(UInt64.max))) traps (Double(UInt64.max) rounds to 2^64, outside UInt64), crashing the provider at startup on a huge finite value — fixed in 678a50f4 with a saturating threshold + regression test.

_resetForTest() is internal (not public) and only reachable via @testable import from the test bundle — not the production binary. Will add a threat-model entry for unbounded VLM media decode on the provider side (the new caps) as suggested.

ethenotethan

This comment was marked as outdated.

@anupsv

anupsv commented Jun 14, 2026

Copy link
Copy Markdown
Contributor Author

@codex review this

Latest commit 678a50f4 applies the fix for the P2 you flagged on ed8e3393:

MLXMemoryGuard.resolvedReserveBytes no longer does UInt64(min(gb * 1GiB, Double(UInt64.max))) (which traps because Double(UInt64.max) rounds up to 2^64, outside UInt64). It now saturates against an explicit uint64MaxAsDouble (== 2^64) threshold:

let scaled = gb * 1_073_741_824
return scaled >= uint64MaxAsDouble ? UInt64.max : UInt64(scaled)

Added mlxGuardReserveEnvClampsHugeValueInsteadOfTrapping (huge value + the exact 2^64-boundary value saturate to UInt64.max; a normal value converts; 0 is honored). 52/52 Swift tests pass.

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, secondsString, and the new VLMDecodeBombTests).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

anupsv added 2 commits June 14, 2026 15:11
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
ethenotethan

This comment was marked as outdated.

@anupsv

anupsv commented Jun 14, 2026

Copy link
Copy Markdown
Contributor Author

@codex review this

Head is now c07a4d73 (merge of master + the fix for your last P2):

37/37 affected Swift tests pass; coordinator go build/go vet clean. Please re-check the CORSResponder catch and the conflict resolution, plus anything else in the diff.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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 {

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.

…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.
@anupsv

anupsv commented Jun 14, 2026

Copy link
Copy Markdown
Contributor Author

@codex review this

Head 5070d29e fixes the streaming-path gap you flagged on c07a4d73:

MultiModelBatchSchedulerEngine.streamChatCompletion now calls VLMRequestInference.validateMedia(request) and propagates its throw synchronously before returning the stream — so an oversized/malformed inline-media request surfaces a MediaError (→ 4xx) on the buffered HTTP path, the SSE streaming path, AND the coordinator WebSocket path, rather than only after a 200 SSE body has begun. validateMedia re-runs the buildUserInput decode for its throwing side-effects (UserInput isn't Sendable, so stream rebuilds it inside the generation task). The CORSResponder catch stays as the local-path 4xx landing point.

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.

ethenotethan

This comment was marked as outdated.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 5070d29e52

ℹ️ 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".

@Gajesh2007
Gajesh2007 merged commit 4ab75e1 into master Jun 14, 2026
66 of 68 checks passed

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference — 5070d29e Deployed Jun 14, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 5070d29e Deployed Jun 14, 2026 by vercel[bot]
Preview – d-inference-landing — 5070d29e Deployed Jun 14, 2026 by vercel[bot]
benchmarks — 5070d29e Deployed Jun 14, 2026 by anupsv via E2E Benchmarks #882
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants