Skip to content
Merged
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
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_<session>_<timestamp>_<digest>`, `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
Expand Down
13 changes: 13 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,19 @@ 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` 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
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:
Expand Down
34 changes: 33 additions & 1 deletion src/everos/infra/persistence/sqlite/_repos/session_cut.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
10 changes: 7 additions & 3 deletions src/everos/infra/persistence/sqlite/_repos/unprocessed_buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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())

Expand Down
11 changes: 11 additions & 0 deletions src/everos/infra/persistence/sqlite/stores.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
38 changes: 37 additions & 1 deletion src/everos/memory/extract/boundary/detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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] = {
Expand Down Expand Up @@ -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))

Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand Down
10 changes: 8 additions & 2 deletions src/everos/memory/extract/boundary/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
6 changes: 3 additions & 3 deletions src/everos/memory/extract/ingest/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Comment thread
gloryfromca marked this conversation as resolved.
Resolved
from .service import process as process

__all__ = [
"gen_message_id",
"message_ids",
"process",
]
48 changes: 40 additions & 8 deletions src/everos/memory/extract/ingest/id_gen.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,49 @@
"""Deterministic, human-readable ``message_id`` generation.

Format: ``m_<session_id>_<timestamp_ms>_<idx:03d>``.
Format: ``m_<session_id>_<timestamp_ms>_<digest>``.

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``.
``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

_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], 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 gen_message_id(session_id: str, timestamp_ms: int, idx: int) -> str:
"""Return ``m_<session_id>_<timestamp_ms>_<idx:03d>``."""
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."""
seen: Counter[str] = Counter()
ids = []
for message in messages:
ts_ms = int(message["timestamp"])
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
9 changes: 4 additions & 5 deletions src/everos/memory/extract/ingest/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()
Expand All @@ -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(
Expand Down
6 changes: 6 additions & 0 deletions src/everos/memory/ports/stores.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/test_memorize_agent_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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:]]

Expand Down
Loading