Repository navigation
fix(harness): detach memory maintenance from agent call response - #2326
Asaduddin18 wants to merge 15 commits into
Conversation
MemoryMaintenanceMiddleware concatenated the maintenance Mono onto the returned Flux via concatWith, so callers that consume the response to completion (blockLast(), takeLast(1)) waited for the full LLM-based consolidation call to finish -- inflating agent call latency by up to 30s and contradicting documentation that describes this as a background/fire-and-forget step. Detach maintenance via doOnComplete(...).subscribe() instead, so the returned Flux completes as soon as the underlying agent call does, independent of maintenance duration. Also add a timeout to the consolidation LLM call so a hung provider can't tie up a shared boundedElastic thread indefinitely. Fixes agentscope-ai#2225
Detaching MemoryMaintenanceMiddleware's fire-and-forget maintenance run (agentscope-ai#2225's fix) left it fully untracked: HarnessAgent.close() returned immediately even while a background maintenance write to the workspace was still in flight. In tests using JUnit @tempdir this raced against directory cleanup and intermittently failed with DirectoryNotEmptyException; in production it could tear down a workspace/sandbox out from under an in-progress write. Track each scheduled maintenance run's Disposable and add MemoryMaintenanceMiddleware.close(), called first from HarnessAgent.close(), which stops scheduling new runs and waits (bounded, 5s) for outstanding ones to finish before disposing stragglers.
…ce guard Adds coverage for the branches introduced by the previous commit that jacoco flagged as untested: scheduleMaintenance() no-op'ing after close(), and close()'s interrupted-wait / dispose-stragglers paths. Also drops the extra "dispose immediately if closed flipped true right after pending.add(d)" guard in scheduleMaintenance(). It only mattered for a TOCTOU race too narrow to hit deterministically in a test, and close()'s own wait-then-dispose-all loop already reclaims that disposable in every realistic timing.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
HarnessAgent.close()'s `if (memoryMaintenanceMw != null)` guard only had its true branch exercised (every existing test that calls close() builds an agent with memory hooks enabled), leaving the disabled-hooks path an untested branch.
oss-maintainer
left a comment
There was a problem hiding this comment.
Review: PR #2326 — fix(harness): detach memory maintenance from agent call response
Verdict: Changes Requested — CI is failing
Concept: Approved ✅
The approach is correct and addresses issue #2276. Moving memory maintenance (consolidate + flush) out of the concatWith chain so it runs asynchronously is the right fix. The close() method properly cleans up the middleware.
Issue: Build failures on both Linux and Windows
The agentscope-harness module has test failures:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.5.5:test
on project agentscope-harness: There are test failures.
Please check the surefire reports and fix the failing tests. Common causes:
- Timing-sensitive async tests — the new async behavior may cause race conditions in tests that assert on timing
- Constructor signature changes — the new
MemoryMaintenanceMiddlewareparameter in theHarnessAgentconstructor may break existing test setups that use the old constructor - Mock setup — tests that mock the middleware chain may need updating for the new detached behavior
Code observations:
- The nested try-finally in
close()is correct for resource cleanup ordering - The
doFinallyfor cleanup is a good pattern - Consider adding a timeout to the async maintenance to prevent resource leaks on shutdown
…ntion localFilesystem_filesPersistAcrossCalls wrote its persistence-demo content to MEMORY.md, which the harness's own memory-maintenance subsystem also owns (on by default whenever a model is configured). Detaching maintenance (this branch's own fix) means background consolidation is no longer serialized with the test's manual write, so it could race in and overwrite MEMORY.md with the stub model's output before the test's second assertion ran -- observed as a flaky CI failure on both Linux and Windows. Move the demo content to notes.md, a path the harness has no opinion about, so the test only exercises the local-filesystem persistence behavior it's actually named for.
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
🤖 AI Review
This PR fixes a critical user-facing latency issue where MemoryMaintenanceMiddleware was appending memory maintenance work (including a potentially slow LLM consolidation call) to the agent response Flux via concatWith. The fix detaches maintenance via doOnComplete with an independent subscribe on boundedElastic, so the response Flux completes as soon as the agent call completes. Also adds close() lifecycle, timeout on consolidation, and comprehensive tests.
(inline comments could not be attached — line numbers fell outside PR hunks. See archived report.)
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
🤖 AI Review
This PR fixes a critical user-facing latency issue where MemoryMaintenanceMiddleware was appending memory maintenance work (including a potentially slow LLM consolidation call) to the agent response Flux via concatWith. The fix detaches maintenance via doOnComplete with an independent subscribe on boundedElastic, so the response Flux completes as soon as the agent call completes. Also adds close() lifecycle, timeout on consolidation, and comprehensive tests.
(inline comments could not be attached — line numbers fell outside PR hunks. See archived report.)
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
🤖 AI Review
This PR fixes a critical user-facing latency issue where MemoryMaintenanceMiddleware was appending memory maintenance work (including a potentially slow LLM consolidation call) to the agent response Flux via concatWith. The fix detaches maintenance via doOnComplete with an independent subscribe on boundedElastic, so the response Flux completes as soon as the agent call completes. Also adds close() lifecycle, timeout on consolidation, and comprehensive tests.
(inline comments could not be attached — line numbers fell outside PR hunks. See archived report.)
|
This PR currently conflicts with git fetch upstream
git checkout fix/harness-memory-maintenance-detach
git rebase upstream/main
# resolve conflicts, then:
git push --force-with-leaseThis is a one-time reminder. Once the conflicts are resolved, comment Automated notification by github-manager-bot |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review after the CI blocker, on head 691c16c0. The approach is right and the earlier objection is resolved: my CHANGES_REQUESTED was about the failing agentscope-harness build and nothing else, and CI is now fully green — build (ubuntu-latest), build (windows-latest) (19m27s), Check License, Check Module Sync, codecov/patch, license/cla. Detaching via doOnComplete + an independent subscribe() is the correct shape: concatWith made every caller that drains the response (blockLast(), takeLast(1)) pay for consolidation including its LLM round-trip, and the new form removes that latency without changing when maintenance fires (still only on completion, not on error or cancel). Approved, with two non-blocking notes pinned inline. The remaining blocker is mechanical: the branch is CONFLICTING/DIRTY against main, which the rebase reminder already on this PR covers.
The only real code change since 82d2cd9d is dfb780c7 — the personal-assistant demo test no longer writes MEMORY.md (the rest of the delta is two main merges). That is a cause fix rather than a symptom fix: MEMORY.md belongs to the memory subsystem and is legitimately fair game for background consolidation once maintenance is detached, so a test that asserts its contents across agent calls is asserting something the harness never promised. Renaming the fixture to notes.md keeps the persistence coverage the test was actually about.
What I checked and it holds
HarnessAgent.close()drains maintenance first, thenshutdownTaskRepository()→ownedWorkspaceIndex.close()→delegate.close()through the nestedfinallychain, so the teardown order is right and an exception in one stage still runs the rest. Thenullguard coversdisableMemoryHooks(), where no middleware is installed.CONSOLIDATION_TIMEOUTtaken fromExecutionConfig.MODEL_DEFAULTS.getTimeout()keeps consolidation on the same per-call ceiling as the rest of the codebase, andMemoryConsolidatorTimeoutTestpins it withStepVerifier.withVirtualTimeagainst aFlux.never()provider rather than by sleeping.- The new tests cover the behavior that actually changed: detached completion timing, the error path reaching
onErrorResumeinstead ofHooks.onErrorDropped, no new scheduling afterclose(), and interrupt-during-drain returning promptly. - Accepted tradeoff worth knowing:
close()can now block its caller for up toCLOSE_AWAIT_TIMEOUT(5 s). That is bounded and far better than racing a@TempDirteardown, so no objection — just not free.
Findings
- [Warning]
MemoryMaintenanceMiddleware.java:182-189— theDisposableis registered inpendingafter the terminal signal may already have fired, so a lost race parks an entry in the set permanently and makes every laterclose()spin the full 5 s. Narrow window, and not a regression against currentmain; counter-based fix inline. - [Info]
MemoryMaintenanceMiddleware.java:213—dispose()cannot interrupt an already-runningMono.fromRunnablebody, so that loop bounds the wait insideclose()but not the detached write itself, which ends atCONSOLIDATION_TIMEOUT(60x longer). A javadoc sentence is enough.
On my side
Approving means no further code objection, not that this is ready to merge — it still needs the rebase, and merging stays with the maintainers. Nothing here is a design objection: the throttle and SHARED_LAST_RUN_AT discipline around the detached call is unchanged from what I already reviewed.
Automated review by github-manager-bot
| .doFinally( | ||
| sig -> { | ||
| if (holder[0] != null) { | ||
| pending.remove(holder[0]); | ||
| } | ||
| }) | ||
| .subscribe(); | ||
| holder[0] = d; |
There was a problem hiding this comment.
[Warning — non-blocking] d can be registered in pending after it has already terminated, which leaves a stale entry that no future signal will ever remove.
subscribeOn(boundedElastic) hands the subscription to a worker thread, and Mono.fromRunnable terminates as soon as maybeRunMaintenance returns — which for a throttled no-op (the common case: every call inside minGap) is microseconds. If that lands before this thread reaches line 189, then:
doFinallyseesholder[0] == nulland removes nothing — the set is still empty at that point — andpending.add(d)then inserts an already-terminatedDisposablethat nothing will ever drop again,
so from then on close() always burns the full CLOSE_AWAIT_TIMEOUT polling a set that can never drain, and each lost race leaks one entry for the lifetime of the middleware. The plain Disposable[] holder also has no happens-before edge with the worker's read of holder[0], so the write is not guaranteed visible there in the first place.
An in-flight counter needs neither the holder nor the set, and it increments before the work is published, so the ordering cannot be lost:
private final AtomicInteger inFlight = new AtomicInteger();
private void scheduleMaintenance(RuntimeContext rc) {
if (closed) {
return;
}
inFlight.incrementAndGet();
Mono.fromRunnable(() -> maybeRunMaintenance(rc))
.subscribeOn(Schedulers.boundedElastic())
.onErrorResume(e -> {
log.warn("Memory maintenance failed: {}", e.getMessage());
return Mono.empty();
})
.doFinally(sig -> inFlight.decrementAndGet())
.subscribe();
}
// close(): while (inFlight.get() > 0 && System.nanoTime() < deadline) { ...unchanged poll/interrupt... }Please fold this into the rebase this PR already needs rather than treating it as a separate round — it is a latent-shape issue, not a regression against current main.
| } | ||
| } | ||
| for (Disposable d : pending) { | ||
| d.dispose(); |
There was a problem hiding this comment.
[Info] This loop bounds how long close() waits, not how long the detached work keeps touching the workspace. dispose() on a Mono.fromRunnable whose task is already executing only cancels signal delivery — it cannot interrupt the worker, and consolidateMemory sits on consolidate(rc).block(). So a run that outlives the drain keeps writing until CONSOLIDATION_TIMEOUT fires, i.e. up to 5 minutes (ExecutionConfig.MODEL_DEFAULTS.getTimeout()), 60x CLOSE_AWAIT_TIMEOUT.
The substantive protection this PR adds — a bounded consolidation call plus a workspace that is no longer torn down underneath a detached write — is unaffected, so this is documentation-level: one sentence in the CLOSE_AWAIT_TIMEOUT/close() javadoc saying close() returns without quiescence after the drain would stop a future reader from reading pending.clear() as "nothing is in flight any more". A shorter ceiling on the shutdown path is the alternative if CI ever still shows a teardown/consolidation collision.
AgentScope-Java Version
2.0.1-SNAPSHOT
Description
Background:
MemoryMaintenanceMiddleware.onAgentconcatenated the memory-maintenanceMonoonto the returnedFluxvia.concatWith(...). BecauseReActAgent.callInternalends its call chain with.takeLast(1)(which can't emit until the upstream Flux signalsonComplete), any caller consuming the agent response to completion —blockLast(),takeLast(1), or a WebFlux controller awaiting theMono<Msg>— ended up waiting for the full LLM-based consolidation call insideconsolidateMemory()(consolidator.consolidate(rc).block()), inflating agent-call latency by up to ~30s in the reported case. This also contradicted the harness memory documentation, which describes this step as running in the "background" in a "fire-and-forget" fashion.Root cause:
doOnComplete(...)(no scheduler switch) was the original implementation and matches what the docs still describe. A later, unrelated commit swapped it for.concatWith(Mono.fromRunnable(...).subscribeOn(Schedulers.boundedElastic())...), which moved the blocking work onto a different thread pool but did not actually detach it from the response —concatWithkeeps the maintenance Mono part of the same Flux the caller is awaiting.Changes:
MemoryMaintenanceMiddleware.onAgent: replaced.concatWith(...)with.doOnComplete(() -> ...).subscribe()so the maintenance Mono is genuinely detached — subscribed independently of the returned Flux, matching the fire-and-forget pattern already used elsewhere in this package (AsyncToolMiddleware,SubagentsMiddleware). The returned Flux now completes as soon as the underlying agent call does, regardless of how long maintenance takes. Error-handling semantics (onErrorResume+log.warn) are unchanged, only relocated.MemoryConsolidator.consolidate(): added a.timeout(CONSOLIDATION_TIMEOUT)on the model call (reusingExecutionConfig.MODEL_DEFAULTS's 5-minute timeout) so a hung model provider can no longer tie up a sharedboundedElasticworker thread indefinitely — this pool is shared process-wide with 40+ other call sites.MemoryMaintenanceMiddlewareto describe the actual (now-correct) detached behavior instead of the staleconcatWithreference.Why no doc changes: This fix restores the exact behavior the existing harness docs (
docs/v2/*/docs/harness/memory.md,compaction.md,workspace.md) already describe (background/fire-and-forget maintenance) — so those docs are accurate again as a result of this fix, rather than needing separate correction.How to test:
mvn test -pl agentscope-harness -am -Dtest=MemoryMaintenanceMiddlewareAsyncBehaviorTest,MemoryConsolidatorTimeoutTestMemoryMaintenanceMiddlewareAsyncBehaviorTest.onAgent_completesBeforeSlowConsolidationFinishes: mocks a slowMemoryConsolidator.consolidate()call and assertsonAgent(...)'s returned Flux completes in well under the consolidation duration — this test fails against the pre-fixconcatWithcode (verified locally: takes 3s instead of completing immediately).MemoryMaintenanceMiddlewareAsyncBehaviorTest.onAgent_onErrorResume_handlesExceptionFromDetachedMaintenance: verifies the detached maintenance error path is still handled byonErrorResume(usingHooks.onErrorDroppedto detect if it would otherwise be silently dropped).MemoryConsolidatorTimeoutTest.consolidate_timesOutInsteadOfHangingForever: usesStepVerifier.withVirtualTimeto confirm a model that never responds causesconsolidate()to error with aTimeoutExceptioninstead of hanging — verified this test fails to even compile without the fix (confirming it's tied to the change).Full harness module suite: 637/637 tests passing, 0 failures/errors. Every changed/added line has full line and branch coverage (verified via JaCoCo — no partial coverage on any touched line).
Fixes #2225
Checklist
mvn spotless:applymvn test)