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

[Bug]: Cancelling native session flush interrupts storage I/O; cancellation-safe flush exposes initialization writer cleanup gap

Open sfgvke opened this issue 1 month ago • 4 comments

Summary

I found two related cancellation problems in the native Session Log lifecycle:

  1. Cancelling SessionRecorder.flush() can interrupt the thread executing journal storage operations.
  2. 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:

  1. Build a ReActAgent with an in-memory Session Log and a mocked model.
  2. Block the first journal commit() using latches while initialization persists its initial events.
  3. Cancel the call subscription before acquireCallExecution() emits its CallExecution.
  4. Allow the already-started commit to finish.
  5. 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:

  1. Protecting each scheduled SessionRecorder.flush() operation from subscriber cancellation.
  2. Adding an inner Mono.usingWhen resource 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

  • #3237 / #3259: cancellation persistence and same-session cleanup ordering.
  • #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.

sfgvke avatar Oct 27 '26 11:10 sfgvke

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 on Mono.fromCallable without interrupt-driven cancellation (or wrap flushNow so interrupts during renew/commit are deferred to a cooperative check rather than propagating mid-I/O); (2) release the writer lease on cancellation of the initialization path before acquireCallExecution emits, so an abandoned acquire can't hold the lease. Tests reproducing both deterministically per your methodology. PR coming shortly.

aiyili avatar Oct 28 '26 12:10 aiyili

Confirmed the first problem on current main and fixed it in #3888.

SessionRecorder.flush() (line 249) is exactly the shape you described:

return Mono.<Void>fromRunnable(this::flushNow).subscribeOn(Schedulers.boundedElastic());

flushNow() renews the writer lease and then commits. Reactor's boundedElastic schedules onto a ScheduledThreadPoolExecutor, and disposing the subscription cancels the task with interruption, so the interrupt lands inside renew or commit. 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 for close() on both its success and onErrorResume paths, so a cancellation could interrupt log.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 Mono still reports completion, failure or cancellation to the subscriber. flush() and both close() 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. On main it fails with disposing 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.

wahllllll avatar Oct 31 '26 13:10 wahllllll

Withdrawing my claim — your fix is better than what I had sketched, and it's already done.

Two things I want to acknowledge specifically:

  1. The "signal-only cancellation" shape is the right abstraction. My sketch (wrapping flushNow with 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.

  2. Finding the same shape in finish()'s both close() paths is the part I'd missed entirely; I'd only traced the flush() 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.

aiyili avatar Oct 31 '26 13:10 aiyili

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.

juruoO-o avatar Nov 12 '26 11:11 juruoO-o