Skip to content

fix(durable): reconcile interrupted native calls when a cancelled Tur… - #4394

Open
BiuBiuH wants to merge 1 commit into
agentscope-ai:mainfrom
BiuBiuH:fix/durable-cancelled-settle
Open

BiuBiuH wants to merge 1 commit into
agentscope-ai:mainfrom
BiuBiuH:fix/durable-cancelled-settle

Conversation

@BiuBiuH

@BiuBiuH BiuBiuH commented Nov 25, 2026 •

Copy link
Copy Markdown

AgentScope-Java Version

2.1.0-SNAPSHOT (main @ ea2aed13221c9b6fcbd44ba0f2c359d7dbfd4786)

Description

Closes #4393 .

Background

A Durable Turn that is cancelled while an in-process (non-executor) tool is running can never
settle. Cancelling sets turn.cancel = true and moves the Turn to CANCELLING, but the
invocation is torn down before the tool reports a result, so the native Thread journal keeps a
tool/dispatch with no matching action/end.

JournalProjection therefore reports a non-empty uncertainToolCalls, and every subsequent
claim re-enters AgentScopeAdapter.settle and throws:

var reconciled =
        frame.tools().stream().map(tool -> tool.request().call().callId()).toList();
if (projection.uncertainToolCalls().stream().anyMatch(id -> !reconciled.contains(id)))
    throw new DurableException(
            DurableException.Code.CONFLICT, "Native tool outcome requires reconciliation");

reconciled is derived only from frame.tools(), i.e. executor-backed (Hands) calls. An
in-process call never appears there, so this gate cannot open by any automatic means. The Turn
stays CANCELLING forever, the Thread's head never becomes terminal, and every later Turn on
that Thread stays QUEUED. The only remediation today is stopping the host and running
ThreadRecovery.reconcile offline.

Note that the same method already synthesizes INTERRUPTED results for pending
interactions a few lines below, so the two categories were handled inconsistently.

Root cause of the missing action/end

Not changed by this PR, but relevant to the fix:

  1. DurableRuntime cancels by setting stopped and then interrupting the worker thread.
    HarnessContext.check() rejects any durable write while stopped is set, so the
    Mono.usingWhen cancel handler in ActionObservations (which records
    action/end(INTERRUPTED)) is fenced before it can commit.
  2. The adapter executes with agent.stream(...).blockLast(), so a thread interrupt disposes the
    subscription instead of emitting an error signal. AgentBase.createErrorHandler never
    routes it to handleInterrupt, so
    synthesizeErrorResultsForPendingToolCalls() never runs.
  3. Even a synthesized tool/result would not clear the gate: JournalProjection only removes
    ids on action/end and on recovery/applied.resolvedToolCallIds.

Changes

AgentScopeAdapter:

  • In settle, when status == CANCELLED, reconcile the uncertain native calls through the
    public ThreadRecovery.reconcile API with INTERRUPTED outcomes, then re-read the projection
    before the existing gate. When nothing is uncertain the call is skipped, so an ordinary
    cancellation is unaffected.
  • Added a private interrupted(ThreadJournal, Set<String>) helper. It resolves tool names from
    the tool/requested events and builds ToolResultBlocks with
    ToolResultState.INTERRUPTED. The model-visible text states that the call was interrupted by
    the user, that its side effect is unknown, and that it will not be retried.
  • FAILED is deliberately unchanged and still requires operator reconciliation.

AgentScopeAdapterTest:

  • cancelReconcilesDispatchedNativeCallSoSettlementCanCommit — a native tool dispatches and then
    blocks; the Turn is cancelled mid-flight; after settlement the Turn is CANCELLED with no
    recorded runtime failure, and the Thread accepts a subsequent Turn.
  • failedSettlementStillRequiresReconciliationForLostNativeCalls — the same shape under FAILED
    still throws Native tool outcome requires reconciliation, pinning the retained manual gate.

Why this is not "guessing an outcome"

HarnessAdapter.settle already documents the required behaviour:

/**
 * Settle FAILED or CANCELLED only after external operations settle. Clear native pending work
 * without inference before committing the terminal task, so the next Turn can use this Thread.
 */

A user cancellation is a fact: the call was abandoned. Recording it as INTERRUPTED does not
claim success, does not invent an output, and does not authorize re-execution — which is exactly
what ThreadRecovery exists to prevent. The repair is written through the same public API an
operator would use, so the journal shape (tool/result(reconciled), recovery/applied,
state/checkpoint) is unchanged.

FAILED stays manual on purpose: after a crash or exhausted retries the Turn may be replayed and
the model may re-issue the same call, so a human must decide whether the lost side effect
happened.

