Repository navigation
fix(memorize): 丢弃已存在于 memcell 的重复转发消息 #495
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 <path/to/system.db> | ||
| """ | ||
|
|
||
| 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]) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |= 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], | ||
|
|
||
There was a problem hiding this comment.
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, andrecord()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. Currentmain'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.