Skip to content

Reduce durable journal storage and add a local file backend - #4221

Open
juruoO-o wants to merge 10 commits into
agentscope-ai:mainfrom
juruoO-o:perf/durable-journal-storage
Open

juruoO-o wants to merge 10 commits into
agentscope-ai:mainfrom
juruoO-o:perf/durable-journal-storage

Conversation

@juruoO-o

@juruoO-o juruoO-o commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Deduplicate the repeated conversation state in large native journal entries and checkpoints with content-defined chunks and shared manifest pages. Compress record-backed chunks and constrain the verified-read cache. The PostgreSQL profiler attributes stored payload bytes to journal entries, checkpoints, shared chunks, and committed public events.

SQLite remains the default for LocalBackend.open(path). LocalBackend.file(path) enables a pure filesystem backend for a single host. A transaction touching multiple scopes publishes one atomic snapshot under an OS writer lock. PostgreSQL snapshot settings are scoped to the transaction so a reused connection can serve a subsequent write.

Verification

Drove one Thread in Docker PostgreSQL 17 with deterministic 2 KiB inputs and the same offline model on the format 27 main and PR revisions:

Turns Revision Journal Checkpoints Shared Public events Total
100 main a8b1b2d668 41.07 MB 43.00 MB 0 1.79 MB 85.85 MB
100 this PR 3.06 MB 2.12 MB 0.47 MB 1.79 MB 7.44 MB
1,000 main a8b1b2d668 3.94 GB 4.25 GB 0 17.90 MB 8.21 GB
1,000 this PR 33.59 MB 24.11 MB 4.84 MB 17.90 MB 80.44 MB

Totals count stored payload bytes and count shared content once. At Turn 1,000, manifest pages contribute 12.91 MB across the journal, checkpoint, and shared columns. Average additions on this PR were 74.4 KB per Turn for Turns 1–100, 79.5 KB for Turns 101–500, and 82.4 KB for Turns 501–1,000.

Verified the local backend contract, concurrent JVM writers, process termination before commit, cross-scope rollback, and 138 JDBC tests against Docker PostgreSQL including reusing the same physical connection for a snapshot and a subsequent write.

Copilot AI balanced review requested due to automatic review settings November 17, 2026 02:53

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.

@mintlify

mintlify Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 2accc5c.

Approve preview

Use the upstream PostgreSQL prefix and scoped-work queries, and implement the new scoped query for the file backend. Preserve journal chunking and the tests for both storage representations.
@juruoO-o juruoO-o changed the title Reduce durable journal storage and index PostgreSQL prefix scans Reduce durable journal storage and add a local file backend Dec 1, 2026
Keep SQLite as the default and support atomic multi-scope commits in the opt-in file backend. Deduplicate large replay content while preserving mainline journal semantics.
@juruoO-o
juruoO-o requested a review from chickenlj December 2, 2026 05:20
@juruoO-o

juruoO-o commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

The latest change scopes the PostgreSQL snapshot settings to the transaction. Please check that a subsequent borrower of the same connection sees its original settings.

juruoO-o pushed a commit that referenced this pull request Dec 2, 2026
…() 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)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants