Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(delivery): recover accepted steer materialization (#1308)

Call White842ebc6381c5
diff --git a/core/session_turns.py b/core/session_turns.py
index 6eb137a40..48804ebc9 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -49,6 +49,7 @@ from core.services.agent_steering import (
SteerOutcome,
SteerReconcileRequest,
SteerRequest,
+ SteerResult,
active_steer_identity,
reconcile_steer_attempt,
result as steer_result,
@@ -85,6 +86,29 @@ def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
+def _accepted_steer_receipt(delivery: dict[str, Any]) -> SteerResult:
+ """Rebuild a typed accepted receipt from durable evidence."""
+
+ try:
+ payload = json.loads(str(delivery.get("current_receipt_json") or "{}"))
+ except (TypeError, ValueError, json.JSONDecodeError):
+ payload = {}
+ if not isinstance(payload, dict):
+ payload = {}
+ details = payload.get("details")
+ if not isinstance(details, dict):
+ details = {}
+ return steer_result(
+ SteerOutcome.ACCEPTED,
+ reason=(
+ str(payload.get("reason"))
+ if payload.get("reason") is not None
+ else None
+ ),
+ **details,
+ )
+
+
def _turn_event_payload(session_id: str, turn_id: str | None = None) -> dict[str, str]:
payload = {"session_id": session_id}
if turn_id:
@@ -2828,17 +2852,12 @@ class SessionTurnManager:
):
terminal_target = target_turn
if outcome_value == SteerOutcome.UNKNOWN.value:
- unknown_rows = [
- row
- if row["state"] == "reconciling_steer"
- else delivery_store.mark_attempt_unknown(
- conn,
- str(row["id"]),
- expected_version=int(row["version"]),
- receipt=body,
- )
- for row in attempt_rows
- ]
+ unknown_rows = delivery_store.mark_attempt_receipt_batch(
+ conn,
+ leader_delivery_id=delivery_id,
+ outcome="unknown",
+ receipt=body,
+ )
saved = unknown_rows[0] if unknown_rows else None
return DeliveryResult(
delivery_id,
@@ -2882,19 +2901,26 @@ class SessionTurnManager:
try:
with self._sqlite_engine().begin() as conn:
reserve_write_lock(conn)
- leader = delivery_store.get_delivery(conn, delivery_id)
- lost_attempt_id = str((leader or {}).get("current_attempt_id") or "")
- for row in delivery_store.attempt_deliveries(conn, lost_attempt_id):
- if row["state"] == "steering":
- delivery_store.mark_attempt_unknown(
- conn,
- str(row["id"]),
- expected_version=int(row["version"]),
- receipt={"reason": "receipt_persistence_lost"},
- )
+ persisted_outcome = (
+ "accepted"
+ if outcome_value == SteerOutcome.ACCEPTED.value
+ else "unknown"
+ )
+ persisted_rows = delivery_store.mark_attempt_receipt_batch(
+ conn,
+ leader_delivery_id=delivery_id,
+ outcome=persisted_outcome,
+ receipt=(
+ body
+ if persisted_outcome == "accepted"
+ else {"reason": "receipt_persistence_lost"}
+ ),
+ )
+ if not persisted_rows:
+ raise RuntimeError("steer receipt batch is no longer recoverable")
except Exception:
logger.exception(
- "failed to persist unknown steer fence for delivery=%s",
+ "failed to persist steer receipt recovery fence for delivery=%s",
delivery_id,
)
return DeliveryResult(
@@ -5398,6 +5424,16 @@ class SessionTurnManager:
)
return True
if delivery["state"] in {"steering", "reconciling_steer"}:
+ if (
+ delivery["state"] == "reconciling_steer"
+ and delivery.get("current_receipt_outcome") == "accepted"
+ ):
+ result = await self._finish_steer(
+ str(delivery["id"]),
+ _accepted_steer_receipt(delivery),
+ context=None,
+ )
+ return result.state != "reconciling_steer"
attempt_id = str(delivery.get("current_attempt_id") or "")
expected_native = str(
delivery.get("current_expected_native_turn_id") or ""
@@ -5640,6 +5676,7 @@ class SessionTurnManager:
with self._sqlite_engine().connect() as conn:
unresolved = delivery_store.unresolved_deliveries(conn, session_id)
+ accepted_steer_attempts: list[dict[str, Any]] = []
steer_attempts: list[tuple[dict[str, Any], str]] = []
seen_attempt_ids: set[str] = set()
for attempt in unresolved:
@@ -5654,15 +5691,31 @@ class SessionTurnManager:
not attempt_id
or attempt_id in seen_attempt_ids
or not target_turn_id
- or not expected_native_id
):
continue
target_turn = delivery_store.get_turn(conn, target_turn_id)
if target_turn is None:
continue
seen_attempt_ids.add(attempt_id)
+ if (
+ attempt["state"] == "reconciling_steer"
+ and attempt.get("current_receipt_outcome") == "accepted"
+ ):
+ accepted_steer_attempts.append(attempt)
+ continue
+ if not expected_native_id:
+ continue
steer_attempts.append((attempt, str(target_turn["backend"])))
+ for attempt in accepted_steer_attempts:
+ result = await self._finish_steer(
+ str(attempt["id"]),
+ _accepted_steer_receipt(attempt),
+ context=None,
+ )
+ if result.state != "reconciling_steer":
+ recovered.append(str(attempt["session_id"]))
+
for attempt, backend in steer_attempts:
attempt_id = str(attempt["current_attempt_id"])
target_turn_id = str(attempt["current_target_turn_id"])
diff --git a/storage/alembic/versions/20260811_0050_accepted_steer_receipt.py b/storage/alembic/versions/20260811_0050_accepted_steer_receipt.py
new file mode 100644
index 000000000..8494a75db
--- /dev/null
+++ b/storage/alembic/versions/20260811_0050_accepted_steer_receipt.py
@@ -0,0 +1,94 @@
+"""retain positive native steer receipts across materialization failures
+
+Revision ID: 20260811_0050
+Revises: 20260809_0049
+Create Date: 2026-08-11
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260811_0050"
+down_revision = "20260809_0049"
+branch_labels = None
+depends_on = None
+
+_CHECK = "ck_message_deliveries_current_receipt"
+_UPGRADE_CHECK = (
+ "(state = 'reconciling_steer' "
+ "and current_receipt_outcome in ('accepted', 'unknown')) "
+ "or (state <> 'reconciling_steer' "
+ "and current_receipt_outcome is null)"
+)
+_DOWNGRADE_CHECK = (
+ "(state = 'reconciling_steer' "
+ "and current_receipt_outcome = 'unknown') "
+ "or (state <> 'reconciling_steer' "
+ "and current_receipt_outcome is null)"
+)
+
+
+def _check_names(bind) -> set[str]:
+ return {
+ str(check["name"])
+ for check in sa.inspect(bind).get_check_constraints("message_deliveries")
+ if check.get("name")
+ }
+
+
+def _replace_check(bind, expression: str) -> None:
+ with op.batch_alter_table(
+ "message_deliveries",
+ naming_convention={
+ "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s"
+ },
+ ) as batch:
+ if _CHECK in _check_names(bind):
+ batch.drop_constraint(_CHECK, type_="check")
+ batch.create_check_constraint(_CHECK, expression)
+
+
+def _sqlite_rebuild(operation) -> None:
+ bind = op.get_bind()
+ with op.get_context().autocommit_block():
+ bind.exec_driver_sql("PRAGMA foreign_keys=OFF")
+ try:
+ operation(bind)
+ finally:
+ bind.exec_driver_sql("PRAGMA foreign_keys=ON")
+ violations = bind.exec_driver_sql("PRAGMA foreign_key_check").fetchall()
+ if violations:
+ raise RuntimeError(
+ "accepted steer receipt migration left invalid SQLite foreign keys"
+ )
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ if bind.dialect.name == "sqlite":
+ _sqlite_rebuild(lambda current_bind: _replace_check(current_bind, _UPGRADE_CHECK))
+ else:
+ _replace_check(bind, _UPGRADE_CHECK)
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ accepted_rows = bind.execute(
+ sa.text(
+ "select count(*) from message_deliveries "
+ "where state = 'reconciling_steer' "
+ "and current_receipt_outcome = 'accepted'"
+ )
+ ).scalar_one()
+ if accepted_rows:
+ raise RuntimeError(
+ "0050 downgrade refused: accepted steer receipt evidence cannot be represented"
+ )
+ if bind.dialect.name == "sqlite":
+ _sqlite_rebuild(
+ lambda current_bind: _replace_check(current_bind, _DOWNGRADE_CHECK)
+ )
+ else:
+ _replace_check(bind, _DOWNGRADE_CHECK)
diff --git a/storage/message_deliveries.py b/storage/message_deliveries.py
index 3daea9f10..74e29b57c 100644
--- a/storage/message_deliveries.py
+++ b/storage/message_deliveries.py
@@ -5,7 +5,7 @@ import json
import time
import uuid
from datetime import datetime, timezone
-from typing import Any, Iterable
+from typing import Any, Iterable, Literal
from sqlalchemy import Select, and_, func, or_, select, update
from sqlalchemy.engine import Connection
@@ -1372,13 +1372,16 @@ def materialize_steer_acceptance(
return accepted
-def mark_attempt_unknown(
+def mark_attempt_receipt(
conn: Connection,
delivery_id: str,
*,
expected_version: int,
+ outcome: Literal["accepted", "unknown"],
receipt: dict[str, Any],
) -> dict[str, Any] | None:
+ if outcome not in {"accepted", "unknown"}:
+ raise ValueError(f"unsupported steer receipt outcome: {outcome}")
delivery = get_delivery(conn, delivery_id)
if delivery is None:
return None
@@ -1392,19 +1395,74 @@ def mark_attempt_unknown(
expected_states=("steering",),
values={
"state": "reconciling_steer",
- "current_receipt_outcome": "unknown",
+ "current_receipt_outcome": outcome,
"current_receipt_json": _canonical_json(receipt),
},
history_event={
"kind": kind or "attempt",
"attempt_id": delivery.get("current_attempt_id"),
"turn_id": delivery.get("current_target_turn_id"),
- "outcome": "unknown",
+ "outcome": outcome,
"receipt": receipt,
},
)
+def mark_attempt_unknown(
+ conn: Connection,
+ delivery_id: str,
+ *,
+ expected_version: int,
+ receipt: dict[str, Any],
+) -> dict[str, Any] | None:
+ return mark_attempt_receipt(
+ conn,
+ delivery_id,
+ expected_version=expected_version,
+ outcome="unknown",
+ receipt=receipt,
+ )
+
+
+def mark_attempt_receipt_batch(
+ conn: Connection,
+ *,
+ leader_delivery_id: str,
+ outcome: Literal["accepted", "unknown"],
+ receipt: dict[str, Any],
+) -> list[dict[str, Any]]:
+ leader = get_delivery(conn, leader_delivery_id)
+ attempt_id = str((leader or {}).get("current_attempt_id") or "")
+ if not attempt_id:
+ return []
+ rows = attempt_deliveries(conn, attempt_id)
+ if not rows or any(
+ row["state"] not in {"steering", "reconciling_steer"}
+ or (
+ row["state"] == "reconciling_steer"
+ and row.get("current_receipt_outcome") != outcome
+ )
+ for row in rows
+ ):
+ return []
+ saved_rows: list[dict[str, Any]] = []
+ for row in rows:
+ if row["state"] == "reconciling_steer":
+ saved_rows.append(row)
+ continue
+ saved = mark_attempt_receipt(
+ conn,
+ str(row["id"]),
+ expected_version=int(row["version"]),
+ outcome=outcome,
+ receipt=receipt,
+ )
+ if saved is None:
+ raise RuntimeError("steer Delivery batch receipt persistence CAS lost")
+ saved_rows.append(saved)
+ return saved_rows
+
+
def record_definitive_attempt(
conn: Connection,
delivery_id: str,
diff --git a/storage/models.py b/storage/models.py
index 39fbacd2c..079ffdb79 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -732,7 +732,7 @@ message_deliveries = Table(
),
CheckConstraint(
"(state = 'reconciling_steer' "
- "and current_receipt_outcome = 'unknown') "
+ "and current_receipt_outcome in ('accepted', 'unknown')) "
"or (state <> 'reconciling_steer' "
"and current_receipt_outcome is null)",
name="ck_message_deliveries_current_receipt",
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index b2f3abef9..65796af1c 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -75,7 +75,7 @@ scenarios:
layer: contract
test: tests/test_session_delivery_fsm.py::test_two_empty_p1_requests_claim_exact_same_head_only
- id: MESSAGE-DELIVERY-011
- name: Lost accepted steering receipt enters reconciliation without a second adapter call
+ name: Lost accepted steering receipt is retained as positive evidence and materialized without reconciliation
status: covered
kind: recovery
layer: contract
@@ -224,5 +224,23 @@ scenarios:
kind: regression
layer: contract
test: tests/test_session_delivery_fsm.py::test_steer_acceptance_materializes_message_before_show_event_link
+ - id: MESSAGE-DELIVERY-311
+ name: Observation recovery materializes accepted steer evidence without another adapter call
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_observation_recovery_materializes_persisted_accepted_receipt_without_reconcile
+ - id: MESSAGE-DELIVERY-312
+ name: Unknown steer evidence remains unreplayed while reconciliation stays conservative
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_missing_restart_evidence_keeps_unknown_without_resteer
+ - id: MESSAGE-DELIVERY-313
+ name: Accepted attempt-batch recovery preserves merged materialization and Agent Run attachment
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_accepted_receipt_recovery_preserves_attempt_batch_and_run_attachment
next_priority:
- - MESSAGE-DELIVERY-311
+ - MESSAGE-DELIVERY-314
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 724b399a9..735ec6982 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -2427,7 +2427,7 @@ def test_lost_accepted_receipt_materializes_from_exact_restart_evidence(
managers,
monkeypatch,
) -> None:
- """MESSAGE-DELIVERY-011: adapter acceptance is may-have-written after DB loss."""
+ """MESSAGE-DELIVERY-011: accepted evidence recovers without adapter reconciliation."""
first, restarted, engine, _engine_b, _starts = managers
turn_id, _ = asyncio.run(_activate(first))
@@ -2453,22 +2453,18 @@ def test_lost_accepted_receipt_materializes_from_exact_restart_evidence(
)
)
monkeypatch.setattr(delivery_store, "materialize_steer_acceptance", original)
+ persisted = _row(engine, str(outcome.delivery_id))
+ assert persisted["state"] == "reconciling_steer"
+ assert persisted["current_receipt_outcome"] == "accepted"
restarted._active_identity = lambda _b, _s, logical: (logical, f"native-{logical}")
-
- async def reconcile(_backend, request):
- assert request.attempt_id
- assert request.expected_logical_turn_id == turn_id
- return steer_result(
- SteerOutcome.ACCEPTED,
- reason="native_attempt_found",
- native_message_id=request.attempt_id,
- )
-
- restarted._reconcile_steer_attempt = reconcile
+ restarted._reconcile_steer_attempt = AsyncMock(
+ side_effect=AssertionError("accepted evidence must not reconcile")
+ )
asyncio.run(restarted.recover_durable_delivery_state())
row = _row(engine, str(outcome.delivery_id))
assert calls == 1
+ restarted._reconcile_steer_attempt.assert_not_awaited()
assert row["state"] == "accepted"
assert row["turn_id"] == turn_id
assert row["current_attempt_id"] is None
@@ -2479,9 +2475,146 @@ def test_lost_accepted_receipt_materializes_from_exact_restart_evidence(
assert message["content_text"] == "accepted once"
-def test_missing_restart_evidence_keeps_unknown_without_resteer(
+def test_observation_recovery_materializes_persisted_accepted_receipt_without_reconcile(
managers,
monkeypatch,
+) -> None:
+ """MESSAGE-DELIVERY-311: observation recovery consumes accepted evidence directly."""
+
+ first, restarted, engine, _engine_b, _starts = managers
+ turn_id, _ = asyncio.run(_activate(first))
+ first._active_identity = lambda _b, _s, logical: (logical, f"native-{logical}")
+ first._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
+ original = delivery_store.materialize_steer_acceptance
+
+ def lose_receipt(*_args, **_kwargs):
+ raise OSError("simulated receipt fsync loss")
+
+ monkeypatch.setattr(
+ delivery_store,
+ "materialize_steer_acceptance",
+ lose_receipt,
+ )
+ outcome = asyncio.run(
+ first.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content="observed"),
+ context=_context(),
+ )
+ )
+ monkeypatch.setattr(delivery_store, "materialize_steer_acceptance", original)
+ observations, _ = restarted.scan_runtime_delivery_recovery(
+ limit=10,
+ occupied=frozenset(),
+ )
+ observation = next(
+ item for item in observations if item.delivery_id == str(outcome.delivery_id)
+ )
+ restarted._reconcile_steer_attempt = AsyncMock(
+ side_effect=AssertionError("accepted evidence must not reconcile")
+ )
+
+ assert asyncio.run(restarted.recover_runtime_delivery_observation(observation))
+ restarted._reconcile_steer_attempt.assert_not_awaited()
+ row = _row(engine, str(outcome.delivery_id))
+ assert row["state"] == "accepted"
+ assert row["turn_id"] == turn_id
+
+
+def test_accepted_receipt_recovery_preserves_attempt_batch_and_run_attachment(
+ managers,
+ monkeypatch,
+) -> None:
+ """MESSAGE-DELIVERY-313: accepted batch recovery retains Turn participants."""
+
+ first, restarted, engine, _engine_b, _starts = managers
+ original = delivery_store.materialize_steer_acceptance
+ run_id = "run-accepted-receipt-batch"
+
+ async def run() -> tuple[str, list[str], MessageContext]:
+ turn_id, active_context = await _activate(first)
+ queued = [
+ await first.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content=text,
+ source="harness",
+ author="harness",
+ message_type="harness",
+ ),
+ context=_context(),
+ )
+ for text in ("batch one", "batch two")
+ ]
+ now = "2026-08-11T00:00:00Z"
+ with engine.begin() as conn:
+ conn.execute(
+ agent_runs.insert().values(
+ id=run_id,
+ definition_id=None,
+ run_type="agent_run",
+ status="running",
+ cancel_requested=0,
+ session_id="ses_fsm",
+ delivery_id=queued[1].delivery_id,
+ created_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+ first._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
+
+ def lose_receipt(*_args, **_kwargs):
+ raise OSError("simulated receipt fsync loss")
+
+ monkeypatch.setattr(
+ delivery_store,
+ "materialize_steer_acceptance",
+ lose_receipt,
+ )
+ await first.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content=None),
+ context=_context(),
+ )
+ monkeypatch.setattr(
+ delivery_store,
+ "materialize_steer_acceptance",
+ original,
+ )
+ delivery_ids = [str(item.delivery_id) for item in queued]
+ persisted = [_row(engine, delivery_id) for delivery_id in delivery_ids]
+ assert {row["state"] for row in persisted} == {"reconciling_steer"}
+ assert {row["current_receipt_outcome"] for row in persisted} == {
+ "accepted"
+ }
+ assert len({row["current_attempt_id"] for row in persisted}) == 1
+
+ holder = asyncio.create_task(asyncio.Event().wait())
+ restarted.in_flight["ses_fsm"] = Turn(
+ task=holder,
+ context=active_context,
+ logical_turn_id=turn_id,
+ )
+ restarted._reconcile_steer_attempt = AsyncMock(
+ side_effect=AssertionError("accepted evidence must not reconcile")
+ )
+ await restarted.recover_durable_delivery_state()
+ holder.cancel()
+ await asyncio.gather(holder, return_exceptions=True)
+ return turn_id, delivery_ids, active_context
+
+ turn_id, delivery_ids, active_context = asyncio.run(run())
+ restarted._reconcile_steer_attempt.assert_not_awaited()
+ accepted = [_row(engine, delivery_id) for delivery_id in delivery_ids]
+ assert {row["state"] for row in accepted} == {"accepted"}
+ assert {row["turn_id"] for row in accepted} == {turn_id}
+ assert len({row["message_id"] for row in accepted}) == 1
+ assert [row["turn_position"] for row in accepted] == [1, 2]
+ assert active_context.platform_specific["accepted_agent_run_ids"] == [run_id]
+
+
+def test_missing_restart_evidence_keeps_unknown_without_resteer(
+ managers,
) -> None:
first, restarted, engine, _engine_b, _starts = managers
turn_id, _ = asyncio.run(_activate(first))
@@ -2489,25 +2622,18 @@ def test_missing_restart_evidence_keeps_unknown_without_resteer(
steer_calls = 0
reconciliation_calls = 0
- async def accepted(_backend, _request):
+ async def unknown(_backend, _request):
nonlocal steer_calls
steer_calls += 1
- return steer_result(SteerOutcome.ACCEPTED)
-
- first._steer = accepted
- original = delivery_store.materialize_steer_acceptance
-
- def lose_receipt(*args, **kwargs):
- raise OSError("simulated receipt fsync loss")
+ return steer_result(SteerOutcome.UNKNOWN, reason="evidence_unavailable")
- monkeypatch.setattr(delivery_store, "materialize_steer_acceptance", lose_receipt)
+ first._steer = unknown
outcome = asyncio.run(
first.deliver(
DeliveryRequest(session_id="ses_fsm", priority="p1", content="still unknown"),
context=_context(),
)
)
- monkeypatch.setattr(delivery_store, "materialize_steer_acceptance", original)
restarted._active_identity = lambda _b, _s, logical: (logical, f"native-{logical}")
async def reconcile(_backend, request):
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index c500bafdb..d04ca5abf 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -31,7 +31,7 @@ from vibe.message_types import build_partial_index_predicate
pytestmark = pytest.mark.no_sqlite_template
-HEAD_REVISION = "20260809_0049"
+HEAD_REVISION = "20260811_0050"
MESSAGE_PARTIAL_INDEX_PREDICATES = {
"ix_messages_inbox_activity": (
"session_id is not null and type in "
@@ -93,6 +93,156 @@ def test_message_index_migration_matches_catalog() -> None:
)
+def test_accepted_steer_receipt_migration_preserves_upgrade_and_downgrade_invariants(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260809_0049")
+ engine = create_sqlite_engine(db_path)
+ now = "2026-08-11T00:00:00Z"
+ with engine.begin() as conn:
+ conn.exec_driver_sql(
+ """
+ insert into agent_sessions (
+ id, scope_id, agent_name, agent_backend, agent_variant,
+ session_anchor, workdir, native_session_id, status, visibility,
+ pinned, agent_status, metadata_json, created_at, updated_at,
+ last_active_at
+ ) values (
+ 'ses_receipt_migration', null, 'codex', 'codex', 'codex',
+ 'receipt-migration', '/tmp', '', 'active', 'foreground',
+ 0, 'idle', '{}', ?, ?, ?
+ )
+ """,
+ (now, now, now),
+ )
+ initial = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="msg_receipt_anchor",
+ session_id="ses_receipt_migration",
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=None,
+ session_id="ses_receipt_migration",
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="anchor",
+ ),
+ dispatch_text="anchor",
+ now=now,
+ )
+ claimed = message_deliveries.claim_start_batch(
+ conn,
+ turn_id="turn_receipt_migration",
+ session_id="ses_receipt_migration",
+ backend="codex",
+ deliveries=[initial],
+ dispatch_text="anchor",
+ )
+ turn = message_deliveries.bind_native_start(
+ conn,
+ "turn_receipt_migration",
+ expected_version=int(claimed["turn"]["version"]),
+ runtime_key="runtime",
+ runtime_turn_id="runtime-turn",
+ native_turn_id="native-turn",
+ )
+ assert turn is not None
+ steer = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="msg_receipt_candidate",
+ session_id="ses_receipt_migration",
+ priority="p1",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=None,
+ session_id="ses_receipt_migration",
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="candidate",
+ ),
+ dispatch_text="candidate",
+ now=now,
+ )
+ steering = message_deliveries.open_steer_attempt(
+ conn,
+ "msg_receipt_candidate",
+ expected_version=int(steer["version"]),
+ turn_id="turn_receipt_migration",
+ attempt_id="attempt_receipt_migration",
+ expected_native_turn_id="native-turn",
+ )
+ assert steering is not None
+ assert message_deliveries.mark_attempt_unknown(
+ conn,
+ "msg_receipt_candidate",
+ expected_version=int(steering["version"]),
+ receipt={"reason": "receipt_persistence_lost"},
+ ) is not None
+
+ command.upgrade(migrations.alembic_config(db_path), "head")
+ with engine.connect() as conn:
+ assert conn.exec_driver_sql(
+ "select state, current_receipt_outcome, current_receipt_json "
+ "from message_deliveries where id = 'msg_receipt_candidate'"
+ ).one() == (
+ "reconciling_steer",
+ "unknown",
+ '{"reason":"receipt_persistence_lost"}',
+ )
+ with engine.begin() as conn:
+ conn.execute(
+ message_deliveries.message_deliveries.update()
+ .where(message_deliveries.message_deliveries.c.id == "msg_receipt_candidate")
+ .values(
+ current_receipt_outcome="accepted",
+ current_receipt_json='{"reason":"native-accepted"}',
+ )
+ )
+ with engine.connect() as conn:
+ assert conn.exec_driver_sql(
+ "select state, current_receipt_outcome from message_deliveries "
+ "where id = 'msg_receipt_candidate'"
+ ).one() == ("reconciling_steer", "accepted")
+
+ with pytest.raises(RuntimeError, match="0050 downgrade refused"):
+ command.downgrade(migrations.alembic_config(db_path), "20260809_0049")
+
+ with engine.begin() as conn:
+ conn.execute(
+ message_deliveries.message_deliveries.update()
+ .where(message_deliveries.message_deliveries.c.id == "msg_receipt_candidate")
+ .values(
+ current_receipt_outcome="unknown",
+ current_receipt_json='{"reason":"receipt_persistence_lost"}',
+ )
+ )
+ command.downgrade(migrations.alembic_config(db_path), "20260809_0049")
+ with engine.connect() as conn:
+ assert conn.exec_driver_sql(
+ "select state, current_receipt_outcome, current_receipt_json "
+ "from message_deliveries where id = 'msg_receipt_candidate'"
+ ).one() == (
+ "reconciling_steer",
+ "unknown",
+ '{"reason":"receipt_persistence_lost"}',
+ )
+ assert conn.exec_driver_sql("select version_num from alembic_version").one() == (
+ "20260809_0049",
+ )
+ with pytest.raises(IntegrityError):
+ with engine.begin() as conn:
+ conn.exec_driver_sql(
+ "update message_deliveries set current_receipt_outcome = 'accepted' "
+ "where id = 'msg_receipt_candidate'"
+ )
+
+
def test_agent_lifecycle_message_index_migration_upgrades_and_downgrades(
tmp_path: Path,
) -> None: