diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift index 59ad2a163c..4cf50c83e2 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift @@ -1245,6 +1245,28 @@ public final class EngineV2: CBv2Engine, CBv2NativeWorkShutdownReporting, @unche try submitOrdinary(request).events } + /// Ordinary scheduling with an acknowledgement for this exact stream + /// generation. Terminal delivery and caller cancellation do not release + /// engine ownership: wait for `retirement` before reusing shared capacity. + /// This applies to ordinary autoregressive engines as well as native ones; + /// it does not grant a native shutdown or physical-memory-release proof. + public func submitWithRetirement(_ request: CBv2Request) throws + -> (events: AsyncStream, retirement: CBv2RequestRetirement) + { + if let tracking = nativeShutdownState { + guard tracking.supported else { + throw CBv2NativeShutdownError.unsupportedConsumer + } + try tracking.requireWork() + } + let submitted = try submitOrdinary(request) + return ( + submitted.events, + submitted.registeredStream.map { CBv2RequestRetirement(stream: $0) } + ?? .acknowledged + ) + } + /// Ordinary scheduling plus the actual registered stream generation's /// ownership acknowledgement. Only the tracked native profile may expose /// this serving guarantee. Terminal delivery/caller cancellation alone is @@ -1258,12 +1280,7 @@ public final class EngineV2: CBv2Engine, CBv2NativeWorkShutdownReporting, @unche throw CBv2NativeShutdownError.unsupportedConsumer } try tracking.requireWork() - let submitted = try submitOrdinary(request) - return ( - submitted.events, - submitted.registeredStream.map { CBv2RequestRetirement(stream: $0) } - ?? .acknowledged - ) + return try submitWithRetirement(request) } /// One normalization/admission/registration/scheduling body for both diff --git a/Libraries/MLXLMCommon/README.md b/Libraries/MLXLMCommon/README.md index 0272d5f86a..c6b375efb6 100644 --- a/Libraries/MLXLMCommon/README.md +++ b/Libraries/MLXLMCommon/README.md @@ -292,3 +292,15 @@ end. This helps prevent over-commit when many inferences launch at once. Use `WiredMemoryManager.events()` to observe policy stacking and limit changes in DEBUG builds. The stream is empty in release builds, so event logging is a no-op in production. + +### Continuous-batching request retirement + +`EngineV2.submitWithRetirement(_:)` returns the ordinary event stream and a +`CBv2RequestRetirement` acknowledgement for that exact stream generation. Call +`await submission.retirement.wait()` before releasing capacity shared with other +engines. A watchdog terminal, a cancelled stream consumer, or cancellation of the +waiter does not establish retirement. The acknowledgement completes only when +scheduler, request KV and backend ownership have been released; zero-work +submissions acknowledge immediately. Native-managed engines retain their native +work-admission checks. This request acknowledgement does not replace the separate +native shutdown or physical-memory-release contract. diff --git a/Tests/MLXLMTests/Integration/Engine/OrdinaryRequestRetirementTests.swift b/Tests/MLXLMTests/Integration/Engine/OrdinaryRequestRetirementTests.swift new file mode 100644 index 0000000000..ac99f3f7cf --- /dev/null +++ b/Tests/MLXLMTests/Integration/Engine/OrdinaryRequestRetirementTests.swift @@ -0,0 +1,96 @@ +import Foundation +import MLX +import Testing + +@testable import MLXLMCommon + +@Suite("Ordinary request ownership retirement", .serialized, .tags(.integration)) +struct OrdinaryRequestRetirementTests { + @Test("ordinary requests expose real retirement without a native shutdown contract") + func ordinarySubmission() async throws { + let harness = CBv2SchedHarness() + #expect(harness.engine.nativeShutdownExecutionContractID == nil) + let submission = try harness.engine.submitWithRetirement( + CBv2SchedFixtures.request(prompt: [1, 2, 3], maxTokens: 4)) + let result = await cbv2SchedCollect(submission.events) + await submission.retirement.wait() + #expect(result.finishReason == .length) + #expect(result.tokens.count == 4) + #expect(harness.backend.liveStates == 0) + #expect(harness.engine.capacity().activeRequests == 0) + await harness.engine.shutdown() + } + + @Test("watchdog terminal and waiter cancellation do not acknowledge a live row") + func earlyTerminalRetainsOwnership() async throws { + let layers = CBv2SchedFixtures.tinyLayerKinds() + let backend = CBv2SchedMockBackend() + let model = RetirementGatedModel() + defer { model.release() } + let engine = EngineV2( + model: model, layerKinds: layers, backend: backend, + cacheProvider: CBv2SchedMockCacheProvider(layerKinds: layers), + sampler: CBv2GreedySampler(), detokenizerFactory: CBv2SchedScriptedDetokFactory(), + loopConfig: .init(stepTimeout: 0.05, watchdogInterval: 0.01)) + let submission = try engine.submitWithRetirement( + CBv2SchedFixtures.request(prompt: [1], maxTokens: 100)) + let retired = RetirementFlag() + let waiter = Task { + await submission.retirement.wait() + retired.set() + } + let result = await cbv2SchedCollect(submission.events) + if case .terminal(let cause, _) = result.finishReason { + #expect(cause == .watchdog) + } else { + Issue.record("expected an early watchdog terminal") + } + #expect(backend.liveStates > 0) + waiter.cancel() + try await Task.sleep(nanoseconds: 50_000_000) + #expect(!retired.value, "cancelling an ownership wait cannot free a live engine row") + model.release() + await waiter.value + #expect(retired.value && backend.liveStates == 0) + await engine.shutdown() + } + + @Test("zero work acknowledges immediately and closed engines reject new work") + func immediateAndClosed() async throws { + let harness = CBv2SchedHarness() + let submission = try harness.engine.submitWithRetirement( + CBv2SchedFixtures.request(prompt: [1], maxTokens: 0)) + await submission.retirement.wait() + #expect(harness.backend.makeCalls == 0) + await harness.engine.shutdown() + #expect(throws: (any Error).self) { + try harness.engine.submitWithRetirement( + CBv2SchedFixtures.request(prompt: [1], maxTokens: 1)) + } + } +} + +private final class RetirementFlag: @unchecked Sendable { + private let lock = NSLock() + private var completed = false + func set() { lock.withLock { completed = true } } + var value: Bool { lock.withLock { completed } } +} + +private final class RetirementGatedModel: CBv2SteppableModel, @unchecked Sendable { + private let model = CBv2SchedScriptedModel() + private let condition = NSCondition() + private var released = false + func release() { + condition.lock() + released = true + condition.broadcast() + condition.unlock() + } + func forward(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) -> MLXArray { + condition.lock() + while !released { condition.wait() } + condition.unlock() + return model.forward(tokens: tokens, caches: caches) + } +} diff --git a/fork.yaml b/fork.yaml index 3ad5e3b825..12d2324dba 100644 --- a/fork.yaml +++ b/fork.yaml @@ -57,7 +57,9 @@ def: `EngineV2` / `EngineLoopV2` (the step loop and its forward-shape dispatch), `SchedulerV2` (admission, capacity shrink-retry, solo-prefill stripe, packed prefill, partial-prefill cap), `AdmissionV2` + first-token deadline admission with content-free unbounded guard reasons, - monotonic phase leases, per-row samplers + monotonic phase leases, and ordinary submission with exact stream-generation retirement + acknowledgements for hosts sharing capacity across engines. Early consumer termination + never acknowledges a live row; native work-admission guards remain authoritative. Per-row samplers with tool-constraint enforcement (`TokenConstraintSamplerV2`, `ToolConstraintV2`), the streaming detokenizer (`DetokenizerV2`, character-exact on non-append-only decodes), attention metadata/packet capture-and-replay for parity testing, logit diagnostics, request @@ -148,6 +150,7 @@ def: asymmetric model and actual complete-checkpoint lifecycle used by the retention test. globs: - "Tests/MLXLMTests/CBv2*" + - "Tests/MLXLMTests/Integration/Engine/**" - "Tests/MLXLMTests/DeadlineAdmission/**" - "Tests/MLXLMTests/Paged*" - "Tests/MLXLMTests/Native*Checkpoint*"