Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/architecture/tla/SubtaskReturn.Poison.cfg

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions docs/architecture/tla/SubtaskReturn.PoisonListener.cfg

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions docs/architecture/tla/SubtaskReturn.cfg

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

120 changes: 120 additions & 0 deletions docs/architecture/tla/SubtaskReturn.tla
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
---- MODULE SubtaskReturn ----
\* Models the orchestrator subtask handoff: AttemptCompletionTool.execute with a
\* set parentTaskId, reopenParentFromDelegation, and the provider onTaskCompleted
\* listener (src/core/webview/ClineProvider.ts).
\* Source: the child records its final response and asks to return to the parent,
\* or the TaskCompleted event reaches the provider listener.
\* Sink: the parent record leaves delegated/awaiting, or a "completed" write lands
\* on a child its parent still awaits.
\* Failure: after one transient handoff skip, the user accepts the completion ask
\* or the listener fires; an unguarded writer records the child "completed" while
\* the parent still awaits it, and every later attempt_completion then reads
\* "completed", stops as a stale replay, and the result never reaches the
\* orchestrator (issue 2677).
\* Invariant NoPoisonedCompletion: no reachable state records the child
\* "completed" while the parent record still awaits that child.
\* Modes: "Guarded" (fix - the accept re-runs the handoff while the parent
\* awaits, and the listener write defers to completeDelegatedChild), "Poison"
\* (pre-fix - accept and listener write "completed" in place), and
\* "PoisonListener" (only the listener guard removed; the accept keeps the fix).
\* Result: "Poison" fails NoPoisonedCompletion (reproduction). "PoisonListener"
\* fails it through ListenerObserve alone: its guarded accept cannot reach the
\* poisoned state. "Guarded" holds, and the listener can write there (free
\* parent) - the hold comes from the guard, not from a dead action.
\* Model-checked 2026-12-05, tla2tools 1.7.4: SubtaskReturn.cfg pass
\* (6 states), SubtaskReturn.PoisonListener.cfg fail (5 states),
\* SubtaskReturn.Poison.cfg fail (5 states). Counts vary run to run.
\* Review: 0 covered, 1 added (PR 2856 round 1, thread SubtaskReturn.tla:60 -
\* ListenerObserve action + PoisonListener sabotage), 1 gap (the
\* provider-dispose test-hygiene finding is not a modeled-system behavior;
\* fixed in the TS spec file).
\* Not modeled: approval denial, persistence retries, cancellation, grandchild
\* delegation, and the message content itself (oracle: taskLifecycle.ts).

EXTENDS Naturals

CONSTANTS Mode

VARIABLES parentAwaiting, childStatus, phase
vars == <<parentAwaiting, childStatus, phase>>

\* Two starts a real system can be in when the child finishes: the parent
\* record still awaits this child, or the parent record is free (gone, or no
\* longer awaiting) while the child task is still active.
Init == \/ /\ parentAwaiting = "child"
/\ childStatus = "active"
/\ phase = "running"
\/ /\ parentAwaiting = "none"
/\ childStatus = "active"
/\ phase = "running"

\* The child streams its final response. The handoff either completes (the
\* reopen succeeds: the pair update frees the parent and completes the child)
\* or is skipped once (transient gate miss or reopen failure) and the tool
\* falls through to the plain completion ask.
AttemptReturn ==
/\ phase = "running"
/\ IF parentAwaiting = "child"
THEN \/ /\ phase' = "handedOff"
/\ parentAwaiting' = "none"
/\ childStatus' = "completed"
\/ /\ phase' = "askUser"
/\ UNCHANGED <<parentAwaiting, childStatus>>
ELSE /\ phase' = "askUser"
/\ UNCHANGED <<parentAwaiting, childStatus>>

\* The provider onTaskCompleted listener fires for the finished child. The
\* guarded form writes "completed" only when the parent record is free; a
\* still-awaited child defers the write to completeDelegatedChild. The
\* unguarded form (Poison, PoisonListener) writes "completed" regardless.
\* An already completed child makes the write a no-op.
ListenerObserve ==
/\ phase \in {"running", "askUser"}
/\ IF childStatus = "completed"
THEN UNCHANGED vars
ELSE IF Mode = "Guarded" /\ parentAwaiting = "child"
THEN UNCHANGED vars
ELSE /\ childStatus' = "completed"
/\ phase' = "closed"
/\ UNCHANGED parentAwaiting

\* The user answers the completion ask. "Poison" records the child completed
\* in place; the parent record keeps awaiting. The other modes re-run the
\* handoff while the parent still awaits this child; only a free child
\* completes in place. A poisoned child can never re-run the handoff: the
\* stale-replay gate reads "completed" and skips delegation forever.
AcceptCompletion ==
/\ phase = "askUser"
/\ IF Mode # "Poison"
THEN IF parentAwaiting = "child"
THEN /\ phase' = "handedOff"
/\ parentAwaiting' = "none"
/\ childStatus' = "completed"
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
ELSE /\ childStatus' = "completed"
/\ phase' = "closed"
/\ UNCHANGED parentAwaiting
ELSE /\ childStatus' = "completed"
/\ phase' = "closed"
/\ UNCHANGED parentAwaiting

\* The user re-prompts the model. A live child retries the handoff; a child
\* already recorded "completed" is treated as a stale replay and stays stuck.
PromptAgain ==
/\ phase \in {"running", "closed"}
/\ IF childStatus = "active" /\ parentAwaiting = "child"
THEN phase' = "running"
ELSE phase' = phase
/\ UNCHANGED <<parentAwaiting, childStatus>>

Next == AttemptReturn \/ AcceptCompletion \/ ListenerObserve \/ PromptAgain

Spec == Init /\ [][Next]_vars

TypeOK == /\ parentAwaiting \in {"child", "none"}
/\ childStatus \in {"active", "completed"}
/\ phase \in {"running", "askUser", "handedOff", "closed"}

NoPoisonedCompletion == ~(childStatus = "completed"
/\ parentAwaiting = "child")

====
43 changes: 43 additions & 0 deletions src/core/task-persistence/__tests__/taskLifecycle.spec.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src/core/task-persistence/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export {
delegateTaskToChild,
interruptDelegatedChild,
LifecycleTransitionError,
parentStillAwaitsChild,
settleRejectedCreateSubtaskAction,
type HistoryItemStatus,
VALID_TASK_STATUS_TRANSITIONS,
Expand Down
22 changes: 22 additions & 0 deletions src/core/task-persistence/taskLifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,25 @@ export function abandonDelegatedChild(
},
}
}

/**
* True when a parent record still delegates to and awaits this child. Only
* completeDelegatedChild may record a still-awaited child "completed", and it
* frees the parent in the same atomic step (#2677). Any other "completed"
* write over such a child poisons the return gate: every later
* attempt_completion reads "completed", skips the handoff as a stale replay,
* and the result never reaches the orchestrator.
*/
export function parentStillAwaitsChild(
child: HistoryItem,
getParent: (parentTaskId: string) => HistoryItem | undefined,
): boolean {
if (!child.parentTaskId) {
return false
}
const parent = getParent(child.parentTaskId)
if (!parent) {
return false
}
return (parent.status === "delegated" || parent.status === "active") && parent.awaitingChildId === child.id
}
51 changes: 51 additions & 0 deletions src/core/tools/AttemptCompletionTool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,37 @@ export class AttemptCompletionTool extends BaseTool<"attempt_completion"> {
const { response, text, images, queuedMessageId, segments } = await task.ask("completion_result", "", false)

if (response === "yesButtonClicked") {
// A skipped handoff (a transient gate miss or a failed reopen) used to
// land here: the user accepted the completion ask, the provider recorded
// the child "completed", and every later attempt_completion then stopped
// as a stale replay - the result never reached the orchestrator (#2677).
// While the parent still awaits this child, the yes button re-attempts
// the handoff instead of acknowledging the child in place.
if (!isStaleHistoryReplay && task.parentTaskId) {
const provider = task.providerRef.deref() as DelegationProvider | undefined

if (provider && (await this.parentStillAwaitingChild(task, provider))) {
const delegation = await this.delegateToParent(
task,
result,
provider,
undefined,
askFinishSubTaskApproval,
pushToolResult,
)

if (delegation === "delegated") {
task.emitFinalTokenUsageUpdate()
provider.emitDelegatedTaskCompleted(task.taskId, task.getTokenUsage(), task.toolUsage)
}

if (delegation !== "continue") {
return
}
// "continue": the reopen found the parent detached after all.
// Fall through to the plain acknowledgment below.
}
}
// A stale history replay reruns this handler on a fresh Task instance for a
// subtask that already completed (and already emitted TaskCompleted) the first
// time through -- re-acknowledging it from history must not emit it again.
Expand Down Expand Up @@ -297,6 +328,26 @@ export class AttemptCompletionTool extends BaseTool<"attempt_completion"> {
return "delegated"
}

/**
* Re-reads the delegation gate before a retried handoff: the parent record
* must still await this child. A read failure counts as "not awaiting", so
* the caller keeps the plain acknowledgment path (#2677).
*/
private async parentStillAwaitingChild(task: Task, provider: DelegationProvider): Promise<boolean> {
if (!task.parentTaskId) {
return false
}
try {
const { historyItem: parentHistory } = await provider.getTaskWithId(task.parentTaskId)
return (
(parentHistory?.status === "delegated" || parentHistory?.status === "active") &&
parentHistory?.awaitingChildId === task.taskId
)
} catch {
return false
}
}

override async handlePartial(task: Task, block: ToolUse<"attempt_completion">): Promise<void> {
const result: string | undefined = block.params.result
const command: string | undefined = block.params.command
Expand Down
Loading
Loading