Skip to content

[Bug]: onError 路径(超时/LLM 异常)下 AgentState 也不持久化,#2461 是否可一并覆盖? #2702

Open

Description

@wzq-xzwj

描述

感谢 #2008 修复 USER interrupt 路径下的 state 持久化,以及 #2461 正在处理 cancellation 路径。

我在阅读当前 main 分支(commit c49dc199)时发现,除 InterruptedException 和下游 cancellation 之外的其他 mid-stream 错误路径,似乎仍然会丢失 in-memory AgentState(包括 user input、partial reasoning、tool state 等)。这与 #1997 报告的本质相同,只是触发条件不同。

想请教一下:#2461 的 hook 机制是否考虑过扩展到 onError 路径?还是希望我把这个问题作为单独的 issue 跟进?

受影响的触发场景

  1. TimeoutException(显式 .timeout(...) 或 LLM 调用超时)
  2. RetryExhaustedException / LLM provider 抛出的异常
  3. ModelError / 网络异常
  4. HarnessAgent.wrappedStreamEvents 路径下的任意错误

复现步骤

  1. 构建 HarnessAgent(或 ReActAgent),配置 JsonFileAgentStateStore
  2. 通过 streamEvents(...) 启动一个长任务
  3. 让 mock model 在发出部分 TextBlockDeltaEvent 之后抛出 RuntimeException("boom")
  4. 等待流 error 终止
  5. 从 store 重新加载 AgentState
  6. 观察:本次流期间 addToContext(msgs) 添加的 user input + 任何 partial state 都不在持久化结果中
Model erroringModel = mock(Model.class);
when(erroringModel.stream(anyList(), any(), any()))
    .thenReturn(Flux.concat(
        Flux.just(textChunk),
        Flux.error(new RuntimeException("boom"))));  // 任何非 InterruptedException

HarnessAgent agent = HarnessAgent.builder()
    .name("t")
    .model(erroringModel)
    .workspace(workspace)
    .abstractFilesystem(new LocalFilesystem(workspace))
    .stateStore(new JsonFileAgentStateStore(...))   // 配置了持久化
    .build();

agent.streamEvents(messages, ctx).blockLast();
// 此时 store 中应包含 partial state(user msgs + 任何 emit 过的内容)
// 实际:从 store 读回,state.context 为空,user msg 丢失

期望行为

createErrorHandler(或类似的错误处理点)应在 rethrow error 之前 best-effort 持久化当前 AgentState,与 #2461 处理 cancellation 的策略一致。

根因分析

AgentBase.createErrorHandler(agentscope-core/src/main/java/io/agentscope/core/agent/AgentBase.java:495-503):

return error -> {
    if (error instanceof InterruptedException
            || (error.getCause() instanceof InterruptedException)) {
        return handleInterrupt(createInterruptContext(), originalArgs);
    }
    return notifyError(error).then(Mono.error(error));  // ← 其他错误绕过 saveStateToSession
};

