agentscope-java icon indicating copy to clipboard operation
agentscope-java copied to clipboard

[Bug]: User interrupt during a running tool leaves journal uncertain calls and bricks the session

Open chcodex opened this issue 5 days ago • 1 comments

Describe the bug

When a user cancels a running HarnessAgent / ReActAgent call while a tool is still executing, the interrupted tool call is left in the journal's uncertainToolCalls set forever. handleInterrupt does reconcile the pending tool calls in AgentState.context, but it never writes action/end or recovery/applied to the journal, so the two views disagree. As a result every later state-changing operation on that session fails with:

Reconcile unresolved tool outcomes before changing session state

For an interactive application this means: one click on "Stop generating" while a tool is running permanently bricks the conversation, because applications have no public way to obtain the uncertain call ids or to trigger ThreadRecovery.reconcile (they only hold an Agent/HarnessAgent, not a ThreadJournal).

To Reproduce

  1. Build a HarnessAgent with native session history (threadJournalStore(...), journalEnabled(true), enablePendingToolRecovery(true)).
  2. Send a message that makes the model invoke a long-running tool (e.g. an execute tool that runs a shell command).
  3. While the tool is executing, cancel the returned Flux (user presses "Stop") — the app calls agent.interrupt(userId, sessionId) from doOnCancel.
  4. Send another message on the same session.

Step 4 throws on the very first state write (setPermissionMode → updateAgentState):

Reconcile unresolved tool outcomes before changing session state

Error messages

WARN  AgentService: chat error: Reconcile unresolved tool outcomes before changing session state after 485ms
ERROR GlobalSubscriptionExceptionResolver: Reconcile unresolved tool outcomes before changing session state
io.agentscope.core.session.SessionLogException: Reconcile unresolved tool outcomes before changing session state
    at io.agentscope.core.session.SessionStateAccess.change(SessionStateAccess.java:85)
    at io.agentscope.core.session.SessionStateAccess.update(SessionStateAccess.java:59)
    at io.agentscope.core.ReActAgent.updateAgentState(ReActAgent.java:5715)
    at io.agentscope.core.ReActAgent.setPermissionMode(ReActAgent.java:5957)
    at io.agentscope.harness.agent.HarnessAgent.setPermissionMode(HarnessAgent.java:500)

Timeline from the same session (redacted):

11:09:30.939 PRE_ACTING  | id=call_xxx, name=execute
11:09:32.097 chat CANCELLED / CancellationException: Agent run cancelled
11:09:32.649 execute failed: <shell command>          # tool was interrupted
            (no POST_ACTING for call_xxx)
            (no "Synthesized interrupted-result for pending tool call" log)
11:33:28.972 Reconcile unresolved tool outcomes before changing session state
11:33:37.920 Reconcile unresolved tool outcomes before changing session state
11:34:17.622 Reconcile unresolved tool outcomes before changing session state
11:34:29.373 Reconcile unresolved tool outcomes before changing session state

Root cause

ReActAgent.handleInterrupt (main, ReActAgent.java:5984) says it reconciles pending tool calls:

// Reconcile any pending tool calls before appending the recovery message.
// The tool_use written during reasoning would otherwise be persisted with no
// matching tool result, leaving the AgentState inconsistent for the next run.
scope.synthesizeErrorResultsForPendingToolCalls();   // ReActAgent.java:5999
...
return saveStateToSession(scope);

But synthesizeErrorResultsForPendingToolCalls (ReActAgent.java:3105) only appends ToolResultMessage to state.context. saveStateToSession then writes a state/checkpoint and tool/result events.

JournalProjection only clears uncertainToolCalls for these event types (JournalProjection.java:77-88):

case "tool/dispatch" -> uncertain.add((String) data.get("toolCallId"));
case "action/end" -> { ... uncertain.remove(id); ... }
case "recovery/applied" -> { ... resolved ids removed ... }

A tool/result message or a state/checkpoint does not remove the id, so after an interrupt the context contains a synthetic error result while the journal still considers the call unknown. ThreadStateAccess.change (ThreadStateAccess.java:89) then rejects every later updateAgentState / saveAgentState.

The task's own test encodes this as expected behavior — ReActNativeToolCancellationTest asserts uncertainToolCalls() still contains slow-call after cancellation and calls ThreadRecovery.reconcile(...) manually. That is reasonable as a crash-recovery rule, but for a deliberate user interrupt the framework already knows the exact pending call ids and has already produced synthetic error results for them, so leaving the journal unresolved is an internal inconsistency rather than a genuinely unknown side effect.

Related but different: #4393 (Durable turn stuck in CANCELLING).

Expected behavior

A user-initiated interrupt should settle the journal as well:

  1. For each pending tool call, write action/end with ActionObservation.Status.INTERRUPTED (or one recovery/applied event carrying resolvedToolCallIds), and flush before the interrupt checkpoint; or
  2. If unresolved is intentional, expose a public API on ReActAgent / HarnessAgent such as listUncertainToolCalls() and reconcile(Map<String, ToolResultBlock>), so applications can recover the session without holding the internal ThreadJournal.

The first option matches the existing interrupt semantics: a user interrupt is not a crash, and the framework already knows the interrupted call ids.

Suggested fix

  • handleInterrupt: after synthesizeErrorResultsForPendingToolCalls(), append an action/end record with INTERRUPTED status for each pending call (the cancel arm of ActionObservations.observe already builds this observation at ActionObservations.java:157, it just never reaches the journal on this path), or append a single recovery/applied event; flush it before saveStateToSession.
  • Make the Reactor-cancel path deterministic: record the interruption from an independent boundedElastic task so it does not depend on the cancelled downstream (the related fix in #3888 keeps the flush alive, but the event still has to be appended).
  • Add listUncertainToolCalls() / reconcile(...) to the agent APIs as a safety net.

Environment

  • AgentScope-Java Version: develop-3ea90457f6-1 (JitPack build, session-based journal); verified by code inspection that upstream/main (80926f92d) still has the same behavior
  • Java Version: 17
  • OS: Linux (Kubernetes pod)
  • Integration: Spring Boot 3.5.7, HarnessAgent + threadJournalStore + journalEnabled(true), project workspace, enablePendingToolRecovery(true)

chcodex avatar Nov 27 '26 04:11 chcodex

I would separate the cancellation UX from whether an external tool outcome is known.

There is already a public recovery path on HarnessAgent, without obtaining an internal journal: inspectThread(ctx) and reconcileToolOutcomes(ctx, outcomes, reason). The first exposes uncertainToolCalls(). The latter accepts results for the original call IDs and delegates to ThreadRecovery. ReActAgent also exposes threadJournal(ctx); the generic Agent interface is a different API surface.

For a direct Harness call, once its writer and external work have actually stopped, the application can inspect those IDs, query the original operation for receipts/status, and pass verified outcomes to reconcileToolOutcomes. This is not something to run blindly in doOnCancel: disposing a subscription does not prove that a remote write stopped, and the journal writer must have released ownership first. Durable-managed calls must use their managed recovery path instead of writing the native journal directly.

There is also a relevant main update after this issue was filed: #4443 landed at 5ef06fab959b. JournalProjection deliberately retains uncertainty for an interrupted dispatched call, even when action/end exists. So appending action/end(INTERRUPTED) alone would not clear this gate on current main. ThreadRecovery now also rejects explicitly unknown outcomes. A synthetic error message is not evidence that an external effect did not happen.

That still leaves a genuine usability problem: applications need a discoverable way to present "stopped, outcome needs confirmation" and resume after confirmation, rather than treating every subsequent state update as a generic chat failure.

I can take a bounded direct-Harness recovery example and regression tests using these public methods: both call and streamEvents cancellation, waiting for writer release, verified recovery followed by a successful state update/next call, no replay of an already completed sibling tool, and user/session isolation. The no-receipt/unknown-outcome case should remain blocked, not be turned into a guessed cancellation result. Would that be a useful first slice here, while any automatic-settlement policy is discussed separately? I have checked the current source/API above; I have not run a current-main reproduction or claimed that #4443 resolves this report.

Update: #4451 now supplies this bounded documentation/test slice on that main revision. Four new cases cover call/streamEvents with plain cancellation and interrupt(ctx) in doOnCancel, including verified-receipt recovery, unchanged state after rejected unknown results, user/session isolation and no sibling replay. The complete Harness dependency reactor passed (6,452 cases, zero failures/errors, 47 existing skips), as did documentation checks. The external receipt is a controlled test fixture, not a live service. This does not auto-settle unknown effects or claim the broader cancellation-policy request is resolved.

CryoThrust avatar Nov 27 '26 04:11 CryoThrust