Skip to content

fix(harness): recover lost async task completions in legacy wait - #2797

Open
Daihonghui wants to merge 1 commit into
agentscope-ai:mainfrom
Daihonghui:bugfix/2791-wait-async-results-notification-loss
Open

Daihonghui wants to merge 1 commit into
agentscope-ai:mainfrom
Daihonghui:bugfix/2791-wait-async-results-notification-loss

Conversation

@Daihonghui

Copy link
Copy Markdown

Summary

  • snapshot non-terminal async tasks when legacy wait_async_results starts
  • keep inbox notifications as the first fast path
  • fall back to authoritative TaskRepository state when a tracked task becomes terminal
  • return the completed task's actual result/error and mark it delivered

Compatibility

  • preserves legacy ANY-result semantics: one tracked completion returns immediately
  • excludes tasks already terminal before wait start
  • leaves task_ids and wait_all=true barrier semantics unchanged
  • preserves inbox fast-path and timeout behavior

Tests

  • reproduced the bug before the production change: the core regression timed out and failed
  • WaitAsyncResultsToolTest: 23 tests passed
  • WaitAsyncResultsToolTest, WorkspaceTaskRepositoryTest, and WorkspaceTaskRepositoryDeliveryTest: 54 tests passed
  • Spotless check passed

Fixes #2791

@CLAassistant

CLAassistant commented Aug 21, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codecov

codecov Bot commented Aug 21, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.55172% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...scope/harness/agent/tool/WaitAsyncResultsTool.java 96.55% 0 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@xiaoyuuuuuupeng xiaoyuuuuuupeng left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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 oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 nested waitSet × tasks loop; the neighbouring barrier path already uses getTask point 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 =

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

jujn pushed a commit that referenced this pull request Oct 13, 2026
## 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.
@jujn jujn added the P1 紧急不重要 label Nov 4, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 紧急不重要

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: WaitAsyncResultsTool waits on the inbox notification chain instead of task state, stalling the main agent when any link breaks

5 participants