Skip to content

fix(harness): bound the memory files replayed into flush and consolidation - #4477

Open
xseruer wants to merge 3 commits into
agentscope-ai:mainfrom
xseruer:fix/memory-input-bound
Open

xseruer wants to merge 3 commits into
agentscope-ai:mainfrom
xseruer:fix/memory-input-bound

Conversation

@xseruer

@xseruer xseruer commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.1.0-SNAPSHOT (agentscope-harness)

Description

Problem. In a long-running production agent the memory flush call started failing with the provider's invalid_parameter_error: Range of input length should be [1, 1048576] on every run. The user message of that call was 2.03M characters: MEMORY.md had grown to 1.42M characters and today's daily ledger to 614K, and both were replayed whole into the prompt.

Root cause. MemoryFlushManager and MemoryConsolidator concatenate the files they read into the prompt without any bound. MEMORY.md is only size-bounded while consolidation succeeds: MemorySaveTool appends straight to it, and a daily ledger grows with every flush and save. Once either file outgrows the model's input window, both auxiliary calls fail every time, so the only step able to shrink MEMORY.md again can never run. The harness budget check does not catch it either: the 2.5-chars-per-token estimate puts 2M characters at ~813K tokens, below a 1M window, while the provider's real count for CJK-heavy text is higher.

Change. Flush replays a bounded slice of each file (new package-private MemoryInputBudget); consolidation merges the pending entries in bounded oldest-first batches and keeps per-ledger progress between runs.

  • Flush: leading 32,000 characters of MEMORY.md, trailing 32,000 characters of today's ledger. The cut is marked in the prompt and logged at WARN; cut points never split a UTF-16 surrogate pair.
  • Consolidation input: leading max(maxChars, 60,000) characters of MEMORY.md (so a memory within its body target is never cut), plus the pending ledger entries oldest first (ledgers by name, ## entries in append order), at most 60,000 characters per run. A single entry larger than that is merged head-truncated, so the input is always bounded.
  • Per-ledger progress. When the cap cuts the batch, the watermark stays where it was and the state records how far each ledger has been read. The next run reads every eligible ledger from its own offset, so nothing is skipped: entries appended to an already-read ledger between runs (e.g. by a writer on another local date) are merged before the watermark may advance. The watermark moves to runStart only when a run read every eligible ledger to its end. The offsets live with the watermark in both places it is stored: one path<TAB>offset line per ledger after the watermark line in memory/.consolidation_state, and the same text under progress in the store item (reads prefer the store).
  • Why an offset rather than per-entry timestamps. Entry headers carry the clock of whichever instance appended them (clock(rc) for flush, the system clock for memory_save). With several instances sharing a ledger, ordering or filtering by header time could skip entries; ledgers are append-only, so an offset is exact.
  • The sizes keep both prompts inside the 64K-token fallback input budget of HarnessContextBuilder, so they also work when the model reports no context window.

With this in place a consolidated result replaces the oversized MEMORY.md and the system recovers on its own. Unchanged from before this PR: an append landing after a completing run's runStart keeps its ledger eligible through its mtime and is replayed from the start on the next run, as for any file modified during a run.

Not changed. MemorySaveTool still appends to MEMORY.md directly. That is the source of the unbounded growth, but changing it alters default tool behaviour, so it is left for a separate discussion.

Tests. MemoryFlushManagerTest (oversized memory and ledger are capped, head and tail kept), MemoryInputBudgetTest (exact cut output, no split surrogate pair, under-limit passthrough), MemoryConsolidatorCommitGateTest: oversizedMemoryAndSingleOversizedEntryAreCappedAndStillCommit, cutBatchKeepsTheWatermarkAndTheNextRunMergesTheSkippedEntries (two-pass: the watermark stays, the skipped entry is merged next, consumed entries are not re-sent, state-file layout), writesToEarlierLedgersBetweenPassesAreMergedBeforeTheWatermarkAdvances (a late append to an already-consumed ledger and a newly created earlier ledger are merged before the watermark advances, consumed entries are not re-sent), cutBatchProgressIsVisibleThroughTheWatermarkStore (per-ledger offsets through the store). All Memory* tests in agentscope-harness pass (159 tests), and the full agentscope-core, agentscope-extensions-ag-ui and agentscope-harness suites pass.

Checklist

Please check the following items before code is ready to be reviewed.

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (e.g. links, examples, etc.)
  • Code is ready for review

…ation

MEMORY.md is only size-bounded while consolidation succeeds, yet memory_save
and the agent's file tools append to it unbounded, and a daily ledger grows
with every flush. Both prompts replayed those files whole, so once they
outgrew the model's input window every flush and consolidation failed with
the provider's invalid_parameter_error, and the only step able to shrink
MEMORY.md could never run again.

Replay at most the head of MEMORY.md and the tail of the ledger instead,
sized to stay within the harness's 64k-token fallback input budget.
@mintlify

mintlify Bot commented Nov 28, 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 ab042c3.

Approve preview

@juruoO-o

juruoO-o commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

I think the consolidation watermark needs to be fixed before merge. tail() can omit unconsolidated ledger entries, but a successful write advances the same watermark past all the selected files. Those omitted entries are then no longer eligible for normal consolidation (even though the source files may still exist). Bounding the prompt is useful, but please process an oldest-first bounded batch and advance only through consumed entries, or persist a continuation cursor; add a two-pass test that proves the skipped input is still eligible.

…t ledger entries

Bounding the consolidation input with a tail cut dropped the oldest
unconsolidated ledger entries while the watermark still advanced past
them, so they were never merged.

Consolidation now merges the oldest entries first in a bounded batch
(60,000 chars per run, entries in append order, files by name). When the
batch is cut, the watermark stays and a continuation cursor (ledger path
and character offset) is persisted with it, so the next run resumes at
the first unmerged entry; the watermark advances only once a run read
everything selected. The cursor travels with the watermark in both the
state file and the distributed store item.
@xseruer

xseruer commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Agreed — the tail cut silently dropped entries. Reworked in d08293e:

  • Oldest-first bounded batch. Consolidation now merges pending entries oldest first (files by name, ## entries in append order), at most 60,000 characters per run. A single entry larger than the cap is merged head-truncated as the first entry of its batch, so the input stays bounded.
  • Advance only through consumed entries. When the cap cuts the batch, the watermark is left untouched and a continuation cursor (ledger path + character offset) is persisted with it, so the next run resumes at the first unmerged entry. The watermark advances to runStart only once a run read everything it selected.
  • Cursor visibility. The cursor travels with the watermark in both places it lives: a second line of memory/.consolidation_state, and cursorPath/cursorOffset in the same store item when a BaseStore is configured (reads prefer the store, so a file-only cursor would be invisible there).

Why an offset cursor rather than per-entry timestamps: entry headers carry the clock of whichever instance appended them (flush uses clock(rc), memory_save the system clock). With several instances sharing a ledger, ordering or filtering by header timestamp could skip entries the same way the tail did; ledgers are append-only, so an offset is exact.

Tests: cutBatchKeepsTheWatermarkAndTheNextRunMergesTheSkippedEntries (two-pass: the watermark stays, the skipped entry is merged on the next run, consumed files/entries are not re-sent) and cutBatchCursorIsVisibleThroughTheWatermarkStore (same two passes through the store, cursor cleared after the full merge). en/zh docs updated accordingly.

@juruoO-o juruoO-o left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] A ledger earlier than the cursor can receive a late append between bounded passes, for example from a writer using a different local date. readDailyBatch skips that whole file by name, then the completing pass advances the watermark past the append. I extended the existing two-day regression by appending one entry to OLDER_DAY between passes: the new fact was absent from the second model input. Please retain enough per-file progress (or an equivalent cutoff and replay rule) to consume writes made between passes before advancing past them. Please cover this with a late-append regression and confirm previously consumed entries are not resent.

…cursor

A single cursor skipped every ledger sorting before it, so an entry
appended to an already-consumed ledger between two bounded passes was
never merged: the completing pass advanced the watermark past it. The
state now records how far each ledger has been read, and the next pass
reads every eligible ledger from its own offset.
@xseruer

xseruer commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in ab042c3: a single cursor no longer decides which ledgers are read. The state now keeps per-ledger progress (ledger path → characters already merged), and every eligible ledger is read from its own offset.

  • Per-file progress. A cut pass records an offset for each ledger it read: the cut one at the cut entry, those before it at their end. No ledger is skipped by name. On the next pass each ledger modified since the unchanged watermark is read again from its recorded offset, so an entry appended to an already-consumed ledger between passes is picked up, and a ledger created with an earlier name is read from the start.
  • Advance only when everything selected was read to its end. The watermark moves to runStart and the progress is cleared only when the pass reached the end of every eligible ledger; otherwise the watermark stays and the offsets are persisted again.
  • Where it lives. Same two places as before, one serialization: one path<TAB>offset line per ledger after the watermark line in memory/.consolidation_state, and the same text under progress in the store item (reads prefer the store, so it must be there).

Regression writesToEarlierLedgersBetweenPassesAreMergedBeforeTheWatermarkAdvances: the first pass consumes OLDER_DAY and is cut inside today's ledger; between the passes one entry is appended to OLDER_DAY and an even earlier ledger is created. The second model input contains both new facts plus the rest of today's entries, still oldest first, and does not contain the already-consumed - fresh fact one / yyy; the watermark advances only after that pass; a third pass makes no model call. cutBatchKeepsTheWatermarkAndTheNextRunMergesTheSkippedEntries now also asserts the state-file layout, and cutBatchProgressIsVisibleThroughTheWatermarkStore the per-ledger offsets through the store.

Unchanged from before this PR: an append landing after a completing pass's runStart keeps its ledger eligible through its mtime and is replayed from the start on the next pass — the existing behavior for a file modified during a run, so nothing is lost.

Tests: Memory* 159 passed; core 3568, ag-ui 607, harness 2300 green; spotless clean. en/zh docs updated.

@xseruer
xseruer requested a review from juruoO-o December 3, 2026 01:04

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