From d4ea039cfcdf39ca9d0c4b61a9adadd481f2be42 Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Fri, 27 Nov 2026 14:53:05 -0800 Subject: [PATCH 1/6] feat(resolution): resolve destinations off the actor, under one deadline Forward resolution of trace, traceClassified, traceStream, ping, the TCP and UDP probes and multipath flows now runs in an executor slot through one primitive, awaitBlockingLookup, which STUN server-name lookups share. The caller's wait ends at an absolute deadline on DiscoveryClock (20 s for traces and ping, config.timeout from entry for the probes); cancellation, by the task or the trace handle, releases the caller at once, and a trace checks its handle at the handoff to probing. One inline classifier answers forced-family literals, mismatches, NULs, IPv4 loopback and unscoped non-link-local IPv6 literals without a resolver or seam; other literals use a one-slot Literal Lane so stalled name lookups cannot hold back a numeric destination. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01A8mvWou2vH56zDnkZkqT2X --- Sources/SwiftFTR/Hostname.swift | 189 ++++--- Sources/SwiftFTR/Multipath.swift | 6 +- Sources/SwiftFTR/Ping.swift | 8 +- Sources/SwiftFTR/STUN.swift | 34 +- Sources/SwiftFTR/TCPProbe.swift | 35 +- Sources/SwiftFTR/TestSeams.swift | 10 +- Sources/SwiftFTR/Traceroute.swift | 21 +- Sources/SwiftFTR/UDPProbe.swift | 37 +- Sources/SwiftFTR/Utils.swift | 48 ++ .../FaultInjectionCancellationTests.swift | 5 +- .../FaultInjectionEnrichmentTests.swift | 55 +- .../FaultInjectionProbeWindowTests.swift | 15 +- .../SwiftFTRTests/FaultInjectionSupport.swift | 20 +- .../ResolutionOffActorTests.swift | 484 ++++++++++++++++++ .../StreamingLifecycleTests.swift | 10 +- Tests/SwiftFTRTests/TraceLifecycleTests.swift | 10 +- 16 files changed, 787 insertions(+), 200 deletions(-) create mode 100644 Tests/SwiftFTRTests/ResolutionOffActorTests.swift diff --git a/Sources/SwiftFTR/Hostname.swift b/Sources/SwiftFTR/Hostname.swift index 2ae7ddad..e121e55d 100644 --- a/Sources/SwiftFTR/Hostname.swift +++ b/Sources/SwiftFTR/Hostname.swift @@ -129,96 +129,75 @@ internal func makeProbeSocketNonBlocking(sockfd: Int32) -> String? { } } -/// Dual-stack host resolver shared across `ping()`, `trace()`, and friends. +/// Dual-stack host resolver shared across `ping()`, `trace()`, and friends, synchronously: the +/// inline answers of ``inlineResolution(host:prefer:)``, otherwise ``blockingResolution(host:prefer:substitute:)`` +/// with the task's `TestSeams.resolveHost`. Operations resolve through +/// ``resolveDestination(_:prefer:until:clock:handle:)``, which runs the blocking branch in an +/// executor slot. /// /// Honors `PreferredFamily`: -/// - `.auto`: literal IPs are dispatched by `detectAddressFamily`; hostnames use -/// `getaddrinfo(AF_UNSPEC)` and take the first answer. Darwin's `getaddrinfo` -/// returns addresses in RFC 6724 source/destination ordering, so the first -/// answer is the system-preferred address for an outgoing connection from this -/// host — not an arbitrary one. On a dual-stack host this typically means v6 -/// first when a routable v6 path exists, v4 otherwise. +/// - `.auto`: hostnames and most literals use `getaddrinfo(AF_UNSPEC)` and take the first answer. +/// Darwin's `getaddrinfo` returns addresses in RFC 6724 source/destination ordering, so the +/// first answer is the system-preferred address for an outgoing connection from this host. A +/// literal goes through it too, so the system can synthesize an IPv6 address for an IPv4 +/// literal on a NAT64 network. /// - `.v4` / `.v6`: forces the family; throws `.resolutionFailed` if unavailable. /// /// The canonical printable form (`inet_ntop`) is returned in `ResolvedHost.canonical`, /// with link-local scope suffix preserved as `addr%ifname` (downstream contract). -/// -/// This helper lives at file scope rather than inside a particular executor so -/// `Ping`, `Trace`, and (eventually) the probes can share it without duplication -/// or cross-module coupling. The full resolver-dedup across `TCPProbe.swift` / -/// `UDPProbe.swift` is Stage 5 in `docs/IPV6.md`; this is the smaller extraction -/// that unblocks Stage 2 traceroute. internal func resolveHost(host: String, prefer: PreferredFamily) throws -> ResolvedHost { - if let substitute = TestSeams.resolveHost { return try substitute(host, prefer) } + if let answer = try inlineResolution(host: host, prefer: prefer) { return answer } + return try blockingResolution(host: host, prefer: prefer, substitute: TestSeams.resolveHost) +} + +/// The answer for `host` that needs no resolver, or `nil` when it needs one. Throws for a NUL and +/// for a literal of the other family than a forced one. +/// +/// Answered here: a literal of a forced family; under `.auto`, an IPv4 loopback literal, which +/// the system never synthesizes for (Libinfo's `_gai_nat64_can_v4_address_be_synthesized`), and +/// an IPv6 literal with no zone outside fe80::/10, fec0::/10 and ff00::/8, which `getaddrinfo` +/// returns unchanged. A zoned or scoped IPv6 literal (`getaddrinfo` turns `fe80:1::1` into +/// `fe80::1` with scope 1) and every other `.auto` IPv4 literal (NAT64) are left to the resolver. +/// Never consults a test seam, so it can run on any thread. +internal func inlineResolution(host: String, prefer: PreferredFamily) throws -> ResolvedHost? { // `getaddrinfo` and `inet_pton` would see only the text before a NUL and resolve that instead. guard !containsNUL(host) else { throw TracerouteError.resolutionFailed(host: host, details: "contains a NUL character") } - let detected = detectAddressFamily(host) - - // Force-mode fast paths: when the caller explicitly asked for v4 or v6, skip - // getaddrinfo and use the literal directly. This preserves the original - // behavior for callers that know their family and want microsecond resolution. - // - // In `.auto` mode we always go through getaddrinfo (even for literals) so - // macOS's resolver can synthesize a v4-mapped v6 address for v4 literals on - // NAT64 networks (RFC 6147 / Apple's CLAT). On dual-stack networks the - // resolver returns the v4 literal unchanged; on v6-only NAT64 networks it - // returns the synthesized v6 address and the trace/probe goes via v6 - // transparently — no caller code changes required. The extra getaddrinfo - // call costs ~tens of microseconds; the NAT64 transparency it buys is worth - // it (matches Apple's own guidance for IPv6-compatible apps). - if prefer == .v4 && detected == AF_INET { - var sin = sockaddr_in() - sin.sin_family = sa_family_t(AF_INET) - sin.sin_len = UInt8(MemoryLayout.size) - _ = inet_pton(AF_INET, host, &sin.sin_addr) - var storage = sockaddr_storage() - _ = withUnsafePointer(to: &sin) { src in - withUnsafeMutablePointer(to: &storage) { dst in - memcpy(dst, src, MemoryLayout.size) - } - } - return ResolvedHost( - family: AF_INET, address: storage, - addressLen: socklen_t(MemoryLayout.size), canonical: ipString(sin)) - } - if prefer == .v6 && detected == AF_INET6 { - let (bare, scopeID) = parseIPv6Scoped(host) - var sin6 = sockaddr_in6() - sin6.sin6_family = sa_family_t(AF_INET6) - sin6.sin6_len = UInt8(MemoryLayout.size) - sin6.sin6_scope_id = scopeID - _ = inet_pton(AF_INET6, bare, &sin6.sin6_addr) - var storage = sockaddr_storage() - _ = withUnsafePointer(to: &sin6) { src in - withUnsafeMutablePointer(to: &storage) { dst in - memcpy(dst, src, MemoryLayout.size) - } - } - return ResolvedHost( - family: AF_INET6, address: storage, - addressLen: socklen_t(MemoryLayout.size), - canonical: ipv6String(sin6.sin6_addr, scopeID: scopeID)) - } - // Mismatched literal vs preferred family throws. - if prefer == .v4 && detected == AF_INET6 { + switch (prefer, detectAddressFamily(host)) { + case (.v4, AF_INET): return ipv4Literal(host) + case (.v6, AF_INET6): return ipv6Literal(host) + case (.v4, AF_INET6): throw TracerouteError.resolutionFailed( host: host, details: "Preferred family v4 but literal is v6") - } - if prefer == .v6 && detected == AF_INET { + case (.v6, AF_INET): throw TracerouteError.resolutionFailed( host: host, details: "Preferred family v6 but literal is v4") + case (.auto, AF_INET): + var addr = in_addr() + _ = inet_pton(AF_INET, host, &addr) + return UInt32(bigEndian: addr.s_addr) >> 24 == 127 ? ipv4Literal(host) : nil + case (.auto, AF_INET6): + var addr = in6_addr() + guard !host.contains("%"), inet_pton(AF_INET6, host, &addr) == 1 else { return nil } + let (first, second) = (addr.__u6_addr.__u6_addr8.0, addr.__u6_addr.__u6_addr8.1) + let scoped = first == 0xFF || (first == 0xFE && second & 0x80 == 0x80) + return scoped ? nil : ipv6Literal(host) + default: + return nil } +} - // `.auto` mode (and any hostname path) — let getaddrinfo handle everything, - // including NAT64 synthesis for v4 literals on v6-only networks. The - // `AI_V4MAPPED | AI_ADDRCONFIG | AI_DEFAULT` flag set tells Darwin's resolver - // to synthesize a v4-mapped v6 address when only v6 is configured locally. +/// The resolver branch for `host`: `substitute` when a test supplies one, otherwise +/// `getaddrinfo`. Blocks for as long as the system resolver takes, so it runs in an executor slot. +internal func blockingResolution( + host: String, prefer: PreferredFamily, substitute: TestSeams.ResolveHost? +) throws -> ResolvedHost { + if let substitute { return try substitute(host, prefer) } + // `AI_V4MAPPED | AI_ADDRCONFIG` (`AI_DEFAULT`, not exposed in every Swift overlay) lets Darwin + // synthesize an IPv6 address for an IPv4 literal when only IPv6 is configured (NAT64). var hints = addrinfo() hints.ai_socktype = SOCK_DGRAM - // AI_DEFAULT == AI_V4MAPPED | AI_ADDRCONFIG. Hardcoded numeric form below - // because AI_DEFAULT isn't exposed in all Swift overlay versions. hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG switch prefer { case .v4: hints.ai_family = AF_INET @@ -263,3 +242,71 @@ internal func resolveHost(host: String, prefer: PreferredFamily) throws -> Resol throw TracerouteError.resolutionFailed( host: host, details: "No matching address for preferred family") } + +/// How long a trace or ping waits for its destination to resolve (docs/BLOCKING-IO.md, decision 7). +let forwardResolutionLimit: TimeInterval = 20 + +/// Resolves `host` for an operation: inline when ``inlineResolution(host:prefer:)`` answers, +/// otherwise in an executor slot, a literal on the Literal Lane (``literalLookupExecutor``) and a +/// name on the main executor, so stalled name lookups cannot hold back a numeric destination. +/// +/// The wait ends at `deadline` on `clock` with `resolutionFailed(details: "timed out")`, and at +/// once when the calling task is cancelled (`CancellationError`) or `handle` is (its reason's +/// error); a `getaddrinfo` already running finishes in its slot. The seam and the executor are +/// read here, on the async side. +internal func resolveDestination( + _ host: String, prefer: PreferredFamily, until deadline: TimeInterval, clock: DiscoveryClock, + handle: TraceHandle? = nil +) async throws -> ResolvedHost { + if let answer = try inlineResolution(host: host, prefer: prefer) { return answer } + let substitute = TestSeams.resolveHost + let lane = + detectAddressFamily(host) == -1 + ? nil : (TestSeams.literalLookupExecutor ?? literalLookupExecutor) + let found = try await withTraceCancellation(handle: handle) { + try await awaitBlockingLookup(until: deadline, clock: clock, on: lane) { + try blockingResolution(host: host, prefer: prefer, substitute: substitute) + } + } + guard let found else { + throw TracerouteError.resolutionFailed(host: host, details: "timed out") + } + return found +} + +/// A literal of IPv4, parsed without the resolver. `host` must be one (``detectAddressFamily(_:)``). +private func ipv4Literal(_ host: String) -> ResolvedHost { + var sin = sockaddr_in() + sin.sin_family = sa_family_t(AF_INET) + sin.sin_len = UInt8(MemoryLayout.size) + _ = inet_pton(AF_INET, host, &sin.sin_addr) + var storage = sockaddr_storage() + _ = withUnsafePointer(to: &sin) { src in + withUnsafeMutablePointer(to: &storage) { dst in + memcpy(dst, src, MemoryLayout.size) + } + } + return ResolvedHost( + family: AF_INET, address: storage, + addressLen: socklen_t(MemoryLayout.size), canonical: ipString(sin)) +} + +/// A literal of IPv6, with its `%zone` as the scope, parsed without the resolver. +private func ipv6Literal(_ host: String) -> ResolvedHost { + let (bare, scopeID) = parseIPv6Scoped(host) + var sin6 = sockaddr_in6() + sin6.sin6_family = sa_family_t(AF_INET6) + sin6.sin6_len = UInt8(MemoryLayout.size) + sin6.sin6_scope_id = scopeID + _ = inet_pton(AF_INET6, bare, &sin6.sin6_addr) + var storage = sockaddr_storage() + _ = withUnsafePointer(to: &sin6) { src in + withUnsafeMutablePointer(to: &storage) { dst in + memcpy(dst, src, MemoryLayout.size) + } + } + return ResolvedHost( + family: AF_INET6, address: storage, + addressLen: socklen_t(MemoryLayout.size), + canonical: ipv6String(sin6.sin6_addr, scopeID: scopeID)) +} diff --git a/Sources/SwiftFTR/Multipath.swift b/Sources/SwiftFTR/Multipath.swift index 50eba7f4..2447fa73 100644 --- a/Sources/SwiftFTR/Multipath.swift +++ b/Sources/SwiftFTR/Multipath.swift @@ -703,10 +703,8 @@ extension SwiftFTR { throw TracerouteError.sourceIPBindFailed(sourceIP: source, errno: errno, details: message) } } - // Literals resolve without `getaddrinfo` under a forced family. - if containsNUL(target) || detectAddressFamily(target) != -1 { - _ = try resolveHost(host: target, prefer: .v4) - } + // A literal, and a NUL, is decided without a resolver under the forced family. + _ = try inlineResolution(host: target, prefer: .v4) } /// Runs flow workers that reuse caches without escaping the caller's task group. diff --git a/Sources/SwiftFTR/Ping.swift b/Sources/SwiftFTR/Ping.swift index 39adfa5d..26e637fa 100644 --- a/Sources/SwiftFTR/Ping.swift +++ b/Sources/SwiftFTR/Ping.swift @@ -220,8 +220,12 @@ struct PingExecutor: Sendable { try config.validateForOperation() try Task.checkCancellation() - // 1. Resolve target, honoring PreferredFamily. - let resolved = try resolveHost(host: target, prefer: config.preferredFamily) + // 1. Resolve target, honoring PreferredFamily, off this thread, within the tracer's + // forward-resolution budget; `config.timeout` is the reply window and is not spent here. + let clock = DiscoveryClock.current + let resolved = try await resolveDestination( + target, prefer: config.preferredFamily, until: clock.now() + forwardResolutionLimit, + clock: clock) try Task.checkCancellation() // 2. Create datagram ICMP socket for the resolved family. diff --git a/Sources/SwiftFTR/STUN.swift b/Sources/SwiftFTR/STUN.swift index 62a9e2e3..9d89a910 100644 --- a/Sources/SwiftFTR/STUN.swift +++ b/Sources/SwiftFTR/STUN.swift @@ -491,7 +491,8 @@ func stunGetPublicIPv6( /// slot when the wait ends. let stunNameLookupLimit: TimeInterval = 20 -/// The clock every public-IP discovery deadline is on, and the only two things done with one. +/// The clock every public-IP discovery and forward-resolution deadline is on, and the only two +/// things done with one. /// A deadline is an absolute instant on `now`; `nil` is none. Every decision to send, submit or /// accept calls ``hasPassed(_:)`` immediately before it, and every blocking step calls it again /// as it returns; every wait for a deadline is ``sleep(until:)``. @@ -562,7 +563,8 @@ private func literalSTUNEndpoint(host: String, port: UInt16, family: Int32) -> ( } /// `server`'s name resolved for `family` on the executor, or `nil` when the lookup failed or its -/// wait ended first. With no time left before `deadline`, nothing is submitted. +/// wait ended first: at the earlier of `deadline` and ``stunNameLookupLimit``. With no time left, +/// nothing is submitted; an endpoint that arrives after the limit is not used. /// /// - Throws: `CancellationError` when the calling task is cancelled. func lookUpSTUNServer( @@ -572,30 +574,12 @@ func lookUpSTUNServer( let clock = DiscoveryClock.current let limit = min( deadline ?? .infinity, clock.now() + (TestSeams.stunNameLookupLimit ?? stunNameLookupLimit)) - // No time left: nothing is submitted, so no lookup starts after the deadline. - guard !clock.hasPassed(limit) else { return nil } - typealias Endpoint = (server: sockaddr_storage, serverLen: socklen_t) - // The wait ends at `limit` on the deadline's own clock, raced here rather than handed to the - // executor, whose timer is on Dispatch's uptime clock and stands still while the Mac sleeps. - let found = try await withThrowingTaskGroup(of: Endpoint?.self) { group -> Endpoint? in - group.addTask { - try await runDetachedBlockingIO { - guard !clock.hasPassed(limit) else { return nil } - let endpoint = resolve(server.host, server.port, family) - // A lookup that returns after its limit is not used, whichever side of the race wins. - return clock.hasPassed(limit) ? nil : endpoint - } - } - group.addTask { - await clock.sleep(until: limit) - return nil - } - // The first to finish decides; the other is cancelled, which withdraws a queued lookup. - defer { group.cancelAll() } - return try await group.next() ?? nil + // Raced on the deadline's own clock, not the executor's timer, which is on Dispatch's uptime + // clock and stands still while the Mac sleeps. + let found = try await awaitBlockingLookup(until: limit, clock: clock) { + resolve(server.host, server.port, family) } - try Task.checkCancellation() - return found + return found ?? nil } /// One server's attempt in a sweep: its name resolved (a numeric address needs no lookup), then diff --git a/Sources/SwiftFTR/TCPProbe.swift b/Sources/SwiftFTR/TCPProbe.swift index e1472a66..2b0a45c4 100644 --- a/Sources/SwiftFTR/TCPProbe.swift +++ b/Sources/SwiftFTR/TCPProbe.swift @@ -167,31 +167,40 @@ public func tcpProbe(config: TCPProbeConfig) async throws -> TCPProbeResult { try Task.checkCancellation() let startTime = Date() + // One budget: resolution's wait ends `config.timeout` after entry, and the connect gets what + // is left, measured at the handoff. + let clock = DiscoveryClock.current + let deadline = clock.now() + config.timeout + let failed = TCPProbeResult( + host: config.host, + resolvedIP: config.host, + port: config.port, + isReachable: false, + connectionState: .error, + rtt: nil, + error: "Failed to resolve hostname", + timestamp: startTime + ) - // Resolve via the shared dual-stack helper (Hostname.swift). + // Resolve via the shared dual-stack helper (Hostname.swift), off this thread. let resolved: ResolvedHost do { - resolved = try resolveHost(host: config.host, prefer: config.preferredFamily) + resolved = try await resolveDestination( + config.host, prefer: config.preferredFamily, until: deadline, clock: clock) } catch { try Task.checkCancellation() - return TCPProbeResult( - host: config.host, - resolvedIP: config.host, - port: config.port, - isReachable: false, - connectionState: .error, - rtt: nil, - error: "Failed to resolve hostname", - timestamp: startTime - ) + return failed } try Task.checkCancellation() + // Nothing left of the budget: no socket is made. + let remaining = deadline - clock.now() + guard remaining > 0 else { return failed } let result = try await performTCPProbe( resolved: resolved, port: config.port, - timeout: config.timeout, + timeout: remaining, startTime: startTime, interface: config.interface, sourceIP: config.sourceIP diff --git a/Sources/SwiftFTR/TestSeams.swift b/Sources/SwiftFTR/TestSeams.swift index 506dd583..7a0a432d 100644 --- a/Sources/SwiftFTR/TestSeams.swift +++ b/Sources/SwiftFTR/TestSeams.swift @@ -10,7 +10,9 @@ import Foundation /// /// See `docs/ROBUSTNESS-TESTING.md` for the battery that uses them. enum TestSeams { - /// Forward resolution of a trace, ping or probe destination, in place of `getaddrinfo`. + /// Forward resolution of a trace, ping or probe destination, in place of `getaddrinfo`. Runs in + /// an executor slot, as the lookup does; inputs answered without the resolver (forced-family + /// literals, mismatches, NULs, and the `.auto` literals `inlineResolution` names) never reach it. typealias ResolveHost = @Sendable (_ host: String, _ prefer: PreferredFamily) throws -> ResolvedHost @@ -77,6 +79,9 @@ enum TestSeams { /// Executor for every `runDetachedBlockingIO` call, in place of the process-wide one. @TaskLocal static var blockingIOExecutor: BlockingIOExecutor? + /// Executor for `.auto` literal destinations, in place of `literalLookupExecutor`. + @TaskLocal static var literalLookupExecutor: BlockingIOExecutor? + @TaskLocal static var fileControl: FileControl? @TaskLocal static var sendDatagram: SendDatagram? @@ -88,7 +93,8 @@ enum TestSeams { @TaskLocal static var connectSocket: ConnectSocket? /// `monotonicNow()` in place of the real clock for every public-IP discovery deadline (the - /// budget, admission, name lookups and each exchange's cutoff), so a test can move the clock past + /// budget, admission, name lookups and each exchange's cutoff) and every forward-resolution + /// deadline, so a test can move the clock past /// a deadline, as a system sleep does, without waiting for it. @TaskLocal static var monotonicClock: (@Sendable () -> TimeInterval)? diff --git a/Sources/SwiftFTR/Traceroute.swift b/Sources/SwiftFTR/Traceroute.swift index f5e34efb..8992c05f 100644 --- a/Sources/SwiftFTR/Traceroute.swift +++ b/Sources/SwiftFTR/Traceroute.swift @@ -708,8 +708,8 @@ public actor SwiftFTR { interfaceIndex = try validateInterface(interfaceName) } - // Resolve destination (dual-stack, honors config.preferredFamily). - let resolved = try resolveHost(host: host, prefer: config.preferredFamily) + // Resolve destination (dual-stack, honors config.preferredFamily), off this actor. + let resolved = try await resolveTraceDestination(host, handle: handle) try handle.checkCancellation() @@ -815,6 +815,17 @@ public actor SwiftFTR { } } + /// `host` resolved for this tracer's preferred family, waiting at most + /// ``forwardResolutionLimit`` and no longer than `handle` and the calling task allow. + private func resolveTraceDestination(_ host: String, handle: TraceHandle) async throws + -> ResolvedHost + { + let clock = DiscoveryClock.current + return try await resolveDestination( + host, prefer: config.preferredFamily, until: clock.now() + forwardResolutionLimit, + clock: clock, handle: handle) + } + // Validate network interface exists and is available internal func validateInterface(_ interfaceName: String) throws -> UInt32 { #if os(macOS) @@ -868,8 +879,10 @@ public actor SwiftFTR { "[SwiftFTR] Starting trace to \(host) with maxHops=\(maxHops), timeout=\(timeout)s, payloadSize=\(payloadSize)" ) } - // Resolve host (dual-stack, honors config.preferredFamily). - let resolved = try resolveHost(host: host, prefer: config.preferredFamily) + // Resolve host (dual-stack, honors config.preferredFamily), off this actor, then hand off to + // probing only if nothing has cancelled the trace meanwhile. + let resolved = try await resolveTraceDestination(host, handle: handle) + try handle.checkCancellation() if config.enableLogging { let famName = resolved.family == AF_INET6 ? "v6" : "v4" print("[SwiftFTR] Resolved \(host) → \(resolved.canonical) (\(famName))") diff --git a/Sources/SwiftFTR/UDPProbe.swift b/Sources/SwiftFTR/UDPProbe.swift index f9a0f3bf..528f864a 100644 --- a/Sources/SwiftFTR/UDPProbe.swift +++ b/Sources/SwiftFTR/UDPProbe.swift @@ -274,30 +274,41 @@ public func udpProbe(config: UDPProbeConfig) async throws -> UDPProbeResult { try config.validateForOperation() try Task.checkCancellation() let startTime = Date() + // One budget: resolution's wait ends `config.timeout` after entry, and the probe gets what is + // left, measured at the handoff. + let clock = DiscoveryClock.current + let deadline = clock.now() + config.timeout + let failed = UDPProbeResult( + host: config.host, + resolvedIP: config.host, + port: config.port, + isReachable: false, + rtt: nil, + responseType: nil, + error: "Failed to resolve hostname", + timestamp: startTime + ) - // Resolve via the shared dual-stack helper (Hostname.swift). + // Resolve via the shared dual-stack helper (Hostname.swift), off this thread. let resolved: ResolvedHost do { - resolved = try resolveHost(host: config.host, prefer: config.preferredFamily) + resolved = try await resolveDestination( + config.host, prefer: config.preferredFamily, until: deadline, clock: clock) } catch { try Task.checkCancellation() - return UDPProbeResult( - host: config.host, - resolvedIP: config.host, - port: config.port, - isReachable: false, - rtt: nil, - responseType: nil, - error: "Failed to resolve hostname", - timestamp: startTime - ) + return failed } + try Task.checkCancellation() + // Nothing left of the budget: no socket is made. + let remaining = deadline - clock.now() + guard remaining > 0 else { return failed } + let result = try await performUDPProbe( resolved: resolved, port: config.port, payload: config.payload, - timeout: config.timeout, + timeout: remaining, interface: config.interface, sourceIP: config.sourceIP ) diff --git a/Sources/SwiftFTR/Utils.swift b/Sources/SwiftFTR/Utils.swift index 95ce35cf..06702ecc 100644 --- a/Sources/SwiftFTR/Utils.swift +++ b/Sources/SwiftFTR/Utils.swift @@ -802,3 +802,51 @@ func runDetachedBlockingIO( let executor = TestSeams.blockingIOExecutor ?? blockingIOExecutor return try await executor.run(priority: priority, deadline: deadline, operation) } + +/// The executor that resolves literal destinations under `.auto` (NAT64 synthesis needs +/// `getaddrinfo`), one slot of its own, so name lookups stalled in every slot of +/// ``blockingIOExecutor`` cannot hold back a probe of a numeric address: the case a host app +/// diagnosing broken DNS relies on. +let literalLookupExecutor = BlockingIOExecutor( + maximumConcurrentOperations: 1, name: "com.networkweather.SwiftFTR.literal-lookup") + +/// Runs `lookup`, a blocking call, in a slot of `executor` (by default the task's +/// `TestSeams.blockingIOExecutor` or ``blockingIOExecutor``) and waits for it until `deadline`, an +/// instant on `clock`. +/// +/// Nothing is submitted once the deadline has passed, and the worker checks it again before it +/// calls `lookup`. When the wait ends, the order of precedence is: the calling task was +/// cancelled (`CancellationError`); the deadline has passed (`nil`, whatever `lookup` produced, +/// value or error); `lookup`'s own outcome. A queued lookup is withdrawn when the wait ends +/// first; one already running finishes in its slot and its outcome is dropped. Read seams and +/// the clock before calling: `lookup` runs on a worker, which cannot see task-locals. +func awaitBlockingLookup( + until deadline: TimeInterval, clock: DiscoveryClock, on executor: BlockingIOExecutor? = nil, + _ lookup: @escaping @Sendable () throws -> T +) async throws -> T? { + try Task.checkCancellation() + guard !clock.hasPassed(deadline) else { return nil } + let pool = executor ?? TestSeams.blockingIOExecutor ?? blockingIOExecutor + let outcome = await withTaskGroup(of: Result?.self) { group -> Result? in + group.addTask { + do { + return try await pool.run(priority: .userInitiated) { () -> Result? in + guard !clock.hasPassed(deadline) else { return nil } + return Result { try lookup() } + } + } catch { + return .failure(error) + } + } + group.addTask { + await clock.sleep(until: deadline) + return nil + } + // The first to finish decides; the other is cancelled, which withdraws a queued lookup. + defer { group.cancelAll() } + return await group.next() ?? nil + } + try Task.checkCancellation() + guard !clock.hasPassed(deadline), let outcome else { return nil } + return try outcome.get() +} diff --git a/Tests/SwiftFTRTests/FaultInjectionCancellationTests.swift b/Tests/SwiftFTRTests/FaultInjectionCancellationTests.swift index 603143d5..0711bfb7 100644 --- a/Tests/SwiftFTRTests/FaultInjectionCancellationTests.swift +++ b/Tests/SwiftFTRTests/FaultInjectionCancellationTests.swift @@ -196,7 +196,10 @@ struct FaultInjectionCancellationTests { return count } let receiving = await eventually(within: Self.watchdog) { - guard let handle = await tracer.activeTraces.first else { return false } + // Probes sent, so past resolution, whose wait also installs a handler. + guard network.probes.value > 0, let handle = await tracer.activeTraces.first else { + return false + } return await handle.hasCancellationHandler } #expect(receiving, "the stream never reached its receive window") diff --git a/Tests/SwiftFTRTests/FaultInjectionEnrichmentTests.swift b/Tests/SwiftFTRTests/FaultInjectionEnrichmentTests.swift index e06e993d..e9de03f2 100644 --- a/Tests/SwiftFTRTests/FaultInjectionEnrichmentTests.swift +++ b/Tests/SwiftFTRTests/FaultInjectionEnrichmentTests.swift @@ -205,58 +205,6 @@ struct FaultInjectionEnrichmentTests { #expect(topology.publicIP == nil) } - /// Who ends a trace stalled in forward resolution. - enum ResolutionCanceller: String, CaseIterable, CustomTestStringConvertible, Sendable { - case taskCancel, cancelActiveTraces - var testDescription: String { rawValue } - } - - @Test( - "A stalled forward resolution does not hold the tracer or its cancellation", - .disabled( - "finding 5 in docs/ROBUSTNESS-TESTING.md: getaddrinfo runs synchronously on the actor"), - arguments: ResolutionCanceller.allCases) - func forwardResolutionStall(canceller: ResolutionCanceller) async throws { - // One gated trace per cancellation source, so each source is the only thing that can end it. - let gate = StallGate() - defer { gate.open() } - let entered = FaultCounter() - let stall: TestSeams.ResolveHost = { host, _ in - entered.increment() - gate.wait(limit: 5) - throw TracerouteError.resolutionFailed(host: host, details: "stalled") - } - let tracer = offlineTracer(SwiftFTRConfig(maxHops: 4, maxWaitMs: 1000, noReverseDNS: true)) - - await TestSeams.$resolveHost.withValue(stall) { - let task = Task { try await tracer.trace(to: "slow-resolver.test") } - #expect(await eventually(within: 2) { entered.value > 0 }) - - // The cancellation call itself must not wait for the resolver: the tracer's, because it is - // a call on the actor the resolver holds; the caller's, because it is synchronous. - let (_, callLag) = await measure { - switch canceller { - case .taskCancel: task.cancel() - case .cancelActiveTraces: await tracer.cancelActiveTraces() - } - } - #expect(callLag < 0.5, "cancelling took \(callLag)s behind a resolver stall") - - let cancelledAt = monotonicNow() - let outcome = await task.result - let lag = monotonicNow() - cancelledAt - #expect(lag < 0.5, "a trace stalled in resolution returned \(lag)s after cancellation") - switch (canceller, outcome) { - case (.taskCancel, .failure(let error)): - #expect(error is CancellationError, "\(error)") - case (.cancelActiveTraces, .failure(TracerouteError.cancelled)): - break - default: - Issue.record("\(canceller): \(outcome)") - } - } - } - // MARK: A full blocking-I/O executor /// Fills a private single-slot executor with a call that holds it for up to 20 s. Returns the @@ -300,7 +248,8 @@ struct FaultInjectionEnrichmentTests { try await daemon.install { try await network.install { try await measure(within: Self.watchdog) { - try await tracer.traceClassified(to: "fake.test", resolver: EmptyASNResolver()) + // A loopback literal resolves without a slot; a name would queue behind the occupant. + try await tracer.traceClassified(to: "127.0.0.1", resolver: EmptyASNResolver()) }.0 } } diff --git a/Tests/SwiftFTRTests/FaultInjectionProbeWindowTests.swift b/Tests/SwiftFTRTests/FaultInjectionProbeWindowTests.swift index 715b3240..f1d2de8b 100644 --- a/Tests/SwiftFTRTests/FaultInjectionProbeWindowTests.swift +++ b/Tests/SwiftFTRTests/FaultInjectionProbeWindowTests.swift @@ -401,19 +401,22 @@ struct FaultInjectionProbeWindowTests { } } - // The destination is a loopback literal: an operation that went around the substitute would - // resolve it locally and fail the details check, without asking any DNS server. + // The destination is a name with a 64-character label: an operation that went around the + // substitute would have it rejected by the system resolver, without a query, and fail the + // details check. (A loopback literal is answered without the resolver, so the seam would + // never see it.) + let host = String(repeating: "a", count: 64) + ".test" await TestSeams.$resolveHost.withValue(fail) { - await expectResolutionFailure("trace") { _ = try await tracer.trace(to: "127.0.0.1") } + await expectResolutionFailure("trace") { _ = try await tracer.trace(to: host) } await expectResolutionFailure("traceClassified") { - _ = try await tracer.traceClassified(to: "127.0.0.1", resolver: EmptyASNResolver()) + _ = try await tracer.traceClassified(to: host, resolver: EmptyASNResolver()) } await expectResolutionFailure("traceStream") { - for try await _ in tracer.traceStream(to: "127.0.0.1", config: Self.streamPastWatchdog) {} + for try await _ in tracer.traceStream(to: host, config: Self.streamPastWatchdog) {} } await expectResolutionFailure("ping") { _ = try await tracer.ping( - to: "127.0.0.1", config: PingConfig(count: 1, timeout: pingTimeout)) + to: host, config: PingConfig(count: 1, timeout: pingTimeout)) } } #expect(await tracer.activeTraces.isEmpty) diff --git a/Tests/SwiftFTRTests/FaultInjectionSupport.swift b/Tests/SwiftFTRTests/FaultInjectionSupport.swift index 1213323a..20599e36 100644 --- a/Tests/SwiftFTRTests/FaultInjectionSupport.swift +++ b/Tests/SwiftFTRTests/FaultInjectionSupport.swift @@ -400,7 +400,8 @@ final class FakeICMPNetwork: @unchecked Sendable { } /// Runs `body` with forward resolution and the ICMP socket factory pointed at this network, or - /// at `socketFactory` when one is given. + /// at `socketFactory` when one is given. Resolution is substituted only where the library asks + /// a resolver: a name, or a literal it does not answer itself (see `inlineResolution`). /// /// Public-IP discovery is substituted too: by the test's own substitute when one is bound, and /// otherwise by one that fails at once, so a classified trace inside `body` can never fall @@ -424,7 +425,7 @@ final class FakeICMPNetwork: @unchecked Sendable { return try await TestSeams.$resolveHost.withValue(resolve) { try await TestSeams.$makeICMPSocket.withValue(makeSocket) { try await TestSeams.$discoverPublicIP.withValue(discover) { - try await TestSeams.$sendProbe.withValue(isolated ? Self.connectingSend : nil) { + try await TestSeams.$sendProbe.withValue(isolated ? connectingSend : nil) { try await body() } } @@ -439,6 +440,21 @@ final class FakeICMPNetwork: @unchecked Sendable { /// can reach the socket. Production ICMP sockets are never connected; a connected one whose peer /// is gone reports ECONNREFUSED once on `recv`, which trace and ping both read as "nothing more /// to read now", and no test stops its network before the operation has closed its socket. + /// ``connectingSend`` aimed at this network whatever address the library resolved, so an + /// operation whose literal destination is answered without the resolution seam (and so has no + /// port) still reaches it. + var connectingSend: TestSeams.SendProbe { + let (address, length) = loopbackAddress(family: family, port: port) + return { fd, bytes, _, _ in + var own = address + return withUnsafePointer(to: &own) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + Self.connectingSend(fd, bytes, $0, length) + } + } + } + } + static let connectingSend: TestSeams.SendProbe = { fd, bytes, destination, length in var peer = sockaddr_storage() var peerLength = socklen_t(MemoryLayout.size) diff --git a/Tests/SwiftFTRTests/ResolutionOffActorTests.swift b/Tests/SwiftFTRTests/ResolutionOffActorTests.swift new file mode 100644 index 00000000..59027b2f --- /dev/null +++ b/Tests/SwiftFTRTests/ResolutionOffActorTests.swift @@ -0,0 +1,484 @@ +import Foundation +import Testing + +@testable import SwiftFTR + +#if canImport(Darwin) + import Darwin +#endif + +/// Forward resolution runs in an executor slot, its wait ends at one deadline, and cancellation +/// releases the caller during it (docs/BLOCKING-IO.md, Resolution Off The Actor; finding 5 in +/// docs/ROBUSTNESS-TESTING.md). Every stalled lookup waits on a gate that holds for `hold`, three +/// times the `watchdog`, so a call that returns within the watchdog returned while it was shut. +@Suite("Resolution off the actor") +struct ResolutionOffActorTests { + static let watchdog: TimeInterval = 20 + static let hold: TimeInterval = 60 + + /// A resolution seam that counts its entries, waits on `gate`, then fails. + static func stalling(_ gate: StallGate, entered: FaultCounter) -> TestSeams.ResolveHost { + { host, _ in + entered.increment() + gate.wait(limit: hold) + throw TracerouteError.resolutionFailed(host: host, details: "stalled") + } + } + + /// An ICMP socket factory that counts its calls and makes nothing, so no test here can send. + static func noSockets(_ count: FaultCounter) -> TestSeams.MakeICMPSocket { + { _ in + count.increment() + throw TracerouteError.socketCreateFailed(errno: EPERM, details: "test: no sockets") + } + } + + static func isTimeout(_ error: Error) -> Bool { + if case TracerouteError.resolutionFailed(_, let details) = error { + return details == "timed out" + } + return false + } + + enum Operation: String, CaseIterable, CustomTestStringConvertible, Sendable { + case trace, stream + var testDescription: String { rawValue } + } + + enum Canceller: String, CaseIterable, CustomTestStringConvertible, Sendable { + case callerTask, cancelActiveTraces, networkChanged + var testDescription: String { rawValue } + } + + // MARK: Off the actor, and released at once + + @Test( + "A stalled forward resolution does not hold the tracer or its cancellation", + arguments: Operation.allCases, Canceller.allCases) + func forwardResolutionStall(operation: Operation, canceller: Canceller) async throws { + let gate = StallGate() + defer { gate.open() } + let entered = FaultCounter() + let sockets = FaultCounter() + let executor = BlockingIOExecutor(maximumConcurrentOperations: 2, name: "test.rdo-stall") + let tracer = offlineTracer(SwiftFTRConfig(maxHops: 4, maxWaitMs: 1000, noReverseDNS: true)) + let stall = Self.stalling(gate, entered: entered) + + try await TestSeams.$blockingIOExecutor.withValue(executor) { + try await TestSeams.$makeICMPSocket.withValue(Self.noSockets(sockets)) { + try await TestSeams.$resolveHost.withValue(stall) { + let task = Task { () async throws -> Int in + switch operation { + case .trace: + _ = try await tracer.trace(to: "slow-resolver.test") + return 0 + case .stream: + var count = 0 + for try await _ in tracer.traceStream(to: "slow-resolver.test") { count += 1 } + return count + } + } + #expect(await eventually(within: Self.watchdog) { entered.value > 0 }) + + // The cancellation itself is inside the watchdog: the tracer's because it is a call on + // the actor a stalled resolution would hold, the caller's because the trace must return. + let (outcome, _) = try await measure(within: Self.watchdog) { + switch canceller { + case .callerTask: task.cancel() + case .cancelActiveTraces: await tracer.cancelActiveTraces() + case .networkChanged: await tracer.networkChanged() + } + return await task.result + } + switch (operation, canceller, outcome) { + case (.stream, .callerTask, .success(let hops)): + #expect(hops == 0) + case (.trace, .callerTask, .failure(let error)): + #expect(error is CancellationError, "\(error)") + case (_, .cancelActiveTraces, .failure(TracerouteError.cancelled)), + (_, .networkChanged, .failure(TracerouteError.cancelled)): + break + default: + Issue.record("\(operation) / \(canceller): \(outcome)") + } + } + } + } + #expect(sockets.value == 0, "a trace cancelled during resolution went on to make its socket") + #expect(await eventually(within: Self.watchdog) { await tracer.activeTraces.isEmpty }) + } + + @Test("Pings waiting on resolution hold no cooperative thread") + func resolutionHoldsNoPoolThread() async throws { + let gate = StallGate() + defer { gate.open() } + let entered = FaultCounter() + let released = FaultCounter() + let sockets = FaultCounter() + let count = ProcessInfo.processInfo.activeProcessorCount + 2 + let executor = BlockingIOExecutor(maximumConcurrentOperations: count, name: "test.rdo-pool") + let stall: TestSeams.ResolveHost = { host, _ in + entered.increment() + gate.wait(limit: Self.hold) + released.increment() + throw TracerouteError.resolutionFailed(host: host, details: "stalled") + } + let tracer = offlineTracer(SwiftFTRConfig()) + + let pings = TestSeams.$blockingIOExecutor.withValue(executor) { + TestSeams.$makeICMPSocket.withValue(Self.noSockets(sockets)) { + TestSeams.$resolveHost.withValue(stall) { + (0.. TimeInterval = { 1_000 } + + try await TestSeams.$blockingIOExecutor.withValue(held.executor) { + try await TestSeams.$literalLookupExecutor.withValue(lane) { + try await TestSeams.$monotonicClock.withValue(frozen) { + try await network.install { + let (results, _) = try await measure(within: Self.watchdog) { + let traces = [ + try await auto.trace(to: "127.0.0.1"), try await forced.trace(to: "127.0.0.1"), + ] + let pings = [ + try await auto.ping(to: "127.0.0.1", config: PingConfig(count: 1)), + try await auto.ping(to: "192.0.2.1", config: PingConfig(count: 1)), + ] + return (traces.map(\.reached), pings.map(\.statistics.received)) + } + #expect(results.0 == [true, true]) + #expect(results.1 == [1, 1]) + } + } + } + } + #expect(held.executor.submissions.value - mainBefore == 0, "a literal waited for a main slot") + // Only the non-loopback `.auto` literal needs the resolver, for NAT64. + #expect(lane.submissions.value - laneBefore == 1) + #expect(held.finished.value == 0) + } + + @Test("Inline answers equal the resolver's, and only resolver inputs reach the seam") + func inlineParity() async throws { + let inline = [ + "127.0.0.1", "127.1.2.3", "::1", "::", "2001:db8::5", "2606:4700:4700::1111", "fd00::1", + "::ffff:192.0.2.1", "64:ff9b::c000:201", + ] + let resolver = [ + "192.0.2.1", "10.0.0.1", "fe80::1", "fe80:1::1", "ff02::1", "fec0::1", "::1%lo0", + ] + // Literals only, so `getaddrinfo` asks no DNS server. Run on a thread of its own: it blocks. + let mismatches = try await onOwnThread { () -> [String] in + var found: [String] = [] + for host in inline { + guard let mine = try inlineResolution(host: host, prefer: .auto) else { + found.append("\(host): not answered inline") + continue + } + let system = try blockingResolution(host: host, prefer: .auto, substitute: nil) + var a = mine.address + var b = system.address + let sameBytes = + mine.addressLen == system.addressLen + && memcmp(&a, &b, Int(mine.addressLen)) == 0 + if !sameBytes || mine.canonical != system.canonical || mine.family != system.family { + found.append("\(host): inline \(mine.canonical) vs getaddrinfo \(system.canonical)") + } + } + for host in resolver where try inlineResolution(host: host, prefer: .auto) != nil { + found.append("\(host): answered inline") + } + return found + } + #expect(mismatches.isEmpty, "\(mismatches)") + + let consulted = FaultCounter() + let seam: TestSeams.ResolveHost = { host, prefer in + consulted.increment() + return try blockingResolution(host: "127.0.0.1", prefer: .v4, substitute: nil) + } + let forcedAndInline = + inline.map { ($0, PreferredFamily.auto) } + [ + ("192.0.2.1", .v4), ("::1", .v6), ("::1", .v4), ("192.0.2.1", .v6), ("bad\u{0}name", .auto), + ] + TestSeams.$resolveHost.withValue(seam) { + for (host, prefer) in forcedAndInline { _ = try? resolveHost(host: host, prefer: prefer) } + } + #expect(consulted.value == 0, "an input answered without a resolver reached the seam") + TestSeams.$resolveHost.withValue(seam) { + _ = try? resolveHost(host: "fe80:1::1", prefer: .auto) + _ = try? resolveHost(host: "name.test", prefer: .v4) + } + #expect(consulted.value == 2) + } + + // MARK: One deadline + + @Test("A lookup that outlives its deadline releases the ping while it is still running") + func deadlineEndsTheWait() async throws { + let gate = StallGate() + defer { gate.open() } + let entered = FaultCounter() + let clock = MovableClock() + let executor = BlockingIOExecutor(maximumConcurrentOperations: 1, name: "test.rdo-deadline") + let tracer = offlineTracer(SwiftFTRConfig()) + + let outcome = try await TestSeams.$blockingIOExecutor.withValue(executor) { + try await TestSeams.$monotonicClock.withValue(clock.now) { + try await TestSeams.$resolveHost.withValue(Self.stalling(gate, entered: entered)) { + let task = Task { try await tracer.ping(to: "gated.test", config: PingConfig(count: 1)) } + #expect(await eventually(within: Self.watchdog) { entered.value == 1 }) + return try await measure(within: Self.watchdog) { + clock.jump(by: forwardResolutionLimit + 1) + return await task.result + }.0 + } + } + } + guard case .failure(let error) = outcome, Self.isTimeout(error) else { + Issue.record("expected the resolution timeout, got \(outcome)") + return + } + } + + @Test("A lookup still queued at its deadline times out and is never run") + func deadlineWhileQueued() async throws { + let held = await HeldExecutor.fill(limit: Self.hold) + defer { held.release() } + let entered = FaultCounter() + let clock = MovableClock() + let seam: TestSeams.ResolveHost = { host, _ in + entered.increment() + throw TracerouteError.resolutionFailed(host: host, details: "ran") + } + let tracer = offlineTracer(SwiftFTRConfig()) + let before = held.executor.submissions.value + + let outcome = try await TestSeams.$blockingIOExecutor.withValue(held.executor) { + try await TestSeams.$monotonicClock.withValue(clock.now) { + try await TestSeams.$resolveHost.withValue(seam) { + let task = Task { try await tracer.ping(to: "queued.test", config: PingConfig(count: 1)) } + #expect( + await eventually(within: Self.watchdog) { held.executor.submissions.value > before }) + return try await measure(within: Self.watchdog) { + clock.jump(by: forwardResolutionLimit + 1) + return await task.result + }.0 + } + } + } + if case .failure(let error) = outcome, Self.isTimeout(error) { + } else { + Issue.record("expected the resolution timeout, got \(outcome)") + } + held.release() + // A sentinel queued after the expired lookup runs only once the workers have reached it. + _ = try await held.executor.run(priority: .userInitiated) {} + #expect(entered.value == 0, "a lookup whose wait had ended was run") + } + + @Test( + "An outcome that arrives after the deadline is a timeout, value or error", + arguments: [false, true]) + func lateOutcomeIsTimeout(throwing: Bool) async throws { + let clock = MovableClock() + let executor = BlockingIOExecutor(maximumConcurrentOperations: 1, name: "test.rdo-late") + let late: TestSeams.ResolveHost = { host, _ in + clock.jump(by: 30) + if throwing { throw TracerouteError.resolutionFailed(host: host, details: "late NXDOMAIN") } + return try blockingResolution(host: "127.0.0.1", prefer: .v4, substitute: nil) + } + let outcome = await TestSeams.$blockingIOExecutor.withValue(executor) { + await TestSeams.$monotonicClock.withValue(clock.now) { + await TestSeams.$resolveHost.withValue(late) { + let now = DiscoveryClock.current + return await resultOf { + try await resolveDestination( + "late.test", prefer: .auto, until: now.now() + 20, clock: now) + } + } + } + } + if case .failure(let error) = outcome, Self.isTimeout(error) { + } else { + Issue.record("expected the resolution timeout, got \(outcome)") + } + } + + // MARK: Cancellation + + @Test( + "A ping cancelled during its lookup reports the cancellation, even when the lookup then fails") + func pingCancelledDuringLookup() async throws { + let gate = StallGate() + defer { gate.open() } + let entered = FaultCounter() + let executor = BlockingIOExecutor(maximumConcurrentOperations: 1, name: "test.rdo-cancel") + let tracer = offlineTracer(SwiftFTRConfig()) + + let outcome = try await TestSeams.$blockingIOExecutor.withValue(executor) { + try await TestSeams.$resolveHost.withValue(Self.stalling(gate, entered: entered)) { + let task = Task { try await tracer.ping(to: "gated.test", config: PingConfig(count: 1)) } + #expect(await eventually(within: Self.watchdog) { entered.value == 1 }) + return try await measure(within: Self.watchdog) { + task.cancel() + gate.open() // the lookup now fails; the cancellation still decides + return await task.result + }.0 + } + } + if case .failure(let error) = outcome, error is CancellationError { + } else { + Issue.record("expected CancellationError, got \(outcome)") + } + } + + @Test("A ping cancelled while its lookup is queued is released and the lookup never runs") + func pingCancelledWhileQueued() async throws { + let held = await HeldExecutor.fill(limit: Self.hold) + defer { held.release() } + let entered = FaultCounter() + let seam: TestSeams.ResolveHost = { host, _ in + entered.increment() + throw TracerouteError.resolutionFailed(host: host, details: "ran") + } + let tracer = offlineTracer(SwiftFTRConfig()) + let before = held.executor.submissions.value + + let outcome = try await TestSeams.$blockingIOExecutor.withValue(held.executor) { + try await TestSeams.$resolveHost.withValue(seam) { + let task = Task { try await tracer.ping(to: "queued.test", config: PingConfig(count: 1)) } + #expect( + await eventually(within: Self.watchdog) { held.executor.submissions.value > before }) + return try await measure(within: Self.watchdog) { + task.cancel() + return await task.result + }.0 + } + } + if case .failure(let error) = outcome, error is CancellationError { + } else { + Issue.record("expected CancellationError, got \(outcome)") + } + held.release() + _ = try await held.executor.run(priority: .userInitiated) {} + #expect(entered.value == 0, "a withdrawn lookup was run") + } + + @Test("A trace cancelled before probing makes no socket", arguments: ["127.0.0.1", "::1"]) + func handoffCheck(host: String) async throws { + let sockets = FaultCounter() + let tracer = offlineTracer(SwiftFTRConfig(maxHops: 2, maxWaitMs: 1000, noReverseDNS: true)) + let outcome = await TestSeams.$makeICMPSocket.withValue(Self.noSockets(sockets)) { + let task = Task { () async throws -> TraceResult in + withUnsafeCurrentTask { $0?.cancel() } + return try await tracer.trace(to: host) + } + return await task.result + } + if case .failure(let error) = outcome, error is CancellationError { + } else { + Issue.record("expected CancellationError, got \(outcome)") + } + #expect(sockets.value == 0, "a cancelled trace made its socket after resolving \(host)") + } + + // MARK: Probes spend one budget + + /// Counts `fcntl` calls, which the TCP and UDP probes make on their socket right after creating it. + static func countingFileControl(_ count: FaultCounter) -> TestSeams.FileControl { + { fd, command, argument in + count.increment() + return fcntl(fd, command, argument) + } + } + + @Test("A probe whose lookup outlives its timeout reports the failure and sets up no socket") + func probeResolutionTimeout() async throws { + let clock = MovableClock() + let configured = FaultCounter() + let executor = BlockingIOExecutor(maximumConcurrentOperations: 1, name: "test.rdo-probe") + let late: TestSeams.ResolveHost = { _, _ in + clock.jump(by: 61) + return try blockingResolution(host: "127.0.0.1", prefer: .v4, substitute: nil) + } + let (tcp, udp) = try await TestSeams.$blockingIOExecutor.withValue(executor) { + try await TestSeams.$monotonicClock.withValue(clock.now) { + try await TestSeams.$fileControl.withValue(Self.countingFileControl(configured)) { + try await TestSeams.$resolveHost.withValue(late) { + try await measure(within: Self.watchdog) { + ( + try await tcpProbe(config: TCPProbeConfig(host: "late.test", port: 9, timeout: 60)), + try await udpProbe(config: UDPProbeConfig(host: "late.test", port: 9, timeout: 60)) + ) + }.0 + } + } + } + } + #expect(tcp.connectionState == .error && !tcp.isReachable && tcp.rtt == nil) + #expect(tcp.error == "Failed to resolve hostname" && tcp.resolvedIP == "late.test") + #expect(!udp.isReachable && udp.rtt == nil && udp.responseType == nil) + #expect(udp.error == "Failed to resolve hostname" && udp.resolvedIP == "late.test") + #expect(configured.value == 0, "a probe set up a socket with none of its timeout left") + } + + @Test("A UDP probe waits only for what resolution left of its timeout") + func probeSpendsOneBudget() async throws { + let clock = MovableClock() + let silent = try bindLoopback(family: AF_INET, type: SOCK_DGRAM) + defer { close(silent.fd) } + let executor = BlockingIOExecutor(maximumConcurrentOperations: 1, name: "test.rdo-budget") + let slow: TestSeams.ResolveHost = { _, _ in + clock.jump(by: 59.5) + return try blockingResolution(host: "127.0.0.1", prefer: .v4, substitute: nil) + } + // The timeout outlasts the watchdog, so a probe given all of it fails the watchdog. + let result = try await TestSeams.$blockingIOExecutor.withValue(executor) { + try await TestSeams.$monotonicClock.withValue(clock.now) { + try await TestSeams.$resolveHost.withValue(slow) { + try await measure(within: Self.watchdog) { + try await udpProbe( + config: UDPProbeConfig(host: "silent.test", port: Int(silent.port), timeout: 60)) + }.0 + } + } + } + #expect(result.responseType == "timeout", "\(result)") + #expect(result.resolvedIP == "127.0.0.1") + } +} diff --git a/Tests/SwiftFTRTests/StreamingLifecycleTests.swift b/Tests/SwiftFTRTests/StreamingLifecycleTests.swift index 789df2b9..b1bfe384 100644 --- a/Tests/SwiftFTRTests/StreamingLifecycleTests.swift +++ b/Tests/SwiftFTRTests/StreamingLifecycleTests.swift @@ -87,7 +87,10 @@ struct StreamingLifecycleTests { } let receiving = await waitUntil { - guard let handle = await tracer.activeTraces.first else { return false } + // Probes sent, so past resolution, whose wait also installs a handler. + guard network.probes.value > 0, let handle = await tracer.activeTraces.first else { + return false + } return await handle.hasCancellationHandler } try #require(receiving, "The streaming receive operation should start before cancellation") @@ -134,7 +137,10 @@ struct StreamingLifecycleTests { } let receiving = await waitUntil { - guard let handle = await tracer.activeTraces.first else { return false } + // Probes sent, so past resolution, whose wait also installs a handler. + guard network.probes.value > 0, let handle = await tracer.activeTraces.first else { + return false + } return await handle.hasCancellationHandler } try #require(receiving, "The streaming receive operation should start before cancellation") diff --git a/Tests/SwiftFTRTests/TraceLifecycleTests.swift b/Tests/SwiftFTRTests/TraceLifecycleTests.swift index d64a95cd..628d46e2 100644 --- a/Tests/SwiftFTRTests/TraceLifecycleTests.swift +++ b/Tests/SwiftFTRTests/TraceLifecycleTests.swift @@ -46,7 +46,10 @@ struct TraceLifecycleTests { } let receiving = await waitUntil { - guard let handle = await tracer.activeTraces.first else { return false } + // Probes sent, so past resolution, whose wait also installs a handler. + guard network.probes.value > 0, let handle = await tracer.activeTraces.first else { + return false + } return await handle.hasCancellationHandler } #expect(receiving, "The streaming trace should start before cancellation") @@ -149,7 +152,10 @@ struct TraceLifecycleTests { } let receiving = await waitUntil { - guard let handle = await tracer.activeTraces.first else { return false } + // Probes sent, so past resolution, whose wait also installs a handler. + guard network.probes.value > 0, let handle = await tracer.activeTraces.first else { + return false + } return await handle.hasCancellationHandler } #expect(receiving, "The classified trace should reach its receive window before cancellation") From 20bdc0a447e80f5f12f5691e7b39d5696e151977 Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Fri, 27 Nov 2026 14:58:06 -0800 Subject: [PATCH 2/6] docs(resolution): forward resolution off the actor, under one deadline Changelog bullet and upgrade-guide entry for each changed caller-visible behaviour, finding 5 marked fixed with its tests, the API reference's PreferredFamily notes, and a ROADMAP line for an absolute cutoff in the TCP and UDP probe operations. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01A8mvWou2vH56zDnkZkqT2X --- CHANGELOG.md | 10 +++++++ README.md | 4 +-- ROADMAP.md | 12 ++++---- .../SwiftFTR/SwiftFTR.docc/MigratingTo019.md | 28 +++++++++++++++++++ docs/README.md | 2 +- docs/ROBUSTNESS-TESTING.md | 18 ++++++------ docs/reference/AI_REFERENCE.md | 10 +++++-- 7 files changed, 63 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 981b8f7b..9208cb7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,16 @@ Unreleased ### Behavior changes +- **Forward resolution no longer runs on the tracer actor or a cooperative thread.** `trace`, + `traceClassified`, `traceStream`, `ping`, `tcpProbe`, `udpProbe` and multipath flows resolve + their destination in an executor slot. The wait ends at a deadline: 20 s for traces and ping, + `config.timeout` from entry for the probes, whose connect or receive window is what resolution + leaves. A trace or ping whose lookup times out throws `resolutionFailed` with details + `"timed out"`; a probe reports its usual resolution failure and opens no socket. Cancelling the + task, `cancelActiveTraces()` or `networkChanged()` during resolution returns at once, and a + ping cancelled during its lookup throws `CancellationError` even if the lookup then fails. + Names share the eight executor slots with STUN server names; literals never queue behind + names (finding 5 in docs/ROBUSTNESS-TESTING.md). - **The library's public-IP resolver asks every STUN server at once, and the first answer decides** (David, 2026-11-24: "return as decisive the first public IP we get … The goal is to be as fast as possible"). Each server's request goes out as soon as its name has resolved, on diff --git a/README.md b/README.md index 396b573e..ee450499 100644 --- a/README.md +++ b/README.md @@ -467,13 +467,13 @@ Every tracked Markdown file has exactly one entry in one of these indexes. - [Bufferbloat](Sources/SwiftFTR/SwiftFTR.docc/Bufferbloat.md): `testBufferbloat` usage, load generation, grading and RPM calculation, video-call severity and baseline-only bound mode. (updated 2026-11-22; update when: grading thresholds, the RPM method, default load endpoints or `BufferbloatConfig` change) - [Multipath](Sources/SwiftFTR/SwiftFTR.docc/Multipath.md): `discoverPaths` usage, topology analysis, ICMP-versus-UDP limitations and the IPv4-only restriction. (updated 2026-11-21; update when: multipath gains UDP or IPv6 support, or `MultipathConfig` or `NetworkTopology` change) - [Interface binding](Sources/SwiftFTR/SwiftFTR.docc/InterfaceBinding.md): which operations honor interface and source-address binding, resolution order and binding errors. (updated 2026-11-24; update when: an operation gains or loses binding support, or HTTP probes become bindable) -- [Migrating to 0.19](Sources/SwiftFTR/SwiftFTR.docc/MigratingTo019.md): upgrade guide from 0.18 to 0.19 for people and coding agents, one entry per change a caller can observe, with what changed, what a caller sees and before-and-after code. (updated 2026-11-24; update when: a change bound for 0.19 alters behavior or source a caller depends on, or 0.18 adopters no longer need it) +- [Migrating to 0.19](Sources/SwiftFTR/SwiftFTR.docc/MigratingTo019.md): upgrade guide from 0.18 to 0.19 for people and coding agents, one entry per change a caller can observe, with what changed, what a caller sees and before-and-after code. (updated 2026-11-27; update when: a change bound for 0.19 alters behavior or source a caller depends on, or 0.18 adopters no longer need it) - [Migrating to 0.18](Sources/SwiftFTR/SwiftFTR.docc/MigratingTo018.md): upgrade guide from 0.17 to 0.18 for people and coding agents, one entry per behavior change with what changed, what a caller sees and before-and-after code, including adopting the structured DNS probe outcome. (updated 2026-11-22; update when: a change bound for 0.18 alters behavior a caller can observe, or 0.17 adopters no longer need it) - [Migrating to 0.14](Sources/SwiftFTR/SwiftFTR.docc/MigratingTo014.md): upgrade guide from 0.13 to 0.14 covering new `DNSError` cases, behavior and CLI changes, plus runtime changes in later releases. (updated 2026-11-21; update when: a later release changes a behavior it describes, or 0.13 adopters no longer need it) ### Reference and examples - [Examples](docs/guides/EXAMPLES.md): worked Swift examples for each feature area, including trace, hop outcomes, configuration, network-change lifecycle, streaming, DNS, ping, multipath, bufferbloat, SwiftUI, concurrency, errors, DNS probe outcomes and ASN strategies. (updated 2026-11-23; update when: a public API used in a sample changes shape, or a release adds a feature area with no example) -- [Condensed API reference](docs/reference/AI_REFERENCE.md): public types, method signatures, defaults, enum and error cases and CLI flags with short snippets, sized to load whole into an agent's context. (updated 2026-11-24; update when: a release changes a public signature, default, enum case or CLI flag) +- [Condensed API reference](docs/reference/AI_REFERENCE.md): public types, method signatures, defaults, enum and error cases and CLI flags with short snippets, sized to load whole into an agent's context. (updated 2026-11-27; update when: a release changes a public signature, default, enum case or CLI flag) ### Tools and fixtures - [hop-monitor](Sources/hop-monitor/README.md): the demo CLI that traces a path and then pings every hop continuously, with its output, statistics and limits. (updated 2026-11-21; update when: `Sources/hop-monitor/main.swift` changes its arguments, limits or statistics) diff --git a/ROADMAP.md b/ROADMAP.md index 75da290d..e3afb237 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -16,12 +16,12 @@ a network that drops mid-operation, a peer that accepts and then goes silent. What remains is the findings it left open, each with a disabled or missing test named there. - **Sequenced plan**: [docs/BLOCKING-IO.md](docs/BLOCKING-IO.md) orders the work into stages, each one pull request, with the gates each must pass. -- **Known unbounded waits** (#84): `traceClassified` has no overall deadline, and forward - resolution runs `getaddrinfo` synchronously on the actor where it can be neither bounded nor - cancelled; a 5 s resolver stall made `cancelActiveTraces()` wait 5 s (finding 5). An overall - deadline whose error names the phase that was running is the requested API; a resolution - budget is what moving `getaddrinfo` onto the executor needs; a way to read executor pressure - (queued and running operations) is the companion. +- **Known unbounded waits** (#84): `traceClassified` has no overall deadline. An overall + deadline whose error names the phase that was running is the requested API; a way to read + executor pressure (queued and running operations) is the companion. +- **An absolute cutoff for the TCP and UDP probe operations**, as `UDPExchange` has. Their connect + and receive timers are relative and armed after socket setup, on Dispatch's uptime clock, so a + probe can run past `timeout` by its setup time, and by a system sleep. - **Standalone `getPublicIPs` has no caller-set bound** (finding 9): each STUN exchange is bounded by `stunTimeout` and each server-name lookup wait by a fixed 20 s, so a stalled resolver holds the call for about 20 s plus `stunTimeout` (longer if more sweeps than executor workers are diff --git a/Sources/SwiftFTR/SwiftFTR.docc/MigratingTo019.md b/Sources/SwiftFTR/SwiftFTR.docc/MigratingTo019.md index 2aa82b7c..6426ccf8 100644 --- a/Sources/SwiftFTR/SwiftFTR.docc/MigratingTo019.md +++ b/Sources/SwiftFTR/SwiftFTR.docc/MigratingTo019.md @@ -746,3 +746,31 @@ let resolver = LocalASNResolver(source: .embedded) await resolver.preload() // 0.19 waits for a loading database only until the timeout let asns = try await resolver.resolve(ipv4Addrs: ips, timeout: 0.1) ``` + +## Forward resolution has a deadline and no longer holds the tracer + +**What changed.** A destination name is resolved in an executor slot rather than on the tracer +actor (`trace`, `traceClassified`, `traceStream`, multipath flows) or a cooperative thread +(`ping`, `tcpProbe`, `udpProbe`). The wait ends 20 s after a trace or ping starts resolving, and +`config.timeout` after a probe starts; a probe's connect or receive window is what resolution +left. Forced-family literals, IPv4 loopback and unscoped IPv6 literals are answered without a +lookup; other `.auto` literals use a slot of their own, so stalled name lookups cannot delay them. +Which address is probed does not change. + +**What a caller sees.** + +- A stalled resolver ends a trace or ping with `TracerouteError.resolutionFailed(host:details:)`, + details `"timed out"`, after 20 s; in 0.18 it waited as long as `getaddrinfo` took. +- `tcpProbe` and `udpProbe` return their usual resolution failure (`"Failed to resolve hostname"`) + at `timeout`, with no socket opened, and a slow lookup shortens the connect or receive window. +- Cancelling a task, or calling `cancelActiveTraces()` or `networkChanged()`, during resolution + returns at once. In 0.18 the tracer's calls waited behind the lookup, and a trace cancelled + during it still opened its socket and sent its probes. A ping cancelled during its lookup throws + `CancellationError`; 0.18 could throw `resolutionFailed`. +- With all eight executor slots held by stalled name lookups, a further name waits for a slot and + times out at its deadline, and a classified trace's STUN server names wait too, so it may finish + without a public address. + +**What to change.** Nothing. A probe that resolves a slow name and needs its full connect or +receive window raises `timeout` by the time resolution takes. + diff --git a/docs/README.md b/docs/README.md index e4c7b568..940bf7e1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,7 +7,7 @@ are in [development/README.md](development/README.md). ## Current design records - [Cache and network-transition lifecycle](CACHE-AND-TRANSITION-LIFECYCLE.md): what the `SwiftFTR` actor caches, what invalidates each cache class, and the network-transition controls callers get, with their shipped signatures and open decisions. (updated 2026-11-24; update when: a cache, invalidation rule or lifecycle control in `Traceroute.swift` or `RDNSCache.swift` changes) - [IPv6 support](IPV6.md): architectural contracts for dual-stack behavior and the sequenced stages of IPv6 parity, with remaining hardening work, test gates and known-good v6 endpoints. (updated 2026-11-24; update when: a Stage 7 hardening item lands or a v6 contract changes) -- [Robustness testing: fault injection, phase by phase](ROBUSTNESS-TESTING.md): why and how the offline fault-injection battery simulates failing networks, the conditions and operations it covers, what is out of scope, the gate commands, and the defects it found. (updated 2026-11-24; update when: a seam, fixture or covered phase is added or removed, or a listed finding changes disposition) +- [Robustness testing: fault injection, phase by phase](ROBUSTNESS-TESTING.md): why and how the offline fault-injection battery simulates failing networks, the conditions and operations it covers, what is out of scope, the gate commands, and the defects it found. (updated 2026-11-27; update when: a seam, fixture or covered phase is added or removed, or a listed finding changes disposition) - [Event-based I/O: no thread held while waiting, one deadline per operation](BLOCKING-IO.md): sequenced plan for making every public operation return within a configuration-derived time, by making DNS, STUN and reverse DNS event-based, moving forward resolution off the tracer actor and adding an overall deadline, with the gates each stage must pass, the review record and the decisions awaiting the owner. (updated 2026-11-24; update when: a stage lands or is reshaped, or one of the listed decisions is made) ## Investigations and plans diff --git a/docs/ROBUSTNESS-TESTING.md b/docs/ROBUSTNESS-TESTING.md index c86742d9..3f23c147 100644 --- a/docs/ROBUSTNESS-TESTING.md +++ b/docs/ROBUSTNESS-TESTING.md @@ -70,7 +70,7 @@ the remaining tests with the library fixes they motivated. All of it is below. | Phase | Conditions | Operations | Tests | |---|---|---|---| -| Forward resolution | fails (the injected error is checked, so a call that went around the seam fails); stalls (disabled, finding 5) | trace, traceClassified, traceStream, ping | `ProbeWindow`, `Enrichment` | +| Forward resolution | fails (the injected error is checked, so a call that went around the seam fails); stalls; outlives its deadline; is cancelled while running or queued; every executor slot held | trace, traceClassified, traceStream, ping, tcpProbe, udpProbe | `ProbeWindow`, `ResolutionOffActor` | | Probe socket | creation fails the way `socket(2)` does; every send fails with a non-transient errno | trace, traceClassified, traceStream, ping | `ProbeWindow` | | Probe socket (ping) | every send fails: nothing is counted as sent, and the ping does not wait out a reply window | ping | `ProbeWindow` | | Probe window | no replies; late replies; truncated, garbage and seeded-random ICMPv4/ICMPv6 ahead of valid replies, which are still processed; another identifier; unreachable; a silent stream that must wait out its window and send its retries | trace, traceStream, ping | `ProbeWindow` | @@ -180,8 +180,6 @@ Not covered, and why: - An overall deadline on `traceClassified` with an error naming the phase, and an executor-pressure reading (#84). Both are API additions for a minor release. -- Moving forward resolution off the actor. It needs a resolution budget, which is a new - configuration field. The test that shows the defect is checked in disabled (finding 5). - `testBufferbloat`, which needs real load traffic, and the interface-bound HTTPS spike. - Raw-socket or privileged fault injection, and any test that sends traffic off the host. @@ -222,13 +220,13 @@ numbers are as of the commit that added this section. truncated the timeout to a zero `timeval`, which disables `SO_RCVTIMEO` (`STUN.swift:213` after the fix). Reachable through the public `getPublicIPs(stunTimeout:)`. Test: `stunTinyTimeout`, still blocked at its watchdog before, immediate after. -5. **Forward resolution is synchronous on the tracer actor and unbounded.** Confirmed (known from - #84), not fixed. `resolveHost` (`Traceroute.swift:629`, `:785`) calls `getaddrinfo` on the - actor, even for a literal under `.auto`, so a stalled resolver holds every other call on that - tracer, `cancelActiveTraces()` and `networkChanged()` included, and cannot be cancelled. With a - 5 s injected stall, `cancelActiveTraces()` took 5.0 s to return. Not fixed: bounding it needs a - resolution budget, which is a configuration field. Test, disabled because it blocks for its - stall: `FaultInjectionEnrichmentTests.forwardResolutionStall`. +5. **Forward resolution was synchronous on the tracer actor and unbounded.** Confirmed (known from + #84) and fixed. `resolveHost` called `getaddrinfo` on the actor, even for a literal under + `.auto`, so a stalled resolver held every other call on that tracer, `cancelActiveTraces()` and + `networkChanged()` included, and could not be cancelled; ping and the probes held a cooperative + thread. Resolution now runs in an executor slot under a deadline, and cancellation releases the + caller at once. Tests: `ResolutionOffActorTests`, among them `forwardResolutionStall` (a gated + lookup, each canceller, released while the gate is shut) and `resolutionHoldsNoPoolThread`. 6. **A failed public-IP discovery was paid twice.** Confirmed and fixed. When discovery failed or timed out, `traceClassified` passed `publicIP: nil` to the classifier, which ran discovery again with the same budget, so the bound was two budgets. The classifier no longer discovers diff --git a/docs/reference/AI_REFERENCE.md b/docs/reference/AI_REFERENCE.md index 598524c9..60c0654f 100644 --- a/docs/reference/AI_REFERENCE.md +++ b/docs/reference/AI_REFERENCE.md @@ -200,7 +200,7 @@ public struct TraceOptions: Sendable, Equatable { ```swift public enum PreferredFamily: Sendable, Codable { - case auto // names and literals both go through getaddrinfo; the first answer is probed + case auto // names and most literals go through getaddrinfo; the first answer is probed case v4 // IPv4 literal used as is; IPv6 literal or no IPv4 address throws resolutionFailed case v6 // IPv6 literal used as is; IPv4 literal or no IPv6 address throws resolutionFailed } @@ -209,7 +209,13 @@ public enum PreferredFamily: Sendable, Codable { `.auto` does not force a literal's family. On an IPv6-only NAT64 network the system resolver synthesizes an IPv6 address for an IPv4 literal, so tracing `1.1.1.1` can probe, and report in `resolvedIP`, an IPv6 address. On dual-stack networks an IPv4 literal comes back unchanged. Use -`.v4` or `.v6` to pin the family. +`.v4` or `.v6` to pin the family. IPv4 loopback and unscoped IPv6 literals, which the system +returns unchanged, are answered without it. + +Resolution runs in an executor slot, never on the tracer or a cooperative thread. Traces and ping +wait at most 20 s for it (`resolutionFailed`, details `"timed out"`); `tcpProbe` and `udpProbe` +spend their `timeout` on resolution and the probe together. Cancellation, `cancelActiveTraces()` +and `networkChanged()` release a caller waiting on it at once. ### 5. TraceResult and TraceHop From 57ae7b230a65ae2136bb67e3c4358357853989a8 Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Fri, 27 Nov 2026 15:02:36 -0800 Subject: [PATCH 3/6] test(resolution): avoid a throwing where clause Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01A8mvWou2vH56zDnkZkqT2X --- Tests/SwiftFTRTests/ResolutionOffActorTests.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Tests/SwiftFTRTests/ResolutionOffActorTests.swift b/Tests/SwiftFTRTests/ResolutionOffActorTests.swift index 59027b2f..bd4f5ae5 100644 --- a/Tests/SwiftFTRTests/ResolutionOffActorTests.swift +++ b/Tests/SwiftFTRTests/ResolutionOffActorTests.swift @@ -219,8 +219,10 @@ struct ResolutionOffActorTests { found.append("\(host): inline \(mine.canonical) vs getaddrinfo \(system.canonical)") } } - for host in resolver where try inlineResolution(host: host, prefer: .auto) != nil { - found.append("\(host): answered inline") + for host in resolver { + if try inlineResolution(host: host, prefer: .auto) != nil { + found.append("\(host): answered inline") + } } return found } From 3c9937a00286fa68db107648076ae99f8de03157 Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Fri, 27 Nov 2026 15:24:04 -0800 Subject: [PATCH 4/6] test(resolution): leave a slow runner time to reach the probe handoff On CI more than half a second passed between entry and the handoff, so the budget test's probe found nothing left. It now leaves 5 s, still well inside the 20 s watchdog that a probe given its whole 60 s timeout exceeds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01A8mvWou2vH56zDnkZkqT2X --- Tests/SwiftFTRTests/ResolutionOffActorTests.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Tests/SwiftFTRTests/ResolutionOffActorTests.swift b/Tests/SwiftFTRTests/ResolutionOffActorTests.swift index bd4f5ae5..d49859ca 100644 --- a/Tests/SwiftFTRTests/ResolutionOffActorTests.swift +++ b/Tests/SwiftFTRTests/ResolutionOffActorTests.swift @@ -466,10 +466,12 @@ struct ResolutionOffActorTests { defer { close(silent.fd) } let executor = BlockingIOExecutor(maximumConcurrentOperations: 1, name: "test.rdo-budget") let slow: TestSeams.ResolveHost = { _, _ in - clock.jump(by: 59.5) + // Leaves 5 s: enough for a slow runner to reach the handoff, well inside the watchdog. + clock.jump(by: 55) return try blockingResolution(host: "127.0.0.1", prefer: .v4, substitute: nil) } - // The timeout outlasts the watchdog, so a probe given all of it fails the watchdog. + // The timeout outlasts the watchdog, so a probe given all of it fails the watchdog; one given + // what is left ends after about 5 s. let result = try await TestSeams.$blockingIOExecutor.withValue(executor) { try await TestSeams.$monotonicClock.withValue(clock.now) { try await TestSeams.$resolveHost.withValue(slow) { From aa015016359a28c9b374f7f763b54c6f51a6b3df Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Fri, 27 Nov 2026 15:36:46 -0800 Subject: [PATCH 5/6] fix(resolution): IPv4 shorthand takes the literal lane The system resolver treats "127.1" as numeric, but inet_pton does not, so it was queued with names and waited out the budget when the name slots were stalled. Lane selection now also accepts what inet_aton recognizes; resolution itself is unchanged. The full-executor test pings 127.1; without the change it is still running at the 20 s watchdog. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01A8mvWou2vH56zDnkZkqT2X --- Sources/SwiftFTR/Hostname.swift | 8 +++++--- Tests/SwiftFTRTests/ResolutionOffActorTests.swift | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/Sources/SwiftFTR/Hostname.swift b/Sources/SwiftFTR/Hostname.swift index e121e55d..28deb93d 100644 --- a/Sources/SwiftFTR/Hostname.swift +++ b/Sources/SwiftFTR/Hostname.swift @@ -260,9 +260,11 @@ internal func resolveDestination( ) async throws -> ResolvedHost { if let answer = try inlineResolution(host: host, prefer: prefer) { return answer } let substitute = TestSeams.resolveHost - let lane = - detectAddressFamily(host) == -1 - ? nil : (TestSeams.literalLookupExecutor ?? literalLookupExecutor) + // Numeric for lane selection is wider than a literal the library parses: the system resolver + // also takes IPv4 shorthand ("127.1"), which `inet_aton` recognizes and `inet_pton` does not. + var shorthand = in_addr() + let numeric = detectAddressFamily(host) != -1 || inet_aton(host, &shorthand) == 1 + let lane = numeric ? (TestSeams.literalLookupExecutor ?? literalLookupExecutor) : nil let found = try await withTraceCancellation(handle: handle) { try await awaitBlockingLookup(until: deadline, clock: clock, on: lane) { try blockingResolution(host: host, prefer: prefer, substitute: substitute) diff --git a/Tests/SwiftFTRTests/ResolutionOffActorTests.swift b/Tests/SwiftFTRTests/ResolutionOffActorTests.swift index d49859ca..f134b95d 100644 --- a/Tests/SwiftFTRTests/ResolutionOffActorTests.swift +++ b/Tests/SwiftFTRTests/ResolutionOffActorTests.swift @@ -177,18 +177,20 @@ struct ResolutionOffActorTests { let pings = [ try await auto.ping(to: "127.0.0.1", config: PingConfig(count: 1)), try await auto.ping(to: "192.0.2.1", config: PingConfig(count: 1)), + // IPv4 shorthand: numeric to the system resolver, not to `inet_pton`. + try await auto.ping(to: "127.1", config: PingConfig(count: 1)), ] return (traces.map(\.reached), pings.map(\.statistics.received)) } #expect(results.0 == [true, true]) - #expect(results.1 == [1, 1]) + #expect(results.1 == [1, 1, 1]) } } } } #expect(held.executor.submissions.value - mainBefore == 0, "a literal waited for a main slot") - // Only the non-loopback `.auto` literal needs the resolver, for NAT64. - #expect(lane.submissions.value - laneBefore == 1) + // The non-loopback `.auto` literal needs the resolver, for NAT64; so does the shorthand. + #expect(lane.submissions.value - laneBefore == 2) #expect(held.finished.value == 0) } From 457e0367f57ca59e75ca02a09b200ef251a22f93 Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Fri, 27 Nov 2026 15:38:30 -0800 Subject: [PATCH 6/6] fix(resolution): only strictly numeric strings take the literal lane inet_aton stops at whitespace and accepts what came before it, so "127.1 example.com" would have been sent to the lane reserved for numeric destinations. Lane selection now requires every character to be one a numeric IPv4 form can contain before asking inet_aton. numericDestinations fails for the three whitespace cases without the check. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01A8mvWou2vH56zDnkZkqT2X --- Sources/SwiftFTR/Hostname.swift | 23 +++++++++++++++---- .../ResolutionOffActorTests.swift | 11 +++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/Sources/SwiftFTR/Hostname.swift b/Sources/SwiftFTR/Hostname.swift index 28deb93d..04e68c1d 100644 --- a/Sources/SwiftFTR/Hostname.swift +++ b/Sources/SwiftFTR/Hostname.swift @@ -246,6 +246,22 @@ internal func blockingResolution( /// How long a trace or ping waits for its destination to resolve (docs/BLOCKING-IO.md, decision 7). let forwardResolutionLimit: TimeInterval = 20 +/// Whether `host` is numeric to the system resolver, so its lookup takes the Literal Lane. Wider +/// than a literal the library parses: the resolver also takes IPv4 shorthand ("127.1"), which +/// `inet_aton` recognizes and `inet_pton` does not. `inet_aton` stops at whitespace and accepts +/// what came before it, so only digits, dots and the hex and octal forms' characters qualify: +/// nothing that could be a name reaches the lane. +internal func isNumericDestination(_ host: String) -> Bool { + if detectAddressFamily(host) != -1 { return true } + guard !host.isEmpty, + host.utf8.allSatisfy({ + $0 == 0x2E || Character(UnicodeScalar($0)).isHexDigit || $0 == 0x78 || $0 == 0x58 + }) + else { return false } + var shorthand = in_addr() + return inet_aton(host, &shorthand) == 1 +} + /// Resolves `host` for an operation: inline when ``inlineResolution(host:prefer:)`` answers, /// otherwise in an executor slot, a literal on the Literal Lane (``literalLookupExecutor``) and a /// name on the main executor, so stalled name lookups cannot hold back a numeric destination. @@ -260,11 +276,8 @@ internal func resolveDestination( ) async throws -> ResolvedHost { if let answer = try inlineResolution(host: host, prefer: prefer) { return answer } let substitute = TestSeams.resolveHost - // Numeric for lane selection is wider than a literal the library parses: the system resolver - // also takes IPv4 shorthand ("127.1"), which `inet_aton` recognizes and `inet_pton` does not. - var shorthand = in_addr() - let numeric = detectAddressFamily(host) != -1 || inet_aton(host, &shorthand) == 1 - let lane = numeric ? (TestSeams.literalLookupExecutor ?? literalLookupExecutor) : nil + let lane = + isNumericDestination(host) ? (TestSeams.literalLookupExecutor ?? literalLookupExecutor) : nil let found = try await withTraceCancellation(handle: handle) { try await awaitBlockingLookup(until: deadline, clock: clock, on: lane) { try blockingResolution(host: host, prefer: prefer, substitute: substitute) diff --git a/Tests/SwiftFTRTests/ResolutionOffActorTests.swift b/Tests/SwiftFTRTests/ResolutionOffActorTests.swift index f134b95d..542df528 100644 --- a/Tests/SwiftFTRTests/ResolutionOffActorTests.swift +++ b/Tests/SwiftFTRTests/ResolutionOffActorTests.swift @@ -194,6 +194,17 @@ struct ResolutionOffActorTests { #expect(held.finished.value == 0) } + @Test("Only what the system resolver reads as a number takes the Literal Lane") + func numericDestinations() { + for host in ["127.1", "1.1.1.1", "0x7f.1", "017700000001", "2130706433", "::1", "fe80::1%lo0"] { + #expect(isNumericDestination(host), "\(host)") + } + // `inet_aton` alone accepts the first three: it stops at whitespace. + for host in ["127.1 example.com", "1.1.1.1\texample.com", "127.1\n", "", "example.com", "a.b"] { + #expect(!isNumericDestination(host), "\(host.debugDescription)") + } + } + @Test("Inline answers equal the resolver's, and only resolver inputs reach the seam") func inlineParity() async throws { let inline = [