Scope / risk

  • Only the CANCELLED branch changes; FAILED behaviour and both existing gates are untouched.
  • No public API, message, event or persisted-format change.
  • Reconciliation writes go through ThreadRecovery and the existing BackendThreadJournal, so
    fencing, sequencing and receipt semantics are preserved.
  • Known follow-up (not in this PR): make the durable cancellation reachable by the core
    cooperative interrupt, and back off a cancelled Turn instead of re-claiming every ~100 ms.

How to test

mvn spotless:apply
mvn -pl agentscope-durable/durable-adapters/durable-adapter-harness-agentscope -am test

Targeted:

mvn -pl agentscope-durable/durable-adapters/durable-adapter-harness-agentscope \
    test -Dtest='AgentScopeAdapterTest#cancelReconcilesDispatchedNativeCallSoSettlementCanCommit+failedSettlementStillRequiresReconciliationForLostNativeCalls'

Checklist

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (e.g. links, examples, etc.)
  • Code is ready for review

@CLAassistant

CLAassistant commented Nov 25, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@ningmao-hlyz ningmao-hlyz 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.

[P1] The new cancellation test does not exercise the change. Instrumenting settle shows uncertain=[] for the CANCELLED case in cancelReconcilesDispatchedNativeCallSoSettlementCanCommit, so !lost.isEmpty() never fires; deleting the whole if (status == TurnStatus.CANCELLED) block leaves the test green (1/1 pass). The blocking tool writes its result before the turn settles. To cover the fix the dispatch has to still be unresolved at settle time, and the assertion should read the journal (uncertainToolCalls empty after settle), not just the next turn succeeding. The FAILED case in the other new test does produce uncertain=[call-1], so the shape is reachable.

[P2] lost is read outside ThreadRecovery.reconcile, which re-reads the projection under its own lease and requires an exact key-set match. A late tool/result landing between the two reads turns settle into IllegalArgumentException("Supply exactly the unresolved tool outcomes") — the same dead end this PR removes. Reading inside one acquire, or retrying once on mismatch, would close it.

[P2] names.getOrDefault(id, "tool") invents a name when tool/requested is missing from the scan window; replay paths that match on the tool name would see a tool that never existed.

@BiuBiuH

BiuBiuH commented Nov 27, 2026

Copy link
Copy Markdown
Author

@ningmao-hlyz
Thanks for the detailed review — the P1 instrumentation is the most useful thing anyone has
said about this PR, and you're right.

[P1] The new cancellation test is vacuous — confirmed

cancelReconcilesDispatchedNativeCallSoSettlementCanCommit never enters the branch it is
supposed to cover:

ticking.start();
assertTrue(entered.await(...));
backend.cancel(thread, turnId, "ui-cancel");
release.countDown();     // <- the blocking tool immediately returns
ticking.join(...);

release.countDown() fires right after cancel(), so the tool returns
ToolResultBlock.text("late") and action/end lands in the journal long before the runtime
notices the cancellation. The heartbeat only polls cancellation every
max(25ms, leaseDuration / 3) — 10s with the default 30s lease — so by the time
DurableRuntime sets stopped and interrupts, there is nothing left unresolved. Hence
uncertain=[] at settle and !lost.isEmpty() never fires. Deleting the whole
if (status == TurnStatus.CANCELLED) block leaving the test green is conclusive: the test
proves nothing today, and that is on me, not on the implementation.

Your note that the FAILED test does produce uncertain=[call-1] is the important hint: the
shape is reachable when settle runs while tool/dispatch is still the journal head. The
rewrite will:

  • keep the tool blocked and drive settlement while the dispatch is unresolved,
  • assert on the journal — JournalProjection.read(log).uncertainToolCalls() empty after
    settle, plus the tool/result(reconciled) → recovery/applied → state/checkpoint triple —
    instead of inferring success from the next Turn succeeding.

[P2] Race on lost — agreed

Reading uncertainToolCalls() outside ThreadRecovery.reconcile and letting it re-read under
its own lease is unsound: a late action/end from the abandoned tool between the two reads
changes the key set, and reconcile rejects it with
IllegalArgumentException("Supply exactly the unresolved tool outcomes"). That converts one
dead end into another. I'll either read inside the same log.acquire(...) window or retry
once on mismatch.

[P2] Invented tool name — agreed

names.getOrDefault(id, "tool") fabricates an identity that never existed, and replay /
normalisation paths match on the tool name. Dropping the fallback and failing as a
CONFLICT on an inconsistent journal is the right behaviour.

The larger issue: main has already moved, with a different design

Before I rebase, please note that #4443 (feat(durable): complete resumable agent execution,
5ef06fab) landed on main two days after this PR was opened and rewrote exactly this area.
AgentScopeAdapter.settle no longer throws on unresolved native calls. It now does:

if (projection.uncertainToolCalls().stream().anyMatch(id -> !executions.containsKey(id))) {
    projection = resolveNativeToolOutcomes(context, log, projection);
    if (projection == null) return;      // parked, not failed
    frame = context.frame();
}

and resolveNativeToolOutcomes is evidence-driven:

  • it looks for a WaitCondition.NATIVE_TOOL_RECONCILIATION signal carrying a
    NativeToolReconciliation whose outcome id set matches the pending set exactly;
  • with no such signal it calls parkNativeToolOutcomes, which commits a
    tool.call.updated ... status=UNKNOWN fact and a WAITING Turn keyed on
    NATIVE_TOOL_RECONCILIATION;
  • with a valid signal it reconciles through ThreadRecovery.reconcile(log, outcomes, reconciliation.evidenceRef()).

So upstream has chosen "wait for out-of-band evidence" over "assume interrupted". That is
compatible with the FAILED half of my proposal, but it is not compatible with auto-recording
INTERRUPTED on CANCELLED, and this PR is now conflicting (mergeable_state: dirty).

It also means the defect reported in #4393 is not actually gone — it changed shape. A
cancelled Turn no longer spins on Native tool outcome requires reconciliation; it parks as
WAITING on NATIVE_TOOL_RECONCILIATION. But the Turn still never becomes terminal, so the
Thread head is still stuck and later Turns still stay QUEUED. The hot-loop part is gone;
the "user cancel cannot settle the Turn" part is not.

What I'd like your call on

For a user-cancelled Turn specifically, is parking as WAITING with no evidence
available the intended behaviour? My reading of HarnessAdapter.settle — "Clear native
pending work without inference before committing the terminal task, so the next Turn can use
this Thread"
— is that a cancellation should be able to reach CANCELLED, and that
"interrupted by the user, outcome unknown, never retried" is a fact rather than an inference.

If the maintainers prefer evidence-only reconciliation for both FAILED and CANCELLED, I'll
close this PR and instead file a focused follow-up against the new design (rebase the
recordFailure back-off part, and reopen the settlement question for cancellation with the
WAITING behaviour as the reference point). If the split is acceptable — auto-INTERRUPTED
for CANCELLED, evidence-only for FAILED — I'll rebase onto 5ef06fab, adapt the
CANCELLED path to the new settle structure, and rework the tests to actually exercise the
branch, addressing all three points above.

Either way: thanks for catching the vacuous test. It would have been embarrassing to land.

@ningmao-hlyz

Copy link
Copy Markdown
Contributor

Split the two statuses. CANCELLED can record INTERRUPTED without evidence; FAILED keeps the gate.

The difference is what the runtime already knows, not what settle's javadoc promises. On a user cancel the abandonment already has its own cause — InvocationRecords closes the active step with host_released, separate from invocation_failed and ownership_lost — and settle already synthesises INTERRUPTED for a call with neither an execution nor a response. The only case that parks is a dispatch with no end, where it is the host's release record that got lost, not the outcome. On FAILED the process is gone and another node may still be running the call; that is what the gate protects.

On main: 5ef06fab (#4443) landed two days after this opened, so the patch is dirty. Drop the back-off half — readyAt returns -1 for a turn waiting on native reconciliation. The other half survives and got quieter: the turn parks, readyAt keeps returning -1, nothing picks it up on its own, and only a reconciliation signal supplied from outside can wake it. InvocationRecorder keeps throwing in the meantime, so the Thread stays blocked — the offline-recovery path the issue describes.

Two things to change before rebasing:

  • uncertainToolCalls() is read outside the lease and handed to ThreadRecovery.reconcile, which re-reads under its own lease and throws Supply exactly the unresolved tool outcomes when the set moved. A late action/end from the abandoned tool is the expected case here, not an edge one.
  • names.getOrDefault(id, "tool") invents a name, and replay matches on names. An id with no recorded call should fail as CONFLICT.

Suggested shape: keep one write path. Extract the body of reconcile into a package-private method that assumes the lease, and add a second entry that derives the outcomes and calls it inside a single acquire. reconcile keeps its exact-set check; the new entry builds the map from the restored ToolUseBlocks, so the check holds by construction. The adapter then needs one line in settle for status == CANCELLED. Clearing through recovery/applied is what lets the next Turn build an InvocationRecorder, so this fixes the Thread, not just the Turn.

Tests: your reading of countDown() is right. After the rebase I would assert status == CANCELLED, empty uncertainToolCalls(), and the tool/result(reconciled) → recovery/applied → state/checkpoint triple — plus a second Turn on the same Thread, which is what the issue is actually about.

Scope: leave FAILED alone here and say so in the description, so it does not read as weakening the gate.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Cancelling a Durable Turn while an in-process tool is running leaves it stuck in CANCELLING

3 participants