From 629c589b22f66deb5ce8e1f526e20964c59c20fc Mon Sep 17 00:00:00 2001 From: zhanghui <23442919+gloryfromca@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:39:59 +0800 Subject: [PATCH 1/3] fix(memorize): drop resent messages a memcell already holds A client that retries /memory/add after a timeout resends messages the first call may have cut into a memcell. Deduplication only looked at the session buffer, which a cut empties, so the retry cut them again: a second memcell and episode with the same messages (#274). The boundary stage now drops fresh messages that a memcell of the session already lists. The memcell rows are the record: the cut inserts them in the same transaction that empties the buffer, and a session delete removes them, so no new table or extra write is needed. Message ids no longer depend on where a message sits in its request: m____, n counting the request's messages that share the timestamp (so they keep their order) and digest covering sender_id, role, content, tool_call_id and tool_calls. A regrouped resend keeps its ids, and two different messages sent in separate requests with one timestamp no longer share an id (the second used to be dropped). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 15 +++++ docs/api.md | 12 ++++ .../persistence/sqlite/_repos/session_cut.py | 34 ++++++++++- src/everos/infra/persistence/sqlite/stores.py | 11 ++++ .../memory/extract/boundary/detection.py | 38 +++++++++++- src/everos/memory/extract/ingest/__init__.py | 6 +- src/everos/memory/extract/ingest/id_gen.py | 41 ++++++++++--- src/everos/memory/extract/ingest/service.py | 9 ++- src/everos/memory/ports/stores.py | 6 ++ tests/integration/test_memorize_agent_mode.py | 4 +- .../test_memorize_window_segmentation.py | 59 ++++++++++++++++++- .../test_infra/test_sqlite/test_stores.py | 17 ++++++ .../test_boundary/test_quarantine.py | 45 ++++++++------ .../test_extract/test_ingest/test_id_gen.py | 34 +++++++++++ .../test_properties/test_boundary_stateful.py | 23 +++++--- 15 files changed, 304 insertions(+), 50 deletions(-) create mode 100644 tests/unit/test_memory/test_extract/test_ingest/test_id_gen.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c47a032b..919e0449c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -141,6 +141,21 @@ unchanged apart from additions. See Upgrade below. of the ingest identity, so a store ingested with an earlier config is not reused. +### Fixed + +- **A resent `/memory/add` no longer cuts the same messages twice** (#274). + Messages were deduplicated only against the session buffer, so a client + retrying after a timeout re-sent messages the first call had already cut + into a memory cell, and they became a second memcell and episode. The + boundary stage now drops fresh messages a memcell of the session already + holds. Message ids no longer depend on the message's position in the + request: `m____`, where `n` counts the + request's messages sharing that timestamp and `digest` covers who said what, + so a regrouped resend keeps its ids and two different messages sent in + separate requests with one timestamp are no longer merged into one. + Buffered messages from an earlier version keep their old ids; a batch sent + before the upgrade and resent after it is not recognized as a resend. + ### Removed - **Foresight.** The `extract_foresight` strategy (off by default since diff --git a/docs/api.md b/docs/api.md index a2f7d65a9..6cfd6bb3a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -606,6 +606,18 @@ correlation. LLM ran extraction and the writers persisted at least one memory cell. The buffer is empty after the call returns. +**Resending a batch.** A client that retries `/add` after a timeout may +resend messages the first call already processed. A message's identity is +its session, its `timestamp`, its place among the request's messages with +that same `timestamp`, and what was said by whom (`sender_id`, `role`, +`content`, `tool_call_id`, `tool_calls`); `sender_name` is not part of it. +A resent message that is still buffered, or already part of a memory cell +of the session, is dropped, so a retry (whole, split or regrouped) never +writes it twice and answers `200` (`"accumulated"` when it cut nothing +new). Two different messages with one `timestamp` are both kept. After the +session's memories are deleted (`/memory/delete` with its `session_id`), a +resend is memorized again. + `202 Accepted` — only with `async_mode`, or when the session already has queued batches (see [Asynchronous mode](#asynchronous-mode)) — returns a SuccessEnvelope wrapping: diff --git a/src/everos/infra/persistence/sqlite/_repos/session_cut.py b/src/everos/infra/persistence/sqlite/_repos/session_cut.py index 6c17c19a3..6ea074011 100644 --- a/src/everos/infra/persistence/sqlite/_repos/session_cut.py +++ b/src/everos/infra/persistence/sqlite/_repos/session_cut.py @@ -13,7 +13,7 @@ import datetime as dt from collections.abc import Sequence -from sqlalchemy import delete, insert, update +from sqlalchemy import bindparam, delete, insert, text, update from sqlalchemy.ext.asyncio import AsyncSession from everos.core.utils.datetime import get_utc_now @@ -68,6 +68,38 @@ async def cut( await _replace_buffer(s, keys, tail) await s.commit() + async def already_cut( + self, + session_id: str, + track: str, + message_ids: Sequence[str], + *, + app_id: str, + project_id: str, + ) -> set[str]: + """Which of ``message_ids`` a memcell of the (session, track) holds. + + The memcells a cut inserts are its record of what it consumed, in the + same transaction, so a message is "already cut" exactly when one of + them lists it. + """ + if not message_ids: + return set() + # ponytail: scans the session's memcells; a (session, message_id) + # table if one session ever holds enough memcells for this to show. + stmt = text( + "SELECT DISTINCT j.value FROM memcell AS m, " + "json_each(m.message_ids_json) AS j " + "WHERE m.app_id = :app_id AND m.project_id = :project_id " + "AND m.session_id = :session_id AND m.track = :track " + "AND j.value IN :ids" + ).bindparams(bindparam("ids", expanding=True)) + params = _keys(app_id, project_id, session_id, track) | { + "ids": list(message_ids) + } + async with session_scope(self._factory) as s: + return set((await s.execute(stmt, params)).scalars()) + def _keys(app_id: str, project_id: str, session_id: str, track: str) -> dict[str, str]: return { diff --git a/src/everos/infra/persistence/sqlite/stores.py b/src/everos/infra/persistence/sqlite/stores.py index 81ef5109a..035f24d16 100644 --- a/src/everos/infra/persistence/sqlite/stores.py +++ b/src/everos/infra/persistence/sqlite/stores.py @@ -137,6 +137,17 @@ async def quarantine( project_id=session.project_id, ) + async def already_cut( + self, session: SessionKey, message_ids: Sequence[str] + ) -> set[str]: + return await self._cut.already_cut( + session.session_id, + _SESSION_TRACK, + message_ids, + app_id=session.app_id, + project_id=session.project_id, + ) + class SqliteMemcellStore: """Memcells over the ``memcell`` table. diff --git a/src/everos/memory/extract/boundary/detection.py b/src/everos/memory/extract/boundary/detection.py index 813c63c85..6c6f89dc1 100644 --- a/src/everos/memory/extract/boundary/detection.py +++ b/src/everos/memory/extract/boundary/detection.py @@ -36,6 +36,7 @@ from everalgo.types import ChatMessage, ConversationItem, MemCell from everos.config import BoundaryDetectionSettings +from everos.core.observability.logging import get_logger from everos.core.observability.tracing import memory_span from everos.core.utils.datetime import from_timestamp from everos.memory.custom_instructions import CustomInstructions @@ -54,6 +55,8 @@ ) from .quarantine import SessionQuarantine +logger = get_logger(__name__) + type Status = Literal["accumulated", "extracted", "skipped"] _RAW_TYPE_BY_MODE: dict[Mode, str] = { @@ -158,7 +161,11 @@ async def buffer(self, ingested: IngestResult, *, mode: Mode) -> BoundaryOutcome if not fresh: return _empty_outcome("skipped", message_count=0) session = _session_of(ingested) - merged = merge_dedupe_sort(await self._session_buffer.list(session), fresh) + buffered = await self._session_buffer.list(session) + fresh = await self._not_yet_cut(session, fresh, buffered) + if not fresh: + return _empty_outcome("skipped", message_count=0) + merged = merge_dedupe_sort(buffered, fresh) await self._keep_buffered(session, merged) return _empty_outcome("accumulated", message_count=len(fresh)) @@ -191,6 +198,9 @@ async def detect( if not fresh and not is_final: return _empty_outcome("skipped", message_count=0) buffered = await self._session_buffer.list(session) + fresh = await self._not_yet_cut(session, fresh, buffered) + if not fresh and not is_final: + return _empty_outcome("skipped", message_count=0) merged = merge_dedupe_sort(buffered, fresh) if not merged: return _empty_outcome("accumulated", message_count=0) @@ -208,6 +218,32 @@ async def detect( session, result, mode=mode, message_count=len(fresh) ) + async def _not_yet_cut( + self, + session: SessionKey, + fresh: list[CanonicalMessage], + buffered: Sequence[CanonicalMessage], + ) -> list[CanonicalMessage]: + """``fresh`` without the messages a memcell of the session already holds. + + A client that resends a batch after a timeout sends messages the first + call may have cut already; those left the buffer, so the merge alone + would cut them a second time. A buffered message is kept: the tail + may share rows with the last cell. + """ + held = {m.message_id for m in buffered} + cut = await self._session_buffer.already_cut( + session, [m.message_id for m in fresh if m.message_id not in held] + ) + if not cut: + return fresh + logger.info( + "boundary_resent_messages_dropped", + session_id=session.session_id, + count=len(cut), + ) + return [m for m in fresh if m.message_id not in cut] + async def _segment_or_quarantine( self, session: SessionKey, diff --git a/src/everos/memory/extract/ingest/__init__.py b/src/everos/memory/extract/ingest/__init__.py index 149360bbe..2dd1da36d 100644 --- a/src/everos/memory/extract/ingest/__init__.py +++ b/src/everos/memory/extract/ingest/__init__.py @@ -1,17 +1,17 @@ """Ingest Gateway — normalise external input into canonical form. External usage: - from everos.memory.extract.ingest import process, gen_message_id + from everos.memory.extract.ingest import process, message_ids The current implementation only handles text content; non-text ``ContentItem`` entries are dropped with a warning. The parser hook (``memory/extract/parser/``) is reserved for future milestones. """ -from .id_gen import gen_message_id as gen_message_id +from .id_gen import message_ids as message_ids from .service import process as process __all__ = [ - "gen_message_id", + "message_ids", "process", ] diff --git a/src/everos/memory/extract/ingest/id_gen.py b/src/everos/memory/extract/ingest/id_gen.py index a88c91968..1fbd58b36 100644 --- a/src/everos/memory/extract/ingest/id_gen.py +++ b/src/everos/memory/extract/ingest/id_gen.py @@ -1,17 +1,42 @@ """Deterministic, human-readable ``message_id`` generation. -Format: ``m___``. +Format: ``m____``. -Human-readable so logs / debugging / md entries stay greppable. Deterministic -so caller retries (same payload) produce the same ids — pipeline merge -naturally dedupes via the message_id PK in ``unprocessed_buffer``. +- ``nth`` counts the messages of one request that share the timestamp, in + request order, so those keep their order when rows sort by + ``(timestamp, message_id)``. +- ``digest`` is 8 hex chars of SHA-256 over who said what (``sender_id``, + ``role``, ``content``, ``tool_call_id``, ``tool_calls``), so two different + messages sent in separate requests with the same millisecond get two ids. + +Neither part depends on where the message sits in its request, so a client +that resends a batch -- whole, split or regrouped -- produces the same ids, +and the boundary stage drops what it already buffered or cut. """ from __future__ import annotations -_IDX_PAD = 3 # caller batches are capped at 500 messages (DTO limit), 3 digits cover it +import hashlib +import json +from collections import Counter +from collections.abc import Mapping, Sequence +from typing import Any + +_IDENTITY_FIELDS = ("sender_id", "role", "content", "tool_call_id", "tool_calls") + + +def _digest(message: Mapping[str, Any]) -> str: + basis = [message.get(field) for field in _IDENTITY_FIELDS] + raw = json.dumps(basis, sort_keys=True, ensure_ascii=False, default=str) + return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:8] -def gen_message_id(session_id: str, timestamp_ms: int, idx: int) -> str: - """Return ``m___``.""" - return f"m_{session_id}_{timestamp_ms}_{idx:0{_IDX_PAD}d}" +def message_ids(session_id: str, messages: Sequence[Mapping[str, Any]]) -> list[str]: + """The id of each message of one request, in order.""" + nth: Counter[int] = Counter() + ids = [] + for message in messages: + ts_ms = int(message["timestamp"]) + ids.append(f"m_{session_id}_{ts_ms}_{nth[ts_ms]:03d}_{_digest(message)}") + nth[ts_ms] += 1 + return ids diff --git a/src/everos/memory/extract/ingest/service.py b/src/everos/memory/extract/ingest/service.py index acbfe5283..548e93534 100644 --- a/src/everos/memory/extract/ingest/service.py +++ b/src/everos/memory/extract/ingest/service.py @@ -35,7 +35,7 @@ require_multimodal, ) -from .id_gen import gen_message_id +from .id_gen import message_ids from .multimodal import coerce_items, derive_text from .sender_names import resolve_sender_names, sender_name_of @@ -75,7 +75,8 @@ async def process( canonical: list[CanonicalMessage] = [] non_text_total = 0 - for idx, m in enumerate(raw_messages): + ids = message_ids(session_id, raw_messages) + for m, message_id in zip(raw_messages, ids, strict=True): content_items = coerce_items(m["content"]) if has_unparsed_multimodal(content_items): require_multimodal() @@ -88,9 +89,7 @@ async def process( text, non_text = derive_text(content_items) non_text_total += non_text - ts_ms: int = int(m["timestamp"]) - message_id = gen_message_id(session_id, ts_ms, idx) - ts = from_timestamp(ts_ms) + ts = from_timestamp(int(m["timestamp"])) canonical.append( CanonicalMessage( diff --git a/src/everos/memory/ports/stores.py b/src/everos/memory/ports/stores.py index 8ee62e352..b6e33c893 100644 --- a/src/everos/memory/ports/stores.py +++ b/src/everos/memory/ports/stores.py @@ -359,6 +359,12 @@ async def quarantine( """Set the buffer (plus ``extra``) aside; return how many moved.""" ... + async def already_cut( + self, session: SessionKey, message_ids: Sequence[str] + ) -> set[str]: + """Which of ``message_ids`` a memcell of the session already holds.""" + ... + @runtime_checkable class MemcellStore(Protocol): diff --git a/tests/integration/test_memorize_agent_mode.py b/tests/integration/test_memorize_agent_mode.py index da4f6f783..78589c313 100644 --- a/tests/integration/test_memorize_agent_mode.py +++ b/tests/integration/test_memorize_agent_mode.py @@ -30,7 +30,7 @@ from everos.infra.ome.records import RunStatus from everos.infra.persistence import MemoryRoot -from everos.memory.extract.ingest.id_gen import gen_message_id +from everos.memory.extract.ingest import message_ids from everos.service import ( MemorizeResult, build_application, @@ -251,7 +251,7 @@ async def test_agent_mode_cut_files_each_tool_row_with_its_segment( ) assert result.status == "extracted" - ids = [gen_message_id(session, m["timestamp"], i) for i, m in enumerate(messages)] + ids = message_ids(session, messages) cells = [json.loads(row["message_ids_json"]) for row in _memcell_rows(tmp_path)] assert cells == [ids[:4], ids[4:]] diff --git a/tests/integration/test_memorize_window_segmentation.py b/tests/integration/test_memorize_window_segmentation.py index f680135b4..d6aeaa283 100644 --- a/tests/integration/test_memorize_window_segmentation.py +++ b/tests/integration/test_memorize_window_segmentation.py @@ -45,6 +45,7 @@ from sqlalchemy import text from everos.infra.persistence import MemoryRoot +from everos.memory.extract.ingest import message_ids from everos.service import ( MemorizeResult, MemoryService, @@ -301,8 +302,7 @@ async def test_second_add_consumes_prior_buffer_and_replaces_tail( assert new_tail_id not in all_cell_msgs # Conservation: 6 distinct message ids covered across cells + buffer. - # (We avoid hard-coding id format here — gen_message_id encodes the - # per-batch index, not a global one.) + # (We avoid hard-coding the id format here; see ingest.message_ids.) covered = all_cell_msgs | {new_tail_id} assert len(covered) == 6, ( f"expected 6 distinct ids covered, got {len(covered)}: {covered}" @@ -386,3 +386,58 @@ async def test_three_sequential_adds_conservation_no_loss( ) # Disjoint assert not (in_cells & in_buffer) + + +# --------------------------------------------------------------------------- +# Resends (#274): a client that retries after a timeout resends messages the +# first call may already have cut; they must not be cut a second time. +# --------------------------------------------------------------------------- + + +async def test_resent_batch_is_not_cut_twice( + memorize_env_scripted: Callable[..., AsyncMock], storage: Storage +) -> None: + """[m0,m1,m2] cut after 2, then the identical request again.""" + await memorize_env_scripted(fake_llm=memorize_llm([[2], []])) + session = "s_resend" + batch = {"session_id": session, "messages": [_msg(i) for i in range(3)]} + + await memorize(batch) + await memorize(batch) + + cells = await _memcell_rows(storage, session) + assert [len(ids) for _, ids in cells] == [2], cells + assert [mid for mid, _ in await _buffer_rows(storage, session)] == [ + message_ids(session, [_msg(2)])[0] + ] + + +async def test_regrouped_resend_keeps_ids_and_drops_what_was_cut( + memorize_env_scripted: Callable[..., AsyncMock], storage: Storage +) -> None: + """The retry carries m1 at another position and one new message, m3.""" + await memorize_env_scripted(fake_llm=memorize_llm([[2], []])) + session = "s_regroup" + + await memorize({"session_id": session, "messages": [_msg(i) for i in range(3)]}) + await memorize({"session_id": session, "messages": [_msg(i) for i in (1, 2, 3)]}) + + cells = await _memcell_rows(storage, session) + assert len(cells) == 1, cells + buffered = [mid for mid, _ in await _buffer_rows(storage, session)] + assert buffered == [message_ids(session, [_msg(i)])[0] for i in (2, 3)] + + +async def test_two_messages_with_one_millisecond_in_two_requests_both_stay( + memorize_env_scripted: Callable[..., AsyncMock], storage: Storage +) -> None: + """Different messages, same timestamp, each first in its request.""" + await memorize_env_scripted(fake_llm=memorize_llm([[], []])) + session = "s_same_ms" + first = _msg(0) + second = _msg(0) | {"content": "a different message"} + + await memorize({"session_id": session, "messages": [first]}) + await memorize({"session_id": session, "messages": [second]}) + + assert len(await _buffer_rows(storage, session)) == 2 diff --git a/tests/unit/test_infra/test_sqlite/test_stores.py b/tests/unit/test_infra/test_sqlite/test_stores.py index 8a701adfd..e320ecd3f 100644 --- a/tests/unit/test_infra/test_sqlite/test_stores.py +++ b/tests/unit/test_infra/test_sqlite/test_stores.py @@ -218,6 +218,23 @@ async def test_cut_records_the_cells_and_buffers_only_the_tail( assert status[1] is not None +async def test_already_cut_names_what_this_sessions_memcells_hold( + stores: _Stores, +) -> None: + m1, m2, m3 = _message("m1", 1), _message("m2", 2), _message("m3", 3) + other = SessionKey(app_id="app", project_id="proj", session_id="s2") + await stores.buffer.cut( + _SESSION, [_record("mc_1", m1, m2)], tail=[m3], last_memcell_ts=m2.timestamp + ) + await stores.buffer.cut( + other, [_record("mc_2", m3)], tail=[], last_memcell_ts=m3.timestamp + ) + + assert await stores.buffer.already_cut(_SESSION, ["m1", "m3", "m9"]) == {"m1"} + assert await stores.buffer.already_cut(other, ["m1", "m3"]) == {"m3"} + assert await stores.buffer.already_cut(_SESSION, []) == set() + + async def test_keep_leaves_the_last_memcell_stamp_alone(stores: _Stores) -> None: m1, m2 = _message("m1", 1), _message("m2", 2) await stores.buffer.keep(_SESSION, [m1], last_message_ts=m1.timestamp) diff --git a/tests/unit/test_memory/test_extract/test_boundary/test_quarantine.py b/tests/unit/test_memory/test_extract/test_boundary/test_quarantine.py index c2a7af088..d1244f1a9 100644 --- a/tests/unit/test_memory/test_extract/test_boundary/test_quarantine.py +++ b/tests/unit/test_memory/test_extract/test_boundary/test_quarantine.py @@ -43,6 +43,7 @@ ) from everos.memory.extract.boundary import BoundaryDetection, BoundaryOutcome from everos.memory.extract.boundary.quarantine import POISON_CALLS +from everos.memory.extract.ingest import message_ids from everos.memory.extract.ingest import service as ingest from everos.memory.extract.llm_retry import OUTPUT_ATTEMPTS from tests.fakes import ( @@ -119,17 +120,8 @@ async def add( async def add_orphan_tool_row(self, session: str, start: int) -> BoundaryOutcome: """An agent-mode add whose tool row answers no tool call.""" - payload = _payload(session, start) - payload["messages"].append( - { - "content": "tool output", - "timestamp": BASE_TS + start, - "sender_id": "tool", - "role": "tool", - } - ) ingested = await ingest.process( - payload, + _orphan_payload(session, start), multimodal_llm=None, raw_file_builder=unused_raw_file_builder, sender_names=InMemorySenderNameStore(), @@ -145,6 +137,24 @@ async def tracks(self, session: str) -> dict[str, list[str]]: } +def _orphan_payload(session: str, start: int) -> dict[str, Any]: + payload = _payload(session, start) + payload["messages"].append( + { + "content": "tool output", + "timestamp": BASE_TS + start, + "sender_id": "tool", + "role": "tool", + } + ) + return payload + + +def _ids(*payloads: dict[str, Any]) -> list[str]: + """The message ids ingest gives these payloads' messages.""" + return [i for p in payloads for i in message_ids(p["session_id"], p["messages"])] + + def _payload(session: str, start: int) -> dict[str, Any]: return { "session_id": session, @@ -175,15 +185,14 @@ async def test_third_consecutive_unusable_call_quarantines_the_buffer() -> None: assert tracks["memorize"] == [], "the session starts over" # The buffered poison and the quarantining call's own message are # kept; the two earlier calls' messages were never persisted. - assert sorted(tracks["quarantine"]) == [ - "m_s1_1700000000001_000", - "m_s1_1700000000004_000", - ] + assert sorted(tracks["quarantine"]) == sorted( + _ids(_payload("s1", 1), _payload("s1", 4)) + ) assert stage.llm.call_count == OUTPUT_ATTEMPTS * POISON_CALLS # The session goes on: a healthy flush cuts a cell from an empty buffer. outcome = await stage.add("s1", 5, final=True) assert outcome.status == "extracted" - assert outcome.per_cell_message_ids == [["m_s1_1700000000005_000"]] + assert outcome.per_cell_message_ids == [_ids(_payload("s1", 5))] assert (await stage.tracks("s1"))["memorize"] == [] assert len((await stage.tracks("s1"))["quarantine"]) == 2 @@ -235,7 +244,5 @@ async def test_an_orphan_tool_row_counts_without_reaching_the_model() -> None: assert stage.llm.call_count == 0, "never retried, never sent" tracks = await stage.tracks("s1") assert tracks["memorize"] == [] - assert sorted(tracks["quarantine"]) == [ - "m_s1_1700000000003_000", - "m_s1_1700000000003_001", - ] + # One timestamp, two rows: request order is kept in the id (_000, _001). + assert sorted(tracks["quarantine"]) == sorted(_ids(_orphan_payload("s1", 3))) diff --git a/tests/unit/test_memory/test_extract/test_ingest/test_id_gen.py b/tests/unit/test_memory/test_extract/test_ingest/test_id_gen.py new file mode 100644 index 000000000..52e013e92 --- /dev/null +++ b/tests/unit/test_memory/test_extract/test_ingest/test_id_gen.py @@ -0,0 +1,34 @@ +"""``message_ids``: what a resend keeps, what two messages never share.""" + +from __future__ import annotations + +from typing import Any + +from everos.memory.extract.ingest import message_ids + +_TS = 1_700_000_000_000 + + +def _m(text: str, ts: int = _TS, sender: str = "u1") -> dict[str, Any]: + return {"sender_id": sender, "role": "user", "timestamp": ts, "content": text} + + +def test_a_message_keeps_its_id_wherever_it_sits_in_the_request() -> None: + a, b = _m("a", _TS), _m("b", _TS + 1) + assert message_ids("s", [a, b])[1] == message_ids("s", [b])[0] + + +def test_one_millisecond_keeps_request_order() -> None: + ids = message_ids("s", [_m("call"), _m("result"), _m("next", _TS + 1)]) + assert [i.split("_")[3] for i in ids] == ["000", "001", "000"] + assert sorted(ids[:2]) == ids[:2] + + +def test_different_messages_in_one_millisecond_never_share_an_id() -> None: + assert message_ids("s", [_m("a")]) != message_ids("s", [_m("b")]) + assert message_ids("s", [_m("a")]) != message_ids("s", [_m("a", sender="u2")]) + + +def test_the_label_is_not_part_of_the_identity() -> None: + named = _m("a") | {"sender_name": "Alice"} + assert message_ids("s", [named]) == message_ids("s", [_m("a")]) diff --git a/tests/unit/test_properties/test_boundary_stateful.py b/tests/unit/test_properties/test_boundary_stateful.py index 6a378e164..270fb0edd 100644 --- a/tests/unit/test_properties/test_boundary_stateful.py +++ b/tests/unit/test_properties/test_boundary_stateful.py @@ -36,12 +36,10 @@ the ``quarantine`` track (nothing dropped, the session starts over), and the quarantine track holds exactly those ids. -Timestamps are unique per message, so ids are unique. ``gen_message_id`` is -deterministic in ``(session, timestamp_ms, index)`` by design (retries of -one payload dedupe through the buffer's primary key); two *different* -messages sent in separate calls with the same millisecond and index share -an id and the second is dropped as a duplicate -- a property of the id -scheme, outside this machine's domain and recorded separately. +Timestamps are unique per message, so ids are unique. ``message_ids`` is +deterministic in the session, the timestamp and what was said, so a resent +message keeps its id (the resend itself is pinned in +``tests/integration/test_memorize_resend.py``). A mid-call crash between the memcell insert and the buffer rewrite (the at-least-once case of #516) is not scripted either: the stage is not @@ -251,16 +249,23 @@ def _apply( def _fresh(self, session: str, msgs: list[tuple[str, str]]) -> list[dict[str, Any]]: out = [] - for idx, (role, text) in enumerate(msgs): + for role, text in msgs: self.next_ts += 1 ts = BASE_TS + self.next_ts + sender = "u" if role == "user" else "a" + request = { + "content": text, + "timestamp": ts, + "sender_id": sender, + "role": role, + } out.append( { - "id": ingest.gen_message_id(session, ts, idx), + "id": ingest.message_ids(session, [request])[0], "ts": ts, "role": role, "text": text, - "sender": "u" if role == "user" else "a", + "sender": sender, } ) return out From 70684c43b173dc812e596d50b08b585c897fc223 Mon Sep 17 00:00:00 2001 From: zhanghui <23442919+gloryfromca@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:12:23 +0800 Subject: [PATCH 2/3] test(memorize): derive the jitter test's message ids The concurrency jitter property test built message ids by hand in the old m___ format; it now asks ingest.message_ids. Co-Authored-By: Claude Opus 5.5 --- .../test_properties/test_memorize_concurrency_jitter.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tests/unit/test_properties/test_memorize_concurrency_jitter.py b/tests/unit/test_properties/test_memorize_concurrency_jitter.py index 947e87ad6..35bb9a38c 100644 --- a/tests/unit/test_properties/test_memorize_concurrency_jitter.py +++ b/tests/unit/test_properties/test_memorize_concurrency_jitter.py @@ -74,6 +74,7 @@ from everos.infra.persistence.sqlite._tables import Memcell from everos.memory.extract.boundary import BoundaryDetection from everos.memory.extract.boundary.quarantine import POISON_CALLS +from everos.memory.extract.ingest import message_ids from everos.memory.extract.pipeline import CellOutcome from tests.fakes import ( UNUSABLE_REPLY, @@ -219,8 +220,7 @@ async def _jittered( async def call(k: int, session: str, kind: str, n: int, pause: float) -> None: await asyncio.sleep(pause) msgs = [] - ids = [] - for idx in range(n if kind != "flush" else 0): + for _ in range(n if kind != "flush" else 0): next_ts[0] += 1 ts = BASE_TS + next_ts[0] msgs.append( @@ -231,10 +231,9 @@ async def call(k: int, session: str, kind: str, n: int, pause: float) -> None: "role": "user", } ) - mid = f"m_{session}_{ts}_{idx:03d}" - ids.append(mid) if next_ts[0] in run.poison_positions: run.poison_texts.add(f"m{next_ts[0]}") + ids = message_ids(session, msgs) payload = {"session_id": session, "messages": msgs} run.note(f"call#{k} {kind} {session} n={len(msgs)}") try: From 52dfa7ee4848b99766923bd4e9085f326e26be01 Mon Sep 17 00:00:00 2001 From: zhanghui <23442919+gloryfromca@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:42:22 +0800 Subject: [PATCH 3/3] fix(memorize): keep message ids stable across split resends The id carried the message's position among same-millisecond messages of its request, so resending [A, B] as [B] gave B a new id and it could be cut into a second memcell. The id is now session + timestamp + a digest of who said what; a verbatim repeat within one request adds its repeat count to the digest. Order among same-millisecond messages is kept by a stable timestamp sort and by reading buffered rows in write order. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 34 ++++++++------- docs/api.md | 7 ++-- .../sqlite/_repos/unprocessed_buffer.py | 10 +++-- .../memory/extract/boundary/messages.py | 10 ++++- src/everos/memory/extract/ingest/id_gen.py | 41 +++++++++++-------- .../test_memorize_window_segmentation.py | 19 +++++++++ .../test_infra/test_sqlite/test_stores.py | 9 ++++ .../test_boundary/test_messages.py | 15 ++++--- .../test_boundary/test_quarantine.py | 2 +- .../test_extract/test_ingest/test_id_gen.py | 16 ++++++-- .../test_merge_and_parse_laws.py | 12 ++++-- 11 files changed, 121 insertions(+), 54 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 919e0449c..c53aceea0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- **A resent `/memory/add` no longer cuts the same messages twice** (#274). + Messages were deduplicated only against the session buffer, so a client + retrying after a timeout re-sent messages the first call had already cut + into a memory cell, and they became a second memcell and episode. The + boundary stage now drops fresh messages a memcell of the session already + holds. Message ids no longer depend on where a message sits in its request: + `m___`, `digest` covering who said what (a + message repeated verbatim in one request is told apart by its repeat + count), so a resend -- whole, split or regrouped, within one millisecond + too -- keeps its ids, and two different messages sent in separate requests + with one timestamp are no longer merged into one. Messages sharing a + timestamp keep arrival order in the buffer rather than sorting by id. + The internal helper `everos.memory.extract.ingest.gen_message_id` is + replaced by `message_ids`. Buffered messages from an earlier version keep + their old ids; a batch sent before the upgrade and resent after it is not + recognized as a resend. + ## [1.7.1] - 2026-11-20 EverOS 1.7.1 writes each conversation's memory in its own language: a short @@ -141,21 +160,6 @@ unchanged apart from additions. See Upgrade below. of the ingest identity, so a store ingested with an earlier config is not reused. -### Fixed - -- **A resent `/memory/add` no longer cuts the same messages twice** (#274). - Messages were deduplicated only against the session buffer, so a client - retrying after a timeout re-sent messages the first call had already cut - into a memory cell, and they became a second memcell and episode. The - boundary stage now drops fresh messages a memcell of the session already - holds. Message ids no longer depend on the message's position in the - request: `m____`, where `n` counts the - request's messages sharing that timestamp and `digest` covers who said what, - so a regrouped resend keeps its ids and two different messages sent in - separate requests with one timestamp are no longer merged into one. - Buffered messages from an earlier version keep their old ids; a batch sent - before the upgrade and resent after it is not recognized as a resend. - ### Removed - **Foresight.** The `extract_foresight` strategy (off by default since diff --git a/docs/api.md b/docs/api.md index 6cfd6bb3a..c7bc8f2a6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -608,9 +608,10 @@ correlation. **Resending a batch.** A client that retries `/add` after a timeout may resend messages the first call already processed. A message's identity is -its session, its `timestamp`, its place among the request's messages with -that same `timestamp`, and what was said by whom (`sender_id`, `role`, -`content`, `tool_call_id`, `tool_calls`); `sender_name` is not part of it. +its session, its `timestamp` and what was said by whom (`sender_id`, `role`, +`content`, `tool_call_id`, `tool_calls`); `sender_name` and its place in the +request are not part of it (a message repeated verbatim within one request +counts as many times as it appears). A resent message that is still buffered, or already part of a memory cell of the session, is dropped, so a retry (whole, split or regrouped) never writes it twice and answers `200` (`"accumulated"` when it cut nothing diff --git a/src/everos/infra/persistence/sqlite/_repos/unprocessed_buffer.py b/src/everos/infra/persistence/sqlite/_repos/unprocessed_buffer.py index a7da474ea..3be0fe214 100644 --- a/src/everos/infra/persistence/sqlite/_repos/unprocessed_buffer.py +++ b/src/everos/infra/persistence/sqlite/_repos/unprocessed_buffer.py @@ -14,7 +14,7 @@ from __future__ import annotations -from sqlalchemy import delete, select, update +from sqlalchemy import delete, literal_column, select, update from sqlalchemy.dialects.sqlite import insert as sqlite_insert from everos.infra.persistence.sqlite._base.repository import RepoBase @@ -34,7 +34,11 @@ async def list_for_track( app_id: str = "default", project_id: str = "default", ) -> list[UnprocessedBuffer]: - """Return all rows of (app, project, session, track), ts asc.""" + """Return all rows of (app, project, session, track), ts asc. + + Rows sharing a timestamp come back in the order they were written + (``rowid``): the buffer is always rewritten whole, in merged order. + """ async with session_scope(self._factory) as s: stmt = ( select(UnprocessedBuffer) @@ -44,7 +48,7 @@ async def list_for_track( UnprocessedBuffer.session_id == session_id, UnprocessedBuffer.track == track, ) - .order_by(UnprocessedBuffer.timestamp.asc()) # type: ignore[union-attr] + .order_by(UnprocessedBuffer.timestamp.asc(), literal_column("rowid")) # type: ignore[union-attr] ) return list((await s.execute(stmt)).scalars().all()) diff --git a/src/everos/memory/extract/boundary/messages.py b/src/everos/memory/extract/boundary/messages.py index 53f74e61f..2e11ac3f2 100644 --- a/src/everos/memory/extract/boundary/messages.py +++ b/src/everos/memory/extract/boundary/messages.py @@ -52,11 +52,17 @@ def filter_for_mode( def merge_dedupe_sort( buffered: Sequence[CanonicalMessage], new: Sequence[CanonicalMessage] ) -> list[CanonicalMessage]: - """Union by ``message_id`` (a buffered row wins), sorted by ``(timestamp, id)``.""" + """Union by ``message_id`` (a buffered row wins), sorted by timestamp. + + The sort is stable: rows sharing a timestamp keep arrival order, buffered + rows (in buffer order) before this call's (in request order). Ids carry no + order of their own (``ingest.message_ids``), so a tool result never sorts + ahead of the call it answers on a tie. + """ seen: dict[str, CanonicalMessage] = {m.message_id: m for m in buffered} for m in new: seen.setdefault(m.message_id, m) - return sorted(seen.values(), key=lambda m: (m.timestamp, m.message_id)) + return sorted(seen.values(), key=lambda m: m.timestamp) class Segmentation(NamedTuple): diff --git a/src/everos/memory/extract/ingest/id_gen.py b/src/everos/memory/extract/ingest/id_gen.py index 1fbd58b36..ac1b67db9 100644 --- a/src/everos/memory/extract/ingest/id_gen.py +++ b/src/everos/memory/extract/ingest/id_gen.py @@ -1,17 +1,17 @@ """Deterministic, human-readable ``message_id`` generation. -Format: ``m____``. - -- ``nth`` counts the messages of one request that share the timestamp, in - request order, so those keep their order when rows sort by - ``(timestamp, message_id)``. -- ``digest`` is 8 hex chars of SHA-256 over who said what (``sender_id``, - ``role``, ``content``, ``tool_call_id``, ``tool_calls``), so two different - messages sent in separate requests with the same millisecond get two ids. - -Neither part depends on where the message sits in its request, so a client -that resends a batch -- whole, split or regrouped -- produces the same ids, -and the boundary stage drops what it already buffered or cut. +Format: ``m___``. + +``digest`` is 8 hex chars of SHA-256 over who said what (``sender_id``, ``role``, +``content``, ``tool_call_id``, ``tool_calls``). Nothing in the id depends on where +the message sits in its request, so a client that resends a batch -- whole, split +or regrouped -- produces the same ids, and the boundary stage drops what it +already buffered or cut. Two different messages in one millisecond get two ids. + +A message repeated verbatim within one request (same sender, words and +millisecond) is told apart by how many identical ones came before it in that +request; only then does the count enter the digest. Order among messages that +share a millisecond is not in the id: the boundary stage keeps arrival order. """ from __future__ import annotations @@ -25,18 +25,25 @@ _IDENTITY_FIELDS = ("sender_id", "role", "content", "tool_call_id", "tool_calls") -def _digest(message: Mapping[str, Any]) -> str: - basis = [message.get(field) for field in _IDENTITY_FIELDS] +def _digest(message: Mapping[str, Any], repeat: int) -> str: + basis: list[Any] = [message.get(field) for field in _IDENTITY_FIELDS] + if repeat: + basis.append(repeat) raw = json.dumps(basis, sort_keys=True, ensure_ascii=False, default=str) return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:8] def message_ids(session_id: str, messages: Sequence[Mapping[str, Any]]) -> list[str]: """The id of each message of one request, in order.""" - nth: Counter[int] = Counter() + seen: Counter[str] = Counter() ids = [] for message in messages: ts_ms = int(message["timestamp"]) - ids.append(f"m_{session_id}_{ts_ms}_{nth[ts_ms]:03d}_{_digest(message)}") - nth[ts_ms] += 1 + first = f"m_{session_id}_{ts_ms}_{_digest(message, 0)}" + ids.append( + first + if not seen[first] + else f"m_{session_id}_{ts_ms}_{_digest(message, seen[first])}" + ) + seen[first] += 1 return ids diff --git a/tests/integration/test_memorize_window_segmentation.py b/tests/integration/test_memorize_window_segmentation.py index d6aeaa283..f4d833db9 100644 --- a/tests/integration/test_memorize_window_segmentation.py +++ b/tests/integration/test_memorize_window_segmentation.py @@ -428,6 +428,25 @@ async def test_regrouped_resend_keeps_ids_and_drops_what_was_cut( assert buffered == [message_ids(session, [_msg(i)])[0] for i in (2, 3)] +async def test_one_millisecond_resent_in_parts_is_not_cut_twice( + memorize_env_scripted: Callable[..., AsyncMock], storage: Storage +) -> None: + """[A, B, C] share one millisecond and are cut after B; the retry carries B + alone. B keeps its id though its place in the request changed.""" + await memorize_env_scripted(fake_llm=memorize_llm([[2], []])) + session = "s_same_ms_parts" + batch = [_msg(0) | {"content": f"part-{i}"} for i in range(3)] + + await memorize({"session_id": session, "messages": batch}) + await memorize({"session_id": session, "messages": [batch[1]]}) + + cells = await _memcell_rows(storage, session) + assert [len(ids) for _, ids in cells] == [2], cells + assert [mid for mid, _ in await _buffer_rows(storage, session)] == message_ids( + session, [batch[2]] + ) + + async def test_two_messages_with_one_millisecond_in_two_requests_both_stay( memorize_env_scripted: Callable[..., AsyncMock], storage: Storage ) -> None: diff --git a/tests/unit/test_infra/test_sqlite/test_stores.py b/tests/unit/test_infra/test_sqlite/test_stores.py index e320ecd3f..958d3d527 100644 --- a/tests/unit/test_infra/test_sqlite/test_stores.py +++ b/tests/unit/test_infra/test_sqlite/test_stores.py @@ -186,6 +186,15 @@ def _record(memcell_id: str, *messages: CanonicalMessage) -> MemcellRecord: ) +async def test_buffer_rows_of_one_timestamp_come_back_in_write_order( + stores: _Stores, +) -> None: + """Ids carry no order, so a tie must not fall back to the id's spelling.""" + call, result = _message("m_z", 1), _message("m_a", 1) + await stores.buffer.keep(_SESSION, [call, result], last_message_ts=call.timestamp) + assert [m.message_id for m in await stores.buffer.list(_SESSION)] == ["m_z", "m_a"] + + async def test_keep_buffers_messages_and_stamps_the_last_message( stores: _Stores, ) -> None: diff --git a/tests/unit/test_memory/test_extract/test_boundary/test_messages.py b/tests/unit/test_memory/test_extract/test_boundary/test_messages.py index 31e71c069..fa8058a7b 100644 --- a/tests/unit/test_memory/test_extract/test_boundary/test_messages.py +++ b/tests/unit/test_memory/test_extract/test_boundary/test_messages.py @@ -88,12 +88,15 @@ def test_merge_dedupe_sort_dedupes_by_message_id() -> None: assert m1.text == "hi" # original, not "overwritten?" -def test_merge_sorts_by_timestamp_then_id() -> None: - a = _msg("m_b", "user", ts_seconds=100) - b = _msg("m_a", "user", ts_seconds=100) - c = _msg("m_c", "user", ts_seconds=50) - merged = merge_dedupe_sort([], [a, b, c]) - assert [m.message_id for m in merged] == ["m_c", "m_a", "m_b"] +def test_merge_sorts_by_timestamp_and_keeps_arrival_order_on_a_tie() -> None: + """Ids carry no order (#274): a tie keeps the order rows arrived in, so a + tool result whose id happens to sort first still follows its call.""" + call = _msg("m_z", "assistant", ts_seconds=100) + result = _msg("m_a", "tool", ts_seconds=100) + earlier = _msg("m_c", "user", ts_seconds=50) + held = _msg("m_y", "user", ts_seconds=100) + merged = merge_dedupe_sort([held], [call, result, earlier]) + assert [m.message_id for m in merged] == ["m_c", "m_y", "m_z", "m_a"] # ── apply_cuts ─────────────────────────────────────────────────────────── diff --git a/tests/unit/test_memory/test_extract/test_boundary/test_quarantine.py b/tests/unit/test_memory/test_extract/test_boundary/test_quarantine.py index d1244f1a9..4fd666443 100644 --- a/tests/unit/test_memory/test_extract/test_boundary/test_quarantine.py +++ b/tests/unit/test_memory/test_extract/test_boundary/test_quarantine.py @@ -244,5 +244,5 @@ async def test_an_orphan_tool_row_counts_without_reaching_the_model() -> None: assert stage.llm.call_count == 0, "never retried, never sent" tracks = await stage.tracks("s1") assert tracks["memorize"] == [] - # One timestamp, two rows: request order is kept in the id (_000, _001). + # One timestamp, two different rows: two ids. assert sorted(tracks["quarantine"]) == sorted(_ids(_orphan_payload("s1", 3))) diff --git a/tests/unit/test_memory/test_extract/test_ingest/test_id_gen.py b/tests/unit/test_memory/test_extract/test_ingest/test_id_gen.py index 52e013e92..e95c09833 100644 --- a/tests/unit/test_memory/test_extract/test_ingest/test_id_gen.py +++ b/tests/unit/test_memory/test_extract/test_ingest/test_id_gen.py @@ -18,10 +18,12 @@ def test_a_message_keeps_its_id_wherever_it_sits_in_the_request() -> None: assert message_ids("s", [a, b])[1] == message_ids("s", [b])[0] -def test_one_millisecond_keeps_request_order() -> None: - ids = message_ids("s", [_m("call"), _m("result"), _m("next", _TS + 1)]) - assert [i.split("_")[3] for i in ids] == ["000", "001", "000"] - assert sorted(ids[:2]) == ids[:2] +def test_one_millisecond_resent_in_parts_keeps_its_ids() -> None: + """[A, B] in one millisecond, then B alone: B is the same message.""" + a, b = _m("a"), _m("b") + first = message_ids("s", [a, b]) + assert message_ids("s", [b]) == [first[1]] + assert message_ids("s", [b, a]) == [first[1], first[0]] def test_different_messages_in_one_millisecond_never_share_an_id() -> None: @@ -29,6 +31,12 @@ def test_different_messages_in_one_millisecond_never_share_an_id() -> None: assert message_ids("s", [_m("a")]) != message_ids("s", [_m("a", sender="u2")]) +def test_a_message_repeated_verbatim_in_one_request_is_kept_twice() -> None: + ids = message_ids("s", [_m("ok"), _m("ok")]) + assert len(set(ids)) == 2 + assert ids[0] == message_ids("s", [_m("ok")])[0] + + def test_the_label_is_not_part_of_the_identity() -> None: named = _m("a") | {"sender_name": "Alice"} assert message_ids("s", [named]) == message_ids("s", [_m("a")]) diff --git a/tests/unit/test_properties/test_merge_and_parse_laws.py b/tests/unit/test_properties/test_merge_and_parse_laws.py index 99df4e573..740b7190d 100644 --- a/tests/unit/test_properties/test_merge_and_parse_laws.py +++ b/tests/unit/test_properties/test_merge_and_parse_laws.py @@ -1,7 +1,9 @@ """Laws of the merge, rank and parse helpers on the memorize and search paths. 1. ``merge_dedupe_sort`` (boundary stage): the result is sorted by - ``(timestamp, message_id)``, holds each id once, its id set is the union + timestamp, rows sharing one keep arrival order (buffered first, in + buffer order, then new ones in request order -- ids carry no order since + #274), it holds each id once, its id set is the union of both inputs, a buffered message wins over a new one with the same id, and merging again changes nothing. ``buffered`` comes from a table keyed by ``message_id``, so it never holds an id twice; the law is stated on @@ -80,8 +82,12 @@ def test_merge_dedupe_sort_laws( buffered: list[CanonicalMessage], new: list[CanonicalMessage] ) -> None: merged = merge_dedupe_sort(buffered, new) - keys = [(m.timestamp, m.message_id) for m in merged] - assert keys == sorted(keys) + assert [m.timestamp for m in merged] == sorted(m.timestamp for m in merged) + arrival = {} + for m in [*buffered, *new]: + arrival.setdefault(m.message_id, len(arrival)) + keys = [(m.timestamp, arrival[m.message_id]) for m in merged] + assert keys == sorted(keys), "a tie keeps arrival order" ids = [m.message_id for m in merged] assert len(ids) == len(set(ids)) assert set(ids) == {m.message_id for m in buffered} | {m.message_id for m in new}