diff --git a/changelog.d/deadline-decode-rate-min-tokens.md b/changelog.d/deadline-decode-rate-min-tokens.md new file mode 100644 index 0000000000..7f3320965c --- /dev/null +++ b/changelog.d/deadline-decode-rate-min-tokens.md @@ -0,0 +1,10 @@ +### A short reply no longer moves the deadline decode rate once a longer one has + +Deadline admission's decode rate now follows the published rate's rule once a +request that generated at least 32 tokens (or a calibration cell) has moved it: +from then on a shorter request leaves it unchanged. Until then, on a new slot +or after the decode evidence expired, every completed request moves it as +before, so a slot that serves only short replies keeps a rate that follows them +and is priced for deadline requests as before. The heartbeat's +`observed_decode_tps`, the rate's age and `performance_measurements` are +unchanged. diff --git a/changelog.d/new-slot-deadline-decode-cadence.md b/changelog.d/new-slot-deadline-decode-cadence.md new file mode 100644 index 0000000000..6ac319ac10 --- /dev/null +++ b/changelog.d/new-slot-deadline-decode-cadence.md @@ -0,0 +1,11 @@ +### A new slot prices deadline requests from the requests it is decoding + +Before its first completed request, a slot refused every request with a +first-content deadline that arrived while another request was decoding: it had +no decode rate (`decode_rate_unavailable`). It now prices that decode work at +the slowest delivered cadence among the requests decoding on it, once one has +8 tokens after its first, charged per row, and admits the request only if the +projection meets the deadline. With no such request, or with +`DARKBLOOM_TTFT_ADMISSION_FIXES=0`, it refuses as before. The +heartbeat's `observed_decode_tps` and `performance_measurements` are +unchanged. diff --git a/changelog.d/published-decode-rate-min-tokens.md b/changelog.d/published-decode-rate-min-tokens.md index 44a3e09edf..69de9e7b13 100644 --- a/changelog.d/published-decode-rate-min-tokens.md +++ b/changelog.d/published-decode-rate-min-tokens.md @@ -5,8 +5,7 @@ request that generated at least 32 tokens, matching the coordinator's own `completion_tokens >= 32` convention. A shorter request's rate is mostly its first steps or its tail: one short reply could pull a Mac that measured 80–100 tok/s down to about 11, and routing then ranked it behind slower Macs. Shorter -requests still feed the deadline decode rate, the rate's age and -`performance_measurements` exactly as before, so deadline admission and the -idle age are unchanged. A slot that has served only short replies publishes no -decode rate, as a slot with no samples does, and the coordinator prices it from -its profile or the fleet. +requests still feed the rate's age and `performance_measurements` exactly as +before, so the idle age is unchanged. A slot that has served only short replies +publishes no decode rate, as a slot with no samples does, and the coordinator +prices it from its profile or the fleet. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index d80462cd40..de7dd14e8f 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3052,11 +3052,23 @@ only on a request that generated at least 32 tokens `completion_tokens >= 32` convention; `updatePublishedDecodeTps` keeps the same EWMA and restart rule over those samples): one short reply measures mostly its first steps or tail and could pull a Mac measuring 80–100 tok/s down to about -11. A shorter request still feeds the deadline decode rate, the rate's age and -`performance_measurements`, as before, so a slot that serves only short -replies is still priced for deadline admission and never ages out while -serving; it publishes no rate until a longer one. Deadline admission is -unchanged: it charges the measured step shape. The projection also mirrors the +11. A shorter request still feeds the rate's age and `performance_measurements`, +as before, so a slot that serves only short replies never ages out while +serving; it publishes no rate until a longer one. The deadline decode rate +(`observedDecodeTpsEwma` and its measured step) follows the same 32-token rule +once a counted request (32 tokens or more, or calibration) has moved it since +it last restarted (`decodeEwmaCounted`, reset with it on calibration or when +the decode evidence expired). Until then every completed request moves it as +before, so a slot that serves only short replies keeps a rate that follows them +and is still priced for deadline admission. Before that first sample, a deadline +request beside decoding rows is priced at the slowest delivered cadence among +requests decoding on the slot now (tokens after the first emission over the +time since the first token, once a request has 8 such tokens; +`EngineV2Bridge.liveDecodeCadence`), charged per row; with no such request, or +with `DARKBLOOM_TTFT_ADMISSION_FIXES=0`, the decode rate stays unavailable and +the request is refused as before. None of +this reaches the heartbeat. Deadline admission otherwise charges the measured +step shape. The projection also mirrors the live MTP plan's depth gates (`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/CBv2MTPRoundDriver.swift`, `CBv2MTPRoundDriver.speculationDepthCeiling`): a step with more decode rows diff --git a/docs/developer/serving-performance-qualification.md b/docs/developer/serving-performance-qualification.md index bc3bb7c76e..bec5b04376 100644 --- a/docs/developer/serving-performance-qualification.md +++ b/docs/developer/serving-performance-qualification.md @@ -23,7 +23,11 @@ separates exactly two conversions. The idle age of the heartbeat's decode rate changes only the `observed_decode_tps` an idle slot advertises to routing, not admission, measurements or any profile. The rate's age on the heartbeat (`observed_decode_tps_age_ms`) needs none -either: it is informational and changes no rate, admission or profile. +either: it is informational and changes no rate, admission or profile. Nor does +the decode rate a slot uses before its first completed request (the slowest +delivered cadence of requests decoding on it, charged per row; see +[deadlines](../architecture/inference.md#deadlines)): a request carrying a +reviewed calibration never takes it. Profile qualification is separate work required to introduce a measured prediction-error envelope. 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 8738428476..08a2f1696d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Admission.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Admission.swift @@ -118,11 +118,14 @@ extension EngineV2Bridge { } 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. + // projected batch step, not every row's tokens. Before its first + // sample, requests decoding here now give the rate. + let perRequestRate = ewmaInitialized && observedDecodeTpsEwma.isFinite && observedDecodeTpsEwma > 0 + ? observedDecodeTpsEwma : nil let decode = DeadlineAdmissionFixes.decodeCharge( - perRequestRate: ewmaInitialized && observedDecodeTpsEwma.isFinite && observedDecodeTpsEwma > 0 - ? observedDecodeTpsEwma : nil, - measuredStep: observedDecodeStep, enabled: admissionFixes, calibrated: calibration != nil) + perRequestRate: perRequestRate, + measuredStep: observedDecodeStep, enabled: admissionFixes, calibrated: calibration != nil, + liveRate: admissionFixes && perRequestRate == nil && calibration == nil ? liveDecodeCadence() : nil) return CBv2FirstTokenDeadlineAdmission( deadline: deadline.instant, @@ -135,6 +138,24 @@ extension EngineV2Bridge { decodeRateShape: decode.shape) } + /// The fewest tokens after its first emission a decoding request needs + /// before its cadence prices deadline admission. + static let minimumLiveDecodeTokens = 8 + + /// The slowest delivered cadence among requests decoding on this slot now: + /// tokens after the first emission over the time since the first token, + /// as `recordFinish` measures a delivered rate. nil when no request has + /// `minimumLiveDecodeTokens` yet. Waiting between tokens only lowers it. + func liveDecodeCadence(now: ContinuousClock.Instant = .now) -> Double? { + active.values.compactMap { state -> Double? in + let tokens = state.completionTokens - state.firstEmissionTokens + guard let firstTokenAt = state.firstTokenAt, tokens >= Self.minimumLiveDecodeTokens else { return nil } + let seconds = WedgeMonitor.seconds(now - firstTokenAt) + let rate = Double(tokens) / seconds + return seconds > 0 && rate.isFinite && rate > 0 ? rate : nil + }.min() + } + /// Nothing but `requestID` occupies this engine and, through the shared /// service budget, no other model's request or device activity holds the Mac. private func macIdle(except requestID: String?) -> Bool { diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Measurements.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Measurements.swift index 15d84d7dbe..ed38d3a097 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Measurements.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Measurements.swift @@ -146,8 +146,9 @@ extension EngineV2Bridge { /// The fewest generated tokens whose decode rate may move the published /// rate (`observed_decode_tps`); the coordinator's own /// `completion_tokens >= 32` convention. A shorter request's rate is mostly - /// its first steps or its tail. It still feeds the deadline decode rate, - /// the rate's age and the performance measurements. + /// its first steps or its tail. It still feeds the rate's age and the + /// performance measurements, and moves the deadline decode rate until a + /// counted sample has. static let minimumPublishedDecodeTokens = 32 static func setsPublishedDecodeRate(completionTokens: Int) -> Bool { diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+RateObservations.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+RateObservations.swift index 790e86ef23..743153cca2 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+RateObservations.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+RateObservations.swift @@ -17,7 +17,9 @@ struct EngineRateObservation: Sendable { var decodeShape = CBv2DecodeRateShape(batchRows: 1) /// Decode only: false for a completed request that generated fewer than /// `EngineV2Bridge.minimumPublishedDecodeTokens` tokens. Such a sample - /// still feeds every estimate except the published rate. + /// never moves the published rate, and moves the deadline decode rate only + /// while no counted sample has moved it since it last restarted; it feeds + /// the performance measurements and their age as before. var setsPublishedDecode = true } @@ -58,8 +60,15 @@ extension EngineV2Bridge { if isDecode && value.aggregate { if calibration || performanceMeasurements.rateExpiration("decode").map({ value.at > $0 }) == true { ewmaInitialized = false + decodeEwmaCounted = false + } + // Short replies move the deadline rate as before until a counted + // sample has; from then on only counted samples move it. + let counted = calibration || value.setsPublishedDecode + if counted || !decodeEwmaCounted { + updateDecodeTpsEwma(value.tps, shape: value.decodeShape) + decodeEwmaCounted = decodeEwmaCounted || counted } - updateDecodeTpsEwma(value.tps, shape: value.decodeShape) if calibration || value.setsPublishedDecode { updatePublishedDecodeTps(value.tps, at: value.at, restart: calibration) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift index f74777682e..3b9a0a28a3 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift @@ -388,6 +388,9 @@ public actor EngineV2Bridge { var generationRequestsTotal: Int64 = 0 var observedDecodeTpsEwma: Double = 0 var ewmaInitialized = false + /// A counted sample (calibration, or `minimumPublishedDecodeTokens` or + /// more) has moved `observedDecodeTpsEwma` since it last restarted. + var decodeEwmaCounted = false /// The published decode rate (`updatePublishedDecodeTps`) and the newest /// sample behind it. var publishedDecodeTps: Double = 0 diff --git a/provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift b/provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift index c6170540f3..abd1a7cea4 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift @@ -28,9 +28,16 @@ enum DeadlineAdmissionFixes { /// per-row conversion is its only fallback, so calibrated policies keep it. /// The step is smoothed and reset with the per-request EWMA, which alone /// says whether decode evidence exists. + /// + /// Without that evidence an uncalibrated policy with the fixes on takes + /// `liveRate`, the cadence of requests decoding on this slot now + /// (`EngineV2Bridge.liveDecodeCadence`), charged per row; nil, or the fixes + /// off, still leaves the decode rate unavailable. static func decodeCharge( - perRequestRate: Double?, measuredStep: MeasuredDecodeStep, enabled: Bool, calibrated: Bool + perRequestRate: Double?, measuredStep: MeasuredDecodeStep, enabled: Bool, calibrated: Bool, + liveRate: Double? = nil ) -> (rate: Double?, shape: CBv2DecodeRateShape?) { + if enabled, !calibrated, perRequestRate == nil, let liveRate { return (liveRate, nil) } guard enabled, !calibrated else { return (perRequestRate, nil) } return (perRequestRate == nil ? nil : measuredStep.tokensPerSecond, measuredStep.shape) } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NewSlotDecodeCadenceAdmissionTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NewSlotDecodeCadenceAdmissionTests.swift new file mode 100644 index 0000000000..6656f75b6a --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NewSlotDecodeCadenceAdmissionTests.swift @@ -0,0 +1,149 @@ +import Foundation +import MLX +@testable import MLXLMCommon +import Testing +@testable import ProviderCore + +/// A slot without a completed decode sample prices a deadline request beside a +/// decoding row from the cadence of the requests decoding on it now. The real +/// engine projects the queue: one row is frozen mid-decode, so the new prompt's +/// steps carry decode work. The bridge's decoding rows are set directly. +@Suite("New-slot decode cadence admission", .serialized) +struct NewSlotDecodeCadenceAdmissionTests { + private struct Fixture { + let engine: EngineV2 + let bridge: EngineV2Bridge + let decoder: AsyncStream + + func release() async { + await bridge.removeDecodingRowsForTesting() + engine.loopForTesting.onEngineQueueSync { + engine.loopForTesting.suspendStepExecutionAtCountForTesting = nil + } + for await _ in decoder {} + await bridge.shutdown() + } + } + + /// One request has prefilled and decoded once; the loop then stops before + /// its next step. Prefill is priced at 1,000 tok/s; there is no decode sample. + private func makeFixture(admissionFixes: Bool = true) async throws -> Fixture { + let model = DeadlineAdmissionFixtureModel() + let engine = EngineV2(model: model, layerKinds: model.kinds, + backend: CBv2ContiguousKVBackend(config: .init(bytesCapacity: 1 << 20)), + cacheProvider: CBv2LayerCacheBank(layerKinds: model.kinds), + sampler: CBv2GreedySampler(), schedulerConfig: .init( + maxConcurrentRequests: 2, maxBatchedTokensPerStep: 64, + prefillChunkSize: 32, maxConcurrentPartialPrefills: 1, + maxWaiting: 4, enablePrefixCache: false)) + engine.loopForTesting.onEngineQueueSync { + engine.loopForTesting.suspendStepExecutionAtCountForTesting = 2 + } + let decoder = try engine.submit(.init(id: .init(910_001), promptTokens: [1], maxTokens: 64)) + let deadline = ContinuousClock.now.advanced(by: .seconds(30)) + while engine.stepCount < 2, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(5)) + } + try #require(engine.stepCount == 2) + let bridge = EngineV2Bridge(engine: engine, modelId: "new-slot-fixture", + tokenizer: TokenizerHandle(PrefillStubTokenizer()), eosTokenIds: [], + prefillDeadlineMode: .enforce, admissionFixes: admissionFixes) + await bridge.updatePrefillTpsEwma(1_000, isolated: true) + #expect(await bridge.ewmaInitialized == false) + return Fixture(engine: engine, bridge: bridge, decoder: decoder) + } + + private func submit(_ fixture: Fixture, id: UInt64, budgetMilliseconds: Int64) async throws + -> (CBv2FirstTokenDeadlineAdmission, CBv2FirstTokenDeadlineResult) + { + let policy = try #require(await fixture.bridge.firstTokenDeadlineAdmission( + deadline: .init(relativeBudgetMilliseconds: budgetMilliseconds), + isMultimodal: false)) + let result = try await fixture.engine.submit( + .init(id: .init(id), promptTokens: Array(repeating: 2, count: 100), maxTokens: 1), + firstTokenDeadline: policy) + return (policy, result) + } + + @Test("a new slot admits a deadline request beside a decoding row at that row's cadence") + func admitsAtLiveCadence() async throws { + let fixture = try await makeFixture() + // 20 tokens after the first in one second: 20 tok/s. + await fixture.bridge.addDecodingRowForTesting("decoding", tokensAfterFirst: 20, since: .seconds(1)) + let (policy, result) = try await submit(fixture, id: 910_002, budgetMilliseconds: 10_000) + let rate = try #require(policy.conservativeDecodeTokensPerSecond) + #expect(rate > 19 && rate <= 20) + #expect(policy.decodeRateShape == nil, "a live cadence is charged per row") + guard case .admitted(let stream, .bounded(let work, _), _, _) = result else { + Issue.record("expected a priced admission, got \(result)") + await fixture.release() + return + } + #expect(work.decodeTokens > 0, "the projection carries the decoding row's work") + await fixture.release() + for await _ in stream {} + } + + @Test("a new slot whose decoding rows' cadence predicts a miss refuses with a priced projection") + func refusesWhenCadencePredictsMiss() async throws { + let fixture = try await makeFixture() + // The slower row prices admission: 1 tok/s, not 100. + await fixture.bridge.addDecodingRowForTesting("fast", tokensAfterFirst: 100, since: .seconds(1)) + await fixture.bridge.addDecodingRowForTesting("slow", tokensAfterFirst: 9, since: .seconds(9)) + let (policy, result) = try await submit(fixture, id: 910_003, budgetMilliseconds: 1_000) + let rate = try #require(policy.conservativeDecodeTokensPerSecond) + #expect(rate > 0.9 && rate <= 1) + guard case .deadlineUnreachable(.bounded(let work, let duration)) = result else { + Issue.record("expected deadline_unreachable from a priced projection, got \(result)") + await fixture.release() + return + } + #expect(work.decodeTokens > 0) + #expect(duration > .seconds(1)) + await fixture.release() + } + + @Test("with no row past 8 tokens after its first the decode rate stays unavailable") + func noRowPastMinimumStaysUnavailable() async throws { + let fixture = try await makeFixture() + await fixture.bridge.addDecodingRowForTesting("young", tokensAfterFirst: 7, since: .seconds(1)) + let (policy, result) = try await submit(fixture, id: 910_004, budgetMilliseconds: 10_000) + #expect(policy.conservativeDecodeTokensPerSecond == nil) + guard case .deadlineUnreachable(.unbounded(reason: .decodeRateUnavailable)) = result else { + Issue.record("expected decode_rate_unavailable, got \(result)") + await fixture.release() + return + } + await fixture.release() + } + + @Test("with the admission fixes off a new slot's decode rate stays unavailable beside a decoding row") + func fixesOffStaysUnavailable() async throws { + let fixture = try await makeFixture(admissionFixes: false) + await fixture.bridge.addDecodingRowForTesting("decoding", tokensAfterFirst: 20, since: .seconds(1)) + let (policy, result) = try await submit(fixture, id: 910_005, budgetMilliseconds: 10_000) + #expect(policy.conservativeDecodeTokensPerSecond == nil) + #expect(policy.decodeRateShape == nil) + guard case .deadlineUnreachable(.unbounded(reason: .decodeRateUnavailable)) = result else { + Issue.record("expected decode_rate_unavailable, got \(result)") + await fixture.release() + return + } + await fixture.release() + } +} + +private extension EngineV2Bridge { + func addDecodingRowForTesting(_ id: String, tokensAfterFirst: Int, since: Duration) { + let firstTokenAt = ContinuousClock.now - since + active[Self.decodingRowPrefix + id] = ActiveRequestState(promptTokens: 1, maxTokens: 1_024, + completionTokens: tokensAfterFirst + 1, submittedAt: firstTokenAt, + firstTokenAt: firstTokenAt, firstEmissionTokens: 1) + } + + static var decodingRowPrefix: String { "live-row-" } + + func removeDecodingRowsForTesting() { + for id in active.keys where id.hasPrefix(Self.decodingRowPrefix) { active.removeValue(forKey: id) } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Performance/DecodeRateSampleLengthTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Performance/DecodeRateSampleLengthTests.swift index 45151fc36d..f5a0a68bd1 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Performance/DecodeRateSampleLengthTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Performance/DecodeRateSampleLengthTests.swift @@ -4,9 +4,10 @@ import Testing @testable import ProviderCore /// Only a request that generated at least 32 tokens moves the published decode -/// rate (`observed_decode_tps`). A shorter one still feeds the deadline decode -/// rate and the rate's age. Completed requests run through a scripted engine; -/// no model or GPU is involved. +/// rate (`observed_decode_tps`) and, once such a request has moved it, the +/// deadline decode rate. A shorter one still feeds the rate's age, and moves the +/// deadline rate until then. Completed requests run through a scripted engine; no model +/// or GPU is involved. @Suite("Decode rate sample length") struct DecodeRateSampleLengthTests { private func makeBridge() -> (EngineV2Bridge, PrefillScriptEngine) { @@ -64,21 +65,68 @@ struct DecodeRateSampleLengthTests { await bridge.shutdown() } - @Test("a short request leaves the published rate unchanged while the deadline rate updates as before") - func shortRequestMovesOnlyTheDeadlineRate() async throws { - let alpha = 0.3 + @Test("a short request after a counted one moves neither the published nor the deadline rate") + func shortRequestMovesNeitherRate() async throws { let (bridge, engine) = makeBridge() try await serve(bridge, engine, tokens: 101, id: "long") #expect(await bridge.backendSlotCapacity().observedDecodeTps == 1_000) let expiration = try #require(await bridge.performanceMeasurements.rateExpiration("decode")) try await serve(bridge, engine, tokens: 11, id: "short") #expect(await bridge.backendSlotCapacity().observedDecodeTps == 1_000) - #expect(await bridge.observedDecodeTpsEwma == alpha * 100 + (1 - alpha) * 1_000) + #expect(await bridge.observedDecodeTpsEwma == 1_000) + #expect(await bridge.observedDecodeStep.tokensPerSecond == 1_000) + // The rate's age still refreshes. let refreshed = try #require(await bridge.performanceMeasurements.rateExpiration("decode")) #expect(refreshed >= expiration) await bridge.shutdown() } + @Test("a short-only slot's deadline rate follows its short replies, as before") + func shortOnlySlotDeadlineRateFollowsShortReplies() async throws { + let alpha = 0.3 + let (bridge, engine) = makeBridge() + try await serve(bridge, engine, tokens: 11, id: "short-first") + #expect(await bridge.observedDecodeTpsEwma == 100) + try await serve(bridge, engine, tokens: 5, id: "short-second") + let second = alpha * 40 + (1 - alpha) * 100 + #expect(await bridge.observedDecodeTpsEwma == second) + try await serve(bridge, engine, tokens: 3, id: "short-third") + #expect(await bridge.observedDecodeTpsEwma == alpha * 20 + (1 - alpha) * second) + await bridge.shutdown() + } + + // It expected a later short reply to leave a rate set by a short one, which + // froze a short-only slot's rate at its first reply; only a counted reply + // stops short ones moving it. + @Test("a short reply starts the deadline rate; once a counted reply has moved it, short ones leave it") + func firstShortReplyStartsTheDeadlineRate() async throws { + let alpha = 0.3 + let (bridge, engine) = makeBridge() + try await serve(bridge, engine, tokens: 11, id: "short-first") + #expect(await bridge.observedDecodeTpsEwma == 100) + try await serve(bridge, engine, tokens: 33, id: "counted") + let counted = alpha * 320 + (1 - alpha) * 100 + #expect(await bridge.observedDecodeTpsEwma == counted) + try await serve(bridge, engine, tokens: 5, id: "short-after") + #expect(await bridge.observedDecodeTpsEwma == counted) + await bridge.shutdown() + } + + @Test("after the decode evidence expires a short reply starts the deadline rate again") + func shortReplyRestartsAnExpiredDeadlineRate() async { + let (bridge, _) = makeBridge() + let now = ContinuousClock.now + await bridge.applyRateObservation(EngineRateObservation(phase: "decode", tps: 80, prompt: 200, + context: 300, cache: "cold", overlap: .init(), at: now - .seconds(300), postureEpoch: nil, + aggregate: true), requestID: "old-long", calibration: false) + #expect(await bridge.observedDecodeTpsEwma == 80) + await bridge.applyRateObservation(EngineRateObservation(phase: "decode", tps: 20, prompt: 200, + context: 300, cache: "cold", overlap: .init(), at: now, postureEpoch: nil, + aggregate: true, setsPublishedDecode: false), requestID: "short", calibration: false) + #expect(await bridge.observedDecodeTpsEwma == 20) + await bridge.shutdown() + } + @Test("31 tokens leave the published rate unchanged; 32 and 33 publish the same EWMA as every sample") func boundaryAt32Tokens() async throws { let alpha = 0.3