Skip to content

fix(memorize): 丢弃已存在于 memcell 的重复转发消息 - #495

Closed
flyto168 wants to merge 1 commit into
EverMind-AI:mainfrom
flyto168:feature/memorize-dedup-reposted
Closed

flyto168 wants to merge 1 commit into
EverMind-AI:mainfrom
flyto168:feature/memorize-dedup-reposted

Conversation

@flyto168

@flyto168 flyto168 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

问题

同一条消息被重复投递时(聊天平台重发/重试),memorize 流程会把它当作新消息再次处理,产生重复的 memcell 内容。

改法

  • 新增 sqlite memorized_message 表与仓库:已在某 memcell 中的重复转发消息在进入 memorize 前被识别并丢弃。
  • 边界检测(boundary detection)接入该去重判断。

验证

  • memory 套件 750 passed(含新增 test_memorize_window_segmentation 覆盖);Ruff check/format 通过。
  • 基于上游 main @ a345d08,仅 8 文件。

范围

仅含通用修复与测试,不含本地环境文件。

The OpenClaw plugin re-posts a session's whole visible transcript on every
agent_end. A message that was already carved into a memcell has left
unprocessed_buffer, so the buffer's message_id PK no longer dedupes it, and
message_id is not stable anyway (its _idx is the position in the request).
Since 2026-10-07 each message landed in 5-18 memcells (35x for the main
session on 2026-10-13), atomic_fact grew from ~3k to ~34k rows a day, and
the derived load (unindexed rows, slow searches, cascade diffs) drove the
daemon into MemoryHigh repeatedly.

A new memorized_message table records (app, project, session, timestamp_ms)
for every item written into a memcell. buffer_messages and prepare_cells
drop fresh messages whose timestamp is already buffered or recorded before
boundary detection, so duplicates cost no LLM call either. Matching on the
timestamp keeps late routed messages that carry an older, never-memorized
timestamp (a high-water mark would have dropped 74 of them since 10-07).
Replaying 10-07..10-13 history: 84% of memcell items dropped, 0 duplicates
left among the kept ones.

scripts/backfill_memorized_messages.py seeds the table from existing
memcells (14,119 memcells -> 134,496 timestamps in ~9 s; idempotent).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@flyto168 flyto168 changed the title fix(memorize): drop re-posted messages that are already in a memcell fix(memorize): 丢弃已存在于 memcell 的重复转发消息 Oct 13, 2026
@gloryfromca

Copy link
Copy Markdown
Member

This PR will stay out of the current batch. For the next revision, please keep the scope focused on retry deduplication:

  1. Keep deduplication independent of the input log (memory: keep a raw input log of /add requests, independent of extraction #537). They should use a consistent message identity for tracing, but deduplication must not depend on input-log availability or retention. There is no need to implement the input log in this PR.
  2. Define and test message identity. The current (app_id, project_id, session_id, timestamp_ms) key can treat different messages with the same timestamp as duplicates. Please cover both a resent message whose position in the request changes and distinct messages sharing a timestamp.
  3. Integrate the deduplication record with the transaction introduced in fix(storage): make session writes atomic under contention #579. Creating memcells and recording their messages as processed should commit or roll back together. The current separate commits leave a failure window in which a memcell exists but its deduplication record does not.

Before revising the implementation, please reproduce #274 on the latest main and establish a regression test there; its applicability to the current main has not yet been reverified. Then update this branch against main and keep the fix scoped to the confirmed behavior. #274 remains open.

@gloryfromca gloryfromca left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Blocking: define a collision-safe message identity, make dedup recording atomic with the session cut, and rebase onto current main.

I independently reproduced the identity failure: with one buffered message, a different incoming message at the same millisecond is logged as dropped and kept_ids is empty. The added integration tests pass but do not cover this required case. I also traced the write sequence: memcells, the dedup ledger, status, and the tail buffer are separate commits, so failures can either permit duplicate memcells on retry or suppress work that never reached downstream extraction. Current main includes #579's atomic session-cut transaction; the ledger needs to participate in that same transaction.

This head is still based on a345d08; current main is 80ef766 and a merge-tree check reports conflicts in the SQLite facade/tables/repos and the deleted service/_boundary.py, so this revision cannot currently be integrated. The requested latest-main #274 regression test is also not present yet. Dedup remains independent of #537's input log, which is correct.

Validation: 2,678 unit tests passed (4 skipped); 188 integration tests passed (7 skipped, 7 deselected); the focused segmentation file passed 7/7; Ruff check/format, import contracts, repository checks, datetime discipline, OpenAPI drift, and git diff --check passed. (make is unavailable in this environment, so I ran the Makefile's lint and test commands directly.)

Covered: repository rules, the full diff, callers and persistence flow, relevant history/current main, backward compatibility and upgrade behavior, test quality (including the missing collision case), architecture constraints, and the complete existing discussion.

messages) are kept, because their timestamp was never memorized.
"""
seen = {to_timestamp_ms(m.timestamp) for m in buffered}
candidates = {to_timestamp_ms(m.timestamp) for m in fresh} - seen

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Blocking: timestamp-only identity can discard distinct messages that share a timestamp.

seen collapses identity to milliseconds. A concrete ordinary sequence is: message A is already buffered, then distinct message B arrives in the same session with the same timestamp; B is removed here before _merge_dedupe_sort, even though its sender/content/role and generated ID differ. I reproduced exactly that sequence and got kept_ids: []. The persisted table and backfill have the same collision, so the identity must distinguish such messages while remaining stable when request position changes, and the regression coverage needs both scenarios.

for i, (cell, memcell_id) in enumerate(zip(cells, memcell_ids, strict=True))
]
await memcell_repo.insert_many(rows)
await memorized_message_repo.record(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Blocking: commit the memcell and its dedup identity in the same session-cut transaction.

insert_many() commits before this call, and record() commits before the later status/buffer writes. If this call fails, the memcell exists while the old buffer remains and a retry can create another memcell. If a later write fails after this succeeds, a retry sees the ledger entry and drops messages whose boundary outcome never reached downstream extraction. Current main's #579 session-cut transaction exists specifically to make the memcell/status/tail update atomic; include the dedup rows in that transaction and test rollback at the failure boundaries.

@gloryfromca

Copy link
Copy Markdown
Member

Closing in favour of #609, which fixes #274 along the lines of the review above. Message ids no longer depend on a message's position in the request. The memcell rows serve as the dedup record and are written in the same transaction as the cut. It also adds regression tests reproduced on current main. Thank you @flyto168 for the original work; #609 credits this PR.

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