Skip to content

Commit 6b0ce9b

Browse files
fix(swift-ios): an offline computer waits the full backoff from when it failed
The passive refresh subtracted each whole tick from a computer's failure backoff, even when the failure arrived partway through that tick or the tick had been pulled earlier. A read that failed 6s into a 10s wait was retried 14s later instead of 20s. Each computer now keeps a retry deadline measured from when its failure was answered, compared against the injected clock at each tick. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent ad20c0a commit 6b0ce9b

2 files changed

Lines changed: 118 additions & 13 deletions

File tree

‎apps/swift-ios/App/NativeFeatureClient.swift‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5025,7 +5025,9 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
50255025
var cycleEnvironmentIDs: Set<String> = []
50265026
var cycleNeedsFastRefresh = false
50275027
var environments: [Environment] = []
5028-
var failureBackoffs: [String: Duration] = [:]
5028+
// Measured from when each failure was answered, not from ticks,
5029+
// because a tick can be pulled earlier or land mid-load.
5030+
var retryDeadlines: [String: ContinuousClock.Instant] = [:]
50295031
defer {
50305032
tickTask?.cancel()
50315033
loadTasks.values.forEach { $0.cancel() }
@@ -5042,7 +5044,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
50425044
} catch {
50435045
return
50445046
}
5045-
eventSink.yield(.tick(id: id, elapsed: interval))
5047+
eventSink.yield(.tick(id: id))
50465048
}
50475049
}
50485050

@@ -5058,7 +5060,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
50585060
return
50595061
}
50605062
switch event {
5061-
case let .tick(id, elapsedInterval):
5063+
case let .tick(id):
50625064
guard id == tickID else { continue }
50635065
tickTask = nil
50645066
let loadGenerations = self.environmentLoadGenerations
@@ -5089,14 +5091,12 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
50895091
continue
50905092
}
50915093
let passiveIDs = Set(passiveEnvironments.map(\.id))
5092-
failureBackoffs = failureBackoffs.reduce(into: [:]) { result, entry in
5093-
guard passiveIDs.contains(entry.key) else { return }
5094-
result[entry.key] = max(.zero, entry.value - elapsedInterval)
5095-
}
5094+
retryDeadlines = retryDeadlines.filter { passiveIDs.contains($0.key) }
5095+
let tickInstant = now()
50965096
// A load still running from an earlier tick keeps its
50975097
// place; it is neither restarted nor waited for.
50985098
let refreshableEnvironments = passiveEnvironments.filter {
5099-
failureBackoffs[$0.id, default: .zero] <= .zero && loadTasks[$0.id] == nil
5099+
(retryDeadlines[$0.id] ?? tickInstant) <= tickInstant && loadTasks[$0.id] == nil
51005100
}
51015101
guard !refreshableEnvironments.isEmpty else {
51025102
scheduleTick(after: fastInterval)
@@ -5125,11 +5125,11 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
51255125
if load.credentialRejected {
51265126
// Only re-pairing changes this. Re-pairing replaces
51275127
// the runtime client and restarts this loop.
5128-
failureBackoffs[load.environment.id] = .seconds(24 * 60 * 60)
5128+
retryDeadlines[load.environment.id] = now() + .seconds(24 * 60 * 60)
51295129
} else if load.shell == nil {
5130-
failureBackoffs[load.environment.id] = failureInterval
5130+
retryDeadlines[load.environment.id] = now() + failureInterval
51315131
} else {
5132-
failureBackoffs[load.environment.id] = nil
5132+
retryDeadlines[load.environment.id] = nil
51335133
}
51345134
}
51355135
self.reconcileEnvironmentLoads(loads, savedEnvironments: environments)
@@ -8982,7 +8982,7 @@ private struct CachedAttachmentURL {
89828982
}
89838983

89848984
private enum AggregateRefreshEvent: Sendable {
8985-
case tick(id: Int, elapsed: Duration)
8985+
case tick(id: Int)
89868986
case loaded(environmentID: String, loads: [EnvironmentShellLoad])
89878987
}
89888988

‎apps/swift-ios/Tests/FeatureTests/NativeMultiEnvironmentTests.swift‎

Lines changed: 106 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1843,13 +1843,85 @@ struct NativePassiveThreadRefreshTests {
18431843
await fixture.client.disconnect()
18441844
}
18451845

1846+
@Test(
1847+
"A failure answered mid-wait backs off from when it failed",
1848+
.timeLimit(.minutes(1))
1849+
)
1850+
func failureAnsweredMidWaitBacksOffFromWhenItFailed() async throws {
1851+
let refreshSleep = ControllableAggregateRefreshSleep()
1852+
let refreshClock = ManualAggregateRefreshClock()
1853+
let fixture = try await NativeMultiEnvironmentTests.makeFixture(
1854+
includeThirdEnvironment: true,
1855+
aggregateRefreshSleep: {
1856+
try await refreshSleep.sleep(for: $0)
1857+
},
1858+
aggregateRefreshNow: {
1859+
refreshClock.now()
1860+
}
1861+
)
1862+
defer { try? FileManager.default.removeItem(at: fixture.directory) }
1863+
_ = try await fixture.client.initialSnapshot()
1864+
let initialShellReads = await fixture.transport.shellReadCount(host: "three.example")
1865+
var events = fixture.client.events().makeAsyncIterator()
1866+
1867+
_ = await refreshSleep.waitUntilRequested(count: 1)
1868+
await fixture.transport.holdNextShellRead(host: "three.example")
1869+
refreshClock.advance(by: .seconds(5))
1870+
await refreshSleep.resume()
1871+
await fixture.transport.waitForHeldShellRead()
1872+
// The unchanged peer answers first and schedules the idle refresh at 15s.
1873+
let idleCadence = await refreshSleep.waitUntilRequested(count: 2)
1874+
#expect(idleCadence == .seconds(10))
1875+
1876+
// The slow computer fails at 11s, so it is not due again until 31s.
1877+
refreshClock.advance(by: .seconds(6))
1878+
await fixture.transport.setReachable(false, host: "three.example")
1879+
await fixture.transport.failHeldShellRead(host: "three.example")
1880+
while let event = await events.next() {
1881+
if case let .snapshot(snapshot) = event,
1882+
snapshot.environments.first(where: { $0.id == "three" })?.connectionState == .disconnected {
1883+
break
1884+
}
1885+
}
1886+
1887+
// With every read failing, a tick is only scheduled once each
1888+
// environment it read has answered, so read counts are settled.
1889+
await fixture.transport.setReachable(false, host: "two.example")
1890+
refreshClock.advance(by: .seconds(4))
1891+
await refreshSleep.resume()
1892+
let afterPeerFailure = await refreshSleep.waitUntilRequested(count: 3)
1893+
#expect(afterPeerFailure == .seconds(10))
1894+
1895+
// Two ten-second waits have passed, but only fourteen seconds since the failure.
1896+
refreshClock.advance(by: .seconds(10))
1897+
await refreshSleep.resume()
1898+
let nothingDue = await refreshSleep.waitUntilRequested(count: 4)
1899+
#expect(nothingDue == .seconds(5))
1900+
#expect(await fixture.transport.shellReadCount(host: "three.example") == initialShellReads + 1)
1901+
1902+
refreshClock.advance(by: .seconds(5))
1903+
await refreshSleep.resume()
1904+
_ = await refreshSleep.waitUntilRequested(count: 5)
1905+
#expect(await fixture.transport.shellReadCount(host: "three.example") == initialShellReads + 1)
1906+
1907+
refreshClock.advance(by: .seconds(5))
1908+
await refreshSleep.resume()
1909+
_ = await refreshSleep.waitUntilRequested(count: 6)
1910+
#expect(await fixture.transport.shellReadCount(host: "three.example") == initialShellReads + 2)
1911+
await fixture.client.disconnect()
1912+
}
1913+
18461914
@Test("A failed passive environment backs off without slowing an active peer")
18471915
func failedPassiveEnvironmentBacksOffWithoutSlowingActivePeer() async throws {
18481916
let refreshSleep = ControllableAggregateRefreshSleep()
1917+
let refreshClock = ManualAggregateRefreshClock()
18491918
let fixture = try await NativeMultiEnvironmentTests.makeFixture(
18501919
includeThirdEnvironment: true,
18511920
aggregateRefreshSleep: {
18521921
try await refreshSleep.sleep(for: $0)
1922+
},
1923+
aggregateRefreshNow: {
1924+
refreshClock.now()
18531925
}
18541926
)
18551927
defer { try? FileManager.default.removeItem(at: fixture.directory) }
@@ -1873,6 +1945,7 @@ struct NativePassiveThreadRefreshTests {
18731945
var events = fixture.client.events().makeAsyncIterator()
18741946
let firstCadence = await refreshSleep.waitUntilRequested(count: 1)
18751947
#expect(firstCadence == .seconds(5))
1948+
refreshClock.advance(by: firstCadence)
18761949
await refreshSleep.resume()
18771950
// The peer's answer alone can schedule the next refresh, so wait
18781951
// until the offline read has reported back before counting reads.
@@ -1890,6 +1963,7 @@ struct NativePassiveThreadRefreshTests {
18901963
#expect(await fixture.transport.shellReadCount(host: "two.example") == initialPeerReads + 1)
18911964

18921965
for requestCount in 2...4 {
1966+
refreshClock.advance(by: .seconds(5))
18931967
await refreshSleep.resume()
18941968
let cadence = await refreshSleep.waitUntilRequested(count: requestCount + 1)
18951969
#expect(cadence == .seconds(5))
@@ -1898,7 +1972,10 @@ struct NativePassiveThreadRefreshTests {
18981972
#expect(await fixture.transport.shellReadCount(host: "two.example") == initialPeerReads + requestCount)
18991973
}
19001974

1975+
// Twenty seconds after the failure, the offline computer is read again.
1976+
refreshClock.advance(by: .seconds(5))
19011977
await refreshSleep.resume()
1978+
await fixture.transport.waitUntilFailedShellReads(host: "three.example", count: 2)
19021979
_ = await refreshSleep.waitUntilRequested(count: 6)
19031980
#expect(await fixture.transport.failedShellReadCount(host: "three.example") == 2)
19041981
#expect(await fixture.transport.shellReadCount(host: "three.example") == initialShellReads + 2)
@@ -2228,6 +2305,11 @@ private actor MultiEnvironmentHTTPTransport: HTTPTransport {
22282305
private var shellReadsEnabledHosts: Set<String>
22292306
private var shellReadCounts: [String: Int] = [:]
22302307
private var failedShellReadCounts: [String: Int] = [:]
2308+
private var failedShellReadWaiters: [(
2309+
host: String,
2310+
count: Int,
2311+
continuation: CheckedContinuation<Void, Never>
2312+
)] = []
22312313
private var dispatched: [MultiEnvironmentDispatchRecord] = []
22322314
private var hostsDroppingNextCreateReply = Set<String>()
22332315
private var diffRequests: [(host: String, input: JSONValue)] = []
@@ -2285,6 +2367,22 @@ private actor MultiEnvironmentHTTPTransport: HTTPTransport {
22852367
failedShellReadCounts[host, default: 0]
22862368
}
22872369

2370+
func waitUntilFailedShellReads(host: String, count: Int) async {
2371+
if failedShellReadCounts[host, default: 0] >= count { return }
2372+
await withCheckedContinuation { failedShellReadWaiters.append((host, count, $0)) }
2373+
}
2374+
2375+
private func recordFailedShellRead(host: String) {
2376+
failedShellReadCounts[host, default: 0] += 1
2377+
let satisfied = failedShellReadWaiters.filter {
2378+
$0.host == host && failedShellReadCounts[host, default: 0] >= $0.count
2379+
}
2380+
failedShellReadWaiters.removeAll {
2381+
$0.host == host && failedShellReadCounts[host, default: 0] >= $0.count
2382+
}
2383+
satisfied.forEach { $0.continuation.resume() }
2384+
}
2385+
22882386
func dropNextCreateReply(host: String) {
22892387
hostsDroppingNextCreateReply.insert(host)
22902388
}
@@ -2320,6 +2418,13 @@ private actor MultiEnvironmentHTTPTransport: HTTPTransport {
23202418
held.continuation.resume(returning: held.response)
23212419
}
23222420

2421+
func failHeldShellRead(host: String) {
2422+
guard let held = heldShellRead else { return }
2423+
heldShellRead = nil
2424+
recordFailedShellRead(host: host)
2425+
held.continuation.resume(throwing: URLError(.cannotConnectToHost))
2426+
}
2427+
23232428
func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) {
23242429
let host = request.url?.host ?? ""
23252430
let path = request.url?.path ?? ""
@@ -2328,7 +2433,7 @@ private actor MultiEnvironmentHTTPTransport: HTTPTransport {
23282433
}
23292434
guard reachableHosts.contains(host) else {
23302435
if path == "/api/orchestration/shell" {
2331-
failedShellReadCounts[host, default: 0] += 1
2436+
recordFailedShellRead(host: host)
23322437
}
23332438
throw URLError(.cannotConnectToHost)
23342439
}

0 commit comments

Comments
 (0)