Skip to content

SessionRecorder drops export requests committed during an in-flight drain #3836

Closed

Description

@chcodex

Summary

SessionRecorder.exportCommitted() silently drops an export request when a drain() is already running. Because close() also disposes the 1-second heartbeat, events committed near the end of a run can stay unexported until an external retry (for example, a 60-second scheduled retry), even though they are already durable in the SessionLog.

This was observed after a long run: run/end was committed at 12:51:50.351, but the sink cursor advanced to the final sequence only at 12:52:07.255 (about 17 seconds later). lastExportAttemptAt == updatedAt showed that the final batch was written by the retry path, not by the normal asynchronous export.

Impact

  • SessionExportSink implementations receive the final message/assistant / turn/output / run/end events late.
  • Downstream projections (session history tables, AG-UI attach cursors, external sinks) are stale and can miss the final assistant message.
  • If the process exits before the next retry or trigger, the export stays pending until another commit or an explicit drain.
  • No data loss in SessionLog itself, but exported state is not read-your-writes.

Root cause

agentscope-core/src/main/java/io/agentscope/core/session/SessionRecorder.java:

private void exportCommitted() {
    if (exporter == null) return;
    if (!exporting.compareAndSet(false, true)) return;
    Schedulers.boundedElastic()
            .schedule(
                    () -> {
                        try {
                            exporter.drain();
                        } catch (RuntimeException error) {
                            LOGGER.warn(
                                    "Committed session export pending retry: {}",
                                    error.toString());
                        } finally {
                            exporting.set(false);
                        }
                    });
}

If exportCommitted() is called while exporting == true, it returns without recording that another drain is needed. The heartbeat calls flushNow() + exportCommitted() every second, but close() disposes the heartbeat:

public synchronized void close() {
    if (closed) return;
    closed = true;
    heartbeat.dispose();
    try {
        log.release(writer);
    } catch (RuntimeException e) {
        if (failure == null) throw e;
    }
}

So a final commit that lands during an in-flight drain has no follow-up trigger.

Reproduction

Deterministic unit-level reproduction:

  1. Create a SessionRecorder with a sink whose accept() blocks on the first event.
  2. recordNow() event A; the asynchronous drain starts and blocks in accept(A).
  3. recordNow() event B while the drain is still blocked; exportCommitted() sees exporting == true and returns.
  4. close() the recorder, disposing the heartbeat.
  5. Release the sink; event A is accepted, but B is never accepted by the normal exporter.

A regression test built this way fails on current main and passes with the proposed fix.

Suggested fix

Track a pending export request and drain until no request is left:

private final AtomicBoolean exportRequested = new AtomicBoolean();

private void exportCommitted() {
    if (exporter == null) return;
    exportRequested.set(true);
    if (!exporting.compareAndSet(false, true)) return;
    Schedulers.boundedElastic()
            .schedule(
                    () -> {
                        try {
                            while (exportRequested.compareAndSet(true, false)) {
                                exporter.drain();
                            }
                        } catch (RuntimeException error) {
                            exportRequested.set(false);
                            LOGGER.warn("Committed session export pending retry: {}", error.toString());
                        } finally {
                            exporting.set(false);
                            if (exportRequested.get()) exportCommitted();
                        }
                    });
}

close() should also request a final export before releasing the writer:

closed = true;
heartbeat.dispose();
exportCommitted();
log.release(writer);

Test

Add a test (for example SessionRecorderExportTest) that uses a blocking sink, commits an event during the first drain, closes the recorder, then asserts both events were accepted. The test should fail against current main.

Environment

  • agentscope-java main at a543f993c
  • Java 17
  • JDBC-backed SessionLogStore against a remote MySQL instance; the affected run had ~4,900 session events.

Happy to prepare a PR with the regression test and fix.

Activity

  1. added a commit that references this issue on Oct 28, 2026
    1082ddf
  2. added a commit that references this issue on Oct 29, 2026
    cb156ef
  3. wahllllll commented on Oct 29, 2026

    @wahllllll
    Contributor

    Confirmed and fixed in #3849.

    The drop is exactly as described: exportCommitted() takes exporting with compareAndSet(false, true) and returns when another drain holds it, without recording that another pass is needed. Because close() disposes the heartbeat, the retry that normally covers this is gone at the end of a run.

    Reproduced deterministically without a provider: a sink that blocks inside accept() on the first event, a second message committed while that drain is running, then close(), then releasing the sink. The sink receives [1] and never sees [2], which is the same shape as the run/end at 12:51:50.351 versus the cursor at 12:52:07.255.

    The fix marks the request before taking the flag and lets the drain loop while requests are pending, re-arming in finally for a commit that lands between the last check and clearing the flag. Draining still happens on boundedElastic, never on the committing thread, so the caller-visible latency is unchanged.

    Two questions your report raised that the fix deliberately leaves alone, in case you have a view:

    • close() still does not drain synchronously. With the pending flag a commit that races a running drain is covered, but a commit made strictly after the last drain finished still waits for a caller that eventually drains. Making close() block on a final drain would change its thread and failure semantics, so I did not fold that in.
    • The lastExportAttemptAt == updatedAt diagnostic you used would still be useful to keep; it is what distinguished the retry path from the asynchronous path here.

    If you would rather see close() guarantee a final drain, say so and I will follow up separately.

  4. added a commit that references this issue on Nov 12, 2026
    2ec6ec0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions