From ed77c15305a93bb3481728aef6d3341efbe08ab1 Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Fri, 27 Nov 2026 16:11:21 -0800 Subject: [PATCH 1/4] test(classify): record the classifier's output for a table of inputs Recorded from TraceClassifier.classify on main before it is split into its ASN lookup and its categorization, so the split can be held to it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01A8mvWou2vH56zDnkZkqT2X --- .../SwiftFTRTests/ClassifierSplitTests.swift | 166 ++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 Tests/SwiftFTRTests/ClassifierSplitTests.swift diff --git a/Tests/SwiftFTRTests/ClassifierSplitTests.swift b/Tests/SwiftFTRTests/ClassifierSplitTests.swift new file mode 100644 index 0000000..57ca6cd --- /dev/null +++ b/Tests/SwiftFTRTests/ClassifierSplitTests.swift @@ -0,0 +1,166 @@ +import Foundation +import Testing + +@testable import SwiftFTR + +/// The classifier's output for a fixed table of inputs, recorded from `TraceClassifier.classify` +/// before it was split into its ASN lookup and its categorization. Both the public entry point and +/// the split parts must keep producing exactly these digests. +@Suite("Classifier split keeps today's output") +struct ClassifierSplitTests { + /// Answers from `mapping`, or throws when `fails`, and records what it was asked. + final class RecordingASNResolver: ASNResolver, @unchecked Sendable { + let mapping: [String: ASNInfo] + let fails: Bool + private let lock = NSLock() + private var asked: [String] = [] + private var timeouts: [TimeInterval] = [] + + init(_ mapping: [String: ASNInfo], fails: Bool = false) { + self.mapping = mapping + self.fails = fails + } + + func resolve(ipv4Addrs: [String], timeout: TimeInterval) async throws -> [String: ASNInfo] { + lock.withLock { + asked += ipv4Addrs + timeouts.append(timeout) + } + struct Refused: Error {} + if fails { throw Refused() } + return mapping.filter { ipv4Addrs.contains($0.key) } + } + + var record: String { + lock.withLock { "asked=\(asked.sorted()) timeouts=\(timeouts)" } + } + } + + struct Case: Sendable, CustomStringConvertible { + let name: String + let hops: [String?] + let destination: String + let publicIP: String? + let vpn: VPNContext? + let mapping: [String: ASNInfo] + let fails: Bool + let expected: String + var description: String { name } + } + + static let isp = ASNInfo(asn: 64501, name: "ISPNet") + static let transit = ASNInfo(asn: 64500, name: "TransitNet") + static let dest = ASNInfo(asn: 15133, name: "ExampleNet") + + static let cases: [Case] = [ + Case( + name: "ISP, transit and destination, with a gap filled", + hops: ["192.168.1.1", "100.64.0.5", "8.8.4.4", nil, "8.8.4.5", "1.1.1.1"], + destination: "1.1.1.1", publicIP: "9.9.9.9", vpn: nil, + mapping: ["9.9.9.9": isp, "8.8.4.4": transit, "8.8.4.5": transit, "1.1.1.1": dest], + fails: false, + expected: + "host=dest.example ip=1.1.1.1 pub=9.9.9.9 client=64501/ISPNet dest=15133/ExampleN" + + "et src=- dh=- ph=- | 1:192.168.1.1:LOCAL:-:-:h1-192.168.1.1:replied 2:100.64.0.5" + + ":ISP:-:-:h2-100.64.0.5:replied 3:8.8.4.4:TRANSIT:64500:TransitNet:h3-8.8.4.4:rep" + + "lied 4:*:TRANSIT:64500:TransitNet:-:timedOut 5:8.8.4.5:TRANSIT:64500:TransitNet:" + + "h5-8.8.4.5:replied 6:1.1.1.1:DESTINATION:15133:ExampleNet:h6-1.1.1.1:replied || " + + "asked=[\"1.1.1.1\", \"8.8.4.4\", \"8.8.4.5\", \"9.9.9.9\"] timeouts=[1.5]"), + Case( + name: "A resolver that throws classifies without ASN data", + hops: ["192.168.1.1", "9.9.9.10", nil, "8.8.4.4", "1.1.1.1"], + destination: "1.1.1.1", publicIP: "9.9.9.9", vpn: nil, + mapping: ["9.9.9.9": isp, "8.8.4.4": transit, "1.1.1.1": dest], + fails: true, + expected: + "host=dest.example ip=1.1.1.1 pub=9.9.9.9 client=-/- dest=-/- src=- dh=- ph=- | 1" + + ":192.168.1.1:LOCAL:-:-:h1-192.168.1.1:replied 2:9.9.9.10:TRANSIT:-:-:h2-9.9.9.10" + + ":replied 3:*:TRANSIT:-:-:-:timedOut 4:8.8.4.4:TRANSIT:-:-:h4-8.8.4.4:replied 5:1" + + ".1.1.1:DESTINATION:-:-:h5-1.1.1.1:replied || asked=[\"1.1.1.1\", \"8.8.4.4\", \"" + + "9.9.9.10\", \"9.9.9.9\"] timeouts=[1.5]"), + Case( + name: "Non-global after public, and a gap between different ASNs", + hops: ["10.0.0.1", "9.9.9.10", "10.1.1.1", nil, "8.8.4.4", nil, nil, "1.1.1.1"], + destination: "1.1.1.1", publicIP: "9.9.9.9", vpn: nil, + mapping: ["9.9.9.9": isp, "9.9.9.10": isp, "8.8.4.4": transit, "1.1.1.1": dest], + fails: false, + expected: + "host=dest.example ip=1.1.1.1 pub=9.9.9.9 client=64501/ISPNet dest=15133/ExampleN" + + "et src=- dh=- ph=- | 1:10.0.0.1:LOCAL:-:-:h1-10.0.0.1:replied 2:9.9.9.10:ISP:645" + + "01:ISPNet:h2-9.9.9.10:replied 3:10.1.1.1:ISP:-:-:h3-10.1.1.1:replied 4:*:UNKNOWN" + + ":-:-:-:timedOut 5:8.8.4.4:TRANSIT:64500:TransitNet:h5-8.8.4.4:replied 6:*:UNKNOW" + + "N:-:-:-:timedOut 7:*:UNKNOWN:-:-:-:timedOut 8:1.1.1.1:DESTINATION:15133:ExampleN" + + "et:h8-1.1.1.1:replied || asked=[\"1.1.1.1\", \"8.8.4.4\", \"9.9.9.10\", \"9.9.9." + + "9\"] timeouts=[1.5]"), + Case( + name: "VPN trace: private and CGNAT are VPN, public after is classified", + hops: ["10.8.0.1", "100.64.1.1", "8.8.4.4", "1.1.1.1"], + destination: "1.1.1.1", publicIP: nil, + vpn: VPNContext(traceInterface: "utun9", isVPNTrace: true, vpnLocalIPs: ["10.8.0.2"]), + mapping: ["8.8.4.4": transit, "1.1.1.1": dest], fails: false, + expected: + "host=dest.example ip=1.1.1.1 pub=- client=-/- dest=15133/ExampleNet src=- dh=- p" + + "h=- | 1:10.8.0.1:VPN:-:-:h1-10.8.0.1:replied 2:100.64.1.1:VPN:-:-:h2-100.64.1.1:" + + "replied 3:8.8.4.4:TRANSIT:64500:TransitNet:h3-8.8.4.4:replied 4:1.1.1.1:DESTINAT" + + "ION:15133:ExampleNet:h4-1.1.1.1:replied || asked=[\"1.1.1.1\", \"8.8.4.4\"] time" + + "outs=[1.5]"), + Case( + name: "IPv6 with link-local, global and a public address of the same AS as a hop", + hops: ["fe80::1%lo0", "2001:4860:4860::8888", nil, "2606:4700:4700::1111"], + destination: "2606:4700:4700::1111", publicIP: "2001:4860:4860::8844", vpn: nil, + mapping: [ + "2001:4860:4860::8844": isp, "2001:4860:4860::8888": isp, + "2606:4700:4700::1111": dest, + ], + fails: false, + expected: + "host=dest.example ip=2606:4700:4700::1111 pub=2001:4860:4860::8844 client=64501/" + + "ISPNet dest=15133/ExampleNet src=- dh=- ph=- | 1:fe80::1%lo0:LOCAL:-:-:h1-fe80::" + + "1%lo0:replied 2:2001:4860:4860::8888:ISP:64501:ISPNet:h2-2001:4860:4860::8888:re" + + "plied 3:*:UNKNOWN:-:-:-:timedOut 4:2606:4700:4700::1111:DESTINATION:15133:Exampl" + + "eNet:h4-2606:4700:4700::1111:replied || asked=[\"2001:4860:4860::8844\", \"2001:" + + "4860:4860::8888\", \"2606:4700:4700::1111\"] timeouts=[1.5]"), + Case( + name: "Nothing answered", + hops: [nil, nil, nil], destination: "1.1.1.1", publicIP: nil, vpn: nil, + mapping: [:], fails: false, + expected: + "host=dest.example ip=1.1.1.1 pub=- client=-/- dest=-/- src=- dh=- ph=- | 1:*:UNK" + + "NOWN:-:-:-:timedOut 2:*:UNKNOWN:-:-:-:timedOut 3:*:UNKNOWN:-:-:-:timedOut || ask" + + "ed=[\"1.1.1.1\"] timeouts=[1.5]"), + ] + + static func trace(_ c: Case) -> TraceResult { + let hops = c.hops.enumerated().map { index, ip in + TraceHop( + ttl: index + 1, ipAddress: ip, rtt: ip == nil ? nil : 0.001 * Double(index + 1), + reachedDestination: ip == c.destination, hostname: ip.map { "h\(index + 1)-\($0)" }) + } + return TraceResult( + destination: "dest.example", maxHops: c.hops.count, reached: true, hops: hops, + resolvedIP: c.destination) + } + + static func digest(_ t: ClassifiedTrace) -> String { + let hops = t.hops.map { + "\($0.ttl):\($0.ip ?? "*"):\($0.category.rawValue):\($0.asn.map(String.init) ?? "-"):" + + "\($0.asName ?? "-"):\($0.hostname ?? "-"):\($0.outcome)" + } + return + "host=\(t.destinationHost) ip=\(t.destinationIP) pub=\(t.publicIP ?? "-") " + + "client=\(t.clientASN.map(String.init) ?? "-")/\(t.clientASName ?? "-") " + + "dest=\(t.destinationASN.map(String.init) ?? "-")/\(t.destinationASName ?? "-") " + + "src=\(t.publicIPSource?.rawValue ?? "-") dh=\(t.destinationHostname ?? "-") " + + "ph=\(t.publicHostname ?? "-") | " + hops.joined(separator: " ") + } + + @Test("classify gives the recorded output", arguments: cases) + func classifyMatchesRecording(_ c: Case) async throws { + let resolver = RecordingASNResolver(c.mapping, fails: c.fails) + let result = try await TraceClassifier().classify( + trace: Self.trace(c), destinationIP: c.destination, resolver: resolver, timeout: 1.5, + publicIP: c.publicIP, vpnContext: c.vpn) + let observed = Self.digest(result) + " || " + resolver.record + #expect(observed == c.expected) + } +} From 74a917534a77b321471b5d62ee80a52bd9599d7a Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Fri, 27 Nov 2026 16:16:21 -0800 Subject: [PATCH 2/4] refactor(deadline): the pieces of an overall deadline, unused so far - TraceDeadline: one absolute instant on DiscoveryClock, with the cutoff for a phase cap (a tie is the deadline's) and its wake-up. - raceDeadline: work raced against a deadline, not joined; a passed deadline starts nothing; a late value or error is expiry; the caller's cancellation wins over expiry. DeadlineRace is generic over the value and the clock, and askWithinDeadline uses it unchanged. - RDNSCache.batchLookup(_:until:): answers gathered before the instant, kept apart from the cache; no query started or joined after it; nil is batchLookup(_:) exactly. - TraceClassifier.classify split into asnLookupAddresses and categorize, with the same output. Preparation for Deadline For Traces; no caller sees a change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01A8mvWou2vH56zDnkZkqT2X --- Sources/SwiftFTR/PublicIPResolver.swift | 48 ++- Sources/SwiftFTR/RDNSCache.swift | 80 ++++- Sources/SwiftFTR/Segmentation.swift | 41 ++- Sources/SwiftFTR/TestSeams.swift | 4 + Sources/SwiftFTR/TraceDeadline.swift | 93 ++++++ .../SwiftFTRTests/ClassifierSplitTests.swift | 16 + Tests/SwiftFTRTests/DeadlinePrepTests.swift | 290 ++++++++++++++++++ 7 files changed, 542 insertions(+), 30 deletions(-) create mode 100644 Sources/SwiftFTR/TraceDeadline.swift create mode 100644 Tests/SwiftFTRTests/DeadlinePrepTests.swift diff --git a/Sources/SwiftFTR/PublicIPResolver.swift b/Sources/SwiftFTR/PublicIPResolver.swift index f8b0e15..91e4979 100644 --- a/Sources/SwiftFTR/PublicIPResolver.swift +++ b/Sources/SwiftFTR/PublicIPResolver.swift @@ -176,9 +176,9 @@ func askWithinDeadline(_ resolver: any PublicIPResolver, _ request: PublicIPRequ let deadline = request.deadline // Nothing is started for a caller already cancelled. try Task.checkCancellation() - let race = DeadlineRace(deadline: deadline) + let race = DeadlineRace(hasPassed: { ContinuousClock.now >= deadline }) let arm = TestSeams.armPublicIPDeadline ?? sleepUntilDeadline - return try await withTaskCancellationHandler { + let outcome = try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { continuation in race.attach(continuation) let ask = Task { @@ -197,6 +197,8 @@ func askWithinDeadline(_ resolver: any PublicIPResolver, _ request: PublicIPRequ } onCancel: { race.commit(.cancellation) } + guard case .completed(let answer) = outcome else { return nil } + return answer } /// The default wake-up for ``askWithinDeadline(_:_:)``: a task sleeping until `deadline`. @@ -213,26 +215,36 @@ func askWithinDeadline(_ resolver: any PublicIPResolver, _ request: PublicIPRequ return { timer.cancel() } } -/// The race behind ``askWithinDeadline(_:_:)``: resumes one continuation with the first outcome -/// committed, from any thread and in any order, then runs the cleanup once. -final class DeadlineRace: @unchecked Sendable { +/// How a wait raced against a deadline ended, when it was not cancelled: with the work's value, +/// committed in time, or at the deadline. Distinct from any value, so a legitimate `nil` is not +/// mistaken for expiry. +enum DeadlineOutcome: Sendable { + case completed(Value) + case expired +} + +/// The race behind ``askWithinDeadline(_:_:)`` and ``raceDeadline(until:arm:_:)``: resumes one +/// continuation with the first outcome committed, from any thread and in any order, then runs the +/// cleanup once. +final class DeadlineRace: @unchecked Sendable { enum Event { - case answer(Result) + case answer(Result) case wake case cancellation } - private let deadline: ContinuousClock.Instant + private let hasPassed: @Sendable () -> Bool private let lock = NSLock() - private var continuation: CheckedContinuation? - private var outcome: Result? + private var continuation: CheckedContinuation, Error>? + private var outcome: Result, Error>? private var cleanup: (@Sendable () -> Void)? - init(deadline: ContinuousClock.Instant) { - self.deadline = deadline + /// - Parameter hasPassed: Whether the deadline has passed, read under the race's lock. + init(hasPassed: @escaping @Sendable () -> Bool) { + self.hasPassed = hasPassed } - func attach(_ newContinuation: CheckedContinuation) { + func attach(_ newContinuation: CheckedContinuation, Error>) { lock.lock() guard let outcome else { continuation = newContinuation @@ -244,15 +256,17 @@ final class DeadlineRace: @unchecked Sendable { } /// The one place an outcome is committed: the first committed is delivered. The clock is read - /// here, under the lock, for every event but cancellation (see ``askWithinDeadline(_:_:)``). + /// here, under the lock, for every event but cancellation, so an answer committed once the + /// deadline has passed is expiry, however late the wake-up runs; a wake-up that runs early + /// commits nothing. func commit(_ event: Event) { lock.lock() guard outcome == nil else { lock.unlock() return } - let passed = ContinuousClock.now >= deadline - let decided: Result + let passed = hasPassed() + let decided: Result, Error> switch event { case .cancellation: decided = .failure(CancellationError()) @@ -261,9 +275,9 @@ final class DeadlineRace: @unchecked Sendable { lock.unlock() return } - decided = .success(nil) + decided = .success(.expired) case .answer(let answer): - decided = passed ? .success(nil) : answer + decided = passed ? .success(.expired) : answer.map { .completed($0) } } outcome = decided let waiting = continuation diff --git a/Sources/SwiftFTR/RDNSCache.swift b/Sources/SwiftFTR/RDNSCache.swift index 83fef31..32472d0 100644 --- a/Sources/SwiftFTR/RDNSCache.swift +++ b/Sources/SwiftFTR/RDNSCache.swift @@ -164,7 +164,12 @@ actor RDNSCache { /// A lookup that belongs to work admitted before a reset (a batch's later addresses) asks /// nothing after it: its addresses are the old network's, and their timeouts are not evidence /// about the new one. - func lookup(_ ip: String, admittedBy admission: Admission) async -> String? { + /// + /// Past `deadline`, only a cached answer is returned: nothing is joined or started. That check + /// and the start of a query are one step on this actor, so no query starts after the instant. + func lookup(_ ip: String, admittedBy admission: Admission, until deadline: TraceDeadline? = nil) + async -> String? + { // A caller cancelled already, or admitted before a reset, starts nothing and joins nothing. guard !Task.isCancelled, admission.withLock({ $0 }), let question = ReverseDNSQuestion(address: ip) @@ -175,6 +180,7 @@ actor RDNSCache { if let entry = cache[key], now < entry.timestamp + ttl { return entry.hostname } + if deadline?.hasPassed == true { return nil } let task: Task if let running = inFlight[key] { @@ -269,6 +275,42 @@ actor RDNSCache { } } + /// ``batchLookup(_:)``, ending its wait at `deadline` with every answer its lookups gave before + /// the instant: `cut` is whether an address was still unanswered when the instant ended the wait. + /// The queries themselves run on to their own timeouts, and each outcome is applied once, as for + /// any other lookup. No query starts after the instant; past it, only cached answers are given. + /// A `nil` deadline is ``batchLookup(_:)`` exactly. A cancelled caller is released at once with + /// what it has. + func batchLookup(_ ips: [String], until deadline: TraceDeadline?) async -> ( + names: [String: String], cut: Bool + ) { + guard let deadline else { return (await batchLookup(ips), false) } + let asked = Set(ips) + let admission = admitting + if deadline.hasPassed { + var names: [String: String] = [:] + for ip in asked { + names[ip] = await lookup(ip, admittedBy: admission, until: deadline) + } + return (names, names.count < asked.count) + } + // The answers live here rather than in the cache, which may be too small or too short-lived to + // hold them, and only those that arrive before the instant are kept. + let answers = BatchAnswers(deadline, observe: TestSeams.observeBatchAnswer) + let outcome = try? await raceDeadline(until: deadline) { + await withTaskGroup(of: Void.self) { group in + for ip in asked { + group.addTask { + answers.record(ip, await self.lookup(ip, admittedBy: admission, until: deadline)) + } + } + } + } + let (names, answered) = answers.snapshot + guard case .expired? = outcome else { return (names, false) } + return (names, answered < asked.count) + } + /// Forgets every query in flight and cancels it, so a request from before a reset neither /// goes out afterwards nor keeps a lookup slot from the new network's questions. Admission is /// closed first: cancelling a query frees its slot, and one still waiting must not take it. @@ -342,3 +384,39 @@ actor RDNSCache { } } } + +/// The answers one ``RDNSCache/batchLookup(_:until:)`` has gathered: each address once, and only +/// while its deadline has not passed, so what the batch returns at the instant is what arrived +/// before it. +private final class BatchAnswers: @unchecked Sendable { + private let deadline: TraceDeadline + private let lock = NSLock() + private var names: [String: String] = [:] + private var answered = 0 + private let observe: (@Sendable (String) -> Void)? + + init(_ deadline: TraceDeadline, observe: (@Sendable (String) -> Void)?) { + self.deadline = deadline + self.observe = observe + } + + /// Records that `ip`'s lookup returned `hostname` (`nil`: no name), unless the instant has passed. + func record(_ ip: String, _ hostname: String?) { + lock.lock() + guard !deadline.hasPassed else { + lock.unlock() + return + } + answered += 1 + if let hostname { names[ip] = hostname } + lock.unlock() + observe?(ip) + } + + /// The names gathered, and how many addresses' lookups returned. + var snapshot: (names: [String: String], answered: Int) { + lock.lock() + defer { lock.unlock() } + return (names, answered) + } +} diff --git a/Sources/SwiftFTR/Segmentation.swift b/Sources/SwiftFTR/Segmentation.swift index b70d22d..edf80af 100644 --- a/Sources/SwiftFTR/Segmentation.swift +++ b/Sources/SwiftFTR/Segmentation.swift @@ -242,20 +242,37 @@ public struct TraceClassifier: Sendable { publicIP: String?, vpnContext: VPNContext? = nil ) async throws -> ClassifiedTrace { - // Gather IPs - let hopIPs: [String] = trace.hops.compactMap { $0.ipAddress } - var allIPs = Set(hopIPs) + let addresses = asnLookupAddresses( + trace: trace, destinationIP: destinationIP, publicIP: publicIP) + let asnMap = try? await resolver.resolve(ipv4Addrs: addresses, timeout: timeout) + return categorize( + trace: trace, destinationIP: destinationIP, asnMap: asnMap, publicIP: publicIP, + vpnContext: vpnContext) + } + + /// The addresses ``classify(trace:destinationIP:resolver:timeout:publicIP:vpnContext:)`` asks + /// its resolver about: every hop, the destination and the public address, each once, and only + /// the globally routable ones. Private and other non-global addresses have no meaningful origin + /// ASN and must not reach a network-backed resolver. + func asnLookupAddresses(trace: TraceResult, destinationIP: String, publicIP: String?) + -> [String] + { + var allIPs = Set(trace.hops.compactMap { $0.ipAddress }) allIPs.insert(destinationIP) - let resolvedPublicIP: String? = publicIP - if let providedIP = publicIP { - allIPs.insert(providedIP) - } + if let publicIP { allIPs.insert(publicIP) } + return Array(Set(allIPs.compactMap(asnLookupAddress))) + } - // Lookup only globally routable addresses. Private and other non-global - // addresses do not have meaningful origin ASN data and must not reach a - // network-backed resolver. - let resolverIPs = Set(allIPs.compactMap(asnLookupAddress)) - let asnMap = try? await resolver.resolve(ipv4Addrs: Array(resolverIPs), timeout: timeout) + /// Categories and interpolation for `trace` from the ASN answers in hand, with no lookup: + /// `asnMap` is `nil` when the lookup failed, which classifies as if no address had an answer. + func categorize( + trace: TraceResult, + destinationIP: String, + asnMap: [String: ASNInfo]?, + publicIP: String?, + vpnContext: VPNContext? + ) -> ClassifiedTrace { + let resolvedPublicIP: String? = publicIP let clientAS = resolvedPublicIP.flatMap { ip in asnLookupAddress(for: ip).flatMap { asnMap?[$0] } } diff --git a/Sources/SwiftFTR/TestSeams.swift b/Sources/SwiftFTR/TestSeams.swift index 7a0a432..bde1a00 100644 --- a/Sources/SwiftFTR/TestSeams.swift +++ b/Sources/SwiftFTR/TestSeams.swift @@ -158,4 +158,8 @@ enum TestSeams { /// Awaited by a `traceStream` producer once its trace has ended, just before it unregisters and /// finishes the stream, so a test can order `cancelActiveTraces()` before or after that step. @TaskLocal static var beforeStreamCommit: (@Sendable () async -> Void)? + + /// Called with each address whose answer a deadline-bounded reverse-DNS batch has kept, so a + /// test can pass the deadline only once an answer is in. + @TaskLocal static var observeBatchAnswer: (@Sendable (_ address: String) -> Void)? } diff --git a/Sources/SwiftFTR/TraceDeadline.swift b/Sources/SwiftFTR/TraceDeadline.swift new file mode 100644 index 0000000..5d89157 --- /dev/null +++ b/Sources/SwiftFTR/TraceDeadline.swift @@ -0,0 +1,93 @@ +import Foundation + +/// One operation's overall deadline: an absolute instant on one clock, taken once and never reset. +/// +/// A wait bounded by it is either handed the instant and holds it itself, or raced against it by +/// ``raceDeadline(until:arm:_:)``, never both, so an answer the work is entitled to give at the +/// instant cannot lose to a second timer aimed at the same one. +struct TraceDeadline: Sendable { + /// The instant, on `clock`. + let instant: TimeInterval + /// The clock `instant` is on, captured where the deadline was taken: queues and workers cannot + /// read the task-local test clock. + let clock: DiscoveryClock + + init(instant: TimeInterval, clock: DiscoveryClock) { + self.instant = instant + self.clock = clock + } + + /// `total` seconds from now on `clock`, or `nil` for positive infinity, which is no deadline. + static func after(_ total: TimeInterval, clock: DiscoveryClock = .current) -> TraceDeadline? { + guard total != .infinity else { return nil } + return TraceDeadline(instant: clock.now() + total, clock: clock) + } + + /// Whether the instant has passed. + var hasPassed: Bool { clock.hasPassed(instant) } + + /// The cutoff for a phase whose own cap is `cap` seconds from now: the earlier of the two, and + /// whether it is this deadline's instant. A tie is the instant, so the overall deadline decides. + func cutoff(cap: TimeInterval) -> (instant: TimeInterval, overallBinds: Bool) { + let own = clock.now() + cap + return own < instant ? (own, false) : (instant, true) + } + + /// Starts the wake-up for this deadline: `wake` runs once the instant has passed, unless the + /// returned stop is called first. A stopped wake-up never runs `wake`. + func armWake(_ wake: @escaping @Sendable () -> Void) -> @Sendable () -> Void { + let clock = clock + let instant = instant + let timer = Task { + await clock.sleep(until: instant) + if !Task.isCancelled { wake() } + } + return { timer.cancel() } + } +} + +/// Starts a wake-up that calls its argument at the deadline, and returns the function that stops it. +typealias ArmDeadlineWake = (_ wake: @escaping @Sendable () -> Void) -> @Sendable () -> Void + +/// `work`'s value if it is committed before `deadline`, else ``DeadlineOutcome/expired``. +/// +/// The work runs in a task of its own that this does not wait for, so work that never returns, or +/// ignores cancellation, cannot hold the caller; it is cancelled once the outcome is committed, and +/// the wake-up is stopped. A deadline already passed starts no work. A value or error committed +/// once the deadline has passed is expiry, decided under the race's lock. The calling task's +/// cancellation wins over expiry, but not over a value committed in time. +/// +/// - Parameter arm: Starts the wake-up; by default `deadline`'s own (``TraceDeadline/armWake(_:)``). +/// - Throws: `CancellationError` when the calling task is cancelled, or the work's own error when +/// it throws in time. +func raceDeadline( + until deadline: TraceDeadline, + arm: ArmDeadlineWake? = nil, + _ work: @escaping @Sendable () async throws -> Value +) async throws -> DeadlineOutcome { + try Task.checkCancellation() + guard !deadline.hasPassed else { return .expired } + let race = DeadlineRace(hasPassed: { deadline.hasPassed }) + let armWake = arm ?? deadline.armWake + let outcome = try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + race.attach(continuation) + let task = Task { + do { + race.commit(.answer(.success(try await work()))) + } catch { + race.commit(.answer(.failure(error))) + } + } + let stopWake = armWake { race.commit(.wake) } + race.onFinish { + task.cancel() + stopWake() + } + } + } onCancel: { + race.commit(.cancellation) + } + if case .expired = outcome, Task.isCancelled { throw CancellationError() } + return outcome +} diff --git a/Tests/SwiftFTRTests/ClassifierSplitTests.swift b/Tests/SwiftFTRTests/ClassifierSplitTests.swift index 57ca6cd..e3afd5a 100644 --- a/Tests/SwiftFTRTests/ClassifierSplitTests.swift +++ b/Tests/SwiftFTRTests/ClassifierSplitTests.swift @@ -163,4 +163,20 @@ struct ClassifierSplitTests { let observed = Self.digest(result) + " || " + resolver.record #expect(observed == c.expected) } + + /// The split parts, composed by hand as the trace will compose them, give the same output and + /// ask the same addresses; a lookup that throws is a `nil` map, as `try?` makes it. + @Test("The lookup addresses and categorization give the recorded output", arguments: cases) + func splitPartsMatchRecording(_ c: Case) async throws { + let classifier = TraceClassifier() + let trace = Self.trace(c) + let resolver = RecordingASNResolver(c.mapping, fails: c.fails) + let addresses = classifier.asnLookupAddresses( + trace: trace, destinationIP: c.destination, publicIP: c.publicIP) + let asnMap = try? await resolver.resolve(ipv4Addrs: addresses, timeout: 1.5) + let result = classifier.categorize( + trace: trace, destinationIP: c.destination, asnMap: asnMap, publicIP: c.publicIP, + vpnContext: c.vpn) + #expect(Self.digest(result) + " || " + resolver.record == c.expected) + } } diff --git a/Tests/SwiftFTRTests/DeadlinePrepTests.swift b/Tests/SwiftFTRTests/DeadlinePrepTests.swift new file mode 100644 index 0000000..b54ff7e --- /dev/null +++ b/Tests/SwiftFTRTests/DeadlinePrepTests.swift @@ -0,0 +1,290 @@ +import Foundation +import Testing + +@testable import SwiftFTR + +/// The pieces the overall deadline for classified traces is built from, each on a test clock: +/// ``TraceDeadline``, ``raceDeadline(until:arm:_:)`` and ``RDNSCache/batchLookup(_:until:)``. +/// Nothing in production uses them yet; these tests hold each to its contract on its own. +@Suite("Deadline preparation") +struct DeadlinePrepTests { + struct Late: Error {} + + /// A deadline 30 s ahead on a clock the test moves, and a wake-up that counts how often it was + /// armed and stopped, so a test can see that nothing is left running. + final class Staging: @unchecked Sendable { + let movable = MovableClock() + let clock: DiscoveryClock + let deadline: TraceDeadline + let armed = FaultCounter() + let stopped = FaultCounter() + var wakes = true + + init() { + clock = DiscoveryClock(now: movable.now, slice: 0.01) + deadline = TraceDeadline(instant: clock.now() + 30, clock: clock) + } + + func pass() { movable.jump(by: 31) } + + var arm: ArmDeadlineWake { { self.armCounting($0) } } + + func armCounting(_ wake: @escaping @Sendable () -> Void) -> @Sendable () -> Void { + armed.increment() + var stop: @Sendable () -> Void = {} + if wakes { stop = deadline.armWake(wake) } + let stopWake = stop + let stopped = self.stopped + return { + stopped.increment() + stopWake() + } + } + } + + @Test("A deadline's cutoff is the earlier instant, and a tie is the deadline's") + func cutoff() { + let staging = Staging() + let deadline = staging.deadline + let early = deadline.cutoff(cap: 10) + #expect(!early.overallBinds && early.instant < deadline.instant) + let late = deadline.cutoff(cap: 40) + #expect(late.overallBinds && late.instant == deadline.instant) + let frozen = DiscoveryClock(now: { 100 }, slice: 0.01) + let tie = TraceDeadline(instant: 130, clock: frozen).cutoff(cap: 30) + #expect(tie.overallBinds && tie.instant == 130) + #expect(TraceDeadline.after(.infinity, clock: frozen) == nil) + #expect(TraceDeadline.after(5, clock: frozen)?.instant == 105) + #expect(!deadline.hasPassed) + staging.pass() + #expect(deadline.hasPassed) + } + + @Test("A value in time is returned, and the wake-up is stopped") + func valueInTime() async throws { + let staging = Staging() + let outcome = try await raceDeadline(until: staging.deadline, arm: staging.arm) { 7 } + guard case .completed(let value) = outcome else { + Issue.record("expected a value, got \(outcome)") + return + } + #expect(value == 7) + #expect(staging.armed.value == 1 && staging.stopped.value == 1) + } + + @Test( + "At the deadline the caller is released while the work still runs, and the work is cancelled") + func expiry() async throws { + let staging = Staging() + let gate = StallGate() + defer { gate.open() } + let entered = FaultCounter() + let workCancelled = FaultCounter() + let race = Task { + try await raceDeadline(until: staging.deadline, arm: staging.arm) { + entered.increment() + // Ignores cancellation, so only the race can release the caller. + await withTaskCancellationHandler { + await gate.waitAsync(limit: 60) + } onCancel: { + workCancelled.increment() + } + return 7 + } + } + #expect(await eventually(within: 20) { entered.value == 1 }) + staging.pass() + let (outcome, _) = try await measure(within: 20) { try await race.value } + guard case .expired = outcome else { + Issue.record("expected expiry, got \(outcome)") + return + } + #expect(staging.armed.value == 1 && staging.stopped.value == 1) + #expect(await eventually(within: 20) { workCancelled.value == 1 }) + } + + @Test("A deadline already passed starts no work and arms no wake-up") + func passedBeforeStart() async throws { + let staging = Staging() + staging.pass() + let invoked = FaultCounter() + let outcome = try await raceDeadline(until: staging.deadline, arm: staging.arm) { + invoked.increment() + return 7 + } + guard case .expired = outcome else { + Issue.record("expected expiry, got \(outcome)") + return + } + #expect(invoked.value == 0 && staging.armed.value == 0) + } + + @Test("A value or an error committed after the deadline is expiry", arguments: [false, true]) + func lateOutcome(throwing: Bool) async throws { + let staging = Staging() + staging.wakes = false + let outcome = try await raceDeadline(until: staging.deadline, arm: staging.arm) { + staging.pass() + if throwing { throw Late() } + return 7 + } + guard case .expired = outcome else { + Issue.record("expected expiry, got \(outcome)") + return + } + #expect(staging.armed.value == 1 && staging.stopped.value == 1) + } + + @Test( + "The caller's cancellation releases it at once, also once the deadline has passed", + arguments: [false, true]) + func cancellation(afterDeadline: Bool) async throws { + let staging = Staging() + // No wake-up runs, so only the cancellation can decide the race. + staging.wakes = false + let gate = StallGate() + defer { gate.open() } + let entered = FaultCounter() + let race = Task { + try await raceDeadline(until: staging.deadline, arm: staging.arm) { + entered.increment() + await gate.waitAsync(limit: 60) + return 7 + } + } + #expect(await eventually(within: 20) { entered.value == 1 }) + if afterDeadline { staging.pass() } + race.cancel() + let (result, _) = try await measure(within: 20) { await resultOf { try await race.value } } + #expect(throws: CancellationError.self) { try result.get() } + #expect(staging.armed.value == 1 && staging.stopped.value == 1) + } + + // MARK: - Reverse-DNS batch + + static let a = "192.0.2.1" + static let b = "192.0.2.2" + static let c = "192.0.2.3" + + /// A PTR resolver that answers `answers` at once and holds `gated` addresses until `gate` opens + /// (ignoring cancellation), counting each address it is asked. + final class ScriptedPTR: @unchecked Sendable { + let gate = StallGate() + private let lock = NSLock() + private var asked: [String: Int] = [:] + let answers: [String: ReverseDNSLookupOutcome] + let gated: Set + /// The outcome a gated address gets once the gate opens: its answer, or `.cancelled` if its + /// query was cancelled meanwhile. + let cancelledQueries = FaultCounter() + + init(_ answers: [String: ReverseDNSLookupOutcome], gated: Set = []) { + self.answers = answers + self.gated = gated + } + + func count(_ address: String) -> Int { lock.withLock { asked[address, default: 0] } } + + var resolver: RDNSCache.Resolver { + { question, _ in + let address = [DeadlinePrepTests.a, DeadlinePrepTests.b, DeadlinePrepTests.c].first { + ReverseDNSQuestion(address: $0) == question + } + guard let address else { return .noSuchRecord } + self.lock.withLock { self.asked[address, default: 0] += 1 } + if self.gated.contains(address) { + await self.gate.waitAsync(limit: 60) + if Task.isCancelled { + self.cancelledQueries.increment() + return .cancelled + } + } + return self.answers[address] ?? .noSuchRecord + } + } + } + + @Test("At the deadline a batch returns the answers it has, though the cache keeps none") + func batchPartialsWithoutCache() async throws { + let staging = Staging() + let ptr = ScriptedPTR( + [Self.a: .answer("a.example"), Self.b: .answer("b.example")], gated: [Self.b]) + defer { ptr.gate.open() } + let cache = RDNSCache(maxSize: 0, lookupDeadline: 30, resolver: ptr.resolver) + let kept = FaultCounter() + let deadline = staging.deadline + let batch = Task { + await TestSeams.$observeBatchAnswer.withValue({ _ in kept.increment() }) { + await cache.batchLookup([Self.a, Self.b], until: deadline) + } + } + // A's answer is in the batch and B's query has been asked; only then does the deadline pass. + #expect(await eventually(within: 20) { kept.value == 1 && ptr.count(Self.b) == 1 }) + staging.pass() + let (result, _) = try await measure(within: 20) { await batch.value } + #expect(result.names == [Self.a: "a.example"]) + #expect(result.cut) + #expect(await cache.count == 0) + // B's query still runs: the batch left it. + #expect(await cache.inFlightCount == 1) + } + + @Test( + "Past the deadline a lookup starts no query and joins none; a cached answer still comes back") + func noQueryAfterDeadline() async throws { + let staging = Staging() + let ptr = ScriptedPTR( + [Self.a: .answer("a.example"), Self.b: .answer("b.example"), Self.c: .answer("c.example")], + gated: [Self.b]) + defer { ptr.gate.open() } + let cache = RDNSCache(lookupDeadline: 30, resolver: ptr.resolver) + // A is cached; B's query is in flight, held at the gate. + #expect(await cache.lookup(Self.a) == "a.example") + let holder = Task { await cache.lookup(Self.b) } + defer { holder.cancel() } + #expect(await eventually(within: 20) { ptr.count(Self.b) == 1 }) + staging.pass() + let (result, _) = try await measure(within: 20) { + await cache.batchLookup([Self.a, Self.b, Self.c], until: staging.deadline) + } + #expect(result.names == [Self.a: "a.example"]) + #expect(result.cut) + #expect(ptr.count(Self.c) == 0 && ptr.count(Self.b) == 1) + #expect(await cache.inFlightCount == 1) + } + + @Test("A query a batch left at its deadline runs on, and its answer is applied once") + func sharedQueryRunsOn() async throws { + let staging = Staging() + let ptr = ScriptedPTR([Self.b: .answer("b.example")], gated: [Self.b]) + defer { ptr.gate.open() } + let cache = RDNSCache(lookupDeadline: 30, resolver: ptr.resolver) + let batch = Task { await cache.batchLookup([Self.b], until: staging.deadline) } + #expect(await eventually(within: 20) { ptr.count(Self.b) == 1 }) + staging.pass() + let (result, _) = try await measure(within: 20) { await batch.value } + #expect(result.names.isEmpty && result.cut) + ptr.gate.open() + #expect(await eventually(within: 20) { await cache.count == 1 }) + #expect(ptr.cancelledQueries.value == 0) + // The answer is cached: a later lookup asks nothing. + #expect(await cache.lookup(Self.b) == "b.example") + #expect(ptr.count(Self.b) == 1) + } + + @Test("Without a deadline, or with one that does not pass, a batch gives today's result") + func batchWithoutDeadlineIsToday() async throws { + let answers: [String: ReverseDNSLookupOutcome] = [ + Self.a: .answer("a.example"), Self.b: .noSuchRecord, Self.c: .timedOut, + ] + let ips = [Self.a, Self.b, Self.c, Self.a] + let today = await RDNSCache(resolver: ScriptedPTR(answers).resolver).batchLookup(ips) + #expect(today == [Self.a: "a.example"]) + let none = await RDNSCache(resolver: ScriptedPTR(answers).resolver) + .batchLookup(ips, until: nil) + #expect(none.names == today && !none.cut) + let far = await RDNSCache(resolver: ScriptedPTR(answers).resolver) + .batchLookup(ips, until: Staging().deadline) + #expect(far.names == today && !far.cut) + } +} From 90e216a9df42b12b1f50996fd9434570f645aede Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Fri, 27 Nov 2026 16:45:18 -0800 Subject: [PATCH 3/4] test(deadline): wait for the wake-up to be stopped before counting it The race resumes its caller before it stops the wake-up, so reading the stop count at once could see zero on a correct run. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01A8mvWou2vH56zDnkZkqT2X --- Tests/SwiftFTRTests/DeadlinePrepTests.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Tests/SwiftFTRTests/DeadlinePrepTests.swift b/Tests/SwiftFTRTests/DeadlinePrepTests.swift index b54ff7e..1b4389b 100644 --- a/Tests/SwiftFTRTests/DeadlinePrepTests.swift +++ b/Tests/SwiftFTRTests/DeadlinePrepTests.swift @@ -69,6 +69,8 @@ struct DeadlinePrepTests { return } #expect(value == 7) + // The race resumes its caller before it stops the wake-up, so the stop is waited for. + #expect(await eventually(within: 20) { staging.stopped.value == 1 }) #expect(staging.armed.value == 1 && staging.stopped.value == 1) } @@ -99,6 +101,8 @@ struct DeadlinePrepTests { Issue.record("expected expiry, got \(outcome)") return } + // The race resumes its caller before it stops the wake-up, so the stop is waited for. + #expect(await eventually(within: 20) { staging.stopped.value == 1 }) #expect(staging.armed.value == 1 && staging.stopped.value == 1) #expect(await eventually(within: 20) { workCancelled.value == 1 }) } @@ -132,6 +136,8 @@ struct DeadlinePrepTests { Issue.record("expected expiry, got \(outcome)") return } + // The race resumes its caller before it stops the wake-up, so the stop is waited for. + #expect(await eventually(within: 20) { staging.stopped.value == 1 }) #expect(staging.armed.value == 1 && staging.stopped.value == 1) } @@ -157,6 +163,8 @@ struct DeadlinePrepTests { race.cancel() let (result, _) = try await measure(within: 20) { await resultOf { try await race.value } } #expect(throws: CancellationError.self) { try result.get() } + // The race resumes its caller before it stops the wake-up, so the stop is waited for. + #expect(await eventually(within: 20) { staging.stopped.value == 1 }) #expect(staging.armed.value == 1 && staging.stopped.value == 1) } From c42b867f4462b052154fabfd656df75b8f2b2091 Mon Sep 17 00:00:00 2001 From: "David E. Weekly" Date: Fri, 27 Nov 2026 16:47:15 -0800 Subject: [PATCH 4/4] fix(rdns): a deadline that ends a batch's wait keeps what the cache holds When the instant passed between the batch's first check and its race, the race expired without running a lookup and the batch returned nothing, even for an address already cached. At expiry the batch now fills any address it has no answer for from the cache, without asking. Shown by cachedAnswerSurvivesExpiryDuringSetup, which fails without the cache read. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01A8mvWou2vH56zDnkZkqT2X --- Sources/SwiftFTR/RDNSCache.swift | 15 +++++++++++++-- Tests/SwiftFTRTests/DeadlinePrepTests.swift | 20 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/Sources/SwiftFTR/RDNSCache.swift b/Sources/SwiftFTR/RDNSCache.swift index 32472d0..24fe22e 100644 --- a/Sources/SwiftFTR/RDNSCache.swift +++ b/Sources/SwiftFTR/RDNSCache.swift @@ -306,9 +306,20 @@ actor RDNSCache { } } } - let (names, answered) = answers.snapshot + var (names, _) = answers.snapshot guard case .expired? = outcome else { return (names, false) } - return (names, answered < asked.count) + // The instant ends the wait for missing answers; it does not discard one the cache already + // holds, whether it was there before the batch or arrived as the wait ended. + for ip in asked where names[ip] == nil { names[ip] = cachedHostname(ip) } + return (names, names.count < asked.count) + } + + /// The unexpired cached answer for `ip`, read without asking anything. + private func cachedHostname(_ ip: String) -> String? { + guard let key = ReverseDNSQuestion(address: ip)?.key, let entry = cache[key], + now() < entry.timestamp + ttl + else { return nil } + return entry.hostname } /// Forgets every query in flight and cancels it, so a request from before a reset neither diff --git a/Tests/SwiftFTRTests/DeadlinePrepTests.swift b/Tests/SwiftFTRTests/DeadlinePrepTests.swift index 1b4389b..f495c96 100644 --- a/Tests/SwiftFTRTests/DeadlinePrepTests.swift +++ b/Tests/SwiftFTRTests/DeadlinePrepTests.swift @@ -237,6 +237,26 @@ struct DeadlinePrepTests { #expect(await cache.inFlightCount == 1) } + @Test("A deadline that passes as the batch sets up still returns the answer the cache holds") + func cachedAnswerSurvivesExpiryDuringSetup() async throws { + let ptr = ScriptedPTR([Self.a: .answer("a.example")], gated: []) + let cache = RDNSCache(lookupDeadline: 30, resolver: ptr.resolver) + #expect(await cache.lookup(Self.a) == "a.example") + // The batch's first clock read is before the instant and every later one is past it, so the + // race expires without running a lookup. + let reads = FaultCounter() + let clock = DiscoveryClock( + now: { + reads.increment() + return reads.value == 1 ? 0 : 100 + }, slice: 0.01) + let deadline = TraceDeadline(instant: 30, clock: clock) + let result = await cache.batchLookup([Self.a, Self.b], until: deadline) + #expect(result.names == [Self.a: "a.example"]) + #expect(result.cut, "B was never answered") + #expect(ptr.count(Self.a) == 1 && ptr.count(Self.b) == 0, "a query started past the instant") + } + @Test( "Past the deadline a lookup starts no query and joins none; a cached answer still comes back") func noQueryAfterDeadline() async throws {