diff --git a/provider-swift/Sources/ProviderCore/Inference/BatchScheduler+EngineBridge.swift b/provider-swift/Sources/ProviderCore/Inference/BatchScheduler+EngineBridge.swift index 45ac843fcc..f0303db627 100644 --- a/provider-swift/Sources/ProviderCore/Inference/BatchScheduler+EngineBridge.swift +++ b/provider-swift/Sources/ProviderCore/Inference/BatchScheduler+EngineBridge.swift @@ -409,6 +409,14 @@ extension BatchScheduler { activeBridges[id] = bridge } + /// Test seam: pin `kvBytesPerToken` so a non-live test can compute exact + /// expected reservation byte counts (production derives it from the model + /// architecture at load time). Internal + @testable-only; stripped from + /// production binaries. + func _setKvBytesPerTokenForTest(_ value: Int) { + kvBytesPerToken = value + } + /// Test accessor: is a bridge still tracked for `id`? This is the exact /// signal `confirmEnqueuedOrAbort` checks after `addRequest` to detect a /// request that was cancelled / timed-out while the submit task was diff --git a/provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift b/provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift index a082aa3ce5..a9f44d4883 100644 --- a/provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift +++ b/provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift @@ -414,18 +414,38 @@ public actor BatchScheduler { /// Materialize an already-admitted checkpoint candidate and attach it to the /// MLX request. This intentionally runs after KV reservation. + /// + /// Returns `true` iff the restore was actually attached to `req` + /// (`req.restoredCheckpoint` set). All four fallback branches — no manager, + /// materialize returned nil, geometry unusable, or the materialized KV + /// exceeded the admitted estimate — return `false` so the caller can + /// downgrade BOTH the scheduler token budget and the global KV-byte + /// reservation back to the cold-prefill footprint (otherwise the + /// restore-sized reservation leaks for the request's whole life → admission + /// starvation under exactly the OOM pressure that triggers restore failures). private func materializeRestoredCheckpoint( _ req: Request, admission: RestoredCheckpointAdmission, promptTokens: [Int], scope: String - ) async { - guard let mgr = checkpointManager else { return } + ) async -> Bool { + guard let mgr = checkpointManager else { return false } guard let hit = await mgr.materialize( candidate: admission.candidate, tokens: promptTokens, scope: scope - ) else { return } + ) else { return false } + + // Use-after-release guard: `mgr.materialize` is an expensive await (RAM + // copy / SSD decrypt). A cancel or pending-timeout can run the bridge's + // cancel path (releaseKVReservation + bridge drop) while it is in flight. + // If the bridge is gone, the reservation these caches were sized against + // has already been released — attaching them would allocate KV against a + // freed reservation. Discard the materialized caches and report failure; + // the cancel path already released the reservation, and the submit path's + // `confirmEnqueuedOrAbort` will refuse to runBridge on the missing bridge. + // `activeBridges` is this actor's own state — no extra lock needed. + guard activeBridges[req.requestId] != nil else { return false } guard Self.restoredCheckpointIsUsable( caches: hit.caches, @@ -435,7 +455,7 @@ public actor BatchScheduler { ) else { prefixCacheLogger.warning( "prefix cache restore rejected: invalid checkpoint geometry; falling back to cold prefill") - return + return false } let actualReservation = restoredCheckpointReservedTokens( @@ -447,10 +467,53 @@ public actor BatchScheduler { guard actualReservation <= admission.reservedTokens else { prefixCacheLogger.warning( "prefix cache restore skipped: materialized KV exceeded admitted estimate; falling back to cold prefill") - return + return false } req.restoredCheckpoint = (caches: hit.caches, tokenCount: hit.tokenCount) + return true + } + + /// Shared restore finalizer for both submit paths. Runs the expensive + /// materialize and, when it falls back (returns false), downgrades BOTH + /// accounting systems from the restore-sized reservation back to the cold + /// `requestBudget` footprint: + /// + /// 1. scheduler token budget — clear `bridge.reservedTokens` so + /// `activeTokenBudgetUsed` falls back to (promptTokens + maxTokens), + /// mirroring the downgrade in `reserveKVForRequest`. + /// 2. global KV bytes — `reduceReservation` shrinks the live reservation to + /// the cold size, atomically freeing the over-charged difference. + /// + /// When materialize SUCCEEDS both reservations stay at the restore-sized + /// amount — the restored KV is really materialized, so that charge is correct. + /// Factored out so the two submit paths share one definition (no drift). + private func finalizeRestore( + _ req: Request, + id: String, + admission: RestoredCheckpointAdmission, + promptTokens: [Int], + scope: String, + requestBudget: Int + ) async { + let attached = await materializeRestoredCheckpoint( + req, + admission: admission, + promptTokens: promptTokens, + scope: scope + ) + guard !attached else { return } + // Restore was planned + accepted (oversized reservations charged) but did + // not materialize. Drop both systems back to the cold-prefill size. + if var bridge = activeBridges[id] { + bridge.reservedTokens = nil + activeBridges[id] = bridge + } + await kvBudget?.reduceReservation( + requestID: id, + kvBytesPerToken: kvBytesPerToken, + tokenCount: requestBudget + ) } static func restoredCheckpointIsUsable( @@ -591,19 +654,44 @@ public actor BatchScheduler { return admission } + /// Which reservation `reserveKVForRequest` actually secured. The submit + /// paths MUST branch on this — capturing `acceptedRestore != nil` before the + /// reserve is not enough, because the reserve can DOWNGRADE a restore to a + /// cold prefill when the restore-sized headroom is unavailable. Materializing + /// the restore-sized KV against a cold-sized reservation under-reserves and + /// OOMs under exactly the memory pressure that forced the downgrade. + enum KVReservationOutcome { + /// The restore-sized reservation is held; the restore may materialize. + case restoreReserved + /// Only the cold (requestTokens) reservation is held — either no restore + /// was planned, or a planned restore was downgraded. The restore must be + /// SKIPPED entirely; the request proceeds as a cold prefill. + case coldReserved + /// No reservation could be secured; the submit must reject the request. + case failed + } + private func reserveKVForRequest( requestId: String, requestTokens: Int, reservationTokens: Int, restorePlanned: Bool - ) async -> Bool { - guard let kvBudget else { return true } + ) async -> KVReservationOutcome { + // No budgeting: preserve the legacy "always proceed" behavior. If a + // restore was planned, treat it as restore-reserved so the restore still + // materializes when budgeting is disabled (the happy path is unchanged). + guard let kvBudget else { + return restorePlanned ? .restoreReserved : .coldReserved + } if await kvBudget.reserve( requestID: requestId, kvBytesPerToken: kvBytesPerToken, tokenCount: reservationTokens ) { - return true + // The reservation we asked for landed. When a restore was planned + // the requested amount IS the restore-sized reservation; otherwise + // it's the cold footprint (reservationTokens == requestTokens). + return restorePlanned ? .restoreReserved : .coldReserved } // A restored checkpoint hit can require materially more headroom than @@ -611,7 +699,7 @@ public actor BatchScheduler { // larger reservation fails, drop the restore and retry the normal // request reservation so the cache miss is slow, not fatal. guard restorePlanned, reservationTokens > requestTokens else { - return false + return .failed } if var bridge = activeBridges[requestId] { @@ -621,11 +709,15 @@ public actor BatchScheduler { prefixCacheLogger.warning( "prefix cache restore skipped: insufficient KV headroom; falling back to cold prefill") - return await kvBudget.reserve( + let coldReserved = await kvBudget.reserve( requestID: requestId, kvBytesPerToken: kvBytesPerToken, tokenCount: requestTokens ) + // Downgraded to cold: the caller MUST NOT materialize the restore — only + // the cold reservation is held. bridge.reservedTokens is already nil + // (cleared above) so activeTokenBudgetUsed already reflects the cold size. + return coldReserved ? .coldReserved : .failed } /// Stale-engine enqueue guard: `submit`/`submitTokenized` capture @@ -725,6 +817,125 @@ public actor BatchScheduler { } } + /// TEST SEAM: drive the real `finalizeRestore` fallback path without a live + /// engine. `RestoredCheckpointAdmission` is `private` to this file, so the + /// regression test (in another file) cannot build one — this seam constructs + /// an admission with the given oversized `reservedTokens` and invokes the + /// exact production helper the submit paths call. With no `checkpointManager` + /// installed, `materializeRestoredCheckpoint` short-circuits to `false`, so + /// this exercises the downgrade-both-systems branch end-to-end. Returns + /// nothing; the caller inspects `activeTokenBudgetUsed`, the bridge's + /// `reservedTokens`, and the kvBudget reservation. Not used in production. + func _testFinalizeRestoreFallback( + id: String, + promptTokens: [Int], + maxTokens: Int, + reservedTokens: Int, + requestBudget: Int + ) async { + let candidate = PrefixLookupCandidate( + digest: Data(), + digestHex: "", + tokenCount: max(1, promptTokens.count - 1), + estimatedBytes: 0, + tier: .ram + ) + let admission = RestoredCheckpointAdmission( + candidate: candidate, + reservedTokens: reservedTokens + ) + let sp = SamplingParams(maxTokens: maxTokens, temperature: 0.0) + let req = Request( + requestId: id, + prompt: promptTokens as AnyHashable, + samplingParams: sp + ) + await finalizeRestore( + req, + id: id, + admission: admission, + promptTokens: promptTokens, + scope: "", + requestBudget: requestBudget + ) + } + + /// TEST SEAM: drive the real `reserveKVForRequest` and return the outcome so + /// a non-live test can prove the downgrade path reports `.coldReserved` (so + /// the submit paths skip restore) rather than secretly holding a cold + /// reservation while reporting success. `reserveKVForRequest` is `private` to + /// this file; this thin wrapper invokes the exact production helper. Not used + /// in production. + func _testReserveKVForRequest( + requestId: String, + requestTokens: Int, + reservationTokens: Int, + restorePlanned: Bool + ) async -> KVReservationOutcome { + await reserveKVForRequest( + requestId: requestId, + requestTokens: requestTokens, + reservationTokens: reservationTokens, + restorePlanned: restorePlanned + ) + } + + /// TEST SEAM: replay the EXACT submit-path restore decision against the real + /// `reserveKVForRequest`, then apply the same branch the submit paths use: + /// call `finalizeRestore` ONLY when the outcome is `.restoreReserved`. Builds + /// a real `Request` and a restore-sized `RestoredCheckpointAdmission` (both + /// `private` to this file, so the cross-file test cannot construct them) and + /// reports the outcome plus whether `req.restoredCheckpoint` stayed nil. This + /// proves the BUG-3 fix end-to-end: a downgraded reserve (.coldReserved) must + /// NOT attach a restored checkpoint. With no `checkpointManager` installed, + /// `materializeRestoredCheckpoint` short-circuits to false, so even the + /// `.restoreReserved` branch leaves the checkpoint nil — the load-bearing + /// signal here is that the `.coldReserved` branch never calls finalizeRestore + /// at all. Not used in production. + func _testReserveThenMaybeRestore( + id: String, + promptTokens: [Int], + maxTokens: Int, + requestBudget: Int, + reservationTokens: Int + ) async -> (outcome: KVReservationOutcome, restoredCheckpointWasNil: Bool) { + let sp = SamplingParams(maxTokens: maxTokens, temperature: 0.0) + let req = Request( + requestId: id, + prompt: promptTokens as AnyHashable, + samplingParams: sp + ) + let candidate = PrefixLookupCandidate( + digest: Data(), + digestHex: "", + tokenCount: max(1, promptTokens.count - 1), + estimatedBytes: 0, + tier: .ram + ) + let admission = RestoredCheckpointAdmission( + candidate: candidate, + reservedTokens: reservationTokens + ) + let outcome = await reserveKVForRequest( + requestId: id, + requestTokens: requestBudget, + reservationTokens: reservationTokens, + restorePlanned: true + ) + // Mirror the submit paths: materialize the restore ONLY on .restoreReserved. + if outcome == .restoreReserved { + await finalizeRestore( + req, + id: id, + admission: admission, + promptTokens: promptTokens, + scope: "", + requestBudget: requestBudget + ) + } + return (outcome, req.restoredCheckpoint == nil) + } + /// Result of building the engine: the engine itself plus the optional /// checkpoint-tier manager + its boundaries (non-nil only for hybrid /// `.checkpoint` models with the flag on). The caller stores the manager @@ -1373,23 +1584,32 @@ public actor BatchScheduler { admission: plannedRestore ) let kvReservationTokens = acceptedRestore?.reservedTokens ?? requestBudget - guard await reserveKVForRequest( + let kvOutcome = await reserveKVForRequest( requestId: id, requestTokens: requestBudget, reservationTokens: kvReservationTokens, restorePlanned: acceptedRestore != nil - ) else { + ) + guard kvOutcome != .failed else { await dropBridge(requestId: id) continuation.yield(.error("token_budget_exhausted: insufficient global KV cache headroom")) continuation.finish() return stream } - if let acceptedRestore { - await materializeRestoredCheckpoint( + // Materialize the restore ONLY when its restore-sized reservation is held + // (`.restoreReserved`). On `.coldReserved` the reserve downgraded a planned + // restore (or none was planned): only the cold reservation is held, so + // attaching restore-sized KV here would under-reserve and OOM. The + // downgrade already cleared bridge.reservedTokens; req.restoredCheckpoint + // stays nil and the request runs as a cold prefill. + if kvOutcome == .restoreReserved, let acceptedRestore { + await finalizeRestore( req, + id: id, admission: acceptedRestore, promptTokens: promptTokens, - scope: cacheScope + scope: cacheScope, + requestBudget: requestBudget ) } // Re-check the engine is still the one we captured (a reload/ @@ -1544,23 +1764,32 @@ public actor BatchScheduler { admission: plannedRestore ) let kvReservationTokens = acceptedRestore?.reservedTokens ?? requestBudget - guard await reserveKVForRequest( + let kvOutcome = await reserveKVForRequest( requestId: id, requestTokens: requestBudget, reservationTokens: kvReservationTokens, restorePlanned: acceptedRestore != nil - ) else { + ) + guard kvOutcome != .failed else { await dropBridge(requestId: id) continuation.yield(.error("token_budget_exhausted: insufficient global KV cache headroom")) continuation.finish() return stream } - if let acceptedRestore { - await materializeRestoredCheckpoint( + // Materialize the restore ONLY when its restore-sized reservation is held + // (`.restoreReserved`). On `.coldReserved` the reserve downgraded a planned + // restore (or none was planned): only the cold reservation is held, so + // attaching restore-sized KV here would under-reserve and OOM. The + // downgrade already cleared bridge.reservedTokens; req.restoredCheckpoint + // stays nil and the request runs as a cold prefill. + if kvOutcome == .restoreReserved, let acceptedRestore { + await finalizeRestore( req, + id: id, admission: acceptedRestore, promptTokens: promptTokens, - scope: request.cacheScope + scope: request.cacheScope, + requestBudget: requestBudget ) } // Re-check the captured engine is still current after the awaits. diff --git a/provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift b/provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift index b6727c20a9..9ff861a5b3 100644 --- a/provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift +++ b/provider-swift/Sources/ProviderCore/Inference/GlobalKVCacheBudget.swift @@ -47,6 +47,22 @@ public actor GlobalKVCacheBudget { reservations.removeValue(forKey: requestID) } + /// Atomically shrink an existing reservation to a smaller byte count, + /// freeing the difference. `reserve`/`release` cannot express a shrink: + /// `reserve` refuses when an entry already exists for the id, and a + /// release-then-reserve is non-atomic — a concurrent submit could grab the + /// freed headroom in between, making the re-reserve spuriously fail and + /// stranding the request with NO reservation. This only ever lowers the + /// reserved bytes (never grows, never fails), so it is safe to call on the + /// fallback path where a planned restore did not materialize and the request + /// must drop back to its cold-prefill footprint. No-op if the id is unknown. + public func reduceReservation(requestID: String, kvBytesPerToken: Int, tokenCount: Int) { + guard let current = reservations[requestID], kvBytesPerToken > 0, tokenCount > 0 else { return } + let (bytes, overflow) = UInt64(kvBytesPerToken).multipliedReportingOverflow(by: UInt64(tokenCount)) + let newBytes = overflow ? UInt64.max : bytes + if newBytes < current { reservations[requestID] = newBytes } // only ever shrink; frees the difference; never fails + } + /// Total KV bytes currently promised to in-flight requests. The model-load /// gate subtracts this so a new model's weights can't be loaded into memory /// already reserved for a request that is mid-decode (those bytes may not diff --git a/provider-swift/Tests/ProviderCoreTests/BatchSchedulerBudgetTests.swift b/provider-swift/Tests/ProviderCoreTests/BatchSchedulerBudgetTests.swift index 9b17b9502b..aca7a3703d 100644 --- a/provider-swift/Tests/ProviderCoreTests/BatchSchedulerBudgetTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/BatchSchedulerBudgetTests.swift @@ -484,4 +484,316 @@ struct BatchSchedulerBudgetTests { #expect(await kvBudget.outstandingReservedBytes() == 0, "the late KV reservation must be released on the bail path (dropBridge alone no-ops)") } + + // MARK: - PR #325 review: reservation leak on materialize fallback (BUG 1) + + /// A planned + accepted restore charges BOTH accounting systems with the + /// restore-sized (oversized) amount up front: (1) `bridge.reservedTokens` + /// feeding `activeTokenBudgetUsed`, and (2) the global kvBudget byte + /// reservation. When `materializeRestoredCheckpoint` then FALLS BACK + /// (manager missing, materialize nil, bad geometry, or actual > estimate), + /// `req.restoredCheckpoint` stays nil — correct cold prefill — but pre-fix + /// BOTH reservations stayed at the restore size for the request's whole life, + /// permanently over-charging admission under exactly the OOM pressure that + /// triggers restore failures. Post-fix `finalizeRestore` downgrades both to + /// the cold `requestBudget` footprint. + /// + /// This drives the REAL `finalizeRestore` via `_testFinalizeRestoreFallback` + /// (no checkpointManager → materialize short-circuits to false → the + /// downgrade branch runs). Revert-guard: remove the downgrade in + /// `finalizeRestore` and both assertions below flip to the restore-sized + /// amount → fails. + @Test("materialize fallback downgrades BOTH reservations to the cold footprint") + func materializeFallbackDowngradesBothReservations() async { + let kvBudget = GlobalKVCacheBudget() + let scheduler = BatchScheduler( + maxConcurrentRequests: 4, defaultMaxTokens: 4096, kvBudget: kvBudget) + await scheduler._setKvBytesPerTokenForTest(1024) + + // Cold footprint = prompt(100) + max(20) = 120 tokens. Restore was + // accepted at an oversized 500-token reservation. + let promptTokens = Array(repeating: 1, count: 100) + let coldBudget = 120 + let restoreTokens = 500 + + await scheduler._testSeedBridge( + id: "restore", promptTokens: 100, maxTokens: 20, reservedTokens: restoreTokens) + let reserved = await kvBudget.reserve( + requestID: "restore", kvBytesPerToken: 1024, tokenCount: restoreTokens) + #expect(reserved, "precondition: oversized restore reservation succeeds") + #expect(await scheduler.activeTokenBudgetUsed == restoreTokens, + "precondition: scheduler budget charges the restore-sized reservation") + #expect(await kvBudget.outstandingReservedBytes() == UInt64(restoreTokens) * 1024, + "precondition: global KV bytes charge the restore-sized reservation") + + // Materialize falls back (no manager) → both systems must downgrade. + await scheduler._testFinalizeRestoreFallback( + id: "restore", + promptTokens: promptTokens, + maxTokens: 20, + reservedTokens: restoreTokens, + requestBudget: coldBudget + ) + + // (1) global KV reservation == cold bytes, NOT the restore-sized amount. + #expect(await kvBudget.outstandingReservedBytes() == UInt64(coldBudget) * 1024, + "BUG 1: global KV reservation must shrink to the cold requestBudget bytes on fallback") + // (2) bridge.reservedTokens == nil → (3) activeTokenBudgetUsed reflects + // cold (prompt + max), not the restore-sized reservation. + #expect(await scheduler.activeTokenBudgetUsed == coldBudget, + "BUG 1: scheduler budget must fall back to (prompt + max), proving reservedTokens == nil") + } + + /// `reduceReservation` is shrink-only and atomic: it must never raise an + /// existing reservation, and must no-op on an unknown id (so a fallback for a + /// request whose reservation was already released by a concurrent cancel does + /// not resurrect bytes). + @Test("reduceReservation only ever shrinks and no-ops on unknown ids") + func reduceReservationShrinksOnly() async { + let kvBudget = GlobalKVCacheBudget() + _ = await kvBudget.reserve(requestID: "r", kvBytesPerToken: 1024, tokenCount: 500) + let before = await kvBudget.outstandingReservedBytes() + #expect(before == UInt64(500) * 1024) + + // Attempt to GROW → must be ignored. + await kvBudget.reduceReservation(requestID: "r", kvBytesPerToken: 1024, tokenCount: 900) + #expect(await kvBudget.outstandingReservedBytes() == before, + "reduceReservation must never grow a reservation") + + // Shrink → frees the difference. + await kvBudget.reduceReservation(requestID: "r", kvBytesPerToken: 1024, tokenCount: 120) + #expect(await kvBudget.outstandingReservedBytes() == UInt64(120) * 1024, + "reduceReservation must shrink to the smaller footprint") + + // Unknown id → no-op (does not create a reservation). + await kvBudget.reduceReservation(requestID: "ghost", kvBytesPerToken: 1024, tokenCount: 50) + #expect(await kvBudget.outstandingReservedBytes() == UInt64(120) * 1024, + "reduceReservation on an unknown id must not resurrect/create bytes") + } + + // MARK: - PR #325 review: use-after-release during materialization (BUG 2) + + /// During the expensive `mgr.materialize` await, a cancel/timeout can run the + /// bridge cancel path (releaseKVReservation + bridge drop). If materialize + /// then attached the restored caches, they would be allocated against an + /// already-released reservation. The post-materialize guard re-checks + /// `activeBridges[req.requestId]`; if the bridge is gone it returns false + /// WITHOUT setting `req.restoredCheckpoint`, and `finalizeRestore`'s downgrade + /// then no-ops on KV (release already happened) without resurrecting bytes. + /// + /// The full submit→suspend-in-materialize→cancel interleaving needs a live + /// engine + checkpoint manager (BatchedEngine is concrete and cannot be + /// stubbed in a non-live unit test). Here we pin the SIGNAL the guard keys + /// on — once a cancel has dropped the bridge, the fallback path attaches no + /// checkpoint and leaves no dangling reservation. (The guard's exact wiring + /// inside materializeRestoredCheckpoint is verified by inspection; the live + /// submit→cancel interleaving is covered by BatchSchedulerEngineIntegration.) + @Test("a cancel during restore leaves no checkpoint and no dangling reservation") + func cancelDuringRestoreLeavesNoDanglingReservation() async { + let kvBudget = GlobalKVCacheBudget() + let scheduler = BatchScheduler( + maxConcurrentRequests: 4, defaultMaxTokens: 4096, kvBudget: kvBudget) + await scheduler._setKvBytesPerTokenForTest(1024) + + let promptTokens = Array(repeating: 1, count: 100) + await scheduler._testSeedBridge( + id: "restore", promptTokens: 100, maxTokens: 20, reservedTokens: 500) + _ = await kvBudget.reserve(requestID: "restore", kvBytesPerToken: 1024, tokenCount: 500) + + // Cancel fires during materialization: drops the bridge + releases KV + // (exactly what the EngineBridge cancel path does). + await scheduler.cancel(requestId: "restore") + #expect(await scheduler._bridgeIsActiveForTest("restore") == false, + "precondition: cancel dropped the bridge mid-materialize") + #expect(await kvBudget.outstandingReservedBytes() == 0, + "precondition: cancel released the KV reservation") + + // The resumed materialize/finalize must NOT resurrect any reservation: + // the bridge-presence guard returns false before attaching, and the + // downgrade's reduceReservation no-ops on the already-released id. + await scheduler._testFinalizeRestoreFallback( + id: "restore", + promptTokens: promptTokens, + maxTokens: 20, + reservedTokens: 500, + requestBudget: 120 + ) + #expect(await kvBudget.outstandingReservedBytes() == 0, + "BUG 2: a cancel during restore must leave no dangling KV reservation") + #expect(await scheduler.activeTokenBudgetUsed == 0, + "BUG 2: no bridge, no charge — the cancelled request must hold no budget") + } + + // MARK: - Under-reserved restore on reserve downgrade (BUG 3) + + /// The reserve-time downgrade leak. `reserveKVForRequest` tries the + /// restore-sized reservation first; when that fails under memory pressure it + /// clears `bridge.reservedTokens` and reserves only the COLD footprint. The + /// submit paths capture `acceptedRestore != nil` BEFORE the reserve, so + /// pre-fix they still called `finalizeRestore` → `materializeRestoredCheckpoint` + /// afterward. That helper's `actualReservation <= admission.reservedTokens` + /// guard compares actual-vs-estimate (both restore-sized) and never against + /// the cold reservation actually held, so it ATTACHED restore-sized KV backed + /// by only a cold reservation → under-reserved → OOM under exactly the memory + /// pressure that forced the downgrade. The whole point of #324/#325 is + /// "restore never OOMs," so this must be closed. + /// + /// Post-fix `reserveKVForRequest` reports WHICH reservation it secured. When + /// the restore-sized reserve fails but the cold reserve succeeds, the outcome + /// is `.coldReserved`, and the submit paths SKIP restore entirely (the + /// request runs as a cold prefill). This drives the REAL `reserveKVForRequest` + /// via `_testReserveKVForRequest`, using a `GlobalKVCacheBudget` whose memory + /// snapshot fits the cold footprint but not the restore-sized one, and proves: + /// (1) outcome == .coldReserved, (2) the held reservation == cold bytes (not + /// restore-sized), (3) bridge.reservedTokens was cleared by the downgrade so + /// the request attaches NO restored checkpoint (activeTokenBudgetUsed == cold + /// prompt+max). Revert-guard: make `reserveKVForRequest` return a Bool again + /// (so the submit path materializes the restore against the cold reservation) + /// and the outcome can no longer distinguish restore from cold → fails. + @Test("a reserve downgrade reports .coldReserved and holds only the cold footprint") + func reserveDowngradeReportsColdReservedAndHoldsColdBytes() async { + // total memory fits the cold reservation (120 * 1024 = 122_880 B) but not + // the restore-sized one (500 * 1024 = 512_000 B). safetyFactor 1.0, + // reserveBytes 0, active/cache 0 → availableReservationBytes() == total. + let kvBudget = GlobalKVCacheBudget( + reserveBytes: 0, + safetyFactor: 1.0, + memorySnapshot: { (total: 200_000, active: 0, cache: 0) } + ) + let scheduler = BatchScheduler( + maxConcurrentRequests: 4, defaultMaxTokens: 4096, kvBudget: kvBudget) + await scheduler._setKvBytesPerTokenForTest(1024) + + let promptTokens = Array(repeating: 1, count: 100) + let coldBudget = 120 // prompt(100) + max(20) + let restoreTokens = 500 + + // Submit seeds the bridge with the restore-sized reservation BEFORE the + // reserve runs (acceptRestoredCheckpointBudget set bridge.reservedTokens). + await scheduler._testSeedBridge( + id: "restore", promptTokens: 100, maxTokens: 20, reservedTokens: restoreTokens) + #expect(await scheduler.activeTokenBudgetUsed == restoreTokens, + "precondition: bridge charges the restore-sized reservation before reserve") + + // Drive the REAL reserve followed by the REAL submit-path restore + // decision (materialize iff outcome == .restoreReserved). restore-sized + // fails (512_000 > 200_000), cold succeeds (122_880 <= 200_000) → + // .coldReserved → restore SKIPPED → req.restoredCheckpoint stays nil. + let result = await scheduler._testReserveThenMaybeRestore( + id: "restore", + promptTokens: promptTokens, + maxTokens: 20, + requestBudget: coldBudget, + reservationTokens: restoreTokens + ) + #expect(result.outcome == .coldReserved, + "BUG 3: a restore that downgrades to cold must report .coldReserved, not success") + + // (1) Only the cold reservation is held — NOT the restore-sized amount. + #expect(await kvBudget.outstandingReservedBytes() == UInt64(coldBudget) * 1024, + "BUG 3: the downgrade must hold exactly the cold requestBudget bytes") + + // (2) bridge.reservedTokens was cleared by the downgrade → the scheduler + // budget falls back to (prompt + max), proving the restore is dropped. + #expect(await scheduler.activeTokenBudgetUsed == coldBudget, + "BUG 3: the downgrade must clear bridge.reservedTokens so no restore-sized charge survives") + + // (3) The submit path branched on .coldReserved → never called + // finalizeRestore → req.restoredCheckpoint stayed nil (cold prefill). + #expect(result.restoredCheckpointWasNil, + "BUG 3: a .coldReserved request must attach NO restored checkpoint") + } + + /// Companion happy-path: when the restore-sized reservation DOES fit, the + /// outcome is `.restoreReserved` and the full restore-sized amount is held — + /// so the submit path proceeds to materialize the restore. Guards against an + /// over-eager downgrade that would turn every restore into a cold prefill. + @Test("a restore that fits reports .restoreReserved and holds the restore footprint") + func reserveThatFitsReportsRestoreReserved() async { + let kvBudget = GlobalKVCacheBudget( + reserveBytes: 0, + safetyFactor: 1.0, + memorySnapshot: { (total: 1_000_000, active: 0, cache: 0) } + ) + let scheduler = BatchScheduler( + maxConcurrentRequests: 4, defaultMaxTokens: 4096, kvBudget: kvBudget) + await scheduler._setKvBytesPerTokenForTest(1024) + + let restoreTokens = 500 + await scheduler._testSeedBridge( + id: "restore", promptTokens: 100, maxTokens: 20, reservedTokens: restoreTokens) + + let outcome = await scheduler._testReserveKVForRequest( + requestId: "restore", + requestTokens: 120, + reservationTokens: restoreTokens, + restorePlanned: true + ) + #expect(outcome == .restoreReserved, + "a restore-sized reservation that fits must report .restoreReserved") + #expect(await kvBudget.outstandingReservedBytes() == UInt64(restoreTokens) * 1024, + "the held reservation must be the full restore-sized amount when it fits") + #expect(await scheduler.activeTokenBudgetUsed == restoreTokens, + "the restore-sized bridge charge must survive when the reserve succeeds") + } + + /// A cold (no-restore) request must reserve + run exactly as before. With no + /// restore planned the requested amount IS the cold footprint, so a + /// successful reserve reports `.coldReserved` (the submit path then skips the + /// restore block, which is correct — there was never a restore). A failed + /// reserve reports `.failed`. + @Test("a plain cold request reports .coldReserved on success and .failed on overflow") + func plainColdRequestOutcomes() async { + let fits = GlobalKVCacheBudget( + reserveBytes: 0, safetyFactor: 1.0, + memorySnapshot: { (total: 1_000_000, active: 0, cache: 0) }) + let schedulerFits = BatchScheduler( + maxConcurrentRequests: 4, defaultMaxTokens: 4096, kvBudget: fits) + await schedulerFits._setKvBytesPerTokenForTest(1024) + await schedulerFits._testSeedBridge(id: "cold", promptTokens: 100, maxTokens: 20) + + let coldOK = await schedulerFits._testReserveKVForRequest( + requestId: "cold", requestTokens: 120, reservationTokens: 120, restorePlanned: false) + #expect(coldOK == .coldReserved, + "a plain cold request that fits must report .coldReserved (no restore to materialize)") + #expect(await fits.outstandingReservedBytes() == UInt64(120) * 1024, + "the cold reservation must be exactly the request footprint") + + // Tiny budget → even the cold reservation fails → .failed (no restore to + // downgrade to). Mirrors the old `false` return. + let tiny = GlobalKVCacheBudget( + reserveBytes: 0, safetyFactor: 1.0, + memorySnapshot: { (total: 1_000, active: 0, cache: 0) }) + let schedulerTiny = BatchScheduler( + maxConcurrentRequests: 4, defaultMaxTokens: 4096, kvBudget: tiny) + await schedulerTiny._setKvBytesPerTokenForTest(1024) + await schedulerTiny._testSeedBridge(id: "cold", promptTokens: 100, maxTokens: 20) + + let coldFail = await schedulerTiny._testReserveKVForRequest( + requestId: "cold", requestTokens: 120, reservationTokens: 120, restorePlanned: false) + #expect(coldFail == .failed, + "a plain cold request that overflows must report .failed") + #expect(await tiny.outstandingReservedBytes() == 0, + "a failed cold reserve must hold no bytes") + } + + /// No-budgeting path (kvBudget == nil): preserve the legacy "always proceed" + /// behavior. A planned restore reports `.restoreReserved` (so the restore + /// still materializes when budgeting is disabled); a cold request reports + /// `.coldReserved`. Neither can fail. + @Test("no-budgeting path proceeds: restore→.restoreReserved, cold→.coldReserved") + func noBudgetingPathPreservesHappyPath() async { + let scheduler = BatchScheduler(maxConcurrentRequests: 4, defaultMaxTokens: 4096) + await scheduler._testSeedBridge(id: "r", promptTokens: 100, maxTokens: 20) + + let restore = await scheduler._testReserveKVForRequest( + requestId: "r", requestTokens: 120, reservationTokens: 500, restorePlanned: true) + #expect(restore == .restoreReserved, + "with no kvBudget, a planned restore must still materialize (.restoreReserved)") + + let cold = await scheduler._testReserveKVForRequest( + requestId: "r", requestTokens: 120, reservationTokens: 120, restorePlanned: false) + #expect(cold == .coldReserved, + "with no kvBudget, a cold request proceeds as .coldReserved") + } }