Skip to content

The agent that grows with you

test(e2e): drop probes for merged delivery fixes; run-time xfails for gaps with no fix PR

teknium11a6b0825aa25
diff --git a/tests/conformance/persistence/README.md b/tests/conformance/persistence/README.md
index 1b959835f48..05e88d27007 100644
--- a/tests/conformance/persistence/README.md
+++ b/tests/conformance/persistence/README.md
@@ -14,7 +14,7 @@ process mid-write.
| 2 — `test_cell2_consume_once` | a parked handoff is claimed by exactly one of N racing processes | adapted from the tracking issue's spot-probe (8-process file-barrier race) |
| 3 — `test_cell3_rotation_atomicity` | a compression rotation is visible entirely or not at all — never a compression-ended parent without a continuation (the #80337 orphan shape; recovery for the legacy population merged in #80487) | new in this suite |
| 4 — fork determinism on edit/rewind | recovery yields exactly the chosen prefix after a fork | **stub** — interlocked with the rewind/archive redesign (#82956–#82959) |
-| 5 — `test_cell5_delivery_outbox_exactly_once` | a crash between provider send and durable record must not double-deliver on catch-up (gateway reboot): per obligation ≤1 unmarked copy, ≥1 copy, every extra copy carries a recovery marker, ledger terminal after the boot sweep, later reboots send nothing; concurrent rebooters never both claim/send a row — effect exactly-once, distinct from cell 2's consume-once | **implemented** — real ledger + real `GatewayRunner` boot claim/redeliver halves, SIGKILL at each kill point; only the transport is faked (fsync'd journal). One **fire**, strict-xfail while it reproduces (fix: #120450): a boot killed inside a *plain* ('pending') redelivery resends it unmarked next boot. Cron-ticker catch-up not covered yet (#83197/#83557) |
+| 5 — `test_cell5_delivery_outbox_exactly_once` | a crash between provider send and durable record must not double-deliver on catch-up (gateway reboot): per obligation ≤1 unmarked copy, ≥1 copy, every extra copy carries a recovery marker, ledger terminal after the boot sweep, later reboots send nothing; concurrent rebooters never both claim/send a row — effect exactly-once, distinct from cell 2's consume-once | **implemented** — real ledger + real `GatewayRunner` boot claim/redeliver halves, SIGKILL at each kill point; only the transport is faked (fsync'd journal); a boot killed inside a *plain* ('pending') redelivery must not resend it unmarked next boot (the #120450 fire, now a plain passing cell). Cron-ticker catch-up not covered yet (#83197/#83557) |
## Method
diff --git a/tests/conformance/persistence/test_cell5_delivery_outbox_exactly_once.py b/tests/conformance/persistence/test_cell5_delivery_outbox_exactly_once.py
index 57b0c8fb994..c665934ad3b 100644
--- a/tests/conformance/persistence/test_cell5_delivery_outbox_exactly_once.py
+++ b/tests/conformance/persistence/test_cell5_delivery_outbox_exactly_once.py
@@ -75,7 +75,6 @@ from tests.conformance.persistence._harness import (
reap,
wait_for,
)
-from tests.e2e.core.delivery._pending_fixes import expect_gap
SESSION_KEY = "agent:main:telegram:dm:cell5"
CHAT_ID = "4242"
@@ -447,16 +446,8 @@ def test_crash_between_send_and_record_never_double_delivers(tmp_path, kill_poin
assert integrity_ok(cell.db_path)
-PLAIN_REDELIVERY_GAP = (
- "FIRE (cell 5, fixed by #120450): sweep_recoverable claims a 'pending' row without flipping it "
- "to 'attempting', and _redeliver_claimed_obligations never marks it attempting before the send "
- "— a boot killed inside that resend leaves it 'pending', so the next boot resends it UNMARKED "
- "(2 unmarked copies)."
-)
-
-
-def test_boot_killed_inside_plain_redelivery_never_double_delivers(tmp_path, request):
- expect_gap(request, 120450, PLAIN_REDELIVERY_GAP) # strict xfail only while the gap reproduces
+def test_boot_killed_inside_plain_redelivery_never_double_delivers(tmp_path):
+ """A boot killed inside a plain ('pending') redelivery must not resend it unmarked next boot."""
cell = Cell(tmp_path)
ids = cell.seed_and_crash(["pending"] * N_OBLIGATIONS)
cell.crashing_boot()
diff --git a/tests/e2e/core/delivery/_pending_fixes.py b/tests/e2e/core/delivery/_pending_fixes.py
index b8ce631bf33..26374b9c1ec 100644
--- a/tests/e2e/core/delivery/_pending_fixes.py
+++ b/tests/e2e/core/delivery/_pending_fixes.py
@@ -9,19 +9,26 @@ cell runs as a plain test, so it must pass. Whichever lands first, suite or fix,
green, and a probe that disagrees with the end-to-end cell still fails loudly (XPASS, or a
real failure) instead of hiding.
-When a fix has landed, delete its entry and every ``expect_gap`` call naming it.
+Probes exercise behaviour only (never read source text). When a fix has landed, delete its
+entry and every ``expect_gap`` / ``gap_open`` call naming it.
+
+A gap with no fix PR yet has no probe: ``known_failure`` is a run-time xfail keyed on the gap's
+own assertion message, so the cell XFAILs only while it fails exactly that way, fails loudly on
+any other failure, and simply passes once someone fixes the gap.
"""
from __future__ import annotations
+import contextlib
import functools
import json
import os
+import re
import subprocess
import sys
import tempfile
from pathlib import Path
-from typing import Dict
+from typing import Callable, Dict, Iterator, Optional
import pytest
@@ -32,20 +39,6 @@ _PRELUDE = "import json, os, sys\nsys.path.insert(0, os.getcwd())\n"
# PR -> (extra env, script). A script prints ``open`` while the defect reproduces, ``fixed`` once
# it no longer does; anything else (including a crash) fails the cell that asked.
PROBES: Dict[int, tuple] = {
- # The due gate compared same-zone wall clocks: 01:00 EST (fold=1) looked due at 01:01 EDT.
- 120314: ({"HERMES_TIMEZONE": "America/New_York", "TZ": "UTC"}, r'''
-from datetime import datetime, timezone
-from zoneinfo import ZoneInfo
-from cron import jobs
-ny = ZoneInfo("America/New_York")
-now = datetime(2026, 11, 1, 5, 1, tzinfo=timezone.utc).astimezone(ny) # 01:01 EDT
-scheduled = datetime(2026, 11, 1, 6, 0, tzinfo=timezone.utc).astimezone(ny) # 01:00 EST, 59 min later
-jobs._hermes_now = lambda: now
-jobs.save_jobs([{"id": "p", "name": "p", "prompt": "p", "schedule": {"kind": "interval", "minutes": 60},
- "next_run_at": scheduled.isoformat(), "last_run_at": None, "enabled": True,
- "state": "scheduled", "repeat": {"times": None, "completed": 0}, "deliver": "local"}])
-print("open" if jobs.get_due_jobs() else "fixed")
-'''),
# No timezone configured: the next cron occurrence kept the base time's fixed UTC offset, so a
# 09:00 job in a DST process zone fired at 10:00 local the day after spring-forward.
119970: ({"TZ": "America/New_York"}, r'''
@@ -89,36 +82,6 @@ async def main():
print("fixed" if asyncio.run(main()) == ["preview never landed and more streamed text then the end."]
else "open")
-'''),
- # Unclean startup ran the 120 s recency sweep: every recently active session was marked
- # resume_pending and auto-resumed, i.e. answered a second time.
- 120377: ({}, r'''
-import inspect
-from gateway.run import GatewayRunner
-src = inspect.getsource(GatewayRunner._recover_unclean_sessions)
-print("open" if "suspend_recently_active" in src else "fixed")
-'''),
- # Inbound de-duplication lived only on the adapter instance; the reconnect watcher builds a
- # fresh adapter without it, so a replay after a reconnect was processed again.
- 120444: ({}, r'''
-import inspect
-from gateway.run import GatewayRunner
-src = inspect.getsource(GatewayRunner._reconnect_failed_platform)
-print("fixed" if "dedup" in src.lower() else "open")
-'''),
- # The boot sweep claimed a 'pending' row without moving it to 'attempting', so a boot killed
- # inside that plain resend left 'pending' behind and the next boot resent it UNMARKED.
- 120450: ({}, r'''
-import sqlite3
-from gateway import delivery_ledger as L
-L.record_obligation(obligation_id="p", session_key="k", platform="telegram", chat_id="1",
- thread_id=None, content="x")
-with L._transaction() as conn:
- conn.execute("UPDATE delivery_obligations SET owner_pid=NULL, owner_started_at=NULL")
-assert [r["obligation_id"] for r in L.sweep_recoverable()] == ["p"]
-with L._transaction() as conn:
- state = conn.execute("SELECT state FROM delivery_obligations").fetchone()[0]
-print("fixed" if state == "attempting" else "open")
'''),
}
@@ -148,3 +111,20 @@ def expect_gap(request, pr: int, reason: str) -> None:
assert f"#{pr}" in reason, f"reason for a #{pr} gap must name the PR: {reason!r}"
if gap_open(pr):
request.applymarker(pytest.mark.xfail(strict=True, reason=reason))
+
+
+def known_failure(pattern: str, reason: str,
+ on_xfail: Optional[Callable[[], None]] = None) -> Iterator[None]:
+ """Run-time xfail for a live gap without a fix PR: an ``AssertionError`` raised inside the
+ block whose message matches ``pattern`` XFAILs the cell; any other failure propagates, and a
+ clean pass stays a pass. Wrap only the final assertions, after every wait has settled, so a
+ lost reply, a failed restart or a timeout can never be mistaken for the gap."""
+ try:
+ yield
+ except AssertionError as exc:
+ if not re.search(pattern, str(exc)):
+ raise
+ if on_xfail is not None:
+ on_xfail()
+ pytest.xfail(f"{reason} [observed: {str(exc).splitlines()[0][:240]}]")
diff --git a/tests/e2e/core/delivery/test_messaging_exactly_once.py b/tests/e2e/core/delivery/test_messaging_exactly_once.py
index e1e8bb15524..bf5cbd57136 100644
--- a/tests/e2e/core/delivery/test_messaging_exactly_once.py
+++ b/tests/e2e/core/delivery/test_messaging_exactly_once.py
@@ -24,6 +24,7 @@ Invariants asserted after every scenario (they hold for every correct implementa
from __future__ import annotations
+import contextlib
import os
import re
import sqlite3
@@ -45,7 +46,7 @@ from tests.e2e.core.delivery._fake_platform import (
visible_copies,
wait_until,
)
-from tests.e2e.core.delivery._pending_fixes import expect_gap, gap_open
+from tests.e2e.core.delivery._pending_fixes import expect_gap, known_failure
from tests.fakes.fake_llm_provider import FakeLLMServer, StallMidStream, Text, ToolCall
pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="SIGKILL + process-group restart harness")
@@ -269,6 +270,11 @@ STREAM_ACK_LOST_GAP = (
"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.")
+# No fix PR yet: a run-time xfail on this exact failure (see _pending_fixes.known_failure), so the
+# cell passes on its own the day the gap closes.
+STREAM_ACK_LOST_SIGNATURE = r"^\d+ unmarked copies of A-fk_(tg|dc)\.ack_lost \(silent duplicate\)"
+# Tokens whose cell actually XFAILed on a known gap this run: excluded from the whole-run audit.
+XFAILED_TOKENS: set = set()
def faults_fired(gw: GatewayProcess, aid: str) -> List[dict]:
@@ -297,13 +303,15 @@ def test_delivery_fault_matrix(gw, director, platform, fault, request):
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 STREAM_OVERFLOW_GAP_CELLS:
expect_gap(request, 120315, STREAM_OVERFLOW_GAP)
- assert_exactly_once(gw, director, platform, chat, token, aid,
- marked_duplicates_allowed=expect == "marked_dupes",
- first_copy_may_be_marked=expect == "one_copy")
+ guard = (known_failure(STREAM_ACK_LOST_SIGNATURE, STREAM_ACK_LOST_GAP,
+ on_xfail=lambda: XFAILED_TOKENS.add(token))
+ if fault == "ack_lost" and STREAMING[platform] else contextlib.nullcontext())
+ with guard:
+ 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 -------------------------
@@ -387,7 +395,7 @@ def test_parallel_threads_are_independent(gw, director):
@pytest.mark.parametrize("when", ["during_turn", "after_turn", "after_reconnect"])
-def test_redelivered_inbound_id_processed_once(gw, director, when, request):
+def test_redelivered_inbound_id_processed_once(gw, director, when):
"""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"
@@ -403,7 +411,6 @@ def test_redelivered_inbound_id_processed_once(gw, director, when, request):
if when == "after_turn":
gw.inject(platform, text, message_id=mid, chat_id=chat)
if when == "after_reconnect":
- expect_gap(request, 120444, 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)
@@ -413,12 +420,6 @@ def test_redelivered_inbound_id_processed_once(gw, director, when, request):
assert_exactly_once(gw, director, platform, chat, tok, f"A-{tok}")
-RECONNECT_DEDUP_GAP = (
- "LIVE GAP (#119848 family, fixed by #120444): 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)
@@ -434,19 +435,20 @@ CRASH_POINTS = {
"stream_accepted_unpersisted": ("any", "hold_after"),
}
-# completed_not_ledgered: until #120377, 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 and only the 120 s recency fallback recovers
-# the reply (by re-running the turn, see RECENCY_FALLBACK_GAP). #120377 removes that fallback and
-# hands the persisted reply to the ledger instead; either way exactly one complete reply must show.
-SENT_ACK_LOST_STREAM_GAP = (
- "LIVE GAP (fixed by #120377): streaming turn persisted, the platform accepted the final edit, "
- "SIGKILL before the ack -> the unclean restart re-runs the already-answered turn (turn marker / "
- "120 s recency fallback) and the model's second answer is sent UNMARKED next to the first.")
+# completed_not_ledgered: the turn is persisted and the handler returned, but the final text never
+# reached the delivery ledger; recovery must hand the persisted reply to the ledger rather than
+# re-run the turn. Either way exactly one complete reply must show.
+
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).")
+# No fix PR yet: run-time xfail only when the visible pair is exactly the gap's shape, the held
+# original answer AND an auto-resumed re-answer, both unmarked.
+STREAM_CRASH_AFTER_ACCEPT_SIGNATURE = (
+ r"(?s)^(2 unmarked complete replies after catch-up|both the held answer and an auto-resumed "
+ r"re-answer are visible)\n.*<<A-fk_tg\.crash-stream_accepted_unpersisted>>.*"
+ r"<<R-fk_tg\.crash-stream_accepted_unpersisted-\d>>")
def _replies(gw: GatewayProcess, platform: str, chat: str, token: str, aid: str):
@@ -475,7 +477,7 @@ def fresh_gw(tmp_path, llm):
@pytest.mark.parametrize("point,platform", CRASH_MATRIX)
-def test_crash_between_completion_and_send(fresh_gw, director, point, platform, request):
+def test_crash_between_completion_and_send(fresh_gw, director, point, platform):
"""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
@@ -484,10 +486,6 @@ def test_crash_between_completion_and_send(fresh_gw, director, point, platform,
gw = fresh_gw
op, kind = CRASH_POINTS[point]
streaming = STREAMING[platform]
- if point == "sent_ack_lost" and streaming:
- expect_gap(request, 120377, SENT_ACK_LOST_STREAM_GAP)
- if point == "stream_accepted_unpersisted":
- 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}"
@@ -513,6 +511,15 @@ def test_crash_between_completion_and_send(fresh_gw, director, point, platform,
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)
+ # Every wait above must have succeeded before a known gap may XFAIL the cell: only the final
+ # assertions run under the run-time xfail, so a lost reply or a failed restart stays red.
+ guard = (known_failure(STREAM_CRASH_AFTER_ACCEPT_SIGNATURE, STREAM_CRASH_AFTER_ACCEPT_GAP)
+ if point == "stream_accepted_unpersisted" else contextlib.nullcontext())
+ with guard:
+ _assert_single_final_reply(gw, director, platform, chat, token, aid, point, streaming)
+
+
+def _assert_single_final_reply(gw, director, platform, chat, token, aid, point, streaming) -> None:
ctx = dump(gw, platform, chat)
originals, resumes = _replies(gw, platform, chat, token, aid)
complete = [c for c in originals + resumes if c.complete]
@@ -535,18 +542,9 @@ def test_crash_between_completion_and_send(fresh_gw, director, point, platform,
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"}
RESUME_EXPECTED: set = set()
-def known_gap_tokens() -> set:
- gaps = set(KNOWN_GAP_TOKENS)
- if gap_open(120444):
- gaps.add("fk_tg.redeliver-after_reconnect")
- return gaps
-
-
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
@@ -554,7 +552,7 @@ def test_zz_whole_run_audit(gw, director):
visible = gw.platform_view().visible()
head = re.compile(r"<<((?:A-|R-)?[A-Za-z0-9_.-]+?)>>")
problems = []
- gaps = known_gap_tokens()
+ gaps = set(XFAILED_TOKENS) # cells that XFAILed on a known gap this run
for token in sorted(director.turns):
if token in gaps or ".crash-" in token: # crash scenarios run on their own homes
continue
@@ -574,19 +572,9 @@ def test_zz_whole_run_audit(gw, director):
assert not problems, "\n".join(problems)
-RECENCY_FALLBACK_GAP = (
- "LIVE GAP (fixed by #120377): 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.")
-
-
-def test_zzz_unclean_restart_reruns_nothing(gw, director, request):
+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."""
- expect_gap(request, 120377, RECENCY_FALLBACK_GAP)
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")