Stop the Tor restart from blocking the main thread on resume

On iOS every return to the foreground restarts Tor:
ensureRunningOnForeground() calls restartArti(), which called the Rust
arti_stop() inline. arti_stop() sleeps 200 ms while it holds Arti's
state lock, and restartArti() runs on the main actor, so the main thread
froze for about 200 ms on every resume (and on any other restart, such
as recovery after a network path change).

Nobody put this call on the main thread on purpose; it inherited it.
TorManager is @MainActor, so restartArti() runs there even though it
wraps its state changes in MainActor.run as if it ran somewhere else.
shutdownCompletely() already makes the same call from inside
Task.detached.

Await arti_stop() on a detached task instead. The restart still waits
for the stop to finish before it continues, so the sequence is the same:
TorWillRestart, the generation bump and flag resets, then the stop, then
the wait loop, then startIfNeeded(). The main actor is simply free while
the stop runs.

Deliberately unchanged:
- The full restart on every foreground. It has been there since #564
  ("iOS can suspend Tor harshly") and was device-verified in the v1.7.1
  pass (#1580); attempts to avoid it never proved out.
- The 200 ms sleep inside arti_stop(). It gives the old run_arti task
  time to clear IS_RUNNING and BOOTSTRAP_PROGRESS before arti_start sets
  them again, so it stays, and the stop still strictly precedes the
  start. No Rust or xcframework change.
- Everything else around the restart: the TorWillRestart notification,
  the generation bump, the flag resets, and AppRuntime's URLSession
  rebuild and relay reset.

Simulator A/B, same build with only the placement of this call toggled,
measured by a background probe that timed main-queue round trips every
10 ms for 10 s after .active:
- Before (7 resumes): arti_stop() took 202 ms on the main thread, and
  each resume had one 190-194 ms main-thread stall. Tor was ready
  1.48-1.49 s after .active.
- After (3 resumes): the worst main-thread stall per resume was
  16.7-17.6 ms. Tor was ready 1.49-1.50 s after .active and the relays
  reconnected.

TorManagerTests scans TorManager.swift and fails if arti_stop() is
called anywhere outside a Task.detached closure. Run against the
previous source, it flags the old call in restartArti().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jack 2026-10-24 16:02:17 -07:00
parent 30c58eee34
commit d49ddc72d2
2 changed files with 120 additions and 1 deletions

View File

@ -0,0 +1,115 @@
import Foundation
import XCTest
/// Keeps `arti_stop()` off the main actor.
///
/// The Rust side of `arti_stop()` sleeps for ~200 ms while it holds Arti's
/// state lock, so the old runtime can wind down before the next `arti_start`.
/// `TorManager` is `@MainActor`, so calling it directly from one of its
/// methods stalls the UI for that long. That is what every iOS return to the
/// foreground did while `restartArti()` called it inline: one ~190 ms
/// main-thread stall per resume in the simulator.
///
/// The FFI declaration is private to TorManager.swift, so that file is the
/// only place a call can appear. This scans it and requires every call to sit
/// inside a `Task.detached` closure.
final class TorManagerTests: XCTestCase {
private static let torManagerSource = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent() // Services
.deletingLastPathComponent() // bitchatTests
.deletingLastPathComponent() // repo root
.appendingPathComponent("localPackages/Arti/Sources/TorManager.swift")
func test_artiStop_isOnlyCalledInsideTaskDetached() throws {
let source = try String(contentsOf: Self.torManagerSource, encoding: .utf8)
let calls = Self.artiStopCalls(in: source)
XCTAssertFalse(
calls.isEmpty,
"Found no arti_stop() call in TorManager.swift. Fix the path, or move this guard along with the call."
)
let blocking = calls.filter { !$0.insideTaskDetached }.map { "TorManager.swift:\($0.line)" }
XCTAssertEqual(
blocking,
[],
"arti_stop() blocks for ~200 ms. Call it inside Task.detached (await .value when the caller has to wait for the stop), never directly on the main actor."
)
}
// MARK: - Scanner
private struct ArtiStopCall {
let line: Int
let insideTaskDetached: Bool
}
/// Finds every use of `arti_stop` other than its declaration, and whether
/// one of the braces enclosing it opened a `Task.detached` closure.
/// Comments and string literals are skipped, so neither the name nor a
/// brace inside them counts.
private static func artiStopCalls(in source: String) -> [ArtiStopCall] {
let text = Array(source)
var calls: [ArtiStopCall] = []
var openBraces: [Bool] = [] // one per unclosed `{`: did it open a Task.detached closure?
var nextBraceOpensTaskDetached = false
var line = 1
var index = 0
func hasPrefix(_ token: String) -> Bool {
text[index...].starts(with: token)
}
func isIdentifierCharacter(at position: Int) -> Bool {
guard text.indices.contains(position) else { return false }
let character = text[position]
return character.isLetter || character.isNumber || character == "_"
}
func followsFuncKeyword() -> Bool {
var position = index - 1
while position >= 0, text[position].isWhitespace { position -= 1 }
return position >= 3 && String(text[(position - 3)...position]) == "func"
}
/// Moves past the next `terminator`, counting the lines it crosses.
func skip(past terminator: String, honoringEscapes: Bool) {
while index < text.count, !hasPrefix(terminator) {
if honoringEscapes, text[index] == "\\" { index += 1 }
if index < text.count, text[index].isNewline { line += 1 }
index += 1
}
index += terminator.count
}
while index < text.count {
if hasPrefix("//") {
while index < text.count, !text[index].isNewline { index += 1 }
} else if hasPrefix("/*") {
index += 2
skip(past: "*/", honoringEscapes: false)
} else if hasPrefix("\"\"\"") {
index += 3
skip(past: "\"\"\"", honoringEscapes: true)
} else if hasPrefix("\"") {
index += 1
skip(past: "\"", honoringEscapes: true)
} else {
let character = text[index]
if character.isNewline {
line += 1
} else if character == "{" {
openBraces.append(nextBraceOpensTaskDetached)
nextBraceOpensTaskDetached = false
} else if character == "}" {
_ = openBraces.popLast()
} else if hasPrefix("Task.detached"), !isIdentifierCharacter(at: index - 1) {
nextBraceOpensTaskDetached = true
} else if hasPrefix("arti_stop"),
!isIdentifierCharacter(at: index - 1),
!isIdentifierCharacter(at: index + "arti_stop".count),
!followsFuncKeyword() {
calls.append(ArtiStopCall(line: line, insideTaskDetached: openBraces.contains(true)))
}
index += 1
}
}
return calls
}
}

View File

@ -415,7 +415,11 @@ public final class TorManager: ObservableObject {
self.lastRestartAt = Date()
}
_ = arti_stop()
// arti_stop() blocks its caller for ~200 ms, and this method runs on
// the main actor (every return to the foreground restarts Tor). Await
// the stop off the main actor so the UI stays responsive; it still
// completes before the restart continues.
_ = await Task.detached(priority: .userInitiated) { arti_stop() }.value
// Wait for stop
var waited = 0