Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 37 additions & 16 deletions provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ public actor BatchScheduler {
var checkpointBoundaries: [Int] = []
/// Per-layer cache class/window signature for restore validation.
var checkpointLayerSignatures: [CheckpointLayerSignature] = []
/// Bounded, single-consumer pipeline that drains checkpoint KV snapshots
/// into `checkpointManager`. Caps the number of live KV snapshots retained
/// in flight so a busy manager can't drive the live Metal buffer count to
/// the 499000 ceiling (the Gemma-4 leak). Built with the engine; shut down
/// in `stopCurrentEngine`. nil ⇒ feature off / no checkpoint manager.
var capturePipeline: CheckpointCapturePipeline<CheckpointCapture>?

/// Engine-tier owner (EncryptedPrefixCachePersistence) for pure-
/// attention models. Non-nil only when the model classifies as `.engine` AND
Expand Down Expand Up @@ -240,6 +246,7 @@ public actor BatchScheduler {
self.checkpointBoundaries = build.checkpointBoundaries
self.checkpointLayerSignatures = build.checkpointLayerSignatures
self.engineTierOwner = build.engineTierOwner
self.capturePipeline = build.capturePipeline
await engine.start()
// Final epoch check after start() — start can suspend too.
// Identity-checked cleanup — only nil self.engine if it's
Expand All @@ -251,6 +258,7 @@ public actor BatchScheduler {
if self.checkpointBoundaries == build.checkpointBoundaries { self.checkpointBoundaries = [] }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ Redundant pipeline shutdown calls in multiple cleanup paths

💡 Suggestion: Add a shutdown flag to make shutdown() idempotent and avoid redundant work in cleanup paths

📊 Score: 3×3 = 9 · Category: Repeated work

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Identical cleanup pattern repeated 4 times with same identity checks

💡 Suggestion: Extract a helper method cleanupBuildArtifacts(build:) to eliminate the repeated identity-checked cleanup pattern

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Identical cleanup pattern repeated 4 times with same identity checks

💡 Suggestion: Extract a helper method cleanupBuildArtifacts(build:) to eliminate the repeated identity-check cleanup pattern

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] 🧩 Identical cleanup pattern repeated 4 times in the file

💡 Suggestion: Extract the identity-checked cleanup pattern into a helper method to reduce duplication and maintenance burden.

📊 Score: 3×4 = 12 · Category: duplicate logic

if self.checkpointLayerSignatures == build.checkpointLayerSignatures { self.checkpointLayerSignatures = [] }
if self.engineTierOwner === build.engineTierOwner { self.engineTierOwner = nil }
if self.capturePipeline === build.capturePipeline { self.capturePipeline?.shutdown(); self.capturePipeline = nil }
await engine.stop()
return
}
Expand Down Expand Up @@ -294,6 +302,7 @@ public actor BatchScheduler {
if self.checkpointBoundaries == build.checkpointBoundaries { self.checkpointBoundaries = [] }
if self.checkpointLayerSignatures == build.checkpointLayerSignatures { self.checkpointLayerSignatures = [] }
if self.engineTierOwner === build.engineTierOwner { self.engineTierOwner = nil }
if self.capturePipeline === build.capturePipeline { self.capturePipeline?.shutdown(); self.capturePipeline = nil }
await engine.stop()
return
}
Expand Down Expand Up @@ -333,6 +342,7 @@ public actor BatchScheduler {
if self.checkpointBoundaries == build.checkpointBoundaries { self.checkpointBoundaries = [] }
if self.checkpointLayerSignatures == build.checkpointLayerSignatures { self.checkpointLayerSignatures = [] }
if self.engineTierOwner === build.engineTierOwner { self.engineTierOwner = nil }
if self.capturePipeline === build.capturePipeline { self.capturePipeline?.shutdown(); self.capturePipeline = nil }
await engine.stop()
return
}
Expand Down Expand Up @@ -818,11 +828,12 @@ public actor BatchScheduler {
)
} ?? []
engine?.core.scheduler.checkpointBoundaries = boundaries
engine?.core.scheduler.onCheckpointCapture = { prefixTokens, length, caches in
let box = SendableKVCaches(caches)
// TB-016 sub-feature B: test seam also RAM-only (no eager flush).
Task { await mgr.store(tokens: prefixTokens, checkpointLength: length, caches: box) }
}
// Same bounded + admission-gated wiring production uses, so the test
// seam exercises the real backpressure path (not the old unbounded one).
self.capturePipeline?.shutdown()
let wiring = Self.makeCheckpointCaptureWiring(manager: mgr)
self.capturePipeline = wiring.pipeline
engine?.core.scheduler.onCheckpointCapture = wiring.hook
}

/// TEST SEAM: drive the real `finalizeRestore` fallback path without a live
Expand Down Expand Up @@ -956,6 +967,9 @@ public actor BatchScheduler {
let checkpointBoundaries: [Int]
let checkpointLayerSignatures: [CheckpointLayerSignature]
let engineTierOwner: EncryptedPrefixCachePersistence?
/// Bounded capture pipeline (non-nil iff `checkpointManager` is). The
/// caller stores it on the actor and shuts it down at teardown.
let capturePipeline: CheckpointCapturePipeline<CheckpointCapture>?
}

private static func makeBatchedEngine(
Expand Down Expand Up @@ -1001,6 +1015,7 @@ public actor BatchScheduler {

var enginePrefixCache: PrefixCache? = nil
var checkpointManager: PrefixCacheManager? = nil
var capturePipeline: CheckpointCapturePipeline<CheckpointCapture>? = nil
var boundaries: [Int] = []
var checkpointLayerSignatures: [CheckpointLayerSignature] = []
// Capture the engine-tier owner for accountant registration.
Expand Down Expand Up @@ -1112,16 +1127,14 @@ public actor BatchScheduler {
// when a manager exists, so .engine/.none models are untouched.
if let mgr = checkpointManager {
scheduler.checkpointBoundaries = boundaries
scheduler.onCheckpointCapture = { prefixTokens, length, caches in
let box = SendableKVCaches(caches)
// TB-016 sub-feature B: capture = RAM-ONLY. Store to RAM
// (fast); 2nd-use promotion handles SSD persistence when the
// prefix is re-accessed (RAM-first admission stops the write
// storm). No eager flushToSSD.
Task {
await mgr.store(tokens: prefixTokens, checkpointLength: length, caches: box)
}
}
// Bound the capture pipeline: at most `max-in-flight` live KV
// snapshots retained while the manager actor is busy (crypto +
// fsync), dropping the surplus rather than queuing it. This is
// the fix for the Gemma-4 Metal live-resource (499000) leak — the
// old `Task { await mgr.store(...) }` per boundary was unbounded.
let wiring = Self.makeCheckpointCaptureWiring(manager: mgr)
capturePipeline = wiring.pipeline
scheduler.onCheckpointCapture = wiring.hook
}
return EngineBuild(
engine: BatchedEngine(
Expand All @@ -1139,7 +1152,8 @@ public actor BatchScheduler {
checkpointManager: checkpointManager,
checkpointBoundaries: boundaries,
checkpointLayerSignatures: checkpointLayerSignatures,
engineTierOwner: engineTierOwner
engineTierOwner: engineTierOwner,
capturePipeline: capturePipeline
)
}
}
Expand Down Expand Up @@ -1930,6 +1944,13 @@ public actor BatchScheduler {
self.engine = nil
modelContainer = nil
tokenizer = nil
// Drain the bounded capture pipeline: the engine is stopped (no more
// capture hooks fire), so finish the stream and cancel the consumer.
// This releases any retained KV snapshots and stops an in-flight
// `mgr.store` from racing the index flush / accountant deregister below,
// and guarantees no snapshot (or consumer Task) leaks across a swap.
capturePipeline?.shutdown()
Comment on lines 1945 to +1952

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ Synchronous shutdown and drain operations in stopCurrentEngine may block actor

💡 Suggestion: Consider making capturePipeline shutdown asynchronous or use a detached task to avoid blocking the actor during engine teardown

📊 Score: 2×2 = 4 · Category: Blocking I/O on hot paths

Comment on lines +1948 to +1952

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ Shutdown called multiple times in different code paths without idempotency check

💡 Suggestion: Add explicit idempotency check in shutdown() method or ensure callers coordinate to avoid redundant shutdown calls

📊 Score: 2×2 = 4 · Category: Repeated work

capturePipeline = nil
// Persist any coalesced index writes before dropping the manager, so
// checkpoints written since the last coalesced save survive restart.
if let mgr = checkpointManager {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
// Copyright © 2026 Eigen Labs.
//
// Bounded, single-consumer pipeline for best-effort checkpoint KV capture.
//
// Background — the Gemma-4 `[metal::malloc] Resource limit (499000) exceeded`
// crash. Heterogeneous models (Gemma-4: sliding [8,256] + full [2,512]) use the
// `.checkpoint` prefix-cache tier. At each checkpoint boundary the engine hands
// the provider a freshly-extracted, per-layer KV snapshot (live MLXArrays,
// ≈ layers × 2 Metal buffers). The previous wiring spawned an UNBOUNDED
// `Task { await mgr.store(...) }` per boundary:
//
// scheduler.onCheckpointCapture = { prefixTokens, length, caches in
// let box = SendableKVCaches(caches)
// Task { await mgr.store(...) } // <-- one detached Task per boundary
// }
//
// `PrefixCacheManager` is a single actor that serializes `store` behind
// AES-GCM serialize + fsync and against every lookup/materialize. Under
// sustained traffic the actor falls behind, the spawned Tasks queue, and each
// queued Task keeps its live KV snapshot pinned until it runs. The live Metal
// resource COUNT (not bytes/cache) climbs to the `iogpu.rsrc_limit` ceiling
// (~499000) → crash. The mlx/mlx-c "count-aware" cache trims can only reclaim
// CACHED buffers; these snapshots are LIVE, so trimming cannot help and the
// idle-gated `Memory.clearCache()` never fires under load.
//
// This pipeline caps the number of snapshots retained in flight. Capture is
// best-effort cache-warming: when the bounded buffer is full the surplus
// snapshot is DROPPED (and released, freeing its Metal buffers) rather than
// queued. Dropping a snapshot only costs a future cache miss, never
// correctness.

import Foundation
import MLX
import MLXLMCommon

/// One checkpoint capture: the prefix tokens it covers, the checkpoint length,
/// and the boxed per-layer KV snapshot to hand to `PrefixCacheManager.store`.
/// `SendableKVCaches` is the ownership-transfer box; this struct is the
/// production payload for ``CheckpointCapturePipeline``.
struct CheckpointCapture: Sendable {
let tokens: [Int]
let length: Int
let caches: SendableKVCaches
}

/// Bounded, single-consumer delivery pipeline.
///
/// A small `AsyncStream` (buffering policy `.bufferingNewest(capacity)`) feeds a
/// single long-lived consumer Task. `submit(_:)` is synchronous, non-blocking,
/// and `@Sendable`, so it is safe to call from the engine queue inside
/// `Scheduler.onCheckpointCapture`. At most `capacity` payloads sit in the
/// buffer and the consumer holds at most one more while it `await`s, so the
/// pipeline retains at most `capacity + 1` payloads — regardless of how far
/// behind the consumer falls. (Counting the single payload being handed to
/// `submit` during an evicting enqueue, at most `capacity + 2` are live for an
/// instant.) Surplus payloads are dropped (and released) rather than queued —
/// this small constant bound is what caps the live Metal buffer count and
/// fixes the 499000 leak.
///
/// Generic over `Payload` so the bounding/drop/teardown logic is unit-testable
/// without MLX (the production instantiation is `Payload == CheckpointCapture`).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ NSLock allocation on every pipeline instance for lightweight counters

💡 Suggestion: Consider using atomic operations (OSAtomicIncrement32 or std::atomic equivalent) for simple counters instead of NSLock to reduce allocation overhead

📊 Score: 2×3 = 6 · Category: Unbounded allocations

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Generic pipeline class when only one concrete type is used

💡 Suggestion: Consider making this concrete for CheckpointCapture since no other payload types are anticipated

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Generic type parameter adds complexity for single concrete use

💡 Suggestion: Remove generic <Payload: Sendable> and hardcode CheckpointCapture since there's only one production use case

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Generic pipeline class when only one concrete type is used

💡 Suggestion: Consider making this non-generic since it's only used with CheckpointCapture. The generic abstraction adds complexity without clear benefit.

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

final class CheckpointCapturePipeline<Payload: Sendable>: @unchecked Sendable {
/// Maximum number of payloads buffered before the surplus is dropped.
let capacity: Int

private let continuation: AsyncStream<Payload>.Continuation
private let consumer: Task<Void, Never>

// Lightweight counters (lock-guarded; read from tests / future telemetry).
private let statsLock = NSLock()
private var _accepted = 0
Comment on lines +69 to +71

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Lock-guarded counters for simple statistics that could be atomic

💡 Suggestion: Use OSAtomicIncrement64 or similar atomic operations instead of NSLock for simple counters

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

private var _dropped = 0
Comment on lines +70 to +72

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ NSLock usage in stats tracking could cause contention on high-frequency submit calls

💡 Suggestion: Replace NSLock with atomic operations (OSAtomicIncrement64 or similar) for simple counters to eliminate lock contention

📊 Score: 2×3 = 6 · Category: Blocking I/O on hot paths

Comment on lines +70 to +72

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Lightweight counters with lock for simple integers

💡 Suggestion: Use atomic operations or remove counters entirely if only used for testing

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

Comment on lines +70 to +72

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Lightweight counters with manual locking for simple statistics

💡 Suggestion: Consider using atomic operations or removing these counters entirely if they're only for testing/debugging. The manual locking adds complexity for simple increment operations.

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


/// - Parameters:
/// - capacity: max buffered payloads (clamped to ≥ 1). Small by design
/// (1–2): this is the hard cap on live KV snapshots retained in flight.
/// - consume: the (async) sink. Invoked serially by the single consumer
/// Task, one payload at a time.
init(
capacity: Int,
consume: @escaping @Sendable (Payload) async -> Void
) {
let cap = max(1, capacity)
self.capacity = cap
let (stream, continuation) = AsyncStream.makeStream(
of: Payload.self,
bufferingPolicy: .bufferingNewest(cap)
)
self.continuation = continuation
Comment on lines +86 to +89

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ AsyncStream with bufferingNewest policy may cause memory pressure under high load

💡 Suggestion: Consider adding telemetry to monitor buffer utilization and dropped payloads to validate the capacity sizing in production

📊 Score: 3×4 = 12 · Category: Unbounded allocations

Comment on lines +86 to +89

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ AsyncStream with bufferingNewest policy may still accumulate tasks under high contention

💡 Suggestion: Consider adding explicit task cancellation tracking or using a semaphore-based approach to guarantee bounded concurrency

📊 Score: 3×4 = 12 · Category: Unbounded goroutines

self.consumer = Task {
for await payload in stream {
// Honor shutdown before consuming. `shutdown()` calls
// `finish()` + `cancel()`, but `finish()` still delivers
// already-buffered payloads to this loop and an AsyncStream
// `for await` does NOT observe Task cancellation on its own.
// Without this guard we would `store(...)` old-model KV
// snapshots after a model swap has begun — pinning large live
// Metal buffers that must not overlap the next engine.
//
// We `continue` rather than `break`: the buffered remainder must
// still be pulled so each payload is released as it drains (the
// retained `continuation` keeps the stream's internal buffer —
// and anything stranded in it — alive). Skipping `consume` drops
// the captures (best-effort) without storing them; the finished
// stream then terminates the loop once its buffer empties.
if Task.isCancelled { continue }
await consume(payload)
Comment on lines +91 to +107

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Honor cancellation before draining buffered captures

When a model is unloaded while this stream has buffered captures, shutdown() calls finish() and cancel(), but this loop never observes cancellation. AsyncStream continues yielding values that were already buffered after finish/cancel, so a backlogged consumer can keep holding and storing old-model KV snapshots after stopCurrentEngine has moved on to flush/deregister or load the next engine. That defeats the teardown guarantee and can overlap large Metal buffers across a model swap; break on Task.isCancelled before consuming buffered values, or explicitly discard the queue, so shutdown actually drops them.

Useful? React with 👍 / 👎.

}
Comment on lines +95 to +108

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Task cancellation check in data processing loop

💡 Suggestion: Consider handling cancellation at the Task level rather than checking it inside the processing loop, which mixes cancellation concerns with data processing logic.

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

}
}
Comment on lines +95 to +110

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ Consumer task processes payloads serially which could create backpressure

💡 Suggestion: Consider parallel processing of payloads if the consume function is I/O bound, or document that this is intentionally serial

📊 Score: 2×3 = 6 · Category: Blocking I/O on hot paths


/// Enqueue a payload. Synchronous, non-blocking, `@Sendable`.
///
/// Returns `true` when the payload was buffered without eviction, `false`
/// when the buffer was already full (an overflow occurred and the surplus
/// payload was dropped + released) or the pipeline has been shut down.
@discardableResult
func submit(_ payload: Payload) -> Bool {
switch continuation.yield(payload) {
case .enqueued:
statsLock.lock(); _accepted += 1; statsLock.unlock()
return true
case .dropped:
// `.bufferingNewest` keeps the newest `capacity` payloads and
// returns the evicted (oldest) one here; letting it go out of scope
// releases its KV snapshot so the Metal buffers free immediately.
statsLock.lock(); _dropped += 1; statsLock.unlock()
return false
case .terminated:
return false
@unknown default:
return false
}
}

/// Count of `submit` calls that buffered without eviction.
var acceptedCount: Int { statsLock.lock(); defer { statsLock.unlock() }; return _accepted }
Comment thread
ethenotethan marked this conversation as resolved.
Resolved
/// Count of `submit` calls that overflowed the buffer (a payload dropped).
var droppedCount: Int { statsLock.lock(); defer { statsLock.unlock() }; return _dropped }

/// Stop accepting, end the consumer loop, and cancel it so an in-flight
/// `consume` is not awaited indefinitely across a model swap. Idempotent.
/// Releases the stream's buffered payloads (their Metal buffers free).
func shutdown() {
continuation.finish()
consumer.cancel()
}

/// Test seam: await the consumer Task draining to completion. Production
/// teardown does not need to await this (ARC + `finish()` reclaim the
/// buffered snapshots); tests use it to assert no payloads leak.
func waitUntilDrained() async {
await consumer.value
}

deinit {
// Belt-and-suspenders: if the owner dropped us without `shutdown()`,
// make sure the stream terminates and the consumer Task ends.
continuation.finish()
consumer.cancel()
}
}
Comment on lines +158 to +162

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Environment variable tuning for internal buffer size

💡 Suggestion: Remove env var tuning - the default of 2 is already conservative and this adds unnecessary configuration surface

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

Comment on lines +156 to +162

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Environment variable parsing with fallback for simple integer

💡 Suggestion: Consider using a simpler approach or removing the environment variable entirely since this is an internal tuning parameter with a reasonable default.

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


// MARK: - BatchScheduler capture wiring

extension BatchScheduler {
/// Fraction of `Memory.resourceLimit` above which checkpoint capture is
/// skipped. Matches the submodule's `[rsrc]` pressure threshold (70%).
static let captureResourcePressureFraction = 0.7

/// Default cap on KV snapshots retained in flight. Intentionally tiny:
/// capture is best-effort, and the whole point is to bound live buffers.
static let captureDefaultMaxInFlight = 2

/// Resolve the in-flight cap. Env-tunable via
/// `DARKBLOOM_KV_CAPTURE_MAX_INFLIGHT` (clamped to ≥ 1).
static func captureMaxInFlight() -> Int {
let raw = ProcessInfo.processInfo.environment["DARKBLOOM_KV_CAPTURE_MAX_INFLIGHT"]?
.trimmingCharacters(in: .whitespaces)
if let raw, let n = Int(raw), n >= 1 { return n }
return captureDefaultMaxInFlight
}

/// Pure decision (testable): is the live Metal buffer count high enough that
/// we should skip capture and stop feeding the leak? An unknown limit (0 —
/// non-Metal backend / unset sysctl) is treated as "no pressure" so capture
/// is never disabled spuriously.
static func captureResourcePressureHigh(numResources: Int, resourceLimit: Int) -> Bool {
guard resourceLimit > 0 else { return false }
return Double(numResources) > captureResourcePressureFraction * Double(resourceLimit)
}

/// Live reading of the above against the MLX allocator counters.
static func captureResourcePressureHigh() -> Bool {
captureResourcePressureHigh(
numResources: MLX.Memory.numResources,
resourceLimit: MLX.Memory.resourceLimit
)
}

/// The `onCheckpointCapture` hook type the engine's `Scheduler` exposes.
typealias CheckpointCaptureHook =
@Sendable (_ prefixTokens: [Int], _ checkpointLength: Int, _ caches: [any KVCache]) -> Void

/// Build the bounded capture pipeline + the synchronous `@Sendable` hook for
/// a checkpoint-tier manager. Shared by the production engine builder and the
/// test seam so both get identical backpressure + admission-gating.
///
/// The hook does two things, both cheap and non-blocking:
/// 1. Admission gate — skip (and release) the snapshot when the live Metal
/// buffer count is already high; that is exactly when feeding more
/// snapshots risks the 499000 ceiling.
/// 2. Backpressure — submit to the bounded pipeline, which drops on full.
static func makeCheckpointCaptureWiring(
manager mgr: PrefixCacheManager
) -> (pipeline: CheckpointCapturePipeline<CheckpointCapture>, hook: CheckpointCaptureHook) {
let maxInFlight = captureMaxInFlight()
let pipeline = CheckpointCapturePipeline<CheckpointCapture>(
capacity: maxInFlight
) { capture in
// TB-016 sub-feature B: capture = RAM-ONLY. The 2nd-use promotion in
// the manager handles SSD persistence; no eager flushToSSD here.
await mgr.store(
tokens: capture.tokens,
checkpointLength: capture.length,
caches: capture.caches
)
}
prefixCacheLogger.info(
"checkpoint capture pipeline: max-in-flight \(maxInFlight) (drop-on-full), admission-gate at \(Int(captureResourcePressureFraction * 100))% of Metal resource limit")
let hook: CheckpointCaptureHook = { [pipeline] prefixTokens, length, caches in
// 1. Admission gate. Returning here lets the `caches` argument go
// out of scope → its Metal buffers free immediately.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ captureResourcePressureHigh() called on every checkpoint capture

💡 Suggestion: Cache the resource pressure check result for a short duration (e.g., 100ms) since MLX.Memory counters don't change rapidly

📊 Score: 2×4 = 8 · Category: Repeated work

if captureResourcePressureHigh() { return }
// Bounded, single-consumer, drop-on-full backpressure. Caps the live
// KV snapshots retained while the manager actor is busy with
// crypto + fsync, regardless of how far behind it falls.
pipeline.submit(
CheckpointCapture(
tokens: prefixTokens,
length: length,
caches: SendableKVCaches(caches)
)
)
}
return (pipeline, hook)
}
}
Loading
Loading