Repository navigation
fix(harness): avoid blocking stream completion on transcript persistence - #3106
ningmao-hlyz wants to merge 2 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 #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
105959a to
a66780c
Compare
oss-maintainer
left a comment
There was a problem hiding this comment.
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 beforeunlock(), so a new caller can publish a secondWriteLockfor 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 remoteTranscriptStore; 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 previousonErrorResumewas dropped fromappendTranscript. - [Info]
TranscriptMiddleware.java:84/:91— state resolution runs inline on the completing thread; failure logging lost itsagent=/session=context. - [Info]
TranscriptMiddlewareAsyncTest.java:242— no test pins down the cancel semantics of thedoOnComplete-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
|
Follow-up on CI for the current head ( The leftover path is a session transcript directory under a 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 |
a66780c to
baacde7
Compare
4fc8029 to
eb67eb2
Compare
oss-maintainer
left a comment
There was a problem hiding this comment.
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 emitsonComplete; this is the tail latency the PR is meant to remove. - [Info]
TranscriptMiddleware.java:96—doOnCompletemeans a cancelled stream persists nothing; either document + test that contract or coverCANCEL. - [Info]
SessionTranscriptWriter.java:125— lock fix confirmed; thecurrent != writeLockbranch leaves the (already-dead)WriteLockcounter undecremented, worth one clarifying comment.
Verification
- No new imports of
Schedulersmisuse;MemoryBackgroundTasks.begin()stays on the calling thread so the task is counted beforesubscribeOnhands off — the pairing withdoFinally(end())plus thecatch (RuntimeException)end()is now symmetric, which closes the "uncounted window" note from last round. - Sandbox branch still keeps persistence in-stream, and
TranscriptMiddlewareAsyncTeststill covers that ordering.
Automated review by github-manager-bot
ab0e0ea to
e36a99c
Compare
oss-maintainer
left a comment
There was a problem hiding this comment.
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-conversationstate.getContext()copy still happens synchronously on the terminal-signal thread insidedoOnComplete. - [Info]
TranscriptMiddleware.java:109— transcript writes now join the process-wideMemoryBackgroundTaskscounter that everyHarnessAgent.close()waits on. - [Info]
SessionTranscriptWriter.java:116— previous lock-protocol warning confirmed fixed and unchanged by the rebase.
Checklist for approval
- Either move the snapshot inside the
Mono.defer(...)body, or document why the copy must stay on the stream thread. - 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.
e36a99c to
bf1acbb
Compare
oss-maintainer
left a comment
There was a problem hiding this comment.
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
TranscriptMiddlewareAsyncTestandSessionTranscriptWriterTestcover completion ordering, snapshot-before-detach, in-stream sandbox writes, shutdown quiescence and failure isolation on both paths.AgentState.getContext()isCollections.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_LOCKSrefcount 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) andlicense/clareports 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
|
@jujn 打扰了,可以看看这个pr嘛,目前处于approve状态 |
|
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 — The concern this PR addressed was completion ordering — async transcript writes outliving the agent stream or a temp workspace. Reading the new 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? |
|
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 Thanks for the redesign — happy to help if anything comes up around the new session model. |
|
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. |
Summary
Fixes #3059.
MemoryBackgroundTasksso shutdown can wait for them.Problem
TranscriptMiddlewareusedconcatWith(...)for transcript persistence. Because the persistence task was part of the sequential stream, downstream subscribers did not receiveonCompleteuntil 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
doOnComplete(...)without delaying downstream completion.MemoryBackgroundTasks, preserving lifecycle shutdown/quiescence guarantees.MemoryFlushMiddlewareandMemoryMaintenanceMiddlewarealready use tracked fire-and-forget execution and are unchanged by this PR.Testing
mvn -pl agentscope-harness -Dtest=SessionTranscriptWriterTest,TranscriptMiddlewareAsyncTest testmvn -pl agentscope-harness spotless:check