Repository navigation
test(harness): drain fire-and-forget memory flush before @TempDir teardown to stop flaky temp-dir deletion - #2935
Conversation
…rdown to stop flaky temp-dir deletion
There was a problem hiding this comment.
🟡 Changes recommended
The new quiescence extension currently ignores timeout/interrupt failures from the await methods, which can allow the original teardown flake to persist without a deterministic, actionable failure.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
This PR addresses intermittent JUnit @TempDir teardown failures in harness tests by ensuring fire-and-forget background writes (session/transcript mirrors and memory background tasks) have quiesced before temporary directories are deleted.
Changes:
- Added a JUnit Jupiter
AfterEachCallbackextension to await harness background task quiescence after each test method. - Added
@HarnessQuiescenceas a composed annotation to apply the extension with a one-liner. - Applied
@HarnessQuiescenceto multiple@TempDir-using harness integration tests that build/transiently runHarnessAgentinstances.
File summaries
| File | Description |
|---|---|
| agentscope-harness/src/test/java/io/agentscope/harness/agent/tools/HarnessAgentToolsConfigTest.java | Applies @HarnessQuiescence to prevent teardown races in this test. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/testing/HarnessQuiescence.java | Introduces composed annotation to register the quiescence extension. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/testing/HarnessBackgroundTaskQuiescenceExtension.java | Adds AfterEachCallback extension that drains mirror + memory background tasks. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/SubagentIsolationIntegrationTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/PlanModeSubagentPropagationTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/JsonSessionDefaultLocationTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/HarnessAgentTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/HarnessAgentSubagentStreamTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/HarnessAgentSubagentStreamEventsTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/HarnessAgentModelStringTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/HarnessAgentIntegrationExampleTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/HarnessAgentDynamicHookBuilderTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/HarnessAgentDistributedSandboxTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/gateway/SubagentRegistryRecoveryIntegrationTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/example/SandboxFilesystemIsolationScopeExampleTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/example/RemoteFilesystemIsolationScopeExampleTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/example/LocalFilesystemUserIsolationExampleTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
| agentscope-harness/src/test/java/io/agentscope/harness/agent/example/LocalFilesystemPersonalAssistantExampleTest.java | Applies @HarnessQuiescence to avoid @TempDir deletion races. |
Review details
- Files reviewed: 18/18 changed files
- Comments generated: 1
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Since agentscope-ai#2777 the per-call memory flush and maintenance run detached from the agent response, tracked by the JVM-wide MemoryBackgroundTasks counter and drained by HarnessAgent.close() via awaitQuiescence. A hung model call, however, has no bound and no escape: - runFlush's pipeline has no timeout, so a hung flush keeps the conversation's coalescing slot in FLUSH_QUEUES running forever - every later flush of that conversation queues behind the dead slot and memory extraction stops for it; - MemoryBackgroundTasks.inFlight never returns to zero, so every subsequent awaitQuiescence call (e.g. HarnessAgent.close()) waits its full budget, gives up, and leaves the stuck task running against the torn-down workspace - the race agentscope-ai#2935 patched at the test level; - maintenance consolidation ran consolidator.consolidate(rc).block() inside Mono.fromRunnable, so a hung consolidation leaked a boundedElastic worker for the rest of the process: the inner block subscription is unreachable from any outer dispose, and once the model eventually returned, the same worker would keep writing retention/prune results into the torn-down workspace. Fixes: - Both pipelines get a 5-minute timeout. The budget runs from subscription, so it also covers any boundedElastic pickup wait: under scheduler saturation a healthy-but-slow run may be skipped and logged - the safe direction for fire-and-forget work. - doMaintenance is now a reactive composition (expire -> consolidator.consolidate -> prune), so a timeout or quiescence cancel propagates down the chain into the consolidation model stream and the worker is actually freed; consolidation failures log and let the retention steps still run, matching the previous try/catch semantics. - MemoryBackgroundTasks gains register/unregister: each task's subscription is listed under the task-tracking monitor (with a disposed re-check, so a terminated subscription can never linger), and awaitQuiescence disposes still-stuck tasks when its timeout elapses instead of leaving them running. Disposal runs outside the monitor so the cancelled task's cleanup can re-enter it safely. Known bound: the quiescence sweep disposes one task per key; that task's doFinally drains the queue and may start the next queued flush for that key before the sweep finishes - at most one flush per key per close escapes cancellation. New MemoryBackgroundHardeningTest: awaitQuiescence cancels stuck tasks; a hung flush times out, releases the quiescence count and the conversation queue recovers; a hung consolidation times out and the cancellation is asserted to reach the consolidation subscription itself (the old .block() variant released the counter while the worker stayed stuck). The timeout is injectable via package-private test hooks; production uses the 5-minute default.
…() returns close() only flipped a flag and returned immediately, so a connection borrowed through connect() could still be mid-transaction (SQLite busy_timeout=10000 lets one run for 10s). The leaked file handle made JUnit's @tempdir teardown fail on Windows with "Failed to delete temp directory ... durable.db", which turned main red three times. Track in-flight borrows in connect(), the single point every pool funnels through, and have close() wait for them to be returned within a budget matching the caller's own close deadline. Connections are counted down when the caller closes them, so no call site changes and the counter cannot leak on a failure path. Mirrors MemoryBackgroundTasks.awaitQuiescence from agentscope-ai#2935.
…() returns (#4509) ## Problem `JdbcRecordStore.close()` only flipped an `AtomicBoolean` and returned immediately: ```java /** Prevents new operations; existing borrowed connections finish and return normally. */ @OverRide public void close() { closed.set(true); } ``` Nothing enforced the javadoc's claim. Every operation borrows a fresh connection through `connect()`, and nothing bounds how long a `store.transaction(...)` may hold one — the caller's action, `synchronous=FULL` fsyncs, and up to 10 seconds of SQLite lock waiting all run on that borrow. So `close()` could return while a write was still in flight, leaving an open SQLite file handle behind. On Windows that surfaces as JUnit `@TempDir` teardown failure, because `unlink` on an open handle succeeds on POSIX but not there. This turned `main` red three times: | Date | Run | Failing method | | --- | --- | --- | | 2026-11-19 | `44566773929` | `httpUsesExplicitCreationAndTargetedIdempotentControls` | | 2026-11-28 | `46179100442` / `46098902103` | (see runs) | | 2026-11-29 | `46231881667` (job `141249277724`) | `toolOutputPreviewIsDeliveredWithoutAdvancingTheSessionCursor` | ``` org.junit.platform.commons.JUnitException: Failed to close extension context Caused by: java.io.IOException: Failed to delete temp directory ...\junit-... The following paths could not be deleted: <root>, preview, preview\durable, preview\durable\durable.db ``` Only `durable.db` resists deletion while the sibling `stateHome` `@TempDir` deletes cleanly, which pins the holder to this class. #4435 listed this exact failure under *"Observed but deliberately not fixed here"* with the note *"no recurrence since"*. It has recurred — the 2026-11-29 run above hit a different victim method. ## Change Track in-flight borrowed connections and have `close()` wait for them, mirroring the already-merged `MemoryBackgroundTasks.awaitQuiescence` from #2935 (which fixed the same bug class for harness memory flushes). Counting lives entirely in `connect()`, the single point every caller funnels through — the constructor, `transaction()`, `ready()` and `keys()`. `connect()` now rejects-or-counts atomically under a monitor, and returns a `Proxy` over the real `Connection` that counts down when the caller closes it. All four call sites already use try-with-resources, so no call site changed and the counter cannot leak on a failure path. `close()` sets the flag, then waits up to 5s for the count to reach zero, logging a `WARNING` (not throwing) if it times out or is interrupted. This is a **bounded best-effort drain, not a guarantee**: nothing bounds how long an operation already in flight may take, so a durable write can outlive `close()`. A returned `close()` is therefore not proof that every handle is released, and callers must not delete the underlying files on the strength of it. The javadoc on `close()` says this explicitly. The 5s budget bounds *this store's drain only*. It is independent of the 5s that `DurableRuntime.close()` spends awaiting `observers`/`timer`/`workers` (`DurableRuntime.java:1163-1172`) before leaving backends to the caller (`:1184`), so a host closing runtime then store sequentially pays up to twice it. Two details worth calling out: - The proxy's `close()` is idempotent via `compareAndSet`. JDBC specifies that closing an already-closed connection is a no-op, and `Connections` is a public interface — a caller may pass a pool that calls `close()` twice. Counting the same borrow twice would steal another borrow's slot and let `close()` return early, reintroducing exactly the leak this fixes. - The proxy never escapes the class: `RecordStore.Transaction` exposes only `now()`/`get()`/`put()`/`keys()`/`schedule()`, never the `Connection`, so no caller can observe the narrowed type or hit the proxy's identity semantics. The logging uses `System.Logger`, already the convention in this module (`PostgresBackend`), so no dependency is added. ## Test `JdbcRecordStoreCloseTest` (new, 4 cases) asserts quiescence directly rather than file-deletability, which is unobservable on POSIX: - `closeWaitsForAnInFlightTransactionToReturnItsConnection` — a transaction started on another thread holds the connection open for 400ms; `close()` must not return before the write commits, and must return promptly (asserting the drain budget is not merely what masks the failure). The write is then re-read through a fresh store to prove it actually landed. - `closeReturnsOnTimeoutWithABorrowStillInFlight` — covers the documented limitation. A transaction holds the borrow past the drain budget; `close()` is asserted bounded in both directions (returns after `>= DRAIN_TIMEOUT_MILLIS`, not before the write finishes at `< +3s`), the write is still in flight when `close()` returns, and the abandoned write still lands durably afterwards. - `closeStillRejectsOperationsStartedAfterIt` — the existing `IllegalStateException` contract is preserved. - `repeatedCloseDoesNotBlock` — double close stays cheap. Per AGENTS.md §3 the test mirrors the production guard instead of weakening an assertion for a Windows-only flake. No `@Disabled`, no OS gating, no widened `ChatControllerTest` timeout, no sleep-based deflake, no surefire rerun, and `LocalBackend` is untouched. Mutation-verified — each injected defect is caught: | Mutation | Result | | --- | --- | | `close()` does not wait (original behaviour) | caught, 1 failure | | `endBorrow()` does not decrement (count never reaches zero) | caught, 1 failure | | `endBorrow()` does not `notifyAll()` (lost wakeup) | caught, 1 failure | | `connect()` does not increment (count stuck at zero) | caught, 1 failure | | timeout path loops instead of returning (`close()` never gives up) | caught, upper-bound assertion trips at 8188ms | | timeout path throws instead of returning | caught, 1 error | ## Verification Run on macOS 14, JDK 17.0.18, Maven 3.9.12. ``` mvn -pl agentscope-extensions/agentscope-extensions-durable-jdbc -am test → Tests run: 134, Failures: 0, Errors: 0, Skipped: 0 (includes the 68-case contract suite) mvn -pl agentscope-durable/durable-runtime test → Tests run: 48, Failures: 0, Errors: 0, Skipped: 0 mvn -pl agentscope-durable/durable-adapters/durable-adapter-harness-agentscope -am test → Tests run: 594, Failures: 0, Errors: 0, Skipped: 11 (pre-existing gating) → Tests run: 120, Failures: 0, Errors: 0, Skipped: 0 mvn -pl agentscope-examples/agents/agentscope-chat test → Tests run: 14, Failures: 0, Errors: 0, Skipped: 0 (includes ChatControllerTest) mvn -pl agentscope-examples/agents/agentscope-chat test -Dtest=ChatControllerTest (x32 rounds) → 32/32 green mvn -pl agentscope-extensions/agentscope-extensions-durable-jdbc -am spotless:check → BUILD SUCCESS mvn -pl agentscope-extensions/agentscope-extensions-durable-jdbc javadoc:javadoc → BUILD SUCCESS (doclint=all,-missing) ``` The new timeout case sleeps out the real 5s drain budget, so `JdbcRecordStoreCloseTest` goes 1.1s → 9.3s and the module suite grows by ~8s. I pinned the test to the production constant (`private` → package-private, reason in its javadoc) rather than adding a shrink-the-budget constructor, because the budget value is exactly what the review raised. RED confirmed first: on unmodified `main` the quiescence assertion fails at `JdbcRecordStoreCloseTest.java:87` with `close() returned while a transaction still held a borrowed connection`. Unrelated pre-existing flake observed while re-running the module: `DurableUserApiTest.committedEventOutboxReusesEventIdentityAfterFailedDeliveryAndReopen:92`. Baseline on pristine `main` (`9e9fa9f95`): 2 failures / 14 full-suite runs; on this branch: 1 / 14; single-test 20/20 green. The case passes `retryDelay = 1ms` while `now` comes from SQLite `julianday` truncated to milliseconds (`JdbcRecordStore.java:289-299`), so `deliver()`'s `dueAt > now` check races the clock's own resolution. Out of scope here. **The definitive confirmation can only come from the `windows-latest` matrix job.** The leak is equally present on Ubuntu but symptomless there, since POSIX `unlink` succeeds on an open handle. Failure rate on Windows before the fix was roughly 2/10. ## Scope notes Deliberately not included: - **No `docs/dev` update**, although AGENTS.md §5 would normally call for one. Both #4221 and #4217 currently modify `docs/dev/{en,zh}/docs/harness/durable.md`; editing it here would collide. Happy to follow up once one of them merges. - **`DurableRuntime.close()`'s single shared 5s budget** across `observers`/`timer`/`workers` (`DurableRuntime.java:1163-1172`) is a second, independent contributor to this flake: the last executor in the list can receive a zero budget. That is separable and I left it out to keep this PR focused. This change already covers it in practice, because all four pools reach SQLite through `connect()`. - The diff touches only imports, two fields, `connect()` and `close()`. `transaction()`, `ready()`, `keys()` and the constructor bodies are untouched, so this does not conflict with #4221 or #4217 beyond line-number drift. Related but distinct: #4337 covers the same bug class for `journal.sqlite3` in a different module. ## Checklist - [x] Tests added for the fixed behaviour - [x] `spotless:check` passes - [x] No public API change - [x] No new dependency - [x] EN/ZH docs — see scope note above (intentionally deferred)
Problem
Two CI runs fail intermittently with JUnit errors that are not test-logic failures but teardown failures:
Failed to delete temp directory(Windows, PR fix(sandbox): docker sandbox native file transfer + reject truncated downloads (#2618) #2923)Failed to close extension context/Failed to delete temp directory(Ubuntu, PR feat(middleware): add final answer filter for ReAct streams #2926)Both surface only when a test builds a transient
HarnessAgent, drives it to completion via.block()/.stream()...block(), and uses@TempDirfor its workspace/state home.Root cause
This is a long-standing race, not a regression of any single commit. The harness memory flush has always been asynchronous: when an agent stream completes,
MemoryFlushMiddleware#onAgentdispatches the flush onSchedulers.boundedElastic()viasubscribe(...)— i.e. fire-and-forget. The calling test's.block()only waits for the business stream, not for that background flush.So the timeline is:
.block()and returns.@TempDirteardown and deletes the temp directory.boundedElasticis still writing session/transcript mirror files into that same@TempDir(or still holds open file handles).The result: directory/file deletion fails with
IOException→ wrapped asJUnitException. It is timing-dependent (depends on IO speed, scheduler, and how many files are written), which is why it flakes rather than failing deterministically, and why Windows (stricter file locking) fails more readily than Linux.The normal production path avoids this because
HarnessAgent#close()callsSessionTree.awaitMirrorQuiescence(...)+MemoryBackgroundTasks.awaitQuiescence(...). The flaky tests never callclose()on their transient agent.Fix
Add test-side quiescence that mirrors what
HarnessAgent#close()already does, run after each test method but before theTempDirextension deletes the directory:HarnessBackgroundTaskQuiescenceExtension— anAfterEachCallbackthat callsSessionTree.awaitMirrorQuiescence(5s)+MemoryBackgroundTasks.awaitQuiescence(5s). When nothing is in flight both calls return immediately, making it a no-op for tests that never trigger a flush.@HarnessQuiescence— a composed meta-annotation (@ExtendWith(HarnessBackgroundTaskQuiescenceExtension.class)) so at-risk tests only need a one-line annotation.@HarnessQuiescenceto 16 harness test classes that match the at-risk pattern (HarnessAgent.builder()+.call()/.stream()+@TempDir), including the three classes that flaked in CI:JsonSessionDefaultLocationTest,HarnessAgentIntegrationExampleTest,HarnessAgentDynamicHookBuilderTest.Production code is unchanged — the flush remains fire-and-forget so conversation completion is never blocked.