Skip to content

fix(harness): report failed background subagent tasks correctly - #4102

Open
xseruer wants to merge 9 commits into
agentscope-ai:mainfrom
xseruer:fix/subagent-task-failure-visibility
Open

xseruer wants to merge 9 commits into
agentscope-ai:mainfrom
xseruer:fix/subagent-task-failure-visibility

Conversation

@xseruer

@xseruer xseruer commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.1.0-SNAPSHOT, merged with main at 31d320049.

Description

Background

Failed background subagent tasks are correctly persisted as FAILED, but their message-bus notification says "has completed" with "Result: (no output)" and omits the execution error.

This gives the parent agent contradictory signals and can cause an execution failure to be treated as an empty business result. The dynamic subagent path relies on this notification for push delivery; the static path can additionally receive a contradictory <task_error> reminder.

Changes

  • Preserve the five-argument TaskCompletionCallback.onCompleted method and add a default onSettled method carrying status and error details.
  • Add TaskSettledCallback, registered through the unchanged setCompletionCallback method.
  • Update the Workspace repository to supply explicit terminal status and errors. Empty successful outputs remain successful.
  • Share notification formatting across dynamic and static wiring: failures explicitly say FAILED and distinguish execution failures from business conclusions.
  • Per maintainer feedback (review round 2): automatic notifications identify the task id, the terminal status, and a fixed error category ("execution failure") — they never embed any part of the raw exception message, so credentials or internal paths cannot leak into the conversation. This applies to both the inbox hint and the aggregated <task_error> blocks in the delivery reminder. The full message stays in the durable task record, reachable via task_output/task_list.
  • Per maintainer feedback (review round 2): the settlement callback now fires with the status actually persisted. When cancellation races a settlement (adopted future cancelled, or a local supplier failing after cancelTask()), the record — and therefore the notification — stays CANCELLED, so the parent agent no longer risks retrying a task the user just cancelled. Settled-task hints gained a CANCELLED wording.
  • Per maintainer feedback (review round 3): the settlement callback reports only the status that is on record. updateStatus reads the record back after writing, because WorkspaceManager.writeTaskRecord logs and swallows storage failures instead of throwing. When the terminal write does not land, no terminal status is announced: the result of a completed task exists only in memory and is handed over with a notice that it is not on record (main's fix(harness): harden context management and recovery #4399 requires the result to survive a failed record write), while an unrecorded failure or cancellation is not announced. The stable docs/v2 additions were removed.
  • Preserve successful notification wording and callback suppression.
  • Add compatibility, repository-contract, remote-failure, and message-bus wiring tests; update English and Chinese documentation.

Task-record formats, durable delivery, model routing, and retry behavior are unchanged.

Compatibility

The change preserves source and binary compatibility with the original five-argument API, including existing lambdas, custom repositories, and precompiled callers.

Tests compile legacy consumers against the original interface and verify both callback bridge directions. The original abstract method descriptor also matches the released 2.0.4 API.

Legacy repositories may continue calling onCompleted; they retain the existing null-result failure convention but cannot provide error details. Repositories should call onSettled to supply explicit status and errors.

Scope

Per maintainer feedback, the durable-runtime late-heartbeat fix and the a2a early task-release fix that were previously part of this PR have been split into #4302 and #4303 for separate review. This PR now contains only the Harness failure-notification changes.

Addresses the FAILED-notification portion of #2159. Related to #2187; thanks to @BG0527 for identifying and addressing this problem.

How to test

Run the focused regression tests:

mvn -pl agentscope-harness -am test \
  -Dtest=SubagentTaskSettledHintTest,SubagentDeliveryTest,WorkspaceTaskRepositoryTest,WorkspaceTaskRepositoryRemoteStreamingTest \
  -Dsurefire.failIfNoSpecifiedTests=false

Coverage includes: legacy source and binary compatibility and both callback bridges; success, failure, empty success, and callback suppression; adopted futures and workspace remote failures; cancelled settlements (adopted + cancelTask, and local post-cancel failure); notifications never leaking raw error content; terminal writes that throw or silently fail, for both completed and failed tasks, at the repository and message-bus wiring levels.

Note on the merged upstream test

SubagentDeliveryTest.deliveryPreservesLargeResultsAndErrorsWithTaskOutputAvailable was added by #4399 and asserted that the delivery reminder carries the raw error text. That contradicts the review request to keep raw exceptions out of the conversation, so the case is now deliveryPreservesLargeResultsAndDefersErrorsToTaskOutput: large results are still delivered in full, errors are left to task_output.

@mintlify

mintlify Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 903849b.

Approve preview

ningmao-hlyz added a commit to ningmao-hlyz/agentscope-java that referenced this pull request Nov 14, 2026
…the stream emitted

`ProcessRecoveryTest` polls `backend.turn(...)` while calling `replacement.tick`,
and the runtime interrupts whoever ticks to deliver a wakeup. The fixture loop in
the same file already cleared the interrupt flag; the two polling loops in the
test body did not, so `Thread.sleep` threw `InterruptedException` and failed the
run even though nothing was wrong. That is the failure seen on agentscope-ai#4102 and on main:

  ProcessRecoveryTest.replacementCollectsOriginalResultWithoutRepeatingEffect
  java.lang.InterruptedException: sleep interrupted

Route all three sleeps through one `pause` helper that clears the flag. The loops
still exit on their deadline, and the terminal `SUCCEEDED` assertion is unchanged,
so a genuine stall still fails.

`AgentScopeAgentExecutorInputRequiredTest.stream` failed with "the stream ended
without reaching TASK_STATE_FAILED", which says nothing about what the stream did
emit before ending. Record the events and put them in the message.

The A2A change is diagnostics only. It did not reproduce locally (30 repetitions,
30 passes), so its root cause is still open and no production code is touched.
ningmao-hlyz added a commit to ningmao-hlyz/agentscope-java that referenced this pull request Nov 14, 2026
…ssages, and ignore wakeups

Two test-harness defects, both seen on CI.

RocketMQ: `Broker.consumer` re-offers a message 50ms after handing it out unless
it was acked, without knowing whether the consumer is still working on it. When
the ack lands after the window the message is delivered twice, which is what
failed this PR's ubuntu build:

  authorizationPrecedesAdmissionAndCancellationTombstoneSurvivesLateExecute:604
  expected: <1> but was: <2>

A single CANCEL produced two acks. Narrowing the window to 1ms reproduces it
locally, together with the recovery flake:

  expected: <1> but was: <2>
  turn.status=WAITING, modelCalls=1, commandAcks=10, eventAcks=17, queuedEvents=2

A real invisible duration is measured in seconds; these tests only need
redelivery to happen inside their 10s waits. Name the window, raise it to one
second, and record the constraint next to it.

ProcessRecovery: the test polls `backend.turn(...)` while ticking, and the runtime
interrupts the ticking thread to deliver a wakeup, so `Thread.sleep` threw
`InterruptedException` and failed a run in which nothing was wrong (agentscope-ai#4102, and
main). The fixture loop in the same file already cleared the flag; route all
three sleeps through one `pause` helper instead. The deadlines and the terminal
assertion are untouched, so a real stall still fails.
ningmao-hlyz added a commit to ningmao-hlyz/agentscope-java that referenced this pull request Nov 14, 2026
…ssages, and ignore wakeups

Two test-harness defects, both seen on CI.

RocketMQ: `Broker.consumer` re-offers a message 50ms after handing it out unless
it was acked, without knowing whether the consumer is still working on it. When
the ack lands after the window the message is delivered twice, which is what
failed this PR's ubuntu build:

  authorizationPrecedesAdmissionAndCancellationTombstoneSurvivesLateExecute:604
  expected: <1> but was: <2>

A single CANCEL produced two acks. Narrowing the window to 1ms reproduces it
locally, together with the recovery flake:

  expected: <1> but was: <2>
  turn.status=WAITING, modelCalls=1, commandAcks=10, eventAcks=17, queuedEvents=2

A real invisible duration is measured in seconds; these tests only need
redelivery to happen inside their 10s waits. Name the window, raise it to one
second, and record the constraint next to it.

ProcessRecovery: the test polls `backend.turn(...)` while ticking, and the runtime
interrupts the ticking thread to deliver a wakeup, so `Thread.sleep` threw
`InterruptedException` and failed a run in which nothing was wrong (agentscope-ai#4102, and
main). The fixture loop in the same file already cleared the flag; route all
three sleeps through one `pause` helper instead. The deadlines and the terminal
assertion are untouched, so a real stall still fails.
ningmao-hlyz added a commit to ningmao-hlyz/agentscope-java that referenced this pull request Nov 14, 2026
…ssages, and ignore wakeups

Two test-harness defects, both seen on CI.

RocketMQ: `Broker.consumer` re-offers a message 50ms after handing it out unless
it was acked, without knowing whether the consumer is still working on it. When
the ack lands after the window the message is delivered twice, which is what
failed this PR's ubuntu build:

  authorizationPrecedesAdmissionAndCancellationTombstoneSurvivesLateExecute:604
  expected: <1> but was: <2>

A single CANCEL produced two acks. Narrowing the window to 1ms reproduces it
locally, together with the recovery flake:

  expected: <1> but was: <2>
  turn.status=WAITING, modelCalls=1, commandAcks=10, eventAcks=17, queuedEvents=2

A real invisible duration is measured in seconds; these tests only need
redelivery to happen inside their 10s waits. Name the window, raise it to one
second, and record the constraint next to it.

ProcessRecovery: the test polls `backend.turn(...)` while ticking, and the runtime
interrupts the ticking thread to deliver a wakeup, so `Thread.sleep` threw
`InterruptedException` and failed a run in which nothing was wrong (agentscope-ai#4102, and
main). The fixture loop in the same file already cleared the flag; route all
three sleeps through one `pause` helper instead. The deadlines and the terminal
assertion are untouched, so a real stall still fails.
ningmao-hlyz added a commit to ningmao-hlyz/agentscope-java that referenced this pull request Nov 14, 2026
…ssages, and ignore wakeups

Two test-harness defects, both seen on CI.

RocketMQ: `Broker.consumer` re-offers a message 50ms after handing it out unless
it was acked, without knowing whether the consumer is still working on it. When
the ack lands after the window the message is delivered twice, which is what
failed this PR's ubuntu build:

  authorizationPrecedesAdmissionAndCancellationTombstoneSurvivesLateExecute:604
  expected: <1> but was: <2>

A single CANCEL produced two acks. Narrowing the window to 1ms reproduces it
locally, together with the recovery flake:

  expected: <1> but was: <2>
  turn.status=WAITING, modelCalls=1, commandAcks=10, eventAcks=17, queuedEvents=2

A real invisible duration is measured in seconds; these tests only need
redelivery to happen inside their 10s waits. Name the window, raise it to one
second, and record the constraint next to it.

ProcessRecovery: the test polls `backend.turn(...)` while ticking, and the runtime
interrupts the ticking thread to deliver a wakeup, so `Thread.sleep` threw
`InterruptedException` and failed a run in which nothing was wrong (agentscope-ai#4102, and
main). The fixture loop in the same file already cleared the flag; route all
three sleeps through one `pause` helper instead. The deadlines and the terminal
assertion are untouched, so a real stall still fails.
ningmao-hlyz added a commit to ningmao-hlyz/agentscope-java that referenced this pull request Nov 14, 2026
…ssages, and ignore wakeups

Two test-harness defects, both seen on CI.

RocketMQ: `Broker.consumer` re-offers a message 50ms after handing it out unless
it was acked, without knowing whether the consumer is still working on it. When
the ack lands after the window the message is delivered twice, which is what
failed this PR's ubuntu build:

  authorizationPrecedesAdmissionAndCancellationTombstoneSurvivesLateExecute:604
  expected: <1> but was: <2>

A single CANCEL produced two acks. Narrowing the window to 1ms reproduces it
locally, together with the recovery flake:

  expected: <1> but was: <2>
  turn.status=WAITING, modelCalls=1, commandAcks=10, eventAcks=17, queuedEvents=2

A real invisible duration is measured in seconds; these tests only need
redelivery to happen inside their 10s waits. Name the window, raise it to one
second, and record the constraint next to it.

ProcessRecovery: the test polls `backend.turn(...)` while ticking, and the runtime
interrupts the ticking thread to deliver a wakeup, so `Thread.sleep` threw
`InterruptedException` and failed a run in which nothing was wrong (agentscope-ai#4102, and
main). The fixture loop in the same file already cleared the flag; route all
three sleeps through one `pause` helper instead. The deadlines and the terminal
assertion are untouched, so a real stall still fails.
@jujn jujn added the P0 重要紧急 label Nov 16, 2026
@juruoO-o

Copy link
Copy Markdown
Collaborator

后台子 Agent 失败时,父 Agent 应该明确收到 FAILED 通知。合入前请调整两处。

  • 请把 A2A 提前释放 task ID 和 Durable Runtime 防止迟到心跳中断线程的改动拆到各自的 PR,分别评审。这个 PR 聚焦 Harness 的失败通知。
  • 发给父 Agent 的通知请使用简短、经过脱敏的错误摘要,避免直接把原始异常消息写进会话提示。排查详情可以通过现有的任务查询渠道获取。

本地 Harness 相关的 50 项测试通过。

…ions

The message-bus completion callback pushed the same "has completed ...
Result: (no output)" inbox hint for FAILED tasks as for delivered
results, so the parent model treated execution failures (e.g. model
retries exhausted) as empty business results and closed the loop
instead of retrying or escalating. The callback now carries the
terminal TaskStatus plus the failure message, and the hint wording
mirrors the task-delivery reminder's <task_error> semantics.
Changing TaskCompletionCallback.onCompleted to seven parameters broke
existing lambdas, custom repositories and precompiled callers, and left
ControlPlaneTaskRepository uncompilable. Restore the original method and
carry terminal status and errors through an additive default onSettled;
TaskSettledCallback lets the built-in message-bus wiring consume them
through the unchanged setCompletionCallback.

Built-in repositories, including the control-plane one, call onSettled
explicitly, so empty successes stay completions. Tests now cover both
bridge directions (including callers compiled against the old interface),
both repository backends and every message-bus wiring path.
Per maintainer feedback on agentscope-ai#4102, notifications to the parent agent now
carry a short, sanitized error summary: the raw exception message is
reduced to its first line and truncated, since stack traces and long
internal dumps can leak paths, endpoints, or credentials into the
conversation prompt. The full message stays in the durable task record,
reachable via task_output/task_list.

Applies the same cap to the aggregated <task_error> blocks in the
delivery reminder, and documents the new behavior in both the v2 and
dev docs sets.
@xseruer

xseruer commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

感谢详细意见,两点都已处理,分支已重构为基于 cd8a21c4a 的干净提交历史:

1. 拆分 PR

2. 错误摘要脱敏

  • 通知里的错误改为简短、脱敏的摘要:原始异常消息压缩为首行、截断 200 字符,多行堆栈和后续内容不会进入会话提示,避免泄露路径/端点等内部信息。
  • 完整错误仍持久化在任务记录中,父 agent 可通过 task_output(task_id=..., block=false) 获取,通知里也明确指路了该渠道。
  • 聚合投递提醒(<task_error> 块)套用了同样的截断上限。
  • 新增 3 个测试覆盖截断与多行场景;Harness 相关 61 项测试通过。

另说明一下 merge base:当前 main 顶端 131e3fe18(#2919)在 agentscope-harness 编译失败(HarnessAgent.java:868 的 call(new UserMessage, Class, ctx) 无匹配重载,CI 为红),所以三个分支都基于最后一个 CI 绿的提交 cd8a21c4a,待上游修复后可再 rebase。

@juruoO-o juruoO-o 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.

复审了 05b3222。A2A 和 Durable 的改动已拆出,原有五参数回调接口也已保留。合入前请再处理两个已复现的问题。

  1. [P1] 用户取消任务后,父 Agent 会收到 FAILED 通知。 在 WorkspaceTaskRepository 中注册状态回调,传入尚未完成的 AdoptedTaskRunSpec,再调用 cancelTask(),持久化记录为 CANCELLED,但同一任务的回调收到 FAILED。取消 Future 会进入 whenComplete 的异常分支;updateStatus 的终态保护保住了 CANCELLED,随后 fireCompletionCallback 仍传出 FAILED,可能让父 Agent 重试用户刚取消的任务。请让通知与实际持久化的终态一致,并覆盖这条取消路径。
  2. [P1] 异常首行仍会原样进入父 Agent 会话。 用包含虚构凭据的单行异常调用 taskSettledHintContent,生成的通知完整保留了该凭据。sanitizeErrorSummary 只去掉后续行并限制长度。建议自动通知使用任务 ID、失败状态和固定错误类别,详细异常沿用 task_output 查询;请同时覆盖 inbox hint 和任务投递 reminder。

Ubuntu、Windows 和本地构建均在 SubagentTaskSettledHintTest.java 第 116 行的 Spotless 检查失败,请一并修正断言换行。跳过该格式检查后,本地 61 项相关测试通过;另用两个独立用例复现了上述问题。

Review follow-up on agentscope-ai#4102, fixing two reproduced issues:

1. Cancelled tasks must not announce FAILED. updateStatus now returns the
   status actually persisted, and every settlement goes through
   settleAndNotify, which fires the callback with that effective status.
   Cancelling an adopted future (or a local supplier failing after
   cancellation) enters the exception branch, but the record — and now the
   notification — stays CANCELLED, so the parent agent no longer risks
   retrying a task the user just cancelled. Settled hints gained a CANCELLED
   wording. Covered by tests for the adopted+cancelTask path and the local
   post-cancel failure path.

2. Automatic notifications no longer embed any part of the exception
   message: the first line of a single-line error still leaked verbatim.
   Hints and <task_error> blocks now carry only the task id, the terminal
   status, and a fixed error category; the raw error remains in the durable
   task record, reachable via task_output. The truncating sanitizer is
   removed along with its length cap.

Also fixes the Spotless violations in the settled-hint tests.
@xseruer

xseruer commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

感谢复现和详细反馈,两个 P1 问题与 Spotless 格式问题都已在 8fd1786 处理:

1. 取消的任务误报 FAILED(P1)

  • updateStatus 现在返回实际持久化的终态;所有结算统一走新增的 settleAndNotify,用该有效终态触发回调。
  • 您的复现路径(未完成的 AdoptedTaskRunSpec + cancelTask()):取消进入 whenComplete 异常分支后,记录已是 CANCELLED,守卫阻止 FAILED 写入,回调现在也报 CANCELLED(通知措辞新增 CANCELLED 分支),父 Agent 不会再收到可引发重试的 FAILED 信号。
  • 补了两个测试:评审复现的 adopted+cancelTask 路径,以及本地任务取消后 supplier 才抛异常的路径,均断言回调与持久化记录一致为 CANCELLED。

2. 单行异常原文仍进入会话(P1)

  • 采纳您的建议:自动通知只包含任务 ID、终态、固定错误类别("execution failure"),完全不再嵌入原始异常消息——此前的首行截断方案已整体删除(sanitizeErrorSummary 及长度上限一并移除)。
  • inbox hint 与任务投递 reminder 的 <task_error> 块均改为固定文案并指路 task_output;完整错误仍持久化在任务记录中。
  • 测试改用含伪造凭据(token=sk-live-secret-...)的单行异常消息,断言其不出现在 hint / reminder 中、但保留在任务记录里。

3. Spotless

  • 断言换行等格式问题已修复,本地 spotless:check 通过。

本地验证:mvn -pl agentscope-harness -am spotless:check test 全量通过(583 项,0 失败)。

@xseruer
xseruer requested a review from juruoO-o November 24, 2026 07:42

@juruoO-o juruoO-o 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.

感谢补齐修复。复审时确认,取消任务误报 FAILED、自动通知带出原始异常和 Spotless 失败均已解决。本地 61 项定向测试通过。

[P1] 终态写入失败后仍会发出完成通知。 我在独立测试中让工作区终态写入抛异常,回调仍收到 COMPLETED,重新读取的任务记录却仍是 RUNNING。persistRecord 捕获写入异常后,updateStatus 仍返回拟写入的状态,settleAndNotify 据此发送通知。请根据实际写入结果决定是否发送终态通知,并覆盖终态落盘失败的用例。

另外,中英文 docs/v2 的新增段落引用了 TaskSettledCallback,而文档对应的 v2.0.4 没有这个接口。中英文开发版文档已有相同说明,请移除稳定版的新增段落。

updateStatus now reads the record back after writing: WorkspaceManager
swallows storage failures, so a normal return from the write says
nothing about what the task exposes afterwards.

The settlement callback therefore never announces a terminal status that
is not on record. A completed result exists only in memory, so it is
handed over with the on-record status instead of being dropped (agentscope-ai#4399
requires the result to survive a failed record write); an unrecorded
failure or cancellation has nothing to deliver and is not announced.
@xseruer

xseruer commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

感谢复现,两点都已在 fffe6fe 处理,同时合入了最新 main(31d320049,冲突已解决,PR 现为 mergeable)。

1. [P1] 终态写入失败后仍发出完成通知

  • 根因上有一层需要补充:WorkspaceManager.writeTaskRecord 是尽力而为的——存储失败时它在内部打日志并吞掉 IOException,正常返回、不抛异常。所以只在 persistRecord 捕获异常时拦截并不够,真实磁盘故障下仍会误发。因此改为 updateStatus 在写入后回读记录,以记录上实际存在的状态作为回调依据(同时覆盖抛异常、静默失败、CAS 冲突三种情况)。
  • 规则:回调只报告记录上的状态,落盘失败时不播报任何终态。
    • FAILED / CANCELLED 未落盘:无可交付内容,不通知(仅记一条 warn)。
    • COMPLETED 未落盘:结果只存在于内存,会随进程退出丢失,因此仍送达一次——回调状态为记录上的状态(非终态),hint 明确说明"终态未能持久化,任务查询可能仍显示运行中,请勿重新发起"。这一点是与 main 上 fix(harness): harden context management and recovery #4399 的要求对齐的:它在您的评论之后 34 分钟合入,其 HarnessContextRegressionTest 的 FAILED_WRITE 场景明确断言记录写入被拒时结果仍须经 inbox 送达一次(wait_async_results 屏障依赖该 hint,否则结果丢失、等待超时)。如果您更希望严格"不通知",需要连同 fix(harness): harden context management and recovery #4399 的这个场景一起调整,请指示。

2. docs/v2

  • 中英文稳定版的新增段落已移除(恢复为 main 版本);开发版文档保留并补充了上述落盘失败的说明。

测试

  • WorkspaceTaskRepositoryTest.unpersistedTerminalStateIsNeverAnnounced:任务成功/失败 × 写入抛异常/静默失败 四种组合,断言回调状态与记录一致、失败任务无回调、无待投递项。
  • SubagentTaskSettledHintTest:落盘失败时,成功任务的 hint 携带结果并唤醒原会话;失败任务不进 inbox、不触发 wakeup。
  • 另:main 的 fix(harness): harden context management and recovery #4399 新增了 SubagentDeliveryTest.deliveryPreservesLargeResultsAndErrorsWithTaskOutputAvailable,断言 reminder 保留原始错误文本,与上一轮"reminder 不带原始异常"的要求冲突。已调整为 deliveryPreservesLargeResultsAndDefersErrorsToTaskOutput(大结果仍完整投递,错误交由 task_output)。

本地验证:mvn -pl agentscope-harness -am spotless:check test 通过(上游模块 3567 项、harness 2304 项,0 失败)。

@xseruer
xseruer requested a review from juruoO-o November 26, 2026 10:48

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

P0 重要紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants