From 262bbc654ea40acd61a872c14a67c88ffad1dddc Mon Sep 17 00:00:00 2001 From: flash2do Date: Fri, 6 Nov 2026 00:14:58 -0800 Subject: [PATCH 1/6] Wait for the relay to dial before turning it off in two host tests testRevokeAllTurnsTheRelayOffAndAKeyScopedRevokeLeavesItOn and testTurningTheRelayOnRefusesWhatItCanBeforeTouchID turned the relay off right after setRelay(enabled: true) and then asserted the fake socket was closed. The relay loop dials on a detached task, so on a slow runner (ThreadSanitizer on CI) the cancel can land before the dial: the loop sees the cancellation, ends without ever opening the socket, and there is nothing to close. Under TSan with eight busy CPU hogs locally this failed 11 of 30 and 1 of 30 runs. Both tests now wait for the connected state first, as the other host tests in the class already do. The product behaviour is right as it is: a relay turned off before it dials never dials. --- Tests/KeysreallysafeTests/RelayHostTests.swift | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Tests/KeysreallysafeTests/RelayHostTests.swift b/Tests/KeysreallysafeTests/RelayHostTests.swift index b759e89..a0fb4bf 100644 --- a/Tests/KeysreallysafeTests/RelayHostTests.swift +++ b/Tests/KeysreallysafeTests/RelayHostTests.swift @@ -364,7 +364,7 @@ final class RelayHostTests: XCTestCase { return makeGatedService(db: db) } - func testTurningTheRelayOnRefusesWhatItCanBeforeTouchID() throws { + func testTurningTheRelayOnRefusesWhatItCanBeforeTouchID() async throws { let (service, gate) = try gatedService() let socket = FakeRelaySocket() service.relayHost = RelayHost(log: { _ in }, dialer: FakeRelayDialer([.success(socket)]), blocker: FakeSleepBlocker()) @@ -402,6 +402,9 @@ final class RelayHostTests: XCTestCase { _ = try service.setRelay(enabled: true) XCTAssertEqual(gate.reasons.count, afterSetup + 1, "already on asks for nothing") + // The loop dials on a detached task. Turned off before it got that far, it ends + // without ever opening the socket, so there would be nothing to close. + try await until("connected") { isConnected(service.relayHost.status.state) } let off = try service.setRelay(enabled: false) XCTAssertFalse(off.host.on) XCTAssertTrue(socket.closed) @@ -411,7 +414,7 @@ final class RelayHostTests: XCTestCase { /// The unscoped kill switch closes the relay path too: the route turns this process's /// relay off (socket closed, lock given back) and says so, with no Touch ID; a second call /// finds it off. A key-scoped revoke leaves a running relay alone. - func testRevokeAllTurnsTheRelayOffAndAKeyScopedRevokeLeavesItOn() throws { + func testRevokeAllTurnsTheRelayOffAndAKeyScopedRevokeLeavesItOn() async throws { let (service, gate) = try gatedService() let first = FakeRelaySocket() service.relayHost = RelayHost(log: { _ in }, dialer: FakeRelayDialer([.success(first)]), blocker: FakeSleepBlocker()) @@ -428,6 +431,8 @@ final class RelayHostTests: XCTestCase { XCTAssertTrue(try service.setRelay(enabled: true).host.on) let prompts = gate.reasons.count + // The loop dials on a detached task: revoked before that, it never opens the socket. + try await until("connected") { isConnected(service.relayHost.status.state) } let scoped = try revokeAll(["key": "demo"]) XCTAssertEqual(scoped["relay_stopped"] as? Bool, false) From e7a7fff2492b28a270c024e610e742376ca95680 Mon Sep 17 00:00:00 2001 From: flash2do Date: Fri, 6 Nov 2026 01:35:09 -0800 Subject: [PATCH 2/6] Wait for menu bar recovery instead of giving it 150 ms testRecoveryWaitsForMenuToClose and its neighbours slept 150 ms after a 20 ms recovery delay and then asserted the status item had been replaced. Recovery runs on the main actor, and on a slow CI runner it ran later than that: run 42090154795 logged "menubar item recovered" after the failed asserts, in a test that took 0.89 s. Locally, the old file failed 17 of 30 runs at background QoS with eight CPU hogs (wake and hidden-item tests). The positive checks now poll until the item is replaced (30 s ceiling; a throttled local run stalled the main thread past 5 s). Checks that nothing was replaced keep a short fixed wait, since a late recovery can only make those pass. The burst test only asserts "not yet replaced" for steps where no gap between requests reached the delay, the one case in which recovery may legitimately fire. MenubarItemController is unchanged. --- .../MenubarRecoveryTests.swift | 52 ++++++++++++++----- 1 file changed, 39 insertions(+), 13 deletions(-) diff --git a/Tests/KeysreallysafeTests/MenubarRecoveryTests.swift b/Tests/KeysreallysafeTests/MenubarRecoveryTests.swift index 9215efe..7e2426a 100644 --- a/Tests/KeysreallysafeTests/MenubarRecoveryTests.swift +++ b/Tests/KeysreallysafeTests/MenubarRecoveryTests.swift @@ -5,6 +5,22 @@ import XCTest final class MenubarRecoveryTests: XCTestCase { private let defaults = MemoryDefaults() + /// Recovery runs on the main actor after its delay, and a busy CI runner has run it well + /// past a fixed 150 ms window (the "recovered" log line came after the failed asserts), so + /// a replacement is waited for. The bound is only a ceiling for a broken build: a throttled + /// local run stalled the main thread for over 5 s. Checks that nothing was replaced still + /// use a short fixed wait: a late recovery can only make those pass, never fail. + @MainActor private func replaced(_ controller: MenubarItemController, from item: NSStatusItem, + within timeout: Duration = .seconds(30)) async throws -> Bool { + let clock = ContinuousClock() + let deadline = clock.now.advanced(by: timeout) + while controller.item === item { + if clock.now >= deadline { return false } + try await Task.sleep(for: .milliseconds(10)) + } + return true + } + @MainActor func testWakeReplacesEvenNominallyVisibleItemAndPreservesMenu() async throws { _ = NSApplication.shared let center = NotificationCenter() @@ -19,8 +35,8 @@ final class MenubarRecoveryTests: XCTestCase { original.menu = menu original.isVisible = true center.post(name: NSWorkspace.didWakeNotification, object: nil) - try await Task.sleep(for: .milliseconds(150)) - XCTAssertFalse(controller.item === original) + let didReplace = try await replaced(controller, from: original) + XCTAssertTrue(didReplace) XCTAssertTrue(controller.item.isVisible) XCTAssertTrue(controller.item.menu === menu) XCTAssertEqual(controller.item.button?.title, "C 12% X 34%") @@ -38,10 +54,10 @@ final class MenubarRecoveryTests: XCTestCase { controller.menuIsOpen = true center.post(name: NSApplication.didChangeScreenParametersNotification, object: nil) try await Task.sleep(for: .milliseconds(150)) - XCTAssertTrue(controller.item === original) + XCTAssertTrue(controller.item === original, "no recovery while the menu is open") controller.menuDidClose() - try await Task.sleep(for: .milliseconds(150)) - XCTAssertFalse(controller.item === original) + let didReplace = try await replaced(controller, from: original) + XCTAssertTrue(didReplace, "the deferred recovery runs once the menu closes") } @MainActor func testHiddenItemRecoversButHealthyRefreshDoesNotReplaceItem() async throws { @@ -53,9 +69,9 @@ final class MenubarRecoveryTests: XCTestCase { let original = controller.item original.isVisible = false controller.checkVisibility() - try await Task.sleep(for: .milliseconds(150)) + let didReplace = try await replaced(controller, from: original) + XCTAssertTrue(didReplace) let recovered = controller.item - XCTAssertFalse(recovered === original) XCTAssertTrue(recovered.isVisible) controller.checkVisibility() try await Task.sleep(for: .milliseconds(150)) @@ -65,18 +81,28 @@ final class MenubarRecoveryTests: XCTestCase { @MainActor func testTransitionBurstCoalescesAndStopCancelsRecovery() async throws { _ = NSApplication.shared let center = NotificationCenter() + let delay = Duration.milliseconds(400) let controller = MenubarItemController(workspaceCenter: center, appCenter: center, - recoveryDelay: .milliseconds(400), defaults: defaults) + recoveryDelay: delay, defaults: defaults) let original = controller.item - // The delay is generous next to the 10 ms steps: a busy CI runner can - // oversleep by tens of milliseconds, which fired recovery mid-burst at 80 ms. + // Each request restarts the delay, so the item can only change mid-burst if some gap + // between two requests, or since the last one, reached the delay. A busy CI runner can + // oversleep a 10 ms step by that much; the check is skipped for a step where it did. + let clock = ContinuousClock() + var longestGap = Duration.zero + var lastRequest: ContinuousClock.Instant? for _ in 0..<5 { + let now = clock.now + if let lastRequest { longestGap = max(longestGap, now - lastRequest) } + lastRequest = now controller.requestRecovery(reason: "test transition") try await Task.sleep(for: .milliseconds(10)) - XCTAssertTrue(controller.item === original) + if longestGap < delay, clock.now - now < delay { + XCTAssertTrue(controller.item === original) + } } - try await Task.sleep(for: .milliseconds(700)) - XCTAssertFalse(controller.item === original) + let didReplace = try await replaced(controller, from: original) + XCTAssertTrue(didReplace) let recovered = controller.item try await Task.sleep(for: .milliseconds(700)) XCTAssertTrue(controller.item === recovered) From e4197fa73ddc28eac698f71cfdad1d2a1d602097 Mon Sep 17 00:00:00 2001 From: flash2do Date: Fri, 6 Nov 2026 01:35:09 -0800 Subject: [PATCH 3/6] Park the keepalive in the socket-drop relay test testSocketDropCancelsOpenRequestsAndReconnects failed once on a9f9132 with the backoff list read as [] although the second socket had been dialed. The cause was a test-side data race: the pinger appended a 3600 s keepalive sleep to RecordingSleeper every millisecond while the test read the array without the lock. ThreadSanitizer reports exactly that race when the a9f9132 helper is put back, and f0598da already fixed it by reading under the lock; the test has not failed on CI since. What was left is the busy keepalive itself: thousands of recorded entries and lock round-trips per run, filtered out at the end. RecordingSleeper can now park one sleep length until cancelled, so the keepalive never ticks and the test asserts the exact backoff list, [1]. --- Tests/KeysreallysafeTests/RelayTests.swift | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Tests/KeysreallysafeTests/RelayTests.swift b/Tests/KeysreallysafeTests/RelayTests.swift index 27a55ca..e7f9808 100644 --- a/Tests/KeysreallysafeTests/RelayTests.swift +++ b/Tests/KeysreallysafeTests/RelayTests.swift @@ -98,6 +98,13 @@ final class RecordingSleeper: @unchecked Sendable { private let lock = NSLock() private var recorded: [TimeInterval] = [] private var limit: Int = .max + private var parkedLength: TimeInterval? + /// Sleeps of this length are neither recorded nor ended: they wait until cancelled, so a + /// keepalive timer never fires and `delays` holds only the backoffs. + var parked: TimeInterval? { + get { lock.withLock { parkedLength } } + set { lock.withLock { parkedLength = newValue } } + } /// Read under the lock: the relay loop appends from its own task while the test asserts, /// and ThreadSanitizer flagged the unguarded read. var delays: [TimeInterval] { lock.withLock { recorded } } @@ -107,6 +114,10 @@ final class RecordingSleeper: @unchecked Sendable { } func sleep(_ seconds: TimeInterval) async throws { + if seconds == parked { + try await Task.sleep(nanoseconds: 3_600_000_000_000) + return + } let stop: Bool = lock.withLock { recorded.append(seconds) return recorded.count >= limit @@ -441,6 +452,9 @@ final class RelayTests: XCTestCase { let second = FakeRelaySocket() let dialer = FakeRelayDialer([.success(first), .success(second)]) let sleeper = RecordingSleeper() + // The keepalive (pingInterval 3600) waits for the socket's end instead of ticking + // every millisecond beside the backoff the test checks. + sleeper.parked = 3600 let client = makeClient(port: 1, dialer: dialer, sleeper: sleeper) let run = Task { await client.run() } defer { run.cancel() } @@ -451,7 +465,7 @@ final class RelayTests: XCTestCase { _ = try await second.frame(.error, id: 4) XCTAssertTrue(first.closed) XCTAssertEqual(dialer.attempts.count, 2) - XCTAssertEqual(sleeper.delays.filter { $0 != 3600 }, [1], "one backoff; the rest are the keepalive timer") + XCTAssertEqual(sleeper.delays, [1], "one backoff between the two sockets") XCTAssertEqual(client.inflightCount, 0, "the half-received request died with its socket") } From f337ff0ee52b1cc22e88781d85234c127f3db51c Mon Sep 17 00:00:00 2001 From: flash2do Date: Fri, 6 Nov 2026 01:53:36 -0800 Subject: [PATCH 4/6] Revert "Park the keepalive in the socket-drop relay test" This reverts commit e4197fa73ddc28eac698f71cfdad1d2a1d602097. --- Tests/KeysreallysafeTests/RelayTests.swift | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/Tests/KeysreallysafeTests/RelayTests.swift b/Tests/KeysreallysafeTests/RelayTests.swift index e7f9808..27a55ca 100644 --- a/Tests/KeysreallysafeTests/RelayTests.swift +++ b/Tests/KeysreallysafeTests/RelayTests.swift @@ -98,13 +98,6 @@ final class RecordingSleeper: @unchecked Sendable { private let lock = NSLock() private var recorded: [TimeInterval] = [] private var limit: Int = .max - private var parkedLength: TimeInterval? - /// Sleeps of this length are neither recorded nor ended: they wait until cancelled, so a - /// keepalive timer never fires and `delays` holds only the backoffs. - var parked: TimeInterval? { - get { lock.withLock { parkedLength } } - set { lock.withLock { parkedLength = newValue } } - } /// Read under the lock: the relay loop appends from its own task while the test asserts, /// and ThreadSanitizer flagged the unguarded read. var delays: [TimeInterval] { lock.withLock { recorded } } @@ -114,10 +107,6 @@ final class RecordingSleeper: @unchecked Sendable { } func sleep(_ seconds: TimeInterval) async throws { - if seconds == parked { - try await Task.sleep(nanoseconds: 3_600_000_000_000) - return - } let stop: Bool = lock.withLock { recorded.append(seconds) return recorded.count >= limit @@ -452,9 +441,6 @@ final class RelayTests: XCTestCase { let second = FakeRelaySocket() let dialer = FakeRelayDialer([.success(first), .success(second)]) let sleeper = RecordingSleeper() - // The keepalive (pingInterval 3600) waits for the socket's end instead of ticking - // every millisecond beside the backoff the test checks. - sleeper.parked = 3600 let client = makeClient(port: 1, dialer: dialer, sleeper: sleeper) let run = Task { await client.run() } defer { run.cancel() } @@ -465,7 +451,7 @@ final class RelayTests: XCTestCase { _ = try await second.frame(.error, id: 4) XCTAssertTrue(first.closed) XCTAssertEqual(dialer.attempts.count, 2) - XCTAssertEqual(sleeper.delays, [1], "one backoff between the two sockets") + XCTAssertEqual(sleeper.delays.filter { $0 != 3600 }, [1], "one backoff; the rest are the keepalive timer") XCTAssertEqual(client.inflightCount, 0, "the half-received request died with its socket") } From fc09ecea239ee80d7847247531e0a5fa85adb0f3 Mon Sep 17 00:00:00 2001 From: flash2do Date: Fri, 6 Nov 2026 01:53:36 -0800 Subject: [PATCH 5/6] Revert "Wait for the relay to dial before turning it off in two host tests" This reverts commit 262bbc654ea40acd61a872c14a67c88ffad1dddc. --- Tests/KeysreallysafeTests/RelayHostTests.swift | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/Tests/KeysreallysafeTests/RelayHostTests.swift b/Tests/KeysreallysafeTests/RelayHostTests.swift index a0fb4bf..b759e89 100644 --- a/Tests/KeysreallysafeTests/RelayHostTests.swift +++ b/Tests/KeysreallysafeTests/RelayHostTests.swift @@ -364,7 +364,7 @@ final class RelayHostTests: XCTestCase { return makeGatedService(db: db) } - func testTurningTheRelayOnRefusesWhatItCanBeforeTouchID() async throws { + func testTurningTheRelayOnRefusesWhatItCanBeforeTouchID() throws { let (service, gate) = try gatedService() let socket = FakeRelaySocket() service.relayHost = RelayHost(log: { _ in }, dialer: FakeRelayDialer([.success(socket)]), blocker: FakeSleepBlocker()) @@ -402,9 +402,6 @@ final class RelayHostTests: XCTestCase { _ = try service.setRelay(enabled: true) XCTAssertEqual(gate.reasons.count, afterSetup + 1, "already on asks for nothing") - // The loop dials on a detached task. Turned off before it got that far, it ends - // without ever opening the socket, so there would be nothing to close. - try await until("connected") { isConnected(service.relayHost.status.state) } let off = try service.setRelay(enabled: false) XCTAssertFalse(off.host.on) XCTAssertTrue(socket.closed) @@ -414,7 +411,7 @@ final class RelayHostTests: XCTestCase { /// The unscoped kill switch closes the relay path too: the route turns this process's /// relay off (socket closed, lock given back) and says so, with no Touch ID; a second call /// finds it off. A key-scoped revoke leaves a running relay alone. - func testRevokeAllTurnsTheRelayOffAndAKeyScopedRevokeLeavesItOn() async throws { + func testRevokeAllTurnsTheRelayOffAndAKeyScopedRevokeLeavesItOn() throws { let (service, gate) = try gatedService() let first = FakeRelaySocket() service.relayHost = RelayHost(log: { _ in }, dialer: FakeRelayDialer([.success(first)]), blocker: FakeSleepBlocker()) @@ -431,8 +428,6 @@ final class RelayHostTests: XCTestCase { XCTAssertTrue(try service.setRelay(enabled: true).host.on) let prompts = gate.reasons.count - // The loop dials on a detached task: revoked before that, it never opens the socket. - try await until("connected") { isConnected(service.relayHost.status.state) } let scoped = try revokeAll(["key": "demo"]) XCTAssertEqual(scoped["relay_stopped"] as? Bool, false) From 897e205ab7e0960a7fe1003f35d30c395126fc10 Mon Sep 17 00:00:00 2001 From: flash2do Date: Fri, 6 Nov 2026 01:56:07 -0800 Subject: [PATCH 6/6] Let the burst test accept a second recovery after a mid-burst one When a slow runner lets a gap in the burst reach the recovery delay, a recovery fires mid-burst and the remaining requests correctly schedule one more. The test took the first replacement as final and then failed its coalescing check when the second one swapped the item. It now waits for the item to hold still for longer than the delay in that case only; a burst with no long gap keeps the strict check. The test also stops its controller on any early exit, like its neighbours. --- .../MenubarRecoveryTests.swift | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/Tests/KeysreallysafeTests/MenubarRecoveryTests.swift b/Tests/KeysreallysafeTests/MenubarRecoveryTests.swift index 7e2426a..bc9fa32 100644 --- a/Tests/KeysreallysafeTests/MenubarRecoveryTests.swift +++ b/Tests/KeysreallysafeTests/MenubarRecoveryTests.swift @@ -84,6 +84,8 @@ final class MenubarRecoveryTests: XCTestCase { let delay = Duration.milliseconds(400) let controller = MenubarItemController(workspaceCenter: center, appCenter: center, recoveryDelay: delay, defaults: defaults) + var stopped = false + defer { if !stopped { controller.stop() } } let original = controller.item // Each request restarts the delay, so the item can only change mid-burst if some gap // between two requests, or since the last one, reached the delay. A busy CI runner can @@ -91,6 +93,7 @@ final class MenubarRecoveryTests: XCTestCase { let clock = ContinuousClock() var longestGap = Duration.zero var lastRequest: ContinuousClock.Instant? + var recoveredMidBurst = false for _ in 0..<5 { let now = clock.now if let lastRequest { longestGap = max(longestGap, now - lastRequest) } @@ -99,15 +102,29 @@ final class MenubarRecoveryTests: XCTestCase { try await Task.sleep(for: .milliseconds(10)) if longestGap < delay, clock.now - now < delay { XCTAssertTrue(controller.item === original) + } else { + recoveredMidBurst = true } } let didReplace = try await replaced(controller, from: original) XCTAssertTrue(didReplace) - let recovered = controller.item + var recovered = controller.item + if recoveredMidBurst { + // A recovery that fired mid-burst leaves the later requests to schedule one more, + // which is correct; the coalescing check below is about the burst's last request, + // so wait for the item to hold still for longer than the delay first. + let deadline = clock.now.advanced(by: .seconds(30)) + while clock.now < deadline { + try await Task.sleep(for: delay + .milliseconds(300)) + if controller.item === recovered { break } + recovered = controller.item + } + } try await Task.sleep(for: .milliseconds(700)) XCTAssertTrue(controller.item === recovered) controller.requestRecovery(reason: "pending at shutdown") controller.stop() + stopped = true center.post(name: NSWorkspace.sessionDidBecomeActiveNotification, object: nil) try await Task.sleep(for: .milliseconds(700)) XCTAssertTrue(controller.item === recovered)