Skip to content

feat(provider+coordinator): OOM protection + detection - #330

Merged
Gajesh2007 merged 4 commits into
masterfrom
feat/oom-protection
Jun 14, 2026
Merged

Gajesh2007 merged 4 commits into
masterfrom
feat/oom-protection

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jun 13, 2026 •

Copy link
Copy Markdown
Member

Problem

A lot of office Macs running as providers were OOM-crashing, invisibly. Over 48h on prod: ~7,880 read_error WS disconnects, a step-function fleet collapse on 06-12 (online ~99 → ~57, ~40% capacity never recovered), and 261 "insufficient memory to load model" 503s (86% gpt-oss-20b) — yet only ~2 panic events reached Datadog. A jetsam SIGKILL is uncatchable, so the kill flushes no telemetry; the crash shows up only as a coordinator-side disconnect indistinguishable from a network blip.

Root cause

The provider had a well-defended model-load gate (ModelLoadAdmission.freeForLoadGb clamps to min(mlxFree, SystemMemory.availableBytes())) but an OS-memory-blind runtime path on a platform (unified memory) where overshoot is a fatal kernel kill:

  1. Runtime KV admission was OS-blind. GlobalKVCacheBudget.availableReservationBytes() and BatchScheduler.tokenBudgetMax computed free RAM as physicalMemory − MLX.active − MLX.cache — counting only MLX's own memory against TOTAL physical RAM. On a shared office Mac where other apps hold tens of GB, both over-admit by exactly that amount → the KV cache grows under batching → jetsam SIGKILL.
  2. No MLX memory ceiling. MLX's memoryLimit defaults to 1.5× the device working set — above physical RAM — so MLX freely allocates past total RAM with no catchable failure.
  3. OOMs were invisible. No oom telemetry kind, no memory-pressure handler, no crash-log scrape; the coordinator bucketed the kill as a generic read_error disconnect.

What changed

Provider OOM fix (the cure)

  • Runtime KV budget consults real OS-available RAM — GlobalKVCacheBudget + BatchScheduler.tokenBudgetMax now clamp to min(mlxFree, SystemMemory.availableBytes()) − reserve, the same clamp the load gate uses. On a tight box this degrades to one-request-at-a-time instead of crashing — capacity is preserved, not derouted.
  • MLXMemoryGuard pins Memory.memoryLimit/cacheLimit below physical RAM once per process (wired idempotently in BatchScheduler.loadModel), 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 (+ both field allowlists + the console-ui set).
  • OOMDetector: on launch, consume any pre-death marker and scrape kernel JetsamEvent / EXC_RESOURCE crash reports for our process, emitting oom telemetry — recovering the signal a SIGKILL destroys.
  • Coordinator classifies abrupt read_error disconnects against the last heartbeat's memory pressure + in-flight count (ClassifyDisconnectReason), emitting provider_oom_suspected_total + an oom event. Turns the silent read-error churn into an attributable metric.

Testing

New coverage for the OS-clamp (both directions + reserve), MLX sizing/idempotency, the .ips parsers / marker round-trip / scan watermark, the memory-pressure policy, and the disconnect classifier. Full swift test (provider) and go test ./... + go vet (coordinator) green. Two independent reviewers passed.

Not derouting / gemma note

A 24 GB box can serve one gpt-oss-20b request when idle; the crashes come from shared machines losing headroom + ungated concurrency + no MLX cap — addressed here without giving up the tier. The structural fix for the 36 GB tier is the separate gemma 8-bit → 4-bit cutover (~28 GB → ~14 GB weights).

Deferred follow-ups (not in this PR)

Free-RAM bytes in the heartbeat; coordinator memory hard-gate (deroute > 0.85 pressure); VLM-path memory gating; watchdog crashloop backoff; max_tokens clamp to context window.

Deploy notes

  • Provider changes require a release for the fleet to pick up (human-gated).
  • The disconnect classifier is coordinator-side → needs a coordinator deploy (EigenCloud, human-only).

🤖 Generated with Claude Code


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

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.
@vercel

vercel Bot commented Jun 13, 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 13, 2026 10:19pm
d-inference-console-ui-dev Ready Ready Preview Jun 13, 2026 10:19pm
d-inference-landing Ready Ready Preview Jun 13, 2026 10:19pm

Request Review

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 6 finding(s) (5 blocking)

  • 🔴 [CRITICAL] provider-swift/Sources/ProviderCore/Inference/BatchScheduler+Telemetry.swift:46-55 — SystemMemory.availableBytes() called synchronously in hot path
    • Suggestion: Cache the OS memory reading or make it async - this syscall can block during memory pressure when it's most needed
  • 🔴 [CRITICAL] provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift:83-95 — SystemMemory.availableBytes() called in memory allocation path
    • Suggestion: Cache the system memory reading with periodic refresh rather than calling on every allocation decision
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/ProviderLoop.swift:2138-2140 — SystemMemory.availableBytes() called in memory pressure handler
    • Suggestion: Pre-cache the memory reading before the pressure event or use async dispatch
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/ProviderLoop.swift:2147-2151 — SystemMemory.availableBytes() called in telemetry emission
    • Suggestion: Cache the memory value from the pressure event rather than re-reading during telemetry
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Diagnostics/OOMDetector.swift:190-220 — Directory scan with file I/O in launch path
    • Suggestion: Move crash log scanning to background task after launch to avoid blocking startup
  • 🟡 [MEDIUM] coordinator/api/provider.go:208-232 — Memory pressure classification computed on every read error
    • Suggestion: Pre-compute classification result when storing diagnostics to avoid repeated work in error path

Type_diligence — 1 finding(s)

  • 🔵 [INFO] coordinator/api/provider.go:218-229 — map[string]any used for telemetry fields in emit call
    • Suggestion: Consider using a typed struct for telemetry fields instead of map[string]any to prevent field name typos and ensure type safety

Additive_complexity — 6 finding(s) (2 blocking)

  • 🔵 [INFO] coordinator/registry/disconnect_classify.go:1-59 — New file with single-purpose classification logic that could be simpler
    • Suggestion: Consider inlining ClassifyDisconnectReason into the caller or making it a simple function rather than a separate package-level abstraction
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Diagnostics/MemoryPressureMonitor.swift:1-97 — Complex abstraction with policy separation and dependency injection for relatively simple memory pressure handling
    • Suggestion: Consider simplifying by combining MemoryPressurePolicy into MemoryPressureMonitor and reducing the number of injected closures
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Diagnostics/OOMDetector.swift:1-276 — Large 276-line file with multiple responsibilities: marker I/O, crash log parsing, directory scanning, and JSON parsing
    • Suggestion: Split into focused modules: OOMMarker for persistence, CrashLogParser for .ips parsing, and OOMScanner for directory operations
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/MLXMemoryGuard.swift:1-117 — Multiple configuration paths (explicit bytes, env var in GB, default) with complex resolution logic
    • Suggestion: Simplify to just explicit parameter and default, removing environment variable override to reduce configuration surface
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift:20-32 — Memory snapshot closure now includes system memory concerns mixing MLX and OS-level responsibilities
    • Suggestion: Create a dedicated MemorySnapshot type to encapsulate the four memory values rather than expanding the closure signature
  • 🔵 [INFO] coordinator/api/provider.go:209-232 — OOM classification logic duplicated between coordinator and registry package
    • Suggestion: Use registry.ClassifyDisconnectReason directly instead of reimplementing the classification in the API layer

13 finding(s) total, 7 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment on lines +46 to +55
let mlxFree = max(0, totalMemory - globalUsed)
// Clamp the MLX-only free figure to what the OS actually reports
// available. `totalMemory - MLX.active - MLX.cache` is blind to every
// other process on the box, so on a shared office Mac it over-reports
// free RAM by whatever Chrome/Xcode/etc. hold — the same OOM hole the
// model-load gate and GlobalKVCacheBudget already close via
// min(mlxFree, SystemMemory.availableBytes()).
let osAvailable = SystemMemory.availableBytes().map { Int(min($0, UInt64(Int.max))) } ?? Int.max
let realFree = min(mlxFree, osAvailable)
let availableHeadroom = max(0, realFree - osReserve - safetyMargin)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 [CRITICAL] ⚡ SystemMemory.availableBytes() called synchronously in hot path

💡 Suggestion: Cache the OS memory reading or make it async - this syscall can block during memory pressure when it's most needed

📊 Score: 4×4 = 16 · Category: blocking_io

Comment on lines +83 to +95
let (total, active, cache, systemAvailable) = memorySnapshot()
// MLX-only view: physical total minus what MLX itself holds. This is
// blind to every other process on the machine, so on a shared office
// Mac it over-reports free memory by whatever Chrome/Xcode/etc. hold.
let mlxUsed = Self.saturatingAdd(active, cache)
let mlxFree = total > mlxUsed ? total - mlxUsed : 0
// Clamp to what the OS actually reports available. The tighter of the
// two bounds wins — the exact same clamp the model-LOAD gate applies
// (`ModelLoadAdmission.freeForLoadGb`: realFree = min(mlxFree, OS-free)).
// Without this, the runtime KV path admits requests against memory other
// processes have already taken and drives the box into a jetsam OOM kill.
let realFree = min(mlxFree, systemAvailable)
let usable = realFree > reserveBytes ? realFree - reserveBytes : 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 [CRITICAL] ⚡ SystemMemory.availableBytes() called in memory allocation path

💡 Suggestion: Cache the system memory reading with periodic refresh rather than calling on every allocation decision

📊 Score: 4×4 = 16 · Category: blocking_io

Comment on lines +2138 to +2140
epochSeconds: Date().timeIntervalSince1970,
peakMemoryBytes: UInt64(max(0, MLX.Memory.peakMemory)),
availableBytesAtEvent: SystemMemory.availableBytes() ?? 0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ SystemMemory.availableBytes() called in memory pressure handler

💡 Suggestion: Pre-cache the memory reading before the pressure event or use async dispatch

📊 Score: 3×3 = 9 · Category: blocking_io

Comment on lines +2147 to +2151
fields: [
"pressure": .string(level.rawValue),
"available_bytes": .int64(Int64(clamping: SystemMemory.availableBytes() ?? 0)),
"mlx_active_bytes": .int64(Int64(clamping: UInt64(max(0, MLX.Memory.activeMemory)))),
])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ SystemMemory.availableBytes() called in telemetry emission

💡 Suggestion: Cache the memory value from the pressure event rather than re-reading during telemetry

📊 Score: 3×3 = 9 · Category: blocking_io

Comment on lines +190 to +220

