Repository navigation
fix(core): persist agent state after call cancellation - #3259
xihongshichaojidan8 wants to merge 6 commits into
Conversation
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Fixes #3237: a cancelled ReActAgent call can now persist its per-session AgentState through a best-effort asynchronous terminal write, with the same-session gate and the graceful-shutdown registration held until that cleanup finishes. The design is sound — Mono.cache() on scope.terminalSave so cancellation joins an in-flight write instead of racing a second CAS, the saveLock/scope monitors never nested in conflicting order, the cancelled-path deep copy so tool reconciliation never mutates live state, ASKING left untouched while PENDING/ALLOWED get error results, and slotVersions correctly handled inside persistAgentStateCas. CI is green on 787e5555 and the 773-line regression test covers both shutdown/save race orders.
Findings
- [Warning]
ReActAgent.java:493—.cache()memoizes a failed terminal write; two in-call follow-up save sites (saveStateAfterCallFailure->saveStateToSession,handleInterrupt) can no longer retry, because only the native structured-output fallback resetsscope.terminalSave. - [Warning]
ReActAgent.java:543— a shutdown checkpoint that joins an in-flight write persists neither the post-snapshot mutations norshutdownInterrupted, which conflicts with the documented "always save because memory may have been updated" contract ofsaveOnInterruptObserved. - [Warning]
ReActAgent.java:566— unboundedterminal.block()is reached from the single-threadedagentscope-shutdown-monitorviaenforceTimeoutAndInterrupt(); one hung store write stalls the whole force-interrupt/checkpoint pass and suppresses the watchdog tick. - [Warning]
AgentBase.java:381— the newafterAgentCancellationcontract says "offload blocking work", but the counterpartshutdownStateSaverForCallperforms unbounded blocking I/O on whichever thread invokes the saver (including the shutdown monitor) and is nowhere documented as such. - [Info]
AgentBase.java:423— theusingWhencancel path is the right fix for the overtake problem; the Javadoc should also state that a cancelled call now waits on its predecessor, and that cleanup must terminate within bounded time.
Suggestions
The four warnings are narrow, mechanical changes rather than redesigns. For the two highest-value ones:
// 1) do not cache failures on the shared terminal write
.cacheInvalidateIf(sig -> {
synchronized (scope) { scope.terminalSave = null; }
return true; // error/terminate -> next participant retries
})
// 2) keep the shutdown watchdog responsive
try {
terminal.block(shutdownBudgetRemaining());
} catch (IllegalStateException timeout) {
log.warn("Shutdown checkpoint timed out joining terminal save (slot={})", scope.slotKey);
}Overall: correct root-cause fix with unusually thorough regression coverage for a concurrency change. I would resolve the cached-failure behaviour (#493) and bound the blocking joins (#535/#566) before merge; the rest is documentation and follow-up polish. CLA is signed and the working tree is mergeable.
Automated review by github-manager-bot
| // cancellation cleanup joins that same write instead of racing a second CAS. | ||
| scope.terminalSave = | ||
| Mono.<Void>fromRunnable( | ||
| () -> { |
There was a problem hiding this comment.
.cache() makes the terminal write remember its error forever, but several callers within the same CallExecution invoke saveStateToSession(scope) more than once. In particular .onErrorResume(error -> saveStateAfterCallFailure(scope, error)) (line 1231) is followed by .flatMap(result -> saveStateToSession(scope)...) (line 1232) and more at 1236, and handleInterrupt (line 4334) also calls it. Before this change every call issued a fresh write attempt; now a failed save is memoized on scope.terminalSave and every later participant in the same call silently receives the same cached error (or, worse, the cached completion of a write that did not land) instead of retrying. Only the native structured-output fallback clears the field (line 1446). Suggested: invalidate on failure, e.g. .cacheInvalidateIf Signals.error -> { synchronized (scope) { scope.terminalSave = null; } }), or explicitly reset scope.terminalSave = null in the saveStateAfterCallFailure / handleInterrupt error branches so a subsequent save in the same call can retry.
| terminal = scope.terminalSave; | ||
| } | ||
| if (terminal == null) { | ||
| state.setShutdownInterrupted(true); |
There was a problem hiding this comment.
When a shutdown checkpoint joins an in-flight terminal write it neither writes the live state nor sets shutdownInterrupted, so the persisted snapshot is the one taken before terminalSave was created. Any context mutation that happened after that point — most importantly the reconcileCancelledTools(...) results, but also tool rounds appended by a still-running iteration — is lost, and the operator-facing shutdownInterrupted flag is never persisted for this session at all, even though the checkpoint ran. GracefulShutdownManager.saveOnInterruptObserved is documented as "always save because memory may have been updated after the previous save", so the join path arguably violates that contract. Could the join path re-check after terminal.block() returns whether the live scope.state still differs from what was written (or at least record a pending shutdownInterrupted flag that the terminal writer applies before serialising)?
| return; | ||
| } | ||
| } | ||
| terminal.block(); |
There was a problem hiding this comment.
Both terminal.block() calls (line 535 and here) are unbounded, and saveState() reaches them from two threads that must not stall: handleInterrupt (via saveOnInterruptObserved, on the call's reactive thread) and, more critically, enforceTimeoutAndInterrupt(), which runs on the shared single-threaded agentscope-shutdown-monitor (new ScheduledThreadPoolExecutor(1) in GracefulShutdownManager) and loops over all active requests. If one session's store I/O hangs, block() never returns, so the force-interrupt/checkpoint pass is stuck on the first request: the remaining sessions are never checkpointed or interrupted, and because scheduleAtFixedRate suppresses further runs on a late task the whole shutdown watchdog stops ticking. Suggested: bound each wait with the remaining shutdown budget (e.g. terminal.block(remaining.orElse(Duration.ofSeconds(x))), catching IllegalStateException on timeout) and/or fan the per-request checkpoints out to a separate executor so one slow writer cannot block the monitor thread for everyone.
| } | ||
|
|
||
| /** Optional per-call override of the agent's registered shutdown state saver. */ | ||
| protected ShutdownStateSaver shutdownStateSaverForCall(Object scope) { |
There was a problem hiding this comment.
The Javadoc here requires implementations to "offload blocking work and handle cleanup failures without throwing", but the default shutdownStateSaverForCall contract (line 381 area) has the opposite effect for the only producer that matters: the saver returned by ReActAgent.shutdownStateSaverForCall performs unbounded terminal.block() and a synchronous stateStore.saveIfVersion(...) directly on the caller's thread, and AgentBase.runLifecycle hands that caller thread over to GracefulShutdownManager / handleInterrupt. So a subclass that behaves correctly per this contract (the cancellation publisher) can still be blocked by an external checkpoint arriving on the saver. Worth aligning the two contracts explicitly — e.g. state in ShutdownStateSaver#save Javadoc that it may be called on a shared shutdown thread and must return within a bounded time — otherwise the two hooks give contradictory guidance to implementers.
| }); | ||
| return Mono.usingWhen( | ||
| Mono.just(Boolean.TRUE), | ||
| ignored -> prev[0].onErrorComplete().then(action), |
There was a problem hiding this comment.
Nit / docs: the cancel path now chains prev[0].onErrorComplete() before cancelCleanup and releaseGate, which is exactly what prevents a cancelled waiter from letting later same-key calls overtake an active writer — nice. Two small things worth spelling out in the Javadoc, since they are new observable behaviour for subclasses: (1) a cancelled call can hold the same-key gate for as long as its predecessor takes to terminate, so a hung predecessor now blocks the queue for cancellations too (previously release was immediate); (2) afterAgentCancellation is invoked from a Reactor cancellation signal, so an implementation that throws or never terminates will wedge the gate permanently — the existing note about offloading blocking work is good, maybe add "and must terminate within a bounded time". onErrorComplete() already guards the throwing case, so this is only about documenting the contract.
|
Thanks for the careful review. I pushed 6f3278a to address the actionable findings:
On the join-versus-second-write concern: cancellation snapshots are built under saveLock after cancellation propagation, and PENDING/ALLOWED tool calls are reconciled before persistence. An additional live-state write could overwrite that reconciled snapshot. The existing shutdownCheckpointJoinsActiveCancellationSave test asserts the intended single-write behavior; I have not found a concrete post-snapshot mutation path, so I did not add a second write. Happy to revisit if there is a specific interleaving to test. Locally, |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of the new commit 6f3278a8 ("retry failed cancellation saves and isolate shutdown checkpoints"). All five findings from the 787e5555 review were addressed, and the fixes are the right ones: the doOnError invalidation makes the shared terminal write retryable instead of memoizing its failure, afterAgentCancellation gets one real retry, the shutdown saver no longer claims shutdownInterrupted on a state it only joins, joinTerminalSaveForShutdown puts a bound on the join, and the checkpoint is off the single agentscope-shutdown-monitor thread so one stalled store write can no longer suppress force-interrupt for every other request. The new blockedCheckpointDoesNotStallMonitor and cancellationRetriesFailedInFlightTerminalSave tests cover exactly the two behaviours that changed. MERGEABLE, CI re-running on the new head, CLA signed.
Findings
- [Warning]
GracefulShutdownManager.java:327—lifecycleEpochis sampled outside theterminationLockblock that reserved the slot, andresetForTesting()bumps it without that lock; losing that race leavespendingCheckpointsnegative, which permanently disables theSHUTTING_DOWN -> TERMINATEDtransition for the process. - [Warning]
GracefulShutdownManager.java:331— checkpoints are scheduled on the sameSchedulers.boundedElastic()that must run the write they block on, so a shutdown with more active requests than pool workers degrades into every checkpoint timing out without persisting. - [Info]
ReActAgent.java:591/ActiveRequestContext.java:105— a join timeout is logged identically to a save failure, and the once-per-request checkpoint means "interrupted but never persisted" has no signal beyond that ambiguous WARN.
Inline comments carry the details and the suggested fixes.
Suggestions
The two warnings are both small: capture epoch inside the existing synchronized (terminationLock) block (and take that lock in resetForTesting()), and give the checkpoint path its own executor rather than reusing boundedElastic(). Neither changes the design, and the second one matters most in exactly the deployment this PR targets — many concurrent sessions shutting down against a slow store.
Overall: the response to the previous round is complete and well tested. Resolve or explicitly accept the two warnings above and this is good to go from a review standpoint.
Automated review by github-manager-bot
| } | ||
| } | ||
| if (checkpoint) { | ||
| long epoch = lifecycleEpoch.get(); |
There was a problem hiding this comment.
[Warning] The epoch is sampled outside the synchronized (terminationLock) block that reserved the slot. If resetForTesting() (which does lifecycleEpoch.incrementAndGet(); pendingCheckpoints.set(0); without taking terminationLock) runs between the increment at line 323 and this read, the task captures the new epoch while its own increment was wiped, so finishCheckpoint decrements a counter that is already 0 -> pendingCheckpoints goes to -1. updateTerminatedIfNoRequests() then requires pendingCheckpoints.get() == 0, so SHUTTING_DOWN -> TERMINATED never fires again and awaitTermination() always times out for every later lifecycle too (the negative value is never repaired except by another reset). Fix: read epoch inside the same lock that increments, and make resetForTesting() mutate lifecycleEpoch/pendingCheckpoints under terminationLock; defensively pendingCheckpoints.updateAndGet(v -> v > 0 ? v - 1 : 0).
| try { | ||
| Schedulers.boundedElastic() | ||
| .schedule( | ||
| () -> { |
There was a problem hiding this comment.
[Warning] Moving the checkpoint off the monitor is the right call, but Schedulers.boundedElastic() is the same pool the awaited write runs on: saveStateToSession does .subscribeOn(Schedulers.boundedElastic()), and joinTerminalSaveForShutdown now blocks one of its workers until that write terminates. boundedElastic's worker count is capped (default 10x CPU) with a queue behind it, so a shutdown with more active requests than workers can put every worker into a join while the writes they are waiting for are still queued — the pathological case self-heals only because the join is bounded, but it degrades into "no request actually gets its checkpoint written, all of them time out". A dedicated executor for checkpoints (sized by the active-request count, or Schedulers.newBoundedElastic(...) created by the manager and shut down with it) keeps the join off the pool that has to make the write progress.
| } else { | ||
| // cache() keeps the write running after this wait expires. The request's normal | ||
| // cancellation cleanup still joins that write before its session gate is released. | ||
| terminal.block(timeout); |
There was a problem hiding this comment.
[Info] A join that expires surfaces as IllegalStateException("Timeout on blocking read…"), which ActiveRequestContext.saveState() swallows into log.warn("Failed to save agent state for request {}", ...). The wording reports a persistence failure for a write that is still running and may well succeed right after; an operator grepping for shutdown state loss cannot tell the two apart. Catching IllegalStateException here (or returning a boolean from joinTerminalSaveForShutdown) and logging "join timed out, in-flight terminal write continues" keeps the two outcomes distinguishable.
| protected Mono<Void> afterAgentCancellation(Object callScope) { | ||
| CallExecution scope = (CallExecution) callScope; | ||
| return Mono.defer(() -> saveStateToSession(scope, true)) | ||
| .onErrorResume(error -> saveStateToSession(scope, true)) |
There was a problem hiding this comment.
[Info] The retry works because the doOnError at line 528 clears scope.terminalSave before the cached error reaches this operator, so the second saveStateToSession builds a new write instead of returning the failed cached mono. That ordering is load-bearing and easy to break from the other side — a doOnError moved below .cache(), or a retry added on a path that grabbed terminal earlier, silently degrades this into a no-op that replays the same error. Worth one sentence in the saveStateToSession javadoc stating that the invalidation must stay upstream of cache().
| } | ||
|
|
||
| boolean startTimeoutCheckpoint() { | ||
| return timeoutCheckpointStarted.compareAndSet(false, true); |
There was a problem hiding this comment.
[Info] startTimeoutCheckpoint() makes the timeout checkpoint once-per-request, which is the correct fix for the old every-tick re-save. It also means a checkpoint that loses the startTimeoutCheckpoint() race for a retried call is never attempted again even though the request is still active and unsaved. Since the monitor ticks at 1s and a force-interrupt is typically followed by the call's own cancellation save, that is almost always covered — but the only signal that a request ended up with neither is the WARN from saveState(). If a bounded re-attempt is not wanted, a debug counter would at least make the "interrupted, checkpoint once, never persisted" case measurable.
When a terminal save already owns a call state, let that save finish under the existing request lifecycle instead of joining or duplicating it from the shutdown checkpoint. Keep the original synchronous checkpoint path when no terminal save exists, and skip saver binding when no state store is configured. Cover both save orderings and another active request during shutdown.
|
Thanks for the re-review. I pushed a01a7d8 and simplified the shutdown path. The async checkpoint scheduling, shared boundedElastic checkpoint workers, pendingCheckpoints, and lifecycleEpoch are gone, so the two warnings on the previous head no longer apply. My earlier comment describing that scheduling is superseded by this commit. When a terminal save is already registered, the checkpoint defers to it without a duplicate write; the request stays tracked until cancellation cleanup finishes. When no terminal save exists, the checkpoint follows the original synchronous save path. That path can still wait for storage or the save lock, so I am not claiming the shutdown monitor is universally non-blocking. I also fixed the no-stateStore case so it does not bind a per-call saver. The regression tests now use a second request that was active before shutdown, and cover both terminal-save-first and checkpoint-first ordering. On the final commit, the full agentscope-core suite passes: 2,425 tests, 0 failures, 0 errors, 9 skipped; Spotless passes too. The PR description now reflects this narrower behavior and scope. |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of a01a7d8b (the single commit after my 6f3278a8 review). Mostly a deletion, and it clears both things I raised last round: with joinTerminalSaveForShutdown gone there is no unbounded block() on the checkpoint path and no boundedElastic worker occupied by a join, which is also what makes dropping the pendingCheckpoints / lifecycleEpoch barrier self-consistent - there is nothing left for the barrier to wait for, so removing blockedCheckpointDoesNotStallMonitor alongside it is coherent rather than careless. stateStore == null short-circuiting the saver fixes a real nonsense-flag bug, and shutdownTimeoutProcessesAnotherRequestDuringCancellationSave is a better test than the one it replaces.
What is left is about the lock this commit keeps rather than the ones it deletes. saveLock is new in this PR, it is held across blocking store I/O, and its nesting against the scope monitor is asserted nowhere.
Findings
- [Warning]
ReActAgent.java:553- the checkpoint's store write runs insidescope.saveLock, the same lock the terminal write holds acrosspersistAgentStateCas; a slow checkpoint now delays that request's own cancellation cleanup, unregister and gate release. - [Warning]
ReActAgent.java:554- the file's onlysaveLock -> scopenesting; no cycle exists today, but the intended order is implicit and the opposite order is a one-line edit away. - [Info]
ReActAgent.java:539- the no-store behaviour relies onbindStateSaver(line 361) staying guarded by the same condition; cross-reference it. - [Info]
ReActAgent.java:549- "registered until the terminal write completes" is now the only guard keepingTERMINATEDahead of an in-flight write; promote it to theAgentBasecontract. - [Info]
ReActAgentCancellationPersistenceTest.java:160- wall-clock negative assertion on a windows runner.
CLA / CI
CLA license/cla: signed. CI on a01a7d8b: green (build ubuntu + windows, Check License, Check Module Sync, codecov/patch). Comment, not request-changes: both Warnings are about documenting or de-risking a lock this PR introduces, not about behaviour that is wrong today, and the author has addressed three rounds of findings promptly.
Automated review by github-manager-bot
| if (terminal != null) { | ||
| return; | ||
| } | ||
| synchronized (scope.saveLock) { |
There was a problem hiding this comment.
[Warning] This is the line where the new saveLock starts doing real damage: the store call below it runs inside the lock, and saveLock is new in this PR (it does not exist on main). On main the timeout checkpoint and the terminal write could interleave freely - two unserialised saveIfVersion calls racing on the same expected version, which is exactly the bug saveLock fixes. The cost of fixing it this way is that they are now serialised across blocking I/O: the terminal write's persistAgentStateCas(...) body takes the same lock (line ~500), so a checkpoint that merely takes its time on the shutdown monitor thread now delays that request's own terminal write, and that write is what afterAgentCancellation chains - i.e. what eventually unregisters the request and releases the same-key session gate. A wedged store therefore converts a slow checkpoint into a stalled call lifecycle for that slot, which is a stronger statement than the field javadoc's "serializes forced-shutdown checkpoints with the terminal write".
The mechanism is right, so I am not asking for a different design. Two options, either is enough: (a) say in the saveLock javadoc that it is held across store I/O and name the two contending paths, so the next reader knows a checkpoint can gate a call's cleanup; or (b) make the checkpoint opportunistic - tryLock with a short wait, skip with a log.warn on failure - since a checkpoint that has to queue behind the terminal write is redundant by definition (the branch at line 549 already returns when a terminal write exists).
| return; | ||
| } | ||
| synchronized (scope.saveLock) { | ||
| synchronized (scope) { |
There was a problem hiding this comment.
[Warning] saveLock -> scope nesting, and the only such nesting in the file. Every other site (saveStateToSession at line ~481, the doOnError reset, the native-fallback clear at line ~1460) takes scope alone and releases it before the save body runs on boundedElastic, so there is no live cycle today - the reverse order exists only as a potential edge, because saveLock is a field of the same object whose monitor is being nested inside it. That makes this a maintenance hazard rather than a bug: acquiring saveLock while holding scope is the natural thing for the next person to write inside saveStateToSession (both are in scope there), and it would deadlock against this line on the shutdown path, where no test will catch it promptly. Either flip this block to read scope.terminalSave in a separate short synchronized (scope) before taking saveLock (the double-check is what the inner read is for; it can be restructured into a flag), or declare the intended order once at the saveLock field - scope may be taken under saveLock, never the other way - so the invariant is written down instead of emergent.
|
|
||
| @Override | ||
| protected ShutdownStateSaver shutdownStateSaverForCall(Object callScope) { | ||
| if (stateStore == null) { |
There was a problem hiding this comment.
[Info] Returning null here means ActiveRequestContext.bindSaver leaves the agent-level binding from registerRequest in place, whose requestScoped is false - and that is precisely the branch of saveState() that still calls state.setShutdownInterrupted(true). So shutdownWithoutStateStoreDoesNotMarkStateForPersistence passes only because bindStateSaver is itself guarded by the same stateStore != null condition at line 361, leaving a store-less agent with no binding at all. A one-line note here ("relies on bindStateSaver at line 361 being guarded by the same condition") keeps a future unconditional bindStateSaver from silently reintroducing the flag mutation this test exists to prevent.
| Mono<Void> terminal; | ||
| synchronized (scope) { | ||
| terminal = scope.terminalSave; | ||
| } |
There was a problem hiding this comment.
[Info] Dropping joinTerminalSaveForShutdown removes both concerns from my last round - the unbounded block() on the checkpoint path, and the boundedElastic worker it occupied - and that in turn is what makes deleting pendingCheckpoints / lifecycleEpoch in GracefulShutdownManager self-consistent. What replaces them is an assumption written only in this comment: the request stays registered until the terminal write finishes. AgentBase does unregister after afterAgentCancellation completes, so it holds. But the manager no longer tracks in-flight writes at all, so this is now the only thing standing between TERMINATED (and therefore JVM exit via AgentScopeJvmShutdownHook) and a persistence write that has started but not landed. That belongs on AgentBase.shutdownStateSaverForCall as a requirement on implementers - out-of-tree savers will not read this comment.
| // request that was already active when shutdown began. | ||
| assertTrue(otherSaved.await(3, TimeUnit.SECONDS)); | ||
| assertEquals(1, store.writes.get()); | ||
| assertFalse(manager.awaitTermination(Duration.ofMillis(100))); |
There was a problem hiding this comment.
[Info] assertFalse(manager.awaitTermination(Duration.ofMillis(100))) is a wall-clock negative assertion, and this test runs in build (windows-latest) where a 100 ms window is routinely exceeded by scheduling noise alone. When it fails it reads like a state-loss regression while being pure timing. Prefer a deterministic witness - e.g. have BlockingStore record that the second request's checkpoint entered saveIfVersion and assert on that, or assert getState() == SHUTTING_DOWN - and keep the positive awaitTermination(3s) unchanged. Same shape at GracefulShutdownTest line 247 if it survived here.
|
Thanks for the re-review. I pushed 26f01e9 to document the two lock-related warnings without changing the save ordering: the saveLock contract now says it spans blocking store I/O, can delay cancellation cleanup and same-session gate release, and must be acquired before the CallExecution monitor. I also documented the no-store binding dependency and the per-call saver requirement that cancellation cleanup await an in-flight terminal write before unregistering the request. On the test note: the first store write is held by an explicit latch when the negative awaitTermination(100 ms) assertion runs, so that assertion checks that the request remains registered while persistence is blocked; a slower scheduler alone cannot make it terminate early. I kept the assertion unchanged. This commit changes comments only; Spotless and git diff --check pass. The core suite passed on the preceding implementation commit a01a7d8. |
|
Independent verification on a second state-store backend — data only, no review comments on your code. Setup. Observations.
Why I'm posting this. Your acceptance list mentions converging on a single terminal save that runs after the upstream cancel. Since today's success path already has exactly one pre-terminal write, the save you add for the cancel path would become that turn's only write — worth keeping that ordering strict enough that no Possibly useful for your tests. Good luck with this one — the cancel-path gap bit us the same way it did in #3237. 补充中文摘要(方便 @xihongshichaojidan8 看):在 |
|
@Cshvee Thanks for independently reproducing #3237 on InMemoryAgentStateStore. Our cancellation regression tests also use that store, including a blocked write and a same-session follow-up call. The cancellation cleanup runs asynchronously after upstream cancellation. A subscriber disposing its stream does not by itself mean that the state write has finished; the same agent's next call for that session waits for cleanup before proceeding. An external rollback that writes directly to the store could still race with that save, especially with the default OVERWRITE conflict policy, so I do not want to claim that CAS alone rules it out. Could you share which API performs the restore/rewind, and what event your host treats as stream termination before invoking it? With that ordering, we can check a concrete interleaving and decide whether it belongs in this PR or needs a separate coordination contract. |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of 26f01e9a (docs-only commit after my a01a7d8b review). This closes all three things I raised, and the documentation is accurate — I checked it against both acquisition sites rather than taking it at face value:
saveLockheld across blocking store I/O — now stated explicitly on the field ("A slow checkpoint can delay cancellation cleanup and release of the same-session gate"), which turns an implicit cost into a documented trade-off.- Implicit lock order —
Lock order is saveLock then this CallExecution monitormatches the code: the checkpoint inshutdownStateSaverForCalltakesscope.saveLockand only thenscopefor the double-checkedterminalSaveread, andsaveStateToSessionacquiresscope.saveLockfrom inside thefromRunnablebody, which runs on the subscribe side rather than under thescopemonitor. So no path currently takessaveLockwhile holding the monitor, and the one-line edit that would break it is now named. stateStore == null— the comment correctly points at the constructor's matchingif (this.stateStore != null)guard aroundbindStateSaver, so the two skip paths are tied together.
No code behaviour changed in this commit; CLA signed; Check License / Check Module Sync green, and the build (ubuntu-latest) / build (windows-latest) runs were still in progress on 26f01e9a when I posted this, so treat this approval as covering the diff, not as a CI verdict.
LGTM from my side.
Automated review by github-manager-bot
|
This PR currently conflicts with git fetch origin
git checkout codex/fix-3237-cancel-persistence
git rebase origin/main
# resolve conflicts, then:
git push --force-with-leaseThis is a one-time reminder. Feel free to @mention me for a re-review after the conflicts are resolved. Automated notification by github-manager-bot |
|
感谢运行 CI。Windows 失败发生在 我用受控时序分别在本 PR 和上游 烦请维护者在方便时重新运行 CI,尤其是失败的 Windows 作业和被取消的 Ubuntu 作业。如果相同断言再次失败,我会继续排查测试隔离问题,并保持本 PR 聚焦于取消时的状态持久化。 |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-reviewed at c5a04e46 (new head since my APPROVE on 26f01e9a). The only change on this PR is a merge of upstream main — the PR's own files are untouched by it: git diff 26f01e9a..c5a04e46 produces zero changes for ShutdownStateSaver.java and ReActAgentCancellationPersistenceTest.java, no conflict markers remain in ReActAgent.java, and the PR's cancellation-save path is still intact (saveStateToSession(scope, cancelled) -> deep copy -> reconcileCancelledTools() -> single CAS write, ReActAgent.java:480-533). The logic I approved is unchanged.
I am not re-approving only because CI is red on this head:
| Check | Result |
|---|---|
| build (windows-latest) | failure — LocalFilesystemPersonalAssistantExampleTest.localFilesystem_filesPersistAcrossCalls (MEMORY.md content should be persisted on disk ==> expected: <true> but was: <false>) |
| build (ubuntu-latest) | cancelled at ~7m |
| Check License / Check Module Sync / license/cla | pass |
The harness module compiled and all PR-owned tests passed on Windows in the same run (ReActAgentCancellationPersistenceTest: 19/19, GracefulShutdownTest$ManagerTests: 30/30), and the same example test passes on main at 3c1c29c0. So this looks like either an interaction between this PR's state-persistence change and the just-merged run-isolation work (#3279), or a Windows-only flake in the local-filesystem example.
Actions requested
- Re-run the failed job (or push a no-op update) to confirm whether
localFilesystem_filesPersistAcrossCallsfails reproducibly on this head. If it reproduces, please look at whether the terminal-save path can delay/short-circuit the workspaceMEMORY.mdflush observed by that example. - Confirm the ubuntu job cancellation is not a hang introduced by the new save ordering (it was cancelled, not failed, so a timeout is possible).
Nothing in the code needs changing for the reasons above — this comment is to keep the CI signal attached to the head it belongs to. Once both builds are green this is good to go from my side.
Automated review by github-manager-bot
|
@xihongshichaojidan8 answering both questions directly. 1. Which API performs the restore / rewindAlways a versioned CAS write: We never use
Before either branch, an ownership gate compares the head version against the version our own turn wrote. If the head is not provably ours we refuse to rewind and rotate the session epoch instead — we would rather take a fresh context generation than overwrite another writer's state. Our 2. What we treat as "stream terminated" before invoking itReactor We do not read that signal as proof that the framework's own write has finished, and that is exactly your concern. Two consequences:
Why this PR changes the picture for us#3259 adds precisely the write we are avoiding: a cancelled call now persists The property a host doing its own rollback needs is one of:
So the concrete question for you: is the post-snapshot window already closed by (1) on the current head, or is it only safe once a caller opts into If useful, I can share the reproducer behind yesterday's two observations: a delegating |
|
@Cshvee 感谢把回滚 API 和触发时序说明清楚。我在当前 PR 提交 这个实验只覆盖“宿主先写、框架后写”的顺序,没有复刻你们的所有权检查和存储装饰器。框架的同会话队列保证后续 AgentScope 调用等待取消清理,但不约束宿主直接调用 我已在本 PR 描述中说明这个边界。#3263 正在为 |
Review follow-up (
|
| Check | Result |
|---|---|
| build (windows-latest) | failure (6m50s) — LocalFilesystemPersonalAssistantExampleTest.localFilesystem_filesPersistAcrossCalls:103, MEMORY.md content should be persisted on disk ==> expected: <true> but was: <false> |
| build (ubuntu-latest) | failure (7m7s) — no failed-log output retrievable for this job |
| Check License / Check Module Sync / license/cla | pass |
This is the same failure I reported in the previous round, so it now reproduces across at least two runs rather than looking like a one-off flake. Since the same example passes on main, the likeliest culprits are an interaction with the run-isolation work merged in #3279 or a Windows-only timing/flush ordering issue in the local-filesystem example, rather than anything in the PR-owned tests (which passed on Windows in the same run).
Actions requested
- Rebase / merge the current
maininto this branch and push, so the two builds are re-run against an up-to-date base — that also tells us whether fix(runtime): isolate contexts and control individual agent runs #3279 or a later fix already made the Windows example green. - If the Windows example still fails after the rebase, please take a look at whether the terminal-save path can delay the workspace
MEMORY.mdflush that the example asserts on; if it fails identically on a plainmain-only run too, it belongs upstream and a maintainer can decide whether to quarantine/fix the example separately.
I am deliberately leaving this as a comment instead of an approval until the builds are green on the head they belong to. Nothing else in the code needs changing for that — ping me after the rebase and I will re-review.
Automated review by github-manager-bot
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review on head ae30ac6d. The only commit added since my previous review is an upstream merge — the six files in the diff are byte-identical to the state I already went through over the last three rounds, so this comment does not restate that feedback. The 4 items below are new points that only became clear once the design settled into its current shape.
Two things that are worth recording for maintainers:
- The reported mechanism is fixed correctly. Terminal state is now written on cancellation, unfinished
PENDING/ALLOWEDtool calls get synthesized error results,ASKINGcalls are left alone, and the unboundedblock()on the shutdown checkpoint path that my earlier round flagged is gone.+868lines of regression tests inReActAgentCancellationPersistenceTestcover the blocked-write and same-session follow-up cases. CI (linux + windows build) is green, CLA is signed. - The declared limitation is the default policy, not an edge case. With
ConflictPolicy.OVERWRITE— which is the default atReActAgentconstruction and whatHarnessAgentdid not expose until #3263 — the cancellation write that loses a CAS deliberately falls through to an unconditionalsaveIfVersion(..., UNVERSIONED). So the "host rollback can be overwritten by cancellation cleanup" behaviour discussed in #3259 is a guaranteed outcome under default configuration rather than a rare race. The PR body already says this, which is honest; the question for maintainers is whether a write on a cancelled, stale execution should be allowed to clobber a versioned write that a host performed intentionally. My suggestion would be to make the cancellation-path write respectFAIL/APPEND_MERGEeven when the builder default isOVERWRITE, or to document explicitly that hosts performing state rollback must not run concurrent cancelled calls on the same slot.
Overall: the fix is sound and I would not hold it for the items above; the concurrency semantics are a design follow-up rather than a regression introduced here.
Automated review by github-manager-bot
| protected Mono<Void> afterAgentCancellation(Object callScope) { | ||
| CallExecution scope = (CallExecution) callScope; | ||
| return Mono.defer(() -> saveStateToSession(scope, true)) | ||
| .onErrorResume(error -> saveStateToSession(scope, true)) |
There was a problem hiding this comment.
[Warning] The cancellation retry only works because saveStateToSession(scope, true) returns the cached terminalSave on the retry (line 486) and the doOnError hook clears that field before the cached error reaches this operator. That is a load-bearing, undocumented ordering contract between three places (the synchronized (scope) guard, the doOnError reset, and this onErrorResume): if the reset is ever moved after the error is propagated, or the clear becomes conditional on identity in a way that no longer matches, every retry silently replays the cached failure and cancellation persistence degrades to a no-op — the exact symptom #3237 reports. Suggest an explicit retryWhen(...) on a freshly built Mono (or a dedicated saveStateForCancellation() that bypasses the cache) plus a comment naming the invariant, and a regression test that asserts the second attempt re-reads the live state.
| * Lock order is saveLock then this CallExecution monitor; never acquire saveLock while | ||
| * holding the CallExecution monitor. | ||
| */ | ||
| final Object saveLock = new Object(); |
There was a problem hiding this comment.
[Warning] saveLock now serialises cancellation cleanup and shutdown checkpoints behind blocking store I/O held inside the lock (the CAS call at line ~503 runs while saveLock is owned). As documented in the Javadoc here, a slow store can therefore delay cancellation cleanup and the release of the same-session gate. The comment also states the lock order as saveLock -> CallExecution monitor, but saveStateToSession reaches the runnable from synchronized (scope) (line 485), and shutdownStateSaverForCall deliberately takes saveLock and then re-acquires scope (line ~554) to re-check terminalSave, so the direction is not uniform across call sites. Worth a note in the PR description for maintainers who own the distributed-session invariants, and, longer term, a per-slot write queue instead of a monitor spanning I/O. Not a blocker for this fix — the previous unbounded block() on the checkpoint path is gone, which was the more serious issue.
| synchronized (scope.saveLock) { | ||
| AgentState toSave = | ||
| cancelled | ||
| ? AgentState.fromJsonString( |
There was a problem hiding this comment.
[Info] AgentState.fromJsonString(scope.state.toJson()) is a full JSON round-trip of the whole conversation on the cancellation path. For long-running sessions this is the most expensive moment to deep-copy the largest object the framework owns, and it happens on boundedElastic while saveLock is held. If the goal is only to freeze a snapshot so reconcileCancelledTools cannot race with the still-unwinding call, a cheaper copy (or appending the synthesized tool_result messages under the same synchronized (scope) guard that produces terminalSave) would avoid the serialization cost. Fine to leave as is if a copy-constructor alternative was already rejected for good reason.
| int loadedContextSize; | ||
|
|
||
| /** Shared terminal write, including cancellation while a normal save is in flight. */ | ||
| Mono<Void> terminalSave; |
There was a problem hiding this comment.
[Info] terminalSave is a non-volatile field read/written from the reactive paths and from the shutdown thread; it is only safe because every access happens under the CallExecution monitor. Consider making that explicit in the Javadoc ("guarded by synchronized (this)"), or making it volatile if any future read is expected outside the monitor — field-level documentation is the only thing keeping the next contributor from reading it lock-free.
|
@jujn 这个请问近期考虑合并吗 |
AgentScope-Java Version
2.0.4-SNAPSHOT (current main)
Description
Fixes #3237.
When a streaming ReActAgent call is cancelled, such as after an SSE disconnect, its current per-session AgentState may never reach the store. Completed tool progress and an answer supplied after HITL resume can then disappear from the next call.
This PR adds best-effort asynchronous persistence after core call cancellation. Cancellation keeps the same-session execution gate and shutdown request active until cleanup finishes. It snapshots state, adds error results for unfinished PENDING/ALLOWED tool calls, and leaves ASKING calls intact. A failed terminal write is cleared from the shared cache so cancellation cleanup can retry once.
Normal completion and cancellation share one terminal write. A request-scoped shutdown checkpoint uses the same save ordering: when a terminal write is already registered, the checkpoint leaves that write to the active request lifecycle instead of duplicating it or overwriting its reconciled state. Otherwise it uses the existing synchronous checkpoint path. Slow storage or waiting for the save lock can still delay the shutdown monitor; this PR does not claim to make every checkpoint non-blocking. Agents without a state store do not bind a shutdown saver.
The same-session gate does not order direct external
agent_statewrites with asynchronous cancellation cleanup. On a versioned store, a host rollback that wins an earlier CAS can still be overwritten after a conflict by the defaultConflictPolicy.OVERWRITE.ConflictPolicy.FAILprevents that overwrite; cancellation persistence then retries once and logs the failure without signaling the disposed subscriber. Integrations that rewind state directly should coordinate with cleanup or configureFAILand handle their own CAS results.The change is limited to agentscope-core. It does not alter harness middleware persistence or transport-level reconnection.
Verification
a01a7d8b:mvn -pl agentscope-core -am test -q— 2,425 tests, 0 failures, 0 errors, 9 skipped. Commit26f01e9achanges comments only; current headc5a04e46merges upstream main.mvn -pl agentscope-core -am spotless:check -qpassed.Checklist