Repository navigation
Description
Summary
I found two related cancellation problems in the native Session Log lifecycle:
- Cancelling
SessionRecorder.flush()can interrupt the thread executing journal storage operations. - If that flush is protected from cancellation, cancelling initialization before
ReActAgent.acquireCallExecution()emits its resource can leave the recorder's writer lease held.
These observations come from deterministic tests using an in-memory Session Log and mocked storage boundaries. No external database or model provider is required.
The second problem is conditional on storage completing without interruption. I am not claiming that every interrupted flush leaks its writer lease.
Relevant implementation
SessionRecorder.flush() currently schedules storage work as follows:
public Mono<Void> flush() {
return Mono.<Void>fromRunnable(this::flushNow)
.subscribeOn(Schedulers.boundedElastic());
}Disposing the subscription can therefore interrupt the worker while flushNow() is executing log.renew(...) or log.commit(...).
For an interruptible storage backend, this may abort I/O while its outcome is still uncertain. Automatically retrying such a commit would not necessarily be safe.
Reproduction 1: cancelling flush interrupts storage work
The following JUnit/Mockito test uses the real in-memory journal and blocks its renew operation:
var store = new InMemorySessionLogStore();
var context = RuntimeContext.builder()
.userId("user-a")
.sessionId("session")
.build();
var log = spy(store.open(
new SessionKey("user-a", "agent", "session"), context));
var entered = new CountDownLatch(1);
var resume = new CountDownLatch(1);
var completed = new CountDownLatch(1);
var interrupted = new AtomicBoolean();
doAnswer(call -> {
entered.countDown();
try {
if (!resume.await(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("test timeout");
}
return call.callRealMethod();
} catch (InterruptedException error) {
interrupted.set(true);
throw new IllegalStateException(error);
} finally {
completed.countDown();
}
}).when(log).renew(any(), any());
var recorder = new SessionRecorder(log, "turn");
try {
var subscription = recorder.flush().subscribe();
assertTrue(entered.await(2, TimeUnit.SECONDS));
subscription.dispose();
resume.countDown();
assertTrue(completed.await(2, TimeUnit.SECONDS));
assertFalse(
interrupted.get(),
"Observer cancellation interrupted storage work");
} finally {
resume.countDown();
recorder.close();
}Actual: the final assertion fails because the storage thread was interrupted.
Expected: cancelling the observer should not interrupt a storage operation that has already started. The lifecycle should still handle its eventual success or failure.
Reproduction 2: initialization cancellation can retain the writer
Protecting the scheduled flush from downstream cancellation, for example with a per-operation cache(), makes the first regression pass:
public Mono<Void> flush() {
return Mono.<Void>fromRunnable(this::flushNow)
.subscribeOn(Schedulers.boundedElastic())
.cache();
}However, protecting the flush alone exposes another cleanup gap.
Steps:
- Build a
ReActAgentwith an in-memory Session Log and a mocked model. - Block the first journal
commit()using latches while initialization persists its initial events. - Cancel the call subscription before
acquireCallExecution()emits itsCallExecution. - Allow the already-started commit to finish.
- Assert that:
- the recorder releases its writer lease;
- another writer can acquire the same session;
- the model was never invoked.
Actual with flush protection alone: the writer-release assertion fails.
The recorder is acquired before this initialization chain finishes:
recorder.start(...).thenReturn(scope)The outer execution resource scope has not received scope yet, so it cannot perform its normal cleanup. The initialization chain has error cleanup, but also needs an explicit cancellation cleanup boundary.
doOnDiscard(CallExecution.class, ...) alone did not cover this case in the regression test.
Expected behavior
- Already-started journal storage operations should reach a definite outcome without being interrupted by observer cancellation.
- Initialization cancellation must release an acquired recorder even before ownership transfers to the main execution scope.
- Same-session continuation must respect writer ownership and cleanup ordering.
- Different users and sessions must remain independent.
- Uncertain storage commits and side-effecting tools must not be blindly retried or replayed.
Candidate fix and local verification
A local candidate combines:
- Protecting each scheduled
SessionRecorder.flush()operation from subscriber cancellation. - Adding an inner
Mono.usingWhenresource boundary around recorder initialization/start, including cancellation cleanup before the outer scope receives the resource.
Both deterministic regressions pass after applying both changes.
Additional assertions verify that another user's writer remains usable and that cancelling initialization does not dispatch the model.
This is a local candidate, not a claim that an upstream fix has been merged or released. No PR has been submitted for it.
Related reports
- [Bug]SSE 断连导致本轮会话进度整体丢失:AgentState 仅在 call() 正常结束时落盘一次,所有 cancel 路径均无保存钩子 #3237 / fix(core): persist agent state after call cancellation #3259: cancellation persistence and same-session cleanup ordering.
- [Bug]:streamEvents cancellation does not guarantee AgentState checkpoint for resumable sessions #1997: state checkpoint guarantees after stream cancellation.
Those reports are related, but this issue focuses specifically on native journal I/O cancellation and recorder ownership during initialization, rather than only the legacy final AgentStateStore snapshot path.
Activity
aiyili commentedon Oct 28, 2026
Hi, I'd like to work on this. The deterministic repro (in-memory Session Log + mocked storage) makes this very tractable. Plan per the report: (1) make
SessionRecorder.flush()cancellation-safe — storage work runs onMono.fromCallablewithout interrupt-driven cancellation (or wrapflushNowso interrupts duringrenew/commitare deferred to a cooperative check rather than propagating mid-I/O); (2) release the writer lease on cancellation of the initialization path beforeacquireCallExecutionemits, so an abandoned acquire can't hold the lease. Tests reproducing both deterministically per your methodology. PR coming shortly.wahllllll commentedon Oct 31, 2026
Confirmed the first problem on current
mainand fixed it in #3888.SessionRecorder.flush()(line 249) is exactly the shape you described:flushNow()renews the writer lease and then commits. Reactor'sboundedElasticschedules onto aScheduledThreadPoolExecutor, and disposing the subscription cancels the task with interruption, so the interrupt lands insidereneworcommit. Your framing of the consequence is the part that matters: the durable outcome becomes unknown rather than merely missing, which is why a blind retry is not an acceptable repair.finish()had the same shape forclose()on both its success andonErrorResumepaths, so a cancellation could interruptlog.release(writer)as well.#3888 submits the storage work so that only the signal can be cancelled: the runnable always runs to completion, and the returned
Monostill reports completion, failure or cancellation to the subscriber.flush()and bothclose()sites use it.The regression test blocks
renew()on a latch, disposes the flush subscription while the journal call is in flight, and asserts the worker was not interrupted and that the queued event still committed. Onmainit fails withdisposing flush interrupted the thread executing journal I/O ==> expected: <false> but was: <true>.I did not touch your second observation — a cancelled initialization can leave the writer lease held. Your own caveat ("conditional on storage completing without interruption") is the reason I left it out: with the flush no longer interruptible, the remaining question is purely about when
close()is guaranteed to run, and answering it properly means deciding the lifecycle contract rather than patching one path. I would rather see that discussed than bundled here.aiyili commentedon Oct 31, 2026
Withdrawing my claim — your fix is better than what I had sketched, and it's already done.
Two things I want to acknowledge specifically:
The "signal-only cancellation" shape is the right abstraction. My sketch (wrapping
flushNowwith a cooperative interrupt check) would have still allowed a narrow window where the interrupt lands between the check and the I/O call. Substituting the storage work so the runnable always completes and only the reactive signal propagates cancellation is cleaner and provably safe — no window at all.Finding the same shape in
finish()'s both close() paths is the part I'd missed entirely; I'd only traced theflush()path from the report. Extending the fix there preempts the same failure on the teardown route.The regression test methodology (latch-blocked renew + dispose mid-flight + asserting no interrupt and durable commit) is exactly the deterministic style the report used — good to see it pinning the fix.
Agreed on deferring the second problem. With flush no longer interruptible, the lease-on-cancelled-init question collapses to "when is close() guaranteed to run," which is a lifecycle contract call, not a patch. That deserves its own discussion with a decision on the contract first.
fix(core): keep journal writes running when a flush subscription is c…
juruoO-o commentedon Nov 12, 2026
Status update: #3888 (merged) addresses the first problem here — journal writes keep running when a flush subscription is cancelled. The initialization writer cleanup gap remains open.