From 057a82ff422fedb91a4c9f38fa60d1dfc9d47c23 Mon Sep 17 00:00:00 2001 From: Lucky <204641331+flyto168@users.noreply.github.com> Date: Tue, 13 Oct 2026 11:10:30 +0800 Subject: [PATCH] fix(memorize): drop re-posted messages that are already in a memcell 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 --- scripts/backfill_memorized_messages.py | 46 +++++++++++ .../infra/persistence/sqlite/__init__.py | 2 + .../persistence/sqlite/repos/__init__.py | 2 + .../sqlite/repos/memorized_message.py | 81 +++++++++++++++++++ .../persistence/sqlite/tables/__init__.py | 2 + .../sqlite/tables/memorized_message.py | 25 ++++++ src/everos/service/_boundary.py | 48 +++++++++++ .../test_memorize_window_segmentation.py | 59 ++++++++++++++ 8 files changed, 265 insertions(+) create mode 100644 scripts/backfill_memorized_messages.py create mode 100644 src/everos/infra/persistence/sqlite/repos/memorized_message.py create mode 100644 src/everos/infra/persistence/sqlite/tables/memorized_message.py diff --git a/scripts/backfill_memorized_messages.py b/scripts/backfill_memorized_messages.py new file mode 100644 index 000000000..f834fcde2 --- /dev/null +++ b/scripts/backfill_memorized_messages.py @@ -0,0 +1,46 @@ +"""One-off backfill for the ``memorized_message`` local patch. + +Records the timestamp of every message already inside a memcell, so the first +re-post after deploying the patch is deduped too. Run with the daemon stopped +(it creates the table if missing; re-running is harmless): + + .venv/bin/python scripts/backfill_memorized_messages.py +""" + +from __future__ import annotations + +import json +import sqlite3 +import sys + +from sqlalchemy import create_engine + +from everos.infra.persistence.sqlite.tables import MemorizedMessage + + +def main(db_path: str) -> None: + MemorizedMessage.__table__.create( # type: ignore[attr-defined] + create_engine(f"sqlite:///{db_path}"), checkfirst=True + ) + conn = sqlite3.connect(db_path) + before = conn.execute("SELECT count(*) FROM memorized_message").fetchone()[0] + cells = 0 + rows: set[tuple[str, str, str, int]] = set() + for app_id, project_id, session_id, payload in conn.execute( + "SELECT app_id, project_id, session_id, payload_json FROM memcell" + ): + cells += 1 + for item in json.loads(payload).get("items", []): + rows.add((app_id, project_id, session_id, int(item["timestamp"]))) + with conn: + conn.executemany( + "INSERT OR IGNORE INTO memorized_message " + "(app_id, project_id, session_id, timestamp_ms) VALUES (?, ?, ?, ?)", + rows, + ) + after = conn.execute("SELECT count(*) FROM memorized_message").fetchone()[0] + print(f"memcells={cells} timestamps={len(rows)} rows {before} -> {after}") + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/src/everos/infra/persistence/sqlite/__init__.py b/src/everos/infra/persistence/sqlite/__init__.py index 57ecb6b69..79244ad50 100644 --- a/src/everos/infra/persistence/sqlite/__init__.py +++ b/src/everos/infra/persistence/sqlite/__init__.py @@ -42,6 +42,7 @@ from .repos import knowledge_topic_sqlite_repo as knowledge_topic_sqlite_repo from .repos import md_change_state_repo as md_change_state_repo from .repos import memcell_repo as memcell_repo +from .repos import memorized_message_repo as memorized_message_repo from .repos import mint_cluster_id as mint_cluster_id from .repos import reflection_report_repo as reflection_report_repo from .repos import unprocessed_buffer_repo as unprocessed_buffer_repo @@ -82,6 +83,7 @@ "knowledge_topic_sqlite_repo", "md_change_state_repo", "memcell_repo", + "memorized_message_repo", "mint_cluster_id", "reflection_report_repo", "unprocessed_buffer_repo", diff --git a/src/everos/infra/persistence/sqlite/repos/__init__.py b/src/everos/infra/persistence/sqlite/repos/__init__.py index 9a656fda6..e8147a47a 100644 --- a/src/everos/infra/persistence/sqlite/repos/__init__.py +++ b/src/everos/infra/persistence/sqlite/repos/__init__.py @@ -16,6 +16,7 @@ from .md_change_state import QueueSummary as QueueSummary from .md_change_state import md_change_state_repo as md_change_state_repo from .memcell import memcell_repo as memcell_repo +from .memorized_message import memorized_message_repo as memorized_message_repo from .reflection_report import reflection_report_repo as reflection_report_repo from .unprocessed_buffer import unprocessed_buffer_repo as unprocessed_buffer_repo @@ -31,6 +32,7 @@ "knowledge_topic_sqlite_repo", "md_change_state_repo", "memcell_repo", + "memorized_message_repo", "mint_cluster_id", "reflection_report_repo", "unprocessed_buffer_repo", diff --git a/src/everos/infra/persistence/sqlite/repos/memorized_message.py b/src/everos/infra/persistence/sqlite/repos/memorized_message.py new file mode 100644 index 000000000..c41a1daf9 --- /dev/null +++ b/src/everos/infra/persistence/sqlite/repos/memorized_message.py @@ -0,0 +1,81 @@ +"""Repository for ``memorized_message`` (local patch) — see the table module.""" + +from __future__ import annotations + +from collections.abc import Iterable + +from sqlalchemy import select +from sqlalchemy.dialects.sqlite import insert +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker + +from everos.core.persistence.sqlite import RepoBase, session_scope + +from ..sqlite_manager import get_session_factory +from ..tables import MemorizedMessage + +_SQLITE_IN_CHUNK = 500 +"""Keeps ``IN (...)`` under SQLite's default 999-variable cap.""" + + +class _MemorizedMessageRepo(RepoBase[MemorizedMessage]): + model = MemorizedMessage + + def _factory_lookup(self) -> async_sessionmaker[AsyncSession]: + return get_session_factory() + + async def find_memorized( + self, + session_id: str, + timestamps_ms: Iterable[int], + *, + app_id: str, + project_id: str, + ) -> set[int]: + """Return the subset of ``timestamps_ms`` already in a memcell.""" + wanted = sorted(set(timestamps_ms)) + found: set[int] = set() + async with session_scope(self._factory) as s: + for start in range(0, len(wanted), _SQLITE_IN_CHUNK): + chunk = wanted[start : start + _SQLITE_IN_CHUNK] + rows = await s.execute( + select(MemorizedMessage.timestamp_ms).where( + MemorizedMessage.app_id == app_id, + MemorizedMessage.project_id == project_id, + MemorizedMessage.session_id == session_id, + MemorizedMessage.timestamp_ms.in_(chunk), # type: ignore[attr-defined] + ) + ) + found.update(rows.scalars().all()) + return found + + async def record( + self, + session_id: str, + timestamps_ms: Iterable[int], + *, + app_id: str, + project_id: str, + ) -> None: + """Insert-or-ignore one row per timestamp.""" + values = [ + { + "app_id": app_id, + "project_id": project_id, + "session_id": session_id, + "timestamp_ms": ts, + } + for ts in sorted(set(timestamps_ms)) + ] + if not values: + return + async with session_scope(self._factory) as s: + for start in range(0, len(values), _SQLITE_IN_CHUNK // 4): + await s.execute( + insert(MemorizedMessage) + .values(values[start : start + _SQLITE_IN_CHUNK // 4]) + .on_conflict_do_nothing() + ) + await s.commit() + + +memorized_message_repo = _MemorizedMessageRepo() diff --git a/src/everos/infra/persistence/sqlite/tables/__init__.py b/src/everos/infra/persistence/sqlite/tables/__init__.py index 39d7bd375..45f22a4ba 100644 --- a/src/everos/infra/persistence/sqlite/tables/__init__.py +++ b/src/everos/infra/persistence/sqlite/tables/__init__.py @@ -14,6 +14,7 @@ from .knowledge import KnowledgeTopicRow as KnowledgeTopicRow from .md_change_state import MdChangeState as MdChangeState from .memcell import Memcell as Memcell +from .memorized_message import MemorizedMessage as MemorizedMessage from .reflection_report import ReflectionReport as ReflectionReport from .unprocessed_buffer import UnprocessedBuffer as UnprocessedBuffer @@ -25,6 +26,7 @@ "KnowledgeTopicRow", "MdChangeState", "Memcell", + "MemorizedMessage", "ReflectionReport", "UnprocessedBuffer", ] diff --git a/src/everos/infra/persistence/sqlite/tables/memorized_message.py b/src/everos/infra/persistence/sqlite/tables/memorized_message.py new file mode 100644 index 000000000..3a9ecfc78 --- /dev/null +++ b/src/everos/infra/persistence/sqlite/tables/memorized_message.py @@ -0,0 +1,25 @@ +"""``memorized_message`` — timestamps of messages already carved into a memcell. + +Local patch. Clients may re-post a session's whole visible transcript on every +turn (the OpenClaw plugin does, on ``agent_end``). Once a message is in a +memcell it has left ``unprocessed_buffer``, so the buffer's ``message_id`` PK +can no longer dedupe it, and ``message_id`` itself is not stable across +re-posts (its ``_idx`` is the position inside the request). The message +timestamp is stable, so ingest drops any message whose +``(app, project, session, timestamp_ms)`` is recorded here. +""" + +from __future__ import annotations + +from sqlmodel import Field, SQLModel + + +class MemorizedMessage(SQLModel, table=True): + """One row per message timestamp already inside a memcell of a session.""" + + __tablename__ = "memorized_message" # type: ignore[assignment] + + app_id: str = Field(primary_key=True) + project_id: str = Field(primary_key=True) + session_id: str = Field(primary_key=True) + timestamp_ms: int = Field(primary_key=True) diff --git a/src/everos/service/_boundary.py b/src/everos/service/_boundary.py index 0aa330e1b..71aa8aa9a 100644 --- a/src/everos/service/_boundary.py +++ b/src/everos/service/_boundary.py @@ -48,6 +48,7 @@ UnprocessedBuffer, conversation_status_repo, memcell_repo, + memorized_message_repo, unprocessed_buffer_repo, ) from everos.memory import CanonicalMessage, IngestResult, ToolCall @@ -110,6 +111,9 @@ async def buffer_messages(ingested: IngestResult, *, mode: Mode) -> BoundaryOutc ingested.session_id, _TRACK, app_id=app_id, project_id=project_id ) buffered = [_row_to_canonical(row) for row in buffer_rows] + fresh = await _drop_already_seen(ingested, fresh, buffered) + if not fresh: + return _empty_outcome(status="skipped", message_count=0) merged = _merge_dedupe_sort(buffered, fresh) await _replace_buffer(ingested.session_id, merged, app_id, project_id) await _touch_last_message_ts(ingested.session_id, merged, app_id, project_id) @@ -137,6 +141,9 @@ async def prepare_cells( ingested.session_id, _TRACK, app_id=app_id, project_id=project_id ) buffered = [_row_to_canonical(r) for r in buffer_rows] + fresh = await _drop_already_seen(ingested, fresh, buffered) + if not fresh and not is_final: + return _empty_outcome(status="skipped", message_count=0) merged = _merge_dedupe_sort(buffered, fresh) if not merged: return _empty_outcome(status="accumulated", message_count=0) @@ -197,6 +204,12 @@ async def prepare_cells( for i, (cell, memcell_id) in enumerate(zip(cells, memcell_ids, strict=True)) ] await memcell_repo.insert_many(rows) + await memorized_message_repo.record( + ingested.session_id, + (item.timestamp for cell in cells for item in cell.items), + app_id=app_id, + project_id=project_id, + ) last_cell_ts = max((cell.timestamp for cell in cells), default=0) if last_cell_ts: @@ -439,6 +452,41 @@ def _row_to_canonical(r: UnprocessedBuffer) -> CanonicalMessage: # ── Merge / split / sender helpers ──────────────────────────────────────── +async def _drop_already_seen( + ingested: IngestResult, + fresh: list[CanonicalMessage], + buffered: list[CanonicalMessage], +) -> list[CanonicalMessage]: + """Local patch: drop re-posted messages before they reach a memcell again. + + A message counts as seen when its timestamp is already in the buffer or + recorded in ``memorized_message``. Matching is by timestamp, not + ``message_id``: the id embeds the message's position in the request, which + shifts when a client re-posts a different slice of the same transcript. + Late messages carrying an old timestamp (e.g. routed inter-session + 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 + seen |= await memorized_message_repo.find_memorized( + ingested.session_id, + candidates, + app_id=ingested.app_id, + project_id=ingested.project_id, + ) + kept = [m for m in fresh if to_timestamp_ms(m.timestamp) not in seen] + if len(kept) < len(fresh): + logger.info( + "memorize_resent_messages_dropped", + extra={ + "session_id": ingested.session_id, + "dropped": len(fresh) - len(kept), + "kept": len(kept), + }, + ) + return kept + + def _merge_dedupe_sort( buffered: list[CanonicalMessage], new: list[CanonicalMessage], diff --git a/tests/integration/test_memorize_window_segmentation.py b/tests/integration/test_memorize_window_segmentation.py index 705b68e82..b619486aa 100644 --- a/tests/integration/test_memorize_window_segmentation.py +++ b/tests/integration/test_memorize_window_segmentation.py @@ -432,3 +432,62 @@ async def test_three_sequential_adds_conservation_no_loss( ) # Disjoint assert not (in_cells & in_buffer) + + +# --------------------------------------------------------------------------- +# Local patch: re-sent history must not be memorized twice +# --------------------------------------------------------------------------- + + +def _ts_of(message_id: str) -> int: + return int(message_id.rsplit("_", 2)[1]) + + +async def test_resent_history_is_not_memorized_again( + memorize_env_scripted: Callable[..., AsyncMock], +) -> None: + """The OpenClaw plugin re-posts the whole visible transcript on every + agent_end. Messages already in a memcell left the buffer, so the buffer's + message_id PK no longer dedupes them; on 2026-10-13 each message landed in + ~35 memcells. Round 2 here re-sends from m1 instead of m0, so the + positional ``_idx`` shifts and the same messages get NEW message_ids.""" + # Round 1: [m0,m1,m2], cut after 2 → cell=[m0,m1], buffer=[m2] + # Round 2: re-send [m1,m2] + new [m3,m4]; only m3,m4 are fresh → + # merged=[m2,m3,m4], cut after 2 → cell=[m2,m3], buffer=[m4] + await memorize_env_scripted(fake_llm=_make_scripted_llm([[2], [2]])) + + session = "s_resend" + await memorize({"session_id": session, "messages": [_msg(i) for i in range(3)]}) + await memorize({"session_id": session, "messages": [_msg(i) for i in range(1, 5)]}) + + cells = await _memcell_rows(session) + buffer = await _buffer_rows(session) + + cell_ts = [_ts_of(mid) for _, ids in cells for mid in ids] + assert len(cell_ts) == len(set(cell_ts)), f"a message was memorized twice: {cells}" + assert len(cells) == 2, cells + assert {_ts_of(mid) for mid in cells[1][1]} == { + _BASE_TS + 2000, + _BASE_TS + 3000, + } + assert [ts for _, ts in buffer] == [_BASE_TS + 4000] + + +async def test_late_message_with_old_timestamp_is_kept( + memorize_env_scripted: Callable[..., AsyncMock], +) -> None: + """Routed inter-session messages arrive after later turns were memorized + but carry their original (older) timestamp. A high-water mark would drop + them; the per-timestamp record keeps them.""" + # Round 1: [m0,m2,m3], cut after 2 → cell=[m0,m2], buffer=[m3] + # Round 2: re-send all plus the late m1 → only m1 is fresh; + # no cut → buffer=[m1,m3] + await memorize_env_scripted(fake_llm=_make_scripted_llm([[2], []])) + + session = "s_late" + await memorize({"session_id": session, "messages": [_msg(i) for i in (0, 2, 3)]}) + await memorize({"session_id": session, "messages": [_msg(i) for i in range(4)]}) + + buffer = await _buffer_rows(session) + assert [ts for _, ts in buffer] == [_BASE_TS + 1000, _BASE_TS + 3000] + assert len(await _memcell_rows(session)) == 1