Repository navigation
fix(ios): deadline-bounded Tailscale readiness so the first QR scan succeeds #10473
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 4 commits
12493bc
086133c
9c2a255
edda52b
961e3ec
f5bd695
4120fe6
2071d98
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,10 +1,18 @@ | ||
| internal import CMUXMobileCore | ||
| import Foundation | ||
| import os | ||
| import CmuxMobileDiagnostics | ||
|
|
||
| nonisolated private let tailscalePreparationLog = Logger( | ||
| subsystem: "com.manaflow.cmux", | ||
| category: "TailscalePreparation" | ||
| ) | ||
|
|
||
| /// Defers the actor-isolated route proof until `connect()` while preserving the | ||
| /// synchronous transport-factory contract. The proven interface is set on | ||
| /// `NWParameters` before Network.framework starts the connection. | ||
| actor CmxPreparingTailscaleByteTransport: CmxByteTransport { | ||
| private static let maximumPreparationAttempts = 3 | ||
| private let request: CmxByteTransportRequest | ||
| private let tailscaleRouteAuthority: any CmxTailscaleRouteAuthorizing | ||
| private let maximumReceiveLength: Int | ||
|
|
@@ -26,8 +34,17 @@ actor CmxPreparingTailscaleByteTransport: CmxByteTransport { | |
| } | ||
|
|
||
| func connect() async throws { | ||
| MobileDebugLog.shared.append("tailscale.transport.connect.begin") | ||
| let transport = try await preparedTransport() | ||
| try await transport.connect() | ||
| do { | ||
| try await transport.connect() | ||
| MobileDebugLog.shared.append("tailscale.transport.connect.success") | ||
| } catch { | ||
| MobileDebugLog.shared.append( | ||
| "tailscale.transport.connect.failed error=\(String(describing: error))" | ||
| ) | ||
|
Comment on lines
+47
to
+49
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win Sanitize dynamic error descriptions before writing diagnostics. The new
📍 Affects 2 files
🤖 Prompt for AI AgentsSource: Coding guidelines |
||
| throw error | ||
| } | ||
| } | ||
|
|
||
| func receive() async throws -> Data? { | ||
|
|
@@ -74,21 +91,48 @@ actor CmxPreparingTailscaleByteTransport: CmxByteTransport { | |
| let maximumReceiveLength = maximumReceiveLength | ||
| let connectTimeoutNanoseconds = connectTimeoutNanoseconds | ||
| task = Task { | ||
| do { | ||
| let prepared = try await authority.prepare(request: request) | ||
| try Task.checkCancellation() | ||
| return try CmxNetworkByteTransport( | ||
| request: request, | ||
| preparedTailscaleRoute: prepared, | ||
| tailscaleRouteAuthority: authority, | ||
| maximumReceiveLength: maximumReceiveLength, | ||
| connectTimeoutNanoseconds: connectTimeoutNanoseconds | ||
| for attempt in 1...Self.maximumPreparationAttempts { | ||
| MobileDebugLog.shared.append( | ||
| "tailscale.prepare.attempt number=\(attempt)/\(Self.maximumPreparationAttempts)" | ||
| ) | ||
| } catch is CancellationError { | ||
| throw CancellationError() | ||
| } catch { | ||
| throw CmxNetworkByteTransportError.tailscaleAuthorizationUnavailable | ||
| do { | ||
| let prepared = try await authority.prepare(request: request) | ||
| try Task.checkCancellation() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift 🧩 Analysis chain🏁 Script executed: #!/usr/bin/env bash
set -euo pipefail
rg -n -C 8 --glob '*.swift' \
'preparationTask|CmxPreparingTailscaleByteTransport|connect\(\)|\.cancel\(\)' \
Packages/iOS/CmuxMobileTransport Packages/iOS/CmuxMobileShellRepository: manaflow-ai/cmux Length of output: 50373 🏁 Script executed: #!/usr/bin/env bash
set -euo pipefail
file="Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/CmxPreparingTailscaleByteTransport.swift"
printf '%s\n' '--- target file ---'
cat -n "$file"
printf '%s\n' '--- focused references ---'
rg -n -C 12 --glob '*.swift' \
'preparationTask|CmxPreparingTailscaleByteTransport' \
Packages/iOS/CmuxMobileTransport Packages/iOS/CmuxMobileShellRepository: manaflow-ai/cmux Length of output: 34066 🏁 Script executed: #!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '--- transport protocol and factory call sites ---'
rg -n -C 10 --glob '*.swift' \
'protocol CmxByteTransport|func connect\(\) async throws|makeTransport\(for:|await .*\.connect\(\)|try await .*\.connect\(\)|transport\.close\(\)|\.close\(\)' \
Packages/iOS/CmuxMobileTransport/Sources Packages/iOS/CmuxMobileShell/Sources \
| head -n 1200
printf '%s\n' '--- cancellation-focused tests and implementations ---'
rg -n -C 12 --glob '*.swift' \
'cancel.*connect|connect.*cancel|CancellationError|SlowIgnoringCancellation|preparationCount|preparationTask' \
Packages/iOS/CmuxMobileTransport/Tests Packages/iOS/CmuxMobileShell/TestsRepository: manaflow-ai/cmux Length of output: 50373 🏁 Script executed: #!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '--- files that reference the preparing transport ---'
rg -l --glob '*.swift' 'CmxPreparingTailscaleByteTransport|preparesExactGrandfatheredTailscaleGrantAtConnectBoundary|preparationCount' \
Packages/iOS/CmuxMobileTransport Packages/iOS/CmuxMobileShell
printf '%s\n' '--- transport tests ---'
rg -n -C 18 --glob '*.swift' \
'preparesExactGrandfatheredTailscaleGrantAtConnectBoundary|preparationCount|CmxPreparingTailscaleByteTransport|connect\(\)' \
Packages/iOS/CmuxMobileTransport/Tests/CmuxMobileTransportTests
printf '%s\n' '--- callers of CmxByteTransport.connect in production ---'
rg -n -C 14 --glob '*.swift' \
'try await [A-Za-z0-9_\.]*connect\(\)|await [A-Za-z0-9_\.]*\.close\(\)' \
Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransportRepository: manaflow-ai/cmux Length of output: 50372 🏁 Script executed: #!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '--- protocol declaration and pinger lifecycle ---'
rg -n -C 16 --glob '*.swift' \
'protocol CmxByteTransport|CmxByteTransport\b|CmxNetworkRoutePinger|try await transport\.connect\(\)' \
Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport \
Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell \
| head -n 1000
printf '%s\n' '--- all repository references to the byte-transport protocol ---'
python3 - <<'PY'
from pathlib import Path
for path in Path("Packages/iOS").rglob("*.swift"):
text = path.read_text(errors="replace")
if "CmxByteTransport" not in text:
continue
print(f"\n{path}")
for number, line in enumerate(text.splitlines(), 1):
if "CmxByteTransport" in line or "try await transport.connect()" in line:
print(f"{number}: {line}")
PYRepository: manaflow-ai/cmux Length of output: 50372 🌐 Web query:
💡 Result: In Swift concurrency, cancellation is not automatically propagated to an unstructured Task (created via Task {... } or Task.detached {... }) when you await its result using task.value [1][2]. This behavior occurs because unstructured tasks exist outside the structured concurrency hierarchy (the task tree) [3][2]. While structured tasks (created via async let or task groups) are automatically cancelled when their parent scope is cancelled, unstructured tasks are independent entities that must be managed explicitly [4][5][2]. When you call await task.value, you are merely awaiting the result of that task [6]. The system does not implicitly register the awaiting context's cancellation state with the unstructured task [3][1]. Consequently, if the parent task that is awaiting the result is cancelled, the unstructured task will continue running unaffected unless you manually trigger its cancellation [1][7]. To propagate cancellation from a parent task to an unstructured task, you must explicitly handle it, typically by using withTaskCancellationHandler [1][7]. This allows you to register an onCancel closure that calls task.cancel when the surrounding context is cancelled [1][7]. Example of manual propagation: func example(task: Task<Success, Failure>) async throws -> Success { return try await withTaskCancellationHandler { try await task.value } onCancel: { task.cancel } } This design is intentional [3][8]. Because unstructured tasks are often intended to outlive the scope in which they were created or to be shared across multiple callers, automatic cancellation propagation upon awaiting would be ambiguous and often undesirable [3][1]. For example, if multiple callers were awaiting the same unstructured task, cancelling one caller would unexpectedly cancel the task for all other callers [1]. Citations:
🏁 Script executed: #!/usr/bin/env bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
import re
path = Path("Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/CmxPreparingTailscaleByteTransport.swift")
text = path.read_text()
assert re.search(r"private var preparationTask:\s*Task<", text)
assert re.search(r"task\s*=\s*Task\s*\{", text)
assert "preparationTask?.cancel()" in text
connect = text[text.index(" func connect()"):text.index(" func receive()")]
assert "withTaskCancellationHandler" not in connect
assert "task.cancel()" not in connect
assert "try Task.checkCancellation()" not in connect
prepared = text[text.index(" private func preparedTransport()"):text.rindex("\n}")]
assert "await task.value" in prepared
assert "withTaskCancellationHandler" not in prepared
retry_body = text[text.index("for attempt in"):text.index("throw CmxNetworkByteTransportError.tailscaleAuthorizationUnavailable", text.index("for attempt in"))]
assert retry_body.count("try Task.checkCancellation()") == 1
assert "try Task.checkCancellation()" not in retry_body[:retry_body.index("do {")]
print("static cancellation ownership check: PASS")
print("preparationTask is unstructured and canceled only by close(); connect()/preparedTransport() do not register caller cancellation.")
print("the retry loop checks cancellation after prepare(), but not before the next attempt.")
PYRepository: manaflow-ai/cmux Length of output: 410 Tie The only explicit cancellation path for 🤖 Prompt for AI AgentsSource: Path instructions |
||
| return try CmxNetworkByteTransport( | ||
| request: request, | ||
| preparedTailscaleRoute: prepared, | ||
| tailscaleRouteAuthority: authority, | ||
| maximumReceiveLength: maximumReceiveLength, | ||
| connectTimeoutNanoseconds: connectTimeoutNanoseconds | ||
| ) | ||
| } catch is CancellationError { | ||
| throw CancellationError() | ||
| } catch let error as CmxTailscaleRouteProofError | ||
| where error.isTransientReadinessFailure | ||
| { | ||
| MobileDebugLog.shared.append( | ||
| "tailscale.prepare.transient_failure attempt=\(attempt) error=\(String(describing: error))" | ||
| ) | ||
| tailscalePreparationLog.debug( | ||
| "Tailscale preparation attempt \(attempt, privacy: .public)/\(Self.maximumPreparationAttempts, privacy: .public) deferred: \(String(describing: error), privacy: .public)" | ||
| ) | ||
| guard attempt < Self.maximumPreparationAttempts else { | ||
| throw CmxNetworkByteTransportError.tailscaleAuthorizationUnavailable | ||
| } | ||
| // Yield so NWPathMonitor's callback can update the | ||
| // authority actor before the next proof attempt. | ||
| await Task.yield() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When the Tailscale interface is still becoming visible, File Used: .github/review-bot-rules/swift-blocking-runtime.md (source) |
||
| } catch { | ||
| MobileDebugLog.shared.append( | ||
| "tailscale.prepare.permanent_failure error=\(String(describing: error))" | ||
| ) | ||
| tailscalePreparationLog.error( | ||
| "Tailscale preparation failed: \(String(describing: error), privacy: .public)" | ||
| ) | ||
| throw CmxNetworkByteTransportError.tailscaleAuthorizationUnavailable | ||
| } | ||
| } | ||
| throw CmxNetworkByteTransportError.tailscaleAuthorizationUnavailable | ||
| } | ||
| preparationTask = task | ||
| } | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.