只有 InterruptedException 走 handleInterrupt 路径(#2008 修过),其他错误直接 rethrow,不调 saveStateToSession。

HarnessAgent.wrappedStreamEvents(agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java:877-892)与 wrappedCall(line 828-854)不对称——前者没有任何错误恢复或 state 保存。

可能的方案(仅供参考)

如果 maintainer 认为这个范围值得合并到 #2461,可以考虑:

  • 方案 A:扩展 onAgentExecutionCancelled(callScope) 为更通用的 onAgentExecutionTerminated(callScope, signal),SignalType.onError 也触发 state 保存
  • 方案 B:在 createErrorHandler 的 notifyError(error).then(...) 之前 best-effort 调一次 saveStateToSession(需要把 saveStateToSession 提升到 AgentBase 或用 protected hook)
  • 方案 C:在 ReActAgent.buildAgentStream 的 doFinally 中判断 SignalType.onError 并触发保存

每个方案都有权衡(错误路径上 IO 的延迟 vs 数据丢失的成本),欢迎指正。

环境

  • AgentScope-Java 版本:2.0.0 / main (c49dc199)
  • Model:任意(mock 或真实 LLM provider)
  • StateStore:JsonFileAgentStateStore(其他 store 同理)

关联

非常感谢各位 maintainer 的辛勤工作 🙏

Activity

  1. added
    bug
    area/core/agent
    on Aug 15, 2026
  2. luo9 commented on Sep 8, 2026

    @luo9

    补充一个case:没输出最终MSG的场景(比如调用tool后结束loop但不输出text时),AgentState也不会持久化,会导致session的下一轮loop时丢失上下文。

    buildFinalMessage() 返回 null,最终 doCallInner() 没有返回 Msg,所以后面的 saveStateToSession() 没有机会执行。

  3. moved this from Backlog to In progress in AgentScope Javaon Sep 8, 2026
  4. oss-maintainer commented on Sep 25, 2026

    @oss-maintainer
    Collaborator

    Automated evaluation — re-verified against current main (3c1c29c01)

    Verdict: the two persistence gaps reported here are already fixed on main. The only case still open is call cancellation, which is tracked by #3259.

    What the code does today

    1. Non-interrupt terminal errors (timeout / model API failure) — fixed.
    ReActAgent.doCall now runs persistence on the error path:

    • agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:1226-1233
      return scope.doCallInner(msgs)
              .onErrorResume(error -> saveStateAfterCallFailure(scope, error))
              .flatMap(result -> saveStateToSession(scope).thenReturn(result))
              .switchIfEmpty(Mono.defer(() -> saveStateToSession(scope).then(Mono.<Msg>empty())));
    • saveStateAfterCallFailure (ReActAgent.java:510-527) re-throws untouched only when the failure wraps an InterruptedException (that case is reconciled inside handleInterrupt, which persists at ReActAgent.java:4364); every other failure saves first, and a save failure is attached as a suppressed exception instead of masking the original error.
    • Same shape on the structured-output path: ReActAgent.java:1379-1407.
    • Landmark commit: 3f0f3dfa4 — fix(agent): 模型调用失败时持久化当前轮次上下文 (fix(agent): 模型调用失败时持久化当前轮次上下文 #2799, 2026-08-22).
    • Pinned by tests: agentscope-core/src/test/java/io/agentscope/core/agent/ReActAgentCallFailurePersistenceTest.java:54-75 (failing model stream → user input is persisted, incomplete tool call is not) and :119-136 (store failure must not replace the model failure).

    2. buildFinalMessage() returning null — fixed.
    The empty-result case is now covered by the switchIfEmpty(saveStateToSession(...)) arm quoted above, so a loop that ends after a tool call with no final text still writes AgentState. Landmark commit: d20ebbe05 — fix(core): persist state after empty agent results (#3049, merged 2026-09-09), whose description explicitly references this issue.

    3. About the AgentBase handler in the original report.
    AgentBase.createErrorHandler (agentscope-core/src/main/java/io/agentscope/core/agent/AgentBase.java:522-531) still only does notifyError(error).then(Mono.error(error)) for non-interrupt errors. That is not a gap: persistence is a ReActAgent concern (the base class has no AgentStateStore binding), and it is applied one layer below, inside doCall, which both call() and streamEvents() funnel through (ReActAgent.java:1148-1150).

    4. HarnessAgent asymmetry — real, but not about persistence.
    wrappedCall carries a context-overflow recovery arm (agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java:959-967) while wrappedStreamEvents (:991-1006) does not. Both ultimately delegate to the same ReActAgent.doCall, so state persistence is symmetric; the missing piece on the streaming side is overflow recovery, which is a different behaviour from the one reported here.

    What is still open

    The cancellation path (subscriber cancels mid-stream) is not covered by the two arms above — cancel is not an onError signal. That is exactly the scope of the open PR #3259 (fix(core): persist agent state after call cancellation), which was closed-once #2461 never merged. #3259 is currently CONFLICTING against main, so it needs a rebase before it can land.

    Suggestion

    If you are still seeing state loss on a timeout or a model error, please share the version you run — anything after #2799 (2026-08-22) and #3049 (2026-09-09) should already behave. A reproduction on a build that includes both would be useful. For cancellation specifically, following or reviewing #3259 is the right place.

    Automated evaluation by github-manager. Verification method: read-only inspection of a main@3c1c29c01 checkout plus the merge history above; no code was modified and nothing was committed.

  5. juruoO-o commented on Nov 12, 2026

    @juruoO-o
    Collaborator

    Status update: #3049 (merged) makes empty agent results persist state via saveStateToSession(). The onError path (timeout / LLM exception) called out here still needs coverage/confirmation — keeping open.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/core/agentbug

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions