Skip to content

Commit 5c87457

Browse files
committed
fix(apple): drain coalesced shutdown responses before closing
1 parent 39f7f65 commit 5c87457

4 files changed

Lines changed: 45 additions & 4 deletions

File tree

‎apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,10 +133,11 @@ extension RunnerTests {
133133
remainder: Data
134134
) {
135135
let closeConnection = !request.keepsConnectionAlive || result.shouldFinish
136+
if result.shouldFinish { shutdownResponseWrites.enter() }
136137
sendResponse(result.response, over: connection, closeConnection: closeConnection) { [weak self] sent in
137138
guard let self else { return }
138139
if result.shouldFinish {
139-
self.finish()
140+
self.shutdownResponseWrites.leave()
140141
} else if sent && !closeConnection {
141142
self.readNextRequest(over: connection, token: token, buffered: remainder)
142143
}
@@ -327,6 +328,10 @@ extension RunnerTests {
327328
for waiter in waiters {
328329
waiter(result)
329330
}
331+
// Register after every waiter starts its write, so a fast response cannot close slower peers.
332+
if result.shouldFinish {
333+
shutdownResponseWrites.notify(queue: transportQueue) { self.finish() }
334+
}
330335
}
331336

332337
// MARK: - Response Encoding
@@ -390,8 +395,6 @@ extension RunnerTests {
390395

391396
private func finish() {
392397
closeTransport()
393-
// Guard against double-fulfill: coalesced shutdown sends deliver one result to
394-
// multiple waiters, each of which may ask to finish.
395398
doneExpectation?.fulfill()
396399
doneExpectation = nil
397400
}

‎apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ final class RunnerTests: XCTestCase {
6161
var listenerToken: RunnerListenerToken?
6262
var doneExpectation: XCTestExpectation?
6363
var transportConnections: [ObjectIdentifier: NWConnection] = [:]
64+
let shutdownResponseWrites = DispatchGroup()
6465
let transportQueue = DispatchQueue(label: "agent-device.runner.transport")
6566
let commandExecutionQueue = DispatchQueue(label: "agent-device.runner.commands")
6667
let app = XCUIApplication()

‎apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+TransportTests.swift‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,40 @@ extension RunnerTests {
344344
XCTAssertEqual(commandJournal.status(normalizedCommandId: "after-shutdown").lifecycleState, RunnerCommandLifecycleState.notAccepted.rawValue)
345345
}
346346

347+
func testCoalescedShutdownDeliversEveryResponseBeforeClosingTransport() throws {
348+
let listener = try startTransportListener()
349+
defer { listener.cancel() }
350+
let port = try XCTUnwrap(listener.port)
351+
let sockets = (0..<32).map { _ in TransportSocket(port: port) }
352+
defer { sockets.forEach { $0.connection.cancel() } }
353+
354+
let releaseCommand = DispatchSemaphore(value: 0)
355+
commandExecutionQueue.async { releaseCommand.wait() }
356+
defer { releaseCommand.signal() }
357+
for socket in sockets {
358+
try socket.send(rawCommand(#"{"command":"shutdown","commandId":"shared-shutdown"}"#))
359+
}
360+
let deadline = Date().addingTimeInterval(3)
361+
var waiterCount = 0
362+
repeat {
363+
inFlightCommandLock.lock()
364+
waiterCount = inFlightCommandWaiters["shared-shutdown"]?.count ?? 0
365+
inFlightCommandLock.unlock()
366+
if waiterCount == sockets.count - 1 { break }
367+
Thread.sleep(forTimeInterval: 0.01)
368+
} while Date() < deadline
369+
XCTAssertEqual(waiterCount, sockets.count - 1)
370+
releaseCommand.signal()
371+
372+
for socket in sockets {
373+
let reply = try socket.response()
374+
XCTAssertEqual(reply.status, 200)
375+
XCTAssertTrue(try reply.envelope().ok)
376+
XCTAssertTrue(reply.head.contains("Connection: close"))
377+
try socket.expectEOF()
378+
}
379+
}
380+
347381
func testHttpIdleExpiryPreservesUnusedLoopbackListenerWatch() throws {
348382
let listener = try startTransportListener()
349383
defer { listener.cancel() }

‎apple/runner/RUNNER_PROTOCOL.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,13 @@ The Apple runner speaks a small internal HTTP+JSON protocol between the TypeScri
1111
- HTTP/1.1 connections persist by default. `Connection: close` ends them after the response.
1212
- HTTP/1.0 connections persist only when the request includes `Connection: keep-alive`.
1313
- Pipelined requests run in order. Each request repeats token, route, and length validation.
14-
- Shutdown and framing or authentication refusals close the connection. Shutdown also closes other open connections.
14+
- Shutdown and framing or authentication refusals close the connection. Shutdown closes other open connections after all coalesced shutdown responses finish sending.
1515

1616
The daemon sends to `http://127.0.0.1:<port>/command` for simulator and macOS runners. A physical device is reached over usbmux when cabled, otherwise at its CoreDevice tunnel address; it is never dialed at this Mac's loopback.
1717

18+
Loopback and CoreDevice tunnel requests use the global `fetch` connection pool to reuse TCP
19+
connections. The usbmux transport sends `Connection: close` and opens a connection per request.
20+
1821
### Listener binding
1922

2023
Simulators and macOS bind `127.0.0.1` only. A physical device listens on every interface: a cabled

0 commit comments

Comments
 (0)