Skip to content

Commit c252743

Browse files
committed
fix(ios): reexecute finished reads without spending their ids
1 parent 6db42ef commit c252743

12 files changed

Lines changed: 213 additions & 79 deletions

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ extension RunnerTests {
190190
return unavailable
191191
}
192192
// Past the last fast refusal, this command's work is going to the device, so its `commandId` is
193-
// spent: a repeat of it is answered from the journal instead of running the device again. Only the
193+
// spent for a non-read command. Finished reads can run again after a lost reply. Only the
194194
// `.execute` verdict reaches this line, so a repeat of a spent id is refused at the transport and no
195195
// busy refusal here can follow the mark for the command it refuses (ADR 0005).
196196
commandJournal.markDispatched(command: command)

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

Lines changed: 26 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -36,18 +36,19 @@ struct RunnerCommandJournalEntry {
3636
/// again, and the sends of that new execution must not be answered by the delivery of the refusal that
3737
/// freed the id.
3838
let executionToken: Int
39+
let isReadOnly: Bool
3940
}
4041

4142
/// The journal's verdict on one command that carries a `commandId`.
4243
enum RunnerCommandAdmission {
43-
/// Nothing is running for this id and nothing has finished: the caller owns the one execution,
44+
/// The caller owns this execution,
4445
/// identified by `executionToken` for as long as that claim answers for it.
4546
case execute(executionToken: Int)
4647
/// An execution is claimed and has not finished: the caller runs nothing and is answered by that
4748
/// execution, the one `executionToken` names. `accept(command:registeringJoin:)` has already
4849
/// registered the send it gave this verdict.
4950
case join(executionToken: Int)
50-
/// Execution finished, and the work reached the device: the caller answers from the journal and
51+
/// Non-read execution finished after dispatch: the caller answers from the journal and
5152
/// never executes this command again. `answersShutdown` says whether the answer being handed over is
5253
/// the runner's own successful `shutdown` answer, which the caller owes the runner's end. Neither the
5354
/// repeat's request nor the command name alone can answer that: a caller may reuse a spent `commandId`
@@ -57,14 +58,13 @@ enum RunnerCommandAdmission {
5758

5859
/// The runner's one command-lifecycle record: what it holds for a `commandId`, whether that id may run,
5960
/// and what `status` answers for it. The transport asks this type before enqueuing anything, so one
60-
/// `commandId` is executed at most once in a runner process, and a command that already finished cannot be
61-
/// replayed onto the device by a repeat that arrives after its answer was delivered. The one release is
62-
/// `closedCommandIdSafetyValve`, and `pruneIfNeeded` states the bound it leaves.
61+
/// mutation id stays spent after execution, while a finished read can execute again after a lost reply.
62+
/// `closedCommandIdSafetyValve` releases the oldest marker; `pruneIfNeeded` states its bound.
6363
final class RunnerCommandJournal {
6464
private let lock = NSLock()
6565
private let maxEntries = 64
6666
/// Memory safety valve on closed-id retention, not an admission boundary: the journal keeps a closed
67-
/// id as long as it runs, and this only stops a runner from growing without limit. It is 64x the entry
67+
/// mutation id until its marker is evicted. It is 64x the entry
6868
/// window because a marker holds no outcome body, only the id. Tests read it rather than repeat it.
6969
static let closedCommandIdSafetyValve = 4096
7070
private let maxResponseJsonBytes = 16 * 1024
@@ -118,9 +118,10 @@ final class RunnerCommandJournal {
118118
register(executionToken)
119119
return .join(executionToken: executionToken)
120120
}
121-
// Nothing of this command ever reached the device, so the id carries no effect to protect and the
122-
// send that reuses it is that command's own first execution.
123-
guard entry.dispatched else {
121+
// Reads execute again after finishing, including after a lost reply or a recorded failure.
122+
// A pre-dispatch refusal also leaves the id reusable. Classification belongs to the recorded
123+
// command: renaming a spent mutation to a read must not bypass its admission history.
124+
guard entry.dispatched, !entry.isReadOnly else {
124125
return claim(command: command, commandId: commandId)
125126
}
126127
let outcome = recordedOutcome(for: entry)
@@ -133,8 +134,7 @@ final class RunnerCommandJournal {
133134
)
134135
}
135136

136-
/// Mints a claim identity. Callers hold the journal's lock, except for the no-`commandId` route, which
137-
/// needs no entry and only asks for a value no other claim carries.
137+
/// Callers hold the journal's lock, including for commands without an id.
138138
private func mintExecutionToken() -> Int {
139139
nextExecutionToken += 1
140140
return nextExecutionToken
@@ -146,8 +146,9 @@ final class RunnerCommandJournal {
146146
}
147147
}
148148

149-
/// Records that this command's work was handed to the device, as opposed to being refused while it
150-
/// was still queued. Until this point a refusal owes the caller a retry of the same `commandId`.
149+
/// Records the outcome that ended this command's execution: the state its `ok` implies, the response
150+
/// body where the command's trait retains a replayable one, and its error. Whether the id this record
151+
/// closes is spent is the separate `dispatched` mark `markDispatched` writes.
151152
func finish(command: Command, response: Response) {
152153
transition(command: command, reorders: true) { entry in
153154
entry.state = response.ok ? .completed : .failed
@@ -157,16 +158,13 @@ final class RunnerCommandJournal {
157158
}
158159
}
159160

160-
/// Records the failure that ended this command's execution. The typed wire code goes with it, the
161-
/// same one the transport puts on the live reply for the same throw: a repeat of this `commandId` is
162-
/// answered from this record, and a failure that arrives without its code reads to the daemon as an
163-
/// ordinary served refusal — which for a `MAIN_THREAD_TIMEOUT` would report the main thread drained
164-
/// when the command that just timed out is what occupied it.
161+
/// Records the failure that ended this command's execution. The typed wire code and the hint go with it,
162+
/// the same error body the transport puts on the live reply for the same throw: a repeat of this
163+
/// `commandId` is answered from this record, and a failure that arrives without its code reads to the
164+
/// daemon as an ordinary served refusal — which for a `MAIN_THREAD_TIMEOUT` would report the main thread
165+
/// drained when the command that just timed out is what occupied it.
165166
func fail(command: Command, error: Error) {
166-
let payload = ErrorPayload(
167-
code: RunnerTests.wireErrorCode(for: error),
168-
message: error.localizedDescription
169-
)
167+
let payload = RunnerTests.thrownErrorPayload(for: error)
170168
transition(command: command, reorders: true) { entry in
171169
entry.state = .failed
172170
entry.error = payload
@@ -205,7 +203,8 @@ final class RunnerCommandJournal {
205203
responseOk: nil,
206204
responseJson: nil,
207205
error: nil,
208-
executionToken: executionToken
206+
executionToken: executionToken,
207+
isReadOnly: command.traits.isReadOnly
209208
)
210209
order.removeAll { $0 == commandId }
211210
order.append(commandId)
@@ -257,9 +256,9 @@ final class RunnerCommandJournal {
257256
return
258257
}
259258
order.removeAll { $0 == removable }
260-
// Only work that reached the device spends its id. A pruned refusal leaves the id free, which is
261-
// what the busy resend of the same `commandId` depends on (ADR 0005).
262-
if entries[removable]?.dispatched == true {
259+
// Only dispatched non-read commands spend their ids. Reads and pre-dispatch refusals leave
260+
// no marker, so resends can execute after the outcome is pruned (ADR 0005).
261+
if let entry = entries[removable], entry.dispatched, !entry.isReadOnly {
263262
// The two closed-id structures stay one-to-one, and nothing here needs a duplicate check to keep
264263
// them that way: an id enters `closedCommandIds` only in this branch, and an id whose entry this
265264
// journal no longer holds can be claimed again only once the marker is gone — which the valve
@@ -325,7 +324,7 @@ final class RunnerCommandJournal {
325324
code: RunnerTests.RunnerWireErrorCode.commandAlreadyFinished,
326325
message: reason,
327326
hint:
328-
"Read the screen with snapshot before sending anything else: the finished command's effect is already on the device."
327+
"Read the screen with snapshot before sending anything else: the finished command's work reached the device, so it may already have had its effect."
329328
)
330329
)
331330
}

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

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,19 +108,23 @@ struct CommandTraits {
108108
let convertsRecordedFailure: Bool
109109
/// Whether the journal may store this command's response JSON, subject to its byte limit.
110110
let retainsJournalResponseJson: Bool
111+
/// Whether a finished command may execute again under the same id after a lost reply.
112+
let isReadOnly: Bool
111113

112114
init(
113115
isInteraction: Bool = false,
114116
retryOnSessionLoss: Bool = false,
115117
launchPolicy: CommandLaunchPolicy,
116118
convertsRecordedFailure: Bool = false,
117-
retainsJournalResponseJson: Bool
119+
retainsJournalResponseJson: Bool,
120+
isReadOnly: Bool = false
118121
) {
119122
self.isInteraction = isInteraction
120123
self.retryOnSessionLoss = retryOnSessionLoss
121124
self.launchPolicy = launchPolicy
122125
self.convertsRecordedFailure = convertsRecordedFailure
123126
self.retainsJournalResponseJson = retainsJournalResponseJson
127+
self.isReadOnly = isReadOnly
124128
}
125129
}
126130

@@ -147,7 +151,8 @@ fileprivate extension CommandTraits {
147151
static func appRead(retainsJournalResponseJson: Bool) -> CommandTraits {
148152
CommandTraits(
149153
retryOnSessionLoss: true, launchPolicy: .existingApp,
150-
retainsJournalResponseJson: retainsJournalResponseJson
154+
retainsJournalResponseJson: retainsJournalResponseJson,
155+
isReadOnly: true
151156
)
152157
}
153158

@@ -166,7 +171,8 @@ fileprivate extension CommandTraits {
166171
static func runnerCaptureRead(retainsJournalResponseJson: Bool) -> CommandTraits {
167172
CommandTraits(
168173
retryOnSessionLoss: true, launchPolicy: .noApp,
169-
retainsJournalResponseJson: retainsJournalResponseJson
174+
retainsJournalResponseJson: retainsJournalResponseJson,
175+
isReadOnly: true
170176
)
171177
}
172178

@@ -191,7 +197,8 @@ fileprivate extension CommandTraits {
191197
static let presentedSurfaceQuery = CommandTraits(
192198
retryOnSessionLoss: true,
193199
launchPolicy: .presentedSurface,
194-
retainsJournalResponseJson: true
200+
retainsJournalResponseJson: true,
201+
isReadOnly: true
195202
)
196203
}
197204

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

Lines changed: 8 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,10 @@ extension RunnerTests {
194194
// spent `commandId` under another command name, and what it receives is still the recorded
195195
// command's outcome. `finish()` guards its own expectation against being fulfilled twice, so a
196196
// shutdown that several sends receive is harmless.
197+
// `jsonResponse` stamps the outcome it is given, so a replayed success reports the main thread's
198+
// occupancy NOW rather than the occupancy the recorded answer was written under — the stored body
199+
// is kept unstamped for exactly this reason. That is what lets a replayed answer settle a stale
200+
// busy report on the daemon side; the journal itself observed nothing.
197201
NSLog(
198202
"AGENT_DEVICE_RUNNER_COMMAND_ALREADY_FINISHED command=%@ commandId=%@",
199203
command.command.rawValue,
@@ -338,34 +342,11 @@ extension RunnerTests {
338342
Response(ok: false, error: ErrorPayload(code: code, message: message, hint: hint))
339343
}
340344

341-
/// Turns a thrown command error into its wire response, under the one code mapping the journal's
342-
/// failure record uses, so the answer a resend reads from the journal cannot disagree with the answer
343-
/// the caller lost.
345+
/// Turns a thrown command error into its wire response, under the one error body the journal's failure
346+
/// record uses, so the answer a resend reads from the journal cannot disagree with the answer the caller
347+
/// lost.
344348
func commandFailedResponse(from error: Error) -> Response {
345-
let code = RunnerTests.wireErrorCode(for: error)
346-
// The hint says the watchdog abandoned this command's work, so it goes only with the error the
347-
// watchdog throws. The code is read from the one owner it derives from, but the branch keys on the
348-
// error's own identity: a later code that `wireErrorCode(for:)` learns to derive must not pull an
349-
// unrelated throw into this claim.
350-
let nsError = error as NSError
351-
if nsError.domain == RunnerErrorDomain.general,
352-
nsError.code == RunnerErrorCode.mainThreadExecutionTimedOut
353-
{
354-
return Response(
355-
ok: false,
356-
error: ErrorPayload(
357-
code: code,
358-
message: error.localizedDescription,
359-
hint:
360-
"The runner abandoned this command's main-thread work past its execution watchdog and it is still draining. Wait and retry, or use a screenshot and interact by coordinates."
361-
)
362-
)
363-
}
364-
return errorResponse(
365-
code: code,
366-
message: error.localizedDescription,
367-
hint: "Check the runner log for XCTest details, then retry after the app is foregrounded if this was a timeout or activation failure."
368-
)
349+
Response(ok: false, error: RunnerTests.thrownErrorPayload(for: error))
369350
}
370351

371352
private func httpResponse(status: Int, body: String) -> Data {

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,20 @@ final class RunnerTests: XCTestCase {
6464
: "COMMAND_FAILED"
6565
}
6666

67+
/// A replayed failure must carry the same code and recovery hint as its live reply.
68+
static func thrownErrorPayload(for error: Error) -> ErrorPayload {
69+
let nsError = error as NSError
70+
let abandoned = nsError.domain == RunnerErrorDomain.general
71+
&& nsError.code == RunnerErrorCode.mainThreadExecutionTimedOut
72+
return ErrorPayload(
73+
code: wireErrorCode(for: error),
74+
message: error.localizedDescription,
75+
hint: abandoned
76+
? "The runner abandoned this command's main-thread work past its execution watchdog and it is still draining. Wait and retry, or use a screenshot and interact by coordinates."
77+
: "Check the runner log for XCTest details, then retry after the app is foregrounded if this was a timeout or activation failure."
78+
)
79+
}
80+
6781
static let springboardBundleId = "com.apple.springboard"
6882
// SpringBoard hosts blocking system modals on iOS/visionOS; tvOS (PineBoard/HeadBoard)
6983
// and macOS have no such host, so there is nothing to probe there.

0 commit comments

Comments
 (0)