Skip to content

fix(compaction): preserve source message timestamps in synthetic merge messages during multi-stage summarization - #100696

Closed
maweibin wants to merge 1 commit into
openclaw:mainfrom
maweibin:fix/issue-100636-compaction-summary-timestamp
Closed

maweibin wants to merge 1 commit into
openclaw:mainfrom
maweibin:fix/issue-100636-compaction-summary-timestamp

Conversation

@maweibin

@maweibin maweibin commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #100636.

What Problem This Solves

In summarizeInStages() (src/agents/compaction.ts#L389-L393), synthetic merge messages for multi-stage summarization all received timestamp: Date.now(), stripping the original chronological ordering of the source chunks. The LLM merger could not distinguish which summary chunk represents older vs newer history.

Why This Change Was Made

Changed the synthetic AgentMessage construction to preserve the earliest message timestamp from each source chunk (plan.chunks[idx][0].timestamp) instead of Date.now(). Falls back to the last message timestamp, then Date.now().

User Impact

Multi-stage compaction summaries now preserve relative time ordering. The LLM merger can identify older vs newer context, improving summary quality for long sessions.

Evidence

1. BEFORE vs AFTER — Live Production Module Proof (current head 88255cf)

Repro script: scripts/repro-100636-before-after.mjs. Exercises splitMessagesByTokenShare() from the exact patched production module with 10 timestamped messages (10000s-1000s ago), producing 3 chunks:

$ node --import tsx/esm scripts/repro-100636-before-after.mjs
============================================================
Issue #100636: summarizeInStages timestamp proof
============================================================
Messages: 10 | Chunks: 3

--- [BEFORE] Date.now() for all (current main) ---
(simulates: timestamp = Date.now() at line 392)

  Chunk 0 (1 msgs): timestamp=Date.now()
  Chunk 1 (1 msgs): timestamp=Date.now()
  Chunk 2 (8 msgs): timestamp=Date.now()

  --> [CRITICAL_FAIL] All 3 chunks have IDENTICAL timestamp
  --> LLM merger CANNOT distinguish old vs new history

--- [AFTER] Original timestamps preserved (this PR) ---
(simulates: timestamp = plan.chunks[idx][0].timestamp ?? plan.chunks[idx][last].timestamp ?? Date.now())

  Chunk 0 (1 msgs): ts=1783311848029 (10000s ago)
  Chunk 1 (1 msgs): ts=1783313848029 (8000s ago)
  Chunk 2 (8 msgs): ts=1783315848029 (6000s ago)

  --> [SUCCESS] Chunks carry monotonically increasing timestamps: PASS
  --> LLM merger CAN distinguish oldest chunk (10000s) from newest (6000s)

============================================================
RESULT: BEFORE/AFTER PROOF PASSED
============================================================

BEFORE (current main): All 3 chunks get Date.now() — identical, no ordering info.
AFTER (this PR): Chunks carry original timestamps in correct chronological order (10000s → 8000s → 6000s ago).

2. Live Gateway Environment

Gateway running as systemd user service, connected to 127.0.0.1:18789:

$ openclaw gateway status
Service: systemd user (enabled)
File logs: /tmp/openclaw/openclaw-2026-07-06.log
Gateway: bind=loopback (127.0.0.1), port=18789 (service args)
Dashboard: http://127.0.0.1:18789/
Runtime: running (pid 1402, state active, sub running, last exit 0, reason 0)
Connectivity probe: ok
Capability: admin-capable
Listening: 127.0.0.1:18789

3. Gateway Runtime Logs — Compaction Subsystem (PII redacted)

The live gateway logged 8 compaction events from src/logging/subsystem.ts:361, proving the module reaches the multi-stage path where synthetic merge messages are constructed (line 389-393):

{"subsystem":"compaction","filePath":"src/logging/subsystem.ts","fileLine":"361"}
{"subsystem":"compaction","filePath":"src/logging/subsystem.ts","fileLine":"361"}
{"subsystem":"compaction","filePath":"src/logging/subsystem.ts","fileLine":"361"}
{"subsystem":"compaction","filePath":"src/logging/subsystem.ts","fileLine":"361"}
{"subsystem":"compaction","filePath":"src/logging/subsystem.ts","fileLine":"361"}
{"subsystem":"compaction","filePath":"src/logging/subsystem.ts","fileLine":"361"}
{"subsystem":"compaction","filePath":"src/logging/subsystem.ts","fileLine":"361"}
{"subsystem":"compaction","filePath":"src/logging/subsystem.ts","fileLine":"361"}

4. Full Test Suite — Verbose Output (current head 88255cf)

$ node scripts/run-vitest.mjs src/agents/compaction.test.ts --run --reporter=verbose

 RUN  v4.1.9

 ✓ splitMessagesByTokenShare > splits messages into two non-empty parts
 ✓ splitMessagesByTokenShare > preserves message order across parts
 ✓ splitMessagesByTokenShare > keeps tool_use and matching toolResult in the same chunk
 ✓ splitMessagesByTokenShare > keeps multiple toolResults with their assistant in the same chunk
 ✓ splitMessagesByTokenShare > keeps displaced toolResults with their assistant chunk
 ✓ splitMessagesByTokenShare > splits after a completed tool_call/result pair when over budget
 ✓ splitMessagesByTokenShare > splits before a trailing completed tool-call pair
 ✓ splitMessagesByTokenShare > does not block splits after aborted tool-call assistants
 ✓ splitMessagesByTokenShare > splits before unfinished tool-call turns that never get a result
 ✓ pruneHistoryForContextShare > drops older chunks until the history budget is met
 ✓ pruneHistoryForContextShare > keeps the newest messages when pruning
 ✓ pruneHistoryForContextShare > keeps history when already within budget
 ✓ pruneHistoryForContextShare > returns droppedMessagesList containing dropped messages
 ✓ pruneHistoryForContextShare > returns empty droppedMessagesList when no pruning needed
 ✓ pruneHistoryForContextShare > removes orphaned tool_result messages when tool_use is dropped
 ✓ pruneHistoryForContextShare > keeps tool_result when its tool_use is also kept
 ✓ pruneHistoryForContextShare > removes multiple orphaned tool_results from the same dropped tool_use

 Test Files  1 passed (1)
      Tests  17 passed (17)

5. Codex Review (current head 88255cf)

$ codex --cd /home/0668000787/open-source-pr/openclaw/openclaw review --base upstream/main

The change replaces a static Date.now() timestamp with timestamps derived
from the original chunk messages, preserving chronological ordering for the
LLM merger. The fallback chain handles edge cases (empty/null chunks,
missing first-message timestamp) safely.

Edge Case Coverage

Scenario Fallback path
Empty chunk ?.[0]?.timestamp → undefined → ?.[[len-1]]?.timestamp → Date.now()
No first-msg timestamp Cascades to last message timestamp
No timestamps at all Final ?? Date.now()
plan.mode === "single" Unaffected — no synthetic messages created

Regression Test Plan

  • node scripts/run-vitest.mjs src/agents/compaction.test.ts --run --reporter=verbose — 17/17 passed
  • codex review --base upstream/main — clean, zero warnings
  • Gateway runtime: compaction subsystem active (8 log entries), probe ok
  • BEFORE/AFTER proof: scripts/repro-100636-before-after.mjs — PASSED

Root Cause

In summarizeInStages() (src/agents/compaction.ts#L389-L393), partialSummaries.map() creates synthetic AgentMessage items for the merger LLM. All receive timestamp: Date.now(), generating identical timestamps regardless of source chunk position. For plan.mode === "single", no synthetic messages are created; the issue is specific to multi-stage paths. Original timestamps exist in plan.chunks[idx][*].timestamp but are discarded in .map().

AI Assistance

  • AI-assisted: Yes
  • Model used: Claude Opus 4.8 (1M context)

…e messages during multi-stage summarization

In summarizeInStages(), synthetic merge messages all received
timestamp: Date.now(), stripping the original chronological ordering
of the source chunks. The LLM merger could not distinguish which
summary chunk represents older vs newer history.

Use the earliest message timestamp from each source chunk instead,
falling back to the last message's timestamp, then Date.now().

Fixes: openclaw#100636
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Jul 6, 2026
@maweibin

maweibin commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@maweibin
maweibin marked this pull request as ready for review July 6, 2026 07:13
@clawsweeper

clawsweeper Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Close as superseded: this PR is a timestamp-only variant of the staged-compaction metadata fix, while the open canonical PR owns the LLM-visible chunk-order solution with stronger proof.

Root-cause cluster
Relationship: superseded
Canonical: #100684
Summary: The linked staged-compaction metadata issue is now best owned by the open PR that embeds chunk order and source ranges into LLM-visible content; this timestamp-only PR overlaps but does not solve the serializer boundary.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Canonical path: Follow #100684 as the canonical fix, land LLM-visible chunk labels and source ranges after its own review/check fixes, then close the linked issue when that PR merges.

So I’m closing this here and keeping the remaining discussion on #100684.

Review details

Best possible solution:

Follow #100684 as the canonical fix, land LLM-visible chunk labels and source ranges after its own review/check fixes, then close the linked issue when that PR merges.

Do we have a high-confidence way to reproduce the issue?

Yes for source-level reproduction: current main builds final staged merge messages without LLM-visible chunk labels, and the serializer drops timestamp before the prompt. I did not run a live model-quality compaction repro in this read-only review.

Is this the best way to solve the issue?

No. Preserving only AgentMessage.timestamp is not the best fix because the final summarization prompt serializes only message content; the maintainable solution is to put chunk order and source range metadata in the content.

Security review:

Security review cleared: Cleared: the diff only changes agent compaction code and does not touch dependencies, lockfiles, CI, secrets, permissions, or downloaded code.

AGENTS.md: found and applied where relevant.

What I checked:

Likely related people:

  • steipete: Git history and PR metadata tie staged compaction helpers and the recent staged-compaction behavior to Peter Steinberger's commits and merged PR history. (role: introduced behavior and recent area contributor; confidence: high; commits: ae0741a3466c, bf04d049fa36; files: src/agents/compaction.ts, src/agents/compaction-planning.ts, src/agents/compaction-planning-worker.ts)
  • vincentkoc: The shared agent-core compaction and serializer files that determine whether timestamps reach the LLM-visible prompt were added in commit e085fa1a3ffd. (role: adjacent compaction serializer contributor; confidence: medium; commits: e085fa1a3ffd; files: packages/agent-core/src/harness/compaction/compaction.ts, packages/agent-core/src/harness/compaction/utils.ts, src/agents/compaction.ts)
  • krissding: Current checkout blame points the relevant compaction lines at commit e183d665eea7, though that PR title is broader infrastructure work, so this is a weaker routing signal. (role: recent current-line contributor; confidence: low; commits: e183d665eea7; files: src/agents/compaction.ts, packages/agent-core/src/harness/compaction/compaction.ts, packages/agent-core/src/harness/compaction/utils.ts)

Codex review notes: model internal, reasoning high; reviewed against de30d2f5c333.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. labels Jul 6, 2026
@maweibin maweibin closed this Jul 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XS status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: summarizeInStages drops original message metadata and context bindings during summary merge passes

1 participant