From 727df9814f6a49698ce80ff4c9abfae79acce7d6 Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Fri, 27 Nov 2026 15:58:56 -0800 Subject: [PATCH 1/3] feat(resolution): a configurable resolution budget, and discoverPaths resolves once SwiftFTRConfig.resolutionTimeout (default 20 s), added through a further initializer, bounds the resolution wait of trace, traceClassified, traceStream, ping and discoverPaths. It must be finite and in (0, Int32.max] seconds, the rule PingConfig.timeout and StreamingTraceConfig.probeTimeout follow; validateForOperation rejects anything else, and ping now checks this one field of its tracer's configuration. discoverPaths resolves its target once, forced IPv4, inside its outcome and commit path and before its public-IP question, and hands the address to every flow, which keeps the caller's name for display. A name that does not resolve ends the run before any question or probe; the reported duration includes the lookup. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01A8mvWou2vH56zDnkZkqT2X --- .../SwiftFTR/ConfigurationValidation.swift | 7 + Sources/SwiftFTR/Hostname.swift | 3 - Sources/SwiftFTR/Multipath.swift | 35 ++- Sources/SwiftFTR/Ping.swift | 3 +- Sources/SwiftFTR/Traceroute.swift | 62 ++++- .../MultipathWorkerConfigTests.swift | 9 +- .../SwiftFTRTests/ResolutionBudgetTests.swift | 261 ++++++++++++++++++ .../ResolutionOffActorTests.swift | 4 +- 8 files changed, 359 insertions(+), 25 deletions(-) create mode 100644 Tests/SwiftFTRTests/ResolutionBudgetTests.swift diff --git a/Sources/SwiftFTR/ConfigurationValidation.swift b/Sources/SwiftFTR/ConfigurationValidation.swift index d34bb7a6..b5e3921b 100644 --- a/Sources/SwiftFTR/ConfigurationValidation.swift +++ b/Sources/SwiftFTR/ConfigurationValidation.swift @@ -57,6 +57,13 @@ extension SwiftFTRConfig { if case .hybrid(_, let fallbackTimeout) = asnResolverStrategy { try validatePositiveTimeout(fallbackTimeout, named: "ASN fallbackTimeout") } + try validateResolutionTimeout() + } + + /// Validates ``resolutionTimeout`` alone: for `ping`, which uses only that field of its tracer's + /// configuration. + func validateResolutionTimeout() throws { + try validatePositiveTimeout(resolutionTimeout, named: "resolutionTimeout") } /// A safe cache TTL used while retaining invalid public input for operation-time validation. diff --git a/Sources/SwiftFTR/Hostname.swift b/Sources/SwiftFTR/Hostname.swift index 04e68c1d..bbe295b9 100644 --- a/Sources/SwiftFTR/Hostname.swift +++ b/Sources/SwiftFTR/Hostname.swift @@ -243,9 +243,6 @@ internal func blockingResolution( 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 - /// 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 diff --git a/Sources/SwiftFTR/Multipath.swift b/Sources/SwiftFTR/Multipath.swift index 2447fa73..f52c9b7a 100644 --- a/Sources/SwiftFTR/Multipath.swift +++ b/Sources/SwiftFTR/Multipath.swift @@ -111,7 +111,8 @@ extension SwiftFTRConfig { sourceIP: sourceIP, asnResolverStrategy: asnResolverStrategy, preferredFamily: .v4, - publicIPResolver: publicIPResolver + publicIPResolver: publicIPResolver, + resolutionTimeout: resolutionTimeout ) } } @@ -641,21 +642,28 @@ extension SwiftFTR { let outcome: Result do { - // One question for the whole run, IPv4 by contract, before the first batch. Its answer, or - // its absence, is handed to every flow, so no flow asks again. It is asked on its own, - // before the race below, because both wait on the handle's one cancellation slot. + // One resolution and one question for the whole run, IPv4 by contract, before the first + // batch, each handed to every flow, so no flow resolves or asks again. Both run on their + // own, before the race below, because each waits on the handle's one cancellation slot. A + // name that does not resolve ends the run before the question is asked. try validateBeforeQuestion(target: target) - let asked = monotonicNow() + let started = monotonicNow() + let clock = DiscoveryClock.current + let destination = try await resolveDestination( + target, prefer: .v4, until: clock.now() + swiftConfig.resolutionTimeout, clock: clock, + handle: handle) + try handle.checkCancellation() let publicIP = try await publicIPObservation(for: .v4, handle: handle) let worker = MultipathWorkerSpawner( baseConfig: swiftConfig, rdnsCache: self.rdnsCache, asnResolver: self.asnResolver, + destination: destination, publicIP: publicIP ) let discovery = MultipathDiscovery( worker: worker, config: swiftConfig, publicIP: publicIP, - elapsedBefore: monotonicNow() - asked) + elapsedBefore: monotonicNow() - started) outcome = .success( try await withThrowingTaskGroup(of: NetworkTopology?.self) { group in group.addTask { @@ -689,9 +697,9 @@ extension SwiftFTR { } /// Rejects, before the run's public-IP question, every input a flow would reject only after it: - /// the interface, the source address (its form, its family, and whether this host can bind it), - /// and a numeric destination of the wrong family. So an unusable binding never sends discovery - /// traffic. A destination name that does not resolve is found only by the flows. + /// the interface and the source address (its form, its family, and whether this host can bind + /// it). So an unusable binding never sends discovery traffic. The destination, a literal of the + /// wrong family included, is checked by the run's one resolution, which follows. private func validateBeforeQuestion(target: String) throws { if let name = config.interface { _ = try validateInterface(name) } if let source = config.sourceIP { @@ -703,8 +711,6 @@ extension SwiftFTR { throw TracerouteError.sourceIPBindFailed(sourceIP: source, errno: errno, details: message) } } - // 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. @@ -712,6 +718,8 @@ extension SwiftFTR { let baseConfig: SwiftFTRConfig let rdnsCache: RDNSCache let asnResolver: ASNResolver + /// The parent's one resolution of the target, which every flow probes; a flow never resolves. + let destination: ResolvedHost /// The parent's public address, or `nil` when it has none; a flow never asks for one. let publicIP: PublicIPObservation? @@ -726,6 +734,7 @@ extension SwiftFTR { let trace = try await worker.performClassifiedTraceWithFlowID( to: target, flowIdentifier: flowID.icmpID, + destination: destination, publicIP: publicIP ) try Task.checkCancellation() @@ -752,6 +761,7 @@ extension SwiftFTR { fileprivate func performClassifiedTraceWithFlowID( to host: String, flowIdentifier: UInt16, + destination: ResolvedHost, publicIP observation: PublicIPObservation? ) async throws -> ClassifiedTrace { try config.validateForOperation() @@ -771,7 +781,8 @@ extension SwiftFTR { // Perform base trace with flow ID let tr = try await withTaskCancellationHandler { - try await performTrace(to: host, handle: handle, flowIdentifier: flowIdentifier) + try await performTrace( + to: host, resolved: destination, handle: handle, flowIdentifier: flowIdentifier) } onCancel: { handle.cancel(for: .callerTask) } diff --git a/Sources/SwiftFTR/Ping.swift b/Sources/SwiftFTR/Ping.swift index 26e637fa..2da87fe4 100644 --- a/Sources/SwiftFTR/Ping.swift +++ b/Sources/SwiftFTR/Ping.swift @@ -218,13 +218,14 @@ struct PingExecutor: Sendable { /// instance never share identifier/sequence space (downstream contract). func ping(to target: String, config: PingConfig) async throws -> PingResult { try config.validateForOperation() + try swiftFTRConfig.validateResolutionTimeout() try Task.checkCancellation() // 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, + target, prefer: config.preferredFamily, until: clock.now() + swiftFTRConfig.resolutionTimeout, clock: clock) try Task.checkCancellation() diff --git a/Sources/SwiftFTR/Traceroute.swift b/Sources/SwiftFTR/Traceroute.swift index 8992c05f..138d8e9c 100644 --- a/Sources/SwiftFTR/Traceroute.swift +++ b/Sources/SwiftFTR/Traceroute.swift @@ -225,6 +225,10 @@ public struct SwiftFTRConfig: Sendable { /// resolvers. public static let defaultRDNSLookupTimeout: TimeInterval = 5.0 + /// Default ``resolutionTimeout``, in seconds: how long the system resolver itself waits has not + /// been measured, so this is a judgement (docs/BLOCKING-IO.md, decision 7). + public static let defaultResolutionTimeout: TimeInterval = 20 + /// Maximum TTL/hops to probe (default: 40) public let maxHops: Int /// Maximum wait time per probe in milliseconds (default: 1000ms) @@ -342,6 +346,15 @@ public struct SwiftFTRConfig: Sendable { /// ``PublicIPResolverStrategy/library``. public let publicIPResolver: PublicIPResolverStrategy + /// How long `trace`, `traceClassified`, `traceStream`, `ping` and `discoverPaths` wait for their + /// destination to resolve, in seconds (default: ``defaultResolutionTimeout``). The lookup runs + /// in an executor slot; when the wait ends first the operation throws + /// ``TracerouteError/resolutionFailed(host:details:)`` with details `"timed out"`, and a + /// `getaddrinfo` already running finishes on its own. Must be finite and in (0, `Int32.max`]: + /// any other value makes those operations throw ``TracerouteError/invalidConfiguration(reason:)`` + /// before they resolve anything. `tcpProbe` and `udpProbe` spend their own `timeout` instead. + public let resolutionTimeout: TimeInterval + /// Creates a new SwiftFTR configuration. /// /// - Parameters: @@ -385,7 +398,8 @@ public struct SwiftFTRConfig: Sendable { rdnsCacheSize: rdnsCacheSize, rdnsLookupTimeout: rdnsLookupTimeout, publicIPDiscoveryTimeout: publicIPDiscoveryTimeout, interface: interface, sourceIP: sourceIP, asnResolverStrategy: asnResolverStrategy, - preferredFamily: preferredFamily, publicIPResolver: .library) + preferredFamily: preferredFamily, publicIPResolver: .library, + resolutionTimeout: SwiftFTRConfig.defaultResolutionTimeout) } /// Creates a new SwiftFTR configuration: the parameters of the initializer above, plus @@ -407,6 +421,37 @@ public struct SwiftFTRConfig: Sendable { asnResolverStrategy: ASNResolverStrategy = .hybrid(.embedded), preferredFamily: PreferredFamily = .auto, publicIPResolver: PublicIPResolverStrategy = .library + ) { + self.init( + maxHops: maxHops, maxWaitMs: maxWaitMs, payloadSize: payloadSize, publicIP: publicIP, + enableLogging: enableLogging, noReverseDNS: noReverseDNS, rdnsCacheTTL: rdnsCacheTTL, + rdnsCacheSize: rdnsCacheSize, rdnsLookupTimeout: rdnsLookupTimeout, + publicIPDiscoveryTimeout: publicIPDiscoveryTimeout, interface: interface, + sourceIP: sourceIP, asnResolverStrategy: asnResolverStrategy, + preferredFamily: preferredFamily, publicIPResolver: publicIPResolver, + resolutionTimeout: SwiftFTRConfig.defaultResolutionTimeout) + } + + /// Creates a new SwiftFTR configuration: the parameters of the initializer above, plus + /// `resolutionTimeout`, how long an operation waits for its destination to resolve (default: + /// ``defaultResolutionTimeout``). + public init( + maxHops: Int = 40, + maxWaitMs: Int = 1000, + payloadSize: Int = 56, + publicIP: String? = nil, + enableLogging: Bool = false, + noReverseDNS: Bool = false, + rdnsCacheTTL: TimeInterval? = nil, + rdnsCacheSize: Int? = nil, + rdnsLookupTimeout: TimeInterval? = nil, + publicIPDiscoveryTimeout: TimeInterval? = nil, + interface: String? = nil, + sourceIP: String? = nil, + asnResolverStrategy: ASNResolverStrategy = .hybrid(.embedded), + preferredFamily: PreferredFamily = .auto, + publicIPResolver: PublicIPResolverStrategy = .library, + resolutionTimeout: TimeInterval = SwiftFTRConfig.defaultResolutionTimeout ) { self.maxHops = maxHops self.maxWaitMs = maxWaitMs @@ -423,6 +468,7 @@ public struct SwiftFTRConfig: Sendable { self.asnResolverStrategy = asnResolverStrategy self.preferredFamily = preferredFamily self.publicIPResolver = publicIPResolver + self.resolutionTimeout = resolutionTimeout } } @@ -816,13 +862,13 @@ 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. + /// ``SwiftFTRConfig/resolutionTimeout`` 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, + host, prefer: config.preferredFamily, until: clock.now() + config.resolutionTimeout, clock: clock, handle: handle) } @@ -848,8 +894,11 @@ public actor SwiftFTR { } // Internal implementation of trace with cancellation support + /// `resolved`, when given, is the destination already resolved for `host` (a multipath flow's, + /// from its parent); `host` is still what the result reports. internal func performTrace( to host: String, + resolved given: ResolvedHost? = nil, handle: TraceHandle, flowIdentifier: UInt16? = nil, maxHopsOverride: Int? = nil @@ -881,7 +930,12 @@ public actor SwiftFTR { } // 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) + let resolved: ResolvedHost + if let given { + resolved = given + } else { + resolved = try await resolveTraceDestination(host, handle: handle) + } try handle.checkCancellation() if config.enableLogging { let famName = resolved.family == AF_INET6 ? "v6" : "v4" diff --git a/Tests/SwiftFTRTests/MultipathWorkerConfigTests.swift b/Tests/SwiftFTRTests/MultipathWorkerConfigTests.swift index b79faf8f..44779fbc 100644 --- a/Tests/SwiftFTRTests/MultipathWorkerConfigTests.swift +++ b/Tests/SwiftFTRTests/MultipathWorkerConfigTests.swift @@ -78,6 +78,7 @@ struct MultipathWorkerConfigTests { "maxHops", "maxWaitMs", "payloadSize", "publicIP", "enableLogging", "noReverseDNS", "rdnsCacheTTL", "rdnsCacheSize", "rdnsLookupTimeout", "publicIPDiscoveryTimeout", "interface", "sourceIP", "asnResolverStrategy", "preferredFamily", "publicIPResolver", + "resolutionTimeout", ] /// A caller configuration with every field away from its default. @@ -96,7 +97,8 @@ struct MultipathWorkerConfigTests { sourceIP: "127.0.0.1", asnResolverStrategy: .dns, preferredFamily: .auto, - publicIPResolver: .disabled + publicIPResolver: .disabled, + resolutionTimeout: 3.5 ) static func fields(of config: SwiftFTRConfig) -> [String: String] { @@ -109,7 +111,7 @@ struct MultipathWorkerConfigTests { } @Test("A flow's configuration is the caller's except the documented overrides") - func flowConfigCopiesEveryField() async { + func flowConfigCopiesEveryField() async throws { let caller = Self.fields(of: Self.callerConfig) let defaults = Self.fields(of: SwiftFTRConfig()) #expect( @@ -123,7 +125,8 @@ struct MultipathWorkerConfigTests { let rdns = RDNSCache { _, _ in .noSuchRecord } let resolver = MultipathRecordingASNResolver(mapping: [:]) let spawner = SwiftFTR.MultipathWorkerSpawner( - baseConfig: Self.callerConfig, rdnsCache: rdns, asnResolver: resolver, publicIP: nil) + baseConfig: Self.callerConfig, rdnsCache: rdns, asnResolver: resolver, + destination: try resolveHost(host: "127.0.0.1", prefer: .v4), publicIP: nil) let flow = spawner.makeFlowTracer(maxHops: 5, timeoutMs: 321) let worker = Self.fields(of: flow.config) diff --git a/Tests/SwiftFTRTests/ResolutionBudgetTests.swift b/Tests/SwiftFTRTests/ResolutionBudgetTests.swift new file mode 100644 index 00000000..67405df4 --- /dev/null +++ b/Tests/SwiftFTRTests/ResolutionBudgetTests.swift @@ -0,0 +1,261 @@ +import Foundation +import Testing + +@testable import SwiftFTR + +#if canImport(Darwin) + import Darwin +#endif + +/// `SwiftFTRConfig.resolutionTimeout` bounds every operation's resolution, and `discoverPaths` +/// resolves its target once, before its public-IP question, for every flow +/// (docs/BLOCKING-IO.md, Resolution Off The Actor, decision 7). Stalled lookups wait on a gate that +/// holds for three times the watchdog. +@Suite("Resolution budget and resolving once") +struct ResolutionBudgetTests { + static let watchdog: TimeInterval = 20 + static let hold: TimeInterval = 60 + + enum Operation: String, CaseIterable, CustomTestStringConvertible, Sendable { + case trace, traceClassified, traceStream, ping + var testDescription: String { rawValue } + + func run(_ tracer: SwiftFTR, to host: String) async throws { + switch self { + case .trace: _ = try await tracer.trace(to: host) + case .traceClassified: + _ = try await tracer.traceClassified(to: host, resolver: EmptyASNResolver()) + case .traceStream: for try await _ in tracer.traceStream(to: host) {} + case .ping: _ = try await tracer.ping(to: host, config: PingConfig(count: 1)) + } + } + } + + /// A public-IP resolver that counts its questions and has no answer. + struct CountingResolver: PublicIPResolver { + let asked: FaultCounter + func publicIP(for request: PublicIPRequest) async throws -> PublicIPObservation? { + asked.increment() + return nil + } + } + + // MARK: The option + + @Test( + "The configured budget, not the default, ends each operation's wait", + arguments: Operation.allCases) + func budgetReachesEachOperation(operation: Operation) async throws { + let gate = StallGate() + defer { gate.open() } + let entered = FaultCounter() + let clock = MovableClock() + let executor = BlockingIOExecutor(maximumConcurrentOperations: 1, name: "test.budget-reach") + let stall: TestSeams.ResolveHost = { host, _ in + entered.increment() + gate.wait(limit: Self.hold) + throw TracerouteError.resolutionFailed(host: host, details: "stalled") + } + let tracer = offlineTracer( + SwiftFTRConfig(maxHops: 2, noReverseDNS: true, resolutionTimeout: 5)) + + let outcome = try await TestSeams.$blockingIOExecutor.withValue(executor) { + try await TestSeams.$monotonicClock.withValue(clock.now) { + try await TestSeams.$resolveHost.withValue(stall) { + let task = Task { try await operation.run(tracer, to: "gated.test") } + #expect(await eventually(within: Self.watchdog) { entered.value == 1 }) + // Past the configured 5 s, well short of the 20 s default. + return try await measure(within: Self.watchdog) { + clock.jump(by: 6) + return await task.result + }.0 + } + } + } + guard case .failure(TracerouteError.resolutionFailed(_, let details)) = outcome else { + Issue.record("\(operation): expected the resolution timeout, got \(outcome)") + return + } + #expect(details == "timed out") + } + + @Test( + "A resolution budget that is not finite and positive is rejected before anything resolves", + arguments: [0, -1, TimeInterval.nan, .infinity, TimeInterval(Int32.max) * 2]) + func invalidBudgetRejected(budget: TimeInterval) async throws { + let consulted = FaultCounter() + let seam: TestSeams.ResolveHost = { host, _ in + consulted.increment() + throw TracerouteError.resolutionFailed(host: host, details: "consulted") + } + let tracer = offlineTracer( + SwiftFTRConfig(maxHops: 2, noReverseDNS: true, resolutionTimeout: budget)) + let config = MultipathConfig(flowVariations: 1, maxPaths: 1, earlyStopThreshold: 1) + let calls: [(String, @Sendable () async throws -> Void)] = [ + ("trace", { _ = try await tracer.trace(to: "name.test") }), + ("ping", { _ = try await tracer.ping(to: "name.test", config: PingConfig(count: 1)) }), + ("discoverPaths", { _ = try await tracer.discoverPaths(to: "name.test", config: config) }), + ] + await TestSeams.$resolveHost.withValue(seam) { + for (name, call) in calls { + do { + try await call() + Issue.record("\(name) accepted resolutionTimeout \(budget)") + } catch TracerouteError.invalidConfiguration(let reason) { + #expect(reason.contains("resolutionTimeout"), "\(name): \(reason)") + } catch { + Issue.record("\(name) threw \(error) for resolutionTimeout \(budget)") + } + } + } + #expect(consulted.value == 0, "an operation resolved with an invalid budget") + } + + @Test("Every published SwiftFTRConfig initializer keeps its meaning, with the 20 s budget") + func initializerSelection() { + // The initializers published before this option, used as function values with their types + // stated: both must still bind, and to the default budget. + let original: + ( + Int, Int, Int, String?, Bool, Bool, TimeInterval?, Int?, TimeInterval?, TimeInterval?, + String?, String?, ASNResolverStrategy, PreferredFamily + ) -> SwiftFTRConfig = SwiftFTRConfig.init + let withResolver: + ( + Int, Int, Int, String?, Bool, Bool, TimeInterval?, Int?, TimeInterval?, TimeInterval?, + String?, String?, ASNResolverStrategy, PreferredFamily, PublicIPResolverStrategy + ) -> SwiftFTRConfig = SwiftFTRConfig.init + let a = original(40, 1000, 56, nil, false, false, nil, nil, nil, nil, nil, nil, .dns, .auto) + let b = withResolver( + 40, 1000, 56, nil, false, false, nil, nil, nil, nil, nil, nil, .dns, .auto, .disabled) + let budgets = [ + a.resolutionTimeout, b.resolutionTimeout, SwiftFTRConfig().resolutionTimeout, + SwiftFTRConfig(maxHops: 3, publicIPResolver: .disabled).resolutionTimeout, + ] + #expect(budgets == Array(repeating: 20, count: 4)) + #expect(SwiftFTRConfig.defaultResolutionTimeout == 20) + let chosen = SwiftFTRConfig(maxHops: 3, resolutionTimeout: 7) + #expect(chosen.resolutionTimeout == 7 && chosen.maxHops == 3) + } + + // MARK: discoverPaths resolves once + + @Test("Every flow of a run probes the parent's one resolution and reports the caller's name") + func discoverPathsResolvesOnce() async throws { + let network = try FakeICMPNetwork(script: pathScript(destinationTTL: 2)) + defer { network.stop() } + let calls = FaultCounter() + let base = network.resolved + // A name whose every lookup gives another address, as a round-robin record can. + let rotating: TestSeams.ResolveHost = { _, _ in + calls.increment() + return ResolvedHost( + family: base.family, address: base.address, addressLen: base.addressLen, + canonical: "198.51.100.\(calls.value)") + } + let tracer = offlineTracer( + SwiftFTRConfig(maxHops: 3, noReverseDNS: true), publicIP: "198.51.100.200") + let config = MultipathConfig( + flowVariations: 3, maxPaths: 8, earlyStopThreshold: 3, timeoutMs: 2000, maxHops: 3) + + let topology = try await network.install { + try await TestSeams.$resolveHost.withValue(rotating) { + try await measure(within: Self.watchdog) { + try await tracer.discoverPaths(to: "rotating.test", config: config) + }.0 + } + } + #expect(calls.value == 1, "the run resolved its target \(calls.value) times") + #expect(topology.paths.count == 3) + #expect(Set(topology.paths.map(\.trace.destinationIP)) == ["198.51.100.1"]) + #expect(topology.paths.allSatisfy { $0.trace.destinationHost == "rotating.test" }) + #expect(topology.destination == "rotating.test") + } + + @Test("A target that does not resolve ends the run before its public-IP question") + func unresolvableTargetAsksNothing() async throws { + let network = try FakeICMPNetwork(script: pathScript(destinationTTL: 2)) + defer { network.stop() } + let asked = FaultCounter() + let nxdomain: TestSeams.ResolveHost = { host, _ in + throw TracerouteError.resolutionFailed(host: host, details: "injected NXDOMAIN") + } + let tracer = offlineTracer( + SwiftFTRConfig( + maxHops: 3, noReverseDNS: true, publicIPResolver: .custom(CountingResolver(asked: asked)))) + let config = MultipathConfig(flowVariations: 2, maxPaths: 4, earlyStopThreshold: 2) + + let outcome = await network.install { + await TestSeams.$resolveHost.withValue(nxdomain) { + await resultOf { try await tracer.discoverPaths(to: "nowhere.test", config: config) } + } + } + guard case .failure(TracerouteError.resolutionFailed(_, let details)) = outcome else { + Issue.record("expected the resolution failure, got \(outcome)") + return + } + #expect(details == "injected NXDOMAIN") + #expect(asked.value == 0, "the caller's resolver was asked for a run that could not resolve") + #expect(network.probes.value == 0) + } + + @Test("A run's reported duration includes resolving its target") + func durationIncludesResolution() async throws { + let network = try FakeICMPNetwork(script: pathScript(destinationTTL: 1)) + defer { network.stop() } + let base = network.resolved + let slow: TestSeams.ResolveHost = { _, _ in + Thread.sleep(forTimeInterval: 0.3) // in its executor slot, not on the cooperative pool + return base + } + let tracer = offlineTracer( + SwiftFTRConfig(maxHops: 2, noReverseDNS: true), publicIP: "198.51.100.200") + let config = MultipathConfig( + flowVariations: 1, maxPaths: 1, earlyStopThreshold: 1, timeoutMs: 2000, maxHops: 2) + let topology = try await network.install { + try await TestSeams.$resolveHost.withValue(slow) { + try await measure(within: Self.watchdog) { + try await tracer.discoverPaths(to: "slow.test", config: config) + }.0 + } + } + #expect(topology.discoveryDuration >= 0.3, "\(topology.discoveryDuration) s omits the lookup") + } + + @Test( + "Cancellation during the run's one resolution reports who cancelled", + arguments: [false, true]) + func cancelledDuringParentResolution(byTracer: Bool) async throws { + let gate = StallGate() + defer { gate.open() } + let entered = FaultCounter() + let asked = FaultCounter() + let executor = BlockingIOExecutor(maximumConcurrentOperations: 1, name: "test.budget-cancel") + let stall: TestSeams.ResolveHost = { host, _ in + entered.increment() + gate.wait(limit: Self.hold) + throw TracerouteError.resolutionFailed(host: host, details: "stalled") + } + let tracer = offlineTracer( + SwiftFTRConfig( + maxHops: 3, noReverseDNS: true, publicIPResolver: .custom(CountingResolver(asked: asked)))) + + let outcome = try await TestSeams.$blockingIOExecutor.withValue(executor) { + try await TestSeams.$resolveHost.withValue(stall) { + let task = Task { try await tracer.discoverPaths(to: "gated.test") } + #expect(await eventually(within: Self.watchdog) { entered.value == 1 }) + return try await measure(within: Self.watchdog) { + if byTracer { await tracer.cancelActiveTraces() } else { task.cancel() } + return await task.result + }.0 + } + } + switch (byTracer, outcome) { + case (true, .failure(TracerouteError.cancelled)): break + case (false, .failure(let error)) where error is CancellationError: break + default: Issue.record("byTracer \(byTracer): \(outcome)") + } + #expect(asked.value == 0) + #expect(await tracer.activeTraces.isEmpty) + } +} diff --git a/Tests/SwiftFTRTests/ResolutionOffActorTests.swift b/Tests/SwiftFTRTests/ResolutionOffActorTests.swift index 542df528..3b4ef6fc 100644 --- a/Tests/SwiftFTRTests/ResolutionOffActorTests.swift +++ b/Tests/SwiftFTRTests/ResolutionOffActorTests.swift @@ -278,7 +278,7 @@ struct ResolutionOffActorTests { 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) + clock.jump(by: SwiftFTRConfig.defaultResolutionTimeout + 1) return await task.result }.0 } @@ -310,7 +310,7 @@ struct ResolutionOffActorTests { #expect( await eventually(within: Self.watchdog) { held.executor.submissions.value > before }) return try await measure(within: Self.watchdog) { - clock.jump(by: forwardResolutionLimit + 1) + clock.jump(by: SwiftFTRConfig.defaultResolutionTimeout + 1) return await task.result }.0 } From 0a687be028f2b3d3665afe6c68c6b5b36239df25 Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Fri, 27 Nov 2026 15:59:34 -0800 Subject: [PATCH 2/3] docs(resolution): the resolution budget option, and multipath resolving once Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01A8mvWou2vH56zDnkZkqT2X --- CHANGELOG.md | 15 +++++++++++-- .../SwiftFTR/SwiftFTR.docc/MigratingTo019.md | 22 ++++++++++++++++++- Sources/SwiftFTR/SwiftFTR.docc/Tracing.md | 5 +++-- docs/ROBUSTNESS-TESTING.md | 2 +- docs/reference/AI_REFERENCE.md | 9 +++++--- 5 files changed, 44 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9208cb7c..e6ff9f1a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,12 @@ Unreleased ### New public API +- **`SwiftFTRConfig.resolutionTimeout`** (default `SwiftFTRConfig.defaultResolutionTimeout`, + 20 s; decision 7): how long `trace`, `traceClassified`, `traceStream`, `ping` and + `discoverPaths` wait for their destination to resolve. It must be finite and in (0, Int32.max] + seconds, as `PingConfig.timeout` must; any other value throws `invalidConfiguration` before + anything resolves, from `ping` too. The option comes as a further initializer, so existing + calls and stated function types keep their meaning. - **`PublicIPResolver`**, and `SwiftFTRConfig.publicIPResolver` with a `PublicIPResolverStrategy`: `.library` (the default: STUN only, see Behavior changes), `.disabled` (send nothing) or `.custom(_:)` (the caller's resolver). A resolver answers a `PublicIPRequest` (one @@ -48,10 +54,15 @@ Unreleased ### Behavior changes +- **`discoverPaths` resolves its target once, before its public-IP question,** and every flow + probes that one address, keeping the caller's name as its destination. A round-robin name could + give flows different addresses before. A name that does not resolve now fails the run before + any public-IP question (no STUN traffic, no caller resolver asked), and + `NetworkTopology.discoveryDuration` includes the lookup. - **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 + their destination in an executor slot. The wait ends at a deadline: `resolutionTimeout` (20 s by + default) 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 diff --git a/Sources/SwiftFTR/SwiftFTR.docc/MigratingTo019.md b/Sources/SwiftFTR/SwiftFTR.docc/MigratingTo019.md index 6426ccf8..b8c6be2e 100644 --- a/Sources/SwiftFTR/SwiftFTR.docc/MigratingTo019.md +++ b/Sources/SwiftFTR/SwiftFTR.docc/MigratingTo019.md @@ -752,7 +752,8 @@ let asns = try await resolver.resolve(ipv4Addrs: ips, timeout: 0.1) **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 +`config.timeout` after a probe starts (traces and ping wait ``SwiftFTR/SwiftFTRConfig/resolutionTimeout``, +20 s by default); 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. @@ -774,3 +775,22 @@ Which address is probed does not change. **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. +## A multipath run resolves its target once, before its public-IP question + +**What changed.** `discoverPaths` resolves its target once, as IPv4, within +``SwiftFTR/SwiftFTRConfig/resolutionTimeout``, before it asks for the public address, and gives +that address to every flow. In 0.18 each flow resolved the name for itself. + +**What a caller sees.** + +- Every path in a ``NetworkTopology`` was probed at one address. A name with rotating records could + give flows different addresses in 0.18, so paths to different hosts were compared as one + destination's. Each path's `destinationHost` is still the name the caller passed. +- A name that does not resolve fails the run with `TracerouteError.resolutionFailed` before the + public-IP question: no STUN traffic is sent, a custom ``SwiftFTR/PublicIPResolver`` is not asked, + and nothing is cached. +- ``NetworkTopology/discoveryDuration`` includes the lookup. + +**What to change.** Nothing, unless code relied on flows reaching different addresses of a +rotating name: run `discoverPaths` once per address instead, passing each as a literal. + diff --git a/Sources/SwiftFTR/SwiftFTR.docc/Tracing.md b/Sources/SwiftFTR/SwiftFTR.docc/Tracing.md index feba78a3..d28e934a 100644 --- a/Sources/SwiftFTR/SwiftFTR.docc/Tracing.md +++ b/Sources/SwiftFTR/SwiftFTR.docc/Tracing.md @@ -55,8 +55,9 @@ for hop in classified.hops { address gets at most one second) and ``SwiftFTR/SwiftFTRConfig/publicIPDiscoveryTimeout`` bounds the one public-IP question a classified trace asks, after its probes. Hops whose lookups run out of time report numerically, and - classification proceeds without a public address. Resolving a hostname destination is not - bounded by either setting. + classification proceeds without a public address. Resolving a hostname destination is + bounded by ``SwiftFTR/SwiftFTRConfig/resolutionTimeout`` (20 s by default), which a + `discoverPaths` run spends once for all its flows. - Set ``SwiftFTR/SwiftFTRConfig/publicIP`` to use a known public address and bypass discovery for classified-trace enrichment of its address family, or ``SwiftFTR/SwiftFTRConfig/publicIPResolver`` to answer the question with your own diff --git a/docs/ROBUSTNESS-TESTING.md b/docs/ROBUSTNESS-TESTING.md index 3f23c147..bac57571 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; outlives its deadline; is cancelled while running or queued; every executor slot held | trace, traceClassified, traceStream, ping, tcpProbe, udpProbe | `ProbeWindow`, `ResolutionOffActor` | +| 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, discoverPaths | `ProbeWindow`, `ResolutionOffActor`, `ResolutionBudget` | | 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` | diff --git a/docs/reference/AI_REFERENCE.md b/docs/reference/AI_REFERENCE.md index 60c0654f..2765f2be 100644 --- a/docs/reference/AI_REFERENCE.md +++ b/docs/reference/AI_REFERENCE.md @@ -132,6 +132,7 @@ public struct SwiftFTRConfig: Sendable { public let asnResolverStrategy: ASNResolverStrategy // default .hybrid(.embedded) public let preferredFamily: PreferredFamily // default .auto public let publicIPResolver: PublicIPResolverStrategy // default .library + public let resolutionTimeout: TimeInterval // default 20 s; destination lookup wait for traces, ping, discoverPaths public init( maxHops: Int = 40, @@ -151,6 +152,8 @@ public struct SwiftFTRConfig: Sendable { ) // The same parameters plus `publicIPResolver: PublicIPResolverStrategy = .library`. public init(maxHops:...preferredFamily:publicIPResolver:) + // The same plus `resolutionTimeout: TimeInterval = SwiftFTRConfig.defaultResolutionTimeout`. + public init(maxHops:...publicIPResolver:resolutionTimeout:) } public enum PublicIPResolverStrategy: Sendable { @@ -177,8 +180,8 @@ public struct PublicIPObservation: Sendable, Hashable, Codable { Arguments must be passed in declaration order. Values are validated when an operation starts: `maxHops` outside 1...255, `maxWaitMs` below 1, `payloadSize` outside 0...65507, a negative or -non-finite `rdnsCacheTTL`, a negative `rdnsCacheSize`, or a non-positive hybrid `fallbackTimeout` -throws `TracerouteError.invalidConfiguration(reason:)`. The two enrichment budgets never throw: a +non-finite `rdnsCacheTTL`, a negative `rdnsCacheSize`, a non-positive hybrid `fallbackTimeout`, or +a `resolutionTimeout` that is not finite and in (0, Int32.max] (checked by `ping` too) throws `TracerouteError.invalidConfiguration(reason:)`. The two enrichment budgets never throw: a `rdnsLookupTimeout` or `publicIPDiscoveryTimeout` that is zero, negative, non-finite or out of range is replaced by its default (5 s and 6 s respectively). A `publicIP` that is not a globally routable address is not used, and it answers only traces of its own family. `interface`, `sourceIP` @@ -213,7 +216,7 @@ synthesizes an IPv6 address for an IPv4 literal, so tracing `1.1.1.1` can probe, 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` +wait at most `resolutionTimeout` (20 s by default) 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. From 0fa14f0eb9e67278fc43628a978560c1e4ae888f Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Fri, 27 Nov 2026 16:02:46 -0800 Subject: [PATCH 3/3] test(resolution): the budget test's clock moves only when the test moves it Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01A8mvWou2vH56zDnkZkqT2X --- Tests/SwiftFTRTests/ResolutionBudgetTests.swift | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Tests/SwiftFTRTests/ResolutionBudgetTests.swift b/Tests/SwiftFTRTests/ResolutionBudgetTests.swift index 67405df4..b0ebe438 100644 --- a/Tests/SwiftFTRTests/ResolutionBudgetTests.swift +++ b/Tests/SwiftFTRTests/ResolutionBudgetTests.swift @@ -31,6 +31,15 @@ struct ResolutionBudgetTests { } } + /// A clock that moves only when the test moves it, so no deadline passes on its own: a wait + /// bounded by the 20 s default instead of the configured budget outlives the watchdog. + final class ManualClock: @unchecked Sendable { + private let lock = NSLock() + private var value: TimeInterval = 1_000 + func jump(by seconds: TimeInterval) { lock.withLock { value += seconds } } + var now: @Sendable () -> TimeInterval { { self.lock.withLock { self.value } } } + } + /// A public-IP resolver that counts its questions and has no answer. struct CountingResolver: PublicIPResolver { let asked: FaultCounter @@ -49,7 +58,7 @@ struct ResolutionBudgetTests { let gate = StallGate() defer { gate.open() } let entered = FaultCounter() - let clock = MovableClock() + let clock = ManualClock() let executor = BlockingIOExecutor(maximumConcurrentOperations: 1, name: "test.budget-reach") let stall: TestSeams.ResolveHost = { host, _ in entered.increment()