diff --git a/changelog.d/coordinator-decode-rate-age-decay.md b/changelog.d/coordinator-decode-rate-age-decay.md new file mode 100644 index 0000000000..24e34ee539 --- /dev/null +++ b/changelog.d/coordinator-decode-rate-age-decay.md @@ -0,0 +1,11 @@ +### An idle Mac keeps its decode rate when the coordinator decays stale rates + +The coordinator can now say, in `trust_status.coordinator_features`, that it +decays a stale `observed_decode_tps` by its `observed_decode_tps_age_ms` +(`decode_rate_age_decay`). While the connected coordinator says so, an idle +slot keeps publishing its decode rate and its age after +`DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS`, instead of omitting it; the +coordinator moves an old rate toward the fleet median, so the slot keeps its +rank instead of alternating between no rate and an old one. Without the field +(every coordinator before it), with any other list, and after a disconnect, the +heartbeat is unchanged. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 780ae21df5..9900685abe 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3054,8 +3054,12 @@ measured `0` restores publishing the last rate however old). The heartbeat also sends the published rate's own age, `observed_decode_tps_age_ms`: the time since the newest sample that moved it, which a short reply does not reset -(`DecodeRateIdleAge.publishedAgeMilliseconds`); it changes nothing the provider -decides. The published rate moves +(`DecodeRateIdleAge.publishedAgeMilliseconds`). While the connected +coordinator's latest `trust_status` lists `decode_rate_age_decay` in +`coordinator_features`, the coordinator decays a stale rate by that age itself, +and the provider stops omitting an idle slot's rate +(`DecodeRateIdleAge.effectiveMaximum`); without it, and after a disconnect, the +heartbeat is unchanged. The published rate moves only on a request that generated at least 32 tokens (`EngineV2Bridge.minimumPublishedDecodeTokens`, the coordinator's `completion_tokens >= 32` convention; `updatePublishedDecodeTps` keeps the same diff --git a/docs/developer/serving-performance-qualification.md b/docs/developer/serving-performance-qualification.md index bec5b04376..0aaa32e53e 100644 --- a/docs/developer/serving-performance-qualification.md +++ b/docs/developer/serving-performance-qualification.md @@ -27,7 +27,13 @@ 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. +reviewed calibration never takes it. Nor does the coordinator's +`decode_rate_age_decay` advertisement (`trust_status.coordinator_features`; +shared wire cases in +`provider-swift/Tests/ProviderCoreTests/Fixtures/Protocol/coordinator_features_wire.json`, +checked by `CoordinatorDecodeRateDecayTests` and +`provider-swift/Tests/test_protocol_fixture_resources.py`): it decides only +whether an idle slot keeps advertising its rate to routing. Profile qualification is separate work required to introduce a measured prediction-error envelope. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 4dd3c62a0e..f5e8693edf 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -635,7 +635,7 @@ and rollback are defined in the [provider configuration reference](../provider/c | `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, a probe that re-measures stale isolated-prefill evidence after three refusals it explains. Off restores the previous estimators and turns that probe off too. Forwarded to the launchd provider job. | | `DARKBLOOM_TTFT_NATIVE_PREFILL_EVIDENCE` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`NativePrefillEvidence`) | GLM-5.3-Flash and native MiMo V2.6 only ([deadlines](../architecture/inference.md#deadlines)): a cold prompt of at most 4,096 tokens may raise the prefill estimate but never lower it, and the smallest prompt-size bucket (up to 1,024 tokens) no longer tightens a prompt. An idle Mac at nominal posture with no calibration cell or longer prompt in the last 120 s is priced at no less than its calibration cell, so once calibrated it takes no short-prompt recovery; a busy Mac or another posture keeps one eighth of the cell as its floor. A slower isolated short sample stays out of the published isolated and observed prefill rates. Off (or `DARKBLOOM_TTFT_ADMISSION_FIXES=0`) restores the previous estimator. Other models, Diffusion Gemma included, are unchanged. Forwarded to the launchd provider job. | -| `DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS` | a positive whole number of seconds; `0`, `false`, `off`, `no` disable (trimmed, case-insensitive); other values keep the default | `1800` | `provider-swift/Sources/ProviderCore/Inference/Performance/DecodeRateIdleAge.swift` (`DecodeRateIdleAge`) | How long an idle slot keeps publishing its decode EWMA as `observed_decode_tps`. Once nothing has run or waited on the slot since a decode sample older than this, the heartbeat omits the rate and the coordinator prices the Mac from its profile or the fleet, as after a reload; the next decode sample is published as measured. Off publishes the last rate however old, as 0.10.17 did. Forwarded to the LaunchAgent. | +| `DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS` | a positive whole number of seconds; `0`, `false`, `off`, `no` disable (trimmed, case-insensitive); other values keep the default | `1800` | `provider-swift/Sources/ProviderCore/Inference/Performance/DecodeRateIdleAge.swift` (`DecodeRateIdleAge`) | How long an idle slot keeps publishing its decode EWMA as `observed_decode_tps`. Once nothing has run or waited on the slot since a decode sample older than this, the heartbeat omits the rate and the coordinator prices the Mac from its profile or the fleet, as after a reload; the next decode sample is published as measured. Off publishes the last rate however old, as 0.10.17 did. Not applied while the connected coordinator advertises `trust_status.coordinator_features` `decode_rate_age_decay`. Forwarded to the LaunchAgent. | | `DARKBLOOM_TTFT_REFUSAL_PROBE` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`DeadlineRefusalProbe`) | The refusal streak's idle probe alone ([deadlines](../architecture/inference.md#deadlines)): off, refusals neither count nor start a probe, and the estimator corrections stay on. Forwarded to the launchd provider job. | | `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY` | trimmed, case-insensitive `0`, `false`, `no`, `off` drop the default; any other value keeps it | on: the model card's 1.5 | `provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift` (`qwen35NineBKeepsCardPenalty`) | The catalog `Qwen3.5-9B`'s `presence_penalty` for a request that omits one (0.10.13; 0.10.12 had none, and its answers with `max_tokens` ≥ 8,192 ran to the limit about three times as often: 5.5 % against 1.7 %). `0` restores 0.10.12's no-penalty default. A request's own value, the coordinator's registry default included, always wins: while the registry sets `presence_penalty` for `Qwen3.5-9B`, routed requests carry it and `0` affects only local requests, so rolling routed traffic back also needs the registry value removed or set to `0`. `darkbloom start` passes it to the launchd 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. | diff --git a/docs/reference/protocol-messages.md b/docs/reference/protocol-messages.md index fdf0500327..a1459ff728 100644 --- a/docs/reference/protocol-messages.md +++ b/docs/reference/protocol-messages.md @@ -587,7 +587,7 @@ routing on them. | `request_limits` | `*SlotRequestLimits` | `SlotRequestLimits?` | opt | The request sizes a cluster pair leader's slot serves; [schema below](#slotsrequest_limits). Omitted by a single Mac's slot and by providers before 0.10.10 | | `active_tokens` | `int64` | `Int64` | req | Σ (prompt + completion) tokens over running requests | | `max_tokens_potential` | `int64` | `Int64` | req | Σ `max_tokens` over running requests | -| `observed_decode_tps` | `float64` | `Double` | opt | EWMA of per-request decode TPS; omitted when unmeasured, and when the slot is idle and its newest decode sample is older than `DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS` (30 minutes by default) | +| `observed_decode_tps` | `float64` | `Double` | opt | EWMA of per-request decode TPS; omitted when unmeasured, and when the slot is idle and its newest decode sample is older than `DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS` (30 minutes by default), unless the connected coordinator advertises `trust_status.coordinator_features` `decode_rate_age_decay` | | `observed_decode_tps_age_ms` | (not read yet) | `Int64?` | opt | Milliseconds since the newest sample that moved `observed_decode_tps` (a reply of at least 32 tokens, or a calibration cell; `EngineV2Bridge.publishedDecodeAt`). Sent only with a published rate. Informational in this release: the provider's rate and the coordinator's ranking are unchanged until the coordinator reads it (`DecodeRateIdleAge.publishedAgeMilliseconds`) | | `observed_prefill_tps` | `float64` | `Double` | opt | Cold-prefill engine-phase EWMA, published at prompt completion; omitted when unmeasured | | `active_token_budget_used`, `active_token_budget_max`, `queued_token_budget` | `int64` | `Int64` | opt | `queued_token_budget` is hard-coded `0` by the v0.8.16 provider (`backendSlotCapacity`, `EngineV2Bridge+Capacity.swift`), so it is always omitted | @@ -1661,7 +1661,18 @@ See [revision lifecycle](../architecture/model-revisions.md). Go `TrustStatusMessage` · Swift `TrustStatus`. `trust_level` ∈ {`none`, `self_signed`, `hardware`}; `status` (`online`, `untrusted`, …); `reason` -(opt in Go, `String` in Swift). Operator diagnostics only. +(opt in Go, `String` in Swift). Operator diagnostics only, except +`coordinator_features`. + +`coordinator_features` (opt, list of strings; Swift `coordinatorFeatures`) +names coordinator behaviours a provider may rely on. Each `trust_status` +replaces the previous list, a disconnect clears it, and absent, malformed or +unknown names leave the provider as it was. `decode_rate_age_decay`: the +coordinator decays a stale `observed_decode_tps` by its +`observed_decode_tps_age_ms`, so the provider stops omitting an idle slot's +rate after `DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS` +(`DecodeRateIdleAge.coordinatorDecays`). Shared cases: +`provider-swift/Tests/ProviderCoreTests/Fixtures/Protocol/coordinator_features_wire.json`. ### `capacity_probe` diff --git a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Connection.swift b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Connection.swift index 61bbcab94e..b53192954c 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Connection.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Connection.swift @@ -40,6 +40,7 @@ extension CoordinatorClient { let end = session.end() let delay = nextMemberAwareReconnectDelay( backoff: TimeInterval.random(in: policy.nextDelayRange(after: end))) + DecodeRateIdleAge.coordinatorDecays.reset() eventContinuation?.yield(.disconnected) let reachable = reachability.isReachable let closeCode = end.closeCode.map { "\($0)" } ?? "none" diff --git a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Inbound.swift b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Inbound.swift index 8ab82e7282..b898c83955 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Inbound.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Inbound.swift @@ -88,6 +88,11 @@ extension CoordinatorClient { // A member that lost trust or runtime verification may not keep an // attachment: its session's native work is cancelled at once. if case .trustStatus(let status) = parsed, ["untrusted", "offline"].contains(status.status) { detachNativePairMember() } + // Only the connected coordinator's latest `trust_status` says whether + // it decays a stale decode rate (`DecodeRateIdleAge.coordinatorDecays`). + if case .trustStatus(let status) = parsed { + DecodeRateIdleAge.coordinatorDecays.update(features: status.coordinatorFeatures) + } if case .runtimeStatus(let status) = parsed, !status.verified || !status.mismatches.isEmpty { detachNativePairMember() } // A coordinator that does not know the member role answers its // registration like any provider's (desired builds, challenges...). diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Capacity.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Capacity.swift index 23bd706620..9b30d42b85 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Capacity.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Capacity.swift @@ -225,7 +225,7 @@ extension EngineV2Bridge { let observedDecodeTps = DecodeRateIdleAge.published(ewma: publishedDecodeTps, newestSampleAge: performanceMeasurements.observationAge("decode", now: now), idle: snapshot.activeRequests == 0 && snapshot.waitingRequests == 0, - maximum: DecodeRateIdleAge.configured) + maximum: DecodeRateIdleAge.effectiveMaximum) return BackendSlotCapacity( model: modelId, state: state, diff --git a/provider-swift/Sources/ProviderCore/Inference/Performance/DecodeRateIdleAge.swift b/provider-swift/Sources/ProviderCore/Inference/Performance/DecodeRateIdleAge.swift index 51c28d6d8a..77c23cdc1e 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Performance/DecodeRateIdleAge.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Performance/DecodeRateIdleAge.swift @@ -19,6 +19,10 @@ import Foundation /// coordinator's idle measurement age; a positive whole number of seconds sets /// it; `0`, `false`, `no` or `off` (trimmed, case-insensitive) publishes the /// last rate however old, as 0.10.17 did. Any other value keeps the default. +/// +/// A coordinator that decays a stale rate by its age advertises +/// `decode_rate_age_decay` in `trust_status.coordinator_features`; while it +/// does, the heartbeat publishes the rate and its age instead (`effectiveMaximum`). enum DecodeRateIdleAge { static let environmentKey = "DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS" static let defaultMaximum: Duration = .seconds(1_800) @@ -33,6 +37,30 @@ enum DecodeRateIdleAge { return .seconds(seconds) } + /// The `trust_status.coordinator_features` entry of a coordinator that + /// decays a stale published decode rate itself, by its + /// `observed_decode_tps_age_ms`. + static let coordinatorDecayFeature = "decode_rate_age_decay" + + /// Whether the connected coordinator advertised `coordinatorDecayFeature` + /// in its latest `trust_status`. False until it does, and again after a + /// disconnect or a `trust_status` without it. + static let coordinatorDecays = CoordinatorDecayAdvertisement() + + /// Tests set this to price one heartbeat without the process-wide value. + @TaskLocal static var coordinatorDecaysOverride: Bool? + + /// The maximum the heartbeat applies: none while the coordinator decays a + /// stale rate itself (it then sees the rate and its age), else `configured`. + static func effectiveMaximum(configured: Duration?, coordinatorDecays: Bool) -> Duration? { + coordinatorDecays ? nil : configured + } + + static var effectiveMaximum: Duration? { + effectiveMaximum(configured: configured, + coordinatorDecays: coordinatorDecaysOverride ?? coordinatorDecays.value) + } + /// The decode rate the heartbeat publishes: `ewma`, or zero when the slot /// is idle and its newest decode sample is older than `maximum`. static func published(ewma: Double, newestSampleAge: Duration?, idle: Bool, maximum: Duration?) -> Double { @@ -52,3 +80,21 @@ enum DecodeRateIdleAge { return age.components.seconds * 1_000 + age.components.attoseconds / 1_000_000_000_000_000 } } + +/// The connected coordinator's `decode_rate_age_decay` advertisement +/// (`DecodeRateIdleAge.coordinatorDecays`). +final class CoordinatorDecayAdvertisement: @unchecked Sendable { + private let lock = NSLock() + private var advertised = false + + var value: Bool { lock.withLock { advertised } } + + /// From one `trust_status`: nil (an older coordinator) or a list without + /// the feature keeps the provider's idle age. + func update(features: [String]?) { + let decays = features?.contains(DecodeRateIdleAge.coordinatorDecayFeature) ?? false + lock.withLock { advertised = decays } + } + + func reset() { lock.withLock { advertised = false } } +} diff --git a/provider-swift/Sources/ProviderCore/Protocol/Messages.swift b/provider-swift/Sources/ProviderCore/Protocol/Messages.swift index 1ddc3e6f51..60306138cc 100644 --- a/provider-swift/Sources/ProviderCore/Protocol/Messages.swift +++ b/provider-swift/Sources/ProviderCore/Protocol/Messages.swift @@ -1921,12 +1921,18 @@ public enum CoordinatorMessage: Sendable, Equatable { public var status: String public var reason: String public var authorization: ProviderAuthorizationStatus? + /// Optional coordinator behaviours the provider may rely on + /// (`coordinator_features`); nil from a coordinator that sends none. + /// Unknown names are ignored. + public var coordinatorFeatures: [String]? public init(trustLevel: String, status: String, reason: String = "", - authorization: ProviderAuthorizationStatus? = nil) { + authorization: ProviderAuthorizationStatus? = nil, + coordinatorFeatures: [String]? = nil) { self.trustLevel = trustLevel self.status = status self.reason = reason self.authorization = authorization + self.coordinatorFeatures = coordinatorFeatures } } } @@ -1978,6 +1984,7 @@ extension CoordinatorMessage: Codable { case priority case trustLevel = "trust_level" case status, reason, authorization + case coordinatorFeatures = "coordinator_features" case paid case models // CapacityProbe @@ -2088,6 +2095,7 @@ extension CoordinatorMessage: Codable { try container.encode(t.trustLevel, forKey: .trustLevel) try container.encode(t.status, forKey: .status) try container.encodeIfPresent(t.authorization, forKey: .authorization) + try container.encodeIfPresent(t.coordinatorFeatures, forKey: .coordinatorFeatures) if !t.reason.isEmpty { try container.encode(t.reason, forKey: .reason) } @@ -2234,7 +2242,8 @@ extension CoordinatorMessage: Codable { trustLevel: try container.decode(String.self, forKey: .trustLevel), status: try container.decode(String.self, forKey: .status), reason: try container.decodeIfPresent(String.self, forKey: .reason) ?? "", - authorization: try container.decodeIfPresent(ProviderAuthorizationStatus.self, forKey: .authorization) + authorization: try container.decodeIfPresent(ProviderAuthorizationStatus.self, forKey: .authorization), + coordinatorFeatures: try? container.decodeIfPresent([String].self, forKey: .coordinatorFeatures) )) case .clusterMemberAccepted: diff --git a/provider-swift/Tests/ProviderCoreTests/Fixtures/Protocol/coordinator_features_wire.json b/provider-swift/Tests/ProviderCoreTests/Fixtures/Protocol/coordinator_features_wire.json new file mode 100644 index 0000000000..0cbbfe8d39 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Fixtures/Protocol/coordinator_features_wire.json @@ -0,0 +1,17 @@ +{ + "feature": "decode_rate_age_decay", + "cases": [ + {"name": "absent", "decays": false, + "message": {"type": "trust_status", "trust_level": "hardware", "status": "online"}}, + {"name": "empty", "decays": false, + "message": {"type": "trust_status", "trust_level": "hardware", "status": "online", "coordinator_features": []}}, + {"name": "other", "decays": false, + "message": {"type": "trust_status", "trust_level": "hardware", "status": "online", "coordinator_features": ["some_later_feature"]}}, + {"name": "advertised", "decays": true, + "message": {"type": "trust_status", "trust_level": "hardware", "status": "online", "coordinator_features": ["decode_rate_age_decay"]}}, + {"name": "advertised_among_others", "decays": true, + "message": {"type": "trust_status", "trust_level": "self_signed", "status": "online", "reason": "qualified", "coordinator_features": ["some_later_feature", "decode_rate_age_decay"]}}, + {"name": "malformed", "decays": false, + "message": {"type": "trust_status", "trust_level": "hardware", "status": "online", "coordinator_features": "decode_rate_age_decay"}} + ] +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Performance/CoordinatorDecodeRateDecayTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Performance/CoordinatorDecodeRateDecayTests.swift new file mode 100644 index 0000000000..913159770c --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Performance/CoordinatorDecodeRateDecayTests.swift @@ -0,0 +1,137 @@ +import Foundation +import MLXLMCommon +import Testing +@testable import ProviderCore + +/// `trust_status.coordinator_features`: the provider stops idle-zeroing its +/// published decode rate only while the coordinator advertises +/// `decode_rate_age_decay`. Without it the heartbeat is what it was. Synthetic +/// observations and a scripted engine; no model or GPU is involved. Nothing here +/// changes the process-wide advertisement: heartbeats take a task-local value. +@Suite("Coordinator decode rate decay") +struct CoordinatorDecodeRateDecayTests { + private func decode(_ tps: Double, at: ContinuousClock.Instant) -> EngineRateObservation { + EngineRateObservation(phase: "decode", tps: tps, prompt: 1_024, context: 1_024, cache: "cold", + overlap: .init(contended: true, peakRequests: 4), at: at, postureEpoch: nil, aggregate: true, + decodeShape: .init(batchRows: 4)) + } + + private struct Fixture: Decodable { + struct Case: Decodable { + let name: String + let decays: Bool + let message: JSONValue + } + let feature: String + let cases: [Case] + } + + /// Any JSON value, re-encoded byte for byte enough to feed the decoder. + private enum JSONValue: Decodable, Encodable { + case object([String: JSONValue]), array([JSONValue]), string(String), number(Double), bool(Bool), null + init(from decoder: Decoder) throws { + let c = try decoder.singleValueContainer() + if c.decodeNil() { self = .null } + else if let v = try? c.decode(Bool.self) { self = .bool(v) } + else if let v = try? c.decode(Double.self) { self = .number(v) } + else if let v = try? c.decode(String.self) { self = .string(v) } + else if let v = try? c.decode([JSONValue].self) { self = .array(v) } + else { self = .object(try c.decode([String: JSONValue].self)) } + } + func encode(to encoder: Encoder) throws { + var c = encoder.singleValueContainer() + switch self { + case .object(let v): try c.encode(v) + case .array(let v): try c.encode(v) + case .string(let v): try c.encode(v) + case .number(let v): try c.encode(v) + case .bool(let v): try c.encode(v) + case .null: try c.encodeNil() + } + } + } + + @Test("every fixture trust_status decodes, and only an advertised feature turns the provider's idle age off") + func sharedFixture() throws { + let url = try #require(Bundle.module.url( + forResource: "coordinator_features_wire", withExtension: "json", subdirectory: "Fixtures/Protocol")) + let fixture = try JSONDecoder().decode(Fixture.self, from: Data(contentsOf: url)) + #expect(fixture.feature == DecodeRateIdleAge.coordinatorDecayFeature) + #expect(fixture.cases.count == 6) + for item in fixture.cases { + let data = try JSONEncoder().encode(item.message) + guard case .trustStatus(let status) = try ProviderProtocolCodec.decodeCoordinatorMessage(from: data) else { + Issue.record("\(item.name): expected trust status"); continue + } + let advertisement = CoordinatorDecayAdvertisement() + advertisement.update(features: status.coordinatorFeatures) + #expect(advertisement.value == item.decays, "\(item.name)") + #expect(DecodeRateIdleAge.effectiveMaximum(configured: .seconds(1_800), + coordinatorDecays: advertisement.value) == (item.decays ? nil : .seconds(1_800)), "\(item.name)") + } + } + + @Test("a trust_status without the field re-encodes without it; with it, the list round-trips") + func wireShape() throws { + let legacy = Data(#"{"type":"trust_status","trust_level":"hardware","status":"online"}"#.utf8) + guard case .trustStatus(let old) = try ProviderProtocolCodec.decodeCoordinatorMessage(from: legacy) else { + Issue.record("expected trust status"); return + } + #expect(old.coordinatorFeatures == nil) + let reencoded = try #require(try JSONSerialization.jsonObject( + with: JSONEncoder().encode(CoordinatorMessage.trustStatus(old))) as? [String: Any]) + #expect(reencoded["coordinator_features"] == nil) + let current = CoordinatorMessage.TrustStatus(trustLevel: "hardware", status: "online", + coordinatorFeatures: [DecodeRateIdleAge.coordinatorDecayFeature]) + let encoded = try JSONEncoder().encode(CoordinatorMessage.trustStatus(current)) + #expect(try JSONDecoder().decode(CoordinatorMessage.self, from: encoded) == .trustStatus(current)) + let object = try #require(try JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + #expect(object["coordinator_features"] as? [String] == ["decode_rate_age_decay"]) + } + + @Test("the advertisement follows each trust_status and clears on reset") + func advertisementLifecycle() { + let advertisement = CoordinatorDecayAdvertisement() + #expect(!advertisement.value) + advertisement.update(features: ["decode_rate_age_decay"]) + #expect(advertisement.value) + advertisement.update(features: nil) + #expect(!advertisement.value, "a later trust_status without the field restores the idle age") + advertisement.update(features: ["decode_rate_age_decay"]) + advertisement.reset() + #expect(!advertisement.value, "a disconnect restores the idle age") + #expect(DecodeRateIdleAge.effectiveMaximum(configured: nil, coordinatorDecays: false) == nil) + #expect(DecodeRateIdleAge.effectiveMaximum(configured: .seconds(900), coordinatorDecays: false) == .seconds(900)) + } + + @Test("without the feature an idle stale slot's heartbeat is byte for byte what it was; with it the rate and its age stay") + func heartbeatBytes() async throws { + let bridge = EngineV2Bridge(engine: PrefillScriptEngine(), modelId: "gemma-4-26b-qat-4bit", + tokenizer: TokenizerHandle(PrefillStubTokenizer()), eosTokenIds: [], admissionFixes: true) + let start = ContinuousClock.now + await bridge.applyRateObservation(decode(16, at: start), requestID: "stacked", calibration: false) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + for offset in [60, 1_801, 7_200] { + let now = start + .seconds(offset) + // The process-wide value is false in tests: no coordinator is connected. + let process = try encoder.encode(await bridge.backendSlotCapacity(now: now)) + let absent = try await DecodeRateIdleAge.$coordinatorDecaysOverride.withValue(false) { + try encoder.encode(await bridge.backendSlotCapacity(now: now)) + } + #expect(process == absent, "offset \(offset)") + let advertised = try await DecodeRateIdleAge.$coordinatorDecaysOverride.withValue(true) { + await bridge.backendSlotCapacity(now: now) + } + let without = try JSONDecoder().decode(BackendSlotCapacity.self, from: absent) + #expect(advertised.observedDecodeTps == 16, "offset \(offset)") + #expect(advertised.observedDecodeTpsAgeMs == Int64(offset) * 1_000, "offset \(offset)") + if offset > 1_800 { + #expect(without.observedDecodeTps == 0 && without.observedDecodeTpsAgeMs == nil) + } else { + #expect(try encoder.encode(advertised) == absent, "a fresh rate is the same either way") + } + } + await bridge.shutdown() + } +} diff --git a/provider-swift/Tests/test_protocol_fixture_resources.py b/provider-swift/Tests/test_protocol_fixture_resources.py index b212240ac6..212c071ed9 100644 --- a/provider-swift/Tests/test_protocol_fixture_resources.py +++ b/provider-swift/Tests/test_protocol_fixture_resources.py @@ -13,6 +13,7 @@ # Digests captured from the original shared fixtures before platform removal. SHA256 = { "calibrated_capacity_wire_fixture": "c73d1be2972540dbe48e8cc5b3871a15f44dcbafb4f8c51f6ee27e88b01c2e41", + "coordinator_features_wire": "aaefb0b56ac4c16415cbcfea86c61625fa9c0d0c97e6db76ff8eeceba9bb7021", "calibrated_deadline_decisions": "079a387c50070d2742e95dee1c6a8115ba49d10934eacc219574adb8c4ac6650", "deadline_coverage_confidence": "3a96307ff7cdb2e3949c039313549d1f2e0142b8f49fc2d23b20882704d760eb", "deadline_unbounded_reasons": "547b9cdf473f19d120e9f2e5db5dd47d3211796f8b1b85d685c7dce748aa1d4c", @@ -30,6 +31,7 @@ "Inference/Performance/Deadline/DeadlineCoverageConfidenceTests.swift": ["deadline_coverage_confidence"], "Inference/Performance/Deadline/DeadlineDecisionFixtureTests.swift": ["calibrated_deadline_decisions"], "Inference/Memory/ProcessMemoryTelemetryTests.swift": ["process_memory_wire"], + "Inference/Performance/CoordinatorDecodeRateDecayTests.swift": ["coordinator_features_wire"], }