diff --git a/changelog.d/coordinator-traffic-verdict.md b/changelog.d/coordinator-traffic-verdict.md index 82c25341ec..5b8af53645 100644 --- a/changelog.d/coordinator-traffic-verdict.md +++ b/changelog.d/coordinator-traffic-verdict.md @@ -1,5 +1,6 @@ ### Say why a connected provider gets no coordinator work -- `darkbloom status` adds a `Traffic:` line and `darkbloom doctor` a `coordinator traffic` check. Either the coordinator can route work to this connection, or the line says why it cannot, with a fix: not connected; no coordinator verdict minutes after connecting (previously only `Trust: awaiting coordinator status`); App Attest authorization expired and not renewed; or the coordinator's reason for not authorizing it. Reasons include a locked login keychain, a stalled Apple App Attest call, App Attest unavailable on macOS 26 or outside a logged-in GUI session, and a connection without a linked account (`darkbloom login`). A connected Mac with a warm model no longer looks healthy while it receives nothing. Neither appears while an add-on holds the connected Mac: the hold, which `darkbloom status` reports on its own `Not serving:` line, is why no work arrives, not the connection's authorization. -- The daemon state file records the coordinator connection (`coordinator_connection`: connected, since when it has been up or down, and the registrations since the provider started). Failed reconnect attempts do not reset the time, so a long outage reads as one. -- The provider now re-registers a connection the coordinator has not authorized for 15–30 minutes (a random delay per process), then again after 30 minutes, 1 hour, 2 hours and every 4 hours while it stays unauthorized. It waits until the provider is idle: no accepted or local requests, model loads, Autopilot operation, drain or update. A new registration starts a new coordinator verification session, which clears coordinator states that previously needed a restart, such as verification that stopped after an unclassified failure or waits out an hourly retry. `darkbloom logs` shows when the coordinator stops or resumes routing work to the connection and each re-registration. +- `darkbloom status` adds a `Traffic:` line and `darkbloom doctor` a `coordinator traffic` check. Either the coordinator can route work to this connection, or the line says why it cannot, with a fix: not connected; no coordinator verdict minutes after connecting (previously only `Trust: awaiting coordinator status`); an `untrusted` or `offline` status; App Attest authorization expired and not renewed; or the coordinator's reason for not authorizing it. Reasons include a locked login keychain, a stalled Apple App Attest call, App Attest unavailable on macOS 26 or outside a logged-in GUI session, and a connection without a linked account (`darkbloom login`). A connected Mac with a warm model no longer looks healthy while it receives nothing. Neither appears while an add-on holds the connected Mac: the hold, which `darkbloom status` reports on its own `Not serving:` line, is why no work arrives, not the connection's authorization. +- Only current evidence says a connection gets no work. A refusal counts while it is at most 60 seconds old, as when the coordinator keeps repeating it, and not in the first 90 seconds after connecting. An older refusal reads `unconfirmed`, with its age and reason and no fix: the current coordinator sends no status when legacy verification authorizes a connection after the refusal it sends at registration, so legacy-verified Macs are never told they are excluded or need macOS 27. A request the coordinator routed after its latest status reads as eligible. +- The daemon state file records the coordinator connection (`coordinator_connection`: connected, since when it has been up or down, the registrations since the provider started, and `last_request_at`, when the coordinator last sent the connection a request). Failed reconnect attempts do not reset the time, so a long outage reads as one. +- The provider now re-registers a connection the coordinator keeps refusing for 15–30 minutes (a random delay per process), then again after 30 minutes, 1 hour, 2 hours and every 4 hours while the refusal stays current. A refusal sent once at registration never triggers it. It waits until the provider is idle: no accepted or local requests, model loads, Autopilot operation, drain or update. A new registration starts a new coordinator verification session, which clears coordinator states that previously needed a restart, such as verification that stopped after an unclassified failure or waits out an hourly retry. `darkbloom logs` shows when the coordinator starts refusing the connection, when it authorizes it, when its refusal is no longer current, and each re-registration. diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index bd551b1e22..e127c3a9b9 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1042,14 +1042,24 @@ Output includes: holds with each hold's UTC expiry and time left. `Not evictable for a load now` lists the resident models no load can evict at the snapshot, with the same reasons a refusal gives (`provider-swift/Sources/darkbloom/StatusCommand+Residency.swift`). -- `Traffic:` whether the coordinator can route work to this connection. `eligible - for coordinator work` names the App Attest lease or legacy verification; - `NOT receiving coordinator work:` names the cause with a `→ fix:` line - (disconnected, with how long the connection has been down across failed - reconnect attempts, no coordinator verdict 90 seconds after connecting, an expired - lease, or the coordinator's reason, such as a locked login keychain, a stalled - Apple call, App Attest unavailable on macOS 26 or outside a logged-in GUI - session, or a connection without a linked account). Omitted while a drain line +- `Traffic:` whether the coordinator can route work to this connection, judged + from current evidence only; the provider re-registers on the same verdict. + `eligible for coordinator work` names the App Attest lease or legacy + verification, or a request the coordinator routed after its latest status + (`received a coordinator request … ago`; state field + `coordinator_connection.last_request_at`). `not yet eligible` covers the first + 90 seconds after connecting (`statusGraceSeconds`) while the coordinator has + sent no status or one that does not authorize the connection yet. + `NOT receiving coordinator work:` names the cause with a `→ fix:` line: + disconnected, with how long the connection has been down across failed + reconnect attempts; no coordinator status 90 seconds after connecting; an + `untrusted` or `offline` status; an expired lease; or a refusal received in the + last 60 seconds (`refusalMaxAge`) with the coordinator's reason, such as a + locked login keychain, a stalled Apple call, App Attest unavailable on macOS 26 + or outside a logged-in GUI session, or a connection without a linked account. + An older refusal reads `unconfirmed`, with its age and reason and no fix: the + current coordinator sends no status when legacy verification authorizes a + connection after the refusal it sends at registration. Omitted while a drain line is shown, while an add-on holds a connected Mac (its `Not serving: held by add-on` line says why no work arrives), for a stale snapshot, and for daemons that predate the `coordinator_connection` state field diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index b2652b9fd4..ab310f9df8 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -80,7 +80,7 @@ App Attest, attestation readiness, trust, model fit, runtime, billing, version; | `coordinator health`, `minimum version`, `coordinator trust` | Coordinator reachable, this version is accepted, trust verdict with reasons | `darkbloom update`; reasons are explained in [attestation](./attestation.md) | | `trust level` stuck at `self_signed` | The MDM `SecurityInfo` cross-check has not passed for this connection | `darkbloom enroll` if not enrolled; otherwise wait — see [Reaching and keeping `hardware` trust](./attestation.md#troubleshooting) | | `daemon`, `daemon connected`, `daemon state freshness` | Daemon process alive, WebSocket connected, snapshot refreshed | See [service lifecycle](#the-service-does-not-stay-running); a stale snapshot ⇒ `darkbloom restart` | -| `coordinator traffic` | Whether the coordinator can route work to this connection: connected, a coordinator verdict received, and an App Attest lease or legacy authorization current. ✗ names the cause: disconnected, no verdict minutes after connecting, an expired lease, or the coordinator's reason for not authorizing it. Skipped while an add-on holds the connected Mac on purpose: `darkbloom status` prints `Not serving: held by add-on …` and `darkbloom addon` shows the hold (`provider-swift/Sources/ProviderCore/Diagnostics/ServingReadiness.swift`) | Follow the printed fix. A locked login keychain, a stalled Apple call or a provider started outside the logged-in GUI session clears after logging in at the console or `darkbloom restart`; `app_attest_identity_required` needs `darkbloom login`; macOS 26 needs macOS 27 unless the Mac is in the legacy MDM cohort. See [connected but no traffic](#coordinator-connection) | +| `coordinator traffic` | Whether the coordinator can route work to this connection: connected, a coordinator verdict received, and an App Attest lease, legacy authorization or a request routed since the latest status. ✗ names the cause from current evidence only: disconnected, no verdict minutes after connecting, an `untrusted` or `offline` status, an expired lease, or a refusal received in the last minute with the coordinator's reason. ℹ `unconfirmed`: the last refusal is older than that, so it does not show an exclusion; the current coordinator sends no status when legacy verification authorizes a connection after its registration refusal. Skipped while an add-on holds the connected Mac on purpose: `darkbloom status` prints `Not serving: held by add-on …` and `darkbloom addon` shows the hold (`provider-swift/Sources/ProviderCore/Diagnostics/ServingReadiness.swift`) | Follow the printed fix. A locked login keychain, a stalled Apple call or a provider started outside the logged-in GUI session clears after logging in at the console or `darkbloom restart`; `app_attest_identity_required` needs `darkbloom login`; macOS 26 needs macOS 27 unless the Mac is in the legacy MDM cohort. `unconfirmed` prints no fix: its reason is the coordinator's last, which may no longer apply. See [connected but no traffic](#coordinator-connection) | | `recent model load` | Last model-load error recorded by the daemon | See [models and memory](#models-and-memory) | | `kv backend posture`, `kv backend crash-loop guard` | Explicit `engine_v2_kv_backend` request honoured; guard record present | See [KV-backend guard](#kv-backend-crash-loop-guard) | | `competing inference` | Another inference server holds the GPU (`provider-swift/Sources/darkbloom/Diagnostics/CompetingInferenceDiagnostics.swift`) | Quit it; it competes for the same unified memory and GPU time | @@ -140,7 +140,7 @@ tail -50 ~/.darkbloom/provider.log ~/.darkbloom/watchdog.log |---|---|---| | `daemon connected` ⚠, console shows offline | The client reconnects with an exponential backoff (`ExponentialBackoff`, `provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Connection.swift`; bounds in [runtime constants](./cli-reference.md#runtime-constants)) | `curl -v https://api.darkbloom.dev/health`; check DNS, clock, TLS interception, firewall on 443 | | Log: `WebSocket pong timeout (no response in 30s)` | No pong within `pongTimeout` of a `pingInterval` ping closes the socket and the backoff restarts it ([runtime constants](./cli-reference.md#runtime-constants)) | Network path stalls; nothing to configure on the provider | -| Heartbeats arrive but requests do not ("no traffic until restart") | A heartbeat every `heartbeat_interval_secs` proves the connection, not routability. The coordinator routes only a connection it authorizes (an App Attest lease or legacy verification) | `darkbloom status` → `Traffic:` and `darkbloom doctor` → `coordinator traffic` name the cause and fix. The provider re-registers a connection the coordinator has not authorized for 15–30 minutes, then after 30 minutes, 1 hour, 2 hours and every 4 hours while it stays unauthorized, only while it is idle: no accepted or local requests, model loads, Autopilot operation, drain or update (`provider-swift/Sources/ProviderCore/Coordinator/UnauthorizedConnectionRecovery.swift`, `provider-swift/Sources/ProviderCore/ProviderLoop+ServingAuthorizationRecovery.swift`), and `darkbloom logs` records when routing stops or resumes. The routing gates are listed in [`../architecture/security/attestation.md#routing-gate`](../architecture/security/attestation.md#routing-gate) | +| Heartbeats arrive but requests do not ("no traffic until restart") | A heartbeat every `heartbeat_interval_secs` proves the connection, not routability. The coordinator routes only a connection it authorizes (an App Attest lease or legacy verification) | `darkbloom status` → `Traffic:` and `darkbloom doctor` → `coordinator traffic` name the cause and fix. The provider re-registers a connection while that verdict stays `NOT receiving` for 15–30 minutes, then after 30 minutes, 1 hour, 2 hours and every 4 hours, only while it is idle: no accepted or local requests, model loads, Autopilot operation, drain or update (`provider-swift/Sources/ProviderCore/Coordinator/UnauthorizedConnectionRecovery.swift`, `provider-swift/Sources/ProviderCore/ProviderLoop+ServingAuthorizationRecovery.swift`). A refusal counts only while the coordinator keeps repeating it, so a refusal sent once at registration never triggers a re-registration. `darkbloom logs` records when the coordinator starts refusing the connection, when it authorizes it, and when its refusal is no longer current. The routing gates are listed in [`../architecture/security/attestation.md#routing-gate`](../architecture/security/attestation.md#routing-gate) | | `minimum version` ✗ | Coordinator rejects this `ProviderCore.version` | `darkbloom update` | | `Requests served` in `status` is higher than the jobs in the console's Earnings | The status count covers only the time since the daemon started (the `… ago` on the line) and includes requests that ended early on a coordinator cancel or a dropped connection, which the coordinator may not pay for, and free [self-route](./self-route.md) requests to your own machine. Earnings lists only paid jobs (`provider-swift/Sources/darkbloom/StatusCommand+ServedRequests.swift`) | Compare Earnings over the same period; the machine card's Tokens/reqs add the status counters up across restarts | diff --git a/provider-swift/Sources/ProviderCore/Coordinator/UnauthorizedConnectionRecovery.swift b/provider-swift/Sources/ProviderCore/Coordinator/UnauthorizedConnectionRecovery.swift index bbb6b893da..e15b10259c 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/UnauthorizedConnectionRecovery.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/UnauthorizedConnectionRecovery.swift @@ -1,6 +1,9 @@ import Foundation /// When to re-register a connection the coordinator keeps refusing to route. +/// "Refusing" is the blocked `ServingReadiness` verdict that `status` and +/// `doctor` show, so only current evidence counts: a refusal the coordinator +/// stopped repeating does not. /// /// A new registration starts a new coordinator verification session. That /// clears coordinator-side states only a reconnect clears: a verification @@ -34,17 +37,4 @@ enum UnauthorizedConnectionRecovery { let doublings = min(max(attempts - 1, 0), 8) return min(firstRetryInterval * pow(2, Double(doublings)), maximumRetryInterval) } - - /// Whether the coordinator's latest status says this connection may not be - /// routed: an explicit `none` path, an expired App Attest lease, or no - /// status long after registering. A status without an authorization object - /// (a coordinator without App Attest serving) is not judged. - static func connectionLacksAuthorization( - connectedAt: Double, trust: DaemonState.Trust?, now: Double - ) -> Bool { - guard let trust else { return now - connectedAt >= ServingReadiness.statusGraceSeconds } - if trust.status == "untrusted" || trust.status == "offline" { return true } - guard let authorization = trust.authorization else { return false } - return !authorization.hasCurrentAppAttestAuthorization(now: now) && authorization.path != "legacy" - } } diff --git a/provider-swift/Sources/ProviderCore/Diagnostics/ServingReadiness.swift b/provider-swift/Sources/ProviderCore/Diagnostics/ServingReadiness.swift index 88807402be..3c8ac251bd 100644 --- a/provider-swift/Sources/ProviderCore/Diagnostics/ServingReadiness.swift +++ b/provider-swift/Sources/ProviderCore/Diagnostics/ServingReadiness.swift @@ -6,21 +6,40 @@ import ProviderAppAttest /// can still receive nothing when the coordinator has not authorized the /// connection; without this verdict it looks healthy in `status`. /// -/// Diagnostics only: the coordinator owns routing and authorization. +/// Diagnostics and the re-registration trigger +/// (`ProviderLoop.superviseServingAuthorization`) only: the coordinator owns +/// routing and authorization. public enum ServingReadiness { public enum Verdict: Equatable, Sendable { - /// The coordinator currently authorizes this connection. + /// The coordinator currently authorizes this connection, or routed it + /// a request after its latest status. case authorized(String) - /// Too early to judge: just connected and no coordinator status yet. + /// Too early to judge: just connected, and the coordinator has sent + /// no status or one that does not authorize the connection yet. case pending(String) + /// The coordinator's latest status refused the connection, but it is + /// too old to say whether the coordinator routes the connection now. + case unconfirmed(String) /// The coordinator cannot route work to this connection. case blocked(DiagnosticAdvice) } /// A coordinator sends its first status right after registration; none - /// after this long means it never confirmed the connection. + /// after this long means it never confirmed the connection. A refusal + /// this early is not a verdict either: the coordinator computes the + /// registration status before it records the connection's first verified + /// challenge, which legacy verification requires. public static let statusGraceSeconds: Double = 90 + /// How long a refusal (an authorization object with no App Attest lease, + /// current or expired, and no legacy verification) describes the + /// connection. The coordinator renews a status it maintains every 5 s + /// (App Attest leases today), but the current coordinator sends none when + /// legacy verification authorizes a connection after its registration + /// refusal. Shorter than `statusGraceSeconds`, so the registration status + /// alone never blocks. + public static let refusalMaxAge: Double = 60 + /// Nil when the daemon predates connection reporting (a reader cannot /// tell disconnected from connected), an add-on holds the connected Mac, /// or the coordinator sends no authorization verdict for a connection @@ -30,24 +49,43 @@ public enum ServingReadiness { macOSMajorVersion: Int = ProcessInfo.processInfo.operatingSystemVersion.majorVersion ) -> Verdict? { guard let connection = state.coordinatorConnection else { return nil } - let cli = BuildEnvironment.current.cliName - // Many registrations in one run with short connections is a reconnect - // loop: the coordinator closes each registration before routing it. - let registrations = connection.connections > 1 ? "; registration \(connection.connections) since the provider started" : "" guard connection.connected else { return .blocked(DiagnosticAdvice( - message: "not connected to the coordinator (disconnected \(age(since: connection.since, now: now)) ago\(registrations)); the provider reconnects on its own", - fix: "check this Mac's network; if it stays disconnected, run `\(cli) restart`")) + message: "not connected to the coordinator (disconnected \(age(since: connection.since, now: now)) ago\(registrations(connection))); the provider reconnects on its own", + fix: "check this Mac's network; if it stays disconnected, run `\(BuildEnvironment.current.cliName) restart`")) } // A hold keeps the connection but leaves routing on purpose; its own // status line explains the missing work, and authorization does not. if state.addonHold?.holds.isEmpty == false { return nil } - guard let trust = state.trust else { - if now - connection.since < statusGraceSeconds { - return .pending("connected \(age(since: connection.since, now: now)) ago\(registrations); waiting for the coordinator's verdict") + return verdict(connection: connection, trust: state.trust, appAttest: state.appAttest, + now: now, macOSMajorVersion: macOSMajorVersion) + } + + /// The verdict for a live connection. The provider re-registers a + /// connection on the same verdict (`ProviderLoop.superviseServingAuthorization`), + /// so only current evidence blocks: an explicit `untrusted` or `offline` + /// status, an expired App Attest lease, a refusal at most + /// `refusalMaxAge` old, or no status at all after `statusGraceSeconds`. + /// A request the coordinator routed after its latest status outweighs a + /// refusal or a missing status. + static func verdict( + connection: DaemonState.CoordinatorConnection, trust: DaemonState.Trust?, + appAttest: AppAttestLocalStatus? = nil, now: Double, + macOSMajorVersion: Int = ProcessInfo.processInfo.operatingSystemVersion.majorVersion + ) -> Verdict? { + let cli = BuildEnvironment.current.cliName + let connectedFor = age(since: connection.since, now: now) + let justConnected = now - connection.since < statusGraceSeconds + let routed = requestAfterLatestStatus(connection, trust: trust).map { + Verdict.authorized("received a coordinator request \(age(since: $0, now: now)) ago") + } + guard let trust else { + if let routed { return routed } + if justConnected { + return .pending("connected \(connectedFor) ago\(registrations(connection)); waiting for the coordinator's verdict") } return .blocked(DiagnosticAdvice( - message: "connected for \(age(since: connection.since, now: now)), but the coordinator has not confirmed this connection", + message: "connected for \(connectedFor), but the coordinator has not confirmed this connection", fix: "run `\(cli) restart`; if it persists, run `\(cli) doctor`")) } if trust.status == "untrusted" || trust.status == "offline" { @@ -70,11 +108,36 @@ public enum ServingReadiness { if authorization.path == "app_attest", let expiresAt = authorization.expiresAt { return .blocked(DiagnosticAdvice( message: "App Attest authorization expired at \(clock(expiresAt)) and has not been renewed", - fix: localCause(state.appAttest, macOSMajorVersion: macOSMajorVersion)?.fix + fix: localCause(appAttest, macOSMajorVersion: macOSMajorVersion)?.fix ?? "the coordinator retries within 10 minutes; if it persists, run `\(cli) restart`")) } + // A refusal: it can go out of date, and routed work outweighs it. + if let routed { return routed } + let reason = authorization.reason.isEmpty ? "" : ": \(authorization.reason)" + if justConnected { + return .pending("connected \(connectedFor) ago\(registrations(connection)); not authorized so far\(reason)") + } + guard now - trust.receivedAt <= refusalMaxAge else { + return .unconfirmed("no current coordinator verdict; the last one, \(age(since: trust.receivedAt, now: now)) ago, did not authorize this connection\(reason)") + } return .blocked(blockedCause( - reason: authorization.reason, appAttest: state.appAttest, macOSMajorVersion: macOSMajorVersion)) + reason: authorization.reason, appAttest: appAttest, macOSMajorVersion: macOSMajorVersion)) + } + + /// When the coordinator last routed this connection a request, if that + /// was after its latest status. + private static func requestAfterLatestStatus( + _ connection: DaemonState.CoordinatorConnection, trust: DaemonState.Trust? + ) -> Double? { + guard let requestAt = connection.lastRequestAt else { return nil } + if let trust, requestAt <= trust.receivedAt { return nil } + return requestAt + } + + /// Many registrations in one run with short connections is a reconnect + /// loop: the coordinator closes each registration before routing it. + private static func registrations(_ connection: DaemonState.CoordinatorConnection) -> String { + connection.connections > 1 ? "; registration \(connection.connections) since the provider started" : "" } /// The cause of an unauthorized connection. A local App Attest observation diff --git a/provider-swift/Sources/ProviderCore/ProviderLogger.swift b/provider-swift/Sources/ProviderCore/ProviderLogger.swift index 83c50d8beb..484de249ae 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLogger.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLogger.swift @@ -146,6 +146,7 @@ enum ProviderOperationalMessage: String, CaseIterable, Sendable { case coordinatorChunkSendFailed = "Coordinator chunk send failed" case coordinatorNotRoutingConnection = "Coordinator is not routing work to this connection. Run {cli} status for the reason." case coordinatorRoutingConnection = "Coordinator authorizes this connection for work" + case coordinatorRefusalUnconfirmed = "Coordinator refusal of this connection is no longer current; routing is unconfirmed" case unauthorizedConnectionReregistering = "Coordinator has not authorized this connection for at least 15 min; re-registering it" // Attestation and integrity lifecycle. diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift index 5d6a04acb6..a8c13679a0 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift @@ -426,6 +426,10 @@ extension ProviderLoop { noteCoordinatorConnection(connected: event.isConnected) clearConnectionAuthorization() cancelAppAttestShadow() + case .inferenceRequest: + // Here, not in the work reader: on arrival, in order with + // the trust statuses `ServingReadiness` compares it to. + noteCoordinatorRequest() default: break } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ServingAuthorizationRecovery.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ServingAuthorizationRecovery.swift index 13e69f9c79..b943443354 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ServingAuthorizationRecovery.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ServingAuthorizationRecovery.swift @@ -12,25 +12,40 @@ extension ProviderLoop { connections: (previous?.connections ?? 0) + (connected ? 1 : 0)) } - /// Runs every capacity tick. Logs when the coordinator stops or resumes - /// routing this connection, and re-registers a connection it keeps - /// refusing (`UnauthorizedConnectionRecovery`). + /// A request the coordinator routes here is newer evidence than a refusal + /// it sent earlier (`ServingReadiness`). The next state write persists it. + internal func noteCoordinatorRequest(now: Double = Date().timeIntervalSince1970) { + guard coordinatorConnection?.connected == true else { return } + coordinatorConnection?.lastRequestAt = now + } + + /// Runs every capacity tick on the verdict `status` and `doctor` show. + /// Logs when the coordinator starts or stops refusing this connection, + /// and re-registers a connection it keeps refusing + /// (`UnauthorizedConnectionRecovery`). internal func superviseServingAuthorization(now: Double = Date().timeIntervalSince1970) { guard let connection = coordinatorConnection, connection.connected, !isShuttingDown else { unauthorizedSince = nil return } - if let authorization = lastTrustStatus?.authorization, - authorization.hasCurrentAppAttestAuthorization(now: now) || authorization.path == "legacy" { + switch ServingReadiness.verdict(connection: connection, trust: lastTrustStatus, now: now) { + case .blocked? where !advertisedModels.isEmpty: + superviseRefusedConnection(now: now) + case .blocked?: + unauthorizedSince = nil + case .authorized?: unauthorizedReconnectAttempts = 0 - } - let lacksAuthorization = UnauthorizedConnectionRecovery.connectionLacksAuthorization( - connectedAt: connection.since, trust: lastTrustStatus, now: now) - guard !advertisedModels.isEmpty, lacksAuthorization else { - if unauthorizedSince != nil, !lacksAuthorization { logger.info(.coordinatorRoutingConnection) } + if unauthorizedSince != nil { logger.info(.coordinatorRoutingConnection) } + unauthorizedSince = nil + case .pending?, .unconfirmed?, nil: + // A refusal the coordinator stopped repeating says nothing about + // the connection now; it is not evidence of routing either. + if unauthorizedSince != nil { logger.info(.coordinatorRefusalUnconfirmed) } unauthorizedSince = nil - return } + } + + private func superviseRefusedConnection(now: Double) { guard let since = unauthorizedSince else { unauthorizedSince = now logger.warning(.coordinatorNotRoutingConnection) diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift index c07d412324..258275d504 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift @@ -153,7 +153,8 @@ extension ProviderLoop { } internal func handleTrustStatus(trustLevel: String, status: String, reason: String, - authorization: ProviderAuthorizationStatus? = nil) { + authorization: ProviderAuthorizationStatus? = nil, + receivedAt: Double = Date().timeIntervalSince1970) { let previous = lastTrustStatus if previous?.trustLevel != trustLevel || previous?.status != status || previous?.reason != reason || !ProviderAuthorizationStatus.sameDiagnosticDecision(previous?.authorization, authorization) { @@ -164,8 +165,7 @@ extension ProviderLoop { // the coordinator's reason (otherwise it is only in the logs). lastTrustStatus = DaemonState.Trust( trustLevel: trustLevel, status: status, reason: reason, - receivedAt: Date().timeIntervalSince1970, - authorization: authorization) + receivedAt: receivedAt, authorization: authorization) writeDaemonState() } diff --git a/provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift b/provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift index fd09aef9d0..0d22a5f01b 100644 --- a/provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift +++ b/provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift @@ -335,10 +335,14 @@ public struct DaemonState: Codable, Sendable, Equatable { public var since: Double /// Registrations this process has completed, including the first. public var connections: Int - public init(connected: Bool, since: Double, connections: Int) { + /// Epoch seconds when the coordinator last sent this connection an + /// inference request; nil before the first. + public var lastRequestAt: Double? + public init(connected: Bool, since: Double, connections: Int, lastRequestAt: Double? = nil) { self.connected = connected self.since = since self.connections = connections + self.lastRequestAt = lastRequestAt } } diff --git a/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift b/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift index a88c690360..2238b1d716 100644 --- a/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift +++ b/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift @@ -14,6 +14,9 @@ enum DoctorRunner { case .pending(let detail): return Diagnostic(section: .traffic, name: "coordinator traffic", level: .info, message: "not yet eligible (\(detail))", fix: nil) + case .unconfirmed(let detail): + return Diagnostic(section: .traffic, name: "coordinator traffic", level: .info, + message: "unconfirmed (\(detail))", fix: nil) case .blocked(let advice): return Diagnostic(section: .traffic, name: "coordinator traffic", level: .fail, message: "NOT receiving coordinator work: \(advice.message)", fix: advice.fix) diff --git a/provider-swift/Sources/darkbloom/StatusCommand+Traffic.swift b/provider-swift/Sources/darkbloom/StatusCommand+Traffic.swift index 4ce274b876..db0434fb51 100644 --- a/provider-swift/Sources/darkbloom/StatusCommand+Traffic.swift +++ b/provider-swift/Sources/darkbloom/StatusCommand+Traffic.swift @@ -9,6 +9,8 @@ extension Status { return ["Traffic: eligible for coordinator work (\(detail))"] case .pending(let detail): return ["Traffic: not yet eligible (\(detail))"] + case .unconfirmed(let detail): + return ["Traffic: unconfirmed (\(detail))"] case .blocked(let advice): return ["Traffic: NOT receiving coordinator work: \(advice.message)"] + (advice.fix.map { [" → fix: \($0)"] } ?? []) diff --git a/provider-swift/Tests/DarkbloomCLITests/DoctorOperatorDiagnosisTests.swift b/provider-swift/Tests/DarkbloomCLITests/DoctorOperatorDiagnosisTests.swift index adeb58d5ab..3ba904440a 100644 --- a/provider-swift/Tests/DarkbloomCLITests/DoctorOperatorDiagnosisTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/DoctorOperatorDiagnosisTests.swift @@ -106,12 +106,13 @@ struct DoctorOperatorDiagnosisTests { "/v1/releases/latest": .init( status: 200, body: CLICommandSandbox.releaseJSON(version: ProviderCore.version)), ]) - func diagnose(_ authorization: ProviderAuthorizationStatus) async throws -> Diagnostic { + func diagnose(_ authorization: ProviderAuthorizationStatus, + receivedAgo: Double = 30) async throws -> Diagnostic { let now = Date().timeIntervalSince1970 var state = try CLICommandSandbox.runningState( now: now, trust: .init(trustLevel: "self_signed", status: "online", - reason: "Provider authorization updated", receivedAt: now - 30, + reason: "Provider authorization updated", receivedAt: now - receivedAgo, authorization: authorization), currentModel: "acme/Warm-4bit", warmModels: ["acme/Warm-4bit"], advertisedModels: ["acme/Warm-4bit"]) @@ -131,6 +132,16 @@ struct DoctorOperatorDiagnosisTests { #expect(blocked.message.hasPrefix("NOT receiving coordinator work: the coordinator is not routing work here: the login keychain")) #expect(blocked.fix?.hasPrefix("log in at this Mac's console to unlock the login keychain") == true) + // The coordinator refused the connection at registration and has + // said nothing since, as it does for a legacy-verified Mac. + let unconfirmed = try await diagnose(ProviderAuthorizationStatus( + appAttestAvailable: true, path: "none", reason: "app_attest_qualification_required", + sessionID: "session", machineID: ""), receivedAgo: 1_150) + #expect(unconfirmed.level == .info) + #expect(unconfirmed.message == "unconfirmed (no current coordinator verdict; the last one, 19m ago, " + + "did not authorize this connection: app_attest_qualification_required)") + #expect(unconfirmed.fix == nil) + let eligible = try await diagnose(CLICommandSandbox.appAttestAuthorization(now: Date().timeIntervalSince1970)) #expect(eligible.level == .pass) #expect(eligible.message.hasPrefix("eligible for coordinator work (App Attest authorized until ")) diff --git a/provider-swift/Tests/DarkbloomCLITests/StatusCommandRunTests.swift b/provider-swift/Tests/DarkbloomCLITests/StatusCommandRunTests.swift index 67fcdeba57..f8a66408bf 100644 --- a/provider-swift/Tests/DarkbloomCLITests/StatusCommandRunTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/StatusCommandRunTests.swift @@ -1,4 +1,5 @@ import Foundation +import ProviderAppAttest import ProviderCore import Testing @@ -195,6 +196,24 @@ struct StatusCommandRunTests { print("== KEYCHAIN") try await runCLICommand(Status.self, arguments) + // A legacy Mac on macOS 26: the coordinator refused it at + // registration and sent nothing when legacy verification + // authorized it moments later. + now = Date().timeIntervalSince1970 + state = try CLICommandSandbox.runningState( + now: now, + trust: .init( + trustLevel: "self_signed", status: "online", + reason: "SE attestation verified, awaiting MDM verification", receivedAt: now - 1_150, + authorization: ProviderAuthorizationStatus( + appAttestAvailable: true, path: "none", reason: "app_attest_qualification_required", + sessionID: "session", machineID: ""))) + state.coordinatorConnection = .init(connected: true, since: now - 1_200, connections: 1) + state.appAttest = AppAttestLocalStatus(observedAt: now, launchSession: .unknown, availabilityReason: .osBelow27) + sandbox.writeState(state) + print("== REGISTRATION REFUSAL ONLY") + try await runCLICommand(Status.self, arguments) + now = Date().timeIntervalSince1970 state = try CLICommandSandbox.runningState( now: now, @@ -213,11 +232,18 @@ struct StatusCommandRunTests { #expect(missing.contains("\nTrust: awaiting coordinator status\nTraffic: NOT receiving coordinator work: " + "connected for 20m, but the coordinator has not confirmed this connection\n → fix: run `darkbloom restart`")) - let keychain = try #require(outputSection(output, from: "== KEYCHAIN", to: "== AUTHORIZED")) + let keychain = try #require(outputSection(output, from: "== KEYCHAIN", to: "== REGISTRATION REFUSAL ONLY")) #expect(keychain.contains("\nTraffic: NOT receiving coordinator work: the coordinator is not routing work here: " + "the login keychain refused this Mac's App Attest key record (it is usually locked)\n" + " → fix: log in at this Mac's console to unlock the login keychain")) + let registrationOnly = try #require(outputSection(output, from: "== REGISTRATION REFUSAL ONLY", to: "== AUTHORIZED")) + let traffic = "\nTraffic: unconfirmed (no current coordinator verdict; the last one, 19m ago, " + + "did not authorize this connection: app_attest_qualification_required)\n" + #expect(registrationOnly.contains(traffic)) + #expect(!registrationOnly.contains(traffic + " → fix:")) + #expect(!registrationOnly.contains("NOT receiving")) + let authorized = try #require(outputSection(output, from: "== AUTHORIZED", to: "== END")) #expect(authorized.contains("\nTraffic: eligible for coordinator work (App Attest authorized until ")) #expect(!authorized.contains("NOT receiving")) diff --git a/provider-swift/Tests/ProviderCoreTests/Diagnostics/ServingReadinessTests.swift b/provider-swift/Tests/ProviderCoreTests/Diagnostics/ServingReadinessTests.swift index ed2e116fd9..2c1bdef3af 100644 --- a/provider-swift/Tests/ProviderCoreTests/Diagnostics/ServingReadinessTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Diagnostics/ServingReadinessTests.swift @@ -24,9 +24,11 @@ import Testing } private func trust(path: String, reason: String, expiresAt: Double? = nil, - level: String = "self_signed", status: String = "online") -> DaemonState.Trust { + level: String = "self_signed", status: String = "online", + receivedAt: Double? = nil) -> DaemonState.Trust { DaemonState.Trust( - trustLevel: level, status: status, reason: "Provider authorization updated", receivedAt: now - 30, + trustLevel: level, status: status, reason: "Provider authorization updated", + receivedAt: receivedAt ?? now - 30, authorization: ProviderAuthorizationStatus( appAttestAvailable: true, path: path, expiresAt: expiresAt, reason: reason, sessionID: "session", machineID: path == "none" ? "" : "machine")) @@ -115,6 +117,68 @@ import Testing let advice = try #require(blocked(ServingReadiness.verdict( state(trust: trust(path: "app_attest", reason: "app_attest_verified", expiresAt: now - 60)), now: now))) #expect(advice.message.contains("App Attest authorization expired at")) + // The lease names its own expiry, so an old status still proves it lapsed. + #expect(blocked(ServingReadiness.verdict(state(since: now - 10_000, trust: trust( + path: "app_attest", reason: "app_attest_verified", expiresAt: now - 3_600, receivedAt: now - 7_200)), + now: now)) != nil) + } + + /// The coordinator computes the registration status before it records + /// the first verified challenge that legacy verification needs, so a + /// refusal right after connecting is not a verdict yet. + @Test func aRefusalRightAfterConnectingIsPending() { + let verdict = ServingReadiness.verdict(state(since: now - 20, trust: trust( + path: "none", reason: "app_attest_qualification_required", receivedAt: now - 19)), now: now) + #expect(verdict == .pending("connected 20s ago; not authorized so far: app_attest_qualification_required")) + } + + /// A legacy (MDM-cohort) Mac on the current coordinator: one refusal at + /// registration, then no status when legacy verification authorizes the + /// connection. Once that refusal is older than `refusalMaxAge` the verdict + /// is unconfirmed, labelled as the last one, with no fix and no macOS 27. + @Test func aRefusalTheCoordinatorStoppedRepeatingIsUnconfirmed() throws { + let osTooOld = AppAttestLocalStatus(observedAt: now, launchSession: .unknown, availabilityReason: .osBelow27) + func verdict(receivedAt: Double) -> ServingReadiness.Verdict? { + ServingReadiness.verdict(state(trust: trust( + path: "none", reason: "app_attest_qualification_required", receivedAt: receivedAt), + appAttest: osTooOld), now: now, macOSMajorVersion: 26) + } + // A refusal the coordinator keeps repeating is current. + let current = try #require(blocked(verdict(receivedAt: now - ServingReadiness.refusalMaxAge))) + #expect(current.fix?.contains("upgrade to macOS 27") == true) + + let lastAtRegistration = verdict(receivedAt: now - 1_199) + #expect(lastAtRegistration == .unconfirmed("no current coordinator verdict; the last one, 19m ago, " + + "did not authorize this connection: app_attest_qualification_required")) + guard case .unconfirmed(let detail)? = verdict(receivedAt: now - ServingReadiness.refusalMaxAge - 1) else { + Issue.record("a refusal older than refusalMaxAge still blocks") + return + } + #expect(!detail.contains("macOS 27")) + #expect(ServingReadiness.refusalMaxAge < ServingReadiness.statusGraceSeconds) + } + + /// A request the coordinator routed after its latest status is newer + /// evidence than a refusal or a missing status, but not than an explicit + /// `untrusted` status or an expired lease. + @Test func aRequestAfterTheLatestStatusIsEligible() { + func verdict(_ trust: DaemonState.Trust?, requestAt: Double) -> ServingReadiness.Verdict? { + var routed = state(trust: trust) + routed.coordinatorConnection?.lastRequestAt = requestAt + return ServingReadiness.verdict(routed, now: now) + } + let refusal = trust(path: "none", reason: "app_attest_keychain_error", receivedAt: now - 30) + #expect(verdict(refusal, requestAt: now - 10) == .authorized("received a coordinator request 10s ago")) + #expect(blocked(verdict(refusal, requestAt: now - 31)) != nil) + #expect(verdict(nil, requestAt: now - 300) == .authorized("received a coordinator request 5m ago")) + let atRegistration = trust(path: "none", reason: "app_attest_qualification_required", receivedAt: now - 1_199) + #expect(verdict(atRegistration, requestAt: now - 600) == .authorized("received a coordinator request 10m ago")) + + let untrusted = DaemonState.Trust( + trustLevel: "self_signed", status: "untrusted", reason: "SIP disabled", receivedAt: now - 30) + #expect(blocked(verdict(untrusted, requestAt: now - 10)) != nil) + let lapsed = trust(path: "app_attest", reason: "app_attest_verified", expiresAt: now - 60, receivedAt: now - 120) + #expect(blocked(verdict(lapsed, requestAt: now - 10)) != nil) } @Test func coordinatorReasonsMapToOperatorCauses() throws { @@ -157,16 +221,22 @@ import Testing let advice = try #require(blocked(ServingReadiness.verdict(state(trust: DaemonState.Trust( trustLevel: "self_signed", status: "untrusted", reason: "SIP disabled", receivedAt: now)), now: now))) #expect(advice.message.contains("System Integrity Protection")) + // The coordinator sends a status when it trusts the connection again. + #expect(blocked(ServingReadiness.verdict(state(since: now - 10_000, trust: DaemonState.Trust( + trustLevel: "self_signed", status: "untrusted", reason: "SIP disabled", receivedAt: now - 7_200)), + now: now)) != nil) } @Test func connectionStateRoundTripsThroughTheStateFile() throws { let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: url) } - let written = state(trust: trust(path: "none", reason: "app_attest_keychain_error")) + var written = state(trust: trust(path: "none", reason: "app_attest_keychain_error")) + written.coordinatorConnection?.lastRequestAt = now - 5 DaemonStateFile.write(written, to: url) let read = try #require(DaemonStateFile.read(from: url)) #expect(read.coordinatorConnection == written.coordinatorConnection) #expect(read.trust?.authorization?.reason == "app_attest_keychain_error") + #expect(try String(contentsOf: url, encoding: .utf8).contains("\"last_request_at\"")) } } @@ -196,23 +266,41 @@ import Testing #expect(Policy.retryInterval(afterAttempts: 10) == Policy.maximumRetryInterval) } + /// Re-registration counts only the blocked `ServingReadiness` verdict + /// that `status` and `doctor` show. @Test func judgesOnlyCoordinatorVerdictsItCanRead() { let now = 100_000.0 - func trust(_ path: String?, expiresAt: Double? = nil, status: String = "online") -> DaemonState.Trust { - DaemonState.Trust(trustLevel: "self_signed", status: status, reason: "", receivedAt: now, + func trust(_ path: String?, expiresAt: Double? = nil, status: String = "online", + receivedAt: Double = 100_000) -> DaemonState.Trust { + DaemonState.Trust(trustLevel: "self_signed", status: status, reason: "", receivedAt: receivedAt, authorization: path.map { ProviderAuthorizationStatus(appAttestAvailable: true, path: $0, expiresAt: expiresAt, sessionID: "s", machineID: "m") }) } + func refuses(connectedAt: Double, _ trust: DaemonState.Trust?, requestAt: Double? = nil) -> Bool { + let connection = DaemonState.CoordinatorConnection( + connected: true, since: connectedAt, connections: 1, lastRequestAt: requestAt) + if case .blocked? = ServingReadiness.verdict(connection: connection, trust: trust, now: now) { return true } + return false + } // No status long after connecting: never confirmed. - #expect(Policy.connectionLacksAuthorization(connectedAt: now - 600, trust: nil, now: now)) - #expect(!Policy.connectionLacksAuthorization(connectedAt: now - 10, trust: nil, now: now)) - #expect(Policy.connectionLacksAuthorization(connectedAt: now - 600, trust: trust("none"), now: now)) - #expect(Policy.connectionLacksAuthorization(connectedAt: now - 600, trust: trust("app_attest", expiresAt: now - 1), now: now)) - #expect(!Policy.connectionLacksAuthorization(connectedAt: now - 600, trust: trust("app_attest", expiresAt: now + 60), now: now)) - #expect(!Policy.connectionLacksAuthorization(connectedAt: now - 600, trust: trust("legacy"), now: now)) + #expect(refuses(connectedAt: now - 600, nil)) + #expect(!refuses(connectedAt: now - 10, nil)) + #expect(refuses(connectedAt: now - 600, trust("none"))) + #expect(refuses(connectedAt: now - 600, trust("app_attest", expiresAt: now - 1))) + #expect(!refuses(connectedAt: now - 600, trust("app_attest", expiresAt: now + 60))) + #expect(!refuses(connectedAt: now - 600, trust("legacy"))) // Without an authorization object (no App Attest serving) nothing is judged. - #expect(!Policy.connectionLacksAuthorization(connectedAt: now - 600, trust: trust(nil), now: now)) - #expect(Policy.connectionLacksAuthorization(connectedAt: now - 600, trust: trust(nil, status: "untrusted"), now: now)) + #expect(!refuses(connectedAt: now - 600, trust(nil))) + #expect(refuses(connectedAt: now - 600, trust(nil, status: "untrusted"))) + // A refusal counts only while current: not right after connecting, not + // once the coordinator stopped repeating it, not before routed work. + #expect(!refuses(connectedAt: now - 30, trust("none"))) + #expect(!refuses(connectedAt: now - 600, trust("none", receivedAt: now - ServingReadiness.refusalMaxAge - 1))) + #expect(!refuses(connectedAt: now - 600, trust("none", receivedAt: now - 5), requestAt: now - 1)) + #expect(!refuses(connectedAt: now - 600, nil, requestAt: now - 1)) + // An expired lease and an explicit untrusted status do not go out of date. + #expect(refuses(connectedAt: now - 9_000, trust("app_attest", expiresAt: now - 3_600, receivedAt: now - 7_200))) + #expect(refuses(connectedAt: now - 9_000, trust(nil, status: "untrusted", receivedAt: now - 7_200))) } } diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ProviderAuthorizationConnectionTests.swift b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ProviderAuthorizationConnectionTests.swift index 9f9ac25fa7..fb00d850ee 100644 --- a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ProviderAuthorizationConnectionTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ProviderAuthorizationConnectionTests.swift @@ -1,4 +1,5 @@ import Foundation +import ProviderAppAttest import Testing @testable import ProviderCore @@ -42,10 +43,15 @@ import Testing private static let keychainRefusal = ProviderAuthorizationStatus( appAttestAvailable: true, path: "none", reason: "app_attest_keychain_error", sessionID: "session", machineID: "") + /// What the current coordinator sends at registration, before it records + /// the first verified challenge that legacy verification needs. + private static let registrationRefusal = ProviderAuthorizationStatus( + appAttestAvailable: true, path: "none", reason: "app_attest_qualification_required", + sessionID: "session", machineID: "") /// A loop advertising one model, writing its state file to `stateURL`, /// with no re-registration jitter. - private static func makeLoop(stateURL: URL) async throws -> ProviderLoop { + private static func makeLoop(stateURL: URL, logs: PublicLogLines? = nil) async throws -> ProviderLoop { let config = ProviderLoopConfig( coordinatorURL: "wss://api.darkbloom.dev/ws/provider", hardware: HardwareInfo( @@ -57,16 +63,29 @@ import Testing config: ProviderConfig( provider: ProviderSettings(name: "supervision-test"), backend: BackendSettings(), coordinator: CoordinatorSettings())) - let loop = try ProviderLoop(config: config, attestationSigner: nil) + let sink: ProviderLogger.Sink? = logs.map { lines -> ProviderLogger.Sink in + { level, visibility, message in lines.append(level, visibility, message) } + } + let loop = try ProviderLoop(config: config, attestationSigner: nil, logSinkForTesting: sink) await loop.installAuthorizationStateFileForTesting(stateURL) await loop.setUnauthorizedReconnectJitterForTesting(0) return loop } + /// The coordinator's status refusing the connection, received at `receivedAt`. + private static func refuse(_ loop: ProviderLoop, at receivedAt: Double, + _ refusal: ProviderAuthorizationStatus = keychainRefusal) async { + await loop.handleTrustStatus( + trustLevel: "self_signed", status: "online", reason: "Provider authorization updated", + authorization: refusal, receivedAt: receivedAt) + } + /// A connected provider the coordinator does not authorize looks healthy - /// but gets no work. The loop records the connection for `status`, starts - /// the unauthorized clock, re-registers once the threshold passes, and - /// clears the clock when the coordinator authorizes the connection. + /// but gets no work. While the coordinator repeats its refusal (every 5 s, + /// as it renews a status it maintains), the loop records the connection + /// for `status`, starts the unauthorized clock, re-registers once the + /// threshold passes, and clears the clock when the coordinator authorizes + /// the connection. @Test func unauthorizedConnectionIsReportedAndReregisteredAfterTheThreshold() async throws { let stateURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: stateURL) } @@ -74,9 +93,7 @@ import Testing let t0 = Date().timeIntervalSince1970 await loop.noteCoordinatorConnection(connected: true, now: t0 - 3_600) - await loop.handleTrustStatus( - trustLevel: "self_signed", status: "online", reason: "Provider authorization updated", - authorization: Self.keychainRefusal) + await Self.refuse(loop, at: t0) let written = try #require(DaemonStateFile.read(from: stateURL)) #expect(written.coordinatorConnection == .init(connected: true, since: t0 - 3_600, connections: 1)) guard case .blocked(let advice)? = ServingReadiness.verdict(written, now: t0) else { @@ -87,9 +104,14 @@ import Testing await loop.superviseServingAuthorization(now: t0) #expect(await loop.unauthorizedSince == t0) - await loop.superviseServingAuthorization(now: t0 + UnauthorizedConnectionRecovery.unauthorizedThreshold - 1) - #expect(await loop.lastUnauthorizedReconnectAt == nil) let due = t0 + UnauthorizedConnectionRecovery.unauthorizedThreshold + for tick in stride(from: t0 + 5, to: due, by: 5) { + await Self.refuse(loop, at: tick) + await loop.superviseServingAuthorization(now: tick) + } + #expect(await loop.lastUnauthorizedReconnectAt == nil) + #expect(await loop.unauthorizedSince == t0) + await Self.refuse(loop, at: due) await loop.superviseServingAuthorization(now: due) #expect(await loop.lastUnauthorizedReconnectAt == due) #expect(await loop.unauthorizedReconnectAttempts == 1) @@ -99,7 +121,8 @@ import Testing trustLevel: "self_signed", status: "online", reason: "Provider authorization updated", authorization: ProviderAuthorizationStatus( appAttestAvailable: true, path: "app_attest", expiresAt: due + 600, - reason: "app_attest_verified", sessionID: "session", machineID: "machine")) + reason: "app_attest_verified", sessionID: "session", machineID: "machine"), + receivedAt: due + 5) await loop.superviseServingAuthorization(now: due + 5) #expect(await loop.unauthorizedSince == nil) #expect(await loop.unauthorizedReconnectAttempts == 0) @@ -109,6 +132,122 @@ import Testing #expect(!disconnected.connected && disconnected.connections == 1) } + /// A legacy (MDM-cohort) Mac on the current coordinator: its only status + /// is the registration refusal, and none follows when legacy verification + /// authorizes the connection. An idle provider must never re-register it, + /// log that the coordinator is not routing it, or tell `status` it is + /// excluded or needs macOS 27. + @Test func aRegistrationRefusalAloneNeverReregisters() async throws { + let stateURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: stateURL) } + let logs = PublicLogLines() + let loop = try await Self.makeLoop(stateURL: stateURL, logs: logs) + + let t0 = Date().timeIntervalSince1970 + await loop.noteCoordinatorConnection(connected: true, now: t0) + await Self.refuse(loop, at: t0 + 1, Self.registrationRefusal) + // Capacity ticks over a day. + let offsets: [Double] = [5, 30, 61, 89, 90, 91, 120] + stride(from: 300, through: 86_400, by: 300).map(Double.init) + for offset in offsets { + await loop.superviseServingAuthorization(now: t0 + offset) + #expect(await loop.unauthorizedSince == nil, "t0+\(offset)") + } + #expect(await loop.lastUnauthorizedReconnectAt == nil) + #expect(await loop.unauthorizedReconnectAttempts == 0) + #expect(!logs.contains(.coordinatorNotRoutingConnection)) + #expect(!logs.contains(.unauthorizedConnectionReregistering)) + + var written = try #require(DaemonStateFile.read(from: stateURL)) + written.appAttest = AppAttestLocalStatus(observedAt: t0, launchSession: .unknown, availabilityReason: .osBelow27) + guard case .pending? = ServingReadiness.verdict(written, now: t0 + 20, macOSMajorVersion: 26) else { + Issue.record("a refusal right after connecting is not pending") + return + } + guard case .unconfirmed(let detail)? = ServingReadiness.verdict(written, now: t0 + 600, macOSMajorVersion: 26) else { + Issue.record("a registration refusal still decides the verdict ten minutes later") + return + } + #expect(detail.contains("the last one, 9m ago") && !detail.contains("macOS 27")) + } + + /// An App Attest lease names its own expiry. Once it passes without a + /// renewal the connection is refused, however old that status is. + @Test func anExpiredLeaseIsJudgedWithoutAFreshStatus() async throws { + let stateURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: stateURL) } + let loop = try await Self.makeLoop(stateURL: stateURL) + + let t0 = Date().timeIntervalSince1970 + await loop.noteCoordinatorConnection(connected: true, now: t0 - 3_600) + await loop.handleTrustStatus( + trustLevel: "self_signed", status: "online", reason: "Provider authorization updated", + authorization: ProviderAuthorizationStatus( + appAttestAvailable: true, path: "app_attest", expiresAt: t0 + 60, + reason: "app_attest_verified", sessionID: "session", machineID: "machine"), + receivedAt: t0) + await loop.superviseServingAuthorization(now: t0 + 30) + #expect(await loop.unauthorizedSince == nil) + let lapsed = t0 + 2 * ServingReadiness.refusalMaxAge + await loop.superviseServingAuthorization(now: lapsed) + #expect(await loop.unauthorizedSince == lapsed) + let due = lapsed + UnauthorizedConnectionRecovery.unauthorizedThreshold + await loop.superviseServingAuthorization(now: due) + #expect(await loop.lastUnauthorizedReconnectAt == due) + } + + /// A request the coordinator routes after its latest status shows that it + /// routes the connection: the clock stops and the backoff resets. A + /// refusal sent after that request counts again. + @Test func aRoutedRequestOutweighsAnEarlierRefusal() async throws { + let stateURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: stateURL) } + let logs = PublicLogLines() + let loop = try await Self.makeLoop(stateURL: stateURL, logs: logs) + + let t0 = Date().timeIntervalSince1970 + await loop.noteCoordinatorConnection(connected: true, now: t0 - 3_600) + await Self.refuse(loop, at: t0) + await loop.superviseServingAuthorization(now: t0) + #expect(await loop.unauthorizedSince == t0) + + await loop.noteCoordinatorRequest(now: t0 + 2) + await loop.superviseServingAuthorization(now: t0 + 3) + #expect(await loop.unauthorizedSince == nil) + #expect(logs.contains(.coordinatorRoutingConnection)) + #expect(ServingReadiness.verdict(await loop.currentDaemonState(), now: t0 + 3) + == .authorized("received a coordinator request 1s ago")) + + await Self.refuse(loop, at: t0 + 5) + await loop.superviseServingAuthorization(now: t0 + 5) + #expect(await loop.unauthorizedSince == t0 + 5) + + // A disconnected provider records no request: the next connection starts clean. + await loop.noteCoordinatorConnection(connected: false, now: t0 + 10) + await loop.noteCoordinatorRequest(now: t0 + 11) + #expect(await loop.coordinatorConnection?.lastRequestAt == nil) + } + + /// When the coordinator stops repeating a refusal, the provider stops + /// counting it, and the log says routing is unconfirmed, not resumed. + @Test func aRefusalTheCoordinatorStopsRepeatingIsLoggedAsUnconfirmed() async throws { + let stateURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: stateURL) } + let logs = PublicLogLines() + let loop = try await Self.makeLoop(stateURL: stateURL, logs: logs) + + let t0 = Date().timeIntervalSince1970 + await loop.noteCoordinatorConnection(connected: true, now: t0 - 3_600) + await Self.refuse(loop, at: t0) + await loop.superviseServingAuthorization(now: t0) + #expect(await loop.unauthorizedSince == t0) + #expect(logs.contains(.coordinatorNotRoutingConnection)) + + await loop.superviseServingAuthorization(now: t0 + ServingReadiness.refusalMaxAge + 1) + #expect(await loop.unauthorizedSince == nil) + #expect(logs.contains(.coordinatorRefusalUnconfirmed)) + #expect(!logs.contains(.coordinatorRoutingConnection)) + } + /// The client reports a disconnect for every failed reconnect attempt, /// up to every 30 s. `status` must still say how long the connection has /// been down, not how long ago the last attempt failed. @@ -151,26 +290,41 @@ import Testing let t0 = Date().timeIntervalSince1970 await loop.noteCoordinatorConnection(connected: true, now: t0 - 3_600) - await loop.handleTrustStatus( - trustLevel: "self_signed", status: "online", reason: "Provider authorization updated", - authorization: Self.keychainRefusal) + await Self.refuse(loop, at: t0) await loop.superviseServingAuthorization(now: t0) #expect(await loop.unauthorizedSince == t0) await loop.setAutopilotCommandForTesting( ModelAutopilotCommand(commandId: "accepted", loadModelId: "acme/model", expiresAtMs: 1)) let due = t0 + UnauthorizedConnectionRecovery.unauthorizedThreshold + await Self.refuse(loop, at: due) await loop.superviseServingAuthorization(now: due) #expect(await loop.lastUnauthorizedReconnectAt == nil) #expect(await loop.unauthorizedReconnectAttempts == 0) await loop.setAutopilotCommandForTesting(nil) + await Self.refuse(loop, at: due + 5) await loop.superviseServingAuthorization(now: due + 5) #expect(await loop.lastUnauthorizedReconnectAt == due + 5) #expect(await loop.unauthorizedReconnectAttempts == 1) } } +/// The public log lines a loop wrote. +private final class PublicLogLines: @unchecked Sendable { + private let lock = NSLock() + private var lines: [String] = [] + + func append(_ level: ProviderLogLevel, _ visibility: ProviderLogVisibility, _ message: String) { + guard visibility == .public else { return } + lock.withLock { lines.append(message) } + } + + func contains(_ message: ProviderOperationalMessage) -> Bool { + lock.withLock { lines.contains(message.text) } + } +} + private extension ProviderLoop { func installAuthorizationStateFileForTesting(_ url: URL) { daemonStateFileOverride = url