Skip to content

[Bug]SSE 断连导致本轮会话进度整体丢失:AgentState 仅在  call()  正常结束时落盘一次,所有 cancel 路径均无保存钩子 #3237

Open

Description

@wxh2010zd

问题现象

  • 长任务(多轮工具调用)执行中途,客户端/网关因空闲超时切断 SSE 连接后,本轮已完成的全部进度丢失。
  • 会话状态回退到本轮 call 开始前的样子,"就像从来没有对话过"。
  • ask_user 挂起场景:回答后 resume 的新一轮若断连,用户回答也一起丢失,会话看起来停留在 ask 阶段。

复现步骤

  1. 启动需要多轮工具调用的任务(如查询+导出)。
  2. 在工具执行间隙或模型长时间无 token 输出时断开客户端(或等待网关空闲超时)。
  3. 重新连接同一 sessionId 继续对话 → 上一轮全部进度丢失。

根因分析

  • AgentState 落盘时机:仅 ReActAgent.call() 整体结束(成功/失败/空)时保存一次(ReActAgent.java L1195-1225, saveStateToSession L475-497)。
  • 流式出口:sink.onCancel(lifecycleDisposable)(ReActAgent.java L1093)——客户端 cancel 时直接 dispose 生命周期 Mono,无保存钩子。
  • Harness 层 TranscriptMiddleware 的 concatWith 落盘、MemoryFlushMiddleware 的 doOnComplete 落盘,在 cancel 时均被短路。
  • saveStateAfterCallFailure(L499-528)遇到 InterruptedException 特意跳过保存(交给 handleInterrupt)——但裸 cancel 不会触发 handleInterrupt 的信号消费(执行循环已死,信号无人读)。
  • 综合:三条 cancel 路径(Controller onErrorResume 只接 error / 框架 sink.onCancel / harness middleware doOnComplete)均无落盘。

影响

  • 长任务在弱网/网关空闲超时(常见 60s)下几乎必然丢进度,用户体验=任务白跑。
  • 模型供应商侧卡顿(如 429 重试、长推理无 token)会放大触发概率。

期望行为

  • 连接被取消时,框架应尽最大努力把当前 AgentState(含已完成轮次)持久化,并补全悬空 tool_use(排除 ASKING),使会话可续接。

Activity

  1. added
    bug
    on Sep 21, 2026
  2. added
    help wanted
    on Sep 21, 2026
  3. oss-maintainer commented on Sep 21, 2026

    @oss-maintainer
    Collaborator

    Issue Evaluation

    Category: bug | Status: Confirmed | Severity: High

    Verified against local main at 7d08f8fda (2026-09-21). Every mechanism in your root-cause analysis holds at HEAD, with line numbers shifted slightly from your citation. The main file is agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java.

    Point-by-point verification

    # Your claim Verdict Actual location
    1 AgentState is persisted only when call() terminates as a whole TRUE doCall at ReActAgent.java:1209-1238 — save happens on the flatMap / switchIfEmpty success paths and the onErrorResume failure path only; no incremental save during streaming
    2 saveStateToSession is the only save entry point TRUE ReActAgent.java:476-497; callers are doCall (:1232, :1236), saveStateAfterCallFailure (:516) and handleInterrupt (:4326)
    3 sink.onCancel(lifecycleDisposable) disposes the lifecycle Mono with no save hook TRUE ReActAgent.java:1107 — disposal only; saveStateToSession is never reached
    4 saveStateAfterCallFailure skips saving on InterruptedException, deferring to handleInterrupt, which a bare cancel never reaches TRUE ReActAgent.java:512-528 returns Mono.error(callFailure) when containsInterruptedException. handleInterrupt (:4299-4336) does save, but a client/gateway cancellation surfaces as CancellationException, not an interrupt, so it never gets there
    5 Harness TranscriptMiddleware (concatWith) and MemoryFlushMiddleware (doOnComplete) are short-circuited on cancel TRUE TranscriptMiddleware.java:68-78 appends via concatWith, so upstream cancel prevents the appended Mono from running; MemoryFlushMiddleware.java:159 flushes in doOnComplete, which does not fire on cancel

    Cancel-path hook search result: none. The only cancel/dispose hooks in the state-saving chain are cleanup-only — ReActAgent.java:1107 (sink.onCancel, disposal) and AsyncToolMiddleware.java:171 (sink.onDispose, disposes timer/subscription). There is no doOnCancel-driven persistence in either agentscope-core or the harness layer. Your conclusion that all three cancel paths lack a save hook is correct.

    Impact. Confirmed as described: a mid-call cancellation disposes the lifecycle before saveStateToSession runs and bypasses the transcript/flush hooks, so the turn's accumulated progress (including a consumed ask_user answer on a resumed turn) is lost and the session reverts to its pre-call state. Reproducible under any gateway idle timeout shorter than the turn duration.

    Suggested fix direction (for discussion, not a commitment):

    1. Add a best-effort persistence hook on the cancellation path — sink.onCancel / doOnCancel on the lifecycle Mono in ReActAgent — that calls saveStateToSession with the state snapshot accumulated so far, guarded so it is a no-op when the normal terminal save already ran.
    2. As you note, dangling tool_use blocks must be reconciled before writing, excluding ASKING, so the next turn resumes on a well-formed transcript.
    3. Consider whether TranscriptMiddleware / MemoryFlushMiddleware should move from concatWith / doOnComplete to a doFinally(signalType -> ...) covering CANCEL, so harness-layer persistence survives cancellation too.
    4. The hook must be idempotent and non-throwing: a failing save on the cancel path should not mask or delay the original cancellation.

    This looks like a genuinely valuable fix for long-running / remote-agent deployments, and the report is complete — no further information needed. No PR is currently linked to this issue. If you or a maintainer would like a written spec and a proposed patch prepared from the direction above, reply here and say so; if you plan to take it yourselves, just note that instead and we will leave it to you.


    Automated evaluation by github-manager-bot

  4. xihongshichaojidan8 commented on Sep 22, 2026

    @xihongshichaojidan8
    Contributor

    我在 main(c0d03cce)上用文件状态库复现了:取消订阅后,新输入和已完成的工具结果未保存;正常结束和报错则会保存。权限确认场景下,取消后磁盘状态也会退回 ASKING。

    我想参与修复,先聚焦 core 的取消保存流程,并参考已关闭 PR #2820 的评审,重点处理保存不阻塞取消、避免重复保存,以及同会话恢复时的读写顺序。请问目前有人在处理吗?这个范围是否合适?

  5. oss-maintainer commented on Sep 22, 2026

    @oss-maintainer
    Collaborator

    Issue Evaluation — follow-up (new input: contributor claims the fix)

    Category: bug | Module: agentscope-core (state persistence on cancellation) | Status: Confirmed — still unfixed at main@ed77530a4

    Thanks for the independent reproduction, @xihongshichaojidan8. Answering your two questions directly.

    1. Is anyone on it? No — no assignee, no PR linked to this issue, and the earlier attempt #2820 was closed unmerged on 2026-09-12. The issue is yours to take. This bot is deliberately standing down on #3237 so we do not open a competing PR.

    2. Is the scope right? Yes. core cancel-path persistence only is the correct cut. Re-checked against current main (ed77530a4):

    Anchor State at HEAD
    ReActAgent.java:1107 sink.onCancel(lifecycleDisposable) — disposes the lifecycle Mono, no persistence
    ReActAgent.java:1094 the only doFinally on the lifecycle chain emits AgentEndEvent + sink.complete(); it does not save
    ReActAgent.java:476 saveStateToSession remains the sole save entry point (CAS write on Schedulers.boundedElastic())
    ReActAgent.java:512 saveStateAfterCallFailure short-circuits on InterruptedException; a bare client/gateway cancel surfaces as CancellationException and reaches neither this nor handleInterrupt (:4307)

    So all three cancel paths are still save-free at HEAD — consistent with your file-store repro.

    3. Take #2820's two blocking review findings as your acceptance list. They are why that PR stalled, and both still apply:

    • P1 — save ordering / double write. Do not persist synchronously before cancellation propagates upstream: it delays the model and tool stop, lets live state keep mutating during the write, and if the cancel lands while the normal async save is in flight you start a second persistState and race loadedVersion/CAS. Converge on a single terminal save that runs after the upstream cancel, on a stable snapshot (doFinally(CANCEL)-style), kept off the event loop the way saveStateToSession already does.
    • P1 — dangling ALLOWED tool_use. Reconciling before the write must clear this turn's result-less PENDING and ALLOWED calls while preserving ASKING. Otherwise the next turn fails on a tool_use with no matching tool_result, and empty-message recovery can re-execute the tool. This is precisely your permission-confirmation scenario, where the on-disk state also regresses to ASKING.
    • Copilot's comment on the same PR flags the same shape: a failure path called persistState directly instead of going through the boundedElastic-scheduled save.
    • Keep the hook non-throwing and idempotent — a save failure on the cancel path must be logged and suppressed, never mask or delay the original cancellation.

    4. Suggested test matrix. cancel during tool execution (assert the tool receives cancel before the store writes); cancel while the normal async save is in flight (assert exactly one write, no version regression); PENDING/ALLOWED reconciled with ASKING preserved; and a JsonFileAgentStateStore round-trip proving the turn's new input plus completed tool results survive a mid-call unsubscribe — that last one matches your repro and would have caught the original bug.

    5. Rebase early. #2820 also stalled on conflicts with main. #3236 (unconditional-save version caching, 7d08f8fda) landed after it and touches the same save path, so pull current main before you build out the tests.

    If you want a written spec first, or want a review once the PR is up, reply here and @mention this account. Labels added: area/core (existing bug / help wanted left untouched).


    Automated evaluation by github-manager-bot

  6. added
    area/core
    on Sep 22, 2026
  7. xihongshichaojidan8 commented on Sep 23, 2026

    @xihongshichaojidan8
    Contributor

    @wxh2010zd @oss-maintainer 我已按前面讨论的 core-only 范围提交 PR #3259(基于当前 main):取消向上传递后异步保存本轮 AgentState,补全未完成的 PENDING/ALLOWED 工具结果并保留 ASKING;同时处理正常保存、取消保存和优雅停机保存的并发顺序。新增了文件状态库、HITL、同会话排队及保存竞态的回归测试,本地 core 测试 2,422 项通过(9 项跳过)。Harness 层持久化不在此 PR 范围内。欢迎查看和提出修改意见。

  8. oss-maintainer commented on Sep 23, 2026

    @oss-maintainer
    Collaborator

    Thanks for the update, @xihongshichaojidan8 — PR #3259 is noted and this bot will not open a competing PR for #3237 (stand-down still in effect).

    Quick status check at this tick (UTC):

    A detailed review against the acceptance list from the previous comment (single terminal save ordered after upstream cancellation, PENDING/ALLOWED reconciled with ASKING preserved, non-throwing/idempotent hook, and the four-case test matrix) will be posted on #3259 during the next PR review sweep, once CI settles. If you want the review earlier, reply here and we will prioritize it.


    Automated response by github-manager-bot

  9. oss-maintainer commented on Sep 24, 2026

    @oss-maintainer
    Collaborator

    Thanks for the update @xihongshichaojidan8, and for scoping it to core as discussed.

    Status of #3259: it has been reviewed and is APPROVED by the automated reviewer, mergeStateStatus=CLEAN, CLA signed — nothing blocking on your side. The remaining step is a merge by a project maintainer (the bot does not merge). cc @wxh2010zd.


    Automated status by github-manager-bot

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/corebughelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions