Repository navigation
Description
Describe the bug
A Durable Turn can never reach CANCELLED if the user cancels it while an in-process
(non-external) tool is running. The Turn stays in CANCELLING indefinitely, and every
subsequent claim re-throws DurableException: Native tool outcome requires reconciliation
from AgentScopeAdapter.settle().
Because the head Turn of the Thread never becomes terminal, all later Turns on the same
Thread remain QUEUED. The Thread is effectively unusable until an operator runs
ThreadRecovery.reconcile offline against the durable backend.
A second defect makes the failure mode much worse: after the cancel, the runtime retries
settlement roughly every 100 ms with no backoff, because recordFailure writes
turn.nextAttemptAt = 0 for cancelled Turns and readyAt returns that value directly.
In the observed case this produced ~4,600 Turn epochs and ~3,300 failure:* receipts over
11 hours, each cycle re-scanning the whole journal (~3,364 events, 67 of them externalized).
To Reproduce
- Register an in-process tool on the agent Toolkit: a
@Toolmethod that is not
declared as an external tool and is not routed to anExecutor(so it is not a
Hands/sandbox tool). Have it block for minutes, e.g. by polling an external job service. - Submit a Turn that invokes that tool, and let the tool enter its long polling loop.
- While the tool is running, request cancellation through the normal control path
(DurableTurn.cancel(...)/ the cancel endpoint). - Observe the durable state:
turn.cancel_requestedis appended andturn.statusbecomesCANCELLING(not
CANCELLED, because the Turn was already running);- the invocation is released with outcome
interrupted/ reasonhost_released; - the native Thread journal ends at
tool/dispatchwith no matchingaction/end,
and that Run has norun/endeither.
- Every later claim for that Thread throws
Native tool outcome requires reconciliation.
turn.statusnever leavesCANCELLING.epochand the number offailure:*receipts
keep growing, and the same WARN is logged on each attempt.
Journal tail of the stuck Thread (sequence numbers only, payloads elided):
seq 3358 step/phase
seq 3359 message/assistant <- model decided to call the long tool
seq 3360 tool/requested <- call_xxx
seq 3361 state/checkpoint <- reason=before_tool; last checkpoint in the Thread
seq 3362 action/start <- call_xxx
seq 3363 tool/decision <- call_xxx allowed
seq 3364 tool/dispatch <- call_xxx; journal head, nothing after this
(no action/end, no run/end, no recovery/applied)
JournalProjection.read(...) on that Thread returns
uncertainToolCalls = {call_xxx} and a non-empty activeRuns containing the interrupted
Run. Persisted Turn state at the same time:
status = CANCELLING
cancel = true
invocationCount = 6 <- unchanged; no new Run was ever created
lastRunId = run_... <- the interrupted Run
error = "Native tool outcome requires reconciliation"
waiting = null
Expected behavior
A user-initiated cancellation should be able to settle the Turn to CANCELLED.
HarnessAdapter.settle already documents this responsibility:
/**
* 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.
*/For a cancelled Turn, recording the abandoned in-flight call as INTERRUPTED ("the outcome
was lost and it will not be retried") states a fact. It does not infer success and does not
violate "never automatic re-execution of an uncertain side effect", which is what
ThreadRecovery exists to prevent.
AgentScopeAdapter.settle currently does not do this. It throws instead:
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) tool calls.
An in-process tool call is never in that list, so this gate cannot open by any automatic
means. Note that a few lines below, the same method already synthesizes INTERRUPTED
results for pending interactions; the two categories are handled inconsistently.
Separately, a cancelled Turn that keeps failing to settle should back off instead of
re-claiming every ~100 ms.
Error messages
2026-11-25T09:20:52.968+08:00 WARN 22216 --- [ durable-worker] io.agentscope.durable.DurableRuntime : Durable invocation failed
io.agentscope.durable.DurableException: Native tool outcome requires reconciliation
at io.agentscope.durable.agentscope.AgentScopeAdapter.settle(AgentScopeAdapter.java:596)
at io.agentscope.durable.DurableRuntime.process(DurableRuntime.java:636)
at io.agentscope.durable.DurableRuntime.lambda$offer$9(DurableRuntime.java:512)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at io.agentscope.durable.DurableRuntime.lambda$daemon$21(DurableRuntime.java:835)
at java.base/java.lang.Thread.run(Thread.java:842)
The same exception also surfaces from InvocationRecorder's constructor when the Thread is
reused, so even a manually failed Turn cannot recover the Thread without explicit
reconciliation:
io.agentscope.core.journal.JournalException:
Explicit reconciliation required for unknown tool outcomes: [call_xxx]
Environment
- AgentScope-Java Version:
2.1.0-SNAPSHOT(main @ea2aed13221c9b6fcbd44ba0f2c359d7dbfd4786) - Java Version: 17.0.12
- OS: Windows 11
- Maven: 3.9.x
- Durable backend: JDBC / SQLite (
durable-data/durable.db), single Brain host - Agent:
HarnessAgentbehindAgentScopeAdapter.forHarness(...) - Affected module:
agentscope-durable/durable-adapters/durable-adapter-harness-agentscope
Note: the agentscope-durable modules landed on main after v2.0.4 and are not present in
that release.
Additional context
Why the existing recovery paths do not cover this case
I traced the whole path. The journal entry is missing because the cancel handler that
should write action/end is fenced before it can commit, and the core-level cooperative
interrupt is never reached.
(1) Durable uses thread interruption, not the core interrupt flag.
On cancel the heartbeat does:
if (activeCall.invoking && backend.turn(key, lease.turnId()).cancellationRequested()) {
activeCall.stopped.set(true);
activeCall.thread.interrupt();
}stopped is set before the interrupt, and HarnessContext.check() is what every
durable write validates against:
public void check() {
if (stopped.get() || Thread.currentThread().isInterrupted())
throw new DurableException(DurableException.Code.FENCED, "Invocation stopped");
}(2) The usingWhen cancel cleanup loses the race.
ActionObservations wraps every tool execution in Mono.usingWhen with a cancel handler
that records action/end(INTERRUPTED). That handler's commit path is
record -> flush -> JournalSchedulers.commits() -> flushNow -> log.commit -> check(writer),
which throws FENCED because stopped is already true (and release(lease) clears the
owner shortly after, so even without stopped the write would be rejected). This is
observable in the journal: action/start and action/end counts differ by exactly the
calls abandoned by cancels.
(3) Core's handleInterrupt is bypassed.
AgentBase.createErrorHandler routes InterruptedException error signals to
handleInterrupt, which calls synthesizeErrorResultsForPendingToolCalls() to reconcile
dangling tool_use before persisting state (see #2470 / PR #2410). The durable adapter
executes with agent.stream(...).blockLast(); interrupting the worker thread disposes the
subscription instead of emitting an error signal, so that handler never runs.
(4) The tool runs on a different thread.
ToolExecutor.applyScheduling uses Schedulers.boundedElastic(). Interrupting the durable
worker thread does not interrupt the tool; the tool keeps running and its eventual result
has no subscriber. In the observed case the tool really did finish much later, outside the
invocation.
(5) Even a synthesized tool/result would not clear the gate.
JournalProjection only removes ids from uncertainToolCalls on action/end and on
recovery/applied.resolvedToolCallIds; a plain tool/result has no effect. So "let core
write the missing result" is not sufficient on its own.
Suggested fix
Two independent parts; happy to send PRs for both.
a. Clear native pending work when a cancelled Turn settles.
In AgentScopeAdapter.settle, for status == CANCELLED, use the existing public
ThreadRecovery.reconcile with INTERRUPTED outcomes for exactly the
uncertainToolCalls set, then re-read the projection before the existing gate. This
honours the documented HarnessAdapter.settle contract. The FAILED path should stay
manual: after a crash or exhausted retries the Turn may be retried, so a human still has to
decide whether the lost call happened.
b. Back off a cancelled Turn that keeps failing to settle.
In TransactionalSessionBackend.recordFailure, replace turn.cancel ? 0 : ... with a
value derived from recovery.policy().delay(failures); readyAt already returns
nextAttemptAt for cancelled Turns, and release only applies
max(nextAttemptAt, now + pollInterval), so a future timestamp is sufficient. This does not
change first-cancel latency, because cancel() still sets nextAttemptAt = 0.
Related issues
- [Bug]: native session 取消 checkpoint 丢失已完成工具结果,恢复时重复执行 #4045 — cancelling a native session drops already-completed tool results on recovery;
same family (cancel-time cleanup does not land in the journal), different symptom. - [Bug]: 子代理因悬空 pending tool_use 永久卡死,根因为 enablePendingToolRecovery 未透传且非 handleInterrupt 中断路径未清理上下文 #3016 — dangling pending
tool_usewedges a session permanently; that one goes through
the coreenablePendingToolRecoverypath, this one is durable-level. - [Bug]: 用户中断 reasoning 时会持久化未执行的工具调用,导致会话上下文无法恢复 #2470 / PR fix(core): reconcile dangling tool_use on interrupt before persisting AgentState #2410 — core already reconciles dangling
tool_useon interrupt. This report
shows the durable cancellation path never reaches that code.
Impact
User-visible cancellation is effectively unusable for any agent with a long-running
in-process tool: the conversation cannot continue on that Thread, and the host burns CPU
and storage in a retry loop. The only remediation today is stopping the process and running
ThreadRecovery.reconcile by hand.
Activity