From 13b1be01a12ab5aa39e35edf4d11c84c80a136f5 Mon Sep 17 00:00:00 2001 From: Eric Dahl Date: Thu, 3 Dec 2026 03:00:04 -0500 Subject: [PATCH 1/3] 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 | 116 ++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 Tests/MixerLinkTests/DiagnosticsTests.swift diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift new file mode 100644 index 0000000..78f3e2d --- /dev/null +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -0,0 +1,116 @@ +#if canImport(Network) +import Foundation +import MixerLink +import Network +import Synchronization +import Testing + +// 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 + + init(listener: NWListener, port: UInt16, flows: Mutex<[NWConnection]>, heard: Mutex) { + self.listener = listener + self.port = port + self.flows = flows + self.heard = heard + } + + 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)) + } + throw CancellationError() + } + + 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 }) + } +} + +@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)) + } + // 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 From a3184b5cbb68911afb976bb3016be577213236cf Mon Sep 17 00:00:00 2001 From: Eric Dahl Date: Thu, 3 Dec 2026 03:04:51 -0500 Subject: [PATCH 2/3] DIAGNOSTICS, do not merge: compile fix Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VCgWWseQZtUzcSRzjqqQJQ --- Tests/MixerLinkTests/DiagnosticsTests.swift | 35 +++++++++++---------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift index 78f3e2d..c26587e 100644 --- a/Tests/MixerLinkTests/DiagnosticsTests.swift +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -18,14 +18,18 @@ enum Diag { final class DiagEcho: Sendable { let listener: NWListener let port: UInt16 - let flows: Mutex<[NWConnection]> - let heard: Mutex + let seen: Seen - init(listener: NWListener, port: UInt16, flows: Mutex<[NWConnection]>, heard: Mutex) { + final class Seen: Sendable { + let flows = Mutex<[NWConnection]>([]) + let heard = Mutex(0) + let replied = Mutex(false) + } + + init(listener: NWListener, port: UInt16, seen: Seen) { self.listener = listener self.port = port - self.flows = flows - self.heard = heard + self.seen = seen } static func listen(on port: NWEndpoint.Port = .any) async throws -> (echo: DiagEcho, tries: Int) { @@ -33,8 +37,7 @@ final class DiagEcho: Sendable { 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 seen = Seen() let started = AsyncStream.makeStream() listener.stateUpdateHandler = { [listener] update in switch update { @@ -44,12 +47,12 @@ final class DiagEcho: Sendable { } } listener.newConnectionHandler = { connection in - flows.withLock { $0.append(connection) } + seen.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 } + seen.heard.withLock { $0 += 1 } connection.send(content: data, completion: .contentProcessed { _ in }) serve() } @@ -59,7 +62,7 @@ final class DiagEcho: Sendable { 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) + return (DiagEcho(listener: listener, port: found, seen: seen), attempt) } listener.cancel() try await Task.sleep(for: .milliseconds(25)) @@ -68,16 +71,16 @@ final class DiagEcho: Sendable { } func closeFlows() { - flows.withLock { for flow in $0 { flow.cancel() }; $0 = [] } + seen.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) + let seen = Seen() connection.start(queue: .global()) connection.receiveMessage { data, _, _, _ in - if data != nil { replied.withLock { $0 = true } } + if data != nil { seen.replied.withLock { $0 = true } } } connection.send(content: Data("ping".utf8), completion: .contentProcessed { _ in }) try await Task.sleep(for: .milliseconds(600)) @@ -85,7 +88,7 @@ final class DiagEcho: Sendable { if case .hostPort(_, let found)? = connection.currentPath?.localEndpoint { local = found.rawValue } let state = "\(connection.state)" connection.cancel() - return (state, local, replied.withLock { $0 }) + return (state, local, seen.replied.withLock { $0 }) } } @@ -103,11 +106,11 @@ struct LeakedFlowTests { // 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 } + let heardDuring = second.seen.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 })") + Diag.log("leakedFlow[\(copy)] leaks=\(leaks) first=\(first.port) second=\(second.port) listenTries=\(tries) before=\(before) during=\(during) heardDuring=\(heardDuring) afterClosingFlows=\(after) heardAfter=\(second.seen.heard.withLock { $0 })") first.listener.cancel() second.listener.cancel() second.closeFlows() From 3d0605a825b6d48cb044dad6bbff82d5ea694994 Mon Sep 17 00:00:00 2001 From: Eric Dahl Date: Thu, 3 Dec 2026 03:11:48 -0500 Subject: [PATCH 3/3] DIAGNOSTICS, do not merge: variants Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VCgWWseQZtUzcSRzjqqQJQ --- Tests/MixerLinkTests/DiagnosticsTests.swift | 34 ++++++++++++--------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/Tests/MixerLinkTests/DiagnosticsTests.swift b/Tests/MixerLinkTests/DiagnosticsTests.swift index c26587e..bc27e4a 100644 --- a/Tests/MixerLinkTests/DiagnosticsTests.swift +++ b/Tests/MixerLinkTests/DiagnosticsTests.swift @@ -75,14 +75,14 @@ final class DiagEcho: Sendable { } /// 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) { + static func ask(_ port: UInt16, sends: Bool = true) async throws -> (state: String, local: UInt16, replied: Bool) { let connection = NWConnection(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: port)!, using: .udp) let seen = Seen() connection.start(queue: .global()) connection.receiveMessage { data, _, _, _ in if data != nil { seen.replied.withLock { $0 = true } } } - connection.send(content: Data("ping".utf8), completion: .contentProcessed { _ in }) + if sends { 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 } @@ -94,26 +94,32 @@ final class DiagEcho: Sendable { @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) + static let variants = ["firstClosed", "firstClientSilent", "probeSilent", "waits5s"] + + @Test("A listener on a port that a client of another listener used", arguments: 0..<12) func leakedFlow(_ copy: Int) async throws { - let leaks = copy % 2 == 0 + let variant = Self.variants[copy % 4] 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 { + let before = try await DiagEcho.ask(first.port, sends: variant != "firstClientSilent") + if variant == "firstClosed" { first.closeFlows() - try await Task.sleep(for: .milliseconds(300)) + first.listener.cancel() + try await Task.sleep(for: .milliseconds(500)) } - // 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.seen.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.seen.heard.withLock { $0 })") + if variant == "waits5s" { try await Task.sleep(for: .seconds(5)) } + let during = try await DiagEcho.ask(second.port, sends: variant != "probeSilent") + let again = try await DiagEcho.ask(second.port) + // What the fix would do: listen somewhere else. + let (third, _) = try await DiagEcho.listen() + let moved = try await DiagEcho.ask(third.port) + Diag.log("leak3[\(copy)] \(variant) first=\(first.port) second=\(second.port) third=\(third.port) listenTries=\(tries) before=\(before) during=\(during) again=\(again) moved=\(moved) heard=\(second.seen.heard.withLock { $0 })") first.listener.cancel() second.listener.cancel() + third.listener.cancel() + first.closeFlows() second.closeFlows() + third.closeFlows() } } #endif