diff --git a/changelog.d/deadline-refusal-streak-expiry.md b/changelog.d/deadline-refusal-streak-expiry.md new file mode 100644 index 0000000000..2c3d6a562c --- /dev/null +++ b/changelog.d/deadline-refusal-streak-expiry.md @@ -0,0 +1,6 @@ +### A stale slow prefill estimate stops refusing after three deadline refusals + +- A `deadline_unreachable` refusal admits nothing, so it measures nothing. An idle Mac whose only prefill measurement was slow and is now older than 120 seconds could go on refusing from it for up to 30 minutes. After three such refusals in a row with nothing admitted in between, the provider admits the next request of at most 1,024 prompt tokens that finds the Mac idle without a time projection, and that request's prefill replaces the estimate. A longer prompt is still refused until a small request has remeasured the Mac. +- Only refusals the Mac's own isolated prefill rate explains count: the Mac was idle and the projection priced nothing but that request's prompt. Refusals beside other work, refusals for memory or capacity, reviewed calibrations, native-media requests and native block engines (which keep their own recovery probe) are unchanged. +- A request whose deadline has already passed is still refused, and a measurement newer than 120 seconds still refuses as measured. A Mac that really is too slow admits one such small request per loaded model every 120 seconds; that request can miss its first-content deadline where it would have been refused at once. +- No wire field changes. `DARKBLOOM_TTFT_ADMISSION_FIXES=0` turns this off with the other estimator corrections. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 9706e6f378..66acbdb6be 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1,6 +1,6 @@ # Hardware support and the provider memory model -> Last updated: 2026-11-09 +> Last updated: 2026-11-10 What hardware the provider runs on and how it decides, in bytes, whether a model may load and how much KV cache each resident model may use. Read this to @@ -864,9 +864,17 @@ serving Mac, so the same request can project differently on other hardware: (`provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift`, `IsolatedPrefillAdmissionRate.anchorFloorFraction`). Native engines keep their recovery probe instead. +- Three consecutive refusals an ordinary engine made on an idle Mac from its + isolated prefill rate alone expire evidence older than 120 seconds + (`provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift`, + `DeadlineRefusalStreak`). The next request of at most 1,024 prompt tokens + that finds the Mac idle is submitted without a time projection and + remeasures the rate on that Mac, at that power and thermal state. A longer + prompt is still refused. A refusal for physical capacity never counts. -The anchor and floor shape admission only. The published isolated rate, -capacity wire fields and the external platform's memory contract are unchanged. +The anchor, floor and refusal streak shape admission only. The published +isolated rate, capacity wire fields and the external platform's memory +contract are unchanged. ### Cross-repository agreement diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 001cf9cb3e..0cd823021f 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-11-09 +> Last updated: 2026-11-10 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -2229,7 +2229,7 @@ This removes the previous doubling of projected processing time; an EWMA is a point estimate and does not guarantee the next request's speed. Actual elapsed deadline expiry, queue/cache projection and physical admission still apply. -Three estimator corrections shape those inputs; +Four estimator corrections shape those inputs; `DARKBLOOM_TTFT_ADMISSION_FIXES=0` restores the previous estimators (`provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift`). @@ -2289,6 +2289,37 @@ that floor, because the anchor comes from a short calibration cell evidence expires after 120 seconds. The published isolated rate is unchanged. A late older cold sample no longer restarts the combined prefill EWMA. +A refusal admits nothing, so it measures nothing: those idle rules are the +only way expired evidence that refuses is replaced, and with no anchor, with an +anchor that is itself slow, or off nominal posture they keep it for 30 minutes. +Ordinary engines therefore count consecutive `deadline_unreachable` refusals +that the isolated prefill rate alone explains +(`provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift`, +`DeadlineRefusalStreak`; +`provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Admission.swift`, +`EngineV2Bridge.recordDeadlineRefusal`): the Mac was idle, the engine's bounded +projection priced only this request's own prompt, and the policy carried no +reviewed calibration and no native-media rate. A refusal beside other work or +from a fail-closed (unbounded) projection, physical capacity included, never +counts, and any engine admission ends the streak. After three, evidence older +than the 120-second freshness window stops blocking the next request of at +most 1,024 prompt tokens that finds the Mac idle +(`provider-swift/Sources/ProviderCore/Inference/Performance/PrefillEvidenceRecovery.swift`, +`PrefillEvidenceRecovery.maximumPromptTokens`, the native recovery probe's +limit). The bridge builds no projection policy for that request, so it is +submitted the way a request with no measured rate is. Absolute expiry still +applies, the decision profile reports `projection = not_attempted` with +`projection_reason = unmeasured_prefill`, and the request's isolated prefill +replaces the expired aggregate and its prompt-size bucket. A longer prompt is +still refused from the expired evidence and leaves the streak full: +unprojected, it could hold a slow Mac until its deadline. Fresh evidence, a +fresh prompt-size bucket for this prompt included, refuses as measured +however many requests it refuses. An admission that ends a full streak starts +a 120-second retry interval, so a loaded model on a Mac that really is too +slow admits one such small request per interval, even when that request ends +before its prompt completes. That request can miss its first-content deadline +where it would have been refused at once. + An independent reviewed deadline profile carries `deadline_calibration`: prompt/context bands, actual cold/reused prefix state, competing profile identities and work limits, phase rates, and a diff --git a/docs/developer/test.md b/docs/developer/test.md index c4f48f9644..d1109ea60a 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-11-09 +> Last updated: 2026-11-10 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -710,8 +710,12 @@ lockouts through the bridge and the real submission path, another model's lease or device activity on a shared whole-Mac service budget, a fresh long-prompt bucket below the floor, decode step-shape measurement and plumbing (including the first-token step's rows), rate and shape kept coupled across -batch widths, the per-row charge kept for reviewed calibrations, and a late -older cold sample. In the SDK, the unit suite +batch widths, the per-row charge kept for reviewed calibrations, a late +older cold sample, and the refusal streak: three idle refusals over stale +evidence admit the next request of at most 1,024 prompt tokens, whose prefill +replaces the estimate, while a longer prompt, fresh evidence, an expired +absolute deadline, a busy Mac, the kill switch and the retry interval keep +refusing. In the SDK, the unit suite `CBv2PerBatchDecodeChargeTests` pins per-step decode accounting, MTP-measured shape conversion, the mirrored MTP depth gates (batch gate and automatic envelope, with a driver check that the ceiling bounds every live plan depth) diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index c5144e63dd..8b3f59f2c5 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1,6 +1,6 @@ # Configuration reference -> Last updated: 2026-11-08 +> Last updated: 2026-11-10 Provider CLI and native-runtime environment variables, compiled defaults and reading symbols. Secrets are named, never valued. Unless specified otherwise, values are read at process start. @@ -540,7 +540,7 @@ and rollback are defined in the [provider configuration reference](../provider/c | `DARKBLOOM_MTP_VERIFICATION_MODE` | `rectangular`, `serial`, `serial_target`, `automatic` | `automatic` | `provider-swift/Sources/ProviderBenchmark/MTPProductionSession.swift` | MTP verification strategy (benchmark session). | | `DARKBLOOM_MTP_ACCEPTANCE` | `exact`, `typical`, `typical:` (finite positive delta) | `exact` | `provider-swift/Sources/ProviderBenchmark/MTPProductionSession.swift`; `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift` (`benchmarkOverride`) | MTP draft acceptance rule (benchmark session only). An unrecognized value uses `exact`. Serving reads no environment variable for this rule; it reads `[backend] mtp_acceptance` and `mtp_acceptance_by_model` in [`provider.toml`](../provider/cli-reference.md#providertoml-keys-read-by-the-cli). | | `DARKBLOOM_PREFILL_DEADLINE_MODE` | exactly `off` disables; any other value enforces | `enforce` | `provider-swift/Sources/ProviderCore/Inference/Engine/PrefillDeadlineMode.swift` (`PrefillDeadlineMode.resolve`) | Prefill-deadline admission on the provider. Read only when `[backend] prefill_deadline_mode` is absent from `provider.toml`; that key takes precedence. | -| `DARKBLOOM_TTFT_ADMISSION_FIXES` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`DeadlineAdmissionFixes`) | Deadline-admission estimator corrections: per-batch decode charging, anchored isolated-prefill rate, newest-observation freshness. Off restores the previous estimators. Forwarded to the launchd provider job. | +| `DARKBLOOM_TTFT_ADMISSION_FIXES` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`DeadlineAdmissionFixes`) | Deadline-admission estimator corrections: per-batch decode charging, anchored isolated-prefill rate, newest-observation freshness, refusal-streak expiry of stale isolated-prefill evidence. Off restores the previous estimators. Forwarded to the launchd provider job. | | `DARKBLOOM_TTFT_SHAPE_WARMUP` | trimmed, case-insensitive `0`, `false`, `no`, `off` disable; `always` skips the probe | unset: probe-gated warmup | `provider-swift/Sources/ProviderCore/Inference/Performance/ModelCalibrationPolicy.swift` (`shapeWarmupMode`) | Excluded load-time [shape warmup](../architecture/inference.md#model-startup-calibration) for ordinary `EngineV2` slots: a 128-token shader-cache probe runs twice and only a cold cache runs the shape cells, within 20 seconds per engine. Trains no rate or counter. Forwarded to the LaunchAgent. | | `DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL` | integer layers | projected from `provider.toml` (`18`) | `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift` | Gemma-4 prefill chunk-eval layers; the provider sets it for the engine, `scripts/install.sh` sets `18` for the smoke test. | | `DARKBLOOM_TTFT_GDN_BLOCKED` | `0`, `false`, `no`, `off` keep the stock kernel; `packed` or `rows` force that kernel; unset or any other value probes. Case-insensitive; surrounding whitespace is ignored | probe | `libs/mlx-swift-lm/Libraries/MLXLMCommon/GatedDelta.swift` (`GatedDeltaPrefill.mode`, `GatedDeltaPrefill.kernel`) | Selects the Gated DeltaNet prompt-window kernel of `qwen3_5`, `qwen3_5_moe` and `prism_hadamard_qwen35` models ([mechanism](../architecture/inference.md#context)). The default probe keeps a four-row kernel only where it reproduces `gated_delta_step` bit for bit on the GPU; it does not compare speed, so `0` is the rollback where a kept kernel is slower. Forced kernels skip that check and are for A/B measurement only. Decode, MTP verification and masked updates always use the stock kernel. Read once per process. Forwarded to the LaunchAgent. | diff --git a/docs/reference/prediction-decision-telemetry.md b/docs/reference/prediction-decision-telemetry.md index 8723303c31..2155132da9 100644 --- a/docs/reference/prediction-decision-telemetry.md +++ b/docs/reference/prediction-decision-telemetry.md @@ -1,6 +1,6 @@ # Prediction decision telemetry -> Last updated: 2026-10-22 +> Last updated: 2026-11-10 Optional attempt records compare what the coordinator selected with what the provider decided. They explain decisions; they do not establish whether a @@ -18,7 +18,7 @@ terminal messages. Sources: [coordinator/protocol/profile_deadline.go](https://g | `verdict` | `accepted`, `deadline_unreachable`, `expired_before_submit`, `cancelled`, `other`. `cancelled` without a returned verdict does not prove the engine never accepted. | | `continuation` | `expired`, `cancelled`, `other`, or absent. Annotates a returned verdict when the bridge's immediate continuation is stopped; it does not replace the verdict. | | `projection` | `bounded`, `unbounded`, `not_attempted`, `other`, or absent. Unbounded is distinct from a measured large duration. | -| `projection_reason` | No service-time prediction: `no_deadline`, `mode_off`, `unsupported_scheduler`, `multimodal`, `unmeasured_prefill`, `other`, or absent. Includes guarded native-media bootstrap; it does not describe an engine projection failure. | +| `projection_reason` | No service-time prediction: `no_deadline`, `mode_off`, `unsupported_scheduler`, `multimodal`, `unmeasured_prefill`, `other`, or absent. Includes guarded native-media bootstrap; it does not describe an engine projection failure. `unmeasured_prefill` also covers a measured rate the provider set aside as expired: idle expiry, or a full refusal streak over stale evidence ([deadlines](../architecture/inference.md#deadlines)). | | `unbounded_reason` | Optional closed engine cause for `projection=unbounded`, listed below. Missing means the engine supplied no cause; it is never reconstructed from occupancy or remaining time. Unknown future values fold to `other`. | | `observed_us` | Offset from the provider profile anchor when the bridge receives a verdict or observes pre-submit expiry. **Not the engine's atomic refusal time.** | | `remaining_us` | Remaining deadline at that provider observation, clamped at zero. | diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Admission.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Admission.swift index a7aba7fd97..d26681ca4a 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Admission.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Admission.swift @@ -102,12 +102,24 @@ extension EngineV2Bridge { macIdle: macIdle(except: requestID), nominalPosture: calibrationPosturePermitsWork()) } - if promptTokens > 0, let shapeRate = performanceMeasurements.freshIsolatedPrefillRate(promptTokens: promptTokens) { - prefillRate = prefillRate.map { min($0, shapeRate) } ?? shapeRate - } + let shapeRate = promptTokens > 0 + ? performanceMeasurements.freshIsolatedPrefillRate(promptTokens: promptTokens) : nil + if let shapeRate { prefillRate = prefillRate.map { min($0, shapeRate) } ?? shapeRate } let calibration = requestID.flatMap { calibratedDeadlinePolicy(requestID: $0, promptTokens: promptTokens, promptWork: promptWork) } + if admissionFixes, !supportsPrefillRecoveryRetirement, calibration == nil, !nativeMedia, + promptTokens <= PrefillEvidenceRecovery.maximumPromptTokens, + deadlineRefusalStreak.expiresStaleEvidence(), isolatedPrefillEvidenceExpired(), + shapeRate == nil, macIdle(except: requestID) { + // Refusals measure nothing, so expired evidence that keeps refusing + // an idle Mac is treated like none: absolute expiry only, and this + // request's isolated prefill replaces it. A fresh prompt-size + // bucket is a current measurement and still refuses. As for the + // native recovery probe, only a small prompt runs unprojected: a + // long one could hold a slow Mac until its deadline. + return nil + } guard prefillRate != nil || calibration != nil || nativeMedia else { return nil } // The decode EWMA is a per-request rate: charge one measured step per // projected batch step, not every row's tokens. @@ -134,6 +146,22 @@ extension EngineV2Bridge { return serviceBudget?.isIdle(except: requestID.map { serviceOwnerPrefix + ":" + $0 }) ?? true } + /// Count a refusal toward `deadlineRefusalStreak` only when the isolated + /// prefill rate alone explains it: an ordinary engine on an idle Mac + /// priced nothing but this request's own prompt. Queue or decode work, + /// a reviewed calibration, native media and every fail-closed (unbounded) + /// projection are refusals a new prefill measurement would not change. + func recordDeadlineRefusal( + requestID: String, policy: CBv2FirstTokenDeadlineAdmission, work: CBv2FirstTokenProjectedWork + ) { + guard admissionFixes, !supportsPrefillRecoveryRetirement, + policy.calibration == nil, policy.nativeTargetPrefill == nil, + case .bounded(let projected, _) = work, projected.decodeTokens == 0, + macIdle(except: requestID) + else { return } + deadlineRefusalStreak.recordRefusal() + } + /// Move post-commit cancellation cleanup out of the cancelling task. The /// retained IDs block provider- and engine-ID reuse while the background /// owner holds every pre-submit reservation through actual engine diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift index 9d76f3ebe6..3e290fcd65 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift @@ -871,6 +871,7 @@ extension EngineV2Bridge { switch result { case .admitted(let stream, let projectedWork, let admittedAt, let retirement): prefillEvidenceRecovery.admit(id) + deadlineRefusalStreak.recordAdmission() profile?.observeDeadlineDecision( .accepted, work: projectedWork, deadline: firstContentDeadline) if Task.isCancelled || pendingCancellationIDs.contains(id) { @@ -953,6 +954,7 @@ extension EngineV2Bridge { case .deadlineUnreachable(let projectedWork): profile?.observeDeadlineDecision( .deadlineUnreachable, work: projectedWork, deadline: firstContentDeadline) + recordDeadlineRefusal(requestID: id, policy: admission, work: projectedWork) if Task.isCancelled || pendingCancellationIDs.contains(id) { profile?.stopDeadlineContinuation(.cancelled) // Refused at admission after a latched cancel: nothing @@ -995,6 +997,7 @@ extension EngineV2Bridge { } else { events = try engine.submit(engineRequest) } + deadlineRefusalStreak.recordAdmission() profile?.observeDeadlineDecision(.accepted, deadline: firstContentDeadline) if prefillEvidenceRecovery.owner == id { do { @@ -1030,6 +1033,7 @@ extension EngineV2Bridge { httpResponse?.applyPendingCancellation() } catch let cancellation as CBv2FirstTokenAdmissionCancellation { prefillEvidenceRecovery.admit(id) + deadlineRefusalStreak.recordAdmission() // This exception proves acceptance but carries no projected work. profile?.observeDeadlineDecision( .accepted, deadline: firstContentDeadline, continuation: .cancelled) diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift index 7f79ac716e..20ec9ad33c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift @@ -384,6 +384,9 @@ public actor EngineV2Bridge { /// Latest published calibration-cell isolated rate: measured idle at /// nominal posture with caching off. Anchors admission's isolated rate. var calibratedIsolatedPrefillTps: Double? + /// Deadline refusals since the last admission that only the isolated + /// prefill rate explains. A full streak expires stale evidence. + var deadlineRefusalStreak = DeadlineRefusalStreak() /// Prompt samples faster than this are dropped, calibration cells /// included. Equal to the coordinator's bound on published prefill rates. /// Tests of toy-weight models, which prefill near it, remove it, so diff --git a/provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift b/provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift index 5bde4fcbff..44048cd013 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift @@ -113,3 +113,45 @@ enum IsolatedPrefillAdmissionRate { return max(observed, anchor * anchorFloorFraction) } } + +/// Consecutive `deadline_unreachable` refusals an ordinary engine made on an +/// idle Mac from its isolated prefill rate alone, with nothing admitted in +/// between. A refusal measures nothing, so expired evidence that refuses is +/// never replaced: with no calibration anchor, with an anchor that is itself +/// slow, or off nominal posture, `IsolatedPrefillAdmissionRate` keeps it for +/// thirty minutes. +/// +/// After `threshold` such refusals the caller stops projecting from evidence +/// older than `EnginePerformanceMeasurements.freshness` for the next request +/// of at most `PrefillEvidenceRecovery.maximumPromptTokens` prompt tokens +/// that finds the Mac idle. That request is submitted like one with no +/// measured rate (its absolute deadline still applies) and its isolated +/// prefill replaces the expired estimate. A longer prompt is still refused +/// from the expired evidence and leaves the streak full: unprojected, it +/// could hold a slow Mac until its deadline. Fresh evidence always refuses +/// as measured. A Mac that really is too slow may end the admitted request +/// before it measures anything; `retryInterval` holds it to one such +/// admission per interval. +struct DeadlineRefusalStreak { + /// One refusal can be one long prompt and two a client's retry of it. + static let threshold = 3 + static let retryInterval = EnginePerformanceMeasurements.freshness + + private(set) var refusals = 0 + private var retryAfter: ContinuousClock.Instant? + + mutating func recordRefusal() { + refusals = min(refusals + 1, Self.threshold) + } + + func expiresStaleEvidence(at now: ContinuousClock.Instant = .now) -> Bool { + refusals >= Self.threshold && (retryAfter.map { now >= $0 } ?? true) + } + + /// Any engine admission ends the streak. One that ends a full streak + /// starts the retry interval whether or not it goes on to measure. + mutating func recordAdmission(at now: ContinuousClock.Instant = .now) { + if refusals >= Self.threshold { retryAfter = now.advanced(by: Self.retryInterval) } + refusals = 0 + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Performance/Deadline/AdmissionRateEstimatorTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Performance/Deadline/AdmissionRateEstimatorTests.swift index 99d0ab3076..4db3ad1ac4 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Performance/Deadline/AdmissionRateEstimatorTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Performance/Deadline/AdmissionRateEstimatorTests.swift @@ -472,6 +472,259 @@ struct AdmissionRateEstimatorTests { #expect(measurements.observationAge("isolated_prefill", now: at + .seconds(1)) == .seconds(122)) #expect(!measurements.coversObservation("isolated_prefill", at: at + .seconds(1))) } + + // MARK: - Refusal streak: a refused request measures nothing + + /// A recovery-sized prompt: the size `submit` sends unless told otherwise. + private static let smallPrompt = 1_000 + + /// A scripted-refusal bridge whose only isolated-prefill evidence is one + /// slow sample `age` old, in the prompt-size bucket `submit` uses. With no + /// calibration anchor, neither the idle anchor nor the short expiry applies. + private func slowBridge(fixes: Bool = true, age: Duration = .seconds(300), + kvBudget: GlobalKVCacheBudget? = nil) async -> (EngineV2Bridge, PrefillScriptEngine) { + let (bridge, engine) = self.bridge(fixes: fixes, kvBudget: kvBudget) + engine.setDeadlineBehavior(.reject) + await bridge.applyRateObservation(observation("isolated_prefill", tps: 50, + at: ContinuousClock.now - age, prompt: Self.smallPrompt), requestID: "slow", calibration: false) + return (bridge, engine) + } + + private func submit(_ bridge: EngineV2Bridge, _ id: String, tokens: Int = smallPrompt, + deadline: FirstContentDeadline = .init(relativeBudgetMilliseconds: 12_000), + profile: RequestProfileBuilder? = nil) async throws -> AsyncStream { + try await bridge.submitTokenized(promptTokens: Array(repeating: 1, count: tokens), + request: ChatCompletionRequest(model: "gemma-4-26b-qat-4bit", messages: [], max_tokens: 8), + requestId: id, firstContentDeadline: deadline, profile: profile) + } + + private func refuse(_ bridge: EngineV2Bridge, tokens: Int = smallPrompt, _ ids: String...) async { + for id in ids { + await #expect(throws: PreContentDeadlineFailure.deadlineUnreachable) { + _ = try await submit(bridge, id, tokens: tokens) + } + } + } + + /// Ends the one ordinarily submitted request. A nil prefill time ends it + /// before any prompt receipt, as a cancel during prefill does. + private func finish(_ stream: AsyncStream, on engine: PrefillScriptEngine, + tokens: Int = smallPrompt, prefillMilliseconds: UInt64?) async throws { + let consumer = Task { for await _ in stream {} } + let continuation = try #require(engine.continuations.last) + if let prefillMilliseconds { + engine.completeColdPrefill(milliseconds: prefillMilliseconds) + continuation.yield(.delta(text: "x", tokens: [11], logprobs: nil)) + } + continuation.yield(.finished(reason: prefillMilliseconds == nil ? .cancelled : .stop, + usage: CBv2Usage(promptTokens: tokens, completionTokens: prefillMilliseconds == nil ? 0 : 1))) + continuation.finish() + await consumer.value + } + + @Test("three refusals on an idle Mac expire stale evidence; the next request is admitted and remeasures") + func refusalStreakExpiresStaleEstimate() async throws { + let (bridge, engine) = await slowBridge() + await refuse(bridge, "refused-1", "refused-2", "refused-3") + #expect(engine.deadlineAdmissions.count == 3) + #expect(engine.deadlineAdmissions.allSatisfy { $0.conservativePrefillTokensPerSecond == 50 }) + #expect(engine.ordinarySubmissionCount == 0) + + // Nothing was measured by those refusals. The next request is checked + // against its absolute deadline only, like one with no measured rate. + let profile = RequestProfileBuilder() + let stream = try await submit(bridge, "admitted", profile: profile) + #expect(engine.deadlineAdmissions.count == 3) + #expect(engine.ordinarySubmissionCount == 1) + #expect(profile.wireObject().deadlineDecision?.verdict == .accepted) + #expect(profile.wireObject().deadlineDecision?.projection == .notAttempted) + + // Its isolated prefill (1,000 tokens in one second) replaces the + // expired estimate, and later requests are projected at that rate. + try await finish(stream, on: engine, prefillMilliseconds: 1_000) + #expect(await bridge._testIsolatedPrefillTps() == 1_000) + await refuse(bridge, "after-refresh") + #expect(engine.deadlineAdmissions.count == 4) + #expect(engine.deadlineAdmissions.last?.conservativePrefillTokensPerSecond == 1_000) + #expect(engine.ordinarySubmissionCount == 1) + await bridge.shutdown() + } + + @Test("a Mac the admitted request measures as slow goes back to refusing") + func refusalStreakProbeConfirmsSlowMac() async throws { + let (bridge, engine) = await slowBridge() + await refuse(bridge, "refused-1", "refused-2", "refused-3") + let stream = try await submit(bridge, "admitted") + // 1,000 tokens in twenty seconds: the estimate was right. + try await finish(stream, on: engine, prefillMilliseconds: 20_000) + #expect(await bridge._testIsolatedPrefillTps() == 50) + await refuse(bridge, "slow-1", "slow-2", "slow-3", "slow-4", "slow-5") + #expect(engine.deadlineAdmissions.count == 8) + #expect(engine.deadlineAdmissions.suffix(5).allSatisfy { $0.conservativePrefillTokensPerSecond == 50 }) + #expect(engine.ordinarySubmissionCount == 1) + await bridge.shutdown() + } + + @Test("an admitted request that measures nothing does not reopen admission straight away") + func refusalStreakRetryIsBounded() async throws { + let (bridge, engine) = await slowBridge() + await refuse(bridge, "refused-1", "refused-2", "refused-3") + let stream = try await submit(bridge, "admitted") + // Ended before its prompt completed: the old evidence stays expired. + try await finish(stream, on: engine, prefillMilliseconds: nil) + #expect(await bridge._testIsolatedPrefillTps() == 50) + await refuse(bridge, "again-1", "again-2", "again-3", "again-4", "again-5") + #expect(engine.deadlineAdmissions.count == 8) + #expect(engine.ordinarySubmissionCount == 1) + await bridge.shutdown() + } + + @Test("a full refusal streak waits for an idle Mac before it admits") + func busyMacDefersStreakExpiry() async throws { + let (bridge, engine) = await slowBridge() + await refuse(bridge, "refused-1", "refused-2", "refused-3") + // Beside other work the admitted prefill would not be an isolated sample. + await bridge.insertPendingSubmissionForTesting("queued-elsewhere") + await refuse(bridge, "beside-other-work") + #expect(engine.deadlineAdmissions.count == 4) + #expect(engine.ordinarySubmissionCount == 0) + await bridge.removePendingSubmissionForTesting("queued-elsewhere") + let stream = try await submit(bridge, "idle-again") + #expect(engine.deadlineAdmissions.count == 4) + #expect(engine.ordinarySubmissionCount == 1) + try await finish(stream, on: engine, prefillMilliseconds: 1_000) + await bridge.shutdown() + } + + @Test("a request whose absolute deadline has passed is refused whatever the refusal streak") + func expiredDeadlineStillRefusedAfterStreak() async throws { + let (bridge, engine) = await slowBridge() + await refuse(bridge, "refused-1", "refused-2", "refused-3") + let profile = RequestProfileBuilder() + await #expect(throws: PreContentDeadlineFailure.deadlineUnreachable) { + _ = try await submit(bridge, "expired", + deadline: .init(relativeBudgetMilliseconds: 0, receivedAt: .now), profile: profile) + } + #expect(profile.wireObject().deadlineDecision?.verdict == .expiredBeforeSubmit) + // Refused before any engine submission, projected or not. + #expect(engine.deadlineAdmissions.count == 3) + #expect(engine.ordinarySubmissionCount == 0) + #expect(await bridge._testPendingSubmissionCount() == 0) + await bridge.shutdown() + } + + @Test("fresh slow evidence keeps refusing however many requests it refuses") + func freshSlowEstimateKeepsRefusing() async throws { + let (bridge, engine) = await slowBridge(age: .zero) + await refuse(bridge, "slow-1", "slow-2", "slow-3", "slow-4", "slow-5", "slow-6") + #expect(engine.deadlineAdmissions.count == 6) + #expect(engine.deadlineAdmissions.allSatisfy { $0.conservativePrefillTokensPerSecond == 50 }) + #expect(engine.ordinarySubmissionCount == 0) + await bridge.shutdown() + } + + @Test("a fresh prompt-size bucket keeps refusing after a streak over a stale aggregate") + func freshBucketKeepsRefusingAfterStreak() async throws { + let (bridge, engine) = await slowBridge() + // A wide calibration cell refreshes its prompt-size bucket and leaves + // the aggregate, which stays expired, alone. + await bridge.applyRateObservation( + EngineRateObservation(phase: "isolated_prefill", tps: 50, prompt: Self.smallPrompt, + context: Self.smallPrompt, + cache: "cold", overlap: .init(contended: false, peakRequests: 2), at: .now, + postureEpoch: nil, aggregate: false), + requestID: "wide-cell", calibration: true) + #expect(await bridge.isolatedPrefillEvidenceExpired()) + await refuse(bridge, "slow-1", "slow-2", "slow-3", "slow-4", "slow-5") + #expect(engine.deadlineAdmissions.count == 5) + #expect(engine.ordinarySubmissionCount == 0) + await bridge.shutdown() + } + + @Test("with the kill switch off, refusals never expire the estimate") + func killSwitchKeepsRefusingAfterStreak() async throws { + let (bridge, engine) = await slowBridge(fixes: false) + await refuse(bridge, "refused-1", "refused-2", "refused-3", "refused-4", "refused-5") + #expect(engine.deadlineAdmissions.count == 5) + #expect(engine.ordinarySubmissionCount == 0) + await bridge.shutdown() + } + + @Test("refusals beside another model's work do not count toward the streak") + func refusalsBesideOtherWorkAreNotCounted() async throws { + let budget = GlobalKVCacheBudget(capFraction: 1, activationReserveBytes: 0, + memorySnapshot: { .init(total: 64 << 30, active: 0, cache: 0, systemAvailable: 64 << 30) }) + let services = budget.serviceBudget + let (bridge, engine) = await slowBridge(kvBudget: budget) + // Queue or device contention, not the estimate, may explain these. + #expect(services.acquire(ownerID: "other-model:busy", concurrency: 2)) + await refuse(bridge, "busy-1", "busy-2", "busy-3") + services.release(ownerID: "other-model:busy") + await refuse(bridge, "idle-1") + #expect(engine.deadlineAdmissions.count == 4) + #expect(engine.ordinarySubmissionCount == 0) + await bridge.shutdown() + } + + @Test("a full streak admits only a prompt of recovery size; a longer one is still refused") + func refusalStreakAdmitsOnlyRecoverySizedPrompt() async throws { + let limit = PrefillEvidenceRecovery.maximumPromptTokens + #expect(limit == 1_024) + let (bridge, engine) = await slowBridge() + await refuse(bridge, "refused-1", "refused-2", "refused-3") + // A long prompt that the stale rate refuses could run to its deadline + // unprojected. It is refused as before and leaves the streak full. + await refuse(bridge, tokens: limit + 1, "just-over") + await refuse(bridge, tokens: 30_000, "long") + #expect(engine.deadlineAdmissions.count == 5) + #expect(engine.deadlineAdmissions.allSatisfy { $0.conservativePrefillTokensPerSecond == 50 }) + #expect(engine.ordinarySubmissionCount == 0) + let stream = try await submit(bridge, "at-limit", tokens: limit) + #expect(engine.deadlineAdmissions.count == 5) + #expect(engine.ordinarySubmissionCount == 1) + // 1,024 tokens in 512 ms. + try await finish(stream, on: engine, tokens: limit, prefillMilliseconds: 512) + #expect(await bridge._testIsolatedPrefillTps() == 2_000) + await bridge.shutdown() + } + + @Test("a slow calibrated Mac keeps refusing long prompts however many it refuses") + func longPromptsNeverOpenUnprojectedAdmission() async throws { + let (bridge, engine) = bridge(fixes: true) + engine.setDeadlineBehavior(.reject) + // The startup cell itself measured 50 tok/s and nothing ran since, so + // the idle anchor prices every request at that rate. + await bridge.applyRateObservation(observation("isolated_prefill", tps: 50, + at: ContinuousClock.now - .seconds(300)), requestID: "calibration-cell", calibration: true) + #expect(await bridge.isolatedPrefillEvidenceExpired()) + await refuse(bridge, tokens: 30_000, "long-1", "long-2", "long-3", "long-4", "long-5") + #expect(engine.deadlineAdmissions.count == 5) + #expect(engine.deadlineAdmissions.allSatisfy { $0.conservativePrefillTokensPerSecond == 50 }) + #expect(engine.ordinarySubmissionCount == 0) + await bridge.shutdown() + } + + @Test("a streak fills at three refusals, ends at any admission and reopens only after the retry interval") + func refusalStreakCounting() { + typealias Streak = DeadlineRefusalStreak + #expect(Streak.threshold == 3) + #expect(Streak.retryInterval == EnginePerformanceMeasurements.freshness) + let start = ContinuousClock.now + var streak = Streak() + streak.recordRefusal() + streak.recordRefusal() + #expect(!streak.expiresStaleEvidence(at: start)) + // An admission that ends a partial streak starts no retry interval. + streak.recordAdmission(at: start) + for _ in 0..<3 { streak.recordRefusal() } + #expect(streak.expiresStaleEvidence(at: start)) + streak.recordAdmission(at: start) + #expect(streak.refusals == 0) + for _ in 0..<5 { streak.recordRefusal() } + #expect(streak.refusals == 3) + #expect(!streak.expiresStaleEvidence(at: start + Streak.retryInterval - .seconds(1))) + #expect(streak.expiresStaleEvidence(at: start + Streak.retryInterval)) + } } private extension EngineV2Bridge {