Skip to content

Commit d22b69a

Browse files
committed
fix(ios): let the command journal decide admission once per commandId
The runner kept command lifecycle in two places: the transport's in-flight id set and the command journal. They were cleared at different moments, so a repeat of a commandId whose answer had already been delivered was admitted again and ran the command a second time — a second tap. Pruning could also evict a command that was still executing, which the daemon reads as notAccepted, and a late transition for a pruned id could invent an entry the runner never claimed. RunnerCommandJournal now answers each inbound request with one verdict: execute, join, or terminal. A terminal id is answered from the recorded outcome, then the recorded error, then COMMAND_ALREADY_FINISHED. Pruning drops only closed entries, and an update never opens a record again. The journal closes a commandId at the last fast RUNNER_BUSY or RUNNER_WEDGED refusal, so the read-only busy resend keeps its reused id (ADR 0005). The transport keeps only the waiter list.
1 parent f7879cf commit d22b69a

7 files changed

Lines changed: 442 additions & 111 deletions

File tree

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,10 @@ extension RunnerTests {
189189
if let unavailable = runnerUnavailableResponse(command: command) {
190190
return unavailable
191191
}
192+
// 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. The
194+
// read-only busy resend arrives before this point, never after it (ADR 0005).
195+
commandJournal.markDispatched(command: command)
192196
if command.command == .snapshot {
193197
return try executeSnapshotDispatched(command: command)
194198
}

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

Lines changed: 139 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -10,41 +10,91 @@ enum RunnerCommandLifecycleState: String {
1010
case failed
1111
}
1212

13+
extension RunnerCommandLifecycleState {
14+
/// Whether execution has ended for an entry in this state. `notAccepted` is never written to an
15+
/// entry — `status` synthesizes it for an id the journal does not hold — so it is not terminal.
16+
var isTerminal: Bool {
17+
self == .completed || self == .failed
18+
}
19+
}
20+
1321
struct RunnerCommandJournalEntry {
1422
let commandId: String
1523
let command: String
1624
var state: RunnerCommandLifecycleState
1725
var responseOk: Bool?
1826
var responseJson: String?
1927
var error: ErrorPayload?
28+
/// Whether any of this command's work reached the device. The runner refuses a command whose main
29+
/// thread is still draining abandoned work before running anything, so such a refusal left nothing
30+
/// on the device and its terminal entry must not close the id: the read-only busy resend carries the
31+
/// same `commandId` (ADR 0005).
32+
var dispatched = false
33+
}
34+
35+
/// The journal's verdict on one command that carries a `commandId`.
36+
enum RunnerCommandAdmission {
37+
/// Nothing is running for this id and nothing has finished: the caller owns the one execution.
38+
case execute
39+
/// An execution is claimed and has not finished: the caller joins its outcome and runs nothing.
40+
case join
41+
/// Execution finished, and the work reached the device: the caller answers from the journal and
42+
/// never executes this command again.
43+
case terminal(outcome: Response)
2044
}
2145

46+
/// The runner's one command-lifecycle record: what it holds for a `commandId`, whether that id may run,
47+
/// and what `status` answers for it. The transport asks this type before enqueuing anything, so one
48+
/// `commandId` is executed at most once, and a command that already finished cannot be replayed onto the
49+
/// device by a repeat that arrives after its answer was delivered.
2250
final class RunnerCommandJournal {
2351
private let lock = NSLock()
2452
private let maxEntries = 64
2553
private let maxResponseJsonBytes = 16 * 1024
2654
private var entries: [String: RunnerCommandJournalEntry] = [:]
2755
private var order: [String] = []
2856

29-
func accept(command: Command) {
30-
guard let commandId = command.commandId?.trimmedNonEmpty else { return }
57+
@discardableResult
58+
func accept(command: Command) -> RunnerCommandAdmission {
59+
guard let commandId = command.commandId?.trimmedNonEmpty else { return .execute }
3160
lock.lock()
3261
defer { lock.unlock() }
33-
entries[commandId] = RunnerCommandJournalEntry(
34-
commandId: commandId,
35-
command: command.command.rawValue,
36-
state: .accepted,
62+
guard let entry = entries[commandId] else {
63+
return claim(command: command, commandId: commandId)
64+
}
65+
if !entry.state.isTerminal {
66+
return .join
67+
}
68+
// Nothing of this command ever reached the device, so the id carries no effect to protect and the
69+
// send that reuses it is that command's own first execution.
70+
guard entry.dispatched else {
71+
return claim(command: command, commandId: commandId)
72+
}
73+
return .terminal(outcome: recordedOutcome(for: entry))
74+
}
75+
76+
func start(command: Command) {
77+
update(
78+
command: command,
79+
state: .started,
3780
responseOk: nil,
3881
responseJson: nil,
39-
error: nil
82+
error: nil,
83+
marksDispatched: false
4084
)
41-
order.removeAll { $0 == commandId }
42-
order.append(commandId)
43-
pruneIfNeeded()
4485
}
4586

46-
func start(command: Command) {
47-
update(command: command, state: .started, responseOk: nil, responseJson: nil, error: nil)
87+
/// Records that this command's work was handed to the device, as opposed to being refused while it
88+
/// was still queued. Until this point a refusal owes the caller a retry of the same `commandId`.
89+
func markDispatched(command: Command) {
90+
update(
91+
command: command,
92+
state: .started,
93+
responseOk: nil,
94+
responseJson: nil,
95+
error: nil,
96+
marksDispatched: true
97+
)
4898
}
4999

50100
func finish(command: Command, response: Response) {
@@ -53,7 +103,8 @@ final class RunnerCommandJournal {
53103
state: response.ok ? .completed : .failed,
54104
responseOk: response.ok,
55105
responseJson: encodeResponseJson(command: command, response: response),
56-
error: response.error
106+
error: response.error,
107+
marksDispatched: false
57108
)
58109
}
59110

@@ -63,10 +114,25 @@ final class RunnerCommandJournal {
63114
state: .failed,
64115
responseOk: nil,
65116
responseJson: nil,
66-
error: ErrorPayload(message: error.localizedDescription)
117+
error: ErrorPayload(message: error.localizedDescription),
118+
marksDispatched: false
67119
)
68120
}
69121

122+
/// The answer a repeat of a finished `commandId` is owed once its execution's own delivery no longer
123+
/// owes the caller one: the outcome the runner kept, then the failure it kept, and only then a typed
124+
/// refusal for a command whose own classification retains no body. `nil` when the id is not closed for
125+
/// execution — a running one still answers through its delivery, and a refusal that dispatched nothing
126+
/// is open again.
127+
func terminalOutcome(for command: Command) -> Response? {
128+
guard let commandId = command.commandId?.trimmedNonEmpty else { return nil }
129+
lock.lock()
130+
let entry = entries[commandId]
131+
lock.unlock()
132+
guard let entry, entry.state.isTerminal, entry.dispatched else { return nil }
133+
return recordedOutcome(for: entry)
134+
}
135+
70136
func status(normalizedCommandId commandId: String) -> DataPayload {
71137
lock.lock()
72138
let entry = entries[commandId]
@@ -89,39 +155,87 @@ final class RunnerCommandJournal {
89155
)
90156
}
91157

158+
/// Writes the claim for one execution. Callers hold the lock.
159+
private func claim(command: Command, commandId: String) -> RunnerCommandAdmission {
160+
entries[commandId] = RunnerCommandJournalEntry(
161+
commandId: commandId,
162+
command: command.command.rawValue,
163+
state: .accepted,
164+
responseOk: nil,
165+
responseJson: nil,
166+
error: nil
167+
)
168+
order.removeAll { $0 == commandId }
169+
order.append(commandId)
170+
pruneIfNeeded()
171+
return .execute
172+
}
173+
174+
/// Moves one claimed entry forward. A transition for an id the journal does not hold describes work it
175+
/// never claimed, and one for an entry that already finished restates a closed outcome: neither may
176+
/// open a record again. Re-opening one would report `accepted` or `started` for work that is not
177+
/// running, and the daemon holds that verdict as an in-flight exchange on a runner it would otherwise
178+
/// hand off.
92179
private func update(
93180
command: Command,
94181
state: RunnerCommandLifecycleState,
95182
responseOk: Bool?,
96183
responseJson: String?,
97-
error: ErrorPayload?
184+
error: ErrorPayload?,
185+
marksDispatched: Bool
98186
) {
99187
guard let commandId = command.commandId?.trimmedNonEmpty else { return }
100188
lock.lock()
101189
defer { lock.unlock() }
102-
var entry = entries[commandId] ?? RunnerCommandJournalEntry(
103-
commandId: commandId,
104-
command: command.command.rawValue,
105-
state: .accepted,
106-
responseOk: nil,
107-
responseJson: nil,
108-
error: nil
109-
)
190+
guard var entry = entries[commandId], !entry.state.isTerminal else { return }
110191
entry.state = state
111192
entry.responseOk = responseOk
112193
entry.responseJson = responseJson
113194
entry.error = error
195+
if marksDispatched {
196+
entry.dispatched = true
197+
}
114198
entries[commandId] = entry
115199
order.removeAll { $0 == commandId }
116200
order.append(commandId)
117201
pruneIfNeeded()
118202
}
119203

204+
/// Drops the oldest closed entries. An entry whose execution is claimed but not finished is never
205+
/// dropped, however deep the backlog: `status` answers `notAccepted` only for an id this journal does
206+
/// not hold, and the daemon cannot read that as a safe terminal state — it would invalidate a session
207+
/// whose runner is still executing the command it lost the answer to.
120208
private func pruneIfNeeded() {
121209
while order.count > maxEntries {
122-
let removed = order.removeFirst()
123-
entries.removeValue(forKey: removed)
210+
guard let removable = order.first(where: { entries[$0]?.state.isTerminal == true }) else {
211+
return
212+
}
213+
order.removeAll { $0 == removable }
214+
entries.removeValue(forKey: removable)
215+
}
216+
}
217+
218+
/// The answer owed a repeat of a finished `commandId`: the outcome the runner kept, then the failure it
219+
/// kept, and only then a typed refusal for a command whose own classification retains no body at all.
220+
private func recordedOutcome(for entry: RunnerCommandJournalEntry) -> Response {
221+
if let responseJson = entry.responseJson,
222+
let recorded = try? JSONDecoder().decode(Response.self, from: Data(responseJson.utf8))
223+
{
224+
return recorded
124225
}
226+
if let error = entry.error {
227+
return Response(ok: false, error: error)
228+
}
229+
return Response(
230+
ok: false,
231+
error: ErrorPayload(
232+
code: RunnerTests.RunnerWireErrorCode.commandAlreadyFinished,
233+
message:
234+
"The runner already finished \(entry.command) with id \(entry.commandId) and kept no response to replay.",
235+
hint:
236+
"Read the screen with snapshot before sending anything else: the finished command's effect is already on the device."
237+
)
238+
)
125239
}
126240

127241
private func encodeResponseJson(command: Command, response: Response) -> String? {

0 commit comments

Comments
 (0)