Repository navigation
Description
Summary
MemoryFlushMiddleware, MemoryMaintenanceMiddleware and TranscriptMiddleware attach their post-turn work to the agent event stream with concatWith(...). Because concatWith is sequential composition, the downstream subscriber does not receive onComplete until that work finishes. subscribeOn(Schedulers.boundedElastic()) only moves the work to another thread — it does not make it fire-and-forget.
The documentation states the opposite, and for flush this is a regression from the previous implementation.
For streaming deployments (SSE / WebSocket), where stream completion is what closes the client connection, this turns background memory maintenance into user-visible latency. We measured up to 85 seconds of dead time after the assistant's final text had already been delivered.
Environment
- agentscope-harness 2.0.2, and current main (verified — see code references below)
- Java 17, Spring Boot 3.3.5, HarnessAgent + RemoteFilesystemSpec (Redis-backed workspace), IsolationScope.USER
- Streaming via agent.streamEvents(...) piped to an SSE endpoint
Expected behavior (per the docs)
docs/v2/zh/docs/harness/memory.md (line 61 on main):
▎ Flush 和 offload 都是异步执行的:它们在响应流结束后通过 doOnComplete 以 fire-and-forget 方式启动,不会阻塞当前 call() 的返回。
("Flush and offload are executed asynchronously: they are started fire-and-forget via doOnComplete after the response stream ends, and do not block the return of the current call().")
Actual behavior
All three middlewares use concatWith, so the caller waits:
// MemoryFlushMiddleware#onAgent (main, L137-L152)
return next.apply(input)
.concatWith(
Mono.defer(() -> doFlush(agent, rc))
.subscribeOn(Schedulers.boundedElastic())
.onErrorResume(e -> { log.warn("Memory flush failed: {}", e.getMessage()); return Mono.empty(); })
.then(Mono.empty()));
MemoryMaintenanceMiddleware#onAgent (L137-L152) is identical in shape, and the work it wraps blocks on an LLM call:
// MemoryMaintenanceMiddleware#consolidateMemory (main, L246)
consolidator.consolidate(rc).block();
TranscriptMiddleware#onAgent follows the same concatWith pattern for transcript append.
The class javadoc of MemoryMaintenanceMiddleware (L44) documents the mechanism explicitly — "Fires on the agent invocation completion (via onAgent concatWith, after MemoryFlushMiddleware)" — so the implementation is self-consistent; it is the docs and the streaming use case that are at odds with it.
How this regressed
Flush used to be genuinely fire-and-forget. Commit 7ab520d (feat(harness): introduce async tool and notification support. #1802, 2026-06-17) changed it:
- return next.apply(input).doOnComplete(() -> doFlush(agent, rc).subscribe());
- return next.apply(input).concatWith(Mono.defer(...).subscribeOn(Schedulers.boundedElastic())...);
(Consolidation appears to have used concatWith from the start; only flush is a regression. If the change was intentional — e.g. to order async-tool notifications correctly — that rationale isn't captured anywhere, and the docs were not updated.)
Impact
The severity depends entirely on how the caller consumes the stream:
- CLI / batch agents: invisible. The output has already been printed; nobody notices the process taking a few more seconds before exiting. Guaranteeing "memory is persisted before the turn is considered over" is arguably the right trade-off here.
- Long-lived streaming connections (SSE / WebSocket): directly user-visible. onComplete is what ends the response; every millisecond spent in these hooks is a user staring at a spinner after the assistant's answer is already fully rendered.
The cost also grows with how much the agent remembers: MemoryConsolidator rewrites MEMORY.md in full on every run, and its prompt budget is maxChars = maxMemoryTokens * 4 (MemoryConsolidator L145), i.e. 16,000 characters by default (consolidationMaxTokens = 4000). A richer memory file means a longer blocking LLM generation.
Measurements from production
A. Same session, same user, consecutive turns — time from the final AGENT_END event to stream completion:
┌──────┬────────────────────────────────────────────┬──────────────┐
│ Turn │ Consolidation triggered │ Tail latency │
├──────┼────────────────────────────────────────────┼──────────────┤
│ n │ no │ 1.76 s │
├──────┼────────────────────────────────────────────┼──────────────┤
│ n+1 │ yes — MEMORY.md consolidated (16295 chars) │ 85.4 s │
└──────┴────────────────────────────────────────────┴──────────────┘
B. Consolidation time is proportional to the rewritten output (same deployment, after we lowered consolidationMaxTokens):
┌───────────────────────────────┬────────────────────┐
│ MEMORY.md output │ Consolidation time │
├───────────────────────────────┼────────────────────┤
│ 16,295 chars (default budget) │ 76 s │
├───────────────────────────────┼────────────────────┤
│ 5,170 chars │ 24 s │
├───────────────────────────────┼────────────────────┤
│ 1,218 chars │ 5.3 s │
└───────────────────────────────┴────────────────────┘
C. Breakdown of one tail (from the middlewares' own debug logs), memory hooks alone:
AGENT_END +0
Running memory maintenance... +1 ms
MEMORY.md consolidated +5.3 s <- consolidation LLM call
Memory maintenance completed +16 ms
Memory flush completed +3.9 s <- flush LLM call
Message offload completed +164 ms
= 9.4 s of blocked stream completion
All of this happens after the last text token has been emitted.
Why it can't be worked around via configuration
MemoryConfig exposes only: model, flushPrompt, consolidationPrompt, consolidationMaxTokens, consolidationMinGap, dailyFileRetentionDays, sessionRetentionDays, flushTrigger. There is no switch for the execution mode.
- flushTrigger(NEVER) disables only the per-call flush; consolidation and transcript append still run — and still block.
- disableMemoryHooks() is all-or-nothing: it removes automatic extraction entirely.
Tuning consolidationMaxTokens / consolidationMinGap only reduces the magnitude and frequency of the stall, not the fact that it sits on the critical path.
Suggested fix
Either of:
- Restore fire-and-forget for these hooks, e.g. doOnComplete(() -> mono.subscribe()), so that onComplete reaches the subscriber immediately (this is also what the docs describe today); or
- Make it configurable, e.g. MemoryConfig.blockOnCompletion(boolean) (defaulting to whatever preserves current behavior), so callers on long-lived streaming connections can opt out while batch/CLI callers keep the "memory durably written before the turn ends" guarantee.
Either way, docs/v2/zh/docs/harness/memory.md should be updated to match the implementation.
Related, smaller observation
While profiling the above we also found WorkspaceIndex.open(...) creating a bare SQLite connection with no journal_mode=WAL and no busy_timeout, in autocommit mode, shared across threads. MemoryFlushManager#offloadMessages → WorkspaceManager#updateSessionIndex (on the stream-completion path) and the single-threaded SessionTree mirror executor both write through it, so they serialize on the JDBC connection. We captured a thread dump showing the stream-completion thread BLOCKED in WorkspaceIndex.upsert while the mirror thread held it. On slower/networked volumes this adds seconds to the same critical path. Happy to file that separately if you'd prefer.
Activity
GG5533 commentedon Sep 9, 2026
Not a maintainer — an outside reader. I went to check this because the mechanism
you describe is a real one, and
TranscriptMiddlewarematches your report exactly.The other two don't, on current
main, and the difference changes the fix.TranscriptMiddleware— confirmed.Sequential composition, so the downstream subscriber doesn't see
onCompleteuntil
appendTranscriptfinishes, andsubscribeOnonly relocates the work.For an SSE deployment where completion closes the connection, that would account
for the dead time you describe.
MemoryFlushMiddleware— does not useconcatWithonmain.and
scheduleFlushdispatches torunFlush(L203), which subscribes independently:That is the fire-and-forget the documentation describes. The
L137-L152range inyour report lands on the constructor rather than
onAgent, which may be wherethe line reference drifted.
MemoryMaintenanceMiddleware— same pattern, inline rather than in a helper:.doOnComplete(() -> { MemoryBackgroundTasks.begin(); Mono.defer(...).subscribeOn(...).doFinally(...).subscribe(...); }).So on
mainit's one middleware blocking completion, not three.What I can't tell from here, and you can. I only read
main. You also listagentscope-harness 2.0.2, and your "regression from the previousimplementation" note for flush suggests you saw something different there. If
2.0.2's flush did use
concatWithandmainhas since changed, then yourmeasurement stands for 2.0.2 and the remaining work on
mainis transcriptalone. Worth pinning which version each of the three observations came from,
because it decides whether this is one fix or three.
One thing I'd raise about the fix, since it isn't a symmetric swap. Both
fire-and-forget middlewares bracket their work with
MemoryBackgroundTasks:with a comment in
scheduleFlushexplaining why the slot is taken at dispatchrather than inside the task — "a queued flush must already be counted, or a
quiescence check could observe an empty in-flight set while work is still
pending."
TranscriptMiddlewarehas no equivalent, and it doesn't currently need one:concatWithkeeps the work inside the stream's lifetime, so the stream itself isthe accounting. Moving it to
doOnCompleteremoves that guarantee and it doesn'tinherit the replacement automatically — the transcript append becomes work with
nothing tracking whether it's still in flight at shutdown or between turns. Given
the flush path already has machinery for exactly this, the fix is probably
"transcript joins
MemoryBackgroundTasks" rather than "transcript switches todoOnComplete".That's an outside reading of three files, not a test run — I haven't reproduced
your 85s or built the project.
CryoThrust commentedon Sep 9, 2026
The version distinction is important here. On the current
main, the evidence appears to narrow the blocking path toTranscriptMiddleware;MemoryFlushMiddlewareandMemoryMaintenanceMiddlewarealready dispatch their work fromdoOnCompleteand track it throughMemoryBackgroundTasks. The report still reproduces a broader regression onagentscope-harness 2.0.2, so I suggest splitting the acceptance criteria by version:MemoryBackgroundTasksquiescence/shutdown accounting;mainis the only supported fix target.That keeps the fix from accidentally making transcript writes fire-and-forget without preserving the shutdown/quiescence guarantee. If maintainers confirm this boundary, I can help prepare the focused test once the target module/version is agreed.
ningmao-hlyz commentedon Sep 10, 2026
I plan to submit a focused fix for the remaining current-main case: TranscriptMiddleware still uses concatWith and delays downstream stream completion while persisting the transcript. MemoryFlushMiddleware and MemoryMaintenanceMiddleware already use tracked fire-and-forget execution, so this change will leave them untouched. The PR will move transcript persistence to the same tracked background-task pattern and add a regression test for completion latency and lifecycle quiescence.
oss-maintainer commentedon Sep 12, 2026
Issue Evaluation
Category:
bug| Status: Confirmed (partially fixed onmain)Verified against
main@c5db8f72:MemoryFlushMiddleware(L159) andMemoryMaintenanceMiddleware(L149-162) now usedoOnComplete(...)+ backgroundsubscribe(...), i.e. genuinely fire-and-forget — the flush/consolidate half of the report no longer reproduces onmain.TranscriptMiddleware(L68-78) still attaches persistence withconcatWith(Mono.defer(() -> appendTranscript(agent, rc)).subscribeOn(Schedulers.boundedElastic())...), so downstreamonCompletewaits for transcript I/O. This is the remaining blocking path behind the observed post-answer dead time on SSE/WebSocket.docs/v2/zh/docs/harness/memory.mdL61 still documents flush/offload as fire-and-forget, so the doc/code contradiction stands for the transcript path.Severity: high (user-visible tail latency on streaming responses).
Scope:
agentscope-harnessmiddleware chain.Note: PR #3106 already targets exactly this remaining case, and
maindoes not contain the fix yet. No new PR will be generated here to avoid duplicating in-flight community work — tracking stays on #3106.Automated evaluation by github-manager-bot