Skip to content

[Bug]:Memory flush / consolidation / transcript block completion of the agent event stream (concatWith instead of fire-and-forget), contradicting the documentation #3059

Open

Description

@baili123

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:

  1. 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
  2. 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

  1. added
    bug
    on Sep 9, 2026
  2. GG5533 commented on Sep 9, 2026

    @GG5533

    Not a maintainer — an outside reader. I went to check this because the mechanism
    you describe is a real one, and TranscriptMiddleware matches your report exactly.
    The other two don't, on current main, and the difference changes the fix.

    TranscriptMiddleware — confirmed.

    // TranscriptMiddleware#onAgent, main
    return next.apply(input)
            .concatWith(
                    Mono.defer(() -> appendTranscript(agent, rc))
                            .subscribeOn(Schedulers.boundedElastic())
                            ...
                            .then(Mono.<AgentEvent>empty()));

    Sequential composition, so the downstream subscriber doesn't see onComplete
    until appendTranscript finishes, and subscribeOn only relocates the work.
    For an SSE deployment where completion closes the connection, that would account
    for the dead time you describe.

    MemoryFlushMiddleware — does not use concatWith on main.

    // MemoryFlushMiddleware#onAgent, main
    return next.apply(input).doOnComplete(() -> scheduleFlush(agent, rc));

    and scheduleFlush dispatches to runFlush (L203), which subscribes independently:

    Mono.defer(() -> doFlush(agent, rc))
            .subscribeOn(Schedulers.boundedElastic())
            ...
            .subscribe(null, e -> log.warn("Memory flush failed: {}", e.getMessage()));

    That is the fire-and-forget the documentation describes. The L137-L152 range in
    your report lands on the constructor rather than onAgent, which may be where
    the line reference drifted.

    MemoryMaintenanceMiddleware — same pattern, inline rather than in a helper:
    .doOnComplete(() -> { MemoryBackgroundTasks.begin(); Mono.defer(...).subscribeOn(...).doFinally(...).subscribe(...); }).

    So on main it's one middleware blocking completion, not three.

    What I can't tell from here, and you can. I only read main. You also list
    agentscope-harness 2.0.2, and your "regression from the previous
    implementation" note for flush suggests you saw something different there. If
    2.0.2's flush did use concatWith and main has since changed, then your
    measurement stands for 2.0.2 and the remaining work on main is transcript
    alone. 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:

    MemoryBackgroundTasks.begin();   // at dispatch, before the task runs
    ...
    .doFinally(signal -> MemoryBackgroundTasks.end());

    with a comment in scheduleFlush explaining why the slot is taken at dispatch
    rather 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."

    TranscriptMiddleware has no equivalent, and it doesn't currently need one:
    concatWith keeps the work inside the stream's lifetime, so the stream itself is
    the accounting. Moving it to doOnComplete removes that guarantee and it doesn't
    inherit 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 to
    doOnComplete".

    That's an outside reading of three files, not a test run — I haven't reproduced
    your 85s or built the project.

  3. CryoThrust commented on Sep 9, 2026

    @CryoThrust
    Contributor

    The version distinction is important here. On the current main, the evidence appears to narrow the blocking path to TranscriptMiddleware; MemoryFlushMiddleware and MemoryMaintenanceMiddleware already dispatch their work from doOnComplete and track it through MemoryBackgroundTasks. The report still reproduces a broader regression on agentscope-harness 2.0.2, so I suggest splitting the acceptance criteria by version:

    1. add a regression test that asserts the subscriber receives completion without waiting for transcript persistence;
    2. add a separate lifecycle test that verifies a queued background task remains visible to the existing MemoryBackgroundTasks quiescence/shutdown accounting;
    3. document whether 2.0.2 behavior is being backported or whether main is 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.

  4. ningmao-hlyz commented on Sep 10, 2026

    @ningmao-hlyz
    Contributor

    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.

  5. oss-maintainer commented on Sep 12, 2026

    @oss-maintainer
    Collaborator

    Issue Evaluation

    Category: bug | Status: Confirmed (partially fixed on main)

    Verified against main @ c5db8f72:

    • MemoryFlushMiddleware (L159) and MemoryMaintenanceMiddleware (L149-162) now use doOnComplete(...) + background subscribe(...), i.e. genuinely fire-and-forget — the flush/consolidate half of the report no longer reproduces on main.
    • TranscriptMiddleware (L68-78) still attaches persistence with concatWith(Mono.defer(() -> appendTranscript(agent, rc)).subscribeOn(Schedulers.boundedElastic())...), so downstream onComplete waits 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.md L61 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-harness middleware chain.

    Note: PR #3106 already targets exactly this remaining case, and main does 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

  6. added
    area/harness
    on Sep 12, 2026
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

    area/harnessbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions