Skip to content

feat(memory): extract Thread journal messages incrementally - #4168

Open
ningmao-hlyz wants to merge 9 commits into
agentscope-ai:mainfrom
ningmao-hlyz:feat/memory-journal-admission
Open

ningmao-hlyz wants to merge 9 commits into
agentscope-ai:mainfrom
ningmao-hlyz:feat/memory-journal-admission

Conversation

@ningmao-hlyz

@ningmao-hlyz ningmao-hlyz commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.1.0-SNAPSHOT, based on main at 2644b0f9.

Description

Fixes #4166.

Read new original messages from the native Thread journal instead of re-extracting working context after each call. Save extraction progress in workspace files so recreated agents resume independently of compaction.

The branch is rebased onto current main as nine commits. The supporting changes it carries:

  1. Fix request output-limit overrides so extraction's requested limit replaces either inherited limit.
  2. Add optional conditional UTF-8 file writes and use them for memory appends. Cover local cross-JVM writers, atomic versioned stores, routed paths, empty files and inherited overlay content.
  3. Consume up to 256 journal events per trigger, split into budgeted requests with Unicode-safe offsets. Append each ledger batch before progress; a deterministic marker records its delivered end for same-day recovery. Native compaction retains originals without a second extraction.
  4. Adapt optional serial memory admission to JEV while preserving assess() behavior, and verify durable finalization replay through the host workspace.
  5. Apply the local content-visibility boundary before opening a conditional file handle.

flushTimeout defaults to two minutes for the whole trigger, including extraction and serial admission in native and legacy modes. Completed rejections consume sources; errors leave the batch retryable. Later invocations can repeat judgments. Prose without bullets is one candidate. Diagnostics include the backend and thread, with recovery steps in both language guides.

Conditional file access checks the local content-visibility boundary before returning a file handle. This also covers the hidden workspace subtree when integrated with #4071; retain its exclusion implementation when resolving the shared hook.

Native extraction requires conditional writes on every memory route. The remote implementation checks supportsAtomicJournalStorage(); a separate COS/OSS memory route does not acquire atomicity from the journal backend. Unsupported routes fail explicitly. Legacy extraction remains available and has no equivalent position-based recovery. Conditional append retains a legacy fallback on unsupported backends, without concurrent-write guarantees.

There is no background retry worker, deferred queue, candidate-level progress, fact eviction or global conflict store. Ledger and progress are separate commits; concurrent attempts can repeat model calls and cross-day retries can repeat facts. Bounded write conflicts fail explicitly for a later trigger. Admission does not cover memory_save or consolidation. A persistently over-budget batch needs a longer timeout or a smaller admission budget.

Behavior changes

  • MemoryConfig.defaults() no longer claims to be a no-op upgrade: it carries a two-minute flushTimeout that the harness's historical behaviour did not have, so an application that only enables long-term memory now gets that bound without opting in.
  • A truncated or tool-block-bearing extraction stream is never appended. Journal extraction retries a truncated page with half the input budget (up to three times) and keeps the page for the next trigger when the smaller budget selects the same messages; legacy extraction drops the stream.
  • Setting either request output limit replaces both inherited limits; a fallback default no longer fills in the other one.
  • Native compaction keeps the originals and no longer runs a second pre-compaction extraction, so flushBeforeCompact applies to legacy execution only.

Validation on Windows, Java 17, at 3a418cb5:

  • Harness module (-pl agentscope-harness -am test): 2,407 tests, 0 failures/errors, 52 skipped; Spotless passed.
  • Core module on the same run: 605 tests, 0 failures/errors.
  • Conditional-file suites (LocalAtomicTextFileTest, OverlayAtomicTextFileTest, RemoteFilesystemCASTest): 31 tests, 0 failures/errors, no skips.
  • JEV admission (JevMemoryAdmissionTest): 7 tests, 0 failures/errors.
  • Durable harness adapter (AgentScopeAdapterTest): 71 tests, one failure in detachedJobReturnsAReceiptBeforeWorkAndWakesTheAwaitingReplacement. The same test fails identically on unmodified main at 2644b0f9 on this machine, so it is not caused by this branch.
  • Rebase conflicts were resolved against main at 2644b0f9; the documentation pages were merged by hand and not re-run through the site checker after the rebase.

Real JEV services, macOS, NFS and power-loss recovery were not exercised locally. The multi-turn stream fixture retains its lifecycle/source assertions and disables memory hooks to protect ordered model replies.

Storage measurements use the actual WorkspaceManager APIs on Windows, Java 17, with three runs per configuration. Single-writer p50 below is the median of three runs, each starting at 64 KiB and appending 253 B 200 times, with WorkspaceIndex disabled. Redis is a real 5.0.14.1 Windows port on loopback with persistence disabled; it is not a cloud latency measurement.

Storage path Legacy p50 Conditional p50
Direct local disk 0.32 ms 43.37 ms
LocalFilesystem 38.45 ms 43.84 ms
Redis loopback 1.77 ms 2.26 ms
Redis with a simulated 2 ms delay per store operation 7.74 ms 10.69 ms