/// Scan DiagnosticReports for OOM-relevant reports modified since `since`.
/// Best-effort; returns [] on any directory/read error.
public static func scanDiagnosticReports(
dir: URL,
processName: String,
since: Date,
fileManager: FileManager = .default
) -> [Finding] {
guard let entries = try? fileManager.contentsOfDirectory(
at: dir, includingPropertiesForKeys: [.contentModificationDateKey], options: [.skipsHiddenFiles])
else { return [] }

var findings: [Finding] = []
for url in entries {
let ext = url.pathExtension.lowercased()
guard ext == "ips" || ext == "panic" else { continue }
let name = url.lastPathComponent
let mtime = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate
if let mtime, mtime < since { continue }
guard let contents = try? String(contentsOf: url, encoding: .utf8) else { continue }

let isJetsam = name.hasPrefix("JetsamEvent")
var finding: Finding?
if isJetsam {
finding = parseJetsamReport(contents: contents, processName: processName)
} else {
finding = parseMemoryCrashReport(contents: contents, processName: processName)
}
if var f = finding {
f.reportName = name

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ Directory scan with file I/O in launch path

💡 Suggestion: Move crash log scanning to background task after launch to avoid blocking startup

📊 Score: 3×2 = 6 · Category: blocking_io

Comment on lines +1 to +97
import Foundation
import Dispatch

/// Coarse memory-pressure level from the kernel (DISPATCH_SOURCE_MEMORYPRESSURE).
public enum MemoryPressureLevel: String, Sendable, Equatable {
case normal
case warning
case critical
}

/// What the provider should do at a given pressure level.
public struct MemoryPressureResponse: Equatable, Sendable {
/// Drop MLX's reusable buffer pool back to the OS immediately.
public var clearCache: Bool
/// Persist an OOM marker so that if jetsam SIGKILLs us next, the following
/// launch can attribute the death to memory pressure.
public var writeMarker: Bool
/// Telemetry severity to emit (nil = don't emit).
public var severity: TelemetrySeverity?
}

/// Pure policy: pressure level -> action. Tested in isolation.
public enum MemoryPressurePolicy {
public static func response(for level: MemoryPressureLevel) -> MemoryPressureResponse {
switch level {
case .normal:
return MemoryPressureResponse(clearCache: false, writeMarker: false, severity: nil)
case .warning:
// Reclaim the cache early; the live admission gate (GlobalKVCacheBudget /
// tokenBudgetMax, now OS-available-aware) naturally tightens as free RAM
// falls, so no forced shedding is needed yet — just return memory. No
// telemetry: warning pressure is routine on healthy Macs and would
// only add noise to the `oom` signal.
return MemoryPressureResponse(clearCache: true, writeMarker: false, severity: nil)
case .critical:
// Last chance before a possible jetsam kill: reclaim everything AND
// drop a marker so the death isn't invisible.
return MemoryPressureResponse(clearCache: true, writeMarker: true, severity: .error)
}
}
}

/// Watches kernel memory pressure and reacts. MLX-free by design: the caller
/// injects the `clearCache` / `writeMarker` / `emit` actions so this stays
/// testable and the file has no MLX dependency. `handle(_:)` is the testable
/// core; `start()` wires it to a real DispatchSource.
public final class MemoryPressureMonitor: @unchecked Sendable {
private let clearCache: @Sendable () -> Void
private let writeMarker: @Sendable (MemoryPressureLevel) -> Void
private let emit: @Sendable (MemoryPressureLevel, TelemetrySeverity) -> Void
private let queue: DispatchQueue
private var source: DispatchSourceMemoryPressure?

public init(
queue: DispatchQueue = DispatchQueue(label: "dev.darkbloom.memory-pressure"),
clearCache: @escaping @Sendable () -> Void,
writeMarker: @escaping @Sendable (MemoryPressureLevel) -> Void,
emit: @escaping @Sendable (MemoryPressureLevel, TelemetrySeverity) -> Void
) {
self.queue = queue
self.clearCache = clearCache
self.writeMarker = writeMarker
self.emit = emit
}

public func start() {
let src = DispatchSource.makeMemoryPressureSource(eventMask: [.warning, .critical], queue: queue)
src.setEventHandler { [weak self] in
guard let self, let data = self.source?.data else { return }
self.handle(Self.level(from: data))
}
self.source = src
src.activate()
}

public func cancel() {
source?.cancel()
source = nil
}

/// Testable core: apply the policy for a level and invoke the injected
/// actions. Safe to call directly from tests.
public func handle(_ level: MemoryPressureLevel) {
let response = MemoryPressurePolicy.response(for: level)
if response.clearCache { clearCache() }
if response.writeMarker { writeMarker(level) }
if let severity = response.severity { emit(level, severity) }
}

/// Map a DispatchSource.MemoryPressureEvent bitmask to our coarse level.
/// Critical dominates warning when both bits are set.
static func level(from data: DispatchSource.MemoryPressureEvent) -> MemoryPressureLevel {
if data.contains(.critical) { return .critical }
if data.contains(.warning) { return .warning }
return .normal
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Complex abstraction with policy separation and dependency injection for relatively simple memory pressure handling

💡 Suggestion: Consider simplifying by combining MemoryPressurePolicy into MemoryPressureMonitor and reducing the number of injected closures

📊 Score: 3×2 = 6 · Category: over-abstraction

Comment on lines +1 to +276
import Foundation

/// Make out-of-memory crashes VISIBLE.
///
/// The defining problem: when macOS jetsam kills the provider for exhausting
/// unified memory, it sends an uncatchable SIGKILL. No signal handler runs, no
/// telemetry flushes — the crash leaves no in-process trace. So OOMs are
/// invisible to our telemetry today (they show up only as a coordinator-side
/// "read_error" disconnect, indistinguishable from a network blip).
///
/// Two complementary detectors recover the signal:
/// 1. **Pre-death marker** — when the provider observes a *critical* memory
/// pressure event (see `MemoryPressureMonitor`), it writes a small marker
/// to disk. If we then get SIGKILL'd, the marker survives and the NEXT
/// launch reports it.
/// 2. **Crash-log scrape** — on launch, scan `~/Library/Logs/DiagnosticReports`
/// for kernel `JetsamEvent-*.ips` reports and `EXC_RESOURCE` memory crash
/// reports naming our process, and emit an `oom` telemetry event for each.
///
/// Both are best-effort and tolerant: a parse failure must never crash startup.
public enum OOMDetector {

// MARK: - Types

/// Marker written just before a suspected OOM death (on critical pressure).
public struct Marker: Codable, Equatable, Sendable {
public var pid: Int32
public var epochSeconds: Double
public var peakMemoryBytes: UInt64
public var availableBytesAtEvent: UInt64
public var modelId: String?

public init(pid: Int32, epochSeconds: Double, peakMemoryBytes: UInt64,
availableBytesAtEvent: UInt64, modelId: String? = nil) {
self.pid = pid
self.epochSeconds = epochSeconds
self.peakMemoryBytes = peakMemoryBytes
self.availableBytesAtEvent = availableBytesAtEvent
self.modelId = modelId
}
}

/// One detected OOM signal, ready to be turned into an `oom` telemetry event.
public struct Finding: Equatable, Sendable {
public enum Source: String, Sendable {
case memoryPressureMarker = "memory_pressure_marker"
case jetsamReport = "jetsam_report"
case memoryCrashReport = "memory_crash_report"
}
public var source: Source
public var message: String
public var reason: String?
public var peakMemoryBytes: UInt64?
public var reportName: String?
public var epochSeconds: Double?

public init(source: Source, message: String, reason: String? = nil,
peakMemoryBytes: UInt64? = nil, reportName: String? = nil,
epochSeconds: Double? = nil) {
self.source = source
self.message = message
self.reason = reason
self.peakMemoryBytes = peakMemoryBytes
self.reportName = reportName
self.epochSeconds = epochSeconds
}
}

// MARK: - Paths

/// Marker lives under ~/.darkbloom/ — a stable, daemon-writable location
/// (the install dir under /usr/local may be read-only for the daemon).
public static func defaultMarkerURL(
home: URL = FileManager.default.homeDirectoryForCurrentUser
) -> URL {
home.appendingPathComponent(".darkbloom").appendingPathComponent("oom_marker.json")
}

public static func defaultDiagnosticReportsURL(
home: URL = FileManager.default.homeDirectoryForCurrentUser
) -> URL {
home.appendingPathComponent("Library/Logs/DiagnosticReports")
}

/// Watermark of the last crash-log scan. Scanning only reports modified
/// after this avoids re-emitting the same JetsamEvent on every launch — the
/// difference between one OOM event and a crashloop spamming the same report.
public static func defaultLastScanURL(
home: URL = FileManager.default.homeDirectoryForCurrentUser
) -> URL {
home.appendingPathComponent(".darkbloom").appendingPathComponent("oom_last_scan")
}

public static func loadLastScan(at url: URL = defaultLastScanURL()) -> Date? {
guard let raw = try? String(contentsOf: url, encoding: .utf8),
let epoch = Double(raw.trimmingCharacters(in: .whitespacesAndNewlines))
else { return nil }
return Date(timeIntervalSince1970: epoch)
}

public static func saveLastScan(_ date: Date, at url: URL = defaultLastScanURL()) {
try? FileManager.default.createDirectory(
at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try? String(date.timeIntervalSince1970).write(to: url, atomically: true, encoding: .utf8)
}

// MARK: - Marker I/O

public static func writeMarker(_ marker: Marker, to url: URL = defaultMarkerURL()) {
do {
try FileManager.default.createDirectory(
at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
let data = try JSONEncoder().encode(marker)
try data.write(to: url, options: .atomic)
} catch {
// Best-effort: a marker we can't write just means this particular
// OOM stays invisible — never fatal.
}
}

/// Read the marker and delete it (consume-once) so the same event isn't
/// reported on every subsequent launch.
@discardableResult
public static func readAndClearMarker(at url: URL = defaultMarkerURL()) -> Marker? {
guard let data = try? Data(contentsOf: url) else { return nil }
defer { try? FileManager.default.removeItem(at: url) }
return try? JSONDecoder().decode(Marker.self, from: data)
}

// MARK: - Pure parsers (.ips reports)

/// Parse a kernel `JetsamEvent-*.ips` report. These are two-part documents:
/// a one-line JSON header followed by a JSON body containing a `processes`
/// array. Returns a finding if our process appears among the killed
/// processes. Pure + tolerant: any malformed input returns nil.
public static func parseJetsamReport(contents: String, processName: String) -> Finding? {
guard let body = jsonBody(from: contents) else { return nil }
let pageSize = (body["pageSize"] as? Int)
?? ((body["memoryStatus"] as? [String: Any])?["pageSize"] as? Int)
?? 16384
guard let processes = body["processes"] as? [[String: Any]] else { return nil }
let needle = processName.lowercased()
for proc in processes {
guard let name = proc["name"] as? String, name.lowercased().contains(needle) else { continue }
let rpages = (proc["rpages"] as? Int) ?? (proc["pages"] as? Int) ?? 0
let bytes = UInt64(max(0, rpages)) &* UInt64(max(0, pageSize))
let reason = (proc["reason"] as? String) ?? (proc["killDelta"] as? String)
return Finding(
source: .jetsamReport,
message: "jetsam killed \(name) (\(reason ?? "memory pressure"))",
reason: reason,
peakMemoryBytes: bytes > 0 ? bytes : nil)
}
return nil
}

/// Parse a process crash `.ips` for a memory kill: `EXC_RESOURCE` with a
/// MEMORY subtype, or a JETSAM termination namespace. Pure + tolerant.
public static func parseMemoryCrashReport(contents: String, processName: String) -> Finding? {
guard let header = jsonHeader(from: contents) else { return nil }
// Header names the app; only consider reports for our process.
let appName = (header["app_name"] as? String) ?? (header["procName"] as? String) ?? ""
guard appName.lowercased().contains(processName.lowercased()) else { return nil }
guard let body = jsonBody(from: contents) else { return nil }

if let exception = body["exception"] as? [String: Any] {
let type = (exception["type"] as? String) ?? ""
let subtype = (exception["subtype"] as? String) ?? ""
if type.contains("EXC_RESOURCE") && subtype.uppercased().contains("MEMORY") {
return Finding(
source: .memoryCrashReport,
message: "\(appName) hit memory resource limit (\(subtype))",
reason: subtype)
}
}
if let termination = body["termination"] as? [String: Any] {
let namespace = (termination["namespace"] as? String) ?? ""
if namespace.uppercased().contains("JETSAM") {
let reason = (termination["indicator"] as? String) ?? namespace
return Finding(
source: .memoryCrashReport,
message: "\(appName) terminated by jetsam (\(reason))",
reason: reason)
}
}
return nil
}

// MARK: - Launch detection (I/O)

/// Scan DiagnosticReports for OOM-relevant reports modified since `since`.
/// Best-effort; returns [] on any directory/read error.
public static func scanDiagnosticReports(
dir: URL,
processName: String,
since: Date,
fileManager: FileManager = .default
) -> [Finding] {
guard let entries = try? fileManager.contentsOfDirectory(
at: dir, includingPropertiesForKeys: [.contentModificationDateKey], options: [.skipsHiddenFiles])
else { return [] }

var findings: [Finding] = []
for url in entries {
let ext = url.pathExtension.lowercased()
guard ext == "ips" || ext == "panic" else { continue }
let name = url.lastPathComponent
let mtime = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate
if let mtime, mtime < since { continue }
guard let contents = try? String(contentsOf: url, encoding: .utf8) else { continue }

let isJetsam = name.hasPrefix("JetsamEvent")
var finding: Finding?
if isJetsam {
finding = parseJetsamReport(contents: contents, processName: processName)
} else {
finding = parseMemoryCrashReport(contents: contents, processName: processName)
}
if var f = finding {
f.reportName = name
f.epochSeconds = mtime?.timeIntervalSince1970
findings.append(f)
}
}
return findings
}

/// Full launch-time detection: consume any pre-death marker AND scan crash
/// logs since `since`. Returns all findings to emit as `oom` telemetry.
public static func detectOnLaunch(
markerURL: URL = defaultMarkerURL(),
diagnosticReportsDir: URL = defaultDiagnosticReportsURL(),
processName: String = "darkbloom",
since: Date,
fileManager: FileManager = .default
) -> [Finding] {
var findings: [Finding] = []
if let marker = readAndClearMarker(at: markerURL) {
findings.append(Finding(
source: .memoryPressureMarker,
message: "provider observed critical memory pressure before exit (likely OOM)",
peakMemoryBytes: marker.peakMemoryBytes > 0 ? marker.peakMemoryBytes : nil,
epochSeconds: marker.epochSeconds))
}
findings.append(contentsOf: scanDiagnosticReports(
dir: diagnosticReportsDir, processName: processName, since: since, fileManager: fileManager))
return findings
}

// MARK: - JSON helpers

/// The first JSON object in an `.ips` document (the one-line header).
static func jsonHeader(from contents: String) -> [String: Any]? {
guard let firstLine = contents.split(separator: "\n", maxSplits: 1, omittingEmptySubsequences: true).first,
let data = firstLine.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else { return nil }
return obj
}

/// The JSON body of an `.ips` document. Some reports are a single JSON
/// object (whole file parses); most are header-line + body. Try whole-file
/// first, then everything after the first newline.
static func jsonBody(from contents: String) -> [String: Any]? {
if let data = contents.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
return obj
}
let parts = contents.split(separator: "\n", maxSplits: 1, omittingEmptySubsequences: true)
guard parts.count == 2,
let data = parts[1].data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else { return nil }
return obj
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] 🧩 Large 276-line file with multiple responsibilities: marker I/O, crash log parsing, directory scanning, and JSON parsing

💡 Suggestion: Split into focused modules: OOMMarker for persistence, CrashLogParser for .ips parsing, and OOMScanner for directory operations

📊 Score: 4×3 = 12 · Category: additive complexity

Comment on lines +1 to +117
import Foundation
import MLX

/// Hard ceiling on MLX's unified-memory footprint.
///
/// THE PROBLEM: on Apple Silicon, MLX allocates GPU buffers from the same
/// unified-memory pool as the OS. MLX's `memoryLimit` defaults to **1.5× the
/// device's recommended max working-set size** — which is *above* physical RAM —
/// so by default MLX will happily try to allocate past total RAM. When it does,
/// macOS jetsam sends the process an uncatchable SIGKILL: an invisible OOM
/// crash (no panic, no telemetry — the kill leaves no trace the process can
/// flush). This is the dominant office-Mac failure mode.
///
/// THE GUARD: pin `Memory.memoryLimit` to `physical − reserve` once at startup.
/// Past that limit MLX's allocator applies backpressure (malloc waits on
/// scheduled GPU tasks to free memory) instead of racing the machine into a
/// kernel kill. This is a *coarse backstop*; the precise, live, shared-machine
/// protection is the per-request admission gate (`GlobalKVCacheBudget` /
/// `tokenBudgetMax`, which clamp to `SystemMemory.availableBytes()`). The two
/// are complementary: admission keeps us from *trying* to over-allocate; the
/// ceiling bounds the blast radius if an estimate is ever wrong.
public enum MLXMemoryGuard {
/// Default headroom (GB) left below physical RAM for macOS + non-MLX
/// process memory. Deliberately larger than the per-request load reserve
/// (4 GB) because this is the *whole-machine* ceiling: it must leave room
/// for the OS, the window server, and whatever else shares the box.
public static let defaultReserveGB: UInt64 = 6

/// Floor so a tiny/misreported machine never gets a pathological (or zero)
/// limit that would wedge every allocation.
static let minimumLimitBytes = 2 * 1024 * 1024 * 1024 // 2 GiB

public struct Limits: Equatable, Sendable {
public let memoryLimitBytes: Int
public let cacheLimitBytes: Int
}

/// Pure, testable sizing policy.
/// - memoryLimit = max(floor, physical − reserve)
/// - cacheLimit = memoryLimit × cacheFraction (bounds the reusable buffer
/// pool below the ceiling so freed buffers return to the OS rather than
/// lingering as the classic "MLX memory wedge"). cacheFraction defaults to
/// 0.75 — generous enough to preserve reuse/perf, bounded enough to help.
static func recommendedLimits(
physicalBytes: UInt64,
reserveBytes: UInt64,
cacheFraction: Double = 0.75
) -> Limits {
let physical = Int(min(physicalBytes, UInt64(Int.max)))
let reserve = Int(min(reserveBytes, UInt64(Int.max)))
let limit = max(minimumLimitBytes, physical > reserve ? physical - reserve : minimumLimitBytes)
let fraction = cacheFraction.isFinite ? min(1.0, max(0.0, cacheFraction)) : 0.75
let cache = max(minimumLimitBytes / 2, Int(Double(limit) * fraction))
return Limits(memoryLimitBytes: limit, cacheLimitBytes: min(cache, limit))
}

/// Resolve the reserve in BYTES from an explicit byte value, the
/// `DARKBLOOM_MLX_MEMORY_RESERVE_GB` env override (in GB), or the default.
/// `explicit` is bytes — consistent with `reserveBytes` everywhere else
/// (GlobalKVCacheBudget, ProviderLoop.memoryReserveBytes).
static func resolvedReserveBytes(
explicit: UInt64?,
env: [String: String] = ProcessInfo.processInfo.environment
) -> 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)))
}
return saturatingGiBToBytes(defaultReserveGB)
}

private static func saturatingGiBToBytes(_ gib: UInt64) -> UInt64 {
let (bytes, overflow) = gib.multipliedReportingOverflow(by: 1_073_741_824)
return overflow ? UInt64.max : bytes
}

// Idempotency: the ceiling only needs to be set once per process. loadModel
// can run many times (reloads, multi-model), so guard with a lock + flag.
private static let lock = NSLock()
nonisolated(unsafe) private static var configured = false

/// Set the MLX memory + cache ceiling once for this process. Idempotent and
/// safe to call from every model load. `apply` is injectable for tests so
/// they exercise the sizing/once-logic without touching real MLX globals.
@discardableResult
public static func configureOnce(
reserveBytes: UInt64? = nil,
physicalBytes: UInt64 = ProcessInfo.processInfo.physicalMemory,
apply: (Limits) -> Void = { limits in
Memory.memoryLimit = limits.memoryLimitBytes
Memory.cacheLimit = limits.cacheLimitBytes
},
log: ((Limits) -> Void)? = nil
) -> Limits? {
lock.lock()
if configured {
lock.unlock()
return nil
}
configured = true
lock.unlock()

let limits = recommendedLimits(
physicalBytes: physicalBytes,
reserveBytes: resolvedReserveBytes(explicit: reserveBytes))
apply(limits)
log?(limits)
return limits
}

/// Test-only: reset the once-flag so a test can drive `configureOnce` again.
static func _resetForTest() {
lock.lock()
configured = false
lock.unlock()
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Multiple configuration paths (explicit bytes, env var in GB, default) with complex resolution logic

💡 Suggestion: Simplify to just explicit parameter and default, removing environment variable override to reduce configuration surface

📊 Score: 2×2 = 4 · Category: over-configuration

Comment on lines +20 to +32
cache: UInt64(Memory.cacheMemory),
// Real OS-available memory (free + reclaimable), accounting for
// every other process on the box. `.max` when unavailable so we
// fall back to the MLX-only view rather than admitting nothing.
systemAvailable: SystemMemory.availableBytes() ?? .max
)
}
}

init(
reserveBytes: UInt64 = 0,
safetyFactor: Double = 0.7,
memorySnapshot: @escaping @Sendable () -> (total: UInt64, active: UInt64, cache: UInt64)
memorySnapshot: @escaping @Sendable () -> (total: UInt64, active: UInt64, cache: UInt64, systemAvailable: UInt64)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] 🧩 Memory snapshot closure now includes system memory concerns mixing MLX and OS-level responsibilities

💡 Suggestion: Create a dedicated MemorySnapshot type to encapsulate the four memory values rather than expanding the closure signature

📊 Score: 3×4 = 12 · Category: misplaced responsibility

Comment on lines +209 to 232

// A read_error is an abrupt drop — the signature of a killed
// process, not a graceful close. Classify it against the last
// heartbeat's memory pressure + in-flight count: a jetsam OOM
// kill leaves no other trace, so this is the only way to make it
// visible (vs. bucketing it as a generic disconnect). See
// registry.ClassifyDisconnectReason.
if provider != nil {
memPressure, inFlight := provider.DisconnectDiagnostics()
if registry.ClassifyDisconnectReason(true, memPressure, inFlight) == registry.DisconnectReasonOOMSuspected {
if s.metrics != nil {
s.metrics.IncCounter("provider_oom_suspected_total")
}
s.ddIncr("provider.oom_suspected", nil)
s.emit(context.Background(), protocol.SeverityError, protocol.KindOOM,
"provider disconnected under memory pressure (suspected OOM)",
map[string]any{
"provider_id": providerID,
"memory_pressure": memPressure,
"in_flight": inFlight,
})
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 OOM classification logic duplicated between coordinator and registry package

💡 Suggestion: Use registry.ClassifyDisconnectReason directly instead of reimplementing the classification in the API layer

📊 Score: 2×3 = 6 · Category: duplicate logic

@github-actions

github-actions Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds OOM diagnostics and MLX memory ceiling enforcement — all changes are neutral-to-positive from a security posture standpoint, with one minor finding worth tracking.


Trust Boundaries Touched

  • TB-002 (Coordinator → Provider WebSocket) — coordinator/api/provider.go emits diagnostic events on suspected OOM disconnect.
  • TB-003 (Provider Operator vs Process) — MLXMemoryGuard, GlobalKVCacheBudget, BatchScheduler.swift tighten memory admission; ProviderLoop.swift adds OOM marker and crash-log scanning.
  • TB-007 (Provider Inference Engine) — core of this PR; memory budget logic, MLX ceiling, telemetry.

Threat-by-Threat Assessment

T-007 — Provider serves manipulated model outputs (BatchScheduler+Telemetry.swift, GlobalKVCacheBudget.swift, MLXMemoryGuard.swift, BatchScheduler.swift)

ℹ️ Neutral. Changes are purely about memory admission accuracy (clamping mlxFree by systemAvailable, setting an MLX memory ceiling). No impact on weight-hash enforcement, model identity, or the routing gate. The fail-open SEC-007 finding is untouched.

T-028 — Residual inference data in GPU Metal buffers (BatchScheduler.swift)

ℹ️ Neutral. MLXMemoryGuard.configureOnce is called at model load time. The cacheLimitBytes cap (75% of memoryLimit) causes MLX to return buffers to the OS more aggressively, which incidentally reduces the window where stale KV-cache data lingers in Metal allocations — but there is no explicit memset/zero of GPU buffers. The open limitation in TB-003/T-028 remains; this is not a mitigation.

T-041 — Cross-tenant prefix-cache TTFT timing oracle (BatchScheduler.swift)

ℹ️ Neutral. MLXMemoryGuard.configureOnce is called but the prefix-cache enable/disable logic (makePrefixCacheBackingIfEnabled) is not touched. SEC-035 remains open and the default-on exposure is unchanged.

T-008 — Provider sends plaintext SSE on encryption failure (ProviderLoop.swift)

ℹ️ Neutral. startMemoryProtection() is added before the inference loop; the encryption failure / plaintext fallback path in ProviderLoop.swift:436–451 is not touched. SEC-016 open finding is unaffected.

T-009 — Swift provider excluded from private routing (ProviderLoop.swift)

ℹ️ Neutral. No changes to Python-flag reporting or the routing gate.

T-010 — Inference cancellation not propagated to inference engine (ProviderLoop.swift)

ℹ️ Neutral. InferenceCancellationToken wiring is unchanged.

T-034 — Provider runs modified code while advertising trusted identity (coordinator/api/provider.go)

ℹ️ Neutral. The OOM-classification block added at provider.go:206–230 runs after return is already executing (it is inside the read_error error-handling arm, before the final return). It reads provider.DisconnectDiagnostics() and emits a metric/event; it does not modify trust state, skip any attestation step, or create a new code path into the APNs challenge. The CodeAttested gate is unaffected.


New Attack Surface Not Covered by Existing Threats

⚠️ Telemetry event carries provider memory diagnostics via coordinator event bus (coordinator/api/provider.go:228–232)

s.emit(context.Background(), protocol.SeverityError, protocol.KindOOM,
    "provider disconnected under memory pressure (suspected OOM)",
    map[string]any{
        "provider_id":     providerID,
        "memory_pressure": memPressure,
        "in_flight":       inFlight,
    })

memPressure comes from provider.DisconnectDiagnostics(). Depending on what that field contains (a raw integer, a string label, a struct), a malicious provider that sends a crafted WebSocket frame just before disconnecting could influence the value logged/emitted. The risk is low (log injection / metric skew, not trust escalation), but:

  1. Confirm DisconnectDiagnostics() reads coordinator-side state (e.g. last heartbeat memory field stored in the registry), not a value extracted from the provider's final WebSocket frame. If the latter, a provider can inject arbitrary strings into coordinator structured logs/metrics.
  2. The in_flight value should also be coordinator-side (active request counter), not provider-reported — verify this is the case.

This is not covered by any existing T-xxx because the threat model doesn't specifically address log/metric injection via provider-controlled data on disconnect. It's low severity but worth a comment on the DisconnectDiagnostics() implementation.

ℹ️ DARKBLOOM_MLX_MEMORY_RESERVE_GB env var (MLXMemoryGuard.swift:52–56)

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

Setting this to 0 gives reserveBytes = 0, which means MLX memoryLimit = physicalRAM (no headroom for OS). The minimumLimitBytes = 2 GiB floor in recommendedLimits still applies to the limit, but with reserve = 0 the limit equals physical RAM — effectively disabling the intended headroom. A provider operator controlling their own .env / launchd plist can do this deliberately to squeeze more model capacity, increasing jetsam risk. This is within the TB-003 accepted risk surface (operator controls their own machine) and is not a new security boundary violation; noting for completeness.


Open Findings Resolved by This PR

None of the SEC-* open findings are closed by this PR. The changes are additive diagnostics and a memory ceiling that address operational reliability, not the tracked security gaps.


Summary for Reviewers

The security-relevant files changed are all in the OOM diagnostics / memory budget stack. No trust state, attestation chain, encryption path, or routing gate logic is modified. The one item to verify before merge: confirm that provider.DisconnectDiagnostics() returns coordinator-owned state (not a value deserialized from the provider's WebSocket stream) to rule out provider-controlled log injection.


🔐 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: b08f9636c2

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

epochSeconds: Date().timeIntervalSince1970,
peakMemoryBytes: UInt64(max(0, MLX.Memory.peakMemory)),
availableBytesAtEvent: SystemMemory.availableBytes() ?? 0)
OOMDetector.writeMarker(marker)

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 Clear survived memory-pressure markers

When a provider receives a critical memory-pressure event but survives it, this writes a persistent marker that is never removed until the next launch; detectOnLaunch then reports the marker as a likely OOM regardless of whether the previous exit was a graceful stop or auto-update restart. In environments that briefly hit critical pressure and recover after clearCache(), this will create false oom telemetry/metrics on the next normal restart, so the marker needs a recovery/graceful-shutdown clear path or a validity check before emitting.

Useful? React with 👍 / 👎.

public static func defaultDiagnosticReportsURL(
home: URL = FileManager.default.homeDirectoryForCurrentUser
) -> URL {
home.appendingPathComponent("Library/Logs/DiagnosticReports")

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 Scan the system DiagnosticReports path for jetsam

For macOS jetsam reports, the files commonly land under the system DiagnosticReports tree (including Retired) rather than this per-user ~/Library directory, so a provider killed by jetsam can restart without detectOnLaunch seeing the JetsamEvent-*.ips report at all. This leaves the main coordinator-visible OOM signal missing for the exact kernel reports this detector is meant to recover; the launch scan should include /Library/Logs/DiagnosticReports and relevant subdirectories, not just the home-relative path.

Useful? React with 👍 / 👎.

let now = Date()
let since = OOMDetector.loadLastScan() ?? now.addingTimeInterval(-24 * 3600)
let findings = OOMDetector.detectOnLaunch(since: since)
OOMDetector.saveLastScan(now)

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 Persist the scan watermark after durable telemetry

This advances the crash-log watermark before the OOM findings are emitted, and TelemetryClient.shared.emit only buffers them in memory until a later flush. If the relaunched provider is killed or exits again before that flush/spill happens, the JetsamEvent has already been watermarked and will never be reported on a subsequent launch, hiding exactly the crash-loop signal this detector is supposed to recover. Move the watermark update until after the event is durably queued or keep it tied to the newest successfully reported file.

Useful? React with 👍 / 👎.

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.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 5 finding(s) (4 blocking)

  • 🔴 [CRITICAL] provider-swift/Sources/ProviderCore/Inference/BatchScheduler+Telemetry.swift:46-51 — SystemMemory.availableBytes() called on hot path during token budget calculation
    • Suggestion: Cache SystemMemory.availableBytes() result or move this calculation off the hot path - it likely involves system calls that can block
  • 🔴 [CRITICAL] provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift:21 — SystemMemory.availableBytes() called in memory snapshot closure
    • Suggestion: Cache the system memory reading or use async/background refresh - this system call can block and is called frequently during memory budget calculations
  • 🔵 [INFO] coordinator/api/provider.go:209-227 — DisconnectDiagnostics() called and ClassifyDisconnectReason computed on every read error
    • Suggestion: Only perform OOM classification when memory pressure is above a threshold to avoid unnecessary work on normal disconnects
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Diagnostics/OOMDetector.swift:176-205 — Directory scan with file I/O operations in scanDiagnosticReports
    • Suggestion: Move diagnostic report scanning to a background queue to avoid blocking the main execution path, especially during startup
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/ProviderLoop.swift:2111-2115 — OOM detection performs synchronous file I/O during startup
    • Suggestion: Move OOM detection to a background task after startup to avoid blocking the provider initialization

Type_diligence — 2 finding(s)

  • 🔵 [INFO] coordinator/api/provider.go:214-222 — map[string]any used for telemetry fields in emit call
    • Suggestion: Consider defining a typed struct for OOM telemetry fields with provider_id, memory_pressure, and in_flight fields instead of map[string]any
  • 🔵 [INFO] coordinator/api/telemetry_handlers.go:80-91 — String-keyed allowlist map could use typed constants
    • Suggestion: Define typed constants for telemetry field names to prevent typos and improve maintainability

Additive_complexity — 5 finding(s) (2 blocking)

  • 🔵 [INFO] coordinator/registry/disconnect_classify.go:1-45 — Single-purpose classification logic could be a simple function
    • Suggestion: Consider making ClassifyDisconnectReason a standalone function instead of creating a new package-level type system for what appears to be a single classification decision
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Diagnostics/MemoryPressureMonitor.swift:15-32 — Policy enum with single static method could be simplified
    • Suggestion: MemoryPressurePolicy.response(for:) could be a standalone function or method on MemoryPressureLevel itself, eliminating the policy enum wrapper
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Diagnostics/OOMDetector.swift:1-257 — Large enum with only static methods should be a module or struct
    • Suggestion: OOMDetector is a namespace enum with 250+ lines of static methods. Consider breaking into focused types (MarkerIO, ReportParser, Scanner) or using a struct/class for better organization and testability
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/MLXMemoryGuard.swift:62-89 — Complex once-only configuration with multiple injection points
    • Suggestion: configureOnce has 4 parameters (reserveBytes, physicalBytes, apply closure, log closure) plus environment variable handling. Consider a configuration struct or builder pattern to reduce parameter complexity
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift:7-32 — Memory snapshot logic duplicated between init methods
    • Suggestion: The default memory snapshot closure is duplicated between the public init and internal init. Extract to a static method or property to avoid repetition

12 finding(s) total, 6 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment on lines +46 to +51
let mlxFree = max(0, totalMemory - globalUsed)
// Clamp the MLX-only view to real OS-free RAM (other processes' usage),
// same as the load gate / GlobalKVCacheBudget; else we OOM on shared boxes.
let osAvailable = SystemMemory.availableBytes().map { Int(min($0, UInt64(Int.max))) } ?? Int.max
let realFree = min(mlxFree, osAvailable)
let availableHeadroom = max(0, realFree - osReserve - safetyMargin)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 [CRITICAL] ⚡ SystemMemory.availableBytes() called on hot path during token budget calculation

💡 Suggestion: Cache SystemMemory.availableBytes() result or move this calculation off the hot path - it likely involves system calls that can block

📊 Score: 4×4 = 16 · Category: blocking_io

active: UInt64(Memory.activeMemory),
cache: UInt64(Memory.cacheMemory)
cache: UInt64(Memory.cacheMemory),
// Real OS-free RAM; `.max` falls back to the MLX-only view.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 [CRITICAL] ⚡ SystemMemory.availableBytes() called in memory snapshot closure

💡 Suggestion: Cache the system memory reading or use async/background refresh - this system call can block and is called frequently during memory budget calculations

📊 Score: 4×4 = 16 · Category: blocking_io

Comment on lines +209 to +227

// An abrupt read_error under high last-known memory pressure is
// very likely a jetsam OOM (the kill leaves no other trace).
// Classify + surface it. See registry.ClassifyDisconnectReason.
if provider != nil {
memPressure, inFlight := provider.DisconnectDiagnostics()
if registry.ClassifyDisconnectReason(true, memPressure, inFlight) == registry.DisconnectReasonOOMSuspected {
if s.metrics != nil {
s.metrics.IncCounter("provider_oom_suspected_total")
}
s.ddIncr("provider.oom_suspected", nil)
s.emit(context.Background(), protocol.SeverityError, protocol.KindOOM,
"provider disconnected under memory pressure (suspected OOM)",
map[string]any{
"provider_id": providerID,
"memory_pressure": memPressure,
"in_flight": inFlight,
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ DisconnectDiagnostics() called and ClassifyDisconnectReason computed on every read error

💡 Suggestion: Only perform OOM classification when memory pressure is above a threshold to avoid unnecessary work on normal disconnects

📊 Score: 2×3 = 6 · Category: repeated_work

Comment on lines +176 to +205
public static func scanDiagnosticReports(
dir: URL,
processName: String,
since: Date,
fileManager: FileManager = .default
) -> [Finding] {
guard let entries = try? fileManager.contentsOfDirectory(
at: dir, includingPropertiesForKeys: [.contentModificationDateKey], options: [.skipsHiddenFiles])
else { return [] }

var findings: [Finding] = []
for url in entries {
let ext = url.pathExtension.lowercased()
guard ext == "ips" || ext == "panic" else { continue }
let name = url.lastPathComponent
let mtime = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate
if let mtime, mtime < since { continue }
guard let contents = try? String(contentsOf: url, encoding: .utf8) else { continue }

let isJetsam = name.hasPrefix("JetsamEvent")
var finding: Finding?
if isJetsam {
finding = parseJetsamReport(contents: contents, processName: processName)
} else {
finding = parseMemoryCrashReport(contents: contents, processName: processName)
}
if var f = finding {
f.reportName = name
f.epochSeconds = mtime?.timeIntervalSince1970
findings.append(f)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ Directory scan with file I/O operations in scanDiagnosticReports

💡 Suggestion: Move diagnostic report scanning to a background queue to avoid blocking the main execution path, especially during startup

📊 Score: 3×3 = 9 · Category: blocking_io

Comment on lines +2111 to +2115
private func startMemoryProtection() {
let now = Date()
let since = OOMDetector.loadLastScan() ?? now.addingTimeInterval(-24 * 3600)
let findings = OOMDetector.detectOnLaunch(since: since)
OOMDetector.saveLastScan(now)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ OOM detection performs synchronous file I/O during startup

💡 Suggestion: Move OOM detection to a background task after startup to avoid blocking the provider initialization

📊 Score: 3×4 = 12 · Category: blocking_io

Comment on lines +1 to +45
package registry

// Disconnect classification. A jetsam OOM kills the provider with an uncatchable
// SIGKILL, so its only trace is the WebSocket abruptly dying ("read_error"),
// bucketed identically to a graceful close. We can't prove an OOM, but the last
// heartbeat carries memory pressure and we know the in-flight count: an abrupt
// drop under high pressure with active inference is very likely a jetsam kill.

// DisconnectReason is the classified cause of a provider socket drop.
type DisconnectReason string

const (
DisconnectReasonNormal DisconnectReason = "disconnect" // graceful/unattributed
DisconnectReasonOOMSuspected DisconnectReason = "oom_suspected" // abrupt drop under memory pressure
)

// Precision-tuned: ≥0.90 pressure is on the edge regardless of load; active
// inference lowers the bar to 0.80 (decode is the allocation that tips it over).
const (
oomPressureHard = 0.90
oomPressureWithInFlight = 0.80
)

// ClassifyDisconnectReason: does an abrupt disconnect look like an OOM, from the
// last-known memory pressure + in-flight count? `abrupt` false = graceful close.
func ClassifyDisconnectReason(abrupt bool, memoryPressure float64, inFlight int) DisconnectReason {
if !abrupt {
return DisconnectReasonNormal
}
if memoryPressure >= oomPressureHard {
return DisconnectReasonOOMSuspected
}
if inFlight > 0 && memoryPressure >= oomPressureWithInFlight {
return DisconnectReasonOOMSuspected
}
return DisconnectReasonNormal
}

// DisconnectDiagnostics returns the signals used to classify a disconnect, read
// atomically under the provider lock.
func (p *Provider) DisconnectDiagnostics() (memoryPressure float64, inFlight int) {
p.mu.Lock()
defer p.mu.Unlock()
return p.SystemMetrics.MemoryPressure, len(p.pendingReqs)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Single-purpose classification logic could be a simple function

💡 Suggestion: Consider making ClassifyDisconnectReason a standalone function instead of creating a new package-level type system for what appears to be a single classification decision

📊 Score: 2×3 = 6 · Category: over-abstraction

Comment on lines +15 to +32
public var severity: TelemetrySeverity? // nil = don't emit telemetry
}

/// Pure policy: pressure level -> action. Tested in isolation.
public enum MemoryPressurePolicy {
public static func response(for level: MemoryPressureLevel) -> MemoryPressureResponse {
switch level {
case .normal:
return MemoryPressureResponse(clearCache: false, writeMarker: false, severity: nil)
case .warning:
// Reclaim cache; the live admission gate handles shedding. No telemetry
// — warning pressure is routine and would only add noise.
return MemoryPressureResponse(clearCache: true, writeMarker: false, severity: nil)
case .critical:
// Last chance before a possible jetsam kill: reclaim + mark for next launch.
return MemoryPressureResponse(clearCache: true, writeMarker: true, severity: .error)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Policy enum with single static method could be simplified

💡 Suggestion: MemoryPressurePolicy.response(for:) could be a standalone function or method on MemoryPressureLevel itself, eliminating the policy enum wrapper

📊 Score: 2×2 = 4 · Category: over-abstraction

Comment on lines +1 to +257
import Foundation

/// Make OOM crashes visible. A jetsam SIGKILL is uncatchable and flushes no
/// telemetry, so OOMs surface only as a coordinator-side "read_error" disconnect.
/// Two best-effort detectors recover the signal: (1) a pre-death marker written
/// on critical memory pressure that the NEXT launch reports; (2) a launch scan of
/// ~/Library/Logs/DiagnosticReports for JetsamEvent/EXC_RESOURCE reports naming
/// our process. Tolerant: a parse failure never crashes startup.
public enum OOMDetector {

// MARK: - Types

/// Marker written just before a suspected OOM death (on critical pressure).
public struct Marker: Codable, Equatable, Sendable {
public var pid: Int32
public var epochSeconds: Double
public var peakMemoryBytes: UInt64
public var availableBytesAtEvent: UInt64
public var modelId: String?

public init(pid: Int32, epochSeconds: Double, peakMemoryBytes: UInt64,
availableBytesAtEvent: UInt64, modelId: String? = nil) {
self.pid = pid
self.epochSeconds = epochSeconds
self.peakMemoryBytes = peakMemoryBytes
self.availableBytesAtEvent = availableBytesAtEvent
self.modelId = modelId
}
}

/// One detected OOM signal, ready to be turned into an `oom` telemetry event.
public struct Finding: Equatable, Sendable {
public enum Source: String, Sendable {
case memoryPressureMarker = "memory_pressure_marker"
case jetsamReport = "jetsam_report"
case memoryCrashReport = "memory_crash_report"
}
public var source: Source
public var message: String
public var reason: String?
public var peakMemoryBytes: UInt64?
public var reportName: String?
public var epochSeconds: Double?

public init(source: Source, message: String, reason: String? = nil,
peakMemoryBytes: UInt64? = nil, reportName: String? = nil,
epochSeconds: Double? = nil) {
self.source = source
self.message = message
self.reason = reason
self.peakMemoryBytes = peakMemoryBytes
self.reportName = reportName
self.epochSeconds = epochSeconds
}
}

// MARK: - Paths

/// ~/.darkbloom/ — stable + daemon-writable (the /usr/local install dir may not be).
public static func defaultMarkerURL(
home: URL = FileManager.default.homeDirectoryForCurrentUser
) -> URL {
home.appendingPathComponent(".darkbloom").appendingPathComponent("oom_marker.json")
}

public static func defaultDiagnosticReportsURL(
home: URL = FileManager.default.homeDirectoryForCurrentUser
) -> URL {
home.appendingPathComponent("Library/Logs/DiagnosticReports")
}

/// Last-scan watermark: only reports newer than this are emitted, so a
/// crashloop doesn't re-report the same JetsamEvent every launch.
public static func defaultLastScanURL(
home: URL = FileManager.default.homeDirectoryForCurrentUser
) -> URL {
home.appendingPathComponent(".darkbloom").appendingPathComponent("oom_last_scan")
}

public static func loadLastScan(at url: URL = defaultLastScanURL()) -> Date? {
guard let raw = try? String(contentsOf: url, encoding: .utf8),
let epoch = Double(raw.trimmingCharacters(in: .whitespacesAndNewlines))
else { return nil }
return Date(timeIntervalSince1970: epoch)
}

public static func saveLastScan(_ date: Date, at url: URL = defaultLastScanURL()) {
try? FileManager.default.createDirectory(
at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try? String(date.timeIntervalSince1970).write(to: url, atomically: true, encoding: .utf8)
}

// MARK: - Marker I/O

public static func writeMarker(_ marker: Marker, to url: URL = defaultMarkerURL()) {
do {
try FileManager.default.createDirectory(
at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
let data = try JSONEncoder().encode(marker)
try data.write(to: url, options: .atomic)
} catch {
// Best-effort: a marker we can't write just keeps this OOM invisible.
}
}

/// Read the marker and delete it (consume-once) so the same event isn't
/// reported on every subsequent launch.
@discardableResult
public static func readAndClearMarker(at url: URL = defaultMarkerURL()) -> Marker? {
guard let data = try? Data(contentsOf: url) else { return nil }
defer { try? FileManager.default.removeItem(at: url) }
return try? JSONDecoder().decode(Marker.self, from: data)
}

// MARK: - Pure parsers (.ips reports)

/// Parse a kernel `JetsamEvent-*.ips` (header line + JSON body with a
/// `processes` array); finding iff our process was killed. Pure + tolerant.
public static func parseJetsamReport(contents: String, processName: String) -> Finding? {
guard let body = jsonBody(from: contents) else { return nil }
let pageSize = (body["pageSize"] as? Int)
?? ((body["memoryStatus"] as? [String: Any])?["pageSize"] as? Int)
?? 16384
guard let processes = body["processes"] as? [[String: Any]] else { return nil }
let needle = processName.lowercased()
for proc in processes {
guard let name = proc["name"] as? String, name.lowercased().contains(needle) else { continue }
let rpages = (proc["rpages"] as? Int) ?? (proc["pages"] as? Int) ?? 0
let bytes = UInt64(max(0, rpages)) &* UInt64(max(0, pageSize))
let reason = (proc["reason"] as? String) ?? (proc["killDelta"] as? String)
return Finding(
source: .jetsamReport,
message: "jetsam killed \(name) (\(reason ?? "memory pressure"))",
reason: reason,
peakMemoryBytes: bytes > 0 ? bytes : nil)
}
return nil
}

/// Parse a process crash `.ips` for a memory kill: `EXC_RESOURCE` with a
/// MEMORY subtype, or a JETSAM termination namespace. Pure + tolerant.
public static func parseMemoryCrashReport(contents: String, processName: String) -> Finding? {
guard let header = jsonHeader(from: contents) else { return nil }
// Header names the app; only consider reports for our process.
let appName = (header["app_name"] as? String) ?? (header["procName"] as? String) ?? ""
guard appName.lowercased().contains(processName.lowercased()) else { return nil }
guard let body = jsonBody(from: contents) else { return nil }

if let exception = body["exception"] as? [String: Any] {
let type = (exception["type"] as? String) ?? ""
let subtype = (exception["subtype"] as? String) ?? ""
if type.contains("EXC_RESOURCE") && subtype.uppercased().contains("MEMORY") {
return Finding(
source: .memoryCrashReport,
message: "\(appName) hit memory resource limit (\(subtype))",
reason: subtype)
}
}
if let termination = body["termination"] as? [String: Any] {
let namespace = (termination["namespace"] as? String) ?? ""
if namespace.uppercased().contains("JETSAM") {
let reason = (termination["indicator"] as? String) ?? namespace
return Finding(
source: .memoryCrashReport,
message: "\(appName) terminated by jetsam (\(reason))",
reason: reason)
}
}
return nil
}

// MARK: - Launch detection (I/O)

/// Scan DiagnosticReports for OOM-relevant reports modified since `since`.
/// Best-effort; returns [] on any directory/read error.
public static func scanDiagnosticReports(
dir: URL,
processName: String,
since: Date,
fileManager: FileManager = .default
) -> [Finding] {
guard let entries = try? fileManager.contentsOfDirectory(
at: dir, includingPropertiesForKeys: [.contentModificationDateKey], options: [.skipsHiddenFiles])
else { return [] }

var findings: [Finding] = []
for url in entries {
let ext = url.pathExtension.lowercased()
guard ext == "ips" || ext == "panic" else { continue }
let name = url.lastPathComponent
let mtime = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate
if let mtime, mtime < since { continue }
guard let contents = try? String(contentsOf: url, encoding: .utf8) else { continue }

let isJetsam = name.hasPrefix("JetsamEvent")
var finding: Finding?
if isJetsam {
finding = parseJetsamReport(contents: contents, processName: processName)
} else {
finding = parseMemoryCrashReport(contents: contents, processName: processName)
}
if var f = finding {
f.reportName = name
f.epochSeconds = mtime?.timeIntervalSince1970
findings.append(f)
}
}
return findings
}

/// Full launch-time detection: consume any pre-death marker AND scan crash
/// logs since `since`. Returns all findings to emit as `oom` telemetry.
public static func detectOnLaunch(
markerURL: URL = defaultMarkerURL(),
diagnosticReportsDir: URL = defaultDiagnosticReportsURL(),
processName: String = "darkbloom",
since: Date,
fileManager: FileManager = .default
) -> [Finding] {
var findings: [Finding] = []
if let marker = readAndClearMarker(at: markerURL) {
findings.append(Finding(
source: .memoryPressureMarker,
message: "provider observed critical memory pressure before exit (likely OOM)",
peakMemoryBytes: marker.peakMemoryBytes > 0 ? marker.peakMemoryBytes : nil,
epochSeconds: marker.epochSeconds))
}
findings.append(contentsOf: scanDiagnosticReports(
dir: diagnosticReportsDir, processName: processName, since: since, fileManager: fileManager))
return findings
}

// MARK: - JSON helpers

/// The first JSON object in an `.ips` document (the one-line header).
static func jsonHeader(from contents: String) -> [String: Any]? {
guard let firstLine = contents.split(separator: "\n", maxSplits: 1, omittingEmptySubsequences: true).first,
let data = firstLine.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else { return nil }
return obj
}

/// The JSON body of an `.ips`: whole-file if it parses, else after line 1.
static func jsonBody(from contents: String) -> [String: Any]? {
if let data = contents.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
return obj
}
let parts = contents.split(separator: "\n", maxSplits: 1, omittingEmptySubsequences: true)
guard parts.count == 2,
let data = parts[1].data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else { return nil }
return obj
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] 🧩 Large enum with only static methods should be a module or struct

💡 Suggestion: OOMDetector is a namespace enum with 250+ lines of static methods. Consider breaking into focused types (MarkerIO, ReportParser, Scanner) or using a struct/class for better organization and testability

📊 Score: 3×4 = 12 · Category: over-abstraction

Comment on lines +62 to +89

/// Set the MLX ceiling once per process (idempotent). `apply` is injectable
/// for tests so they avoid touching real MLX globals.
@discardableResult
public static func configureOnce(
reserveBytes: UInt64? = nil,
physicalBytes: UInt64 = ProcessInfo.processInfo.physicalMemory,
apply: (Limits) -> Void = { limits in
Memory.memoryLimit = limits.memoryLimitBytes
Memory.cacheLimit = limits.cacheLimitBytes
},
log: ((Limits) -> Void)? = nil
) -> Limits? {
lock.lock()
if configured {
lock.unlock()
return nil
}
configured = true
lock.unlock()

let limits = recommendedLimits(
physicalBytes: physicalBytes,
reserveBytes: resolvedReserveBytes(explicit: reserveBytes))
apply(limits)
log?(limits)
return limits
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] 🧩 Complex once-only configuration with multiple injection points

💡 Suggestion: configureOnce has 4 parameters (reserveBytes, physicalBytes, apply closure, log closure) plus environment variable handling. Consider a configuration struct or builder pattern to reduce parameter complexity

📊 Score: 3×3 = 9 · Category: over-configuration

Comment on lines 7 to 32
@@ -17,15 +17,17 @@ public actor GlobalKVCacheBudget {
(
total: ProcessInfo.processInfo.physicalMemory,
active: UInt64(Memory.activeMemory),
cache: UInt64(Memory.cacheMemory)
cache: UInt64(Memory.cacheMemory),
// Real OS-free RAM; `.max` falls back to the MLX-only view.
systemAvailable: SystemMemory.availableBytes() ?? .max
)
}
}

init(
reserveBytes: UInt64 = 0,
safetyFactor: Double = 0.7,
memorySnapshot: @escaping @Sendable () -> (total: UInt64, active: UInt64, cache: UInt64)
memorySnapshot: @escaping @Sendable () -> (total: UInt64, active: UInt64, cache: UInt64, systemAvailable: UInt64)
) {
self.reserveBytes = reserveBytes

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Memory snapshot logic duplicated between init methods

💡 Suggestion: The default memory snapshot closure is duplicated between the public init and internal init. Extract to a static method or property to avoid repetition

📊 Score: 2×3 = 6 · Category: duplicate logic

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.

@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: 6d5d6e2cf2

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


// Pin MLX's memory ceiling below physical RAM (idempotent). MLX's default
// (1.5× working set, above RAM) otherwise allows a jetsam OOM. See MLXMemoryGuard.
MLXMemoryGuard.configureOnce(log: { limits in

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 Configure MLX limits before loading weights

In the provider load path, ProviderLoop.ensureModelLoaded calls loadModelContainer(from:) before constructing a BatchScheduler and reaching this call, so the first large MLX weight allocation has already happened with MLX's default memory limit. On boxes where loading the selected model is what pushes the process over physical RAM, this guard will not prevent the jetsam OOM it is meant to avoid; move the once-only configuration to startup or immediately before loadModelContainer.

Useful? React with 👍 / 👎.

Comment thread coordinator/api/provider.go Outdated
// Classify + surface it. See registry.ClassifyDisconnectReason.
if provider != nil {
memPressure, inFlight := provider.DisconnectDiagnostics()
if registry.ClassifyDisconnectReason(true, memPressure, inFlight) == registry.DisconnectReasonOOMSuspected {

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 Avoid classifying graceful socket closes as OOM

This always passes abrupt=true for every error in the CloseStatus(err) == -1 branch, but the Swift client deliberately closes the provider socket with .goingAway in shutdown() and refreshAPNsToken; nhooyr surfaces normal/going-away close frames as non-CloseError EOFs, so those graceful re-register/stop paths also land here. If the last heartbeat had memory pressure ≥0.9 (or ≥0.8 with an in-flight request), a routine close is emitted as oom_suspected, so distinguish graceful EOF/going-away closes from true abrupt disconnects before calling the classifier.

Useful? React with 👍 / 👎.

Comment on lines +228 to +229
findings.append(contentsOf: scanDiagnosticReports(
dir: diagnosticReportsDir, processName: processName, since: since, fileManager: fileManager))

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 Deduplicate marker and crash-report OOM findings

When a critical-pressure marker was written before a real jetsam kill, the next launch appends that marker finding and then unconditionally appends any JetsamEvent/memory crash report for the same death below. In the common case where both signals exist, startMemoryProtection emits two oom events for one crash, inflating Datadog/telemetry counts and any OOM alerting; coalesce findings by timestamp/PID or prefer the crash report over the marker.

Useful? React with 👍 / 👎.

guard let processes = body["processes"] as? [[String: Any]] else { return nil }
let needle = processName.lowercased()
for proc in processes {
guard let name = proc["name"] as? String, name.lowercased().contains(needle) else { continue }

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 Require jetsam to show darkbloom was killed

Jetsam reports include a process table for the memory-pressure event, but this returns an OOM finding for any entry whose name merely contains darkbloom, even when that entry has no kill reason and another process was actually jetsammed. On a Mac where the provider was just running during a Safari/WindowServer jetsam, the next launch would emit a provider oom event; require the report's killed/largest process or a kill reason for the darkbloom entry before returning.

Useful? React with 👍 / 👎.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 3 finding(s) (2 blocking)

  • 🔴 [CRITICAL] provider-swift/Sources/ProviderCore/Inference/BatchScheduler+Telemetry.swift:46-51 — SystemMemory.availableBytes() called on hot path during token budget calculation
    • Suggestion: Cache SystemMemory.availableBytes() result or move to background thread - this appears to be a system call that could block during memory pressure
  • 🔴 [CRITICAL] provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift:30-31 — SystemMemory.availableBytes() called in memory snapshot closure on admission path
    • Suggestion: Cache the system memory reading or use async/background refresh - this system call blocks the admission decision
  • 🔵 [INFO] coordinator/api/provider.go:209-227 — DisconnectDiagnostics() called under provider lock during error handling
    • Suggestion: Move the diagnostic collection outside the error path or cache the values to avoid lock contention during disconnects

Type_diligence — 1 finding(s) (1 blocking)

  • 🟡 [MEDIUM] coordinator/api/provider.go:213-226 — map[string]any used for telemetry fields in OOM detection
    • Suggestion: Consider defining a typed struct for OOM telemetry fields with provider_id, memory_pressure, and in_flight fields instead of map[string]any

Additive_complexity — 5 finding(s) (1 blocking)

  • 🔵 [INFO] coordinator/registry/disconnect_classify.go:1-45 — Single-purpose classification logic could be a simple function
    • Suggestion: Consider making ClassifyDisconnectReason a standalone function rather than creating a new package-level type system for what appears to be a single classification decision
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Diagnostics/MemoryPressureMonitor.swift:15-32 — Policy enum with single static method could be simplified
    • Suggestion: MemoryPressurePolicy could be a simple function rather than an enum with one static method - consider func memoryPressureResponse(for level: MemoryPressureLevel) -> MemoryPressureResponse
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Diagnostics/OOMDetector+CrashReports.swift:1-87 — Complex parsing logic in extension creates tight coupling
    • Suggestion: Move crash report parsing to a dedicated CrashReportParser type to reduce OOMDetector's responsibilities and improve testability
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift:8-16 — MemorySnapshot struct wraps simple tuple with minimal added value
    • Suggestion: Consider using a simple tuple return type instead of a dedicated struct for the four memory values, or add meaningful methods to justify the struct
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Diagnostics/OOMDetector.swift:32-54 — Finding struct has many optional fields suggesting unclear responsibility
    • Suggestion: Consider splitting Finding into specific types (MarkerFinding, CrashReportFinding) or use a discriminated union to clarify which fields are valid for each source type

9 finding(s) total, 4 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment on lines +46 to +51
let mlxFree = max(0, totalMemory - globalUsed)
// Clamp the MLX-only view to real OS-free RAM (other processes' usage),
// same as the load gate / GlobalKVCacheBudget; else we OOM on shared boxes.
let osAvailable = SystemMemory.availableBytes().map { Int(min($0, UInt64(Int.max))) } ?? Int.max
let realFree = min(mlxFree, osAvailable)
let availableHeadroom = max(0, realFree - osReserve - safetyMargin)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 [CRITICAL] ⚡ SystemMemory.availableBytes() called on hot path during token budget calculation

💡 Suggestion: Cache SystemMemory.availableBytes() result or move to background thread - this appears to be a system call that could block during memory pressure

📊 Score: 4×4 = 16 · Category: blocking_io

Comment on lines +30 to +31
// Real OS-free RAM; `.max` falls back to the MLX-only view.
systemAvailable: SystemMemory.availableBytes() ?? .max)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 [CRITICAL] ⚡ SystemMemory.availableBytes() called in memory snapshot closure on admission path

💡 Suggestion: Cache the system memory reading or use async/background refresh - this system call blocks the admission decision

📊 Score: 4×4 = 16 · Category: blocking_io

Comment on lines +209 to +227

// An abrupt read_error under high last-known memory pressure is
// very likely a jetsam OOM (the kill leaves no other trace).
// Classify + surface it. See registry.ClassifyDisconnectReason.
if provider != nil {
memPressure, inFlight := provider.DisconnectDiagnostics()
if registry.ClassifyDisconnectReason(true, memPressure, inFlight) == registry.DisconnectReasonOOMSuspected {
if s.metrics != nil {
s.metrics.IncCounter("provider_oom_suspected_total")
}
s.ddIncr("provider.oom_suspected", nil)
s.emit(context.Background(), protocol.SeverityError, protocol.KindOOM,
"provider disconnected under memory pressure (suspected OOM)",
map[string]any{
"provider_id": providerID,
"memory_pressure": memPressure,
"in_flight": inFlight,
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ DisconnectDiagnostics() called under provider lock during error handling

💡 Suggestion: Move the diagnostic collection outside the error path or cache the values to avoid lock contention during disconnects

📊 Score: 2×3 = 6 · Category: repeated_work

Comment on lines +213 to +226
if provider != nil {
memPressure, inFlight := provider.DisconnectDiagnostics()
if registry.ClassifyDisconnectReason(true, memPressure, inFlight) == registry.DisconnectReasonOOMSuspected {
if s.metrics != nil {
s.metrics.IncCounter("provider_oom_suspected_total")
}
s.ddIncr("provider.oom_suspected", nil)
s.emit(context.Background(), protocol.SeverityError, protocol.KindOOM,
"provider disconnected under memory pressure (suspected OOM)",
map[string]any{
"provider_id": providerID,
"memory_pressure": memPressure,
"in_flight": inFlight,
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] 🏷️ map[string]any used for telemetry fields in OOM detection

💡 Suggestion: Consider defining a typed struct for OOM telemetry fields with provider_id, memory_pressure, and in_flight fields instead of map[string]any

📊 Score: 3×3 = 9 · Category: map[string]any usage

Comment on lines +1 to +45
package registry

// Disconnect classification. A jetsam OOM kills the provider with an uncatchable
// SIGKILL, so its only trace is the WebSocket abruptly dying ("read_error"),
// bucketed identically to a graceful close. We can't prove an OOM, but the last
// heartbeat carries memory pressure and we know the in-flight count: an abrupt
// drop under high pressure with active inference is very likely a jetsam kill.

// DisconnectReason is the classified cause of a provider socket drop.
type DisconnectReason string

const (
DisconnectReasonNormal DisconnectReason = "disconnect" // graceful/unattributed
DisconnectReasonOOMSuspected DisconnectReason = "oom_suspected" // abrupt drop under memory pressure
)

// Precision-tuned: ≥0.90 pressure is on the edge regardless of load; active
// inference lowers the bar to 0.80 (decode is the allocation that tips it over).
const (
oomPressureHard = 0.90
oomPressureWithInFlight = 0.80
)

// ClassifyDisconnectReason: does an abrupt disconnect look like an OOM, from the
// last-known memory pressure + in-flight count? `abrupt` false = graceful close.
func ClassifyDisconnectReason(abrupt bool, memoryPressure float64, inFlight int) DisconnectReason {
if !abrupt {
return DisconnectReasonNormal
}
if memoryPressure >= oomPressureHard {
return DisconnectReasonOOMSuspected
}
if inFlight > 0 && memoryPressure >= oomPressureWithInFlight {
return DisconnectReasonOOMSuspected
}
return DisconnectReasonNormal
}

// DisconnectDiagnostics returns the signals used to classify a disconnect, read
// atomically under the provider lock.
func (p *Provider) DisconnectDiagnostics() (memoryPressure float64, inFlight int) {
p.mu.Lock()
defer p.mu.Unlock()
return p.SystemMetrics.MemoryPressure, len(p.pendingReqs)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Single-purpose classification logic could be a simple function

💡 Suggestion: Consider making ClassifyDisconnectReason a standalone function rather than creating a new package-level type system for what appears to be a single classification decision

📊 Score: 2×3 = 6 · Category: over-abstraction

Comment on lines +15 to +32
public var severity: TelemetrySeverity? // nil = don't emit telemetry
}

/// Pure policy: pressure level -> action. Tested in isolation.
public enum MemoryPressurePolicy {
public static func response(for level: MemoryPressureLevel) -> MemoryPressureResponse {
switch level {
case .normal:
return MemoryPressureResponse(clearCache: false, writeMarker: false, severity: nil)
case .warning:
// Reclaim cache; the live admission gate handles shedding. No telemetry
// — warning pressure is routine and would only add noise.
return MemoryPressureResponse(clearCache: true, writeMarker: false, severity: nil)
case .critical:
// Last chance before a possible jetsam kill: reclaim + mark for next launch.
return MemoryPressureResponse(clearCache: true, writeMarker: true, severity: .error)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Policy enum with single static method could be simplified

💡 Suggestion: MemoryPressurePolicy could be a simple function rather than an enum with one static method - consider func memoryPressureResponse(for level: MemoryPressureLevel) -> MemoryPressureResponse

📊 Score: 2×2 = 4 · Category: over-abstraction

Comment on lines +1 to +87
import Foundation

/// Pure `.ips` crash-report parsing for OOM detection. Split from OOMDetector
/// (which owns marker I/O + directory scanning) so the parsing logic — the
/// bulk of the test surface — stands alone. All functions are pure + tolerant:
/// malformed input returns nil, never throws.
extension OOMDetector {

/// Parse a kernel `JetsamEvent-*.ips` (header line + JSON body with a
/// `processes` array); finding iff our process was killed.
public static func parseJetsamReport(contents: String, processName: String) -> Finding? {
guard let body = jsonBody(from: contents) else { return nil }
let pageSize = (body["pageSize"] as? Int)
?? ((body["memoryStatus"] as? [String: Any])?["pageSize"] as? Int)
?? 16384
guard let processes = body["processes"] as? [[String: Any]] else { return nil }
let needle = processName.lowercased()
for proc in processes {
guard let name = proc["name"] as? String, name.lowercased().contains(needle) else { continue }
let rpages = (proc["rpages"] as? Int) ?? (proc["pages"] as? Int) ?? 0
let bytes = UInt64(max(0, rpages)) &* UInt64(max(0, pageSize))
let reason = (proc["reason"] as? String) ?? (proc["killDelta"] as? String)
return Finding(
source: .jetsamReport,
message: "jetsam killed \(name) (\(reason ?? "memory pressure"))",
reason: reason,
peakMemoryBytes: bytes > 0 ? bytes : nil)
}
return nil
}

/// Parse a process crash `.ips` for a memory kill: `EXC_RESOURCE` with a
/// MEMORY subtype, or a JETSAM termination namespace.
public static func parseMemoryCrashReport(contents: String, processName: String) -> Finding? {
guard let header = jsonHeader(from: contents) else { return nil }
let appName = (header["app_name"] as? String) ?? (header["procName"] as? String) ?? ""
guard appName.lowercased().contains(processName.lowercased()) else { return nil }
guard let body = jsonBody(from: contents) else { return nil }

if let exception = body["exception"] as? [String: Any] {
let type = (exception["type"] as? String) ?? ""
let subtype = (exception["subtype"] as? String) ?? ""
if type.contains("EXC_RESOURCE") && subtype.uppercased().contains("MEMORY") {
return Finding(
source: .memoryCrashReport,
message: "\(appName) hit memory resource limit (\(subtype))",
reason: subtype)
}
}
if let termination = body["termination"] as? [String: Any] {
let namespace = (termination["namespace"] as? String) ?? ""
if namespace.uppercased().contains("JETSAM") {
let reason = (termination["indicator"] as? String) ?? namespace
return Finding(
source: .memoryCrashReport,
message: "\(appName) terminated by jetsam (\(reason))",
reason: reason)
}
}
return nil
}

// MARK: - JSON helpers

/// The first JSON object in an `.ips` document (the one-line header).
static func jsonHeader(from contents: String) -> [String: Any]? {
guard let firstLine = contents.split(separator: "\n", maxSplits: 1, omittingEmptySubsequences: true).first,
let data = firstLine.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else { return nil }
return obj
}

/// The JSON body of an `.ips`: whole-file if it parses, else after line 1.
static func jsonBody(from contents: String) -> [String: Any]? {
if let data = contents.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
return obj
}
let parts = contents.split(separator: "\n", maxSplits: 1, omittingEmptySubsequences: true)
guard parts.count == 2,
let data = parts[1].data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else { return nil }
return obj
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] 🧩 Complex parsing logic in extension creates tight coupling

💡 Suggestion: Move crash report parsing to a dedicated CrashReportParser type to reduce OOMDetector's responsibilities and improve testability

📊 Score: 3×3 = 9 · Category: misplaced-responsibility

Comment on lines +8 to +16
/// The four memory figures an admission decision needs: physical total, MLX's
/// own active + cache, and the OS's real free RAM (the cross-process view).
public struct MemorySnapshot: Sendable {
public var total: UInt64
public var active: UInt64
public var cache: UInt64
public var systemAvailable: UInt64
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 MemorySnapshot struct wraps simple tuple with minimal added value

💡 Suggestion: Consider using a simple tuple return type instead of a dedicated struct for the four memory values, or add meaningful methods to justify the struct

📊 Score: 2×2 = 4 · Category: over-abstraction

Comment on lines +32 to +54
public struct Finding: Equatable, Sendable {
public enum Source: String, Sendable {
case memoryPressureMarker = "memory_pressure_marker"
case jetsamReport = "jetsam_report"
case memoryCrashReport = "memory_crash_report"
}
public var source: Source
public var message: String
public var reason: String?
public var peakMemoryBytes: UInt64?
public var reportName: String?
public var epochSeconds: Double?

public init(source: Source, message: String, reason: String? = nil,
peakMemoryBytes: UInt64? = nil, reportName: String? = nil,
epochSeconds: Double? = nil) {
self.source = source
self.message = message
self.reason = reason
self.peakMemoryBytes = peakMemoryBytes
self.reportName = reportName
self.epochSeconds = epochSeconds
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Finding struct has many optional fields suggesting unclear responsibility

💡 Suggestion: Consider splitting Finding into specific types (MarkerFinding, CrashReportFinding) or use a discriminated union to clarify which fields are valid for each source type

📊 Score: 2×3 = 6 · Category: over-abstraction

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

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 5 finding(s) (2 blocking)

  • 🔴 [CRITICAL] provider-swift/Sources/ProviderCore/Inference/BatchScheduler+Telemetry.swift:43-51 — SystemMemory.availableBytes() called on hot path during token budget calculation
    • Suggestion: Cache SystemMemory.availableBytes() result or move to background thread - this appears to be called for every batch scheduling decision
  • 🔴 [CRITICAL] provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift:88-96 — SystemMemory.availableBytes() called in availableReservationBytes() on admission path
    • Suggestion: Cache the OS memory reading or use async background updates - this is called for every KV cache reservation request
  • 🔵 [INFO] coordinator/api/provider.go:206-232 — Memory pressure classification logic runs on every read error
    • Suggestion: Consider caching the classification result or moving the logic outside the hot error path
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Diagnostics/OOMDetector.swift:176-204 — Directory scanning and file I/O in detectOnLaunch without bounds
    • Suggestion: Add limits on number of files scanned and use async I/O to avoid blocking startup
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Diagnostics/OOMDetector+CrashReports.swift:17-38 — Linear search through processes array in parseJetsamReport
    • Suggestion: For large process lists, consider early termination or indexing if this becomes a bottleneck

Type_diligence — 2 finding(s)

  • 🔵 [INFO] coordinator/api/provider.go:219-225 — map[string]any used for telemetry fields in OOM detection
    • Suggestion: Consider defining a typed struct for OOM telemetry fields with provider_id, memory_pressure, and in_flight fields instead of map[string]any
  • 🔵 [INFO] coordinator/api/telemetry_handlers.go:83-91 — Field allowlist uses map[string]struct{} pattern for telemetry validation
    • Suggestion: This is a legitimate use of map[string]struct{} for set membership - no change needed

Additive_complexity — 6 finding(s) (2 blocking)

  • 🔵 [INFO] coordinator/registry/disconnect_classify.go:1-45 — new file with single-use classification logic could be simpler
    • Suggestion: consider inlining ClassifyDisconnectReason into the single call site in api/provider.go rather than creating a separate package-level function
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Diagnostics/MemoryPressureMonitor.swift:37-88 — complex monitor class with dependency injection for simple pressure handling
    • Suggestion: consider a simpler approach with direct MLX.Memory.clearCache() calls and inline telemetry emission rather than injected closures
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Diagnostics/OOMDetector+CrashReports.swift:1-96 — crash report parsing split into separate file for testability
    • Suggestion: consider keeping parsing logic in main OOMDetector file unless the split provides clear maintenance benefits
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Diagnostics/OOMDetector.swift:1-205 — large enum with multiple detection strategies and file I/O operations
    • Suggestion: consider breaking into smaller focused components: MarkerIO, CrashScanner, and a coordinator rather than one large enum
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/MLXMemoryGuard.swift:1-97 — memory guard with environment variable override and multiple configuration paths
    • Suggestion: consider simplifying to just explicit configuration or default, removing environment variable complexity
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/ProviderLoop.swift:2109-2165 — memory protection logic embedded in main provider loop
    • Suggestion: extract memory protection setup into a dedicated component that ProviderLoop can compose rather than implementing directly

13 finding(s) total, 4 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment on lines 43 to +51
let osReserve = 4 * 1024 * 1024 * 1024
let safetyMargin = totalMemory / 10
let globalUsed = Int(MLX.GPU.activeMemory) + Int(MLX.GPU.cacheMemory)
let availableHeadroom = max(0, totalMemory - osReserve - safetyMargin - globalUsed)
let mlxFree = max(0, totalMemory - globalUsed)
// Clamp the MLX-only view to real OS-free RAM (other processes' usage),
// same as the load gate / GlobalKVCacheBudget; else we OOM on shared boxes.
let osAvailable = SystemMemory.availableBytes().map { Int(min($0, UInt64(Int.max))) } ?? Int.max
let realFree = min(mlxFree, osAvailable)
let availableHeadroom = max(0, realFree - osReserve - safetyMargin)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 [CRITICAL] ⚡ SystemMemory.availableBytes() called on hot path during token budget calculation

💡 Suggestion: Cache SystemMemory.availableBytes() result or move to background thread - this appears to be called for every batch scheduling decision

📊 Score: 4×4 = 16 · Category: blocking_io

Comment on lines 88 to +96
private func availableReservationBytes() -> UInt64 {
let (total, active, cache) = memorySnapshot()
let usedBeforeReservations = Self.saturatingAdd(active, cache, reserveBytes)
let usable = total > usedBeforeReservations ? total - usedBeforeReservations : 0
let snap = memorySnapshot()
let mlxUsed = Self.saturatingAdd(snap.active, snap.cache)
let mlxFree = snap.total > mlxUsed ? snap.total - mlxUsed : 0
// Clamp the MLX-only view (blind to other processes) to real OS-free RAM,
// mirroring the load gate (ModelLoadAdmission.freeForLoadGb). Without it
// the runtime admits against memory other apps hold → jetsam OOM.
let realFree = min(mlxFree, snap.systemAvailable)
let usable = realFree > reserveBytes ? realFree - reserveBytes : 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 [CRITICAL] ⚡ SystemMemory.availableBytes() called in availableReservationBytes() on admission path

💡 Suggestion: Cache the OS memory reading or use async background updates - this is called for every KV cache reservation request

📊 Score: 4×4 = 16 · Category: blocking_io

Comment on lines 206 to +232
)
}
s.ddIncr("ws.disconnects", []string{"reason:read_error"})

// An abrupt read_error under high last-known memory pressure with
// active inference is very likely a jetsam OOM (the kill leaves no
// other trace). Require in-flight > 0: a graceful shutdown/update
// drains first (and may surface here as a frame-less EOF rather
// than a clean close), so gating on in-flight avoids misreading a
// drained going-away close as OOM. Idle-box kills are recovered by
// the provider's crash-log scrape instead.
if provider != nil {
memPressure, inFlight := provider.DisconnectDiagnostics()
if inFlight > 0 && registry.ClassifyDisconnectReason(true, memPressure, inFlight) == registry.DisconnectReasonOOMSuspected {
if s.metrics != nil {
s.metrics.IncCounter("provider_oom_suspected_total")
}
s.ddIncr("provider.oom_suspected", nil)
s.emit(context.Background(), protocol.SeverityError, protocol.KindOOM,
"provider disconnected under memory pressure (suspected OOM)",
map[string]any{
"provider_id": providerID,
"memory_pressure": memPressure,
"in_flight": inFlight,
})
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ Memory pressure classification logic runs on every read error

💡 Suggestion: Consider caching the classification result or moving the logic outside the hot error path

📊 Score: 2×3 = 6 · Category: repeated_work

Comment on lines +176 to +204
diagnosticReportsDirs: [URL] = defaultDiagnosticReportsDirs(),
processName: String = "darkbloom",
since: Date,
fileManager: FileManager = .default
) -> [Finding] {
// Crash reports are the authoritative signal. Scan every candidate dir
// (user + system + Retired); dedupe by report filename across dirs.
var seenReports = Set<String>()
var crashFindings: [Finding] = []
for dir in diagnosticReportsDirs {
for f in scanDiagnosticReports(dir: dir, processName: processName, since: since, fileManager: fileManager) {
if let name = f.reportName, !seenReports.insert(name).inserted { continue }
crashFindings.append(f)
}
}

// Always consume the marker (so it never lingers), but only surface it
// when no crash report already attributes this death — otherwise one OOM
// would emit twice (marker + JetsamEvent).
let marker = readAndClearMarker(at: markerURL)
if crashFindings.isEmpty, let marker {
return [Finding(
source: .memoryPressureMarker,
message: "provider observed critical memory pressure before exit (likely OOM)",
peakMemoryBytes: marker.peakMemoryBytes > 0 ? marker.peakMemoryBytes : nil,
epochSeconds: marker.epochSeconds)]
}
return crashFindings
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ Directory scanning and file I/O in detectOnLaunch without bounds

💡 Suggestion: Add limits on number of files scanned and use async I/O to avoid blocking startup

📊 Score: 3×2 = 6 · Category: blocking_io

Comment on lines +17 to +38
public static func parseJetsamReport(contents: String, processName: String) -> Finding? {
guard let body = jsonBody(from: contents) else { return nil }
let pageSize = (body["pageSize"] as? Int)
?? ((body["memoryStatus"] as? [String: Any])?["pageSize"] as? Int)
?? 16384
guard let processes = body["processes"] as? [[String: Any]] else { return nil }
let needle = processName.lowercased()
let largest = (body["largestProcess"] as? String)?.lowercased()
for proc in processes {
guard let name = proc["name"] as? String, name.lowercased().contains(needle) else { continue }
let reason = (proc["reason"] as? String) ?? (proc["killDelta"] as? String)
let wasKilled = !(reason ?? "").isEmpty || (largest.map { name.lowercased().contains($0) } ?? false)
guard wasKilled else { continue } // present in the table but not the victim
let rpages = (proc["rpages"] as? Int) ?? (proc["pages"] as? Int) ?? 0
let bytes = UInt64(max(0, rpages)) &* UInt64(max(0, pageSize))
return Finding(
source: .jetsamReport,
message: "jetsam killed \(name) (\(reason ?? "memory pressure"))",
reason: reason,
peakMemoryBytes: bytes > 0 ? bytes : nil)
}
return nil

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ Linear search through processes array in parseJetsamReport

💡 Suggestion: For large process lists, consider early termination or indexing if this becomes a bottleneck

📊 Score: 2×3 = 6 · Category: inefficient_data_structures

Comment on lines +37 to +88
/// real DispatchSource.
public final class MemoryPressureMonitor: @unchecked Sendable {
private let clearCache: @Sendable () -> Void
private let writeMarker: @Sendable (MemoryPressureLevel) -> Void
private let emit: @Sendable (MemoryPressureLevel, TelemetrySeverity) -> Void
private let queue: DispatchQueue
private var source: DispatchSourceMemoryPressure?

public init(
queue: DispatchQueue = DispatchQueue(label: "dev.darkbloom.memory-pressure"),
clearCache: @escaping @Sendable () -> Void,
writeMarker: @escaping @Sendable (MemoryPressureLevel) -> Void,
emit: @escaping @Sendable (MemoryPressureLevel, TelemetrySeverity) -> Void
) {
self.queue = queue
self.clearCache = clearCache
self.writeMarker = writeMarker
self.emit = emit
}

public func start() {
let src = DispatchSource.makeMemoryPressureSource(eventMask: [.warning, .critical], queue: queue)
src.setEventHandler { [weak self] in
guard let self, let data = self.source?.data else { return }
self.handle(Self.level(from: data))
}
self.source = src
src.activate()
}

public func cancel() {
source?.cancel()
source = nil
}

/// Testable core: apply the policy for a level and invoke the injected
/// actions. Safe to call directly from tests.
public func handle(_ level: MemoryPressureLevel) {
let response = MemoryPressurePolicy.response(for: level)
if response.clearCache { clearCache() }
if response.writeMarker { writeMarker(level) }
if let severity = response.severity { emit(level, severity) }
}

/// Map a DispatchSource.MemoryPressureEvent bitmask to our coarse level.
/// Critical dominates warning when both bits are set.
static func level(from data: DispatchSource.MemoryPressureEvent) -> MemoryPressureLevel {
if data.contains(.critical) { return .critical }
if data.contains(.warning) { return .warning }
return .normal
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] 🧩 complex monitor class with dependency injection for simple pressure handling

💡 Suggestion: consider a simpler approach with direct MLX.Memory.clearCache() calls and inline telemetry emission rather than injected closures

📊 Score: 3×4 = 12 · Category: over-abstraction

Comment on lines +1 to +96
import Foundation

/// Pure `.ips` crash-report parsing for OOM detection. Split from OOMDetector
/// (which owns marker I/O + directory scanning) so the parsing logic — the
/// bulk of the test surface — stands alone. All functions are pure + tolerant:
/// malformed input returns nil, never throws.
extension OOMDetector {

/// Parse a kernel `JetsamEvent-*.ips` (header line + JSON body with a
/// `processes` array); finding iff OUR process was the one jetsam killed.
///
/// A JetsamEvent lists the whole process table at the pressure event, not
/// just the victim — so merely matching the name would flag a provider OOM
/// any time darkbloom was resident during someone else's jetsam. Require a
/// kill signal on our entry: a `reason` (carried by jetsammed processes) or
/// being named the report's `largestProcess`.
public static func parseJetsamReport(contents: String, processName: String) -> Finding? {
guard let body = jsonBody(from: contents) else { return nil }
let pageSize = (body["pageSize"] as? Int)
?? ((body["memoryStatus"] as? [String: Any])?["pageSize"] as? Int)
?? 16384
guard let processes = body["processes"] as? [[String: Any]] else { return nil }
let needle = processName.lowercased()
let largest = (body["largestProcess"] as? String)?.lowercased()
for proc in processes {
guard let name = proc["name"] as? String, name.lowercased().contains(needle) else { continue }
let reason = (proc["reason"] as? String) ?? (proc["killDelta"] as? String)
let wasKilled = !(reason ?? "").isEmpty || (largest.map { name.lowercased().contains($0) } ?? false)
guard wasKilled else { continue } // present in the table but not the victim
let rpages = (proc["rpages"] as? Int) ?? (proc["pages"] as? Int) ?? 0
let bytes = UInt64(max(0, rpages)) &* UInt64(max(0, pageSize))
return Finding(
source: .jetsamReport,
message: "jetsam killed \(name) (\(reason ?? "memory pressure"))",
reason: reason,
peakMemoryBytes: bytes > 0 ? bytes : nil)
}
return nil
}

/// Parse a process crash `.ips` for a memory kill: `EXC_RESOURCE` with a
/// MEMORY subtype, or a JETSAM termination namespace.
public static func parseMemoryCrashReport(contents: String, processName: String) -> Finding? {
guard let header = jsonHeader(from: contents) else { return nil }
let appName = (header["app_name"] as? String) ?? (header["procName"] as? String) ?? ""
guard appName.lowercased().contains(processName.lowercased()) else { return nil }
guard let body = jsonBody(from: contents) else { return nil }

if let exception = body["exception"] as? [String: Any] {
let type = (exception["type"] as? String) ?? ""
let subtype = (exception["subtype"] as? String) ?? ""
if type.contains("EXC_RESOURCE") && subtype.uppercased().contains("MEMORY") {
return Finding(
source: .memoryCrashReport,
message: "\(appName) hit memory resource limit (\(subtype))",
reason: subtype)
}
}
if let termination = body["termination"] as? [String: Any] {
let namespace = (termination["namespace"] as? String) ?? ""
if namespace.uppercased().contains("JETSAM") {
let reason = (termination["indicator"] as? String) ?? namespace
return Finding(
source: .memoryCrashReport,
message: "\(appName) terminated by jetsam (\(reason))",
reason: reason)
}
}
return nil
}

// MARK: - JSON helpers

/// The first JSON object in an `.ips` document (the one-line header).
static func jsonHeader(from contents: String) -> [String: Any]? {
guard let firstLine = contents.split(separator: "\n", maxSplits: 1, omittingEmptySubsequences: true).first,
let data = firstLine.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else { return nil }
return obj
}

/// The JSON body of an `.ips`: whole-file if it parses, else after line 1.
static func jsonBody(from contents: String) -> [String: Any]? {
if let data = contents.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
return obj
}
let parts = contents.split(separator: "\n", maxSplits: 1, omittingEmptySubsequences: true)
guard parts.count == 2,
let data = parts[1].data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else { return nil }
return obj
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 crash report parsing split into separate file for testability

💡 Suggestion: consider keeping parsing logic in main OOMDetector file unless the split provides clear maintenance benefits

📊 Score: 2×3 = 6 · Category: over-abstraction

Comment on lines +1 to +205
import Foundation

/// Make OOM crashes visible. A jetsam SIGKILL is uncatchable and flushes no
/// telemetry, so OOMs surface only as a coordinator-side "read_error" disconnect.
/// Two best-effort detectors recover the signal: (1) a pre-death marker written
/// on critical memory pressure that the NEXT launch reports; (2) a launch scan of
/// ~/Library/Logs/DiagnosticReports for JetsamEvent/EXC_RESOURCE reports naming
/// our process. Tolerant: a parse failure never crashes startup.
public enum OOMDetector {

// MARK: - Types

/// Marker written just before a suspected OOM death (on critical pressure).
public struct Marker: Codable, Equatable, Sendable {
public var pid: Int32
public var epochSeconds: Double
public var peakMemoryBytes: UInt64
public var availableBytesAtEvent: UInt64
public var modelId: String?

public init(pid: Int32, epochSeconds: Double, peakMemoryBytes: UInt64,
availableBytesAtEvent: UInt64, modelId: String? = nil) {
self.pid = pid
self.epochSeconds = epochSeconds
self.peakMemoryBytes = peakMemoryBytes
self.availableBytesAtEvent = availableBytesAtEvent
self.modelId = modelId
}
}

/// One detected OOM signal, ready to be turned into an `oom` telemetry event.
public struct Finding: Equatable, Sendable {
public enum Source: String, Sendable {
case memoryPressureMarker = "memory_pressure_marker"
case jetsamReport = "jetsam_report"
case memoryCrashReport = "memory_crash_report"
}
public var source: Source
public var message: String
public var reason: String?
public var peakMemoryBytes: UInt64?
public var reportName: String?
public var epochSeconds: Double?

public init(source: Source, message: String, reason: String? = nil,
peakMemoryBytes: UInt64? = nil, reportName: String? = nil,
epochSeconds: Double? = nil) {
self.source = source
self.message = message
self.reason = reason
self.peakMemoryBytes = peakMemoryBytes
self.reportName = reportName
self.epochSeconds = epochSeconds
}
}

// MARK: - Paths

/// ~/.darkbloom/ — stable + daemon-writable (the /usr/local install dir may not be).
public static func defaultMarkerURL(
home: URL = FileManager.default.homeDirectoryForCurrentUser
) -> URL {
home.appendingPathComponent(".darkbloom").appendingPathComponent("oom_marker.json")
}

/// Where macOS writes crash/jetsam reports. KERNEL jetsam reports
/// (`JetsamEvent-*.ips`) land in the SYSTEM tree `/Library/Logs/...`, not the
/// per-user `~/Library/...` — so we must scan both, plus each `Retired`
/// subdir where older reports are moved. Missing/unreadable dirs are skipped.
public static func defaultDiagnosticReportsDirs(
home: URL = FileManager.default.homeDirectoryForCurrentUser
) -> [URL] {
let bases = [
home.appendingPathComponent("Library/Logs/DiagnosticReports"),
URL(fileURLWithPath: "/Library/Logs/DiagnosticReports"),
]
return bases + bases.map { $0.appendingPathComponent("Retired") }
}

/// Last-scan watermark: only reports newer than this are emitted, so a
/// crashloop doesn't re-report the same JetsamEvent every launch.
public static func defaultLastScanURL(
home: URL = FileManager.default.homeDirectoryForCurrentUser
) -> URL {
home.appendingPathComponent(".darkbloom").appendingPathComponent("oom_last_scan")
}

public static func loadLastScan(at url: URL = defaultLastScanURL()) -> Date? {
guard let raw = try? String(contentsOf: url, encoding: .utf8),
let epoch = Double(raw.trimmingCharacters(in: .whitespacesAndNewlines))
else { return nil }
return Date(timeIntervalSince1970: epoch)
}

public static func saveLastScan(_ date: Date, at url: URL = defaultLastScanURL()) {
try? FileManager.default.createDirectory(
at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try? String(date.timeIntervalSince1970).write(to: url, atomically: true, encoding: .utf8)
}

// MARK: - Marker I/O

public static func writeMarker(_ marker: Marker, to url: URL = defaultMarkerURL()) {
do {
try FileManager.default.createDirectory(
at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
let data = try JSONEncoder().encode(marker)
try data.write(to: url, options: .atomic)
} catch {
// Best-effort: a marker we can't write just keeps this OOM invisible.
}
}

/// Read the marker and delete it (consume-once) so the same event isn't
/// reported on every subsequent launch.
@discardableResult
public static func readAndClearMarker(at url: URL = defaultMarkerURL()) -> Marker? {
guard let data = try? Data(contentsOf: url) else { return nil }
defer { try? FileManager.default.removeItem(at: url) }
return try? JSONDecoder().decode(Marker.self, from: data)
}

/// Delete the marker on a GRACEFUL exit. The marker is written on critical
/// pressure; if the provider then survives and stops/updates cleanly, this
/// removes it so the next normal launch doesn't misreport a recovered
/// pressure spike as an OOM. A jetsam SIGKILL bypasses this, leaving the
/// marker to be reported — exactly the case we want.
public static func clearMarker(at url: URL = defaultMarkerURL()) {
try? FileManager.default.removeItem(at: url)
}

// MARK: - Launch detection (I/O)
// (.ips parsing lives in OOMDetector+CrashReports.swift)

/// Scan DiagnosticReports for OOM-relevant reports modified since `since`.
/// Best-effort; returns [] on any directory/read error.
public static func scanDiagnosticReports(
dir: URL,
processName: String,
since: Date,
fileManager: FileManager = .default
) -> [Finding] {
guard let entries = try? fileManager.contentsOfDirectory(
at: dir, includingPropertiesForKeys: [.contentModificationDateKey], options: [.skipsHiddenFiles])
else { return [] }

var findings: [Finding] = []
for url in entries {
let ext = url.pathExtension.lowercased()
guard ext == "ips" || ext == "panic" else { continue }
let name = url.lastPathComponent
let mtime = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate
if let mtime, mtime < since { continue }
guard let contents = try? String(contentsOf: url, encoding: .utf8) else { continue }

let isJetsam = name.hasPrefix("JetsamEvent")
var finding: Finding?
if isJetsam {
finding = parseJetsamReport(contents: contents, processName: processName)
} else {
finding = parseMemoryCrashReport(contents: contents, processName: processName)
}
if var f = finding {
f.reportName = name
f.epochSeconds = mtime?.timeIntervalSince1970
findings.append(f)
}
}
return findings
}

/// Full launch-time detection: scan crash logs since `since` AND consume any
/// pre-death marker. Returns the findings to emit as `oom` telemetry.
public static func detectOnLaunch(
markerURL: URL = defaultMarkerURL(),
diagnosticReportsDirs: [URL] = defaultDiagnosticReportsDirs(),
processName: String = "darkbloom",
since: Date,
fileManager: FileManager = .default
) -> [Finding] {
// Crash reports are the authoritative signal. Scan every candidate dir
// (user + system + Retired); dedupe by report filename across dirs.
var seenReports = Set<String>()
var crashFindings: [Finding] = []
for dir in diagnosticReportsDirs {
for f in scanDiagnosticReports(dir: dir, processName: processName, since: since, fileManager: fileManager) {
if let name = f.reportName, !seenReports.insert(name).inserted { continue }
crashFindings.append(f)
}
}

// Always consume the marker (so it never lingers), but only surface it
// when no crash report already attributes this death — otherwise one OOM
// would emit twice (marker + JetsamEvent).
let marker = readAndClearMarker(at: markerURL)
if crashFindings.isEmpty, let marker {
return [Finding(
source: .memoryPressureMarker,
message: "provider observed critical memory pressure before exit (likely OOM)",
peakMemoryBytes: marker.peakMemoryBytes > 0 ? marker.peakMemoryBytes : nil,
epochSeconds: marker.epochSeconds)]
}
return crashFindings
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] 🧩 large enum with multiple detection strategies and file I/O operations

💡 Suggestion: consider breaking into smaller focused components: MarkerIO, CrashScanner, and a coordinator rather than one large enum

📊 Score: 3×3 = 9 · Category: additive complexity

Comment on lines +1 to +97
import Foundation
import MLX

/// Hard ceiling on MLX's unified-memory footprint.
///
/// MLX's `memoryLimit` defaults to 1.5× the device working set — above physical
/// RAM — so by default MLX can allocate past total RAM and hit an uncatchable
/// jetsam SIGKILL (an invisible OOM). Pinning it to `physical − reserve` makes
/// the allocator throttle (malloc waits on scheduled tasks) instead. Coarse
/// backstop; the live per-request gate (GlobalKVCacheBudget / tokenBudgetMax,
/// clamped to SystemMemory.availableBytes) is the precise one.
public enum MLXMemoryGuard {
/// Headroom (GB) left below physical RAM for macOS + non-MLX memory. Larger
/// than the per-request load reserve (4 GB): this is the whole-machine ceiling.
public static let defaultReserveGB: UInt64 = 6

/// Floor so a tiny/misreported machine never gets a pathological limit.
static let minimumLimitBytes = 2 * 1024 * 1024 * 1024 // 2 GiB

public struct Limits: Equatable, Sendable {
public let memoryLimitBytes: Int
public let cacheLimitBytes: Int
}

/// Pure sizing policy. memoryLimit = max(floor, physical − reserve);
/// cacheLimit = memoryLimit × cacheFraction (bounds the reusable pool so
/// freed buffers return to the OS; 0.75 keeps reuse/perf while helping).
static func recommendedLimits(
physicalBytes: UInt64,
reserveBytes: UInt64,
cacheFraction: Double = 0.75
) -> Limits {
let physical = Int(min(physicalBytes, UInt64(Int.max)))
let reserve = Int(min(reserveBytes, UInt64(Int.max)))
let limit = max(minimumLimitBytes, physical > reserve ? physical - reserve : minimumLimitBytes)
let fraction = cacheFraction.isFinite ? min(1.0, max(0.0, cacheFraction)) : 0.75
let cache = max(minimumLimitBytes / 2, Int(Double(limit) * fraction))
return Limits(memoryLimitBytes: limit, cacheLimitBytes: min(cache, limit))
}

/// Reserve in BYTES from explicit (bytes), env DARKBLOOM_MLX_MEMORY_RESERVE_GB
/// (GB), or default. `explicit` is bytes, like reserveBytes everywhere else.
static func resolvedReserveBytes(
explicit: UInt64?,
env: [String: String] = ProcessInfo.processInfo.environment
) -> 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)))
}
return saturatingGiBToBytes(defaultReserveGB)
}

private static func saturatingGiBToBytes(_ gib: UInt64) -> UInt64 {
let (bytes, overflow) = gib.multipliedReportingOverflow(by: 1_073_741_824)
return overflow ? UInt64.max : bytes
}

// Set once per process; loadModel runs many times, so guard with lock + flag.
private static let lock = NSLock()
nonisolated(unsafe) private static var configured = false

/// Set the MLX ceiling once per process (idempotent). `apply` is injectable
/// for tests so they avoid touching real MLX globals.
@discardableResult
public static func configureOnce(
reserveBytes: UInt64? = nil,
physicalBytes: UInt64 = ProcessInfo.processInfo.physicalMemory,
apply: (Limits) -> Void = { limits in
Memory.memoryLimit = limits.memoryLimitBytes
Memory.cacheLimit = limits.cacheLimitBytes
},
log: ((Limits) -> Void)? = nil
) -> Limits? {
lock.lock()
if configured {
lock.unlock()
return nil
}
configured = true
lock.unlock()

let limits = recommendedLimits(
physicalBytes: physicalBytes,
reserveBytes: resolvedReserveBytes(explicit: reserveBytes))
apply(limits)
log?(limits)
return limits
}

/// Test-only: reset the once-flag so a test can drive `configureOnce` again.
static func _resetForTest() {
lock.lock()
configured = false
lock.unlock()
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 memory guard with environment variable override and multiple configuration paths

💡 Suggestion: consider simplifying to just explicit configuration or default, removing environment variable complexity

📊 Score: 2×2 = 4 · Category: over-configuration

Comment on lines 2109 to +2165
}
}

// MARK: - Memory protection

/// Surface any prior-run OOM (consume marker + scrape crash logs → oom
/// telemetry) and watch live memory pressure (reclaim cache + drop a marker
/// on critical so a kill before we can report it is attributed next launch).
private func startMemoryProtection() {
// Pin the MLX memory ceiling BEFORE any model weights are loaded (the
// first big allocation happens in ensureModelLoaded → loadModelContainer,
// which runs after this). Idempotent; the BatchScheduler.loadModel call
// is a backstop for the standalone path. See MLXMemoryGuard.
MLXMemoryGuard.configureOnce(log: { [logger] limits in
logger.info(
"MLX memory ceiling: limit=\(limits.memoryLimitBytes / (1024 * 1024 * 1024))GB cache=\(limits.cacheLimitBytes / (1024 * 1024 * 1024))GB")
})

let now = Date()
let since = OOMDetector.loadLastScan() ?? now.addingTimeInterval(-24 * 3600)
let findings = OOMDetector.detectOnLaunch(since: since)
for finding in findings {
var fields: [String: AnyCodableValue] = ["detect_source": .string(finding.source.rawValue)]
if let reason = finding.reason { fields["reason"] = .string(reason) }
if let peak = finding.peakMemoryBytes { fields["peak_memory_bytes"] = .int64(Int64(clamping: peak)) }
if let report = finding.reportName { fields["report"] = .string(report) }
TelemetryClient.shared.emit(
kind: .oom, severity: .error, message: finding.message, fields: fields)
logger.error("OOM detected on launch: \(finding.message)")
}
// Advance the scan watermark only AFTER findings are handed to telemetry,
// so a crash before this point re-scans the same reports next launch.
OOMDetector.saveLastScan(now)

let monitor = MemoryPressureMonitor(
clearCache: { MLX.Memory.clearCache() },
writeMarker: { _ in
let marker = OOMDetector.Marker(
pid: ProcessInfo.processInfo.processIdentifier,
epochSeconds: Date().timeIntervalSince1970,
peakMemoryBytes: UInt64(max(0, MLX.Memory.peakMemory)),
availableBytesAtEvent: SystemMemory.availableBytes() ?? 0)
OOMDetector.writeMarker(marker)
},
emit: { level, severity in
TelemetryClient.shared.emit(
kind: .oom, severity: severity,
message: "memory pressure \(level.rawValue) — possible imminent OOM",
fields: [
"pressure": .string(level.rawValue),
"available_bytes": .int64(Int64(clamping: SystemMemory.availableBytes() ?? 0)),
"mlx_active_bytes": .int64(Int64(clamping: UInt64(max(0, MLX.Memory.activeMemory)))),
])
})
monitor.start()
self.memoryPressureMonitor = monitor
logger.info("Memory protection active (OOM detection + pressure monitor)")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 memory protection logic embedded in main provider loop

💡 Suggestion: extract memory protection setup into a dedicated component that ProviderLoop can compose rather than implementing directly

📊 Score: 2×3 = 6 · Category: misplaced responsibility

@Gajesh2007
Gajesh2007 merged commit f9f3825 into master Jun 14, 2026
57 of 59 checks passed
@Gajesh2007
Gajesh2007 deleted the feat/oom-protection branch June 14, 2026 18:17
jonathan308 added a commit that referenced this pull request Oct 22, 2026
Brings master through #1516 (GLM-5.3-Flash) and pins mlx-swift-lm main
889fe3cc, which contains #322 (Flint) as merged plus #324 and #326-#330.
Conflicts keep Flint and GLM side by side: sampling defaults honor Flint and
the exact GLM identities; backend preparation passes Flint's model type and
keeps GLM's paged target; the advertised context is GLM's for a GLM target,
else Flint's, else the existing limits; request validation runs Flint's
policy beside GLM's controls and MiMo's tool restoration; native tool
failures name GLM, Flint or MiMo; both sampling-default tests stay. The
DiffusionGemma Responses expectation takes master's form.

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference-console-ui-dev — 8a75592f Deployed Jun 13, 2026 by vercel[bot]
Preview – d-inference — 8a75592f Deployed Jun 13, 2026 by vercel[bot]
Preview – d-inference-landing — 8a75592f Deployed Jun 13, 2026 by vercel[bot]
benchmarks — 8a75592f Deployed Jun 13, 2026 by Gajesh2007 via E2E Benchmarks #809
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.

2 participants