bug(subagents): wait_agent can miss turn completion when a queued message starts the next turn
Summary
wait_agent can miss a turn's completion when a queued deferred message starts the next turn before the waiter observes the terminal status.
The agent goes from Running to Completed or Failed, then back to Running. Because wait only checks the current status, it can keep waiting for the follow-up turn or time out instead of returning the preceding turn's outcome.
This appears to violate the documented behavior in docs/subagents.md: "A completion that arrives after the wait begins returns normally."
Expected behavior
If a selected agent reaches a terminal status after the wait begins, the wait should return that outcome, even if a queued message has already started another turn.
What happens
When a turn ends with a deferred message queued, the following sequence can occur:
- The harness drops the active turn, which releases its capacity and bumps the capacity revision. It then publishes the turn's terminal status (turn completion, capacity release).
- The harness sees the capacity change and starts the queued deferred message (queued message processing).
- The new turn sets the agent back to
Runningbefore it callsagent.prompt(...).await(starting the next turn). - The waiter reads the current status, sees
Running, and keeps waiting (wait loop).
Steps 1–3 can complete before the waiter next reads the registry. Waking on a change to the registry revision therefore does not guarantee that the waiter sees the terminal status. The registry revision is a watch channel: it signals that the state changed, but the wait does not keep the terminal outcome once the agent moves back to Running.
Reproduction
The test below polls the wait once to establish that it is pending, then reproduces the terminal-to-running transitions described above. It drives the registry directly and does not exercise the harness's message queue or capacity handling.
Test (append to crates/subagents/src/runtime/tests.rs)
#[tokio::test]
async fn wait_returns_a_turn_that_ended_before_a_queued_turn_started() {
let (registry, _control, _updates) = super::channel(32);
let reservation = registry.reserve("main").await.unwrap();
let id = reservation.id;
let mut session = test_session(id, "child-session", None);
let token = session.turn.start().unwrap();
session.status = AgentStatus::Running;
registry
.state
.lock()
.await
.insert(
reservation.root_session_id.clone(),
id,
session.descriptor.session_id.clone(),
session,
)
.unwrap();
registry
.submit_result("child-session", token, json!({ "report": "done" }))
.await
.unwrap();
let ids = [id];
let mut waiting = Box::pin(registry.wait("main", &ids, Duration::from_secs(1)));
assert!(futures_util::poll!(&mut waiting).is_pending());
// Reproduce the registry transitions when a queued turn starts
// before the waiter observes the preceding turn's terminal status.
registry
.harness_turn_finished(
"main",
id,
Ok(nanocodex::TurnResult::from_backend(None, String::new(), None)),
)
.await;
registry.harness_turn_started("main", id).await.unwrap();
let (summaries, timed_out) = waiting.await.unwrap();
assert!(!timed_out, "status: {:?}", summaries[0].status);
assert_eq!(
summaries[0].status,
AgentStatus::Completed {
output: json!({ "report": "done" })
}
);
}
To run it on a946370 after adding the test:
cargo test -p tact-subagents wait_returns_a_turn_that_ended_before_a_queued_turn_started
On that revision, the wait times out after 1 s and the assert!(!timed_out, ...) assertion fails with status: Running.
I also saw the same ordering through a real child harness. It used a fake model transport that fails the first turn while a deferred message is queued, on both the current-thread and the multi-thread runtime. I can include that test in a PR.
Impact
- A caller can wait until the follow-up turn finishes or the timeout expires (30 s by default, 300 s at most).
- The wait can miss a failed turn's error.
- A successful result stays in
last_outputafter the agent restarts, but a later successful turn overwrites it. A caller that has not retrieved the earlier result by then can miss it.
The last point is also a question of result retention: fixing the wait alone does not keep every turn's output.
The scenario described here involves a deferred message queued behind an active turn. send_agent_message defaults to deferred delivery, so ordinary messages from the root or a sibling can create this condition.
The interactive TUI has a separate continuation path (#172) for successful completions of the root's direct children while the root is idle. That path does not protect an active wait_agent call. Affected callers include subagents waiting on their own children, and code-mode or headless workflows that use wait_agent to collect results.
Possible fix
Keep a per-agent record of the latest terminal outcome, numbered by a monotonically increasing sequence.
When a wait starts, validate the selected agents and record their sequence numbers under the same registry lock. Return once any selected agent's sequence advances, and report its recorded terminal outcome even if its current status is already Running again.
The existing already-terminal rejection and timeout behavior should stay the same.
I have a local implementation that passes the registry test above, and I can open a PR if this approach works for you.
Open question
Should a wait return only the latest terminal outcome since it began, or keep every outcome in between?
Keeping only the latest fixes the single-completion case. It can still drop an earlier outcome if several terminal transitions happen before the waiter resumes, for example when the queued turn fails to start right away.
Related work
#266 mentions a follow-up migration to nanocode::subagents. The same waiting contract may be worth checking there before that migration. This report does not establish that the upstream runtime has the same bug.