Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions scripts/backfill_memorized_messages.py
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])
2 changes: 2 additions & 0 deletions src/everos/infra/persistence/sqlite/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down
2 changes: 2 additions & 0 deletions src/everos/infra/persistence/sqlite/repos/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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",
Expand Down
81 changes: 81 additions & 0 deletions src/everos/infra/persistence/sqlite/repos/memorized_message.py
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()
2 changes: 2 additions & 0 deletions src/everos/infra/persistence/sqlite/tables/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -25,6 +26,7 @@
"KnowledgeTopicRow",
"MdChangeState",
"Memcell",
"MemorizedMessage",
"ReflectionReport",
"UnprocessedBuffer",
]
25 changes: 25 additions & 0 deletions src/everos/infra/persistence/sqlite/tables/memorized_message.py
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)
48 changes: 48 additions & 0 deletions src/everos/service/_boundary.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
UnprocessedBuffer,
conversation_status_repo,
memcell_repo,
memorized_message_repo,
unprocessed_buffer_repo,
)
from everos.memory import CanonicalMessage, IngestResult, ToolCall
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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(

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.

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:
Expand Down Expand Up @@ -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

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.

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],
Expand Down
59 changes: 59 additions & 0 deletions tests/integration/test_memorize_window_segmentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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