Repository navigation
feat(provider+coordinator): OOM protection + detection - #330
Conversation
Office Macs were OOM-crashing invisibly: the runtime KV admission was OS-memory-blind (counted only MLX's own memory against TOTAL physical RAM, ignoring everything else on a shared Mac), MLX had no memory ceiling (default is 1.5x working set, above physical RAM), and a jetsam SIGKILL leaves no in-process trace so the kills never reached telemetry. Provider OOM fix: - GlobalKVCacheBudget + tokenBudgetMax now clamp free RAM to min(physical - MLX.active - MLX.cache - reserve, SystemMemory.availableBytes()) — the same clamp the load gate already uses. Stops over-admission on shared boxes. - MLXMemoryGuard pins Memory.memoryLimit/cacheLimit below physical RAM once at load, so overshoot throttles instead of racing into a kernel kill. - MemoryPressureMonitor (DISPATCH_SOURCE_MEMORYPRESSURE): reclaim MLX cache on warning; on critical also drop an OOM marker + emit telemetry. OOM detection / observability: - New TelemetryKind=oom mirrored in Swift/Go/TS. - OOMDetector: on launch, consume any pre-death marker and scrape kernel JetsamEvent/EXC_RESOURCE crash reports for our process; emit oom telemetry. - Coordinator classifies abrupt read_error disconnects against the last heartbeat's memory pressure + in-flight count (ClassifyDisconnectReason); emits provider_oom_suspected_total + an oom telemetry event. - Telemetry field allowlists (Swift + Go) extended for the non-sensitive memory fields. Tests: GlobalKVCacheBudget OS-clamp, MLXMemoryGuard sizing/idempotency, OOMDetector parsers/marker/scan, memory-pressure policy, disconnect classifier. All provider + coordinator suites green.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
ethenotethan
left a comment
There was a problem hiding this comment.
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
| 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) |
There was a problem hiding this comment.
🔴 [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
| 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 |
There was a problem hiding this comment.
🔴 [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
| epochSeconds: Date().timeIntervalSince1970, | ||
| peakMemoryBytes: UInt64(max(0, MLX.Memory.peakMemory)), | ||
| availableBytesAtEvent: SystemMemory.availableBytes() ?? 0) |
There was a problem hiding this comment.
🟡 [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
| 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)))), | ||
| ]) |
There was a problem hiding this comment.
🟡 [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
|
|
||
| /// 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 |
There was a problem hiding this comment.
🔵 [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
| 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 | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [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
| 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 | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 [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
| 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() | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [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
| 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) |
There was a problem hiding this comment.
🟡 [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
|
|
||
| // 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, | ||
| }) | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [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
|
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
Threat-by-Threat AssessmentT-007 — Provider serves manipulated model outputs (
|
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
| 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) |
There was a problem hiding this comment.
🔴 [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. |
There was a problem hiding this comment.
🔴 [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
|
|
||
| // 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, | ||
| }) | ||
| } |
There was a problem hiding this comment.
🔵 [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
| 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) |
There was a problem hiding this comment.
🟡 [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
| private func startMemoryProtection() { | ||
| let now = Date() | ||
| let since = OOMDetector.loadLastScan() ?? now.addingTimeInterval(-24 * 3600) | ||
| let findings = OOMDetector.detectOnLaunch(since: since) | ||
| OOMDetector.saveLastScan(now) |
There was a problem hiding this comment.
🟡 [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
| 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) | ||
| } |
There was a problem hiding this comment.
🔵 [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
| 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) | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [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
| 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 | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 [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
|
|
||
| /// 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 | ||
| } |
There was a problem hiding this comment.
🟡 [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
| @@ -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 | |||
There was a problem hiding this comment.
🔵 [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.
There was a problem hiding this comment.
💡 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 |
There was a problem hiding this comment.
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 👍 / 👎.
| // Classify + surface it. See registry.ClassifyDisconnectReason. | ||
| if provider != nil { | ||
| memPressure, inFlight := provider.DisconnectDiagnostics() | ||
| if registry.ClassifyDisconnectReason(true, memPressure, inFlight) == registry.DisconnectReasonOOMSuspected { |
There was a problem hiding this comment.
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 👍 / 👎.
| findings.append(contentsOf: scanDiagnosticReports( | ||
| dir: diagnosticReportsDir, processName: processName, since: since, fileManager: fileManager)) |
There was a problem hiding this comment.
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 } |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
- Suggestion: MemoryPressurePolicy could be a simple function rather than an enum with one static method - consider
- 🟡 [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
| 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) |
There was a problem hiding this comment.
🔴 [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
| // Real OS-free RAM; `.max` falls back to the MLX-only view. | ||
| systemAvailable: SystemMemory.availableBytes() ?? .max) |
There was a problem hiding this comment.
🔴 [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
|
|
||
| // 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, | ||
| }) | ||
| } |
There was a problem hiding this comment.
🔵 [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
| 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, | ||
| }) |
There was a problem hiding this comment.
🟡 [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
| 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) | ||
| } |
There was a problem hiding this comment.
🔵 [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
| 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) | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [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
| 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 | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 [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
| /// 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 | ||
| } | ||
|
|
There was a problem hiding this comment.
🔵 [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
| 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 | ||
| } |
There was a problem hiding this comment.
🔵 [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
left a comment
There was a problem hiding this comment.
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
| 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) |
There was a problem hiding this comment.
🔴 [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
| 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 |
There was a problem hiding this comment.
🔴 [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
| ) | ||
| } | ||
| 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, | ||
| }) | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [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
| 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 | ||
| } |
There was a problem hiding this comment.
🔵 [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
| 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 |
There was a problem hiding this comment.
🔵 [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
| /// 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 | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 [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
| 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 | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [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
| 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 | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 [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
| 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() | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [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
| } | ||
| } | ||
|
|
||
| // 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)") |
There was a problem hiding this comment.
🔵 [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
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.
Problem
A lot of office Macs running as providers were OOM-crashing, invisibly. Over 48h on prod: ~7,880
read_errorWS 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 ~2panicevents 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.freeForLoadGbclamps tomin(mlxFree, SystemMemory.availableBytes())) but an OS-memory-blind runtime path on a platform (unified memory) where overshoot is a fatal kernel kill:GlobalKVCacheBudget.availableReservationBytes()andBatchScheduler.tokenBudgetMaxcomputed free RAM asphysicalMemory − 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.memoryLimitdefaults to 1.5× the device working set — above physical RAM — so MLX freely allocates past total RAM with no catchable failure.oomtelemetry kind, no memory-pressure handler, no crash-log scrape; the coordinator bucketed the kill as a genericread_errordisconnect.What changed
Provider OOM fix (the cure)
GlobalKVCacheBudget+BatchScheduler.tokenBudgetMaxnow clamp tomin(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.MLXMemoryGuardpinsMemory.memoryLimit/cacheLimitbelow physical RAM once per process (wired idempotently inBatchScheduler.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
TelemetryKind = oom, mirrored in Swift / Go / TS (+ both field allowlists + the console-ui set).OOMDetector: on launch, consume any pre-death marker and scrape kernelJetsamEvent/EXC_RESOURCEcrash reports for our process, emittingoomtelemetry — recovering the signal a SIGKILL destroys.read_errordisconnects against the last heartbeat's memory pressure + in-flight count (ClassifyDisconnectReason), emittingprovider_oom_suspected_total+ anoomevent. Turns the silent read-error churn into an attributable metric.Testing
New coverage for the OS-clamp (both directions + reserve), MLX sizing/idempotency, the
.ipsparsers / marker round-trip / scan watermark, the memory-pressure policy, and the disconnect classifier. Fullswift test(provider) andgo 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_tokensclamp to context window.Deploy notes
🤖 Generated with Claude Code
Need help on this PR? Tag
/codesmithwith what you need. Autofix is disabled.