From 89f6c040b6d7414cb5d3cdb5c0e91577dcc3a88d Mon Sep 17 00:00:00 2001 From: Eric Dahl Date: Thu, 3 Dec 2026 01:36:10 -0500 Subject: [PATCH 01/10] DIAGNOSTICS, do not merge: file descriptors while the fake Mixers serve (ShowRecorder #1215, #1248) Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VCgWWseQZtUzcSRzjqqQJQ --- .github/workflows/ci.yml | 1 + Tests/MixerLinkTests/DiagnosticsTests.swift | 150 ++++++++++++++++++ .../Support/FakeXAirMixer.swift | 4 + 3 files changed, 155 insertions(+) create mode 100644 Tests/MixerLinkTests/DiagnosticsTests.swift diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d83a2d..f63fe47 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,7 @@ jobs: run: | xcodebuild -version swift --version + echo "ulimit -n: $(ulimit -n) hard: $(ulimit -Hn)"; sysctl hw.ncpu kern.maxfilesperproc; launchctl limit maxfiles || true # Until the shared modules move in (#3) the repo holds no package, and there is nothing to test. - name: Package tests diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift new file mode 100644 index 0000000..c9f0e33 --- /dev/null +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -0,0 +1,150 @@ +import Darwin +import Foundation +import MixerLink +import Testing + +// DIAGNOSTICS ONLY (ShowRecorder #1215, #1248, #1249): never merge. Measures file descriptors while the fakes serve. + +enum Diag { + static func limit() -> UInt64 { + var r = rlimit() + getrlimit(RLIMIT_NOFILE, &r) + return r.rlim_cur + } + + /// (open descriptors, of which sockets) + static func fds() -> (Int, Int) { + var open = 0, sockets = 0 + for fd in 0.. peak + 10 || Int(Date().timeIntervalSince(start)) % 5 == 0 { + peak = max(peak, open) + Diag.log("sample t=\(String(format: "%.1f", Date().timeIntervalSince(start))) open=\(open) sockets=\(sockets)") + } + Thread.sleep(forTimeInterval: 0.5) + } + } + thread.start() + } + + @Test("WING knocks: descriptors per knock") + func wingKnocks() async throws { + let before = Diag.fds() + do { + let wing = try await FakeWing() + let driver = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .seconds(20)) + var answered = 0 + for _ in 0..<50 { if (try? await driver.identify()) != nil { answered += 1 } } + Diag.log("wingKnocks answered=\(answered)/50 before=\(before) after=\(Diag.fds())") + } + try await Task.sleep(for: .seconds(2)) + Diag.log("wingKnocks 2 s after the fake and the driver went away: \(Diag.fds())") + } + + @Test("X-Air drivers: descriptors per driver") + func xAirDrivers() async throws { + let before = Diag.fds() + do { + let mixer = try await FakeXAirMixer() + var answered = 0 + for _ in 0..<50 { + let driver = XAirDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: mixer.port), timeout: .seconds(20)) + if (try? await driver.identify()) != nil { answered += 1 } + } + Diag.log("xAirDrivers answered=\(answered)/50 before=\(before) after=\(Diag.fds())") + } + try await Task.sleep(for: .seconds(2)) + Diag.log("xAirDrivers 2 s after the fake and the drivers went away: \(Diag.fds())") + } + + @Test("Power off, then on at once") + func powerCycleAtOnce() async throws { + let mixer = try await FakeXAirMixer() + let driver = XAirDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: mixer.port), timeout: .seconds(20)) + _ = try await driver.identify() + for cycle in 1...20 { + mixer.powerOff() + let start = ContinuousClock.now + let on = await withTaskGroup(of: Bool.self) { group in + group.addTask { (try? await mixer.powerOn()) != nil } + group.addTask { try? await Task.sleep(for: .seconds(15)); return false } + let first = await group.next() ?? false + group.cancelAll() + return first + } + Diag.log("powerCycleAtOnce cycle=\(cycle) on=\(on) after=\(ContinuousClock.now - start)") + if !on { break } + let again = XAirDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: mixer.port), timeout: .seconds(20)) + Diag.log("powerCycleAtOnce cycle=\(cycle) identify=\((try? await again.identify()) != nil)") + } + } +} + +@MainActor +@Suite("Diagnostics, Link") +struct DiagnosticsLinkTests { + @Test("The power-cycle test's steps after a connect that failed") + func powerCycleAfterFailedConnect() async throws { + var state = FakeXAirMixer.State() + state.channels[0] = .init(name: "Kick", color: 1) + state.usbRouting = XAirDriverTests.defaultRouting + state.answers = false + let mixer = try await FakeXAirMixer(state) + let link = MixerLinkController(timeout: .milliseconds(500), renewEvery: .milliseconds(100)) + await link.connect(to: "127.0.0.1:\(mixer.port)", usbChannelCount: 18) + Diag.log("afterFailedConnect status=\(link.status) fds=\(Diag.fds())") + try await Task.sleep(for: .seconds(3)) + Diag.log("afterFailedConnect 3 s of keepTrying: fds=\(Diag.fds())") + mixer.update { $0.answers = true } + + mixer.powerOff() + _ = await eventually(30) { if case .down = link.status { true } else { false } } + mixer.update { $0.channels[0].name = "Bass Drum" } + let start = ContinuousClock.now + let on = await withTaskGroup(of: Bool.self) { group in + group.addTask { (try? await mixer.powerOn()) != nil } + group.addTask { try? await Task.sleep(for: .seconds(15)); return false } + let first = await group.next() ?? false + group.cancelAll() + return first + } + Diag.log("afterFailedConnect powerOn=\(on) after=\(ContinuousClock.now - start)") + let back = await eventually(20) { link.sources[safe: 0]?.name == "Bass Drum" } + Diag.log("afterFailedConnect back=\(back) status=\(link.status) fds=\(Diag.fds())") + } + + @Test("A WING Link renewing every 100 ms: descriptors over 5 s") + func wingLinkRenewals() async throws { + let wing = try await FakeWing(WingLiveUpdatesTests.twoChannelWing()) + let oscPort = wing.oscPort + let link = MixerLinkController(timeout: .seconds(10), renewEvery: .milliseconds(100)) { endpoint, timeout in + WingDriver(endpoint: endpoint, oscPort: oscPort, timeout: timeout, rereadEvery: .zero) + } + let before = Diag.fds() + await link.connect(to: "127.0.0.1:\(wing.port)", usbChannelCount: 2) + try await Task.sleep(for: .seconds(5)) + Diag.log("wingLinkRenewals status=\(link.status) knocks=\(wing.queries.filter { $0 == "WING?" }.count) before=\(before) after=\(Diag.fds())") + } +} diff --git a/Tests/MixerLinkTests/Support/FakeXAirMixer.swift b/Tests/MixerLinkTests/Support/FakeXAirMixer.swift index 4291d79..db082ac 100644 --- a/Tests/MixerLinkTests/Support/FakeXAirMixer.swift +++ b/Tests/MixerLinkTests/Support/FakeXAirMixer.swift @@ -125,6 +125,10 @@ final class FakeXAirMixer: Sendable { let ready = AsyncStream.makeStream() listener.stateUpdateHandler = { [listener] update in if case .ready = update, let port = listener.port?.rawValue { ready.continuation.yield(port) } + switch update { + case .failed(let error), .waiting(let error): fputs("[diag] X-Air listener on \(port): \(update) \(error)\n", stderr) + default: break + } } listener.newConnectionHandler = { connection in connection.start(queue: .global()) From 0e76da5c45513449cc2ea68ebf940993ff717f26 Mon Sep 17 00:00:00 2001 From: Eric Dahl Date: Thu, 3 Dec 2026 01:47:29 -0500 Subject: [PATCH 02/10] DIAGNOSTICS, do not merge: synthetic load, copies of the flaky tests, traces of unanswered requests Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VCgWWseQZtUzcSRzjqqQJQ --- Sources/MixerLink/OSCUDPClient.swift | 12 ++ Sources/MixerLink/WingDriver.swift | 18 +- Tests/MixerLinkTests/DiagnosticsTests.swift | 182 +++++++++++--------- Tests/MixerLinkTests/Support/FakeWing.swift | 1 + 4 files changed, 127 insertions(+), 86 deletions(-) diff --git a/Sources/MixerLink/OSCUDPClient.swift b/Sources/MixerLink/OSCUDPClient.swift index ea1cb79..3398256 100644 --- a/Sources/MixerLink/OSCUDPClient.swift +++ b/Sources/MixerLink/OSCUDPClient.swift @@ -2,6 +2,7 @@ import Foundation import Network import OSC +import Synchronization /// Sends OSC queries over UDP and matches replies to them by address. actor OSCUDPClient { @@ -68,6 +69,7 @@ actor OSCUDPClient { pending.append(Pending(id: id, address: replyAddress ?? message.address, continuation: continuation)) let connection = connection connection.send(content: Data(message.encoded()), completion: .contentProcessed { [weak self] error in + self?.diagNote("sent \(message.address) error=\(String(describing: error))") guard let error, let self else { return } // With the path, a send refused for Local Network access says so, not "join the Wi-Fi". let problem = MixerLinkProblem(error, path: connection.currentPath, host: self.endpoint.host, port: self.endpoint.port) @@ -97,6 +99,7 @@ actor OSCUDPClient { let connection = connection, generation = generation connection.stateUpdateHandler = { [weak self] state in guard let self else { return } + self.diagNote("state \(state) gen=\(generation)") switch state { case .waiting(let error): // Waiting recovers by itself (the network comes back); fail requests meanwhile. @@ -117,6 +120,7 @@ actor OSCUDPClient { private nonisolated func receive(on connection: NWConnection, generation: Int) { connection.receiveMessage { [weak self] data, _, _, error in guard let self else { return } + self.diagNote("receive data=\(data?.count ?? -1) error=\(String(describing: error))") if let data, let packet = try? OSCPacket(decoding: Array(data)) { self.received.yield(packet.messages) } @@ -139,7 +143,14 @@ actor OSCUDPClient { problem = nil } + private nonisolated let diagTrace = Mutex<[String]>([]) + private nonisolated let diagStart = ContinuousClock.now + private nonisolated func diagNote(_ text: String) { + diagTrace.withLock { if $0.count < 40 { $0.append("\(ContinuousClock.now - diagStart) \(text)") } } + } + private func deliver(_ messages: [OSCMessage]) { + diagNote("deliver \(messages.map(\.address))") for message in messages { // An XR18 echoes each set back with no arguments: that's never the reply to a query. guard !message.arguments.isEmpty, let index = pending.firstIndex(where: { $0.address == message.address }) else { @@ -152,6 +163,7 @@ actor OSCUDPClient { private func fail(_ id: UUID, with problem: MixerLinkProblem) { guard let index = pending.firstIndex(where: { $0.id == id }) else { return } + fputs("[diag] osc fail port=\(endpoint.port) address=\(pending[index].address) problem=\(problem) state=\(connection.state) generation=\(generation) needsRebuild=\(needsRebuild) pending=\(pending.count) trace=\(diagTrace.withLock { $0 })\n", stderr) pending.remove(at: index).continuation.resume(throwing: problem) } diff --git a/Sources/MixerLink/WingDriver.swift b/Sources/MixerLink/WingDriver.swift index 5bc9eb6..5b1af8b 100644 --- a/Sources/MixerLink/WingDriver.swift +++ b/Sources/MixerLink/WingDriver.swift @@ -177,20 +177,34 @@ enum TextRequest { let finish: @Sendable ([UInt8]?) -> Void = { reply in waiting.withLock { $0.take() }?.resume(returning: reply) } + let trace = Mutex<[String]>([]) + let t0 = ContinuousClock.now + let note: @Sendable (String) -> Void = { text in trace.withLock { $0.append("\(ContinuousClock.now - t0) \(text)") } } + connection.stateUpdateHandler = { note("state \($0)") } let reply = await withTaskCancellationHandler { await withCheckedContinuation { (continuation: CheckedContinuation<[UInt8]?, Never>) in waiting.withLock { $0 = continuation } - connection.receiveMessage { data, _, _, _ in finish(data.map { Array($0) }) } + connection.receiveMessage { data, _, _, error in + note("receive data=\(data?.count ?? -1) error=\(String(describing: error))") + finish(data.map { Array($0) }) + } connection.start(queue: .global(qos: .userInitiated)) - connection.send(content: Data(request), completion: .contentProcessed { _ in }) + connection.send(content: Data(request), completion: .contentProcessed { note("sent error=\(String(describing: $0))") }) + note("started") Task { + note("timeout task began") try? await Task.sleep(for: timeout) + note("timeout") finish(nil) } } } onCancel: { + note("cancel") finish(nil) } + if reply == nil { + fputs("[diag] ask port=\(endpoint.port) timeout=\(timeout) nil after \(ContinuousClock.now - t0): \(trace.withLock { $0 })\n", stderr) + } guard let reply else { throw .noReply(host: endpoint.host) } return reply } diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift index c9f0e33..bac2b0b 100644 --- a/Tests/MixerLinkTests/DiagnosticsTests.swift +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -3,7 +3,8 @@ import Foundation import MixerLink import Testing -// DIAGNOSTICS ONLY (ShowRecorder #1215, #1248, #1249): never merge. Measures file descriptors while the fakes serve. +// DIAGNOSTICS ONLY (ShowRecorder #1215, #1248, #1249): never merge. A synthetic load like ShowRecorder's old test run +// (a main actor busy for about 30 s, a full thread pool), with many copies of the flaky tests and a dump when one fails. enum Diag { static func limit() -> UInt64 { @@ -27,124 +28,137 @@ enum Diag { static func log(_ text: String) { fputs("[diag] \(text)\n", stderr) } + + static let start = Date() + static var t: String { String(format: "t=%.1f", Date().timeIntervalSince(start)) } + + static func summary(_ queries: [String]) -> String { + var counts: [String: Int] = [:] + for query in queries { counts[query, default: 0] += 1 } + return counts.sorted { $0.key < $1.key }.map { "\($0.key)x\($0.value)" }.joined(separator: " ") + } +} + +@MainActor +@Suite("Load: main actor") +struct MainActorLoadTests { + @Test("Blocks the main actor for 10 ms", arguments: 0..<3000) + func block(_ index: Int) { + Thread.sleep(forTimeInterval: 0.01) + } +} + +@Suite("Load: pool") +struct PoolLoadTests { + @Test("Burns a pool thread for 400 ms", arguments: 0..<240) + func burn(_ index: Int) { + let end = Date().addingTimeInterval(0.4) + var x = 0.0 + while Date() < end { x += sin(x + 1) } + } } @Suite("Diagnostics") struct DiagnosticsTests { @Test("fd sampler") func sampler() async throws { - Diag.log("limit=\(Diag.limit()) ncpu=\(ProcessInfo.processInfo.activeProcessorCount)") + Diag.log("limit=\(Diag.limit()) ncpu=\(ProcessInfo.processInfo.activeProcessorCount) \(Diag.t)") let thread = Thread { - let start = Date() - var peak = 0 while true { let (open, sockets) = Diag.fds() - if open > peak + 10 || Int(Date().timeIntervalSince(start)) % 5 == 0 { - peak = max(peak, open) - Diag.log("sample t=\(String(format: "%.1f", Date().timeIntervalSince(start))) open=\(open) sockets=\(sockets)") - } - Thread.sleep(forTimeInterval: 0.5) + Diag.log("sample \(Diag.t) open=\(open) sockets=\(sockets)") + Thread.sleep(forTimeInterval: 5) } } thread.start() } +} - @Test("WING knocks: descriptors per knock") - func wingKnocks() async throws { - let before = Diag.fds() - do { - let wing = try await FakeWing() - let driver = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .seconds(20)) - var answered = 0 - for _ in 0..<50 { if (try? await driver.identify()) != nil { answered += 1 } } - Diag.log("wingKnocks answered=\(answered)/50 before=\(before) after=\(Diag.fds())") +@MainActor +@Suite("Diagnostics: copies of the flaky tests") +struct FlakyCopiesTests { + @Test("WING rename through the Link (#1248)", arguments: 0..<25) + func renameReachesTheLink(_ copy: Int) async throws { + let wing = try await FakeWing(WingLiveUpdatesTests.twoChannelWing()) + let oscPort = wing.oscPort + let link = MixerLinkController(timeout: Loopback.replyTimeout, renewEvery: .milliseconds(100)) { endpoint, timeout in + WingDriver(endpoint: endpoint, oscPort: oscPort, timeout: timeout, rereadEvery: .zero) } - try await Task.sleep(for: .seconds(2)) - Diag.log("wingKnocks 2 s after the fake and the driver went away: \(Diag.fds())") - } - - @Test("X-Air drivers: descriptors per driver") - func xAirDrivers() async throws { - let before = Diag.fds() - do { - let mixer = try await FakeXAirMixer() - var answered = 0 - for _ in 0..<50 { - let driver = XAirDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: mixer.port), timeout: .seconds(20)) - if (try? await driver.identify()) != nil { answered += 1 } - } - Diag.log("xAirDrivers answered=\(answered)/50 before=\(before) after=\(Diag.fds())") + let began = Diag.t + await link.connect(to: "127.0.0.1:\(wing.port)", usbChannelCount: 2) + let connected = link.sources.first?.name == "Kick" + if !connected { + Diag.log("rename[\(copy)] CONNECT FAILED began \(began) now \(Diag.t) ports=\(wing.port)/\(wing.oscPort) status=\(link.status) queries=\(Diag.summary(wing.queries))") } - try await Task.sleep(for: .seconds(2)) - Diag.log("xAirDrivers 2 s after the fake and the drivers went away: \(Diag.fds())") + wing.rename(source: "LCL/1", to: "Kick In") + let renamed = await eventually(30) { link.sources.first?.name == "Kick In" } + if !renamed { + Diag.log("rename[\(copy)] NEVER RENAMED \(Diag.t) ports=\(wing.port)/\(wing.oscPort) status=\(link.status) sources=\(link.sources.map(\.name)) queries=\(Diag.summary(wing.queries)) fds=\(Diag.fds())") + let probe = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: oscPort, timeout: .seconds(5)) + let identity = try? await probe.identify() + let sources = try? await probe.sources(usbChannelCount: 2) + Diag.log("rename[\(copy)] fresh probe: identity=\(String(describing: identity)) sources=\(String(describing: sources?.map(\.name))) queries=\(Diag.summary(wing.queries))") + } else if !connected { + Diag.log("rename[\(copy)] came up later \(Diag.t)") + } + #expect(connected && renamed) } - @Test("Power off, then on at once") - func powerCycleAtOnce() async throws { - let mixer = try await FakeXAirMixer() - let driver = XAirDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: mixer.port), timeout: .seconds(20)) - _ = try await driver.identify() - for cycle in 1...20 { - mixer.powerOff() - let start = ContinuousClock.now - let on = await withTaskGroup(of: Bool.self) { group in - group.addTask { (try? await mixer.powerOn()) != nil } - group.addTask { try? await Task.sleep(for: .seconds(15)); return false } - let first = await group.next() ?? false - group.cancelAll() - return first - } - Diag.log("powerCycleAtOnce cycle=\(cycle) on=\(on) after=\(ContinuousClock.now - start)") - if !on { break } - let again = XAirDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: mixer.port), timeout: .seconds(20)) - Diag.log("powerCycleAtOnce cycle=\(cycle) identify=\((try? await again.identify()) != nil)") + @Test("WING that answers no OSC: the Link comes up", arguments: 0..<25) + func linkUpWithGenericNames(_ copy: Int) async throws { + let wing = try await FakeWing(.init(answersOSC: false, unansweredKnocks: 3)) + let oscPort = wing.oscPort + let link = MixerLinkController(timeout: .milliseconds(300), renewEvery: .milliseconds(100)) { endpoint, timeout in + WingDriver(endpoint: endpoint, oscPort: oscPort, timeout: timeout) + } + let began = Diag.t + await link.connect(to: "127.0.0.1:\(wing.port)", usbChannelCount: 48) + let up = await eventually(30) { link.identity != nil && link.sources.count == 48 } + if !up { + Diag.log("noOSC[\(copy)] NEVER UP began \(began) now \(Diag.t) ports=\(wing.port)/\(wing.oscPort) status=\(link.status) queries=\(Diag.summary(wing.queries)) fds=\(Diag.fds())") + let probe = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: oscPort, timeout: .seconds(5)) + let identity = try? await probe.identify() + Diag.log("noOSC[\(copy)] fresh probe: identity=\(String(describing: identity)) queries=\(Diag.summary(wing.queries))") + try? await Task.sleep(for: .seconds(3)) + Diag.log("noOSC[\(copy)] 3 s later: status=\(link.status) queries=\(Diag.summary(wing.queries))") } + #expect(up) } -} -@MainActor -@Suite("Diagnostics, Link") -struct DiagnosticsLinkTests { - @Test("The power-cycle test's steps after a connect that failed") - func powerCycleAfterFailedConnect() async throws { + @Test("X-Air power cycle (#1215)", arguments: 0..<25) + func powerCycle(_ copy: Int) async throws { var state = FakeXAirMixer.State() state.channels[0] = .init(name: "Kick", color: 1) state.usbRouting = XAirDriverTests.defaultRouting - state.answers = false let mixer = try await FakeXAirMixer(state) - let link = MixerLinkController(timeout: .milliseconds(500), renewEvery: .milliseconds(100)) + let link = MixerLinkController(timeout: Loopback.mixedTimeout, renewEvery: .milliseconds(100)) + let began = Diag.t await link.connect(to: "127.0.0.1:\(mixer.port)", usbChannelCount: 18) - Diag.log("afterFailedConnect status=\(link.status) fds=\(Diag.fds())") - try await Task.sleep(for: .seconds(3)) - Diag.log("afterFailedConnect 3 s of keepTrying: fds=\(Diag.fds())") - mixer.update { $0.answers = true } + let connected = link.sources[safe: 0]?.name == "Kick" + if !connected { + Diag.log("power[\(copy)] CONNECT FAILED began \(began) now \(Diag.t) port=\(mixer.port) status=\(link.status) queries=\(mixer.queries.count) last=\(mixer.queries.suffix(3))") + } mixer.powerOff() - _ = await eventually(30) { if case .down = link.status { true } else { false } } + let down = await eventually(30) { if case .down = link.status { true } else { false } } mixer.update { $0.channels[0].name = "Bass Drum" } - let start = ContinuousClock.now + let onStart = ContinuousClock.now let on = await withTaskGroup(of: Bool.self) { group in group.addTask { (try? await mixer.powerOn()) != nil } - group.addTask { try? await Task.sleep(for: .seconds(15)); return false } + group.addTask { try? await Task.sleep(for: .seconds(30)); return false } let first = await group.next() ?? false group.cancelAll() return first } - Diag.log("afterFailedConnect powerOn=\(on) after=\(ContinuousClock.now - start)") - let back = await eventually(20) { link.sources[safe: 0]?.name == "Bass Drum" } - Diag.log("afterFailedConnect back=\(back) status=\(link.status) fds=\(Diag.fds())") - } - - @Test("A WING Link renewing every 100 ms: descriptors over 5 s") - func wingLinkRenewals() async throws { - let wing = try await FakeWing(WingLiveUpdatesTests.twoChannelWing()) - let oscPort = wing.oscPort - let link = MixerLinkController(timeout: .seconds(10), renewEvery: .milliseconds(100)) { endpoint, timeout in - WingDriver(endpoint: endpoint, oscPort: oscPort, timeout: timeout, rereadEvery: .zero) + if !on || !connected || !down { + Diag.log("power[\(copy)] \(Diag.t) connected=\(connected) down=\(down) powerOn=\(on) after \(ContinuousClock.now - onStart) status=\(link.status)") } - let before = Diag.fds() - await link.connect(to: "127.0.0.1:\(wing.port)", usbChannelCount: 2) - try await Task.sleep(for: .seconds(5)) - Diag.log("wingLinkRenewals status=\(link.status) knocks=\(wing.queries.filter { $0 == "WING?" }.count) before=\(before) after=\(Diag.fds())") + let back = await eventually(30) { link.sources[safe: 0]?.name == "Bass Drum" } + mixer.rename(channel: 2, to: "Snare") + let pushed = await eventually(30) { link.sources[safe: 1]?.name == "Snare" } + if !back || !pushed { + Diag.log("power[\(copy)] \(Diag.t) back=\(back) pushed=\(pushed) status=\(link.status) sources=\(link.sources.prefix(2).map(\.name)) queries=\(mixer.queries.count) last=\(mixer.queries.suffix(4)) fds=\(Diag.fds())") + } + #expect(connected && down && on && back && pushed) } } diff --git a/Tests/MixerLinkTests/Support/FakeWing.swift b/Tests/MixerLinkTests/Support/FakeWing.swift index ceef034..e7f16e6 100644 --- a/Tests/MixerLinkTests/Support/FakeWing.swift +++ b/Tests/MixerLinkTests/Support/FakeWing.swift @@ -127,6 +127,7 @@ final class FakeWing: Sendable { case .failed: ready.continuation.finish() default: break } + if case .ready = update {} else { fputs("[diag] WING listener \(String(describing: listener.port)): \(update)\n", stderr) } } listener.newConnectionHandler = { connection in connection.start(queue: .global()) From 2ca9302166dc7375477f65de01239a4e7f75bf6b Mon Sep 17 00:00:00 2001 From: Eric Dahl Date: Thu, 3 Dec 2026 01:56:09 -0500 Subject: [PATCH 03/10] DIAGNOSTICS, do not merge: port census Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VCgWWseQZtUzcSRzjqqQJQ --- Tests/MixerLinkTests/DiagnosticsTests.swift | 199 ++++++-------------- 1 file changed, 57 insertions(+), 142 deletions(-) diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift index bac2b0b..a4b53fa 100644 --- a/Tests/MixerLinkTests/DiagnosticsTests.swift +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -1,164 +1,79 @@ import Darwin import Foundation import MixerLink +import Network +import Synchronization import Testing -// DIAGNOSTICS ONLY (ShowRecorder #1215, #1248, #1249): never merge. A synthetic load like ShowRecorder's old test run -// (a main actor busy for about 30 s, a full thread pool), with many copies of the flaky tests and a dump when one fails. +// DIAGNOSTICS ONLY (ShowRecorder #1215, #1248, #1249): never merge. Does a loopback UDP listener share its port with a +// client connection's local port, and does it then stop hearing new clients? enum Diag { - static func limit() -> UInt64 { - var r = rlimit() - getrlimit(RLIMIT_NOFILE, &r) - return r.rlim_cur - } - - /// (open descriptors, of which sockets) - static func fds() -> (Int, Int) { - var open = 0, sockets = 0 - for fd in 0.. String { - var counts: [String: Int] = [:] - for query in queries { counts[query, default: 0] += 1 } - return counts.sorted { $0.key < $1.key }.map { "\($0.key)x\($0.value)" }.joined(separator: " ") - } -} - -@MainActor -@Suite("Load: main actor") -struct MainActorLoadTests { - @Test("Blocks the main actor for 10 ms", arguments: 0..<3000) - func block(_ index: Int) { - Thread.sleep(forTimeInterval: 0.01) + static func localPort(_ connection: NWConnection) -> UInt16? { + if case .hostPort(_, let port)? = connection.currentPath?.localEndpoint { return port.rawValue } + return nil } } -@Suite("Load: pool") -struct PoolLoadTests { - @Test("Burns a pool thread for 400 ms", arguments: 0..<240) - func burn(_ index: Int) { - let end = Date().addingTimeInterval(0.4) - var x = 0.0 - while Date() < end { x += sin(x + 1) } - } -} - -@Suite("Diagnostics") -struct DiagnosticsTests { - @Test("fd sampler") - func sampler() async throws { - Diag.log("limit=\(Diag.limit()) ncpu=\(ProcessInfo.processInfo.activeProcessorCount) \(Diag.t)") - let thread = Thread { - while true { - let (open, sockets) = Diag.fds() - Diag.log("sample \(Diag.t) open=\(open) sockets=\(sockets)") - Thread.sleep(forTimeInterval: 5) - } +@Suite("Diagnostics: port census") +struct PortCensusTests { + @Test("Listener ports against client local ports") + func census() async throws { + var wings: [FakeWing] = [] + for _ in 0..<150 { wings.append(try await FakeWing(WingLiveUpdatesTests.twoChannelWing())) } + var listenerPorts: [UInt16: Int] = [:] // port -> index of its WING + for (index, wing) in wings.enumerated() { + listenerPorts[wing.port] = index + listenerPorts[wing.oscPort] = index } - thread.start() - } -} + Diag.log("census: \(wings.count) WINGs, \(listenerPorts.count) distinct listener ports, range \(listenerPorts.keys.min() ?? 0)...\(listenerPorts.keys.max() ?? 0)") -@MainActor -@Suite("Diagnostics: copies of the flaky tests") -struct FlakyCopiesTests { - @Test("WING rename through the Link (#1248)", arguments: 0..<25) - func renameReachesTheLink(_ copy: Int) async throws { - let wing = try await FakeWing(WingLiveUpdatesTests.twoChannelWing()) - let oscPort = wing.oscPort - let link = MixerLinkController(timeout: Loopback.replyTimeout, renewEvery: .milliseconds(100)) { endpoint, timeout in - WingDriver(endpoint: endpoint, oscPort: oscPort, timeout: timeout, rereadEvery: .zero) - } - let began = Diag.t - await link.connect(to: "127.0.0.1:\(wing.port)", usbChannelCount: 2) - let connected = link.sources.first?.name == "Kick" - if !connected { - Diag.log("rename[\(copy)] CONNECT FAILED began \(began) now \(Diag.t) ports=\(wing.port)/\(wing.oscPort) status=\(link.status) queries=\(Diag.summary(wing.queries))") - } - wing.rename(source: "LCL/1", to: "Kick In") - let renamed = await eventually(30) { link.sources.first?.name == "Kick In" } - if !renamed { - Diag.log("rename[\(copy)] NEVER RENAMED \(Diag.t) ports=\(wing.port)/\(wing.oscPort) status=\(link.status) sources=\(link.sources.map(\.name)) queries=\(Diag.summary(wing.queries)) fds=\(Diag.fds())") - let probe = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: oscPort, timeout: .seconds(5)) - let identity = try? await probe.identify() - let sources = try? await probe.sources(usbChannelCount: 2) - Diag.log("rename[\(copy)] fresh probe: identity=\(String(describing: identity)) sources=\(String(describing: sources?.map(\.name))) queries=\(Diag.summary(wing.queries))") - } else if !connected { - Diag.log("rename[\(copy)] came up later \(Diag.t)") - } - #expect(connected && renamed) - } - - @Test("WING that answers no OSC: the Link comes up", arguments: 0..<25) - func linkUpWithGenericNames(_ copy: Int) async throws { - let wing = try await FakeWing(.init(answersOSC: false, unansweredKnocks: 3)) - let oscPort = wing.oscPort - let link = MixerLinkController(timeout: .milliseconds(300), renewEvery: .milliseconds(100)) { endpoint, timeout in - WingDriver(endpoint: endpoint, oscPort: oscPort, timeout: timeout) - } - let began = Diag.t - await link.connect(to: "127.0.0.1:\(wing.port)", usbChannelCount: 48) - let up = await eventually(30) { link.identity != nil && link.sources.count == 48 } - if !up { - Diag.log("noOSC[\(copy)] NEVER UP began \(began) now \(Diag.t) ports=\(wing.port)/\(wing.oscPort) status=\(link.status) queries=\(Diag.summary(wing.queries)) fds=\(Diag.fds())") - let probe = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: oscPort, timeout: .seconds(5)) - let identity = try? await probe.identify() - Diag.log("noOSC[\(copy)] fresh probe: identity=\(String(describing: identity)) queries=\(Diag.summary(wing.queries))") - try? await Task.sleep(for: .seconds(3)) - Diag.log("noOSC[\(copy)] 3 s later: status=\(link.status) queries=\(Diag.summary(wing.queries))") + // Clients as OSCUDPClient makes them, each to some WING's OSC port, kept open. + var clients: [(connection: NWConnection, wing: Int)] = [] + for index in 0..<3000 { + let wing = index % wings.count + let connection = NWConnection(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: wings[wing].oscPort)!, using: .udp) + connection.start(queue: .global(qos: .userInitiated)) + clients.append((connection, wing)) } - #expect(up) - } - - @Test("X-Air power cycle (#1215)", arguments: 0..<25) - func powerCycle(_ copy: Int) async throws { - var state = FakeXAirMixer.State() - state.channels[0] = .init(name: "Kick", color: 1) - state.usbRouting = XAirDriverTests.defaultRouting - let mixer = try await FakeXAirMixer(state) - let link = MixerLinkController(timeout: Loopback.mixedTimeout, renewEvery: .milliseconds(100)) - let began = Diag.t - await link.connect(to: "127.0.0.1:\(mixer.port)", usbChannelCount: 18) - let connected = link.sources[safe: 0]?.name == "Kick" - if !connected { - Diag.log("power[\(copy)] CONNECT FAILED began \(began) now \(Diag.t) port=\(mixer.port) status=\(link.status) queries=\(mixer.queries.count) last=\(mixer.queries.suffix(3))") + try await Task.sleep(for: .seconds(5)) + var clientPorts: [UInt16: Int] = [:] + var unknown = 0, onAListener = 0, onItsOwnWing = 0, onItsOwnDestination = 0 + var hit: Set = [] + for client in clients { + guard let port = Diag.localPort(client.connection) else { unknown += 1; continue } + clientPorts[port, default: 0] += 1 + if let wing = listenerPorts[port] { + onAListener += 1 + hit.insert(wing) + if wing == client.wing { onItsOwnWing += 1 } + if port == wings[client.wing].oscPort { onItsOwnDestination += 1 } + } } + let shared = clientPorts.values.filter { $0 > 1 }.count + Diag.log("census: clients=\(clients.count) noLocalPort=\(unknown) distinctClientPorts=\(clientPorts.count) portsSharedByClients=\(shared) clientsOnAListenerPort=\(onAListener) onItsOwnWing=\(onItsOwnWing) onItsOwnDestination=\(onItsOwnDestination) range \(clientPorts.keys.min() ?? 0)...\(clientPorts.keys.max() ?? 0)") - mixer.powerOff() - let down = await eventually(30) { if case .down = link.status { true } else { false } } - mixer.update { $0.channels[0].name = "Bass Drum" } - let onStart = ContinuousClock.now - let on = await withTaskGroup(of: Bool.self) { group in - group.addTask { (try? await mixer.powerOn()) != nil } - group.addTask { try? await Task.sleep(for: .seconds(30)); return false } - let first = await group.next() ?? false - group.cancelAll() - return first - } - if !on || !connected || !down { - Diag.log("power[\(copy)] \(Diag.t) connected=\(connected) down=\(down) powerOn=\(on) after \(ContinuousClock.now - onStart) status=\(link.status)") - } - let back = await eventually(30) { link.sources[safe: 0]?.name == "Bass Drum" } - mixer.rename(channel: 2, to: "Snare") - let pushed = await eventually(30) { link.sources[safe: 1]?.name == "Snare" } - if !back || !pushed { - Diag.log("power[\(copy)] \(Diag.t) back=\(back) pushed=\(pushed) status=\(link.status) sources=\(link.sources.prefix(2).map(\.name)) queries=\(mixer.queries.count) last=\(mixer.queries.suffix(4)) fds=\(Diag.fds())") + // Does a WING whose port a client also has still hear a new client? Against WINGs no client landed on. + func heard(_ indexes: [Int]) async -> (knocks: Int, osc: Int, of: Int) { + var knocks = 0, osc = 0 + for index in indexes { + let wing = wings[index] + let driver = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .seconds(3)) + if (try? await driver.identify()) != nil { knocks += 1 } + if let sources = try? await driver.sources(usbChannelCount: 1), sources.first?.name == "Kick" { osc += 1 } + } + return (knocks, osc, indexes.count) } - #expect(connected && down && on && back && pushed) + let hitList = Array(hit.sorted().prefix(40)) + let clear = Array((0.. Date: Thu, 3 Dec 2026 02:10:55 -0500 Subject: [PATCH 04/10] DIAGNOSTICS, do not merge: fresh reads against fake WINGs, with what each listener saw Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VCgWWseQZtUzcSRzjqqQJQ --- Sources/MixerLink/OSCUDPClient.swift | 2 +- Tests/MixerLinkTests/DiagnosticsTests.swift | 83 ++++++++------------- Tests/MixerLinkTests/Support/FakeWing.swift | 19 ++++- 3 files changed, 51 insertions(+), 53 deletions(-) diff --git a/Sources/MixerLink/OSCUDPClient.swift b/Sources/MixerLink/OSCUDPClient.swift index 3398256..60aa50f 100644 --- a/Sources/MixerLink/OSCUDPClient.swift +++ b/Sources/MixerLink/OSCUDPClient.swift @@ -99,7 +99,7 @@ actor OSCUDPClient { let connection = connection, generation = generation connection.stateUpdateHandler = { [weak self] state in guard let self else { return } - self.diagNote("state \(state) gen=\(generation)") + self.diagNote("state \(state) gen=\(generation) local=\(String(describing: connection.currentPath?.localEndpoint))") switch state { case .waiting(let error): // Waiting recovers by itself (the network comes back); fail requests meanwhile. diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift index a4b53fa..1f896a0 100644 --- a/Tests/MixerLinkTests/DiagnosticsTests.swift +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -19,61 +19,42 @@ enum Diag { } } -@Suite("Diagnostics: port census") -struct PortCensusTests { - @Test("Listener ports against client local ports") - func census() async throws { +@Suite("Diagnostics: fresh reads") +struct FreshReadsTests { + /// `idle` clients stay connected to each WING's OSC port without sending, as in the census. + @Test("A new driver reads one Source from a fake WING, many times", arguments: [0, 20]) + func freshReads(idle: Int) async throws { var wings: [FakeWing] = [] - for _ in 0..<150 { wings.append(try await FakeWing(WingLiveUpdatesTests.twoChannelWing())) } - var listenerPorts: [UInt16: Int] = [:] // port -> index of its WING - for (index, wing) in wings.enumerated() { - listenerPorts[wing.port] = index - listenerPorts[wing.oscPort] = index - } - Diag.log("census: \(wings.count) WINGs, \(listenerPorts.count) distinct listener ports, range \(listenerPorts.keys.min() ?? 0)...\(listenerPorts.keys.max() ?? 0)") - - // Clients as OSCUDPClient makes them, each to some WING's OSC port, kept open. - var clients: [(connection: NWConnection, wing: Int)] = [] - for index in 0..<3000 { - let wing = index % wings.count - let connection = NWConnection(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: wings[wing].oscPort)!, using: .udp) - connection.start(queue: .global(qos: .userInitiated)) - clients.append((connection, wing)) - } - try await Task.sleep(for: .seconds(5)) - var clientPorts: [UInt16: Int] = [:] - var unknown = 0, onAListener = 0, onItsOwnWing = 0, onItsOwnDestination = 0 - var hit: Set = [] - for client in clients { - guard let port = Diag.localPort(client.connection) else { unknown += 1; continue } - clientPorts[port, default: 0] += 1 - if let wing = listenerPorts[port] { - onAListener += 1 - hit.insert(wing) - if wing == client.wing { onItsOwnWing += 1 } - if port == wings[client.wing].oscPort { onItsOwnDestination += 1 } + for _ in 0..<40 { wings.append(try await FakeWing(WingLiveUpdatesTests.twoChannelWing())) } + var clients: [NWConnection] = [] + for wing in wings { + for _ in 0.. 1 }.count - Diag.log("census: clients=\(clients.count) noLocalPort=\(unknown) distinctClientPorts=\(clientPorts.count) portsSharedByClients=\(shared) clientsOnAListenerPort=\(onAListener) onItsOwnWing=\(onItsOwnWing) onItsOwnDestination=\(onItsOwnDestination) range \(clientPorts.keys.min() ?? 0)...\(clientPorts.keys.max() ?? 0)") - - // Does a WING whose port a client also has still hear a new client? Against WINGs no client landed on. - func heard(_ indexes: [Int]) async -> (knocks: Int, osc: Int, of: Int) { - var knocks = 0, osc = 0 - for index in indexes { - let wing = wings[index] - let driver = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .seconds(3)) - if (try? await driver.identify()) != nil { knocks += 1 } - if let sources = try? await driver.sources(usbChannelCount: 1), sources.first?.name == "Kick" { osc += 1 } + try await Task.sleep(for: .seconds(2)) + var reads = 0, failed = 0 + func heard(_ wing: FakeWing) -> Int { wing.queries.filter { $0 == "/io/out/USB/1/grp" }.count } + for round in 1...25 { + for (index, wing) in wings.enumerated() { + let driver = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .seconds(2)) + let before = heard(wing) + reads += 1 + let first = (try? await driver.sources(usbChannelCount: 1))?.first?.name + guard first != "Kick" else { continue } + failed += 1 + let afterFirst = heard(wing) + let again = (try? await driver.sources(usbChannelCount: 1))?.first?.name + let afterAgain = heard(wing) + let other = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .seconds(2)) + let fresh = (try? await other.sources(usbChannelCount: 1))?.first?.name + let last = DiagFlows.all.withLock { Array(($0[wing.oscPort] ?? []).suffix(14)) } + Diag.log("fresh[idle=\(idle)] FAILED round=\(round) wing=\(index) oscPort=\(wing.oscPort) heardFirst=\(afterFirst - before) sameDriverAgain=\(again ?? "nil") heardAgain=\(afterAgain - afterFirst) newDriver=\(fresh ?? "nil") flows=\(DiagFlows.count(wing.oscPort)) last=\(last)") } - return (knocks, osc, indexes.count) } - let hitList = Array(hit.sorted().prefix(40)) - let clear = Array((0..([:]) + static let start = ContinuousClock.now + static func note(_ port: UInt16, _ text: String) { + all.withLock { $0[port, default: []].append("\(ContinuousClock.now - start) \(text)") } + } + static func dump(_ port: UInt16, containing text: String) -> [String] { + all.withLock { ($0[port] ?? []).filter { $0.contains(text) } } + } + static func count(_ port: UInt16) -> Int { all.withLock { $0[port]?.count ?? 0 } } +} #endif From 62e07af6132b6b934fa01ac8570fb5b5510e61a3 Mon Sep 17 00:00:00 2001 From: Eric Dahl Date: Thu, 3 Dec 2026 02:19:38 -0500 Subject: [PATCH 05/10] DIAGNOSTICS, do not merge: replies that come after the wait Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VCgWWseQZtUzcSRzjqqQJQ --- Tests/MixerLinkTests/DiagnosticsTests.swift | 124 +++++++++++++----- Tests/MixerLinkTests/Support/FakeWing.swift | 7 +- .../Support/FakeXAirMixer.swift | 11 +- 3 files changed, 105 insertions(+), 37 deletions(-) diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift index 1f896a0..cc25255 100644 --- a/Tests/MixerLinkTests/DiagnosticsTests.swift +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -1,3 +1,4 @@ +#if canImport(Network) import Darwin import Foundation import MixerLink @@ -19,42 +20,95 @@ enum Diag { } } -@Suite("Diagnostics: fresh reads") -struct FreshReadsTests { - /// `idle` clients stay connected to each WING's OSC port without sending, as in the census. - @Test("A new driver reads one Source from a fake WING, many times", arguments: [0, 20]) - func freshReads(idle: Int) async throws { - var wings: [FakeWing] = [] - for _ in 0..<40 { wings.append(try await FakeWing(WingLiveUpdatesTests.twoChannelWing())) } - var clients: [NWConnection] = [] - for wing in wings { - for _ in 0.. Int { wing.queries.filter { $0 == "/io/out/USB/1/grp" }.count } - for round in 1...25 { - for (index, wing) in wings.enumerated() { - let driver = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .seconds(2)) - let before = heard(wing) - reads += 1 - let first = (try? await driver.sources(usbChannelCount: 1))?.first?.name - guard first != "Kick" else { continue } - failed += 1 - let afterFirst = heard(wing) - let again = (try? await driver.sources(usbChannelCount: 1))?.first?.name - let afterAgain = heard(wing) - let other = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .seconds(2)) - let fresh = (try? await other.sources(usbChannelCount: 1))?.first?.name - let last = DiagFlows.all.withLock { Array(($0[wing.oscPort] ?? []).suffix(14)) } - Diag.log("fresh[idle=\(idle)] FAILED round=\(round) wing=\(index) oscPort=\(wing.oscPort) heardFirst=\(afterFirst - before) sameDriverAgain=\(again ?? "nil") heardAgain=\(afterAgain - afterFirst) newDriver=\(fresh ?? "nil") flows=\(DiagFlows.count(wing.oscPort)) last=\(last)") - } + let flows = DiagFlows.all.withLock { $0[wing.port] ?? [] } + Diag.log("wingKnockLate[\(copy)] first=\(first) later=\(later) knocksHeard=\(wing.queries.filter { $0 == "WING?" }.count) flows=\(flows)") + #expect(later.allSatisfy { $0 }) + } + + @Test("WING Link whose first knock is answered late", arguments: 0..<5) + func wingLinkLate(_ copy: Int) async throws { + let wing = try await FakeWing(WingLiveUpdatesTests.twoChannelWing()) + wing.update { $0.knockReplyDelay = 0.8 } + let oscPort = wing.oscPort + let link = MixerLinkController(timeout: .milliseconds(300), renewEvery: .milliseconds(100)) { endpoint, timeout in + WingDriver(endpoint: endpoint, oscPort: oscPort, timeout: timeout, rereadEvery: .zero) + } + await link.connect(to: "127.0.0.1:\(wing.port)", usbChannelCount: 2) + let atOnce = link.status + try await Task.sleep(for: .seconds(1)) + wing.update { $0.knockReplyDelay = 0 } + let up = await eventually(15) { link.sources.first?.name == "Kick" } + Diag.log("wingLinkLate[\(copy)] atOnce=\(atOnce) up=\(up) status=\(link.status) knocksHeard=\(wing.queries.filter { $0 == "WING?" }.count)") + #expect(up) + } + + @Test("X-Air answered late, then asked again", arguments: 0..<5) + func xAirLate(_ copy: Int) async throws { + let mixer = try await FakeXAirMixer() + mixer.update { $0.replyDelay = 0.6 } + var first = false + do { + let quick = XAirDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: mixer.port), timeout: .milliseconds(200)) + first = (try? await quick.identify()) != nil + } + try await Task.sleep(for: .seconds(1)) + mixer.update { $0.replyDelay = 0 } + var later: [Bool] = [] + for _ in 0..<5 { + let patient = XAirDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: mixer.port), timeout: .seconds(3)) + later.append((try? await patient.identify()) != nil) + } + Diag.log("xAirLate[\(copy)] first=\(first) later=\(later) heard=\(mixer.queries.count)") + #expect(later.allSatisfy { $0 }) + } + + @Test("X-Air Link whose first answers come late, then the power cycle", arguments: 0..<5) + func xAirLinkLate(_ copy: Int) async throws { + var state = FakeXAirMixer.State() + state.channels[0] = .init(name: "Kick", color: 1) + state.usbRouting = XAirDriverTests.defaultRouting + state.replyDelay = 0.8 + let mixer = try await FakeXAirMixer(state) + let link = MixerLinkController(timeout: .milliseconds(300), renewEvery: .milliseconds(100)) + await link.connect(to: "127.0.0.1:\(mixer.port)", usbChannelCount: 18) + let atOnce = link.status + try await Task.sleep(for: .seconds(1)) + mixer.update { $0.replyDelay = 0 } + let up = await eventually(15) { link.sources[safe: 0]?.name == "Kick" } + Diag.log("xAirLinkLate[\(copy)] atOnce=\(atOnce) up=\(up) status=\(link.status) heard=\(mixer.queries.count)") + + // The power cycle test's steps, with the Link down at power-off as in run 43502838420. + mixer.update { $0.replyDelay = 0.8 } + try await Task.sleep(for: .seconds(1)) + let before = link.status + mixer.powerOff() + mixer.update { $0.replyDelay = 0; $0.channels[0].name = "Bass Drum" } + let on = await withTaskGroup(of: Bool.self) { group in + group.addTask { (try? await mixer.powerOn()) != nil } + group.addTask { try? await Task.sleep(for: .seconds(20)); return false } + let first = await group.next() ?? false + group.cancelAll() + return first } - Diag.log("fresh[idle=\(idle)] reads=\(reads) failed=\(failed)") - for client in clients { client.cancel() } + let back = await eventually(15) { link.sources[safe: 0]?.name == "Bass Drum" } + Diag.log("xAirLinkLate[\(copy)] beforePowerOff=\(before) powerOn=\(on) back=\(back) status=\(link.status)") + #expect(up && on && back) } } +#endif diff --git a/Tests/MixerLinkTests/Support/FakeWing.swift b/Tests/MixerLinkTests/Support/FakeWing.swift index f0233b6..ae4aeaf 100644 --- a/Tests/MixerLinkTests/Support/FakeWing.swift +++ b/Tests/MixerLinkTests/Support/FakeWing.swift @@ -20,6 +20,8 @@ final class FakeWing: Sendable { var answersOSC = true /// Knocks still to go unanswered, as on a starved CI runner where the answer comes after the wait (#1223). var unansweredKnocks = 0 + /// DIAGNOSTICS: seconds each knock reply is held before it is sent. + var knockReplyDelay: TimeInterval = 0 /// OSC replies still to drop: each query is logged but gets no answer (#1223). var droppedOSCReplies = 0 } @@ -52,7 +54,10 @@ final class FakeWing: Sendable { init(_ initial: State = State()) async throws { let box = Box(initial) self.box = box - let (knock, port) = try await Self.listen { data in + let (knock, port) = try await Self.listen(deliver: { send in + let delay = box.state.withLock { $0.knockReplyDelay } + if delay > 0 { DispatchQueue.global().asyncAfter(deadline: .now() + delay) { send() } } else { send() } + }) { data in let text = String(decoding: data, as: UTF8.self) return box.state.withLock { state in state.queries.append(text) diff --git a/Tests/MixerLinkTests/Support/FakeXAirMixer.swift b/Tests/MixerLinkTests/Support/FakeXAirMixer.swift index db082ac..95d4e19 100644 --- a/Tests/MixerLinkTests/Support/FakeXAirMixer.swift +++ b/Tests/MixerLinkTests/Support/FakeXAirMixer.swift @@ -43,6 +43,8 @@ final class FakeXAirMixer: Sendable { var auxReturn = Channel(name: "", color: 0) /// When false, the mixer receives queries but never answers. var answers = true + /// DIAGNOSTICS: seconds each reply is held before it is sent. + var replyDelay: TimeInterval = 0 /// When false, mute, fader and input source queries go unanswered (older firmware, say). var answersMixState = true /// When true, faders are reported as integers instead of floats. @@ -263,7 +265,14 @@ final class FakeXAirMixer: Sendable { } if echo { connection.send(content: Data(OSCMessage(message.address).encoded()), completion: .contentProcessed { _ in }) } } else if let data, let query = try? OSCMessage(decoding: Array(data)), let reply = reply(to: query) { - connection.send(content: Data(reply.encoded()), completion: .contentProcessed { _ in }) + let delay = state.withLock { $0.replyDelay } + if delay > 0 { + DispatchQueue.global().asyncAfter(deadline: .now() + delay) { + connection.send(content: Data(reply.encoded()), completion: .contentProcessed { _ in }) + } + } else { + connection.send(content: Data(reply.encoded()), completion: .contentProcessed { _ in }) + } } serve(connection) } From eaa2261d8cf5a29ee9ca69a10d9a4564945e2278 Mon Sep 17 00:00:00 2001 From: Eric Dahl Date: Thu, 3 Dec 2026 02:27:00 -0500 Subject: [PATCH 06/10] DIAGNOSTICS, do not merge: the fake X-Air listens again after a failed listen Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VCgWWseQZtUzcSRzjqqQJQ --- Tests/MixerLinkTests/DiagnosticsTests.swift | 5 +- .../Support/FakeXAirMixer.swift | 56 +++++++++++++------ 2 files changed, 42 insertions(+), 19 deletions(-) diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift index cc25255..351e9dd 100644 --- a/Tests/MixerLinkTests/DiagnosticsTests.swift +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -78,12 +78,13 @@ struct LateReplyTests { #expect(later.allSatisfy { $0 }) } - @Test("X-Air Link whose first answers come late, then the power cycle", arguments: 0..<5) + @Test("X-Air Link whose first answers come late, then the power cycle", arguments: 0..<24) func xAirLinkLate(_ copy: Int) async throws { var state = FakeXAirMixer.State() state.channels[0] = .init(name: "Kick", color: 1) state.usbRouting = XAirDriverTests.defaultRouting state.replyDelay = 0.8 + state.diagRefusesLateFlows = copy % 2 == 0 let mixer = try await FakeXAirMixer(state) let link = MixerLinkController(timeout: .milliseconds(300), renewEvery: .milliseconds(100)) await link.connect(to: "127.0.0.1:\(mixer.port)", usbChannelCount: 18) @@ -107,7 +108,7 @@ struct LateReplyTests { return first } let back = await eventually(15) { link.sources[safe: 0]?.name == "Bass Drum" } - Diag.log("xAirLinkLate[\(copy)] beforePowerOff=\(before) powerOn=\(on) back=\(back) status=\(link.status)") + Diag.log("xAirLinkLate[\(copy)] refuses=\(copy % 2 == 0) beforePowerOff=\(before) powerOn=\(on) back=\(back) status=\(link.status)") #expect(up && on && back) } } diff --git a/Tests/MixerLinkTests/Support/FakeXAirMixer.swift b/Tests/MixerLinkTests/Support/FakeXAirMixer.swift index 95d4e19..aad8bec 100644 --- a/Tests/MixerLinkTests/Support/FakeXAirMixer.swift +++ b/Tests/MixerLinkTests/Support/FakeXAirMixer.swift @@ -45,6 +45,7 @@ final class FakeXAirMixer: Sendable { var answers = true /// DIAGNOSTICS: seconds each reply is held before it is sent. var replyDelay: TimeInterval = 0 + var diagRefusesLateFlows = true /// When false, mute, fader and input source queries go unanswered (older firmware, say). var answersMixState = true /// When true, faders are reported as integers instead of floats. @@ -120,30 +121,49 @@ final class FakeXAirMixer: Sendable { /// Opens a loopback UDP listener on `port` that answers with `responder`, and returns it with its port. private static func listen(on port: NWEndpoint.Port, responder: Responder) async throws -> (NWListener, UInt16) { - let parameters = NWParameters.udp - parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: port) - parameters.allowLocalEndpointReuse = true - let listener = try NWListener(using: parameters) - let ready = AsyncStream.makeStream() - listener.stateUpdateHandler = { [listener] update in - if case .ready = update, let port = listener.port?.rawValue { ready.continuation.yield(port) } - switch update { - case .failed(let error), .waiting(let error): fputs("[diag] X-Air listener on \(port): \(update) \(error)\n", stderr) - default: break + var attempt = 0 + while true { + attempt += 1 + let parameters = NWParameters.udp + parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: port) + parameters.allowLocalEndpointReuse = true + let listener = try NWListener(using: parameters) + let ready = AsyncStream.makeStream() + listener.stateUpdateHandler = { [listener, attempt] update in + switch update { + case .ready: ready.continuation.yield(listener.port?.rawValue) + case .failed(let error), .waiting(let error): + fputs("[diag] X-Air listener on \(port) attempt \(attempt): \(update) \(error)\n", stderr) + ready.continuation.yield(nil) + default: break + } } + let epoch = responder.epoch.withLock { $0 } + listener.newConnectionHandler = { connection in + let refuses = responder.state.withLock { $0.diagRefusesLateFlows } + if responder.epoch.withLock({ $0 }) != epoch { + fputs("[diag] X-Air listener on \(port): a flow after power-off from \(connection.endpoint), refused=\(refuses)\n", stderr) + if refuses { connection.cancel(); return } + } + connection.start(queue: .global()) + responder.serve(connection) + } + listener.start(queue: .global()) + var iterator = ready.stream.makeAsyncIterator() + if let found = await iterator.next(), let found { + if attempt > 1 { fputs("[diag] X-Air listener on \(port): ready at attempt \(attempt)\n", stderr) } + return (listener, found) + } + listener.cancel() + if attempt >= 200 || Task.isCancelled { throw CancellationError() } + try await Task.sleep(for: .milliseconds(25)) } - listener.newConnectionHandler = { connection in - connection.start(queue: .global()) - responder.serve(connection) - } - listener.start(queue: .global()) - var iterator = ready.stream.makeAsyncIterator() - return (listener, await iterator.next() ?? 0) } /// Switches the Mixer off, as a power cycle does: nothing listens on its port any more. (On loopback macOS doesn't /// report the bounce to the Link's connection, so this doesn't make it fail; `OSCUDPClientRecoveryTests` covers that.) func powerOff() { + responder.epoch.withLock { $0 += 1 } listener.withLock { $0?.cancel(); $0 = nil } responder.dropConnections() } @@ -214,6 +234,8 @@ final class FakeXAirMixer: Sendable { private let subscribers = Mutex<[(connection: NWConnection, expires: Date)]>([]) init(_ state: State) { self.state = Mutex(state) } + /// Counts power-offs: a flow a listener hands over after its power-off is not served. + let epoch = Mutex(0) /// Every connection served, so a power-off can close them all. private let connections = Mutex<[NWConnection]>([]) From 0f978621ee171cc670dd802986e99ab3264ab4c7 Mon Sep 17 00:00:00 2001 From: Eric Dahl Date: Thu, 3 Dec 2026 02:33:52 -0500 Subject: [PATCH 07/10] DIAGNOSTICS, do not merge: red/green check of listening again, under load Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VCgWWseQZtUzcSRzjqqQJQ --- Tests/MixerLinkTests/DiagnosticsTests.swift | 136 +++++++----------- .../Support/FakeXAirMixer.swift | 5 +- 2 files changed, 53 insertions(+), 88 deletions(-) diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift index 351e9dd..3168976 100644 --- a/Tests/MixerLinkTests/DiagnosticsTests.swift +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -1,115 +1,79 @@ #if canImport(Network) -import Darwin import Foundation import MixerLink -import Network -import Synchronization import Testing -// DIAGNOSTICS ONLY (ShowRecorder #1215, #1248, #1249): never merge. Does a loopback UDP listener share its port with a -// client connection's local port, and does it then stop hearing new clients? +// DIAGNOSTICS ONLY (ShowRecorder #1215): never merge. Red/green check of the fake X-Air listening again on its port. enum Diag { static func log(_ text: String) { fputs("[diag] \(text)\n", stderr) } - - static func localPort(_ connection: NWConnection) -> UInt16? { - if case .hostPort(_, let port)? = connection.currentPath?.localEndpoint { return port.rawValue } - return nil - } } @MainActor -@Suite("Diagnostics: a reply that comes after the wait") -struct LateReplyTests { - @Test("WING knock answered late, then asked again", arguments: 0..<5) - func wingKnockLate(_ copy: Int) async throws { - let wing = try await FakeWing(WingLiveUpdatesTests.twoChannelWing()) - wing.update { $0.knockReplyDelay = 0.6 } - let quick = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .milliseconds(200)) - let first = (try? await quick.identify()) != nil - try await Task.sleep(for: .seconds(1)) // the late reply has gone out to a closed port - wing.update { $0.knockReplyDelay = 0 } - var later: [Bool] = [] - for _ in 0..<5 { - let patient = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .seconds(3)) - later.append((try? await patient.identify()) != nil) - } - let flows = DiagFlows.all.withLock { $0[wing.port] ?? [] } - Diag.log("wingKnockLate[\(copy)] first=\(first) later=\(later) knocksHeard=\(wing.queries.filter { $0 == "WING?" }.count) flows=\(flows)") - #expect(later.allSatisfy { $0 }) - } - - @Test("WING Link whose first knock is answered late", arguments: 0..<5) - func wingLinkLate(_ copy: Int) async throws { - let wing = try await FakeWing(WingLiveUpdatesTests.twoChannelWing()) - wing.update { $0.knockReplyDelay = 0.8 } - let oscPort = wing.oscPort - let link = MixerLinkController(timeout: .milliseconds(300), renewEvery: .milliseconds(100)) { endpoint, timeout in - WingDriver(endpoint: endpoint, oscPort: oscPort, timeout: timeout, rereadEvery: .zero) - } - await link.connect(to: "127.0.0.1:\(wing.port)", usbChannelCount: 2) - let atOnce = link.status - try await Task.sleep(for: .seconds(1)) - wing.update { $0.knockReplyDelay = 0 } - let up = await eventually(15) { link.sources.first?.name == "Kick" } - Diag.log("wingLinkLate[\(copy)] atOnce=\(atOnce) up=\(up) status=\(link.status) knocksHeard=\(wing.queries.filter { $0 == "WING?" }.count)") - #expect(up) +@Suite("Load: main actor") +struct MainActorLoadTests { + @Test("Blocks the main actor for 10 ms", arguments: 0..<1500) + func block(_ index: Int) { + Thread.sleep(forTimeInterval: 0.01) } +} - @Test("X-Air answered late, then asked again", arguments: 0..<5) - func xAirLate(_ copy: Int) async throws { - let mixer = try await FakeXAirMixer() - mixer.update { $0.replyDelay = 0.6 } - var first = false - do { - let quick = XAirDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: mixer.port), timeout: .milliseconds(200)) - first = (try? await quick.identify()) != nil - } - try await Task.sleep(for: .seconds(1)) - mixer.update { $0.replyDelay = 0 } - var later: [Bool] = [] - for _ in 0..<5 { - let patient = XAirDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: mixer.port), timeout: .seconds(3)) - later.append((try? await patient.identify()) != nil) - } - Diag.log("xAirLate[\(copy)] first=\(first) later=\(later) heard=\(mixer.queries.count)") - #expect(later.allSatisfy { $0 }) +@Suite("Load: pool") +struct PoolLoadTests { + @Test("Burns a pool thread for 400 ms", arguments: 0..<120) + func burn(_ index: Int) { + let end = Date().addingTimeInterval(0.4) + var x = 0.0 + while Date() < end { x += sin(x + 1) } } +} - @Test("X-Air Link whose first answers come late, then the power cycle", arguments: 0..<24) - func xAirLinkLate(_ copy: Int) async throws { +@MainActor +@Suite("Diagnostics: power cycle at once") +struct PowerCycleAtOnceTests { + /// The planned regression test. Odd copies listen once only, as the fake did before; a failed listen then throws + /// here where the old fake waited forever. + @Test("Late answers on their way at power-off", arguments: 0..<24) + func lateAnswers(_ copy: Int) async throws { var state = FakeXAirMixer.State() state.channels[0] = .init(name: "Kick", color: 1) state.usbRouting = XAirDriverTests.defaultRouting - state.replyDelay = 0.8 - state.diagRefusesLateFlows = copy % 2 == 0 + state.diagListenAttempts = copy % 2 == 0 ? 200 : 1 let mixer = try await FakeXAirMixer(state) let link = MixerLinkController(timeout: .milliseconds(300), renewEvery: .milliseconds(100)) await link.connect(to: "127.0.0.1:\(mixer.port)", usbChannelCount: 18) - let atOnce = link.status - try await Task.sleep(for: .seconds(1)) - mixer.update { $0.replyDelay = 0 } - let up = await eventually(15) { link.sources[safe: 0]?.name == "Kick" } - Diag.log("xAirLinkLate[\(copy)] atOnce=\(atOnce) up=\(up) status=\(link.status) heard=\(mixer.queries.count)") - - // The power cycle test's steps, with the Link down at power-off as in run 43502838420. + let up = await eventually(30) { link.sources[safe: 0]?.name == "Kick" } mixer.update { $0.replyDelay = 0.8 } - try await Task.sleep(for: .seconds(1)) - let before = link.status + let down = await eventually(30) { if case .down = link.status { true } else { false } } mixer.powerOff() mixer.update { $0.replyDelay = 0; $0.channels[0].name = "Bass Drum" } - let on = await withTaskGroup(of: Bool.self) { group in - group.addTask { (try? await mixer.powerOn()) != nil } - group.addTask { try? await Task.sleep(for: .seconds(20)); return false } - let first = await group.next() ?? false - group.cancelAll() - return first - } - let back = await eventually(15) { link.sources[safe: 0]?.name == "Bass Drum" } - Diag.log("xAirLinkLate[\(copy)] refuses=\(copy % 2 == 0) beforePowerOff=\(before) powerOn=\(on) back=\(back) status=\(link.status)") - #expect(up && on && back) + var on = true + do { try await mixer.powerOn() } catch { on = false } + let back = on ? await eventually(30) { link.sources[safe: 0]?.name == "Bass Drum" } : false + Diag.log("lateAnswers[\(copy)] retries=\(copy % 2 == 0) up=\(up) down=\(down) powerOn=\(on) back=\(back)") + } + + /// Closer to CI run 43502838420: the first connect fails, the Link keeps trying, no answer is late. + @Test("First connect failed, the Link keeps trying", arguments: 0..<24) + func connectFailed(_ copy: Int) async throws { + var state = FakeXAirMixer.State() + state.channels[0] = .init(name: "Kick", color: 1) + state.usbRouting = XAirDriverTests.defaultRouting + state.answers = false + state.diagListenAttempts = 1 + let mixer = try await FakeXAirMixer(state) + let link = MixerLinkController(timeout: .milliseconds(300), renewEvery: .milliseconds(100)) + await link.connect(to: "127.0.0.1:\(mixer.port)", usbChannelCount: 18) + try await Task.sleep(for: .milliseconds(100 * (copy % 6))) + mixer.powerOff() + _ = await eventually(30) { if case .down = link.status { true } else { false } } + mixer.update { $0.answers = true; $0.channels[0].name = "Bass Drum" } + var on = true + do { try await mixer.powerOn() } catch { on = false } + let back = on ? await eventually(30) { link.sources[safe: 0]?.name == "Bass Drum" } : false + Diag.log("connectFailed[\(copy)] powerOn=\(on) back=\(back)") } } #endif diff --git a/Tests/MixerLinkTests/Support/FakeXAirMixer.swift b/Tests/MixerLinkTests/Support/FakeXAirMixer.swift index aad8bec..70e7ea4 100644 --- a/Tests/MixerLinkTests/Support/FakeXAirMixer.swift +++ b/Tests/MixerLinkTests/Support/FakeXAirMixer.swift @@ -45,7 +45,8 @@ final class FakeXAirMixer: Sendable { var answers = true /// DIAGNOSTICS: seconds each reply is held before it is sent. var replyDelay: TimeInterval = 0 - var diagRefusesLateFlows = true + var diagRefusesLateFlows = false + var diagListenAttempts = 200 /// When false, mute, fader and input source queries go unanswered (older firmware, say). var answersMixState = true /// When true, faders are reported as integers instead of floats. @@ -155,7 +156,7 @@ final class FakeXAirMixer: Sendable { return (listener, found) } listener.cancel() - if attempt >= 200 || Task.isCancelled { throw CancellationError() } + if attempt >= responder.state.withLock({ $0.diagListenAttempts }) || Task.isCancelled { throw CancellationError() } try await Task.sleep(for: .milliseconds(25)) } } From b642674acb2ba02c6b5eeaa13e89fbb6507dcbef Mon Sep 17 00:00:00 2001 From: Eric Dahl Date: Thu, 3 Dec 2026 02:41:29 -0500 Subject: [PATCH 08/10] DIAGNOSTICS, do not merge: the new test's body, with and without the second listen, no load Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VCgWWseQZtUzcSRzjqqQJQ --- Tests/MixerLinkTests/DiagnosticsTests.swift | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift index 3168976..c19ad00 100644 --- a/Tests/MixerLinkTests/DiagnosticsTests.swift +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -14,7 +14,7 @@ enum Diag { @MainActor @Suite("Load: main actor") struct MainActorLoadTests { - @Test("Blocks the main actor for 10 ms", arguments: 0..<1500) + @Test("Blocks the main actor for 10 ms", arguments: 0..<1) func block(_ index: Int) { Thread.sleep(forTimeInterval: 0.01) } @@ -22,7 +22,7 @@ struct MainActorLoadTests { @Suite("Load: pool") struct PoolLoadTests { - @Test("Burns a pool thread for 400 ms", arguments: 0..<120) + @Test("Burns a pool thread for 400 ms", arguments: 0..<1) func burn(_ index: Int) { let end = Date().addingTimeInterval(0.4) var x = 0.0 @@ -55,25 +55,24 @@ struct PowerCycleAtOnceTests { Diag.log("lateAnswers[\(copy)] retries=\(copy % 2 == 0) up=\(up) down=\(down) powerOn=\(on) back=\(back)") } - /// Closer to CI run 43502838420: the first connect fails, the Link keeps trying, no answer is late. + /// The new test's body. Odd copies listen once only, as the fake did before. @Test("First connect failed, the Link keeps trying", arguments: 0..<24) func connectFailed(_ copy: Int) async throws { var state = FakeXAirMixer.State() state.channels[0] = .init(name: "Kick", color: 1) state.usbRouting = XAirDriverTests.defaultRouting state.answers = false - state.diagListenAttempts = 1 + state.diagListenAttempts = copy % 2 == 0 ? 200 : 1 let mixer = try await FakeXAirMixer(state) - let link = MixerLinkController(timeout: .milliseconds(300), renewEvery: .milliseconds(100)) + let link = MixerLinkController(timeout: .seconds(1), renewEvery: .milliseconds(100)) await link.connect(to: "127.0.0.1:\(mixer.port)", usbChannelCount: 18) - try await Task.sleep(for: .milliseconds(100 * (copy % 6))) - mixer.powerOff() _ = await eventually(30) { if case .down = link.status { true } else { false } } - mixer.update { $0.answers = true; $0.channels[0].name = "Bass Drum" } + mixer.powerOff() + mixer.update { $0.answers = true } var on = true do { try await mixer.powerOn() } catch { on = false } - let back = on ? await eventually(30) { link.sources[safe: 0]?.name == "Bass Drum" } : false - Diag.log("connectFailed[\(copy)] powerOn=\(on) back=\(back)") + let back = on ? await eventually(30) { link.sources[safe: 0]?.name == "Kick" } : false + Diag.log("connectFailed[\(copy)] retries=\(copy % 2 == 0) powerOn=\(on) back=\(back)") } } #endif From 8985689990b18617ff3a6d489f2546a0383c7521 Mon Sep 17 00:00:00 2001 From: Eric Dahl Date: Thu, 3 Dec 2026 02:48:29 -0500 Subject: [PATCH 09/10] DIAGNOSTICS, do not merge: census 2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VCgWWseQZtUzcSRzjqqQJQ --- Tests/MixerLinkTests/DiagnosticsTests.swift | 115 ++++++++++---------- 1 file changed, 56 insertions(+), 59 deletions(-) diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift index c19ad00..01e542a 100644 --- a/Tests/MixerLinkTests/DiagnosticsTests.swift +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -1,78 +1,75 @@ #if canImport(Network) import Foundation import MixerLink +import Network import Testing -// DIAGNOSTICS ONLY (ShowRecorder #1215): never merge. Red/green check of the fake X-Air listening again on its port. +// DIAGNOSTICS ONLY (ShowRecorder #1248): never merge. Which fake WINGs stop hearing a new driver while many client +// connections are open, and what is special about them. enum Diag { static func log(_ text: String) { fputs("[diag] \(text)\n", stderr) } -} -@MainActor -@Suite("Load: main actor") -struct MainActorLoadTests { - @Test("Blocks the main actor for 10 ms", arguments: 0..<1) - func block(_ index: Int) { - Thread.sleep(forTimeInterval: 0.01) + static func localPort(_ connection: NWConnection) -> UInt16? { + if case .hostPort(_, let port)? = connection.currentPath?.localEndpoint { return port.rawValue } + return nil } } -@Suite("Load: pool") -struct PoolLoadTests { - @Test("Burns a pool thread for 400 ms", arguments: 0..<1) - func burn(_ index: Int) { - let end = Date().addingTimeInterval(0.4) - var x = 0.0 - while Date() < end { x += sin(x + 1) } - } -} +@Suite("Diagnostics: census 2") +struct Census2Tests { + @Test("Every fake WING is asked by a new driver while idle clients stay open", arguments: [20, 0]) + func census(idle: Int) async throws { + var wings: [FakeWing] = [] + for _ in 0..<150 { wings.append(try await FakeWing(WingLiveUpdatesTests.twoChannelWing())) } + var listenerPorts: [UInt16: String] = [:] + for (index, wing) in wings.enumerated() { + listenerPorts[wing.port] = "knock\(index)" + listenerPorts[wing.oscPort] = "osc\(index)" + } + var clients: [(connection: NWConnection, wing: Int)] = [] + for index in 0..<(idle * wings.count) { + let wing = index % wings.count + let connection = NWConnection(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: wings[wing].oscPort)!, using: .udp) + connection.start(queue: .global(qos: .userInitiated)) + clients.append((connection, wing)) + } + try await Task.sleep(for: .seconds(5)) -@MainActor -@Suite("Diagnostics: power cycle at once") -struct PowerCycleAtOnceTests { - /// The planned regression test. Odd copies listen once only, as the fake did before; a failed listen then throws - /// here where the old fake waited forever. - @Test("Late answers on their way at power-off", arguments: 0..<24) - func lateAnswers(_ copy: Int) async throws { - var state = FakeXAirMixer.State() - state.channels[0] = .init(name: "Kick", color: 1) - state.usbRouting = XAirDriverTests.defaultRouting - state.diagListenAttempts = copy % 2 == 0 ? 200 : 1 - let mixer = try await FakeXAirMixer(state) - let link = MixerLinkController(timeout: .milliseconds(300), renewEvery: .milliseconds(100)) - await link.connect(to: "127.0.0.1:\(mixer.port)", usbChannelCount: 18) - let up = await eventually(30) { link.sources[safe: 0]?.name == "Kick" } - mixer.update { $0.replyDelay = 0.8 } - let down = await eventually(30) { if case .down = link.status { true } else { false } } - mixer.powerOff() - mixer.update { $0.replyDelay = 0; $0.channels[0].name = "Bass Drum" } - var on = true - do { try await mixer.powerOn() } catch { on = false } - let back = on ? await eventually(30) { link.sources[safe: 0]?.name == "Bass Drum" } : false - Diag.log("lateAnswers[\(copy)] retries=\(copy % 2 == 0) up=\(up) down=\(down) powerOn=\(on) back=\(back)") - } + var byPort: [UInt16: [Int]] = [:] // local port -> indexes into clients + var states: [String: Int] = [:] + for (index, client) in clients.enumerated() { + states["\(client.connection.state)", default: 0] += 1 + if let port = Diag.localPort(client.connection) { byPort[port, default: []].append(index) } + } + Diag.log("census2[idle=\(idle)] clients=\(clients.count) states=\(states) distinctLocalPorts=\(byPort.count)") + var special: Set = [] + for (port, indexes) in byPort where indexes.count > 1 || listenerPorts[port] != nil { + let targets = Set(indexes.map { clients[$0].wing }) + special.formUnion(targets) + let detail = indexes.prefix(4).map { "\(clients[$0].connection.state) path=\(String(describing: clients[$0].connection.currentPath?.status)) local=\(String(describing: clients[$0].connection.currentPath?.localEndpoint)) remote=\(String(describing: clients[$0].connection.currentPath?.remoteEndpoint))" } + Diag.log("census2[idle=\(idle)] local port \(port) used by \(indexes.count) clients to WINGs \(targets.sorted()) (their OSC ports \(targets.sorted().map { wings[$0].oscPort })); also a listener: \(listenerPorts[port] ?? "no"); \(detail)") + } - /// The new test's body. Odd copies listen once only, as the fake did before. - @Test("First connect failed, the Link keeps trying", arguments: 0..<24) - func connectFailed(_ copy: Int) async throws { - var state = FakeXAirMixer.State() - state.channels[0] = .init(name: "Kick", color: 1) - state.usbRouting = XAirDriverTests.defaultRouting - state.answers = false - state.diagListenAttempts = copy % 2 == 0 ? 200 : 1 - let mixer = try await FakeXAirMixer(state) - let link = MixerLinkController(timeout: .seconds(1), renewEvery: .milliseconds(100)) - await link.connect(to: "127.0.0.1:\(mixer.port)", usbChannelCount: 18) - _ = await eventually(30) { if case .down = link.status { true } else { false } } - mixer.powerOff() - mixer.update { $0.answers = true } - var on = true - do { try await mixer.powerOn() } catch { on = false } - let back = on ? await eventually(30) { link.sources[safe: 0]?.name == "Kick" } : false - Diag.log("connectFailed[\(copy)] retries=\(copy % 2 == 0) powerOn=\(on) back=\(back)") + var deaf: [Int] = [] + for (index, wing) in wings.enumerated() { + let driver = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .seconds(3)) + let knock = (try? await driver.identify()) != nil + let heardBefore = wing.queries.filter { $0 == "/io/out/USB/1/grp" }.count + let name = (try? await driver.sources(usbChannelCount: 1))?.first?.name + guard !knock || name != "Kick" else { continue } + deaf.append(index) + let heard = wing.queries.filter { $0 == "/io/out/USB/1/grp" }.count - heardBefore + let again = (try? await driver.sources(usbChannelCount: 1))?.first?.name + let other = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .seconds(3)) + let fresh = (try? await other.sources(usbChannelCount: 1))?.first?.name + let flows = DiagFlows.all.withLock { Array(($0[wing.oscPort] ?? []).suffix(10)) } + Diag.log("census2[idle=\(idle)] DEAF wing=\(index) ports=\(wing.port)/\(wing.oscPort) special=\(special.contains(index)) knock=\(knock) name=\(name ?? "nil") heardByFake=\(heard) sameDriverAgain=\(again ?? "nil") newDriver=\(fresh ?? "nil") flows=\(flows)") + } + Diag.log("census2[idle=\(idle)] deaf=\(deaf) special=\(special.sorted())") + for client in clients { client.connection.cancel() } } } #endif From 6747c990ba69685f9aa2ab20252757c6a9e8d416 Mon Sep 17 00:00:00 2001 From: Eric Dahl Date: Thu, 3 Dec 2026 02:59:17 -0500 Subject: [PATCH 10/10] DIAGNOSTICS, do not merge: a listener on a leaked flow's remote port Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VCgWWseQZtUzcSRzjqqQJQ --- Tests/MixerLinkTests/DiagnosticsTests.swift | 147 +++++++++++++------- 1 file changed, 94 insertions(+), 53 deletions(-) diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift index 01e542a..78f3e2d 100644 --- a/Tests/MixerLinkTests/DiagnosticsTests.swift +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -2,74 +2,115 @@ import Foundation import MixerLink import Network +import Synchronization import Testing -// DIAGNOSTICS ONLY (ShowRecorder #1248): never merge. Which fake WINGs stop hearing a new driver while many client -// connections are open, and what is special about them. +// DIAGNOSTICS ONLY (ShowRecorder #1248): never merge. Does a flow that a listener never closed make a later listener +// on that flow's remote port unreachable? enum Diag { static func log(_ text: String) { fputs("[diag] \(text)\n", stderr) } +} + +/// A loopback UDP listener that answers every datagram and, like the fakes, keeps the flows it accepted. +final class DiagEcho: Sendable { + let listener: NWListener + let port: UInt16 + let flows: Mutex<[NWConnection]> + let heard: Mutex - static func localPort(_ connection: NWConnection) -> UInt16? { - if case .hostPort(_, let port)? = connection.currentPath?.localEndpoint { return port.rawValue } - return nil + init(listener: NWListener, port: UInt16, flows: Mutex<[NWConnection]>, heard: Mutex) { + self.listener = listener + self.port = port + self.flows = flows + self.heard = heard } -} -@Suite("Diagnostics: census 2") -struct Census2Tests { - @Test("Every fake WING is asked by a new driver while idle clients stay open", arguments: [20, 0]) - func census(idle: Int) async throws { - var wings: [FakeWing] = [] - for _ in 0..<150 { wings.append(try await FakeWing(WingLiveUpdatesTests.twoChannelWing())) } - var listenerPorts: [UInt16: String] = [:] - for (index, wing) in wings.enumerated() { - listenerPorts[wing.port] = "knock\(index)" - listenerPorts[wing.oscPort] = "osc\(index)" + static func listen(on port: NWEndpoint.Port = .any) async throws -> (echo: DiagEcho, tries: Int) { + for attempt in 1...200 { + let parameters = NWParameters.udp + parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: port) + let listener = try NWListener(using: parameters) + let flows = Mutex<[NWConnection]>([]) + let heard = Mutex(0) + let started = AsyncStream.makeStream() + listener.stateUpdateHandler = { [listener] update in + switch update { + case .ready: started.continuation.yield(listener.port?.rawValue) + case .failed, .waiting: started.continuation.yield(nil) + default: break + } + } + listener.newConnectionHandler = { connection in + flows.withLock { $0.append(connection) } + connection.start(queue: .global()) + @Sendable func serve() { + connection.receiveMessage { data, _, _, error in + guard error == nil, let data else { return } + heard.withLock { $0 += 1 } + connection.send(content: data, completion: .contentProcessed { _ in }) + serve() + } + } + serve() + } + listener.start(queue: .global()) + var iterator = started.stream.makeAsyncIterator() + if let found = await iterator.next(), let found { + return (DiagEcho(listener: listener, port: found, flows: flows, heard: heard), attempt) + } + listener.cancel() + try await Task.sleep(for: .milliseconds(25)) } - var clients: [(connection: NWConnection, wing: Int)] = [] - for index in 0..<(idle * wings.count) { - let wing = index % wings.count - let connection = NWConnection(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: wings[wing].oscPort)!, using: .udp) - connection.start(queue: .global(qos: .userInitiated)) - clients.append((connection, wing)) - } - try await Task.sleep(for: .seconds(5)) + throw CancellationError() + } - var byPort: [UInt16: [Int]] = [:] // local port -> indexes into clients - var states: [String: Int] = [:] - for (index, client) in clients.enumerated() { - states["\(client.connection.state)", default: 0] += 1 - if let port = Diag.localPort(client.connection) { byPort[port, default: []].append(index) } - } - Diag.log("census2[idle=\(idle)] clients=\(clients.count) states=\(states) distinctLocalPorts=\(byPort.count)") - var special: Set = [] - for (port, indexes) in byPort where indexes.count > 1 || listenerPorts[port] != nil { - let targets = Set(indexes.map { clients[$0].wing }) - special.formUnion(targets) - let detail = indexes.prefix(4).map { "\(clients[$0].connection.state) path=\(String(describing: clients[$0].connection.currentPath?.status)) local=\(String(describing: clients[$0].connection.currentPath?.localEndpoint)) remote=\(String(describing: clients[$0].connection.currentPath?.remoteEndpoint))" } - Diag.log("census2[idle=\(idle)] local port \(port) used by \(indexes.count) clients to WINGs \(targets.sorted()) (their OSC ports \(targets.sorted().map { wings[$0].oscPort })); also a listener: \(listenerPorts[port] ?? "no"); \(detail)") + func closeFlows() { + flows.withLock { for flow in $0 { flow.cancel() }; $0 = [] } + } + + /// Sends one datagram to `port` from a new connection and reports what became of it. + static func ask(_ port: UInt16) async throws -> (state: String, local: UInt16, replied: Bool) { + let connection = NWConnection(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: port)!, using: .udp) + let replied = Mutex(false) + connection.start(queue: .global()) + connection.receiveMessage { data, _, _, _ in + if data != nil { replied.withLock { $0 = true } } } + connection.send(content: Data("ping".utf8), completion: .contentProcessed { _ in }) + try await Task.sleep(for: .milliseconds(600)) + var local: UInt16 = 0 + if case .hostPort(_, let found)? = connection.currentPath?.localEndpoint { local = found.rawValue } + let state = "\(connection.state)" + connection.cancel() + return (state, local, replied.withLock { $0 }) + } +} - var deaf: [Int] = [] - for (index, wing) in wings.enumerated() { - let driver = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .seconds(3)) - let knock = (try? await driver.identify()) != nil - let heardBefore = wing.queries.filter { $0 == "/io/out/USB/1/grp" }.count - let name = (try? await driver.sources(usbChannelCount: 1))?.first?.name - guard !knock || name != "Kick" else { continue } - deaf.append(index) - let heard = wing.queries.filter { $0 == "/io/out/USB/1/grp" }.count - heardBefore - let again = (try? await driver.sources(usbChannelCount: 1))?.first?.name - let other = WingDriver(endpoint: MixerEndpoint(host: "127.0.0.1", port: wing.port), oscPort: wing.oscPort, timeout: .seconds(3)) - let fresh = (try? await other.sources(usbChannelCount: 1))?.first?.name - let flows = DiagFlows.all.withLock { Array(($0[wing.oscPort] ?? []).suffix(10)) } - Diag.log("census2[idle=\(idle)] DEAF wing=\(index) ports=\(wing.port)/\(wing.oscPort) special=\(special.contains(index)) knock=\(knock) name=\(name ?? "nil") heardByFake=\(heard) sameDriverAgain=\(again ?? "nil") newDriver=\(fresh ?? "nil") flows=\(flows)") +@Suite("Diagnostics: leaked flow") +struct LeakedFlowTests { + @Test("A listener on a port that an unclosed flow elsewhere still names as its remote", arguments: 0..<12) + func leakedFlow(_ copy: Int) async throws { + let leaks = copy % 2 == 0 + let (first, _) = try await DiagEcho.listen() + let before = try await DiagEcho.ask(first.port) // its client is closed; `first` keeps the flow, as the fakes do + if !leaks { + first.closeFlows() + try await Task.sleep(for: .milliseconds(300)) } - Diag.log("census2[idle=\(idle)] deaf=\(deaf) special=\(special.sorted())") - for client in clients { client.connection.cancel() } + // A later fake is given the port that client used. + let (second, tries) = try await DiagEcho.listen(on: NWEndpoint.Port(rawValue: before.local)!) + let during = try await DiagEcho.ask(second.port) + let heardDuring = second.heard.withLock { $0 } + first.closeFlows() + try await Task.sleep(for: .milliseconds(300)) + let after = try await DiagEcho.ask(second.port) + Diag.log("leakedFlow[\(copy)] leaks=\(leaks) first=\(first.port) second=\(second.port) listenTries=\(tries) before=\(before) during=\(during) heardDuring=\(heardDuring) afterClosingFlows=\(after) heardAfter=\(second.heard.withLock { $0 })") + first.listener.cancel() + second.listener.cancel() + second.closeFlows() } } #endif