Skip to content

fix(harness): avoid blocking stream completion on transcript persistence - #3106

Closed
ningmao-hlyz wants to merge 2 commits into
agentscope-ai:mainfrom
ningmao-hlyz:fix/transcript-async-completion
Closed

ningmao-hlyz wants to merge 2 commits into
agentscope-ai:mainfrom
ningmao-hlyz:fix/transcript-async-completion

Conversation

@ningmao-hlyz

Copy link
Copy Markdown
Contributor

Summary

Fixes #3059.

  • Keep transcript persistence fire-and-forget for regular agent calls.
  • Track pending transcript writes with MemoryBackgroundTasks so shutdown can wait for them.
  • Keep sandbox-backed calls in the stream until transcript persistence finishes.
  • Serialize concurrent transcript appends for the same session.
  • Add regression coverage for stream completion, shutdown quiescence, and sandbox release ordering.

Problem

TranscriptMiddleware used concatWith(...) for transcript persistence. Because the persistence task was part of the sequential stream, downstream subscribers did not receive onComplete until transcript writing finished.

This added user-visible tail latency for streaming callers such as SSE and WebSocket deployments, even after the final assistant event had already been emitted.

Changes

  • Regular calls now schedule transcript persistence from doOnComplete(...) without delaying downstream completion.
  • Pending asynchronous writes are counted by MemoryBackgroundTasks, preserving lifecycle shutdown/quiescence guarantees.
  • The conversation context is copied before the asynchronous task is scheduled.
  • Same-session transcript read/merge/write cycles are serialized across writer instances.
  • Sandbox-backed calls intentionally keep persistence inside the stream so the sandbox is not released before the writer finishes.

MemoryFlushMiddleware and MemoryMaintenanceMiddleware already use tracked fire-and-forget execution and are unchanged by this PR.

Testing

  • mvn -pl agentscope-harness -Dtest=SessionTranscriptWriterTest,TranscriptMiddlewareAsyncTest test
  • mvn -pl agentscope-harness spotless:check

@codecov

codecov Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.07547% with 19 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...harness/agent/middleware/TranscriptMiddleware.java 73.46% 13 Missing ⚠️
.../agent/memory/session/SessionTranscriptWriter.java 89.47% 3 Missing and 3 partials ⚠️

📢 Thoughts on this report? Let us know!

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Fixes #3059 by scheduling transcript persistence from doOnComplete instead of concatWith, keeping sandbox-backed calls in-stream, and serialising same-session read/merge/write behind a ref-counted per-path lock. The direction is right, the fire-and-forget task is correctly tracked by MemoryBackgroundTasks, and the regression tests cover completion ordering, sandbox release ordering and the pre-detach snapshot.

Verdict

No blocking issue found — inline comments are latency/robustness polish plus one doc-accuracy note.


Automated review by github-manager-bot

@ningmao-hlyz
ningmao-hlyz force-pushed the fix/transcript-async-completion branch 2 times, most recently from 105959a to a66780c Compare September 11, 2026 17:58

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Moves non-sandbox transcript persistence off the critical path: TranscriptMiddleware now dispatches the append in doOnComplete as a tracked fire-and-forget MemoryBackgroundTasks task (sandbox calls keep it in-stream so the per-call sandbox stays alive), and SessionTranscriptWriter guards the load → syncFromRemote → flush cycle with a reference-counted per-path lock so concurrent appends for one session can't interleave. The direction is right and the test coverage is genuinely good (onComplete fires before the write finishes, sandbox writes stay in-stream, message snapshot taken before detaching, failure paths don't break the stream). One ordering bug in the new lock protocol and a scope question on the guard are worth fixing before this lands.

Findings

  • [Warning] SessionTranscriptWriter.java:108 — the refcount is dropped before unlock(), so a new caller can publish a second WriteLock for the same path while an append is still in flight; the eviction check runs under the map bin lock, not the write lock.
  • [Warning] SessionTranscriptWriter.java:66 — the lock is process-local while the guarded cycle reaches the remote TranscriptStore; two JVMs on a shared workspace are still unprotected. Please confirm the intended scope and document it.
  • [Warning] TranscriptMiddleware.java:88 — the sandbox branch and the background branch now have different error-discipline; the previous onErrorResume was dropped from appendTranscript.
  • [Info] TranscriptMiddleware.java:84 / :91 — state resolution runs inline on the completing thread; failure logging lost its agent=/session= context.
  • [Info] TranscriptMiddlewareAsyncTest.java:242 — no test pins down the cancel semantics of the doOnComplete-only dispatch.

Suggestions

The lock fix is small — take the eviction decision while still holding the monitor (see the inline comment for a snippet), so users == 0 → remove and users++ → reuse can never overlap with an in-flight append. For the error-discipline item, hoisting the existing onErrorResume lambda into a private static Mono<Void> logFailure(Throwable) and applying it in both branches would keep the two paths from drifting again.

Neither item blocks the design: the change is a clear improvement over blocking stream completion on a disk/remote write, and the added tests exercise exactly the races that matter.


Automated review by github-manager-bot

@oss-maintainer

Copy link
Copy Markdown
Collaborator

Follow-up on CI for the current head (105959a6) — the Linux build is failing, and the failure shape looks related to this change rather than flaky:

[ERROR] AgentSpawnToolPlanModeTest.agentSend_reappliesParentPlanModeBeforeInvokingExistingChild » JUnit Failed to close extension context
Caused by: java.io.IOException: Failed to delete temp directory /tmp/junit-…
  The following paths could not be deleted: <root>, user, user/agents, user/agents/worker/sessions
[ERROR] Tests run: 1048, Failures: 0, Errors: 1, Skipped: 9

https://github.com/agentscope-ai/agentscope-java/actions/runs/34626731278

The leftover path is a session transcript directory under a @TempDir workspace, and the error is DirectoryNotEmptyException during JUnit's extension teardown — i.e. something wrote into the temp workspace after the test body finished. With this PR the non-sandbox transcript append moves to doOnComplete + a detached boundedElastic task, so a @TempDir-based test whose agent stream completes can now have an in-flight write outliving the directory. MemoryBackgroundTasks.awaitQuiescence(...) is already the right tool: awaiting it in the affected test's teardown (or in a shared @AfterEach for harness tests that use @TempDir workspaces) should make the ordering explicit instead of timing-dependent.

Not blocking on this, and if you can show the same test failing on an unrelated head please treat this as a red herring — but it is worth ruling the ordering out before the build is re-run a few times and assumed flaky.


Automated review follow-up by github-manager-bot

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Re-reviewed against the updated head eb67eb22. The lock protocol I flagged last round is now correct: the unlock happens inside WRITE_LOCKS.computeIfPresent, so a new caller can no longer publish a replacement lock for a key whose append has not actually been released, and the waiters are counted before blocking. Class docs now say explicitly that the serialisation is process-local and that cross-process coordination belongs to the TranscriptStore, which is the other thing I asked for. Both earlier warnings are resolved — thanks.

Downgraded to COMMENT (not APPROVE) because the latency point on the snapshot is still open on the exact path this PR exists to optimise, and the cancellation contract is still undocumented. CLA status is unknown for this repo/head (license/cla context not reported), so per my gating rule I'm not approving either way.

Findings

  • [Warning] TranscriptMiddleware.java:132 — state.getContext() deep-copies the whole conversation synchronously on the thread that emits onComplete; this is the tail latency the PR is meant to remove.
  • [Info] TranscriptMiddleware.java:96 — doOnComplete means a cancelled stream persists nothing; either document + test that contract or cover CANCEL.
  • [Info] SessionTranscriptWriter.java:125 — lock fix confirmed; the current != writeLock branch leaves the (already-dead) WriteLock counter undecremented, worth one clarifying comment.

Verification

  • No new imports of Schedulers misuse; MemoryBackgroundTasks.begin() stays on the calling thread so the task is counted before subscribeOn hands off — the pairing with doFinally(end()) plus the catch (RuntimeException) end() is now symmetric, which closes the "uncounted window" note from last round.
  • Sandbox branch still keeps persistence in-stream, and TranscriptMiddlewareAsyncTest still covers that ordering.

Automated review by github-manager-bot

@ningmao-hlyz
ningmao-hlyz force-pushed the fix/transcript-async-completion branch from ab0e0ea to e36a99c Compare September 13, 2026 11:36

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Re-reviewed against the force-pushed head e36a99c0. The lock protocol and the sandbox-vs-background split both read correctly, the process-local scope is now stated in the class javadoc, and the new TranscriptMiddlewareAsyncTest covers the cases raised last round (in-stream sandbox write, shutdown quiescence, snapshot-before-write, failure isolation on both paths). CI is green on ubuntu and windows, and license/cla now reports signed.

Both warnings from the previous round are resolved; downgraded to COMMENT rather than APPROVE only because the snapshot latency point is still open on the exact path this PR exists to optimise.

Findings

  • [Warning] TranscriptMiddleware.java:135 — the full-conversation state.getContext() copy still happens synchronously on the terminal-signal thread inside doOnComplete.
  • [Info] TranscriptMiddleware.java:109 — transcript writes now join the process-wide MemoryBackgroundTasks counter that every HarnessAgent.close() waits on.
  • [Info] SessionTranscriptWriter.java:116 — previous lock-protocol warning confirmed fixed and unchanged by the rebase.

