Repository navigation
fix(durable): drain borrowed connections before JdbcRecordStore.close() returns - #4509
Conversation
|
Non-blocking if the goal is mitigation: please document that |
|
All four points verified and addressed in 1. One correction to the mechanism, same conclusion: 2. Independent budgets, confirmed against the code. 3. Budget comment corrected. "Matches the caller's own close budget, so draining cannot out-block whoever closes us" was wrong on both counts: the runtime budget is separate, and the store drain can be the second of two waits. Rewritten. 4. Timeout test added — Two things worth flagging:
|
…() 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.
…effort Review follow-up. The drain has never guaranteed that every borrowed connection is returned when close() returns, but the javadoc still read as if it did, and the constant's comment claimed the budget matched the caller's. Neither held: DurableRuntime.close() spends its own 5s on observers/timer/workers and leaves backends to the caller, so a host closing runtime then store sequentially pays up to twice this budget. State that close() is a mitigation, not a guarantee, and that nothing bounds how long an already-running operation takes, so a write may still outlive it. Cover the timeout path with a test asserting close() is bounded in both directions, returns while the write is still in flight, and leaves the abandoned write durable.
40bc371 to
c11e95d
Compare
juruoO-o
left a comment
There was a problem hiding this comment.
The close contract now documents the independent, bounded best-effort wait. The timeout test holds a transaction past the drain deadline, checks that close returns while the write is pending, and verifies the late write after reopening. Reviewed the borrow accounting and the success, timeout, and interrupt paths. Ubuntu and Windows CI passed.
Problem
JdbcRecordStore.close()only flipped anAtomicBooleanand returned immediately:Nothing enforced the javadoc's claim. Every operation borrows a fresh connection through
connect(), and nothing bounds how long astore.transaction(...)may hold one — the caller's action,synchronous=FULLfsyncs, and up to 10 seconds of SQLite lock waiting all run on that borrow. Soclose()could return while a write was still in flight, leaving an open SQLite file handle behind.On Windows that surfaces as JUnit
@TempDirteardown failure, becauseunlinkon an open handle succeeds on POSIX but not there. This turnedmainred three times:44566773929httpUsesExplicitCreationAndTargetedIdempotentControls46179100442/4609890210346231881667(job141249277724)toolOutputPreviewIsDeliveredWithoutAdvancingTheSessionCursorOnly
durable.dbresists deletion while the siblingstateHome@TempDirdeletes 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-mergedMemoryBackgroundTasks.awaitQuiescencefrom #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()andkeys().connect()now rejects-or-counts atomically under a monitor, and returns aProxyover the realConnectionthat 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 aWARNING(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 returnedclose()is therefore not proof that every handle is released, and callers must not delete the underlying files on the strength of it. The javadoc onclose()says this explicitly.The 5s budget bounds this store's drain only. It is independent of the 5s that
DurableRuntime.close()spends awaitingobservers/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:
close()is idempotent viacompareAndSet. JDBC specifies that closing an already-closed connection is a no-op, andConnectionsis a public interface — a caller may pass a pool that callsclose()twice. Counting the same borrow twice would steal another borrow's slot and letclose()return early, reintroducing exactly the leak this fixes.RecordStore.Transactionexposes onlynow()/get()/put()/keys()/schedule(), never theConnection, 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 whenclose()returns, and the abandoned write still lands durably afterwards.closeStillRejectsOperationsStartedAfterIt— the existingIllegalStateExceptioncontract 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 widenedChatControllerTesttimeout, no sleep-based deflake, no surefire rerun, andLocalBackendis untouched.Mutation-verified — each injected defect is caught:
close()does not wait (original behaviour)endBorrow()does not decrement (count never reaches zero)endBorrow()does notnotifyAll()(lost wakeup)connect()does not increment (count stuck at zero)close()never gives up)Verification
Run on macOS 14, JDK 17.0.18, Maven 3.9.12.
The new timeout case sleeps out the real 5s drain budget, so
JdbcRecordStoreCloseTestgoes 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
mainthe quiescence assertion fails atJdbcRecordStoreCloseTest.java:87withclose() returned while a transaction still held a borrowed connection.Unrelated pre-existing flake observed while re-running the module:
DurableUserApiTest.committedEventOutboxReusesEventIdentityAfterFailedDeliveryAndReopen:92. Baseline on pristinemain(9e9fa9f95): 2 failures / 14 full-suite runs; on this branch: 1 / 14; single-test 20/20 green. The case passesretryDelay = 1mswhilenowcomes from SQLitejuliandaytruncated to milliseconds (JdbcRecordStore.java:289-299), sodeliver()'sdueAt > nowcheck races the clock's own resolution. Out of scope here.The definitive confirmation can only come from the
windows-latestmatrix job. The leak is equally present on Ubuntu but symptomless there, since POSIXunlinksucceeds on an open handle. Failure rate on Windows before the fix was roughly 2/10.Scope notes
Deliberately not included:
docs/devupdate, although AGENTS.md §5 would normally call for one. Both Reduce durable journal storage and add a local file backend #4221 and Harden Durable Harness recovery across Brain and Hands failover #4217 currently modifydocs/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 acrossobservers/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 throughconnect().connect()andclose().transaction(),ready(),keys()and the constructor bodies are untouched, so this does not conflict with Reduce durable journal storage and add a local file backend #4221 or Harden Durable Harness recovery across Brain and Hands failover #4217 beyond line-number drift.Related but distinct: #4337 covers the same bug class for
journal.sqlite3in a different module.Checklist
spotless:checkpasses