Skip to content

The agent that grows with you

test: messaging exactly-once through the real gateway (C12)

teknium1b477dd96c388
diff --git a/tests/e2e/core/delivery/_fake_platform.py b/tests/e2e/core/delivery/_fake_platform.py
new file mode 100644
index 00000000000..1576d5fb534
--- /dev/null
+++ b/tests/e2e/core/delivery/_fake_platform.py
@@ -0,0 +1,748 @@
+"""Lane-private harness for the C12 messaging exactly-once suite (test_messaging_exactly_once.py).
+
+What is real and what is fake:
+
+* REAL: ``GatewayRunner`` constructed and ``start()``-ed normally (adapters are created through the
+ real ``_create_adapter`` -> ``platform_registry`` path), the base-adapter session guard / busy
+ queue / ``_send_with_retry`` / delivery ledger + boot redelivery sweep, the stream consumer,
+ ``AIAgent``, SessionDB on disk, and the OpenAI-compatible client talking to
+ ``tests/fakes/fake_llm_provider.py`` (which lives in the TEST process).
+* FAKE: only the platform wire. ``FakePlatformAdapter`` implements the ``BasePlatformAdapter``
+ contract (send / edit_message / delete_message / threads / per-platform length caps) against
+ ``FakePlatformServer`` - the ground truth of what a user would SEE. Every accepted effect is
+ journaled (fsync) to ``platform.jsonl`` BEFORE the call returns, so the journal survives a
+ SIGKILL and a restarted gateway sees the same chat. Faults (send timeout, sent-but-ack-lost,
+ 429 retry_after, connection reset, a crash hold) are scripted per operation over RPC.
+
+The gateway runs in a CHILD process (``python -m tests.e2e.core.delivery._fake_platform serve
+<spool>``), controlled over a JSON-lines TCP socket. That keeps it isolated from the per-test
+autouse fixtures of this suite's conftest (which close every SessionDB and reset plugin singletons
+after each test), lets one ~15 s gateway boot serve a whole scenario matrix, and makes a real
+``kill -9`` + restart on the same HERMES_HOME possible.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import re
+import signal
+import socket
+import subprocess
+import sys
+import threading
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Callable, Dict, List, Optional
+
+POLL = 0.02
+DEADLINE = 120.0
+REPO_ROOT = Path(__file__).resolve().parents[4]
+
+# Per-platform send/edit semantics (what the real service enforces, not what Hermes believes).
+PROFILES: Dict[str, Dict[str, Any]] = {
+ "telegram": {"max_len": 4096, "edits": True, "threads": False},
+ "discord": {"max_len": 2000, "edits": True, "threads": True},
+ "slack": {"max_len": 3900, "edits": True, "threads": True},
+ "noedit": {"max_len": 4096, "edits": False, "threads": False},
+}
+
+
+def wait_until(predicate: Callable[[], Any], what: str, timeout: float = DEADLINE,
+ proc: Optional[subprocess.Popen] = None, log: Optional[Path] = None) -> Any:
+ deadline = time.monotonic() + timeout
+ while True:
+ value = predicate()
+ if value:
+ return value
+ if proc is not None and proc.poll() is not None:
+ tail = log.read_text(errors="replace")[-4000:] if log and log.exists() else ""
+ raise AssertionError(f"gateway child exited (rc={proc.returncode}) waiting for {what}\n{tail}")
+ if time.monotonic() >= deadline:
+ raise AssertionError(f"timed out after {timeout:.0f}s waiting for {what}")
+ time.sleep(POLL)
+
+
+def _append_jsonl(path: Path, record: dict) -> None:
+ line = (json.dumps(record, sort_keys=True) + "\n").encode("utf-8")
+ fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
+ try:
+ os.write(fd, line)
+ os.fsync(fd)
+ finally:
+ os.close(fd)
+
+
+def read_jsonl(path: Path) -> List[dict]:
+ if not path.exists():
+ return []
+ out = []
+ for line in path.read_text(encoding="utf-8").splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ out.append(json.loads(line))
+ except json.JSONDecodeError:
+ continue # a torn last line from a SIGKILLed writer
+ return out
+
+
+# Platform ground truth ------------------------------------------------------------------------
+
+
+@dataclass
+class PlatformMessage:
+ message_id: str
+ platform: str
+ chat_id: str
+ thread_id: Optional[str]
+ text: str
+ reply_to: Optional[str] = None
+ deleted: bool = False
+ edits: int = 0
+
+
+class FakePlatformServer:
+ """What the chat service holds. Thread-safe; journaled so it survives the gateway process."""
+
+ def __init__(self, journal: Path) -> None:
+ self._lock = threading.Lock()
+ self.messages: Dict[str, PlatformMessage] = {}
+ self.order: List[str] = []
+ self.journal = journal
+ for rec in read_jsonl(journal):
+ self._apply(rec)
+
+ def _apply(self, rec: dict) -> None:
+ kind = rec["kind"]
+ if kind == "post":
+ msg = PlatformMessage(rec["message_id"], rec["platform"], rec["chat_id"], rec.get("thread_id"),
+ rec["text"], rec.get("reply_to"))
+ self.messages[msg.message_id] = msg
+ self.order.append(msg.message_id)
+ elif kind == "edit":
+ msg = self.messages.get(rec["message_id"])
+ if msg is not None:
+ msg.text = rec["text"]
+ msg.edits += 1
+ elif kind == "delete":
+ msg = self.messages.get(rec["message_id"])
+ if msg is not None:
+ msg.deleted = True
+
+ def _commit(self, rec: dict) -> None:
+ rec["t"] = time.time()
+ _append_jsonl(self.journal, rec)
+ self._apply(rec)
+
+ def post(self, platform: str, chat_id: str, thread_id: Optional[str], text: str,
+ reply_to: Optional[str]) -> str:
+ with self._lock:
+ mid = f"pm-{os.getpid()}-{len(self.order) + 1}"
+ self._commit({"kind": "post", "message_id": mid, "platform": platform, "chat_id": str(chat_id),
+ "thread_id": thread_id, "text": text, "reply_to": reply_to})
+ return mid
+
+ def edit(self, message_id: str, text: str) -> bool:
+ with self._lock:
+ msg = self.messages.get(message_id)
+ if msg is None or msg.deleted:
+ return False
+ self._commit({"kind": "edit", "message_id": message_id, "text": text})
+ return True
+
+ def delete(self, message_id: str) -> bool:
+ with self._lock:
+ if message_id not in self.messages:
+ return False
+ self._commit({"kind": "delete", "message_id": message_id})
+ return True
+
+ def visible(self, platform: Optional[str] = None, chat_id: Optional[str] = None) -> List[PlatformMessage]:
+ with self._lock:
+ return [m for m in (self.messages[i] for i in self.order)
+ if not m.deleted and (platform is None or m.platform == platform)
+ and (chat_id is None or m.chat_id == str(chat_id))]
+
+
+# Fault injection ------------------------------------------------------------------------------
+
+
+@dataclass
+class Fault:
+ """One scripted platform fault, consumed by the first ``times`` matching calls.
+
+ ``op``: "send" | "edit" | "any" (send or edit) | "pre_ledger". ``contains``: substring the content must include (None = any call).
+ ``kind``:
+ timeout - the platform never saw it; the adapter reports a timeout.
+ ack_lost - the platform accepted it (visible) but the ack never came back (timeout).
+ rate_limit - 429: refused, SendResult carries ``retry_after``.
+ conn_error - refused with a retryable connection reset.
+ hold - park the call BEFORE the platform accepts it (until SIGKILL).
+ hold_after - the platform accepts it, then park (the ack dies with the process).
+ """
+
+ platform: str
+ op: str
+ kind: str
+ contains: Optional[str] = None
+ retry_after: float = 0.3
+ times: int = 1
+ chat_id: Optional[str] = None
+ hits: int = 0
+
+ def matches(self, platform: str, op: str, content: str, chat_id: Optional[str] = None) -> bool:
+ if self.hits >= self.times or platform != self.platform:
+ return False
+ if self.chat_id is not None and chat_id != self.chat_id:
+ return False
+ if self.op != op and not (self.op == "any" and op in ("send", "edit")):
+ return False
+ return self.contains is None or self.contains in content
+
+
+# Adapter (child process) ----------------------------------------------------------------------
+
+
+def _adapter_class():
+ from gateway.config import Platform
+ from gateway.platforms.base import BasePlatformAdapter, SendResult
+ from gateway.platforms.event import MessageEvent, MessageType
+ from gateway.platforms.helpers import MessageDeduplicator
+
+ class FakePlatformAdapter(BasePlatformAdapter):
+ """A platform adapter honouring the base contract against ``FakePlatformServer``."""
+
+ splits_long_messages = True
+
+ def __init__(self, config, *, name: str, profile: str, world: "ChildWorld"):
+ super().__init__(config, Platform(name))
+ self.pname = name
+ self.world = world
+ self.profile = PROFILES[profile]
+ self.MAX_MESSAGE_LENGTH = self.profile["max_len"]
+ self.SUPPORTS_MESSAGE_EDITING = self.profile["edits"]
+ # Inbound de-duplication is adapter-owned in the contract; like most real adapters this
+ # uses the shared helper, whose state lives on the adapter instance.
+ self._dedup = MessageDeduplicator()
+
+ # lifecycle
+ async def connect(self, *, is_reconnect: bool = False) -> bool:
+ self._running = True
+ self._mark_connected()
+ return True
+
+ async def disconnect(self) -> None:
+ self._running = False
+ self._mark_disconnected()
+
+ async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
+ return {"name": f"chat-{chat_id}", "type": "dm", "chat_id": chat_id}
+
+ async def send_typing(self, chat_id: str, metadata=None) -> None:
+ return None
+
+ # faults
+ async def _fault(self, op: str, content: str, accept: Callable[[], Any],
+ chat_id: Optional[str] = None) -> Optional[Any]:
+ fault = self.world.take_fault(self.pname, op, content, chat_id)
+ if fault is None:
+ return None
+ if fault.kind == "timeout":
+ return SendResult(success=False, error="Timed out waiting for platform response",
+ error_kind="transient")
+ if fault.kind == "ack_lost":
+ accept()
+ return SendResult(success=False, error="Timed out waiting for platform response",
+ error_kind="transient")
+ if fault.kind == "rate_limit":
+ return SendResult(success=False, error=f"Too Many Requests: retry after {fault.retry_after}",
+ retry_after=fault.retry_after, error_kind="rate_limited")
+ if fault.kind == "conn_error":
+ return SendResult(success=False, error="Connection reset by peer", retryable=True,
+ error_kind="transient")
+ if fault.kind in ("hold", "hold_after"):
+ if fault.kind == "hold_after":
+ accept()
+ self.world.note_hold(self.pname, op, content)
+ await asyncio.Event().wait() # parked until the process is killed
+ raise AssertionError(f"unknown fault kind {fault.kind}")
+
+ def _thread(self, metadata: Optional[Dict[str, Any]]) -> Optional[str]:
+ if not self.profile["threads"] or not metadata:
+ return None
+ tid = metadata.get("thread_id")
+ return str(tid) if tid else None
+
+ # outbound
+ async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None,
+ metadata: Optional[Dict[str, Any]] = None) -> SendResult:
+ content = content or ""
+ thread_id = self._thread(metadata)
+ self.world.record_op({"platform": self.pname, "op": "send", "chat_id": str(chat_id),
+ "thread_id": thread_id, "content": content,
+ "interim": bool((metadata or {}).get("_interim_send"))})
+ chunks = self.truncate_message(content, self.MAX_MESSAGE_LENGTH) if content else [""]
+ posted: List[str] = []
+
+ def accept() -> None:
+ for chunk in chunks:
+ posted.append(self.world.server.post(self.pname, chat_id, thread_id, chunk, reply_to))
+
+ faulted = await self._fault("send", content, accept, str(chat_id))
+ if faulted is not None:
+ return faulted
+ accept()
+ return SendResult(success=True, message_id=posted[-1], continuation_message_ids=tuple(posted[:-1]))
+
+ async def edit_message(self, chat_id: str, message_id: str, content: str, *,
+ finalize: bool = False) -> SendResult:
+ self.world.record_op({"platform": self.pname, "op": "edit", "chat_id": str(chat_id),
+ "message_id": message_id, "content": content, "finalize": finalize})
+ if not self.profile["edits"]:
+ return SendResult(success=False, error="Not supported")
+ if len(content) > self.MAX_MESSAGE_LENGTH:
+ return SendResult(success=False, error="Bad Request: message is too long", error_kind="too_long")
+ faulted = await self._fault("edit", content, lambda: self.world.server.edit(message_id, content),
+ str(chat_id))
+ if faulted is not None:
+ return faulted
+ if not self.world.server.edit(message_id, content):
+ return SendResult(success=False, error="Bad Request: message to edit not found",
+ error_kind="not_found")
+ return SendResult(success=True, message_id=message_id)
+
+ async def delete_message(self, chat_id: str, message_id: str) -> bool:
+ self.world.record_op({"platform": self.pname, "op": "delete", "chat_id": str(chat_id),
+ "message_id": message_id})
+ return self.world.server.delete(message_id)
+
+ # a crash point between "handler returned (turn persisted)" and "final text ledgered"
+ async def _extract_response_content(self, response, event, session_key, **kw):
+ chat = str(getattr(getattr(event, "source", None), "chat_id", "") or "")
+ if self.world.take_fault(self.pname, "pre_ledger", str(response or ""), chat) is not None:
+ self.world.note_hold(self.pname, "pre_ledger", str(response or ""))
+ await asyncio.Event().wait()
+ return await super()._extract_response_content(response, event, session_key, **kw)
+
+ # inbound
+ async def inject(self, text: str, message_id: str, *, chat_id: str = "c1", user_id: str = "u1",
+ thread_id: Optional[str] = None, chat_type: str = "dm") -> None:
+ if self._dedup.is_duplicate(message_id):
+ self.world.record_op({"platform": self.pname, "op": "inbound_duplicate_dropped",
+ "chat_id": str(chat_id), "message_id": message_id})
+ return
+ self.world.record_op({"platform": self.pname, "op": "inbound", "chat_id": str(chat_id),
+ "message_id": message_id, "content": text})
+ source = self.build_source(chat_id=chat_id, chat_name=f"chat-{chat_id}", chat_type=chat_type,
+ user_id=user_id, user_name="tester", thread_id=thread_id)
+ event = MessageEvent(text=text, message_type=MessageType.TEXT, source=source, message_id=message_id)
+ await self.handle_message(event)
+
+ return FakePlatformAdapter
+
+
+class ChildWorld:
+ """Child-process state shared by every fake adapter instance (survives adapter re-creation)."""
+
+ def __init__(self, spool: Path) -> None:
+ self.spool = spool
+ self.server = FakePlatformServer(spool / "platform.jsonl")
+ self._lock = threading.Lock()
+ self.faults: List[Fault] = []
+
+ def take_fault(self, platform: str, op: str, content: str, chat_id: Optional[str] = None) -> Optional[Fault]:
+ with self._lock:
+ for f in self.faults:
+ if f.matches(platform, op, content, chat_id):
+ f.hits += 1
+ _append_jsonl(self.spool / "faults_fired.jsonl",
+ {"pid": os.getpid(), "platform": platform, "op": op, "kind": f.kind,
+ "chat_id": chat_id, "content": content[:200]})
+ return f
+ return None
+
+ def note_hold(self, platform: str, op: str, content: str) -> None:
+ _append_jsonl(self.spool / "holds.jsonl", {"pid": os.getpid(), "platform": platform, "op": op,
+ "content": content})
+
+ def record_op(self, op: dict) -> None:
+ op["pid"] = os.getpid()
+ _append_jsonl(self.spool / "ops.jsonl", op)
+
+
+def _serve(spool: Path) -> None: # pragma: no cover - runs in the child process
+ cfg = json.loads((spool / "config.json").read_text())
+ world = ChildWorld(spool)
+
+ # Knob-only: shrink the ledger's in-process redelivery backoff (30 s / 120 s) so a rejected final
+ # is retried within the test's patience; the policy (who retries, with which marker) is untouched.
+ import gateway.delivery_ledger as ledger
+ ledger._RETRY_BACKOFF_SECONDS = tuple(cfg.get("ledger_backoff", (0.5, 1.0)))
+
+ from gateway.config import GatewayConfig, HomeChannel, Platform, PlatformConfig, StreamingConfig
+ from gateway.platform_registry import PlatformEntry, platform_registry
+ from gateway.run import GatewayRunner
+
+ cls = _adapter_class()
+ platforms = {}
+ for name, profile in cfg["platforms"].items():
+ platform_registry.register(PlatformEntry(
+ name=name, label=name, check_fn=lambda: True, source="plugin",
+ adapter_factory=lambda pc, n=name, p=profile: cls(pc, name=n, profile=p, world=world),
+ allow_all_env=f"{name.upper()}_ALLOW_ALL_USERS"))
+ os.environ[f"{name.upper()}_ALLOW_ALL_USERS"] = "true"
+ plat = Platform(name)
+ platforms[plat] = PlatformConfig(enabled=True, token="fake-token",
+ home_channel=HomeChannel(platform=plat, chat_id="home", name="home"))
+
+ config = GatewayConfig(
+ platforms=platforms,
+ streaming=StreamingConfig(enabled=True, transport="edit", edit_interval=0.05, buffer_threshold=24,
+ cursor=""),
+ loop_watchdog=False, write_sessions_json=False, multiplex_profiles=False,
+ )
+
+ async def handle_rpc(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ while True:
+ line = await reader.readline()
+ if not line:
+ break
+ req = json.loads(line)
+ try:
+ resp = await dispatch(req)
+ except Exception as exc: # surfaced to the test as an RPC error
+ resp = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
+ writer.write((json.dumps(resp) + "\n").encode())
+ await writer.drain()
+
+ runner: Any = None
+
+ async def dispatch(req: dict) -> dict:
+ cmd = req["cmd"]
+ if cmd == "inject":
+ adapter = runner.adapters[Platform(req["platform"])]
+ await adapter.inject(req["text"], req["message_id"], chat_id=req.get("chat_id", "c1"),
+ thread_id=req.get("thread_id"))
+ return {"ok": True}
+ if cmd == "adapter_id":
+ adapter = runner.adapters.get(Platform(req["platform"]))
+ return {"ok": True, "id": id(adapter) if adapter is not None else None}
+ if cmd == "reconnect":
+ # The adapter's socket dies with a retryable error; the REAL reconnect watcher replaces it.
+ old = runner.adapters[Platform(req["platform"])]
+ old._set_fatal_error("fake_socket_closed", "socket closed by peer", retryable=True)
+ await old._notify_fatal_error()
+ return {"ok": True, "id": id(old)}
+ if cmd == "fault":
+ with world._lock:
+ world.faults.append(Fault(**req["fault"]))
+ return {"ok": True}
+ if cmd == "busy":
+ chats = req.get("chats")
+
+ def mine(key: str) -> bool:
+ return chats is None or any(re.search(rf":{re.escape(c)}(:|$)", key) for c in chats)
+
+ busy = []
+ for adapter in runner.adapters.values():
+ keys = set(adapter._active_sessions) | set(adapter._pending_messages) | set(adapter._session_tasks)
+ busy.extend(k for k in keys if mine(k))
+ running = [k for k in list(runner._running_agents) if mine(k)]
+ return {"ok": True, "busy": sorted(busy), "running": sorted(running)}
+ raise ValueError(f"unknown rpc {cmd}")
+
+ async def orphan_watchdog(parent: int) -> None:
+ # The child runs in its own session (so kill9 can take the whole group); if the test
+ # process dies without teardown (CI per-file timeout), exit instead of lingering.
+ while os.getppid() == parent:
+ await asyncio.sleep(0.5)
+ os._exit(0)
+
+ async def main() -> None:
+ nonlocal runner
+ parent = int(os.environ.get("C12_PARENT_PID") or os.getppid())
+ watchdog = asyncio.ensure_future(orphan_watchdog(parent)) # noqa: F841 - lives with the loop
+ runner = GatewayRunner(config)
+ ok = await runner.start()
+ if not ok:
+ raise SystemExit(3)
+ server = await asyncio.start_server(handle_rpc, "127.0.0.1", 0)
+ port = server.sockets[0].getsockname()[1]
+ _append_jsonl(spool / "ready.jsonl", {"pid": os.getpid(), "port": port})
+ async with server:
+ await server.serve_forever()
+
+ asyncio.run(main())
+
+
+# Test-process side ----------------------------------------------------------------------------
+
+
+_KEEP_ENV = ("PATH", "LANG", "LC_ALL", "TMPDIR", "PYTHONPATH", "VIRTUAL_ENV", "SYSTEMROOT")
+
+
+class GatewayProcess:
+ """A real gateway in a child process on ``home``; RPC + SIGKILL + restart on the same state."""
+
+ def __init__(self, root: Path, *, platforms: Dict[str, str], llm_base_url: str,
+ extra_config: str = "", ledger_backoff=(0.5, 1.0)) -> None:
+ from tests.fakes.fake_llm_provider import write_hermes_home
+
+ self.root = root
+ self.home = root / "home"
+ self.hermes_home = self.home / ".hermes"
+ self.spool = root / "spool"
+ self.spool.mkdir(parents=True, exist_ok=True)
+ write_hermes_home(self.hermes_home, llm_base_url, extra_config=extra_config)
+ (self.spool / "config.json").write_text(json.dumps(
+ {"platforms": platforms, "ledger_backoff": list(ledger_backoff)}))
+ self.proc: Optional[subprocess.Popen] = None
+ self.sock: Optional[socket.socket] = None
+ self._rfile = None
+ self.boots = 0
+ self.pids: List[int] = []
+
+ @property
+ def db_path(self) -> Path:
+ return self.hermes_home / "state.db"
+
+ @property
+ def log(self) -> Path:
+ return self.spool / f"child-{self.boots}.log"
+
+ def env(self) -> Dict[str, str]:
+ env = {k: os.environ[k] for k in _KEEP_ENV if k in os.environ}
+ env.update({
+ "HOME": str(self.home), "HERMES_HOME": str(self.hermes_home),
+ # The child's HOME is itself a throwaway tmp dir, so ~/.hermes IS the temp home here; the
+ # live-system guard (armed by the inherited isolation marker) would refuse it.
+ "HERMES_STATE_DB_GUARD_BYPASS": "1",
+ "HERMES_GATEWAY_LOCK_DIR": str(self.root / "gateway-locks"),
+ "TZ": "UTC", "PYTHONHASHSEED": "0", "PYTHONUNBUFFERED": "1", "C12_PARENT_PID": str(os.getpid()),
+ "HERMES_DISABLE_LAZY_INSTALLS": "1", "TIRITH_ENABLED": "false",
+ "AWS_EC2_METADATA_DISABLED": "true", "HERMES_HONCHO_HOST": "hermes",
+ "PYTHONPATH": f"{REPO_ROOT}{os.pathsep}{os.environ.get('PYTHONPATH', '')}".rstrip(os.pathsep),
+ })
+ return env
+
+ def start(self) -> "GatewayProcess":
+ assert self.proc is None
+ self.boots += 1
+ ready_before = len(read_jsonl(self.spool / "ready.jsonl"))
+ with open(self.log, "wb") as log:
+ self.proc = subprocess.Popen(
+ [sys.executable, "-m", "tests.e2e.core.delivery._fake_platform", "serve", str(self.spool)],
+ cwd=str(REPO_ROOT), env=self.env(), stdout=log, stderr=subprocess.STDOUT,
+ start_new_session=True)
+ self.pids.append(self.proc.pid)
+ rec = wait_until(
+ lambda: next((r for r in read_jsonl(self.spool / "ready.jsonl")[ready_before:]
+ if r["pid"] == self.proc.pid), None),
+ "gateway child ready", timeout=240, proc=self.proc, log=self.log)
+ self.sock = socket.create_connection(("127.0.0.1", rec["port"]), timeout=120)
+ self._rfile = self.sock.makefile("rb")
+ return self
+
+ def rpc(self, cmd: str, **kw: Any) -> dict:
+ assert self.sock is not None, "gateway not running"
+ self.sock.sendall((json.dumps({"cmd": cmd, **kw}) + "\n").encode())
+ line = self._rfile.readline()
+ if not line:
+ raise AssertionError(f"gateway child closed the RPC channel during {cmd}\n"
+ + self.log.read_text(errors="replace")[-4000:])
+ resp = json.loads(line)
+ assert resp.get("ok"), f"rpc {cmd} failed: {resp}"
+ return resp
+
+ def inject(self, platform: str, text: str, message_id: str, chat_id: str, thread_id: Optional[str] = None):
+ return self.rpc("inject", platform=platform, text=text, message_id=message_id, chat_id=chat_id,
+ thread_id=thread_id)
+
+ def fault(self, **fault: Any) -> None:
+ self.rpc("fault", fault=fault)
+
+ def idle(self, chats: Optional[List[str]]) -> bool:
+ r = self.rpc("busy", chats=chats)
+ return not r["busy"] and not r["running"]
+
+ def wait_idle(self, chats: Optional[List[str]], what: str, timeout: float = DEADLINE, settle: int = 3) -> None:
+ """Idle for ``settle`` consecutive polls (a queued drain task can hop between checks)."""
+ streak = [0]
+
+ def check() -> bool:
+ streak[0] = streak[0] + 1 if self.idle(chats) else 0
+ return streak[0] >= settle
+
+ wait_until(check, what, timeout=timeout, proc=self.proc, log=self.log)
+
+ def holds(self) -> List[dict]:
+ return read_jsonl(self.spool / "holds.jsonl")
+
+ def kill9(self) -> None:
+ assert self.proc is not None
+ assert self.proc.poll() is None, "gateway exited before the kill (a clean exit is not a crash test)"
+ os.killpg(self.proc.pid, signal.SIGKILL)
+ self.proc.wait(timeout=60)
+ self._close()
+
+ def stop(self) -> None:
+ if self.proc is None:
+ return
+ if self.proc.poll() is None:
+ try:
+ os.killpg(self.proc.pid, signal.SIGTERM)
+ self.proc.wait(timeout=60)
+ except (subprocess.TimeoutExpired, ProcessLookupError):
+ try:
+ os.killpg(self.proc.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ self.proc.wait(timeout=30)
+ self._close()
+
+ def _close(self) -> None:
+ for closer in (self._rfile, self.sock):
+ try:
+ if closer is not None:
+ closer.close()
+ except OSError:
+ pass
+ self.sock = self._rfile = None
+ self.proc = None
+
+ # ground truth
+ def platform_view(self) -> FakePlatformServer:
+ return FakePlatformServer(self.spool / "platform.jsonl")
+
+ def ops(self) -> List[dict]:
+ return read_jsonl(self.spool / "ops.jsonl")
+
+
+# Oracle ---------------------------------------------------------------------------------------
+
+RECOVERY_MARKER_PREFIXES: tuple = ()
+
+
+def recovery_markers() -> tuple:
+ from gateway.delivery_ledger import FLOOD_MARKER, RECONNECTED_MARKER, RECOVERED_MARKER
+ return (RECOVERED_MARKER, RECONNECTED_MARKER, FLOOD_MARKER)
+
+
+_CHUNK_INDICATOR = re.compile(r"\s\(\d+/\d+\)\s*$")
+
+
+def norm(text: str) -> str:
+ """Compare text modulo whitespace: platform splitters (base truncate_message, the stream
+ consumer's overflow split) cut at or inside whitespace and strip it, sometimes mid-word."""
+ return "".join((text or "").split())
+
+
+def join_chunks(parts: List[str]) -> str:
+ """Re-join a reply rendered across several messages.
+
+ The stream consumer's fallback continuation deliberately re-sends the broken word when the last
+ landed edit ended mid-word (``StreamFallbackMixin._continuation_text``): a trailing partial word
+ that is a proper prefix of the next chunk's first word is that documented overlap, not content.
+ """
+ out = ""
+ for part in parts:
+ if out and part and not out[-1].isspace():
+ tail = re.split(r"\s", out)[-1]
+ head = (part.split() or [""])[0]
+ if tail and head != tail and head.startswith(tail):
+ out = out[: len(out) - len(tail)]
+ out += part
+ return out
+
+
+def header(aid: str) -> str:
+ return f"<<{aid}>>"
+
+
+def footer(aid: str) -> str:
+ return f"<</{aid}>>"
+
+
+@dataclass
+class Copy:
+ text: str
+ marked: bool
+ complete: bool
+ message_ids: List[str]
+
+
+def visible_copies(msgs: List[PlatformMessage], aid: str) -> List[Copy]:
+ """Every visible rendition of answer ``aid``: starts at a message carrying its header and spans
+ split chunks until the footer. A copy without a footer is incomplete (truncated/stale preview)."""
+ markers = recovery_markers()
+ cleaned = []
+ for m in msgs:
+ text, marked = m.text, False
+ for mk in markers:
+ if text.startswith(mk):
+ text, marked = text[len(mk):], True
+ cleaned.append((m.message_id, _CHUNK_INDICATOR.sub("", text), marked))
+ copies: List[Copy] = []
+ h, f = header(aid), footer(aid)
+ for i, (mid, text, marked) in enumerate(cleaned):
+ start = text.index(h) if h in text else None
+ if start is None:
+ stub = text.strip()
+ if not (len(stub) >= 3 and h.startswith(stub)):
+ continue
+ # A preview cut inside the header itself. When the final edit then fails, the fallback
+ # continuation carries the rest from the original cut (a prefix with no word boundary is
+ # not backed up), so the header spans two messages: one rendition, not a stale stub.
+ ahead = [c[1] for c in cleaned[i + 1:i + 2] if h not in c[1]]
+ if not (ahead and join_chunks([stub, ahead[0]]).startswith(h)):
+ copies.append(Copy(norm(stub), marked, False, [mid]))
+ continue
+ text, start = stub, 0
+ parts, ids = [text[start:]], [mid]
+ j = i
+ while f not in parts[-1] and j + 1 < len(cleaned) and header(aid) not in cleaned[j + 1][1]:
+ j += 1
+ parts.append(cleaned[j][1])
+ ids.append(cleaned[j][0])
+ if f in cleaned[j][1]:
+ break
+ joined = join_chunks(parts)
+ complete = f in joined
+ if complete:
+ joined = joined[: joined.index(f) + len(f)]
+ copies.append(Copy(norm(joined), marked, complete, ids))
+ return copies
+
+
+def persisted_answers(db_path: Path, aid: str) -> List[str]:
+ import sqlite3
+
+ conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30)
+ try:
+ rows = conn.execute(
+ "SELECT content FROM messages WHERE role='assistant' AND content LIKE ? ORDER BY id",
+ (f"%{header(aid)}%",)).fetchall()
+ finally:
+ conn.close()
+ return [r[0] for r in rows]
+
+
+def persisted_user_rows(db_path: Path, token: str) -> List[str]:
+ import sqlite3
+
+ conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30)
+ try:
+ rows = conn.execute("SELECT content FROM messages WHERE role='user' AND content LIKE ? ORDER BY id",
+ (f"%{token}%",)).fetchall()
+ finally:
+ conn.close()
+ return [r[0] for r in rows]
+
+
+if __name__ == "__main__": # pragma: no cover - child process entry
+ if len(sys.argv) >= 3 and sys.argv[1] == "serve":
+ _serve(Path(sys.argv[2]))
diff --git a/tests/e2e/core/delivery/test_messaging_exactly_once.py b/tests/e2e/core/delivery/test_messaging_exactly_once.py
new file mode 100644
index 00000000000..4427d4d172e
--- /dev/null
+++ b/tests/e2e/core/delivery/test_messaging_exactly_once.py
@@ -0,0 +1,599 @@
+"""C12 — messaging-platform delivery exactly-once, through the REAL gateway and the REAL agent.
+
+One real ``GatewayRunner`` (child process, real ``start()``) serves three fake platforms that honour
+the ``BasePlatformAdapter`` contract with different wire semantics — a Telegram-like editable chat
+(4096 cap, streaming on), a Discord-like one (2000 cap, threads, streaming on) and a non-editable
+one (streaming off). The model is ``tests/fakes/fake_llm_provider.py`` scripted per inbound message
+(tool calls, long answers, slow streams). Faults are injected at the platform wire: send timeouts,
+sent-but-ack-lost, 429 with retry_after, connection resets, a slow turn with a busy follow-up,
+interrupts, and SIGKILL of the gateway process between provider completion and the send.
+
+Invariants asserted after every scenario (they hold for every correct implementation):
+
+* every inbound message gets exactly one COMPLETE final visible reply — no duplicate, no truncated
+ or stale partial rendition left visible, never silence;
+* a redelivery that might duplicate an already-visible reply is never silent: any second copy
+ carries a recovery marker (the ledger's documented honest at-least-once), and a delivery that the
+ platform provably never saw is not marked at all;
+* the final visible text equals the persisted assistant text (whitespace-normalised, split chunks
+ re-joined), and the answer is persisted exactly once;
+* no inbound message is processed twice (one user row, one model turn per inbound id);
+* after a crash, catch-up delivers every pending obligation exactly once and does not re-run the
+ already-answered turn.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import sqlite3
+import sys
+import threading
+from pathlib import Path
+from typing import Dict, List, Optional
+
+import pytest
+
+from tests.e2e.core.delivery._fake_platform import (
+ GatewayProcess,
+ read_jsonl,
+ footer,
+ header,
+ norm,
+ persisted_answers,
+ persisted_user_rows,
+ visible_copies,
+ wait_until,
+)
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="SIGKILL + process-group restart harness")
+
+PLATFORMS = {"fk_tg": "telegram", "fk_dc": "discord", "fk_ne": "noedit"}
+STREAMING = {"fk_tg": True, "fk_dc": True, "fk_ne": False}
+EXTRA_CONFIG = (
+ "display:\n"
+ " platforms:\n"
+ " fk_ne:\n"
+ " streaming: false\n"
+)
+
+_TOKEN_RE = re.compile(r"\[in:([A-Za-z0-9_.-]+)\]")
+
+
+class Director:
+ """Scripts the fake model per inbound token and records which turns each token started."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self.scripts: Dict[str, List] = {}
+ self.turns: Dict[str, int] = {}
+ self.resumes: Dict[str, int] = {}
+
+ def script(self, token: str, *responses) -> None:
+ with self._lock:
+ self.scripts[token] = list(responses)
+
+ @staticmethod
+ def answer(aid: str, body: str, **kw) -> Text:
+ return Text(f"{header(aid)} {body} {footer(aid)}", **kw)
+
+ def __call__(self, record: dict):
+ request = record["body"]
+ users = [m for m in request.get("messages", []) if m.get("role") == "user"]
+
+ def text_of(m) -> str:
+ c = m.get("content")
+ if isinstance(c, list):
+ c = " ".join(p.get("text", "") for p in c if isinstance(p, dict))
+ return c or ""
+
+ last = text_of(users[-1]) if users else ""
+ # A resumed turn's recovery note can arrive merged with the original tagged user message
+ # (the unanswered user row and the note are consecutive user turns). It is still a resume,
+ # not a second run of that token.
+ resumed = "previous turn was interrupted" in last.lower()
+ tokens = [] if resumed else _TOKEN_RE.findall(last)
+ # A tool-result continuation re-sends the same last user message: it is the same turn.
+ continuation = request["messages"][-1].get("role") == "tool"
+ with self._lock:
+ if not tokens:
+ # No inbound token in the newest user message: a gateway-synthesized turn (restart
+ # auto-resume). Attribute it to the newest inbound in the history.
+ earlier = [t for m in users for t in _TOKEN_RE.findall(text_of(m))]
+ owner = earlier[-1] if earlier else "none"
+ if not continuation:
+ self.resumes[owner] = self.resumes.get(owner, 0) + 1
+ return self.answer(f"R-{owner}-{self.resumes.get(owner, 0)}", "resumed turn")
+ token = tokens[-1]
+ if not continuation:
+ self.turns[token] = self.turns.get(token, 0) + 1
+ queue = self.scripts.get(token)
+ if queue:
+ return queue.pop(0)
+ n = self.turns.get(token, 0)
+ return self.answer(f"{token}-extra{n}", "unscripted extra turn")
+
+
[email protected](scope="module")
+def director():
+ return Director()
+
+
[email protected](scope="module")
+def llm(director):
+ with FakeLLMServer(director) as srv:
+ yield srv
+
+
[email protected](scope="module")
+def gw(tmp_path_factory, llm):
+ keep = os.environ.get("C12_SPOOL_ROOT") # debugging: keep the child's home/spool after the run
+ root = Path(keep) / f"gw-{os.getpid()}" if keep else tmp_path_factory.mktemp("c12-gw")
+ proc = GatewayProcess(root, platforms=PLATFORMS, llm_base_url=llm.base_url,
+ extra_config=EXTRA_CONFIG)
+ proc.start()
+ yield proc
+ proc.stop()
+
+
+def ledger_rows(db_path: Path, chat: str) -> List[tuple]:
+ conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30)
+ try:
+ return conn.execute("SELECT state, attempts, content FROM delivery_obligations WHERE chat_id=?",
+ (chat,)).fetchall()
+ except sqlite3.OperationalError:
+ return []
+ finally:
+ conn.close()
+
+
+def ledger_quiescent(db_path: Path, chat: str) -> bool:
+ return all(state in ("delivered", "abandoned") for state, _, _ in ledger_rows(db_path, chat))
+
+
+def dump(gw: GatewayProcess, platform: str, chat: str) -> str:
+ lines = [f"--- visible in {platform}:{chat}"]
+ for m in gw.platform_view().visible(platform, chat):
+ lines.append(f" [{m.message_id} edits={m.edits}] {m.text[:160]!r}")
+ lines.append("--- ops")
+ for op in gw.ops():
+ if op.get("platform") == platform and op.get("chat_id") == chat:
+ lines.append(f" {op['op']} {op.get('content', '')[:100]!r}")
+ lines.append(f"--- ledger {ledger_rows(gw.db_path, chat)}")
+ fired = read_jsonl(gw.spool / "faults_fired.jsonl")[-4:]
+ lines.append(f"--- last faults fired {[(f['op'], f['kind'], f['content'][:40]) for f in fired]}")
+ return "\n".join(lines)
+
+
+def assert_exactly_once(gw: GatewayProcess, director: Director, platform: str, chat: str, token: str,
+ aid: str, *, marked_duplicates_allowed: bool = False,
+ first_copy_may_be_marked: bool = False) -> None:
+ ctx = dump(gw, platform, chat)
+ msgs = gw.platform_view().visible(platform, chat)
+ copies = visible_copies(msgs, aid)
+ persisted = persisted_answers(gw.db_path, aid)
+ assert len(persisted) == 1, f"answer {aid} persisted {len(persisted)}x\n{ctx}"
+ want = norm(persisted[0])
+ complete = [c for c in copies if c.complete]
+ partial = [c for c in copies if not c.complete]
+ assert complete, f"no complete visible reply for {aid} (silently lost or truncated)\n{ctx}"
+ assert not partial, f"a truncated/stale partial rendition of {aid} stayed visible: {partial}\n{ctx}"
+ for c in complete:
+ if c.text != want:
+ at = next((i for i, (a, b) in enumerate(zip(c.text, want)) if a != b), min(len(c.text), len(want)))
+ raise AssertionError(
+ f"visible reply != persisted assistant text (whitespace-insensitive), first diff at {at}:\n"
+ f"visible: ...{c.text[max(0, at - 60):at + 60]!r}\npersisted: ...{want[max(0, at - 60):at + 60]!r}\n{ctx}")
+ unmarked = [c for c in complete if not c.marked]
+ marked = [c for c in complete if c.marked]
+ if marked_duplicates_allowed:
+ assert len(unmarked) <= 1, f"{len(unmarked)} unmarked copies of {aid} (silent duplicate)\n{ctx}"
+ elif first_copy_may_be_marked:
+ assert len(complete) == 1, f"{len(complete)} visible copies of {aid}, expected exactly one\n{ctx}"
+ else:
+ assert len(unmarked) == 1 and not marked, (
+ f"expected exactly one unmarked reply for {aid}: unmarked={len(unmarked)} marked={len(marked)}\n{ctx}")
+ stray = [m.text[:80] for m in msgs if "<<R-" in m.text or "-extra" in m.text.split(">>")[0]]
+ assert not stray, f"an extra model turn (re-run / auto-resume) replied in this chat: {stray}\n{ctx}"
+ assert not director.resumes.get(token), f"inbound {token} was re-run by auto-resume\n{ctx}"
+ rows = persisted_user_rows(gw.db_path, f"[in:{token}]")
+ assert len(rows) == 1, f"inbound {token} persisted {len(rows)}x as a user turn\n{ctx}"
+ assert director.turns.get(token) == 1, f"inbound {token} started {director.turns.get(token)} model turns\n{ctx}"
+
+
+LONG = " ".join(f"word{i:04d}" for i in range(900)) # ~8.1k chars: splits on both caps
+SLOW = dict(chunk_chars=6, delay_per_chunk=0.03) # a ~2 s stream: preview + several edits
+
+
+def _say(body: str, **kw):
+ return lambda aid: [Director.answer(aid, body, **kw)]
+
+
+# fault id -> (fault kind | None, op, target, responses(aid), expectation)
+# op: "send" | "edit" | "any"; target: "footer" = the op carrying the FINAL text,
+# "header" = the first op of the reply (the stream preview's first send)
+# expectation: exact = one unmarked copy, nothing else; one_copy = exactly one complete copy (a
+# retry of a never-seen send may carry the honest "may be a duplicate" marker); marked_dupes = the
+# platform may hold a second copy (ack lost) but every extra copy is marked.
+FAULTS = {
+ "clean": (None, "any", "footer", _say("short answer."), "exact"),
+ "tool_then_answer": (None, "any", "footer",
+ lambda aid: [ToolCall("terminal", {"command": "echo hi"}),
+ Director.answer(aid, "after the tool, done.")], "exact"),
+ "long_split": (None, "any", "footer", _say(LONG, chunk_chars=400), "exact"),
+ "long_streamed": (None, "any", "footer", _say(LONG, chunk_chars=120, delay_per_chunk=0.01), "exact"),
+ # Two 4.5k bursts 3 s apart (edit interval 0.8 s): the first send overflows (split, tail kept as
+ # the live preview), then the second burst leaves a remainder over the limit after sealing.
+ "burst_overflow": (None, "any", "footer", _say(LONG, chunk_chars=4500, delay_per_chunk=3.0), "exact"),
+ "slow_stream": (None, "any", "footer", _say("a slowly streamed answer " * 6, **SLOW), "exact"),
+ "rate_limit_429": ("rate_limit", "any", "footer", _say("throttled once then fine."), "exact"),
+ "conn_reset": ("conn_error", "any", "footer", _say("connection reset once."), "exact"),
+ "send_timeout": ("timeout", "any", "footer", _say("platform never saw the first try."), "one_copy"),
+ # One chunk: on streaming platforms the consumer's FIRST send then carries the whole reply (and
+ # the footer the fault targets), so the ack is always lost on that send, never on a later edit.
+ "ack_lost": ("ack_lost", "any", "footer", _say("sent but the ack vanished.", chunk_chars=10_000), "marked_dupes"),
+ "stream_429_final_edit": ("rate_limit", "any", "footer", _say("stream throttled " * 8, **SLOW), "exact"),
+ "stream_timeout_final_edit": ("timeout", "any", "footer", _say("stream final lost " * 8, **SLOW),
+ "one_copy"),
+ "stream_ack_lost_final_edit": ("ack_lost", "any", "footer", _say("stream ack lost " * 8, **SLOW),
+ "marked_dupes"),
+ "stream_timeout_first_send": ("timeout", "send", "header", _say("preview never landed " * 8, **SLOW),
+ "one_copy"),
+}
+
+
+# Red until #120315 lands (overflow tail keeps the "(n/n)" indicator / seal remainder re-sent;
+# uneditable partial preview after a failed first send): every streamed reply over the platform
+# limit, plus the first-send timeout. Value = strict: burst_overflow and the 2000-char first-send
+# timeout fail every run; the others depend on stream/edit-tick timing, so a strict mark would flake
+# on the runs where the bug does not trigger. Delete the table with #120315.
+UNLANDED_STREAM_FIX = {
+ ("burst_overflow", "fk_tg"): True,
+ ("burst_overflow", "fk_dc"): True,
+ ("stream_timeout_first_send", "fk_dc"): True,
+ ("stream_timeout_first_send", "fk_tg"): False,
+ ("long_split", "fk_tg"): False,
+ ("long_split", "fk_dc"): False,
+ ("long_streamed", "fk_tg"): False,
+ ("long_streamed", "fk_dc"): False,
+}
+
+
+STREAM_ACK_LOST_GAP = (
+ "LIVE GAP (#53449/#25349 family): on a streaming platform the stream consumer's first send is the "
+ "whole short reply; when the platform accepts it but the ack is lost (timeout), the consumer reports "
+ "nothing delivered and the gateway's final send re-sends it UNMARKED -> the user sees the reply "
+ "twice with no 'may be a duplicate' marker. The non-streaming path hands the same timeout to the "
+ "delivery ledger, which redelivers with the marker.")
+
+
+def faults_fired(gw: GatewayProcess, aid: str) -> List[dict]:
+ chat = "m-" + aid[2:].replace(".", "-", 1)
+ return [f for f in read_jsonl(gw.spool / "faults_fired.jsonl") if f.get("chat_id") == chat]
+
+
[email protected]("platform", list(PLATFORMS))
[email protected]("fault", list(FAULTS))
+def test_delivery_fault_matrix(gw, director, platform, fault, request):
+ kind, op, target, build, expect = FAULTS[fault]
+ token = f"{platform}.{fault}"
+ chat = f"m-{platform}-{fault}"
+ aid = f"A-{token}"
+ director.script(token, *build(aid))
+ if kind is not None:
+ if target == "footer":
+ gw.fault(platform=platform, op=op, kind=kind, contains=footer(aid), chat_id=chat)
+ else: # the reply's first platform call, whatever it carries (a stream preview is a prefix)
+ gw.fault(platform=platform, op=op, kind=kind, chat_id=chat)
+ gw.inject(platform, f"[in:{token}] please answer", message_id=f"in-{token}", chat_id=chat)
+ gw.wait_idle([chat], f"{token} turn to finish")
+ wait_until(lambda: ledger_quiescent(gw.db_path, chat), f"{token} ledger to settle",
+ proc=gw.proc, log=gw.log)
+ wait_until(lambda: any(c.complete for c in visible_copies(gw.platform_view().visible(platform, chat), aid)),
+ f"{token} complete reply\n" + dump(gw, platform, chat), proc=gw.proc, log=gw.log)
+ if kind is not None:
+ assert faults_fired(gw, aid), f"injected {kind} never hit a platform call\n{dump(gw, platform, chat)}"
+ if fault == "ack_lost" and STREAMING[platform]:
+ request.applymarker(pytest.mark.xfail(strict=True, reason=STREAM_ACK_LOST_GAP))
+ if (fault, platform) in UNLANDED_STREAM_FIX:
+ request.applymarker(pytest.mark.xfail(strict=UNLANDED_STREAM_FIX[(fault, platform)],
+ reason="fixed by #120315"))
+ assert_exactly_once(gw, director, platform, chat, token, aid,
+ marked_duplicates_allowed=expect == "marked_dupes",
+ first_copy_may_be_marked=expect == "one_copy")
+
+
+# Concurrency: slow turn + busy follow-up, interrupt, parallel threads -------------------------
+
+
+def _first_op_seen(gw: GatewayProcess, platform: str, chat: str) -> bool:
+ return any(o.get("platform") == platform and o.get("chat_id") == chat and o["op"] in ("send", "edit")
+ for o in gw.ops())
+
+
+def _order(gw: GatewayProcess, platform: str, chat: str, aid: str) -> int:
+ for i, m in enumerate(gw.platform_view().visible(platform, chat)):
+ if header(aid) in m.text:
+ return i
+ return -1
+
+
+VERY_SLOW = dict(chunk_chars=6, delay_per_chunk=0.08)
+
+
[email protected]("platform", ["fk_tg", "fk_ne"])
+def test_slow_turn_with_queued_followup(gw, director, platform):
+ """A follow-up sent with /queue while the first turn streams: both inbound messages get exactly
+ one complete reply, in arrival order, and neither turn runs twice."""
+ t1, t2 = f"{platform}.q1", f"{platform}.q2"
+ chat = f"q-{platform}"
+ director.script(t1, Director.answer(f"A-{t1}", "first, slowly " * 10, **VERY_SLOW))
+ director.script(t2, Director.answer(f"A-{t2}", "second answer."))
+ gw.inject(platform, f"[in:{t1}] first", message_id=f"in-{t1}", chat_id=chat)
+ wait_until(lambda: director.turns.get(t1) == 1, f"{t1} model turn to start", proc=gw.proc, log=gw.log)
+ gw.inject(platform, f"/queue [in:{t2}] second", message_id=f"in-{t2}", chat_id=chat)
+ gw.wait_idle([chat], "both turns to drain")
+ wait_until(lambda: ledger_quiescent(gw.db_path, chat), "ledger to settle", proc=gw.proc, log=gw.log)
+ for tok in (t1, t2):
+ assert_exactly_once(gw, director, platform, chat, tok, f"A-{tok}")
+ assert 0 <= _order(gw, platform, chat, f"A-{t1}") < _order(gw, platform, chat, f"A-{t2}"), dump(gw, platform, chat)
+
+
[email protected]("platform", ["fk_tg", "fk_ne"])
+def test_slow_turn_interrupted_by_followup(gw, director, platform):
+ """A plain follow-up interrupts the running turn (default busy mode). The follow-up gets exactly
+ one complete reply; the interrupted turn never leaves a second or stale-partial copy behind and
+ is not re-run; nothing is persisted twice."""
+ t1, t2 = f"{platform}.i1", f"{platform}.i2"
+ chat = f"i-{platform}"
+ director.script(t1, Director.answer(f"A-{t1}", "long interrupted answer " * 30, **VERY_SLOW))
+ director.script(t2, Director.answer(f"A-{t2}", "the follow-up answer."))
+ gw.inject(platform, f"[in:{t1}] first", message_id=f"in-{t1}", chat_id=chat)
+ wait_until(lambda: director.turns.get(t1) == 1, f"{t1} model turn to start", proc=gw.proc, log=gw.log)
+ if STREAMING[platform]:
+ wait_until(lambda: _first_op_seen(gw, platform, chat), "first preview", proc=gw.proc, log=gw.log)
+ gw.inject(platform, f"[in:{t2}] actually, do this instead", message_id=f"in-{t2}", chat_id=chat)
+ gw.wait_idle([chat], "interrupt + follow-up to drain")
+ wait_until(lambda: ledger_quiescent(gw.db_path, chat), "ledger to settle", proc=gw.proc, log=gw.log)
+ print(dump(gw, platform, chat))
+ assert_exactly_once(gw, director, platform, chat, t2, f"A-{t2}")
+ assert director.turns.get(t1) == 1, dump(gw, platform, chat)
+ assert len(persisted_user_rows(gw.db_path, f"[in:{t1}]")) == 1, dump(gw, platform, chat)
+ copies = visible_copies(gw.platform_view().visible(platform, chat), f"A-{t1}")
+ assert len([c for c in copies if c.complete]) <= 1, dump(gw, platform, chat)
+
+
+def test_parallel_threads_are_independent(gw, director):
+ """Two Discord threads in one channel run slow turns at the same time: each gets exactly one
+ complete reply, delivered into its own thread."""
+ chat = "par-dc"
+ toks = ["fk_dc.th1", "fk_dc.th2"]
+ for tok in toks:
+ director.script(tok, Director.answer(f"A-{tok}", f"reply for {tok} " * 8, **SLOW))
+ for n, tok in enumerate(toks):
+ gw.inject("fk_dc", f"[in:{tok}] go", message_id=f"in-{tok}", chat_id=chat, thread_id=f"thr{n}")
+ gw.wait_idle([chat], "both threads to finish")
+ for n, tok in enumerate(toks):
+ wait_until(lambda: ledger_quiescent(gw.db_path, chat), "ledger to settle", proc=gw.proc, log=gw.log)
+ assert_exactly_once(gw, director, "fk_dc", chat, tok, f"A-{tok}")
+ threads = {m.thread_id for m in gw.platform_view().visible("fk_dc", chat) if header(f"A-{tok}") in m.text}
+ assert threads == {f"thr{n}"}, f"{tok} delivered into {threads}\n{dump(gw, 'fk_dc', chat)}"
+
+
+# Inbound re-delivery ---------------------------------------------------------------------------
+
+
[email protected]("when", ["during_turn", "after_turn", "after_reconnect"])
+def test_redelivered_inbound_id_processed_once(gw, director, when, request):
+ """The platform re-delivers an inbound id (webhook retry, websocket resume, reconnect replay):
+ the message is processed exactly once and answered exactly once."""
+ platform = "fk_tg"
+ tok = f"{platform}.redeliver-{when}"
+ chat = f"r-{when}"
+ director.script(tok, Director.answer(f"A-{tok}", "answer once " * 6, **SLOW))
+ text, mid = f"[in:{tok}] hello", f"in-{tok}"
+ gw.inject(platform, text, message_id=mid, chat_id=chat)
+ if when == "during_turn":
+ wait_until(lambda: director.turns.get(tok) == 1, "turn start", proc=gw.proc, log=gw.log)
+ gw.inject(platform, text, message_id=mid, chat_id=chat)
+ gw.wait_idle([chat], f"{tok} turn")
+ if when == "after_turn":
+ gw.inject(platform, text, message_id=mid, chat_id=chat)
+ if when == "after_reconnect":
+ request.applymarker(pytest.mark.xfail(strict=True, reason=RECONNECT_DEDUP_GAP))
+ before = gw.rpc("reconnect", platform=platform)["id"]
+ wait_until(lambda: gw.rpc("adapter_id", platform=platform)["id"] not in (before, None),
+ "the reconnect watcher to install a fresh adapter", proc=gw.proc, log=gw.log)
+ gw.inject(platform, text, message_id=mid, chat_id=chat)
+ gw.wait_idle([chat], f"{tok} after re-delivery")
+ wait_until(lambda: ledger_quiescent(gw.db_path, chat), "ledger to settle", proc=gw.proc, log=gw.log)
+ assert_exactly_once(gw, director, platform, chat, tok, f"A-{tok}")
+
+
+RECONNECT_DEDUP_GAP = (
+ "LIVE GAP (#119848 family): inbound de-duplication state lives on the adapter instance "
+ "(MessageDeduplicator); the gateway's reconnect watcher builds a FRESH adapter, so a platform "
+ "replaying a recent inbound id after the reconnect gets it processed and answered a second time.")
+
+
+# Crash between provider completion and the send: SIGKILL + restart on the same state ------------
+
+# crash point -> (fault op, fault kind)
+CRASH_POINTS = {
+ # the turn returned (persisted), the final text not yet handed to the delivery ledger
+ "completed_not_ledgered": ("pre_ledger", "hold"),
+ # the final send/edit is in flight and the platform never saw it
+ "send_in_flight": ("any", "hold"),
+ # the platform accepted the final send/edit; the ack died with the process
+ "sent_ack_lost": ("any", "hold_after"),
+}
+
+# completed_not_ledgered: GatewayRunner._handle_message clears the durable active-turn marker in its
+# finally BEFORE the base adapter records the delivery obligation, so a SIGKILL in that window leaves
+# neither a resume marker nor a ledger row. Today the reply is still recovered - by the 120 s recency
+# fallback re-running the turn (see RECENCY_FALLBACK_GAP). If that fallback is narrowed without
+# closing the window, this scenario goes red: the persisted answer is then never delivered.
+STREAM_CRASH_AFTER_ACCEPT_GAP = (
+ "LIVE GAP: streaming turn, the platform already shows the complete final answer, SIGKILL before "
+ "the turn is persisted -> restart auto-resumes and the model answers AGAIN; the second answer is "
+ "unmarked and the first (visible) answer was never persisted (visible != transcript).")
+
+
+def _replies(gw: GatewayProcess, platform: str, chat: str, token: str, aid: str):
+ msgs = gw.platform_view().visible(platform, chat)
+ originals = visible_copies(msgs, aid)
+ resumes = [c for n in range(1, 6) for c in visible_copies(msgs, f"R-{token}-{n}")]
+ return originals, resumes
+
+
+CRASH_MATRIX = [("completed_not_ledgered", "fk_ne"), # streaming finals are sent before the handler returns
+ ("send_in_flight", "fk_ne"), ("send_in_flight", "fk_tg"),
+ ("sent_ack_lost", "fk_ne"), ("sent_ack_lost", "fk_tg")]
+
+
+def fresh_gw(tmp_path, llm):
+ """A gateway on its OWN home: one unclean restart per home keeps the restart-loop breaker and
+ the 120 s recency fallback of other scenarios out of the picture."""
+ keep = os.environ.get("C12_SPOOL_ROOT")
+ root = Path(keep) / f"crash-{tmp_path.name}" if keep else tmp_path / "gw"
+ proc = GatewayProcess(root, platforms=PLATFORMS, llm_base_url=llm.base_url, extra_config=EXTRA_CONFIG)
+ proc.start()
+ yield proc
+ proc.stop()
+
+
[email protected]("point,platform", CRASH_MATRIX)
+def test_crash_between_completion_and_send(fresh_gw, director, point, platform, request):
+ """kill -9 the gateway at a point between provider completion and the platform ack, restart it
+ on the same HERMES_HOME. Recovery may be the delivery ledger (redeliver the held answer) or,
+ for a turn that never finished, auto-resume (a fresh model turn): either way the inbound ends
+ with exactly ONE complete visible reply that matches the transcript, and any second copy the
+ platform may hold is marked as a possible duplicate."""
+ gw = fresh_gw
+ op, kind = CRASH_POINTS[point]
+ streaming = STREAMING[platform]
+ if point == "sent_ack_lost" and streaming:
+ request.applymarker(pytest.mark.xfail(strict=True, reason=STREAM_CRASH_AFTER_ACCEPT_GAP))
+ token = f"{platform}.crash-{point}"
+ chat = f"k-{platform}-{point}"
+ aid = f"A-{token}"
+ director.script(token, Director.answer(aid, "answer computed before the crash."))
+ gw.fault(platform=platform, op=op, kind=kind, contains=footer(aid), chat_id=chat)
+ gw.inject(platform, f"[in:{token}] question", message_id=f"in-{token}", chat_id=chat)
+ wait_until(lambda: any(footer(aid) in h["content"] for h in gw.holds()), f"{token} to reach the crash point",
+ proc=gw.proc, log=gw.log)
+ gw.kill9()
+ gw.start()
+
+ def replied() -> bool:
+ originals, resumes = _replies(gw, platform, chat, token, aid)
+ return any(c.complete for c in originals + resumes)
+
+ wait_until(replied, f"{token} catch-up reply after restart\n" + dump(gw, platform, chat),
+ proc=gw.proc, log=gw.log)
+ gw.wait_idle([chat], f"{token} to settle after restart")
+ wait_until(lambda: ledger_quiescent(gw.db_path, chat), f"{token} ledger to settle", proc=gw.proc, log=gw.log)
+ ctx = dump(gw, platform, chat)
+ originals, resumes = _replies(gw, platform, chat, token, aid)
+ complete = [c for c in originals + resumes if c.complete]
+ unmarked = [c for c in complete if not c.marked]
+ assert len(unmarked) <= 1, f"{len(unmarked)} unmarked complete replies after catch-up\n{ctx}"
+ assert len(complete) - len(unmarked) <= (1 if point == "sent_ack_lost" else 0) or not unmarked, (
+ f"unexpected extra marked copies\n{ctx}")
+ # A crash mid-stream may leave the interrupted preview on screen; nothing else may be partial.
+ assert not [c for c in resumes if not c.complete], ctx
+ if not streaming:
+ assert not [c for c in originals if not c.complete], ctx
+ assert not (resumes and [c for c in originals if c.complete]), (
+ f"both the held answer and an auto-resumed re-answer are visible\n{ctx}")
+ final = resumes[0] if resumes else next(c for c in originals if c.complete)
+ final_aid = aid if not resumes else f"R-{token}-{director.resumes.get(token, 0)}"
+ persisted = persisted_answers(gw.db_path, final_aid)
+ assert len(persisted) == 1 and norm(persisted[0]) == final.text, (
+ f"visible final reply is not the (single) persisted assistant text: persisted={persisted}\n{ctx}")
+ assert director.turns.get(token) == 1, ctx
+ assert len(persisted_user_rows(gw.db_path, f"[in:{token}]")) == 1, ctx
+
+
+# Scenarios whose strict xfail documents a live gap: excluded from the whole-run audit below.
+KNOWN_GAP_TOKENS = {"fk_tg.ack_lost", "fk_dc.ack_lost", "fk_tg.redeliver-after_reconnect"}
+RESUME_EXPECTED: set = set()
+
+
+def test_zz_whole_run_audit(gw, director):
+ """Across EVERY chat of the module (every scenario, every restart): no inbound ended with two
+ unmarked complete replies (held answer, extra turn or auto-resume), and no already-answered
+ inbound was re-run by a LATER restart's auto-resume."""
+ visible = gw.platform_view().visible()
+ head = re.compile(r"<<((?:A-|R-)?[A-Za-z0-9_.-]+?)>>")
+ problems = []
+ for token in sorted(director.turns):
+ if token in KNOWN_GAP_TOKENS or ".crash-" in token: # crash scenarios run on their own homes
+ continue
+ ids = {m.group(1) for v in visible for m in head.finditer(v.text)
+ if m.group(1) in (f"A-{token}",) or m.group(1).startswith((f"R-{token}-", f"{token}-extra"))}
+ unmarked = 0
+ for aid in ids:
+ by_chat: Dict[str, list] = {}
+ for v in visible:
+ by_chat.setdefault((v.platform, v.chat_id), []).append(v)
+ for msgs in by_chat.values():
+ unmarked += sum(1 for c in visible_copies(msgs, aid) if c.complete and not c.marked)
+ if unmarked > 1:
+ problems.append(f"{token}: {unmarked} unmarked complete replies ({sorted(ids)})")
+ if director.resumes.get(token) and token not in RESUME_EXPECTED:
+ problems.append(f"{token}: re-run by auto-resume {director.resumes[token]}x after it was answered")
+ assert not problems, "\n".join(problems)
+
+
+RECENCY_FALLBACK_GAP = (
+ "LIVE GAP: on an unclean startup GatewayRunner._recover_unclean_sessions also runs the legacy "
+ "recency fallback SessionStore.suspend_recently_active(120), which marks EVERY session updated in "
+ "the last 120 s resume_pending with reason 'restart_interrupted' - a reason in _AUTO_RESUME_REASONS - "
+ "so _schedule_resume_pending_sessions synthesizes a turn for sessions whose turn had already "
+ "completed and been delivered: after a crash/OOM/kill -9 every recently active chat gets an "
+ "unsolicited second answer.")
+
+
[email protected](strict=True, reason=RECENCY_FALLBACK_GAP)
+def test_zzz_unclean_restart_reruns_nothing(gw, director):
+ """Runs LAST on the module gateway: after every scenario above has been answered, an unclean
+ restart with NOTHING in flight must not re-run or re-deliver anything."""
+ tok = "fk_tg.quiet-restart"
+ director.script(tok, Director.answer(f"A-{tok}", "answered long before the crash."))
+ gw.inject("fk_tg", f"[in:{tok}] hi", message_id=f"in-{tok}", chat_id="quiet")
+ gw.wait_idle(None, "every chat idle before the crash", settle=5)
+ wait_until(lambda: all(state in ("delivered", "abandoned") for state, _, _ in all_ledger_rows(gw.db_path)),
+ "ledger quiescent before the crash", proc=gw.proc, log=gw.log)
+ assert_exactly_once(gw, director, "fk_tg", "quiet", tok, f"A-{tok}")
+ before = {m.message_id for m in gw.platform_view().visible()}
+ turns = dict(director.turns)
+ gw.kill9()
+ gw.start()
+ # A buggy restart shows its first extra reply within a few seconds of boot; a correct one never
+ # does. Waiting for the bad outcome (not for idleness) keeps the check honest on a slow box.
+ try:
+ wait_until(lambda: [m for m in gw.platform_view().visible() if m.message_id not in before],
+ "an unsolicited post-restart reply", timeout=30, proc=gw.proc, log=gw.log)
+ except AssertionError as exc:
+ if "timed out" not in str(exc):
+ raise
+ gw.wait_idle(None, "the restarted gateway to go idle", settle=5)
+ new = [m for m in gw.platform_view().visible() if m.message_id not in before]
+ assert not new, f"an unclean restart with nothing in flight delivered {len(new)} new messages, e.g.:\n" + \
+ "\n".join(f" {m.chat_id}: {m.text[:100]!r}" for m in new[:8])
+ assert director.turns == turns and not director.resumes, f"model re-run after restart: {director.resumes}"
+
+
+
+
+def all_ledger_rows(db_path: Path) -> List[tuple]:
+ conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30)
+ try:
+ return conn.execute("SELECT state, attempts, chat_id FROM delivery_obligations").fetchall()
+ except sqlite3.OperationalError:
+ return []
+ finally:
+ conn.close()