Checklist for approval

  1. Either move the snapshot inside the Mono.defer(...) body, or document why the copy must stay on the stream thread.
  2. Confirm the cancellation contract (persist-or-discard) is the intended product decision for SSE/WebSocket disconnects — the javadoc now states it, which is enough for me.

Automated review by github-manager-bot

Preserve fire-and-forget transcript writes for regular calls while delaying sandbox release until the transcript append completes. Snapshot messages before asynchronous persistence and add regression coverage for the sandbox lifecycle.
@ningmao-hlyz
ningmao-hlyz force-pushed the fix/transcript-async-completion branch from e36a99c to bf1acbb Compare September 13, 2026 13:55

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Re-reviewed the force-pushed head bf1acbb (this work now lands as a single squashed commit). Both items from my previous approval checklist are resolved: the synchronous snapshot is justified in place inside scheduleTranscript rather than left implicit, and the cancellation contract is now stated in the class javadoc ("Cancellation intentionally discards the in-progress turn"). The HarnessAgent.close() reorder — draining MemoryBackgroundTasks before SessionTree.awaitMirrorQuiescence — plus the shared @HarnessQuiescence extension on AgentSpawnToolPlanModeTest is the ordering fix I pointed at on 2026-09-11 for the DirectoryNotEmptyException teardown failure, and it is the right shape: one explicit shared teardown contract instead of per-test timing workarounds.

Findings

No blocking issues. Two non-blocking notes are inline (the process-wide drain cost now paid in close(), and the sandbox vs non-sandbox per-call cost asymmetry this PR makes permanent).

Verification

  • TranscriptMiddlewareAsyncTest and SessionTranscriptWriterTest cover completion ordering, snapshot-before-detach, in-stream sandbox writes, shutdown quiescence and failure isolation on both paths.
  • AgentState.getContext() is Collections.unmodifiableList(new ArrayList<>(context)) — a shallow defensive copy — which confirms keeping the snapshot on the terminal-signal thread is a correctness requirement, not an oversight.
  • The WRITE_LOCKS refcount protocol is unchanged from the previous head and still correct: waiters are counted before blocking, and the unlock happens inside the map mutation, so no caller can publish a replacement lock for a path whose append is still in flight.
  • CI is green on bf1acbb (ubuntu + windows builds, License, Module Sync, codecov) and license/cla reports signed; the PR is mergeable and blocked only on review.

LGTM — approving. Thanks for the patience across the force-pushes, and for turning the teardown flake into a shared test contract.


Automated review by github-manager-bot

@ningmao-hlyz

Copy link
Copy Markdown
Contributor Author

@jujn 打扰了,可以看看这个pr嘛,目前处于approve状态

@ningmao-hlyz

Copy link
Copy Markdown
Contributor Author

Before I try to sync this branch: upstream #3441 (merged 2026-10-08) redesigned the Harness context and session model, and it removes the classes this branch is built on — TranscriptMiddleware, SessionTranscriptWriter, and their tests no longer exist on main, and HarnessAgent was rewritten around the new context / Session Log model. So the branch is superseded at the file level: a merge now stops on modify/delete conflicts for exactly those classes.

The concern this PR addressed was completion ordering — async transcript writes outliving the agent stream or a temp workspace. Reading the new HarnessAgent.close(), upstream already drains pending background work via MemoryBackgroundTasks.awaitQuiescence(...) and closes sessions explicitly, which may cover the same ordering issue.

How would you like to proceed — close this PR as superseded, or should I re-check the new context/session path for the same ordering gap and open a fresh PR against the redesigned code if something is still missing?

@ningmao-hlyz

Copy link
Copy Markdown
Contributor Author

Following up on my note from 2026-10-09: after studying the JEV/session redesign (#3441), I'm closing the loop on this PR rather than rebasing — the redesign resolves this PR's concern structurally, and better.

What this PR tried to guarantee, and where it now lives: fire-and-forget persistence is now SessionRecorder.append buffering in memory while durability happens off the stream path (a 1s heartbeat on boundedElastic plus composable Mono<Void> flush() hooks); shutdown quiescence is covered by Mono-composed flush checkpoints; concurrent appends are serialized by the recorder's monitor and the per-run writer lease; and crash windows are handled by reconciliation (uncertainToolCalls, SessionInboxCrashRecoveryTest) instead of by blocking the stream — a better availability trade-off than what this PR proposed.

Thanks for the redesign — happy to help if anything comes up around the new session model.

@ningmao-hlyz

Copy link
Copy Markdown
Contributor Author

Closing as noted in my comment above — the JEV/session redesign resolves this PR's concern structurally, so there's no point keeping it open. Thanks for the reviews along the way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants