Repository navigation
fix(harness): recover lost async task completions in legacy wait - #2797
Daihonghui wants to merge 1 commit into
Conversation
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
xiaoyuuuuuupeng
left a comment
There was a problem hiding this comment.
Thanks for addressing the notification-loss failure in the legacy
wait_async_results path. Falling back to authoritative TaskRepository state
is the right direction.
I found one case that still leaves a reproduction from #2791 unresolved:
a task that becomes terminal before legacy wait starts is excluded from the
non-terminal snapshot, even when its result has not been delivered. The tool
then reports that all tasks are complete without returning the lost result.
Please recover terminal-but-undelivered tasks before taking the non-terminal
snapshot. The existing findPendingDeliveries / delivery metadata appears to
provide the distinction needed to avoid returning already-delivered historical
tasks.
I also left two smaller comments:
- repository recovery is bypassed after the consecutive-wait budget is
exhausted; - the initial repository snapshot runs before the first inbox check, so the
claimed inbox fast path can still be delayed or broken by repository
failures.
The main repository fallback is a good improvement, but I think the
terminal-before-wait case should be addressed before this PR closes #2791.
| if (taskRepository != null) { | ||
| boolean hasNonTerminal = | ||
| hasNonTerminalTasks(runtimeContext, sessionId) || hasExternalWork(); | ||
| legacyWaitSet = snapshotNonTerminalTaskIds(runtimeContext, sessionId); |
There was a problem hiding this comment.
[P1] Recover terminal-but-undelivered tasks before taking this snapshot
This snapshot only includes tasks that are non-terminal when the legacy wait
starts. If a task completes before this call and its completion notification
is lost, it is excluded from legacyWaitSet and its result is not returned.
That leaves the callback-registration race described in #2791 unresolved.
Please check for terminal-but-undelivered tasks before building this snapshot,
using findPendingDeliveries or equivalent delivery metadata. Already-delivered
historical tasks should remain excluded. A regression test should start with
a terminal, undelivered task and an empty inbox, then verify that legacy wait
returns the result and marks it delivered.
| + "wait_all=true when you need every task in a group."; | ||
| } | ||
| BackgroundTask terminalTask = | ||
| findFirstTerminalTrackedTask(runtimeContext, sessionId, legacyWaitSet); |
There was a problem hiding this comment.
[P2] Make repository recovery reachable after the wait budget is exhausted
This fallback is never reached once MAX_CONSECUTIVE_EMPTY_WAITS has been hit,
because the legacy path rejects earlier after checking only the inbox.
For example, two waits may time out while the task is still running; the task
then completes, its inbox notification is lost, and the next legacy wait is
rejected without consulting TaskRepository.
Please perform one terminal-but-undelivered repository check before applying
the exhausted-budget rejection. A regression test should cover completion
after the second timeout with an empty inbox.
| + "blocking."; | ||
| } | ||
|
|
||
| List<String> legacyWaitSet = List.of(); |
There was a problem hiding this comment.
[Suggestion] Check the inbox before querying TaskRepository
The initial non-terminal snapshot queries TaskRepository before the first
inbox check. With a remote repository, an already-available inbox result may
therefore be delayed; if listTasks throws, the call fails without observing
the inbox result.
Please check inboxHasMessages before taking the repository snapshot. Repository
fallback failures should also degrade to the original inbox-only behavior
rather than preventing it.
A small test with inbox=true and a repository whose listTasks throws would
verify the ordering and degradation behavior.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Makes the legacy (task_ids/wait_all absent) mode of wait_async_results recover a sub-agent completion that never arrived as an inbox notification: it snapshots the non-terminal task ids at wait start, keeps the inbox as the fast path, and on each tick falls back to the authoritative TaskRepository state, returning the first tracked task that reached terminal state through the extracted formatTerminalResults (so results, errors and cancellations all surface, and delivery is marked exactly once).
I read the change against the legacy ANY contract and it holds: tasks already terminal before the wait are excluded by snapshotNonTerminalTaskIds, the task_ids / wait_all=true barrier is untouched, and the new tests pin the fast path, the historical-completion exclusion, the failed and cancelled returns. The points below are cost, timeout-precision and one semantics question — none of them block the fix.
Findings
- [Warning]
WaitAsyncResultsTool.java:384—listTasks(rc, sessionId, null)rescans the whole session task list on every 3 s tick, with a nestedwaitSet × tasksloop; the neighbouring barrier path already usesgetTaskpoint lookups. - [Info]
WaitAsyncResultsTool.java:231— the deadline check moved below the two probes, so the last iteration can overshoot the caller's timeout by one probe round; fine if intentional, but it softens the guardrail the comment right below still advertises. - [Info]
WaitAsyncResultsTool.java:183— the wait set is snapshotted once, so a sub-agent spawned while this call is blocked stays invisible and the tool times out even when that task completed mid-wait.
Suggestions
For the rescan, getTask is a drop-in for the tracked set:
for (String taskId : waitSet) {
BackgroundTask task = taskRepository.getTask(runtimeContext, sessionId, taskId);
if (task != null && task.getTaskStatus().isTerminal()) {
return task;
}
}If the single snapshot is deliberate (it matches the documented wait_all semantics), one line in the class javadoc saying so will save the next reader the same question.
Verified: CLA signed, CI green at head 84893b96 (build (ubuntu-latest), build (windows-latest), Check License, Check Module Sync, codecov/patch all SUCCESS), mergeable=true, mergeable_state=BLOCKED (branch protection, not a conflict). No blocking issue found — LGTM for the maintainer's call once the inline items are triaged.
Automated review by github-manager-bot
| if (waitSet.isEmpty()) { | ||
| return null; | ||
| } | ||
| Collection<BackgroundTask> currentTasks = |
There was a problem hiding this comment.
listTasks(rc, sessionId, null) re-materialises the whole session task list on every 3 s tick, and the nested waitSet × currentTasks loop is O(n·m) per tick. The barrier path right next to it uses point lookups (taskRepository.getTask(rc, sessionId, taskId) in completeTaskBarrierIfReady), which is both cheaper and stable when a session accumulates many historical tasks. Since legacyWaitSet is already the exact id set you care about, could the fallback iterate it with getTask (or index the listing into a HashMap once per tick)? Purely a cost/consistency point — behaviour is equivalent.
| emptyWaits.set(0); | ||
| return formatLegacyResult(runtimeContext, sessionId, terminalTask); | ||
| } | ||
| long remainingMs = deadlineMs - System.currentTimeMillis(); |
There was a problem hiding this comment.
Moving the deadline check below the two probes means the final iteration now runs inboxHasMessages(...).block() plus the repository scan after the budget has expired, so an explicit timeoutSeconds=1 call can return slightly later than before (one extra probe round). That is arguably an improvement — a completion landing exactly at the deadline is still caught — but it does relax the guardrail the comment right below advertises ("never overshoot the caller's timeout"). If intentional, please say so in the loop comment; otherwise checking remainingMs at the top and doing one final probe after break keeps the old bound.
| hasNonTerminalTasks(runtimeContext, sessionId) || hasExternalWork(); | ||
| legacyWaitSet = snapshotNonTerminalTaskIds(runtimeContext, sessionId); | ||
| boolean hasNonTerminal = !legacyWaitSet.isEmpty() || hasExternalWork(); | ||
| if (!hasNonTerminal) { |
There was a problem hiding this comment.
The wait set is snapshotted once, before normalizeTimeout, so a sub-agent spawned while this call is blocked is still invisible to the fallback: with an empty inbox it will keep ticking to the timeout even though a tracked task completed mid-wait. That mirrors the documented wait_all semantics ("tasks created while waiting are not added"), so it may well be deliberate for legacy mode as well — but the failure this PR fixes is exactly "a completion nobody noticed", so it is worth stating the choice in the javadoc above, or re-snapshotting the non-terminal set on each tick.
## Description `WaitAsyncResultsToolTest.timeoutClampedToMax` currently spends 120 seconds waiting for an empty inbox. The test named `nullTimeoutUsesDefault` passes `1`, so it does not exercise the actual 60-second default. Add package-local clock and sleep injection to run those same polling loops with virtual elapsed time. The public constructors still use `System.currentTimeMillis` and `Thread.sleep`; production timeout values and polling behavior remain unchanged. The tests now check the 600 → 120 clamp, null → 60 default, remaining sleep budget, consecutive-empty accounting and incomplete task barriers. A real-thread interruption test uses the public constructor, alongside a deterministic check that interruption restores the flag without consuming the empty-wait budget. Existing real async-completion tests remain. This is a narrow test-time slice of #3521, not a change to test parallelism or the whole build optimization assigned there. #2797 touches the same class for async-completion recovery; that functional change remains separate.
Summary
wait_async_resultsstartsTaskRepositorystate when a tracked task becomes terminalCompatibility
task_idsandwait_all=truebarrier semantics unchangedTests
WaitAsyncResultsToolTest: 23 tests passedWaitAsyncResultsToolTest,WorkspaceTaskRepositoryTest, andWorkspaceTaskRepositoryDeliveryTest: 54 tests passedFixes #2791