The direct-local increase includes replacing in-place append with a full-file write, force and atomic rename. The remote path makes two reads and one conditional write instead of one read and one write. These measurements do not include model calls or a complete extraction trigger.

Four independent JVMs continuously contending for one file produced 716 explicit bounded-conflict failures in 12,000 conditional append attempts; every successful append remained present. This stress workload is not reported as an error-free result. With one-second gaps per writer, local and Redis checks retained all 240 writes without errors. No retry queue or unbounded retry was added.

Checklist

  • Code has been formatted; Spotless checks pass.
  • Tests pass for the commands listed above.
  • Javadoc comments follow project conventions.
  • Related English and Chinese documentation has been updated.
  • Code is ready for review.

@mintlify

mintlify Bot commented Nov 13, 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 3a418cb.

Approve preview

@ningmao-hlyz

Copy link
Copy Markdown
Contributor Author

@jujn Could you review this PR when you have time?

A request-supplied maxTokens or maxCompletionTokens replaces either inherited
output limit. Preserve defaults when neither is supplied, and preserve both
when the request explicitly supplies both. Add regression coverage.
Expose optional conditional text IO through local, remote, composite and overlay
filesystems. Use it for memory appends to detect concurrent updates across
instances. Keep legacy append behavior on backends without the capability.

Cover empty files, inherited overlay content, cross-JVM writers and internal
artifacts, including the grep fallback when rg is unavailable.
Persist an extraction position independently of working context and compaction.
Commit budgeted ledger batches before progress, and record their ends for same-day
retry. Add optional serial admission and a trigger-wide timeout.

Document backend requirements and recovery limits. Keep the subagent stream
fixture isolated from background extraction of its ordered model replies.
Keep assess() behavior and expose the Harness admission policy through an
adapter. Document the two entry points and verify durable finalization replay
through the host workspace in adapter tests.
compactionFlushRequiresMemoryOptIn asserted the pre-compaction flush for both
execution modes. Native execution keeps the originals in the journal and
extracts them incrementally, so the prefix is not flushed a second time;
ConversationCompactor has always skipped it when an InvocationRecorder is
attached, which is now true for every journal-enabled build.

The expectation becomes memory && flush && !journal, and the file assertion
follows it. Three of the fifteen parameterized cases change; the rest are
unaffected.
Follow-ups from review:

- MemoryFlushMiddleware lost the note that the throttle window follows the
  isolation key and that NEVER stops only the per-call hook. MemoryFlushManager
  lost which class owns each memory file. Both are restored where the behaviour
  lives, and FlushMode.NEVER now names compaction and overflow recovery.

- The journal progress check combined && and || without parentheses; split it
  into named predicates.

- FLUSH_WARNINGS was an anonymous LinkedHashMap subclass. Name it, declare a
  serialVersionUID, and keep the FIFO bound instead of clearing the whole map;
  replace the List.toString() key with String.join.

- LocalAtomicTextFile retry counts become named constants, and prefix() records
  why only an oversized message pays for the binary search.

Also covers candidates() directly (bullets, indented continuations, prose) and
records that the durable adapter selects inline extraction through
INLINE_CONTEXT_KEY.

mvn -pl agentscope-harness -am test for the memory, middleware, conditional-file
and regression classes passes (104 tests, 0 failures).
The Windows build failed while closing the test's temp directory: writer-2.log,
the second child's redirected output, was still locked. destroyForcibly()
returns before the process and its handles are gone.

Wait for both children and close their three streams, and skip cleanup for this
test's directory, because Windows can keep a redirected log locked for a moment
after exit. A failed delete surfaces as an extension-context error that fails
the whole class rather than the one test.

mvn -pl agentscope-harness -am test -Dtest=LocalAtomicTextFileTest passes
(14 tests, 0 failures).
@ningmao-hlyz
ningmao-hlyz force-pushed the feat/memory-journal-admission branch from e9ca45e to 5ecc6e9 Compare December 2, 2026 08:22
A page whose extraction always hits the output limit kept its position pinned:
the retry rebuilt the same page from the same events and the same 8K input
budget, so it truncated again on every trigger. Only the first failure was
visible per Thread, so a stalled memory pipeline looked idle.

Journal extraction now retries a truncated page with half the input budget, up
to three times, and gives up with the original error when the smaller budget
selects the same messages (one oversized message, or a page that cannot
shrink). Legacy extraction still drops a truncated stream, and neither path
appends partial text.

Also: log the no-reply outcome and the admission summary at debug, since both
fired once per call; cut the deduplication excerpts on code-point boundaries
so an emoji at the edge cannot leave a lone surrogate in the prompt; and keep
the fire-and-forget note in the middleware javadoc.
@ningmao-hlyz
ningmao-hlyz force-pushed the feat/memory-journal-admission branch from cdff91c to 3a418cb Compare December 2, 2026 10:24
@ningmao-hlyz ningmao-hlyz reopened this Dec 2, 2026

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

P2 重要不紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Extract long-term memory incrementally from the native Thread journal

2 participants