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.

refactor(harness): separate Delivery, Turn, and Message (#1134)

Call White89befed41467
diff --git a/core/chat_discovery.py b/core/chat_discovery.py
index 68b16e774..ac0e6a616 100644
--- a/core/chat_discovery.py
+++ b/core/chat_discovery.py
@@ -11,12 +11,20 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any
-from sqlalchemy import Connection, and_, select
+from sqlalchemy import Connection, and_, func, select
from config import paths
from storage.db import create_sqlite_engine
from storage.migrations import guard_source_checkout_default_state_migration, run_migrations
-from storage.models import agent_events, media_objects, messages, scope_settings, scopes, state_meta
+from storage.models import (
+ agent_events,
+ media_objects,
+ message_deliveries,
+ messages,
+ scope_settings,
+ scopes,
+ state_meta,
+)
from storage.settings_service import make_scope_id, upsert_scope
from config.v2_settings import make_thread_native_id, split_thread_native_id
@@ -946,11 +954,11 @@ def _mark_not_returned(
def _scope_has_history(conn: Connection, scope_id: str) -> bool:
- """True if the scope owns rows whose FK to scopes is ON DELETE CASCADE.
+ """True if deleting the scope would destroy or invalidate retained history.
``messages``, ``agent_events`` and ``media_objects`` cascade-delete with the
- scope row, so deleting a scope that owns any of them would destroy stored
- chat history/traces/media — not just the discovery entry.
+ scope row. Nonterminal Deliveries retain the prospective Message scope inside
+ their immutable snapshot and need that Scope to survive materialization.
"""
for table in (messages, agent_events, media_objects):
exists = conn.execute(
@@ -958,7 +966,16 @@ def _scope_has_history(conn: Connection, scope_id: str) -> bool:
).first()
if exists is not None:
return True
- return False
+ delivery_exists = conn.execute(
+ select(message_deliveries.c.id)
+ .where(
+ func.json_extract(message_deliveries.c.snapshot_json, "$.scope_id")
+ == scope_id
+ )
+ .where(message_deliveries.c.state != "retired")
+ .limit(1)
+ ).first()
+ return delivery_exists is not None
def _descendant_scope_rows(conn: Connection, scope_id: str) -> list[dict[str, Any]]:
diff --git a/core/controller.py b/core/controller.py
index 7e7f0f9ad..61ebd0dd3 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -225,6 +225,10 @@ class Controller:
from core.session_turns import SessionTurnManager
self.session_turns = SessionTurnManager(self)
+ # Durable Delivery recovery must not classify a Turn before backend
+ # adapters have restored their restart-stable native identities.
+ self._delivery_recovery_barrier = asyncio.Event()
+ self._delivery_recovery_complete = asyncio.Event()
self._init_model_hub()
@@ -271,10 +275,9 @@ class Controller:
# Restore session mappings on startup (after handlers are initialized)
self.session_handler.restore_session_mappings()
- # Crash recovery: no turn survives a restart, so any session left
- # ``running`` in the table is stale — reset it to ``idle`` so the
- # workbench sidebar dot doesn't show a phantom green forever.
- self.session_turns.reset_stale()
+ # Clean only pre-durable status projections. Durable Turn owners remain
+ # running until backend restoration and exact reconciliation complete.
+ self.session_turns.reset_legacy_ownerless_status()
def _init_model_hub(self) -> None:
"""Create the Model Hub aggregate only for an explicit release opt-in."""
@@ -934,7 +937,10 @@ class Controller:
workbench_platforms = {"avibe"}
if self.primary_platform == "avibe":
workbench_platforms.add("")
- await self._restore_active_polls(workbench_platforms)
+ try:
+ await self._restore_active_polls(workbench_platforms)
+ finally:
+ self._delivery_recovery_barrier.set()
try:
await self.update_checker.check_and_send_post_update_notification(ready_platform="avibe")
except Exception as e:
@@ -1185,18 +1191,9 @@ class Controller:
# ----- Live agent-runtime status (workbench sidebar dot) -------------
#
- # ``agent_sessions.agent_status`` is idle/running/failed, written at EXACTLY
- # two chokepoints every turn funnels through — no per-path / per-backend
- # instrumentation:
- # * inbound — ``AgentService.handle_message`` flips the session to
- # ``running`` (every source/backend dispatches through it).
- # * outbound — ``MessageDispatcher.emit_agent_message`` settles the terminal
- # ``result`` to ``idle`` (or ``failed`` when ``is_error``).
- # A fire-and-forget backend error surfaces as an emitted message, not an
- # exception, so terminal failures are emitted as ``result`` + ``is_error`` and
- # ride the same outbound chokepoint. ``set_agent_status`` is the shared writer;
- # ``SessionTurnManager.reset_stale`` recovers ``running`` rows to ``idle`` on
- # startup (a turn whose process died never reached the outbound chokepoint).
+ # ``agent_sessions.agent_status`` is a projection of durable Turn ownership.
+ # Admission projects running; the terminal transaction projects the exact
+ # successor state. Legacy non-durable paths use this writer directly.
@staticmethod
def _session_id_from_context(context: Optional[MessageContext]) -> Optional[str]:
@@ -1417,30 +1414,29 @@ class Controller:
delivery: Any = None,
):
"""Backward-compatible entrypoint; delegated to message dispatcher."""
- try:
- return await self.message_dispatcher.emit_agent_message(
- context=context,
- message_type=message_type,
- text=text,
- parse_mode=parse_mode,
- is_error=is_error,
- level=level,
- status_label=status_label,
- result_footer=result_footer,
- output=output,
- terminal_error=terminal_error,
- # Forwarded ONLY when a caller asked for it, for the same reason
- # ``emit_backend_failure`` does: ``message_dispatcher`` is a
- # substitutable collaborator (six test suites replace it), so passing
- # an optional diagnostic unconditionally would change the required
- # signature of every stand-in.
- **({"delivery": delivery} if delivery is not None else {}),
- )
- finally:
- manager = getattr(self, "session_turns", None)
- complete = getattr(manager, "on_terminal_delivery_complete", None)
- if callable(complete):
- complete(context)
+ result = await self.message_dispatcher.emit_agent_message(
+ context=context,
+ message_type=message_type,
+ text=text,
+ parse_mode=parse_mode,
+ is_error=is_error,
+ level=level,
+ status_label=status_label,
+ result_footer=result_footer,
+ output=output,
+ terminal_error=terminal_error,
+ # Forwarded ONLY when a caller asked for it, for the same reason
+ # ``emit_backend_failure`` does: ``message_dispatcher`` is a
+ # substitutable collaborator (six test suites replace it), so passing
+ # an optional diagnostic unconditionally would change the required
+ # signature of every stand-in.
+ **({"delivery": delivery} if delivery is not None else {}),
+ )
+ manager = getattr(self, "session_turns", None)
+ complete = getattr(manager, "on_terminal_delivery_complete", None)
+ if callable(complete):
+ complete(context)
+ return result
def note_session_tokens(self, context: MessageContext, *, total: int) -> None:
"""Report the session's current context-window occupancy for the status
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index ffe93f5b9..5d668255b 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -14,6 +14,10 @@ from core.audio_asr import (
)
from core.message_output import terminal_output_for, terminal_turn_output
from core.message_context import resolve_context_thread_id
+from core.native_dispatch_phase import (
+ DISPATCH_PHASE_PREWRITE,
+ set_dispatch_phase,
+)
from modules.agents.base import AgentRequest
from modules.agents.catalog import display_name_for_backend, is_agent_backend
from modules.im import MessageContext
@@ -83,6 +87,7 @@ class MessageHandler(BaseHandler):
"""Shared turn-processing pipeline used by both human and scheduled turns."""
processing_indicator = None
request: AgentRequest | None = None
+ dispatch_evidence = set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)
# Tracks whether we actually dispatched an agent turn (whose reply
# streams in asynchronously). If we leave this method WITHOUT having
# dispatched — early returns, missing/disabled backend, errors — no
@@ -148,23 +153,26 @@ class MessageHandler(BaseHandler):
raise RuntimeError("Session handler not initialized")
context = await self._prepare_turn_context(context, source)
+ set_dispatch_phase(
+ context,
+ DISPATCH_PHASE_PREWRITE,
+ evidence=dispatch_evidence,
+ )
- # Mirror the originating prompt into the workbench messages table
- # before we kick off the agent, so the transcript shows the turn
- # that produced the reply. Human turns are source='user'; harness
- # turns (scheduled task / watch / webhook) use a first-class harness
- # author/type so they cannot be mistaken for human input. Wrapped in
- # try/except inside the helper so a mirror failure can't break the turn.
- if source == self.TURN_SOURCE_HUMAN:
- from core.message_mirror import mirror_inbound
+ # Durable Deliveries materialize their Message only after exact native
+ # acceptance. Legacy direct turns still mirror at this boundary.
+ durable_delivery_owned = bool(
+ (context.platform_specific or {}).get("delivery_ids")
+ )
+ if not durable_delivery_owned:
+ if source == self.TURN_SOURCE_HUMAN:
+ from core.message_mirror import mirror_inbound
- mirror_inbound(context, control_message)
- else:
- # Harness turns retain a complete local transcript even when their
- # session is background-only; visibility gates outward delivery.
- from core.message_mirror import mirror_harness_inbound
+ mirror_inbound(context, control_message)
+ else:
+ from core.message_mirror import mirror_harness_inbound
- mirror_harness_inbound(context, message)
+ mirror_harness_inbound(context, message)
base_session_id, working_path, composite_key = self.session_handler.get_session_info(context, source=source)
payload = dict(context.platform_specific or {})
diff --git a/core/internal_server.py b/core/internal_server.py
index 67f2ca5f6..c3c336f0c 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -45,13 +45,11 @@ from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED
from modules.im.base import MessageContext
from storage.db import get_cached_sqlite_engine
from vibe.message_identity import HARNESS_TYPE, is_input_turn
-from vibe.message_types import types_with
if TYPE_CHECKING: # pragma: no cover - typing only
from core.controller import Controller
logger = logging.getLogger(__name__)
-_ACCEPTED_RESERVATION_TYPES = set(types_with("acceptedReservation"))
def default_socket_path() -> Path:
@@ -99,7 +97,7 @@ def create_app(controller: "Controller") -> FastAPI:
# builder now that the gate (which owns _build_session_context) is built. A fake
# controller in tests may lack one — create it then. The registry bound below
# is the SAME object the closures + ``controller.session_turn_gate`` use.
- from core.session_turns import SessionTurnManager, queue_pending_user_message
+ from core.session_turns import SessionTurnManager
manager = getattr(controller, "session_turns", None)
if not isinstance(manager, SessionTurnManager):
@@ -115,173 +113,348 @@ def create_app(controller: "Controller") -> FastAPI:
in_flight = manager.in_flight
app.state.in_flight_dispatches = in_flight
+ def _publish_scheduled_queue_growth(session_id: str, state: str) -> None:
+ if state != "queued":
+ return
+ try:
+ from core.inbox_events import bus
+
+ bus.publish("queue.updated", {"session_id": session_id})
+ except Exception:
+ logger.exception(
+ "scheduled Delivery queue projection failed for Session=%s",
+ session_id,
+ )
+
async def _submit_scheduled_turn(
session_id: str,
context: MessageContext,
text: str,
*,
- delivery_intent: str = "queue",
+ delivery_intent: str = "steer",
) -> Any:
"""Run a scheduled / watch turn through the SAME unified ``manager.submit``
the interactive Chat path uses, so a scheduled run can never preempt an
active Chat turn and gets the full turn lifecycle (in_flight + turn.start /
- turn.end + Stop) the Chat page renders (Codex P2). Unlike Chat there is no
- pre-persisted ``pending`` row to promote, so the enqueue callback ``append``s
- a fresh ``queued`` row attributed to the harness.
+ turn.end + Stop) the Chat page renders (Codex P2). Its submission is a
+ Delivery until exact native acceptance materializes the harness Message.
"""
if not session_id:
submission = await manager.submit(None, context, text, source=SOURCE_SCHEDULED)
return submission.route
- native_message_id = str(getattr(context, "message_id", None) or "").strip()
- if native_message_id:
- active = manager.in_flight.get(session_id)
- active_message_id = str(getattr(getattr(active, "context", None), "message_id", None) or "").strip()
- if active_message_id == native_message_id:
- return "duplicate"
- from storage import messages_service
+ from core.message_mirror import _scope_id_for_session
+ from core.session_turns import (
+ DeliveryRequest,
+ SCHEDULED_PROVENANCE_KEY,
+ TurnSubmissionResult,
+ capture_scheduled_provenance,
+ )
+ from storage import message_deliveries, messages_service
+ from storage.background import (
+ agent_run_cancellation_won_in_connection,
+ attach_agent_run_delivery_in_connection,
+ cancel_queued_agent_run_delivery_in_connection,
+ normalize_run_status,
+ record_agent_run_delivery_outcome_in_connection,
+ run_update_event_transaction,
+ )
- engine = get_cached_sqlite_engine()
- with engine.connect() as conn:
- if messages_service.native_message_exists(
+ native_message_id = str(getattr(context, "message_id", None) or "").strip()
+ dedupe_key = message_deliveries.native_dedupe_key(
+ "avibe", native_message_id
+ )
+ delivery_id: str | None = None
+ delivery_request: DeliveryRequest | None = None
+ scope_id: str | None = None
+ delivery_owner_transferred = False
+ target_was_busy = False
+ effective_delivery_intent = delivery_intent
+ execution_id = str(
+ (context.platform_specific or {}).get("task_execution_id") or ""
+ ).strip()
+ with run_update_event_transaction(get_cached_sqlite_engine()) as conn:
+ from sqlalchemy import select
+ from storage.agent_session_rows import reserve_write_lock
+ from storage.models import agent_runs, agent_sessions
+
+ reserve_write_lock(conn)
+ existing = (
+ message_deliveries.get_delivery_by_dedupe(conn, dedupe_key)
+ if dedupe_key
+ else None
+ )
+ legacy_accepted = bool(
+ native_message_id
+ and messages_service.native_message_exists(
conn,
platform="avibe",
native_message_id=native_message_id,
- ):
- return "duplicate"
-
- queue_owner_transferred = False
- queue_transfer_cancelled = False
-
- class _QueueTransferCancelled(RuntimeError):
- pass
-
- def _enqueue() -> bool:
- nonlocal queue_owner_transferred, queue_transfer_cancelled
-
- from core.message_mirror import _scope_id_for_session
- from core.session_turns import SCHEDULED_PROVENANCE_KEY, capture_scheduled_provenance
- from storage import messages_service
- from storage.background import (
- agent_run_cancellation_won_in_connection,
- hold_running_agent_run_for_workbench_in_connection,
- run_update_event_transaction,
+ )
)
-
- # Persist the scheduled run's delivery / attribution provenance on the
- # queued row's metadata so flush_queue re-runs it as SOURCE_SCHEDULED with
- # that restored — keeping suppress_delivery / the delivery target / the task
- # attribution instead of degrading to a plain user turn (#84). The key's
- # PRESENCE also marks this row as a scheduled segment for the flush.
- engine = get_cached_sqlite_engine()
- with run_update_event_transaction(engine) as conn:
- scope_id = _scope_id_for_session(conn, session_id)
- try:
- with conn.begin_nested():
- messages_service.append(
- conn,
- scope_id=scope_id,
- session_id=session_id,
- platform="avibe",
- author="harness",
- source="harness",
- message_type=messages_service.QUEUED_TYPE,
- text=text,
- metadata={SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(context)},
- native_message_id=native_message_id or None,
+ target_was_busy = message_deliveries.active_turn(conn, session_id) is not None
+ if existing is not None and existing["session_id"] != session_id:
+ return "duplicate"
+ if existing is not None and existing["state"] != "reserved":
+ if execution_id:
+ run_owner = conn.execute(
+ select(
+ agent_runs.c.status,
+ agent_runs.c.session_id,
+ agent_runs.c.delivery_id,
)
- if delivery_intent == "send_now":
- execution_id = str(
- (context.platform_specific or {}).get(
- "task_execution_id"
- )
- or ""
- ).strip()
- if not hold_running_agent_run_for_workbench_in_connection(
+ .where(agent_runs.c.id == execution_id)
+ .limit(1)
+ ).mappings().first()
+ if (
+ run_owner is not None
+ and normalize_run_status(run_owner["status"])
+ in {"queued", "running"}
+ and run_owner["session_id"] == session_id
+ and run_owner["delivery_id"] == existing["id"]
+ ):
+ existing_state = str(existing["state"])
+ if existing_state == "retired":
+ cancel_queued_agent_run_delivery_in_connection(
conn,
execution_id,
- delivery_outcome={
- "intent": "send_now",
- "status": "admitted",
- "target_was_busy": bool(
- manager.in_flight.get(session_id)
- ),
- },
- ):
- if agent_run_cancellation_won_in_connection(
- conn,
- execution_id,
- ):
- raise _QueueTransferCancelled
- raise RuntimeError(
- "send-now Agent Run queue ownership transfer was refused"
- )
- queue_owner_transferred = True
- except _QueueTransferCancelled:
- queue_transfer_cancelled = True
- return False
- except IntegrityError:
- logger.info("scheduled turn duplicate native id already queued: %s", native_message_id)
- if delivery_intent == "send_now":
- # A send-now attempt may not treat somebody else's
- # duplicate row as its own admission; that would
- # interrupt without transferring this Run.
- return False
- return bool(
- native_message_id
- and messages_service.native_message_exists(
- conn,
- platform="avibe",
- native_message_id=native_message_id,
+ session_id=session_id,
+ delivery_id=str(existing["id"]),
+ )
+ return TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=False,
+ target_was_busy=target_was_busy,
+ delivery_status="canceled",
+ )
+ return TurnSubmissionResult(
+ route=(
+ "enqueued"
+ if existing_state
+ in {
+ "queued",
+ "interrupt_waiting",
+ "waiting_terminal",
+ "reconciling_steer",
+ }
+ else "ran"
+ ),
+ queue_persisted=True,
+ target_was_busy=target_was_busy,
+ delivery_status=existing_state,
+ delivery_owner_transferred=True,
)
- )
- return True
-
- submission = await manager.submit(
- session_id,
- context,
- text,
- source=SOURCE_SCHEDULED,
- enqueue=_enqueue,
- delivery_intent=delivery_intent,
- )
- if submission.route == "enqueued" and submission.queue_persisted is not True:
- if queue_transfer_cancelled:
- submission = replace(submission, delivery_status="canceled")
+ return "duplicate"
+ if legacy_accepted:
+ return "duplicate"
+ status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)
+ ).scalar_one_or_none()
+ if status != "active":
+ raise ValueError("Session is archived")
+ if existing is not None:
+ delivery_id = str(existing["id"])
+ delivery_request = manager._request_from_delivery(existing)
+ scope_id = delivery_request.scope_id
+ effective_delivery_intent = (
+ "send_now" if delivery_request.priority == "p0" else "steer"
+ )
+ provenance = (delivery_request.metadata or {}).get(
+ SCHEDULED_PROVENANCE_KEY
+ )
+ persisted_spec = (
+ provenance.get("platform_specific")
+ if isinstance(provenance, dict)
+ else None
+ )
+ if isinstance(persisted_spec, dict):
+ execution_id = str(
+ persisted_spec.get("task_execution_id") or execution_id
+ ).strip()
else:
- raise RuntimeError("scheduled turn queue row was not persisted")
- if delivery_intent == "send_now":
- from storage.background import (
- record_agent_run_delivery_outcome_in_connection,
- run_update_event_transaction,
- )
-
- execution_id = str(
- (context.platform_specific or {}).get("task_execution_id") or ""
- ).strip()
- outcome = {
- "intent": "send_now",
- "status": submission.delivery_status or submission.route,
- "target_was_busy": submission.target_was_busy,
- }
- with run_update_event_transaction(get_cached_sqlite_engine()) as conn:
- if not record_agent_run_delivery_outcome_in_connection(
+ scope_id = _scope_id_for_session(conn, session_id)
+ delivery_id = message_deliveries.new_delivery_id()
+ admitted_state = "reserved"
+ message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=session_id,
+ priority="p0" if delivery_intent == "send_now" else "p1",
+ state=admitted_state,
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text=text,
+ metadata={
+ SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(
+ context
+ )
+ },
+ native_message_id=native_message_id or None,
+ ),
+ dispatch_text=text,
+ dedupe_key=dedupe_key,
+ history_event={
+ "kind": "admission",
+ "priority": "p0" if delivery_intent == "send_now" else "p1",
+ "state": admitted_state,
+ },
+ )
+ if execution_id:
+ if not attach_agent_run_delivery_in_connection(
conn,
execution_id,
- outcome,
+ session_id=session_id,
+ delivery_id=delivery_id,
+ delivery_outcome={
+ "intent": effective_delivery_intent,
+ "status": "admitted",
+ "target_was_busy": target_was_busy,
+ },
):
- raise RuntimeError(
- "send-now Agent Run delivery outcome could not be recorded"
+ if agent_run_cancellation_won_in_connection(conn, execution_id):
+ message_deliveries.retire_not_written(
+ conn,
+ session_id,
+ delivery_id,
+ reason="agent_run_canceled",
+ )
+ return TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=False,
+ delivery_status="canceled",
+ )
+ raise RuntimeError("Agent Run Delivery binding was refused")
+ delivery_owner_transferred = True
+
+ if delivery_request is None:
+ delivery_request = DeliveryRequest(
+ session_id=session_id,
+ priority="p0" if delivery_intent == "send_now" else "p1",
+ content=text,
+ delivery_id=delivery_id,
+ scope_id=scope_id,
+ source="harness",
+ author="harness",
+ message_type="harness",
+ display_text=text,
+ metadata={
+ SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(context)
+ },
+ native_message_id=native_message_id or None,
+ )
+
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ context.platform_specific.update(
+ {
+ "delivery_id": delivery_id,
+ "native_message_id": delivery_request.native_message_id,
+ "scope_id": scope_id,
+ "display_text": delivery_request.display_text,
+ "message_metadata": dict(delivery_request.metadata or {}),
+ }
+ )
+ try:
+ result = await manager.deliver(
+ delivery_request,
+ context=context,
+ )
+ except Exception:
+ if not delivery_owner_transferred:
+ raise
+ logger.exception(
+ "Delivery admission deferred to recovery after Agent Run ownership "
+ "transfer: run=%s delivery=%s",
+ execution_id,
+ delivery_id,
+ )
+ delivery_status = "reserved"
+ try:
+ with run_update_event_transaction(get_cached_sqlite_engine()) as conn:
+ persisted = message_deliveries.get_delivery(conn, delivery_id)
+ delivery_status = str(
+ (persisted or {}).get("state") or delivery_status
)
- submission = replace(
- submission,
- queue_owner_transferred=queue_owner_transferred,
+ recorded = record_agent_run_delivery_outcome_in_connection(
+ conn,
+ execution_id,
+ {
+ "intent": effective_delivery_intent,
+ "status": delivery_status,
+ "target_was_busy": target_was_busy,
+ },
+ )
+ if not recorded:
+ logger.warning(
+ "Agent Run deferred Delivery outcome lost its exact CAS: "
+ "run=%s delivery=%s",
+ execution_id,
+ delivery_id,
+ )
+ except Exception:
+ logger.exception(
+ "Agent Run deferred outcome projection failed; Delivery "
+ "ownership remains authoritative: run=%s delivery=%s",
+ execution_id,
+ delivery_id,
+ )
+ _publish_scheduled_queue_growth(session_id, delivery_status)
+ return TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ target_was_busy=target_was_busy,
+ delivery_status=delivery_status,
+ delivery_owner_transferred=True,
)
- # Existing scheduled/task/watch callers consume only the route string.
- # A direct Agent Run with send-now also needs the turn owner's exact
- # interrupt outcome, so return the structured result only for that
- # explicit contract and keep every legacy caller byte-compatible.
- return submission if delivery_intent == "send_now" else submission.route
+ route = "enqueued" if result.state in {
+ "queued",
+ "interrupt_waiting",
+ "waiting_terminal",
+ "reconciling_steer",
+ } else "ran"
+ submission = TurnSubmissionResult(
+ route=route,
+ queue_persisted=True,
+ target_was_busy=target_was_busy,
+ delivery_status=(
+ result.state if effective_delivery_intent == "send_now" else None
+ ),
+ delivery_owner_transferred=delivery_owner_transferred,
+ )
+ _publish_scheduled_queue_growth(session_id, str(result.state))
+ if effective_delivery_intent == "send_now":
+ try:
+ with run_update_event_transaction(get_cached_sqlite_engine()) as conn:
+ recorded = record_agent_run_delivery_outcome_in_connection(
+ conn,
+ execution_id,
+ {
+ "intent": "send_now",
+ "status": result.state,
+ "target_was_busy": submission.target_was_busy,
+ },
+ )
+ if not recorded:
+ logger.warning(
+ "send-now Agent Run outcome lost its exact CAS after Delivery "
+ "ownership transfer: run=%s delivery=%s",
+ execution_id,
+ delivery_id,
+ )
+ except Exception:
+ logger.exception(
+ "send-now Agent Run outcome persistence deferred after Delivery "
+ "ownership transfer: run=%s delivery=%s",
+ execution_id,
+ delivery_id,
+ )
+ return submission
+ return submission if delivery_owner_transferred else route
@app.get("/internal/health")
async def _health() -> dict[str, Any]:
@@ -339,285 +512,90 @@ def create_app(controller: "Controller") -> FastAPI:
@app.post("/internal/dispatch_async")
async def _dispatch_async(request: Request) -> Any:
- """Fire-and-forget turn dispatch for the session/page-scoped stream.
-
- Starts the turn and returns ``202`` immediately. The reply — plus any
- notify/result — reaches the browser over the persistent ``message.new``
- session stream, so the HTTP response isn't held open for the turn's
- duration and a closed browser tab can't cancel an in-flight turn.
- ``_run_turn`` holds the turn open (keeping ``in_flight`` populated so
- Stop works), publishes the turn lifecycle, and flushes the
- send-while-busy queue when it settles.
- """
- from storage import messages_service
+ """Admit one already-persisted Delivery on the controller loop."""
+
+ from storage import message_deliveries
+ from storage import workbench_sessions_service
payload = await _safe_json(request)
try:
text, context = await _build_dispatch_payload(payload)
except ValueError as err:
return JSONResponse(status_code=400, content={"ok": False, "error": str(err)})
+ session_id = str(payload.get("session_id") or "").strip()
+ delivery_id = str(payload.get("user_message_id") or "").strip()
+ if not session_id or not delivery_id:
+ return JSONResponse(
+ status_code=400,
+ content={"ok": False, "error": "session_id and user_message_id are required"},
+ )
+ with get_cached_sqlite_engine().begin() as conn:
+ from storage.agent_session_rows import reserve_write_lock
- session_id = payload.get("session_id")
- sid = session_id if isinstance(session_id, str) and session_id else None
- user_message_id = payload.get("user_message_id")
- reserved_type: str | None = None
-
- def _reservation_state() -> tuple[dict[str, Any] | None, bool]:
- if not (
- isinstance(user_message_id, str)
- and user_message_id
- and sid
- ):
- return None, False
-
- from sqlalchemy import select
- from storage import workbench_sessions_service
- from storage.models import messages
-
- with get_cached_sqlite_engine().connect() as conn:
- reserved = conn.execute(
- select(
- messages.c.type,
- messages.c.author,
- messages.c.source,
- ).where(
- messages.c.id == user_message_id,
- messages.c.session_id == sid,
- )
- ).mappings().first()
- archived = workbench_sessions_service.is_session_archived(conn, sid)
- return reserved, archived
-
- async def _cancel_matching_turn() -> None:
- if not (
- isinstance(user_message_id, str)
- and user_message_id
- and sid
+ reserve_write_lock(conn)
+ delivery = message_deliveries.get_delivery(conn, delivery_id)
+ archived = workbench_sessions_service.is_session_archived(conn, session_id)
+ if (
+ archived
+ and delivery is not None
+ and delivery["session_id"] == session_id
+ and delivery["state"] == "reserved"
):
- return
- active = manager.in_flight.get(sid)
- active_message_id = str(
- getattr(getattr(active, "context", None), "message_id", None) or ""
- ).strip()
- if active_message_id == user_message_id:
- result = await manager.cancel(sid)
- if not result.get("ok") and not active.task.done():
- active.task.cancel()
- await asyncio.gather(active.task, return_exceptions=True)
- if manager.in_flight.get(sid) is active:
- manager.in_flight.pop(sid, None)
- from core.inbox_events import bus
-
- bus.publish("turn.end", {"session_id": sid})
- controller.set_agent_status(sid, "idle")
-
- def _reservation_conflict(*, archived: bool) -> JSONResponse:
+ message_deliveries.retire_not_written(
+ conn,
+ session_id,
+ delivery_id,
+ reason="session_archived",
+ )
+ delivery = message_deliveries.get_delivery(conn, delivery_id)
+ if archived or delivery is None or delivery["session_id"] != session_id:
return JSONResponse(
status_code=409,
content={
"ok": False,
- "code": (
- "session_archived"
- if archived
- else "message_reservation_lost"
- ),
+ "code": "session_archived" if archived else "delivery_reservation_lost",
"session_id": session_id,
- "message_id": user_message_id,
+ "delivery_id": delivery_id,
},
)
-
- def _enqueue() -> bool:
- # The caller already persisted an input as ``pending``; promote it to
- # ``queued`` so it drains after the active turn. Keep the exact
- # agent-facing text separately from its transcript display text.
- if isinstance(user_message_id, str) and user_message_id:
- engine = get_cached_sqlite_engine()
- with engine.begin() as conn:
- return queue_pending_user_message(
- conn,
- user_message_id,
- text,
- )
- return False
-
- def _accept_reserved_input() -> dict[str, Any] | None:
- """Persist controller acceptance before the HTTP response can be lost."""
-
- if not (
- isinstance(user_message_id, str)
- and user_message_id
- and sid
- ):
- return None
-
- from core.inbox_events import bus
- from storage import messages_service
-
- promoted = False
- with get_cached_sqlite_engine().begin() as conn:
- row = messages_service.get_message(
- conn,
- user_message_id,
- session_id=sid,
- )
- if row is None:
- return None
- target_type = messages_service.pending_message_target_type(
- row.get("author"),
- row.get("source"),
- row.get("author_name"),
- )
- promoted = messages_service.promote_pending(
- conn,
- user_message_id,
- target_type,
- )
- if promoted:
- row = messages_service.get_message(
- conn,
- user_message_id,
- session_id=sid,
- )
-
- if promoted and row is not None:
- bus.publish("message.new", row)
- bus.publish(
- "session.activity",
- {
- "session_id": sid,
- "scope_id": row.get("scope_id"),
- "event": (
- "show_event"
- if row.get("author") == HARNESS_TYPE
- and is_input_turn(
- row.get("author"),
- row.get("type"),
- )
- else "user_message"
- ),
- },
- )
- try:
- with get_cached_sqlite_engine().connect() as conn:
- inbox_row = messages_service.get_inbox_session(
- conn,
- sid,
- platform="avibe",
- )
- if inbox_row is not None:
- bus.publish("inbox.session.updated", inbox_row)
- except Exception:
- logger.debug(
- "inbox.session.updated publish (accepted input) failed",
- exc_info=True,
- )
- return row
-
- if isinstance(user_message_id, str) and user_message_id and sid:
- active = manager.in_flight.get(sid)
- active_message_id = str(
- getattr(getattr(active, "context", None), "message_id", None) or ""
- ).strip()
- reserved, archived = _reservation_state()
- if archived or reserved is None:
- return _reservation_conflict(archived=archived)
- reserved_type = str(reserved["type"])
- if (
- active_message_id == user_message_id
- and reserved_type == messages_service.PENDING_TYPE
- ):
- accepted = _accept_reserved_input()
- if accepted is None:
- reserved, archived = _reservation_state()
- if archived or reserved is None:
- await _cancel_matching_turn()
- return _reservation_conflict(archived=archived)
- reserved_type = (
- str(accepted["type"])
- if accepted is not None
- else messages_service.PENDING_TYPE
- )
- if active_message_id == user_message_id or reserved_type in (
- _ACCEPTED_RESERVATION_TYPES - {messages_service.QUEUED_TYPE}
- ):
- return JSONResponse(
- status_code=202,
- content={
- "ok": True,
- "duplicate": True,
- "session_id": session_id,
- "message_id": user_message_id,
- **({"message_type": reserved_type} if reserved_type else {}),
- },
- )
- if reserved_type == messages_service.QUEUED_TYPE:
- return JSONResponse(
- status_code=202,
- content={
- "ok": True,
- "queued": True,
- "duplicate": True,
- "session_id": session_id,
- "message_id": user_message_id,
- "message_type": messages_service.QUEUED_TYPE,
- },
- )
-
- submission = await manager.submit(sid, context, text, enqueue=_enqueue)
- settled_message_id = user_message_id
- settled_type = None
- if submission.route == "ran":
- settled = _accept_reserved_input()
- settled_type = settled.get("type") if settled is not None else None
- if (
- settled_type is None
- and isinstance(settled_message_id, str)
- and settled_message_id
- and sid
- ):
- settled, archived = _reservation_state()
- settled_type = str(settled["type"]) if settled is not None else None
- if archived or settled is None:
- if submission.route == "ran":
- await _cancel_matching_turn()
- return _reservation_conflict(archived=archived)
-
- if submission.route == "enqueued":
- # An idle session can already have queue rows left by Stop. ``submit``
- # may drain synchronously before returning. Read the stored row rather
- # than inferring durability from the route.
- if settled_type != messages_service.QUEUED_TYPE:
- return JSONResponse(
- status_code=202,
- content={
- "ok": True,
- "drained": True,
- "session_id": session_id,
- **(
- {"message_id": settled_message_id}
- if settled_type
- else {}
- ),
- **({"message_type": settled_type} if settled_type else {}),
- },
- )
+ if delivery["state"] != "reserved":
return JSONResponse(
status_code=202,
content={
"ok": True,
- "queued": True,
+ "duplicate": True,
"session_id": session_id,
- "message_id": settled_message_id,
- "message_type": messages_service.QUEUED_TYPE,
+ "delivery_id": delivery_id,
+ "message_id": delivery.get("message_id"),
+ "delivery_state": delivery["state"],
+ "queued": delivery["state"] == "queued",
},
)
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ context.platform_specific.update(
+ {
+ "delivery_id": delivery_id,
+ "scope_id": payload.get("scope_id"),
+ "display_text": payload.get("display_text"),
+ "message_content": payload.get("content"),
+ "message_metadata": payload.get("metadata") or {},
+ "author_id": payload.get("author_id"),
+ "author_name": payload.get("author_name"),
+ }
+ )
+ submission = await manager.submit(session_id, context, text)
+ with get_cached_sqlite_engine().connect() as conn:
+ settled = message_deliveries.get_delivery(conn, delivery_id)
return JSONResponse(
status_code=202,
content={
"ok": True,
"session_id": session_id,
- **({"message_id": settled_message_id} if settled_type else {}),
- **({"message_type": settled_type} if settled_type else {}),
+ "delivery_id": delivery_id,
+ "message_id": (settled or {}).get("message_id"),
+ "delivery_state": (settled or {}).get("state"),
+ "queued": submission.route == "enqueued",
},
)
@@ -779,17 +757,23 @@ def create_app(controller: "Controller") -> FastAPI:
code = result.get("code")
if code == "not_in_flight":
return JSONResponse(status_code=404, content=result)
- if code == "stop_failed":
+ if code in {"stop_failed", "stop_unknown"}:
return JSONResponse(status_code=409, content=result)
return result
@app.post("/internal/send-now/{session_id}")
- async def _send_now(session_id: str) -> Any:
+ async def _send_now(
+ session_id: str,
+ expected_delivery_id: str | None = None,
+ ) -> Any:
"""HTTP adapter: delegate "立即发送" (run the send-while-busy queue now) to
the turn owner (FSM, Phase 1b); typed failures remain HTTP failures."""
- result = await manager.send_now(session_id)
+ result = await manager.send_now(
+ session_id,
+ expected_delivery_id=expected_delivery_id,
+ )
code = result.get("code")
- if code == "stop_failed":
+ if code in {"stop_failed", "stale_head", "ordering_fence"}:
return JSONResponse(status_code=409, content=result)
if code == "flush_failed":
return JSONResponse(status_code=503, content=result)
@@ -831,17 +815,38 @@ async def serve(controller: "Controller", *, socket_path: Optional[Path] = None)
app = create_app(controller)
manager = getattr(controller, "session_turns", None)
- recover_queue = getattr(manager, "recover_persisted_agent_run_queue", None)
- if callable(recover_queue):
- try:
- recovered = await recover_queue()
- if recovered:
- logger.info(
- "Recovered persisted Workbench Agent Run queues for %s",
- ",".join(recovered),
- )
- except Exception:
- logger.exception("Failed to recover persisted Workbench Agent Run queues")
+ restore_barrier = getattr(controller, "_delivery_recovery_barrier", None)
+ if restore_barrier is not None:
+ await restore_barrier.wait()
+ recovery_complete = getattr(controller, "_delivery_recovery_complete", None)
+ try:
+ delivery_recovery_ok = True
+ recover_deliveries = getattr(manager, "recover_durable_delivery_state", None)
+ if callable(recover_deliveries):
+ try:
+ recovered = await recover_deliveries(service_restart=True)
+ if recovered:
+ logger.info(
+ "Recovered durable Session delivery owners for %s",
+ ",".join(recovered),
+ )
+ except Exception:
+ delivery_recovery_ok = False
+ logger.exception("Failed to recover durable Session delivery owners")
+ recover_queue = getattr(manager, "recover_persisted_agent_run_queue", None)
+ if callable(recover_queue) and delivery_recovery_ok:
+ try:
+ recovered = await recover_queue()
+ if recovered:
+ logger.info(
+ "Recovered persisted Workbench Agent Run queues for %s",
+ ",".join(recovered),
+ )
+ except Exception:
+ logger.exception("Failed to recover persisted Workbench Agent Run queues")
+ finally:
+ if recovery_complete is not None:
+ recovery_complete.set()
config = uvicorn.Config(
app,
log_config=None,
@@ -975,6 +980,19 @@ async def _build_dispatch_payload(payload: dict[str, Any]) -> tuple[str, Message
message_id=payload.get("message_id") or payload.get("user_message_id"),
files=files,
)
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ context.platform_specific.update(
+ {
+ "delivery_id": payload.get("user_message_id"),
+ "scope_id": payload.get("scope_id"),
+ "display_text": payload.get("display_text"),
+ "message_content": payload.get("content"),
+ "message_metadata": payload.get("metadata") or {},
+ "author_id": payload.get("author_id"),
+ "author_name": payload.get("author_name"),
+ }
+ )
return text, context
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 4832dd15e..08029913b 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -23,7 +23,7 @@ from core.delivery_evidence import STAGE_PERSIST, STAGE_SEND, STAGE_STREAM, Deli
from core.message_mirror import (
agent_message_exists,
persist_agent_message,
- persist_silent_completion_marker,
+ persist_silent_terminal,
)
from core.message_output import (
HARNESS_RUN_ID_TRIGGER_KINDS,
@@ -44,18 +44,18 @@ from vibe.i18n import t as i18n_t
logger = logging.getLogger(__name__)
-def _coalesced_task_execution_ids(payload: dict[str, Any]) -> list[str]:
+def _owned_agent_run_ids(payload: dict[str, Any]) -> list[str]:
run_ids: list[str] = []
- primary = str(payload.get("task_execution_id") or "").strip()
- if primary:
- run_ids.append(primary)
- coalesced = payload.get("coalesced_queue")
- execution_ids = coalesced.get("execution_ids") if isinstance(coalesced, dict) else None
- if isinstance(execution_ids, list):
- for value in execution_ids:
+ accepted = payload.get("accepted_agent_run_ids")
+ if isinstance(accepted, list):
+ for value in accepted:
run_id = str(value or "").strip()
if run_id and run_id not in run_ids:
run_ids.append(run_id)
+ if payload.get("task_trigger_kind") in HARNESS_RUN_ID_TRIGGER_KINDS:
+ primary = str(payload.get("task_execution_id") or "").strip()
+ if primary and primary not in run_ids:
+ run_ids.append(primary)
return run_ids
@@ -1030,7 +1030,10 @@ class ConsolidatedMessageDispatcher:
terminal_status: Optional[str] = None,
) -> None:
payload = context.platform_specific or {}
- run_ids = _coalesced_task_execution_ids(payload)
+ run_ids = _owned_agent_run_ids(payload)
+ for run_id in self._durable_accepted_agent_run_ids(context):
+ if run_id not in run_ids:
+ run_ids.append(run_id)
if not run_ids:
return
store = None
@@ -1152,8 +1155,11 @@ class ConsolidatedMessageDispatcher:
run_id = str(value or "").strip()
if run_id and run_id not in run_ids:
run_ids.append(run_id)
- if not run_ids and payload.get("task_trigger_kind") in HARNESS_RUN_ID_TRIGGER_KINDS:
- run_ids = _coalesced_task_execution_ids(payload)
+ if not run_ids:
+ run_ids = _owned_agent_run_ids(payload)
+ for durable_run_id in self._durable_accepted_agent_run_ids(context):
+ if durable_run_id not in run_ids:
+ run_ids.append(durable_run_id)
if not run_ids:
return
terminal_status = None
@@ -1179,6 +1185,25 @@ class ConsolidatedMessageDispatcher:
finally:
if store is not None:
store.close()
+
+ def _durable_accepted_agent_run_ids(self, context: MessageContext) -> list[str]:
+ turn_id = str((context.platform_specific or {}).get("turn_token") or "").strip()
+ if not turn_id:
+ return []
+ manager = getattr(self.controller, "session_turns", None)
+ read = getattr(manager, "accepted_agent_run_ids_for_turn", None)
+ if not callable(read):
+ return []
+ try:
+ return list(read(turn_id))
+ except Exception:
+ logger.warning(
+ "Failed to read durable Agent Run attribution for Turn %s",
+ turn_id,
+ exc_info=True,
+ )
+ return []
+
def _record_suppressed_agent_run_terminal_result(
self,
context: MessageContext,
@@ -1454,24 +1479,10 @@ class ConsolidatedMessageDispatcher:
else:
terminal_reason = "failed"
- # OUTBOUND status chokepoint (one of exactly two — the other is the
- # inbound AgentService.handle_message). A terminal ``result`` ends the
- # turn, so settle the avibe sidebar dot here regardless of delivery
- # outcome. Non-avibe contexts resolve to no session id and are skipped;
- # ``getattr`` keeps it a no-op for controllers without the hook (mirrors
- # ``_signal_turn_complete``).
if canonical_type == "result":
if not current_runtime_turn and not output_semantics.detached:
logger.info("Dropping stale result emit for superseded runtime turn in %s", self._get_session_key(context))
return None
- # Settle the avibe dot for the ACTIVE turn's terminal result (idle, or
- # failed on is_error) via the turn owner, which applies the active-turn
- # guard + skips non-avibe contexts. Runtime gate release happens after
- # the result path clears/persists/streams its own state.
- if mutates_turn_lifecycle:
- manager = getattr(self.controller, "session_turns", None)
- if manager is not None:
- manager.on_terminal_result(context, is_error=is_error)
raw_text = text
enhanced = None
if canonical_type == "result" and level != "silent":
@@ -1480,6 +1491,23 @@ class ConsolidatedMessageDispatcher:
text = enhanced.visible_text
else:
text = strip_silent_blocks(raw_text)
+ # Persist the exact terminal body in the Turn snapshot before delivery.
+ # A steer accepted after this Turn settles can then complete its Agent Run
+ # without guessing from transcript order or requiring a live sink.
+ if mutates_turn_lifecycle:
+ terminal_body = enhanced.text if enhanced and enhanced.text.strip() else text
+ manager = getattr(self.controller, "session_turns", None)
+ if manager is not None:
+ manager.on_terminal_result(
+ context,
+ is_error=is_error,
+ terminal_evidence={
+ "result_text": self._fold_footer(terminal_body, result_footer),
+ "terminal_error": terminal_error,
+ "settles_run": output_semantics.settles_run,
+ "output_provenance": output_semantics.provenance(context),
+ },
+ )
# ``level="silent"`` is the explicit visibility control (orthogonal to type):
# the message already settled the dot above (for a terminal result), so here
# we release the SSE waiter and return BEFORE any delivery / persistence /
@@ -1487,6 +1515,13 @@ class ConsolidatedMessageDispatcher:
# body (e.g. a ``<silent>`` directive reduced to nothing) is silent too.
if level == "silent" or not text or not text.strip():
try:
+ if (
+ mutates_turn_lifecycle
+ and context.platform != "avibe"
+ and self._turn_release_settlement(output_semantics)
+ != SETTLED_BY_STOPPED
+ ):
+ persist_silent_terminal(context, is_error=is_error)
if canonical_type == "result" and output_semantics.settles_run:
# Run completion is independent from visible Message and Turn
# completion cardinality. A detached/empty final output may
@@ -1511,26 +1546,6 @@ class ConsolidatedMessageDispatcher:
context,
settled_by=self._turn_release_settlement(output_semantics),
)
- if level != "silent" and not is_error:
- # A CLEAN silent completion — ``level='normal'`` with an
- # empty/``<silent>``-stripped body (we're already inside the
- # ``level=='silent' or not text.strip()`` branch, so here the
- # body is empty). Persist an INVISIBLE ``silent`` terminal
- # marker; without it the activity grouping sees "activity rows +
- # no terminal" and misreads a legal completion as interrupted.
- #
- # This must NOT fire for ``level='silent'``: the user-stop paths
- # (codex/claude/opencode) emit a terminal ``result`` with
- # ``level='silent'`` and ``is_error=False`` — a stop legitimately
- # stays ``interrupted``, so ``not is_error`` is the wrong gate.
- # Backend failures also arrive ``level='silent'`` (after a
- # visible notify), and are excluded here too. Background
- # sessions still keep this local terminal marker; visibility
- # suppresses outward delivery, not durable history.
- try:
- persist_silent_completion_marker(context)
- except Exception:
- logger.exception("emit_agent_message: silent completion marker failed")
return None
finally:
if mutates_turn_lifecycle:
@@ -1984,8 +1999,13 @@ class ConsolidatedMessageDispatcher:
and output_semantics.settles_run
and bool(run_provenance.get("run_id") or run_provenance.get("run_ids"))
)
+ workbench_terminal_waits_for_persistence = (
+ target_context.platform == "avibe" and mutates_turn_lifecycle
+ )
settlement_waits_for_persistence = (
- output_semantics.requires_delivery_for_run_settlement or workbench_run_waits_for_persistence
+ output_semantics.requires_delivery_for_run_settlement
+ or workbench_run_waits_for_persistence
+ or workbench_terminal_waits_for_persistence
)
if not settlement_waits_for_persistence:
@@ -2046,6 +2066,10 @@ class ConsolidatedMessageDispatcher:
and agent_message_exists(target_context, native_output_id)
)
)
+ if workbench_terminal_waits_for_persistence and not durable_output_exists:
+ raise RuntimeError(
+ "Workbench terminal output was not durably persisted"
+ )
if workbench_run_waits_for_persistence and not durable_output_exists:
raise RuntimeError("Workbench run output was not durably persisted")
if (
diff --git a/core/message_mirror.py b/core/message_mirror.py
index 4dafcffd8..07b0c2974 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -248,73 +248,6 @@ def _trace_ids_from_context(context: MessageContext) -> tuple[Optional[str], Opt
return turn_id, run_id
-def persist_silent_completion_marker(context: MessageContext) -> None:
- """Persist the invisible ``silent`` terminal marker for a turn that completed
- NORMALLY but delivered no user-visible message — a ``<silent>``-stripped/empty
- final reply, or a reply-less bookkeeping turn (common for watch/scheduled runs).
-
- Written ONCE per turn at the delivery chokepoint
- (``MessageDispatcher.emit_agent_message``) on the clean-completion path only — NOT
- for cancel/Stop (which legitimately stays ``interrupted``) nor backend failures
- (which already emit a visible ``notify``). It exists solely so the activity
- grouping closes the turn as DONE instead of misreading "activity + no terminal" as
- interrupted; it is never delivered, or shown as a transcript bubble (see
- ``messages_service.SILENT_TYPE`` and its allowlist/denylist exclusions). Writes via
- ``_append_quietly`` directly — bypassing ``persist_agent_message``'s empty-text
- guard and the ``message.new`` publish (the marker is invisible in the transcript).
-
- It DOES recompute + publish the inbox row, though: the marker counts as a reply for
- the inbox awaiting/replied flag, so an open sidebar must clear "awaiting the agent"
- live instead of staying stale until a reconnect. No web-push (a silent completion is
- not a notifiable reply). Best-effort: the caller wraps it; a failure must never break
- turn completion.
- """
- if not context.platform:
- return
- session_id = (context.platform_specific or {}).get("agent_session_id")
- suppress_delivery = bool((context.platform_specific or {}).get("suppress_delivery"))
- engine = get_cached_sqlite_engine()
- inbox_row = None
- with engine.begin() as conn:
- if context.platform == "avibe":
- session_row = _session_row(conn, session_id) if session_id else None
- scope_id = session_row["scope_id"] if session_row else None
- else:
- session_row = None
- scope_id = _resolve_scope_id(conn, context)
- if scope_id is None and session_row is None:
- return
- agent_name, _backend = _agent_provenance_from_context(context, session_row)
- _append_quietly(
- conn,
- scope_id=scope_id,
- session_id=session_id,
- platform=context.platform,
- author="agent",
- source="agent",
- author_name=agent_name,
- message_type=messages_service.SILENT_TYPE,
- text="",
- metadata=None,
- native_message_id=None,
- parent_native_message_id=context.thread_id,
- content={"kind": "silent"},
- )
- # Recompute the session's inbox row so the awaiting/replied flag clears live.
- # avibe-only (the workbench inbox is avibe-scoped; IM rows aren't shown there).
- if context.platform == "avibe" and session_id and not suppress_delivery:
- inbox_row = messages_service.get_inbox_session(conn, session_id)
- if inbox_row is not None:
- # Same ``inbox.session.updated`` event a visible reply publishes — but NOT
- # ``message.new`` (no transcript bubble) and NOT web-push (not a notifiable reply).
- try:
- from core.inbox_events import bus
-
- bus.publish("inbox.session.updated", inbox_row)
- except Exception:
- logger.debug("persist_silent_completion_marker: inbox publish failed", exc_info=True)
-
-
def persist_agent_message(
context: MessageContext,
canonical_type: str,
@@ -507,6 +440,52 @@ def persist_agent_message(
return None
+def persist_silent_terminal(context: MessageContext, *, is_error: bool) -> None:
+ """Record reply-less IM terminal evidence outside the Message transcript.
+
+ Durable Workbench turns settle through ``session_turns``. IM turns do not have
+ that execution owner, so their empty/silent terminal result is retained as an
+ append-only trace event for activity grouping and fork-boundary recovery.
+ """
+
+ session_id = (context.platform_specific or {}).get("agent_session_id")
+ if not context.platform or not session_id:
+ return
+ try:
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as conn:
+ if context.platform == "avibe":
+ session_row = _session_row(conn, session_id)
+ scope_id = session_row["scope_id"] if session_row else None
+ else:
+ session_row = None
+ scope_id = _resolve_scope_id(conn, context)
+ if scope_id is None and session_row is None:
+ return
+ agent_name, backend = _agent_provenance_from_context(context, session_row)
+ turn_id, run_id = _trace_ids_from_context(context)
+ agent_events_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform=context.platform,
+ event_type="silent_terminal",
+ visibility="trace",
+ metadata={
+ "terminal_outcome": "failed" if is_error else "completed",
+ },
+ agent_name=agent_name,
+ backend=backend,
+ turn_id=turn_id,
+ run_id=run_id,
+ )
+ except Exception:
+ logger.exception(
+ "persist_silent_terminal: failure on platform=%s",
+ context.platform,
+ )
+
+
def agent_message_exists(context: MessageContext, native_message_id: str | None) -> bool:
"""Check a stable output identity before external delivery.
diff --git a/core/native_dispatch_phase.py b/core/native_dispatch_phase.py
new file mode 100644
index 000000000..50f37e1bf
--- /dev/null
+++ b/core/native_dispatch_phase.py
@@ -0,0 +1,49 @@
+"""Shared evidence for whether a turn crossed the native dispatch boundary."""
+
+from __future__ import annotations
+
+from typing import Any, Optional
+
+
+DISPATCH_PHASE_KEY = "agent_dispatch_phase"
+DISPATCH_EVIDENCE_KEY = "agent_dispatch_evidence"
+DISPATCH_PHASE_PREWRITE = "prewrite"
+DISPATCH_PHASE_ATTEMPTING = "attempting"
+
+
+def set_dispatch_phase(
+ context: Any,
+ phase: str,
+ *,
+ evidence: dict[str, str] | None = None,
+) -> dict[str, str]:
+ payload = dict(getattr(context, "platform_specific", None) or {})
+ current = payload.get(DISPATCH_EVIDENCE_KEY)
+ if evidence is None:
+ evidence = current if isinstance(current, dict) else {}
+ evidence["phase"] = phase
+ payload[DISPATCH_EVIDENCE_KEY] = evidence
+ payload[DISPATCH_PHASE_KEY] = phase
+ context.platform_specific = payload
+ return evidence
+
+
+def backend_dispatch_attempted(context: Any) -> Optional[bool]:
+ payload = getattr(context, "platform_specific", None) or {}
+ evidence = payload.get(DISPATCH_EVIDENCE_KEY)
+ phase = str(
+ (evidence.get("phase") if isinstance(evidence, dict) else None)
+ or payload.get(DISPATCH_PHASE_KEY)
+ or ""
+ )
+ if phase == DISPATCH_PHASE_PREWRITE:
+ return False
+ if phase == DISPATCH_PHASE_ATTEMPTING:
+ return True
+ return None
+
+
+def mark_backend_dispatch_attempted(context: Any) -> None:
+ """Record the boundary immediately before an adapter's native write."""
+
+ set_dispatch_phase(context, DISPATCH_PHASE_ATTEMPTING)
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index fb616543a..434d381f7 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -24,7 +24,6 @@ from sqlalchemy.exc import SQLAlchemyError
from config import paths
from config.platform_registry import PLATFORM_REGISTRY
from config.v2_config import (
- DEFAULT_HARNESS_RUN_HOLD_TTL_SECONDS,
DEFAULT_HARNESS_RUN_ORPHAN_GRACE_SECONDS,
DEFAULT_HARNESS_RUN_QUEUED_TTL_SECONDS,
DEFAULT_HARNESS_RUN_SWEEP_INTERVAL_SECONDS,
@@ -52,6 +51,7 @@ from modules.im import MessageContext
from storage.agent_session_rows import (
INBOX_SESSION_VISIBILITIES,
WORKSPACE_NOTICE_SESSION_ID,
+ reserve_write_lock,
session_is_runtime_owned,
)
from storage.db import create_sqlite_engine, get_cached_sqlite_engine
@@ -90,10 +90,10 @@ from vibe.i18n import t as i18n_t
logger = logging.getLogger(__name__)
-AGENT_RUN_DELIVERY_QUEUE = "queue"
+AGENT_RUN_DELIVERY_STEER = "steer"
AGENT_RUN_DELIVERY_SEND_NOW = "send_now"
AGENT_RUN_DELIVERY_INTENTS = frozenset(
- {AGENT_RUN_DELIVERY_QUEUE, AGENT_RUN_DELIVERY_SEND_NOW}
+ {AGENT_RUN_DELIVERY_STEER, AGENT_RUN_DELIVERY_SEND_NOW}
)
AGENT_RUN_DELIVERY_INTENT_METADATA_KEY = "delivery_intent"
AGENT_RUN_DELIVERY_OUTCOME_METADATA_KEY = "delivery_outcome"
@@ -137,7 +137,9 @@ def _json_loads(value: str | None, default: Any) -> Any:
def normalize_agent_run_delivery_intent(value: Any) -> str:
"""Return the durable Agent Run delivery intent or reject an unknown value."""
- normalized = str(value or AGENT_RUN_DELIVERY_QUEUE).strip().lower()
+ normalized = str(value or AGENT_RUN_DELIVERY_STEER).strip().lower()
+ if normalized == "queue":
+ normalized = AGENT_RUN_DELIVERY_STEER
if normalized not in AGENT_RUN_DELIVERY_INTENTS:
raise ValueError(f"unsupported Agent Run delivery intent: {normalized}")
return normalized
@@ -431,6 +433,16 @@ class TaskExecutionResult:
session_key: str
session_id: Optional[str]
failure_code: Optional[str] = None
+ complete_on_return: bool = True
+ reconcile_delivery_on_return: bool = False
+
+
+@dataclass(frozen=True)
+class TaskDispatchResult:
+ """Admission result for any Task/Watch/Hook input submission."""
+
+ error: Optional[str]
+ complete_on_return: bool = True
@dataclass(frozen=True)
@@ -439,7 +451,6 @@ class AgentRunExecutionResult:
complete_on_return: bool
requeue_on_return: bool = False
recover_queue_on_return: bool = False
- coalesced_completion_ids: tuple[str, ...] = ()
# The run's terminal row was already written by the executor itself (through a
# guarded writer), so the caller must skip ``complete()`` but still run the
# post-completion side effects: callback delivery and session-queue recovery.
@@ -875,6 +886,7 @@ class TaskExecutionRequest:
session_policy: Optional[str] = None
callback_session_id: Optional[str] = None
callback_status: Optional[str] = None
+ delivery_id: Optional[str] = None
metadata: dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
@@ -905,67 +917,20 @@ class TaskExecutionRequest:
session_policy=payload.get("session_policy"),
callback_session_id=payload.get("callback_session_id"),
callback_status=payload.get("callback_status"),
+ delivery_id=payload.get("delivery_id"),
metadata=payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {},
)
def _agent_run_message_for_request(request: TaskExecutionRequest) -> str:
- coalesced = (request.metadata or {}).get("coalesced_queue")
- if isinstance(coalesced, dict):
- live_execution_ids = _live_coalesced_agent_run_ids(request)
- live_set = set(live_execution_ids) if live_execution_ids is not None else None
- prompt = str(coalesced.get("prompt") or "")
- if prompt and live_set is None:
- return prompt
- messages = coalesced.get("messages")
- if isinstance(messages, list):
- parts: list[str] = []
- for item in messages:
- if not isinstance(item, dict):
- continue
- execution_id = str(item.get("execution_id") or "").strip()
- if live_set is not None and execution_id not in live_set:
- continue
- message = str(item.get("message") or item.get("prompt") or "")
- if message:
- parts.append(message)
- if parts:
- return "\n\n---\n\n".join(parts)
return str(request.message or "")
-def _live_coalesced_agent_run_ids(request: TaskExecutionRequest) -> list[str] | None:
- coalesced = (request.metadata or {}).get("coalesced_queue")
- if not isinstance(coalesced, dict):
- return None
- execution_ids = coalesced.get("execution_ids")
- if not isinstance(execution_ids, list):
- return None
- run_ids: list[str] = []
- seen: set[str] = set()
- for value in execution_ids:
- run_id = str(value or "").strip()
- if run_id and run_id not in seen:
- seen.add(run_id)
- run_ids.append(run_id)
- if not run_ids:
- return []
- store = SQLiteBackgroundTaskStore()
- try:
- queued_ids, _stale_ids = store.inspect_queued_runs_for_workbench(run_ids)
- finally:
- store.close()
- live = [request.id]
- for run_id in queued_ids:
- if run_id not in live:
- live.append(run_id)
- return live
-
-
def _retire_stale_agent_run_queue_rows(
*,
session_id: Optional[str],
execution_ids: list[str],
+ resubmit_execution_id: Optional[str] = None,
) -> int:
"""Retire old queued Workbench rows for recovered direct Agent Runs.
@@ -987,44 +952,42 @@ def _retire_stale_agent_run_queue_rows(
if not session_id or not normalized_ids:
return 0
- from storage import messages_service
- from storage.models import messages
+ from sqlalchemy import select
+ from storage import message_deliveries
+ from storage.models import agent_runs
- native_ids = [f"agent_run:{execution_id}" for execution_id in normalized_ids]
- primary_native_id = native_ids[0]
engine = create_sqlite_engine()
with engine.begin() as conn:
- rows = list(
+ reserve_write_lock(conn)
+ bindings = {
+ str(row["id"]): str(row["delivery_id"])
+ for row in
conn.execute(
- select(messages.c.id, messages.c.native_message_id)
- .where(messages.c.session_id == session_id)
- .where(messages.c.platform == "avibe")
- .where(messages.c.type == messages_service.QUEUED_TYPE)
- .where(messages.c.native_message_id.in_(native_ids))
- )
- )
- primary_row_ids = [str(row.id) for row in rows if str(row.native_message_id or "") == primary_native_id]
- marker_row_ids = [str(row.id) for row in rows if str(row.native_message_id or "") != primary_native_id]
- if marker_row_ids:
- conn.execute(
- messages.update()
- .where(messages.c.id.in_(marker_row_ids))
- .values(
- author="harness",
- source="harness",
- type=messages_service.HARNESS_DEDUPE_TYPE,
- content_text="",
- content_json=json.dumps({"text": ""}),
- metadata_json=json.dumps({"coalesced_from": primary_native_id, "recovered_queue_row": True}),
- updated_at=_utc_now_iso(),
+ select(agent_runs.c.id, agent_runs.c.delivery_id)
+ .where(agent_runs.c.id.in_(normalized_ids))
+ .where(agent_runs.c.session_id == session_id)
+ .where(agent_runs.c.delivery_id.is_not(None))
+ ).mappings()
+ }
+ retired = 0
+ for run_id, delivery_id in bindings.items():
+ delivery = message_deliveries.get_delivery(conn, str(delivery_id))
+ if delivery is None or delivery["state"] != "queued":
+ continue
+ if run_id == resubmit_execution_id:
+ retired += int(
+ message_deliveries.retire_queued_for_resubmission(
+ conn,
+ session_id,
+ str(delivery_id),
+ expected_dedupe_key=f"avibe:agent_run:{resubmit_execution_id}",
+ )
)
- )
- row_ids = primary_row_ids + marker_row_ids
- if not row_ids:
- return 0
- if primary_row_ids:
- messages_service.delete_queued(conn, primary_row_ids)
- return len(row_ids)
+ else:
+ retired += int(
+ message_deliveries.retire_queued(conn, session_id, str(delivery_id))
+ )
+ return retired
class ScheduledTaskStore:
@@ -1817,7 +1780,7 @@ class TaskExecutionStore:
parent_run_id: Optional[str] = None,
callback_session_id: Optional[str] = None,
callback_active: bool = True,
- delivery_intent: str = AGENT_RUN_DELIVERY_QUEUE,
+ delivery_intent: str = AGENT_RUN_DELIVERY_STEER,
metadata: Optional[dict[str, Any]] = None,
expected_enabled_agent_id: Optional[str] = None,
) -> TaskExecutionRequest:
@@ -1862,7 +1825,6 @@ class TaskExecutionStore:
TaskExecutionRequest.from_dict(item)
for item in self._sqlite.list_runs(status="pending")
if item.get("request_type") in {"task_run", "hook_send", "agent_run", "scheduled", "watch", "webhook"}
- and not (item.get("metadata") or {}).get("workbench_queue_holds_run")
]
self._ensure_dirs()
requests: list[TaskExecutionRequest] = []
@@ -1993,10 +1955,8 @@ class TaskExecutionStore:
owned_run_ids: set[str],
error_texts: dict[str, str],
deliverable_run_ids: Optional[set[str]] = None,
- busy_session_ids: Optional[set[str]] = None,
orphan_grace_seconds: int,
queued_ttl_seconds: int,
- hold_ttl_seconds: int,
) -> list[SweptRun]:
"""Terminalize provably stale runs. Empty for the legacy file store."""
@@ -2006,10 +1966,8 @@ class TaskExecutionStore:
owned_run_ids=owned_run_ids,
error_texts=error_texts,
deliverable_run_ids=deliverable_run_ids,
- busy_session_ids=busy_session_ids,
orphan_grace_seconds=orphan_grace_seconds,
queued_ttl_seconds=queued_ttl_seconds,
- hold_ttl_seconds=hold_ttl_seconds,
)
def supports_guarded_settlement(self) -> bool:
@@ -2488,7 +2446,7 @@ class TaskExecutionStore:
tmp_path.replace(completed_path)
processing_path.unlink(missing_ok=True)
- def complete_coalesced(
+ def settle_turn_participants(
self,
request: TaskExecutionRequest,
run_ids: list[str],
@@ -2498,12 +2456,12 @@ class TaskExecutionStore:
) -> None:
if self._sqlite is not None:
from storage.background import (
- complete_coalesced_agent_runs_for_workbench_in_connection,
+ settle_agent_runs_for_turn_in_connection,
run_update_event_transaction,
)
with run_update_event_transaction(self._sqlite.engine) as conn:
- complete_coalesced_agent_runs_for_workbench_in_connection(
+ settle_agent_runs_for_turn_in_connection(
conn,
run_ids,
ok=ok,
@@ -2956,26 +2914,6 @@ class ScheduledTaskService:
owned |= {str(run_id) for run_id in provider() if run_id}
return owned
- def _busy_session_ids(self) -> set[str]:
- """Sessions with a live turn, which is why their queue holds exist.
-
- The gate answers ``enqueued`` for a run submitted into a session that already
- has a turn in flight, and that run is then requeued with
- ``workbench_queue_holds_run``. Nobody reports it as owned — the live turn owns
- only the ids it is itself executing — so the hold class needs this second live
- fact or it fails the follower of any turn longer than the hold TTL (Codex P2).
-
- Raises when the turn lane cannot be reached, for the same reason
- :meth:`_owned_agent_run_ids` does: "no session is busy" and "I cannot tell" are
- opposite answers, and the caller must fail closed on the second.
- """
-
- session_turns = getattr(self.controller, "session_turns", None)
- provider = getattr(session_turns, "busy_session_ids", None)
- if not callable(provider):
- raise RuntimeError("controller.session_turns.busy_session_ids is unavailable")
- return {str(session_id) for session_id in provider() if session_id}
-
def _deliverable_queued_run_ids(self) -> set[str]:
"""Queued runs whose transport is ready RIGHT NOW, whatever the row remembers.
@@ -3074,30 +3012,14 @@ class ScheduledTaskService:
)
deliverable_run_ids = set()
queued_ttl_seconds = 0
- hold_ttl_seconds = self._runtime_seconds(
- "harness_run_hold_ttl_seconds", DEFAULT_HARNESS_RUN_HOLD_TTL_SECONDS
- )
- try:
- busy_session_ids = self._busy_session_ids()
- except Exception:
- # Fail closed by disabling the class, same posture as deliverability: a hold
- # is only abandoned if no live turn explains it, and "I cannot tell which
- # sessions are busy" would fail a run the gate is about to flush.
- logger.warning(
- "Skipping queue-hold sweep: live session turns are unknown", exc_info=True
- )
- busy_session_ids = set()
- hold_ttl_seconds = 0
swept = self.request_store.sweep_stale_runs(
owned_run_ids=owned_run_ids,
deliverable_run_ids=deliverable_run_ids,
- busy_session_ids=busy_session_ids,
error_texts={reason: self._t(key) for reason, key in SWEEP_I18N_KEYS.items()},
orphan_grace_seconds=self._runtime_seconds(
"harness_run_orphan_grace_seconds", DEFAULT_HARNESS_RUN_ORPHAN_GRACE_SECONDS
),
queued_ttl_seconds=queued_ttl_seconds,
- hold_ttl_seconds=hold_ttl_seconds,
)
# Unconditional: the in-memory wedge and the stale rows are independent
# failures, and either can outlive the other.
@@ -4957,7 +4879,7 @@ class ScheduledTaskService:
should_complete = True
settled_out_of_band = False
recover_queue_on_return = False
- coalesced_completion_ids: list[str] = _live_coalesced_agent_run_ids(request) or []
+ reconcile_delivery_on_return = False
task_id = request.task_id
session_key = request.session_key
session_id = request.session_id
@@ -4985,6 +4907,8 @@ class ScheduledTaskService:
session_key = result.session_key
session_id = result.session_id
failure_code = result.failure_code
+ should_complete = result.complete_on_return
+ reconcile_delivery_on_return = result.reconcile_delivery_on_return
elif request.request_type in {"hook_send", "watch", "webhook"}:
if not request.prompt:
raise ValueError("hook request requires prompt")
@@ -4999,7 +4923,7 @@ class ScheduledTaskService:
session_key = ""
elif not (request.session_id or request.session_key):
raise ValueError("hook request requires session_id or session_key")
- error = await self._execute_request(
+ dispatch_result = await self._execute_request(
session_key=session_key,
session_id=session_id,
post_to=request.post_to,
@@ -5009,8 +4933,14 @@ class ScheduledTaskService:
task_id=task_id,
trigger_kind=request.request_type if request.request_type != "hook_send" else "hook",
agent_name=request.agent_name,
+ _capture_dispatch_result=True,
**({"agent_id": request.agent_id} if request.agent_id else {}),
)
+ if isinstance(dispatch_result, TaskDispatchResult):
+ error = dispatch_result.error
+ should_complete = dispatch_result.complete_on_return
+ else:
+ error = dispatch_result
elif request.request_type == "agent_run":
message = _agent_run_message_for_request(request)
if not message.strip():
@@ -5043,15 +4973,12 @@ class ScheduledTaskService:
settled_out_of_band = result.settled_out_of_band
recover_queue_on_return = result.recover_queue_on_return
if result.requeue_on_return:
- requeue_metadata: dict[str, Any] = {
- "workbench_queue_holds_run": True,
- }
+ requeue_metadata: dict[str, Any] = {}
if result.delivery_outcome is not None:
requeue_metadata[
AGENT_RUN_DELIVERY_OUTCOME_METADATA_KEY
] = result.delivery_outcome
self.request_store.requeue(request.id, metadata=requeue_metadata)
- coalesced_completion_ids = list(result.coalesced_completion_ids)
else:
raise ValueError(f"unknown task request type: {request.request_type}")
except asyncio.CancelledError:
@@ -5113,29 +5040,32 @@ class ScheduledTaskService:
settled_out_of_band = False
finally:
if should_complete:
- if coalesced_completion_ids:
- self.request_store.complete_coalesced(
- request,
- coalesced_completion_ids,
- ok=not error,
- error=error,
- )
- else:
- self.request_store.complete(
- request,
- ok=not error,
- error=error,
- task_id=task_id,
- session_key=session_key,
- session_id=session_id,
- # ``None`` for every ordinary completion, so the settlement
- # writer's metadata merge is a no-op exactly as before. Only
- # ``complete`` carries it: ``complete_coalesced`` settles
- # ``agent_run`` fan-outs, which reserve their own session per
- # run and so cannot reach the branch above.
- interrupt_reason=interrupt_reason,
- failure_code=failure_code,
- )
+ self.request_store.complete(
+ request,
+ ok=not error,
+ error=error,
+ task_id=task_id,
+ session_key=session_key,
+ session_id=session_id,
+ interrupt_reason=interrupt_reason,
+ failure_code=failure_code,
+ )
+ if reconcile_delivery_on_return and session_id:
+ manager = getattr(self.controller, "session_turns", None)
+ reconcile_delivery = getattr(
+ manager,
+ "reconcile_terminal_run_delivery",
+ None,
+ )
+ if callable(reconcile_delivery):
+ try:
+ await reconcile_delivery(request.id, session_id=session_id)
+ except Exception:
+ logger.exception(
+ "Failed to reconcile terminal task Delivery: run=%s session=%s",
+ request.id,
+ session_id,
+ )
if should_complete or settled_out_of_band:
# An out-of-band settlement still made this run terminal, so it owes
# the same callback follow-through as ``complete()``.
@@ -5173,6 +5103,8 @@ class ScheduledTaskService:
agent_id: Optional[str] = None,
) -> TaskExecutionResult:
error: Optional[str] = None
+ complete_on_return = True
+ reconcile_delivery_on_return = False
failure_code: Optional[str] = None
session_id = task.session_id
session_key = task.session_key
@@ -5193,7 +5125,7 @@ class ScheduledTaskService:
workdir=task.cwd,
)
session_key = ""
- error = await self._execute_request(
+ dispatch_result = await self._execute_request(
session_key=session_key,
session_id=session_id,
post_to=task.post_to,
@@ -5203,8 +5135,14 @@ class ScheduledTaskService:
task_id=task.id,
trigger_kind="scheduled",
agent_name=task.agent_name,
+ _capture_dispatch_result=True,
**({"agent_id": agent_id} if agent_id else {}),
)
+ if isinstance(dispatch_result, TaskDispatchResult):
+ error = dispatch_result.error
+ complete_on_return = dispatch_result.complete_on_return
+ else:
+ error = dispatch_result
except asyncio.CancelledError:
self.reconcile_jobs()
raise
@@ -5226,7 +5164,7 @@ class ScheduledTaskService:
session_id = binding_change.new_session_id
session_key = ""
try:
- error = await self._execute_request(
+ dispatch_result = await self._execute_request(
session_key=session_key,
session_id=session_id,
post_to=task.post_to,
@@ -5236,12 +5174,18 @@ class ScheduledTaskService:
task_id=task.id,
trigger_kind="scheduled",
agent_name=task.agent_name,
+ _capture_dispatch_result=True,
**(
{"agent_id": agent_id}
if agent_id and task.agent_name
else {}
),
)
+ if isinstance(dispatch_result, TaskDispatchResult):
+ error = dispatch_result.error
+ complete_on_return = dispatch_result.complete_on_return
+ else:
+ error = dispatch_result
except asyncio.CancelledError:
self.reconcile_jobs()
raise
@@ -5267,9 +5211,10 @@ class ScheduledTaskService:
# success, while an ``at`` task that was never disabled can fire again.
# Carried on the EXISTING error channel: a non-empty ``error`` is already
# what makes ``complete(ok=not error)`` record the run as failed and what
- # the CLI and the Harness detail pane show, so no new settlement path is
- # needed. A real failure keeps its own message; only a would-be success
- # gains one.
+ # the CLI and the Harness detail pane show. A real failure keeps its own
+ # message; only a would-be success gains one. If a durable Delivery owns
+ # the run, the caller reconciles that exact owner after the failed run
+ # write commits so the Turn cannot later replace it with success.
logger.warning(
"Scheduled task %s produced a result the store refused to stamp; "
"reporting the run as failed",
@@ -5277,6 +5222,8 @@ class ScheduledTaskService:
)
if not error:
error = _TASK_RESULT_NOT_RECORDED_ERROR
+ reconcile_delivery_on_return = not complete_on_return
+ complete_on_return = True
if binding_change is not None:
# ``execution_id`` IS the run row's id on every path that reaches here
# (``_execute_claimed_request`` passes ``request.id``), and this runs
@@ -5294,6 +5241,8 @@ class ScheduledTaskService:
session_key=session_key,
session_id=session_id,
failure_code=failure_code if error else None,
+ complete_on_return=complete_on_return,
+ reconcile_delivery_on_return=reconcile_delivery_on_return,
)
async def _execute_agent_run(
@@ -5379,24 +5328,6 @@ class ScheduledTaskService:
delivery_outcome=delivery_outcome,
)
if target.platform == "avibe" and session_id and gate is not None:
- stale_queue_rows = _retire_stale_agent_run_queue_rows(
- session_id=session_id,
- execution_ids=_live_coalesced_agent_run_ids(
- TaskExecutionRequest(
- id=execution_id,
- request_type="agent_run",
- metadata=metadata or {},
- )
- )
- or [execution_id],
- )
- if stale_queue_rows:
- try:
- from core.inbox_events import bus
-
- bus.publish("queue.updated", {"session_id": session_id})
- except Exception:
- logger.debug("agent_run recovery: queue.updated publish failed", exc_info=True)
if delivery_intent == AGENT_RUN_DELIVERY_SEND_NOW:
state = await gate.submit_scheduled(
session_id,
@@ -5438,7 +5369,7 @@ class ScheduledTaskService:
complete_on_return=False,
requeue_on_return=not (
isinstance(state, TurnSubmissionResult)
- and state.queue_owner_transferred
+ and state.delivery_owner_transferred
),
recover_queue_on_return=bool(
isinstance(state, TurnSubmissionResult)
@@ -5447,17 +5378,9 @@ class ScheduledTaskService:
delivery_outcome=delivery_outcome,
)
if route == "duplicate":
- live_ids = _live_coalesced_agent_run_ids(
- TaskExecutionRequest(
- id=execution_id,
- request_type="agent_run",
- metadata=metadata or {},
- )
- )
return AgentRunExecutionResult(
error=None,
complete_on_return=True,
- coalesced_completion_ids=tuple(live_ids or [execution_id]),
)
return AgentRunExecutionResult(
error=None,
@@ -5542,6 +5465,99 @@ class ScheduledTaskService:
if settled_any:
self._drain_dirty = True
+ def settle_agent_runs_from_terminal_turn(
+ self,
+ execution_ids: Sequence[str],
+ *,
+ turn_id: str,
+ outcome: str,
+ settled_by: str | None,
+ evidence_kind: str | None,
+ evidence: Mapping[str, Any],
+ ) -> None:
+ """Settle late accepted Runs from their immutable Turn snapshot."""
+
+ if settled_by in SETTLEMENTS_WITHOUT_RESULT:
+ self.settle_agent_runs_without_result(
+ execution_ids,
+ settled_by=str(settled_by),
+ )
+ return
+ if evidence.get("settles_run") is not True:
+ return
+ store = self.request_store.sqlite_backend
+ if store is None:
+ logger.warning(
+ "cannot settle late accepted Agent Runs for Turn=%s without SQLite",
+ turn_id,
+ )
+ return
+ terminal_status = {
+ "completed": "succeeded",
+ "failed": "failed",
+ "canceled": "canceled",
+ }.get(outcome)
+ if terminal_status is None:
+ return
+ result_text = str(evidence.get("result_text") or "")
+ terminal_error = evidence.get("terminal_error")
+ message_id = str(evidence.get("message_id") or "").strip() or None
+ output_provenance = evidence.get("output_provenance")
+ output_provenance = (
+ dict(output_provenance) if isinstance(output_provenance, Mapping) else {}
+ )
+ output_id = str(output_provenance.get("output_id") or "").strip()
+ if not output_id and output_provenance.get("sequence") is not None:
+ output_id = f"sequence:{output_provenance['sequence']}"
+ if not output_id:
+ output_id = "terminal"
+ registry = getattr(
+ getattr(getattr(self, "controller", None), "agent_service", None),
+ "activities",
+ None,
+ )
+ has_blocker = getattr(registry, "has_blocking_run_activity", None)
+ settled_any = False
+ for raw_execution_id in execution_ids:
+ execution_id = str(raw_execution_id or "").strip()
+ if not execution_id:
+ continue
+ run_terminal_status = terminal_status
+ if callable(has_blocker) and has_blocker(execution_id):
+ if not store.defer_run_terminal(
+ execution_id,
+ terminal_status=terminal_status,
+ result_text=result_text,
+ error=(
+ str(terminal_error) if terminal_error is not None else None
+ ),
+ ):
+ logger.warning(
+ "failed to defer late terminal settlement for Run=%s Turn=%s",
+ execution_id,
+ turn_id,
+ )
+ run_terminal_status = None
+ result = store.record_run_output(
+ execution_id,
+ output_id=output_id,
+ text=result_text,
+ message_id=message_id,
+ provenance={
+ **output_provenance,
+ "turn_id": turn_id,
+ "evidence_kind": evidence_kind,
+ "settled_by": settled_by,
+ },
+ terminal_status=run_terminal_status,
+ error=str(terminal_error) if terminal_error is not None else None,
+ )
+ settled_any = settled_any or bool(
+ result.get("terminal_transition") or result.get("text_backfilled")
+ )
+ if settled_any:
+ self._drain_dirty = True
+
def _settle_agent_run_without_result(
self,
execution_id: str,
@@ -6532,7 +6548,8 @@ class ScheduledTaskService:
session_id: Optional[str] = None,
agent_name: Optional[str] = None,
agent_id: Optional[str] = None,
- ) -> Optional[str]:
+ _capture_dispatch_result: bool = False,
+ ) -> Optional[str] | TaskDispatchResult:
target_info = resolve_session_id_target(session_id) if session_id else None
target = target_info.session_key if target_info else parse_session_key(session_key or "")
delivery_target = self._resolve_delivery_target(
@@ -6569,13 +6586,24 @@ class ScheduledTaskService:
# the direct ``handle_scheduled_message`` path byte-for-byte.
gate = getattr(self.controller, "session_turn_gate", None)
if target.platform == "avibe" and session_id and gate is not None:
- await gate.submit_scheduled(session_id, context, prompt)
- return None
- return await self.controller.message_handler.handle_scheduled_message(
+ from core.session_turns import TurnSubmissionResult
+
+ submission = await gate.submit_scheduled(session_id, context, prompt)
+ if isinstance(submission, TurnSubmissionResult):
+ result = TaskDispatchResult(
+ error=None,
+ complete_on_return=not submission.delivery_owner_transferred,
+ )
+ return result if _capture_dispatch_result else result.error
+ result = TaskDispatchResult(error=None)
+ return result if _capture_dispatch_result else result.error
+ error = await self.controller.message_handler.handle_scheduled_message(
context=context,
message=prompt,
parsed_session_key=target,
)
+ result = TaskDispatchResult(error=error)
+ return result if _capture_dispatch_result else result.error
async def _build_context(
self,
@@ -6657,7 +6685,6 @@ class ScheduledTaskService:
"source_actor": (metadata or {}).get("source_actor"),
"parent_run_id": (metadata or {}).get("parent_run_id"),
"callback_session_id": (metadata or {}).get("callback_session_id"),
- "coalesced_queue": (metadata or {}).get("coalesced_queue"),
"suppress_delivery": bool(target_info.suppress_delivery) if target_info else False,
"agent_session_target": (
{
diff --git a/core/services/agent_steering.py b/core/services/agent_steering.py
index f2c069f4a..1dfee83b2 100644
--- a/core/services/agent_steering.py
+++ b/core/services/agent_steering.py
@@ -31,6 +31,17 @@ class SteerRequest:
expected_logical_turn_id: str
expected_native_turn_id: str
text: str
+ attempt_id: str = ""
+
+
+@dataclass(frozen=True)
+class SteerReconcileRequest:
+ """One read-only query for exact evidence about a prior steer attempt."""
+
+ target_session_id: str
+ expected_logical_turn_id: str
+ expected_native_turn_id: str
+ attempt_id: str
@dataclass(frozen=True)
@@ -212,3 +223,38 @@ async def steer_active_turn(
if not isinstance(receipt, SteerResult):
return result(SteerOutcome.UNKNOWN, reason="invalid_adapter_receipt", backend=backend)
return receipt
+
+
+async def reconcile_steer_attempt(
+ controller: Any,
+ backend: str,
+ request: SteerReconcileRequest,
+) -> SteerResult:
+ """Read exact backend evidence without repeating the native write."""
+
+ targets = [
+ target
+ for target in _active_targets(controller, backend, request.target_session_id)
+ if target.logical_turn_id == request.expected_logical_turn_id
+ ]
+ if len(targets) != 1:
+ return result(
+ SteerOutcome.UNKNOWN,
+ reason="reconciliation_target_unavailable",
+ backend=backend,
+ )
+ reconcile = getattr(targets[0].agent, "reconcile_steer_attempt", None)
+ if not callable(reconcile):
+ return result(
+ SteerOutcome.UNKNOWN,
+ reason="reconciliation_unsupported",
+ backend=backend,
+ )
+ receipt = await reconcile(request, targets[0])
+ if not isinstance(receipt, SteerResult):
+ return result(
+ SteerOutcome.UNKNOWN,
+ reason="invalid_reconciliation_receipt",
+ backend=backend,
+ )
+ return receipt
diff --git a/core/services/dispatch.py b/core/services/dispatch.py
index 71959ce6c..f3a8876ff 100644
--- a/core/services/dispatch.py
+++ b/core/services/dispatch.py
@@ -36,6 +36,7 @@ from core.run_settlement import (
SETTLED_BY_NO_TERMINAL_RESULT,
SETTLED_BY_REFUSED_CONCURRENT_TURN,
)
+from core.native_dispatch_phase import backend_dispatch_attempted
from modules.im import MessageContext
if TYPE_CHECKING: # pragma: no cover - typing-only
@@ -70,6 +71,7 @@ class TurnDispatchOutcome:
error: Optional[str]
settled_by: Optional[str]
+ backend_dispatch_attempted: Optional[bool] = None
async def dispatch_turn(
@@ -79,6 +81,7 @@ async def dispatch_turn(
*,
source: str = SOURCE_HUMAN,
on_chunk: Optional[ChunkCallback] = None,
+ logical_turn_id: str | None = None,
) -> Optional[str]:
"""Run one agent turn for ``context`` and return the primary message id.
@@ -92,6 +95,7 @@ async def dispatch_turn(
text,
source=source,
on_chunk=on_chunk,
+ logical_turn_id=logical_turn_id,
)
return outcome.error
@@ -103,6 +107,7 @@ async def dispatch_turn_with_outcome(
*,
source: str = SOURCE_HUMAN,
on_chunk: Optional[ChunkCallback] = None,
+ logical_turn_id: str | None = None,
) -> TurnDispatchOutcome:
"""Run one agent turn for ``context`` and report how its waiter was released.
@@ -130,7 +135,11 @@ async def dispatch_turn_with_outcome(
if on_chunk is None:
# IM / CLI: fire-and-forget; no live stream to hold open.
- return TurnDispatchOutcome(error=await _run(), settled_by=None)
+ return TurnDispatchOutcome(
+ error=await _run(),
+ settled_by=None,
+ backend_dispatch_attempted=backend_dispatch_attempted(context),
+ )
session_key = controller._get_session_key(context)
if controller.get_turn_sink(session_key) is not None:
@@ -146,14 +155,25 @@ async def dispatch_turn_with_outcome(
# settlement — report it directly. A caller holding a durable record (an
# ``agent_runs`` row) must settle it: this turn never reached a backend, so
# no terminal result will ever arrive for it.
- return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_REFUSED_CONCURRENT_TURN)
+ return TurnDispatchOutcome(
+ error=None,
+ settled_by=SETTLED_BY_REFUSED_CONCURRENT_TURN,
+ backend_dispatch_attempted=False,
+ )
# Tag this turn with a unique token, stamped into the context the agent
# receiver will carry. ``_stream_chunk`` only forwards an emit to the sink
# when the emit's context token matches the registered sink's token, so a
# late straggler emit from a PREVIOUS (stopped / timed-out) turn can't
# cross-feed into this turn's live stream or prematurely complete it.
# Fail-open: emits without a token still flow (byte-identical to before).
- turn_token = uuid.uuid4().hex
+ existing_turn_token = str(
+ (context.platform_specific or {}).get("turn_token") or ""
+ ).strip()
+ turn_token = (
+ str(logical_turn_id or "").strip()
+ or existing_turn_token
+ or uuid.uuid4().hex
+ )
if context.platform_specific is None:
context.platform_specific = {}
context.platform_specific["turn_token"] = turn_token
@@ -181,7 +201,11 @@ async def dispatch_turn_with_outcome(
settled_by = SETTLED_BY_NO_TERMINAL_RESULT
if isinstance(sink, dict) and sink.get("done_event") is done:
settled_by = str(sink.get("settled_by") or SETTLED_BY_NO_TERMINAL_RESULT)
- return TurnDispatchOutcome(error=result, settled_by=settled_by)
+ return TurnDispatchOutcome(
+ error=result,
+ settled_by=settled_by,
+ backend_dispatch_attempted=backend_dispatch_attempted(context),
+ )
finally:
# Pass our own done event so a turn that was superseded by a newer
# concurrent turn doesn't evict the newer turn's sink on cleanup.
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index 9330c64b1..f2f86c147 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import json
import secrets
from dataclasses import dataclass
+from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
@@ -20,9 +21,8 @@ from vibe.message_identity import INPUT_TURN_AUTHOR_TYPES, is_input_turn
from vibe.message_types import spec_for, types_with
TRIM_LATEST_RUNNING_TURN_BACKENDS = {"codex", "opencode"}
-# ``silent`` is the invisible completion marker (messages_service.SILENT_TYPE): a turn
-# that finished with no user-visible reply is still TERMINAL, so a fork created after
-# it must not trim/roll back the completed turn as if it were still running.
+# Turn settlement is read from ``session_turns`` below, so a reply-less completion
+# cannot be mistaken for a still-running input.
TERMINAL_AGENT_OUTPUT_TYPES = {
message_type
for message_type in types_with("activityRole")
@@ -135,10 +135,11 @@ class SourceMessageAnchor:
message_id: Optional[str] = None
author: Optional[str] = None
message_type: Optional[str] = None
+ running_turn: bool = False
@property
def is_running_input_turn(self) -> bool:
- return is_input_turn(self.author, self.message_type)
+ return self.running_turn or is_input_turn(self.author, self.message_type)
def reserve_forked_session(
@@ -638,6 +639,26 @@ def _clean_optional(value: Any) -> Optional[str]:
return text or None
+def _parse_utc_timestamp(value: Any) -> datetime | None:
+ try:
+ parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
+ except (TypeError, ValueError):
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed.astimezone(timezone.utc)
+
+
+def _emitted_micros(row_id: Any, timestamp: datetime) -> int:
+ identity = str(row_id or "")
+ if len(identity) >= 19 and identity[3] == "_":
+ try:
+ return int(identity[4:19], 16)
+ except ValueError:
+ pass
+ return int(timestamp.timestamp() * 1_000_000)
+
+
def _forked_session_title(source_title: str, lang: str = "en") -> str:
return t("fork.title", lang, title=source_title) if source_title else t("fork.titleUntitled", lang)
@@ -645,27 +666,121 @@ def _forked_session_title(source_title: str, lang: str = "en") -> str:
def _latest_source_message_anchor(conn: Any, source_session_id: str) -> SourceMessageAnchor:
from sqlalchemy import select
- from storage.models import messages
+ from storage.models import agent_events, message_deliveries, messages, session_turns
+
+ active_initial = conn.execute(
+ select(
+ messages.c.id,
+ messages.c.author,
+ messages.c.type,
+ message_deliveries.c.state.label("delivery_state"),
+ )
+ .select_from(
+ session_turns.join(
+ message_deliveries,
+ message_deliveries.c.id == session_turns.c.initial_delivery_id,
+ ).outerjoin(
+ messages,
+ messages.c.id == message_deliveries.c.message_id,
+ )
+ )
+ .where(
+ session_turns.c.session_id == source_session_id,
+ session_turns.c.state.in_(("starting", "active")),
+ )
+ .order_by(session_turns.c.created_at.desc(), session_turns.c.id.desc())
+ .limit(1)
+ ).mappings().first()
+ if active_initial is not None and active_initial["id"] is not None:
+ return SourceMessageAnchor(
+ message_id=str(active_initial["id"]),
+ author=str(active_initial["author"] or "").strip() or None,
+ message_type=str(active_initial["type"] or "").strip() or None,
+ )
+ pre_materialized_start = bool(
+ active_initial is not None
+ and active_initial["delivery_state"] == "claimed"
+ )
row = conn.execute(
- select(messages.c.id, messages.c.author, messages.c.type)
+ select(messages.c.id, messages.c.author, messages.c.type, messages.c.created_at)
.where(
messages.c.session_id == source_session_id,
- # Include the invisible ``silent`` completion marker so a turn that
- # finished silently is the anchor (a terminal, NOT a running input),
- # otherwise the anchor falls back to the input row and the fork treats
- # the completed turn as still running and trims/rolls it back.
messages.c.type.in_(_FORK_ANCHOR_TYPES),
)
.order_by(messages.c.created_at.desc(), messages.c.id.desc())
.limit(1)
).mappings().first()
if row is None:
- return SourceMessageAnchor()
+ return SourceMessageAnchor(running_turn=pre_materialized_start)
+ latest_turn = conn.execute(
+ select(
+ session_turns.c.state,
+ session_turns.c.terminal_outcome,
+ session_turns.c.terminal_at,
+ )
+ .where(session_turns.c.session_id == source_session_id)
+ .where(
+ session_turns.c.terminal_outcome.is_(None)
+ | (session_turns.c.terminal_outcome != "not_written")
+ )
+ .order_by(session_turns.c.created_at.desc(), session_turns.c.id.desc())
+ .limit(1)
+ ).mappings().first()
+ silent_terminal = conn.execute(
+ select(
+ agent_events.c.id,
+ agent_events.c.created_at,
+ agent_events.c.metadata_json,
+ )
+ .where(
+ agent_events.c.session_id == source_session_id,
+ agent_events.c.event_type == "silent_terminal",
+ )
+ .order_by(agent_events.c.created_at.desc(), agent_events.c.id.desc())
+ .limit(1)
+ ).mappings().first()
+ terminal_candidates: list[tuple[int, str]] = []
+ if latest_turn is not None and latest_turn["state"] == "terminal":
+ terminal_at = _parse_utc_timestamp(latest_turn["terminal_at"])
+ if terminal_at is not None:
+ terminal_candidates.append(
+ (
+ int(terminal_at.timestamp() * 1_000_000),
+ str(latest_turn["terminal_outcome"] or "completed"),
+ )
+ )
+ if silent_terminal is not None:
+ terminal_at = _parse_utc_timestamp(silent_terminal["created_at"])
+ if terminal_at is not None:
+ metadata = _load_metadata(silent_terminal["metadata_json"])
+ event_id = metadata.get("legacy_message_id") or silent_terminal["id"]
+ terminal_candidates.append(
+ (
+ _emitted_micros(event_id, terminal_at),
+ str(metadata.get("terminal_outcome") or "completed"),
+ )
+ )
+ message_at = _parse_utc_timestamp(row["created_at"])
+ latest_terminal = max(terminal_candidates, default=None)
+ if (
+ message_at is not None
+ and latest_terminal is not None
+ and latest_terminal[0] >= _emitted_micros(row["id"], message_at)
+ ):
+ return SourceMessageAnchor(
+ message_id=str(row["id"]) if row["id"] else None,
+ author="agent",
+ message_type=(
+ "error" if latest_terminal[1] == "failed" else "result"
+ ),
+ running_turn=pre_materialized_start,
+ )
return SourceMessageAnchor(
message_id=str(row["id"]) if row["id"] else None,
author=str(row["author"] or "").strip() or None,
message_type=str(row["type"] or "").strip() or None,
+ running_turn=pre_materialized_start,
)
diff --git a/core/services/sessions.py b/core/services/sessions.py
index 54f6f6399..97d0ed373 100644
--- a/core/services/sessions.py
+++ b/core/services/sessions.py
@@ -50,7 +50,6 @@ from storage.workbench_sessions_service import (
is_session_archived,
list_sessions,
list_sessions_page,
- reset_running_agent_status,
require_enabled_agent_backend,
require_enabled_agent_identity,
set_agent_status,
@@ -74,7 +73,6 @@ __all__ = [
"is_session_archived",
"list_sessions",
"list_sessions_page",
- "reset_running_agent_status",
"set_agent_status",
"session_archived_message",
"touch_session",
diff --git a/core/session_turns.py b/core/session_turns.py
index bcb0ca037..b20541089 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -6,12 +6,10 @@ and restore paths stop reconciling several separate stores. A session has **at
most one active turn** (IDLE ↔ RUNNING; no turn-duration timeout — a long agent
runs until it emits its terminal result or the user Stops it).
-``SessionTurnManager`` is wired as ``controller.session_turns`` by
-``core.internal_server.create_app``. It owns the in_flight registry + the
-flush-intent sets, and the turn lifecycle: ``submit`` (start + hold-open) and
-``flush_queue`` (drain the send-while-busy queue). The internal-server HTTP
-handlers and the scheduler are thin callers. Cancel / send-now / turn-state /
-terminal-result move onto the manager in subsequent commits.
+``SessionTurnManager`` is wired as ``controller.session_turns``. It is the sole
+orchestrator of durable Delivery admission, Turn execution/control, terminal
+settlement, and Session backlog policy. Process-local registries project those
+owners for live tasks and streaming only.
"""
from __future__ import annotations
@@ -19,7 +17,8 @@ from __future__ import annotations
import asyncio
import json
import logging
-from dataclasses import dataclass
+import uuid
+from dataclasses import dataclass, replace
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Callable, Literal, Optional
@@ -28,18 +27,36 @@ from sqlalchemy.engine import Connection, Engine
from sqlalchemy.exc import IntegrityError
from core.web_push_notifications import WEB_PUSH_USER_KEY_METADATA, WEB_PUSH_USER_KEYS_METADATA
+from core.native_dispatch_phase import backend_dispatch_attempted
from core.run_settlement import (
SETTLEMENTS_WITHOUT_RESULT,
SETTLED_BY_BACKEND_REFRESH,
SETTLED_BY_NO_TERMINAL_RESULT,
+ SETTLED_BY_REFUSED_CONCURRENT_TURN,
SETTLED_BY_STOPPED,
SETTLED_BY_TERMINAL_RESULT,
)
from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn_with_outcome
+from core.services.agent_steering import (
+ SteerOutcome,
+ SteerReconcileRequest,
+ SteerRequest,
+ active_steer_identity,
+ reconcile_steer_attempt,
+ result as steer_result,
+ steer_active_turn,
+)
from storage import messages_service
+from storage import message_deliveries as delivery_store
+from storage.agent_session_rows import reserve_write_lock
from storage.db import get_cached_sqlite_engine
from storage.background import normalize_run_status
-from storage.models import agent_runs, messages
+from storage.models import (
+ agent_runs,
+ agent_sessions,
+ message_deliveries as delivery_rows,
+ session_turns as session_turn_rows,
+)
from storage.workbench_sessions_service import derive_session_harness_activities
from core.message_output import terminal_turn_output
from vibe.i18n import t as i18n_t
@@ -54,6 +71,13 @@ def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
+def _turn_event_payload(session_id: str, turn_id: str | None = None) -> dict[str, str]:
+ payload = {"session_id": session_id}
+ if turn_id:
+ payload["turn_id"] = turn_id
+ return payload
+
+
def _as_backend_activity_item(item: dict[str, Any]) -> dict[str, Any]:
"""Annotate a registry background activity with the unified banner fields.
@@ -75,12 +99,12 @@ def _as_backend_activity_item(item: dict[str, Any]) -> dict[str, Any]:
# a plain human turn (#84). Its PRESENCE also marks the row as a scheduled segment
# (vs a user send) for flush_queue.
SCHEDULED_PROVENANCE_KEY = "scheduled_provenance"
-QUEUED_DISPATCH_TEXT_KEY = messages_service.QUEUED_DISPATCH_TEXT_KEY
SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS = 60
SCHEDULED_QUEUE_BURST_HINT_THRESHOLD = 3
SCHEDULED_QUEUE_FULL_DETAIL_LIMIT = 3
_SHOW_CHECKPOINT_DEFERRED_START_KEY = "_avibe_show_git_deferred_start"
_SHOW_CHECKPOINT_TERMINAL_PENDING_KEY = "_avibe_show_git_terminal_pending"
+_TERMINAL_RESULT_LATCH_KEY = "_avibe_terminal_result_latch"
# The platform_specific keys the FLUSH rebuilds fresh from the session row (avibe
# routing). Everything ELSE the scheduled context carries is delivery / attribution
@@ -91,46 +115,63 @@ _SHOW_CHECKPOINT_TERMINAL_PENDING_KEY = "_avibe_show_git_terminal_pending"
_FLUSH_REBUILT_KEYS = frozenset(
{"platform", "is_dm", "workbench_session_id", "agent_session_id", "agent_session_target", "turn_token"}
)
+_EXECUTION_ROUTING_KEYS = _FLUSH_REBUILT_KEYS | frozenset(
+ {
+ "vibe_agent_id",
+ "vibe_agent_name",
+ "scheduled_target_agent_name",
+ "resolved_vibe_agent",
+ }
+)
SCHEDULED_TARGET_AGENT_KEY = "scheduled_target_agent_name"
+_NON_RESTORABLE_RUNTIME_BACKENDS = frozenset({"claude", "codex"})
+_MAX_AUTOMATIC_UNKNOWN_START_REPLAYS = 1
+_UNKNOWN_START_REPLAY_INSTRUCTION = (
+ "[Avibe recovery: this request may have been delivered before restart. "
+ "Before any irreversible action, check whether the work is already complete.]\n\n"
+)
-def queue_pending_user_message(conn: Connection, message_id: str, dispatch_text: str) -> bool:
- """Move a reserved input row into the queue.
- Queue rows keep user-visible transcript text in ``content_text``. The prompt
- submitted by an entry point may be richer (attachment paths, Show event IDs,
- reply guidance), so store that separately for ``flush_queue`` to replay.
- This runs only from ``SessionTurnManager.submit``'s enqueue callback.
- """
- queueable_types = (messages_service.PENDING_TYPE,)
- raw_metadata = conn.execute(
- select(messages.c.metadata_json).where(
- messages.c.id == message_id,
- messages.c.type.in_(queueable_types),
- )
- ).scalar_one_or_none()
- if raw_metadata is None:
- return False
- try:
- metadata = json.loads(raw_metadata or "{}")
- except (TypeError, json.JSONDecodeError):
- metadata = {}
- if not isinstance(metadata, dict):
- metadata = {}
- metadata[QUEUED_DISPATCH_TEXT_KEY] = dispatch_text
- result = conn.execute(
- update(messages)
- .where(
- messages.c.id == message_id,
- messages.c.type.in_(queueable_types),
- )
- .values(
- type=messages_service.QUEUED_TYPE,
- metadata_json=json.dumps(metadata),
- updated_at=_utc_now_iso(),
+def _start_replay_count(deliveries: list[dict[str, Any]]) -> int:
+ counts: list[int] = []
+ for delivery in deliveries:
+ try:
+ history = json.loads(str(delivery.get("delivery_history_json") or "{}"))
+ except (TypeError, ValueError, json.JSONDecodeError):
+ history = {}
+ events = history.get("events") if isinstance(history, dict) else None
+ counts.append(
+ sum(
+ 1
+ for event in events or []
+ if isinstance(event, dict)
+ and event.get("kind") == "start"
+ and event.get("outcome") == "restart_replayed"
+ )
)
+ return max(counts, default=0)
+
+
+def _opencode_native_session_id(native_turn_id: str | None) -> str | None:
+ value = str(native_turn_id or "").strip()
+ if not value.startswith("opencode:"):
+ return None
+ native_session_id, separator, generation = value[len("opencode:") :].rpartition(":")
+ if not separator or not native_session_id or not generation:
+ return None
+ return native_session_id
+
+
+def _same_opencode_native_session(
+ persisted_native_turn_id: str | None,
+ restored_native_turn_id: str | None,
+) -> bool:
+ persisted_session = _opencode_native_session_id(persisted_native_turn_id)
+ return bool(
+ persisted_session
+ and persisted_session == _opencode_native_session_id(restored_native_turn_id)
)
- return bool(result.rowcount)
def capture_scheduled_provenance(context: "MessageContext") -> dict:
@@ -159,29 +200,6 @@ def capture_scheduled_provenance(context: "MessageContext") -> dict:
}
-def emit_matches_active_turn(sink: dict, context: "MessageContext") -> bool:
- """The ONE active-turn token rule (FSM Phase 2 — collapses the three previously
- duplicated guards: ``_stream_chunk`` completion, ``_is_active_turn``, and
- ``Controller.mark_turn_complete``).
-
- A live sink WITH a token means an interactive turn is in flight; only its OWN
- result (matching token) is the active turn's. A result whose token DIFFERS or is
- ABSENT is stale — a superseded / stopped / older turn, or a scheduled / watch run
- that carries no token — and must NOT complete the turn (set ``done_event``) or
- settle its dot. Fail-open when the sink itself is tokenless, so non-streaming
- turns still settle. (Chunk FORWARDING is deliberately NOT gated — see
- ``_stream_chunk``; only COMPLETION + dot-settle are.)
-
- NOTE (no-timeout invariant): with the turn-duration timeout gone, a turn whose
- OWN terminal result is tokenless would hang here forever. The FSM therefore must
- guarantee every terminal result carries the active turn's token (Claude adoption
- / FSM-attached token); this guard is intentionally strict.
- """
- sink_token = sink.get("turn_token")
- ctx_token = (getattr(context, "platform_specific", None) or {}).get("turn_token")
- return not (sink_token is not None and ctx_token != sink_token)
-
-
def _parse_queue_timestamp(value: Any) -> Optional[datetime]:
if not value:
return None
@@ -197,39 +215,17 @@ def _parse_queue_timestamp(value: Any) -> Optional[datetime]:
return parsed.astimezone(timezone.utc)
-def _run_metadata_holds_workbench_queue(value: Any) -> bool:
- try:
- metadata = json.loads(value or "{}")
- except (TypeError, ValueError):
- return False
- return bool(
- isinstance(metadata, dict)
- and metadata.get("workbench_queue_holds_run") is True
- )
-
-
-def _scheduled_provenance(row: dict) -> Optional[dict]:
+def _scheduled_provenance(row: dict[str, Any]) -> Optional[dict[str, Any]]:
metadata = row.get("metadata") or {}
provenance = metadata.get(SCHEDULED_PROVENANCE_KEY)
return provenance if isinstance(provenance, dict) else None
-def _agent_run_merge_definition_id(spec: dict) -> str:
- """Return the coalescing bucket for direct Agent Run queue rows.
-
- Callback-backed runs can deliver results into different caller sessions, so
- keep those rows isolated by execution id. Plain CLI/direct runs may coalesce,
- and their prompt builder always includes every queued message verbatim.
- """
- execution_id = str(spec.get("task_execution_id") or "").strip()
- if "source_kind" not in spec and "callback_session_id" not in spec:
- return f"agent_run:{execution_id}" if execution_id else ""
- if spec.get("callback_session_id") or spec.get("source_kind") == "callback":
- return f"agent_run:{execution_id}" if execution_id else ""
+def _agent_run_merge_definition_id(spec: dict[str, Any]) -> str:
return "agent_run"
-def _scheduled_merge_key(row: dict) -> Optional[tuple[str, ...]]:
+def _scheduled_merge_key(row: dict[str, Any]) -> Optional[tuple[str, ...]]:
provenance = _scheduled_provenance(row)
if provenance is None:
return None
@@ -242,21 +238,27 @@ def _scheduled_merge_key(row: dict) -> Optional[tuple[str, ...]]:
definition_id = _agent_run_merge_definition_id(spec)
if not trigger_kind or not definition_id:
return None
- delivery_override = spec.get("delivery_override") if isinstance(spec.get("delivery_override"), dict) else {}
- delivery_alias = spec.get("scheduled_delivery_alias") if isinstance(spec.get("scheduled_delivery_alias"), dict) else {}
+ delivery_override = (
+ spec.get("delivery_override")
+ if isinstance(spec.get("delivery_override"), dict)
+ else {}
+ )
+ delivery_alias = (
+ spec.get("scheduled_delivery_alias")
+ if isinstance(spec.get("scheduled_delivery_alias"), dict)
+ else {}
+ )
+ stable_agent_key = str(spec.get("vibe_agent_id") or "").strip()
+ if not stable_agent_key:
+ stable_agent_key = str(
+ spec.get("vibe_agent_name")
+ or spec.get(SCHEDULED_TARGET_AGENT_KEY)
+ or ""
+ )
return (
trigger_kind,
definition_id,
- str(spec.get("agent_session_id") or ""),
- str(spec.get("vibe_agent_name") or ""),
- str(spec.get(SCHEDULED_TARGET_AGENT_KEY) or ""),
- str((spec.get("agent_session_target") or {}).get("agent_name") or "")
- if isinstance(spec.get("agent_session_target"), dict)
- else "",
- str(spec.get("callback_session_id") or ""),
- str(spec.get("source_kind") or ""),
- str(spec.get("source_actor") or ""),
- str(spec.get("parent_run_id") or ""),
+ stable_agent_key,
str(spec.get("delivery_key_external") or ""),
str(spec.get("delivery_scope_session_key") or ""),
str(delivery_override.get("platform") or ""),
@@ -269,39 +271,41 @@ def _scheduled_merge_key(row: dict) -> Optional[tuple[str, ...]]:
)
-def _within_scheduled_merge_window(previous: dict, current: dict) -> bool:
- prev_ts = _parse_queue_timestamp(previous.get("created_at"))
- current_ts = _parse_queue_timestamp(current.get("created_at"))
- if prev_ts is None or current_ts is None:
- return False
- delta = (current_ts - prev_ts).total_seconds()
- return 0 <= delta <= SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS
-
+def _collect_delivery_segment(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Return the one compatible leading segment a Turn may claim."""
-def _collect_scheduled_segment(rows: list[dict]) -> list[dict]:
if not rows:
return []
- first_key = _scheduled_merge_key(rows[0])
- if first_key is None:
+ message_identity = delivery_store.message_merge_identity(rows[0])
+ scheduled_key = _scheduled_merge_key(rows[0])
+ if _scheduled_provenance(rows[0]) is not None and scheduled_key is None:
return [rows[0]]
- segment = [rows[0]]
- latest = rows[0]
- for row in rows[1:]:
- if _scheduled_merge_key(row) != first_key:
- break
- if not _within_scheduled_merge_window(latest, row):
- break
- segment.append(row)
- latest = row
- return segment
-
-
-def _collect_user_segment(rows: list[dict]) -> list[dict]:
- """Collect one user turn without coalescing durable message identities."""
- segment: list[dict] = []
+ if scheduled_key is not None:
+ segment = [rows[0]]
+ latest = rows[0]
+ for row in rows[1:]:
+ previous = _parse_queue_timestamp(latest.get("submitted_at"))
+ current = _parse_queue_timestamp(row.get("submitted_at"))
+ if (
+ delivery_store.message_merge_identity(row) != message_identity
+ or _scheduled_merge_key(row) != scheduled_key
+ or previous is None
+ or current is None
+ ):
+ break
+ delta = (current - previous).total_seconds()
+ if delta < 0 or delta > SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS:
+ break
+ segment.append(row)
+ latest = row
+ return segment
+
+ segment: list[dict[str, Any]] = []
for row in rows:
if _scheduled_provenance(row) is not None:
break
+ if delivery_store.message_merge_identity(row) != message_identity:
+ break
native_message_id = str(row.get("native_message_id") or "").strip()
if native_message_id:
if not segment:
@@ -311,379 +315,34 @@ def _collect_user_segment(rows: list[dict]) -> list[dict]:
return segment
-def _build_scheduled_segment_text(segment: list[dict]) -> str:
- texts = [str(row.get("text") or "") for row in segment if str(row.get("text") or "")]
- if not texts:
- return ""
- if len(texts) == 1:
- return texts[0]
-
- if _scheduled_segment_trigger_kind(segment) == "agent_run":
- return "\n\n---\n\n".join(texts)
-
- lang = _scheduled_segment_language(segment)
- parts = [
- texts[0],
- "\n\n"
- + i18n_t(
- "harness.queueCoalesced.summary",
- lang,
- count=len(texts),
- window=SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS,
- ),
- ]
- if len(texts) <= SCHEDULED_QUEUE_FULL_DETAIL_LIMIT:
- parts.append(
- "\n\n"
- + i18n_t("harness.queueCoalesced.messagesLabel", lang)
- + "\n"
- + "\n\n---\n\n".join(texts[1:])
- )
- else:
- parts.append(
- "\n\n"
- + i18n_t("harness.queueCoalesced.latestLabel", lang, additional=len(texts) - 1)
- + f"\n{texts[-1]}"
- )
- if len(texts) >= SCHEDULED_QUEUE_BURST_HINT_THRESHOLD:
- parts.append("\n\n" + i18n_t("harness.queueCoalesced.burstHint", lang))
- return "".join(parts)
-
-
-def _scheduled_segment_trigger_kind(segment: list[dict]) -> str:
- spec = (_scheduled_provenance(segment[0]) or {}).get("platform_specific") or {} if segment else {}
- return str(spec.get("task_trigger_kind") or "").strip() if isinstance(spec, dict) else ""
+def _segment_dispatch_text(segment: list[dict[str, Any]]) -> str:
+ texts = [str(row.get("dispatch_text") or "") for row in segment]
+ texts = [text for text in texts if text.strip()]
+ scheduled = bool(segment and _scheduled_merge_key(segment[0]) is not None)
+ return ("\n\n---\n\n" if scheduled else "\n").join(texts)
-def _scheduled_segment_language(segment: list[dict]) -> str:
- for row in segment:
- spec = (_scheduled_provenance(row) or {}).get("platform_specific") or {}
- if not isinstance(spec, dict):
- continue
- lang = str(spec.get("language") or spec.get("lang") or "").strip()
- if lang:
- return lang
- return "en"
-
-
-def _scheduled_segment_native_ids(segment: list[dict]) -> list[str]:
- native_ids: list[str] = []
- for row in segment:
- native_id = str(row.get("native_message_id") or "").strip()
- if not native_id:
- native_id = str((_scheduled_provenance(row) or {}).get("message_id") or "").strip()
- if native_id and native_id not in native_ids:
- native_ids.append(native_id)
- return native_ids
-
-
-def _scheduled_segment_execution_id(row: dict) -> str:
- spec = (_scheduled_provenance(row) or {}).get("platform_specific") or {}
- if not isinstance(spec, dict):
- return ""
- return str(spec.get("task_execution_id") or "").strip()
-
-
-def _scheduled_row_execution_ids(row: dict) -> list[str]:
- execution_ids: list[str] = []
- execution_id = _scheduled_segment_execution_id(row)
- if execution_id:
- execution_ids.append(execution_id)
- spec = (_scheduled_provenance(row) or {}).get("platform_specific") or {}
- coalesced = spec.get("coalesced_queue") if isinstance(spec, dict) else None
- coalesced_ids = coalesced.get("execution_ids") if isinstance(coalesced, dict) else None
- if isinstance(coalesced_ids, list):
- for value in coalesced_ids:
- coalesced_id = str(value or "").strip()
- if coalesced_id and coalesced_id not in execution_ids:
- execution_ids.append(coalesced_id)
- return execution_ids
-
-
-def _scheduled_segment_execution_ids(segment: list[dict]) -> list[str]:
- execution_ids: list[str] = []
- for row in segment:
- for execution_id in _scheduled_row_execution_ids(row):
- if execution_id not in execution_ids:
- execution_ids.append(execution_id)
- return execution_ids
-
-
-def _scheduled_segment_rows_for_execution_ids(segment: list[dict], execution_ids: set[str]) -> list[dict]:
- return [row for row in segment if set(_scheduled_row_execution_ids(row)) & execution_ids]
-
-
-def _scheduled_segment_stale_row_ids(segment: list[dict], queued_ids: set[str]) -> list[str]:
- row_ids: list[str] = []
- for row in segment:
- row_id = row.get("id")
- if not row_id:
- continue
- represented = set(_scheduled_row_execution_ids(row))
- if represented and not (represented & queued_ids):
- row_ids.append(row_id)
- return row_ids
-
-
-def _filter_coalesced_agent_run_provenance(provenance: dict, execution_ids: list[str]) -> dict:
- if not execution_ids:
- return provenance
- execution_set = set(execution_ids)
- coalesced = provenance.get("coalesced_queue")
- if not isinstance(coalesced, dict):
- return provenance
- filtered = dict(coalesced)
- raw_ids = coalesced.get("execution_ids")
- if isinstance(raw_ids, list):
- filtered["execution_ids"] = [
- str(value)
- for value in raw_ids
- if str(value or "").strip() in execution_set
- ]
- raw_messages = coalesced.get("messages")
- if isinstance(raw_messages, list):
- messages = [
- item
- for item in raw_messages
- if isinstance(item, dict)
- and str(item.get("execution_id") or "").strip() in execution_set
- ]
- filtered["messages"] = messages
- prompt_parts = [
- str(item.get("message") or item.get("prompt") or "")
- for item in messages
- if str(item.get("message") or item.get("prompt") or "")
- ]
- if prompt_parts:
- filtered["prompt"] = "\n\n---\n\n".join(prompt_parts)
- else:
- filtered.pop("prompt", None)
- result = dict(provenance)
- result["coalesced_queue"] = filtered
- current_id = str(result.get("task_execution_id") or "").strip()
- if current_id not in execution_set:
- result["task_execution_id"] = execution_ids[0]
- return result
-
-
-def _scheduled_segment_suppresses_delivery(segment: list[dict]) -> bool:
- for row in segment:
- spec = (_scheduled_provenance(row) or {}).get("platform_specific") or {}
- if isinstance(spec, dict) and bool(spec.get("suppress_delivery")):
- return True
- return False
-
+def emit_matches_active_turn(sink: dict, context: "MessageContext") -> bool:
+ """The ONE active-turn token rule (FSM Phase 2 — collapses the three previously
+ duplicated guards: ``_stream_chunk`` completion, ``_is_active_turn``, and
+ ``Controller.mark_turn_complete``).
-def _write_coalesced_native_id_markers(conn: Any, segment: list[dict]) -> None:
- """Keep native-id dedupe coverage for coalesced queued harness rows.
+ A live sink WITH a token means an interactive turn is in flight; only its OWN
+ result (matching token) is the active turn's. A result whose token DIFFERS or is
+ ABSENT is stale — a superseded / stopped / older turn, or a scheduled / watch run
+ that carries no token — and must NOT complete the turn (set ``done_event``) or
+ settle its dot. Fail-open when the sink itself is tokenless, so non-streaming
+ turns still settle. (Chunk FORWARDING is deliberately NOT gated — see
+ ``_stream_chunk``; only COMPLETION + dot-settle are.)
- The first native id is restored on the dispatched context and mirrored as
- the visible harness prompt. Later coalesced queued rows are deleted before
- dispatch, so write hidden rows for their native ids; otherwise a waiter retry
- for one of those callbacks would not hit ``uq_messages_platform_native``.
- """
- native_ids = _scheduled_segment_native_ids(segment)
- if not native_ids:
- return
- first = segment[0]
- suppresses_delivery = _scheduled_segment_suppresses_delivery(segment)
- marker_ids = native_ids[1:]
- if not marker_ids:
- return
-
- for native_id in marker_ids:
- try:
- messages_service.append(
- conn,
- scope_id=first["scope_id"],
- session_id=first.get("session_id"),
- platform=first.get("platform") or "avibe",
- author="harness",
- source="harness",
- message_type=messages_service.HARNESS_DEDUPE_TYPE,
- text="",
- metadata={"coalesced_from": first.get("id"), "suppressed_delivery": suppresses_delivery},
- native_message_id=native_id,
- )
- except IntegrityError:
- logger.debug("queue flush: coalesced native id marker already exists for %s", native_id, exc_info=True)
-
-
-def _restore_queued_rows(conn: Any, rows: list[dict]) -> None:
- native_ids = [
- str(row.get("native_message_id") or "").strip()
- for row in rows
- if str(row.get("native_message_id") or "").strip()
- ]
- if native_ids:
- conn.execute(
- messages.delete()
- .where(messages.c.type == messages_service.HARNESS_DEDUPE_TYPE)
- .where(messages.c.native_message_id.in_(native_ids))
- )
- for row in rows:
- payload = {
- "id": row["id"],
- "scope_id": row["scope_id"],
- "session_id": row.get("session_id"),
- "platform": row.get("platform") or "avibe",
- "author": row.get("author") or "harness",
- "type": messages_service.QUEUED_TYPE,
- "author_id": row.get("author_id"),
- "author_name": row.get("author_name"),
- "source": row.get("source"),
- "native_message_id": row.get("native_message_id"),
- "parent_native_message_id": row.get("parent_native_message_id"),
- "content_text": row.get("text") or "",
- "content_json": json.dumps(row.get("content") or {"text": row.get("text") or ""}),
- "metadata_json": json.dumps(row.get("metadata") or {}),
- "created_at": row.get("created_at"),
- "updated_at": row.get("updated_at") or row.get("created_at"),
- "delivered_at": row.get("delivered_at"),
- "read_at": row.get("read_at"),
- }
- try:
- conn.execute(messages.insert().values(**payload))
- except IntegrityError:
- logger.debug("queue flush: queued row already restored or replaced for %s", row.get("id"), exc_info=True)
-
-
-def _claim_agent_run_segment_and_retire_queue(
- conn: Any,
- *,
- run_ids: list[str],
- segment: list[dict],
-) -> list[str]:
- from storage.background import claim_queued_runs_for_workbench_in_connection
-
- claimed_run_ids = claim_queued_runs_for_workbench_in_connection(conn, run_ids)
- if set(claimed_run_ids) != set(run_ids):
- return claimed_run_ids
- messages_service.delete_queued(conn, [r["id"] for r in segment if r.get("id")])
- _write_coalesced_native_id_markers(conn, segment)
- return claimed_run_ids
-
-
-def _scheduled_claimed_queue_row_ids(conn: Any, segment: list[dict]) -> set[str]:
- native_ids = _scheduled_segment_native_ids(segment)
- if not native_ids:
- return set()
- native_by_row_id = {
- str(row.get("id") or ""): str(row.get("native_message_id") or (_scheduled_provenance(row) or {}).get("message_id") or "").strip()
- for row in segment
- if row.get("id")
- }
- native_to_row_ids: dict[str, set[str]] = {}
- for row_id, native_id in native_by_row_id.items():
- if native_id:
- native_to_row_ids.setdefault(native_id, set()).add(row_id)
- platform = str(segment[0].get("platform") or "avibe")
- rows = (
- conn.execute(
- select(messages.c.id, messages.c.native_message_id)
- .where(messages.c.platform == platform)
- .where(messages.c.native_message_id.in_(native_ids))
- )
- .all()
- )
- claimed_row_ids: set[str] = set()
- segment_row_ids = set(native_by_row_id)
- for row_id, native_id in rows:
- if str(row_id) in segment_row_ids:
- continue
- claimed_row_ids.update(native_to_row_ids.get(str(native_id or ""), set()))
- return claimed_row_ids
-
-
-def _promote_merged_user_segment(
- conn: Connection,
- segment: list[dict[str, Any]],
- *,
- text: str,
- attachments: list[dict[str, Any]],
- metadata: Optional[dict[str, Any]],
- author_id: Optional[str],
-) -> dict[str, Any]:
- """Replace a queued input segment with one freshly ordered visible message.
-
- ``messages`` sort by ``(created_at, id)`` and ids encode creation time. Reusing
- an old queued id with a new timestamp makes that pair contradictory, so mint
- both together and atomically repoint every dependent record.
+ NOTE (no-timeout invariant): with the turn-duration timeout gone, a turn whose
+ OWN terminal result is tokenless would hang here forever. The FSM therefore must
+ guarantee every terminal result carries the active turn's token (Claude adoption
+ / FSM-attached token); this guard is intentionally strict.
"""
- canonical = segment[0]
- visible_type = messages_service.pending_message_target_type(
- canonical.get("author"),
- canonical.get("source"),
- canonical.get("author_name"),
- )
- is_harness = messages_service.HARNESS_TYPE in {
- canonical.get("author"),
- canonical.get("source"),
- }
- native_message_ids = [
- str(row.get("native_message_id") or "").strip()
- for row in segment
- if str(row.get("native_message_id") or "").strip()
- ]
- if native_message_ids and len(segment) != 1:
- raise ValueError("independently identified user rows must flush as separate segments")
- merged_content: dict[str, Any] = {"text": text}
- annotation = (canonical.get("content") or {}).get("annotation")
- if isinstance(annotation, dict):
- merged_content["annotation"] = annotation
- if attachments:
- merged_content["attachments"] = attachments
- visible = messages_service.append(
- conn,
- scope_id=canonical.get("scope_id"),
- session_id=str(canonical["session_id"]),
- platform=str(canonical.get("platform") or "avibe"),
- author=messages_service.HARNESS_TYPE if is_harness else "user",
- message_type=visible_type,
- text=text,
- content=merged_content,
- metadata=metadata,
- author_id=canonical.get("author_id") if is_harness else author_id,
- author_name=canonical.get("author_name") if is_harness else None,
- source=messages_service.HARNESS_TYPE if is_harness else "user",
- parent_native_message_id=canonical.get("parent_native_message_id"),
- delivered_at=canonical.get("delivered_at"),
- read_at=canonical.get("read_at"),
- )
- source_ids = [str(row["id"]) for row in segment]
- visible_id = str(visible["id"])
- _repoint_message_dependents(conn, source_ids, visible_id)
- messages_service.delete_queued(conn, source_ids)
-
- native_message_id = native_message_ids[0] if native_message_ids else None
- if native_message_id:
- conn.execute(
- update(messages)
- .where(messages.c.id == visible_id)
- .values(native_message_id=native_message_id)
- )
- visible["native_message_id"] = native_message_id
- return visible
-
-
-def _repoint_message_dependents(
- conn: Connection,
- source_ids: list[str],
- target_id: str,
-) -> None:
- """Retarget every foreign key to messages merged into one canonical row."""
- for table in messages.metadata.tables.values():
- if table is messages:
- continue
- for foreign_key in table.foreign_keys:
- if foreign_key.column.table is not messages or foreign_key.column.name != messages.c.id.name:
- continue
- column = foreign_key.parent
- conn.execute(
- update(table)
- .where(column.in_(source_ids))
- .values({column.name: target_id})
- )
+ sink_token = sink.get("turn_token")
+ ctx_token = (getattr(context, "platform_specific", None) or {}).get("turn_token")
+ return not (sink_token is not None and ctx_token != sink_token)
@dataclass
@@ -695,16 +354,8 @@ class Turn:
turn STARTED under (so Stop interrupts the backend it actually ran on, even if
the Chat header later swapped agent/model). ``task`` is the Stop target
(``/internal/cancel``) and the ``/turn-state`` source.
- - ``flush_on_cancel``: drain the send-while-busy queue even though the turn ends
- via cancellation — ``send-now`` cancels the running turn but wants the queue to
- run right after. A plain Stop keeps the queue ("不清空队列").
- - ``stop_no_flush``: a plain Stop is interrupting this turn and it must NOT flush,
- even if the backend interrupt lets the turn settle normally (no
- ``CancelledError``) during the awaited stop.
-
- The two intents live HERE rather than in parallel ``set``s so they retire with
- the turn: ``cancel`` / ``send_now`` set them on this object and ``_run`` reads
- them off the SAME object when it pops it — no separate ``.discard()`` to leak.
+ Queue policy is deliberately absent. The durable Session hold and Turn control
+ slot decide whether backlog may drain across both process lifetime and restart.
The streaming SINK is deliberately NOT held here: it is keyed by ``session_key``
(platform-prefixed ``avibe::<id>``) not ``session_id``, is registered from the
@@ -715,21 +366,54 @@ class Turn:
task: asyncio.Task
context: "MessageContext"
started_at: str = ""
- flush_on_cancel: bool = False
- stop_no_flush: bool = False
#: WHY this turn's task was cancelled, in the ``core.run_settlement``
#: vocabulary — set by the canceller BEFORE ``task.cancel()`` so ``_run`` can
- #: attribute the run it owns correctly. ``None`` means a plain user Stop
- #: (``cancel`` / ``send_now``), which is the default reading of a cancelled
- #: turn; a backend runtime refresh sets ``SETTLED_BY_BACKEND_REFRESH`` so a
- #: routine ``agents.*`` reconciliation is not reported as if the user pressed
- #: Stop (Codex P1). It rides on the Turn for the same reason the flush intents
- #: do: it retires when the turn is popped, with no parallel set to leak.
+ #: attribute the run it owns correctly. User interruption paths set
+ #: ``SETTLED_BY_STOPPED`` before invoking the backend because a successful Stop
+ #: may emit its terminal result before ``handle_stop`` returns; backend runtime
+ #: refresh sets ``SETTLED_BY_BACKEND_REFRESH`` so a routine ``agents.*``
+ #: reconciliation is not reported as if the user pressed Stop (Codex P1). It
+ #: rides on the Turn so it retires when the turn is popped.
cancel_settled_by: Optional[str] = None
- #: One shared backend Stop attempt for concurrent send-now callers. Each
- #: caller already owns its own durable queue row; they must not interrupt the
- #: same active turn more than once.
- send_now_task: Optional[asyncio.Task[dict[str, Any]]] = None
+ logical_turn_id: Optional[str] = None
+ delivery_id: Optional[str] = None
+ terminal_is_error: bool = False
+
+
+@dataclass(frozen=True)
+class DeliveryRequest:
+ """Private P0/P1/P3 admission contract owned by ``SessionTurnManager``."""
+
+ session_id: str
+ priority: Literal["p0", "p1", "p3"]
+ content: str | None = None
+ # Empty dispatch text can still carry accepted communication content through
+ # attachments. ``None`` preserves the public empty-P0/P1 control semantics.
+ has_content: bool | None = None
+ delivery_id: str | None = None
+ expected_delivery_id: str | None = None
+ expected_turn_id: str | None = None
+ scope_id: str | None = None
+ platform: str = "avibe"
+ source: str = "user"
+ author: str = "user"
+ message_type: str | None = None
+ author_id: str | None = None
+ author_name: str | None = None
+ display_text: str | None = None
+ content_json: dict[str, Any] | None = None
+ metadata: dict[str, Any] | None = None
+ native_message_id: str | None = None
+ parent_native_message_id: str | None = None
+
+
+@dataclass(frozen=True)
+class DeliveryResult:
+ delivery_id: str | None
+ message_id: str | None
+ state: str
+ turn_id: str | None = None
+ reason: str | None = None
@dataclass(frozen=True)
@@ -740,7 +424,7 @@ class TurnSubmissionResult:
queue_persisted: bool | None = None
target_was_busy: bool = False
delivery_status: str | None = None
- queue_owner_transferred: bool = False
+ delivery_owner_transferred: bool = False
class SessionTurnManager:
@@ -749,9 +433,7 @@ class SessionTurnManager:
State (a session has at most one active turn):
- ``in_flight``: ``session_id -> Turn`` for the active turn — the Stop target
- (``/internal/cancel``), the ``/turn-state`` source, the trigger for draining
- the send-while-busy queue, and the carrier of the two end-of-turn flush
- intents (``Turn.flush_on_cancel`` / ``Turn.stop_no_flush``).
+ (``/internal/cancel``) and the ``/turn-state`` projection.
- ``active_turn_sinks``: the live streaming sink per ``session_key`` — the
streaming half, kept separate on purpose (see ``Turn``).
@@ -786,6 +468,17 @@ class SessionTurnManager:
self._engine = get_cached_sqlite_engine()
return self._engine
+ def _durable_schema_available(self) -> bool:
+ engine = self._sqlite_engine()
+ with engine.connect() as conn:
+ return conn.dialect.has_table(
+ conn,
+ "session_turns",
+ ) and conn.dialect.has_table(
+ conn,
+ "message_deliveries",
+ ) and conn.dialect.has_table(conn, "agent_sessions")
+
def is_in_flight(self, session_id: Optional[str]) -> bool:
"""True when ``session_id`` has an active (RUNNING) turn."""
return bool(session_id) and session_id in self.in_flight
@@ -796,18 +489,86 @@ class SessionTurnManager:
if not isinstance(spec, dict):
return set()
found: set[str] = set()
- primary = str(spec.get("task_execution_id") or "").strip()
- if primary:
- found.add(primary)
- coalesced = spec.get("coalesced_queue")
- execution_ids = coalesced.get("execution_ids") if isinstance(coalesced, dict) else None
- if isinstance(execution_ids, list):
- for value in execution_ids:
+ accepted_ids = spec.get("accepted_agent_run_ids")
+ if isinstance(accepted_ids, list):
+ for value in accepted_ids:
execution_id = str(value or "").strip()
if execution_id:
found.add(execution_id)
+ primary = str(spec.get("task_execution_id") or "").strip()
+ if primary:
+ found.add(primary)
return found
+ def _settle_agent_run_ids(
+ self,
+ run_ids: set[str] | list[str],
+ settled_by: Optional[str],
+ ) -> None:
+ if settled_by not in SETTLEMENTS_WITHOUT_RESULT or not run_ids:
+ return
+ normalized = sorted({str(run_id) for run_id in run_ids if str(run_id).strip()})
+ if not normalized:
+ return
+ service = (
+ getattr(self.controller, "scheduled_task_service", None)
+ if self.controller
+ else None
+ )
+ settle = getattr(service, "settle_agent_runs_without_result", None)
+ if not callable(settle):
+ logger.debug("turn settlement: no harness settlement writer available")
+ return
+ try:
+ settle(normalized, settled_by=settled_by)
+ except Exception:
+ logger.warning(
+ "turn settlement: failed to settle runs %s as %s",
+ normalized,
+ settled_by,
+ exc_info=True,
+ )
+
+ def _settle_agent_run_ids_from_terminal_turn(
+ self,
+ run_ids: set[str] | list[str],
+ turn: dict[str, Any],
+ ) -> None:
+ normalized = sorted({str(run_id) for run_id in run_ids if str(run_id).strip()})
+ if not normalized:
+ return
+ service = (
+ getattr(self.controller, "scheduled_task_service", None)
+ if self.controller
+ else None
+ )
+ settle = getattr(service, "settle_agent_runs_from_terminal_turn", None)
+ if not callable(settle):
+ self._settle_agent_run_ids(normalized, turn.get("settled_by"))
+ return
+ try:
+ evidence = json.loads(str(turn.get("terminal_evidence_json") or "{}"))
+ if not isinstance(evidence, dict):
+ evidence = {}
+ except (TypeError, ValueError, json.JSONDecodeError):
+ evidence = {}
+ try:
+ settle(
+ normalized,
+ turn_id=str(turn["id"]),
+ outcome=str(turn.get("terminal_outcome") or "completed"),
+ settled_by=str(turn.get("settled_by") or "") or None,
+ evidence_kind=str(turn.get("terminal_evidence_kind") or "") or None,
+ evidence=evidence,
+ )
+ except Exception:
+ logger.warning(
+ "turn settlement: failed to settle late accepted runs %s from Turn=%s",
+ normalized,
+ turn.get("id"),
+ exc_info=True,
+ )
+
def _settle_turn_owned_agent_runs(self, context: "MessageContext", settled_by: Optional[str]) -> None:
"""Settle the ``agent_runs`` rows this turn owned when no result arrived.
@@ -832,59 +593,129 @@ class SessionTurnManager:
terminal result is safe in both directions.
"""
- if settled_by not in SETTLEMENTS_WITHOUT_RESULT:
- return
run_ids = self._agent_run_ids_from_spec(getattr(context, "platform_specific", None))
+ self._settle_agent_run_ids(run_ids, settled_by)
+
+ def _reconcile_terminal_agent_runs(self) -> None:
+ """Retry exact terminal-snapshot settlement before the stale-run sweep."""
+
+ with self._sqlite_engine().connect() as conn:
+ pairs = list(
+ conn.execute(
+ select(
+ agent_runs.c.id.label("run_id"),
+ delivery_rows.c.turn_id,
+ )
+ .join(
+ delivery_rows,
+ delivery_rows.c.id == agent_runs.c.delivery_id,
+ )
+ .join(
+ session_turn_rows,
+ session_turn_rows.c.id == delivery_rows.c.turn_id,
+ )
+ .where(
+ agent_runs.c.status.in_(
+ ["queued", "pending", "running", "processing"]
+ )
+ )
+ .where(delivery_rows.c.state == "accepted")
+ .where(session_turn_rows.c.state == "terminal")
+ ).mappings()
+ )
+ run_ids_by_turn: dict[str, list[str]] = {}
+ terminal_turns: dict[str, dict[str, Any]] = {}
+ for pair in pairs:
+ turn_id = str(pair["turn_id"] or "")
+ run_id = str(pair["run_id"] or "")
+ if not turn_id or not run_id:
+ continue
+ run_ids_by_turn.setdefault(turn_id, []).append(run_id)
+ for turn_id in run_ids_by_turn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ if turn is not None:
+ terminal_turns[turn_id] = turn
+ for turn_id, run_ids in run_ids_by_turn.items():
+ turn = terminal_turns.get(turn_id)
+ if turn is not None:
+ self._settle_agent_run_ids_from_terminal_turn(run_ids, turn)
+
+ @staticmethod
+ def _append_accepted_agent_run_ids(spec: dict[str, Any], run_ids: list[str]) -> None:
+ accepted = spec.get("accepted_agent_run_ids")
+ values = list(accepted) if isinstance(accepted, list) else []
+ for run_id in run_ids:
+ normalized = str(run_id or "").strip()
+ if normalized and normalized not in values:
+ values.append(normalized)
+ if values:
+ spec["accepted_agent_run_ids"] = values
+
+ def _attach_accepted_agent_runs(
+ self,
+ *,
+ session_id: str,
+ turn_id: str,
+ run_ids: list[str],
+ context: Optional["MessageContext"],
+ ) -> None:
if not run_ids:
return
- service = getattr(self.controller, "scheduled_task_service", None) if self.controller else None
- settle = getattr(service, "settle_agent_runs_without_result", None)
- if not callable(settle):
- # A fake/partial controller (tests, a boot window before the service
- # exists). The sweep remains the backstop; guessing is not an option.
- logger.debug("turn settlement: no harness settlement writer available")
- return
- try:
- settle(sorted(run_ids), settled_by=settled_by)
- except Exception:
- logger.warning(
- "turn settlement: failed to settle runs %s as %s",
- sorted(run_ids),
- settled_by,
- exc_info=True,
+ projected = self.in_flight.get(session_id)
+ if projected is not None and projected.logical_turn_id == turn_id:
+ if projected.context.platform_specific is None:
+ projected.context.platform_specific = {}
+ self._append_accepted_agent_run_ids(
+ projected.context.platform_specific,
+ run_ids,
)
+ context_token = str(
+ ((getattr(context, "platform_specific", None) or {}).get("turn_token") or "")
+ )
+ if context is not None and context_token == turn_id:
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ self._append_accepted_agent_run_ids(context.platform_specific, run_ids)
+ for sink in self.active_turn_sinks.values():
+ if str(sink.get("turn_token") or "") == turn_id:
+ self._append_accepted_agent_run_ids(sink, run_ids)
def owned_agent_run_ids(self) -> set[str]:
- """Run ids a live turn in THIS process is currently executing.
-
- The staleness sweep (``docs/plans/agent-run-zombie-settlement.md`` §4.1) needs
- to know which ``running`` rows still have an owner before it declares any of
- them orphaned. ``ScheduledTaskService`` can answer for its own drain path, but
- the workbench lane never enters ``_inflight_executions``:
- ``claim_queued_runs_for_workbench_in_connection`` claims rows that
- ``flush_queue`` executes. ``Turn`` carries no run-id field, so the ids are read
- off the context each turn started under — the same ``task_execution_id`` /
- ``coalesced_queue`` keys ``_turn_sink_identity`` reads.
-
- A coalesced turn owns EVERY id it is settling, not just the primary, or the
- sweep would fail the siblings out from under a live flush.
-
- Live streaming sinks are unioned in as well. They carry the same attribution
- and are registered/popped on a different boundary than ``in_flight``, so a run
- visible through either one is owned. Over-reporting an owner only delays a
- sweep; under-reporting one fails a live run.
-
- A malformed context contributes no ids rather than raising — but note the
- caller must still fail closed if this method is missing or raises outright,
- because "no owners" and "cannot tell" are opposite answers.
- """
+ """Run ids owned by a durable Delivery or a live process projection."""
owned: set[str] = set()
for turn in list(self.in_flight.values()):
owned |= self._agent_run_ids_from_spec(getattr(turn.context, "platform_specific", None))
for sink in list(self.active_turn_sinks.values()):
owned |= self._agent_run_ids_from_spec(sink)
+ if self._durable_schema_available():
+ self._reconcile_terminal_agent_runs()
+ with self._sqlite_engine().connect() as conn:
+ owned.update(
+ str(run_id)
+ for run_id in conn.execute(
+ select(agent_runs.c.id)
+ .join(
+ delivery_rows,
+ delivery_rows.c.id == agent_runs.c.delivery_id,
+ )
+ .where(
+ agent_runs.c.status.in_(
+ ["queued", "pending", "running", "processing"]
+ )
+ )
+ .where(delivery_rows.c.state != "retired")
+ ).scalars()
+ )
return owned
+ def accepted_agent_run_ids_for_turn(self, turn_id: str) -> list[str]:
+ """Read restart-stable Run attribution for one exact logical Turn."""
+
+ if not turn_id or not self._durable_schema_available():
+ return []
+ with self._sqlite_engine().connect() as conn:
+ return delivery_store.accepted_agent_run_ids_for_turn(conn, turn_id)
+
def busy_session_ids(self) -> set[str]:
"""Sessions whose gate is occupied by a live turn RIGHT NOW.
@@ -896,13 +727,17 @@ class SessionTurnManager:
this, a legitimate Workbench turn lasting longer than the hold TTL had its own
queued follower failed underneath it (Codex P2).
- ``in_flight`` is the right predicate because it is the same map
- ``submit``/``submit_scheduled`` consult before answering ``enqueued`` — the very
- decision that created the hold. Sinks are not unioned in here: they are keyed by
- session KEY, not session id, and a streaming turn always has an ``in_flight``
- entry anyway.
+ ``in_flight`` covers live tasks in this process. A restored native runtime can
+ instead be owned only by ``session_turns``; ``submit`` treats that durable owner
+ as busy too, so the sweep projection must use the same combined predicate.
+ Sinks are not unioned in here: they are keyed by session KEY, not session id,
+ and a streaming turn always has one of those two owners.
"""
- return {session_id for session_id in list(self.in_flight) if session_id}
+ busy = {session_id for session_id in list(self.in_flight) if session_id}
+ if self._durable_schema_available():
+ with self._sqlite_engine().connect() as conn:
+ busy |= delivery_store.session_ids_with_live_turns(conn)
+ return busy
def model_hub_turn_id_for_task(
self,
@@ -1002,7 +837,10 @@ class SessionTurnManager:
return
for session_id in sorted(session_ids):
if not self.is_in_flight(session_id):
- await self.flush_queue(session_id)
+ if self._durable_schema_available():
+ await self._resume_post_terminal(session_id)
+ else:
+ await self.flush_queue(session_id)
def active_session_ids_for_backend(self, backend: str) -> set[str]:
return {
@@ -1013,7 +851,7 @@ class SessionTurnManager:
def active_runtime_session_ids_for_backend(self, backend: str) -> set[str]:
"""Active Sessions that actually entered the old backend generation."""
- return {
+ active = {
session_id
for session_id, turn in self.in_flight.items()
if not turn.task.done()
@@ -1024,134 +862,3296 @@ class SessionTurnManager:
)
)
}
+ if self._durable_schema_available():
+ with self._sqlite_engine().connect() as conn:
+ active |= delivery_store.active_runtime_session_ids_for_backend(
+ conn,
+ backend,
+ )
+ return active
@staticmethod
async def _noop_chunk(_envelope: dict) -> None:
# Chunks are discarded — the browser renders from ``message.new``.
return None
- async def submit(
- self,
- session_id: Optional[str],
- context: "MessageContext",
- text: str,
- *,
- source: str = SOURCE_HUMAN,
- enqueue: Optional[Callable[[], bool]] = None,
- delivery_intent: Literal["queue", "send_now"] = "queue",
- ) -> TurnSubmissionResult:
- """Unified turn entry for BOTH Chat and the scheduler: idle → run now; busy
- (or a pre-existing send-while-busy queue) → enqueue and run later.
-
- The result separates the routing decision (``route``) from whether the
- SOURCE-specific enqueue callback actually persisted its row
- (``queue_persisted``). Chat promotes its pre-saved pending row; the
- scheduler appends a harness row. Their shapes differ, so the caller owns the
- write and reports its durable result through the callback.
-
- The in_flight check and callback have no ``await`` between them, which only
- prevents this event loop from finishing + flushing the active turn in that
- gap. It does NOT make the callback atomic with external transactions such as
- session archival; callers must use ``queue_persisted`` (and any domain-owned
- post-submit observation) rather than infer durability from ``route``.
- """
- if delivery_intent not in {"queue", "send_now"}:
- raise ValueError(f"unsupported delivery intent: {delivery_intent}")
- if not (isinstance(session_id, str) and session_id):
- # No session key (CLI-style) — just run; nothing to queue against.
- await self._run(None, context, text, source=source)
- return TurnSubmissionResult(
- route="ran",
- delivery_status="ran" if delivery_intent == "send_now" else None,
- )
-
- backend = self._context_backend(context)
- entry = self.in_flight.get(session_id)
- busy = entry is not None and not entry.task.done()
- # Enqueue when a turn is running OR a prior Stop left queued rows behind — the
- # new message must run AFTER them, not jump ahead (Codex P2).
- if delivery_intent == "send_now":
- # Send-now always enters through the durable queue, even if the
- # Session became idle before admission. Busy and idle delivery then
- # share the same FIFO, provenance, and restart contract.
- should_enqueue = True
- if backend in self._draining_backends:
- self._deferred_restart_sessions.setdefault(backend, set()).add(
- session_id
- )
- elif backend in self._draining_backends:
- should_enqueue = True
- self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)
- elif busy:
- should_enqueue = True
- else:
- with self._sqlite_engine().connect() as conn:
- should_enqueue = bool(messages_service.list_queued(conn, session_id))
- if should_enqueue:
- queue_persisted = bool(enqueue()) if enqueue is not None else False
- delivery_status = None
- if queue_persisted and delivery_intent == "send_now":
- if backend in self._draining_backends and not busy:
- # The row is durable, but a backend cutover deliberately owns
- # when the next turn may start. Report the deferral instead of
- # mislabelling the still-present queue as empty.
- delivery_status = "deferred"
- else:
- delivery_result = await self.send_now(session_id)
- delivery_status = str(
- delivery_result.get("status")
- or delivery_result.get("code")
- or "failed"
+ def _delivery_context(self, session_id: str) -> "MessageContext":
+ if self._build_context is None:
+ raise RuntimeError("Session delivery context builder is not bound")
+ return self._build_context(session_id)
+
+ def _delivery_backend(self, session_id: str, context: Optional["MessageContext"]) -> tuple[str, "MessageContext"]:
+ resolved = context or self._delivery_context(session_id)
+ with self._sqlite_engine().connect() as conn:
+ backend = str(
+ conn.execute(
+ select(agent_sessions.c.agent_backend).where(
+ agent_sessions.c.id == session_id
)
- if queue_persisted and (busy or backend in self._draining_backends):
- # The row joins the active turn's queue and stays until it drains —
- # surface the queue growth NOW so the UI reflects it immediately
- # (the later flush emits its own queue.updated when it pops). This
- # closes the enqueue-time gap for BOTH Chat and scheduled sends.
- from core.inbox_events import bus
+ ).scalar_one_or_none()
+ or ""
+ ).strip()
+ if not backend:
+ backend = self._context_backend(resolved)
+ if not backend:
+ raise RuntimeError(f"Session {session_id} has no resolved backend")
+ return backend, resolved
- bus.publish("queue.updated", {"session_id": session_id})
- elif (
- delivery_intent != "send_now"
- and not busy
- and backend not in self._draining_backends
- ):
- # Idle + pre-existing queue → no running turn to flush behind, so
- # drain the durable queue now, in order. If this callback lost an
- # archival race, only pre-existing rows remain. flush_queue publishes
- # queue.updated itself.
- await self.flush_queue(session_id)
- return TurnSubmissionResult(
- route="enqueued",
- queue_persisted=queue_persisted,
- target_was_busy=busy,
- delivery_status=delivery_status,
- )
- await self._run(session_id, context, text, source=source)
- return TurnSubmissionResult(
- route="ran",
- target_was_busy=busy,
- delivery_status="ran" if delivery_intent == "send_now" else None,
+ @staticmethod
+ def _delivery_snapshot(request: DeliveryRequest) -> dict[str, Any]:
+ if request.content is None:
+ raise ValueError("content Delivery requires a Message snapshot")
+ return delivery_store.message_snapshot(
+ scope_id=request.scope_id,
+ session_id=request.session_id,
+ platform=request.platform,
+ author=request.author,
+ source=request.source,
+ message_type=request.message_type,
+ text=request.display_text if request.display_text is not None else request.content,
+ content=request.content_json,
+ metadata=request.metadata,
+ author_id=request.author_id,
+ author_name=request.author_name,
+ native_message_id=request.native_message_id,
+ parent_native_message_id=request.parent_native_message_id,
)
- async def _run(
+ def _request_from_delivery(
self,
- session_id: Optional[str],
- context: "MessageContext",
- text: str,
+ delivery: dict[str, Any],
*,
- source: str = SOURCE_HUMAN,
- ) -> None:
- """Start a fire-and-forget turn and HOLD it open until it settles.
+ has_attachments: bool = False,
+ ) -> DeliveryRequest:
+ payload = delivery_store.delivery_payload(delivery)
+ return DeliveryRequest(
+ session_id=str(delivery["session_id"]),
+ priority=str(delivery["priority"]),
+ content=str(delivery.get("dispatch_text") or ""),
+ has_content=delivery_store.has_substantive_content(
+ delivery,
+ has_attachments=has_attachments,
+ ),
+ delivery_id=str(delivery["id"]),
+ scope_id=payload.get("scope_id"),
+ platform=str(payload.get("platform") or "avibe"),
+ source=str(payload.get("source") or "user"),
+ author=str(payload.get("author") or "user"),
+ message_type=str(payload.get("type") or "user"),
+ author_id=payload.get("author_id"),
+ author_name=payload.get("author_name"),
+ display_text=str(payload.get("text") or ""),
+ content_json=dict(payload.get("content") or {}),
+ metadata=dict(payload.get("metadata") or {}),
+ native_message_id=payload.get("native_message_id"),
+ parent_native_message_id=payload.get("parent_native_message_id"),
+ )
- A no-op chunk sink keeps ``dispatch_turn`` alive for the turn's lifetime so
- ``in_flight`` stays populated (Stop works) and the session-level
- ``turn.start`` / ``turn.end`` lifecycle is published for the browser's
- working indicator. On NATURAL completion the queue is flushed: messages the
- user sent while this turn ran are merged + run as the next turn. A user Stop
- (cancellation) does NOT flush — the queue is kept per the user's "don't
- clear the queue on stop" rule — unless ``send-now`` opted this session into
- ``flush_on_cancel``. The reply reaches the browser over ``message.new``.
+ def _committed_delivery_result(
+ self,
+ delivery_id: str,
+ *,
+ attempted_turn_id: str | None = None,
+ ) -> DeliveryResult:
+ """Return the exact post-transition Delivery instead of a cached claim."""
+
+ with self._sqlite_engine().connect() as conn:
+ delivery = delivery_store.get_delivery(conn, delivery_id)
+ if delivery is None:
+ raise RuntimeError(f"durable Delivery disappeared after transition: {delivery_id}")
+ turn_id = str(
+ delivery.get("turn_id")
+ or delivery.get("current_target_turn_id")
+ or attempted_turn_id
+ or ""
+ ).strip()
+ return DeliveryResult(
+ delivery_id,
+ str(delivery.get("message_id") or "").strip() or None,
+ str(delivery["state"]),
+ turn_id or None,
+ )
+
+ @staticmethod
+ def _claim_start_batch(
+ conn: Connection,
+ *,
+ turn_id: str,
+ session_id: str,
+ backend: str,
+ deliveries: list[dict[str, Any]],
+ dispatch_text: str,
+ attempt_id: str | None = None,
+ ) -> dict[str, Any]:
+ """Claim a Delivery batch and all linked Agent Runs atomically."""
+
+ run_ids = list(
+ dict.fromkeys(
+ run_id
+ for delivery in deliveries
+ for run_id in delivery_store.agent_run_ids_for_delivery(conn, delivery)
+ )
+ )
+ if run_ids:
+ from storage.background import claim_agent_runs_for_turn_in_connection
+
+ claimed_run_ids = claim_agent_runs_for_turn_in_connection(conn, run_ids)
+ if claimed_run_ids != run_ids:
+ raise RuntimeError("Delivery batch contains an unclaimable Agent Run")
+ return delivery_store.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend=backend,
+ deliveries=deliveries,
+ dispatch_text=dispatch_text,
+ attempt_id=attempt_id,
+ )
+
+ @staticmethod
+ def _cancel_runs_for_retired_delivery(
+ conn: Connection,
+ delivery: dict[str, Any] | None,
+ ) -> list[str]:
+ """Make Delivery retirement and exact Run cancellation one transaction."""
+
+ if delivery is None or delivery.get("state") != "retired":
+ return []
+ from storage.background import (
+ cancel_agent_runs_for_retired_deliveries_in_connection,
+ )
+
+ return cancel_agent_runs_for_retired_deliveries_in_connection(
+ conn,
+ session_id=str(delivery["session_id"]),
+ delivery_ids=[str(delivery["id"])],
+ )
+
+ @classmethod
+ def _record_definitive_delivery_attempt(
+ cls,
+ conn: Connection,
+ delivery_id: str,
+ **kwargs: Any,
+ ) -> dict[str, Any] | None:
+ delivery = delivery_store.record_definitive_attempt(
+ conn,
+ delivery_id,
+ **kwargs,
+ )
+ cls._cancel_runs_for_retired_delivery(conn, delivery)
+ return delivery
+
+ @classmethod
+ def _retire_delivery_not_written(
+ cls,
+ conn: Connection,
+ session_id: str,
+ delivery_id: str,
+ *,
+ reason: str,
+ ) -> bool:
+ retired = delivery_store.retire_not_written(
+ conn,
+ session_id,
+ delivery_id,
+ reason=reason,
+ )
+ if retired:
+ cls._cancel_runs_for_retired_delivery(
+ conn,
+ delivery_store.get_delivery(conn, delivery_id),
+ )
+ return retired
+
+ def _claim_fifo_batch_in_transaction(
+ self,
+ conn: Connection,
+ *,
+ session_id: str,
+ backend: str,
+ ) -> str | None:
+ """Claim the exact open FIFO head while the caller owns SQLite's writer slot."""
+
+ if (
+ delivery_store.active_turn(conn, session_id) is not None
+ or delivery_store.queue_is_held(conn, session_id)
+ or backend in self._draining_backends
+ ):
+ return None
+ while True:
+ head = delivery_store.claimable_fifo_head(conn, session_id)
+ queued = delivery_store.claimable_fifo_prefix(conn, session_id)
+ if head is None or not queued or str(queued[0]["id"]) != str(head["id"]):
+ return None
+ segment_payloads = _collect_delivery_segment(queued)
+ segment = [
+ delivery_store.get_delivery(conn, str(row["id"]))
+ for row in segment_payloads
+ ]
+ if not segment or any(row is None for row in segment):
+ return None
+ delivery_rows = [row for row in segment if row is not None]
+ invalid_rows = [
+ row
+ for row in delivery_rows
+ if not self._has_resolvable_delivery_input(conn, row)
+ ]
+ if invalid_rows:
+ for row in invalid_rows:
+ if not self._retire_delivery_not_written(
+ conn,
+ session_id,
+ str(row["id"]),
+ reason="invalid_input_before_fifo_claim",
+ ):
+ raise RuntimeError("invalid FIFO Delivery retirement lost")
+ logger.warning(
+ "retired queued Delivery=%s because it has no resolvable input",
+ row["id"],
+ )
+ continue
+ turn_id = delivery_store.new_turn_id()
+ self._claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend=backend,
+ deliveries=delivery_rows,
+ dispatch_text=_segment_dispatch_text(segment_payloads),
+ )
+ return turn_id
+
+ def _hydrate_delivery_context(
+ self,
+ context: "MessageContext",
+ delivery: dict[str, Any],
+ ) -> dict[str, Any]:
+ """Restore dispatch inputs only from the durable Delivery snapshot."""
+
+ payload = delivery_store.delivery_payload(delivery)
+ context.message_id = str(delivery["id"])
+ context.platform = str(payload.get("platform") or context.platform or "avibe")
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ context.platform_specific.update(
+ {
+ "delivery_id": str(delivery["id"]),
+ "scope_id": payload.get("scope_id"),
+ "display_text": payload.get("text") or "",
+ "message_content": dict(payload.get("content") or {}),
+ "message_metadata": dict(payload.get("metadata") or {}),
+ "author_id": payload.get("author_id"),
+ "author_name": payload.get("author_name"),
+ "native_message_id": payload.get("native_message_id"),
+ }
+ )
+ from core.workbench_media import (
+ file_attachments_from_specs,
+ resolve_attachment_specs,
+ )
+
+ attachments = (payload.get("content") or {}).get("attachments") or []
+ with self._sqlite_engine().connect() as conn:
+ specs = resolve_attachment_specs(
+ conn,
+ session_id=str(delivery["session_id"]),
+ attachments=attachments,
+ )
+ context.files = file_attachments_from_specs(specs)
+ return payload
+
+ @staticmethod
+ def _has_resolvable_delivery_input(
+ conn: Connection,
+ delivery: dict[str, Any],
+ ) -> bool:
+ payload = delivery_store.delivery_payload(delivery)
+ from core.workbench_media import resolve_attachment_specs
+
+ specs = resolve_attachment_specs(
+ conn,
+ session_id=str(delivery["session_id"]),
+ attachments=(payload.get("content") or {}).get("attachments") or [],
+ )
+ return delivery_store.has_substantive_content(
+ delivery,
+ has_attachments=bool(specs),
+ )
+
+ @staticmethod
+ def _delivery_has_attachment_references(delivery: dict[str, Any]) -> bool:
+ payload = delivery_store.delivery_payload(delivery)
+ return bool((payload.get("content") or {}).get("attachments"))
+
+ def _hydrate_delivery_batch_context(
+ self,
+ context: "MessageContext",
+ deliveries: list[dict[str, Any]],
+ ) -> dict[str, Any]:
+ if not deliveries:
+ raise RuntimeError("a durable Turn has no initial Delivery batch")
+ first = self._hydrate_delivery_context(context, deliveries[0])
+ payloads = [delivery_store.delivery_payload(row) for row in deliveries]
+ attachments = [
+ attachment
+ for payload in payloads
+ for attachment in ((payload.get("content") or {}).get("attachments") or [])
+ ]
+ from core.workbench_media import (
+ file_attachments_from_specs,
+ resolve_attachment_specs,
+ )
+
+ with self._sqlite_engine().connect() as conn:
+ specs = resolve_attachment_specs(
+ conn,
+ session_id=str(deliveries[0]["session_id"]),
+ attachments=attachments,
+ )
+ run_ids = list(
+ dict.fromkeys(
+ run_id
+ for row in deliveries
+ for run_id in delivery_store.agent_run_ids_for_delivery(conn, row)
+ )
+ )
+ context.files = file_attachments_from_specs(specs)
+ context.platform_specific.update(
+ {
+ "delivery_id": str(deliveries[0]["id"]),
+ "delivery_ids": [str(row["id"]) for row in deliveries],
+ "message_content": {
+ "text": "\n".join(
+ str(payload.get("text") or "")
+ for payload in payloads
+ if str(payload.get("text") or "")
+ ),
+ **({"attachments": attachments} if attachments else {}),
+ },
+ }
+ )
+ self._append_accepted_agent_run_ids(context.platform_specific, run_ids)
+ return first
+
+ @staticmethod
+ def _insert_delivery(
+ conn: Connection,
+ request: DeliveryRequest,
+ *,
+ priority: str,
+ state: str,
+ ) -> dict[str, Any]:
+ delivery_id = request.delivery_id or delivery_store.new_delivery_id()
+ existing = delivery_store.get_delivery(conn, delivery_id)
+ if existing is not None:
+ if existing["session_id"] != request.session_id:
+ raise ValueError("Delivery does not belong to the target Session")
+ return existing
+ dedupe_key = delivery_store.native_dedupe_key(
+ request.platform,
+ request.native_message_id,
+ )
+ return delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=request.session_id,
+ priority=priority,
+ state=state,
+ snapshot=SessionTurnManager._delivery_snapshot(request),
+ dispatch_text=str(request.content or ""),
+ dedupe_key=dedupe_key,
+ history_event={"kind": "admission", "priority": priority, "state": state},
+ )
+
+ def _active_identity(
+ self,
+ backend: str,
+ session_id: str,
+ logical_turn_id: str,
+ ) -> tuple[str, str] | None:
+ return active_steer_identity(
+ self.controller,
+ backend,
+ session_id,
+ expected_logical_turn_id=logical_turn_id,
+ )
+
+ async def _steer(self, backend: str, request: SteerRequest):
+ return await steer_active_turn(self.controller, backend, request)
+
+ async def _attempt_steer(self, backend: str, request: SteerRequest):
+ try:
+ return await self._steer(backend, request)
+ except Exception as exc:
+ logger.exception(
+ "native steering outcome is unknown for Session=%s Turn=%s",
+ request.target_session_id,
+ request.expected_logical_turn_id,
+ )
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="adapter_error",
+ error_type=type(exc).__name__,
+ )
+
+ async def _reconcile_steer_attempt(
+ self,
+ backend: str,
+ request: SteerReconcileRequest,
+ ):
+ try:
+ return await reconcile_steer_attempt(self.controller, backend, request)
+ except Exception as exc:
+ logger.exception(
+ "native steering reconciliation failed for Session=%s Turn=%s Attempt=%s",
+ request.target_session_id,
+ request.expected_logical_turn_id,
+ request.attempt_id,
+ )
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="adapter_reconciliation_error",
+ error_type=type(exc).__name__,
+ )
+
+ def _observe_active_delivery_turn(
+ self,
+ session_id: str,
+ ) -> tuple[dict[str, Any] | None, tuple[str, str] | None]:
+ with self._sqlite_engine().connect() as conn:
+ turn = delivery_store.active_turn(conn, session_id)
+ if turn is None:
+ return turn, None
+ identity = self._active_identity(
+ str(turn["backend"]),
+ session_id,
+ str(turn["id"]),
+ )
+ persisted_native_id = str(turn.get("native_turn_id") or "").strip()
+ if identity is None and turn["state"] == "active" and persisted_native_id:
+ identity = (str(turn["id"]), persisted_native_id)
+ if identity is not None and turn["state"] != "active":
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ latest = delivery_store.get_turn(conn, str(turn["id"]))
+ if latest is None or latest["state"] not in delivery_store.TURN_OWNER_STATES:
+ return latest, None
+ bound = delivery_store.bind_native_start(
+ conn,
+ str(turn["id"]),
+ expected_version=int(latest["version"]),
+ runtime_key=latest.get("runtime_key"),
+ runtime_turn_id=latest.get("runtime_turn_id"),
+ native_turn_id=identity[1],
+ )
+ if bound is None:
+ return latest, None
+ turn = bound
+ return turn, identity
+
+ async def deliver(
+ self,
+ request: DeliveryRequest,
+ *,
+ context: Optional["MessageContext"] = None,
+ ) -> DeliveryResult:
+ """Execute the private durable P0/P1/P3 ownership state machine."""
+
+ if not request.session_id:
+ raise ValueError("Session delivery requires a Session id")
+ if request.priority not in {"p0", "p1", "p3"}:
+ raise ValueError(f"unsupported delivery priority: {request.priority}")
+ content_present = (
+ request.has_content
+ if request.has_content is not None
+ else bool(request.content)
+ )
+ if not content_present and request.content == "":
+ request = replace(request, content=None)
+ if request.priority == "p3" and not content_present:
+ raise ValueError("P3 requires content")
+ backend, resolved_context = self._delivery_backend(request.session_id, context)
+ if request.priority == "p3":
+ return await self._admit_p3(request, backend, resolved_context)
+ if request.priority == "p1":
+ return await self._admit_p1(request, backend, resolved_context)
+ return await self._admit_p0(request, backend, resolved_context)
+
+ async def _admit_p3(
+ self,
+ request: DeliveryRequest,
+ backend: str,
+ context: "MessageContext",
+ ) -> DeliveryResult:
+ turn_id: str | None = None
+ delivery_turn_id: str | None = None
+ start_context: MessageContext | None = None
+ delivery: dict[str, Any]
+ backend_draining = backend in self._draining_backends
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == request.session_id)
+ ).scalar_one_or_none()
+ if status != "active":
+ existing = (
+ delivery_store.get_delivery(conn, request.delivery_id)
+ if request.delivery_id
+ else None
+ )
+ if existing is not None and existing["state"] in {"reserved", "queued"}:
+ self._retire_delivery_not_written(
+ conn,
+ request.session_id,
+ str(existing["id"]),
+ reason="session_archived",
+ )
+ return DeliveryResult(str(existing["id"]), None, "retired")
+ raise ValueError("Session is archived")
+ delivery = self._insert_delivery(
+ conn,
+ request,
+ priority="p3",
+ state="queued",
+ )
+ if delivery["state"] not in {"queued", "reserved"}:
+ return DeliveryResult(
+ str(delivery["id"]),
+ str(delivery.get("message_id") or "") or None,
+ str(delivery["state"]),
+ str(delivery.get("turn_id") or delivery.get("current_target_turn_id") or "")
+ or None,
+ )
+ if delivery["state"] == "reserved":
+ queued = delivery_store.cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={"state": "queued"},
+ history_event={"kind": "queue", "reason": "p3_admission"},
+ )
+ if queued is None:
+ raise RuntimeError("P3 queue claim lost after writer reservation")
+ delivery = queued
+ active = delivery_store.active_turn(conn, request.session_id)
+ if active is None and not backend_draining:
+ held = delivery_store.queue_is_held(conn, request.session_id)
+ queued_payloads = delivery_store.claimable_fifo_prefix(
+ conn, request.session_id
+ )
+ held_fence = (
+ delivery_store.ordering_head(
+ conn,
+ request.session_id,
+ include_claimable=False,
+ )
+ if held
+ else None
+ )
+ if held and held_fence is not None:
+ segment_payloads = []
+ elif held:
+ segment_payloads = [delivery_store.delivery_payload(delivery)]
+ else:
+ segment_payloads = _collect_delivery_segment(queued_payloads)
+ segment = [
+ delivery_store.get_delivery(conn, str(row["id"]))
+ for row in segment_payloads
+ ]
+ if segment and all(row is not None for row in segment):
+ turn_id = delivery_store.new_turn_id()
+ claimed_batch = self._claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=request.session_id,
+ backend=backend,
+ deliveries=[row for row in segment if row is not None],
+ dispatch_text=_segment_dispatch_text(segment_payloads),
+ )
+ for claimed in claimed_batch["deliveries"]:
+ if str(claimed["id"]) == str(delivery["id"]):
+ delivery = claimed
+ delivery_turn_id = turn_id
+ if int(claimed.get("turn_position") or 0) == 0:
+ start_context = context
+ break
+ if backend_draining:
+ self._deferred_restart_sessions.setdefault(backend, set()).add(
+ request.session_id
+ )
+ if turn_id:
+ await self._start_persisted_turn(turn_id, context=start_context)
+ return self._committed_delivery_result(
+ str(delivery["id"]),
+ attempted_turn_id=turn_id,
+ )
+ return DeliveryResult(
+ str(delivery["id"]),
+ str(delivery.get("message_id") or "") or None,
+ str(delivery["state"]),
+ delivery_turn_id,
+ )
+
+ async def _admit_p1(
+ self,
+ request: DeliveryRequest,
+ backend: str,
+ context: "MessageContext",
+ ) -> DeliveryResult:
+ if request.content is None:
+ return await self._promote_fifo_head(
+ request.session_id,
+ backend,
+ context,
+ expected_delivery_id=request.expected_delivery_id,
+ )
+
+ observed, identity = self._observe_active_delivery_turn(request.session_id)
+ observed_id = str((observed or {}).get("id") or "") or None
+ attempt_id: str | None = None
+ native_id: str | None = None
+ turn_id: str | None = None
+ steer_backend = backend
+ delivery: dict[str, Any]
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == request.session_id)
+ ).scalar_one_or_none()
+ if status != "active":
+ existing = (
+ delivery_store.get_delivery(conn, request.delivery_id)
+ if request.delivery_id
+ else None
+ )
+ if existing is not None and existing["state"] == "reserved":
+ self._retire_delivery_not_written(
+ conn,
+ request.session_id,
+ str(existing["id"]),
+ reason="session_archived",
+ )
+ return DeliveryResult(str(existing["id"]), None, "retired")
+ raise ValueError("Session is archived")
+ current = delivery_store.active_turn(conn, request.session_id)
+ delivery = self._insert_delivery(
+ conn,
+ request,
+ priority="p1",
+ state="reserved",
+ )
+ if delivery["state"] != "reserved":
+ return DeliveryResult(
+ str(delivery["id"]),
+ str(delivery.get("message_id") or "") or None,
+ str(delivery["state"]),
+ str(delivery.get("current_target_turn_id") or "") or None,
+ )
+ same_active = bool(
+ current is not None
+ and observed_id
+ and str(current["id"]) == observed_id
+ and current["state"] == "active"
+ and identity is not None
+ and identity[0] == observed_id
+ )
+ if current is not None and self._delivery_has_attachment_references(delivery):
+ claimed = delivery_store.cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={"priority": "p3", "state": "queued"},
+ history_event={
+ "kind": "steer",
+ "turn_id": str(current["id"]),
+ "outcome": "attachments_require_new_turn",
+ },
+ )
+ if claimed is None:
+ raise RuntimeError("attachment P1 fallback claim lost")
+ delivery = claimed
+ elif same_active:
+ attempt_id = delivery_store.new_attempt_id()
+ native_id = str(identity[1])
+ turn_id = observed_id
+ steer_backend = str(current["backend"])
+ claimed = delivery_store.open_steer_attempt(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ expected_native_turn_id=native_id,
+ )
+ if claimed is None:
+ raise RuntimeError("P1 steer claim lost after writer reservation")
+ delivery = claimed
+ elif current is None:
+ turn_id = delivery_store.new_turn_id()
+ if observed_id:
+ delivery = delivery_store.cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={},
+ history_event={
+ "kind": "admission",
+ "turn_id": observed_id,
+ "outcome": "observed_turn_settled_before_claim",
+ },
+ ) or delivery
+ claimed_batch = self._claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=request.session_id,
+ backend=backend,
+ deliveries=[delivery],
+ dispatch_text=str(delivery.get("dispatch_text") or ""),
+ )
+ delivery = claimed_batch["deliveries"][0]
+ elif observed_id and str(current["id"]) == observed_id:
+ attempt_id = delivery_store.new_attempt_id()
+ pending_rows = delivery_store.open_pending_steer_batch(
+ conn,
+ deliveries=[delivery],
+ turn_id=str(current["id"]),
+ attempt_id=attempt_id,
+ )
+ delivery = pending_rows[0]
+ turn_id = str(current["id"])
+ else:
+ claimed = delivery_store.cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={"priority": "p3", "state": "queued"},
+ history_event={
+ "kind": "steer",
+ "turn_id": observed_id,
+ "outcome": "target_changed_before_claim",
+ "current_turn_id": str(current["id"]),
+ },
+ )
+ if claimed is None:
+ raise RuntimeError("P1 stale-target fallback claim lost")
+ delivery = claimed
+
+ if delivery["state"] == "claimed" and turn_id:
+ await self._start_persisted_turn(turn_id, context=context)
+ return self._committed_delivery_result(
+ str(delivery["id"]),
+ attempted_turn_id=turn_id,
+ )
+ elif delivery["state"] == "steering" and turn_id and attempt_id and native_id:
+ receipt = await self._attempt_steer(
+ steer_backend,
+ SteerRequest(
+ target_session_id=request.session_id,
+ expected_logical_turn_id=turn_id,
+ expected_native_turn_id=native_id,
+ text=str(delivery.get("dispatch_text") or ""),
+ attempt_id=attempt_id,
+ ),
+ )
+ return await self._finish_steer(str(delivery["id"]), receipt, context=context)
+ return DeliveryResult(str(delivery["id"]), None, str(delivery["state"]), turn_id)
+
+ async def _promote_fifo_head(
+ self,
+ session_id: str,
+ backend: str,
+ context: "MessageContext",
+ *,
+ expected_delivery_id: str | None = None,
+ ) -> DeliveryResult:
+ with self._sqlite_engine().connect() as conn:
+ observed_head = delivery_store.ordering_head(conn, session_id)
+ observed_segment_payloads = _collect_delivery_segment(
+ delivery_store.claimable_fifo_prefix(conn, session_id)
+ )
+ if observed_head is None:
+ return DeliveryResult(None, None, "empty")
+ observed_owner_id = str(observed_head["id"])
+ if expected_delivery_id and observed_owner_id != expected_delivery_id:
+ return DeliveryResult(
+ expected_delivery_id,
+ None,
+ "refused",
+ reason="stale_head",
+ )
+ if observed_head["state"] != "queued":
+ return DeliveryResult(
+ observed_owner_id,
+ None,
+ "refused",
+ reason="ordering_fence",
+ )
+ observed_turn, identity = self._observe_active_delivery_turn(session_id)
+ observed_turn_id = str((observed_turn or {}).get("id") or "") or None
+ observed_segment_ids = [str(row["id"]) for row in observed_segment_payloads]
+ if not observed_segment_ids or observed_segment_ids[0] != observed_owner_id:
+ return DeliveryResult(observed_owner_id, None, "refused", reason="stale_head")
+ delivery_id = observed_owner_id
+ turn_id: str | None = None
+ attempt_id: str | None = None
+ native_id: str | None = None
+ steer_backend = backend
+ claimed_rows: list[dict[str, Any]] = []
+ dispatch_text = _segment_dispatch_text(observed_segment_payloads)
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)
+ ).scalar_one_or_none()
+ if status != "active":
+ return DeliveryResult(observed_owner_id, None, "refused", reason="session_archived")
+ current_head = delivery_store.ordering_head(conn, session_id)
+ if (
+ current_head is None
+ or str(current_head["id"]) != observed_owner_id
+ or (
+ expected_delivery_id
+ and str(current_head["id"]) != expected_delivery_id
+ )
+ ):
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "refused",
+ reason="stale_head",
+ )
+ if current_head["state"] != "queued":
+ return DeliveryResult(delivery_id, None, "refused", reason="ordering_fence")
+ current_segment_payloads = _collect_delivery_segment(
+ delivery_store.claimable_fifo_prefix(conn, session_id)
+ )
+ if [str(row["id"]) for row in current_segment_payloads[: len(observed_segment_ids)]] != observed_segment_ids:
+ return DeliveryResult(delivery_id, None, "refused", reason="stale_head")
+ segment = [
+ delivery_store.get_delivery(conn, candidate_id)
+ for candidate_id in observed_segment_ids
+ ]
+ if any(row is None or row["state"] != "queued" for row in segment):
+ return DeliveryResult(delivery_id, None, "refused", reason="stale_head")
+ delivery_rows = [row for row in segment if row is not None]
+ current_turn = delivery_store.active_turn(conn, session_id)
+ if current_turn is None:
+ turn_id = delivery_store.new_turn_id()
+ claimed = self._claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend=backend,
+ deliveries=delivery_rows,
+ dispatch_text=dispatch_text,
+ )
+ claimed_rows = claimed["deliveries"]
+ elif any(
+ self._delivery_has_attachment_references(row)
+ for row in delivery_rows
+ ):
+ if not delivery_store.set_queue_hold(conn, session_id, held=False):
+ raise RuntimeError("attachment queue promotion lost its Session hold CAS")
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "queued",
+ str(current_turn["id"]),
+ reason="attachments_wait_for_new_turn",
+ )
+ elif (
+ observed_turn_id
+ and str(current_turn["id"]) == observed_turn_id
+ and current_turn["state"] == "active"
+ and identity is not None
+ and identity[0] == observed_turn_id
+ ):
+ turn_id = observed_turn_id
+ attempt_id = delivery_store.new_attempt_id()
+ native_id = str(identity[1])
+ steer_backend = str(current_turn["backend"])
+ claimed_rows = delivery_store.open_steer_attempt_batch(
+ conn,
+ deliveries=delivery_rows,
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ expected_native_turn_id=native_id,
+ )
+ elif observed_turn_id and str(current_turn["id"]) == observed_turn_id:
+ turn_id = str(current_turn["id"])
+ attempt_id = delivery_store.new_attempt_id()
+ claimed_rows = delivery_store.open_pending_steer_batch(
+ conn,
+ deliveries=delivery_rows,
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ )
+ else:
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "refused",
+ reason="stale_turn",
+ )
+ if not claimed_rows:
+ return DeliveryResult(delivery_id, None, "refused", reason="claim_lost")
+ if not delivery_store.set_queue_hold(conn, session_id, held=False):
+ raise RuntimeError("successful queue promotion lost its Session hold CAS")
+
+ leader = claimed_rows[0]
+ if leader["state"] == "claimed" and turn_id:
+ await self._start_persisted_turn(turn_id)
+ return self._committed_delivery_result(
+ delivery_id,
+ attempted_turn_id=turn_id,
+ )
+ elif leader["state"] == "steering" and turn_id and attempt_id and native_id:
+ receipt = await self._attempt_steer(
+ steer_backend,
+ SteerRequest(
+ target_session_id=session_id,
+ expected_logical_turn_id=turn_id,
+ expected_native_turn_id=native_id,
+ text=dispatch_text,
+ attempt_id=attempt_id,
+ ),
+ )
+ return await self._finish_steer(delivery_id, receipt, context=context)
+ return DeliveryResult(delivery_id, None, str(leader["state"]), turn_id)
+
+ async def _finish_steer(
+ self,
+ delivery_id: str,
+ receipt: Any,
+ *,
+ context: Optional["MessageContext"],
+ ) -> DeliveryResult:
+ outcome = getattr(receipt, "outcome", SteerOutcome.UNKNOWN)
+ outcome_value = str(getattr(outcome, "value", outcome))
+ body = {
+ "reason": getattr(receipt, "reason", None),
+ "details": dict(getattr(receipt, "details", {}) or {}),
+ }
+ should_drain = False
+ materialized = False
+ saved: dict[str, Any] | None = None
+ accepted_run_ids: list[str] = []
+ terminal_target: dict[str, Any] | None = None
+ session_id = ""
+ try:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ delivery = delivery_store.get_delivery(conn, delivery_id)
+ if delivery is None:
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "reconciling_steer",
+ reason="missing_delivery",
+ )
+ target_turn_id = str(delivery.get("current_target_turn_id") or "")
+ session_id = str(delivery["session_id"])
+ attempt_id = str(delivery.get("current_attempt_id") or "")
+ attempt_rows = (
+ delivery_store.attempt_deliveries(conn, attempt_id)
+ if attempt_id
+ else [delivery]
+ )
+ if outcome_value == SteerOutcome.ACCEPTED.value:
+ accepted_run_ids = list(
+ dict.fromkeys(
+ run_id
+ for row in attempt_rows
+ for run_id in delivery_store.agent_run_ids_for_delivery(conn, row)
+ )
+ )
+ accepted_rows = delivery_store.materialize_steer_acceptance(
+ conn,
+ leader_delivery_id=delivery_id,
+ expected_attempt_id=attempt_id,
+ turn_id=target_turn_id,
+ evidence={"kind": "steer_receipt", "receipt": body},
+ )
+ if not accepted_rows:
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "reconciling_steer",
+ target_turn_id or None,
+ "receipt_cas_lost",
+ )
+ saved = accepted_rows[0]
+ materialized = True
+ target_turn = delivery_store.get_turn(conn, target_turn_id)
+ if (
+ accepted_run_ids
+ and target_turn is not None
+ and target_turn["state"] == "terminal"
+ ):
+ 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
+ ]
+ saved = unknown_rows[0] if unknown_rows else None
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "reconciling_steer",
+ target_turn_id or None,
+ None if unknown_rows and all(unknown_rows) else "receipt_cas_lost",
+ )
+ if not materialized:
+ session_status = conn.execute(
+ select(agent_sessions.c.status).where(
+ agent_sessions.c.id == str(delivery["session_id"])
+ )
+ ).scalar_one_or_none()
+ next_state = "queued" if session_status == "active" else "retired"
+ fallback_rows = [
+ self._record_definitive_delivery_attempt(
+ conn,
+ str(row["id"]),
+ expected_version=int(row["version"]),
+ expected_states=(str(row["state"]),),
+ outcome=outcome_value,
+ next_state=next_state,
+ next_priority="p3",
+ receipt=body,
+ )
+ for row in attempt_rows
+ ]
+ if not fallback_rows or not all(fallback_rows):
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "reconciling_steer",
+ target_turn_id or None,
+ "fallback_cas_lost",
+ )
+ saved = fallback_rows[0]
+ should_drain = saved is not None and saved["state"] == "queued"
+ except Exception:
+ logger.exception("failed to persist steering receipt for delivery=%s", delivery_id)
+ 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"},
+ )
+ except Exception:
+ logger.exception(
+ "failed to persist unknown steer fence for delivery=%s",
+ delivery_id,
+ )
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "reconciling_steer",
+ reason="receipt_persistence_lost",
+ )
+
+ if materialized:
+ self._attach_accepted_agent_runs(
+ session_id=session_id,
+ turn_id=target_turn_id,
+ run_ids=accepted_run_ids,
+ context=context,
+ )
+ if terminal_target is not None:
+ self._settle_agent_run_ids_from_terminal_turn(
+ accepted_run_ids,
+ terminal_target,
+ )
+ self._publish_materialized_delivery(delivery_id)
+ return DeliveryResult(
+ delivery_id,
+ str((saved or {}).get("message_id") or delivery_id),
+ "accepted",
+ target_turn_id or None,
+ )
+ if should_drain:
+ await self.drain_delivery_queue(session_id)
+ return self._committed_delivery_result(
+ delivery_id,
+ )
+ return DeliveryResult(
+ delivery_id,
+ None,
+ str((saved or {}).get("state") or "reconciling_steer"),
+ None,
+ )
+
+ async def _admit_p0(
+ self,
+ request: DeliveryRequest,
+ backend: str,
+ context: "MessageContext",
+ ) -> DeliveryResult:
+ delivery_id: str | None = None
+ successor_id: str | None = None
+ interrupt_target_id: str | None = None
+ should_interrupt = False
+ joined = False
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ session_status = conn.execute(
+ select(agent_sessions.c.status).where(
+ agent_sessions.c.id == request.session_id
+ )
+ ).scalar_one_or_none()
+ current = delivery_store.active_turn(conn, request.session_id)
+ if request.content is not None and session_status != "active":
+ existing = (
+ delivery_store.get_delivery(conn, request.delivery_id)
+ if request.delivery_id
+ else None
+ )
+ if existing is not None and existing["state"] == "reserved":
+ self._retire_delivery_not_written(
+ conn,
+ request.session_id,
+ str(existing["id"]),
+ reason="session_archived",
+ )
+ return DeliveryResult(str(existing["id"]), None, "retired")
+ raise ValueError("Session is archived")
+ current_id = str((current or {}).get("id") or "") or None
+ if current is None:
+ if request.content is None:
+ observed_turn_id = str(request.expected_turn_id or "").strip()
+ if observed_turn_id:
+ observed_turn = delivery_store.get_turn(conn, observed_turn_id)
+ if (
+ observed_turn is not None
+ and observed_turn["session_id"] == request.session_id
+ and observed_turn["state"] == "terminal"
+ ):
+ delivery_store.set_queue_hold(
+ conn,
+ request.session_id,
+ held=True,
+ )
+ return DeliveryResult(None, None, "settled", reason="not_active")
+ delivery = self._insert_delivery(
+ conn,
+ request,
+ priority="p0",
+ state="reserved",
+ )
+ delivery_id = str(delivery["id"])
+ successor_id = delivery_store.new_turn_id()
+ self._claim_start_batch(
+ conn,
+ turn_id=successor_id,
+ session_id=request.session_id,
+ backend=backend,
+ deliveries=[delivery],
+ dispatch_text=str(delivery.get("dispatch_text") or ""),
+ )
+ else:
+ interrupt_target_id = current_id
+ delivery = None
+ queue_was_held = delivery_store.queue_is_held(
+ conn,
+ request.session_id,
+ )
+ control_in_progress = current.get("control_state") in {
+ "pending",
+ "interrupting",
+ "waiting_terminal",
+ "reconciling",
+ }
+ if request.content is not None:
+ delivery = self._insert_delivery(
+ conn,
+ request,
+ priority="p0",
+ state="reserved",
+ )
+ delivery_id = str(delivery["id"])
+ if delivery["state"] != "reserved":
+ return DeliveryResult(
+ delivery_id,
+ str(delivery.get("message_id") or "") or None,
+ str(delivery["state"]),
+ str(delivery.get("current_target_turn_id") or "") or None,
+ )
+ if control_in_progress:
+ joined = True
+ if request.content is None and current.get("control_mode") == "replace":
+ successor_turn_id = str(
+ current.get("control_successor_turn_id") or ""
+ )
+ successor_delivery_id = str(
+ current.get("control_successor_delivery_id") or ""
+ )
+ successor = delivery_store.get_turn(conn, successor_turn_id)
+ successor_delivery = delivery_store.get_delivery(
+ conn,
+ successor_delivery_id,
+ )
+ if (
+ successor is None
+ or successor["state"] != "waiting"
+ or successor_delivery is None
+ or successor_delivery["state"] != "interrupt_waiting"
+ ):
+ return DeliveryResult(
+ None,
+ None,
+ "refused",
+ current_id,
+ "replacement_supersede_lost",
+ )
+ terminalized = self._write_terminal_snapshot(
+ conn,
+ successor_turn_id,
+ outcome="not_written",
+ settled_by="explicit_stop",
+ evidence_kind="replacement_superseded_by_stop",
+ )
+ retired = self._record_definitive_delivery_attempt(
+ conn,
+ successor_delivery_id,
+ expected_version=int(successor_delivery["version"]),
+ expected_states=("interrupt_waiting",),
+ outcome="not_written",
+ next_state="retired",
+ receipt={"kind": "replacement_superseded_by_stop"},
+ )
+ if not terminalized.get("changed") or retired is None:
+ raise RuntimeError("replacement supersession lost")
+ delivery_store.set_queue_hold(
+ conn,
+ request.session_id,
+ held=True,
+ )
+ superseded = delivery_store.cas_turn(
+ conn,
+ current_id,
+ expected_version=int(current["version"]),
+ expected_states=(str(current["state"]),),
+ values={
+ "control_mode": "stop_only",
+ "control_successor_delivery_id": None,
+ "control_successor_turn_id": None,
+ },
+ )
+ if superseded is None:
+ raise RuntimeError("replacement control supersession lost")
+ if delivery is not None:
+ # Only the control-slot winner may replace the active Turn.
+ # A content loser remains one FIFO submission and never calls Stop.
+ queued = delivery_store.cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={"priority": "p3", "state": "queued"},
+ history_event={
+ "kind": "interrupt_join",
+ "target_turn_id": current_id,
+ "outcome": "coalesced_to_queue",
+ },
+ )
+ if queued is None:
+ raise RuntimeError("concurrent P0 loser queue claim lost")
+ else:
+ # Only an empty-P0 Stop establishes a backlog hold. A content-P0
+ # replacement preserves whatever policy already existed; its
+ # successor may bypass that policy but must not rewrite it.
+ if delivery_id is None:
+ delivery_store.set_queue_hold(
+ conn,
+ request.session_id,
+ held=True,
+ )
+ if delivery_id is not None:
+ successor_id = delivery_store.new_turn_id()
+ delivery_store.insert_turn(
+ conn,
+ turn_id=successor_id,
+ session_id=request.session_id,
+ initial_delivery_id=delivery_id,
+ state="waiting",
+ backend=backend,
+ )
+ claimed_delivery = delivery_store.cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={
+ "priority": "p0",
+ "state": "interrupt_waiting",
+ "turn_id": successor_id,
+ "turn_role": "initial",
+ "turn_position": 0,
+ },
+ history_event={
+ "kind": "interrupt_join",
+ "target_turn_id": current_id,
+ "successor_turn_id": successor_id,
+ "outcome": "control_slot_claimed",
+ },
+ )
+ if claimed_delivery is None:
+ raise RuntimeError("P0 successor reservation claim lost")
+ attempt_id = delivery_store.new_attempt_id()
+ claimed_control = delivery_store.cas_turn(
+ conn,
+ current_id,
+ expected_version=int(current["version"]),
+ expected_states=(str(current["state"]),),
+ values={
+ "control_state": (
+ "interrupting" if current["state"] == "active" else "pending"
+ ),
+ "control_mode": "replace" if delivery_id else "stop_only",
+ "control_attempt_id": attempt_id,
+ "control_expected_native_turn_id": current.get("native_turn_id"),
+ "control_receipt_outcome": None,
+ "control_receipt_json": json.dumps(
+ {"queue_hold_was_held": queue_was_held},
+ sort_keys=True,
+ ),
+ "control_successor_delivery_id": delivery_id,
+ "control_successor_turn_id": successor_id,
+ },
+ )
+ if claimed_control is None:
+ raise RuntimeError("P0 control-slot claim lost")
+ should_interrupt = current["state"] == "active"
+
+ if current is None and successor_id:
+ await self._start_persisted_turn(successor_id, context=context)
+ return self._committed_delivery_result(
+ str(delivery_id),
+ attempted_turn_id=successor_id,
+ )
+ if joined:
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "queued" if delivery_id else "interrupt_waiting",
+ interrupt_target_id,
+ "joined_existing_interrupt",
+ )
+ if not should_interrupt:
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "interrupt_waiting",
+ interrupt_target_id,
+ )
+ interrupted = await self._interrupt_durable_turn(
+ request.session_id,
+ interrupt_target_id,
+ )
+ return DeliveryResult(
+ delivery_id,
+ None,
+ str(interrupted.get("state") or "reconciling"),
+ interrupt_target_id,
+ interrupted.get("reason"),
+ )
+
+ async def _interrupt_durable_turn(
+ self,
+ session_id: str,
+ logical_turn_id: str | None,
+ ) -> dict[str, Any]:
+ turn = self.in_flight.get(session_id)
+ runtime_turn = turn
+ if (
+ turn is None
+ or not logical_turn_id
+ or turn.logical_turn_id != logical_turn_id
+ or turn.task.done()
+ ):
+ runtime_turn = None
+ stop_context = runtime_turn.context if runtime_turn is not None else None
+ unavailable_reason = "runtime_owner_unavailable"
+ if stop_context is None and logical_turn_id:
+ with self._sqlite_engine().connect() as conn:
+ durable_turn = delivery_store.get_turn(conn, logical_turn_id)
+ active_turn = delivery_store.active_turn(conn, session_id)
+ exact_owner = bool(
+ durable_turn is not None
+ and active_turn is not None
+ and str(active_turn["id"]) == logical_turn_id
+ and durable_turn["state"] == "active"
+ and str(durable_turn.get("native_turn_id") or "").strip()
+ )
+ identity = (
+ self._active_identity(
+ str(durable_turn["backend"]),
+ session_id,
+ logical_turn_id,
+ )
+ if exact_owner
+ else None
+ )
+ if identity == (
+ logical_turn_id,
+ str((durable_turn or {}).get("native_turn_id") or "").strip(),
+ ):
+ try:
+ stop_context = self._delivery_context(session_id)
+ except Exception:
+ logger.exception(
+ "failed to rebuild restored interrupt context for Session=%s",
+ session_id,
+ )
+ unavailable_reason = "runtime_context_unavailable"
+ else:
+ if stop_context.platform_specific is None:
+ stop_context.platform_specific = {}
+ stop_context.platform_specific.update(
+ {
+ "turn_token": logical_turn_id,
+ "agent_runtime_turn_key": str(
+ durable_turn.get("runtime_key") or ""
+ ),
+ "agent_runtime_turn_token": str(
+ durable_turn.get("runtime_turn_id") or ""
+ ),
+ }
+ )
+ if stop_context is None:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ durable_turn = delivery_store.get_turn(conn, str(logical_turn_id or ""))
+ if durable_turn is None:
+ return {"state": "reconciling", "reason": "turn_missing"}
+ if durable_turn.get("control_state") == "interrupting":
+ saved = delivery_store.cas_turn(
+ conn,
+ str(logical_turn_id),
+ expected_version=int(durable_turn["version"]),
+ expected_states=(str(durable_turn["state"]),),
+ values={
+ "control_state": "reconciling",
+ "control_receipt_outcome": "unknown",
+ "control_receipt_json": json.dumps(
+ {"reason": unavailable_reason},
+ sort_keys=True,
+ ),
+ },
+ )
+ if saved is None:
+ return {"state": "reconciling", "reason": "receipt_cas_lost"}
+ return {"state": "reconciling", "reason": unavailable_reason}
+ if stop_context.platform_specific is None:
+ stop_context.platform_specific = {}
+ stop_context.platform_specific["suppress_stop_no_active_notice"] = True
+ if runtime_turn is not None:
+ runtime_turn.cancel_settled_by = SETTLED_BY_STOPPED
+ stop_error = False
+ try:
+ stopped = bool(
+ await self.controller.command_handler.handle_stop(stop_context)
+ )
+ except Exception:
+ logger.exception("durable P0 interrupt failed for Session=%s", session_id)
+ stopped = False
+ stop_error = True
+ if not stopped and runtime_turn is not None:
+ runtime_turn.cancel_settled_by = None
+ terminal_proven = False
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ durable_turn = delivery_store.get_turn(conn, str(logical_turn_id or ""))
+ if durable_turn is None:
+ return {"state": "reconciling", "reason": "turn_missing"}
+ if durable_turn.get("control_state") != "interrupting":
+ return {
+ "state": str(durable_turn.get("control_state") or "reconciling"),
+ "reason": None,
+ }
+ if stopped:
+ saved = delivery_store.cas_turn(
+ conn,
+ str(logical_turn_id),
+ expected_version=int(durable_turn["version"]),
+ expected_states=(str(durable_turn["state"]),),
+ values={
+ "control_state": "waiting_terminal",
+ "control_receipt_outcome": "accepted",
+ "control_receipt_json": json.dumps(
+ {"kind": "stop_receipt"}, sort_keys=True
+ ),
+ },
+ )
+ return {
+ "state": "waiting_terminal" if saved is not None else "reconciling",
+ "reason": None if saved is not None else "receipt_cas_lost",
+ }
+ reason = str(
+ (getattr(stop_context, "platform_specific", None) or {}).get(
+ "stop_failure_reason"
+ )
+ or ""
+ )
+ definitive = not stop_error and reason in {"not_active", "refused"}
+ terminal_proven = definitive and reason == "not_active"
+ fallback_state: str | None = None
+ successor_delivery_id = str(
+ durable_turn.get("control_successor_delivery_id") or ""
+ )
+ successor_turn_id = str(
+ durable_turn.get("control_successor_turn_id") or ""
+ )
+ if definitive and not terminal_proven and successor_delivery_id and successor_turn_id:
+ successor = delivery_store.get_turn(conn, successor_turn_id)
+ successor_delivery = delivery_store.get_delivery(
+ conn,
+ successor_delivery_id,
+ )
+ if (
+ successor is not None
+ and successor["state"] == "waiting"
+ and successor_delivery is not None
+ and successor_delivery["state"] == "interrupt_waiting"
+ ):
+ terminalized = self._write_terminal_snapshot(
+ conn,
+ successor_turn_id,
+ outcome="not_written",
+ settled_by="interrupt_refused",
+ evidence_kind="definitive_stop_receipt",
+ evidence={"reason": reason},
+ )
+ queued = delivery_store.cas_delivery(
+ conn,
+ successor_delivery_id,
+ expected_version=int(successor_delivery["version"]),
+ expected_states=("interrupt_waiting",),
+ values={
+ "state": "queued",
+ "priority": "p3",
+ "turn_id": None,
+ "turn_role": None,
+ "turn_position": None,
+ },
+ history_event={
+ "kind": "interrupt_join",
+ "attempt_id": durable_turn.get("control_attempt_id"),
+ "turn_id": str(durable_turn["id"]),
+ "outcome": "refused_to_p3",
+ "receipt": {"reason": reason},
+ },
+ )
+ if not terminalized.get("changed") or queued is None:
+ raise RuntimeError("definitive P0 refusal fallback lost")
+ fallback_state = "queued"
+ if (
+ definitive
+ and not terminal_proven
+ and durable_turn.get("control_mode") == "replace"
+ ):
+ try:
+ control_context = json.loads(
+ str(durable_turn.get("control_receipt_json") or "{}")
+ )
+ except (TypeError, ValueError):
+ control_context = {}
+ delivery_store.set_queue_hold(
+ conn,
+ session_id,
+ held=bool(control_context.get("queue_hold_was_held")),
+ )
+ saved = delivery_store.cas_turn(
+ conn,
+ str(logical_turn_id),
+ expected_version=int(durable_turn["version"]),
+ expected_states=(str(durable_turn["state"]),),
+ values={
+ "control_state": (
+ "waiting_terminal"
+ if terminal_proven
+ else "refused"
+ if definitive
+ else "reconciling"
+ ),
+ "control_receipt_outcome": (
+ "not_active"
+ if terminal_proven
+ else "refused"
+ if definitive
+ else "unknown"
+ ),
+ "control_receipt_json": json.dumps(
+ {"reason": reason or "stop_error"}, sort_keys=True
+ ),
+ },
+ )
+ receipt_result = {
+ "state": fallback_state or ("refused" if definitive else "reconciling"),
+ "reason": (
+ reason
+ if definitive
+ else "stop_unknown"
+ if saved is not None
+ else "receipt_cas_lost"
+ ),
+ }
+ if terminal_proven and saved is not None:
+ terminal = self._terminalize_durable_turn(
+ str(logical_turn_id),
+ "canceled",
+ settled_by="adapter_not_active",
+ evidence_kind="stop_not_active",
+ evidence={"reason": "not_active"},
+ )
+ projected = self.in_flight.get(session_id)
+ if (
+ projected is not None
+ and projected.logical_turn_id == logical_turn_id
+ and not projected.task.done()
+ ):
+ projected.cancel_settled_by = "adapter_not_active"
+ projected.task.cancel()
+ await asyncio.gather(projected.task, return_exceptions=True)
+ if self.in_flight.get(session_id) is projected and projected is not None:
+ self.in_flight.pop(session_id, None)
+ from core.inbox_events import bus
+
+ bus.publish(
+ "turn.end",
+ _turn_event_payload(session_id, logical_turn_id),
+ )
+ successor_turn_id = terminal.get("successor_turn_id")
+ if successor_turn_id:
+ await self._start_persisted_turn(str(successor_turn_id))
+ return {
+ "state": "claimed" if successor_turn_id else "settled",
+ "reason": "not_active",
+ }
+ return receipt_result
+
+ async def _start_persisted_turn(
+ self,
+ turn_id: str,
+ *,
+ context: Optional["MessageContext"] = None,
+ ) -> bool:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ turn = delivery_store.get_turn(conn, turn_id)
+ if turn is None or turn["state"] != "starting":
+ return False
+ backend = str(turn.get("backend") or "").strip()
+ if backend in self._draining_backends:
+ self._deferred_restart_sessions.setdefault(backend, set()).add(
+ str(turn["session_id"])
+ )
+ return False
+ deliveries = delivery_store.initial_deliveries_for_turn(conn, turn_id)
+ delivery = deliveries[0] if deliveries else None
+ if (
+ delivery is None
+ or any(row["state"] != "claimed" for row in deliveries)
+ or not turn.get("start_attempt_id")
+ or not turn.get("dispatch_sha256")
+ ):
+ logger.error("durable Turn has no exact start-attempt owner: %s", turn_id)
+ return False
+ attempt_id = str(turn["start_attempt_id"])
+ try:
+ resolved = (
+ self._delivery_context(str(turn["session_id"]))
+ if self._build_context is not None
+ else context
+ )
+ if resolved is None:
+ raise RuntimeError("durable native start has no Session routing context")
+ except Exception:
+ logger.exception("durable native start failed before dispatch for Turn=%s", turn_id)
+ self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by="pre_write_failure",
+ evidence_kind="context_build_failed",
+ )
+ return False
+ archived_before_dispatch = False
+ run_terminal_before_dispatch = False
+ invalid_delivery_ids: set[str] = set()
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ latest = delivery_store.get_turn(conn, turn_id)
+ session_status = conn.execute(
+ select(agent_sessions.c.status).where(
+ agent_sessions.c.id == str(turn["session_id"])
+ )
+ ).scalar_one_or_none()
+ fresh_deliveries = delivery_store.initial_deliveries_for_turn(conn, turn_id)
+ fresh_delivery = fresh_deliveries[0] if fresh_deliveries else None
+ if (
+ latest is None
+ or latest["state"] != "starting"
+ or latest.get("start_attempt_id") != attempt_id
+ or fresh_delivery is None
+ or latest.get("initial_delivery_id") != fresh_delivery.get("id")
+ or any(row["state"] != "claimed" for row in fresh_deliveries)
+ ):
+ return False
+ turn = latest
+ deliveries = fresh_deliveries
+ delivery = fresh_delivery
+ archived_before_dispatch = session_status != "active"
+ invalid_delivery_ids = {
+ str(row["id"])
+ for row in deliveries
+ if not self._has_resolvable_delivery_input(conn, row)
+ }
+ run_ids = list(
+ dict.fromkeys(
+ run_id
+ for row in deliveries
+ for run_id in delivery_store.agent_run_ids_for_delivery(conn, row)
+ )
+ )
+ if not archived_before_dispatch and run_ids:
+ run_rows = {
+ str(row["id"]): row
+ for row in conn.execute(
+ select(
+ agent_runs.c.id,
+ agent_runs.c.status,
+ agent_runs.c.cancel_requested,
+ agent_runs.c.metadata_json,
+ ).where(agent_runs.c.id.in_(run_ids))
+ ).mappings()
+ }
+ for run_id in run_ids:
+ run_row = run_rows.get(run_id)
+ if run_row is None:
+ continue
+ run_status = normalize_run_status(run_row["status"])
+ if bool(run_row["cancel_requested"]) or run_status not in {
+ "queued",
+ "running",
+ }:
+ run_terminal_before_dispatch = True
+ if archived_before_dispatch:
+ self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by="session_archive",
+ evidence_kind="archive_won_before_native_dispatch",
+ )
+ return False
+ if run_terminal_before_dispatch:
+ terminal = self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by="agent_run_terminal",
+ evidence_kind="agent_run_terminal_before_native_dispatch",
+ )
+ if terminal.get("changed"):
+ await self._resume_post_terminal(str(turn["session_id"]))
+ return False
+ if invalid_delivery_ids:
+ logger.error(
+ "durable Turn=%s lost its resolvable input before native dispatch",
+ turn_id,
+ )
+ terminal = self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by="invalid_input",
+ evidence_kind="invalid_input_before_native_dispatch",
+ retire_unwritten_delivery_ids=invalid_delivery_ids,
+ )
+ if terminal.get("changed"):
+ self._publish_queue_update(str(turn["session_id"]))
+ await self._resume_post_terminal(str(turn["session_id"]))
+ return False
+ try:
+ delivery_payload = self._hydrate_delivery_batch_context(resolved, deliveries)
+ resolved.platform_specific["turn_token"] = turn_id
+ resolved.platform_specific["delivery_start_attempt_id"] = attempt_id
+ metadata = delivery_payload.get("metadata") or {}
+ provenance = metadata.get(SCHEDULED_PROVENANCE_KEY)
+ source = SOURCE_HUMAN
+ if isinstance(provenance, dict):
+ source = SOURCE_SCHEDULED
+ native_message_id = str(provenance.get("message_id") or "").strip()
+ resolved.message_id = native_message_id or str(delivery["id"])
+ preserved = provenance.get("platform_specific")
+ if isinstance(preserved, dict):
+ if resolved.platform_specific is None:
+ resolved.platform_specific = {}
+ resolved.platform_specific.update(
+ {
+ key: value
+ for key, value in preserved.items()
+ if key not in _EXECUTION_ROUTING_KEYS
+ }
+ )
+ else:
+ resolved.message_id = str(delivery["id"])
+ text = str(turn.get("dispatch_text") or "")
+ except Exception:
+ logger.exception(
+ "durable native start failed during pre-dispatch preparation for Turn=%s",
+ turn_id,
+ )
+ self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by="pre_write_failure",
+ evidence_kind="dispatch_preparation_failed",
+ )
+ return False
+ try:
+ await self._run(
+ str(turn["session_id"]),
+ resolved,
+ text,
+ source=source,
+ logical_turn_id=turn_id,
+ delivery_id=str((delivery or {}).get("id") or "") or None,
+ durable_preallocated=True,
+ )
+ return True
+ except Exception:
+ logger.exception("durable native start became ambiguous for Turn=%s", turn_id)
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ latest = delivery_store.get_turn(conn, turn_id)
+ if (
+ latest is not None
+ and latest["state"] == "starting"
+ and latest.get("start_attempt_id") == attempt_id
+ ):
+ delivery_store.mark_start_unknown(
+ conn,
+ expected_version=int(latest["version"]),
+ turn_id=turn_id,
+ receipt={"reason": "dispatch_may_have_written"},
+ )
+ return False
+
+ async def drain_delivery_queue(self, session_id: str) -> bool:
+ turn_id: str | None = None
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ backend = str(
+ conn.execute(
+ select(agent_sessions.c.agent_backend).where(
+ agent_sessions.c.id == session_id
+ )
+ ).scalar_one_or_none()
+ or ""
+ ).strip()
+ if not backend:
+ raise RuntimeError(f"Session {session_id} has no resolved backend")
+ if backend in self._draining_backends:
+ self._deferred_restart_sessions.setdefault(backend, set()).add(
+ session_id
+ )
+ return False
+ turn_id = self._claim_fifo_batch_in_transaction(
+ conn,
+ session_id=session_id,
+ backend=backend,
+ )
+ if turn_id is None:
+ return False
+ return await self._start_persisted_turn(turn_id)
+
+ @staticmethod
+ def _write_terminal_snapshot(
+ conn: Connection,
+ turn_id: str,
+ *,
+ outcome: str,
+ settled_by: str | None,
+ evidence_kind: str,
+ evidence: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """The only low-level terminal write; callers add reconciliation around it."""
+
+ return delivery_store.terminalize_turn(
+ conn,
+ turn_id,
+ outcome=outcome,
+ settled_by=settled_by,
+ evidence_kind=evidence_kind,
+ evidence=evidence,
+ )
+
+ def _terminalize_durable_turn(
+ self,
+ turn_id: str,
+ outcome: str,
+ *,
+ settled_by: str | None = None,
+ evidence_kind: str = "terminal_reconciliation",
+ evidence: dict[str, Any] | None = None,
+ expected_start_attempt_id: str | None = None,
+ replay_unknown_start: bool = False,
+ abandon_unaccepted_start: bool = False,
+ retire_unwritten_delivery_ids: set[str] | None = None,
+ ) -> dict[str, Any]:
+ if not self._durable_schema_available():
+ return {
+ "changed": False,
+ "successor_turn_id": None,
+ "delivery_id": None,
+ "preserve_queue": False,
+ }
+ result: dict[str, Any]
+ materialized_id: str | None = None
+ terminal_run_ids: list[str] = []
+ projected_status: str | None = None
+ status_changed = False
+ replayed_unknown_start = False
+ unknown_start_exhausted = False
+ unknown_start_run_ids: list[str] = []
+ forced_retire_ids = retire_unwritten_delivery_ids or set()
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ turn = delivery_store.get_turn(conn, turn_id)
+ if (
+ turn is None
+ or turn["state"] == "terminal"
+ or (
+ expected_start_attempt_id is not None
+ and turn.get("start_attempt_id") != expected_start_attempt_id
+ )
+ ):
+ result = {
+ "changed": False,
+ "successor_turn_id": None,
+ "delivery_id": None,
+ "preserve_queue": delivery_store.queue_is_held(
+ conn, str((turn or {}).get("session_id") or "")
+ ),
+ }
+ else:
+ if outcome not in {"completed", "failed", "canceled", "not_written"}:
+ raise ValueError(f"invalid semantic Turn outcome: {outcome}")
+ session_id = str(turn["session_id"])
+ session_status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)
+ ).scalar_one_or_none()
+ initial_batch = delivery_store.initial_deliveries_for_turn(conn, turn_id)
+ unknown_start_reconciliation = bool(
+ replay_unknown_start
+ and outcome == "failed"
+ and initial_batch
+ and all(row["state"] == "claimed" for row in initial_batch)
+ and turn.get("start_receipt_outcome") == "unknown"
+ )
+ abandoned_start = bool(
+ abandon_unaccepted_start
+ and outcome == "failed"
+ and initial_batch
+ and all(row["state"] == "claimed" for row in initial_batch)
+ and turn.get("start_receipt_outcome") != "accepted"
+ )
+ if (
+ initial_batch
+ and all(row["state"] == "claimed" for row in initial_batch)
+ and outcome != "not_written"
+ and turn.get("start_receipt_outcome") != "accepted"
+ and not unknown_start_reconciliation
+ and not abandoned_start
+ ):
+ return {
+ "changed": False,
+ "successor_turn_id": None,
+ "delivery_id": None,
+ "preserve_queue": True,
+ "reason": "start_acceptance_unproven",
+ }
+ if initial_batch and all(row["state"] == "claimed" for row in initial_batch):
+ if abandoned_start:
+ for initial in initial_batch:
+ retired = self._record_definitive_delivery_attempt(
+ conn,
+ str(initial["id"]),
+ expected_version=int(initial["version"]),
+ expected_states=("claimed",),
+ outcome="backend_refresh_failed",
+ next_state="retired",
+ receipt={"kind": evidence_kind, **(evidence or {})},
+ )
+ if retired is None:
+ raise RuntimeError(
+ "terminal settlement lost an unresolved start Delivery"
+ )
+ elif unknown_start_reconciliation:
+ run_rows = []
+ run_ids = list(
+ dict.fromkeys(
+ run_id
+ for initial in initial_batch
+ for run_id in delivery_store.agent_run_ids_for_delivery(
+ conn, initial
+ )
+ )
+ )
+ if run_ids:
+ run_rows = list(
+ conn.execute(
+ select(
+ agent_runs.c.status,
+ agent_runs.c.cancel_requested,
+ ).where(agent_runs.c.id.in_(run_ids))
+ ).mappings()
+ )
+ run_can_replay = len(run_rows) == len(run_ids) and all(
+ not bool(row["cancel_requested"])
+ and normalize_run_status(row["status"]) in {"queued", "running"}
+ for row in run_rows
+ )
+ replayed_unknown_start = bool(
+ session_status == "active"
+ and not turn.get("control_mode")
+ and run_can_replay
+ and _start_replay_count(initial_batch)
+ < _MAX_AUTOMATIC_UNKNOWN_START_REPLAYS
+ )
+ unknown_start_exhausted = not replayed_unknown_start
+ unknown_start_run_ids = run_ids
+ next_state = "queued" if replayed_unknown_start else "retired"
+ attempt_outcome = (
+ "restart_replayed"
+ if replayed_unknown_start
+ else "restart_retry_exhausted"
+ )
+ for initial in initial_batch:
+ reconciled = self._record_definitive_delivery_attempt(
+ conn,
+ str(initial["id"]),
+ expected_version=int(initial["version"]),
+ expected_states=("claimed",),
+ outcome=attempt_outcome,
+ next_state=next_state,
+ next_priority=str(initial["priority"]),
+ receipt={"kind": evidence_kind, **(evidence or {})},
+ )
+ if reconciled is None:
+ raise RuntimeError(
+ "unknown start recovery lost a Delivery batch CAS"
+ )
+ elif outcome == "not_written":
+ for initial in initial_batch:
+ retire_unwritten = str(initial["id"]) in forced_retire_ids
+ owned_run_terminal = False
+ run_ids = (
+ []
+ if retire_unwritten
+ else delivery_store.agent_run_ids_for_delivery(conn, initial)
+ )
+ if run_ids:
+ run_rows = list(
+ conn.execute(
+ select(
+ agent_runs.c.status,
+ agent_runs.c.cancel_requested,
+ ).where(
+ agent_runs.c.id.in_(run_ids)
+ )
+ ).mappings()
+ )
+ owned_run_terminal = bool(
+ run_rows
+ and all(
+ bool(row["cancel_requested"])
+ or normalize_run_status(row["status"])
+ not in {"queued", "running"}
+ for row in run_rows
+ )
+ )
+ next_state = "queued"
+ if retire_unwritten or session_status != "active" or owned_run_terminal:
+ next_state = "retired"
+ definitive = self._record_definitive_delivery_attempt(
+ conn,
+ str(initial["id"]),
+ expected_version=int(initial["version"]),
+ expected_states=("claimed",),
+ outcome=("invalid_input" if retire_unwritten else "not_written"),
+ next_state=next_state,
+ next_priority="p3",
+ receipt={"kind": evidence_kind, **(evidence or {})},
+ )
+ if definitive is None:
+ raise RuntimeError(
+ "terminal no-write evidence lost a Delivery batch CAS"
+ )
+ else:
+ accepted = delivery_store.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "terminal_proof", "outcome": outcome},
+ )
+ if not accepted:
+ raise RuntimeError(
+ "terminal evidence could not materialize initial Delivery batch"
+ )
+ materialized_id = str(accepted[0].get("message_id") or accepted[0]["id"])
+ settled = self._write_terminal_snapshot(
+ conn,
+ turn_id,
+ outcome=outcome,
+ settled_by=settled_by,
+ evidence_kind=evidence_kind,
+ evidence=evidence,
+ )
+ if not settled.get("changed"):
+ result = {
+ "changed": False,
+ "successor_turn_id": None,
+ "delivery_id": materialized_id,
+ "preserve_queue": delivery_store.queue_is_held(conn, session_id),
+ }
+ else:
+ # A never-called steer has definitive negative evidence once
+ # its exact target Turn settles. In-flight and unknown attempts
+ # remain untouched because they may already have written.
+ pending_rows = conn.execute(
+ select(delivery_store.message_deliveries).where(
+ delivery_store.message_deliveries.c.session_id == session_id,
+ delivery_store.message_deliveries.c.state == "pending_steer",
+ delivery_store.message_deliveries.c.current_target_turn_id == turn_id,
+ )
+ ).mappings()
+ for pending_row in pending_rows:
+ fallback = self._record_definitive_delivery_attempt(
+ conn,
+ str(pending_row["id"]),
+ expected_version=int(pending_row["version"]),
+ expected_states=("pending_steer",),
+ outcome="not_active",
+ next_state=("queued" if session_status == "active" else "retired"),
+ next_priority="p3",
+ receipt={"kind": "target_turn_terminal", "turn_id": turn_id},
+ )
+ if fallback is None:
+ raise RuntimeError("pending steer terminal fallback lost")
+
+ successor_turn_id = str(turn.get("control_successor_turn_id") or "")
+ successor_delivery_id = str(
+ turn.get("control_successor_delivery_id") or ""
+ )
+ claimed_successor: str | None = None
+ if (
+ successor_turn_id
+ and successor_delivery_id
+ and turn.get("control_state")
+ in {"pending", "interrupting", "waiting_terminal", "reconciling"}
+ ):
+ successor = delivery_store.get_turn(conn, successor_turn_id)
+ successor_delivery = delivery_store.get_delivery(
+ conn, successor_delivery_id
+ )
+ if (
+ successor is not None
+ and successor["state"] == "waiting"
+ and successor_delivery is not None
+ and successor_delivery["state"] == "interrupt_waiting"
+ ):
+ if session_status != "active":
+ self._write_terminal_snapshot(
+ conn,
+ successor_turn_id,
+ outcome="not_written",
+ settled_by="session_archive",
+ evidence_kind="unstarted_successor_retired",
+ )
+ retired = self._record_definitive_delivery_attempt(
+ conn,
+ successor_delivery_id,
+ expected_version=int(successor_delivery["version"]),
+ expected_states=("interrupt_waiting",),
+ outcome="not_written",
+ next_state="retired",
+ receipt={"kind": "session_archive"},
+ )
+ if retired is None:
+ raise RuntimeError("archived P0 successor retirement lost")
+ else:
+ started = delivery_store.activate_waiting_successor(
+ conn,
+ turn=successor,
+ delivery=successor_delivery,
+ )
+ if started is None:
+ raise RuntimeError(
+ "P0 successor claim lost after terminal proof"
+ )
+ claimed_successor = successor_turn_id
+ if (
+ claimed_successor is None
+ and replayed_unknown_start
+ and session_status == "active"
+ ):
+ retry_rows = [
+ delivery_store.get_delivery(conn, str(initial["id"]))
+ for initial in initial_batch
+ ]
+ if any(row is None or row["state"] != "queued" for row in retry_rows):
+ raise RuntimeError(
+ "unknown start recovery lost its replayable Delivery batch"
+ )
+ claimed_successor = delivery_store.new_turn_id()
+ self._claim_start_batch(
+ conn,
+ turn_id=claimed_successor,
+ session_id=session_id,
+ backend=str(turn["backend"]),
+ deliveries=[row for row in retry_rows if row is not None],
+ dispatch_text=(
+ _UNKNOWN_START_REPLAY_INSTRUCTION
+ + str(turn.get("dispatch_text") or "")
+ ),
+ )
+ if (
+ claimed_successor is None
+ and outcome == "completed"
+ and session_status == "active"
+ ):
+ claimed_successor = self._claim_fifo_batch_in_transaction(
+ conn,
+ session_id=session_id,
+ backend=str(turn["backend"]),
+ )
+ latest_turn = delivery_store.get_turn(conn, turn_id)
+ if latest_turn is not None and latest_turn.get("control_state") in {
+ "pending",
+ "interrupting",
+ "waiting_terminal",
+ "reconciling",
+ }:
+ delivery_store.cas_turn(
+ conn,
+ turn_id,
+ expected_version=int(latest_turn["version"]),
+ expected_states=("terminal",),
+ values={
+ "control_state": "settled",
+ "control_receipt_outcome": (
+ latest_turn.get("control_receipt_outcome") or "accepted"
+ ),
+ },
+ )
+ result = {
+ "changed": True,
+ "successor_turn_id": claimed_successor,
+ "delivery_id": materialized_id,
+ "preserve_queue": delivery_store.queue_is_held(conn, session_id),
+ "unknown_start_exhausted": unknown_start_exhausted,
+ }
+ terminal_run_ids = (
+ unknown_start_run_ids
+ if unknown_start_exhausted
+ else delivery_store.accepted_agent_run_ids_for_turn(
+ conn,
+ turn_id,
+ )
+ )
+ projected_status = (
+ "running"
+ if claimed_successor
+ else "failed"
+ if outcome == "failed"
+ else "idle"
+ )
+ projected = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .where(agent_sessions.c.agent_status != projected_status)
+ .values(agent_status=projected_status)
+ )
+ status_changed = bool(projected.rowcount)
+ if result.get("changed"):
+ run_settled_by = (
+ SETTLED_BY_NO_TERMINAL_RESULT
+ if result.get("unknown_start_exhausted")
+ else settled_by
+ )
+ self._settle_agent_run_ids(terminal_run_ids, run_settled_by)
+ if materialized_id:
+ self._publish_materialized_delivery(materialized_id)
+ if result.get("changed"):
+ self._publish_terminal_inbox_update(session_id)
+ if status_changed and projected_status is not None:
+ from core.inbox_events import bus
+
+ bus.publish(
+ "session.status",
+ {"session_id": session_id, "agent_status": projected_status},
+ )
+ return result
+
+ def reconcile_start_attempt_not_written(
+ self,
+ turn_id: str,
+ attempt_id: str,
+ *,
+ backend: str,
+ ) -> bool:
+ """Consume exact adapter proof that a persisted start never reached native."""
+
+ if not turn_id or not attempt_id:
+ return False
+ result = self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by="adapter_start_absent",
+ evidence_kind="native_start_attempt_absent",
+ evidence={"backend": backend, "attempt_id": attempt_id},
+ expected_start_attempt_id=attempt_id,
+ )
+ return bool(result.get("changed"))
+
+ def _settle_durable_prewrite_failure(
+ self,
+ turn_id: str,
+ *,
+ outcome: str,
+ ) -> dict[str, Any]:
+ """Settle definitive no-write evidence at the terminal chokepoint."""
+ return self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by=outcome,
+ evidence_kind="definitive_prewrite_failure",
+ evidence={"reason": outcome},
+ )
+
+ def _reconcile_durable_runner_release(
+ self,
+ turn_id: str,
+ *,
+ cancelled: bool,
+ failed: bool,
+ prewrite_refused: bool,
+ definitive_prewrite_exit: bool,
+ settled_by: str | None,
+ terminal_is_error: bool,
+ ) -> dict[str, Any]:
+ """Contain post-native ownership writes so runner cleanup always finishes."""
+
+ try:
+ if cancelled:
+ return self._terminalize_durable_turn(
+ turn_id,
+ "canceled",
+ settled_by=settled_by or SETTLED_BY_STOPPED,
+ evidence_kind="runner_release",
+ )
+ if failed:
+ # Dispatch may have written before raising. Preserve starting work
+ # for exact-evidence recovery instead of replaying it.
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ turn = delivery_store.get_turn(conn, turn_id)
+ if turn is not None and turn["state"] == "starting":
+ delivery_store.mark_start_unknown(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ receipt={"reason": "runner_dispatch_failure"},
+ )
+ return {}
+ if prewrite_refused:
+ return self._settle_durable_prewrite_failure(
+ turn_id,
+ outcome=SETTLED_BY_REFUSED_CONCURRENT_TURN,
+ )
+ if definitive_prewrite_exit:
+ return self._settle_durable_prewrite_failure(
+ turn_id,
+ outcome=SETTLED_BY_NO_TERMINAL_RESULT,
+ )
+ if settled_by is not None:
+ return self._terminalize_durable_turn(
+ turn_id,
+ self._durable_terminal_outcome(
+ is_error=terminal_is_error,
+ settled_by=settled_by,
+ ),
+ settled_by=settled_by,
+ evidence_kind="runner_release",
+ )
+ except Exception:
+ logger.exception(
+ "normal turn durable terminal reconciliation deferred for Turn=%s",
+ turn_id,
+ )
+ return {}
+
+ async def terminalize_turn(self, turn_id: str, *, outcome: str = "completed") -> bool:
+ result = self._terminalize_durable_turn(
+ turn_id,
+ outcome,
+ settled_by="explicit_terminalize",
+ evidence_kind="explicit_terminalize",
+ )
+ successor_id = str(result.get("successor_turn_id") or "")
+ if successor_id:
+ await self._start_persisted_turn(successor_id)
+ elif result.get("changed") and not result.get("preserve_queue"):
+ with self._sqlite_engine().connect() as conn:
+ terminal = delivery_store.get_turn(conn, turn_id)
+ if terminal is not None:
+ await self.drain_delivery_queue(str(terminal["session_id"]))
+ return bool(result.get("changed"))
+
+ async def _run_pending_interrupt(
+ self,
+ session_id: str,
+ logical_turn_id: str,
+ ) -> None:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ pending = delivery_store.pending_control_for_turn(conn, logical_turn_id)
+ if pending is None:
+ return
+ claimed = delivery_store.cas_turn(
+ conn,
+ logical_turn_id,
+ expected_version=int(pending["version"]),
+ expected_states=("active",),
+ values={"control_state": "interrupting"},
+ )
+ if claimed is not None:
+ await self._interrupt_durable_turn(session_id, logical_turn_id)
+
+ async def _run_pending_steers(
+ self,
+ session_id: str,
+ logical_turn_id: str,
+ context: "MessageContext",
+ ) -> None:
+ while True:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ turn = delivery_store.get_turn(conn, logical_turn_id)
+ if (
+ turn is None
+ or turn["session_id"] != session_id
+ or turn["state"] != "active"
+ or delivery_store.pending_control_for_turn(conn, logical_turn_id)
+ is not None
+ ):
+ return
+ native_turn_id = str(turn.get("native_turn_id") or "").strip()
+ pending = delivery_store.pending_steer_for_turn(conn, logical_turn_id)
+ if not native_turn_id or pending is None:
+ return
+ attempt_id = str(pending.get("current_attempt_id") or "")
+ pending_batch = delivery_store.attempt_deliveries(conn, attempt_id)
+ if not attempt_id or not pending_batch:
+ return
+ claimed_batch = delivery_store.open_steer_attempt_batch(
+ conn,
+ deliveries=pending_batch,
+ turn_id=logical_turn_id,
+ attempt_id=attempt_id,
+ expected_native_turn_id=native_turn_id,
+ )
+ if not claimed_batch:
+ continue
+ steer_text = "\n".join(
+ str(row.get("dispatch_text") or "")
+ for row in claimed_batch
+ if str(row.get("dispatch_text") or "")
+ )
+ backend = str(turn["backend"])
+ delivery_id = str(claimed_batch[0]["id"])
+ receipt = await self._attempt_steer(
+ backend,
+ SteerRequest(
+ target_session_id=session_id,
+ expected_logical_turn_id=logical_turn_id,
+ expected_native_turn_id=native_turn_id,
+ text=steer_text,
+ attempt_id=attempt_id,
+ ),
+ )
+ await self._finish_steer(delivery_id, receipt, context=context)
+
+ def _publish_materialized_delivery(self, delivery_id: str) -> None:
+ """Publish one accepted immutable Message after its transaction commits."""
+
+ try:
+ with self._sqlite_engine().connect() as conn:
+ row = messages_service.get_message(conn, delivery_id)
+ inbox_row = (
+ messages_service.get_inbox_session(
+ conn,
+ str(row.get("session_id") or ""),
+ platform="avibe",
+ )
+ if row is not None and row.get("session_id")
+ else None
+ )
+ if row is None:
+ return
+ from core.inbox_events import bus
+
+ bus.publish("message.new", row)
+ bus.publish(
+ "queue.updated",
+ {"session_id": row.get("session_id")},
+ )
+ bus.publish(
+ "session.activity",
+ {
+ "session_id": row.get("session_id"),
+ "scope_id": row.get("scope_id"),
+ "event": (
+ "show_event" if row.get("type") == messages_service.ANNOTATION_TYPE else "user_message"
+ ),
+ },
+ )
+ if inbox_row is not None:
+ bus.publish("inbox.session.updated", inbox_row)
+ except Exception:
+ logger.exception("accepted Delivery publish failed for %s", delivery_id)
+
+ @staticmethod
+ def _publish_queue_update(session_id: str) -> None:
+ try:
+ from core.inbox_events import bus
+
+ bus.publish("queue.updated", {"session_id": session_id})
+ except Exception:
+ logger.exception("Delivery queue update publish failed for %s", session_id)
+
+ def _publish_terminal_inbox_update(self, session_id: str) -> None:
+ """Publish the Inbox projection only after terminal ownership commits."""
+
+ try:
+ with self._sqlite_engine().connect() as conn:
+ inbox_row = messages_service.get_inbox_session(
+ conn,
+ session_id,
+ platform="avibe",
+ )
+ if inbox_row is None:
+ return
+ from core.inbox_events import bus
+
+ bus.publish("inbox.session.updated", inbox_row)
+ except Exception:
+ logger.debug(
+ "terminal Inbox projection failed for Session=%s",
+ session_id,
+ exc_info=True,
+ )
+
+ def on_native_start(
+ self,
+ context: "MessageContext",
+ *,
+ backend: str,
+ runtime_key: str,
+ runtime_turn_id: str,
+ ) -> asyncio.Task[None] | None:
+ logical_turn_id = str(
+ (getattr(context, "platform_specific", None) or {}).get("turn_token") or ""
+ ).strip()
+ session_id = self.controller._session_id_from_context(context) if self.controller else None
+ if not logical_turn_id or not session_id:
+ return
+ if not self._durable_schema_available():
+ return
+ try:
+ identity = self._active_identity(backend, session_id, logical_turn_id)
+ native_turn_id = identity[1] if identity and identity[0] == logical_turn_id else None
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ turn = delivery_store.get_turn(conn, logical_turn_id)
+ if turn is None or turn["session_id"] != session_id:
+ return
+ bound = delivery_store.bind_native_start(
+ conn,
+ logical_turn_id,
+ expected_version=int(turn["version"]),
+ runtime_key=runtime_key,
+ runtime_turn_id=runtime_turn_id,
+ native_turn_id=native_turn_id,
+ )
+ materialized: list[dict[str, Any]] = []
+ if bound is not None:
+ materialized = delivery_store.materialize_start_acceptance(
+ conn,
+ turn_id=logical_turn_id,
+ evidence={
+ "kind": "native_start",
+ "runtime_key": runtime_key,
+ "runtime_turn_id": runtime_turn_id,
+ "native_turn_id": native_turn_id,
+ },
+ )
+ if not materialized:
+ raise RuntimeError("native start could not materialize initial Delivery batch")
+ has_pending_interrupt = bool(
+ bound is not None
+ and delivery_store.pending_control_for_turn(conn, logical_turn_id)
+ )
+ has_pending_steer = bool(
+ bound is not None
+ and native_turn_id
+ and not has_pending_interrupt
+ and delivery_store.pending_steer_for_turn(conn, logical_turn_id)
+ )
+ except Exception:
+ logger.exception(
+ "durable native start binding deferred to reconciliation for Turn=%s",
+ logical_turn_id,
+ )
+ return None
+ if materialized:
+ self._publish_materialized_delivery(
+ str(materialized[0].get("message_id") or materialized[0]["id"])
+ )
+ if has_pending_interrupt:
+ return asyncio.create_task(
+ self._run_pending_interrupt(session_id, logical_turn_id),
+ name=f"durable-interrupt:{session_id}",
+ )
+ if has_pending_steer:
+ return asyncio.create_task(
+ self._run_pending_steers(session_id, logical_turn_id, context),
+ name=f"durable-steer:{session_id}",
+ )
+ return None
+
+ async def _resume_after_native_terminal(
+ self,
+ session_id: str,
+ logical_turn_id: str,
+ ) -> None:
+ try:
+ current = self.in_flight.get(session_id)
+ if current is not None and current.logical_turn_id == logical_turn_id:
+ await asyncio.gather(current.task, return_exceptions=True)
+ await self._resume_post_terminal(session_id)
+ except Exception:
+ logger.exception(
+ "failed to resume durable Session after native terminal: %s",
+ session_id,
+ )
+
+ def on_native_terminal(
+ self,
+ context: "MessageContext",
+ *,
+ outcome: str,
+ ) -> asyncio.Task[None] | None:
+ payload = getattr(context, "platform_specific", None) or {}
+ logical_turn_id = str(payload.get("turn_token") or "").strip()
+ runtime_turn_id = str(payload.get("agent_runtime_turn_token") or "").strip()
+ if not logical_turn_id:
+ return None
+ if not self._durable_schema_available():
+ return None
+ if outcome == "terminal":
+ get_sink = getattr(self.controller, "get_turn_sink", None)
+ get_key = getattr(self.controller, "_get_session_key", None)
+ if callable(get_sink) and callable(get_key):
+ try:
+ sink = get_sink(get_key(context))
+ except Exception:
+ logger.debug("failed to inspect native terminal Turn sink", exc_info=True)
+ else:
+ if (
+ isinstance(sink, dict)
+ and sink.get("done_event") is not None
+ and str(sink.get("turn_token") or "") == logical_turn_id
+ ):
+ # The result hook captured this exact sink before output
+ # delivery. Its waiter owns the authoritative completed /
+ # failed / canceled outcome after sink settlement.
+ return None
+ with self._sqlite_engine().connect() as conn:
+ turn = delivery_store.get_turn(conn, logical_turn_id)
+ if turn is None or turn["state"] not in delivery_store.TURN_OWNER_STATES:
+ return None
+ expected_runtime_id = str(turn.get("runtime_turn_id") or "").strip()
+ if expected_runtime_id and runtime_turn_id != expected_runtime_id:
+ return None
+ session_id = str(turn["session_id"])
+ semantic_outcome = outcome if outcome in {
+ "completed",
+ "failed",
+ "canceled",
+ "not_written",
+ } else "completed"
+ result = self._terminalize_durable_turn(
+ logical_turn_id,
+ semantic_outcome,
+ settled_by="native_terminal",
+ evidence_kind="native_terminal",
+ evidence={"reported_outcome": outcome},
+ )
+ current = self.in_flight.get(session_id)
+ should_resume = bool(result.get("successor_turn_id")) or (
+ current is None and not bool(result.get("preserve_queue"))
+ )
+ if result.get("changed") and should_resume:
+ return asyncio.create_task(
+ self._resume_after_native_terminal(session_id, logical_turn_id),
+ name=f"durable-terminal-resume:{session_id}",
+ )
+ return None
+
+ async def recover_durable_delivery_state(
+ self,
+ session_id: str | None = None,
+ *,
+ service_restart: bool = False,
+ ) -> list[str]:
+ """Restore exact owners after backend restore, then project status.
+
+ ``service_restart`` is the proof that process-bound Claude/Codex runtimes
+ cannot still be executing in another live controller recovery pass.
+ """
+
+ with self._sqlite_engine().connect() as conn:
+ turns = delivery_store.recovery_turns(conn, session_id)
+ pending_interrupts: list[tuple[str, str]] = []
+ pending_steers: list[tuple[str, str]] = []
+ unresolved_starts: list[tuple[str, str, str]] = []
+ lost_active_turns: list[tuple[str, str, str, str]] = []
+ recovered: list[str] = []
+ materialized_ids: set[str] = set()
+ for turn in turns:
+ turn_id = str(turn["id"])
+ target_session = str(turn["session_id"])
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ latest = delivery_store.get_turn(conn, turn_id)
+ terminal_stop_receipt = bool(
+ latest is not None
+ and latest["state"] in delivery_store.TURN_OWNER_STATES
+ and latest.get("control_receipt_outcome") == "not_active"
+ )
+ if terminal_stop_receipt:
+ terminal = self._terminalize_durable_turn(
+ turn_id,
+ "canceled",
+ settled_by="adapter_not_active",
+ evidence_kind="stop_not_active",
+ evidence={"reason": "not_active", "source": "recovery"},
+ )
+ recovered.append(target_session)
+ projected = self.in_flight.get(target_session)
+ if (
+ projected is not None
+ and projected.logical_turn_id == turn_id
+ and not projected.task.done()
+ ):
+ projected.cancel_settled_by = "adapter_not_active"
+ projected.task.cancel()
+ await asyncio.gather(projected.task, return_exceptions=True)
+ if self.in_flight.get(target_session) is projected:
+ self.in_flight.pop(target_session, None)
+ successor_turn_id = str(terminal.get("successor_turn_id") or "")
+ if successor_turn_id:
+ await self._start_persisted_turn(successor_turn_id)
+ continue
+ identity = self._active_identity(
+ str(turn["backend"]),
+ target_session,
+ turn_id,
+ )
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ latest = delivery_store.get_turn(conn, turn_id)
+ if latest is None or latest["state"] not in delivery_store.TURN_OWNER_STATES:
+ continue
+ if turn["state"] == "waiting" and latest["state"] == "starting":
+ # This successor was activated by an earlier reconciliation in
+ # this same pass. Its native start is live now, not crash residue.
+ continue
+ if identity and identity[0] == turn_id:
+ bound = delivery_store.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(latest["version"]),
+ runtime_key=latest.get("runtime_key"),
+ runtime_turn_id=latest.get("runtime_turn_id"),
+ native_turn_id=identity[1],
+ )
+ if (
+ bound is None
+ and latest["state"] == "active"
+ and latest.get("start_receipt_outcome") == "accepted"
+ and str(latest.get("backend") or "") == "opencode"
+ and _same_opencode_native_session(
+ latest.get("native_turn_id"),
+ identity[1],
+ )
+ ):
+ bound = delivery_store.rebind_restored_native_generation(
+ conn,
+ turn_id,
+ expected_version=int(latest["version"]),
+ expected_native_turn_id=str(latest["native_turn_id"]),
+ restored_native_turn_id=identity[1],
+ )
+ if bound is not None:
+ initial_batch = delivery_store.initial_deliveries_for_turn(
+ conn, turn_id
+ )
+ if initial_batch and all(
+ delivery["state"] == "claimed"
+ for delivery in initial_batch
+ ):
+ materialized = delivery_store.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "restored_native_identity", "native_turn_id": identity[1]},
+ )
+ if materialized:
+ materialized_ids.add(
+ str(
+ materialized[0].get("message_id")
+ or materialized[0]["id"]
+ )
+ )
+ recovered.append(target_session)
+ if delivery_store.pending_control_for_turn(conn, turn_id):
+ pending_interrupts.append((target_session, turn_id))
+ elif identity[1] and delivery_store.pending_steer_for_turn(
+ conn,
+ turn_id,
+ ):
+ pending_steers.append((target_session, turn_id))
+ continue
+ delivery = delivery_store.delivery_for_turn(conn, turn_id)
+ if delivery is None:
+ raise RuntimeError(f"durable Turn {turn_id} lost its initial Delivery")
+ if latest["state"] == "starting" and latest.get(
+ "start_receipt_outcome"
+ ) is None:
+ latest = delivery_store.mark_start_unknown(
+ conn,
+ turn_id,
+ expected_version=int(latest["version"]),
+ receipt={"reason": "restart_without_native_evidence"},
+ )
+ if (
+ latest is not None
+ and latest["state"] == "starting"
+ and latest.get("start_receipt_outcome") == "unknown"
+ and str(latest.get("backend") or "")
+ in _NON_RESTORABLE_RUNTIME_BACKENDS
+ ):
+ unresolved_starts.append(
+ (
+ target_session,
+ turn_id,
+ str(latest.get("start_attempt_id") or ""),
+ )
+ )
+ elif (
+ latest is not None
+ and latest["state"] == "active"
+ and latest.get("start_receipt_outcome") == "accepted"
+ and service_restart
+ and str(latest.get("backend") or "")
+ in _NON_RESTORABLE_RUNTIME_BACKENDS
+ ):
+ lost_active_turns.append(
+ (
+ target_session,
+ turn_id,
+ str(latest.get("start_attempt_id") or ""),
+ str(latest.get("backend") or ""),
+ )
+ )
+
+ for target_session, turn_id, attempt_id, backend in lost_active_turns:
+ terminal = self._terminalize_durable_turn(
+ turn_id,
+ "failed",
+ settled_by=SETTLED_BY_NO_TERMINAL_RESULT,
+ evidence_kind="restart_runtime_missing",
+ evidence={
+ "backend": backend,
+ "reason": "accepted_turn_runtime_not_restorable",
+ },
+ expected_start_attempt_id=attempt_id,
+ )
+ if not terminal.get("changed"):
+ continue
+ recovered.append(target_session)
+ successor_turn_id = str(terminal.get("successor_turn_id") or "")
+ if successor_turn_id:
+ await self._start_persisted_turn(successor_turn_id)
+
+ for target_session, turn_id, attempt_id in unresolved_starts:
+ terminal = self._terminalize_durable_turn(
+ turn_id,
+ "failed",
+ settled_by="restart_unknown_start",
+ evidence_kind="restart_unknown_start",
+ evidence={
+ "reason": "native_start_acceptance_unrecoverable",
+ "automatic_replay_limit": _MAX_AUTOMATIC_UNKNOWN_START_REPLAYS,
+ },
+ expected_start_attempt_id=attempt_id,
+ replay_unknown_start=True,
+ )
+ if not terminal.get("changed"):
+ continue
+ recovered.append(target_session)
+ retry_turn_id = str(terminal.get("successor_turn_id") or "")
+ if retry_turn_id:
+ await self._start_persisted_turn(retry_turn_id)
+
+ with self._sqlite_engine().connect() as conn:
+ unresolved = delivery_store.unresolved_deliveries(conn, session_id)
+ steer_attempts: list[tuple[dict[str, Any], str]] = []
+ seen_attempt_ids: set[str] = set()
+ for attempt in unresolved:
+ if attempt["state"] not in {"steering", "reconciling_steer"}:
+ continue
+ attempt_id = str(attempt.get("current_attempt_id") or "")
+ target_turn_id = str(attempt.get("current_target_turn_id") or "")
+ expected_native_id = str(
+ attempt.get("current_expected_native_turn_id") or ""
+ )
+ if (
+ 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)
+ steer_attempts.append((attempt, str(target_turn["backend"])))
+
+ for attempt, backend in steer_attempts:
+ attempt_id = str(attempt["current_attempt_id"])
+ target_turn_id = str(attempt["current_target_turn_id"])
+ receipt = await self._reconcile_steer_attempt(
+ backend,
+ SteerReconcileRequest(
+ target_session_id=str(attempt["session_id"]),
+ expected_logical_turn_id=target_turn_id,
+ expected_native_turn_id=str(
+ attempt["current_expected_native_turn_id"]
+ ),
+ attempt_id=attempt_id,
+ ),
+ )
+ outcome = getattr(receipt, "outcome", SteerOutcome.UNKNOWN)
+ if (
+ str(getattr(outcome, "value", outcome)) == SteerOutcome.UNKNOWN.value
+ and attempt["state"] == "reconciling_steer"
+ ):
+ continue
+ result = await self._finish_steer(
+ str(attempt["id"]),
+ receipt,
+ context=None,
+ )
+ if result.state != "reconciling_steer":
+ recovered.append(str(attempt["session_id"]))
+
+ for target_session, turn_id in pending_interrupts:
+ await self._run_pending_interrupt(target_session, turn_id)
+ for target_session, turn_id in pending_steers:
+ await self._run_pending_steers(
+ target_session,
+ turn_id,
+ self._delivery_context(target_session),
+ )
+ # Reservations are definitive pre-write admissions left between the UI /
+ # Harness transaction and controller claim. Re-enter the same manager path
+ # after adapter restoration; its writer CAS makes concurrent recovery and
+ # a late original dispatch idempotent.
+ with self._sqlite_engine().connect() as conn:
+ reservations = delivery_store.recoverable_reservations(conn, session_id)
+ for reservation in reservations:
+ target_session = str(reservation["session_id"])
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ latest = delivery_store.get_delivery(conn, str(reservation["id"]))
+ if latest is None or latest["state"] != "reserved":
+ continue
+ retired = False
+ if not self._has_resolvable_delivery_input(conn, latest):
+ retired = delivery_store.retire_reserved(
+ conn,
+ target_session,
+ str(latest["id"]),
+ reason="empty_or_invalid_reserved_submission",
+ )
+ if retired:
+ retired_delivery = delivery_store.get_delivery(
+ conn,
+ str(latest["id"]),
+ )
+ self._cancel_runs_for_retired_delivery(conn, retired_delivery)
+ else:
+ reservation = latest
+ if retired:
+ logger.warning(
+ "retired reserved Delivery=%s because it has no resolvable input",
+ reservation["id"],
+ )
+ recovered.append(target_session)
+ continue
+ try:
+ context = self._delivery_context(target_session)
+ self._hydrate_delivery_context(context, reservation)
+ result = await self.deliver(
+ self._request_from_delivery(
+ reservation,
+ has_attachments=bool(context.files),
+ ),
+ context=context,
+ )
+ except Exception:
+ logger.exception(
+ "failed to recover reserved Delivery=%s",
+ reservation["id"],
+ )
+ else:
+ if result.state != "reserved":
+ recovered.append(target_session)
+ with self._sqlite_engine().connect() as conn:
+ terminal_run_owners = delivery_store.terminal_turn_agent_run_owners(
+ conn,
+ session_id,
+ )
+ all_run_ids = {
+ run_id
+ for _terminal_turn, run_ids in terminal_run_owners
+ for run_id in run_ids
+ }
+ statuses = {
+ str(row["id"]): normalize_run_status(row["status"])
+ for row in conn.execute(
+ select(agent_runs.c.id, agent_runs.c.status).where(
+ agent_runs.c.id.in_(all_run_ids)
+ )
+ ).mappings()
+ }
+ unsettled_owners: list[tuple[dict[str, Any], list[str]]] = []
+ for terminal_turn, run_ids in terminal_run_owners:
+ unsettled = [
+ run_id
+ for run_id in run_ids
+ if statuses.get(run_id) in {"queued", "running"}
+ ]
+ if unsettled:
+ unsettled_owners.append((terminal_turn, unsettled))
+ for terminal_turn, run_ids in unsettled_owners:
+ self._settle_agent_run_ids_from_terminal_turn(run_ids, terminal_turn)
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ queued_without_owner = set(
+ delivery_store.queued_session_ids_without_live_turns(conn, session_id)
+ )
+ for target_session in sorted(queued_without_owner):
+ await self._resume_post_terminal(target_session)
+ for delivery_id in sorted(materialized_ids):
+ self._publish_materialized_delivery(delivery_id)
+ self.project_durable_agent_status()
+ return sorted(set(recovered))
+
+ def project_durable_agent_status(self) -> None:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ live = delivery_store.session_ids_with_live_turns(conn)
+ owned = delivery_store.session_ids_with_turn_history(conn)
+ idle = owned - live
+ if idle:
+ cleared = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id.in_(idle))
+ .where(agent_sessions.c.status == "active")
+ .where(agent_sessions.c.agent_status == "running")
+ .values(agent_status="idle")
+ )
+ _ = cleared.rowcount
+ if live:
+ running = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id.in_(live))
+ .where(agent_sessions.c.status == "active")
+ .where(agent_sessions.c.agent_status != "running")
+ .values(agent_status="running")
+ )
+ _ = running.rowcount
+
+ async def _resume_durable_session(self, session_id: str) -> None:
+ with self._sqlite_engine().connect() as conn:
+ owner = delivery_store.active_turn(conn, session_id)
+ if owner is None:
+ await self.drain_delivery_queue(session_id)
+ elif owner["state"] == "starting":
+ await self._start_persisted_turn(str(owner["id"]))
+
+ async def _resume_post_terminal(self, session_id: str) -> None:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ owner = delivery_store.active_turn(conn, session_id)
+ if owner is not None:
+ await self._resume_durable_session(session_id)
+ else:
+ await self.drain_delivery_queue(session_id)
+
+ def _turn_has_terminal_run(self, turn_id: str) -> bool:
+ with self._sqlite_engine().connect() as conn:
+ deliveries = delivery_store.initial_deliveries_for_turn(conn, turn_id)
+ run_ids = list(
+ dict.fromkeys(
+ run_id
+ for delivery in deliveries
+ for run_id in delivery_store.agent_run_ids_for_delivery(
+ conn, delivery
+ )
+ )
+ )
+ if not run_ids:
+ return False
+ statuses = {
+ str(row["id"]): normalize_run_status(row["status"])
+ for row in conn.execute(
+ select(agent_runs.c.id, agent_runs.c.status).where(
+ agent_runs.c.id.in_(run_ids)
+ )
+ ).mappings()
+ }
+ return any(
+ statuses.get(run_id) not in {"queued", "running"}
+ for run_id in run_ids
+ )
+
+ async def submit(
+ self,
+ session_id: Optional[str],
+ context: "MessageContext",
+ text: str,
+ *,
+ source: str = SOURCE_HUMAN,
+ delivery_intent: Literal["queue", "send_now"] = "queue",
+ ) -> TurnSubmissionResult:
+ """Admit one caller through the durable Delivery owner."""
+ if delivery_intent not in {"queue", "send_now"}:
+ raise ValueError(f"unsupported delivery intent: {delivery_intent}")
+ if not (isinstance(session_id, str) and session_id):
+ # No session key (CLI-style) — just run; nothing to queue against.
+ await self._run(None, context, text, source=source)
+ return TurnSubmissionResult(
+ route="ran",
+ delivery_status="ran" if delivery_intent == "send_now" else None,
+ )
+
+ spec = dict(getattr(context, "platform_specific", None) or {})
+ with self._sqlite_engine().connect() as conn:
+ busy = delivery_store.active_turn(conn, session_id) is not None
+ source_value = "harness" if source == SOURCE_SCHEDULED else "user"
+ delivery_id = str(spec.get("delivery_id") or "").strip() or None
+ native_message_id = str(spec.get("native_message_id") or "").strip() or None
+ if native_message_id is None and source == SOURCE_SCHEDULED:
+ native_message_id = str(getattr(context, "message_id", None) or "").strip() or None
+ if delivery_id is None:
+ candidate = str(getattr(context, "message_id", None) or "").strip()
+ if candidate.startswith("msg_"):
+ delivery_id = candidate
+ request = DeliveryRequest(
+ session_id=session_id,
+ priority="p0" if delivery_intent == "send_now" else "p3",
+ content=text,
+ has_content=delivery_store.has_substantive_input(
+ text,
+ has_attachments=bool(getattr(context, "files", None)),
+ ),
+ delivery_id=delivery_id,
+ scope_id=str(spec.get("scope_id") or "").strip() or None,
+ platform="avibe",
+ source=source_value,
+ author="harness" if source == SOURCE_SCHEDULED else "user",
+ message_type="harness" if source == SOURCE_SCHEDULED else "user",
+ display_text=str(spec.get("display_text") or text),
+ content_json=spec.get("message_content") if isinstance(spec.get("message_content"), dict) else None,
+ metadata=spec.get("message_metadata") if isinstance(spec.get("message_metadata"), dict) else {},
+ author_id=str(spec.get("author_id") or "").strip() or None,
+ author_name=str(spec.get("author_name") or "").strip() or None,
+ native_message_id=native_message_id,
+ )
+ result = await self.deliver(request, context=context)
+ enqueued_states = {
+ "queued",
+ "pending_steer",
+ "steering",
+ "reconciling_steer",
+ "interrupt_waiting",
+ }
+ enqueued = result.state in enqueued_states
+ if enqueued:
+ from core.inbox_events import bus
+
+ bus.publish("queue.updated", {"session_id": session_id})
+ return TurnSubmissionResult(
+ route="enqueued" if enqueued else "ran",
+ queue_persisted=True,
+ target_was_busy=busy,
+ delivery_status=result.state if delivery_intent == "send_now" else None,
+ )
+
+ async def _run(
+ self,
+ session_id: Optional[str],
+ context: "MessageContext",
+ text: str,
+ *,
+ source: str = SOURCE_HUMAN,
+ logical_turn_id: str | None = None,
+ delivery_id: str | None = None,
+ durable_preallocated: bool = False,
+ ) -> None:
+ """Start a fire-and-forget turn and HOLD it open until it settles.
+
+ A no-op chunk sink keeps ``dispatch_turn`` alive for the turn's lifetime so
+ ``in_flight`` stays populated (Stop works) and the session-level
+ ``turn.start`` / ``turn.end`` lifecycle is published for the browser's
+ working indicator. On NATURAL completion the queue is flushed: messages the
+ user sent while this turn ran are merged + run as the next turn when the
+ durable Session hold is open. Stop and replacement policy lives in that
+ hold plus the durable Turn control slot, not on this process task.
``source`` selects the human vs. scheduler turn path in ``dispatch_turn``;
a scheduled / watch run passes ``SOURCE_SCHEDULED`` so it goes through the
@@ -1161,9 +4161,25 @@ class SessionTurnManager:
"""
from core.inbox_events import bus
+ durable_turn_registered = durable_preallocated
+ if durable_preallocated and not logical_turn_id:
+ raise ValueError("preallocated durable Turn requires its logical id")
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ context_turn_id = str(context.platform_specific.get("turn_token") or "").strip()
+ if isinstance(session_id, str) and session_id:
+ if self._durable_schema_available() and not durable_preallocated:
+ raise RuntimeError("Session native dispatch requires a preallocated Delivery Turn")
+ logical_turn_id = logical_turn_id or context_turn_id or uuid.uuid4().hex
+ else:
+ logical_turn_id = logical_turn_id or context_turn_id or uuid.uuid4().hex
+ context.platform_specific["turn_token"] = logical_turn_id
+
async def _runner() -> None:
cancelled = False
failed = False
+ prewrite_refused = False
+ definitive_prewrite_exit = False
# How this turn's waiter was released, in the ``core.run_settlement``
# vocabulary. Anything other than a real terminal result means no result
# is coming, so an ``agent_runs`` row this turn owns has to be settled
@@ -1171,6 +4187,19 @@ class SessionTurnManager:
# turn ends, so nobody downstream can do it (Codex P1).
settled_by: Optional[str] = None
try:
+ if (
+ durable_turn_registered
+ and logical_turn_id
+ and self._turn_has_terminal_run(logical_turn_id)
+ ):
+ prewrite_refused = True
+ self._terminalize_durable_turn(
+ logical_turn_id,
+ "not_written",
+ settled_by="terminal_run",
+ evidence_kind="terminal_run_before_native_dispatch",
+ )
+ return
outcome = await dispatch_turn_with_outcome(
self.controller,
context,
@@ -1187,6 +4216,7 @@ class SessionTurnManager:
on_chunk=self._noop_chunk,
)
settled_by = outcome.settled_by
+ definitive_prewrite_exit = outcome.backend_dispatch_attempted is False
except asyncio.CancelledError:
cancelled = True
# Do NOT decide the reason here: the canceller knows it, and it is
@@ -1196,23 +4226,42 @@ class SessionTurnManager:
# value so it is not misreported as a user stop (Codex P1).
raise
except Exception:
- # dispatch_turn raised before any backend turn was actually
- # dispatched (missing/disabled backend, synchronous setup error).
- # No agent reply was produced, so this is a terminal FAILURE — it must
- # NOT auto-flush the send-while-busy queue onto a fresh turn (Codex
- # P2). (An explicit send-now flush_on_cancel still flushes.)
- failed = True
+ # Preserve the exact boundary phase even when the handler's own
+ # terminal-error persistence raises. A proven pre-write failure is
+ # safe to requeue; anything at or beyond adapter entry is logged and
+ # retained as an unknown start instead of guessing that it was absent.
+ definitive_prewrite_exit = backend_dispatch_attempted(context) is False
+ failed = not definitive_prewrite_exit
settled_by = SETTLED_BY_NO_TERMINAL_RESULT
logger.exception("internal async dispatch failed for session=%s", session_id)
finally:
if isinstance(session_id, str):
+ durable_terminal_result: dict[str, Any] = {}
+ prewrite_refused = prewrite_refused or (
+ settled_by == SETTLED_BY_REFUSED_CONCURRENT_TURN
+ )
# The turn is over — the agent emitted its terminal result, the
# user stopped it, or dispatch raised before any backend turn.
# NO turn-duration timeout: the slot is freed only by a real
# terminal signal here (Phase 1a — STUCK/sentinel removed).
- turn = self.in_flight.pop(session_id, None)
+ current = self.in_flight.get(session_id)
+ turn = (
+ current
+ if current is not None
+ and current.task is asyncio.current_task()
+ and current.logical_turn_id == logical_turn_id
+ else None
+ )
+ terminal_is_error = bool(
+ turn is not None and turn.terminal_is_error
+ )
+ if turn is not None:
+ self.in_flight.pop(session_id, None)
if turn is not None:
- bus.publish("turn.end", {"session_id": session_id})
+ bus.publish(
+ "turn.end",
+ _turn_event_payload(session_id, logical_turn_id),
+ )
if cancelled:
# Attribute the cancellation to whoever caused it. The Turn
# carries the cause when the canceller had a more specific one
@@ -1223,37 +4272,66 @@ class SessionTurnManager:
getattr(turn, "cancel_settled_by", None) if turn is not None else None
) or SETTLED_BY_STOPPED
self._settle_model_hub_turn(context, settled_by)
- # Converge the no-terminal-result outcome onto the OUTBOUND status
- # chokepoint. The normal path already emitted a terminal result;
- # only ``failed`` reaches here without one: dispatch raised before
- # any backend turn (missing/disabled backend) → empty error result
- # → dot red. This is a real terminal FAILURE, not a timeout.
- if failed:
- await self.controller.emit_agent_message(
- context,
- "result",
- "",
- is_error=True,
- output=terminal_turn_output(),
+ if logical_turn_id and durable_turn_registered:
+ durable_terminal_result = self._reconcile_durable_runner_release(
+ logical_turn_id,
+ cancelled=cancelled,
+ failed=failed,
+ prewrite_refused=prewrite_refused,
+ definitive_prewrite_exit=definitive_prewrite_exit,
+ settled_by=settled_by,
+ terminal_is_error=terminal_is_error,
)
+ # Only definitive pre-write failure may synthesize an empty
+ # terminal result. Once native work may have produced output, a
+ # persistence failure leaves the durable Turn unresolved for
+ # exact reconciliation; an empty fallback would overwrite that
+ # evidence with a fabricated terminal response.
+ if definitive_prewrite_exit:
+ try:
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ is_error=True,
+ output=terminal_turn_output(),
+ )
+ except Exception:
+ logger.exception(
+ "failed to persist terminal dispatch error for session=%s",
+ session_id,
+ )
# Settle before flushing: the next turn must not start while a run
# this one owned is still ``running``. Placed after the failure
# emit above so the honest outbound terminal writes first and this
# guarded write degrades to a no-op.
self._settle_turn_owned_agent_runs(context, settled_by)
- # Flush intents ride on the popped Turn (set by cancel / send_now),
- # so they retire with it — no parallel set to discard. Don't flush
- # after a plain Stop (keep the queue) or a terminal failure; send-now
- # still forces a flush via flush_on_cancel.
+ # Durable Session policy is the only backlog authority. Legacy
+ # non-DB turns conservatively avoid draining after Stop/failure.
+ preserve_durable_queue = bool(
+ durable_turn_registered
+ and durable_terminal_result.get("preserve_queue")
+ )
should_flush = (
- (not cancelled and not failed and not (turn is not None and turn.stop_no_flush))
- or (turn is not None and turn.flush_on_cancel)
+ not preserve_durable_queue
+ and not cancelled
+ and not failed
+ and not prewrite_refused
+ and not definitive_prewrite_exit
+ and settled_by != SETTLED_BY_STOPPED
)
backend = self._context_backend(context)
if should_flush and backend in self._draining_backends:
self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)
elif should_flush:
- await self.flush_queue(session_id)
+ if durable_turn_registered:
+ await self._resume_post_terminal(session_id)
+ else:
+ await self.flush_queue(session_id)
+ elif durable_turn_registered and durable_terminal_result.get(
+ "successor_turn_id"
+ ):
+ await self._resume_durable_session(session_id)
task = asyncio.create_task(_runner(), name="internal-dispatch-async")
if isinstance(session_id, str) and session_id:
@@ -1261,6 +4339,8 @@ class SessionTurnManager:
task=task,
context=context,
started_at=_utc_now_iso(),
+ logical_turn_id=logical_turn_id,
+ delivery_id=delivery_id,
)
# Make the DB row authoritative at ACCEPTANCE, not at dispatch start:
# ``update_session``'s backend lock re-checks ``agent_status`` inside
@@ -1270,297 +4350,63 @@ class SessionTurnManager:
# read idle (and would then be silently undone by the bind-time
# backfill). The inbound chokepoint's own ``running`` write becomes a
# no-op; every terminal path still settles the status (outbound
- # chokepoint / cancel / startup recovery).
- self.controller.set_agent_status(session_id, "running")
- bus.publish("turn.start", {"session_id": session_id})
-
- async def flush_queue(self, session_id: str) -> bool:
- """Drain the send-while-busy queue ONE segment per call — the turn's
- completion re-flushes the next, so segments run in order, one at a time.
-
- A leading run of anonymous USER rows is merged into one user turn (the
- user's choice — one dispatch, not N). A row with ``native_message_id`` is
- already an independently addressable event and therefore runs as its own
- segment. A SCHEDULED row (it carries stored provenance) is NOT merged: it
- runs as its OWN ``SOURCE_SCHEDULED`` turn with its delivery / attribution
- provenance restored, so a scheduled run that was enqueued behind an active
- turn keeps its suppress-delivery / delivery-target / source when it finally
- runs (#84). Returns True if a turn was started, False on an empty queue /
- failure."""
- from core.inbox_events import bus
- from core.workbench_media import file_attachments_from_specs, resolve_attachment_specs
- from storage.background import run_update_event_transaction
-
- if not session_id:
- return False
- if self._build_context is None:
- logger.error("queue flush: no build_context bound for session=%s", session_id)
- return False
- try:
- context = await asyncio.to_thread(self._build_context, session_id)
- except Exception:
- logger.exception("queue flush: failed to build context for session=%s", session_id)
- return False
- backend = self._context_backend(context)
- if backend in self._draining_backends:
- self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)
- return False
-
- is_scheduled = False
- scheduled_text = ""
- scheduled_prov: dict = {}
- scheduled_message_id = None
- scheduled_native_ids: list[str] = []
- dropped_duplicate_segment = False
- user_row = None
- inbox_row = None
- attachment_specs: list = []
- pending_agent_run_ids: list[str] = []
- pending_scheduled_segment: list[dict] = []
- claimed_agent_run_ids: list[str] = []
- dispatch_text = ""
- engine = self._sqlite_engine()
- try:
- with run_update_event_transaction(engine) as conn:
- rows = messages_service.list_queued(conn, session_id)
- if not rows:
- return False
- if _scheduled_provenance(rows[0]) is not None:
- from storage.background import inspect_queued_runs_for_workbench_in_connection
-
- # Scheduled segment: a leading run of same-definition harness
- # rows within the rolling merge window runs as one scheduled
- # turn. Rows remain visible individually while queued; only the
- # Agent-facing dispatch is coalesced.
- is_scheduled = True
- initial_segment = _collect_scheduled_segment(rows)
- claimed_row_ids = _scheduled_claimed_queue_row_ids(conn, initial_segment)
- if claimed_row_ids:
- messages_service.delete_queued(conn, list(claimed_row_ids))
- bus.publish("queue.updated", {"session_id": session_id})
- segment = [r for r in initial_segment if str(r.get("id") or "") not in claimed_row_ids]
- if not segment:
- dropped_duplicate_segment = True
- else:
- segment = initial_segment
- if dropped_duplicate_segment:
- pass
- else:
- if _scheduled_segment_trigger_kind(segment) == "agent_run":
- run_ids = _scheduled_segment_execution_ids(segment)
- queued_run_ids, stale_run_ids = inspect_queued_runs_for_workbench_in_connection(conn, run_ids)
- if stale_run_ids:
- stale_set = set(stale_run_ids)
- queued_set = set(queued_run_ids)
- stale_row_ids = _scheduled_segment_stale_row_ids(segment, queued_set)
- if stale_row_ids:
- messages_service.delete_queued(conn, stale_row_ids)
- bus.publish("queue.updated", {"session_id": session_id})
- logger.info(
- "queue flush: removed stale coalesced agent_run rows before dispatching survivors: %s",
- ",".join(sorted(stale_set)),
- )
- segment = _scheduled_segment_rows_for_execution_ids(segment, queued_set)
- if not segment:
- dropped_duplicate_segment = True
-
- if dropped_duplicate_segment:
- pass
- else:
- scheduled_text = _build_scheduled_segment_text(segment)
- scheduled_native_ids = _scheduled_segment_native_ids(segment)
- prov = _scheduled_provenance(segment[0]) or {}
- scheduled_message_id = scheduled_native_ids[0] if scheduled_native_ids else None
- scheduled_prov = prov.get("platform_specific") or {}
- if len(segment) > 1:
- scheduled_prov = dict(scheduled_prov)
- scheduled_prov["coalesced_queue"] = {
- "count": len(segment),
- "window_seconds": SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS,
- "message_ids": [r.get("id") for r in segment if r.get("id")],
- "native_message_ids": scheduled_native_ids,
- "execution_ids": queued_run_ids
- if _scheduled_segment_trigger_kind(segment) == "agent_run"
- else _scheduled_segment_execution_ids(segment),
- }
- if scheduled_prov.get("task_trigger_kind") == "agent_run" and queued_run_ids:
- pending_agent_run_ids = list(queued_run_ids)
- scheduled_prov = _filter_coalesced_agent_run_provenance(
- scheduled_prov,
- pending_agent_run_ids,
- )
- scheduled_message_id = f"agent_run:{pending_agent_run_ids[0]}"
- coalesced = scheduled_prov.get("coalesced_queue")
- if isinstance(coalesced, dict):
- coalesced_prompt = str(coalesced.get("prompt") or "")
- if coalesced_prompt:
- scheduled_text = coalesced_prompt
- pending_scheduled_segment = segment
- else:
- segment = _collect_user_segment(rows)
- if is_scheduled and segment and not pending_agent_run_ids:
- messages_service.delete_queued(conn, [r["id"] for r in segment])
- if not is_scheduled:
- texts = [str(r.get("text") or "") for r in segment if str(r.get("text") or "").strip()]
- dispatch_texts = [
- str((r.get("metadata") or {}).get(QUEUED_DISPATCH_TEXT_KEY) or r.get("text") or "")
- for r in segment
- if str(
- (r.get("metadata") or {}).get(QUEUED_DISPATCH_TEXT_KEY)
- or r.get("text")
- or ""
- ).strip()
- ]
- # Carry attachments queued in this user segment so a file
- # attached while the agent was busy still reaches the merged
- # turn. An attachment-only input or annotation with an empty
- # display body still has work to dispatch, so the guard uses
- # agent-facing text rather than transcript text.
- queued_attachments = [
- att
- for r in segment
- for att in ((r.get("content") or {}).get("attachments") or [])
- ]
- if not dispatch_texts and not queued_attachments:
- messages_service.delete_queued(conn, [r["id"] for r in segment])
- return False
- user_owners = list(
- dict.fromkeys(
- owner.strip()
- for r in segment
- if isinstance((owner := (r.get("metadata") or {}).get(WEB_PUSH_USER_KEY_METADATA)), str)
- and owner.strip()
- )
- )
- user_owner = user_owners[0] if len(user_owners) == 1 else None
- user_metadata = dict(segment[0].get("metadata") or {})
- user_metadata.pop(QUEUED_DISPATCH_TEXT_KEY, None)
- user_metadata.pop(WEB_PUSH_USER_KEY_METADATA, None)
- user_metadata.pop(WEB_PUSH_USER_KEYS_METADATA, None)
- if user_owner:
- user_metadata[WEB_PUSH_USER_KEY_METADATA] = user_owner
- elif user_owners:
- user_metadata[WEB_PUSH_USER_KEYS_METADATA] = user_owners
- attachment_specs = resolve_attachment_specs(
- conn, session_id=session_id, attachments=queued_attachments
- )
- visible_text = "\n".join(texts)
- dispatch_text = "\n".join(dispatch_texts)
- user_row = _promote_merged_user_segment(
- conn,
- segment,
- text=visible_text,
- attachments=queued_attachments,
- metadata=user_metadata,
- author_id=user_owner,
- )
- inbox_row = messages_service.get_inbox_session(conn, session_id)
- except Exception:
- logger.exception("queue flush: failed to claim/merge for session=%s", session_id)
- return False
-
- if dropped_duplicate_segment:
- return await self.flush_queue(session_id)
+ # chokepoint / cancel / startup recovery).
+ self.controller.set_agent_status(session_id, "running")
+ bus.publish(
+ "turn.start",
+ _turn_event_payload(session_id, logical_turn_id),
+ )
- # Surface the flushed (merged) user message + bump the inbox card so other
- # workbench views re-rank / flip 'replied' without waiting for the result
- # (Codex P2). A scheduled segment has NO user row — its prompt is mirrored by
- # its own dispatch, exactly as a non-enqueued scheduled run. Either way the
- # queue changed.
- if user_row is not None:
- bus.publish("message.new", user_row)
- if inbox_row is not None:
- bus.publish("inbox.session.updated", inbox_row)
- bus.publish("queue.updated", {"session_id": session_id})
+ async def flush_queue(self, session_id: str) -> bool:
+ """Drain one claimable Delivery through the sole FIFO owner."""
+ return await self.drain_delivery_queue(session_id)
- if not is_scheduled:
- # Carry the queued segment's uploaded files into the merged turn.
- context.files = file_attachments_from_specs(attachment_specs)
- context.message_id = user_row["id"]
- await self._run(session_id, context, dispatch_text)
- else:
- # Restore the scheduled run's delivery / source provenance onto the rebuilt
- # (fresh-routing) context, then run as SOURCE_SCHEDULED — not a plain user
- # turn — so suppress_delivery / the delivery target / the task attribution
- # carry through the queue (#84).
- #
- # The coalesced native-id set is split deliberately: the first id is
- # assigned to this visible harness prompt, while later ids have already
- # been preserved as hidden dedupe marker rows during the queue claim.
- if context.platform_specific is None:
- context.platform_specific = {}
- context.platform_specific.update(scheduled_prov)
- if scheduled_message_id is not None:
- # Restore the stable scheduled:/watch:/webhook: native id so the
- # flushed prompt persists + dedupes under it (Codex P2), not None.
- context.message_id = scheduled_message_id
- if pending_agent_run_ids:
- retry_agent_run_flush = False
- try:
- with run_update_event_transaction(engine) as conn:
- claimed_run_ids = _claim_agent_run_segment_and_retire_queue(
- conn,
- run_ids=pending_agent_run_ids,
- segment=pending_scheduled_segment,
- )
- if set(claimed_run_ids) != set(pending_agent_run_ids):
- queued_run_ids, stale_run_ids = inspect_queued_runs_for_workbench_in_connection(
- conn,
- pending_agent_run_ids,
- )
- stale_set = set(stale_run_ids)
- stale_row_ids = _scheduled_segment_stale_row_ids(
- pending_scheduled_segment,
- set(queued_run_ids),
- )
- if stale_row_ids:
- messages_service.delete_queued(conn, stale_row_ids)
- bus.publish("queue.updated", {"session_id": session_id})
- logger.info(
- "queue flush: skipped coalesced agent_run segment because some runs are no longer queued: %s",
- ",".join(sorted(set(pending_agent_run_ids) - set(claimed_run_ids))),
- )
- if queued_run_ids:
- retry_agent_run_flush = True
- else:
- return False
- if retry_agent_run_flush:
- return await self.flush_queue(session_id)
- claimed_agent_run_ids = claimed_run_ids
- bus.publish("queue.updated", {"session_id": session_id})
- except Exception:
- logger.warning(
- "queue flush: failed to claim coalesced agent_run segment for session=%s",
- session_id,
- exc_info=True,
- )
- return False
- try:
- await self._run(session_id, context, scheduled_text, source=SOURCE_SCHEDULED)
- except Exception:
- if claimed_agent_run_ids:
- try:
- from storage.background import reset_workbench_claimed_runs_in_connection
+ async def reconcile_terminal_run_delivery(
+ self,
+ run_id: str,
+ *,
+ session_id: str,
+ ) -> dict[str, Any]:
+ """Retire an exact terminal Run input when no native effect is possible."""
+
+ retired = False
+ state: str | None = None
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ run = conn.execute(
+ select(
+ agent_runs.c.status,
+ agent_runs.c.session_id,
+ agent_runs.c.delivery_id,
+ )
+ .where(agent_runs.c.id == run_id)
+ .limit(1)
+ ).mappings().first()
+ if (
+ run is None
+ or normalize_run_status(run["status"]) in {"queued", "running"}
+ or str(run["session_id"] or "") != session_id
+ or not run["delivery_id"]
+ ):
+ return {"changed": False, "state": None}
+ delivery = delivery_store.get_delivery(conn, str(run["delivery_id"]))
+ if delivery is None or str(delivery["session_id"]) != session_id:
+ return {"changed": False, "state": None}
+ state = str(delivery["state"])
+ if delivery_store.policy_for(state).run_cancel == "retire":
+ retired = self._retire_delivery_not_written(
+ conn,
+ session_id,
+ str(delivery["id"]),
+ reason="terminal_run_before_native_write",
+ )
+ if retired:
+ state = "retired"
+ if retired:
+ from core.inbox_events import bus
- with run_update_event_transaction(engine) as conn:
- reset_workbench_claimed_runs_in_connection(conn, claimed_agent_run_ids)
- _restore_queued_rows(conn, pending_scheduled_segment)
- except Exception:
- logger.exception("queue flush: failed to reset claimed agent runs for session=%s", session_id)
- logger.exception("queue flush: failed to start scheduled segment for session=%s", session_id)
- return False
- if not pending_agent_run_ids:
- if pending_scheduled_segment:
- with engine.begin() as conn:
- messages_service.delete_queued(conn, [r["id"] for r in pending_scheduled_segment])
- bus.publish("queue.updated", {"session_id": session_id})
- try:
- with engine.begin() as conn:
- _write_coalesced_native_id_markers(conn, segment)
- except Exception:
- logger.exception("queue flush: failed to preserve coalesced native ids for session=%s", session_id)
- return False
- return True
+ bus.publish("queue.updated", {"session_id": session_id})
+ return {"changed": retired, "state": state}
async def recover_persisted_agent_run_queue(
self,
@@ -1568,116 +4414,84 @@ class SessionTurnManager:
) -> list[str]:
"""Resume durable Workbench Agent Run queues after their owner vanished.
- ``workbench_queue_holds_run`` rows are deliberately invisible to the
- scheduler because the Session FSM owns their FIFO position. A process
- restart drops the in-memory owner and therefore must re-enter that FSM.
- Recovery is evidence-based: only a persisted queue row that references
- a still-queued Agent Run is eligible. An older, scheduler-owned queued
- Run defers recovery until that Run reaches its normal synchronous or
- terminal path, preserving FIFO across restart.
+ The Delivery relation is the durable owner. A restart may resume its
+ exact FIFO head only while the linked Agent Run remains nonterminal.
"""
if self._build_context is None:
return []
- if session_id:
- session_ids = [session_id]
- else:
- with self._sqlite_engine().connect() as conn:
- session_ids = messages_service.list_queued_session_ids(conn)
-
+ with self._sqlite_engine().connect() as conn:
+ session_ids = delivery_store.queued_session_ids_without_live_turns(
+ conn,
+ session_id,
+ )
recovered: list[str] = []
for queued_session_id in session_ids:
- lock = self._queue_recovery_locks.setdefault(
- queued_session_id,
- asyncio.Lock(),
- )
+ lock = self._queue_recovery_locks.setdefault(queued_session_id, asyncio.Lock())
async with lock:
- entry = self.in_flight.get(queued_session_id)
- if entry is not None and not entry.task.done():
- continue
with self._sqlite_engine().connect() as conn:
- queue_rows = messages_service.list_queued(conn, queued_session_id)
- if not queue_rows:
- continue
- head_provenance = _scheduled_provenance(queue_rows[0]) or {}
- head_spec = head_provenance.get("platform_specific") or {}
- if (
- not isinstance(head_spec, dict)
- or head_spec.get("task_trigger_kind") != "agent_run"
- ):
+ head = delivery_store.claimable_fifo_head(conn, queued_session_id)
+ if head is None:
continue
- head_segment = _collect_scheduled_segment(queue_rows)
- referenced_run_ids = _scheduled_segment_execution_ids(
- head_segment
+ head_payload = delivery_store.delivery_payload(head)
+ provenance = (head_payload.get("metadata") or {}).get(
+ SCHEDULED_PROVENANCE_KEY
)
- if not referenced_run_ids:
- continue
- run_rows = list(
- conn.execute(
- select(
- agent_runs.c.id,
- agent_runs.c.created_at,
- agent_runs.c.status,
- agent_runs.c.metadata_json,
- )
- .where(agent_runs.c.session_id == queued_session_id)
- .where(agent_runs.c.run_type == "agent_run")
- .order_by(agent_runs.c.created_at, agent_runs.c.id)
- ).mappings()
+ spec = (
+ provenance.get("platform_specific")
+ if isinstance(provenance, dict)
+ else None
)
-
- queued_rows = [
- row
- for row in run_rows
- if normalize_run_status(row["status"]) == "queued"
- ]
- live_references = {
- str(row["id"])
- for row in queued_rows
- if str(row["id"]) in referenced_run_ids
- and _run_metadata_holds_workbench_queue(row["metadata_json"])
- }
- if not live_references:
- continue
-
- first_reference_at = min(
- (
- parsed
- for row in queued_rows
- if str(row["id"]) in live_references
- and (parsed := _parse_queue_timestamp(row["created_at"]))
- is not None
- ),
- default=None,
- )
- defer_to_scheduler = False
- for row in queued_rows:
- run_id = str(row["id"])
- if run_id in live_references:
- continue
- try:
- metadata = json.loads(row["metadata_json"] or "{}")
- except (TypeError, ValueError):
- metadata = {}
- if isinstance(metadata, dict) and metadata.get(
- "workbench_queue_holds_run"
- ):
- continue
- created_at = _parse_queue_timestamp(row["created_at"])
+ run_ids = delivery_store.agent_run_ids_for_delivery(conn, head)
+ run_id = run_ids[0] if run_ids else None
if (
- first_reference_at is None
- or created_at is None
- or created_at <= first_reference_at
+ not isinstance(spec, dict)
+ or spec.get("task_trigger_kind") != "agent_run"
+ or not run_id
):
- defer_to_scheduler = True
- break
- if defer_to_scheduler:
+ continue
+ run_row = conn.execute(
+ select(agent_runs.c.status, agent_runs.c.cancel_requested)
+ .where(agent_runs.c.id == run_id)
+ ).mappings().first()
+ if (
+ run_row is None
+ or bool(run_row["cancel_requested"])
+ or normalize_run_status(run_row["status"]) not in {"queued", "running"}
+ ):
continue
-
- if await self.flush_queue(queued_session_id):
+ if await self.drain_delivery_queue(queued_session_id):
recovered.append(queued_session_id)
return recovered
+ def _repair_ownerless_running_projection(self, session_id: str) -> bool:
+ """Clear a legacy running projection only after an exact owner recheck."""
+
+ engine = self._sqlite_engine()
+ if not callable(getattr(engine, "connect", None)):
+ return False
+ if not self._durable_schema_available():
+ return False
+ with engine.begin() as conn:
+ reserve_write_lock(conn)
+ if delivery_store.active_turn(conn, session_id) is not None:
+ return False
+ repaired = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .where(agent_sessions.c.agent_status == "running")
+ .values(agent_status="idle")
+ )
+ changed = bool(repaired.rowcount)
+ if changed:
+ from core.inbox_events import bus
+
+ bus.publish(
+ "session.status",
+ {"session_id": session_id, "agent_status": "idle"},
+ )
+ return changed
+
def turn_state(self, session_id: str) -> dict:
"""Compose orthogonal foreground, inbox, Activity, and connection facts."""
entry = self.in_flight.get(session_id)
@@ -1701,17 +4515,18 @@ class SessionTurnManager:
backend_alive = probe(entry.context)
except Exception:
logger.debug("turn_state: backend liveness probe failed", exc_info=True)
- coalesced = payload.get("coalesced_queue")
- owner_run_ids = (
- [str(value) for value in coalesced.get("execution_ids", []) if str(value or "").strip()]
- if isinstance(coalesced, dict) and isinstance(coalesced.get("execution_ids"), list)
- else []
- )
+ owner_run_ids = sorted(self._agent_run_ids_from_spec(payload))
owner_run_id = str(payload.get("task_execution_id") or "").strip()
if owner_run_id and owner_run_id not in owner_run_ids:
owner_run_ids.insert(0, owner_run_id)
+ if not owner_run_id and owner_run_ids:
+ owner_run_id = owner_run_ids[0]
owner = {
- "source": str(payload.get("task_trigger_kind") or payload.get("turn_source") or "human"),
+ "source": str(
+ payload.get("task_trigger_kind")
+ or payload.get("turn_source")
+ or ("agent_run" if payload.get("accepted_agent_run_ids") else "human")
+ ),
"acquired_at": entry.started_at or None,
"run_id": owner_run_id or None,
"run_ids": owner_run_ids,
@@ -1723,7 +4538,66 @@ class SessionTurnManager:
harness_activities: list[dict[str, Any]] = []
try:
with self._sqlite_engine().begin() as conn:
- pending_input_count = len(messages_service.list_queued(conn, session_id))
+ pending_input_count = len(delivery_store.list_queued(conn, session_id))
+ if not active and self._durable_schema_available():
+ durable_turn = delivery_store.active_turn(conn, session_id)
+ if durable_turn is not None:
+ active = True
+ native_turn_started = durable_turn["state"] == "active"
+ backend = str(durable_turn.get("backend") or "").strip()
+ initial = delivery_store.delivery_for_turn(
+ conn,
+ str(durable_turn["id"]),
+ )
+ record: dict[str, Any] = {}
+ if initial is not None:
+ record = delivery_store.delivery_payload(initial)
+ if initial.get("message_id"):
+ message = messages_service.get_message(
+ conn,
+ str(initial["message_id"]),
+ session_id=session_id,
+ )
+ if message is not None:
+ record = message
+ metadata = record.get("metadata") or {}
+ provenance = metadata.get(SCHEDULED_PROVENANCE_KEY)
+ restored_spec = (
+ provenance.get("platform_specific")
+ if isinstance(provenance, dict)
+ and isinstance(provenance.get("platform_specific"), dict)
+ else {}
+ )
+ owner_run_ids = sorted(self._agent_run_ids_from_spec(restored_spec))
+ for run_id in delivery_store.accepted_agent_run_ids_for_turn(
+ conn,
+ str(durable_turn["id"]),
+ ):
+ if run_id not in owner_run_ids:
+ owner_run_ids.append(run_id)
+ native_message_id = str(record.get("native_message_id") or "")
+ if native_message_id.startswith("agent_run:"):
+ native_run_id = native_message_id.removeprefix("agent_run:")
+ if native_run_id and native_run_id not in owner_run_ids:
+ owner_run_ids.insert(0, native_run_id)
+ owner_run_id = str(restored_spec.get("task_execution_id") or "").strip()
+ if not owner_run_id and owner_run_ids:
+ owner_run_id = owner_run_ids[0]
+ owner = {
+ "source": str(
+ restored_spec.get("task_trigger_kind")
+ or restored_spec.get("turn_source")
+ or ("scheduled" if isinstance(provenance, dict) else "human")
+ ),
+ "acquired_at": durable_turn.get("started_at")
+ or durable_turn.get("created_at"),
+ "run_id": owner_run_id or None,
+ "run_ids": owner_run_ids,
+ "runtime_key": str(durable_turn.get("runtime_key") or "").strip()
+ or None,
+ "native_turn_started": native_turn_started,
+ "backend_alive": None,
+ }
try:
harness_activities = derive_session_harness_activities(conn, session_id)
except Exception:
@@ -1766,6 +4640,11 @@ class SessionTurnManager:
0,
),
"connection": activity_state.get("connection", "unknown"),
+ "recovered_agent_status": (
+ False
+ if active
+ else self._repair_ownerless_running_projection(session_id)
+ ),
}
if backend:
result["backend"] = backend
@@ -1791,8 +4670,21 @@ class SessionTurnManager:
if not backend or not base_session_ids:
return 0
- released = 0
+ released_sessions: set[str] = set()
+ legacy_projection_sessions: set[str] = set()
tasks_to_settle: list[asyncio.Task] = []
+ restored_owners: list[dict[str, Any]] = []
+ if self._durable_schema_available():
+ with self._sqlite_engine().connect() as conn:
+ # Refresh owns exactly the generation that existed when draining
+ # began. Cancelling one of these Turns may activate a replacement;
+ # that successor belongs to the post-refresh generation and must
+ # remain deferred until the backend reopens.
+ restored_owners = delivery_store.live_turns_for_backend_sessions(
+ conn,
+ backend,
+ base_session_ids,
+ )
for session_id, turn in list(self.in_flight.items()):
if session_id not in base_session_ids:
continue
@@ -1805,7 +4697,6 @@ class SessionTurnManager:
)
if turn_backend and turn_backend != backend:
continue
- turn.stop_no_flush = True
# Record the cause BEFORE cancelling: this is a runtime refresh, not a
# user Stop, so a scheduled run this turn owns must not settle as
# ``canceled`` with the user-stop explanation (Codex P1). ``_run`` reads
@@ -1815,17 +4706,58 @@ class SessionTurnManager:
self.in_flight.pop(session_id, None)
from core.inbox_events import bus
- bus.publish("turn.end", {"session_id": session_id})
+ bus.publish(
+ "turn.end",
+ _turn_event_payload(session_id, turn.logical_turn_id),
+ )
else:
turn.task.cancel()
tasks_to_settle.append(turn.task)
- if self.controller is not None:
- self.controller.set_agent_status(session_id, "idle")
if backend in self._draining_backends:
self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)
- released += 1
+ released_sessions.add(session_id)
+ if not turn.logical_turn_id:
+ legacy_projection_sessions.add(session_id)
if tasks_to_settle:
await asyncio.gather(*tasks_to_settle, return_exceptions=True)
+ if self.controller is not None:
+ for session_id in legacy_projection_sessions:
+ self.controller.set_agent_status(session_id, "idle")
+ released_restored: set[str] = set()
+ for owner in restored_owners:
+ owner_id = str(owner["id"])
+ if owner["state"] == "starting":
+ terminal = self._terminalize_durable_turn(
+ owner_id,
+ "failed",
+ settled_by=SETTLED_BY_BACKEND_REFRESH,
+ evidence_kind="backend_refresh_start_failed",
+ evidence={
+ "backend": backend,
+ "reason": "forced_refresh_during_unresolved_start",
+ },
+ abandon_unaccepted_start=True,
+ )
+ if terminal.get("changed"):
+ logger.error(
+ "Forced %s refresh failed unresolved durable Turn=%s",
+ backend,
+ owner_id,
+ )
+ else:
+ terminal = self._terminalize_durable_turn(
+ owner_id,
+ "canceled",
+ settled_by=SETTLED_BY_BACKEND_REFRESH,
+ evidence_kind="backend_refresh",
+ )
+ if terminal.get("changed"):
+ released_restored.add(str(owner["session_id"]))
+ for session_id in released_restored:
+ if backend in self._draining_backends:
+ self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)
+ released_sessions.update(released_restored)
+ released = len(released_sessions)
if released:
logger.info(
"Released %d active Workbench turn(s) for %s runtime refresh",
@@ -1834,25 +4766,79 @@ class SessionTurnManager:
)
return released
+ def fail_restored_backend_turn(
+ self,
+ turn_id: str,
+ *,
+ backend: str,
+ reason: str,
+ ) -> bool:
+ """Terminal-fail an exact durable owner whose backend restore cannot register."""
+
+ terminal = self._terminalize_durable_turn(
+ turn_id,
+ "failed",
+ settled_by=SETTLED_BY_BACKEND_REFRESH,
+ evidence_kind="backend_restore_failed",
+ evidence={"backend": backend, "reason": reason},
+ abandon_unaccepted_start=True,
+ )
+ if terminal.get("changed"):
+ logger.error(
+ "Failed restored %s Turn=%s after backend registration error",
+ backend,
+ turn_id,
+ )
+ return bool(terminal.get("changed"))
+
async def cancel(self, session_id: str) -> dict:
- """Stop the active turn: interrupt the agent's backend run via the SAME path
- the IM ``/stop`` command uses (Claude interrupt / Codex turn-interrupt /
- OpenCode abort) — not just the waiter — keeping the send-while-busy queue
- ("不清空"). Returns a result dict; ``code`` is ``not_in_flight`` /
- ``stop_failed`` for the HTTP adapter to map to 404 / 409, else a 200 status.
- """
+ """Persist one empty-P0 control request against the exact active Turn."""
turn = self.in_flight.get(session_id)
+ if not self._durable_schema_available():
+ return await self._cancel_legacy_turn(session_id, turn)
+ with self._sqlite_engine().connect() as conn:
+ owner = delivery_store.active_turn(conn, session_id)
+ if owner is None:
+ return {
+ "ok": False,
+ "code": "not_in_flight",
+ "session_id": session_id,
+ "recovered_agent_status": self._repair_ownerless_running_projection(
+ session_id
+ ),
+ }
+ result = await self.deliver(
+ DeliveryRequest(
+ session_id=session_id,
+ priority="p0",
+ content=None,
+ expected_turn_id=str(owner["id"]),
+ ),
+ context=turn.context if turn is not None else None,
+ )
+ if result.state in {"waiting_terminal", "interrupt_waiting"}:
+ return {"ok": True, "session_id": session_id, "status": "cancel_requested"}
+ if result.state == "settled" and result.reason == "not_active":
+ return {
+ "ok": True,
+ "session_id": session_id,
+ "status": "stale_released",
+ "reason": "not_active",
+ }
+ return {
+ "ok": False,
+ "code": "stop_unknown" if result.state == "reconciling" else "stop_failed",
+ "session_id": session_id,
+ "reason": result.reason,
+ }
+
+ async def _cancel_legacy_turn(self, session_id: str, turn: Turn | None) -> dict:
+ """Keep non-Workbench/test runtimes on the existing in-memory Stop path."""
if turn is None:
return {"ok": False, "code": "not_in_flight", "session_id": session_id}
if turn.task.done():
return {"ok": True, "session_id": session_id, "status": "already_finished"}
- # Record the no-flush intent BEFORE awaiting the interrupt: if the backend
- # stop lets the turn settle normally during the await (no CancelledError),
- # _run's finally would otherwise treat it as a natural completion and
- # flush — but a plain Stop keeps the queue (Codex P2). We pass the context the
- # turn STARTED under so the right backend is interrupted even if the Chat
- # header swapped the session's agent / model mid-turn.
- turn.stop_no_flush = True
+ turn.cancel_settled_by = SETTLED_BY_STOPPED
if turn.context.platform_specific is None:
turn.context.platform_specific = {}
turn.context.platform_specific["suppress_stop_no_active_notice"] = True
@@ -1864,20 +4850,17 @@ class SessionTurnManager:
if not stopped:
spec = getattr(turn.context, "platform_specific", None) or {}
reason = str(spec.get("stop_failure_reason") or "").strip()
- stale_backend = reason in {"not_active", "runtime_unavailable"}
- if stale_backend:
- # The backend no longer has an active runtime handle, but Workbench
- # still owns an in-flight waiter. Keeping it would leave Stop stuck
- # and queue future sends behind a phantom turn. Release only after
- # an explicit user Stop and keep ``stop_no_flush`` so queued
- # messages are preserved.
+ if reason in {"not_active", "runtime_unavailable"}:
turn.task.cancel()
await asyncio.gather(turn.task, return_exceptions=True)
released_turn = self.in_flight.pop(session_id, None)
from core.inbox_events import bus
if released_turn is not None:
- bus.publish("turn.end", {"session_id": session_id})
+ bus.publish(
+ "turn.end",
+ _turn_event_payload(session_id, turn.logical_turn_id),
+ )
if self.controller is not None:
self.controller.set_agent_status(session_id, "idle")
backend = self._context_backend(turn.context)
@@ -1890,11 +4873,13 @@ class SessionTurnManager:
"status": "stale_released",
"reason": reason,
}
- # Stop failed/refused while the backend may still be producing output;
- # keep the Workbench turn registered so Stop remains available and
- # later natural completion can flush normally.
- turn.stop_no_flush = False
- return {"ok": False, "code": "stop_failed", "session_id": session_id, "reason": reason or None}
+ turn.cancel_settled_by = None
+ return {
+ "ok": False,
+ "code": "stop_failed",
+ "session_id": session_id,
+ "reason": reason or None,
+ }
backend = self._context_backend(turn.context)
deferred = self._deferred_restart_sessions.get(backend)
if deferred is not None:
@@ -1902,114 +4887,36 @@ class SessionTurnManager:
turn.task.cancel()
return {"ok": True, "session_id": session_id, "status": "cancel_requested"}
- @staticmethod
- def _clear_send_now_task(
- turn: Turn,
- task: asyncio.Task[dict[str, Any]],
- ) -> None:
- if turn.send_now_task is task:
- turn.send_now_task = None
-
- async def _interrupt_for_send_now(self, session_id: str, turn: Turn) -> dict:
- """Own one backend Stop attempt shared by concurrent send-now callers."""
-
- turn.flush_on_cancel = True
- if turn.context.platform_specific is None:
- turn.context.platform_specific = {}
- turn.context.platform_specific["suppress_stop_no_active_notice"] = True
- stopped = False
- try:
- stopped = bool(
- await self.controller.command_handler.handle_stop(turn.context)
- )
- except Exception:
- logger.exception(
- "internal send-now: backend stop failed for session=%s",
- session_id,
- )
- if not stopped:
- turn.flush_on_cancel = False
+ async def send_now(
+ self,
+ session_id: str,
+ *,
+ expected_delivery_id: str | None = None,
+ ) -> dict:
+ """Promote the exact Delivery ordering head through empty P1."""
+ with self._sqlite_engine().connect() as conn:
+ head = delivery_store.ordering_head(conn, session_id)
+ if head is None:
+ return {"ok": True, "session_id": session_id, "status": "empty"}
+ result = await self.deliver(
+ DeliveryRequest(
+ session_id=session_id,
+ priority="p1",
+ content=None,
+ expected_delivery_id=expected_delivery_id,
+ ),
+ )
+ if result.state == "refused":
return {
"ok": False,
- "code": "stop_failed",
+ "code": result.reason or "send_now_refused",
"session_id": session_id,
}
- turn.task.cancel()
return {
"ok": True,
"session_id": session_id,
- "status": "interrupted",
- }
-
- async def send_now(self, session_id: str) -> dict:
- """Run the session's send-while-busy queue immediately ("立即发送").
-
- If a turn is running (and something is queued), interrupt it (the user chose
- to cut in) and opt into ``flush_on_cancel`` so the queue runs as that turn
- unwinds. If nothing is running, flush directly as a fresh turn. No-op when
- the queue is empty. A refused Stop or idle flush returns a typed failure for
- the HTTP/CLI caller while leaving the durable queue retryable.
- """
- turn = self.in_flight.get(session_id)
- if turn is not None and not turn.task.done():
- # Don't interrupt a live turn unless there is actually something queued to
- # cut in with — a stale queue item already flushed by another tab would
- # otherwise make send-now an unintended Stop (Codex P2).
- with self._sqlite_engine().connect() as conn:
- has_queue = bool(messages_service.list_queued(conn, session_id))
- if not has_queue:
- return {"ok": True, "session_id": session_id, "status": "empty"}
- # Concurrent send-now callers share one Stop attempt and therefore one
- # truthful result. Shield the transition because caller cancellation
- # cannot undo an already-admitted durable queue row.
- send_now_task = turn.send_now_task
- if send_now_task is None:
- send_now_task = asyncio.create_task(
- self._interrupt_for_send_now(session_id, turn),
- name=f"send-now:{session_id}",
- )
- turn.send_now_task = send_now_task
- try:
- result = await asyncio.shield(send_now_task)
- finally:
- if (
- send_now_task.done()
- and not bool(send_now_task.result().get("ok"))
- ):
- # Existing waiters are already queued to resume. Clearing on
- # the next loop tick lets a later explicit refusal retry make
- # a new Stop attempt without duplicating this one. A successful
- # Stop stays attached until the Turn is popped, so no caller
- # can interrupt the same unwinding Turn twice.
- asyncio.get_running_loop().call_soon(
- self._clear_send_now_task,
- turn,
- send_now_task,
- )
- return dict(result)
- # No running turn — flush the queue directly as a new turn (rebuilds routing
- # from the current session row internally). A false flush is only ``empty``
- # when the queue is now actually empty; context/claim/dispatch failures keep
- # their durable rows and must enter the caller's queue-recovery path.
- flushed = await self.flush_queue(session_id)
- if flushed:
- return {"ok": True, "session_id": session_id, "status": "flushed"}
- try:
- with self._sqlite_engine().connect() as conn:
- queue_remains = bool(messages_service.list_queued(conn, session_id))
- except Exception:
- logger.exception(
- "send-now: failed to verify queue after a refused flush for session=%s",
- session_id,
- )
- queue_remains = True
- return {
- "session_id": session_id,
- **(
- {"ok": False, "code": "flush_failed"}
- if queue_remains
- else {"ok": True, "status": "empty"}
- ),
+ "status": result.state,
+ "delivery_id": result.delivery_id,
}
# --- shared turn chokepoints (status + Show checkpoint projection) ------------
@@ -2077,26 +4984,154 @@ class SessionTurnManager:
if session_id:
self.controller.set_agent_status(session_id, "running")
- def on_terminal_result(self, context: "MessageContext", *, is_error: bool) -> None:
+ @staticmethod
+ def _durable_terminal_outcome(*, is_error: bool, settled_by: str | None) -> str:
+ if is_error:
+ return "failed"
+ if settled_by == SETTLED_BY_STOPPED:
+ return "canceled"
+ return "completed"
+
+ def _finish_durable_terminal_result(
+ self,
+ session_id: str,
+ logical_turn_id: str,
+ *,
+ is_error: bool,
+ settled_by: str | None,
+ terminal_evidence: dict[str, Any] | None = None,
+ ) -> None:
+ try:
+ terminal = self._terminalize_durable_turn(
+ logical_turn_id,
+ self._durable_terminal_outcome(
+ is_error=is_error,
+ settled_by=settled_by,
+ ),
+ settled_by=settled_by or SETTLED_BY_TERMINAL_RESULT,
+ evidence_kind="terminal_result",
+ evidence=terminal_evidence,
+ )
+ except Exception:
+ logger.exception(
+ "durable terminal reconciliation deferred after native completion for Turn=%s",
+ logical_turn_id,
+ )
+ return
+ current = self.in_flight.get(session_id)
+ should_resume = bool(terminal.get("successor_turn_id")) or not bool(
+ terminal.get("preserve_queue")
+ )
+ if (
+ terminal.get("changed")
+ and should_resume
+ and (current is None or current.logical_turn_id != logical_turn_id)
+ ):
+ asyncio.create_task(
+ self._resume_after_native_terminal(session_id, logical_turn_id),
+ name=f"durable-result-resume:{session_id}",
+ )
+
+ def on_terminal_result(
+ self,
+ context: "MessageContext",
+ *,
+ is_error: bool,
+ terminal_evidence: dict[str, Any] | None = None,
+ ) -> None:
"""OUTBOUND turn chokepoint for the active terminal ``result``."""
if self.controller is None:
return
if not self.is_active_emit(context):
return
- # The dispatcher calls this before delivery. Record authority now, then
- # checkpoint from Controller.emit_agent_message's post-delivery finally.
+ # The dispatcher calls this before delivery. Latch evidence only; the
+ # controller's post-delivery boundary performs the durable transition.
self._set_context_flag(context, _SHOW_CHECKPOINT_TERMINAL_PENDING_KEY, True)
session_id = self.controller._session_id_from_context(context)
if not session_id:
return
- self.controller.set_agent_status(session_id, "failed" if is_error else "idle")
+ logical_turn_id = str(
+ (getattr(context, "platform_specific", None) or {}).get("turn_token")
+ or ""
+ ).strip()
+ if logical_turn_id:
+ current = self.in_flight.get(session_id)
+ if current is not None and current.logical_turn_id == logical_turn_id:
+ current.terminal_is_error = current.terminal_is_error or is_error
+ sink = None
+ get_key = getattr(self.controller, "_get_session_key", None)
+ if callable(get_key):
+ try:
+ sink = self.get_turn_sink(get_key(context))
+ except Exception:
+ logger.debug("failed to inspect terminal Turn sink", exc_info=True)
+ if isinstance(sink, dict):
+ sink["terminal_evidence"] = dict(terminal_evidence or {})
+ payload = dict(getattr(context, "platform_specific", None) or {})
+ payload[_TERMINAL_RESULT_LATCH_KEY] = {
+ "session_id": session_id,
+ "logical_turn_id": logical_turn_id,
+ "is_error": is_error,
+ "terminal_evidence": dict(terminal_evidence or {}),
+ }
+ context.platform_specific = payload
def on_terminal_delivery_complete(self, context: "MessageContext") -> None:
- """Checkpoint an accepted terminal result after delivery and persistence."""
+ """Commit terminal evidence after the output delivery attempt has settled."""
if not self._pop_context_flag(context, _SHOW_CHECKPOINT_TERMINAL_PENDING_KEY):
return
self._end_show_checkpoint(context)
+ payload = dict(getattr(context, "platform_specific", None) or {})
+ latch = payload.pop(_TERMINAL_RESULT_LATCH_KEY, None)
+ context.platform_specific = payload
+ if not isinstance(latch, dict):
+ return
+ session_id = str(latch.get("session_id") or "")
+ logical_turn_id = str(latch.get("logical_turn_id") or "")
+ is_error = bool(latch.get("is_error"))
+ if not session_id:
+ return
+ durable_turn_exists = False
+ if logical_turn_id and self._durable_schema_available():
+ try:
+ with self._sqlite_engine().connect() as conn:
+ durable_turn_exists = (
+ delivery_store.get_turn(conn, logical_turn_id) is not None
+ )
+ except Exception:
+ logger.debug(
+ "failed to inspect delivered terminal Turn authority",
+ exc_info=True,
+ )
+ if not durable_turn_exists:
+ self.controller.set_agent_status(
+ session_id,
+ "failed" if is_error else "idle",
+ )
+ return
+ current = self.in_flight.get(session_id)
+ sink = None
+ get_key = getattr(self.controller, "_get_session_key", None)
+ if callable(get_key):
+ try:
+ sink = self.get_turn_sink(get_key(context))
+ except Exception:
+ logger.debug("failed to inspect delivered terminal Turn sink", exc_info=True)
+ self._finish_durable_terminal_result(
+ session_id,
+ logical_turn_id,
+ is_error=is_error,
+ settled_by=(
+ str((sink or {}).get("settled_by") or "")
+ or (current.cancel_settled_by if current is not None else None)
+ ),
+ terminal_evidence=(
+ dict(latch.get("terminal_evidence") or {})
+ if isinstance(latch.get("terminal_evidence"), dict)
+ else None
+ ),
+ )
def register_agent_initiated_turn(self, context: "MessageContext") -> bool:
"""Register a turn the BACKEND started on its own (agent-initiated:
@@ -2134,7 +5169,116 @@ class SessionTurnManager:
return False
from core.inbox_events import bus
- turn_token = (getattr(context, "platform_specific", None) or {}).get("turn_token")
+ payload = getattr(context, "platform_specific", None) or {}
+ turn_token = str(payload.get("turn_token") or delivery_store.new_turn_id())
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ context.platform_specific["turn_token"] = turn_token
+ engine = self._sqlite_engine()
+ durable_schema = self._durable_schema_available()
+ with engine.connect() as conn:
+ session_exists = durable_schema and (
+ conn.execute(
+ select(agent_sessions.c.id).where(agent_sessions.c.id == session_id)
+ ).scalar_one_or_none()
+ is not None
+ )
+ durable_turn_registered = False
+ materialized_delivery_id: str | None = None
+ if session_exists:
+ with engine.begin() as conn:
+ reserve_write_lock(conn)
+ durable = delivery_store.get_turn(conn, turn_token)
+ if durable is None:
+ if delivery_store.active_turn(conn, session_id) is not None:
+ return False
+ session_row = conn.execute(
+ select(
+ agent_sessions.c.scope_id,
+ agent_sessions.c.status,
+ ).where(agent_sessions.c.id == session_id)
+ ).mappings().one()
+ if session_row["status"] != "active":
+ return False
+ delivery_id = delivery_store.new_delivery_id()
+ language_getter = getattr(self.controller, "_get_lang", None)
+ language = (
+ language_getter()
+ if callable(language_getter)
+ else getattr(
+ getattr(self.controller, "config", None),
+ "language",
+ "en",
+ )
+ )
+ trigger_text = str(
+ payload.get("agent_initiated_trigger_text")
+ or i18n_t("harness.agentInitiatedContinuation", language)
+ )
+ delivery = delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=session_id,
+ priority="p3",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=session_row["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text=trigger_text,
+ metadata={
+ "source": "agent_initiated",
+ "runtime_key": payload.get("agent_runtime_turn_key"),
+ },
+ ),
+ dispatch_text="",
+ history_event={
+ "kind": "admission",
+ "turn_id": turn_token,
+ "outcome": "backend_initiated",
+ },
+ )
+ self._claim_start_batch(
+ conn,
+ turn_id=turn_token,
+ session_id=session_id,
+ backend=self._context_backend(context),
+ deliveries=[delivery],
+ dispatch_text="",
+ )
+ durable = delivery_store.get_turn(conn, turn_token)
+ if durable is None:
+ return False
+ bound = delivery_store.bind_native_start(
+ conn,
+ turn_token,
+ expected_version=int(durable["version"]),
+ runtime_key=str(payload.get("agent_runtime_turn_key") or "agent-initiated"),
+ runtime_turn_id=str(payload.get("agent_runtime_turn_token") or "agent-initiated"),
+ native_turn_id=None,
+ )
+ durable_turn_registered = bound is not None
+ if bound is not None:
+ materialized = delivery_store.materialize_start_acceptance(
+ conn,
+ turn_id=turn_token,
+ evidence={"kind": "backend_initiated_output"},
+ )
+ if not materialized:
+ raise RuntimeError(
+ "agent-initiated Turn could not materialize its trigger Delivery"
+ )
+ materialized_delivery_id = str(
+ materialized[0].get("message_id") or materialized[0]["id"]
+ )
+ if not durable_turn_registered:
+ return False
+ if materialized_delivery_id:
+ context.message_id = materialized_delivery_id
+ self._publish_materialized_delivery(materialized_delivery_id)
done = asyncio.Event()
self.register_turn_sink(
session_key,
@@ -2146,26 +5290,76 @@ class SessionTurnManager:
async def _holder() -> None:
cancelled = False
+ durable_terminal_result: dict[str, Any] = {}
try:
await done.wait()
except asyncio.CancelledError:
cancelled = True
raise
finally:
+ sink = self.get_turn_sink(session_key)
+ settled_by = str((sink or {}).get("settled_by") or "")
+ terminal_evidence = (sink or {}).get("terminal_evidence")
self.pop_turn_sink(session_key, done)
- turn = self.in_flight.pop(session_id, None)
+ current = self.in_flight.get(session_id)
+ turn = current if current is not None and current.task is asyncio.current_task() else None
+ terminal_is_error = bool(
+ turn is not None and turn.terminal_is_error
+ )
+ if turn is not None:
+ self.in_flight.pop(session_id, None)
if turn is not None:
- bus.publish("turn.end", {"session_id": session_id})
- # Flush the send-while-busy queue on NATURAL completion (mirrors
- # ``_run``): a plain Stop keeps the queue, send_now opts back in.
- should_flush = (not cancelled and not (turn is not None and turn.stop_no_flush)) or (
- turn is not None and turn.flush_on_cancel
+ bus.publish(
+ "turn.end",
+ _turn_event_payload(session_id, turn_token),
+ )
+ if durable_turn_registered:
+ try:
+ durable_terminal_result = self._terminalize_durable_turn(
+ turn_token,
+ self._durable_terminal_outcome(
+ is_error=terminal_is_error,
+ settled_by=(
+ SETTLED_BY_STOPPED
+ if cancelled
+ else settled_by or None
+ ),
+ ),
+ settled_by=(
+ SETTLED_BY_STOPPED
+ if cancelled
+ else settled_by or SETTLED_BY_TERMINAL_RESULT
+ ),
+ evidence_kind="agent_initiated_terminal",
+ evidence=(
+ dict(terminal_evidence)
+ if isinstance(terminal_evidence, dict)
+ else None
+ ),
+ )
+ except Exception:
+ logger.exception(
+ "agent-initiated durable terminal reconciliation deferred "
+ "for Turn=%s",
+ turn_token,
+ )
+ should_flush = (
+ not bool(durable_terminal_result.get("preserve_queue"))
+ and not cancelled
+ and settled_by != SETTLED_BY_STOPPED
)
if should_flush:
try:
- await self.flush_queue(session_id)
+ if durable_turn_registered:
+ await self._resume_post_terminal(session_id)
+ else:
+ await self.flush_queue(session_id)
except Exception:
- logger.debug("agent-initiated turn: flush_queue failed", exc_info=True)
+ logger.debug("agent-initiated turn: queue resume failed", exc_info=True)
+ elif durable_turn_registered and durable_terminal_result.get(
+ "successor_turn_id"
+ ):
+ await self._resume_durable_session(session_id)
try:
task = asyncio.create_task(_holder(), name="agent-initiated-turn-holder")
@@ -2178,8 +5372,12 @@ class SessionTurnManager:
task=task,
context=context,
started_at=_utc_now_iso(),
+ logical_turn_id=turn_token,
+ )
+ bus.publish(
+ "turn.start",
+ _turn_event_payload(session_id, turn_token),
)
- bus.publish("turn.start", {"session_id": session_id})
if self._pop_context_flag(context, _SHOW_CHECKPOINT_DEFERRED_START_KEY):
self._begin_show_checkpoint(context)
return True
@@ -2225,15 +5423,9 @@ class SessionTurnManager:
task_execution_id = str(spec.get("task_execution_id") or "").strip()
if task_execution_id:
identity["task_execution_id"] = task_execution_id
- coalesced_queue = spec.get("coalesced_queue")
- if isinstance(coalesced_queue, dict):
- copied_queue = dict(coalesced_queue)
- execution_ids = copied_queue.get("execution_ids")
- if isinstance(execution_ids, list):
- copied_queue["execution_ids"] = list(execution_ids)
- identity["coalesced_queue"] = copied_queue
- elif coalesced_queue is not None:
- identity["coalesced_queue"] = coalesced_queue
+ accepted_run_ids = spec.get("accepted_agent_run_ids")
+ if isinstance(accepted_run_ids, list):
+ identity["accepted_agent_run_ids"] = list(accepted_run_ids)
return identity
def register_turn_sink(self, session_key: str, *, on_chunk, done_event, turn_token=None, context=None) -> None:
@@ -2319,7 +5511,11 @@ class SessionTurnManager:
):
return None
token = sink.get("turn_token")
- attribution_keys = ("task_trigger_kind", "task_execution_id", "coalesced_queue")
+ attribution_keys = (
+ "task_trigger_kind",
+ "task_execution_id",
+ "accepted_agent_run_ids",
+ )
if token or any(key in sink for key in attribution_keys):
if context.platform_specific is None:
context.platform_specific = {}
@@ -2335,6 +5531,8 @@ class SessionTurnManager:
if isinstance(execution_ids, list):
copied_value["execution_ids"] = list(execution_ids)
value = copied_value
+ elif isinstance(value, list):
+ value = list(value)
context.platform_specific[key] = value
return {
"session_key": session_key,
@@ -2393,30 +5591,51 @@ class SessionTurnManager:
# --- boot / restore edge transitions -----------------------------------------
@staticmethod
- def reset_stale() -> None:
- """Crash recovery (boot): no turn survives a restart, so any avibe session
- left ``running`` in the table is stale → reset it to ``idle`` so the sidebar
- dot doesn't show a phantom green forever. Runs in ``Controller.__init__``
- BEFORE any ``/internal/events`` subscriber exists, so it does NOT broadcast
- ``session.status`` (the bus drops events with no subscribers); the browser
- reconciles by refetching sessions when its inbox stream (re)connects."""
+ def reset_legacy_ownerless_status() -> None:
+ """Reset only legacy running projections with no durable Turn owner."""
try:
- from core.services import sessions as workbench_sessions_service
-
engine = get_cached_sqlite_engine()
with engine.begin() as conn:
- reset = workbench_sessions_service.reset_running_agent_status(conn)
+ reserve_write_lock(conn)
+ live = select(session_turn_rows.c.session_id).where(
+ session_turn_rows.c.state.in_(delivery_store.TURN_OWNER_STATES)
+ )
+ result = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.agent_status == "running")
+ .where(~agent_sessions.c.id.in_(live))
+ .values(agent_status="idle")
+ )
+ reset = result.rowcount or 0
if reset:
- logger.info("Reset %s stale 'running' agent session(s) to idle on startup", reset)
+ logger.info(
+ "Reset %s ownerless 'running' agent session(s) to idle on startup",
+ reset,
+ )
except Exception:
logger.debug("agent_status startup reset failed", exc_info=True)
def restore_running(self, session_id: Optional[str]) -> None:
- """Re-mark an avibe session ``running`` when its OpenCode poll is restored
- after a restart: the restored poll resumes the backend turn WITHOUT
- re-entering the inbound chokepoint (``handle_message``), so without this the
- dot would read idle for a still-live turn until the poll's terminal result
- settles it back. IM polls carry no workbench session id, so they pass nothing
- here and stay dot-less."""
- if session_id and self.controller is not None:
+ """Restore the status projection for pre-durable OpenCode polls only.
+
+ Durable owners are reconciled once, after every backend identity has been
+ restored. This callback runs while OpenCode is still rebuilding its maps,
+ so it must never start durable reconciliation itself.
+ """
+ if not session_id or self.controller is None:
+ return
+ if not self._durable_schema_available():
+ self.controller.set_agent_status(session_id, "running")
+ return
+ try:
+ with self._sqlite_engine().connect() as conn:
+ has_history = session_id in delivery_store.session_ids_with_turn_history(conn)
+ except Exception:
+ logger.debug(
+ "could not inspect durable Turn history for restored poll %s",
+ session_id,
+ exc_info=True,
+ )
+ return
+ if not has_history:
self.controller.set_agent_status(session_id, "running")
diff --git a/core/show_git.py b/core/show_git.py
index b3b9c50bb..56ef5b6e4 100644
--- a/core/show_git.py
+++ b/core/show_git.py
@@ -97,12 +97,14 @@ class TurnCheckpointContext:
message: str = ""
run_id: str | None = None
message_id: str | None = None
+ turn_id: str | None = None
@dataclass(frozen=True)
class _ActiveTurnCheckpoint:
context: TurnCheckpointContext
started_at: str
+ turn_id: str | None = None
def _record_checkpoint_service_state(active: bool) -> None:
@@ -258,16 +260,134 @@ def _run_id_from_native_message_id(value: Any) -> str | None:
return run_id or None
-def load_turn_checkpoint_context(session_id: str, *, after: str | None = None) -> TurnCheckpointContext:
+def _delivery_snapshot_text(value: Any) -> str:
+ try:
+ snapshot = json.loads(value or "{}")
+ except (TypeError, ValueError):
+ return ""
+ if not isinstance(snapshot, dict):
+ return ""
+ return _read_message_text(
+ snapshot.get("content_text"),
+ snapshot.get("content_json"),
+ )
+
+
+def load_turn_checkpoint_context(
+ session_id: str,
+ *,
+ turn_id: str | None = None,
+ after: str | None = None,
+) -> TurnCheckpointContext:
"""Read the driving message/run without changing the turn event payload."""
try:
- from sqlalchemy import select, tuple_
+ from sqlalchemy import func, select, tuple_
from storage.db import get_cached_sqlite_engine
- from storage.models import agent_runs, messages
+ from storage.models import (
+ agent_runs,
+ message_deliveries,
+ messages,
+ session_turns,
+ )
with get_cached_sqlite_engine().connect() as conn:
+ turn_query = select(
+ session_turns.c.id,
+ session_turns.c.initial_delivery_id,
+ session_turns.c.created_at,
+ session_turns.c.started_at,
+ ).where(session_turns.c.session_id == session_id)
+ if turn_id:
+ turn_query = turn_query.where(session_turns.c.id == turn_id).limit(1)
+ elif after is None:
+ turn_query = (
+ turn_query.where(session_turns.c.state.in_(("starting", "active")))
+ .order_by(
+ func.coalesce(
+ session_turns.c.started_at,
+ session_turns.c.created_at,
+ ).desc(),
+ session_turns.c.id.desc(),
+ )
+ .limit(1)
+ )
+ else:
+ turn_query = (
+ turn_query.where(
+ func.coalesce(
+ session_turns.c.started_at,
+ session_turns.c.created_at,
+ )
+ >= after
+ )
+ .order_by(
+ func.coalesce(
+ session_turns.c.started_at,
+ session_turns.c.created_at,
+ ).asc(),
+ session_turns.c.id.asc(),
+ )
+ .limit(1)
+ )
+ turn = conn.execute(turn_query).first()
+ if turn is not None:
+ delivery = conn.execute(
+ select(
+ message_deliveries.c.id,
+ message_deliveries.c.message_id,
+ message_deliveries.c.snapshot_json,
+ )
+ .where(
+ message_deliveries.c.id == turn.initial_delivery_id
+ )
+ .limit(1)
+ ).first()
+ if delivery is not None:
+ run_id = conn.execute(
+ select(agent_runs.c.id)
+ .where(agent_runs.c.delivery_id == delivery.id)
+ .where(agent_runs.c.run_type != "watch_runtime")
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ .limit(1)
+ ).scalar_one_or_none()
+ if delivery.message_id:
+ message_row = conn.execute(
+ select(
+ messages.c.id,
+ messages.c.author,
+ messages.c.type,
+ messages.c.content_text,
+ messages.c.content_json,
+ messages.c.native_message_id,
+ )
+ .where(messages.c.id == delivery.message_id)
+ .limit(1)
+ ).first()
+ if message_row is not None:
+ return TurnCheckpointContext(
+ message=_read_message_text(
+ message_row.content_text,
+ message_row.content_json,
+ ),
+ run_id=(
+ str(run_id)
+ if run_id is not None
+ else _run_id_from_native_message_id(
+ message_row.native_message_id
+ )
+ ),
+ message_id=str(message_row.id),
+ turn_id=str(turn.id),
+ )
+ return TurnCheckpointContext(
+ message=_delivery_snapshot_text(delivery.snapshot_json),
+ run_id=str(run_id) if run_id is not None else None,
+ message_id=str(delivery.id),
+ turn_id=str(turn.id),
+ )
+
active_run = conn.execute(
select(agent_runs.c.id, agent_runs.c.message, agent_runs.c.prompt)
.where(agent_runs.c.session_id == session_id)
@@ -290,11 +410,9 @@ def load_turn_checkpoint_context(session_id: str, *, after: str | None = None) -
messages.c.native_message_id,
).where(messages.c.session_id == session_id)
if after is None:
- message_query = (
- message_query.where(messages.c.type.not_in(("queued", "draft", "harness_dedupe")))
- .order_by(messages.c.created_at.desc(), messages.c.id.desc())
- .limit(1)
- )
+ message_query = message_query.order_by(
+ messages.c.created_at.desc(), messages.c.id.desc()
+ ).limit(1)
else:
message_query = (
message_query.where(
@@ -735,7 +853,11 @@ class ShowGitCheckpointService:
# Workbench and /internal/dispatch may already have published their UI
# lifecycle before backend execution reached this shared boundary.
if owns_bus_lifecycle:
- self._bus.publish("turn.start", {"session_id": session_id})
+ turn_id = str(payload.get("turn_token") or "").strip()
+ event = {"session_id": session_id}
+ if turn_id:
+ event["turn_id"] = turn_id
+ self._bus.publish("turn.start", event)
def end_turn(self, context: Any) -> None:
"""Publish checkpoint end from the shared terminal-result boundary."""
@@ -751,7 +873,11 @@ class ShowGitCheckpointService:
payload[_TURN_STATE_KEY] = {**state, "ended": True, "message_linked": message_linked}
context.platform_specific = payload
if session_id and (not state.get("start_observed") or state.get("owns_bus_lifecycle")):
- self._bus.publish("turn.end", {"session_id": session_id})
+ turn_id = str(payload.get("turn_token") or "").strip()
+ event = {"session_id": session_id}
+ if turn_id:
+ event["turn_id"] = turn_id
+ self._bus.publish("turn.end", event)
def _handle_event(self, event_type: str, data: Any) -> None:
if event_type not in {"turn.start", "turn.end"} or not isinstance(data, dict):
@@ -770,21 +896,43 @@ class ShowGitCheckpointService:
try:
if event_type == "turn.start":
started_at = datetime.now(timezone.utc).isoformat()
- context = load_turn_checkpoint_context(session_id)
- self._active_turns[session_id] = _ActiveTurnCheckpoint(context=context, started_at=started_at)
+ turn_id = str(data.get("turn_id") or "").strip() or None
+ context = (
+ load_turn_checkpoint_context(session_id, turn_id=turn_id)
+ if turn_id
+ else load_turn_checkpoint_context(session_id)
+ )
+ self._active_turns[session_id] = _ActiveTurnCheckpoint(
+ context=context,
+ started_at=started_at,
+ turn_id=turn_id or context.turn_id,
+ )
self._repository(session_id).checkpoint(PRE_TURN, run_id=context.run_id)
return
active = self._active_turns.pop(session_id, None)
if active is None:
- context = load_turn_checkpoint_context(session_id)
+ turn_id = str(data.get("turn_id") or "").strip() or None
+ context = (
+ load_turn_checkpoint_context(session_id, turn_id=turn_id)
+ if turn_id
+ else load_turn_checkpoint_context(session_id)
+ )
start_context = TurnCheckpointContext()
else:
start_context = active.context
context = (
TurnCheckpointContext()
if start_context.message_id is not None
- else load_turn_checkpoint_context(session_id, after=active.started_at)
+ else load_turn_checkpoint_context(
+ session_id,
+ turn_id=active.turn_id,
+ )
+ if active.turn_id
+ else load_turn_checkpoint_context(
+ session_id,
+ after=active.started_at,
+ )
)
run_id = start_context.run_id or context.run_id
self._repository(session_id).checkpoint(
diff --git a/core/show_session_events.py b/core/show_session_events.py
index 26eb3c989..2535d8079 100644
--- a/core/show_session_events.py
+++ b/core/show_session_events.py
@@ -15,6 +15,8 @@ from config import paths
from config.v2_config import V2Config
from core.services import sessions as workbench_sessions_service
from storage import messages_service
+from storage import message_deliveries
+from storage.agent_session_rows import reserve_write_lock
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
from storage.models import agent_sessions, media_objects, show_session_events
@@ -152,6 +154,7 @@ class ShowSessionEventStore:
with ExitStack() as cleanup:
with self.engine.begin() as conn:
+ reserve_write_lock(conn)
session = conn.execute(
select(agent_sessions.c.id, agent_sessions.c.scope_id, agent_sessions.c.status)
.where(agent_sessions.c.id == session_id)
@@ -229,6 +232,7 @@ class ShowSessionEventStore:
),
transcript_text=transcript_text,
message_id=None,
+ delivery_id=None,
created_at=created_at,
)
)
@@ -261,6 +265,8 @@ class ShowSessionEventStore:
return existing
message: dict[str, Any] | None = None
message_id: str | None = None
+ delivery: dict[str, Any] | None = None
+ delivery_id: str | None = None
writes_annotation = (
event_type == "human.annotation.created"
or (
@@ -271,7 +277,6 @@ class ShowSessionEventStore:
if writes_annotation or (
transcript_text and event_type not in ANNOTATION_EVENT_TYPES
):
- harness_input = requests_dispatch
content: dict[str, Any] = {"text": transcript_text}
metadata: dict[str, Any] = {
"source": "show_page",
@@ -287,42 +292,68 @@ class ShowSessionEventStore:
content["attachments"] = attachments
metadata.update(_annotation_metadata(event_payload, anchor))
if requests_dispatch:
- metadata[messages_service.QUEUED_DISPATCH_TEXT_KEY] = dispatch_text
- message = messages_service.append(
- conn,
- scope_id=session["scope_id"],
- session_id=session_id,
- platform="avibe",
- author=(
- "agent"
- if actor in {"assistant", "system"}
- else messages_service.HARNESS_TYPE
- if harness_input
- else "user"
- ),
- message_type=(
- messages_service.PENDING_TYPE
- if requests_dispatch and reserve_dispatch
- else messages_service.ANNOTATION_TYPE
- if writes_annotation
- else messages_service.HARNESS_TYPE
- if harness_input
- else None
- ),
- text=transcript_text,
- content=content,
- metadata=metadata,
- source=messages_service.HARNESS_TYPE if harness_input else None,
- author_name=SHOW_TRIGGER_KIND[event_type] if harness_input else None,
- author_id=event_id if harness_input else None,
- native_message_id=f"show:{event_id}",
- )
- message_id = message["id"]
- conn.execute(
- update(show_session_events)
- .where(show_session_events.c.id == event_id)
- .values(message_id=message_id)
- )
+ delivery_id = message_deliveries.new_delivery_id()
+ delivery_row = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=session_id,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author=messages_service.HARNESS_TYPE,
+ source=messages_service.HARNESS_TYPE,
+ message_type=(
+ messages_service.ANNOTATION_TYPE
+ if writes_annotation
+ else messages_service.HARNESS_TYPE
+ ),
+ text=transcript_text,
+ content=content,
+ metadata=metadata,
+ author_name=SHOW_TRIGGER_KIND[event_type],
+ author_id=event_id,
+ native_message_id=f"show:{event_id}",
+ ),
+ dispatch_text=dispatch_text,
+ dedupe_key=f"show:{event_id}",
+ history_event={
+ "kind": "admission",
+ "priority": "p3",
+ "state": "reserved",
+ },
+ )
+ delivery = message_deliveries.delivery_payload(delivery_row)
+ conn.execute(
+ update(show_session_events)
+ .where(show_session_events.c.id == event_id)
+ .values(delivery_id=delivery_id)
+ )
+ else:
+ message = messages_service.append(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="agent" if actor in {"assistant", "system"} else "user",
+ message_type=(
+ messages_service.ANNOTATION_TYPE
+ if writes_annotation
+ else None
+ ),
+ text=transcript_text,
+ content=content,
+ metadata=metadata,
+ native_message_id=f"show:{event_id}",
+ )
+ message_id = message["id"]
+ conn.execute(
+ update(show_session_events)
+ .where(show_session_events.c.id == event_id)
+ .values(message_id=message_id)
+ )
workbench_sessions_service.touch_session(conn, session_id)
cleanup.pop_all()
@@ -338,6 +369,8 @@ class ShowSessionEventStore:
"transcript_text": transcript_text,
"message_id": message_id,
"message": message,
+ "delivery_id": delivery_id,
+ "delivery": delivery,
"created_at": created_at,
}
return event
@@ -1105,6 +1138,7 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:
"payload": payload,
"transcript_text": row.get("transcript_text"),
"message_id": row.get("message_id"),
+ "delivery_id": row.get("delivery_id"),
"created_at": row.get("created_at"),
}
@@ -1140,6 +1174,14 @@ def _existing_event_payload(
None,
)
event["message"] = message
+ delivery_id = event.get("delivery_id")
+ event["delivery"] = (
+ message_deliveries.delivery_payload(delivery)
+ if isinstance(delivery_id, str)
+ and delivery_id
+ and (delivery := message_deliveries.get_delivery(conn, delivery_id)) is not None
+ else None
+ )
return event
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index d539eb8e5..bfdff0187 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -297,7 +297,7 @@ Use `vibe agent run --fork-self --message ...` when work should branch from this
When `vibe agent run --session-id <id>` targets an existing Session, it sends a new message into that Session. It does not change that Session's cwd, scope, Agent, model, or reasoning settings; those properties belong to the Session itself. Use a new Session or a fork when those properties need to differ.
-That existing-Session send queues behind an active turn by default. When coordinating another Workbench Session, decide whether its current work should finish or be preempted based on the dependency, urgency, and cost of discarding in-flight work; an explicit user request is one signal, not a prerequisite. Use `vibe agent run --session-id <id> --send-now --message ...` to persist a new Run and then dispatch the Session's FIFO queue head. If older work is already queued, that older head runs first and the new message does not leapfrog it. Use `vibe session send-now <id>` to dispatch an already-queued head without adding another message. Both forms require a Web/Workbench Session, interrupt through the shared Stop path, and start the queue head as a new turn; they do not steer the same native turn. If interruption is refused, the active turn and durable queue remain intact.
+That existing-Session send is a P1 delivery by default: it steers into an active native Turn, starts immediately when idle, and falls back to the durable P3 queue if steering is definitively refused or no longer active. When coordinating another Workbench Session, decide whether its current work should finish, accept a steer, or be replaced based on the dependency, urgency, and cost of discarding in-flight work; an explicit user request is one signal, not a prerequisite. Use `vibe agent run --session-id <id> --send-now --message ...` when the new instruction itself must preempt: `--send-now --message` is a content-P0 admission. With an active turn it claims the shared interrupt control and persists its successor before Stop; when idle it starts that new instruction immediately even if older backlog is held, without releasing or promoting that backlog. Use `vibe session send-now <id>` for an empty-P1 promotion: it adds no Message; it releases the hold and promotes the exact oldest queued P3 head. If a Turn is active, empty P1 steers that exact head into the active logical/native Turn; if the Session is idle, it starts that head as a new Turn. Both forms require a Web/Workbench Session. Only content P0 interrupts through the shared Stop path; if that interruption is refused, the active Turn and durable queue remain intact.
Coordinating Agents can inspect the same durable Workbench queue the user sees with `vibe session queue list <id>`. If one queued instruction has become obsolete, contradictory, or duplicated, remove that exact row with `vibe session queue remove <id> <message-id>`. Always list first and use the returned stable message id; never guess an id or delete a different row to simulate reordering.
diff --git a/core/vibe_agents.py b/core/vibe_agents.py
index f7e091cc8..7293dd49d 100644
--- a/core/vibe_agents.py
+++ b/core/vibe_agents.py
@@ -242,14 +242,14 @@ def _rewrite_definition_agent_name(
return _json_dumps(payload), True
-def _rewrite_queued_agent_provenance(
+def _rewrite_scheduled_agent_provenance(
raw: str | None,
reference_names: frozenset[str],
new_name: str,
*,
agent_id: str,
) -> tuple[str, bool]:
- """Move routing names captured on a queued Workbench harness message."""
+ """Move routing names captured in scheduled submission metadata."""
try:
payload = json.loads(raw or "{}")
@@ -904,7 +904,7 @@ class VibeAgentStore:
conn.execute(
agent_sessions.update()
.where(agent_sessions.c.id.in_(session_ids))
- .values(agent_name=new_name)
+ .values(agent_id=agent_id, agent_name=new_name)
)
run_ids = [
@@ -924,26 +924,9 @@ class VibeAgentStore:
conn.execute(
agent_runs.update()
.where(agent_runs.c.id.in_(run_ids))
- .values(agent_name=new_name)
+ .values(agent_id=agent_id, agent_name=new_name)
)
- queued_rows = conn.execute(
- select(messages.c.id, messages.c.metadata_json).where(messages.c.type == "queued")
- ).mappings().all()
- for row in queued_rows:
- metadata, changed = _rewrite_queued_agent_provenance(
- row["metadata_json"],
- reference_names,
- new_name,
- agent_id=agent_id,
- )
- if changed:
- conn.execute(
- messages.update()
- .where(messages.c.id == row["id"])
- .values(metadata_json=metadata)
- )
-
scope_rows = conn.execute(
select(scope_settings.c.scope_id, scope_settings.c.agent_name, scope_settings.c.settings_json)
).mappings().all()
diff --git a/docs/CLI.md b/docs/CLI.md
index b9a40eff0..31d9243fc 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -263,16 +263,17 @@ vibe agent run --session-id sesworker123 --callback-session-id sescaller456 --me
vibe agent run --no-callback --create-session --scope-id slack::channel::C999 --agent release-reviewer --message 'Post the deployment summary.'
```
-`--send-now` is valid only with an existing `--session-id`. Avibe first
-persists the Agent Run in that Session's queue, then applies the same operation
-as Workbench's **Send now** control: interrupt the active turn through the
-shared Stop path and dispatch the FIFO queue head as a new turn. It does not
-inject input into the same backend-native turn or move the new message ahead of
-older queued work. If interruption is refused, the active turn keeps running
-and the Agent Run remains queued. The accepted command payload names the
-`delivery_intent`; `vibe runs show <run-id>` exposes the durable
-`metadata.delivery_outcome` (`interrupted`, `flushed`, `deferred`, or
-`stop_failed`) after the controller consumes it.
+With an existing `--session-id`, the default admission is P1: Avibe steers the
+new Run into an active native Turn, starts it immediately when idle, or moves the
+same Delivery to the durable P3 queue after a definitive refusal/not-active
+receipt. It does not interrupt the active Turn.
+
+`--send-now` is valid only with an existing `--session-id`. It admits the new
+Run as content P0: with an active Turn, Avibe persists the replacement successor
+before calling Stop; when idle, it starts the new Run immediately. This is
+different from `vibe session send-now`, which adds no message and promotes only
+the exact current P3 queue head, steering it when active or starting it when
+idle. A stale head is refused rather than replaced by the next queued item.
Use `--fork-session <session-id>` when a new Agent Session should branch from
an existing Session's native backend context instead of starting blank. The new
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index ec1714722..70cb0a064 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -873,13 +873,12 @@ with `run_id` / `session_id`, and uses the callback policy to deliver the final
result later. Use `--sync` only when the terminal should wait for completion.
`--async` is still accepted for older scripts but is no longer required.
-With an existing `--session-id`, `--send-now` first persists the Agent Run and
-then reuses Workbench's Session-level interrupt-and-flush transition. It stops
-the active turn through the shared Stop path and dispatches the existing FIFO
-queue head as a new turn. It does not provide same-turn steering or queue
-reordering; a refused interrupt leaves the Run queued. The command response
-includes `delivery_intent`, and `vibe runs show <run-id>` exposes the durable
-`metadata.delivery_outcome` after the controller consumes the request.
+With an existing `--session-id`, the default is P1: steer the new Run into an
+active native Turn, start it when idle, or move the same Delivery to P3 after a
+definitive refusal/not-active receipt. `--send-now` instead admits the new Run as
+content P0 and persists its replacement successor before stopping an active
+Turn. `vibe session send-now` adds no message; it promotes only the exact current
+P3 queue head, steering it when active or starting it when idle.
`--fork-session <session_id>` creates a new Agent Session by forking the source
Session's native backend context. It is for alternate investigations or
diff --git a/docs/plans/session-delivery-foundation.md b/docs/plans/session-delivery-foundation.md
new file mode 100644
index 000000000..5dd888962
--- /dev/null
+++ b/docs/plans/session-delivery-foundation.md
@@ -0,0 +1,155 @@
+# Session Delivery Foundation
+
+## Goal
+
+Replace the mutable pseudo-Message queue with one durable model that remains
+coherent before dispatch, during a native Turn, and after acceptance.
+
+## Ownership
+
+- `message_deliveries` owns submitted content until native acceptance. A queued
+ Delivery remains independently removable. Its submission snapshot is
+ immutable: Agent rename/archive and later routing changes never rewrite it.
+- `session_turns` owns one native dispatch, including its start attempt, exact
+ merged dispatch text, ordered initial Delivery batch, control slot, runtime
+ identity, and terminal snapshot.
+- `messages` owns accepted communication only. One accepted initial batch
+ materializes one Message; every Delivery in that batch links to it.
+- `agent_sessions` owns archive state, queue hold, and composer draft.
+- `agent_runs` may reference the Delivery created for that Run. It does not own
+ queue order and never binds directly to a Message. Each Run has at most one
+ Delivery, while one Turn may accept several Deliveries and therefore several
+ Runs.
+
+Once a Run is bound to a Delivery, the Delivery/Turn owns its completion. A
+producer returning from admission is not a terminal event: a queued Delivery
+keeps its Run nonterminal, exact queue removal cancels both, and accepted work is
+settled only from the Turn's terminal evidence.
+
+## Delivery State Matrix
+
+One runtime matrix defines the meaning of every Delivery state. It records four
+orthogonal facts: FIFO role, whether native work may have happened, whether Run
+cancellation may retire the Delivery directly, and whether durable admission
+has completed. Queue claiming, Run cancellation, Show admission, and recovery
+derive their state sets from those facts; they do not maintain local state
+lists.
+
+| State | Ordering | Native effect | Run cancel | Submission |
+| --- | --- | --- | --- | --- |
+| `reserved` | fence | none | retire | reserved |
+| `queued` | claimable | none | retire | admitted |
+| `claimed` | Turn-owned | possible | Turn owner | admitted |
+| `pending_steer` | fence | none | retire | admitted |
+| `steering` | fence | possible | Turn owner | admitted |
+| `interrupt_waiting` | Turn-owned | possible | Turn owner | admitted |
+| `reconciling_steer` | fence | unknown | Turn owner | admitted |
+| `accepted` | terminal | accepted | complete | admitted |
+| `retired` | terminal | none | complete | retired |
+
+An empty send-now request also carries the exact Delivery ID observed by its
+caller. The writer transaction may promote only that ID if it is still the FIFO
+head; it never substitutes a newer head.
+
+## Queue Batching
+
+Queued Deliveries remain separate until a Turn is claimed. The claim transaction
+selects one compatible leading segment, records every member and its position on
+the Turn, records the exact merged prompt, and only then permits one backend call.
+
+Before claim, removing B from `[A, B]` retires only B. After `[A, B]` is claimed,
+Stop interrupts their shared Turn; neither submission can be withdrawn alone.
+
+Compatibility follows the existing segment rules:
+
+- adjacent ordinary user inputs may merge;
+- native-targeted P1 attempts remain separate before any refusal;
+- scheduled inputs that have fallen back to P3 may merge only under their
+ existing definition, trigger-kind, and rolling-window rules;
+- P1 steering never consumes a P3 backlog segment. A definitively refused P1
+ may fall back to P3 and later participate under normal queue rules.
+
+## Acceptance
+
+Positive native start evidence atomically creates one merged inbound Message and
+links every initial Delivery to that Message and Turn. Original submission times
+stay on Deliveries; the Message `created_at` is the first Delivery's submission
+time and `delivered_at` is the acceptance time. Positive steer evidence
+materializes that single Delivery as a participant Message on the exact Turn,
+including after the Turn became terminal.
+
+The Turn's persisted `start_receipt_outcome='accepted'` is the only gate for
+initial Message materialization. Terminal output alone cannot prove that native
+input was accepted: without the start receipt, the Turn remains owned and
+blocked for reconciliation rather than exposing a phantom Message or idle gap.
+
+Unknown steer outcomes never retry. For Claude and Codex, an unresolvable start
+after restart replays the same Delivery batch once with a private instruction to
+check existing effects before irreversible work. A second unknown attempt retires
+that batch and releases the Session. OpenCode retains its stronger exact-attempt
+reconciliation. A definitive pre-write start failure requeues the entire claimed
+batch in its original order. A late event for T1 cannot mutate T2.
+
+OpenCode writes the persisted Delivery attempt ID as the native `messageID`.
+After restart, reconciliation reads that exact native Message without issuing a
+second prompt: exact presence accepts, while absence or transport uncertainty
+remains blocked.
+
+Terminal settlement, the next compatible FIFO claim, and the Session status
+projection share one writer transaction. Result evidence is committed only after
+output persistence/delivery has settled. A post-native storage failure therefore
+keeps the prior Turn and running projection for recovery instead of exposing an
+idle gap.
+
+Every backend write must first persist enough identity to query that exact
+attempt after restart. OpenCode persists its poll/recovery address before the
+prompt call and restores even an already-completed exact start, so recovery can
+materialize and settle it without replaying native work.
+
+An OpenCode verification error is unknown evidence, not proof that a poll is
+stale. Startup preserves and restores that durable poll until exact positive or
+definitive-negative evidence is available.
+
+Turn-scoped consumers never infer the current input from transcript timestamps.
+They resolve `session_turns.initial_delivery_id`: before acceptance they read the
+Delivery snapshot, and afterward they read its linked Message.
+
+Delivery provenance never selects the Agent that executes later work. Dispatch
+rebuilds routing from the current Session and its stable `agent_id`; historical
+Agent names remain immutable attribution only. Agent archive or rename updates
+live Session/Run bindings and cannot mutate an unaccepted Delivery snapshot.
+
+## Product Policy
+
+- Web user input is P3; while busy it joins the removable backlog.
+- existing-Session Agent Run and Watch input is P1 by default; it steers the
+ active Turn, starts itself when idle, and falls back to P3 only after a
+ definitive refusal or not-active receipt;
+- explicit send-now/content replacement is P0;
+- empty send-now promotes the exact current P3 head segment;
+- only empty P0/Stop establishes the durable backlog hold;
+- content P0 preserves the existing hold and its replacement Turn bypasses it.
+
+On startup, OpenCode first restores the exact logical/runtime/native identity
+map. Restored polling then waits until durable Delivery/Turn reconciliation has
+finished, so neither side can consume the other's evidence early.
+
+## Migration
+
+Revision 0044 follows the already-shipped 0043 migration. It creates
+`message_deliveries` and `session_turns`, moves unaccepted pseudo Messages into
+Deliveries, and leaves accepted communication Messages as immutable history.
+Legacy `pending` rows have no recoverable native identity, so migration retains
+their snapshot as a retired, not-replayed Delivery instead of creating a FIFO
+fence that can never resolve.
+`/new` archives a non-empty Session and re-anchors future work; only empty
+Sessions are physically removed, so accepted Messages and their Delivery/Turn
+audit graph remain intact.
+
+## Delivery Gate
+
+The implementation ships as one authority cutover. No producer may create
+queued, pending, draft, dedupe, silent, or tool-call pseudo Messages. No runtime
+path may merge Agent Runs before the Turn claim. Review stops before another push
+when one root-cause class appears on a second reviewed head, or when three
+findings-bearing heads follow this rewrite without a clean pass.
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 4029b7154..e2fcff231 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -13,6 +13,7 @@ from core.message_output import (
terminal_output_for,
terminal_turn_output,
)
+from core.native_dispatch_phase import mark_backend_dispatch_attempted
from core.reply_enhancer import strip_silent_blocks
from core.services.agent_steering import (
ActiveSteerTarget,
@@ -164,6 +165,7 @@ class ClaudeAgent(BaseAgent):
# Prepare message with file attachment info if present
message = self._prepare_message_with_files(request)
+ mark_backend_dispatch_attempted(request.context)
await client.query(message, session_id=runtime_session_key)
if (
runtime_session_key not in self.receiver_tasks
@@ -1951,7 +1953,11 @@ class ClaudeAgent(BaseAgent):
token = src_payload.get(AGENT_TURN_TOKEN)
runtime_key = src_payload.get(AGENT_RUNTIME_TURN_KEY)
runtime_token = src_payload.get(AGENT_RUNTIME_TURN_TOKEN)
- attribution_keys = ("task_trigger_kind", "task_execution_id", "coalesced_queue")
+ attribution_keys = (
+ "task_trigger_kind",
+ "task_execution_id",
+ "accepted_agent_run_ids",
+ )
current_payload = getattr(context, "platform_specific", None) or {}
updates_attribution = any(
key in src_payload or key in current_payload for key in attribution_keys
@@ -1971,6 +1977,8 @@ class ClaudeAgent(BaseAgent):
context.platform_specific.pop(key, None)
continue
value = src_payload[key]
+ if isinstance(value, list):
+ value = list(value)
if isinstance(value, dict):
value = dict(value)
execution_ids = value.get("execution_ids")
@@ -2262,8 +2270,7 @@ class ClaudeAgent(BaseAgent):
primary = str(spec.get("task_execution_id") or "").strip()
if primary:
run_ids.append(primary)
- coalesced = spec.get("coalesced_queue")
- values = coalesced.get("execution_ids") if isinstance(coalesced, dict) else None
+ values = spec.get("accepted_agent_run_ids")
if isinstance(values, list):
for value in values:
run_id = str(value or "").strip()
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index a3e3a6666..e0a8fe61e 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -19,6 +19,7 @@ from core.avibe_cloud import avibe_cloud_url_available
from core.backend_failure import emit_backend_failure
from core.caller_context import caller_env_for_platform_payload
from core.message_output import stop_output_for, terminal_output_for
+from core.native_dispatch_phase import mark_backend_dispatch_attempted
from core.services.agent_steering import (
ActiveSteerTarget,
SteerOutcome,
@@ -1724,6 +1725,7 @@ class CodexAgent(BaseAgent):
)
if callable(snapshot_generated_images):
snapshot_generated_images(thread_id, request.base_session_id)
+ mark_backend_dispatch_attempted(request.context)
resp = await transport.send_request("turn/start", turn_params)
turn_id = resp.get("id", "")
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 158f56287..03ab624b5 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -20,10 +20,12 @@ import aiohttp
from core.avibe_cloud import avibe_cloud_url_available
from core.backend_failure import emit_backend_failure
from core.message_output import stop_output_for, terminal_output_for
+from core.native_dispatch_phase import mark_backend_dispatch_attempted
from core.resource_governance import governor_from_controller
from core.services.agent_steering import (
ActiveSteerTarget,
SteerOutcome,
+ SteerReconcileRequest,
SteerRequest,
SteerResult,
result as steer_result,
@@ -52,6 +54,8 @@ from .utils import resolve_opencode_model_id, resolve_opencode_reasoning_effort
logger = logging.getLogger(__name__)
_STEERING_SNAPSHOT_KEY = "opencode_native_steering"
_STATUS_RECONCILIATION_FAILURE_LIMIT = 3
+_RESTORED_IM_REGISTRATION_RETRY_DELAY_SECONDS = 0.25
+_RESTORED_IM_PLATFORMS = {"slack", "discord", "telegram", "lark", "wechat"}
def _task_is_stopping(task: asyncio.Task) -> bool:
@@ -616,6 +620,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
# non-404), and the error-cleanup paths reference session_id — keep it
# defined so they can't trip UnboundLocalError (Codex P2).
session_id = None
+ logical_turn_id = ""
+ start_attempt_id = ""
+ native_start_phase = "before_write"
try:
model_hub_runtime = getattr(self.controller, "model_hub_runtime", None)
turn_mode = getattr(model_hub_runtime, "turn_mode", None)
@@ -814,30 +821,81 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
except Exception:
logger.warning("Failed to bind OpenCode caller context for session %s", session_id, exc_info=True)
+ raw_settings_key = _raw_settings_key_from_session_key(request.session_key)
+ platform_payload = request.context.platform_specific or {}
+ logical_turn_id = str(platform_payload.get("turn_token") or "").strip()
+ start_attempt_id = str(
+ platform_payload.get("delivery_start_attempt_id") or ""
+ ).strip()
+ processing_indicator = self.controller.processing_indicator.snapshot_request(
+ request
+ )
+ target_session_id = _target_agent_session_id(request)
+ if target_session_id and logical_turn_id:
+ processing_indicator[_STEERING_SNAPSHOT_KEY] = {
+ "target_session_id": target_session_id,
+ "logical_turn_id": logical_turn_id,
+ "agent": agent_to_use,
+ "system": system_prompt_injection,
+ }
+ if start_attempt_id:
+ processing_indicator["delivery_start_attempt_id"] = start_attempt_id
+ launch_identity = persisted_launch_identity(model_hub_launch)
+ if launch_identity is not None:
+ processing_indicator["model_hub_launch"] = launch_identity
+
await server.mark_run_active(session_id)
run_registered = True
+ # Persist the complete recovery address before the first native write.
+ # A crash after OpenCode accepts the exact message ID can now rebuild the
+ # poll and Turn owner even if no post-prompt Python statement ran.
+ self.sessions.add_active_poll(
+ opencode_session_id=session_id,
+ base_session_id=request.base_session_id,
+ channel_id=request.context.channel_id,
+ thread_id=request.context.thread_id,
+ settings_key=raw_settings_key,
+ working_path=request.working_path,
+ baseline_message_ids=list(baseline_message_ids),
+ ack_reaction_message_id=request.ack_reaction_message_id,
+ ack_reaction_emoji=request.ack_reaction_emoji,
+ typing_indicator_active=request.typing_indicator_active,
+ context_token=str(platform_payload.get("context_token") or ""),
+ processing_indicator=processing_indicator,
+ user_id=request.context.user_id or "",
+ platform=request.context.platform or platform_payload.get("platform") or "",
+ prompt_started_at=None,
+ model_dict=model_dict,
+ reasoning_effort=reasoning_effort,
+ session_key=request.session_key,
+ )
+ mark_backend_dispatch_attempted(request.context)
+ native_start_phase = "may_have_written"
await server.prompt_async(
session_id=session_id,
directory=request.working_path,
text=prompt_text,
+ message_id=str(
+ (request.context.platform_specific or {}).get(
+ "delivery_start_attempt_id"
+ )
+ or ""
+ )
+ or None,
agent=agent_to_use,
model=model_dict,
reasoning_effort=reasoning_effort,
system=system_prompt_injection,
tools={"question": False},
)
- get_started_at = getattr(server, "get_last_prompt_started_at", None)
- prompt_started_at = get_started_at(session_id) if callable(get_started_at) else None
current_task = asyncio.current_task()
if current_task is None:
raise RuntimeError("OpenCode runner task is unavailable")
steer_state = _OpenCodeSteerState(
task=current_task,
base_session_id=request.base_session_id,
- target_session_id=_target_agent_session_id(request),
- logical_turn_id=str(
- (request.context.platform_specific or {}).get("turn_token") or ""
- ),
+ target_session_id=target_session_id,
+ logical_turn_id=logical_turn_id,
native_session_id=session_id,
directory=request.working_path,
agent=agent_to_use,
@@ -853,6 +911,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
)
self._steering_states[request.base_session_id] = steer_state
self.mark_runtime_turn_started(request.context)
+ native_start_phase = "accepted"
logger.info(
"Starting OpenCode poll loop for %s (thread=%s, cwd=%s)",
@@ -861,43 +920,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
request.working_path,
)
- # Keep both the raw settings key for legacy lookup and the complete
- # scoped key so restored polls remain attached to typed scopes.
- raw_settings_key = _raw_settings_key_from_session_key(request.session_key)
- platform_payload = request.context.platform_specific or {}
- processing_indicator = self.controller.processing_indicator.snapshot_request(request)
- if steer_state.target_session_id and steer_state.logical_turn_id:
- processing_indicator[_STEERING_SNAPSHOT_KEY] = {
- "target_session_id": steer_state.target_session_id,
- "logical_turn_id": steer_state.logical_turn_id,
- "agent": steer_state.agent,
- "system": steer_state.system,
- }
- launch_identity = persisted_launch_identity(model_hub_launch)
- if launch_identity is not None:
- processing_indicator["model_hub_launch"] = launch_identity
-
- self.sessions.add_active_poll(
- opencode_session_id=session_id,
- base_session_id=request.base_session_id,
- channel_id=request.context.channel_id,
- thread_id=request.context.thread_id,
- settings_key=raw_settings_key,
- working_path=request.working_path,
- baseline_message_ids=list(baseline_message_ids),
- ack_reaction_message_id=request.ack_reaction_message_id,
- ack_reaction_emoji=request.ack_reaction_emoji,
- typing_indicator_active=request.typing_indicator_active,
- context_token=str(platform_payload.get("context_token") or ""),
- processing_indicator=processing_indicator,
- user_id=request.context.user_id or "",
- platform=request.context.platform or platform_payload.get("platform") or "",
- prompt_started_at=prompt_started_at,
- model_dict=model_dict,
- reasoning_effort=reasoning_effort,
- session_key=request.session_key,
- )
-
poll_server = _SteeringAwareOpenCodeServer(
server,
steer_state,
@@ -944,6 +966,46 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
if session_id:
self.sessions.remove_active_poll(session_id)
raise
+ except OpenCodePromptRejectedError as e:
+ error_text = f"{type(e).__name__}: {e}"
+ logger.error("OpenCode prompt was definitively rejected: %s", e)
+
+ poll_can_be_removed = not (logical_turn_id and start_attempt_id)
+ if logical_turn_id and start_attempt_id:
+ reconcile = getattr(
+ getattr(self.controller, "session_turns", None),
+ "reconcile_start_attempt_not_written",
+ None,
+ )
+ if callable(reconcile):
+ try:
+ poll_can_be_removed = bool(
+ reconcile(
+ logical_turn_id,
+ start_attempt_id,
+ backend=self.name,
+ )
+ )
+ except Exception:
+ logger.exception(
+ "Failed to persist definitive rejected OpenCode start "
+ "for Turn=%s; preserving its active poll",
+ logical_turn_id,
+ )
+
+ await self._remove_ack_reaction(request)
+ if session_id and poll_can_be_removed:
+ self.sessions.remove_active_poll(session_id)
+
+ await self.record_model_hub_native_failure(request.context, error_text)
+ await emit_backend_failure(
+ self.controller,
+ request.context,
+ self.name,
+ error_text,
+ display_text=f"OpenCode request failed: {error_text}",
+ request=request,
+ )
except Exception as e:
error_name = type(e).__name__
error_details = str(e).strip()
@@ -958,8 +1020,15 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
logger.warning(f"Failed to abort OpenCode session after error: {abort_err}")
await self._remove_ack_reaction(request)
- if session_id:
+ if session_id and native_start_phase != "may_have_written":
self.sessions.remove_active_poll(session_id)
+ elif session_id:
+ logger.warning(
+ "Preserving OpenCode active poll after ambiguous native start "
+ "failure for Turn=%s attempt=%s",
+ logical_turn_id,
+ start_attempt_id,
+ )
message = f"OpenCode request failed: {error_text}"
await emit_backend_failure(
@@ -1074,15 +1143,20 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
)
before_insert = _SteeringAwareOpenCodeServer._message_ids(messages)
try:
+ prompt_kwargs = {
+ "session_id": native_session_id,
+ "directory": directory,
+ "text": request.text,
+ "agent": state.agent,
+ "model": state.model,
+ "reasoning_effort": state.reasoning_effort,
+ "system": state.system,
+ "tools": {"question": False},
+ }
+ if request.attempt_id:
+ prompt_kwargs["message_id"] = request.attempt_id
await server.prompt_async(
- session_id=native_session_id,
- directory=directory,
- text=request.text,
- agent=state.agent,
- model=state.model,
- reasoning_effort=state.reasoning_effort,
- system=state.system,
- tools={"question": False},
+ **prompt_kwargs,
)
except aiohttp.ClientConnectorError:
raise
@@ -1137,6 +1211,77 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
runner_generation=native_turn_id,
)
+ async def reconcile_steer_attempt(
+ self,
+ request: SteerReconcileRequest,
+ target: ActiveSteerTarget,
+ ) -> SteerResult:
+ """Resolve one prior OpenCode write by its native message identity."""
+
+ if not request.attempt_id:
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="missing_attempt_identity",
+ backend=self.name,
+ )
+ active_request = target.agent_request
+ base_session_id = (
+ active_request.base_session_id
+ if active_request is not None
+ else target.runtime_key
+ )
+ request_session = self._session_manager.get_request_session(base_session_id)
+ if request_session is None:
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="native_session_unavailable",
+ backend=self.name,
+ )
+ native_session_id, directory, _session_key = request_session
+ if not request.expected_native_turn_id.startswith(f"opencode:{native_session_id}:"):
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="stale_native_session",
+ backend=self.name,
+ )
+ server = self._client_manager._server_manager
+ if server is None:
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="runtime_unavailable",
+ backend=self.name,
+ )
+ try:
+ message = await server.get_message(
+ native_session_id,
+ request.attempt_id,
+ directory,
+ )
+ except Exception as exc: # noqa: BLE001 - absence is not negative proof
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="attempt_evidence_unavailable",
+ backend=self.name,
+ diagnostic=str(exc),
+ )
+ info = message.get("info") if isinstance(message, dict) else None
+ if (
+ isinstance(info, dict)
+ and str(info.get("id") or "") == request.attempt_id
+ and info.get("role") == "user"
+ ):
+ return steer_result(
+ SteerOutcome.ACCEPTED,
+ reason="native_message_found",
+ backend=self.name,
+ native_message_id=request.attempt_id,
+ )
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="untrusted_attempt_evidence",
+ backend=self.name,
+ )
+
async def handle_stop(self, request: AgentRequest) -> bool:
task = self._active_requests.get(request.base_session_id)
if not task or task.done():
@@ -1275,6 +1420,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
restored_count = 0
stale_poll_ids = []
+ restoration_results: list[
+ tuple[asyncio.Future[bool], asyncio.Event, Any]
+ ] = []
for session_id, poll_info in active_polls.items():
poll_platform = restored_platform_from_poll_info(poll_info)
@@ -1283,6 +1431,21 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
existing_task = self._active_requests.get(poll_info.base_session_id)
if existing_task is not None and not existing_task.done():
continue
+ processing_snapshot = (
+ poll_info.processing_indicator
+ if isinstance(poll_info.processing_indicator, dict)
+ else {}
+ )
+ start_attempt_id = str(
+ processing_snapshot.get("delivery_start_attempt_id") or ""
+ ).strip()
+ steering_snapshot = processing_snapshot.get(_STEERING_SNAPSHOT_KEY)
+ logical_turn_id = (
+ str(steering_snapshot.get("logical_turn_id") or "").strip()
+ if isinstance(steering_snapshot, dict)
+ else ""
+ )
+ verification_unknown = False
try:
server = await self._get_server()
messages = await server.list_messages(
@@ -1291,10 +1454,17 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
)
except Exception as err:
logger.warning(f"Failed to verify OpenCode session {session_id} for restoration: {err}")
- stale_poll_ids.append(session_id)
- continue
+ messages = []
+ verification_unknown = True
baseline_message_ids = set(poll_info.baseline_message_ids)
+ start_attempt_found = any(
+ start_attempt_id
+ and message.get("info", {}).get("role") == "user"
+ and str(message.get("info", {}).get("id") or "")
+ == start_attempt_id
+ for message in messages
+ )
has_in_progress = False
last_assistant_finish = None
last_completed_assistant_index = -1
@@ -1327,16 +1497,17 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
if has_post_assistant_user
else None
)
- try:
- status_unknown = False
- native_status = await server.get_session_status(
- poll_info.opencode_session_id,
- poll_info.working_path,
- )
- except Exception as err:
- logger.debug("Failed to read OpenCode status while restoring %s: %s", session_id, err)
- status_unknown = True
- native_status = None
+ status_unknown = verification_unknown
+ native_status = None
+ if not verification_unknown:
+ try:
+ native_status = await server.get_session_status(
+ poll_info.opencode_session_id,
+ poll_info.working_path,
+ )
+ except Exception as err:
+ logger.debug("Failed to read OpenCode status while restoring %s: %s", session_id, err)
+ status_unknown = True
native_status_is_active = (
native_status is not None
@@ -1354,8 +1525,23 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
or has_in_progress
or last_assistant_finish == "tool-calls"
or has_post_assistant_user
+ or start_attempt_found
)
if not session_still_active:
+ if start_attempt_id and logical_turn_id:
+ try:
+ self.controller.session_turns.reconcile_start_attempt_not_written(
+ logical_turn_id,
+ start_attempt_id,
+ backend="opencode",
+ )
+ except Exception:
+ logger.exception(
+ "Failed to persist definitive missing OpenCode start "
+ "attempt for Turn=%s",
+ logical_turn_id,
+ )
+ continue
logger.info(f"OpenCode session {session_id} has completed, removing from active polls")
await self._poll_loop.remove_restored_ack(poll_info)
stale_poll_ids.append(session_id)
@@ -1366,26 +1552,20 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
f"(thread={poll_info.base_session_id}, cwd={poll_info.working_path})"
)
- # Re-mark the avibe workbench session ``running`` via the turn owner (FSM).
- # ``SessionTurnManager.reset_stale`` flips every ``running`` row to ``idle``
- # on startup, but a restored poll resumes the backend turn WITHOUT
- # re-entering ``AgentService.handle_message`` (the inbound status
- # chokepoint), so without this the sidebar dot would show idle/gray for a
- # turn that is still live until it settles. The outbound chokepoint (the
- # poll loop's terminal result) settles it back to idle/failed, so only the
- # ``running`` flip is missing here (Codex P2). IM polls carry no workbench
- # session id, so they are unaffected — only avibe sessions get a dot.
- workbench_session_id = self._workbench_session_id_for_poll(poll_info)
- if workbench_session_id:
- self.controller.session_turns.restore_running(workbench_session_id)
-
+ restoration_ready = asyncio.get_running_loop().create_future()
+ restoration_published = asyncio.Event()
task = asyncio.create_task(
self._run_restored_poll_loop_with_tracking(
poll_info,
reconcile_initial_status=status_unknown,
reconcile_after_message_ids=reconcile_after_message_ids,
+ restoration_ready=restoration_ready,
+ restoration_published=restoration_published,
)
)
+ restoration_results.append(
+ (restoration_ready, restoration_published, poll_info)
+ )
self._active_requests[poll_info.base_session_id] = task
self._session_manager.set_request_session(
poll_info.base_session_id,
@@ -1393,11 +1573,27 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
poll_info.working_path,
restored_session_key_from_poll_info(poll_info),
)
- restored_count += 1
-
for session_id in stale_poll_ids:
self.sessions.remove_active_poll(session_id)
+ if restoration_results:
+ registered = await asyncio.gather(
+ *(future for future, _, _ in restoration_results)
+ )
+ for is_registered, (_, published, poll_info) in zip(
+ registered,
+ restoration_results,
+ ):
+ try:
+ if not is_registered:
+ continue
+ workbench_session_id = self._workbench_session_id_for_poll(poll_info)
+ if workbench_session_id:
+ self.controller.session_turns.restore_running(workbench_session_id)
+ restored_count += 1
+ finally:
+ published.set()
+
if restored_count > 0:
logger.info(f"Restored {restored_count} active poll loop(s)")
if stale_poll_ids:
@@ -1411,74 +1607,140 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
*,
reconcile_initial_status: bool = False,
reconcile_after_message_ids: set[str] | None = None,
+ restoration_ready: asyncio.Future[bool] | None = None,
+ restoration_published: asyncio.Event | None = None,
) -> None:
- server = await self._get_server()
- await server.mark_run_active(poll_info.opencode_session_id)
current_task = asyncio.current_task()
steer_state = None
- steering_snapshot = (
- poll_info.processing_indicator.get(_STEERING_SNAPSHOT_KEY)
- if isinstance(poll_info.processing_indicator, dict)
- else None
- )
- target_session_id = (
- str(steering_snapshot.get("target_session_id") or "")
- if isinstance(steering_snapshot, dict)
- else ""
- )
- logical_turn_id = (
- str(steering_snapshot.get("logical_turn_id") or "")
- if isinstance(steering_snapshot, dict)
- else ""
- )
- has_steering_identity = bool(target_session_id and logical_turn_id)
- if current_task is not None and (
- has_steering_identity
- or reconcile_initial_status
- or reconcile_after_message_ids is not None
- ):
- steer_state = _OpenCodeSteerState(
- task=current_task,
- base_session_id=poll_info.base_session_id,
- target_session_id=target_session_id,
- logical_turn_id=logical_turn_id,
- native_session_id=poll_info.opencode_session_id,
- directory=poll_info.working_path,
- agent=(
- steering_snapshot.get("agent")
- if isinstance(steering_snapshot, dict)
- and isinstance(steering_snapshot.get("agent"), str)
- else None
- ),
- model=poll_info.model_dict,
- reasoning_effort=poll_info.reasoning_effort,
- system=(
- steering_snapshot.get("system")
- if isinstance(steering_snapshot, dict)
- and isinstance(steering_snapshot.get("system"), str)
- else None
- ),
- baseline_message_ids=set(poll_info.baseline_message_ids),
- awaiting_after_message_ids=(
- set(reconcile_after_message_ids)
- if reconcile_after_message_ids is not None
- else None
- ),
- idle_reconciliation_message=self._idle_reconciliation_message(
- poll_info.model_dict,
- poll_info.reasoning_effort,
- ),
- restored=True,
- reconcile_initial_status=reconcile_initial_status,
+ server = None
+ restoration_registered = False
+ try:
+ poll_platform = restored_platform_from_poll_info(poll_info)
+ registration_attempts = 2 if poll_platform in _RESTORED_IM_PLATFORMS else 1
+ for attempt in range(registration_attempts):
+ try:
+ server = await self._get_server()
+ await server.mark_run_active(poll_info.opencode_session_id)
+ break
+ except Exception:
+ if attempt + 1 >= registration_attempts:
+ raise
+ logger.warning(
+ "Retrying restored OpenCode IM poll registration for session=%s",
+ poll_info.opencode_session_id,
+ exc_info=True,
+ )
+ await asyncio.sleep(_RESTORED_IM_REGISTRATION_RETRY_DELAY_SECONDS)
+ steering_snapshot = (
+ poll_info.processing_indicator.get(_STEERING_SNAPSHOT_KEY)
+ if isinstance(poll_info.processing_indicator, dict)
+ else None
)
- if has_steering_identity:
- self._steering_states[poll_info.base_session_id] = steer_state
- self._restored_poll_servers[current_task] = _SteeringAwareOpenCodeServer(
- server,
- steer_state,
+ target_session_id = (
+ str(steering_snapshot.get("target_session_id") or "")
+ if isinstance(steering_snapshot, dict)
+ else ""
)
- try:
+ logical_turn_id = (
+ str(steering_snapshot.get("logical_turn_id") or "")
+ if isinstance(steering_snapshot, dict)
+ else ""
+ )
+ has_steering_identity = bool(target_session_id and logical_turn_id)
+ if current_task is not None and (
+ has_steering_identity
+ or reconcile_initial_status
+ or reconcile_after_message_ids is not None
+ ):
+ steer_state = _OpenCodeSteerState(
+ task=current_task,
+ base_session_id=poll_info.base_session_id,
+ target_session_id=target_session_id,
+ logical_turn_id=logical_turn_id,
+ native_session_id=poll_info.opencode_session_id,
+ directory=poll_info.working_path,
+ agent=(
+ steering_snapshot.get("agent")
+ if isinstance(steering_snapshot, dict)
+ and isinstance(steering_snapshot.get("agent"), str)
+ else None
+ ),
+ model=poll_info.model_dict,
+ reasoning_effort=poll_info.reasoning_effort,
+ system=(
+ steering_snapshot.get("system")
+ if isinstance(steering_snapshot, dict)
+ and isinstance(steering_snapshot.get("system"), str)
+ else None
+ ),
+ baseline_message_ids=set(poll_info.baseline_message_ids),
+ awaiting_after_message_ids=(
+ set(reconcile_after_message_ids)
+ if reconcile_after_message_ids is not None
+ else None
+ ),
+ idle_reconciliation_message=self._idle_reconciliation_message(
+ poll_info.model_dict,
+ poll_info.reasoning_effort,
+ ),
+ restored=True,
+ reconcile_initial_status=reconcile_initial_status,
+ )
+ if has_steering_identity:
+ self._steering_states[poll_info.base_session_id] = steer_state
+ self._restored_poll_servers[current_task] = _SteeringAwareOpenCodeServer(
+ server,
+ steer_state,
+ )
+ restoration_registered = True
+ if restoration_ready is not None and not restoration_ready.done():
+ restoration_ready.set_result(True)
+ if restoration_published is not None:
+ await restoration_published.wait()
+ delivery_recovery_complete = getattr(
+ self.controller,
+ "_delivery_recovery_complete",
+ None,
+ )
+ if delivery_recovery_complete is not None:
+ await delivery_recovery_complete.wait()
await self._poll_loop.run_restored_poll_loop(poll_info)
+ except Exception as err:
+ if restoration_registered:
+ raise
+ else:
+ steering_snapshot = (
+ poll_info.processing_indicator.get(_STEERING_SNAPSHOT_KEY)
+ if isinstance(poll_info.processing_indicator, dict)
+ else None
+ )
+ logical_turn_id = (
+ str(steering_snapshot.get("logical_turn_id") or "").strip()
+ if isinstance(steering_snapshot, dict)
+ else ""
+ )
+ terminal_persisted = False
+ if logical_turn_id:
+ try:
+ terminal_persisted = bool(
+ self.controller.session_turns.fail_restored_backend_turn(
+ logical_turn_id,
+ backend="opencode",
+ reason="poll_registration_failed",
+ )
+ )
+ except Exception:
+ logger.exception(
+ "Failed to terminalize OpenCode Turn=%s after poll registration error",
+ logical_turn_id,
+ )
+ if terminal_persisted:
+ self.sessions.remove_active_poll(poll_info.opencode_session_id)
+ logger.error(
+ "OpenCode poll registration failed for session=%s: %s",
+ poll_info.opencode_session_id,
+ err,
+ )
finally:
if current_task is not None:
self._restored_poll_servers.pop(current_task, None)
@@ -1487,10 +1749,19 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
steer_state.closing = True
if self._steering_states.get(poll_info.base_session_id) is steer_state:
self._steering_states.pop(poll_info.base_session_id, None)
- await server.mark_run_inactive(poll_info.opencode_session_id)
+ if server is not None:
+ try:
+ await server.mark_run_inactive(poll_info.opencode_session_id)
+ except Exception:
+ logger.exception(
+ "Failed to clear restored OpenCode run marker for session=%s",
+ poll_info.opencode_session_id,
+ )
if self._active_requests.get(poll_info.base_session_id) is current_task:
self._active_requests.pop(poll_info.base_session_id, None)
self._session_manager.pop_request_session(poll_info.base_session_id)
+ if restoration_ready is not None and not restoration_ready.done():
+ restoration_ready.set_result(False)
def _prepare_message_with_files(self, request: AgentRequest) -> str:
"""Prepare message with file attachment information.
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index 71d5e839e..65b0c625c 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -1506,6 +1506,7 @@ class OpenCodeServerManager:
session_id: str,
directory: str,
text: str,
+ message_id: Optional[str] = None,
agent: Optional[str] = None,
model: Optional[Dict[str, str]] = None,
reasoning_effort: Optional[str] = None,
@@ -1521,6 +1522,8 @@ class OpenCodeServerManager:
body: Dict[str, Any] = {
"parts": [{"type": "text", "text": text}],
}
+ if message_id:
+ body["messageID"] = message_id
if agent:
body["agent"] = agent
if model:
diff --git a/modules/agents/service.py b/modules/agents/service.py
index c5b212e37..747e0def8 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -378,7 +378,11 @@ class AgentService:
and gate.token
and gate.runtime_started
):
- self.release_runtime_turn(request.context)
+ # A stale Stop result proves only that this process-local gate no
+ # longer owns a stoppable runtime. It is not terminal evidence for
+ # the durable Turn: ``not_active`` is consumed by the Turn control
+ # receipt, while ``runtime_unavailable`` remains ambiguous.
+ self.release_runtime_turn_key(runtime_key, gate.token)
return handled
def mark_runtime_turn_started(self, context: Any) -> None:
@@ -393,6 +397,15 @@ class AgentService:
gate.runtime_started = True
gate.liveness_probe = self._capture_backend_liveness(gate, context)
self._start_runtime_liveness_monitor(runtime_key, gate, runtime_token)
+ manager = getattr(self.controller, "session_turns", None)
+ bind_native = getattr(manager, "on_native_start", None)
+ if callable(bind_native):
+ bind_native(
+ context,
+ backend=str(gate.backend or ""),
+ runtime_key=runtime_key,
+ runtime_turn_id=runtime_token,
+ )
def _capture_backend_liveness(
self,
@@ -658,7 +671,18 @@ class AgentService:
gate = self._turn_gates.get(runtime_key)
if gate is None or gate.token != runtime_token:
return
- self.release_runtime_turn_key(runtime_key, runtime_token)
+ manager = getattr(self.controller, "session_turns", None)
+ bind_terminal = getattr(manager, "on_native_terminal", None)
+ try:
+ if callable(bind_terminal):
+ try:
+ bind_terminal(context, outcome="terminal")
+ except Exception:
+ logger.exception(
+ "native terminal ownership reconciliation failed after output delivery"
+ )
+ finally:
+ self.release_runtime_turn_key(runtime_key, runtime_token)
def release_runtime_turn_key(self, runtime_key: str, runtime_token: str | None = None) -> None:
runtime_key = str(runtime_key or "").strip()
diff --git a/storage/agent_activity_service.py b/storage/agent_activity_service.py
index bdbb16ecf..102d0c957 100644
--- a/storage/agent_activity_service.py
+++ b/storage/agent_activity_service.py
@@ -3,20 +3,23 @@
Composes the two persisted trace sources into per-turn groups:
* interim ``assistant`` messages (``messages`` table, ``type='assistant'``), and
-* ``tool_call`` events (``agent_events`` table, ``event_type='tool_call'``).
-
-A *turn* is bounded by transcript markers rather than an id: it ends at the
-agent's terminal reply (``result`` / ``error`` / backend-failure ``notify``) or,
-when the user starts a new turn without one, is reported as ``interrupted``.
-Grouping is chronological because ``messages`` carries no ``turn_id`` (only
-``agent_events`` does). Both tables persist WHOLE-SECOND ``...Z`` ``created_at``,
-which cannot order same-second rows — but both also mint ids with a MICROSECOND
-clock prefix (``<pfx>_<15-hex microsecond epoch><uuid8>``), so the merge sorts by
+* activity and migrated terminal events from ``agent_events``.
+
+A *turn* ends at the agent's terminal reply (``result`` / ``error`` /
+backend-failure ``notify``) or, when a new turn starts without one, is reported
+as ``interrupted``. Durable input roles and start boundaries come from the
+Delivery-to-Turn ownership graph: an initial Delivery opens its accepted Turn,
+while accepted steer participants remain inside that Turn. Legacy/non-durable
+rows fall back to transcript chronology. Message/event rows persist whole-second
+``created_at``, but both also mint ids with a MICROSECOND clock prefix
+(``<pfx>_<15-hex microsecond epoch><uuid8>``), so the merge sorts by
that decoded microsecond, recovering the true emission order ACROSS tables (a fast
turn's tool call before its same-second terminal; one turn's terminal before the
-next turn's same-second opener). A phase tiebreak (turn-start < activity <
-terminal) only applies when the microsecond can't be decoded (format drift), and
-the whole-second ``created_at`` still bounds the event scan.
+next turn's same-second opener). Durable Turn terminals retain their own
+subsecond timestamp because they do not have a clock-bearing id. A phase
+tiebreak (turn-start < activity < terminal) only applies when the microsecond
+can't be decoded (format drift), and the whole-second ``created_at`` still
+bounds the event scan.
Each group is keyed by the id of its first activity row (stable across summary
and detail reads). ``anchor_message_id`` is the transcript message the chip
@@ -34,8 +37,11 @@ from __future__ import annotations
from datetime import datetime, timezone
from typing import Any, Optional
+from sqlalchemy import func, select
+
from core.backend_failure import is_backend_failure_notification
from storage import agent_events_service, messages_service
+from storage.models import message_deliveries, session_turns
from vibe.message_types import spec_for, types_with
# Bound the scan. The Chat retains ~300 recent messages and pages older on
@@ -110,7 +116,7 @@ def _is_terminal(msg_type: Any, author: Any, metadata: Optional[dict]) -> bool:
Terminals: a visible ``result``/``error`` reply, a ``backend_failure`` ``notify``
diagnostic, OR — when the turn produced nothing user-visible (a ``<silent>``-
stripped/empty final, or a reply-less bookkeeping turn) — the invisible ``silent``
- marker persisted at the delivery chokepoint. Only cancel/Stop (no terminal at all)
+ event persisted at the delivery chokepoint. Only cancel/Stop (no terminal at all)
stays ``interrupted``.
A PLAIN ``notify`` is deliberately NOT terminal: agents emit mid-turn notify rows
@@ -162,6 +168,15 @@ def _emit_micros(row_id: Optional[str], ts: datetime) -> int:
return int(ts.timestamp() * 1_000_000)
+def _event_emit_micros(event: dict[str, Any], ts: datetime) -> int:
+ metadata = event.get("metadata") or {}
+ legacy_message_id = metadata.get("legacy_message_id")
+ return _emit_micros(
+ str(legacy_message_id) if legacy_message_id else event.get("id"),
+ ts,
+ )
+
+
def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, Any]]:
"""Merge the recent tail of relevant messages + tool-call events into one
chronologically-ordered list of classified items."""
@@ -175,10 +190,43 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An
events = agent_events_service.list_session_events(
conn,
session_id=session_id,
- event_types=("tool_call",),
+ event_types=("tool_call", "silent_terminal"),
limit=EVENT_SCAN_LIMIT,
newest_first=True,
)
+ message_ids = tuple(
+ str(message["id"])
+ for message in msgs
+ if message.get("id") is not None
+ )
+ accepted_roles: dict[str, dict[str, Any]] = {}
+ if message_ids:
+ rows = conn.execute(
+ select(
+ message_deliveries.c.message_id,
+ message_deliveries.c.id.label("delivery_id"),
+ message_deliveries.c.materialized_at,
+ session_turns.c.initial_delivery_id,
+ session_turns.c.started_at,
+ session_turns.c.created_at.label("turn_created_at"),
+ )
+ .select_from(
+ message_deliveries.join(
+ session_turns,
+ session_turns.c.id == message_deliveries.c.turn_id,
+ )
+ )
+ .where(message_deliveries.c.state == "accepted")
+ .where(message_deliveries.c.message_id.in_(message_ids))
+ ).mappings()
+ for row in rows:
+ if row["message_id"] is None:
+ continue
+ key = str(row["message_id"])
+ candidate = dict(row)
+ current = accepted_roles.get(key)
+ if current is None or candidate["delivery_id"] == candidate["initial_delivery_id"]:
+ accepted_roles[key] = candidate
items: list[dict[str, Any]] = []
for msg in msgs:
@@ -186,21 +234,40 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An
author = msg.get("author")
metadata = msg.get("metadata") or {}
activity_role = spec_for(mtype if isinstance(mtype, str) else "")["activityRole"]
+ accepted_role = accepted_roles.get(str(msg.get("id") or ""))
if _is_terminal(mtype, author, metadata):
kind = "terminal"
elif activity_role == "turn_start":
- kind = "turn_start"
+ kind = (
+ "turn_start"
+ if accepted_role is None
+ or accepted_role["delivery_id"]
+ == accepted_role["initial_delivery_id"]
+ else "ignore"
+ )
elif activity_role == "activity":
kind = "activity"
else:
kind = "ignore"
- mts = _parse_ts(msg.get("created_at"))
+ created_at = msg.get("created_at")
+ if kind == "turn_start" and accepted_role is not None:
+ created_at = (
+ accepted_role.get("started_at")
+ or accepted_role.get("materialized_at")
+ or accepted_role.get("turn_created_at")
+ or created_at
+ )
+ mts = _parse_ts(created_at)
items.append(
{
"ts": mts,
- "sort": _emit_micros(msg.get("id"), mts),
+ "sort": (
+ int(mts.timestamp() * 1_000_000)
+ if accepted_role is not None and kind == "turn_start"
+ else _emit_micros(msg.get("id"), mts)
+ ),
"rank": _PHASE_RANK[kind],
- "created_at": msg.get("created_at"),
+ "created_at": created_at,
"kind": kind,
"id": msg.get("id"),
"mtype": mtype,
@@ -210,7 +277,7 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An
# so a group closing on it must anchor to the (visible) turn trigger
# rather than the marker itself; ``terminal_status`` is resolved here so
# ``notify`` failure/normal is decided with its metadata in hand.
- "is_silent": mtype == messages_service.SILENT_TYPE,
+ "is_silent": False,
"terminal_status": _terminal_status(mtype, metadata) if kind == "terminal" else None,
}
)
@@ -224,9 +291,31 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An
oldest_msg_sort = min((item["sort"] for item in items), default=None)
for event in events:
event_ts = _parse_ts(event.get("created_at"))
- event_sort = _emit_micros(event.get("id"), event_ts)
+ event_sort = _event_emit_micros(event, event_ts)
if oldest_msg_sort is not None and event_sort < oldest_msg_sort:
continue
+ if event.get("event_type") == "silent_terminal":
+ terminal_outcome = (event.get("metadata") or {}).get(
+ "terminal_outcome"
+ )
+ items.append(
+ {
+ "ts": event_ts,
+ "sort": event_sort,
+ "rank": _PHASE_RANK["terminal"],
+ "created_at": event.get("created_at"),
+ "kind": "terminal",
+ "id": event.get("id"),
+ "mtype": "silent_terminal",
+ "row_kind": "turn_terminal",
+ "text": None,
+ "is_silent": True,
+ "terminal_status": (
+ "failed" if terminal_outcome == "failed" else "done"
+ ),
+ }
+ )
+ continue
items.append(
{
"ts": event_ts,
@@ -240,6 +329,44 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An
"text": event.get("text") if include_text else None,
}
)
+ for turn in conn.execute(
+ select(
+ session_turns.c.id,
+ session_turns.c.terminal_outcome,
+ session_turns.c.terminal_at,
+ )
+ .where(session_turns.c.session_id == session_id)
+ .where(session_turns.c.state == "terminal")
+ .where(session_turns.c.terminal_outcome != "not_written")
+ .where(session_turns.c.terminal_at.is_not(None))
+ .order_by(
+ func.julianday(session_turns.c.terminal_at).desc(),
+ session_turns.c.id.desc(),
+ )
+ .limit(MESSAGE_SCAN_LIMIT)
+ ).mappings():
+ terminal_ts = _parse_ts(turn["terminal_at"])
+ items.append(
+ {
+ "ts": terminal_ts,
+ "sort": int(terminal_ts.timestamp() * 1_000_000),
+ "rank": _PHASE_RANK["terminal"],
+ "created_at": turn["terminal_at"],
+ "kind": "terminal",
+ "id": f"turn-terminal:{turn['id']}",
+ "mtype": "turn_terminal",
+ "row_kind": "turn_terminal",
+ "text": None,
+ "is_silent": True,
+ "terminal_status": (
+ "failed"
+ if turn["terminal_outcome"] == "failed"
+ else "interrupted"
+ if turn["terminal_outcome"] in {"canceled", "not_written"}
+ else "done"
+ ),
+ }
+ )
# Sort by decoded emission microsecond (true cross-table order); the phase rank
# is a fallback for undecodable ids, and the id a final deterministic tiebreak.
items.sort(key=lambda item: (item["sort"], item["rank"], item["id"]))
diff --git a/storage/alembic/versions/20260801_0044_session_delivery_foundation.py b/storage/alembic/versions/20260801_0044_session_delivery_foundation.py
new file mode 100644
index 000000000..24efaa2ca
--- /dev/null
+++ b/storage/alembic/versions/20260801_0044_session_delivery_foundation.py
@@ -0,0 +1,1362 @@
+"""separate submitted deliveries from accepted Session messages
+
+Revision ID: 20260801_0044
+Revises: 20260731_0043
+Create Date: 2026-07-31
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from importlib import import_module
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260801_0044"
+down_revision = "20260731_0043"
+branch_labels = None
+depends_on = None
+
+_AGENT_RUN_INDEX_MODULES = (
+ "storage.alembic.versions.20260728_0039_agent_runs_settled_at_index",
+ "storage.alembic.versions.20260728_0041_agent_runs_owed_notice_backoff_index",
+ "storage.alembic.versions.20260729_0042_agent_runs_definition_streak_index",
+)
+
+_OLD_INBOX_ACTIVITY_PREDICATE = (
+ "session_id is not null and type not in "
+ "('queued', 'draft', 'pending', 'harness_dedupe', 'silent')"
+)
+_INBOX_ACTIVITY_SQL = (
+ "create index ix_messages_inbox_activity "
+ "on messages (platform, session_id, created_at desc, id desc) "
+ "where session_id is not null and type in "
+ "('user', 'harness', 'annotation', 'result', 'notify', 'error', 'assistant')"
+)
+_INBOX_AGENT_REPLY_SQL = (
+ "create index ix_messages_inbox_agent_reply "
+ "on messages (platform, session_id, created_at desc, id desc) "
+ "where session_id is not null and type in ('result', 'notify', 'error')"
+)
+_INBOX_USER_SEND_SQL = (
+ "create index ix_messages_inbox_user_send "
+ "on messages (platform, session_id, created_at desc, id desc) "
+ "where session_id is not null and ((author = 'user' and type = 'user') "
+ "or (author = 'harness' and type = 'harness') "
+ "or (author = 'harness' and type = 'annotation'))"
+)
+
+
+def _restore_agent_run_expression_indexes(bind) -> None:
+ # SQLite batch-alter rebuilds the table and cannot reflect expression indexes.
+ for module_name in _AGENT_RUN_INDEX_MODULES:
+ revision_module = import_module(module_name)
+ bind.exec_driver_sql(revision_module.DROP_INDEX_SQL)
+ bind.exec_driver_sql(revision_module.CREATE_INDEX_SQL)
+
+
+def _json(value: object) -> str:
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
+
+
+def _hash(value: str) -> str:
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
+
+
+def _legacy_inbound_type(row: sa.RowMapping) -> str:
+ if (
+ row["author"] == "harness"
+ and row["source"] == "harness"
+ and row["author_name"] == "show_annotation"
+ ):
+ return "annotation"
+ if "harness" in {row["author"], row["source"]}:
+ return "harness"
+ return "user"
+
+
+def _legacy_delivery_dedupe_key(row: sa.RowMapping) -> str | None:
+ native_id = str(row["native_message_id"] or "").strip()
+ if not native_id:
+ return None
+ platform = str(row["platform"] or "")
+ if str(row["type"]) == "harness_dedupe" or _legacy_inbound_type(row) in {
+ "harness",
+ "annotation",
+ }:
+ return f"{platform}:{native_id}"
+ return f"legacy:{platform}:{native_id}"
+
+
+def _legacy_live_run_id(
+ bind,
+ row: sa.RowMapping,
+ provenance_spec: object,
+) -> str | None:
+ run_id = ""
+ if isinstance(provenance_spec, dict):
+ run_id = str(provenance_spec.get("task_execution_id") or "").strip()
+ if not run_id and str(row["native_message_id"] or "").startswith("agent_run:"):
+ run_id = str(row["native_message_id"] or "").removeprefix("agent_run:").strip()
+ if not run_id:
+ return None
+ run = bind.execute(
+ sa.text(
+ "select session_id, status, delivery_id from agent_runs where id = :run_id"
+ ),
+ {"run_id": run_id},
+ ).mappings().first()
+ if run is None:
+ return None
+ if str(run["session_id"] or "") != str(row["session_id"] or ""):
+ raise RuntimeError(
+ f"0044 migration Run {run_id} belongs to a different Session"
+ )
+ if str(run["status"] or "") not in {"queued", "pending", "running", "processing"}:
+ return None
+ linked_delivery_id = str(run["delivery_id"] or "")
+ if linked_delivery_id and linked_delivery_id != str(row["id"]):
+ raise RuntimeError(
+ f"0044 migration Run {run_id} already belongs to Delivery "
+ f"{linked_delivery_id}"
+ )
+ return run_id
+
+
+def _message_snapshot(row: sa.RowMapping) -> dict[str, object]:
+ legacy_type = str(row["type"])
+ inbound_type = (
+ _legacy_inbound_type(row)
+ if legacy_type in {"queued", "pending", "draft", "harness_dedupe"}
+ else None
+ )
+ return {
+ "scope_id": row["scope_id"],
+ "session_id": row["session_id"],
+ "platform": row["platform"],
+ "author": (
+ "user" if inbound_type == "user" else "harness"
+ )
+ if inbound_type is not None
+ else row["author"],
+ "type": inbound_type or legacy_type,
+ "author_id": row["author_id"],
+ "author_name": row["author_name"],
+ "source": row["source"],
+ "native_message_id": row["native_message_id"],
+ "parent_native_message_id": row["parent_native_message_id"],
+ "content_text": row["content_text"],
+ "content_json": row["content_json"] or "{}",
+ "metadata_json": row["metadata_json"] or "{}",
+ "read_at": row["read_at"],
+ }
+
+
+def _metadata(value: object) -> dict[str, object]:
+ try:
+ parsed = json.loads(str(value or "{}"))
+ except (TypeError, ValueError):
+ return {}
+ return dict(parsed) if isinstance(parsed, dict) else {}
+
+
+def _legacy_event_id(bind, message_id: str, event_type: str) -> str:
+ base = f"evt_legacy_{hashlib.sha256(f'{event_type}:{message_id}'.encode()).hexdigest()[:24]}"
+ candidate = base
+ suffix = 0
+ while bind.execute(sa.text("select 1 from agent_events where id = :id"), {"id": candidate}).first():
+ suffix += 1
+ candidate = f"{base}_{suffix}"
+ return candidate
+
+
+def _migrate_legacy_trace(bind, row: sa.RowMapping) -> None:
+ event_type = "tool_call" if row["type"] == "tool_call" else "silent_terminal"
+ metadata = _metadata(row["metadata_json"])
+ metadata.update(
+ {
+ "legacy_message_id": row["id"],
+ "legacy_message_type": row["type"],
+ "legacy_message_snapshot": {
+ **_message_snapshot(row),
+ "created_at": row["created_at"],
+ "updated_at": row["updated_at"],
+ "delivered_at": row["delivered_at"],
+ },
+ "migration_revision": revision,
+ }
+ )
+ existing = bind.execute(
+ sa.text(
+ "select id, metadata_json from agent_events "
+ "where session_id is :session_id and event_type = :event_type "
+ "and json_valid(metadata_json) = 1 "
+ "and json_extract(metadata_json, '$.legacy_message_id') = :message_id limit 1"
+ ),
+ {
+ "session_id": row["session_id"],
+ "event_type": event_type,
+ "message_id": row["id"],
+ },
+ ).first()
+ if existing:
+ previous_metadata_json = str(existing[1] or "{}")
+ existing_metadata = _metadata(existing[1])
+ existing_metadata.update(
+ {
+ **metadata,
+ "migration_event_created": False,
+ "migration_previous_metadata_json": previous_metadata_json,
+ }
+ )
+ bind.execute(
+ sa.text(
+ "update agent_events set metadata_json = :metadata_json "
+ "where id = :id"
+ ),
+ {"id": existing[0], "metadata_json": _json(existing_metadata)},
+ )
+ return
+ metadata["migration_event_created"] = True
+ bind.execute(
+ sa.text(
+ "insert into agent_events ("
+ "id, scope_id, session_id, turn_id, run_id, platform, agent_name, backend, "
+ "event_type, visibility, sequence, content_text, content_json, metadata_json, "
+ "source, created_at, updated_at"
+ ") values ("
+ ":id, :scope_id, :session_id, null, null, :platform, :agent_name, null, "
+ ":event_type, 'trace', null, :content_text, :content_json, :metadata_json, "
+ ":source, :created_at, :updated_at)"
+ ),
+ {
+ "id": _legacy_event_id(bind, str(row["id"]), event_type),
+ "scope_id": row["scope_id"],
+ "session_id": row["session_id"],
+ "platform": row["platform"],
+ "agent_name": row["author_name"],
+ "event_type": event_type,
+ "content_text": row["content_text"],
+ "content_json": row["content_json"] or "{}",
+ "metadata_json": _json(metadata),
+ "source": row["source"],
+ "created_at": row["created_at"],
+ "updated_at": row["updated_at"],
+ },
+ )
+
+
+def _migrate_pseudo_messages(bind) -> None:
+ rows = bind.execute(
+ sa.text(
+ "select id, scope_id, session_id, platform, author, type, author_id, "
+ "author_name, source, native_message_id, parent_native_message_id, "
+ "content_text, content_json, metadata_json, created_at, updated_at, "
+ "delivered_at, read_at from messages where type in "
+ "('queued','pending','draft','harness_dedupe','silent','tool_call') "
+ "order by created_at, id"
+ )
+ ).mappings()
+ latest_drafts: dict[str, sa.RowMapping] = {}
+ seen_queued_sessions: set[str] = set()
+ for row in rows:
+ kind = str(row["type"])
+ session_id = str(row["session_id"] or "")
+ if kind == "draft":
+ if session_id:
+ latest_drafts[session_id] = row
+ continue
+ if kind in {"silent", "tool_call"}:
+ _migrate_legacy_trace(bind, row)
+ continue
+ if not session_id:
+ # There is no Session queue owner to migrate to; retain an audit trace
+ # and remove the pseudo communication record.
+ _migrate_legacy_trace(bind, {**dict(row), "type": "tool_call"})
+ continue
+ session_status = bind.execute(
+ sa.text("select status from agent_sessions where id = :session_id"),
+ {"session_id": session_id},
+ ).scalar_one_or_none()
+ if session_status is None:
+ _migrate_legacy_trace(bind, {**dict(row), "type": "tool_call"})
+ continue
+ snapshot = _message_snapshot(row)
+ snapshot_json = _json(snapshot)
+ metadata = _metadata(row["metadata_json"])
+ provenance = metadata.get("scheduled_provenance")
+ provenance_spec = (
+ provenance.get("platform_specific")
+ if isinstance(provenance, dict)
+ else None
+ )
+ live_run_id = (
+ _legacy_live_run_id(bind, row, provenance_spec)
+ if kind == "queued"
+ else None
+ )
+ dispatch_text = str(
+ metadata.get("_queued_dispatch_text")
+ or row["content_text"]
+ or _metadata(row["content_json"]).get("text")
+ or ""
+ )
+ state = {
+ "queued": "queued",
+ "pending": "retired",
+ "harness_dedupe": "retired",
+ }[kind]
+ if session_status != "active":
+ state = "retired"
+ if (
+ kind == "queued"
+ and session_status == "active"
+ and session_id not in seen_queued_sessions
+ ):
+ seen_queued_sessions.add(session_id)
+ if not live_run_id:
+ # Legacy startup resumed only a live-Run-owned queue head.
+ # Keep an ordinary head held so upgrade cannot dispatch it.
+ bind.execute(
+ sa.text(
+ "update agent_sessions set queue_hold_state = 'held', "
+ "queue_hold_version = queue_hold_version + 1, "
+ "queue_held_at = :held_at where id = :session_id"
+ ),
+ {
+ "held_at": row["updated_at"] or row["created_at"],
+ "session_id": session_id,
+ },
+ )
+ history = {
+ "version": 1,
+ "events": [
+ {
+ "at": row["updated_at"] or row["created_at"],
+ "kind": "migration",
+ "revision": revision,
+ "legacy_type": kind,
+ "outcome": "unknown_not_replayed" if kind == "pending" else "moved",
+ }
+ ],
+ }
+ delivery_values = {
+ "id": row["id"],
+ "session_id": session_id,
+ "state": state,
+ "snapshot_json": snapshot_json,
+ "snapshot_sha256": _hash(snapshot_json),
+ "dispatch_text": dispatch_text,
+ "dispatch_sha256": _hash(dispatch_text),
+ "dedupe_key": _legacy_delivery_dedupe_key(row),
+ "attempt_id": None,
+ "attempt_kind": None,
+ "receipt_outcome": None,
+ "attempt_opened_at": None,
+ "history_json": _json(history),
+ "submitted_at": row["created_at"],
+ "updated_at": row["updated_at"],
+ "retired_at": row["updated_at"] if state == "retired" else None,
+ }
+ bind.execute(
+ sa.text(
+ "insert or ignore into message_deliveries ("
+ "id, session_id, message_id, priority, state, snapshot_json, snapshot_sha256, "
+ "dispatch_text, dispatch_sha256, dedupe_key, turn_id, turn_role, turn_position, "
+ "current_attempt_id, current_attempt_kind, current_target_turn_id, "
+ "current_expected_native_turn_id, current_receipt_outcome, current_receipt_json, "
+ "current_attempt_opened_at, delivery_history_json, version, submitted_at, "
+ "updated_at, materialized_at, retired_at"
+ ") values ("
+ ":id, :session_id, null, 'p3', :state, :snapshot_json, :snapshot_sha256, "
+ ":dispatch_text, :dispatch_sha256, :dedupe_key, null, null, null, "
+ ":attempt_id, :attempt_kind, null, null, :receipt_outcome, '{}', :attempt_opened_at, "
+ ":history_json, 1, :submitted_at, :updated_at, null, :retired_at)"
+ ),
+ delivery_values,
+ )
+ persisted = bind.execute(
+ sa.text(
+ "select session_id, snapshot_sha256, submitted_at from message_deliveries "
+ "where id = :id"
+ ),
+ {"id": row["id"]},
+ ).one()
+ if tuple(persisted) != (
+ session_id,
+ delivery_values["snapshot_sha256"],
+ delivery_values["submitted_at"],
+ ):
+ raise RuntimeError(
+ f"0044 migration Delivery {row['id']} conflicts with its Message snapshot"
+ )
+ bind.execute(
+ sa.text(
+ "update show_session_events set delivery_id = :id, message_id = null "
+ "where message_id = :id"
+ ),
+ {"id": row["id"]},
+ )
+ if live_run_id:
+ linked = bind.execute(
+ sa.text(
+ "update agent_runs set delivery_id = :delivery_id "
+ "where id = :run_id and session_id = :session_id "
+ "and status in ('queued','pending','running','processing') "
+ "and delivery_id is null"
+ ),
+ {
+ "delivery_id": row["id"],
+ "run_id": live_run_id,
+ "session_id": session_id,
+ },
+ )
+ if linked.rowcount != 1:
+ persisted_delivery_id = bind.execute(
+ sa.text("select delivery_id from agent_runs where id = :run_id"),
+ {"run_id": live_run_id},
+ ).scalar_one_or_none()
+ if persisted_delivery_id != row["id"]:
+ raise RuntimeError(
+ f"0044 migration Run {live_run_id} lost its Delivery binding"
+ )
+ bind.execute(
+ sa.text("update media_objects set message_id = null where message_id = :id"),
+ {"id": row["id"]},
+ )
+ for session_id, row in latest_drafts.items():
+ bind.execute(
+ sa.text(
+ "update agent_sessions set composer_draft_text = :text, "
+ "composer_draft_updated_at = :updated_at where id = :session_id"
+ ),
+ {
+ "text": row["content_text"] or "",
+ "updated_at": row["updated_at"] or row["created_at"],
+ "session_id": session_id,
+ },
+ )
+ bind.execute(
+ sa.text(
+ "delete from messages where type in "
+ "('queued','pending','draft','harness_dedupe','silent','tool_call')"
+ )
+ )
+
+
+def _precreated_schema_gaps(bind) -> list[str]:
+ inspector = sa.inspect(bind)
+ gaps: list[str] = []
+ required_columns = {
+ "message_deliveries": {
+ "id", "session_id", "message_id", "priority", "state",
+ "snapshot_json", "snapshot_sha256", "dispatch_text",
+ "dispatch_sha256", "dedupe_key", "turn_id", "turn_role",
+ "turn_position", "current_attempt_id", "current_attempt_kind",
+ "current_target_turn_id", "current_expected_native_turn_id",
+ "current_receipt_outcome", "current_receipt_json",
+ "current_attempt_opened_at", "delivery_history_json", "version",
+ "submitted_at", "updated_at", "materialized_at", "retired_at",
+ },
+ "session_turns": {
+ "id", "session_id", "initial_delivery_id", "state", "backend",
+ "runtime_key", "runtime_turn_id", "native_turn_id",
+ "start_attempt_id", "start_receipt_outcome", "start_receipt_json",
+ "dispatch_text", "dispatch_sha256", "terminal_outcome", "settled_by",
+ "terminal_evidence_kind", "terminal_evidence_json", "control_state",
+ "control_mode", "control_attempt_id", "control_expected_native_turn_id",
+ "control_receipt_outcome", "control_receipt_json",
+ "control_successor_delivery_id", "control_successor_turn_id", "version",
+ "created_at", "updated_at", "started_at", "terminal_at",
+ },
+ }
+ for table_name, expected in required_columns.items():
+ present = {column["name"] for column in inspector.get_columns(table_name)}
+ for name in sorted(expected - present):
+ gaps.append(f"{table_name}.{name}")
+
+ required_checks = {
+ "message_deliveries": {
+ "ck_message_deliveries_priority",
+ "ck_message_deliveries_state",
+ "ck_message_deliveries_current_attempt_kind",
+ "ck_message_deliveries_current_attempt_shape",
+ "ck_message_deliveries_current_receipt",
+ "ck_message_deliveries_history_json",
+ "ck_message_deliveries_materialization",
+ "ck_message_deliveries_turn_membership",
+ },
+ "session_turns": {
+ "ck_session_turns_state",
+ "ck_session_turns_terminal_outcome",
+ "ck_session_turns_start_receipt_outcome",
+ "ck_session_turns_start_shape",
+ "ck_session_turns_control_state",
+ "ck_session_turns_control_mode",
+ "ck_session_turns_terminal_shape",
+ "ck_session_turns_control_shape",
+ },
+ }
+ for table_name, expected in required_checks.items():
+ present = {
+ constraint["name"]
+ for constraint in inspector.get_check_constraints(table_name)
+ }
+ for name in sorted(expected - present):
+ gaps.append(f"constraint {name}")
+
+ required_foreign_keys = {
+ "message_deliveries": {
+ (("session_id",), "agent_sessions"),
+ (("message_id",), "messages"),
+ (("turn_id",), "session_turns"),
+ (("current_target_turn_id",), "session_turns"),
+ },
+ "session_turns": {
+ (("session_id",), "agent_sessions"),
+ (("initial_delivery_id",), "message_deliveries"),
+ (("control_successor_delivery_id",), "message_deliveries"),
+ (("control_successor_turn_id",), "session_turns"),
+ },
+ }
+ for table_name, expected in required_foreign_keys.items():
+ present = {
+ (tuple(foreign_key["constrained_columns"]), foreign_key["referred_table"])
+ for foreign_key in inspector.get_foreign_keys(table_name)
+ if foreign_key.get("options", {}).get("deferrable") is True
+ and str(foreign_key.get("options", {}).get("initially") or "").upper()
+ == "DEFERRED"
+ }
+ for columns, target in sorted(expected - present):
+ gaps.append(f"deferred FK {table_name}.{','.join(columns)}->{target}")
+
+ unique_names = {
+ constraint["name"]
+ for constraint in inspector.get_unique_constraints("message_deliveries")
+ }
+ if "uq_message_deliveries_dedupe" not in unique_names:
+ gaps.append("constraint uq_message_deliveries_dedupe")
+ return gaps
+
+
+def _column_names(bind, table_name: str) -> set[str]:
+ return {column["name"] for column in sa.inspect(bind).get_columns(table_name)}
+
+
+def _index_names(bind, table_name: str) -> set[str]:
+ return {
+ str(name)
+ for name in bind.execute(
+ sa.text(
+ "select name from sqlite_master "
+ "where type = 'index' and tbl_name = :table_name"
+ ),
+ {"table_name": table_name},
+ ).scalars()
+ }
+
+
+def _has_deferred_fk(bind, table_name: str, column: str, target: str) -> bool:
+ return any(
+ foreign_key["constrained_columns"] == [column]
+ and foreign_key["referred_table"] == target
+ and foreign_key.get("options", {}).get("deferrable") is True
+ and str(foreign_key.get("options", {}).get("initially") or "").upper()
+ == "DEFERRED"
+ for foreign_key in sa.inspect(bind).get_foreign_keys(table_name)
+ )
+
+
+def _add_precreated_columns(bind) -> None:
+ session_columns = _column_names(bind, "agent_sessions")
+ if "queue_hold_state" not in session_columns:
+ op.add_column(
+ "agent_sessions",
+ sa.Column(
+ "queue_hold_state",
+ sa.String(),
+ sa.CheckConstraint(
+ "queue_hold_state in ('open', 'held')",
+ name="ck_agent_sessions_queue_hold_state",
+ ),
+ server_default="open",
+ nullable=False,
+ ),
+ )
+ if "queue_hold_version" not in session_columns:
+ op.add_column(
+ "agent_sessions",
+ sa.Column("queue_hold_version", sa.Integer(), server_default="1", nullable=False),
+ )
+ for name, column_type in (
+ ("queue_held_at", sa.String()),
+ ("composer_draft_text", sa.Text()),
+ ("composer_draft_updated_at", sa.String()),
+ ):
+ if name not in session_columns:
+ op.add_column("agent_sessions", sa.Column(name, column_type, nullable=True))
+
+ if "delivery_id" not in _column_names(bind, "show_session_events"):
+ with op.batch_alter_table("show_session_events") as batch:
+ batch.add_column(sa.Column("delivery_id", sa.String(), nullable=True))
+ if "delivery_id" not in _column_names(bind, "agent_runs"):
+ with op.batch_alter_table("agent_runs") as batch:
+ batch.add_column(sa.Column("delivery_id", sa.String(), nullable=True))
+
+
+def _finish_upgrade(bind) -> None:
+ _add_precreated_columns(bind)
+ session_checks = {
+ constraint["name"]
+ for constraint in sa.inspect(bind).get_check_constraints("agent_sessions")
+ }
+ if "ck_agent_sessions_queue_hold_state" not in session_checks:
+ raise RuntimeError(
+ "pre-existing agent_sessions queue hold columns lack their 0044 constraint"
+ )
+ if not _has_deferred_fk(
+ bind, "show_session_events", "delivery_id", "message_deliveries"
+ ):
+ with op.batch_alter_table("show_session_events") as batch:
+ batch.create_foreign_key(
+ "fk_show_session_events_delivery",
+ "message_deliveries",
+ ["delivery_id"],
+ ["id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ )
+ if not _has_deferred_fk(bind, "agent_runs", "delivery_id", "message_deliveries"):
+ with op.batch_alter_table("agent_runs") as batch:
+ batch.create_foreign_key(
+ "fk_agent_runs_delivery",
+ "message_deliveries",
+ ["delivery_id"],
+ ["id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ )
+ _restore_agent_run_expression_indexes(bind)
+
+ delivery_indexes = _index_names(bind, "message_deliveries")
+ for name, columns, unique, where in (
+ (
+ "ix_message_deliveries_session_order",
+ ["session_id", "submitted_at", "id"],
+ False,
+ "state in ('reserved','queued','claimed','pending_steer','steering','reconciling_steer')",
+ ),
+ ("ix_message_deliveries_session_state", ["session_id", "state", "submitted_at", "id"], False, None),
+ ("ix_message_deliveries_turn", ["turn_id", "turn_position"], False, None),
+ ("uq_message_deliveries_turn_position", ["turn_id", "turn_position"], True, "turn_id is not null"),
+ ("ix_message_deliveries_current_attempt", ["current_attempt_id"], False, None),
+ ("ix_message_deliveries_current_target_turn", ["current_target_turn_id"], False, None),
+ ):
+ if name not in delivery_indexes:
+ op.create_index(
+ name,
+ "message_deliveries",
+ columns,
+ unique=unique,
+ **({"sqlite_where": sa.text(where)} if where else {}),
+ )
+
+ turn_indexes = _index_names(bind, "session_turns")
+ for name, columns, unique, where in (
+ ("ix_session_turns_session_created", ["session_id", "created_at", "id"], False, None),
+ ("uq_session_turns_live_session", ["session_id"], True, "state in ('starting','active')"),
+ (
+ "uq_session_turns_message_written_attempt",
+ ["initial_delivery_id"],
+ True,
+ "state <> 'terminal' or start_receipt_outcome = 'accepted'",
+ ),
+ ("uq_session_turns_waiting_successor", ["session_id"], True, "state = 'waiting'"),
+ ("uq_session_turns_control_attempt", ["control_attempt_id"], True, "control_attempt_id is not null"),
+ ("uq_session_turns_start_attempt", ["start_attempt_id"], True, "start_attempt_id is not null"),
+ ):
+ if name not in turn_indexes:
+ op.create_index(
+ name,
+ "session_turns",
+ columns,
+ unique=unique,
+ **({"sqlite_where": sa.text(where)} if where else {}),
+ )
+ if "uq_agent_runs_delivery" not in _index_names(bind, "agent_runs"):
+ op.create_index(
+ "uq_agent_runs_delivery",
+ "agent_runs",
+ ["delivery_id"],
+ unique=True,
+ sqlite_where=sa.text("delivery_id is not null"),
+ )
+
+ _migrate_pseudo_messages(bind)
+ message_checks = {
+ constraint["name"]
+ for constraint in sa.inspect(bind).get_check_constraints("messages")
+ }
+ messages_complete = (
+ "ck_messages_communication_type" in message_checks
+ and _has_deferred_fk(bind, "messages", "session_id", "agent_sessions")
+ )
+ if not messages_complete:
+ _snapshot_message_references(bind)
+ with op.batch_alter_table(
+ "messages",
+ naming_convention={
+ "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s"
+ },
+ ) as batch:
+ batch.drop_constraint(
+ "fk_messages_session_id_agent_sessions",
+ type_="foreignkey",
+ )
+ batch.create_foreign_key(
+ "fk_messages_session_id_agent_sessions",
+ "agent_sessions",
+ ["session_id"],
+ ["id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ )
+ batch.create_check_constraint(
+ "ck_messages_communication_type",
+ "type not in ('queued','pending','draft','harness_dedupe','silent','tool_call')",
+ )
+ _restore_message_references(bind)
+ for index_name, create_sql in (
+ ("ix_messages_inbox_activity", _INBOX_ACTIVITY_SQL),
+ ("ix_messages_inbox_agent_reply", _INBOX_AGENT_REPLY_SQL),
+ ("ix_messages_inbox_user_send", _INBOX_USER_SEND_SQL),
+ ):
+ op.execute(f"drop index if exists {index_name}")
+ op.execute(create_sql)
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ tables = set(sa.inspect(bind).get_table_names())
+ operational_tables = {"message_deliveries", "session_turns"}
+ if operational_tables.issubset(tables):
+ gaps = _precreated_schema_gaps(bind)
+ if gaps:
+ raise RuntimeError(
+ "pre-existing durable Message delivery tables indicate an interrupted "
+ f"0044 migration; incomplete: {', '.join(gaps)}"
+ )
+ _finish_upgrade(bind)
+ return
+ if operational_tables & tables:
+ raise RuntimeError(
+ "pre-existing durable Message delivery tables indicate an interrupted "
+ "0044 migration; incomplete: one operational table is missing"
+ )
+
+ op.add_column(
+ "agent_sessions",
+ sa.Column(
+ "queue_hold_state",
+ sa.String(),
+ sa.CheckConstraint(
+ "queue_hold_state in ('open', 'held')",
+ name="ck_agent_sessions_queue_hold_state",
+ ),
+ server_default="open",
+ nullable=False,
+ ),
+ )
+ op.add_column(
+ "agent_sessions",
+ sa.Column("queue_hold_version", sa.Integer(), server_default="1", nullable=False),
+ )
+ op.add_column("agent_sessions", sa.Column("queue_held_at", sa.String(), nullable=True))
+ op.add_column("agent_sessions", sa.Column("composer_draft_text", sa.Text(), nullable=True))
+ op.add_column("agent_sessions", sa.Column("composer_draft_updated_at", sa.String(), nullable=True))
+ with op.batch_alter_table("show_session_events") as batch:
+ batch.add_column(sa.Column("delivery_id", sa.String(), nullable=True))
+ with op.batch_alter_table("agent_runs") as batch:
+ batch.add_column(sa.Column("delivery_id", sa.String(), nullable=True))
+ _restore_agent_run_expression_indexes(op.get_bind())
+
+ op.create_table(
+ "message_deliveries",
+ sa.Column("id", sa.String(), nullable=False),
+ sa.Column("session_id", sa.String(), nullable=False),
+ sa.Column("message_id", sa.String(), nullable=True),
+ sa.Column("priority", sa.String(), nullable=False),
+ sa.Column("state", sa.String(), nullable=False),
+ sa.Column("snapshot_json", sa.Text(), nullable=True),
+ sa.Column("snapshot_sha256", sa.String(), nullable=False),
+ sa.Column("dispatch_text", sa.Text(), nullable=True),
+ sa.Column("dispatch_sha256", sa.String(), nullable=False),
+ sa.Column("dedupe_key", sa.Text(), nullable=True),
+ sa.Column("turn_id", sa.String(), nullable=True),
+ sa.Column("turn_role", sa.String(), nullable=True),
+ sa.Column("turn_position", sa.Integer(), nullable=True),
+ sa.Column("current_attempt_id", sa.String(), nullable=True),
+ sa.Column("current_attempt_kind", sa.String(), nullable=True),
+ sa.Column("current_target_turn_id", sa.String(), nullable=True),
+ sa.Column("current_expected_native_turn_id", sa.Text(), nullable=True),
+ sa.Column("current_receipt_outcome", sa.String(), nullable=True),
+ sa.Column("current_receipt_json", sa.Text(), server_default="{}", nullable=False),
+ sa.Column("current_attempt_opened_at", sa.String(), nullable=True),
+ sa.Column(
+ "delivery_history_json",
+ sa.Text(),
+ server_default='{"version":1,"events":[]}',
+ nullable=False,
+ ),
+ sa.Column("version", sa.Integer(), server_default="1", nullable=False),
+ sa.Column("submitted_at", sa.String(), nullable=False),
+ sa.Column("updated_at", sa.String(), nullable=False),
+ sa.Column("materialized_at", sa.String(), nullable=True),
+ sa.Column("retired_at", sa.String(), nullable=True),
+ sa.CheckConstraint("priority in ('p0','p1','p3')", name="ck_message_deliveries_priority"),
+ sa.CheckConstraint(
+ "state in ('reserved','queued','claimed','pending_steer','steering',"
+ "'interrupt_waiting','reconciling_steer',"
+ "'accepted','retired')",
+ name="ck_message_deliveries_state",
+ ),
+ sa.CheckConstraint(
+ "current_attempt_kind is null or current_attempt_kind = 'steer'",
+ name="ck_message_deliveries_current_attempt_kind",
+ ),
+ sa.CheckConstraint(
+ "json_valid(delivery_history_json) = 1 "
+ "and json_extract(delivery_history_json, '$.version') = 1 "
+ "and json_type(delivery_history_json, '$.events') = 'array'",
+ name="ck_message_deliveries_history_json",
+ ),
+ sa.CheckConstraint(
+ "(state in ('steering','reconciling_steer') "
+ "and current_attempt_id is not null and current_attempt_kind = 'steer' "
+ "and current_target_turn_id is not null and current_expected_native_turn_id is not null) "
+ "or (state = 'pending_steer' and current_attempt_id is not null "
+ "and current_attempt_kind = 'steer' and current_target_turn_id is not null "
+ "and current_expected_native_turn_id is null) "
+ "or (state not in ('steering','reconciling_steer','pending_steer') "
+ "and current_attempt_id is null "
+ "and current_attempt_kind is null and current_target_turn_id is null "
+ "and current_expected_native_turn_id is null)",
+ name="ck_message_deliveries_current_attempt_shape",
+ ),
+ sa.CheckConstraint(
+ "(state = 'reconciling_steer' "
+ "and current_receipt_outcome = 'unknown') "
+ "or (state <> 'reconciling_steer' "
+ "and current_receipt_outcome is null)",
+ name="ck_message_deliveries_current_receipt",
+ ),
+ sa.CheckConstraint(
+ "(state = 'accepted' and message_id is not null and turn_id is not null "
+ "and turn_role in ('initial','steer') and turn_position is not null "
+ "and materialized_at is not null and snapshot_json is null and dispatch_text is null "
+ "and current_attempt_id is null and current_attempt_kind is null "
+ "and current_target_turn_id is null and current_expected_native_turn_id is null "
+ "and current_receipt_outcome is null and current_attempt_opened_at is null) "
+ "or (state <> 'accepted' and message_id is null and materialized_at is null)",
+ name="ck_message_deliveries_materialization",
+ ),
+ sa.CheckConstraint(
+ "(state in ('claimed','interrupt_waiting') and turn_id is not null "
+ "and turn_role = 'initial' and turn_position is not null) "
+ "or (state = 'accepted' and turn_id is not null and turn_role is not null "
+ "and turn_position is not null) "
+ "or (state not in ('claimed','interrupt_waiting','accepted') "
+ "and turn_id is null and turn_role is null and turn_position is null)",
+ name="ck_message_deliveries_turn_membership",
+ ),
+ sa.ForeignKeyConstraint(
+ ["session_id"],
+ ["agent_sessions.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ ),
+ sa.ForeignKeyConstraint(
+ ["message_id"],
+ ["messages.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ ),
+ sa.ForeignKeyConstraint(
+ ["turn_id"],
+ ["session_turns.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ ),
+ sa.ForeignKeyConstraint(
+ ["current_target_turn_id"],
+ ["session_turns.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ ),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint("dedupe_key", name="uq_message_deliveries_dedupe"),
+ )
+ op.create_table(
+ "session_turns",
+ sa.Column("id", sa.String(), nullable=False),
+ sa.Column("session_id", sa.String(), nullable=False),
+ sa.Column("initial_delivery_id", sa.String(), nullable=False),
+ sa.Column("state", sa.String(), nullable=False),
+ sa.Column("backend", sa.String(), nullable=False),
+ sa.Column("runtime_key", sa.Text(), nullable=True),
+ sa.Column("runtime_turn_id", sa.Text(), nullable=True),
+ sa.Column("native_turn_id", sa.Text(), nullable=True),
+ sa.Column("start_attempt_id", sa.String(), nullable=True),
+ sa.Column("start_receipt_outcome", sa.String(), nullable=True),
+ sa.Column("start_receipt_json", sa.Text(), server_default="{}", nullable=False),
+ sa.Column("dispatch_text", sa.Text(), nullable=True),
+ sa.Column("dispatch_sha256", sa.String(), nullable=True),
+ sa.Column("terminal_outcome", sa.String(), nullable=True),
+ sa.Column("settled_by", sa.String(), nullable=True),
+ sa.Column("terminal_evidence_kind", sa.String(), nullable=True),
+ sa.Column("terminal_evidence_json", sa.Text(), server_default="{}", nullable=False),
+ sa.Column("control_state", sa.String(), nullable=True),
+ sa.Column("control_mode", sa.String(), nullable=True),
+ sa.Column("control_attempt_id", sa.String(), nullable=True),
+ sa.Column("control_expected_native_turn_id", sa.Text(), nullable=True),
+ sa.Column("control_receipt_outcome", sa.String(), nullable=True),
+ sa.Column("control_receipt_json", sa.Text(), server_default="{}", nullable=False),
+ sa.Column("control_successor_delivery_id", sa.String(), nullable=True),
+ sa.Column("control_successor_turn_id", sa.String(), nullable=True),
+ sa.Column("version", sa.Integer(), server_default="1", nullable=False),
+ sa.Column("created_at", sa.String(), nullable=False),
+ sa.Column("updated_at", sa.String(), nullable=False),
+ sa.Column("started_at", sa.String(), nullable=True),
+ sa.Column("terminal_at", sa.String(), nullable=True),
+ sa.CheckConstraint("state in ('waiting','starting','active','terminal')", name="ck_session_turns_state"),
+ sa.CheckConstraint(
+ "terminal_outcome is null or terminal_outcome in ('completed','failed','canceled','not_written')",
+ name="ck_session_turns_terminal_outcome",
+ ),
+ sa.CheckConstraint(
+ "start_receipt_outcome is null or start_receipt_outcome in "
+ "('accepted','not_written','unknown')",
+ name="ck_session_turns_start_receipt_outcome",
+ ),
+ sa.CheckConstraint(
+ "(state = 'waiting' and start_attempt_id is null and dispatch_text is null "
+ "and dispatch_sha256 is null and start_receipt_outcome is null) "
+ "or (state = 'starting' and start_attempt_id is not null "
+ "and dispatch_text is not null and dispatch_sha256 is not null "
+ "and (start_receipt_outcome is null or start_receipt_outcome = 'unknown')) "
+ "or (state = 'active' and start_attempt_id is not null "
+ "and dispatch_text is not null and dispatch_sha256 is not null "
+ "and start_receipt_outcome = 'accepted') "
+ "or (state = 'terminal' and (((terminal_outcome <> 'not_written' "
+ "and start_attempt_id is not null and dispatch_text is not null "
+ "and dispatch_sha256 is not null and start_receipt_outcome = 'accepted') "
+ "or (terminal_outcome = 'failed' and start_attempt_id is not null "
+ "and dispatch_text is not null and dispatch_sha256 is not null "
+ "and start_receipt_outcome = 'unknown')) "
+ "or (terminal_outcome = 'not_written' and start_attempt_id is not null "
+ "and dispatch_text is not null and dispatch_sha256 is not null "
+ "and start_receipt_outcome = 'not_written') "
+ "or (terminal_outcome = 'not_written' and start_attempt_id is null "
+ "and dispatch_text is null and dispatch_sha256 is null)))",
+ name="ck_session_turns_start_shape",
+ ),
+ sa.CheckConstraint(
+ "control_state is null or control_state in "
+ "('pending','interrupting','waiting_terminal','reconciling','refused','settled')",
+ name="ck_session_turns_control_state",
+ ),
+ sa.CheckConstraint(
+ "control_mode is null or control_mode in ('stop_only','replace')",
+ name="ck_session_turns_control_mode",
+ ),
+ sa.CheckConstraint(
+ "(state = 'terminal' and terminal_outcome is not null and terminal_at is not null) "
+ "or (state <> 'terminal' and terminal_outcome is null and terminal_at is null)",
+ name="ck_session_turns_terminal_shape",
+ ),
+ sa.CheckConstraint(
+ "(control_mode = 'replace' and control_successor_delivery_id is not null "
+ "and control_successor_turn_id is not null) "
+ "or (control_mode = 'stop_only' and control_successor_delivery_id is null "
+ "and control_successor_turn_id is null) "
+ "or (control_mode is null and control_successor_delivery_id is null "
+ "and control_successor_turn_id is null)",
+ name="ck_session_turns_control_shape",
+ ),
+ sa.ForeignKeyConstraint(
+ ["session_id"],
+ ["agent_sessions.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ ),
+ sa.ForeignKeyConstraint(
+ ["initial_delivery_id"],
+ ["message_deliveries.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ ),
+ sa.ForeignKeyConstraint(
+ ["control_successor_delivery_id"],
+ ["message_deliveries.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ ),
+ sa.ForeignKeyConstraint(
+ ["control_successor_turn_id"],
+ ["session_turns.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ ),
+ sa.PrimaryKeyConstraint("id"),
+ )
+ _finish_upgrade(bind)
+
+
+def _snapshot_message_references(bind) -> None:
+ bind.execute(
+ sa.text(
+ "create temporary table _0044_show_message_refs as "
+ "select id, message_id from show_session_events where message_id is not null"
+ )
+ )
+ bind.execute(
+ sa.text(
+ "create temporary table _0044_media_message_refs as "
+ "select token, message_id from media_objects where message_id is not null"
+ )
+ )
+
+
+def _restore_message_references(bind) -> None:
+ bind.execute(
+ sa.text(
+ "update show_session_events set message_id = ("
+ "select message_id from _0044_show_message_refs refs "
+ "where refs.id = show_session_events.id) "
+ "where id in (select id from _0044_show_message_refs)"
+ )
+ )
+ bind.execute(
+ sa.text(
+ "update media_objects set message_id = ("
+ "select message_id from _0044_media_message_refs refs "
+ "where refs.token = media_objects.token) "
+ "where token in (select token from _0044_media_message_refs)"
+ )
+ )
+ bind.execute(sa.text("drop table _0044_show_message_refs"))
+ bind.execute(sa.text("drop table _0044_media_message_refs"))
+
+
+def _restore_legacy_messages(bind) -> None:
+ rows = bind.execute(
+ sa.text(
+ "select * from message_deliveries where message_id is null "
+ "and json_valid(delivery_history_json) = 1 "
+ "and json_array_length(json_extract(delivery_history_json, '$.events')) = 1 "
+ "and json_extract(delivery_history_json, '$.events[0].kind') = 'migration'"
+ )
+ ).mappings()
+ for row in rows:
+ snapshot = json.loads(row["snapshot_json"] or "{}")
+ legacy_type = bind.execute(
+ sa.text(
+ "select json_extract(:history, '$.events[0].legacy_type')"
+ ),
+ {"history": row["delivery_history_json"]},
+ ).scalar_one()
+ if legacy_type not in {"queued", "pending", "harness_dedupe"}:
+ raise RuntimeError("0044 downgrade cannot represent this Delivery safely")
+ bind.execute(
+ sa.text(
+ "insert into messages ("
+ "id, scope_id, session_id, platform, author, type, author_id, author_name, source, "
+ "native_message_id, parent_native_message_id, content_text, content_json, metadata_json, "
+ "created_at, updated_at, delivered_at, read_at"
+ ") values ("
+ ":id, :scope_id, :session_id, :platform, :author, :type, :author_id, :author_name, "
+ ":source, :native_message_id, :parent_native_message_id, :content_text, :content_json, "
+ ":metadata_json, :created_at, :updated_at, null, :read_at)"
+ ),
+ {
+ "id": row["id"],
+ **snapshot,
+ "type": legacy_type,
+ "created_at": row["submitted_at"],
+ "updated_at": row["updated_at"],
+ },
+ )
+ bind.execute(
+ sa.text(
+ "update show_session_events set message_id = :id, delivery_id = null "
+ "where delivery_id = :id"
+ ),
+ {"id": row["id"]},
+ )
+ bind.execute(
+ sa.text(
+ "insert into _0044_message_session_refs (message_id, session_id) "
+ "values (:message_id, :session_id)"
+ ),
+ {"message_id": row["id"], "session_id": row["session_id"]},
+ )
+
+
+def _restore_legacy_drafts(bind) -> None:
+ rows = bind.execute(
+ sa.text(
+ "select id, scope_id, composer_draft_text, composer_draft_updated_at, "
+ "updated_at from agent_sessions where composer_draft_text is not null"
+ )
+ ).mappings()
+ for row in rows:
+ session_id = str(row["id"])
+ base_id = (
+ "msg_legacy_draft_"
+ + hashlib.sha256(session_id.encode("utf-8")).hexdigest()[:24]
+ )
+ message_id = base_id
+ suffix = 0
+ while bind.execute(
+ sa.text("select 1 from messages where id = :id"),
+ {"id": message_id},
+ ).first():
+ suffix += 1
+ message_id = f"{base_id}_{suffix}"
+ text = str(row["composer_draft_text"])
+ timestamp = row["composer_draft_updated_at"] or row["updated_at"]
+ bind.execute(
+ sa.text(
+ "insert into messages ("
+ "id, scope_id, session_id, platform, author, type, author_id, author_name, "
+ "source, native_message_id, parent_native_message_id, content_text, "
+ "content_json, metadata_json, created_at, updated_at, delivered_at, read_at"
+ ") values ("
+ ":id, :scope_id, :session_id, 'avibe', 'user', 'draft', null, null, "
+ "'user', null, null, :content_text, :content_json, '{}', :created_at, "
+ ":updated_at, null, null)"
+ ),
+ {
+ "id": message_id,
+ "scope_id": row["scope_id"],
+ "session_id": session_id,
+ "content_text": text,
+ "content_json": _json({"text": text}),
+ "created_at": timestamp,
+ "updated_at": timestamp,
+ },
+ )
+ bind.execute(
+ sa.text(
+ "insert into _0044_message_session_refs (message_id, session_id) "
+ "values (:message_id, :session_id)"
+ ),
+ {"message_id": message_id, "session_id": session_id},
+ )
+
+
+def _restore_legacy_trace_messages(bind) -> None:
+ rows = bind.execute(
+ sa.text(
+ "select id, metadata_json from agent_events "
+ "where event_type in ('tool_call', 'silent_terminal') "
+ "and json_valid(metadata_json) = 1 "
+ "and json_extract(metadata_json, '$.migration_revision') = :revision"
+ ),
+ {"revision": revision},
+ ).mappings()
+ for row in rows:
+ metadata = _metadata(row["metadata_json"])
+ legacy_type = metadata.get("legacy_message_type")
+ snapshot = metadata.get("legacy_message_snapshot")
+ if legacy_type not in {"tool_call", "silent"} or not isinstance(
+ snapshot, dict
+ ):
+ raise RuntimeError(
+ "0044 downgrade cannot restore migrated trace Message safely"
+ )
+ message_id = str(metadata.get("legacy_message_id") or "")
+ if not message_id or bind.execute(
+ sa.text("select 1 from messages where id = :id"),
+ {"id": message_id},
+ ).first():
+ raise RuntimeError(
+ "0044 downgrade cannot restore migrated trace Message identity"
+ )
+ bind.execute(
+ sa.text(
+ "insert into messages ("
+ "id, scope_id, session_id, platform, author, type, author_id, "
+ "author_name, source, native_message_id, parent_native_message_id, "
+ "content_text, content_json, metadata_json, created_at, updated_at, "
+ "delivered_at, read_at"
+ ") values ("
+ ":id, :scope_id, :session_id, :platform, :author, :type, :author_id, "
+ ":author_name, :source, :native_message_id, :parent_native_message_id, "
+ ":content_text, :content_json, :metadata_json, :created_at, :updated_at, "
+ ":delivered_at, :read_at)"
+ ),
+ {"id": message_id, **snapshot, "type": legacy_type},
+ )
+ session_id = str(snapshot.get("session_id") or "")
+ if session_id:
+ bind.execute(
+ sa.text(
+ "insert into _0044_message_session_refs (message_id, session_id) "
+ "values (:message_id, :session_id)"
+ ),
+ {"message_id": message_id, "session_id": session_id},
+ )
+ if metadata.get("migration_event_created") is True:
+ bind.execute(
+ sa.text(
+ "delete from agent_events where id = :id "
+ "and json_valid(metadata_json) = 1 "
+ "and json_extract(metadata_json, '$.migration_revision') = :revision "
+ "and json_extract(metadata_json, '$.legacy_message_id') = :message_id"
+ ),
+ {
+ "id": row["id"],
+ "revision": revision,
+ "message_id": message_id,
+ },
+ )
+ else:
+ previous_metadata_json = metadata.get(
+ "migration_previous_metadata_json"
+ )
+ if not isinstance(previous_metadata_json, str):
+ raise RuntimeError(
+ "0044 downgrade cannot restore pre-existing trace event metadata"
+ )
+ bind.execute(
+ sa.text("update agent_events set metadata_json = :metadata_json where id = :id"),
+ {"id": row["id"], "metadata_json": previous_metadata_json},
+ )
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ unsafe = bind.execute(
+ sa.text(
+ "select count(*) from message_deliveries where not ("
+ "message_id is null and json_valid(delivery_history_json) = 1 "
+ "and json_array_length(json_extract(delivery_history_json, '$.events')) = 1 "
+ "and json_extract(delivery_history_json, '$.events[0].kind') = 'migration' and ("
+ "(json_extract(delivery_history_json, '$.events[0].legacy_type') = 'queued' "
+ "and state in ('queued','retired')) or "
+ "(json_extract(delivery_history_json, '$.events[0].legacy_type') = 'pending' "
+ "and state = 'retired') or "
+ "(json_extract(delivery_history_json, '$.events[0].legacy_type') = 'harness_dedupe' "
+ "and state = 'retired')))"
+ )
+ ).scalar_one()
+ live_turns = bind.execute(
+ sa.text("select count(*) from session_turns where state <> 'terminal'")
+ ).scalar_one()
+ held = bind.execute(
+ sa.text(
+ "select count(*) from agent_sessions sessions "
+ "where sessions.queue_hold_state = 'held' and not exists ("
+ "select 1 from message_deliveries deliveries "
+ "where deliveries.session_id = sessions.id "
+ "and deliveries.message_id is null "
+ "and deliveries.state in ('queued','retired') "
+ "and json_valid(deliveries.delivery_history_json) = 1 "
+ "and json_array_length(json_extract(deliveries.delivery_history_json, '$.events')) = 1 "
+ "and json_extract(deliveries.delivery_history_json, '$.events[0].kind') = 'migration' "
+ "and json_extract(deliveries.delivery_history_json, '$.events[0].legacy_type') = 'queued'"
+ ")"
+ )
+ ).scalar_one()
+ if unsafe or live_turns or held:
+ raise RuntimeError(
+ "0044 downgrade refused: live, accepted, or ambiguous Delivery state cannot be represented without replay risk"
+ )
+ _snapshot_message_references(bind)
+ with op.batch_alter_table(
+ "messages",
+ naming_convention={
+ "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s"
+ },
+ ) as batch:
+ batch.drop_constraint("ck_messages_communication_type", type_="check")
+ batch.drop_constraint(
+ "fk_messages_session_id_agent_sessions",
+ type_="foreignkey",
+ )
+ batch.create_foreign_key(
+ "fk_messages_session_id_agent_sessions",
+ "agent_sessions",
+ ["session_id"],
+ ["id"],
+ ondelete="SET NULL",
+ )
+ _restore_message_references(bind)
+ bind.execute(
+ sa.text(
+ "create temporary table _0044_message_session_refs ("
+ "message_id text primary key, session_id text not null)"
+ )
+ )
+ _restore_legacy_messages(bind)
+ _restore_legacy_drafts(bind)
+ _restore_legacy_trace_messages(bind)
+ op.drop_index("ix_messages_inbox_activity", table_name="messages")
+ op.create_index(
+ "ix_messages_inbox_activity",
+ "messages",
+ ["platform", "session_id", sa.text("created_at desc"), sa.text("id desc")],
+ sqlite_where=sa.text(_OLD_INBOX_ACTIVITY_PREDICATE),
+ )
+ with op.batch_alter_table("show_session_events") as batch:
+ batch.drop_constraint("fk_show_session_events_delivery", type_="foreignkey")
+ batch.drop_column("delivery_id")
+ op.drop_index("uq_agent_runs_delivery", table_name="agent_runs")
+ with op.batch_alter_table("agent_runs") as batch:
+ batch.drop_constraint("fk_agent_runs_delivery", type_="foreignkey")
+ batch.drop_column("delivery_id")
+ _restore_agent_run_expression_indexes(op.get_bind())
+ op.drop_index("uq_session_turns_start_attempt", table_name="session_turns")
+ op.drop_index("uq_session_turns_control_attempt", table_name="session_turns")
+ op.drop_index("uq_session_turns_waiting_successor", table_name="session_turns")
+ op.drop_index("uq_session_turns_message_written_attempt", table_name="session_turns")
+ op.drop_index("uq_session_turns_live_session", table_name="session_turns")
+ op.drop_index("ix_session_turns_session_created", table_name="session_turns")
+ op.drop_table("session_turns")
+ op.drop_index("ix_message_deliveries_current_attempt", table_name="message_deliveries")
+ op.drop_index("ix_message_deliveries_current_target_turn", table_name="message_deliveries")
+ op.drop_index("uq_message_deliveries_turn_position", table_name="message_deliveries")
+ op.drop_index("ix_message_deliveries_turn", table_name="message_deliveries")
+ op.drop_index("ix_message_deliveries_session_state", table_name="message_deliveries")
+ op.drop_index("ix_message_deliveries_session_order", table_name="message_deliveries")
+ op.drop_table("message_deliveries")
+ with op.batch_alter_table("agent_sessions") as batch:
+ batch.drop_constraint("ck_agent_sessions_queue_hold_state", type_="check")
+ batch.drop_column("composer_draft_updated_at")
+ batch.drop_column("composer_draft_text")
+ batch.drop_column("queue_held_at")
+ batch.drop_column("queue_hold_version")
+ batch.drop_column("queue_hold_state")
+ bind.execute(
+ sa.text(
+ "update messages set session_id = ("
+ "select session_id from _0044_message_session_refs refs "
+ "where refs.message_id = messages.id) "
+ "where id in (select message_id from _0044_message_session_refs)"
+ )
+ )
+ bind.execute(sa.text("drop table _0044_message_session_refs"))
diff --git a/storage/background.py b/storage/background.py
index 2152ca276..85aa5a25c 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -1642,24 +1642,6 @@ def _like_contains_pattern(value: str) -> str:
return "%" + "%".join(escape(part) for part in parts) + "%"
-def _coalesced_agent_run_metadata(rows: dict[str, Any], run_ids: list[str]) -> dict[str, Any]:
- messages: list[dict[str, str]] = []
- prompt_parts: list[str] = []
- for run_id in run_ids:
- row = rows[run_id]
- message = str(row["message"] or row["prompt"] or "")
- messages.append({"execution_id": run_id, "message": message})
- if message:
- prompt_parts.append(message)
- metadata: dict[str, Any] = {
- "execution_ids": run_ids,
- "messages": messages,
- }
- if prompt_parts:
- metadata["prompt"] = "\n\n---\n\n".join(prompt_parts)
- return metadata
-
-
def cancel_not_requested() -> Any:
"""SQL for "still nobody has asked to cancel this run", evaluated by SQLite.
@@ -1706,10 +1688,10 @@ def _cancel_aware_terminal_status(
return status, guards
-def _coalesced_terminal_write(
+def _turn_participant_terminal_write(
conn: Any, row: Any, *, run_id: str, ok: bool, error: Optional[str], now: str
) -> Optional[tuple[dict[str, Any], list[Any]]]:
- """The values and the CAS predicates one coalesced run's settlement needs.
+ """Build one Turn participant's guarded terminal write.
``None`` means "write nothing": the row was already settled by another actor.
Without that skip the UPDATE rewrites a row wholesale — a ``record_run_output``
@@ -1758,7 +1740,7 @@ def _coalesced_terminal_write(
return values, predicates
-def complete_coalesced_agent_runs_for_workbench_in_connection(
+def settle_agent_runs_for_turn_in_connection(
conn: Any,
run_ids: list[str],
*,
@@ -1795,7 +1777,7 @@ def complete_coalesced_agent_runs_for_workbench_in_connection(
for final_attempt in (False, True):
if row is None:
break
- plan = _coalesced_terminal_write(
+ plan = _turn_participant_terminal_write(
conn, row, run_id=run_id, ok=ok, error=error, now=now
)
if plan is None:
@@ -1818,7 +1800,7 @@ def complete_coalesced_agent_runs_for_workbench_in_connection(
return completed_ids
-def claim_queued_runs_for_workbench_in_connection(
+def claim_agent_runs_for_turn_in_connection(
conn: Any,
run_ids: list[str],
*,
@@ -1832,72 +1814,55 @@ def claim_queued_runs_for_workbench_in_connection(
continue
seen.add(run_id)
normalized_run_ids.append(run_id)
- queued_run_ids, stale_run_ids = inspect_queued_runs_for_workbench_in_connection(conn, normalized_run_ids)
- if stale_run_ids or queued_run_ids != normalized_run_ids:
+ eligible_run_ids, stale_run_ids = inspect_agent_runs_for_turn_in_connection(
+ conn, normalized_run_ids
+ )
+ if stale_run_ids or eligible_run_ids != normalized_run_ids:
return []
- primary_run_id = normalized_run_ids[0] if normalized_run_ids else ""
- if not primary_run_id:
+ if not normalized_run_ids:
return []
now = started_at or _utc_now_iso()
- rows = {
- row["id"]: row
- for row in conn.execute(select(agent_runs).where(agent_runs.c.id.in_(normalized_run_ids))).mappings()
- }
+ changed_run_ids: list[str] = []
for run_id in normalized_run_ids:
- row = rows[run_id]
- metadata = _json_loads(row["metadata_json"], {})
- if not isinstance(metadata, dict):
- metadata = {}
- metadata["workbench_queue_holds_run"] = run_id != primary_run_id
- metadata["effective_run_id"] = primary_run_id
- if run_id == primary_run_id and len(normalized_run_ids) > 1:
- metadata["coalesced_queue"] = _coalesced_agent_run_metadata(rows, normalized_run_ids)
- if run_id != primary_run_id:
- metadata["coalesced_into_run_id"] = primary_run_id
- result = conn.execute(
- update(agent_runs)
- .where(agent_runs.c.id == run_id)
- .where(agent_runs.c.status.in_(_status_query_values("queued")))
- .values(
- updated_at=now,
- metadata_json=_json_dumps(metadata),
- )
- )
- if not result.rowcount:
- raise RuntimeError(f"failed to claim queued agent run {run_id}")
+ row = conn.execute(
+ select(agent_runs.c.status)
+ .where(agent_runs.c.id == run_id)
+ .limit(1)
+ ).mappings().one()
+ if normalize_run_status(row["status"]) == "running":
continue
result = conn.execute(
update(agent_runs)
.where(agent_runs.c.id == run_id)
.where(agent_runs.c.status.in_(_status_query_values("queued")))
+ .where(agent_runs.c.delivery_id.is_not(None))
.values(
status="running",
started_at=now,
updated_at=now,
- metadata_json=_json_dumps(metadata),
)
)
if not result.rowcount:
- raise RuntimeError(f"failed to claim queued agent run {run_id}")
- _defer_run_ids_updated_from_connection(conn, normalized_run_ids)
+ raise RuntimeError(f"failed to claim Delivery-owned agent run {run_id}")
+ changed_run_ids.append(run_id)
+ _defer_run_ids_updated_from_connection(conn, changed_run_ids)
return normalized_run_ids
-def hold_running_agent_run_for_workbench_in_connection(
+def attach_agent_run_delivery_in_connection(
conn: Any,
run_id: str,
*,
+ session_id: str,
+ delivery_id: str,
delivery_outcome: Optional[dict[str, Any]] = None,
) -> bool:
- """Transfer a claimed Agent Run to the durable Workbench queue.
-
- The caller persists the matching queued message in the same write
- transaction. The queue row therefore cannot become flushable while the
- scheduler still owns the Run as ``running``.
- """
+ """Bind one Agent Run to its one durable input Delivery."""
normalized_run_id = str(run_id or "").strip()
- if not normalized_run_id:
+ normalized_session_id = str(session_id or "").strip()
+ normalized_delivery_id = str(delivery_id or "").strip()
+ if not normalized_run_id or not normalized_session_id or not normalized_delivery_id:
return False
row = conn.execute(
select(agent_runs)
@@ -1909,18 +1874,31 @@ def hold_running_agent_run_for_workbench_in_connection(
metadata = _json_loads(row["metadata_json"], {})
if not isinstance(metadata, dict):
metadata = {}
- metadata["workbench_queue_holds_run"] = True
+ if bool(row["cancel_requested"]):
+ return False
+ if str(row["session_id"] or "").strip() != normalized_session_id:
+ return False
+ existing_delivery_id = str(row["delivery_id"] or "").strip()
+ if existing_delivery_id == normalized_delivery_id:
+ return True
+ if existing_delivery_id:
+ return False
if delivery_outcome is not None:
metadata["delivery_outcome"] = dict(delivery_outcome)
now = _utc_now_iso()
result = conn.execute(
update(agent_runs)
.where(agent_runs.c.id == normalized_run_id)
- .where(agent_runs.c.status.in_(_status_query_values("running")))
+ .where(agent_runs.c.session_id == normalized_session_id)
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values("running") + _status_query_values("queued")
+ )
+ )
.where(agent_runs.c.cancel_requested == 0)
+ .where(agent_runs.c.delivery_id.is_(None))
.values(
- status="queued",
- started_at=None,
+ delivery_id=normalized_delivery_id,
updated_at=now,
metadata_json=_json_dumps(metadata),
)
@@ -1949,23 +1927,19 @@ def agent_run_cancellation_won_in_connection(conn: Any, run_id: str) -> bool:
) == "canceled"
-def cancel_workbench_queued_agent_run_in_connection(
+def cancel_queued_agent_run_delivery_in_connection(
conn: Any,
run_id: str,
*,
session_id: str,
+ delivery_id: str,
) -> bool:
- """Cancel a Run only while the named Workbench queue still owns it.
-
- Queue-row deletion and this transition share the caller's transaction. A
- concurrent claim/settlement therefore either wins before this guard (and the
- row is not removed) or loses after both cancellation and deletion commit.
- Missing Run rows are stale queue input and may be removed.
- """
+ """Cancel a nonterminal Run only while it owns the exact queued Delivery."""
normalized_run_id = str(run_id or "").strip()
normalized_session_id = str(session_id or "").strip()
- if not normalized_run_id or not normalized_session_id:
+ normalized_delivery_id = str(delivery_id or "").strip()
+ if not normalized_run_id or not normalized_session_id or not normalized_delivery_id:
return False
row = conn.execute(
select(agent_runs)
@@ -1974,12 +1948,10 @@ def cancel_workbench_queued_agent_run_in_connection(
).mappings().first()
if row is None:
return True
- metadata = _json_loads(row["metadata_json"], {})
if (
- normalize_run_status(row["status"]) != "queued"
+ normalize_run_status(row["status"]) not in {"queued", "running"}
or str(row["session_id"] or "").strip() != normalized_session_id
- or not isinstance(metadata, dict)
- or metadata.get("workbench_queue_holds_run") is not True
+ or str(row["delivery_id"] or "").strip() != normalized_delivery_id
):
return False
now = _utc_now_iso()
@@ -1987,8 +1959,12 @@ def cancel_workbench_queued_agent_run_in_connection(
update(agent_runs)
.where(agent_runs.c.id == normalized_run_id)
.where(agent_runs.c.session_id == normalized_session_id)
- .where(agent_runs.c.status.in_(_status_query_values("queued")))
- .where(agent_runs.c.metadata_json == row["metadata_json"])
+ .where(agent_runs.c.delivery_id == normalized_delivery_id)
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values("queued") + _status_query_values("running")
+ )
+ )
.values(
status="canceled",
cancel_requested=1,
@@ -2008,6 +1984,56 @@ def cancel_workbench_queued_agent_run_in_connection(
return True
+def cancel_agent_runs_for_retired_deliveries_in_connection(
+ conn: Any,
+ *,
+ session_id: str,
+ delivery_ids: list[str],
+) -> list[str]:
+ """Terminal-cancel every nonterminal Run whose exact Delivery was retired."""
+
+ normalized_session_id = str(session_id or "").strip()
+ normalized_delivery_ids = list(
+ dict.fromkeys(
+ str(delivery_id or "").strip()
+ for delivery_id in delivery_ids
+ if str(delivery_id or "").strip()
+ )
+ )
+ if not normalized_session_id or not normalized_delivery_ids:
+ return []
+ active_statuses = _status_query_values("queued") + _status_query_values("running")
+ run_ids = list(
+ conn.execute(
+ select(agent_runs.c.id)
+ .where(agent_runs.c.session_id == normalized_session_id)
+ .where(agent_runs.c.delivery_id.in_(normalized_delivery_ids))
+ .where(agent_runs.c.status.in_(active_statuses))
+ ).scalars()
+ )
+ if not run_ids:
+ return []
+ now = _utc_now_iso()
+ transition = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id.in_(run_ids))
+ .where(agent_runs.c.session_id == normalized_session_id)
+ .where(agent_runs.c.delivery_id.in_(normalized_delivery_ids))
+ .where(agent_runs.c.status.in_(active_statuses))
+ .values(
+ status="canceled",
+ cancel_requested=1,
+ cancel_requested_at=now,
+ completed_at=now,
+ updated_at=now,
+ )
+ )
+ if transition.rowcount != len(run_ids):
+ raise RuntimeError("Delivery retirement lost an exact Agent Run transition")
+ _defer_run_ids_updated_from_connection(conn, run_ids)
+ return run_ids
+
+
def record_agent_run_delivery_outcome_in_connection(
conn: Any,
run_id: str,
@@ -2037,78 +2063,9 @@ def record_agent_run_delivery_outcome_in_connection(
return True
-def _refresh_recovered_coalesced_workbench_runs_in_connection(conn: Any, *, now: str) -> None:
- rows = list(
- conn.execute(
- select(agent_runs)
- .where(agent_runs.c.run_type == "agent_run")
- .where(agent_runs.c.status.in_(_status_query_values("queued")))
- ).mappings()
- )
- rows_by_id = {row["id"]: row for row in rows}
- processed: set[str] = set()
- for row in rows:
- run_id = str(row["id"] or "")
- if run_id in processed:
- continue
- metadata = _json_loads(row["metadata_json"], {})
- if not isinstance(metadata, dict):
- metadata = {}
- coalesced = metadata.get("coalesced_queue") if isinstance(metadata, dict) else None
- raw_ids = coalesced.get("execution_ids") if isinstance(coalesced, dict) else None
- if not isinstance(raw_ids, list):
- continue
- run_ids: list[str] = []
- for value in raw_ids:
- coalesced_id = str(value or "").strip()
- if coalesced_id and coalesced_id not in run_ids:
- run_ids.append(coalesced_id)
- if run_id not in run_ids:
- run_ids.insert(0, run_id)
- live_ids = [
- candidate
- for candidate in run_ids
- if candidate in rows_by_id
- and not bool(rows_by_id[candidate]["cancel_requested"])
- and normalize_run_status(rows_by_id[candidate]["status"]) == "queued"
- ]
- if not live_ids:
- processed.update(run_ids)
- continue
- primary_id = live_ids[0]
- live_rows = {candidate: rows_by_id[candidate] for candidate in live_ids}
- primary_metadata = _json_loads(rows_by_id[primary_id]["metadata_json"], {})
- if not isinstance(primary_metadata, dict):
- primary_metadata = {}
- primary_metadata["workbench_queue_holds_run"] = False
- primary_metadata["effective_run_id"] = primary_id
- primary_metadata.pop("coalesced_into_run_id", None)
- if len(live_ids) > 1:
- primary_metadata["coalesced_queue"] = _coalesced_agent_run_metadata(live_rows, live_ids)
- else:
- primary_metadata.pop("coalesced_queue", None)
- conn.execute(
- update(agent_runs)
- .where(agent_runs.c.id == primary_id)
- .values(metadata_json=_json_dumps(primary_metadata), updated_at=now)
- )
- for child_id in live_ids[1:]:
- child_metadata = _json_loads(rows_by_id[child_id]["metadata_json"], {})
- if not isinstance(child_metadata, dict):
- child_metadata = {}
- child_metadata["workbench_queue_holds_run"] = True
- child_metadata["effective_run_id"] = primary_id
- child_metadata["coalesced_into_run_id"] = primary_id
- child_metadata.pop("coalesced_queue", None)
- conn.execute(
- update(agent_runs)
- .where(agent_runs.c.id == child_id)
- .values(metadata_json=_json_dumps(child_metadata), updated_at=now)
- )
- processed.update(run_ids)
-
-
-def inspect_queued_runs_for_workbench_in_connection(conn: Any, run_ids: list[str]) -> tuple[list[str], list[str]]:
+def inspect_agent_runs_for_turn_in_connection(
+ conn: Any, run_ids: list[str]
+) -> tuple[list[str], list[str]]:
normalized_run_ids: list[str] = []
seen: set[str] = set()
for raw_run_id in run_ids:
@@ -2123,7 +2080,7 @@ def inspect_queued_runs_for_workbench_in_connection(conn: Any, run_ids: list[str
row["id"]: row
for row in conn.execute(select(agent_runs).where(agent_runs.c.id.in_(normalized_run_ids))).mappings()
}
- queued_run_ids: list[str] = []
+ eligible_run_ids: list[str] = []
stale_run_ids: list[str] = []
cancel_requested_run_ids: list[str] = []
for run_id in normalized_run_ids:
@@ -2136,10 +2093,13 @@ def inspect_queued_runs_for_workbench_in_connection(conn: Any, run_ids: list[str
cancel_requested_run_ids.append(run_id)
stale_run_ids.append(run_id)
continue
- if normalize_run_status(row["status"]) != "queued":
+ status = normalize_run_status(row["status"])
+ if status not in {"queued", "running"} or not str(
+ row["delivery_id"] or ""
+ ).strip():
stale_run_ids.append(run_id)
continue
- queued_run_ids.append(run_id)
+ eligible_run_ids.append(run_id)
if cancel_requested_run_ids:
now = _utc_now_iso()
conn.execute(
@@ -2149,41 +2109,7 @@ def inspect_queued_runs_for_workbench_in_connection(conn: Any, run_ids: list[str
.values(status="canceled", completed_at=now, updated_at=now)
)
_defer_run_ids_updated_from_connection(conn, cancel_requested_run_ids)
- return queued_run_ids, stale_run_ids
-
-
-def reset_workbench_claimed_runs_in_connection(conn: Any, run_ids: list[str]) -> None:
- now = _utc_now_iso()
- seen: set[str] = set()
- changed_ids: list[str] = []
- for raw_run_id in run_ids:
- run_id = str(raw_run_id or "").strip()
- if not run_id or run_id in seen:
- continue
- seen.add(run_id)
- row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
- if not row:
- continue
- metadata = _json_loads(row["metadata_json"], {})
- if not isinstance(metadata, dict):
- metadata = {}
- metadata["workbench_queue_holds_run"] = True
- metadata.pop("effective_run_id", None)
- metadata.pop("coalesced_into_run_id", None)
- values = {
- "updated_at": now,
- "metadata_json": _json_dumps(metadata),
- }
- if normalize_run_status(row["status"]) == "running":
- values["status"] = "queued"
- values["started_at"] = None
- conn.execute(
- update(agent_runs)
- .where(agent_runs.c.id == run_id)
- .values(**values)
- )
- changed_ids.append(run_id)
- _defer_run_ids_updated_from_connection(conn, changed_ids)
+ return eligible_run_ids, stale_run_ids
def upsert_definition_in_connection(
@@ -3148,6 +3074,7 @@ class SQLiteBackgroundTaskStore:
def cancel_run(self, run_id: str, *, requested_at: Optional[str] = None) -> bool:
now = requested_at or _utc_now_iso()
row_to_publish = None
+ rows_to_publish: list[dict[str, Any]] = []
queue_session_id = ""
with self.engine.begin() as conn:
# Cancellation and Workbench queue retirement are one ownership
@@ -3162,13 +3089,25 @@ class SQLiteBackgroundTaskStore:
if not row:
return False
status = normalize_run_status(row["status"])
- metadata = _json_loads(row["metadata_json"], {})
values: dict[str, Any] = {
"cancel_requested": 1,
"cancel_requested_at": now,
"updated_at": now,
}
- if status == "queued":
+ delivery_id = str(row["delivery_id"] or "").strip()
+ retired_delivery = False
+ if delivery_id:
+ from storage import message_deliveries
+
+ retired_delivery = message_deliveries.retire_for_run_cancellation(
+ conn,
+ str(row["session_id"] or ""),
+ delivery_id,
+ )
+ # Once a Delivery exists its matrix policy outranks a stale Run
+ # projection. A Turn-owned Delivery may have written natively and
+ # must settle through that Turn even if the Run still says queued.
+ if retired_delivery or (status == "queued" and not delivery_id):
values["status"] = "canceled"
values["completed_at"] = now
result = conn.execute(
@@ -3180,21 +3119,9 @@ class SQLiteBackgroundTaskStore:
row_to_publish = dict(
conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().one()
)
- if (
- status == "queued"
- and isinstance(metadata, dict)
- and metadata.get("workbench_queue_holds_run") is True
- ):
- from storage import messages_service
-
- session_id = str(row["session_id"] or "").strip()
- if messages_service.delete_queued_agent_run(
- conn,
- session_id=session_id,
- run_id=run_id,
- ):
- queue_session_id = session_id
- _publish_run_rows_updated([row_to_publish])
+ if retired_delivery:
+ queue_session_id = str(row["session_id"] or "").strip()
+ _publish_run_rows_updated(rows_to_publish or [row_to_publish])
_publish_queue_updated(queue_session_id)
return row_to_publish is not None
@@ -3509,26 +3436,28 @@ class SQLiteBackgroundTaskStore:
_publish_run_rows_updated([row_to_publish])
return row_to_publish is not None
- def claim_queued_run_for_workbench(
+ def claim_agent_run_for_turn(
self,
run_id: str,
*,
started_at: Optional[str] = None,
) -> bool:
- return self.claim_queued_runs_for_workbench([run_id], started_at=started_at) == [run_id]
+ return self.claim_agent_runs_for_turn([run_id], started_at=started_at) == [run_id]
- def claim_queued_runs_for_workbench(
+ def claim_agent_runs_for_turn(
self,
run_ids: list[str],
*,
started_at: Optional[str] = None,
) -> list[str]:
with run_update_event_transaction(self.engine) as conn:
- return claim_queued_runs_for_workbench_in_connection(conn, run_ids, started_at=started_at)
+ return claim_agent_runs_for_turn_in_connection(
+ conn, run_ids, started_at=started_at
+ )
- def inspect_queued_runs_for_workbench(self, run_ids: list[str]) -> tuple[list[str], list[str]]:
+ def inspect_agent_runs_for_turn(self, run_ids: list[str]) -> tuple[list[str], list[str]]:
with run_update_event_transaction(self.engine) as conn:
- return inspect_queued_runs_for_workbench_in_connection(conn, run_ids)
+ return inspect_agent_runs_for_turn_in_connection(conn, run_ids)
def record_run_message(
self,
@@ -4094,6 +4023,7 @@ class SQLiteBackgroundTaskStore:
select(agent_runs.c.id, agent_runs.c.result_payload_json)
.where(agent_runs.c.status.in_(_status_query_values("running")))
.where(agent_runs.c.run_type != "watch_runtime")
+ .where(agent_runs.c.delivery_id.is_(None))
).mappings()
)
recovered_ids = []
@@ -4110,7 +4040,6 @@ class SQLiteBackgroundTaskStore:
.where(agent_runs.c.id.in_(recovered_ids))
.values(status="queued", started_at=None, pid=None, updated_at=now)
)
- _refresh_recovered_coalesced_workbench_runs_in_connection(conn, now=now)
_defer_run_ids_updated_from_connection(conn, recovered_ids)
def record_run_skip_reason(self, run_id: str, *, reason: str, at: Optional[str] = None) -> bool:
@@ -4219,16 +4148,14 @@ class SQLiteBackgroundTaskStore:
owned_run_ids: set[str],
error_texts: dict[str, str],
deliverable_run_ids: Optional[set[str]] = None,
- busy_session_ids: Optional[set[str]] = None,
now: Optional[str] = None,
orphan_grace_seconds: int = 0,
queued_ttl_seconds: int = 0,
- hold_ttl_seconds: int = 0,
) -> list[SweptRun]:
"""Terminalize runs that provably have nothing left to settle them.
- Three evidence-based classes (``docs/plans/agent-run-zombie-settlement.md``
- §4.2). Each is disabled by passing ``0`` for its window:
+ Two evidence-based classes remain. Each is disabled by passing ``0``
+ for its window:
- ``orphaned``: a ``running`` agent run with no live owner, older than
``orphan_grace_seconds``. The grace period is what keeps a run that is
@@ -4239,18 +4166,8 @@ class SQLiteBackgroundTaskStore:
caller still cannot deliver. The reason is read off the row, never
re-derived, so a run deferred for capacity or a session lock — both of which
are progress — is never swept.
- - ``queue_hold_expired``: a ``queued`` run holding a workbench queue slot that
- has not been touched in ``hold_ttl_seconds``, in a session with no live turn.
-
- ``owned_run_ids`` exempts a row from **every** class, not just ``orphaned``. A
- coalesced workbench turn claims its secondary runs and deliberately leaves them
- ``queued`` while the primary settles them, so a live owner has to outrank the
- queue TTLs too — otherwise a turn that outlives ``hold_ttl_seconds`` would have
- its own siblings failed underneath it, reintroducing the turn-duration timeout
- this design does not have. It must be the union of every ownership source; the
- caller is responsible for failing closed (passing "everything is owned", or not calling
- at all) when it cannot enumerate owners. This method cannot tell an empty set
- meaning "nothing is running" from one meaning "I could not look".
+ ``owned_run_ids`` exempts a row from every class. It includes both live
+ process work and Runs linked to unresolved durable Deliveries.
``deliverable_run_ids`` is the same contract for the transport class, and it is
why the recorded reason alone is not enough. The drain stops at its concurrency
@@ -4263,16 +4180,6 @@ class SQLiteBackgroundTaskStore:
without the clear a recovered-then-failed-again transport would be read as one
continuous outage and skip the whole configured reconnect window (Codex P2).
- ``busy_session_ids`` is the same contract again, for the hold class: a run the
- gate parked behind a live turn is NOT reported by ``owned_agent_run_ids`` (the
- live turn only owns the ids of the run it is itself executing), so a legitimate
- Workbench turn outliving ``hold_ttl_seconds`` would have its own queued follower
- failed even though the gate would flush it on completion (Codex P2). The set is
- session ids, not run ids, because that is the granularity the gate occupies.
- ``None`` means "no exemptions", so a caller that cannot enumerate live turns
- must fail closed by disabling the class (``hold_ttl_seconds=0``), exactly as it
- does for deliverability.
-
Candidate selection is read-only; each row is then terminalized through
:meth:`settle_run_terminal`, so every write inherits the same guards — scoped
to ``queued|running``, ``cancel_requested`` honored, deferred/Activity-owned
@@ -4318,12 +4225,7 @@ class SQLiteBackgroundTaskStore:
run_id = str(row["id"])
if run_id in owned_run_ids:
# A live owner outranks every TTL, whatever the row's status. This is
- # NOT only about ``running`` rows: a coalesced workbench turn claims its
- # secondary runs and deliberately leaves them ``queued`` with
- # ``workbench_queue_holds_run`` while the primary settles them, and
- # ``owned_agent_run_ids`` reports all of them as owned. Aging those out
- # would fail live siblings mid-turn — a turn-duration timeout by the back
- # door, which this design explicitly does not have.
+ # A durable Delivery or Turn owns this run across process loss.
continue
reason: Optional[str] = None
if status == "running":
@@ -4344,19 +4246,7 @@ class SQLiteBackgroundTaskStore:
# stale ``last_skip_at`` would make the NEXT outage look like a
# continuation of this one and skip its whole TTL (Codex P2).
recovered_ids.add(run_id)
- # Hold before transport: it is the more specific piece of evidence, and
- # its TTL is deliberately the longest so an actively recovering queue
- # survives.
if (
- metadata.get("workbench_queue_holds_run")
- # A live turn in this row's session is why it is parked. The gate
- # will flush it when that turn ends, and the turn does NOT report
- # this run as owned — it owns only the ids it is executing itself.
- and str(row["session_id"] or "") not in (busy_session_ids or set())
- and _older_than(row["updated_at"], hold_ttl_seconds)
- ):
- reason = SWEEP_REASON_QUEUE_HOLD_EXPIRED
- elif (
metadata.get("last_skip_reason") == SKIP_REASON_TRANSPORT_UNAVAILABLE
# Two independent facts, both required: the drain recorded that this
# row's platform was down, AND the caller still cannot deliver it.
@@ -5713,6 +5603,7 @@ class SQLiteBackgroundTaskStore:
"result_text": payload.get("result_text"),
"result_payload_json": self._payload_json(payload, "result_payload", "result_payload_json"),
"message_ids_json": self._payload_json(payload, "message_ids", "message_ids_json"),
+ "delivery_id": payload.get("delivery_id"),
"callback_session_id": payload.get("callback_session_id"),
"callback_status": payload.get("callback_status"),
"callback_error": payload.get("callback_error"),
@@ -5833,6 +5724,7 @@ class SQLiteBackgroundTaskStore:
"result_text": row["result_text"],
"result_payload": _json_loads(row["result_payload_json"], None),
"message_ids": _json_loads(row["message_ids_json"], []),
+ "delivery_id": row["delivery_id"],
"callback_session_id": row["callback_session_id"],
"callback_status": row["callback_status"],
"callback_error": row["callback_error"],
diff --git a/storage/delivery_states.py b/storage/delivery_states.py
new file mode 100644
index 000000000..a912ccbd7
--- /dev/null
+++ b/storage/delivery_states.py
@@ -0,0 +1,72 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from types import MappingProxyType
+from typing import Literal, Mapping
+
+
+OrderingRole = Literal["claimable", "fence", "turn_owned", "terminal"]
+NativeEffect = Literal["none", "possible", "unknown", "accepted"]
+RunCancelAction = Literal["retire", "turn_owner", "complete"]
+SubmissionStatus = Literal["reserved", "admitted", "retired"]
+
+
+@dataclass(frozen=True)
+class DeliveryStatePolicy:
+ ordering: OrderingRole
+ native_effect: NativeEffect
+ run_cancel: RunCancelAction
+ submission: SubmissionStatus
+
+
+# This is the sole runtime meaning of a Delivery state. Callers express an
+# operation (claim or cancel) and consume a derived property instead of
+# maintaining their own state lists.
+DELIVERY_STATE_MATRIX: Mapping[str, DeliveryStatePolicy] = MappingProxyType(
+ {
+ "reserved": DeliveryStatePolicy("fence", "none", "retire", "reserved"),
+ "queued": DeliveryStatePolicy("claimable", "none", "retire", "admitted"),
+ "claimed": DeliveryStatePolicy(
+ "turn_owned", "possible", "turn_owner", "admitted"
+ ),
+ "pending_steer": DeliveryStatePolicy(
+ "fence", "none", "retire", "admitted"
+ ),
+ "steering": DeliveryStatePolicy(
+ "fence", "possible", "turn_owner", "admitted"
+ ),
+ "interrupt_waiting": DeliveryStatePolicy(
+ "turn_owned", "possible", "turn_owner", "admitted"
+ ),
+ "reconciling_steer": DeliveryStatePolicy(
+ "fence", "unknown", "turn_owner", "admitted"
+ ),
+ "accepted": DeliveryStatePolicy(
+ "terminal", "accepted", "complete", "admitted"
+ ),
+ "retired": DeliveryStatePolicy(
+ "terminal", "none", "complete", "retired"
+ ),
+ }
+)
+
+DELIVERY_STATES = tuple(DELIVERY_STATE_MATRIX)
+CLAIMABLE_QUEUE_STATES = tuple(
+ state for state, policy in DELIVERY_STATE_MATRIX.items() if policy.ordering == "claimable"
+)
+FENCE_STATES = tuple(
+ state for state, policy in DELIVERY_STATE_MATRIX.items() if policy.ordering == "fence"
+)
+RUN_CANCEL_RETIRE_STATES = tuple(
+ state for state, policy in DELIVERY_STATE_MATRIX.items() if policy.run_cancel == "retire"
+)
+ADMITTED_DELIVERY_STATES = tuple(
+ state for state, policy in DELIVERY_STATE_MATRIX.items() if policy.submission == "admitted"
+)
+
+
+def policy_for(state: str) -> DeliveryStatePolicy:
+ try:
+ return DELIVERY_STATE_MATRIX[state]
+ except KeyError as exc:
+ raise ValueError(f"unknown Delivery state: {state}") from exc
diff --git a/storage/message_deliveries.py b/storage/message_deliveries.py
new file mode 100644
index 000000000..2def4e653
--- /dev/null
+++ b/storage/message_deliveries.py
@@ -0,0 +1,1923 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import time
+import uuid
+from datetime import datetime, timezone
+from typing import Any, Iterable
+
+from sqlalchemy import Select, and_, func, or_, select, update
+from sqlalchemy.engine import Connection
+
+from storage.delivery_states import (
+ CLAIMABLE_QUEUE_STATES,
+ FENCE_STATES,
+ RUN_CANCEL_RETIRE_STATES,
+ policy_for,
+)
+from storage.models import (
+ agent_runs,
+ agent_sessions,
+ message_deliveries,
+ messages,
+ session_turns,
+ show_session_events,
+)
+
+
+TURN_OWNER_STATES = ("starting", "active")
+WEB_PUSH_USER_KEY_METADATA = "_web_push_user_key"
+WEB_PUSH_USER_KEYS_METADATA = "_web_push_user_keys"
+
+
+def utc_now_iso() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def turn_now_iso() -> str:
+ """Preserve the true order of Turn lifecycle boundaries."""
+
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
+
+
+def new_turn_id() -> str:
+ return f"trn_{uuid.uuid4().hex}"
+
+
+def new_delivery_id() -> str:
+ return f"msg_{int(time.time() * 1_000_000):015x}{uuid.uuid4().hex[:8]}"
+
+
+def new_attempt_id() -> str:
+ return f"atm_{uuid.uuid4().hex}"
+
+
+def _canonical_json(value: Any) -> str:
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
+
+
+def _sha256_text(value: str) -> str:
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
+
+
+def native_dedupe_key(platform: str, native_message_id: str | None) -> str | None:
+ """Return the canonical live dedupe identity for a native submission."""
+
+ native_id = str(native_message_id or "").strip()
+ return f"{platform}:{native_id}" if native_id else None
+
+
+def _json_object(value: Any) -> dict[str, Any]:
+ if isinstance(value, dict):
+ return dict(value)
+ if not value:
+ return {}
+ try:
+ parsed = json.loads(str(value))
+ except (TypeError, ValueError):
+ return {}
+ return dict(parsed) if isinstance(parsed, dict) else {}
+
+
+def _history(value: Any) -> dict[str, Any]:
+ parsed = _json_object(value)
+ events = parsed.get("events")
+ return {
+ "version": 1,
+ "events": list(events) if isinstance(events, list) else [],
+ }
+
+
+def _append_history_value(value: Any, event: dict[str, Any]) -> str:
+ history = _history(value)
+ history["events"].append({"at": utc_now_iso(), **event})
+ return _canonical_json(history)
+
+
+def message_snapshot(
+ *,
+ scope_id: str | None,
+ session_id: str,
+ platform: str,
+ author: str,
+ source: str | None,
+ message_type: str | None = None,
+ text: str | None = None,
+ content: dict[str, Any] | None = None,
+ metadata: dict[str, Any] | None = None,
+ author_id: str | None = None,
+ author_name: str | None = None,
+ native_message_id: str | None = None,
+ parent_native_message_id: str | None = None,
+ read_at: str | None = None,
+) -> dict[str, Any]:
+ """Build the immutable Message candidate held before native acceptance."""
+
+ body = dict(content or {})
+ if text is not None:
+ body.setdefault("text", text)
+ resolved_type = message_type or ("user" if author == "user" else "assistant")
+ if source == "harness" and author == "user" and resolved_type == "user":
+ author = "harness"
+ resolved_type = "harness"
+ return {
+ "scope_id": scope_id,
+ "session_id": session_id,
+ "platform": platform,
+ "author": author,
+ "type": resolved_type,
+ "author_id": author_id,
+ "author_name": author_name,
+ "source": source,
+ "native_message_id": native_message_id,
+ "parent_native_message_id": parent_native_message_id,
+ "content_text": text if text is not None else body.get("text") or None,
+ "content_json": _canonical_json(body),
+ "metadata_json": _canonical_json(metadata or {}),
+ "read_at": read_at,
+ }
+
+
+def _one(conn: Connection, query: Select[Any]) -> dict[str, Any] | None:
+ row = conn.execute(query).mappings().first()
+ return dict(row) if row else None
+
+
+def get_turn(conn: Connection, turn_id: str) -> dict[str, Any] | None:
+ return _one(conn, select(session_turns).where(session_turns.c.id == turn_id))
+
+
+def get_delivery(conn: Connection, delivery_id: str) -> dict[str, Any] | None:
+ return _one(conn, select(message_deliveries).where(message_deliveries.c.id == delivery_id))
+
+
+def get_delivery_by_dedupe(conn: Connection, dedupe_key: str) -> dict[str, Any] | None:
+ return _one(
+ conn,
+ select(message_deliveries).where(message_deliveries.c.dedupe_key == dedupe_key),
+ )
+
+
+def active_turn(conn: Connection, session_id: str) -> dict[str, Any] | None:
+ return _one(
+ conn,
+ select(session_turns)
+ .where(session_turns.c.session_id == session_id)
+ .where(session_turns.c.state.in_(TURN_OWNER_STATES))
+ .order_by(session_turns.c.created_at.desc(), session_turns.c.id.desc())
+ .limit(1),
+ )
+
+
+def ordering_head(
+ conn: Connection,
+ session_id: str,
+ *,
+ include_claimable: bool = True,
+) -> dict[str, Any] | None:
+ """Oldest eligible queued row or unresolved ordering fence."""
+
+ predicates = [message_deliveries.c.state.in_(FENCE_STATES)]
+ if include_claimable:
+ predicates.append(
+ and_(
+ message_deliveries.c.priority == "p3",
+ message_deliveries.c.state.in_(CLAIMABLE_QUEUE_STATES),
+ )
+ )
+
+ return _one(
+ conn,
+ select(message_deliveries)
+ .where(message_deliveries.c.session_id == session_id)
+ .where(or_(*predicates))
+ .order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ .limit(1),
+ )
+
+
+def claimable_fifo_head(conn: Connection, session_id: str) -> dict[str, Any] | None:
+ head = ordering_head(conn, session_id)
+ return head if head is not None and head["state"] == "queued" else None
+
+
+def claimable_fifo_prefix(conn: Connection, session_id: str) -> list[dict[str, Any]]:
+ """Queued prefix before the first unresolved ordering fence."""
+
+ rows = conn.execute(
+ select(message_deliveries)
+ .where(message_deliveries.c.session_id == session_id)
+ .where(
+ or_(
+ and_(
+ message_deliveries.c.priority == "p3",
+ message_deliveries.c.state == "queued",
+ ),
+ message_deliveries.c.state.in_(FENCE_STATES),
+ )
+ )
+ .order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ ).mappings()
+ prefix: list[dict[str, Any]] = []
+ for row in rows:
+ current = dict(row)
+ if current["state"] != "queued":
+ break
+ prefix.append(delivery_payload(current))
+ return prefix
+
+
+def list_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
+ rows = conn.execute(
+ select(message_deliveries)
+ .where(message_deliveries.c.session_id == session_id)
+ .where(message_deliveries.c.state == "queued")
+ .order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ ).mappings()
+ return [delivery_payload(dict(row)) for row in rows]
+
+
+def delivery_payload(row: dict[str, Any]) -> dict[str, Any]:
+ snapshot = _json_object(row.get("snapshot_json"))
+ content = _json_object(snapshot.get("content_json"))
+ metadata = _json_object(snapshot.get("metadata_json"))
+ return {
+ "id": row["id"],
+ "delivery_id": row["id"],
+ "message_id": row.get("message_id"),
+ "turn_id": row.get("turn_id"),
+ "turn_role": row.get("turn_role"),
+ "turn_position": row.get("turn_position"),
+ "session_id": row.get("session_id"),
+ "scope_id": snapshot.get("scope_id"),
+ "platform": snapshot.get("platform"),
+ "author": snapshot.get("author"),
+ "type": snapshot.get("type"),
+ "source": snapshot.get("source"),
+ "author_id": snapshot.get("author_id"),
+ "author_name": snapshot.get("author_name"),
+ "native_message_id": snapshot.get("native_message_id"),
+ "parent_native_message_id": snapshot.get("parent_native_message_id"),
+ "text": snapshot.get("content_text") or content.get("text") or "",
+ "content": content,
+ "metadata": metadata,
+ "dispatch_text": row.get("dispatch_text") or "",
+ "priority": row.get("priority"),
+ "state": row.get("state"),
+ "created_at": row.get("submitted_at"),
+ "submitted_at": row.get("submitted_at"),
+ "updated_at": row.get("updated_at"),
+ "retired_at": row.get("retired_at"),
+ "version": row.get("version"),
+ }
+
+
+_MESSAGE_MERGE_IDENTITY_FIELDS = (
+ "scope_id",
+ "platform",
+ "author",
+ "type",
+ "source",
+ "author_id",
+ "author_name",
+ "parent_native_message_id",
+)
+
+
+def message_merge_identity(value: dict[str, Any]) -> tuple[Any, ...]:
+ """Return the Message fields that must stay singular after batching."""
+
+ return tuple(value.get(field) for field in _MESSAGE_MERGE_IDENTITY_FIELDS)
+
+
+def has_substantive_input(
+ dispatch_text: str | None,
+ *,
+ has_attachments: bool = False,
+) -> bool:
+ """Whether an admission contains text or a previously resolved attachment."""
+
+ return bool(str(dispatch_text or "").strip()) or has_attachments
+
+
+def has_substantive_content(
+ delivery: dict[str, Any],
+ *,
+ has_attachments: bool = False,
+) -> bool:
+ """Whether a reserved Delivery can produce a meaningful backend input."""
+
+ return has_substantive_input(
+ delivery.get("dispatch_text"),
+ has_attachments=has_attachments,
+ )
+
+
+def list_queued_page(conn: Connection, session_id: str, *, page_request: Any) -> Any:
+ from storage.pagination import page_result_from_limit_plus_one
+
+ query = (
+ select(message_deliveries)
+ .where(message_deliveries.c.session_id == session_id)
+ .where(message_deliveries.c.state == "queued")
+ .order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ .limit(page_request.limit + 1)
+ .offset(page_request.offset)
+ )
+ return page_result_from_limit_plus_one(
+ [delivery_payload(dict(row)) for row in conn.execute(query).mappings()],
+ page_request,
+ )
+
+
+def insert_turn(
+ conn: Connection,
+ *,
+ turn_id: str,
+ session_id: str,
+ initial_delivery_id: str,
+ state: str,
+ backend: str,
+ start_attempt_id: str | None = None,
+ dispatch_text: str | None = None,
+ now: str | None = None,
+) -> dict[str, Any]:
+ timestamp = now or turn_now_iso()
+ has_started = state in {"starting", "active"}
+ resolved_attempt_id = start_attempt_id or new_attempt_id() if has_started else None
+ resolved_dispatch_text = dispatch_text if has_started else None
+ if has_started and resolved_dispatch_text is None:
+ initial = get_delivery(conn, initial_delivery_id)
+ resolved_dispatch_text = str((initial or {}).get("dispatch_text") or "")
+ values = {
+ "id": turn_id,
+ "session_id": session_id,
+ "initial_delivery_id": initial_delivery_id,
+ "state": state,
+ "backend": backend,
+ "runtime_key": None,
+ "runtime_turn_id": None,
+ "native_turn_id": None,
+ "start_attempt_id": resolved_attempt_id,
+ "start_receipt_outcome": "accepted" if state == "active" else None,
+ "start_receipt_json": (
+ _canonical_json({"kind": "seeded_active"}) if state == "active" else "{}"
+ ),
+ "dispatch_text": resolved_dispatch_text,
+ "dispatch_sha256": (
+ _sha256_text(resolved_dispatch_text or "") if has_started else None
+ ),
+ "terminal_outcome": None,
+ "settled_by": None,
+ "terminal_evidence_kind": None,
+ "terminal_evidence_json": "{}",
+ "control_state": None,
+ "control_mode": None,
+ "control_attempt_id": None,
+ "control_expected_native_turn_id": None,
+ "control_receipt_outcome": None,
+ "control_receipt_json": "{}",
+ "control_successor_delivery_id": None,
+ "control_successor_turn_id": None,
+ "version": 1,
+ "created_at": timestamp,
+ "updated_at": timestamp,
+ "started_at": timestamp if has_started else None,
+ "terminal_at": None,
+ }
+ conn.execute(session_turns.insert().values(**values))
+ return values
+
+
+def insert_delivery(
+ conn: Connection,
+ *,
+ delivery_id: str,
+ session_id: str,
+ priority: str,
+ state: str,
+ snapshot: dict[str, Any],
+ dispatch_text: str,
+ dedupe_key: str | None = None,
+ turn_id: str | None = None,
+ current_attempt_id: str | None = None,
+ current_attempt_kind: str | None = None,
+ current_target_turn_id: str | None = None,
+ current_expected_native_turn_id: str | None = None,
+ current_receipt_outcome: str | None = None,
+ current_receipt: dict[str, Any] | None = None,
+ history_event: dict[str, Any] | None = None,
+ now: str | None = None,
+) -> dict[str, Any]:
+ timestamp = now or utc_now_iso()
+ serialized_snapshot = _canonical_json(snapshot)
+ history = {"version": 1, "events": []}
+ if history_event:
+ history["events"].append({"at": timestamp, **history_event})
+ values = {
+ "id": delivery_id,
+ "session_id": session_id,
+ "message_id": None,
+ "priority": priority,
+ "state": state,
+ "snapshot_json": serialized_snapshot,
+ "snapshot_sha256": _sha256_text(serialized_snapshot),
+ "dispatch_text": dispatch_text,
+ "dispatch_sha256": _sha256_text(dispatch_text),
+ "dedupe_key": dedupe_key,
+ "turn_id": turn_id,
+ "turn_role": None,
+ "turn_position": None,
+ "current_attempt_id": current_attempt_id,
+ "current_attempt_kind": current_attempt_kind,
+ "current_target_turn_id": current_target_turn_id,
+ "current_expected_native_turn_id": current_expected_native_turn_id,
+ "current_receipt_outcome": current_receipt_outcome,
+ "current_receipt_json": _canonical_json(current_receipt or {}),
+ "current_attempt_opened_at": timestamp if current_attempt_id else None,
+ "delivery_history_json": _canonical_json(history),
+ "version": 1,
+ "submitted_at": timestamp,
+ "updated_at": timestamp,
+ "materialized_at": None,
+ "retired_at": None,
+ }
+ conn.execute(message_deliveries.insert().values(**values))
+ return values
+
+
+def enqueue_queued(
+ conn: Connection,
+ *,
+ scope_id: str | None,
+ session_id: str,
+ text: str,
+ dispatch_text: str | None = None,
+ platform: str = "avibe",
+ author: str = "user",
+ source: str | None = "user",
+ message_type: str | None = None,
+ author_id: str | None = None,
+ author_name: str | None = None,
+ native_message_id: str | None = None,
+ metadata: dict[str, Any] | None = None,
+ now: str | None = None,
+) -> dict[str, Any]:
+ """Persist one P3 submission without creating a transcript Message."""
+
+ delivery_id = new_delivery_id()
+ row = insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=session_id,
+ priority="p3",
+ state="queued",
+ snapshot=message_snapshot(
+ scope_id=scope_id,
+ session_id=session_id,
+ platform=platform,
+ author=author,
+ source=source,
+ message_type=message_type,
+ text=text,
+ metadata=metadata,
+ author_id=author_id,
+ author_name=author_name,
+ native_message_id=native_message_id,
+ ),
+ dispatch_text=text if dispatch_text is None else dispatch_text,
+ dedupe_key=native_dedupe_key(platform, native_message_id),
+ history_event={"kind": "submitted", "priority": "p3"},
+ now=now,
+ )
+ return delivery_payload(row)
+
+
+def cas_turn(
+ conn: Connection,
+ turn_id: str,
+ *,
+ expected_version: int,
+ expected_states: Iterable[str],
+ values: dict[str, Any],
+) -> dict[str, Any] | None:
+ next_values = {**values, "version": expected_version + 1, "updated_at": utc_now_iso()}
+ if next_values.get("state") == "starting" and "started_at" not in next_values:
+ next_values["started_at"] = turn_now_iso()
+ result = conn.execute(
+ update(session_turns)
+ .where(session_turns.c.id == turn_id)
+ .where(session_turns.c.version == expected_version)
+ .where(session_turns.c.state.in_(tuple(expected_states)))
+ .values(**next_values)
+ )
+ return get_turn(conn, turn_id) if result.rowcount == 1 else None
+
+
+def cas_delivery(
+ conn: Connection,
+ delivery_id: str,
+ *,
+ expected_version: int,
+ expected_states: Iterable[str],
+ values: dict[str, Any],
+ history_event: dict[str, Any] | None = None,
+) -> dict[str, Any] | None:
+ current = get_delivery(conn, delivery_id)
+ if current is None or int(current["version"]) != expected_version:
+ return None
+ next_values = dict(values)
+ if history_event is not None:
+ next_values["delivery_history_json"] = _append_history_value(
+ current.get("delivery_history_json"),
+ history_event,
+ )
+ next_values.update(version=expected_version + 1, updated_at=utc_now_iso())
+ result = conn.execute(
+ update(message_deliveries)
+ .where(message_deliveries.c.id == delivery_id)
+ .where(message_deliveries.c.version == expected_version)
+ .where(message_deliveries.c.state.in_(tuple(expected_states)))
+ .values(**next_values)
+ )
+ return get_delivery(conn, delivery_id) if result.rowcount == 1 else None
+
+
+def open_start_attempt(
+ conn: Connection,
+ delivery_id: str,
+ *,
+ expected_version: int,
+ turn_id: str,
+ attempt_id: str,
+) -> dict[str, Any] | None:
+ turn = get_turn(conn, turn_id)
+ delivery = get_delivery(conn, delivery_id)
+ if turn is None or delivery is None or turn["state"] != "starting":
+ return None
+ if turn.get("initial_delivery_id") != delivery_id:
+ return None
+ updated_turn = cas_turn(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ expected_states=("starting",),
+ values={
+ "start_attempt_id": attempt_id,
+ "dispatch_text": str(delivery.get("dispatch_text") or ""),
+ "dispatch_sha256": _sha256_text(str(delivery.get("dispatch_text") or "")),
+ },
+ )
+ if updated_turn is None:
+ return None
+ return cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=expected_version,
+ expected_states=("reserved", "queued", "interrupt_waiting"),
+ values={
+ "state": "claimed",
+ "turn_id": turn_id,
+ "turn_role": "initial",
+ "turn_position": 0,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": utc_now_iso(),
+ },
+ history_event={"kind": "start", "attempt_id": attempt_id, "turn_id": turn_id, "outcome": "opened"},
+ )
+
+
+def claim_start_batch(
+ conn: Connection,
+ *,
+ turn_id: str,
+ session_id: str,
+ backend: str,
+ deliveries: list[dict[str, Any]],
+ dispatch_text: str,
+ attempt_id: str | None = None,
+) -> dict[str, Any]:
+ """Claim one ordered Delivery segment for exactly one native start."""
+
+ if not deliveries:
+ raise ValueError("a Turn requires at least one Delivery")
+ resolved_attempt_id = attempt_id or new_attempt_id()
+ turn = insert_turn(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ initial_delivery_id=str(deliveries[0]["id"]),
+ state="starting",
+ backend=backend,
+ start_attempt_id=resolved_attempt_id,
+ dispatch_text=dispatch_text,
+ )
+ claimed: list[dict[str, Any]] = []
+ for position, delivery in enumerate(deliveries):
+ row = cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved", "queued", "interrupt_waiting"),
+ values={
+ "state": "claimed",
+ "turn_id": turn_id,
+ "turn_role": "initial",
+ "turn_position": position,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ },
+ history_event={
+ "kind": "start",
+ "attempt_id": resolved_attempt_id,
+ "turn_id": turn_id,
+ "position": position,
+ "outcome": "claimed",
+ },
+ )
+ if row is None:
+ raise RuntimeError("Delivery batch claim lost after writer reservation")
+ claimed.append(row)
+ return {"turn": turn, "deliveries": claimed}
+
+
+def activate_waiting_successor(
+ conn: Connection,
+ *,
+ turn: dict[str, Any],
+ delivery: dict[str, Any],
+) -> dict[str, Any] | None:
+ if (
+ turn.get("state") != "waiting"
+ or delivery.get("state") != "interrupt_waiting"
+ or delivery.get("turn_id") != turn.get("id")
+ ):
+ return None
+ attempt_id = new_attempt_id()
+ dispatch_text = str(delivery.get("dispatch_text") or "")
+ started = cas_turn(
+ conn,
+ str(turn["id"]),
+ expected_version=int(turn["version"]),
+ expected_states=("waiting",),
+ values={
+ "state": "starting",
+ "start_attempt_id": attempt_id,
+ "start_receipt_outcome": None,
+ "start_receipt_json": "{}",
+ "dispatch_text": dispatch_text,
+ "dispatch_sha256": _sha256_text(dispatch_text),
+ },
+ )
+ if started is None:
+ return None
+ claimed = cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("interrupt_waiting",),
+ values={"state": "claimed"},
+ history_event={
+ "kind": "start",
+ "attempt_id": attempt_id,
+ "turn_id": turn["id"],
+ "position": 0,
+ "outcome": "claimed_after_interrupt",
+ },
+ )
+ if claimed is None:
+ raise RuntimeError("waiting successor Delivery claim lost")
+ return started
+
+
+def open_steer_attempt(
+ conn: Connection,
+ delivery_id: str,
+ *,
+ expected_version: int,
+ turn_id: str,
+ attempt_id: str,
+ expected_native_turn_id: str,
+) -> dict[str, Any] | None:
+ current = get_delivery(conn, delivery_id)
+ if (
+ current is not None
+ and current.get("state") == "pending_steer"
+ and current.get("current_attempt_id") != attempt_id
+ ):
+ return None
+ return cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=expected_version,
+ expected_states=("reserved", "queued", "pending_steer"),
+ values={
+ "state": "steering",
+ "current_attempt_id": attempt_id,
+ "current_attempt_kind": "steer",
+ "current_target_turn_id": turn_id,
+ "current_expected_native_turn_id": expected_native_turn_id,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": utc_now_iso(),
+ },
+ history_event={
+ "kind": "steer",
+ "attempt_id": attempt_id,
+ "turn_id": turn_id,
+ "expected_native_turn_id": expected_native_turn_id,
+ "outcome": "opened",
+ },
+ )
+
+
+def open_steer_attempt_batch(
+ conn: Connection,
+ *,
+ deliveries: list[dict[str, Any]],
+ turn_id: str,
+ attempt_id: str,
+ expected_native_turn_id: str,
+) -> list[dict[str, Any]]:
+ """Claim one ordered queue segment for one native steer call."""
+
+ claimed: list[dict[str, Any]] = []
+ for delivery in deliveries:
+ saved = open_steer_attempt(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ expected_native_turn_id=expected_native_turn_id,
+ )
+ if saved is None:
+ raise RuntimeError("Delivery steer batch claim lost after writer reservation")
+ claimed.append(saved)
+ return claimed
+
+
+def open_pending_steer_batch(
+ conn: Connection,
+ *,
+ deliveries: list[dict[str, Any]],
+ turn_id: str,
+ attempt_id: str,
+) -> list[dict[str, Any]]:
+ pending: list[dict[str, Any]] = []
+ for delivery in deliveries:
+ saved = cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved", "queued"),
+ values={
+ "state": "pending_steer",
+ "current_attempt_id": attempt_id,
+ "current_attempt_kind": "steer",
+ "current_target_turn_id": turn_id,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": utc_now_iso(),
+ },
+ history_event={
+ "kind": "steer",
+ "attempt_id": attempt_id,
+ "turn_id": turn_id,
+ "outcome": "pending_native_identity",
+ },
+ )
+ if saved is None:
+ raise RuntimeError("Delivery pending-steer batch claim lost")
+ pending.append(saved)
+ return pending
+
+
+def bind_native_start(
+ conn: Connection,
+ turn_id: str,
+ *,
+ expected_version: int,
+ runtime_key: str | None,
+ runtime_turn_id: str | None,
+ native_turn_id: str | None,
+) -> dict[str, Any] | None:
+ turn = get_turn(conn, turn_id)
+ if turn is None:
+ return None
+ for column, observed in (
+ ("runtime_key", runtime_key),
+ ("runtime_turn_id", runtime_turn_id),
+ ("native_turn_id", native_turn_id),
+ ):
+ persisted = str(turn.get(column) or "").strip()
+ candidate = str(observed or "").strip()
+ if persisted and candidate and persisted != candidate:
+ return None
+ return cas_turn(
+ conn,
+ turn_id,
+ expected_version=expected_version,
+ expected_states=("starting", "active"),
+ values={
+ "state": "active",
+ "runtime_key": runtime_key or turn.get("runtime_key"),
+ "runtime_turn_id": runtime_turn_id or turn.get("runtime_turn_id"),
+ "native_turn_id": native_turn_id or turn.get("native_turn_id"),
+ "start_receipt_outcome": "accepted",
+ "start_receipt_json": _canonical_json({"kind": "native_start"}),
+ "started_at": turn.get("started_at") or turn_now_iso(),
+ },
+ )
+
+
+def rebind_restored_native_generation(
+ conn: Connection,
+ turn_id: str,
+ *,
+ expected_version: int,
+ expected_native_turn_id: str,
+ restored_native_turn_id: str,
+) -> dict[str, Any] | None:
+ """Rotate one restored runtime generation and every unresolved exact target."""
+
+ turn = get_turn(conn, turn_id)
+ if (
+ turn is None
+ or turn["state"] != "active"
+ or turn.get("start_receipt_outcome") != "accepted"
+ or int(turn["version"]) != expected_version
+ or str(turn.get("native_turn_id") or "") != expected_native_turn_id
+ or not restored_native_turn_id
+ or restored_native_turn_id == expected_native_turn_id
+ ):
+ return None
+ turn_values: dict[str, Any] = {"native_turn_id": restored_native_turn_id}
+ if (
+ turn.get("control_state")
+ in {"pending", "interrupting", "waiting_terminal", "reconciling"}
+ and str(turn.get("control_expected_native_turn_id") or "")
+ == expected_native_turn_id
+ ):
+ turn_values["control_expected_native_turn_id"] = restored_native_turn_id
+ rebound = cas_turn(
+ conn,
+ turn_id,
+ expected_version=expected_version,
+ expected_states=("active",),
+ values=turn_values,
+ )
+ if rebound is None:
+ return None
+
+ attempts = list(
+ conn.execute(
+ select(message_deliveries).where(
+ message_deliveries.c.current_target_turn_id == turn_id,
+ message_deliveries.c.state.in_(("steering", "reconciling_steer")),
+ message_deliveries.c.current_expected_native_turn_id
+ == expected_native_turn_id,
+ )
+ ).mappings()
+ )
+ for attempt in attempts:
+ saved = cas_delivery(
+ conn,
+ str(attempt["id"]),
+ expected_version=int(attempt["version"]),
+ expected_states=(str(attempt["state"]),),
+ values={
+ "current_expected_native_turn_id": restored_native_turn_id,
+ },
+ history_event={
+ "kind": "native_generation_rebind",
+ "attempt_id": attempt.get("current_attempt_id"),
+ "turn_id": turn_id,
+ "previous_native_turn_id": expected_native_turn_id,
+ "restored_native_turn_id": restored_native_turn_id,
+ },
+ )
+ if saved is None:
+ raise RuntimeError("restored native generation lost a Delivery attempt CAS")
+ return rebound
+
+
+def mark_start_unknown(
+ conn: Connection,
+ turn_id: str,
+ *,
+ expected_version: int,
+ receipt: dict[str, Any],
+) -> dict[str, Any] | None:
+ return cas_turn(
+ conn,
+ turn_id,
+ expected_version=expected_version,
+ expected_states=("starting",),
+ values={
+ "start_receipt_outcome": "unknown",
+ "start_receipt_json": _canonical_json(receipt),
+ },
+ )
+
+
+def _verified_snapshot(delivery: dict[str, Any]) -> dict[str, Any]:
+ snapshot_json = str(delivery.get("snapshot_json") or "")
+ if not snapshot_json or _sha256_text(snapshot_json) != delivery.get("snapshot_sha256"):
+ raise RuntimeError("Delivery snapshot integrity check failed")
+ snapshot = _json_object(snapshot_json)
+ required = {"session_id", "platform", "author", "type", "content_json", "metadata_json"}
+ if not required <= set(snapshot):
+ raise RuntimeError("Delivery snapshot is incomplete")
+ return snapshot
+
+
+def _insert_message(
+ conn: Connection,
+ *,
+ message_id: str,
+ snapshot: dict[str, Any],
+ accepted_at: str,
+) -> None:
+ existing = conn.execute(select(messages).where(messages.c.id == message_id)).mappings().first()
+ values = {
+ "id": message_id,
+ "scope_id": snapshot.get("scope_id"),
+ "session_id": snapshot["session_id"],
+ "platform": snapshot["platform"],
+ "author": snapshot["author"],
+ "type": snapshot["type"],
+ "author_id": snapshot.get("author_id"),
+ "author_name": snapshot.get("author_name"),
+ "source": snapshot.get("source"),
+ "native_message_id": snapshot.get("native_message_id"),
+ "parent_native_message_id": snapshot.get("parent_native_message_id"),
+ "content_text": snapshot.get("content_text"),
+ "content_json": snapshot["content_json"],
+ "metadata_json": snapshot["metadata_json"],
+ "created_at": snapshot.get("created_at") or accepted_at,
+ "updated_at": accepted_at,
+ "delivered_at": accepted_at,
+ "read_at": snapshot.get("read_at"),
+ }
+ if existing is None:
+ conn.execute(messages.insert().values(**values))
+ return
+ immutable = tuple(key for key in values if key not in {"updated_at", "delivered_at"})
+ if any(existing[key] != values[key] for key in immutable):
+ raise RuntimeError("Delivery Message identity collided with different content")
+
+
+def _merged_initial_snapshot(deliveries: list[dict[str, Any]]) -> dict[str, Any]:
+ snapshots = [_verified_snapshot(delivery) for delivery in deliveries]
+ expected_identity = message_merge_identity(snapshots[0])
+ if any(message_merge_identity(snapshot) != expected_identity for snapshot in snapshots[1:]):
+ raise RuntimeError("Delivery batch contains incompatible Message identities")
+ first = dict(snapshots[0])
+ first["created_at"] = deliveries[0]["submitted_at"]
+ contents = [_json_object(snapshot.get("content_json")) for snapshot in snapshots]
+ texts = [str(snapshot.get("content_text") or "") for snapshot in snapshots]
+ visible_text = "\n".join(text for text in texts if text)
+ attachments = [
+ attachment
+ for content in contents
+ for attachment in (content.get("attachments") or [])
+ ]
+ merged_content = dict(contents[0])
+ if visible_text:
+ merged_content["text"] = visible_text
+ elif "text" in merged_content:
+ merged_content.pop("text", None)
+ if attachments:
+ merged_content["attachments"] = attachments
+ metadata = _json_object(first.get("metadata_json"))
+ web_push_user_keys: list[str] = []
+ for snapshot in snapshots:
+ snapshot_metadata = _json_object(snapshot.get("metadata_json"))
+ values = [snapshot_metadata.get(WEB_PUSH_USER_KEY_METADATA)]
+ plural = snapshot_metadata.get(WEB_PUSH_USER_KEYS_METADATA)
+ if isinstance(plural, list):
+ values.extend(plural)
+ for value in values:
+ key = str(value or "").strip()
+ if key and key not in web_push_user_keys:
+ web_push_user_keys.append(key)
+ metadata.pop(WEB_PUSH_USER_KEY_METADATA, None)
+ metadata.pop(WEB_PUSH_USER_KEYS_METADATA, None)
+ if len(web_push_user_keys) == 1:
+ metadata[WEB_PUSH_USER_KEY_METADATA] = web_push_user_keys[0]
+ elif web_push_user_keys:
+ metadata[WEB_PUSH_USER_KEYS_METADATA] = web_push_user_keys
+ if len(deliveries) > 1:
+ metadata["merged_delivery_ids"] = [str(delivery["id"]) for delivery in deliveries]
+ native_ids = [
+ str(snapshot.get("native_message_id") or "")
+ for snapshot in snapshots
+ if str(snapshot.get("native_message_id") or "")
+ ]
+ if native_ids:
+ metadata["merged_native_message_ids"] = native_ids
+ first["content_text"] = visible_text or None
+ first["content_json"] = _canonical_json(merged_content)
+ first["metadata_json"] = _canonical_json(metadata)
+ return first
+
+
+def materialize_start_acceptance(
+ conn: Connection,
+ *,
+ turn_id: str,
+ evidence: dict[str, Any],
+) -> list[dict[str, Any]]:
+ turn = get_turn(conn, turn_id)
+ if turn is None or turn["state"] not in {"starting", "active", "terminal"}:
+ return []
+ if turn.get("start_receipt_outcome") != "accepted":
+ return []
+ rows = [
+ dict(row)
+ for row in conn.execute(
+ select(message_deliveries)
+ .where(message_deliveries.c.turn_id == turn_id)
+ .where(message_deliveries.c.turn_role == "initial")
+ .order_by(message_deliveries.c.turn_position, message_deliveries.c.id)
+ ).mappings()
+ ]
+ if not rows:
+ raise RuntimeError("active Turn has no initial Delivery batch")
+ if all(row["state"] == "accepted" for row in rows):
+ return rows
+ if any(row["state"] != "claimed" for row in rows):
+ raise RuntimeError("initial Delivery batch is only partially materialized")
+ message_id = str(turn["initial_delivery_id"])
+ accepted_at = turn_now_iso()
+ snapshot = _merged_initial_snapshot(rows)
+ _insert_message(
+ conn,
+ message_id=message_id,
+ snapshot=snapshot,
+ accepted_at=accepted_at,
+ )
+ accepted: list[dict[str, Any]] = []
+ for row in rows:
+ saved = cas_delivery(
+ conn,
+ str(row["id"]),
+ expected_version=int(row["version"]),
+ expected_states=("claimed",),
+ values={
+ "state": "accepted",
+ "message_id": message_id,
+ "snapshot_json": None,
+ "dispatch_text": None,
+ "materialized_at": accepted_at,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ },
+ history_event={
+ "kind": "start",
+ "attempt_id": turn.get("start_attempt_id"),
+ "turn_id": turn_id,
+ "outcome": "accepted",
+ "evidence": evidence,
+ },
+ )
+ if saved is None:
+ raise RuntimeError("initial Delivery materialization CAS lost")
+ accepted.append(saved)
+ conn.execute(
+ update(show_session_events)
+ .where(show_session_events.c.delivery_id == str(row["id"]))
+ .where(show_session_events.c.message_id.is_(None))
+ .values(message_id=message_id)
+ )
+ return accepted
+
+
+def materialize_acceptance(
+ conn: Connection,
+ *,
+ delivery_id: str,
+ expected_attempt_id: str | None,
+ turn_id: str,
+ evidence: dict[str, Any],
+) -> dict[str, Any] | None:
+ delivery = get_delivery(conn, delivery_id)
+ if delivery is None:
+ return None
+ if delivery["state"] == "accepted":
+ if delivery.get("message_id") == delivery_id and delivery.get("turn_id") == turn_id:
+ if conn.execute(select(messages.c.id).where(messages.c.id == delivery_id)).scalar_one_or_none() is None:
+ raise RuntimeError("accepted Delivery is missing its Message")
+ return delivery
+ return None
+ if expected_attempt_id is not None and delivery.get("current_attempt_id") != expected_attempt_id:
+ return None
+ target_turn_id = str(delivery.get("current_target_turn_id") or "")
+ if target_turn_id != turn_id:
+ return None
+ target_turn = get_turn(conn, turn_id)
+ if (
+ target_turn is None
+ or target_turn["session_id"] != delivery["session_id"]
+ ):
+ return None
+ snapshot = _verified_snapshot(delivery)
+ now = turn_now_iso()
+ position = int(
+ conn.execute(
+ select(func.coalesce(func.max(message_deliveries.c.turn_position), -1)).where(
+ message_deliveries.c.turn_id == turn_id
+ )
+ ).scalar_one()
+ ) + 1
+ values = {
+ "state": "accepted",
+ "message_id": delivery_id,
+ "turn_id": turn_id,
+ "turn_role": "steer",
+ "turn_position": position,
+ "snapshot_json": None,
+ "dispatch_text": None,
+ "materialized_at": now,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ }
+ accepted = cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=(str(delivery["state"]),),
+ values=values,
+ history_event={
+ "kind": str(delivery.get("current_attempt_kind") or evidence.get("kind") or "start"),
+ "attempt_id": delivery.get("current_attempt_id"),
+ "turn_id": turn_id,
+ "outcome": "accepted",
+ "evidence": evidence,
+ },
+ )
+ if accepted is None:
+ return None
+
+ _insert_message(conn, message_id=delivery_id, snapshot=snapshot, accepted_at=now)
+ conn.execute(
+ update(show_session_events)
+ .where(show_session_events.c.delivery_id == delivery_id)
+ .where(show_session_events.c.message_id.is_(None))
+ .values(message_id=delivery_id)
+ )
+ return accepted
+
+
+def attempt_deliveries(conn: Connection, attempt_id: str) -> list[dict[str, Any]]:
+ return [
+ dict(row)
+ for row in conn.execute(
+ select(message_deliveries)
+ .where(message_deliveries.c.current_attempt_id == attempt_id)
+ .order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ ).mappings()
+ ]
+
+
+def materialize_steer_acceptance(
+ conn: Connection,
+ *,
+ leader_delivery_id: str,
+ expected_attempt_id: str,
+ turn_id: str,
+ evidence: dict[str, Any],
+) -> list[dict[str, Any]]:
+ leader = get_delivery(conn, leader_delivery_id)
+ if leader is None or leader.get("current_attempt_id") != expected_attempt_id:
+ return []
+ rows = attempt_deliveries(conn, expected_attempt_id)
+ if not rows or any(
+ row["state"] not in {"steering", "reconciling_steer"}
+ or row.get("current_target_turn_id") != turn_id
+ for row in rows
+ ):
+ return []
+ target_turn = get_turn(conn, turn_id)
+ if target_turn is None or any(row["session_id"] != target_turn["session_id"] for row in rows):
+ return []
+ now = turn_now_iso()
+ message_id = str(rows[0]["id"])
+ snapshot = _merged_initial_snapshot(rows)
+ first_position = int(
+ conn.execute(
+ select(func.coalesce(func.max(message_deliveries.c.turn_position), -1)).where(
+ message_deliveries.c.turn_id == turn_id
+ )
+ ).scalar_one()
+ ) + 1
+ accepted: list[dict[str, Any]] = []
+ for offset, row in enumerate(rows):
+ saved = cas_delivery(
+ conn,
+ str(row["id"]),
+ expected_version=int(row["version"]),
+ expected_states=(str(row["state"]),),
+ values={
+ "state": "accepted",
+ "message_id": message_id,
+ "turn_id": turn_id,
+ "turn_role": "steer",
+ "turn_position": first_position + offset,
+ "snapshot_json": None,
+ "dispatch_text": None,
+ "materialized_at": now,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ },
+ history_event={
+ "kind": "steer",
+ "attempt_id": expected_attempt_id,
+ "turn_id": turn_id,
+ "outcome": "accepted",
+ "evidence": evidence,
+ },
+ )
+ if saved is None:
+ raise RuntimeError("steer Delivery batch materialization CAS lost")
+ accepted.append(saved)
+ conn.execute(
+ update(show_session_events)
+ .where(show_session_events.c.delivery_id == str(row["id"]))
+ .where(show_session_events.c.message_id.is_(None))
+ .values(message_id=message_id)
+ )
+ _insert_message(conn, message_id=message_id, snapshot=snapshot, accepted_at=now)
+ return accepted
+
+
+def mark_attempt_unknown(
+ conn: Connection,
+ delivery_id: str,
+ *,
+ expected_version: int,
+ receipt: dict[str, Any],
+) -> dict[str, Any] | None:
+ delivery = get_delivery(conn, delivery_id)
+ if delivery is None:
+ return None
+ kind = str(delivery.get("current_attempt_kind") or "")
+ if kind != "steer":
+ return None
+ return cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=expected_version,
+ expected_states=("steering",),
+ values={
+ "state": "reconciling_steer",
+ "current_receipt_outcome": "unknown",
+ "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",
+ "receipt": receipt,
+ },
+ )
+
+
+def record_definitive_attempt(
+ conn: Connection,
+ delivery_id: str,
+ *,
+ expected_version: int,
+ expected_states: Iterable[str],
+ outcome: str,
+ next_state: str,
+ next_priority: str | None = None,
+ next_turn_id: str | None = None,
+ receipt: dict[str, Any] | None = None,
+) -> dict[str, Any] | None:
+ delivery = get_delivery(conn, delivery_id)
+ if delivery is None:
+ return None
+ values: dict[str, Any] = {
+ "state": next_state,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": next_turn_id,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ }
+ if next_priority:
+ values["priority"] = next_priority
+ if next_state in {"queued", "reserved", "retired"}:
+ values.update(turn_id=None, turn_role=None, turn_position=None)
+ if next_state == "retired":
+ values["retired_at"] = utc_now_iso()
+ history_kind = str(delivery.get("current_attempt_kind") or "")
+ if not history_kind:
+ if delivery.get("state") == "claimed":
+ history_kind = "start"
+ elif delivery.get("state") == "pending_steer":
+ history_kind = "steer"
+ else:
+ history_kind = "interrupt_join"
+ return cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=expected_version,
+ expected_states=expected_states,
+ values=values,
+ history_event={
+ "kind": history_kind,
+ "attempt_id": delivery.get("current_attempt_id"),
+ "turn_id": delivery.get("current_target_turn_id"),
+ "outcome": outcome,
+ "receipt": receipt or {},
+ },
+ )
+
+
+def terminalize_turn(
+ conn: Connection,
+ turn_id: str,
+ *,
+ outcome: str,
+ settled_by: str | None,
+ evidence_kind: str,
+ evidence: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ turn = get_turn(conn, turn_id)
+ if turn is None or turn["state"] == "terminal":
+ return {"changed": False, "turn": turn}
+ values = {
+ "state": "terminal",
+ "terminal_outcome": outcome,
+ "settled_by": settled_by,
+ "terminal_evidence_kind": evidence_kind,
+ "terminal_evidence_json": _canonical_json(evidence or {}),
+ "terminal_at": turn_now_iso(),
+ }
+ if outcome == "not_written" and turn.get("start_attempt_id"):
+ if turn.get("start_receipt_outcome") == "accepted":
+ return {"changed": False, "turn": turn}
+ values.update(
+ {
+ "start_receipt_outcome": "not_written",
+ "start_receipt_json": _canonical_json(
+ {"kind": evidence_kind, **(evidence or {})}
+ ),
+ }
+ )
+ settled = cas_turn(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ expected_states=(str(turn["state"]),),
+ values=values,
+ )
+ return {"changed": settled is not None, "turn": settled or turn}
+
+
+def recovery_turns(conn: Connection, session_id: str | None = None) -> list[dict[str, Any]]:
+ query = select(session_turns).where(session_turns.c.state.in_(("waiting",) + TURN_OWNER_STATES))
+ if session_id:
+ query = query.where(session_turns.c.session_id == session_id)
+ return [dict(row) for row in conn.execute(query.order_by(session_turns.c.created_at, session_turns.c.id)).mappings()]
+
+
+def unresolved_deliveries(conn: Connection, session_id: str | None = None) -> list[dict[str, Any]]:
+ query = select(message_deliveries).where(
+ message_deliveries.c.state.in_(FENCE_STATES + ("claimed",))
+ )
+ if session_id:
+ query = query.where(message_deliveries.c.session_id == session_id)
+ return [dict(row) for row in conn.execute(query.order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)).mappings()]
+
+
+def recoverable_reservations(
+ conn: Connection,
+ session_id: str | None = None,
+) -> list[dict[str, Any]]:
+ """Pre-write producer reservations safe to re-enter through admission."""
+
+ query = select(message_deliveries).where(message_deliveries.c.state == "reserved")
+ if session_id:
+ query = query.where(message_deliveries.c.session_id == session_id)
+ return [
+ dict(row)
+ for row in conn.execute(
+ query.order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ ).mappings()
+ ]
+
+
+def session_ids_with_live_turns(conn: Connection) -> set[str]:
+ return {
+ str(value)
+ for value in conn.execute(
+ select(session_turns.c.session_id).where(session_turns.c.state.in_(TURN_OWNER_STATES)).distinct()
+ ).scalars()
+ }
+
+
+def session_ids_with_turn_history(conn: Connection) -> set[str]:
+ return {str(value) for value in conn.execute(select(session_turns.c.session_id).distinct()).scalars()}
+
+
+def active_runtime_session_ids_for_backend(conn: Connection, backend: str) -> set[str]:
+ return {
+ str(value)
+ for value in conn.execute(
+ select(session_turns.c.session_id)
+ .where(session_turns.c.backend == backend)
+ .where(session_turns.c.state == "active")
+ .distinct()
+ ).scalars()
+ }
+
+
+def live_turns_for_backend_sessions(
+ conn: Connection,
+ backend: str,
+ session_ids: set[str],
+) -> list[dict[str, Any]]:
+ if not session_ids:
+ return []
+ return [
+ dict(row)
+ for row in conn.execute(
+ select(session_turns)
+ .where(session_turns.c.backend == backend)
+ .where(session_turns.c.session_id.in_(session_ids))
+ .where(session_turns.c.state.in_(TURN_OWNER_STATES))
+ ).mappings()
+ ]
+
+
+def delivery_for_turn(conn: Connection, turn_id: str) -> dict[str, Any] | None:
+ turn = get_turn(conn, turn_id)
+ return get_delivery(conn, str((turn or {}).get("initial_delivery_id") or ""))
+
+
+def initial_deliveries_for_turn(conn: Connection, turn_id: str) -> list[dict[str, Any]]:
+ return [
+ dict(row)
+ for row in conn.execute(
+ select(message_deliveries)
+ .where(message_deliveries.c.turn_id == turn_id)
+ .where(message_deliveries.c.turn_role == "initial")
+ .order_by(message_deliveries.c.turn_position, message_deliveries.c.id)
+ ).mappings()
+ ]
+
+
+def message_for_delivery(conn: Connection, delivery: dict[str, Any]) -> dict[str, Any] | None:
+ message_id = str(delivery.get("message_id") or "")
+ return _one(conn, select(messages).where(messages.c.id == message_id)) if message_id else None
+
+
+def queued_session_ids_without_live_turns(
+ conn: Connection,
+ session_id: str | None = None,
+ *,
+ include_held: bool = False,
+) -> list[str]:
+ live = select(session_turns.c.id).where(
+ session_turns.c.session_id == message_deliveries.c.session_id,
+ session_turns.c.state.in_(TURN_OWNER_STATES),
+ ).exists()
+ query = (
+ select(message_deliveries.c.session_id)
+ .join(agent_sessions, agent_sessions.c.id == message_deliveries.c.session_id)
+ .where(message_deliveries.c.state == "queued")
+ .where(agent_sessions.c.status == "active")
+ .where(~live)
+ )
+ if not include_held:
+ query = query.where(agent_sessions.c.queue_hold_state == "open")
+ if session_id:
+ query = query.where(message_deliveries.c.session_id == session_id)
+ return [str(value) for value in conn.execute(query.distinct()).scalars()]
+
+
+def retire_queued(conn: Connection, session_id: str, delivery_id: str) -> bool:
+ delivery = get_delivery(conn, delivery_id)
+ if (
+ delivery is None
+ or delivery["session_id"] != session_id
+ or delivery["state"] != "queued"
+ ):
+ return False
+ updated = cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=("queued",),
+ values={"state": "retired", "retired_at": utc_now_iso()},
+ history_event={"kind": "retire", "reason": "queue_remove"},
+ )
+ return updated is not None
+
+
+def retire_queued_for_resubmission(
+ conn: Connection,
+ session_id: str,
+ delivery_id: str,
+ *,
+ expected_dedupe_key: str,
+) -> bool:
+ """Retire a recovered primary row and release its native dedupe claim."""
+
+ delivery = get_delivery(conn, delivery_id)
+ if (
+ delivery is None
+ or delivery["session_id"] != session_id
+ or delivery["state"] != "queued"
+ or delivery.get("dedupe_key") != expected_dedupe_key
+ or delivery.get("current_attempt_id") is not None
+ ):
+ return False
+ updated = cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=("queued",),
+ values={
+ "state": "retired",
+ "retired_at": utc_now_iso(),
+ "dedupe_key": None,
+ },
+ history_event={
+ "kind": "retire",
+ "reason": "agent_run_recovery_resubmit",
+ "released_dedupe_key": expected_dedupe_key,
+ },
+ )
+ return updated is not None
+
+
+def agent_run_ids_for_delivery(
+ conn: Connection,
+ delivery: dict[str, Any],
+) -> list[str]:
+ """Return the Agent Runs operationally represented by one Delivery."""
+
+ delivery_id = str(delivery.get("id") or "").strip()
+ if not delivery_id:
+ return []
+ return [
+ str(run_id)
+ for run_id in conn.execute(
+ select(agent_runs.c.id)
+ .where(agent_runs.c.delivery_id == delivery_id)
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ ).scalars()
+ ]
+
+
+def accepted_agent_run_ids_for_turn(conn: Connection, turn_id: str) -> list[str]:
+ """Return every accepted Agent Run participant owned by an exact Turn."""
+
+ run_ids: list[str] = []
+ for delivery in deliveries_for_turn(conn, turn_id):
+ if (
+ delivery.get("state") != "accepted"
+ or delivery.get("turn_id") != turn_id
+ ):
+ continue
+ for run_id in agent_run_ids_for_delivery(conn, delivery):
+ if run_id not in run_ids:
+ run_ids.append(run_id)
+ return run_ids
+
+
+def retire_queued_with_run(
+ conn: Connection,
+ session_id: str,
+ delivery_id: str,
+) -> bool:
+ """Retire an exact queued Delivery and its held Agent Run atomically."""
+
+ delivery = get_delivery(conn, delivery_id)
+ if (
+ delivery is None
+ or delivery["session_id"] != session_id
+ or delivery["state"] != "queued"
+ ):
+ return False
+ run_ids = agent_run_ids_for_delivery(conn, delivery)
+ if run_ids:
+ from storage.background import (
+ cancel_queued_agent_run_delivery_in_connection,
+ )
+ if len(run_ids) != 1:
+ return False
+ if not cancel_queued_agent_run_delivery_in_connection(
+ conn,
+ run_ids[0],
+ session_id=session_id,
+ delivery_id=delivery_id,
+ ):
+ return False
+ return retire_queued(conn, session_id, delivery_id)
+
+
+def terminal_turn_agent_run_owners(
+ conn: Connection,
+ session_id: str | None = None,
+) -> list[tuple[dict[str, Any], list[str]]]:
+ """Return terminal Turns and their accepted Agent Run participants."""
+
+ query = (
+ select(
+ session_turns.c.id.label("turn_id"),
+ session_turns.c.terminal_outcome,
+ session_turns.c.settled_by,
+ session_turns.c.terminal_evidence_kind,
+ session_turns.c.terminal_evidence_json,
+ session_turns.c.terminal_at,
+ agent_runs.c.id.label("run_id"),
+ )
+ .join(
+ message_deliveries,
+ message_deliveries.c.turn_id == session_turns.c.id,
+ )
+ .join(agent_runs, agent_runs.c.delivery_id == message_deliveries.c.id)
+ .where(session_turns.c.state == "terminal")
+ .where(message_deliveries.c.state == "accepted")
+ )
+ if session_id:
+ query = query.where(session_turns.c.session_id == session_id)
+ owners: dict[str, tuple[dict[str, Any], list[str]]] = {}
+ rows = conn.execute(
+ query.order_by(session_turns.c.terminal_at, session_turns.c.id)
+ ).mappings()
+ for row in rows:
+ turn_id = str(row["turn_id"])
+ run_id = str(row["run_id"])
+ owner = owners.setdefault(
+ turn_id,
+ (
+ {
+ "id": turn_id,
+ "terminal_outcome": row["terminal_outcome"],
+ "settled_by": row["settled_by"],
+ "terminal_evidence_kind": row["terminal_evidence_kind"],
+ "terminal_evidence_json": row["terminal_evidence_json"],
+ },
+ [],
+ ),
+ )
+ if run_id not in owner[1]:
+ owner[1].append(run_id)
+ return list(owners.values())
+
+
+def retire_reserved(
+ conn: Connection,
+ session_id: str,
+ delivery_id: str,
+ *,
+ reason: str,
+) -> bool:
+ """Retire only a producer reservation that no executor has claimed."""
+
+ delivery = get_delivery(conn, delivery_id)
+ if (
+ delivery is None
+ or delivery["session_id"] != session_id
+ or delivery["state"] != "reserved"
+ or delivery.get("current_attempt_id")
+ ):
+ return False
+ updated = cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={"state": "retired", "retired_at": utc_now_iso()},
+ history_event={"kind": "retire", "reason": reason},
+ )
+ return updated is not None
+
+
+def retire_not_written(conn: Connection, session_id: str, delivery_id: str, *, reason: str) -> bool:
+ delivery = get_delivery(conn, delivery_id)
+ if (
+ delivery is None
+ or delivery["session_id"] != session_id
+ or policy_for(str(delivery["state"])).run_cancel != "retire"
+ ):
+ return False
+ updated = cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=(str(delivery["state"]),),
+ values={
+ "state": "retired",
+ "retired_at": utc_now_iso(),
+ "turn_id": None,
+ "turn_role": None,
+ "turn_position": None,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ },
+ history_event={"kind": "retire", "reason": reason},
+ )
+ return updated is not None
+
+
+def retire_for_run_cancellation(
+ conn: Connection,
+ session_id: str,
+ delivery_id: str,
+) -> bool:
+ """Retire an exact Run input only when its state proves no native side effect."""
+
+ return retire_not_written(
+ conn,
+ session_id,
+ delivery_id,
+ reason="agent_run_canceled_before_native_write",
+ )
+
+
+def retire_for_archive(conn: Connection, session_id: str) -> dict[str, Any]:
+ """Retire only states proven not written; ambiguity remains reconcilable."""
+
+ rows = [
+ dict(row)
+ for row in conn.execute(
+ select(message_deliveries)
+ .where(message_deliveries.c.session_id == session_id)
+ .where(message_deliveries.c.state.in_(RUN_CANCEL_RETIRE_STATES))
+ ).mappings()
+ ]
+ retired = 0
+ retired_delivery_ids: list[str] = []
+ for row in rows:
+ if cas_delivery(
+ conn,
+ str(row["id"]),
+ expected_version=int(row["version"]),
+ expected_states=(str(row["state"]),),
+ values={
+ "state": "retired",
+ "retired_at": utc_now_iso(),
+ "turn_id": None,
+ "turn_role": None,
+ "turn_position": None,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ },
+ history_event={"kind": "retire", "reason": "session_archive"},
+ ) is not None:
+ retired += 1
+ retired_delivery_ids.append(str(row["id"]))
+ return {
+ "retired": retired,
+ "delivery_ids": retired_delivery_ids,
+ }
+
+
+def set_queue_hold(conn: Connection, session_id: str, *, held: bool) -> bool:
+ row = conn.execute(
+ select(agent_sessions.c.queue_hold_version).where(agent_sessions.c.id == session_id)
+ ).first()
+ if row is None:
+ return False
+ version = int(row[0])
+ result = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .where(agent_sessions.c.queue_hold_version == version)
+ .values(
+ queue_hold_state="held" if held else "open",
+ queue_hold_version=version + 1,
+ queue_held_at=utc_now_iso() if held else None,
+ )
+ )
+ return result.rowcount == 1
+
+
+def queue_is_held(conn: Connection, session_id: str) -> bool:
+ value = conn.execute(
+ select(agent_sessions.c.queue_hold_state).where(agent_sessions.c.id == session_id)
+ ).scalar_one_or_none()
+ return value == "held"
+
+
+def set_draft(conn: Connection, session_id: str, text: str | None) -> bool:
+ now = utc_now_iso()
+ result = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .values(
+ composer_draft_text=text if text and text.strip() else None,
+ composer_draft_updated_at=now if text and text.strip() else None,
+ updated_at=now,
+ )
+ )
+ return result.rowcount == 1
+
+
+def get_draft(conn: Connection, session_id: str) -> dict[str, Any] | None:
+ row = conn.execute(
+ select(
+ agent_sessions.c.composer_draft_text,
+ agent_sessions.c.composer_draft_updated_at,
+ ).where(agent_sessions.c.id == session_id)
+ ).first()
+ if row is None or not row[0]:
+ return None
+ return {"text": str(row[0]), "updated_at": row[1]}
+
+
+def pending_control_for_turn(conn: Connection, turn_id: str) -> dict[str, Any] | None:
+ return _one(
+ conn,
+ select(session_turns)
+ .where(session_turns.c.id == turn_id)
+ .where(
+ session_turns.c.control_state.in_(
+ ("pending", "interrupting", "waiting_terminal", "reconciling")
+ )
+ ),
+ )
+
+
+def pending_steer_for_turn(conn: Connection, turn_id: str) -> dict[str, Any] | None:
+ return _one(
+ conn,
+ select(message_deliveries)
+ .where(message_deliveries.c.current_target_turn_id == turn_id)
+ .where(message_deliveries.c.state == "pending_steer")
+ .order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ .limit(1),
+ )
+
+
+def turn_has_delivery_owner(conn: Connection, turn_id: str) -> bool:
+ turn = get_turn(conn, turn_id)
+ return bool(turn and get_delivery(conn, str(turn["initial_delivery_id"])))
+
+
+def deliveries_for_turn(conn: Connection, turn_id: str) -> list[dict[str, Any]]:
+ return [
+ dict(row)
+ for row in conn.execute(
+ select(message_deliveries)
+ .where(
+ or_(
+ message_deliveries.c.turn_id == turn_id,
+ message_deliveries.c.current_target_turn_id == turn_id,
+ )
+ )
+ .order_by(
+ message_deliveries.c.turn_position,
+ message_deliveries.c.submitted_at,
+ message_deliveries.c.id,
+ )
+ ).mappings()
+ ]
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 2cad7bef0..ef530885a 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -1,11 +1,10 @@
-"""CRUD over the platform-agnostic ``messages`` table.
+"""Accepted communication records in the platform-agnostic ``messages`` table.
The workbench Inbox + per-session history both read through this
module so they get a consistent shape regardless of which platform
-originated the row. ``append`` is the canonical write path —
-adapters and REST routes call it instead of touching the table
-directly so future invariants (e.g. SSE fan-out hooks, audit logging)
-land in one place.
+originated the row. Inbound content materializes here only after a Delivery is
+accepted; ``append`` is for communication that is already accepted when written,
+such as agent output and mirrored IM records.
"""
from __future__ import annotations
@@ -26,20 +25,35 @@ from storage.models import (
agent_runs,
agent_sessions,
agents,
+ message_deliveries,
messages,
scope_settings,
scopes,
+ session_turns,
)
from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one
from storage.sessions_service import session_agent_display_label
from vibe.message_identity import HARNESS_TYPE, INPUT_TURN_AUTHOR_TYPES
-from vibe.message_types import types_with, types_without
+from vibe.message_types import types_with
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+def _timestamp_key(value: Any, row_id: Any) -> tuple[datetime, str]:
+ text = str(value or "").strip()
+ if text.endswith("Z"):
+ text = text[:-1] + "+00:00"
+ try:
+ instant = datetime.fromisoformat(text)
+ except ValueError:
+ instant = datetime.min.replace(tzinfo=timezone.utc)
+ if instant.tzinfo is None:
+ instant = instant.replace(tzinfo=timezone.utc)
+ return instant.astimezone(timezone.utc), str(row_id or "")
+
+
def _new_message_id() -> str:
"""Time-sortable message id.
@@ -87,34 +101,6 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:
_AGENT_RUN_NATIVE_PREFIX = "agent_run:"
-_SCHEDULED_PROVENANCE_KEY = "scheduled_provenance"
-
-
-def _queued_agent_run_id(row: dict[str, Any]) -> str:
- native_message_id = str(row.get("native_message_id") or "").strip()
- if native_message_id.startswith(_AGENT_RUN_NATIVE_PREFIX):
- return native_message_id[len(_AGENT_RUN_NATIVE_PREFIX):]
- try:
- metadata = json.loads(row.get("metadata_json") or "{}")
- except (TypeError, json.JSONDecodeError):
- return ""
- provenance = (
- metadata.get(_SCHEDULED_PROVENANCE_KEY)
- if isinstance(metadata, dict)
- else None
- )
- platform_specific = (
- provenance.get("platform_specific")
- if isinstance(provenance, dict)
- else None
- )
- if (
- not isinstance(platform_specific, dict)
- or str(platform_specific.get("task_trigger_kind") or "").strip()
- != "agent_run"
- ):
- return ""
- return str(platform_specific.get("task_execution_id") or "").strip()
def _attach_agent_run_provenance(
@@ -741,49 +727,14 @@ def first_user_text(conn: Connection, session_id: str) -> str:
return str(content.get("text") or "").strip() if isinstance(content, dict) else ""
-# --- Send-while-busy queue + per-session draft -----------------------------
-# Both reuse the ``messages`` table via dedicated ``type`` values so no extra
-# table is needed (the queue is ephemeral operational state, not conversation):
-# type='queued' — input sent while a turn was in flight; flushed (merged, in
-# order) into one dispatch when the turn ends.
-# type='draft' — the user's unsent compose text for a session; one row per
-# session, persisted so switching sessions/devices keeps it.
-# The transcript, inbox, and unread queries are type-filtered, so neither leaks
-# into the conversation.
-
-QUEUED_TYPE = "queued"
-DRAFT_TYPE = "draft"
-QUEUED_DISPATCH_TEXT_KEY = "_queued_dispatch_text"
-# A reserved-but-not-yet-accepted input row: persisted BEFORE dispatch (so it
-# reserves its (created_at, id) for correct ordering) but hidden from the
-# transcript, the queue AND the inbox until the controller decides whether the
-# turn started (→ promote by origin) or must be queued (→ promote to 'queued').
-# This stops another tab from briefly seeing the row as a sent prompt during the
-# dispatch window (Codex P2).
-PENDING_TYPE = "pending"
-# Hidden row used only to keep native-message-id dedupe coverage after multiple
-# queued harness callbacks are coalesced into one dispatched turn.
-HARNESS_DEDUPE_TYPE = "harness_dedupe"
-# An INVISIBLE, agent-authored terminal marker persisted when a turn completes
-# NORMALLY but produces no user-visible message — a ``<silent>``-stripped or empty
-# final reply, or a reply-less bookkeeping turn (common for watch/scheduled
-# orchestration). It exists ONLY so the activity grouping can close such a turn as
-# DONE instead of misreading "activity rows + no terminal" as ``interrupted``. It is
-# kept out of every user-facing surface by the allowlist reads (TRANSCRIPT_TYPES,
-# inbox preview, unread, web-push, live publish) and, being author='agent', is listed
-# in NON_CONVERSATION_TYPES below so it never bumps the inbox activity clock / last
-# author. Never delivered to IM (avibe-persistence only).
-SILENT_TYPE = "silent"
ANNOTATION_TYPE = "annotation"
-# Types that must never count as inbox conversation activity: the ephemeral user rows
-# above plus the invisible agent silent-completion marker.
-NON_CONVERSATION_TYPES = types_without("inboxActivity")
+INBOX_ACTIVITY_TYPES = types_with("inboxActivity")
# The transcript-visible types — the SINGLE source of truth shared by the
# history fetch (``list_session_messages``) AND the live ``message.new`` publish
# gate, so what a page loads and what it receives over the stream are identical.
-# Excludes the agent's process log (``assistant`` / ``tool_call``) and ``system``
-# (which isn't persisted at all). Harness-triggered prompts have their own type
+# Excludes hidden ``assistant`` communication; tool calls live in ``agent_events``
+# and ``system`` is not persisted. Harness-triggered prompts have their own type
# so they cannot be mistaken for human input. Show Page annotations in either
# direction share one explicit transcript type. ``error`` is a terminal FAILED
# result (turned the dot red): shown in the conversation like any terminal
@@ -795,336 +746,6 @@ _INBOX_SETTLES_REPLY_TYPES = types_with("inboxSettlesReply")
_UNREAD_TYPES = types_with("unread")
-def enqueue_queued(
- conn: Connection,
- *,
- scope_id: str,
- session_id: str,
- text: str,
- author_id: Optional[str] = None,
- author_name: Optional[str] = None,
-) -> dict[str, Any]:
- """Append a queued ('send while busy') message for a session."""
- return append(
- conn,
- scope_id=scope_id,
- session_id=session_id,
- platform="avibe",
- author="user",
- source="user",
- message_type=QUEUED_TYPE,
- text=text,
- author_id=author_id,
- author_name=author_name,
- )
-
-
-def _queued_query(session_id: str):
- return (
- select(messages)
- .where(messages.c.session_id == session_id)
- .where(messages.c.type == QUEUED_TYPE)
- .order_by(messages.c.created_at.asc(), messages.c.id.asc())
- )
-
-
-def list_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
- """Pending queued messages for a session, oldest first."""
- query = _queued_query(session_id)
- return [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
-
-
-def list_queued_page(
- conn: Connection,
- session_id: str,
- *,
- page_request: PageRequest,
-) -> PageResult[dict[str, Any]]:
- """One bounded FIFO page for Agent-facing Session queue inspection."""
-
- query = (
- _queued_query(session_id)
- .limit(page_request.limit + 1)
- .offset(page_request.offset)
- )
- rows = [
- _row_to_payload(dict(row))
- for row in conn.execute(query).mappings().all()
- ]
- return page_result_from_limit_plus_one(rows, page_request)
-
-
-def list_recoverable_pending(conn: Connection) -> list[dict[str, Any]]:
- """Every pending input reservation considered by startup cleanup.
-
- The caller deletes rows whose sessions are gone and decides which live-session
- origins are safe to make visible without replaying their work.
- """
-
- query = (
- select(messages)
- .where(messages.c.type == PENDING_TYPE)
- .order_by(messages.c.created_at.asc(), messages.c.id.asc())
- )
- return [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
-
-
-def list_queued_session_ids(conn: Connection) -> list[str]:
- """Session ids with persisted queue rows, ordered by their oldest row."""
-
- query = (
- select(messages.c.session_id)
- .where(messages.c.session_id.is_not(None))
- .where(messages.c.type == QUEUED_TYPE)
- .group_by(messages.c.session_id)
- .order_by(func.min(messages.c.created_at), func.min(messages.c.id))
- )
- return [str(session_id) for session_id in conn.execute(query).scalars() if session_id]
-
-
-def pop_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
- """Claim the session's queued messages: read them (oldest first), then delete
- them in the SAME transaction, so the rows are returned exactly once. Empty
- list when the queue is empty.
-
- Select-then-delete rather than ``DELETE ... RETURNING``: RETURNING needs
- SQLite >= 3.35, which the project does not pin, so on an older libsqlite the
- flush would raise — ``_flush_queue`` returns False and the send-while-busy
- queue never dispatches, stranding the user's queued follow-up (Codex P2).
-
- The DELETE is scoped to the CLAIMED row ids (not a broad session+type
- predicate): the UI server is a SEPARATE writer that can promote a just-sent
- prompt to ``queued`` between the SELECT and the DELETE, and a broad delete
- would drop that newer row without returning it — losing the user's message.
- Deleting only the ids we actually read leaves any concurrently-enqueued row
- for the next flush (Codex P2).
- """
- rows_q = (
- select(messages)
- .where(messages.c.session_id == session_id)
- .where(messages.c.type == QUEUED_TYPE)
- .order_by(messages.c.created_at.asc(), messages.c.id.asc())
- )
- rows = [_row_to_payload(dict(row)) for row in conn.execute(rows_q).mappings().all()]
- if not rows:
- return []
- claimed_ids = [r["id"] for r in rows]
- conn.execute(delete(messages).where(messages.c.id.in_(claimed_ids)))
- return rows
-
-
-def delete_queued(conn: Connection, ids: list[str]) -> None:
- """Delete a CLAIMED subset of queued rows by id. The caller read them via
- ``list_queued`` and is claiming exactly this segment (e.g. the leading run of
- user rows, or one scheduled row). Scoped to the read ids — not a broad
- session+type predicate — so a row another writer enqueued after the read
- survives for the next flush (same safety rationale as ``pop_queued``)."""
- if not ids:
- return
- conn.execute(delete(messages).where(messages.c.id.in_(ids)))
-
-
-def delete_queued_agent_run(
- conn: Connection,
- *,
- session_id: str,
- run_id: str,
-) -> int:
- """Retire the exact queued row owned by a canceled Workbench Agent Run."""
-
- normalized_session_id = str(session_id or "").strip()
- normalized_run_id = str(run_id or "").strip()
- if not normalized_session_id or not normalized_run_id:
- return 0
- rows = list(
- conn.execute(
- select(
- messages.c.id,
- messages.c.native_message_id,
- messages.c.metadata_json,
- )
- .where(messages.c.session_id == normalized_session_id)
- .where(messages.c.type == QUEUED_TYPE)
- ).mappings()
- )
- row_ids = [
- str(row["id"])
- for row in rows
- if _queued_agent_run_id(dict(row)) == normalized_run_id
- ]
- if not row_ids:
- return 0
- result = conn.execute(
- delete(messages)
- .where(messages.c.id.in_(row_ids))
- .where(messages.c.session_id == normalized_session_id)
- .where(messages.c.type == QUEUED_TYPE)
- )
- return result.rowcount or 0
-
-
-def clear_queued(conn: Connection, session_id: str) -> int:
- """Drop ALL send-while-busy queued rows for a session. Used by archive so no
- queued prompt can later be flushed into a now-terminal session (on natural
- turn completion or via send-now) — unlike ``delete_queued``, which claims a
- specific id segment during a flush. Returns the number removed."""
- result = conn.execute(
- delete(messages)
- .where(messages.c.session_id == session_id)
- .where(messages.c.type == QUEUED_TYPE)
- )
- return result.rowcount or 0
-
-
-def clear_pending(conn: Connection, session_id: str) -> int:
- """Drop unsettled transcript reservations for a session."""
- result = conn.execute(
- delete(messages)
- .where(messages.c.session_id == session_id)
- .where(messages.c.type == PENDING_TYPE)
- )
- return result.rowcount or 0
-
-
-def delete_pending(conn: Connection, message_id: str) -> bool:
- """Delete one reserved pending row by id. Returns True when removed."""
-
- result = conn.execute(
- delete(messages)
- .where(messages.c.id == message_id)
- .where(messages.c.type == PENDING_TYPE)
- )
- return bool(result.rowcount)
-
-
-def promote_pending(conn: Connection, message_id: str, to_type: str) -> bool:
- """Advance one reservation and discard its prompt only when delivered."""
-
- values: dict[str, Any] = {"type": to_type}
- if to_type != QUEUED_TYPE:
- values["metadata_json"] = case(
- (
- func.json_valid(messages.c.metadata_json) == 1,
- func.json_remove(
- messages.c.metadata_json,
- f"$.{QUEUED_DISPATCH_TEXT_KEY}",
- ),
- ),
- else_=messages.c.metadata_json,
- )
- result = conn.execute(
- update(messages)
- .where(messages.c.id == message_id)
- .where(messages.c.type == PENDING_TYPE)
- .values(**values)
- )
- return bool(result.rowcount)
-
-
-def pending_message_target_type(
- author: Optional[str],
- source: Optional[str],
- author_name: Optional[str],
-) -> str:
- """Resolve an accepted input reservation to its transcript-visible type."""
- if (
- author == HARNESS_TYPE
- and source == HARNESS_TYPE
- and author_name == "show_annotation"
- ):
- return ANNOTATION_TYPE
- if HARNESS_TYPE in {author, source}:
- return HARNESS_TYPE
- return "user"
-
-
-def remove_queued(conn: Connection, session_id: str, message_id: str) -> bool:
- """Delete one queued message and cancel any Agent Run it durably owns.
-
- The Session/type predicates keep stale and cross-Session ids inert. An
- Agent-Run-backed row may be removed only while that Run is still queued and
- explicitly held by Workbench; its cancellation and the row deletion commit
- together in the caller's transaction.
- """
- row = conn.execute(
- select(messages.c.native_message_id, messages.c.metadata_json)
- .where(messages.c.id == message_id)
- .where(messages.c.session_id == session_id)
- .where(messages.c.type == QUEUED_TYPE)
- .limit(1)
- ).mappings().first()
- if row is None:
- return False
- run_id = _queued_agent_run_id(dict(row))
- if run_id:
- from storage.background import (
- cancel_workbench_queued_agent_run_in_connection,
- )
-
- if not cancel_workbench_queued_agent_run_in_connection(
- conn,
- run_id,
- session_id=session_id,
- ):
- return False
- result = conn.execute(
- delete(messages)
- .where(messages.c.id == message_id)
- .where(messages.c.session_id == session_id)
- .where(messages.c.type == QUEUED_TYPE)
- )
- if run_id and not result.rowcount:
- raise RuntimeError(
- "queued Agent Run cancellation succeeded but its message deletion was refused"
- )
- return bool(result.rowcount)
-
-
-def get_draft(conn: Connection, session_id: str) -> Optional[dict[str, Any]]:
- """The session's current unsent draft, or None."""
- query = (
- select(messages)
- .where(messages.c.session_id == session_id)
- .where(messages.c.type == DRAFT_TYPE)
- .order_by(messages.c.created_at.desc(), messages.c.id.desc())
- .limit(1)
- )
- row = conn.execute(query).mappings().first()
- return _row_to_payload(dict(row)) if row else None
-
-
-def set_draft(
- conn: Connection,
- *,
- scope_id: Optional[str],
- session_id: str,
- text: Optional[str],
-) -> Optional[dict[str, Any]]:
- """Upsert the session's draft (one row per session). Blank text clears it."""
- conn.execute(
- delete(messages).where(messages.c.session_id == session_id).where(messages.c.type == DRAFT_TYPE)
- )
- if not text or not text.strip():
- return None
- return append(
- conn,
- scope_id=scope_id,
- session_id=session_id,
- platform="avibe",
- author="user",
- source="user",
- message_type=DRAFT_TYPE,
- text=text,
- )
-
-
-def clear_draft(conn: Connection, session_id: str) -> None:
- """Drop the session's draft (e.g. after a successful send)."""
- conn.execute(
- delete(messages).where(messages.c.session_id == session_id).where(messages.c.type == DRAFT_TYPE)
- )
-
-
def unread_counts(
conn: Connection,
*,
@@ -1136,8 +757,8 @@ def unread_counts(
plus the global count without dragging every row through Python.
Filtered to ``type='result'`` so it agrees with the inbox feed's UNREAD
count, which is also result-only — otherwise intermediate ``assistant`` /
- ``tool_call`` rows (now persisted for avibe too) would inflate the badge
- past what the feed shows. (Inbox *eligibility* and *preview* also accept a
+ process-event rows in ``agent_events`` would inflate the badge past what the
+ feed shows. (Inbox *eligibility* and *preview* also accept a
terminal ``notify`` so failed turns stay visible, but a failure notify is
not an unread reply — it never bumps this badge.)
"""
@@ -1284,7 +905,7 @@ def list_inbox_sessions(
)
)
if conversation_only:
- query = query.where(msg.c.type.notin_(NON_CONVERSATION_TYPES))
+ query = query.where(msg.c.type.in_(INBOX_ACTIVITY_TYPES))
return query.scalar_subquery()
# Drive from the small session set and do top-1 index probes per session.
@@ -1294,16 +915,52 @@ def list_inbox_sessions(
last_author = _latest_message_value("author", conversation_only=True)
preview_id = _latest_message_value("id", types=_INBOX_PREVIEW_TYPES)
preview_at = _latest_message_value("created_at", types=_INBOX_PREVIEW_TYPES)
- # The awaiting/replied calc must count the INVISIBLE ``silent`` completion marker
- # as a reply too (a reply-less turn is still answered) — otherwise a silently
- # completed turn keeps the sidebar showing "awaiting the agent". The PREVIEW text
- # stays the last VISIBLE reply, so ``silent`` is included here but NOT in preview_*.
last_terminal_id = _latest_message_value("id", types=_INBOX_SETTLES_REPLY_TYPES)
last_terminal_at = _latest_message_value("created_at", types=_INBOX_SETTLES_REPLY_TYPES)
+ last_turn_terminal_id = (
+ select(session_turns.c.id)
+ .where(
+ session_turns.c.session_id == agent_sessions.c.id,
+ session_turns.c.state == "terminal",
+ session_turns.c.terminal_outcome != "not_written",
+ )
+ .order_by(
+ func.julianday(session_turns.c.terminal_at).desc(),
+ session_turns.c.id.desc(),
+ )
+ .limit(1)
+ .scalar_subquery()
+ )
+ last_turn_terminal_at = (
+ select(session_turns.c.terminal_at)
+ .where(
+ session_turns.c.session_id == agent_sessions.c.id,
+ session_turns.c.state == "terminal",
+ session_turns.c.terminal_outcome != "not_written",
+ )
+ .order_by(
+ func.julianday(session_turns.c.terminal_at).desc(),
+ session_turns.c.id.desc(),
+ )
+ .limit(1)
+ .scalar_subquery()
+ )
last_input_at = _latest_message_value(
"created_at", conversation_only=True, input_turn_only=True
)
last_input_id = _latest_message_value("id", conversation_only=True, input_turn_only=True)
+ last_input_turn_state = (
+ select(session_turns.c.state)
+ .select_from(
+ message_deliveries.join(
+ session_turns,
+ session_turns.c.id == message_deliveries.c.turn_id,
+ )
+ )
+ .where(message_deliveries.c.message_id == last_input_id)
+ .limit(1)
+ .scalar_subquery()
+ )
# Unread agent messages per session.
m = messages
@@ -1334,8 +991,11 @@ def list_inbox_sessions(
preview_at.label("preview_at"),
last_terminal_id.label("last_terminal_id"),
last_terminal_at.label("last_terminal_at"),
+ last_turn_terminal_id.label("last_turn_terminal_id"),
+ last_turn_terminal_at.label("last_turn_terminal_at"),
last_input_at.label("last_input_at"),
last_input_id.label("last_input_id"),
+ last_input_turn_state.label("last_input_turn_state"),
)
.select_from(
agent_sessions.join(scopes, scopes.c.id == agent_sessions.c.scope_id, isouter=True).join(
@@ -1409,19 +1069,28 @@ def list_inbox_sessions(
# reply.
last_input_at = row["last_input_at"]
last_input_id = row["last_input_id"]
- # Compare against the last TERMINAL (incl. the invisible ``silent`` marker),
- # not the preview: a silently-completed turn HAS replied even though its text
- # is not the visible preview.
- terminal_at = row["last_terminal_at"]
- terminal_id = row["last_terminal_id"]
- awaiting_reply = bool(
- last_input_at is not None
- and terminal_at is not None
- and (
- last_input_at > terminal_at
- or (last_input_at == terminal_at and (last_input_id or "") > (terminal_id or ""))
- )
+ # Execution settlement belongs to SessionTurn. A visible result Message
+ # can be later (for example after delivery retries), so use the newest
+ # semantic terminal evidence without creating an invisible Message marker.
+ terminal_candidates = [
+ (row["last_terminal_at"], row["last_terminal_id"]),
+ (row["last_turn_terminal_at"], row["last_turn_terminal_id"]),
+ ]
+ terminal_at, terminal_id = max(
+ (candidate for candidate in terminal_candidates if candidate[0] is not None),
+ key=lambda candidate: _timestamp_key(candidate[0], candidate[1]),
+ default=(None, None),
)
+ accepted_turn_state = str(row["last_input_turn_state"] or "")
+ if accepted_turn_state:
+ awaiting_reply = accepted_turn_state in {"starting", "active"}
+ else:
+ awaiting_reply = bool(
+ last_input_at is not None
+ and terminal_at is not None
+ and _timestamp_key(last_input_at, last_input_id)
+ > _timestamp_key(terminal_at, terminal_id)
+ )
sessions.append(
{
"session_id": row["session_id"],
diff --git a/storage/migrations.py b/storage/migrations.py
index 2b0546efd..aacc72694 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -53,6 +53,8 @@ HEAD_TABLES = INITIAL_TABLES | {
"agent_runs",
"show_pages",
"messages",
+ "message_deliveries",
+ "session_turns",
"agent_events",
"show_session_events",
"media_objects",
@@ -70,7 +72,7 @@ PRE_SHOW_SESSION_EVENTS_HEAD_TABLES = INITIAL_TABLES | {
"show_pages",
"messages",
}
-HEAD_REQUIRED_COLUMNS = {
+PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS = {
"agents": {"enabled"},
"scope_settings": {"agent_name"},
"agent_sessions": {"agent_id", "agent_name", "visibility", "pinned"},
@@ -110,6 +112,33 @@ HEAD_REQUIRED_COLUMNS = {
"cancel_requested_at",
},
}
+HEAD_REQUIRED_COLUMNS = PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS | {
+ "agent_sessions": PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS["agent_sessions"]
+ | {
+ "queue_hold_state",
+ "queue_hold_version",
+ "queue_held_at",
+ "composer_draft_text",
+ "composer_draft_updated_at",
+ },
+ "message_deliveries": {
+ "message_id",
+ "priority",
+ "state",
+ "dispatch_text",
+ "delivery_history_json",
+ "version",
+ },
+ "session_turns": {
+ "initial_delivery_id",
+ "state",
+ "native_turn_id",
+ "control_state",
+ "terminal_outcome",
+ "settled_by",
+ "version",
+ },
+}
HEAD_ONLY_REQUIRED_COLUMNS = {
"web_push_subscriptions": {"device_id"},
"vault_requests": {"callback_status"},
@@ -450,7 +479,10 @@ def _head_schema_ready(conn: sqlite3.Connection, tables: set[str]) -> bool:
def _pre_show_session_events_head_schema_ready(conn: sqlite3.Connection, tables: set[str]) -> bool:
if not PRE_SHOW_SESSION_EVENTS_HEAD_TABLES.issubset(tables):
return False
- return all(required_columns.issubset(_column_names(conn, table)) for table, required_columns in HEAD_REQUIRED_COLUMNS.items())
+ return all(
+ required_columns.issubset(_column_names(conn, table))
+ for table, required_columns in PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS.items()
+ )
def _repair_head_required_columns(conn: sqlite3.Connection, tables: set[str]) -> bool:
@@ -732,6 +764,8 @@ def _ensure_agent_runs_expression_indexes(conn: sqlite3.Connection) -> None:
def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:
+ from vibe.message_types import build_partial_index_predicate
+
if "agent_sessions" in tables:
conn.execute(
"create index if not exists ix_agent_sessions_visibility "
@@ -758,25 +792,17 @@ def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -
'create index if not exists ix_messages_mark_read '
'on messages (session_id, author, read_at, created_at, id)'
)
- conn.execute("drop index if exists ix_messages_inbox_activity")
- conn.execute(
- "create index ix_messages_inbox_activity "
- "on messages (platform, session_id, created_at desc, id desc) "
- "where session_id is not null and type not in ('queued', 'draft', 'pending', 'harness_dedupe', 'silent')"
- )
- conn.execute(
- "create index if not exists ix_messages_inbox_agent_reply "
- "on messages (platform, session_id, created_at desc, id desc) "
- "where session_id is not null and type in ('result', 'notify', 'error')"
- )
- conn.execute("drop index if exists ix_messages_inbox_user_send")
- conn.execute(
- "create index ix_messages_inbox_user_send "
- "on messages (platform, session_id, created_at desc, id desc) "
- "where session_id is not null and "
- "((author = 'user' and type = 'user') or "
- "(author = 'harness' and type = 'harness'))"
- )
+ for index_name in (
+ "ix_messages_inbox_activity",
+ "ix_messages_inbox_agent_reply",
+ "ix_messages_inbox_user_send",
+ ):
+ conn.execute(f"drop index if exists {index_name}")
+ conn.execute(
+ f"create index {index_name} "
+ "on messages (platform, session_id, created_at desc, id desc) "
+ f"where {build_partial_index_predicate(index_name)}"
+ )
def _ensure_agent_events_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:
@@ -864,7 +890,7 @@ def _missing_pre_show_session_events_head_schema_description(conn: sqlite3.Conne
if not PRE_SHOW_SESSION_EVENTS_HEAD_TABLES.issubset(tables)
else []
)
- for table, required_columns in HEAD_REQUIRED_COLUMNS.items():
+ for table, required_columns in PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS.items():
if table not in tables:
continue
missing_columns = required_columns - _column_names(conn, table)
diff --git a/storage/models.py b/storage/models.py
index bc02e8db2..870bb4312 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -1,10 +1,12 @@
from __future__ import annotations
from sqlalchemy import (
+ CheckConstraint,
Column,
DDL,
Float,
ForeignKey,
+ ForeignKeyConstraint,
Index,
Integer,
MetaData,
@@ -17,10 +19,16 @@ from sqlalchemy import (
text,
)
+from storage.delivery_states import DELIVERY_STATES
from vibe.message_types import build_partial_index_predicate
metadata = MetaData()
+
+def _sql_string_set(values: tuple[str, ...]) -> str:
+ return ", ".join(f"'{value}'" for value in values)
+
+
state_meta = Table(
"state_meta",
metadata,
@@ -130,6 +138,14 @@ agent_sessions = Table(
# ``running`` while a turn is in flight, ``failed`` when the most recent
# turn errored, ``idle`` otherwise. Drives the workbench sidebar status dot.
Column("agent_status", String, nullable=False, server_default="idle"),
+ # Session-level policy/state. The hold blocks only autonomous backlog drain;
+ # explicit admission and empty-P1 release remain Delivery-manager decisions.
+ Column("queue_hold_state", String, nullable=False, server_default="open"),
+ Column("queue_hold_version", Integer, nullable=False, server_default="1"),
+ Column("queue_held_at", String, nullable=True),
+ # Composer state is one value per Session, not a communication record.
+ Column("composer_draft_text", Text, nullable=True),
+ Column("composer_draft_updated_at", String, nullable=True),
Column("metadata_json", Text, nullable=False),
Column("created_at", String, nullable=False),
Column("updated_at", String, nullable=False),
@@ -155,6 +171,10 @@ agent_sessions = Table(
"id",
),
Index("ix_agent_sessions_native_session", "native_session_id"),
+ CheckConstraint(
+ "queue_hold_state in ('open', 'held')",
+ name="ck_agent_sessions_queue_hold_state",
+ ),
)
runtime_records = Table(
@@ -249,6 +269,7 @@ agent_runs = Table(
Column("result_text", Text, nullable=True),
Column("result_payload_json", Text, nullable=True),
Column("message_ids_json", Text, nullable=True),
+ Column("delivery_id", String, nullable=True),
Column("callback_session_id", String, nullable=True),
Column("callback_status", String, nullable=True),
Column("callback_error", Text, nullable=True),
@@ -270,6 +291,12 @@ agent_runs = Table(
Index("ix_agent_runs_status_created", "status", "created_at"),
Index("ix_agent_runs_type_status_created", "run_type", "status", "created_at"),
Index("ix_agent_runs_session_created", "session_id", "created_at"),
+ Index(
+ "uq_agent_runs_delivery",
+ "delivery_id",
+ unique=True,
+ sqlite_where=text("delivery_id is not null"),
+ ),
Index("ix_agent_runs_agent_created", "agent_name", "created_at"),
Index("ix_agent_runs_callback_status", "callback_status", "completed_at"),
# Leading-timestamp index for the run-graph window scan: updated_at bumps on
@@ -308,6 +335,7 @@ show_session_events = Table(
Column("payload_json", Text, nullable=False),
Column("transcript_text", Text, nullable=True),
Column("message_id", String, ForeignKey("messages.id", ondelete="SET NULL"), nullable=True),
+ Column("delivery_id", String, nullable=True),
Column("created_at", String, nullable=False),
Index("ix_show_session_events_session_created", "session_id", "created_at"),
Index("ix_show_session_events_type_created", "event_type", "created_at"),
@@ -354,12 +382,22 @@ messages = Table(
metadata,
Column("id", String, primary_key=True),
Column("scope_id", String, ForeignKey("scopes.id", ondelete="CASCADE"), nullable=True),
- Column("session_id", String, ForeignKey("agent_sessions.id", ondelete="SET NULL"), nullable=True),
+ Column(
+ "session_id",
+ String,
+ ForeignKey(
+ "agent_sessions.id",
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ name="fk_messages_session_id_agent_sessions",
+ ),
+ nullable=True,
+ ),
Column("platform", String, nullable=False),
Column("author", String, nullable=False),
- # Fine-grained message type, distinct from the coarse ``author``:
- # user / assistant / tool_call / notify / result. The inbox preview uses
- # the latest ``assistant`` row. Persisted regardless of IM display muting.
+ # Fine-grained accepted communication kind, distinct from coarse ``author``.
+ # Operational queue/trace/draft concepts are forbidden from this ledger.
Column("type", String, nullable=False, server_default="assistant"),
Column("author_id", String, nullable=True),
Column("author_name", Text, nullable=True),
@@ -412,6 +450,345 @@ messages = Table(
Index("ix_messages_scope_created", "scope_id", "created_at"),
Index("ix_messages_scope_unread", "scope_id", "read_at"),
Index("ix_messages_author_created", "author", "created_at"),
+ CheckConstraint(
+ "type not in ('queued', 'pending', 'draft', 'harness_dedupe', 'silent', 'tool_call')",
+ name="ck_messages_communication_type",
+ ),
+)
+
+# Durable execution ownership for one logical Agent Turn per Session. The Turn
+# references its initial Delivery even before native acceptance has materialized
+# a Message. Accepted steer participants reference the Turn from their Delivery.
+session_turns = Table(
+ "session_turns",
+ metadata,
+ Column("id", String, primary_key=True),
+ Column(
+ "session_id",
+ String,
+ ForeignKey(
+ "agent_sessions.id",
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ ),
+ nullable=False,
+ ),
+ Column("initial_delivery_id", String, nullable=False),
+ Column("state", String, nullable=False),
+ Column("backend", String, nullable=False),
+ Column("runtime_key", Text, nullable=True),
+ Column("runtime_turn_id", Text, nullable=True),
+ Column("native_turn_id", Text, nullable=True),
+ Column("start_attempt_id", String, nullable=True),
+ Column("start_receipt_outcome", String, nullable=True),
+ Column("start_receipt_json", Text, nullable=False, server_default="{}"),
+ Column("dispatch_text", Text, nullable=True),
+ Column("dispatch_sha256", String, nullable=True),
+ Column("terminal_outcome", String, nullable=True),
+ Column("settled_by", String, nullable=True),
+ Column("terminal_evidence_kind", String, nullable=True),
+ Column("terminal_evidence_json", Text, nullable=False, server_default="{}"),
+ # One coalesced control slot owns empty/content P0 against this exact Turn.
+ Column("control_state", String, nullable=True),
+ Column("control_mode", String, nullable=True),
+ Column("control_attempt_id", String, nullable=True),
+ Column("control_expected_native_turn_id", Text, nullable=True),
+ Column("control_receipt_outcome", String, nullable=True),
+ Column("control_receipt_json", Text, nullable=False, server_default="{}"),
+ Column("control_successor_delivery_id", String, nullable=True),
+ Column("control_successor_turn_id", String, nullable=True),
+ Column("version", Integer, nullable=False, server_default="1"),
+ Column("created_at", String, nullable=False),
+ Column("updated_at", String, nullable=False),
+ Column("started_at", String, nullable=True),
+ Column("terminal_at", String, nullable=True),
+ ForeignKeyConstraint(
+ ["initial_delivery_id"],
+ ["message_deliveries.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ name="fk_session_turns_initial_delivery",
+ ),
+ ForeignKeyConstraint(
+ ["control_successor_delivery_id"],
+ ["message_deliveries.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ name="fk_session_turns_control_successor_delivery",
+ ),
+ ForeignKeyConstraint(
+ ["control_successor_turn_id"],
+ ["session_turns.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ name="fk_session_turns_control_successor_turn",
+ ),
+ CheckConstraint(
+ "state in ('waiting', 'starting', 'active', 'terminal')",
+ name="ck_session_turns_state",
+ ),
+ CheckConstraint(
+ "terminal_outcome is null or terminal_outcome in "
+ "('completed', 'failed', 'canceled', 'not_written')",
+ name="ck_session_turns_terminal_outcome",
+ ),
+ CheckConstraint(
+ "start_receipt_outcome is null or start_receipt_outcome in "
+ "('accepted', 'not_written', 'unknown')",
+ name="ck_session_turns_start_receipt_outcome",
+ ),
+ CheckConstraint(
+ "(state = 'waiting' and start_attempt_id is null and dispatch_text is null "
+ "and dispatch_sha256 is null and start_receipt_outcome is null) "
+ "or (state = 'starting' and start_attempt_id is not null "
+ "and dispatch_text is not null and dispatch_sha256 is not null "
+ "and (start_receipt_outcome is null or start_receipt_outcome = 'unknown')) "
+ "or (state = 'active' and start_attempt_id is not null "
+ "and dispatch_text is not null and dispatch_sha256 is not null "
+ "and start_receipt_outcome = 'accepted') "
+ "or (state = 'terminal' and (((terminal_outcome <> 'not_written' "
+ "and start_attempt_id is not null and dispatch_text is not null "
+ "and dispatch_sha256 is not null and start_receipt_outcome = 'accepted') "
+ "or (terminal_outcome = 'failed' and start_attempt_id is not null "
+ "and dispatch_text is not null and dispatch_sha256 is not null "
+ "and start_receipt_outcome = 'unknown')) "
+ "or (terminal_outcome = 'not_written' and start_attempt_id is not null "
+ "and dispatch_text is not null and dispatch_sha256 is not null "
+ "and start_receipt_outcome = 'not_written') "
+ "or (terminal_outcome = 'not_written' and start_attempt_id is null "
+ "and dispatch_text is null and dispatch_sha256 is null)))",
+ name="ck_session_turns_start_shape",
+ ),
+ CheckConstraint(
+ "control_state is null or control_state in "
+ "('pending', 'interrupting', 'waiting_terminal', 'reconciling', 'refused', 'settled')",
+ name="ck_session_turns_control_state",
+ ),
+ CheckConstraint(
+ "control_mode is null or control_mode in ('stop_only', 'replace')",
+ name="ck_session_turns_control_mode",
+ ),
+ CheckConstraint(
+ "(state = 'terminal' and terminal_outcome is not null and terminal_at is not null) "
+ "or (state <> 'terminal' and terminal_outcome is null and terminal_at is null)",
+ name="ck_session_turns_terminal_shape",
+ ),
+ CheckConstraint(
+ "(control_mode = 'replace' and control_successor_delivery_id is not null "
+ "and control_successor_turn_id is not null) "
+ "or (control_mode = 'stop_only' and control_successor_delivery_id is null "
+ "and control_successor_turn_id is null) "
+ "or (control_mode is null and control_successor_delivery_id is null "
+ "and control_successor_turn_id is null)",
+ name="ck_session_turns_control_shape",
+ ),
+ Index("ix_session_turns_session_created", "session_id", "created_at", "id"),
+ Index(
+ "uq_session_turns_live_session",
+ "session_id",
+ unique=True,
+ sqlite_where=text("state in ('starting', 'active')"),
+ ),
+ Index(
+ "uq_session_turns_message_written_attempt",
+ "initial_delivery_id",
+ unique=True,
+ sqlite_where=text("state <> 'terminal' or start_receipt_outcome = 'accepted'"),
+ ),
+ Index(
+ "uq_session_turns_waiting_successor",
+ "session_id",
+ unique=True,
+ sqlite_where=text("state = 'waiting'"),
+ ),
+ Index(
+ "uq_session_turns_control_attempt",
+ "control_attempt_id",
+ unique=True,
+ sqlite_where=text("control_attempt_id is not null"),
+ ),
+ Index(
+ "uq_session_turns_start_attempt",
+ "start_attempt_id",
+ unique=True,
+ sqlite_where=text("start_attempt_id is not null"),
+ ),
+)
+
+# One durable operational owner per submitted content-bearing input. Before
+# positive native acceptance the complete immutable Message candidate lives only
+# here. Acceptance moves one Delivery snapshot, or one ordered merged batch,
+# into ``messages`` and links every participating Delivery to that record.
+message_deliveries = Table(
+ "message_deliveries",
+ metadata,
+ Column("id", String, primary_key=True),
+ Column(
+ "session_id",
+ String,
+ ForeignKey(
+ "agent_sessions.id",
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ ),
+ nullable=False,
+ ),
+ Column("message_id", String, nullable=True),
+ Column("priority", String, nullable=False),
+ Column("state", String, nullable=False),
+ Column("snapshot_json", Text, nullable=True),
+ Column("snapshot_sha256", String, nullable=False),
+ # The exact backend-facing prompt is independent of Message display content
+ # and remains immutable after materialization for audit/recovery.
+ Column("dispatch_text", Text, nullable=True),
+ Column("dispatch_sha256", String, nullable=False),
+ Column("dedupe_key", Text, nullable=True),
+ Column("turn_id", String, nullable=True),
+ Column("turn_role", String, nullable=True),
+ Column("turn_position", Integer, nullable=True),
+ Column("current_attempt_id", String, nullable=True),
+ Column("current_attempt_kind", String, nullable=True),
+ Column("current_target_turn_id", String, nullable=True),
+ Column("current_expected_native_turn_id", Text, nullable=True),
+ Column("current_receipt_outcome", String, nullable=True),
+ Column("current_receipt_json", Text, nullable=False, server_default="{}"),
+ Column("current_attempt_opened_at", String, nullable=True),
+ Column("delivery_history_json", Text, nullable=False, server_default='{"version":1,"events":[]}'),
+ Column("version", Integer, nullable=False, server_default="1"),
+ Column("submitted_at", String, nullable=False),
+ Column("updated_at", String, nullable=False),
+ Column("materialized_at", String, nullable=True),
+ Column("retired_at", String, nullable=True),
+ ForeignKeyConstraint(
+ ["message_id"],
+ ["messages.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ name="fk_message_deliveries_message",
+ ),
+ ForeignKeyConstraint(
+ ["turn_id"],
+ ["session_turns.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ name="fk_message_deliveries_turn",
+ ),
+ ForeignKeyConstraint(
+ ["current_target_turn_id"],
+ ["session_turns.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ name="fk_message_deliveries_current_target_turn",
+ ),
+ UniqueConstraint("dedupe_key", name="uq_message_deliveries_dedupe"),
+ CheckConstraint("priority in ('p0', 'p1', 'p3')", name="ck_message_deliveries_priority"),
+ CheckConstraint(
+ f"state in ({_sql_string_set(DELIVERY_STATES)})",
+ name="ck_message_deliveries_state",
+ ),
+ CheckConstraint(
+ "current_attempt_kind is null or current_attempt_kind = 'steer'",
+ name="ck_message_deliveries_current_attempt_kind",
+ ),
+ CheckConstraint(
+ "json_valid(delivery_history_json) = 1 "
+ "and json_extract(delivery_history_json, '$.version') = 1 "
+ "and json_type(delivery_history_json, '$.events') = 'array'",
+ name="ck_message_deliveries_history_json",
+ ),
+ CheckConstraint(
+ "(state in ('steering', 'reconciling_steer') "
+ "and current_attempt_id is not null and current_attempt_kind = 'steer' "
+ "and current_target_turn_id is not null "
+ "and current_expected_native_turn_id is not null) "
+ "or (state = 'pending_steer' and current_attempt_id is not null "
+ "and current_attempt_kind = 'steer' and current_target_turn_id is not null "
+ "and current_expected_native_turn_id is null) "
+ "or (state not in ('steering', 'reconciling_steer', 'pending_steer') "
+ "and current_attempt_id is null "
+ "and current_attempt_kind is null and current_target_turn_id is null "
+ "and current_expected_native_turn_id is null)",
+ name="ck_message_deliveries_current_attempt_shape",
+ ),
+ CheckConstraint(
+ "(state = 'reconciling_steer' "
+ "and current_receipt_outcome = 'unknown') "
+ "or (state <> 'reconciling_steer' "
+ "and current_receipt_outcome is null)",
+ name="ck_message_deliveries_current_receipt",
+ ),
+ CheckConstraint(
+ "(state = 'accepted' and message_id is not null and turn_id is not null "
+ "and turn_role in ('initial', 'steer') and turn_position is not null "
+ "and materialized_at is not null and snapshot_json is null and dispatch_text is null "
+ "and current_attempt_id is null and current_attempt_kind is null "
+ "and current_target_turn_id is null and current_expected_native_turn_id is null "
+ "and current_receipt_outcome is null and current_attempt_opened_at is null) "
+ "or (state <> 'accepted' and message_id is null and materialized_at is null)",
+ name="ck_message_deliveries_materialization",
+ ),
+ CheckConstraint(
+ "(state in ('claimed', 'interrupt_waiting') and turn_id is not null "
+ "and turn_role = 'initial' and turn_position is not null) "
+ "or (state = 'accepted' and turn_id is not null and turn_role is not null "
+ "and turn_position is not null) "
+ "or (state not in ('claimed', 'interrupt_waiting', 'accepted') "
+ "and turn_id is null and turn_role is null and turn_position is null)",
+ name="ck_message_deliveries_turn_membership",
+ ),
+ Index(
+ "ix_message_deliveries_session_order",
+ "session_id",
+ "submitted_at",
+ "id",
+ sqlite_where=text(
+ "state in ('reserved', 'queued', 'claimed', 'pending_steer', 'steering', "
+ "'reconciling_steer')"
+ ),
+ ),
+ Index("ix_message_deliveries_session_state", "session_id", "state", "submitted_at", "id"),
+ Index("ix_message_deliveries_turn", "turn_id", "turn_position"),
+ Index(
+ "uq_message_deliveries_turn_position",
+ "turn_id",
+ "turn_position",
+ unique=True,
+ sqlite_where=text("turn_id is not null"),
+ ),
+ Index("ix_message_deliveries_current_target_turn", "current_target_turn_id"),
+ Index("ix_message_deliveries_current_attempt", "current_attempt_id"),
+)
+
+agent_runs.append_constraint(
+ ForeignKeyConstraint(
+ ["delivery_id"],
+ ["message_deliveries.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ name="fk_agent_runs_delivery",
+ )
+)
+
+# The Show event can exist before its input is accepted, so its durable anchor is
+# the Delivery. The Message link is filled only on acceptance for history reads.
+show_session_events.append_constraint(
+ ForeignKeyConstraint(
+ ["delivery_id"],
+ ["message_deliveries.id"],
+ ondelete="NO ACTION",
+ deferrable=True,
+ initially="DEFERRED",
+ name="fk_show_session_events_delivery",
+ )
)
# Opaque-token proxy for chat media. The workbench browser can't load
diff --git a/storage/session_reclaim.py b/storage/session_reclaim.py
index 504aa9d8b..fb3a28cb9 100644
--- a/storage/session_reclaim.py
+++ b/storage/session_reclaim.py
@@ -123,6 +123,29 @@ def current_reclaim_ledger() -> list[dict[str, Any]] | None:
return _teardown_ledger.get()
+def retire_session_delivery_owners(
+ conn: Connection,
+ session_id: str,
+) -> dict[str, Any]:
+ """Retire proven-unwritten Deliveries and cancel their Runs atomically."""
+
+ from storage import message_deliveries as delivery_store
+ from storage.background import (
+ cancel_agent_runs_for_retired_deliveries_in_connection,
+ )
+
+ retired = delivery_store.retire_for_archive(conn, session_id)
+ canceled_run_ids = cancel_agent_runs_for_retired_deliveries_in_connection(
+ conn,
+ session_id=session_id,
+ delivery_ids=list(retired.get("delivery_ids") or []),
+ )
+ return {
+ **retired,
+ "canceled_run_ids": canceled_run_ids,
+ }
+
+
@contextmanager
def reclaim_ledger_transaction() -> Iterator[None]:
"""Scope ledger entries to a transaction; discard them if it does not commit.
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index c518370ed..35e6cffa6 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -8,7 +8,7 @@ from datetime import datetime, timezone, timedelta
from pathlib import Path
from typing import Any, Mapping
-from sqlalchemy import Connection, and_, case, func, or_, select
+from sqlalchemy import Connection, and_, case, func, or_, select, update
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.exc import IntegrityError
@@ -30,7 +30,10 @@ from storage.agent_session_rows import (
)
from storage.models import (
agents,
+ agent_runs,
agent_sessions,
+ message_deliveries,
+ messages,
metadata,
run_definitions,
runtime_records,
@@ -45,8 +48,10 @@ from storage.session_reclaim import (
reclaim_bound_definitions,
reclaim_ledger_transaction,
reconcile_explicit_overrides,
+ retire_session_delivery_owners,
)
from storage.settings_service import make_scope_id, upsert_scope
+from storage import message_deliveries as delivery_store
SESSIONS_LAST_ACTIVITY_KEY = "sessions_last_activity"
SESSION_ID_ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz"
@@ -2151,14 +2156,11 @@ def _delete_agent_session_rows(
reclaim_mode: ReclaimMode,
reclaim_reason: str | None,
) -> int:
- """Hard-delete session rows, reclaiming what was bound to them first.
+ """Remove Session rows from active routing, preserving retained history.
- Every hard delete of a session row runs through here so no teardown path can
- leave a ``run_definitions.session_id`` pointing at a row that no longer exists
- — the root cause of a pinned task that fires and fails forever. The reclaim
- must run BEFORE the delete: it is the last moment both rows are visible, and
- the settings snapshot it takes is what lets a later rebind preserve the
- session's model / agent instead of silently resetting to scope defaults.
+ Empty rows are deleted. A row with Message or Delivery history is archived
+ and re-anchored instead, so ``/new`` frees the original anchor without
+ orphaning immutable communication or execution audit.
``id_query`` is re-asserted BY THE DELETE, so a row that stopped matching after
the id read is kept, and the returned count names only the rows actually removed.
@@ -2193,20 +2195,87 @@ def _delete_agent_session_rows(
# the user asked to clear, ``pause`` keeps them re-enablable, and the kept row is
# a superseded one the thread has already moved off.
reclaim_bound_definitions(conn, session_id, mode=reclaim_mode, reason=reclaim_reason)
- removed = bool(
+ claimed = bool(
conn.execute(
- agent_sessions.delete()
+ agent_sessions.update()
.where(agent_sessions.c.id == session_id)
.where(agent_sessions.c.id.in_(id_query))
+ .values(updated_at=agent_sessions.c.updated_at)
).rowcount
)
- if not removed:
+ if not claimed:
logger.warning(
"Skipped hard-deleting session %s: it stopped matching the teardown "
"query concurrently (superseded, re-anchored or already gone)",
session_id,
)
continue
+ has_retained_history = bool(
+ conn.execute(
+ select(messages.c.id)
+ .where(messages.c.session_id == session_id)
+ .limit(1)
+ ).first()
+ or conn.execute(
+ select(message_deliveries.c.id)
+ .where(message_deliveries.c.session_id == session_id)
+ .limit(1)
+ ).first()
+ )
+ if has_retained_history:
+ row = conn.execute(
+ select(agent_sessions.c.session_anchor).where(
+ agent_sessions.c.id == session_id
+ )
+ ).first()
+ current_anchor = str((row or ("",))[0] or "")
+ superseded_anchor = (
+ current_anchor
+ if SUPERSEDED_ANCHOR_INFIX in current_anchor
+ else (
+ f"{current_anchor}{SUPERSEDED_ANCHOR_INFIX}{session_id}"
+ if current_anchor
+ else f"superseded:{session_id}"
+ )
+ )
+ now = _utc_now_iso()
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.session_id == session_id)
+ .where(agent_runs.c.status.in_(("pending", "queued", "processing", "running")))
+ .values(cancel_requested=1, cancel_requested_at=now, updated_at=now)
+ )
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.session_id == session_id)
+ .where(agent_runs.c.status.in_(("pending", "queued")))
+ .values(status="canceled", completed_at=now, updated_at=now)
+ )
+ retire_session_delivery_owners(conn, session_id)
+ delivery_store.set_draft(conn, session_id, None)
+ retained = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .values(
+ status="archived",
+ agent_status="idle",
+ session_anchor=superseded_anchor,
+ updated_at=now,
+ )
+ )
+ if retained.rowcount != 1:
+ raise RuntimeError(
+ f"claimed Session {session_id} disappeared during archival"
+ )
+ deleted += 1
+ continue
+ removed = bool(
+ conn.execute(
+ agent_sessions.delete().where(agent_sessions.c.id == session_id)
+ ).rowcount
+ )
+ if not removed:
+ raise RuntimeError(f"claimed Session {session_id} disappeared during teardown")
deleted += 1
return deleted
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 10ae9c7d6..234de5ddb 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -29,17 +29,20 @@ from storage.agent_session_rows import (
WORKSPACE_NOTICE_SESSION_ID,
create_agent_session_row,
new_session_id,
+ reserve_write_lock,
)
from storage.db import escape_sql_like
from storage.session_reclaim import (
RECLAIM_DELETE,
reclaim_bound_definitions,
reconcile_explicit_overrides,
+ retire_session_delivery_owners,
)
from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one
from storage.models import (
agent_runs,
agent_sessions,
+ message_deliveries,
messages,
run_definitions,
scope_settings,
@@ -482,6 +485,7 @@ def update_session(
"""
if str(session_id) == WORKSPACE_NOTICE_SESSION_ID:
raise ReservedSessionError(str(session_id))
+ reserve_write_lock(conn)
existing = conn.execute(
select(
agent_sessions.c.id,
@@ -864,18 +868,12 @@ def count_bound_resources(conn: Connection, session_id: str) -> dict[str, int]:
).scalar()
or 0
)
- # Send-while-busy queued prompts are user-entered text that archive discards;
- # surface them so the confirm dialog doesn't say "nothing linked" while
- # silently dropping them. (PENDING reservations are transient dispatch state,
- # not user-visible, so they're not counted here.)
- from storage.messages_service import QUEUED_TYPE
-
queued = (
conn.execute(
select(func.count())
- .select_from(messages)
- .where(messages.c.session_id == session_id)
- .where(messages.c.type == QUEUED_TYPE)
+ .select_from(message_deliveries)
+ .where(message_deliveries.c.session_id == session_id)
+ .where(message_deliveries.c.state == "queued")
).scalar()
or 0
)
@@ -1177,11 +1175,10 @@ def archive_session(conn: Connection, session_id: str) -> dict[str, Any]:
.values(status="canceled", completed_at=now)
)
- # 3b) Reclaim all unsent user input so the terminal session retains none:
- # queued prompts (flushed on completion / send-now), ``pending`` rows a
- # concurrent send reserved just before this committed (``promote_pending``
- # then no-ops on that in-flight send), and the saved composer draft.
- from storage.messages_service import clear_draft, clear_pending, clear_queued
+ # 3b) Retire only submissions proven not written. Native start/steer/control
+ # ambiguity remains durable and can still materialize positive evidence
+ # after archive; the archived admission guard prevents any new work.
+ from storage import message_deliveries as delivery_store
from storage.vault_service import (
ACTIVE_GRANT_STATES,
agent_release_scopes_after_rows,
@@ -1190,9 +1187,8 @@ def archive_session(conn: Connection, session_id: str) -> dict[str, Any]:
vault_grants,
)
- clear_queued(conn, session_id)
- clear_pending(conn, session_id)
- clear_draft(conn, session_id)
+ retire_session_delivery_owners(conn, session_id)
+ delivery_store.set_draft(conn, session_id, None)
revoked_vault_grant_rows = [
dict(row)
for row in conn.execute(
@@ -1251,21 +1247,3 @@ def set_agent_status(conn: Connection, session_id: str, status: str) -> bool:
update(agent_sessions).where(agent_sessions.c.id == session_id).values(agent_status=status)
)
return True
-
-
-def reset_running_agent_status(conn: Connection) -> int:
- """Reset every ``running`` session to ``idle`` (startup crash recovery).
-
- No turn survives a controller restart, so a ``running`` left in the table
- is stale. Returns the number of rows reset. The browser reconciles the reset
- by refetching sessions when its inbox-event stream (re)connects, NOT from a
- broadcast — this runs in ``Controller.__init__`` before any event subscriber
- exists, so a broadcast here would be dropped.
- """
-
- result = conn.execute(
- update(agent_sessions)
- .where(agent_sessions.c.agent_status == "running")
- .values(agent_status="idle")
- )
- return result.rowcount or 0
diff --git a/tests/scenario_harness/message_delivery.py b/tests/scenario_harness/message_delivery.py
index 659d01dd9..a42e98ad0 100644
--- a/tests/scenario_harness/message_delivery.py
+++ b/tests/scenario_harness/message_delivery.py
@@ -44,7 +44,7 @@ class MessageDeliveryController(ScenarioControllerBase):
),
)
self.session_turns = SimpleNamespace(
- on_terminal_result=lambda context, is_error: setattr(
+ on_terminal_result=lambda context, is_error, **_kwargs: setattr(
self,
"turn_terminal_calls",
self.turn_terminal_calls + 1,
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index 335c629ca..4ae9a1d8f 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -4,6 +4,7 @@ capability:
name: full-duplex message delivery
canonical_tests:
- tests/scenarios/message_delivery/test_message_delivery_scenarios.py
+ - tests/test_session_delivery_fsm.py
shared_harness:
- tests/scenario_harness/core.py
- tests/scenario_harness/message_delivery.py
@@ -61,8 +62,72 @@ scenarios:
kind: concurrency
layer: contract
test: tests/test_scheduled_tasks.py::test_directed_run_and_callback_remain_distinct_while_target_busy
+ - id: MESSAGE-DELIVERY-009
+ name: P1 terminal race produces one accepted attachment or one P3 fallback owner
+ status: covered
+ kind: concurrency
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_terminal_between_p1_observation_and_claim_starts_same_submission_once
+ - id: MESSAGE-DELIVERY-010
+ name: Concurrent empty P1 requests can claim only the observed FIFO head
+ status: covered
+ kind: concurrency
+ 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
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_lost_accepted_receipt_restarts_unknown_without_resteer
+ - id: MESSAGE-DELIVERY-012
+ name: Definitive P1 refusal and idle drain start one fallback Turn
+ status: covered
+ kind: concurrency
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_definitive_refusal_racing_idle_drain_starts_same_delivery_once
+ - id: MESSAGE-DELIVERY-013
+ name: P0 never interrupts before its successor is durable
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_p0_successor_persistence_failure_never_calls_stop
+ - id: MESSAGE-DELIVERY-014
+ name: P0 terminal and restart race claims its successor once after terminal proof
+ status: covered
+ kind: concurrency
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_p0_terminal_restart_claims_successor_once_after_old_terminal
+ - id: MESSAGE-DELIVERY-015
+ name: Concurrent idle P3 admissions choose one Turn owner and retain one FIFO loser
+ status: covered
+ kind: concurrency
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_two_idle_p3_admissions_leave_one_fifo_loser
+ - id: MESSAGE-DELIVERY-016
+ name: A late T1 terminal event cannot clear or overwrite active T2
+ status: covered
+ kind: concurrency
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_late_t1_terminal_cannot_clear_active_t2
+ - id: MESSAGE-DELIVERY-017
+ name: Ambiguous native start replays once, then fails open without blocking FIFO
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_start_write_ambiguity_replays_once_after_restart
+ - id: MESSAGE-DELIVERY-101
+ name: Unresolved fallback-capable delivery fences only later FIFO submissions
+ status: covered
+ kind: concurrency
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_unresolved_p1_fence_blocks_later_but_not_older_fifo
+ - id: MESSAGE-DELIVERY-102
+ name: Queue hold blocks autonomous backlog but not a new idle admission
+ status: covered
+ kind: lifecycle
+ layer: contract
+ test: tests/test_session_delivery_fsm.py::test_held_old_backlog_does_not_block_new_idle_p3
next_priority:
- - MESSAGE-DELIVERY-101
- - MESSAGE-DELIVERY-102
- MESSAGE-DELIVERY-201
- MESSAGE-DELIVERY-202
diff --git a/tests/test_agent_activity_service.py b/tests/test_agent_activity_service.py
index 518a8e971..314bcc27d 100644
--- a/tests/test_agent_activity_service.py
+++ b/tests/test_agent_activity_service.py
@@ -17,6 +17,8 @@ from __future__ import annotations
import json
import sys
+import time
+from datetime import datetime, timezone
from pathlib import Path
import pytest
@@ -24,7 +26,7 @@ from sqlalchemy import select # noqa: F401 (kept parallel to sibling tests)
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from storage import agent_activity_service, messages_service
+from storage import agent_activity_service, message_deliveries, messages_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_events, agent_sessions, messages
@@ -79,18 +81,28 @@ def _msg(conn, scope_id, session_id, *, mid, mtype, author, created_at, text="",
)
-def _evt(conn, scope_id, session_id, *, eid, created_at, text):
+def _evt(
+ conn,
+ scope_id,
+ session_id,
+ *,
+ eid,
+ created_at,
+ text,
+ event_type="tool_call",
+ metadata=None,
+):
conn.execute(
agent_events.insert().values(
id=eid,
scope_id=scope_id,
session_id=session_id,
platform="avibe",
- event_type="tool_call",
+ event_type=event_type,
visibility="trace",
content_text=text,
content_json=json.dumps({"kind": "tool_call", "text": text}),
- metadata_json="{}",
+ metadata_json=json.dumps(metadata or {}),
source="agent",
created_at=created_at,
updated_at=created_at,
@@ -98,6 +110,24 @@ def _evt(conn, scope_id, session_id, *, eid, created_at, text):
)
+def _accept_start(conn, turn_id: str) -> list[dict]:
+ turn = message_deliveries.get_turn(conn, turn_id)
+ assert turn is not None
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ runtime_key=f"runtime:{turn_id}",
+ runtime_turn_id=f"runtime-turn:{turn_id}",
+ native_turn_id=f"native:{turn_id}",
+ ) is not None
+ return message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+
+
def test_done_failed_interrupted_and_trailing_groups(isolated_state):
engine = create_sqlite_engine()
sid = "ses_act"
@@ -300,6 +330,67 @@ def test_same_second_pre_window_event_dropped_by_id(isolated_state):
assert summary["groups"] == []
+def test_migrated_terminal_uses_original_message_clock_for_same_second_order(
+ isolated_state,
+):
+ engine = create_sqlite_engine()
+ sid = "ses_legacy_terminal_order"
+ base = int(
+ datetime(2026, 6, 1, 10, 0, 0, tzinfo=timezone.utc).timestamp()
+ * 1_000_000
+ )
+ timestamp = "2026-06-01T10:00:00Z"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(
+ conn,
+ scope,
+ sid,
+ mid=_clock_id("msg", base + 1_000),
+ mtype="user",
+ author="user",
+ created_at=timestamp,
+ text="q1",
+ source="user",
+ )
+ _evt(
+ conn,
+ scope,
+ sid,
+ eid=_clock_id("evt", base + 2_000),
+ created_at=timestamp,
+ text="tool",
+ )
+ _evt(
+ conn,
+ scope,
+ sid,
+ eid="evt_legacy_without_clock",
+ created_at=timestamp,
+ text="",
+ event_type="silent_terminal",
+ metadata={"legacy_message_id": _clock_id("msg", base + 3_000)},
+ )
+ _msg(
+ conn,
+ scope,
+ sid,
+ mid=_clock_id("msg", base + 4_000),
+ mtype="user",
+ author="user",
+ created_at=timestamp,
+ text="q2",
+ source="user",
+ )
+
+ with engine.connect() as conn:
+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)[
+ "groups"
+ ]
+ assert groups[0]["status"] == "done"
+ assert groups[0]["anchor_message_id"] == _clock_id("msg", base + 1_000)
+
+
def test_duration_measured_from_turn_opener(isolated_state):
"""The chip duration spans the turn opener → terminal (what the history endpoint
reports), not first-activity → terminal — so live and reloaded chips agree."""
@@ -511,31 +602,573 @@ def test_get_turn_group_unknown_id_returns_none(isolated_state):
def test_silent_completion_marks_turn_done(isolated_state):
- """The reported bug: a watch-triggered turn runs tool steps then finishes with a
- ``<silent>`` reply (stripped, nothing delivered → an invisible ``silent`` marker).
- It MUST be ``done``, not ``interrupted``, and — since the marker is invisible in
- the transcript — anchored to the (visible) trigger AFTER it, not the marker."""
+ """A reply-less terminal Turn closes activity without a pseudo Message."""
engine = create_sqlite_engine()
sid = "ses_silent"
with engine.begin() as conn:
scope = _seed_session(conn, session_id=sid)
- _msg(conn, scope, sid, mid="m_h1", mtype="harness", author="harness", created_at="2026-06-01T10:00:00.000000+00:00", text="watch fired", source="harness")
+ turn_id = "trn_silent"
+ attempt_id = "atm_silent"
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="m_h1",
+ session_id=sid,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope,
+ session_id=sid,
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="watch fired",
+ ),
+ dispatch_text="watch fired",
+ now="2026-06-01T10:00:00.000000+00:00",
+ )
+ message_deliveries.insert_turn(
+ conn,
+ turn_id=turn_id,
+ session_id=sid,
+ initial_delivery_id=delivery["id"],
+ state="starting",
+ backend="codex",
+ start_attempt_id=attempt_id,
+ dispatch_text="watch fired",
+ now="2026-06-01T10:00:00.000000+00:00",
+ )
+ assert message_deliveries.open_start_attempt(
+ conn,
+ delivery["id"],
+ expected_version=int(delivery["version"]),
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ ) is not None
+ assert _accept_start(conn, turn_id)
_evt(conn, scope, sid, eid="e_s1", created_at="2026-06-01T10:00:01Z", text="🔧 `Bash` `{\"command\":\"a\"}`")
_evt(conn, scope, sid, eid="e_s2", created_at="2026-06-01T10:00:02Z", text="🔧 `Read` `{\"file_path\":\"b\"}`")
- # The invisible marker (type='silent', empty text) written at the chokepoint.
- _msg(conn, scope, sid, mid="m_sil1", mtype="silent", author="agent", created_at="2026-06-01T10:00:03.000000+00:00", text="")
+ message_deliveries.terminalize_turn(
+ conn,
+ turn_id,
+ outcome="completed",
+ settled_by="terminal_result",
+ evidence_kind="test_replyless_completion",
+ )
with engine.connect() as conn:
groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]
assert len(groups) == 1
g = groups[0]
assert g["status"] == "done"
- assert g["anchor_message_id"] == "m_h1" # visible trigger, not the invisible marker
+ assert g["anchor_message_id"] == "m_h1"
assert g["anchor_position"] == "after"
assert g["open"] is False
assert g["steps"] == 2
+def test_replyless_terminal_keeps_subsecond_order_after_last_activity(isolated_state):
+ """A Turn terminal is emitted after its final tool event, even in one second."""
+
+ engine = create_sqlite_engine()
+ sid = "ses_precise_terminal"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ turn_id = "trn_precise_terminal"
+ attempt_id = "atm_precise_terminal"
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="msg_precise_terminal",
+ session_id=sid,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope,
+ session_id=sid,
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="watch fired",
+ ),
+ dispatch_text="watch fired",
+ )
+ message_deliveries.insert_turn(
+ conn,
+ turn_id=turn_id,
+ session_id=sid,
+ initial_delivery_id=delivery["id"],
+ state="starting",
+ backend="codex",
+ start_attempt_id=attempt_id,
+ dispatch_text="watch fired",
+ )
+ assert message_deliveries.open_start_attempt(
+ conn,
+ delivery["id"],
+ expected_version=int(delivery["version"]),
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ ) is not None
+ assert _accept_start(conn, turn_id)
+ emitted_micros = int(time.time() * 1_000_000)
+ emitted_at = datetime.fromtimestamp(
+ emitted_micros / 1_000_000,
+ timezone.utc,
+ ).strftime("%Y-%m-%dT%H:%M:%SZ")
+ _evt(
+ conn,
+ scope,
+ sid,
+ eid=f"evt_{emitted_micros:015x}deadbeef",
+ created_at=emitted_at,
+ text="final tool call",
+ )
+ terminal = message_deliveries.terminalize_turn(
+ conn,
+ turn_id,
+ outcome="completed",
+ settled_by="terminal_result",
+ evidence_kind="test_replyless_completion",
+ )
+
+ terminal_at = str(terminal["turn"]["terminal_at"])
+ assert "." in terminal_at and terminal_at.endswith("Z")
+ with engine.connect() as conn:
+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]
+ assert len(groups) == 1
+ assert groups[0]["status"] == "done"
+ assert groups[0]["steps"] == 1
+
+
+def test_not_written_successor_does_not_close_active_turn_activity(isolated_state):
+ engine = create_sqlite_engine()
+ sid = "ses_not_written_activity"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ active_delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="msg_active_initial",
+ session_id=sid,
+ priority="p1",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope,
+ session_id=sid,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="active input",
+ ),
+ dispatch_text="active input",
+ now="2026-06-01T10:00:00Z",
+ )
+ message_deliveries.insert_turn(
+ conn,
+ turn_id="trn_active",
+ session_id=sid,
+ initial_delivery_id=active_delivery["id"],
+ state="starting",
+ backend="codex",
+ start_attempt_id="atm_active_initial",
+ dispatch_text="active input",
+ now="2026-06-01T10:00:00Z",
+ )
+ assert message_deliveries.open_start_attempt(
+ conn,
+ active_delivery["id"],
+ expected_version=int(active_delivery["version"]),
+ turn_id="trn_active",
+ attempt_id="atm_active_initial",
+ ) is not None
+ assert _accept_start(conn, "trn_active")
+ _evt(
+ conn,
+ scope,
+ sid,
+ eid="evt_active_tool",
+ created_at="2026-06-01T10:00:01Z",
+ text="active tool",
+ )
+ successor = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="msg_refused_successor",
+ session_id=sid,
+ priority="p0",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope,
+ session_id=sid,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="replacement",
+ ),
+ dispatch_text="replacement",
+ now="2026-06-01T10:00:02Z",
+ )
+ message_deliveries.insert_turn(
+ conn,
+ turn_id="trn_refused_successor",
+ session_id=sid,
+ initial_delivery_id="msg_refused_successor",
+ state="waiting",
+ backend="codex",
+ now="2026-06-01T10:00:02Z",
+ )
+ assert message_deliveries.cas_delivery(
+ conn,
+ successor["id"],
+ expected_version=int(successor["version"]),
+ expected_states=("reserved",),
+ values={
+ "state": "interrupt_waiting",
+ "turn_id": "trn_refused_successor",
+ "turn_role": "initial",
+ "turn_position": 0,
+ },
+ ) is not None
+ message_deliveries.terminalize_turn(
+ conn,
+ "trn_refused_successor",
+ outcome="not_written",
+ settled_by="interrupt_refused",
+ evidence_kind="definitive_stop_receipt",
+ )
+
+ with engine.connect() as conn:
+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)[
+ "groups"
+ ]
+
+ assert len(groups) == 1
+ assert groups[0]["status"] == "interrupted"
+ assert groups[0]["open"] is True
+ assert groups[0]["steps"] == 1
+
+
+def test_queued_initial_message_opens_at_its_accepted_turn(
+ isolated_state,
+ monkeypatch,
+):
+ """Submission order stays in the transcript, but execution grouping starts when
+ the queued Delivery becomes the initial owner of its accepted Turn."""
+
+ engine = create_sqlite_engine()
+ sid = "ses_queued_boundary"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(
+ conn,
+ scope,
+ sid,
+ mid="msg_first_input",
+ mtype="user",
+ author="user",
+ created_at="2026-06-01T10:00:00Z",
+ text="first",
+ source="user",
+ )
+ _evt(
+ conn,
+ scope,
+ sid,
+ eid="event_first_tool",
+ created_at="2026-06-01T10:00:10Z",
+ text="first tool",
+ )
+ waiting_delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="msg_queued_input",
+ session_id=sid,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope,
+ session_id=sid,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="queued while first turn runs",
+ ),
+ dispatch_text="queued while first turn runs",
+ now="2026-06-01T10:00:15Z",
+ )
+ _msg(
+ conn,
+ scope,
+ sid,
+ mid="msg_first_result",
+ mtype="result",
+ author="agent",
+ created_at="2026-06-01T10:00:20Z",
+ text="first done",
+ )
+ message_deliveries.insert_turn(
+ conn,
+ turn_id="trn_queued_input",
+ session_id=sid,
+ initial_delivery_id="msg_queued_input",
+ state="waiting",
+ backend="codex",
+ now="2026-06-01T10:00:15Z",
+ )
+ waiting_delivery = message_deliveries.cas_delivery(
+ conn,
+ waiting_delivery["id"],
+ expected_version=int(waiting_delivery["version"]),
+ expected_states=("reserved",),
+ values={
+ "state": "interrupt_waiting",
+ "turn_id": "trn_queued_input",
+ "turn_role": "initial",
+ "turn_position": 0,
+ },
+ )
+ assert waiting_delivery is not None
+ monkeypatch.setattr(
+ message_deliveries,
+ "turn_now_iso",
+ lambda: "2026-06-01T10:00:21.000001Z",
+ )
+ waiting_turn = message_deliveries.get_turn(conn, "trn_queued_input")
+ waiting_delivery = message_deliveries.get_delivery(conn, "msg_queued_input")
+ assert waiting_turn is not None
+ assert waiting_delivery is not None
+ assert message_deliveries.activate_waiting_successor(
+ conn,
+ turn=waiting_turn,
+ delivery=waiting_delivery,
+ ) is not None
+ assert _accept_start(conn, "trn_queued_input")
+ _evt(
+ conn,
+ scope,
+ sid,
+ eid="event_second_tool",
+ created_at="2026-06-01T10:00:22Z",
+ text="second tool",
+ )
+ _msg(
+ conn,
+ scope,
+ sid,
+ mid="msg_second_result",
+ mtype="result",
+ author="agent",
+ created_at="2026-06-01T10:00:23Z",
+ text="second done",
+ )
+
+ with engine.connect() as conn:
+ transcript = messages_service.list_session_messages(
+ conn,
+ session_id=sid,
+ types=("user", "result"),
+ )["messages"]
+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)[
+ "groups"
+ ]
+
+ assert [row["id"] for row in transcript] == [
+ "msg_first_input",
+ "msg_queued_input",
+ "msg_first_result",
+ "msg_second_result",
+ ]
+ assert [group["status"] for group in groups] == ["done", "done"]
+ assert [group["anchor_message_id"] for group in groups] == [
+ "msg_first_result",
+ "msg_second_result",
+ ]
+
+
+def test_accepted_steer_participant_does_not_open_a_second_turn(isolated_state):
+ engine = create_sqlite_engine()
+ sid = "ses_steer_participant"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ initial_delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="msg_initial",
+ session_id=sid,
+ priority="p1",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope,
+ session_id=sid,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="initial",
+ ),
+ dispatch_text="initial",
+ now="2026-06-01T10:00:00Z",
+ )
+ message_deliveries.insert_turn(
+ conn,
+ turn_id="trn_shared",
+ session_id=sid,
+ initial_delivery_id=initial_delivery["id"],
+ state="starting",
+ backend="codex",
+ start_attempt_id="atm_initial",
+ dispatch_text="initial",
+ now="2026-06-01T10:00:00Z",
+ )
+ assert message_deliveries.open_start_attempt(
+ conn,
+ initial_delivery["id"],
+ expected_version=int(initial_delivery["version"]),
+ turn_id="trn_shared",
+ attempt_id="atm_initial",
+ ) is not None
+ assert _accept_start(conn, "trn_shared")
+ _evt(
+ conn,
+ scope,
+ sid,
+ eid="event_before_steer",
+ created_at="2026-06-01T10:00:01Z",
+ text="before steer",
+ )
+ message_deliveries.insert_delivery(
+ conn,
+ delivery_id="msg_steer",
+ session_id=sid,
+ priority="p1",
+ state="steering",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope,
+ session_id=sid,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="steer participant",
+ ),
+ dispatch_text="steer participant",
+ current_attempt_id="atm_steer",
+ current_attempt_kind="steer",
+ current_target_turn_id="trn_shared",
+ current_expected_native_turn_id="native-shared",
+ now="2026-06-01T10:00:02Z",
+ )
+ assert message_deliveries.materialize_acceptance(
+ conn,
+ delivery_id="msg_steer",
+ expected_attempt_id="atm_steer",
+ turn_id="trn_shared",
+ evidence={"kind": "test_steer_acceptance"},
+ ) is not None
+ _evt(
+ conn,
+ scope,
+ sid,
+ eid="event_after_steer",
+ created_at="2026-06-01T10:00:03Z",
+ text="after steer",
+ )
+ _msg(
+ conn,
+ scope,
+ sid,
+ mid="msg_result",
+ mtype="result",
+ author="agent",
+ created_at="2026-06-01T10:00:04Z",
+ text="done",
+ )
+
+ with engine.connect() as conn:
+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)[
+ "groups"
+ ]
+
+ assert len(groups) == 1
+ assert groups[0]["status"] == "done"
+ assert groups[0]["steps"] == 2
+ assert groups[0]["anchor_message_id"] == "msg_result"
+
+
+def test_merged_initial_deliveries_keep_one_turn_start(isolated_state, monkeypatch):
+ engine = create_sqlite_engine()
+ sid = "ses_merged_initial"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ deliveries = [
+ message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=sid,
+ priority="p3",
+ state="queued",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope,
+ session_id=sid,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text=text,
+ ),
+ dispatch_text=text,
+ now=created_at,
+ )
+ for delivery_id, text, created_at in (
+ ("msg_merged_initial", "first", "2026-06-01T10:00:00Z"),
+ ("msg_merged_second", "second", "2026-06-01T10:00:01Z"),
+ )
+ ]
+ monkeypatch.setattr(
+ message_deliveries,
+ "turn_now_iso",
+ lambda: "2026-06-01T10:00:02Z",
+ )
+ message_deliveries.claim_start_batch(
+ conn,
+ turn_id="trn_merged",
+ session_id=sid,
+ backend="codex",
+ deliveries=deliveries,
+ dispatch_text="first\nsecond",
+ attempt_id="atm_merged",
+ )
+ assert _accept_start(conn, "trn_merged")
+ _evt(
+ conn,
+ scope,
+ sid,
+ eid="event_merged_tool",
+ created_at="2026-06-01T10:00:03Z",
+ text="merged tool",
+ )
+ _msg(
+ conn,
+ scope,
+ sid,
+ mid="msg_merged_result",
+ mtype="result",
+ author="agent",
+ created_at="2026-06-01T10:00:04Z",
+ text="done",
+ )
+
+ with engine.connect() as conn:
+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)[
+ "groups"
+ ]
+
+ assert len(groups) == 1
+ assert groups[0]["status"] == "done"
+ assert groups[0]["steps"] == 1
+ assert groups[0]["anchor_message_id"] == "msg_merged_result"
+
+
def test_midturn_notify_does_not_split_or_close_a_turn(isolated_state):
"""A plain (non-backend-failure) ``notify`` is NOT terminal: agents emit mid-turn
notify rows that keep the turn going (e.g. Claude's model-refusal fallback). It must
diff --git a/tests/test_agent_service.py b/tests/test_agent_service.py
index e8878f259..eebe8d641 100644
--- a/tests/test_agent_service.py
+++ b/tests/test_agent_service.py
@@ -9,6 +9,11 @@ from unittest.mock import AsyncMock, Mock
import pytest
from core.message_output import terminal_turn_output
+from core.native_dispatch_phase import (
+ DISPATCH_PHASE_PREWRITE,
+ backend_dispatch_attempted,
+ set_dispatch_phase,
+)
from core.session_activities import SessionActivityRegistry
from modules.agents.service import AgentService
from modules.agents.codex.transport import CodexTransport
@@ -136,7 +141,9 @@ def test_agent_service_runs_turn_start_hooks_after_gate_before_agent() -> None:
agent = _OrderRecordingAgent(log)
service.register(agent)
- await service.handle_message("claude", _request("hi"))
+ request = _request("hi")
+ set_dispatch_phase(request.context, DISPATCH_PHASE_PREWRITE)
+ await service.handle_message("claude", request)
# on_running (gate confirmed) must precede the bubble hooks, which in turn
# precede the agent run. This is what keeps a queued turn from claiming
@@ -147,6 +154,7 @@ def test_agent_service_runs_turn_start_hooks_after_gate_before_agent() -> None:
"begin_status_bubble",
"handle_message",
]
+ assert backend_dispatch_attempted(request.context) is False
asyncio.run(_run())
@@ -942,6 +950,37 @@ def test_agent_service_marks_runtime_started_from_matching_context_only() -> Non
assert gate.runtime_started is False
+def test_agent_service_contains_terminal_owner_failure_after_releasing_gate() -> None:
+ async def _run():
+ controller = _Controller()
+
+ class _TurnOwner:
+ @staticmethod
+ def on_native_terminal(_context, *, outcome):
+ assert outcome == "terminal"
+ raise RuntimeError("terminal owner write failed")
+
+ controller.session_turns = _TurnOwner()
+ service = AgentService(controller=controller)
+ runtime_key = "session:/repo"
+ gate = service._get_turn_gate(runtime_key)
+ await gate.lock.acquire()
+ gate.token = "runtime-token"
+ context = SimpleNamespace(
+ platform_specific={
+ "agent_runtime_turn_key": runtime_key,
+ "agent_runtime_turn_token": "runtime-token",
+ }
+ )
+
+ service.release_runtime_turn(context)
+
+ assert not gate.lock.locked()
+ assert gate.token == ""
+
+ asyncio.run(_run())
+
+
def test_agent_service_clear_backend_sessions_does_not_release_other_backend_gate() -> None:
async def _run():
service = AgentService(controller=_Controller())
@@ -986,10 +1025,16 @@ def test_agent_service_refresh_runtime_config_releases_backend_gates() -> None:
asyncio.run(_run())
-def test_agent_service_releases_runtime_gate_for_stale_stop() -> None:
[email protected]("reason", ["not_active", "runtime_unavailable"])
+def test_agent_service_releases_runtime_gate_for_stale_stop_without_terminal_evidence(
+ reason: str,
+) -> None:
async def _run():
- service = AgentService(controller=_Controller())
- agent = _StopRuntimeAgent("not_active")
+ controller = _Controller()
+ terminal_owner = Mock()
+ controller.session_turns = SimpleNamespace(on_native_terminal=terminal_owner)
+ service = AgentService(controller=controller)
+ agent = _StopRuntimeAgent(reason)
service.register(agent)
request = _request("stop")
gate = service._get_turn_gate("session:/repo")
@@ -1003,6 +1048,7 @@ def test_agent_service_releases_runtime_gate_for_stale_stop() -> None:
assert handled is False
assert not gate.lock.locked()
assert request.context.platform_specific["agent_runtime_turn_token"] == "stop-token"
+ terminal_owner.assert_not_called()
asyncio.run(_run())
diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.py
index d40c4c4e3..8c8a8f1ab 100644
--- a/tests/test_agent_steering.py
+++ b/tests/test_agent_steering.py
@@ -11,8 +11,10 @@ from aiohttp.client_reqrep import ConnectionKey
from core.services.agent_steering import (
ActiveSteerTarget,
SteerOutcome,
+ SteerReconcileRequest,
SteerRequest,
active_steer_identity,
+ reconcile_steer_attempt,
steer_active_turn,
)
from modules.agents.base import AgentRequest
@@ -148,7 +150,10 @@ class _OpenCodeServer:
raise self.error
self.messages.append(
{
- "info": {"id": f"steer-user-{len(self.prompt_calls)}", "role": "user"},
+ "info": {
+ "id": kwargs.get("message_id") or f"steer-user-{len(self.prompt_calls)}",
+ "role": "user",
+ },
"parts": [{"type": "text", "text": kwargs["text"]}],
}
)
@@ -166,6 +171,13 @@ class _OpenCodeServer:
return self.status_responses.pop(0)
return self.status
+ async def get_message(self, session_id: str, message_id: str, directory: str) -> dict:
+ return next(
+ message
+ for message in self.messages
+ if message.get("info", {}).get("id") == message_id
+ )
+
async def abort_session(self, *args) -> bool:
self.abort_calls.append(args)
return True
@@ -604,6 +616,49 @@ async def test_opencode_steers_existing_runner_without_abort_or_new_turn() -> No
await _cancel_tasks(gate_task)
+async def test_opencode_reconciles_exact_native_attempt_without_resteering() -> None:
+ primary = _primary_request(backend="opencode")
+ gate_task = await _held_task()
+ server = _OpenCodeServer()
+ agent = _opencode_agent(primary, gate_task, server)
+ controller = _controller_with_active_gate(agent, primary, gate_task)
+ attempt_id = "atm_exact_restart_evidence"
+ try:
+ identity = active_steer_identity(controller, "opencode", "avibe-session")
+ assert identity is not None
+ receipt = await steer_active_turn(
+ controller,
+ "opencode",
+ SteerRequest(
+ target_session_id="avibe-session",
+ expected_logical_turn_id=identity[0],
+ expected_native_turn_id=identity[1],
+ text=STEER_TEXT,
+ attempt_id=attempt_id,
+ ),
+ )
+ assert receipt.outcome is SteerOutcome.ACCEPTED
+ assert server.prompt_calls[0]["message_id"] == attempt_id
+
+ reconciled = await reconcile_steer_attempt(
+ controller,
+ "opencode",
+ SteerReconcileRequest(
+ target_session_id="avibe-session",
+ expected_logical_turn_id=identity[0],
+ expected_native_turn_id=identity[1],
+ attempt_id=attempt_id,
+ ),
+ )
+
+ assert reconciled.outcome is SteerOutcome.ACCEPTED
+ assert reconciled.details["native_message_id"] == attempt_id
+ assert len(server.prompt_calls) == 1
+ finally:
+ await _cancel_tasks(gate_task)
+
+
@pytest.mark.anyio
async def test_opencode_stop_waits_for_in_flight_steering_write() -> None:
primary = _primary_request(backend="opencode")
@@ -856,6 +911,243 @@ async def test_opencode_coordinator_error_aborts_through_steering_owner(
backend_failure.assert_awaited_once()
[email protected]("reconciliation_fails", [False, True])
+async def test_opencode_definitive_start_rejection_reconciles_before_poll_cleanup(
+ monkeypatch,
+ reconciliation_fails: bool,
+) -> None:
+ primary = _primary_request(backend="opencode")
+ primary.context.platform_specific["delivery_start_attempt_id"] = "atm-start"
+ events: list[str] = []
+
+ class _Server:
+ async def ensure_running(self):
+ return None
+
+ async def list_messages(self, session_id, directory):
+ return []
+
+ async def prompt_async(self, **kwargs):
+ events.append("prompt")
+ raise OpenCodePromptRejectedError(409, "prompt refused")
+
+ async def abort_session(self, session_id, directory):
+ events.append("abort")
+ return True
+
+ async def mark_run_active(self, session_id):
+ return None
+
+ async def mark_run_inactive(self, session_id):
+ return None
+
+ def get_default_agent_from_config(self):
+ return None
+
+ def get_agent_model_from_config(self, agent):
+ return None
+
+ def get_agent_reasoning_effort_from_config(self, agent):
+ return None
+
+ class _SessionManager:
+ async def ensure_working_dir(self, path):
+ return None
+
+ async def get_or_create_session_id(self, request, server):
+ return "opencode-session"
+
+ def set_request_session(self, base_session_id, session_id, directory, session_key):
+ return None
+
+ def mark_initialized(self, session_id):
+ return False
+
+ class _Sessions:
+ def add_active_poll(self, **kwargs):
+ events.append("persist_poll")
+
+ def remove_active_poll(self, session_id):
+ events.append("remove_poll")
+
+ def reconcile_start_attempt_not_written(turn_id, attempt_id, *, backend):
+ events.append(f"reconcile:{turn_id}:{attempt_id}:{backend}")
+ if reconciliation_fails:
+ raise RuntimeError("storage unavailable")
+ return True
+
+ server = _Server()
+ controller = SimpleNamespace(
+ config=SimpleNamespace(
+ platform="avibe",
+ reply_enhancements=False,
+ show_pages_prompt=False,
+ remote_access=None,
+ language="en",
+ opencode=SimpleNamespace(
+ default_model=None,
+ default_provider=None,
+ default_reasoning_effort=None,
+ ),
+ ),
+ model_hub_runtime=None,
+ processing_indicator=SimpleNamespace(snapshot_request=lambda request: {}),
+ get_opencode_overrides=lambda context: (None, None, None),
+ session_turns=SimpleNamespace(
+ reconcile_start_attempt_not_written=reconcile_start_attempt_not_written,
+ ),
+ )
+ agent = object.__new__(OpenCodeAgent)
+ agent.controller = controller
+ agent.config = controller.config
+ agent.sessions = _Sessions()
+ agent._session_manager = _SessionManager()
+ agent._poll_loop = SimpleNamespace()
+ agent._steering_states = {}
+ agent._active_requests = {}
+ agent._client_manager = SimpleNamespace(_server_manager=server)
+ agent._get_server = AsyncMock(return_value=server)
+ agent._delete_ack = AsyncMock()
+ agent._remove_ack_reaction = AsyncMock()
+ agent._prepare_message_with_files = lambda request: request.message
+ agent.record_model_hub_native_failure = AsyncMock()
+ monkeypatch.setattr(
+ "modules.agents.opencode.agent.build_system_prompt_injection",
+ lambda **kwargs: "system prompt",
+ )
+ monkeypatch.setattr(
+ "modules.agents.opencode.agent.bind_caller_context_session",
+ lambda *args, **kwargs: None,
+ )
+ backend_failure = AsyncMock()
+ monkeypatch.setattr(
+ "modules.agents.opencode.agent.emit_backend_failure",
+ backend_failure,
+ )
+
+ await agent._process_message(primary)
+
+ assert events[:3] == [
+ "persist_poll",
+ "prompt",
+ "reconcile:logical-turn:atm-start:opencode",
+ ]
+ assert "abort" not in events
+ assert ("remove_poll" in events) is not reconciliation_fails
+ backend_failure.assert_awaited_once()
+
+
+async def test_opencode_ambiguous_start_failure_preserves_recovery_poll(
+ monkeypatch,
+) -> None:
+ primary = _primary_request(backend="opencode")
+ primary.context.platform_specific["delivery_start_attempt_id"] = "atm-start"
+ events: list[str] = []
+
+ class _Server:
+ async def ensure_running(self):
+ return None
+
+ async def list_messages(self, session_id, directory):
+ return []
+
+ async def prompt_async(self, **kwargs):
+ events.append("prompt")
+ raise OSError("connection lost after prompt write")
+
+ async def abort_session(self, session_id, directory):
+ events.append("abort")
+ return True
+
+ async def mark_run_active(self, session_id):
+ return None
+
+ async def mark_run_inactive(self, session_id):
+ return None
+
+ def get_default_agent_from_config(self):
+ return None
+
+ def get_agent_model_from_config(self, agent):
+ return None
+
+ def get_agent_reasoning_effort_from_config(self, agent):
+ return None
+
+ class _SessionManager:
+ async def ensure_working_dir(self, path):
+ return None
+
+ async def get_or_create_session_id(self, request, server):
+ return "opencode-session"
+
+ def set_request_session(self, base_session_id, session_id, directory, session_key):
+ return None
+
+ def mark_initialized(self, session_id):
+ return False
+
+ class _Sessions:
+ def add_active_poll(self, **kwargs):
+ events.append("persist_poll")
+
+ def remove_active_poll(self, session_id):
+ events.append("remove_poll")
+
+ server = _Server()
+ controller = SimpleNamespace(
+ config=SimpleNamespace(
+ platform="avibe",
+ reply_enhancements=False,
+ show_pages_prompt=False,
+ remote_access=None,
+ language="en",
+ opencode=SimpleNamespace(
+ default_model=None,
+ default_provider=None,
+ default_reasoning_effort=None,
+ ),
+ ),
+ model_hub_runtime=None,
+ processing_indicator=SimpleNamespace(snapshot_request=lambda request: {}),
+ get_opencode_overrides=lambda context: (None, None, None),
+ )
+ agent = object.__new__(OpenCodeAgent)
+ agent.controller = controller
+ agent.config = controller.config
+ agent.sessions = _Sessions()
+ agent._session_manager = _SessionManager()
+ agent._poll_loop = SimpleNamespace()
+ agent._steering_states = {}
+ agent._active_requests = {}
+ agent._client_manager = SimpleNamespace(_server_manager=server)
+ agent._get_server = AsyncMock(return_value=server)
+ agent._delete_ack = AsyncMock()
+ agent._remove_ack_reaction = AsyncMock()
+ agent._prepare_message_with_files = lambda request: request.message
+ agent.record_model_hub_native_failure = AsyncMock()
+ monkeypatch.setattr(
+ "modules.agents.opencode.agent.build_system_prompt_injection",
+ lambda **kwargs: "system prompt",
+ )
+ monkeypatch.setattr(
+ "modules.agents.opencode.agent.bind_caller_context_session",
+ lambda *args, **kwargs: None,
+ )
+ backend_failure = AsyncMock()
+ monkeypatch.setattr(
+ "modules.agents.opencode.agent.emit_backend_failure",
+ backend_failure,
+ )
+
+ await agent._process_message(primary)
+
+ assert events == ["persist_poll", "prompt", "abort"]
+ backend_failure.assert_awaited_once()
+
+
@pytest.mark.anyio
async def test_opencode_question_abort_claims_terminal_owner_before_steering() -> None:
primary = _primary_request(backend="opencode")
diff --git a/tests/test_background_work_banner.py b/tests/test_background_work_banner.py
index 78c31b283..9f1ec4af9 100644
--- a/tests/test_background_work_banner.py
+++ b/tests/test_background_work_banner.py
@@ -310,12 +310,12 @@ def test_turn_state_survives_harness_derivation_failure(tmp_path: Path):
import core.session_turns as session_turns
- original = session_turns.messages_service.list_queued
- session_turns.messages_service.list_queued = lambda conn, sid: []
+ original = session_turns.delivery_store.list_queued
+ session_turns.delivery_store.list_queued = lambda conn, sid: []
try:
state = manager.turn_state("ses-1")
finally:
- session_turns.messages_service.list_queued = original
+ session_turns.delivery_store.list_queued = original
assert [item["id"] for item in state["background_activities"]] == ["bg-1"]
assert state["background_activities"][0]["item_kind"] == "backend_activity"
diff --git a/tests/test_chat_discovery.py b/tests/test_chat_discovery.py
index 04759b117..034dac0d8 100644
--- a/tests/test_chat_discovery.py
+++ b/tests/test_chat_discovery.py
@@ -6,6 +6,8 @@ from pathlib import Path
from config.v2_settings import ChannelSettings, SettingsState
from core import chat_discovery
from storage.migrations import run_migrations
+from storage import message_deliveries as delivery_store
+from storage.workbench_sessions_service import create_session
from storage.settings_service import SQLiteSettingsService
@@ -1044,6 +1046,107 @@ def test_delete_scope_with_history_dismisses_instead_of_deleting(tmp_path: Path)
assert kept is not None
+def test_delete_scope_with_pending_delivery_dismisses_instead_of_deleting(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ chat_discovery.remember_chat("telegram", "pending", name="Pending", db_path=db_path)
+ scope_id = chat_discovery.make_scope_id(
+ "telegram",
+ chat_discovery.CHANNEL_SCOPE_TYPE,
+ "pending",
+ )
+
+ engine = chat_discovery._engine(db_path)
+ try:
+ with engine.begin() as conn:
+ session = create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="codex",
+ title="Pending delivery",
+ )
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id="delivery-pending-scope",
+ session_id=str(session["id"]),
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=scope_id,
+ session_id=str(session["id"]),
+ platform="telegram",
+ author="user",
+ source="user",
+ text="queued input",
+ ),
+ dispatch_text="queued input",
+ )
+ finally:
+ engine.dispose()
+
+ assert chat_discovery.delete_scope("telegram", "pending", db_path=db_path) == {
+ "removed": False,
+ "dismissed": True,
+ }
+
+ engine = chat_discovery._engine(db_path)
+ try:
+ with engine.connect() as conn:
+ assert delivery_store.get_delivery(conn, "delivery-pending-scope") is not None
+ finally:
+ engine.dispose()
+
+
+def test_delete_scope_ignores_retired_delivery_snapshots(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ chat_discovery.remember_chat("telegram", "retired", name="Retired", db_path=db_path)
+ scope_id = chat_discovery.make_scope_id(
+ "telegram",
+ chat_discovery.CHANNEL_SCOPE_TYPE,
+ "retired",
+ )
+
+ engine = chat_discovery._engine(db_path)
+ try:
+ with engine.begin() as conn:
+ session = create_session(
+ conn,
+ scope_id=None,
+ agent_backend="codex",
+ title="Retired delivery",
+ )
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id="delivery-retired-scope",
+ session_id=str(session["id"]),
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=scope_id,
+ session_id=str(session["id"]),
+ platform="telegram",
+ author="user",
+ source="user",
+ text="retired input",
+ ),
+ dispatch_text="retired input",
+ )
+ assert delivery_store.retire_not_written(
+ conn,
+ str(session["id"]),
+ "delivery-retired-scope",
+ reason="test_retirement",
+ )
+ finally:
+ engine.dispose()
+
+ assert chat_discovery.delete_scope("telegram", "retired", db_path=db_path) == {
+ "removed": True,
+ "dismissed": False,
+ }
+
+
def test_remember_chat_clears_dismissed_on_passive_rediscovery(tmp_path: Path) -> None:
from datetime import datetime, timezone
diff --git a/tests/test_claude_agent_initiated_turn.py b/tests/test_claude_agent_initiated_turn.py
index 50486a828..460b01097 100644
--- a/tests/test_claude_agent_initiated_turn.py
+++ b/tests/test_claude_agent_initiated_turn.py
@@ -2526,7 +2526,7 @@ class ActivityRunAttributionTests(unittest.IsolatedAsyncioTestCase):
self._pending(
task_trigger_kind="scheduled",
task_execution_id="run-scheduled",
- coalesced_queue={"execution_ids": ["run-scheduled", "run-coalesced"]},
+ accepted_agent_run_ids=["run-scheduled", "run-coalesced"],
)
]
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index 9388722fc..16ac4382c 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -8,6 +8,11 @@ from unittest.mock import ANY, AsyncMock, MagicMock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from modules.agents.base import BaseAgent
+from core.native_dispatch_phase import (
+ DISPATCH_PHASE_PREWRITE,
+ backend_dispatch_attempted,
+ set_dispatch_phase,
+)
from core.services.agent_steering import ActiveSteerTarget, SteerOutcome, SteerRequest
from modules.agents.claude_agent import ClaudeAgent
from modules.agents.service import AgentService
@@ -864,8 +869,14 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
controller = _StubController()
controller.emit_agent_message = AsyncMock()
runtime_key = "wechat_o9:reviewer:/tmp/work"
+ request_context = SimpleNamespace(platform_specific={})
+ set_dispatch_phase(request_context, DISPATCH_PHASE_PREWRITE)
+
+ async def _query_at_native_boundary(*_args, **_kwargs):
+ self.assertIs(backend_dispatch_attempted(request_context), True)
+
client = SimpleNamespace(
- query=AsyncMock(),
+ query=AsyncMock(side_effect=_query_at_native_boundary),
_vibe_runtime_base_session_id="wechat_o9:reviewer",
_vibe_runtime_session_key=runtime_key,
)
@@ -884,7 +895,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
agent._receive_messages = AsyncMock()
request = SimpleNamespace(
- context=SimpleNamespace(),
+ context=request_context,
message="hello",
working_path="/tmp/work",
base_session_id="wechat_o9",
@@ -2820,13 +2831,13 @@ class AdoptPendingTurnTokenTests(unittest.TestCase):
"task_execution_id": "run-old",
}
)
- coalesced = {"execution_ids": ["run-new", "run-child"]}
+ accepted = ["run-new", "run-child"]
pending = SimpleNamespace(
context=SimpleNamespace(
platform_specific={
"task_trigger_kind": "agent_run",
"task_execution_id": "run-new",
- "coalesced_queue": coalesced,
+ "accepted_agent_run_ids": accepted,
}
)
)
@@ -2834,12 +2845,8 @@ class AdoptPendingTurnTokenTests(unittest.TestCase):
ClaudeAgent._adopt_pending_turn_token(ctx, pending)
self.assertEqual(ctx.platform_specific["task_execution_id"], "run-new")
- self.assertEqual(ctx.platform_specific["coalesced_queue"], coalesced)
- self.assertIsNot(ctx.platform_specific["coalesced_queue"], coalesced)
- self.assertIsNot(
- ctx.platform_specific["coalesced_queue"]["execution_ids"],
- coalesced["execution_ids"],
- )
+ self.assertEqual(ctx.platform_specific["accepted_agent_run_ids"], accepted)
+ self.assertIsNot(ctx.platform_specific["accepted_agent_run_ids"], accepted)
def test_clears_stale_agent_run_attribution_for_plain_turn(self):
ctx = SimpleNamespace(
@@ -2847,7 +2854,7 @@ class AdoptPendingTurnTokenTests(unittest.TestCase):
"turn_token": "T1",
"task_trigger_kind": "agent_run",
"task_execution_id": "run-old",
- "coalesced_queue": {"execution_ids": ["run-old"]},
+ "accepted_agent_run_ids": ["run-old"],
}
)
pending = SimpleNamespace(
@@ -2859,7 +2866,7 @@ class AdoptPendingTurnTokenTests(unittest.TestCase):
self.assertEqual(ctx.platform_specific["turn_token"], "T2")
self.assertNotIn("task_trigger_kind", ctx.platform_specific)
self.assertNotIn("task_execution_id", ctx.platform_specific)
- self.assertNotIn("coalesced_queue", ctx.platform_specific)
+ self.assertNotIn("accepted_agent_run_ids", ctx.platform_specific)
class _FakeBaseAgent(BaseAgent):
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 77bba17d5..07489a840 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -2793,6 +2793,12 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("Current session id: `sesk8m4q2p7x`", params["developerInstructions"])
async def test_start_turn_uses_sandbox_policy_object(self):
+ from core.native_dispatch_phase import (
+ DISPATCH_PHASE_PREWRITE,
+ backend_dispatch_attempted,
+ set_dispatch_phase,
+ )
+
agent = object.__new__(CodexAgent)
agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, None, None)))
agent.codex_config = SimpleNamespace(default_model=None)
@@ -2810,8 +2816,15 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
subagent_name=None,
subagent_model=None,
subagent_reasoning_effort=None,
+ context=SimpleNamespace(platform_specific={}),
)
- transport = SimpleNamespace(send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}))
+ set_dispatch_phase(request.context, DISPATCH_PHASE_PREWRITE)
+
+ async def _send_at_native_boundary(*_args, **_kwargs):
+ self.assertIs(backend_dispatch_attempted(request.context), True)
+ return {"turn": {"id": "turn-1"}}
+
+ transport = SimpleNamespace(send_request=AsyncMock(side_effect=_send_at_native_boundary))
thread_id = await agent._start_turn(transport, request, "thread-1")
@@ -2826,7 +2839,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
"sandboxPolicy": {"type": "dangerFullAccess"},
},
)
- agent.controller.get_codex_overrides.assert_not_called()
+ agent.controller.get_codex_overrides.assert_called_once_with(request.context)
async def test_start_turn_writes_current_caller_env_script_for_reused_threads(self):
agent = object.__new__(CodexAgent)
diff --git a/tests/test_controller_agent_status.py b/tests/test_controller_agent_status.py
index 2d7664fb6..7949d1793 100644
--- a/tests/test_controller_agent_status.py
+++ b/tests/test_controller_agent_status.py
@@ -95,8 +95,21 @@ def test_run_marks_running_at_acceptance_before_dispatch(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
from storage.importer import ensure_sqlite_state
+ from storage.agent_session_rows import create_agent_session_row
+ from storage.db import create_sqlite_engine
ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ create_agent_session_row(
+ conn,
+ session_id="ses-accept",
+ scope_id=None,
+ session_anchor=None,
+ agent_backend="claude",
+ agent_variant="claude",
+ workdir=str(tmp_path),
+ )
import core.session_turns as session_turns_module
from core.session_turns import SessionTurnManager
@@ -118,7 +131,7 @@ def test_run_marks_running_at_acceptance_before_dispatch(monkeypatch, tmp_path):
monkeypatch.setattr(session_turns_module, "dispatch_turn_with_outcome", _dispatch)
async def _exercise():
- await mgr._run("ses-accept", _ctx("ses-accept"), "hi")
+ await mgr.submit("ses-accept", _ctx("ses-accept"), "hi")
# _run returns right after acceptance; the dispatch task hasn't run yet
# (single-threaded loop) — the running mark must already be recorded.
assert ("ses-accept", "running") in calls
diff --git a/tests/test_controller_dispatch_loop.py b/tests/test_controller_dispatch_loop.py
index b067b43e9..cf6c7032c 100644
--- a/tests/test_controller_dispatch_loop.py
+++ b/tests/test_controller_dispatch_loop.py
@@ -6,6 +6,8 @@ import sys
from pathlib import Path
from types import SimpleNamespace
+import pytest
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.controller import Controller
@@ -419,3 +421,29 @@ def test_terminal_checkpoint_runs_after_dispatcher_delivery() -> None:
assert result == "result-1"
assert order == ["checkpoint-start", "delivered", "checkpoint-end"]
+
+
+def test_terminal_delivery_failure_keeps_turn_owner_live() -> None:
+ controller = Controller.__new__(Controller)
+ completed: list[MessageContext] = []
+
+ class _Dispatcher:
+ @staticmethod
+ async def emit_agent_message(**_kwargs):
+ raise RuntimeError("Workbench run output was not durably persisted")
+
+ controller.message_dispatcher = _Dispatcher()
+ controller.session_turns = SimpleNamespace(
+ on_terminal_delivery_complete=lambda context: completed.append(context)
+ )
+ context = MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ platform_specific={"turn_token": "turn-live"},
+ )
+
+ with pytest.raises(RuntimeError, match="not durably persisted"):
+ asyncio.run(controller.emit_agent_message(context, "result", "done"))
+
+ assert completed == []
diff --git a/tests/test_controller_im_ready.py b/tests/test_controller_im_ready.py
index 5db167245..a20829741 100644
--- a/tests/test_controller_im_ready.py
+++ b/tests/test_controller_im_ready.py
@@ -21,6 +21,7 @@ def test_runtime_services_start_when_post_update_notification_fails() -> None:
controller.runtime_command_watcher = SimpleNamespace(start=AsyncMock())
controller._get_idle_cleanup_timeouts = Mock(return_value=(0, 0))
controller.cleanup_task = None
+ controller._delivery_recovery_barrier = asyncio.Event()
asyncio.run(controller._on_runtime_ready())
diff --git a/tests/test_core_services_dispatch.py b/tests/test_core_services_dispatch.py
index d64eb7f6d..7e748555c 100644
--- a/tests/test_core_services_dispatch.py
+++ b/tests/test_core_services_dispatch.py
@@ -36,6 +36,12 @@ from core.services.dispatch import (
dispatch_turn,
dispatch_turn_with_outcome,
)
+from core.native_dispatch_phase import (
+ DISPATCH_PHASE_ATTEMPTING,
+ DISPATCH_PHASE_PREWRITE,
+ backend_dispatch_attempted,
+ set_dispatch_phase,
+)
from modules.im import MessageContext
@@ -175,6 +181,32 @@ def test_outcome_reports_release_without_terminal_result():
assert outcome.settled_by == SETTLED_BY_NO_TERMINAL_RESULT
+def test_outcome_reports_definite_prewrite_exit() -> None:
+ controller = _streaming_controller(sink_settled_by=SETTLED_BY_TERMINAL_RESULT)
+
+ async def no_backend_dispatch(context, _text):
+ set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)
+ return "agent is unavailable"
+
+ controller.message_handler.handle_user_message = AsyncMock(side_effect=no_backend_dispatch)
+ outcome = asyncio.run(
+ dispatch_turn_with_outcome(controller, _ctx(), "hi", on_chunk=AsyncMock())
+ )
+
+ assert outcome.backend_dispatch_attempted is False
+
+
+def test_dispatch_evidence_survives_prepared_context_replacement() -> None:
+ original = _ctx()
+ evidence = set_dispatch_phase(original, DISPATCH_PHASE_PREWRITE)
+ prepared = _ctx()
+ set_dispatch_phase(prepared, DISPATCH_PHASE_PREWRITE, evidence=evidence)
+
+ set_dispatch_phase(prepared, DISPATCH_PHASE_ATTEMPTING)
+
+ assert backend_dispatch_attempted(original) is True
+
+
def test_outcome_reports_refused_concurrent_turn():
# The refusal returns BEFORE any sink is registered, so the settlement cannot
# ride the sink — it has to be reported directly or the caller's run row would
diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.py
index 7083d5a04..862c475fc 100644
--- a/tests/test_core_services_sessions.py
+++ b/tests/test_core_services_sessions.py
@@ -76,7 +76,6 @@ def test_public_surface_is_stable():
"is_session_archived",
"list_sessions",
"list_sessions_page",
- "reset_running_agent_status",
"set_agent_status",
"touch_session",
"update_session",
@@ -114,7 +113,6 @@ def test_each_workbench_function_delegates_to_storage():
"get_session",
"is_session_archived",
"list_sessions",
- "reset_running_agent_status",
"set_agent_status",
"touch_session",
"update_session",
@@ -567,22 +565,6 @@ def test_set_agent_status_rejects_unknown_value(isolated_state):
assert sessions_service.get_session(conn, sid)["agent_status"] == "idle"
-def test_reset_running_agent_status_clears_only_running(isolated_state):
- """Startup recovery: stale ``running`` → ``idle``; failed/idle untouched."""
- engine = create_sqlite_engine()
- with engine.begin() as conn:
- scope_id = _seed_avibe_scope(conn)
- running = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")["id"]
- failed = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")["id"]
- sessions_service.set_agent_status(conn, running, "running")
- sessions_service.set_agent_status(conn, failed, "failed")
- reset = sessions_service.reset_running_agent_status(conn)
- assert reset == 1
- with engine.connect() as conn:
- assert sessions_service.get_session(conn, running)["agent_status"] == "idle"
- assert sessions_service.get_session(conn, failed)["agent_status"] == "failed"
-
-
def _bind_native(conn, session_id: str, native_id: str = "native-1") -> None:
"""Simulate the first turn's native bind (``bind_agent_session_by_id``)."""
conn.execute(
@@ -720,14 +702,11 @@ def test_update_session_running_turn_locks_agent_less_session_too(isolated_state
assert sessions_service.get_session(conn, sid)["agent_backend"] == "codex"
-def test_update_session_backend_switch_loses_race_with_native_bind(isolated_state):
- """The lock guard is read-then-write and the first turn's native bind can
- commit in between (the SELECT runs before the UPDATE takes the write lock).
- The UPDATE re-asserts the lock in its WHERE predicate, so a cross-backend
- switch that loses the race raises instead of stamping a backend that
- mismatches the backend owning the just-bound native."""
+def test_update_session_backend_switch_reserves_writer_before_decision(isolated_state):
+ """A route edit and first native bind are serialized before the decision read."""
from sqlalchemy import event
+ from sqlalchemy.exc import OperationalError
engine = create_sqlite_engine()
with engine.begin() as conn:
@@ -737,29 +716,33 @@ def test_update_session_backend_switch_loses_race_with_native_bind(isolated_stat
)["id"]
bind_engine = create_sqlite_engine()
- fired = {"done": False}
+ race = {"fired": False, "blocked": False}
- def bind_native_before_update(_conn, _cursor, statement, _params, _context, _executemany):
- # Right before update_session's UPDATE executes — i.e. AFTER its lock
- # check read "no native yet" — land the first turn's native bind on a
- # separate connection, exactly the racing interleave.
- if fired["done"] or not statement.lstrip().upper().startswith("UPDATE AGENT_SESSIONS"):
+ def bind_native_after_read(_conn, _cursor, statement, _params, _context, _executemany):
+ if race["fired"] or not statement.lstrip().upper().startswith("SELECT AGENT_SESSIONS.ID"):
return
- fired["done"] = True
- with bind_engine.begin() as bind_conn:
- _bind_native(bind_conn, sid)
-
- event.listen(engine, "before_cursor_execute", bind_native_before_update)
+ race["fired"] = True
+ try:
+ with bind_engine.begin() as bind_conn:
+ bind_conn.exec_driver_sql("PRAGMA busy_timeout = 1")
+ _bind_native(bind_conn, sid)
+ except OperationalError as exc:
+ race["blocked"] = "database is locked" in str(exc)
+
+ event.listen(engine, "after_cursor_execute", bind_native_after_read)
try:
with engine.begin() as conn:
- with pytest.raises(sessions_service.SessionBackendLockedError):
- sessions_service.update_session(conn, sid, agent_backend="codex", agent_name="codex")
+ sessions_service.update_session(conn, sid, agent_backend="codex", agent_name="codex")
finally:
- event.remove(engine, "before_cursor_execute", bind_native_before_update)
+ event.remove(engine, "after_cursor_execute", bind_native_after_read)
- assert fired["done"], "race interleave never triggered — test setup is broken"
+ assert race == {"fired": True, "blocked": True}
+ with bind_engine.begin() as bind_conn:
+ _bind_native(bind_conn, sid)
with engine.connect() as conn:
- assert sessions_service.get_session(conn, sid)["agent_backend"] == "claude"
+ session = sessions_service.get_session(conn, sid)
+ assert session["agent_backend"] == "codex"
+ assert session["native_session_id"] == "native-1"
def test_update_session_legacy_blank_backend_keeps_initial_pin_escape(isolated_state):
diff --git a/tests/test_delivery_state_matrix.py b/tests/test_delivery_state_matrix.py
new file mode 100644
index 000000000..d3f880a91
--- /dev/null
+++ b/tests/test_delivery_state_matrix.py
@@ -0,0 +1,95 @@
+from __future__ import annotations
+
+import inspect
+import re
+
+from core.session_turns import SessionTurnManager
+from core.vibe_agents import VibeAgentStore
+from storage.background import SQLiteBackgroundTaskStore
+from storage.delivery_states import (
+ ADMITTED_DELIVERY_STATES,
+ CLAIMABLE_QUEUE_STATES,
+ DELIVERY_STATE_MATRIX,
+ DELIVERY_STATES,
+ FENCE_STATES,
+ RUN_CANCEL_RETIRE_STATES,
+)
+from storage.models import message_deliveries
+
+
+def test_delivery_state_matrix_matches_database_state_constraint() -> None:
+ constraint = next(
+ item
+ for item in message_deliveries.constraints
+ if item.name == "ck_message_deliveries_state"
+ )
+ database_states = set(re.findall(r"'([^']+)'", str(constraint.sqltext)))
+
+ assert database_states == set(DELIVERY_STATE_MATRIX)
+ assert tuple(DELIVERY_STATE_MATRIX) == DELIVERY_STATES
+
+
+def test_delivery_state_matrix_matches_migrated_sqlite_constraint(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ with create_sqlite_engine().connect() as conn:
+ ddl = conn.exec_driver_sql(
+ "select sql from sqlite_master where type='table' and name='message_deliveries'"
+ ).scalar_one()
+ match = re.search(
+ r"CONSTRAINT ck_message_deliveries_state CHECK \(state in \((.*?)\)\)",
+ ddl,
+ flags=re.DOTALL,
+ )
+
+ assert match is not None
+ assert set(re.findall(r"'([^']+)'", match.group(1))) == set(DELIVERY_STATE_MATRIX)
+
+
+def test_delivery_state_matrix_derives_every_cross_cutting_state_set() -> None:
+ assert CLAIMABLE_QUEUE_STATES == tuple(
+ state
+ for state, policy in DELIVERY_STATE_MATRIX.items()
+ if policy.ordering == "claimable"
+ )
+ assert FENCE_STATES == tuple(
+ state
+ for state, policy in DELIVERY_STATE_MATRIX.items()
+ if policy.ordering == "fence"
+ )
+ assert RUN_CANCEL_RETIRE_STATES == tuple(
+ state
+ for state, policy in DELIVERY_STATE_MATRIX.items()
+ if policy.run_cancel == "retire"
+ )
+ assert ADMITTED_DELIVERY_STATES == tuple(
+ state
+ for state, policy in DELIVERY_STATE_MATRIX.items()
+ if policy.submission == "admitted"
+ )
+
+ for policy in DELIVERY_STATE_MATRIX.values():
+ if policy.run_cancel == "retire":
+ assert policy.native_effect == "none"
+
+
+def test_cross_cutting_callers_consume_matrix_semantics() -> None:
+ from vibe import ui_server
+
+ cancel_source = inspect.getsource(SQLiteBackgroundTaskStore.cancel_run)
+ archive_source = inspect.getsource(VibeAgentStore._rewrite_references)
+ send_now_source = inspect.getsource(SessionTurnManager._promote_fifo_head)
+ show_dispatch_source = inspect.getsource(ui_server._run_show_event_dispatch)
+
+ assert "retire_for_run_cancellation" in cancel_source
+ assert 'delivery["state"]' not in cancel_source
+ assert "message_deliveries" not in archive_source
+ assert "snapshot_json" not in archive_source
+ assert "expected_delivery_id" in send_now_source
+ assert "ADMITTED_DELIVERY_STATES" in show_dispatch_source
diff --git a/tests/test_harness_failure_visibility.py b/tests/test_harness_failure_visibility.py
index 388eca2b3..450747917 100644
--- a/tests/test_harness_failure_visibility.py
+++ b/tests/test_harness_failure_visibility.py
@@ -112,10 +112,10 @@ def test_complete_does_not_clobber_an_already_terminal_run(tmp_path: Path) -> No
assert saved["result_text"] == "the report"
-def test_complete_coalesced_does_not_clobber_an_already_succeeded_run(tmp_path: Path) -> None:
- """HFR-061 — the coalesced completer must skip already-terminal rows.
+def test_turn_participant_settlement_does_not_clobber_an_already_succeeded_run(tmp_path: Path) -> None:
+ """HFR-061 — Turn settlement must skip already-terminal rows.
- ``complete_coalesced_agent_runs_for_workbench_in_connection`` honors
+ ``settle_agent_runs_for_turn_in_connection`` honors
``cancel_requested`` but has no ``queued|running`` predicate and no
already-terminal skip, so it rewrites a settled row wholesale.
"""
@@ -135,7 +135,7 @@ def test_complete_coalesced_does_not_clobber_an_already_succeeded_run(tmp_path:
terminal_status="succeeded",
)
- requests.complete_coalesced(claimed, [request.id], ok=False, error="turn died")
+ requests.settle_turn_participants(claimed, [request.id], ok=False, error="turn died")
saved = sqlite.get_run(request.id)
assert saved["status"] == "succeeded", "a settled success must not be rewritten to failed"
@@ -206,7 +206,7 @@ def test_a_cancel_landing_under_the_coalesced_completer_is_not_overwritten(
listener, fired = _cancel_mid_write(sqlite, request.id, fire_on="UPDATE agent_runs")
event.listen(sqlite.engine, "before_cursor_execute", listener)
try:
- requests.complete_coalesced(claimed, [request.id], ok=False, error="turn died")
+ requests.settle_turn_participants(claimed, [request.id], ok=False, error="turn died")
finally:
event.remove(sqlite.engine, "before_cursor_execute", listener)
@@ -357,7 +357,7 @@ def test_the_cancel_cas_does_not_leave_an_uncancelled_run_unsettled(tmp_path: Pa
)
claimed = requests.claim(coalesced.id)
assert claimed is not None
- requests.complete_coalesced(claimed, [coalesced.id], ok=False, error="turn died")
+ requests.settle_turn_participants(claimed, [coalesced.id], ok=False, error="turn died")
saved = sqlite.get_run(coalesced.id)
assert saved["status"] == "failed"
assert (saved.get("metadata") or {}).get(OWED_FAILURE_NOTICE_KEY) is not None
@@ -379,7 +379,12 @@ def test_the_cancel_cas_does_not_leave_an_uncancelled_run_unsettled(tmp_path: Pa
claimed = requests.claim(requested.id)
assert claimed is not None
sqlite.cancel_run(requested.id)
- requests.complete_coalesced(claimed, [requested.id], ok=False, error="turn died")
+ requests.settle_turn_participants(
+ claimed,
+ [requested.id],
+ ok=False,
+ error="turn died",
+ )
saved = sqlite.get_run(requested.id)
assert saved["status"] == "canceled"
assert (saved.get("metadata") or {}).get(OWED_FAILURE_NOTICE_KEY) is None
@@ -1214,7 +1219,12 @@ def test_every_terminal_failure_transition_stamps_an_owed_notice(tmp_path: Path)
# 4. the coalesced completer
fourth = requests.enqueue_agent_run(session_key="slack::channel::C1", message="d", agent_name=None)
claimed_fourth = requests.claim(fourth.id)
- requests.complete_coalesced(claimed_fourth, [fourth.id], ok=False, error="coalesced boom")
+ requests.settle_turn_participants(
+ claimed_fourth,
+ [fourth.id],
+ ok=False,
+ error="turn participant boom",
+ )
for run_id in (first.id, second.id, third.id, fourth.id):
notice = sqlite.owed_failure_notice(run_id)
@@ -1309,7 +1319,12 @@ def test_a_terminal_writer_never_rewrites_unparseable_metadata(tmp_path: Path) -
elif writer == "settle_deferred_run":
sqlite.settle_deferred_run(run.id)
else:
- requests.complete_coalesced(claimed, [run.id], ok=False, error="boom")
+ requests.settle_turn_participants(
+ claimed,
+ [run.id],
+ ok=False,
+ error="boom",
+ )
saved = sqlite.get_run(run.id)
assert _raw_metadata_json(sqlite, run.id) == blob, (
@@ -4265,34 +4280,9 @@ def test_workspace_notification_session_is_created_once_and_reused(
tmp_path: Path,
monkeypatch,
) -> None:
- """The second owed test at plan ``docs/plans/harness-run-reliability.md:3222``.
-
- Subordinate coverage under §D5's rung-(5) requirement (plan :3193, :3215-3222);
- no new scenario id this round — the §10.7 HFR-280…319 assignment is offered to
- the maintainer as a follow-up.
-
- Rung (5) resolves-or-CREATES, so the identity has to do the deduplication. Two
- caller-less definitions fail and are drained in two separate passes; exactly ONE
- ``agent_sessions`` row may exist afterwards and BOTH notices must land in it.
-
- Idempotence rests on the PRIMARY KEY, not on a marker search: the reserved id is
- spelled outside ``SESSION_ID_ALPHABET`` (which has no ``-``), so
- ``new_session_id`` can never mint it and the reserved row cannot collide with an
- ordinary session. The create re-decides under SQLite's write lock
- (``reserve_write_lock``), which is the same answer ``get_or_create_agent_session_row``
- already gives the first-turn INSERT — so two drain owners racing the creation
- produce one row, not an ``IntegrityError``.
-
- DURABILITY BY RECREATION, deliberately, rather than by exempting the row from
- ``/new`` clears and eviction: nothing here asks the session-clear or reclaim
- machinery for a special case. The third phase deletes the row outright and drains
- a third failure — the next notice simply recreates it, which is why an exemption
- is not needed at all.
- """
+ """Repeated workspace notices reuse one retained Session history owner."""
from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
- from storage.db import get_cached_sqlite_engine
- from storage.models import agent_sessions
_no_background_web_push(monkeypatch)
controller, _dispatcher, _touched = _live_turn_dispatcher()
@@ -4330,21 +4320,15 @@ def test_workspace_notification_session_is_created_once_and_reused(
for run_id in (first, second):
assert sqlite.owed_failure_notice(run_id)["state"] == NOTICE_SENT
- # --- durability by recreation, not by exemption -------------------------
- with get_cached_sqlite_engine().begin() as conn:
- conn.execute(
- agent_sessions.delete().where(agent_sessions.c.id == WORKSPACE_NOTICE_SESSION_ID)
- )
- assert _workspace_notice_session_rows() == []
-
third = _fail("task-cli-c")
asyncio.run(service._drain_failure_notices())
assert len(_workspace_notice_session_rows()) == 1, (
- "a cleared workspace session is recreated by the next notice"
+ "later notices must keep using the retained workspace Session"
)
+ assert len(_persisted_messages()) == 3
assert sqlite.owed_failure_notice(third)["state"] == NOTICE_SENT, (
- "so a clear cannot make a later notice unsendable"
+ "retaining accepted history cannot make a later notice unsendable"
)
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 1fa36173f..07df51660 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -40,6 +40,7 @@ from core.services.dispatch import (
dispatch_turn,
)
from modules.im import MessageContext
+from storage import message_deliveries
# ---------------------------------------------------------------------
@@ -70,6 +71,154 @@ def _seed_project_workdir(conn, scope_id: str, workdir: Path, *, now: str = "202
)
+def _reserve_submission(
+ conn,
+ *,
+ scope_id: str | None,
+ session_id: str,
+ text: str,
+ author: str = "user",
+ source: str = "user",
+ message_type: str = "user",
+ author_name: str | None = None,
+ content: dict | None = None,
+ metadata: dict | None = None,
+ native_message_id: str | None = None,
+):
+ delivery_id = message_deliveries.new_delivery_id()
+ row = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=session_id,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author=author,
+ source=source,
+ message_type=message_type,
+ text=text,
+ content=content,
+ metadata=metadata,
+ author_name=author_name,
+ native_message_id=native_message_id,
+ ),
+ dispatch_text=text,
+ dedupe_key=(
+ f"avibe:{native_message_id}" if native_message_id else None
+ ),
+ history_event={"kind": "test_admission", "priority": "p3"},
+ )
+ return message_deliveries.delivery_payload(row)
+
+
+def _create_test_session(tmp_path: Path, *, native_id: str, backend: str = "claude"):
+ from core.services import sessions as sessions_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id=native_id,
+ now="2026-05-31T00:00:00Z",
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend=backend,
+ agent_name="worker",
+ )
+ return engine, session
+
+
+def _create_active_test_turn(
+ tmp_path: Path,
+ *,
+ native_id: str,
+ backend: str = "claude",
+):
+ engine, session = _create_test_session(tmp_path, native_id=native_id, backend=backend)
+ with engine.begin() as conn:
+ delivery = _reserve_submission(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session["id"],
+ text="active owner",
+ )
+ turn_id = message_deliveries.new_turn_id()
+ message_deliveries.insert_turn(
+ conn,
+ turn_id=turn_id,
+ session_id=session["id"],
+ initial_delivery_id=delivery["id"],
+ state="starting",
+ backend=backend,
+ )
+ claimed = message_deliveries.open_start_attempt(
+ conn,
+ delivery["id"],
+ expected_version=1,
+ turn_id=turn_id,
+ attempt_id=message_deliveries.new_attempt_id(),
+ )
+ assert claimed is not None
+ bound = message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(message_deliveries.get_turn(conn, turn_id)["version"]),
+ runtime_key=f"runtime:{session['id']}",
+ runtime_turn_id=f"runtime-turn:{turn_id}",
+ native_turn_id=f"native:{turn_id}",
+ )
+ assert bound is not None
+ accepted = message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+ assert accepted
+ return engine, session, turn_id
+
+
+def _bind_test_native_start(engine, context: MessageContext) -> str:
+ """Simulate the narrow backend start binding bypassed by dispatch doubles."""
+
+ turn_id = str((context.platform_specific or {}).get("turn_token") or "")
+ assert turn_id
+ with engine.begin() as conn:
+ turn = message_deliveries.get_turn(conn, turn_id)
+ assert turn is not None
+ if turn["state"] == "starting":
+ turn = message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ runtime_key=f"runtime:{turn_id}",
+ runtime_turn_id=f"runtime-turn:{turn_id}",
+ native_turn_id=f"native:{turn_id}",
+ )
+ assert turn is not None
+ delivery = message_deliveries.delivery_for_turn(conn, turn_id)
+ assert delivery is not None
+ if delivery["state"] != "accepted":
+ accepted = message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+ assert accepted
+ return turn_id
+
+
def _build_controller_double(handler=None):
"""A MagicMock controller whose ``message_handler.handle_user_message``
can be patched to emit chunks via the real ``_stream_chunk`` hook.
@@ -103,8 +252,26 @@ def _build_controller_double(handler=None):
controller.pop_turn_sink = _pop
controller.get_turn_sink = lambda session_key: sinks.get(session_key)
+ controller._session_id_from_context = lambda ctx: str(
+ (getattr(ctx, "platform_specific", None) or {}).get("workbench_session_id")
+ or (getattr(ctx, "platform_specific", None) or {}).get("agent_session_id")
+ or ""
+ ) or None
def _mark_turn_complete(ctx):
+ manager = getattr(controller, "session_turns", None)
+ if manager is not None:
+ spec = getattr(ctx, "platform_specific", None) or {}
+ logical_turn_id = str(spec.get("turn_token") or "")
+ target = spec.get("agent_session_target") or {}
+ backend = str(target.get("agent_backend") or "claude")
+ if logical_turn_id:
+ manager.on_native_start(
+ ctx,
+ backend=backend,
+ runtime_key=f"runtime:{logical_turn_id}",
+ runtime_turn_id=f"runtime-turn:{logical_turn_id}",
+ )
sink = sinks.get(controller._get_session_key(ctx))
if sink and sink.get("done_event") is not None:
sink["done_event"].set()
@@ -501,6 +668,12 @@ def test_dispatch_forwards_session_routing_into_platform_specific(monkeypatch, t
"fork_source_backend": "claude",
},
)
+ delivery = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ text="hi",
+ )
session_id = session["id"]
captured: dict = {}
@@ -517,7 +690,14 @@ def test_dispatch_forwards_session_routing_into_platform_specific(monkeypatch, t
async def _go():
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- resp = await client.post("/internal/dispatch_async", json={"session_id": session_id, "text": "hi"})
+ resp = await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session_id,
+ "text": "hi",
+ "user_message_id": delivery["id"],
+ },
+ )
assert resp.status_code == 202
# Fire-and-forget: wait for the background turn to run + capture.
for _ in range(200):
@@ -555,7 +735,15 @@ def test_dispatch_async_starts_turn_and_returns_202(monkeypatch, tmp_path):
# dispatch_async reads the queue (to preserve order after a Stop), so it needs
# an initialized state DB even on the empty-queue happy path.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- ensure_sqlite_state()
+ engine, session = _create_test_session(tmp_path, native_id="proj_dispatch_start")
+ with engine.begin() as conn:
+ delivery = _reserve_submission(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session["id"],
+ text="hi",
+ )
+ session_id = session["id"]
started = asyncio.Event()
@@ -574,17 +762,27 @@ def test_dispatch_async_starts_turn_and_returns_202(monkeypatch, tmp_path):
events: list[str] = []
try:
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- resp = await client.post("/internal/dispatch_async", json={"session_id": "ses_a", "text": "hi"})
+ resp = await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session_id,
+ "text": "hi",
+ "user_message_id": delivery["id"],
+ },
+ )
await asyncio.wait_for(started.wait(), timeout=3)
for _ in range(100):
- if "ses_a" not in app.state.in_flight_dispatches:
+ if session_id not in app.state.in_flight_dispatches:
break
await asyncio.sleep(0.02)
- # Drain the bus: turn.start (at accept) + turn.end (at settle).
- for _ in range(2):
+ # Materialization also emits message.new; collect until the
+ # lifecycle closes instead of assuming adjacent bus events.
+ for _ in range(12):
try:
evt, _data = await asyncio.wait_for(queue.get(), timeout=1.0)
events.append(evt)
+ if evt == "turn.end":
+ break
except asyncio.TimeoutError:
break
finally:
@@ -595,11 +793,14 @@ def test_dispatch_async_starts_turn_and_returns_202(monkeypatch, tmp_path):
assert resp.status_code == 202
assert resp.json()["ok"] is True
controller.message_handler.handle_user_message.assert_awaited()
- assert "ses_a" not in app.state.in_flight_dispatches, "slot released after the turn"
- assert events == ["turn.start", "turn.end"], "publishes session turn lifecycle on the bus"
+ assert session_id not in app.state.in_flight_dispatches, "slot released after the turn"
+ assert [event for event in events if event.startswith("turn.")] == [
+ "turn.start",
+ "turn.end",
+ ], "publishes session turn lifecycle on the bus"
-def test_dispatch_async_no_terminal_result_keeps_session_in_flight(monkeypatch, tmp_path):
+def test_dispatch_async_stop_receipt_waits_for_terminal_evidence(monkeypatch, tmp_path):
"""There is NO turn-duration timeout (Phase 1a): a turn whose backend never
emits a terminal result stays in_flight indefinitely — the slot is freed ONLY
by a real terminal result or a cancel, never by any timer. A long-running
@@ -612,7 +813,15 @@ def test_dispatch_async_no_terminal_result_keeps_session_in_flight(monkeypatch,
from storage.importer import ensure_sqlite_state
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- ensure_sqlite_state()
+ engine, session = _create_test_session(tmp_path, native_id="proj_dispatch_long")
+ with engine.begin() as conn:
+ delivery = _reserve_submission(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session["id"],
+ text="hi",
+ )
+ session_id = session["id"]
started = asyncio.Event()
@@ -634,27 +843,36 @@ def test_dispatch_async_no_terminal_result_keeps_session_in_flight(monkeypatch,
async def _go():
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- resp = await client.post("/internal/dispatch_async", json={"session_id": "ses_long", "text": "hi"})
+ resp = await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session_id,
+ "text": "hi",
+ "user_message_id": delivery["id"],
+ },
+ )
assert resp.status_code == 202
await asyncio.wait_for(started.wait(), timeout=3)
# Give any (nonexistent) timer ample time to fire, then confirm the slot
# is STILL held — no timer auto-freed it.
await asyncio.sleep(0.1)
- entry = app.state.in_flight_dispatches.get("ses_long")
+ entry = app.state.in_flight_dispatches.get(session_id)
captured["held"] = entry is not None and not entry.task.done()
# Only a real cancel frees the slot — clean up so the loop tears down.
- resp_cancel = await client.post("/internal/cancel/ses_long")
+ resp_cancel = await client.post(f"/internal/cancel/{session_id}")
captured["cancel_status"] = resp_cancel.status_code
- for _ in range(200):
- if "ses_long" not in app.state.in_flight_dispatches:
- break
- await asyncio.sleep(0.02)
- captured["freed_after_cancel"] = "ses_long" not in app.state.in_flight_dispatches
+ await asyncio.sleep(0.05)
+ captured["held_after_stop_receipt"] = (
+ session_id in app.state.in_flight_dispatches
+ )
+ turn = app.state.in_flight_dispatches[session_id]
+ turn.task.cancel()
+ await asyncio.gather(turn.task, return_exceptions=True)
asyncio.run(_go())
assert captured["held"] is True, "a turn with no terminal result is NOT auto-freed by any timer"
assert captured["cancel_status"] == 200, "the user's Stop ends the wedged turn"
- assert captured["freed_after_cancel"] is True, "only a cancel (or terminal result) frees the slot"
+ assert captured["held_after_stop_receipt"] is True
def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):
@@ -664,7 +882,7 @@ def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):
a competing agent turn. The row flushes when the running turn ends."""
from core.services import sessions as sessions_service
- from storage import messages_service
+ from storage import message_deliveries, messages_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.settings_service import upsert_scope
@@ -680,11 +898,26 @@ def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):
session = sessions_service.create_session(
conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
)
- # The UI reserves the user row as 'pending' before dispatching; the
- # controller promotes it to 'queued' when it finds a turn in flight.
- user_row = messages_service.append(
- conn, scope_id=scope_id, session_id=session["id"], platform="avibe", author="user",
- source="user", message_type=messages_service.PENDING_TYPE, text="while busy",
+ owner = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ text="active owner",
+ )
+ owner_turn_id = message_deliveries.new_turn_id()
+ message_deliveries.insert_turn(
+ conn,
+ turn_id=owner_turn_id,
+ session_id=session["id"],
+ initial_delivery_id=owner["id"],
+ state="active",
+ backend="claude",
+ )
+ user_row = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ text="while busy",
)
session_id = session["id"]
@@ -702,6 +935,7 @@ def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):
app.state.in_flight_dispatches[session_id] = session_turns.Turn(
task=task,
context=MessageContext(user_id="U", channel_id="C", platform="avibe"),
+ logical_turn_id=owner_turn_id,
)
sub_id, events = bus.subscribe()
try:
@@ -730,204 +964,54 @@ def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):
assert ("queue.updated", {"session_id": session_id}) in published
with engine.connect() as conn:
# The row was atomically re-typed to queued (now out of the transcript).
- assert [q["text"] for q in messages_service.list_queued(conn, session_id)] == ["while busy"]
+ assert [q["text"] for q in message_deliveries.list_queued(conn, session_id)] == ["while busy"]
transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
assert transcript["messages"] == []
- (
- "stored_type",
- "author",
- "source",
- "author_name",
- "content",
- "active_same_message",
- "expect_queued",
- "expected_type",
- "expected_activity",
- ),
- (
- (
- "pending",
- "user",
- "user",
- None,
- {},
- True,
- False,
- "user",
- "user_message",
- ),
- (
- "pending",
- "user",
- "user",
- "show_annotation",
- {},
- True,
- False,
- "user",
- "user_message",
- ),
- (
- "pending",
- "harness",
- "harness",
- None,
- {},
- True,
- False,
- "harness",
- "show_event",
- ),
- (
- "pending",
- "harness",
- "harness",
- "show_annotation",
- {"annotation": {"direction": "user", "action": "created"}},
- True,
- False,
- "annotation",
- "show_event",
- ),
- ("queued", "user", "user", None, {}, False, True, "queued", None),
- ("user", "user", "user", None, {}, False, False, "user", None),
- (
- "annotation",
- "harness",
- "harness",
- "show_annotation",
- {"annotation": {"direction": "user", "action": "created"}},
- False,
- False,
- "annotation",
- None,
- ),
- ),
-)
-def test_dispatch_async_deduplicates_replayed_reserved_message(
- monkeypatch,
- tmp_path,
- stored_type,
- author,
- source,
- author_name,
- content,
- active_same_message,
- expect_queued,
- expected_type,
- expected_activity,
-):
- from core.inbox_events import bus
- from core.services import sessions as sessions_service
- from storage import messages_service
- from storage.db import create_sqlite_engine
- from storage.importer import ensure_sqlite_state
- from storage.settings_service import upsert_scope
+def test_dispatch_async_replay_of_queued_delivery_is_idempotent(monkeypatch, tmp_path):
+ from storage import message_deliveries, messages_service
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- ensure_sqlite_state()
- engine = create_sqlite_engine()
+ engine, session = _create_test_session(tmp_path, native_id="proj_replay_queued")
with engine.begin() as conn:
- scope_id = upsert_scope(
- conn,
- platform="avibe",
- scope_type="project",
- native_id=f"proj_replay_{stored_type}",
- now="2026-05-31T00:00:00Z",
- )
- _seed_project_workdir(conn, scope_id, tmp_path)
- session = sessions_service.create_session(
- conn,
- scope_id=scope_id,
- agent_backend="claude",
- agent_name="worker",
- )
- row = messages_service.append(
+ row = message_deliveries.enqueue_queued(
conn,
- scope_id=scope_id,
+ scope_id=session["scope_id"],
session_id=session["id"],
- platform="avibe",
- author=author,
- source=source,
- author_name=author_name,
- message_type=stored_type,
text="same show event",
- content=content,
)
controller = _build_controller_double()
- published: list[tuple[str, dict]] = []
- monkeypatch.setattr(
- bus,
- "publish",
- lambda event_type, data: published.append((event_type, data)),
- )
app = internal_server.create_app(controller)
transport = httpx.ASGITransport(app=app)
async def _go():
- active_task = None
- if active_same_message:
- active_task = asyncio.create_task(asyncio.sleep(60))
- app.state.in_flight_dispatches[session["id"]] = session_turns.Turn(
- task=active_task,
- context=MessageContext(
- user_id="U",
- channel_id="C",
- platform="avibe",
- message_id=row["id"],
- ),
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ ) as client:
+ return await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session["id"],
+ "text": "same show event",
+ "user_message_id": row["id"],
+ },
)
- try:
- async with httpx.AsyncClient(
- transport=transport,
- base_url="http://testserver",
- ) as client:
- return await client.post(
- "/internal/dispatch_async",
- json={
- "session_id": session["id"],
- "text": "same show event",
- "user_message_id": row["id"],
- },
- )
- finally:
- if active_task is not None:
- active_task.cancel()
response = asyncio.run(_go())
assert response.status_code == 202
assert response.json()["duplicate"] is True
- assert bool(response.json().get("queued")) is expect_queued
+ assert response.json()["queued"] is True
controller.message_handler.handle_user_message.assert_not_awaited()
with engine.connect() as conn:
- rows = messages_service.list_session_messages(
+ transcript = messages_service.list_session_messages(
conn,
session_id=session["id"],
)["messages"]
- assert [item["id"] for item in rows] == [row["id"]]
- assert rows[0]["type"] == expected_type
- visible_events = [
- data
- for event_type, data in published
- if event_type == "message.new"
- ]
- if stored_type == messages_service.PENDING_TYPE:
- assert [item["id"] for item in visible_events] == [row["id"]]
- else:
- assert visible_events == []
- activity_events = [
- data["event"]
- for event_type, data in published
- if event_type == "session.activity"
- ]
- assert activity_events == (
- [expected_activity] if expected_activity is not None else []
- )
+ assert transcript == []
def test_dispatch_async_persists_acceptance_before_a_lost_response_replay(
@@ -959,14 +1043,13 @@ def test_dispatch_async_persists_acceptance_before_a_lost_response_replay(
agent_backend="claude",
agent_name="worker",
)
- row = messages_service.append(
+ row = _reserve_submission(
conn,
scope_id=scope_id,
session_id=session["id"],
- platform="avibe",
author="harness",
source="harness",
- message_type=messages_service.PENDING_TYPE,
+ message_type="harness",
text="Dispatch exactly once.",
)
@@ -1006,16 +1089,12 @@ def test_dispatch_async_persists_acceptance_before_a_lost_response_replay(
first, replay = asyncio.run(_go())
assert first.status_code == 202
- assert first.json()["message_type"] == messages_service.HARNESS_TYPE
+ assert first.json()["delivery_state"] in {"claimed", "accepted"}
assert replay.status_code == 202
assert replay.json()["duplicate"] is True
controller.message_handler.handle_user_message.assert_awaited_once()
with engine.connect() as conn:
- settled = messages_service.get_message(
- conn,
- row["id"],
- session_id=session["id"],
- )
+ settled = messages_service.get_message(conn, row["id"], session_id=session["id"])
assert settled is not None
assert settled["type"] == messages_service.HARNESS_TYPE
assert [
@@ -1053,14 +1132,13 @@ def test_dispatch_async_rejects_archived_session_after_reservation_reclaimed(
agent_backend="claude",
agent_name="worker",
)
- row = messages_service.append(
+ row = _reserve_submission(
conn,
scope_id=scope_id,
session_id=session["id"],
- platform="avibe",
author="harness",
source="harness",
- message_type=messages_service.PENDING_TYPE,
+ message_type="harness",
text="Do not dispatch after archive.",
)
with engine.begin() as conn:
@@ -1091,7 +1169,7 @@ def test_dispatch_async_rejects_archived_session_after_reservation_reclaimed(
controller.message_handler.handle_user_message.assert_not_awaited()
-def test_dispatch_async_cancels_turn_when_archive_reclaims_reservation_during_submit(
+def test_dispatch_async_archive_after_start_does_not_reclaim_may_have_written_delivery(
monkeypatch,
tmp_path,
):
@@ -1119,14 +1197,13 @@ def test_dispatch_async_cancels_turn_when_archive_reclaims_reservation_during_su
agent_backend="claude",
agent_name="worker",
)
- row = messages_service.append(
+ row = _reserve_submission(
conn,
scope_id=scope_id,
session_id=session["id"],
- platform="avibe",
author="harness",
source="harness",
- message_type=messages_service.PENDING_TYPE,
+ message_type="harness",
text="Archive before acceptance.",
)
@@ -1164,11 +1241,12 @@ def test_dispatch_async_cancels_turn_when_archive_reclaims_reservation_during_su
response = asyncio.run(_go())
- assert response.status_code == 409
- assert response.json()["code"] == "session_archived"
- assert session["id"] not in app.state.in_flight_dispatches
- controller.command_handler.handle_stop.assert_awaited_once()
- controller.message_handler.handle_user_message.assert_not_awaited()
+ assert response.status_code == 202
+ controller.command_handler.handle_stop.assert_not_awaited()
+ with engine.connect() as conn:
+ delivery = message_deliveries.get_delivery(conn, row["id"])
+ assert delivery is not None
+ assert delivery["state"] not in {"retired", "queued", "reserved"}
def test_slow_live_show_post_cli_timeout_waits_without_duplicate_submit(
@@ -1358,6 +1436,12 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(
agent_backend="claude",
agent_name="worker",
)
+ first_delivery = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ text="active turn",
+ )
session_id = session["id"]
first_started = asyncio.Event()
@@ -1379,7 +1463,11 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
first = await client.post(
"/internal/dispatch_async",
- json={"session_id": session_id, "text": "active turn"},
+ json={
+ "session_id": session_id,
+ "text": "active turn",
+ "user_message_id": first_delivery["id"],
+ },
)
assert first.status_code == 202
await asyncio.wait_for(first_started.wait(), timeout=3)
@@ -1401,30 +1489,26 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(
)
finally:
store.close()
- assert annotation["message"]["type"] == messages_service.PENDING_TYPE
- enriched_dispatch_text = annotation["message"]["metadata"][
- session_turns.QUEUED_DISPATCH_TEXT_KEY
- ]
+ assert annotation["message"] is None
+ assert annotation["delivery"]["state"] == "reserved"
+ enriched_dispatch_text = annotation["delivery"]["dispatch_text"]
assert f"Show event id: {annotation['id']}" in enriched_dispatch_text
queued = await client.post(
"/internal/dispatch_async",
json={
"session_id": session_id,
"text": enriched_dispatch_text,
- "user_message_id": annotation["message_id"],
+ "user_message_id": annotation["delivery_id"],
"show_event_id": annotation["id"],
},
)
assert queued.status_code == 202
assert queued.json()["queued"] is True
with engine.connect() as conn:
- queued_rows = messages_service.list_queued(conn, session_id)
- assert [row["id"] for row in queued_rows] == [annotation["message_id"]]
+ queued_rows = message_deliveries.list_queued(conn, session_id)
+ assert [row["id"] for row in queued_rows] == [annotation["delivery_id"]]
assert queued_rows[0]["text"] == annotation["transcript_text"]
- assert (
- queued_rows[0]["metadata"][session_turns.QUEUED_DISPATCH_TEXT_KEY]
- == enriched_dispatch_text
- )
+ assert queued_rows[0]["dispatch_text"] == enriched_dispatch_text
visible = messages_service.list_session_messages(
conn,
session_id=session_id,
@@ -1447,7 +1531,7 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(
with engine.connect() as conn:
from storage.models import show_session_events
- assert messages_service.list_queued(conn, session_id) == []
+ assert message_deliveries.list_queued(conn, session_id) == []
visible = messages_service.list_session_messages(
conn,
session_id=session_id,
@@ -1458,17 +1542,20 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(
linked_message_id = conn.execute(
select(show_session_events.c.message_id).where(show_session_events.c.id == annotation["id"])
).scalar_one()
- assert [message["text"] for message in visible["messages"]] == [annotation["transcript_text"]]
- assert visible["messages"][0]["type"] == messages_service.ANNOTATION_TYPE
- assert visible["messages"][0]["author"] == messages_service.HARNESS_TYPE
- assert visible["messages"][0]["source"] == messages_service.HARNESS_TYPE
- assert visible["messages"][0]["author_name"] == "show_annotation"
- assert visible["messages"][0]["content"]["annotation"] == expected_display
- assert visible["messages"][0]["id"] != annotation["message_id"]
- assert visible["messages"][0]["metadata"]["source"] == "show_page"
- assert visible["messages"][0]["metadata"]["show_event_id"] == annotation["id"]
- assert session_turns.QUEUED_DISPATCH_TEXT_KEY not in visible["messages"][0]["metadata"]
- assert linked_message_id == visible["messages"][0]["id"]
+ assert [message["text"] for message in visible["messages"]] == [
+ "active turn",
+ annotation["transcript_text"],
+ ]
+ delivered = visible["messages"][-1]
+ assert delivered["type"] == messages_service.ANNOTATION_TYPE
+ assert delivered["author"] == messages_service.HARNESS_TYPE
+ assert delivered["source"] == messages_service.HARNESS_TYPE
+ assert delivered["author_name"] == "show_annotation"
+ assert delivered["content"]["annotation"] == expected_display
+ assert delivered["id"] == annotation["delivery_id"]
+ assert delivered["metadata"]["source"] == "show_page"
+ assert delivered["metadata"]["show_event_id"] == annotation["id"]
+ assert linked_message_id == delivered["id"]
def test_startup_recovered_annotation_retries_reserved_dispatch_text(
@@ -1522,15 +1609,7 @@ def test_startup_recovered_annotation_retries_reserved_dispatch_text(
)
finally:
store.close()
- expected_dispatch = annotation["message"]["metadata"][
- session_turns.QUEUED_DISPATCH_TEXT_KEY
- ]
-
- assert ui_server._recover_stale_pending_messages() == {
- "promoted": 0,
- "deleted": 0,
- "skipped": 1,
- }
+ expected_dispatch = annotation["delivery"]["dispatch_text"]
controller = _build_controller_double()
internal_app = internal_server.create_app(controller)
@@ -1544,8 +1623,23 @@ def test_startup_recovered_annotation_retries_reserved_dispatch_text(
)
dispatched = []
- async def capture_run(sid, context, text, *, source=SOURCE_HUMAN):
+ async def capture_run(
+ sid,
+ context,
+ text,
+ *,
+ source=SOURCE_HUMAN,
+ logical_turn_id=None,
+ **_kwargs,
+ ):
dispatched.append((sid, context.message_id, text, source))
+ _bind_test_native_start(engine, context)
+ manager._terminalize_durable_turn(
+ logical_turn_id,
+ "completed",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ evidence_kind="test_terminal",
+ )
manager._run = capture_run
@@ -1566,7 +1660,7 @@ def test_startup_recovered_annotation_retries_reserved_dispatch_text(
assert outcome == ui_server._ShowEventDispatchOutcome.ACCEPTED
with engine.connect() as conn:
- queued = messages_service.list_queued(conn, session["id"])
+ queued = message_deliveries.list_queued(conn, session["id"])
transcript = messages_service.list_session_messages(
conn,
session_id=session["id"],
@@ -1575,20 +1669,16 @@ def test_startup_recovered_annotation_retries_reserved_dispatch_text(
tail=True,
)["messages"]
assert queued == []
- assert dispatched[0][1] == annotation["message_id"]
+ assert dispatched[0][1] == annotation["delivery_id"]
assert dispatched[0][2] == expected_dispatch
assert "Anchor: #summary" in dispatched[0][2]
assert f"Show event id: {annotation['id']}" in dispatched[0][2]
assert transcript[0]["type"] == messages_service.ANNOTATION_TYPE
assert transcript[0]["text"] == "Recover and deliver this."
assert transcript[0]["content"]["annotation"]["quote"] == "Quarterly summary"
- assert (
- session_turns.QUEUED_DISPATCH_TEXT_KEY
- not in transcript[0]["metadata"]
- )
-def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(
+def test_idle_show_admission_starts_itself_without_releasing_held_backlog(
monkeypatch,
tmp_path,
):
@@ -1597,7 +1687,7 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(
from storage import messages_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
- from storage.models import messages, show_session_events
+ from storage.models import show_session_events
from storage.settings_service import upsert_scope
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -1618,16 +1708,13 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(
agent_backend="claude",
agent_name="worker",
)
- messages_service.append(
+ older = message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id=session["id"],
- platform="avibe",
- author="user",
- source="user",
- message_type=messages_service.QUEUED_TYPE,
text="older stopped message",
)
+ assert message_deliveries.set_queue_hold(conn, session["id"], held=True)
store = ShowSessionEventStore()
try:
annotation = store.append(
@@ -1656,8 +1743,23 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(
)
runs = []
- async def capture_run(sid, context, text, *, source=SOURCE_HUMAN):
+ async def capture_run(
+ sid,
+ context,
+ text,
+ *,
+ source=SOURCE_HUMAN,
+ logical_turn_id=None,
+ **_kwargs,
+ ):
runs.append((sid, text, source))
+ _bind_test_native_start(engine, context)
+ manager._terminalize_durable_turn(
+ logical_turn_id,
+ "completed",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ evidence_kind="test_terminal",
+ )
manager._run = capture_run
transport = httpx.ASGITransport(app=app)
@@ -1671,10 +1773,8 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(
"/internal/dispatch_async",
json={
"session_id": session["id"],
- "text": annotation["message"]["metadata"][
- session_turns.QUEUED_DISPATCH_TEXT_KEY
- ],
- "user_message_id": annotation["message_id"],
+ "text": annotation["delivery"]["dispatch_text"],
+ "user_message_id": annotation["delivery_id"],
"show_event_id": annotation["id"],
},
)
@@ -1682,42 +1782,17 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(
response = asyncio.run(_go())
assert response.status_code == 202
- assert response.json()["queued"] is True
+ assert response.json()["queued"] is False
assert response.json().get("drained") is None
assert len(runs) == 1
- assert runs[0][1] == "older stopped message"
- with engine.connect() as conn:
- queued = messages_service.list_queued(conn, session["id"])
- linked_message_id = conn.execute(
- select(show_session_events.c.message_id).where(
- show_session_events.c.id == annotation["id"]
- )
- ).scalar_one()
- original_exists = conn.execute(
- select(messages.c.id).where(messages.c.id == annotation["message_id"])
- ).scalar_one_or_none()
- visible = messages_service.list_session_messages(
- conn,
- session_id=session["id"],
- limit=50,
- types=messages_service.TRANSCRIPT_TYPES,
- tail=True,
- )["messages"]
- assert [row["id"] for row in queued] == [annotation["message_id"]]
- assert original_exists == annotation["message_id"]
- assert linked_message_id == annotation["message_id"]
- assert [row["text"] for row in visible] == ["older stopped message"]
-
- assert asyncio.run(manager.flush_queue(session["id"])) is True
+ assert runs[0][1] == annotation["delivery"]["dispatch_text"]
with engine.connect() as conn:
+ queued = message_deliveries.list_queued(conn, session["id"])
linked_message_id = conn.execute(
select(show_session_events.c.message_id).where(
show_session_events.c.id == annotation["id"]
)
).scalar_one()
- original_exists = conn.execute(
- select(messages.c.id).where(messages.c.id == annotation["message_id"])
- ).scalar_one_or_none()
visible = messages_service.list_session_messages(
conn,
session_id=session["id"],
@@ -1725,17 +1800,14 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(
types=messages_service.TRANSCRIPT_TYPES,
tail=True,
)["messages"]
- assert [run[1] for run in runs] == [
- "older stopped message",
- annotation["message"]["metadata"][
- session_turns.QUEUED_DISPATCH_TEXT_KEY
- ],
- ]
- assert original_exists is None
- assert linked_message_id == visible[1]["id"]
- assert visible[1]["type"] == messages_service.ANNOTATION_TYPE
- assert visible[1]["author_name"] == "show_annotation"
- assert visible[1]["native_message_id"] == f"show:{annotation['id']}"
+ assert [row["id"] for row in queued] == [older["id"]]
+ assert linked_message_id == annotation["delivery_id"]
+ assert [row["text"] for row in visible] == [annotation["transcript_text"]]
+ assert visible[0]["id"] == annotation["delivery_id"]
+ assert visible[0]["type"] == messages_service.ANNOTATION_TYPE
+ assert visible[0]["author_name"] == "show_annotation"
+ assert visible[0]["native_message_id"] == f"show:{annotation['id']}"
+ assert asyncio.run(manager.flush_queue(session["id"])) is False
def test_flush_promoted_user_row_uses_fresh_id_for_same_second_order(
@@ -1743,26 +1815,30 @@ def test_flush_promoted_user_row_uses_fresh_id_for_same_second_order(
monkeypatch,
):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr(
+ message_deliveries,
+ "new_delivery_id",
+ lambda: "msg_000000000000200aaaaaaaa",
+ )
session_id = _seed_avibe_session_with_queue([("queued follow-up", None)])
from sqlalchemy import update
from storage import messages_service
from storage.db import create_sqlite_engine
- from storage.models import messages
+ from storage.models import message_deliveries as delivery_rows, messages
with create_sqlite_engine().begin() as conn:
- queued = messages_service.list_queued(conn, session_id)[0]
+ queued = message_deliveries.list_queued(conn, session_id)[0]
queued_id = queued["id"]
conn.execute(
- update(messages)
- .where(messages.c.id == queued["id"])
- .values(created_at="2026-06-22T00:00:36Z")
+ update(delivery_rows)
+ .where(delivery_rows.c.id == queued["id"])
+ .values(submitted_at="2026-06-22T00:00:37Z")
)
generated_ids = iter(
(
"msg_000000000000100aaaaaaaa",
- "msg_000000000000200aaaaaaaa",
"msg_000000000000300aaaaaaaa",
)
)
@@ -1796,8 +1872,24 @@ def test_flush_promoted_user_row_uses_fresh_id_for_same_second_order(
lambda event_type, data: published.append((event_type, data)),
)
- async def append_fast_result(sid, context, text, *, source=SOURCE_HUMAN):
+ async def append_fast_result(
+ sid,
+ context,
+ text,
+ *,
+ source=SOURCE_HUMAN,
+ logical_turn_id=None,
+ delivery_id=None,
+ **_kwargs,
+ ):
+ _bind_test_native_start(create_sqlite_engine(), context)
with create_sqlite_engine().begin() as conn:
+ accepted = message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=logical_turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+ assert accepted
messages_service.append(
conn,
scope_id=context.platform_specific.get("scope_id"),
@@ -1807,6 +1899,7 @@ def test_flush_promoted_user_row_uses_fresh_id_for_same_second_order(
message_type="result",
text="fast queued result",
)
+ manager._publish_materialized_delivery(delivery_id)
async def fail_if_sleeping(_delay):
pytest.fail("queue promotion must not wait for wall-clock time")
@@ -1836,7 +1929,7 @@ def test_flush_promoted_user_row_uses_fresh_id_for_same_second_order(
"msg_000000000000200aaaaaaaa",
"msg_000000000000300aaaaaaaa",
]
- assert queued_id not in {row["id"] for row in transcript["messages"]}
+ assert queued_id == "msg_000000000000200aaaaaaaa"
assert [
(event_type, data.get("id"))
for event_type, data in published
@@ -1846,7 +1939,7 @@ def test_flush_promoted_user_row_uses_fresh_id_for_same_second_order(
assert not hasattr(session_turns, "_wait_until_message_timestamp")
-def test_flush_promoted_user_row_repoints_canonical_and_merged_dependencies(
+def test_flush_materializes_exact_head_and_links_delivery_dependencies(
tmp_path,
monkeypatch,
):
@@ -1860,14 +1953,14 @@ def test_flush_promoted_user_row_repoints_canonical_and_merged_dependencies(
from storage import messages_service
from storage.db import create_sqlite_engine
- from storage.models import media_objects, messages, show_session_events
+ from storage.models import show_session_events
engine = create_sqlite_engine()
with engine.begin() as conn:
- queued = messages_service.list_queued(conn, session_id)
- canonical_id = queued[0]["id"]
- merged_id = queued[1]["id"]
- for index, message_id in enumerate((canonical_id, merged_id), start=1):
+ queued = message_deliveries.list_queued(conn, session_id)
+ head_id = queued[0]["id"]
+ second_id = queued[1]["id"]
+ for index, delivery_id in enumerate((head_id, second_id), start=1):
conn.execute(
show_session_events.insert().values(
id=f"show_evt_repoint_{index}",
@@ -1878,24 +1971,13 @@ def test_flush_promoted_user_row_repoints_canonical_and_merged_dependencies(
anchor_json="{}",
payload_json="{}",
transcript_text=f"annotation {index}",
- message_id=message_id,
- created_at=f"2026-06-22T00:00:0{index}Z",
- )
- )
- conn.execute(
- media_objects.insert().values(
- token=f"media_repoint_{index}",
- scope_id=queued[index - 1]["scope_id"],
- session_id=session_id,
- message_id=message_id,
- kind="file",
- source="user_upload",
- local_path=f"/tmp/repoint-{index}.txt",
+ message_id=None,
+ delivery_id=delivery_id,
created_at=f"2026-06-22T00:00:0{index}Z",
)
)
- manager, _runs = _manager_capturing_runs()
+ manager, _runs = _manager_accepting_runs()
assert asyncio.run(manager.flush_queue(session_id)) is True
with engine.connect() as conn:
@@ -1909,22 +1991,15 @@ def test_flush_promoted_user_row_repoints_canonical_and_merged_dependencies(
show_session_events.c.id
)
).scalars().all()
- media_message_ids = conn.execute(
- select(media_objects.c.message_id).order_by(media_objects.c.token)
- ).scalars().all()
- old_ids = conn.execute(
- select(messages.c.id).where(messages.c.id.in_((canonical_id, merged_id)))
- ).scalars().all()
+ queued_ids = [row["id"] for row in message_deliveries.list_queued(conn, session_id)]
assert len(visible) == 1
- visible_id = visible[0]["id"]
- assert visible_id not in {canonical_id, merged_id}
- assert event_message_ids == [visible_id, visible_id]
- assert media_message_ids == [visible_id, visible_id]
- assert old_ids == []
+ assert visible[0]["id"] == head_id
+ assert event_message_ids == [head_id, head_id]
+ assert queued_ids == []
-def test_flush_keeps_independently_identified_user_rows_as_separate_turns(
+def test_flush_claims_compatible_user_rows_as_one_turn_and_one_message(
tmp_path,
monkeypatch,
):
@@ -1936,22 +2011,15 @@ def test_flush_keeps_independently_identified_user_rows_as_separate_turns(
]
)
- from sqlalchemy import update
-
from storage import messages_service
from storage.db import create_sqlite_engine
- from storage.models import messages, show_session_events
+ from storage.models import show_session_events
engine = create_sqlite_engine()
with engine.begin() as conn:
- queued = messages_service.list_queued(conn, session_id)
+ queued = message_deliveries.list_queued(conn, session_id)
for index, row in enumerate(queued, start=1):
event_id = f"show_evt_identity_{index}"
- conn.execute(
- update(messages)
- .where(messages.c.id == row["id"])
- .values(native_message_id=f"show:{event_id}")
- )
conn.execute(
show_session_events.insert().values(
id=event_id,
@@ -1962,13 +2030,13 @@ def test_flush_keeps_independently_identified_user_rows_as_separate_turns(
anchor_json="{}",
payload_json="{}",
transcript_text=row["text"],
- message_id=row["id"],
+ message_id=None,
+ delivery_id=row["id"],
created_at=f"2026-06-22T00:00:0{index}Z",
)
)
- manager, runs = _manager_capturing_runs()
- assert asyncio.run(manager.flush_queue(session_id)) is True
+ manager, runs = _manager_accepting_runs()
assert asyncio.run(manager.flush_queue(session_id)) is True
with engine.connect() as conn:
@@ -1984,23 +2052,17 @@ def test_flush_keeps_independently_identified_user_rows_as_separate_turns(
).all()
assert [text for text, _source, _context in runs] == [
- "first show annotation",
- "second show annotation",
- ]
- assert [row["native_message_id"] for row in visible] == [
- "show:show_evt_identity_1",
- "show:show_evt_identity_2",
+ "first show annotation\nsecond show annotation"
]
+ assert len(visible) == 1
assert event_links == [
("show_evt_identity_1", visible[0]["id"]),
- ("show_evt_identity_2", visible[1]["id"]),
+ ("show_evt_identity_2", visible[0]["id"]),
]
-def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):
- """When a turn ends, messages queued (send-while-busy) during it are popped,
- merged (newline-joined) into ONE user row, and run as the next turn —
- draining the queue. Exercises the controller-side flush wiring end to end."""
+def test_async_dispatch_flushes_one_compatible_queue_segment_on_turn_end(monkeypatch, tmp_path):
+ """Natural settlement combines the compatible FIFO segment into one Turn."""
from core.services import sessions as sessions_service
from storage import messages_service
from storage.db import create_sqlite_engine
@@ -2018,6 +2080,12 @@ def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):
session = sessions_service.create_session(
conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
)
+ first = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ text="first turn",
+ )
session_id = session["id"]
seen_texts: list[str] = []
@@ -2028,27 +2096,26 @@ def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):
# real flow — queued rows only exist during an active turn).
if text == "first turn":
with engine.begin() as conn:
- messages_service.append(
+ message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id=session_id,
platform="avibe",
author="user",
source="user",
- message_type=messages_service.QUEUED_TYPE,
text="q1",
author_id="remote:user-a",
metadata={"_web_push_user_key": "remote:user-a"},
)
- messages_service.append(
+ message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id=session_id,
platform="avibe",
author="user",
source="user",
- message_type=messages_service.QUEUED_TYPE,
text="q2",
+ author_id="remote:user-a",
)
controller.mark_turn_complete(ctx) # release each turn immediately
return None
@@ -2059,7 +2126,14 @@ def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):
async def _go():
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- await client.post("/internal/dispatch_async", json={"session_id": session_id, "text": "first turn"})
+ await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session_id,
+ "text": "first turn",
+ "user_message_id": first["id"],
+ },
+ )
# Wait for the first turn AND the flush turn to both drain the queue.
for _ in range(200):
if len(seen_texts) >= 2 and session_id not in app.state.in_flight_dispatches:
@@ -2067,14 +2141,13 @@ def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):
await asyncio.sleep(0.02)
asyncio.run(_go())
- # First the user's turn, then ONE merged flush turn for the two queued msgs.
assert seen_texts == ["first turn", "q1\nq2"]
with engine.connect() as conn:
- assert messages_service.list_queued(conn, session_id) == []
+ assert message_deliveries.list_queued(conn, session_id) == []
transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
- assert [m["text"] for m in transcript["messages"]] == ["q1\nq2"], "the flush persisted one merged user row"
- assert transcript["messages"][0]["author_id"] == "remote:user-a"
- assert transcript["messages"][0]["metadata"]["_web_push_user_key"] == "remote:user-a"
+ assert [m["text"] for m in transcript["messages"]] == ["first turn", "q1\nq2"]
+ assert transcript["messages"][1]["author_id"] == "remote:user-a"
+ assert transcript["messages"][1]["metadata"]["_web_push_user_key"] == "remote:user-a"
def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):
@@ -2098,15 +2171,21 @@ def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):
session = sessions_service.create_session(
conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
)
+ first = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ text="first",
+ )
session_id = session["id"]
started = asyncio.Event()
async def long_handler(ctx, text):
+ _bind_test_native_start(engine, ctx)
started.set()
await asyncio.sleep(5) # held until the test cancels it
return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
- return None
controller = _build_controller_double(handler=long_handler)
app = internal_server.create_app(controller)
@@ -2114,11 +2193,18 @@ def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):
async def _go():
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- await client.post("/internal/dispatch_async", json={"session_id": session_id, "text": "first"})
+ await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session_id,
+ "text": "first",
+ "user_message_id": first["id"],
+ },
+ )
await asyncio.wait_for(started.wait(), timeout=3)
# Queue a message while the turn runs, then Stop.
with engine.begin() as conn:
- messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q1")
+ message_deliveries.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q1")
await client.post(f"/internal/cancel/{session_id}")
for _ in range(200):
if session_id not in app.state.in_flight_dispatches:
@@ -2127,10 +2213,10 @@ def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):
asyncio.run(_go())
with engine.connect() as conn:
- queued = messages_service.list_queued(conn, session_id)
+ queued = message_deliveries.list_queued(conn, session_id)
transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
assert [q["text"] for q in queued] == ["q1"], "Stop must keep the queue intact"
- assert transcript["messages"] == [], "Stop must not flush the queue into a turn"
+ assert [row["text"] for row in transcript["messages"]] == ["first"]
def test_turn_state_reflects_in_flight():
@@ -2166,7 +2252,38 @@ def test_turn_state_reflects_in_flight():
assert busy["backend"] == "opencode"
-def test_cancel_returns_404_when_session_not_in_flight():
+def test_turn_state_projects_a_restored_durable_owner_without_in_flight(
+ tmp_path,
+ monkeypatch,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _engine, session, turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="restored-turn-state",
+ backend="opencode",
+ )
+ app = internal_server.create_app(_build_controller_double())
+ transport = httpx.ASGITransport(app=app)
+
+ async def _go():
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return (await client.get(f"/internal/turn-state/{session['id']}")).json()
+
+ state = asyncio.run(_go())
+ assert state["in_flight"] is True
+ assert state["foreground"] == "running"
+ assert state["native_turn_started"] is True
+ assert state["backend"] == "opencode"
+ assert state["owner"]["runtime_key"] == f"runtime:{session['id']}"
+ assert state["owner"]["native_turn_started"] is True
+ assert turn_id
+
+
+def test_cancel_returns_404_when_session_not_in_flight(tmp_path, monkeypatch):
+ from storage.importer import ensure_sqlite_state
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
app = internal_server.create_app(_build_controller_double())
transport = httpx.ASGITransport(app=app)
@@ -2181,7 +2298,13 @@ def test_cancel_returns_404_when_session_not_in_flight():
assert body["code"] == "not_in_flight"
-def test_cancel_releases_stale_turn_when_backend_not_active():
+def test_cancel_releases_stale_turn_when_backend_not_active(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session, turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_stale_cancel",
+ )
+ session_id = session["id"]
controller = _build_controller_double()
app = internal_server.create_app(controller)
transport = httpx.ASGITransport(app=app)
@@ -2195,9 +2318,13 @@ def test_cancel_releases_stale_turn_when_backend_not_active():
user_id="U",
channel_id="C",
platform="avibe",
- platform_specific={"agent_session_id": "ses_stale"},
+ platform_specific={"agent_session_id": session_id},
+ )
+ app.state.in_flight_dispatches[session_id] = session_turns.Turn(
+ task=task,
+ context=context,
+ logical_turn_id=turn_id,
)
- app.state.in_flight_dispatches["ses_stale"] = session_turns.Turn(task=task, context=context)
async def _not_active(_context):
notices.append(_context.platform_specific.get("suppress_stop_no_active_notice"))
@@ -2206,9 +2333,9 @@ def test_cancel_releases_stale_turn_when_backend_not_active():
controller.command_handler.handle_stop = AsyncMock(side_effect=_not_active)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- resp = await client.post("/internal/cancel/ses_stale")
+ resp = await client.post(f"/internal/cancel/{session_id}")
for _ in range(200):
- if "ses_stale" not in app.state.in_flight_dispatches:
+ if session_id not in app.state.in_flight_dispatches:
break
await asyncio.sleep(0.02)
return resp, task
@@ -2219,12 +2346,25 @@ def test_cancel_releases_stale_turn_when_backend_not_active():
assert body["status"] == "stale_released"
assert body["reason"] == "not_active"
assert task.cancelled()
- assert "ses_stale" not in app.state.in_flight_dispatches
- assert statuses == [("ses_stale", "idle")]
+ assert session_id not in app.state.in_flight_dispatches
+ assert statuses == []
+ from storage.models import agent_sessions
+
+ with engine.connect() as conn:
+ status = conn.execute(
+ select(agent_sessions.c.agent_status).where(agent_sessions.c.id == session_id)
+ ).scalar_one()
+ assert status == "idle"
assert notices == [True]
-def test_cancel_waits_for_stale_dispatch_cleanup_before_releasing():
+def test_cancel_waits_for_stale_dispatch_cleanup_before_releasing(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _engine, session, turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_stale_cleanup",
+ )
+ session_id = session["id"]
controller = _build_controller_double()
app = internal_server.create_app(controller)
transport = httpx.ASGITransport(app=app)
@@ -2238,7 +2378,7 @@ def test_cancel_waits_for_stale_dispatch_cleanup_before_releasing():
user_id="U",
channel_id="C",
platform="avibe",
- platform_specific={"agent_session_id": "ses_stale_cleanup"},
+ platform_specific={"agent_session_id": session_id},
)
async def _stale_dispatch():
@@ -2261,7 +2401,11 @@ def test_cancel_waits_for_stale_dispatch_cleanup_before_releasing():
break
await asyncio.sleep(0.01)
assert controller.get_turn_sink("avibe::C") is not None
- app.state.in_flight_dispatches["ses_stale_cleanup"] = session_turns.Turn(task=task, context=context)
+ app.state.in_flight_dispatches[session_id] = session_turns.Turn(
+ task=task,
+ context=context,
+ logical_turn_id=turn_id,
+ )
async def _not_active(_context):
_context.platform_specific["stop_failure_reason"] = "not_active"
@@ -2269,11 +2413,11 @@ def test_cancel_waits_for_stale_dispatch_cleanup_before_releasing():
controller.command_handler.handle_stop = AsyncMock(side_effect=_not_active)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- cancel_task = asyncio.create_task(client.post("/internal/cancel/ses_stale_cleanup"))
+ cancel_task = asyncio.create_task(client.post(f"/internal/cancel/{session_id}"))
await asyncio.wait_for(cleanup_started.wait(), timeout=1)
await asyncio.sleep(0.02)
assert not cancel_task.done()
- assert "ses_stale_cleanup" in app.state.in_flight_dispatches
+ assert session_id in app.state.in_flight_dispatches
allow_cleanup.set()
resp = await cancel_task
return resp, task
@@ -2285,7 +2429,13 @@ def test_cancel_waits_for_stale_dispatch_cleanup_before_releasing():
assert controller.get_turn_sink("avibe::C") is None
-def test_cancel_keeps_turn_when_backend_interrupt_failed():
+def test_cancel_keeps_turn_when_backend_interrupt_failed(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _engine, session, turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_failed_stop",
+ )
+ session_id = session["id"]
controller = _build_controller_double()
app = internal_server.create_app(controller)
transport = httpx.ASGITransport(app=app)
@@ -2296,9 +2446,13 @@ def test_cancel_keeps_turn_when_backend_interrupt_failed():
user_id="U",
channel_id="C",
platform="avibe",
- platform_specific={"agent_session_id": "ses_failed_stop"},
+ platform_specific={"agent_session_id": session_id},
+ )
+ app.state.in_flight_dispatches[session_id] = session_turns.Turn(
+ task=task,
+ context=context,
+ logical_turn_id=turn_id,
)
- app.state.in_flight_dispatches["ses_failed_stop"] = session_turns.Turn(task=task, context=context)
async def _interrupt_failed(_context):
_context.platform_specific["stop_failure_reason"] = "interrupt_failed"
@@ -2306,8 +2460,8 @@ def test_cancel_keeps_turn_when_backend_interrupt_failed():
controller.command_handler.handle_stop = AsyncMock(side_effect=_interrupt_failed)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- resp = await client.post("/internal/cancel/ses_failed_stop")
- held = "ses_failed_stop" in app.state.in_flight_dispatches and not task.done()
+ resp = await client.post(f"/internal/cancel/{session_id}")
+ held = session_id in app.state.in_flight_dispatches and not task.done()
task.cancel()
return resp, held
@@ -2315,8 +2469,8 @@ def test_cancel_keeps_turn_when_backend_interrupt_failed():
assert resp.status_code == 409
body = resp.json()
assert body["ok"] is False
- assert body["code"] == "stop_failed"
- assert body["reason"] == "interrupt_failed"
+ assert body["code"] == "stop_unknown"
+ assert body["reason"] == "stop_unknown"
assert held is True
@@ -2394,19 +2548,26 @@ def test_release_for_backend_refresh_leaves_other_backend_turn_running():
assert statuses == []
-def test_backend_drain_queues_idle_session_without_dispatching():
+def test_backend_drain_queues_idle_session_without_dispatching(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_backend_drain",
+ backend="codex",
+ )
+ session_id = session["id"]
controller = _build_controller_double()
manager = session_turns.SessionTurnManager(controller)
- enqueue = Mock(return_value=True)
- context = MessageContext(user_id="U", channel_id="ses_codex", platform="avibe")
+ context = MessageContext(user_id="U", channel_id=session_id, platform="avibe")
context.platform_specific = {
- "agent_session_id": "ses_codex",
+ "agent_session_id": session_id,
+ "scope_id": session["scope_id"],
"agent_session_target": {"agent_backend": "codex"},
}
async def _go():
manager.begin_backend_drain("codex")
- return await manager.submit("ses_codex", context, "next", enqueue=enqueue)
+ return await manager.submit(session_id, context, "next")
result = asyncio.run(_go())
@@ -2414,57 +2575,128 @@ def test_backend_drain_queues_idle_session_without_dispatching():
route="enqueued",
queue_persisted=True,
)
- enqueue.assert_called_once_with()
- assert manager.is_in_flight("ses_codex") is False
- assert manager._deferred_restart_sessions == {"codex": {"ses_codex"}}
+ with engine.connect() as conn:
+ assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == ["next"]
+ assert manager.is_in_flight(session_id) is False
+ assert manager._deferred_restart_sessions == {"codex": {session_id}}
+
+
+def test_backend_drain_queues_pre_reserved_idle_submission_before_resume(
+ tmp_path,
+ monkeypatch,
+):
+ """A Web-reserved Delivery becomes claimable before the backend drain ends."""
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_backend_drain_reserved",
+ backend="codex",
+ )
+ session_id = session["id"]
+ with engine.begin() as conn:
+ reserved = _reserve_submission(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ text="reserved during refresh",
+ )
-def test_backend_drain_exposes_failed_queue_persistence():
controller = _build_controller_double()
manager = session_turns.SessionTurnManager(controller)
- enqueue = Mock(return_value=False)
- context = MessageContext(user_id="U", channel_id="ses_codex", platform="avibe")
- context.platform_specific = {
- "agent_session_id": "ses_codex",
- "agent_session_target": {"agent_backend": "codex"},
- }
+ manager._start_persisted_turn = AsyncMock(return_value=None)
+ context = MessageContext(
+ user_id="U",
+ channel_id=session_id,
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": session_id,
+ "scope_id": session["scope_id"],
+ "delivery_id": reserved["id"],
+ "agent_session_target": {"agent_backend": "codex"},
+ },
+ )
async def _go():
manager.begin_backend_drain("codex")
- return await manager.submit("ses_codex", context, "next", enqueue=enqueue)
+ admitted = await manager.submit(
+ session_id,
+ context,
+ "reserved during refresh",
+ )
+ with engine.connect() as conn:
+ queued = message_deliveries.get_delivery(conn, reserved["id"])
+ await manager.end_backend_drain("codex")
+ return admitted, queued
- result = asyncio.run(_go())
+ admitted, queued = asyncio.run(_go())
- assert result == session_turns.TurnSubmissionResult(
+ assert admitted == session_turns.TurnSubmissionResult(
route="enqueued",
- queue_persisted=False,
+ queue_persisted=True,
+ )
+ assert queued is not None and queued["state"] == "queued"
+ manager._start_persisted_turn.assert_awaited_once()
+
+
+def test_backend_drain_exposes_failed_queue_persistence(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_backend_drain_failure",
+ backend="codex",
+ )
+ session_id = session["id"]
+ controller = _build_controller_double()
+ manager = session_turns.SessionTurnManager(controller)
+ context = MessageContext(user_id="U", channel_id=session_id, platform="avibe")
+ context.platform_specific = {
+ "agent_session_id": session_id,
+ "scope_id": session["scope_id"],
+ "agent_session_target": {"agent_backend": "codex"},
+ }
+ monkeypatch.setattr(
+ manager,
+ "_insert_delivery",
+ Mock(side_effect=RuntimeError("queue persistence failed")),
)
- enqueue.assert_called_once_with()
- assert manager.is_in_flight("ses_codex") is False
+
+ async def _go():
+ manager.begin_backend_drain("codex")
+ return await manager.submit(session_id, context, "next")
+
+ with pytest.raises(RuntimeError, match="queue persistence failed"):
+ asyncio.run(_go())
+ assert manager.is_in_flight(session_id) is False
-def test_backend_drain_resolves_inherited_default_agent_backend():
+def test_backend_drain_resolves_inherited_default_agent_backend(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_backend_drain_default",
+ backend="codex",
+ )
+ session_id = session["id"]
controller = _build_controller_double()
controller.resolve_agent_for_context = Mock(return_value="codex")
manager = session_turns.SessionTurnManager(controller)
- enqueue = Mock(return_value=True)
- context = MessageContext(user_id="U", channel_id="ses_default", platform="avibe")
+ context = MessageContext(user_id="U", channel_id=session_id, platform="avibe")
context.platform_specific = {
- "agent_session_id": "ses_default",
+ "agent_session_id": session_id,
+ "scope_id": session["scope_id"],
"agent_session_target": {"agent_name": None, "agent_backend": None},
}
async def _go():
manager.begin_backend_drain("codex")
- return await manager.submit("ses_default", context, "next", enqueue=enqueue)
+ return await manager.submit(session_id, context, "next")
assert asyncio.run(_go()) == session_turns.TurnSubmissionResult(
route="enqueued",
queue_persisted=True,
)
- enqueue.assert_called_once_with()
- controller.resolve_agent_for_context.assert_called_once_with(context)
- assert manager._deferred_restart_sessions == {"codex": {"ses_default"}}
+ assert manager._deferred_restart_sessions == {"codex": {session_id}}
def test_backend_drain_flushes_deferred_session_after_cutover():
@@ -2480,44 +2712,84 @@ def test_backend_drain_flushes_deferred_session_after_cutover():
assert "codex" not in manager._draining_backends
-def test_backend_drain_blocks_direct_queue_flush():
+def test_backend_drain_blocks_direct_queue_flush(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_direct_drain",
+ backend="codex",
+ )
+ session_id = session["id"]
+ with engine.begin() as conn:
+ message_deliveries.enqueue_queued(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ text="queued",
+ )
controller = _build_controller_double()
- context = MessageContext(user_id="U", channel_id="ses_codex", platform="avibe")
+ context = MessageContext(user_id="U", channel_id=session_id, platform="avibe")
context.platform_specific = {
- "agent_session_id": "ses_codex",
+ "agent_session_id": session_id,
"agent_session_target": {"agent_backend": "codex"},
}
manager = session_turns.SessionTurnManager(controller, build_context=lambda _session_id: context)
manager._run = AsyncMock() # type: ignore[method-assign]
manager.begin_backend_drain("codex")
- assert asyncio.run(manager.flush_queue("ses_codex")) is False
+ assert asyncio.run(manager.flush_queue(session_id)) is False
manager._run.assert_not_awaited()
- assert manager._deferred_restart_sessions == {"codex": {"ses_codex"}}
+ with engine.connect() as conn:
+ assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == ["queued"]
+ assert manager._deferred_restart_sessions == {"codex": {session_id}}
-def test_stop_during_backend_drain_keeps_existing_queue_parked():
+def test_stop_during_backend_drain_keeps_existing_queue_parked(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session, turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_stop_drain",
+ backend="codex",
+ )
+ session_id = session["id"]
+ with engine.begin() as conn:
+ message_deliveries.enqueue_queued(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ text="queued",
+ )
controller = _build_controller_double()
manager = session_turns.SessionTurnManager(controller)
- context = MessageContext(user_id="U", channel_id="ses_codex", platform="avibe")
+ context = MessageContext(user_id="U", channel_id=session_id, platform="avibe")
context.platform_specific = {
- "agent_session_id": "ses_codex",
+ "agent_session_id": session_id,
"agent_session_target": {"agent_backend": "codex"},
}
async def _go():
task = asyncio.create_task(asyncio.sleep(60))
- manager.in_flight["ses_codex"] = session_turns.Turn(task=task, context=context)
+ manager.in_flight[session_id] = session_turns.Turn(
+ task=task,
+ context=context,
+ logical_turn_id=turn_id,
+ )
manager.begin_backend_drain("codex")
- manager._deferred_restart_sessions["codex"].add("ses_codex")
- result = await manager.cancel("ses_codex")
+ manager._deferred_restart_sessions["codex"].add(session_id)
+ result = await manager.cancel(session_id)
+ held = not task.done()
+ task.cancel()
await asyncio.gather(task, return_exceptions=True)
- return result
+ return result, held
- result = asyncio.run(_go())
+ result, held = asyncio.run(_go())
assert result["status"] == "cancel_requested"
- assert manager._deferred_restart_sessions == {"codex": set()}
+ assert held is True
+ with engine.connect() as conn:
+ assert message_deliveries.queue_is_held(conn, session_id) is True
+ assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == ["queued"]
+ assert manager._deferred_restart_sessions == {"codex": {session_id}}
# ---------------------------------------------------------------------
@@ -2567,12 +2839,12 @@ def test_scheduled_gate_idle_runs_turn_with_lifecycle(monkeypatch, tmp_path):
for the scheduled turn's whole lifetime so a Chat send can't preempt a
still-running scheduled turn (Codex P2)."""
from core import inbox_events
- from storage.importer import ensure_sqlite_state
-
- # submit_scheduled reads the queue (idle → empty-queue happy path), so it
- # needs an initialized state DB.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- ensure_sqlite_state()
+ _engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_scheduled_idle",
+ )
+ session_id = session["id"]
captured: dict = {}
started = asyncio.Event()
@@ -2581,7 +2853,7 @@ def test_scheduled_gate_idle_runs_turn_with_lifecycle(monkeypatch, tmp_path):
captured["source"] = source
captured["on_chunk"] = on_chunk
captured["text"] = text
- captured["in_flight_while_running"] = "ses_sched" in app.state.in_flight_dispatches
+ captured["in_flight_while_running"] = session_id in app.state.in_flight_dispatches
started.set()
# The manager now branches on the outcome to settle a run whose turn ended
# without a terminal result, so a double has to return one.
@@ -2591,16 +2863,24 @@ def test_scheduled_gate_idle_runs_turn_with_lifecycle(monkeypatch, tmp_path):
controller = _build_controller_double()
app = internal_server.create_app(controller)
- ctx = MessageContext(user_id="workbench", channel_id="ses_sched", platform="avibe")
+ ctx = MessageContext(
+ user_id="workbench",
+ channel_id=session_id,
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": session_id,
+ "agent_session_target": {"agent_backend": "claude"},
+ },
+ )
async def _go():
sub_id, queue = inbox_events.bus.subscribe()
events: list[str] = []
try:
- await controller.session_turn_gate.submit_scheduled("ses_sched", ctx, "digest please")
+ await controller.session_turn_gate.submit_scheduled(session_id, ctx, "digest please")
await asyncio.wait_for(started.wait(), timeout=3)
for _ in range(100):
- if "ses_sched" not in app.state.in_flight_dispatches:
+ if session_id not in app.state.in_flight_dispatches:
break
await asyncio.sleep(0.02)
for _ in range(2):
@@ -2624,7 +2904,7 @@ def test_scheduled_gate_idle_runs_turn_with_lifecycle(monkeypatch, tmp_path):
assert captured["text"] == "digest please"
assert captured["in_flight_while_running"] is True, "registered in_flight (Stop works) while running"
assert events == ["turn.start", "turn.end"], "publishes the session turn lifecycle on the bus"
- assert "ses_sched" not in app.state.in_flight_dispatches, "slot released after the turn"
+ assert session_id not in app.state.in_flight_dispatches, "slot released after the turn"
def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatch, tmp_path):
@@ -2632,23 +2912,15 @@ def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatch
harness-attributed ``queued`` row (so it runs AFTER the active turn via the
existing flush) instead of preempting it — and it never starts a competing
turn nor disturbs the in-flight Chat task (Codex P2)."""
- from core.services import sessions as sessions_service
+ from core.inbox_events import bus
from storage import messages_service
- from storage.db import create_sqlite_engine
- from storage.importer import ensure_sqlite_state
- from storage.settings_service import upsert_scope
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- ensure_sqlite_state()
- engine = create_sqlite_engine()
- with engine.begin() as conn:
- scope_id = upsert_scope(
- conn, platform="avibe", scope_type="project", native_id="proj_sched_busy", now="2026-05-31T00:00:00Z"
- )
- _seed_project_workdir(conn, scope_id, tmp_path)
- session = sessions_service.create_session(
- conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
- )
+ engine, session, owner_turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_sched_busy",
+ )
+ scope_id = session["scope_id"]
session_id = session["id"]
# A scheduled run must NEVER reach dispatch_turn while busy — a call here fails
@@ -2657,6 +2929,12 @@ def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatch
raise AssertionError("a busy scheduled run must enqueue, not dispatch a turn")
monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _explode_dispatch_turn)
+ published: list[tuple[str, dict]] = []
+ monkeypatch.setattr(
+ bus,
+ "publish",
+ lambda event, payload: published.append((event, payload)),
+ )
controller = _build_controller_double()
app = internal_server.create_app(controller)
@@ -2668,7 +2946,11 @@ def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatch
chat_task = asyncio.create_task(_busy())
chat_ctx = MessageContext(user_id="U", channel_id="C", platform="avibe")
- app.state.in_flight_dispatches[session_id] = session_turns.Turn(task=chat_task, context=chat_ctx)
+ app.state.in_flight_dispatches[session_id] = session_turns.Turn(
+ task=chat_task,
+ context=chat_ctx,
+ logical_turn_id=owner_turn_id,
+ )
try:
await controller.session_turn_gate.submit_scheduled(session_id, ctx, "scheduled while busy")
finally:
@@ -2681,26 +2963,26 @@ def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatch
chat_ctx = asyncio.run(_go())
controller.message_handler.handle_user_message.assert_not_awaited()
with engine.connect() as conn:
- queued = messages_service.list_queued(conn, session_id)
+ queued = message_deliveries.list_queued(conn, session_id)
# The queued row is drainable + carries the session's scope and harness
# attribution; it stays OUT of the user transcript.
transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
assert [q["text"] for q in queued] == ["scheduled while busy"]
assert queued[0]["scope_id"] == scope_id
assert queued[0]["author"] == "harness"
- assert transcript["messages"] == []
+ assert [row["text"] for row in transcript["messages"]] == ["active owner"]
+ assert ("queue.updated", {"session_id": session_id}) in published
def test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head(monkeypatch, tmp_path):
"""HFR-430 — Agent-to-Agent send-now reuses the Workbench turn transition.
The Agent Run row and queued message must exist before Stop is attempted. The
- active turn is then canceled once, and its ``flush_on_cancel`` finally starts
+ active turn is then canceled once, and the durable successor claim starts
the durable Agent Run as a new scheduled turn.
"""
from core.scheduled_tasks import TaskExecutionStore
from core.services import sessions as sessions_service
- from storage import messages_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.settings_service import upsert_scope
@@ -2723,6 +3005,12 @@ def test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head(monkeypatch
agent_backend="claude",
agent_name="worker",
)["id"]
+ original = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ text="original work",
+ )
request_store = TaskExecutionStore()
request = request_store.enqueue_agent_run(
@@ -2740,6 +3028,7 @@ def test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head(monkeypatch
async def _dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):
seen.append((text, source))
if text == "original work":
+ _bind_test_native_start(engine, ctx)
original_started.set()
try:
await asyncio.sleep(60)
@@ -2755,11 +3044,23 @@ def test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head(monkeypatch
app = internal_server.create_app(controller)
transport = httpx.ASGITransport(app=app)
+ async def _stop_original(_context):
+ active = app.state.in_flight_dispatches.get(session_id)
+ assert active is not None
+ active.task.cancel()
+ return True
+
+ controller.command_handler.handle_stop.side_effect = _stop_original
+
async def _go():
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
response = await client.post(
"/internal/dispatch_async",
- json={"session_id": session_id, "text": "original work"},
+ json={
+ "session_id": session_id,
+ "text": "original work",
+ "user_message_id": original["id"],
+ },
)
assert response.status_code == 202
await asyncio.wait_for(original_started.wait(), timeout=3)
@@ -2794,8 +3095,8 @@ def test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head(monkeypatch
route="enqueued",
queue_persisted=True,
target_was_busy=True,
- delivery_status="interrupted",
- queue_owner_transferred=True,
+ delivery_status="waiting_terminal",
+ delivery_owner_transferred=True,
)
controller.command_handler.handle_stop.assert_awaited_once()
assert seen == [
@@ -2803,12 +3104,12 @@ def test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head(monkeypatch
("apply the correction", SOURCE_SCHEDULED),
]
with engine.connect() as conn:
- assert messages_service.list_queued(conn, session_id) == []
+ assert message_deliveries.list_queued(conn, session_id) == []
stored = request_store.get_run(request.id)
assert stored is not None
assert stored["metadata"]["delivery_outcome"] == {
"intent": "send_now",
- "status": "interrupted",
+ "status": "waiting_terminal",
"target_was_busy": True,
}
@@ -2816,30 +3117,12 @@ def test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head(monkeypatch
def test_agent_run_send_now_refusal_keeps_the_turn_and_queue(monkeypatch, tmp_path):
"""A refused interrupt is truthful and leaves both durable owners untouched."""
from core.scheduled_tasks import TaskExecutionStore
- from core.services import sessions as sessions_service
- from storage import messages_service
- from storage.db import create_sqlite_engine
- from storage.importer import ensure_sqlite_state
- from storage.settings_service import upsert_scope
-
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- ensure_sqlite_state()
- engine = create_sqlite_engine()
- with engine.begin() as conn:
- scope_id = upsert_scope(
- conn,
- platform="avibe",
- scope_type="project",
- native_id="proj_agent_send_now_refused",
- now="2026-07-30T00:00:00Z",
- )
- _seed_project_workdir(conn, scope_id, tmp_path)
- session_id = sessions_service.create_session(
- conn,
- scope_id=scope_id,
- agent_backend="claude",
- agent_name="worker",
- )["id"]
+ engine, session, owner_turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_agent_send_now_refused",
+ )
+ session_id = session["id"]
request_store = TaskExecutionStore()
request = request_store.enqueue_agent_run(
@@ -2850,7 +3133,12 @@ def test_agent_run_send_now_refusal_keeps_the_turn_and_queue(monkeypatch, tmp_pa
)
assert request_store.claim(request.id) is not None
controller = _build_controller_double()
- controller.command_handler.handle_stop = AsyncMock(return_value=False)
+
+ async def _refuse_stop(context):
+ context.platform_specific["stop_failure_reason"] = "refused"
+ return False
+
+ controller.command_handler.handle_stop = AsyncMock(side_effect=_refuse_stop)
app = internal_server.create_app(controller)
async def _go():
@@ -2858,6 +3146,7 @@ def test_agent_run_send_now_refusal_keeps_the_turn_and_queue(monkeypatch, tmp_pa
app.state.in_flight_dispatches[session_id] = session_turns.Turn(
task=task,
context=MessageContext(user_id="U", channel_id=session_id, platform="avibe"),
+ logical_turn_id=owner_turn_id,
)
context = MessageContext(
user_id="workbench",
@@ -2889,27 +3178,32 @@ def test_agent_run_send_now_refusal_keeps_the_turn_and_queue(monkeypatch, tmp_pa
route="enqueued",
queue_persisted=True,
target_was_busy=True,
- delivery_status="stop_failed",
- queue_owner_transferred=True,
+ delivery_status="queued",
+ delivery_owner_transferred=True,
)
assert held is True
with engine.connect() as conn:
- assert [row["text"] for row in messages_service.list_queued(conn, session_id)] == [
+ queued = message_deliveries.list_queued(conn, session_id)
+ assert [row["text"] for row in queued] == [
"keep this queued"
]
stored = request_store.get_run(request.id)
assert stored is not None
- assert stored["status"] == "queued"
- assert stored["metadata"]["workbench_queue_holds_run"] is True
+ assert stored["status"] == "running"
+ assert stored["delivery_id"] == queued[0]["id"]
+ assert "workbench_queue_holds_run" not in stored["metadata"]
assert stored["metadata"]["delivery_outcome"] == {
"intent": "send_now",
- "status": "stop_failed",
+ "status": "queued",
"target_was_busy": True,
}
-def test_concurrent_agent_run_send_now_callers_share_one_interrupt(monkeypatch, tmp_path):
- """Two admitted Runs share one Stop and keep FIFO order under real overlap."""
+def test_concurrent_agent_run_send_now_callers_share_one_interrupt_and_drain_fifo(
+ monkeypatch,
+ tmp_path,
+):
+ """Two admitted Runs share one Stop, then drain the joined FIFO in order."""
from core.scheduled_tasks import TaskExecutionStore
from core.services import sessions as sessions_service
from storage import messages_service
@@ -2935,6 +3229,12 @@ def test_concurrent_agent_run_send_now_callers_share_one_interrupt(monkeypatch,
agent_backend="claude",
agent_name="worker",
)["id"]
+ original = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ text="original work",
+ )
request_store = TaskExecutionStore()
requests = [
@@ -2957,6 +3257,7 @@ def test_concurrent_agent_run_send_now_callers_share_one_interrupt(monkeypatch,
async def _dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):
seen.append(text)
+ _bind_test_native_start(engine, ctx)
if text == "original work":
original_started.set()
try:
@@ -2972,6 +3273,9 @@ def test_concurrent_agent_run_send_now_callers_share_one_interrupt(monkeypatch,
async def _stop(_context):
stop_entered.set()
await release_stop.wait()
+ active = app.state.in_flight_dispatches.get(session_id)
+ assert active is not None
+ active.task.cancel()
return True
monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _dispatch)
@@ -2999,7 +3303,11 @@ def test_concurrent_agent_run_send_now_callers_share_one_interrupt(monkeypatch,
) as client:
response = await client.post(
"/internal/dispatch_async",
- json={"session_id": session_id, "text": "original work"},
+ json={
+ "session_id": session_id,
+ "text": "original work",
+ "user_message_id": original["id"],
+ },
)
assert response.status_code == 202
await asyncio.wait_for(original_started.wait(), timeout=3)
@@ -3017,7 +3325,9 @@ def test_concurrent_agent_run_send_now_callers_share_one_interrupt(monkeypatch,
await asyncio.wait_for(stop_entered.wait(), timeout=3)
for _ in range(100):
with engine.connect() as conn:
- if len(messages_service.list_queued(conn, session_id)) == 2:
+ queued = message_deliveries.list_queued(conn, session_id)
+ owner = message_deliveries.active_turn(conn, session_id)
+ if len(queued) == 1 and owner and owner["control_successor_turn_id"]:
break
await asyncio.sleep(0.01)
assert controller.command_handler.handle_stop.await_count == 1
@@ -3033,60 +3343,45 @@ def test_concurrent_agent_run_send_now_callers_share_one_interrupt(monkeypatch,
results = asyncio.run(_go())
assert controller.command_handler.handle_stop.await_count == 1
- assert all(
- result
- == session_turns.TurnSubmissionResult(
- route="enqueued",
- queue_persisted=True,
- target_was_busy=True,
- delivery_status="interrupted",
- queue_owner_transferred=True,
- )
- for result in results
- )
+ assert [result.delivery_status for result in results] == [
+ "waiting_terminal",
+ "queued",
+ ]
+ assert all(result.route == "enqueued" for result in results)
+ assert all(result.queue_persisted is True for result in results)
+ assert all(result.target_was_busy is True for result in results)
+ assert all(result.delivery_owner_transferred is True for result in results)
assert seen == ["original work", "first correction", "second correction"]
with engine.connect() as conn:
- assert messages_service.list_queued(conn, session_id) == []
- for request in requests:
+ assert message_deliveries.list_queued(conn, session_id) == []
+ assert message_deliveries.queue_is_held(conn, session_id) is False
+ for request, expected_status in zip(
+ requests,
+ ("waiting_terminal", "queued"),
+ strict=True,
+ ):
stored = request_store.get_run(request.id)
assert stored is not None
assert stored["metadata"]["delivery_outcome"] == {
"intent": "send_now",
- "status": "interrupted",
+ "status": expected_status,
"target_was_busy": True,
}
-def test_agent_run_send_now_restart_recovers_without_a_second_interrupt(
+def test_agent_run_send_now_restart_preserves_refused_queue_behind_durable_owner(
monkeypatch,
tmp_path,
):
- """A refused durable send-now is recovered as queued work, not replayed Stop."""
+ """Restart neither replays Stop nor bypasses the still-active durable owner."""
from core.scheduled_tasks import TaskExecutionStore
- from core.services import sessions as sessions_service
- from storage import messages_service
- from storage.db import create_sqlite_engine
- from storage.importer import ensure_sqlite_state
- from storage.settings_service import upsert_scope
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- ensure_sqlite_state()
- engine = create_sqlite_engine()
- with engine.begin() as conn:
- scope_id = upsert_scope(
- conn,
- platform="avibe",
- scope_type="project",
- native_id="proj_agent_send_now_restart",
- now="2026-07-30T00:00:00Z",
- )
- _seed_project_workdir(conn, scope_id, tmp_path)
- session_id = sessions_service.create_session(
- conn,
- scope_id=scope_id,
- agent_backend="claude",
- agent_name="worker",
- )["id"]
+ engine, session, owner_turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_agent_send_now_restart",
+ )
+ session_id = session["id"]
request_store = TaskExecutionStore()
request = request_store.enqueue_agent_run(
@@ -3097,7 +3392,12 @@ def test_agent_run_send_now_restart_recovers_without_a_second_interrupt(
)
assert request_store.claim(request.id) is not None
first_controller = _build_controller_double()
- first_controller.command_handler.handle_stop = AsyncMock(return_value=False)
+
+ async def _refuse_stop(stop_context):
+ stop_context.platform_specific["stop_failure_reason"] = "refused"
+ return False
+
+ first_controller.command_handler.handle_stop = AsyncMock(side_effect=_refuse_stop)
first_app = internal_server.create_app(first_controller)
context = MessageContext(
user_id="workbench",
@@ -3119,6 +3419,7 @@ def test_agent_run_send_now_restart_recovers_without_a_second_interrupt(
channel_id=session_id,
platform="avibe",
),
+ logical_turn_id=owner_turn_id,
)
try:
result = await first_controller.session_turn_gate.submit_scheduled(
@@ -3134,9 +3435,9 @@ def test_agent_run_send_now_restart_recovers_without_a_second_interrupt(
return result
admitted = asyncio.run(_admit_then_restart())
- assert admitted.delivery_status == "stop_failed"
+ assert admitted.delivery_status == "queued"
with engine.connect() as conn:
- assert [row["text"] for row in messages_service.list_queued(conn, session_id)] == [
+ assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == [
"recover after restart"
]
@@ -3158,25 +3459,24 @@ def test_agent_run_send_now_restart_recovers_without_a_second_interrupt(
session_id
)
for _ in range(200):
- if (
- seen == ["recover after restart"]
- and session_id not in second_controller.session_turns.in_flight
- ):
+ if session_id not in second_controller.session_turns.in_flight:
break
await asyncio.sleep(0.01)
return recovered
recovered = asyncio.run(_recover())
- assert recovered == [session_id]
- assert seen == ["recover after restart"]
+ assert recovered == []
+ assert seen == []
second_controller.command_handler.handle_stop.assert_not_awaited()
with engine.connect() as conn:
- assert messages_service.list_queued(conn, session_id) == []
+ assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == [
+ "recover after restart"
+ ]
stored = request_store.get_run(request.id)
assert stored is not None
assert stored["metadata"]["delivery_intent"] == "send_now"
- assert stored["metadata"]["delivery_outcome"]["status"] == "stop_failed"
+ assert stored["metadata"]["delivery_outcome"]["status"] == "queued"
def test_agent_run_send_now_on_an_idle_backlog_does_not_stop_the_head(monkeypatch, tmp_path):
@@ -3206,12 +3506,13 @@ def test_agent_run_send_now_on_an_idle_backlog_does_not_stop_the_head(monkeypatc
agent_backend="claude",
agent_name="worker",
)["id"]
- messages_service.enqueue_queued(
+ message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id=session_id,
text="older queued input",
)
+ assert message_deliveries.set_queue_hold(conn, session_id, held=True)
request_store = TaskExecutionStore()
request = request_store.enqueue_agent_run(
@@ -3249,7 +3550,7 @@ def test_agent_run_send_now_on_an_idle_backlog_does_not_stop_the_head(monkeypatc
delivery_intent="send_now",
)
for _ in range(300):
- if len(seen) == 2 and session_id not in app.state.in_flight_dispatches:
+ if len(seen) == 1 and session_id not in app.state.in_flight_dispatches:
break
await asyncio.sleep(0.01)
return result
@@ -3257,17 +3558,25 @@ def test_agent_run_send_now_on_an_idle_backlog_does_not_stop_the_head(monkeypatc
result = asyncio.run(_go())
assert result == session_turns.TurnSubmissionResult(
- route="enqueued",
+ route="ran",
queue_persisted=True,
target_was_busy=False,
- delivery_status="flushed",
- queue_owner_transferred=True,
+ delivery_status="claimed",
+ delivery_owner_transferred=True,
)
- assert seen == ["older queued input", "new urgent input"]
+ assert seen == ["new urgent input"]
+ with engine.connect() as conn:
+ assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == [
+ "older queued input"
+ ]
+ assert message_deliveries.queue_is_held(conn, session_id)
controller.command_handler.handle_stop.assert_not_awaited()
-def test_agent_run_send_now_idle_flush_failure_is_recoverable(monkeypatch, tmp_path):
+def test_agent_run_send_now_idle_start_failure_is_reconciled_without_replay(
+ monkeypatch,
+ tmp_path,
+):
from core.scheduled_tasks import TaskExecutionStore
from core.services import sessions as sessions_service
from storage import messages_service
@@ -3303,8 +3612,13 @@ def test_agent_run_send_now_idle_flush_failure_is_recoverable(monkeypatch, tmp_p
)
assert request_store.claim(request.id) is not None
controller = _build_controller_double()
- internal_server.create_app(controller)
- controller.session_turns.flush_queue = AsyncMock(return_value=False)
+ app = internal_server.create_app(controller)
+ controller.emit_agent_message = AsyncMock()
+
+ async def _ambiguous_dispatch(*args, **kwargs):
+ raise RuntimeError("native start outcome lost")
+
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _ambiguous_dispatch)
context = MessageContext(
user_id="workbench",
channel_id=session_id,
@@ -3316,30 +3630,44 @@ def test_agent_run_send_now_idle_flush_failure_is_recoverable(monkeypatch, tmp_p
},
)
- result = asyncio.run(
- controller.session_turn_gate.submit_scheduled(
+ async def _go():
+ result = await controller.session_turn_gate.submit_scheduled(
session_id,
context,
request.message or "",
delivery_intent="send_now",
)
- )
+ for _ in range(300):
+ if session_id not in app.state.in_flight_dispatches:
+ break
+ await asyncio.sleep(0.01)
+ return result
+
+ result = asyncio.run(_go())
assert result == session_turns.TurnSubmissionResult(
- route="enqueued",
+ route="ran",
queue_persisted=True,
target_was_busy=False,
- delivery_status="flush_failed",
- queue_owner_transferred=True,
+ delivery_status="claimed",
+ delivery_owner_transferred=True,
)
with engine.connect() as conn:
- assert [row["text"] for row in messages_service.list_queued(conn, session_id)] == [
- "retry the idle flush"
- ]
+ delivery = message_deliveries.get_delivery_by_dedupe(
+ conn,
+ f"avibe:agent_run:{request.id}",
+ )
+ assert delivery is not None
+ assert delivery["state"] == "claimed"
+ turn = message_deliveries.get_turn(conn, delivery["turn_id"])
+ assert turn is not None
+ assert turn["start_receipt_outcome"] == "unknown"
+ assert message_deliveries.list_queued(conn, session_id) == []
stored = request_store.get_run(request.id)
assert stored is not None
- assert stored["status"] == "queued"
- assert stored["metadata"]["workbench_queue_holds_run"] is True
+ assert stored["status"] == "running"
+ assert stored["delivery_id"] == delivery["id"]
+ assert "workbench_queue_holds_run" not in stored["metadata"]
def test_canceling_held_agent_run_retires_queue_before_send_now(
@@ -3382,22 +3710,27 @@ def test_canceling_held_agent_run_retires_queue_before_send_now(
delivery_intent="send_now",
)
assert request_store.claim(request.id) is not None
- request_store.requeue(
- request.id,
- metadata={"workbench_queue_holds_run": True},
- )
+ request_store.requeue(request.id)
with engine.begin() as conn:
- messages_service.append(
+ queued_delivery = message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id=session_id,
platform="avibe",
author="harness",
source="harness",
- message_type=messages_service.QUEUED_TYPE,
+ message_type="harness",
native_message_id=f"agent_run:{request.id}",
text=request.message or "",
)
+ from storage.background import attach_agent_run_delivery_in_connection
+
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ request.id,
+ session_id=session_id,
+ delivery_id=queued_delivery["id"],
+ )
controller = _build_controller_double()
app = internal_server.create_app(controller)
@@ -3429,18 +3762,18 @@ def test_canceling_held_agent_run_retires_queue_before_send_now(
}
controller.command_handler.handle_stop.assert_not_awaited()
with engine.connect() as conn:
- assert messages_service.list_queued(conn, session_id) == []
+ assert message_deliveries.list_queued(conn, session_id) == []
stored = request_store.get_run(request.id)
assert stored is not None
assert stored["status"] == "canceled"
assert stored["cancel_requested"] is True
-def test_idle_send_now_flush_failure_is_an_http_failure(
+def test_idle_send_now_releases_hold_and_starts_the_exact_head(
monkeypatch,
tmp_path,
):
- """A durable queue refusal stays retryable and never reports success."""
+ """Empty P1 releases a hold and claims only the observed FIFO head."""
from core.services import sessions as sessions_service
from storage import messages_service
@@ -3466,16 +3799,24 @@ def test_idle_send_now_flush_failure_is_an_http_failure(
agent_backend="claude",
agent_name="worker",
)["id"]
- messages_service.enqueue_queued(
+ queued = message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id=session_id,
text="retry me later",
)
+ assert message_deliveries.set_queue_hold(conn, session_id, held=True)
controller = _build_controller_double()
app = internal_server.create_app(controller)
- controller.session_turns.flush_queue = AsyncMock(return_value=False)
+ controller.emit_agent_message = AsyncMock()
+
+ async def _dispatch(ctrl, context, text, *, source=SOURCE_HUMAN, on_chunk=None):
+ assert text == "retry me later"
+ _bind_test_native_start(engine, context)
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
+
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _dispatch)
async def _exercise():
transport = httpx.ASGITransport(app=app)
@@ -3483,20 +3824,26 @@ def test_idle_send_now_flush_failure_is_an_http_failure(
transport=transport,
base_url="http://testserver",
) as client:
- return await client.post(f"/internal/send-now/{session_id}")
+ response = await client.post(f"/internal/send-now/{session_id}")
+ for _ in range(300):
+ if session_id not in app.state.in_flight_dispatches:
+ break
+ await asyncio.sleep(0.01)
+ return response
response = asyncio.run(_exercise())
- assert response.status_code == 503
+ assert response.status_code == 200
assert response.json() == {
- "ok": False,
- "code": "flush_failed",
+ "ok": True,
"session_id": session_id,
+ "status": "claimed",
+ "delivery_id": queued["id"],
}
with engine.connect() as conn:
- assert [row["text"] for row in messages_service.list_queued(conn, session_id)] == [
- "retry me later"
- ]
+ assert message_deliveries.list_queued(conn, session_id) == []
+ assert not message_deliveries.queue_is_held(conn, session_id)
+ assert messages_service.get_message(conn, queued["id"], session_id=session_id)
def test_agent_run_send_now_cancel_race_never_becomes_failed(monkeypatch, tmp_path):
@@ -3575,7 +3922,7 @@ def test_agent_run_send_now_cancel_race_never_becomes_failed(monkeypatch, tmp_pa
assert stored["error"] is None
assert stored["metadata"]["delivery_outcome"]["status"] == "canceled"
with engine.connect() as conn:
- assert messages_service.list_queued(conn, session_id) == []
+ assert message_deliveries.list_queued(conn, session_id) == []
def test_scheduled_gate_busy_duplicate_native_id_is_skipped(monkeypatch, tmp_path):
@@ -3598,6 +3945,61 @@ def test_scheduled_gate_busy_duplicate_native_id_is_skipped(monkeypatch, tmp_pat
session = sessions_service.create_session(
conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
)
+ active_delivery = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ text="running",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ native_message_id="watch:def-watch:running",
+ )
+ active_turn_id = message_deliveries.new_turn_id()
+ message_deliveries.insert_turn(
+ conn,
+ turn_id=active_turn_id,
+ session_id=session["id"],
+ initial_delivery_id=active_delivery["id"],
+ state="starting",
+ backend="claude",
+ )
+ opened = message_deliveries.open_start_attempt(
+ conn,
+ active_delivery["id"],
+ expected_version=1,
+ turn_id=active_turn_id,
+ attempt_id=message_deliveries.new_attempt_id(),
+ )
+ assert opened is not None
+ bound = message_deliveries.bind_native_start(
+ conn,
+ active_turn_id,
+ expected_version=int(
+ message_deliveries.get_turn(conn, active_turn_id)["version"]
+ ),
+ runtime_key=f"runtime:{session['id']}",
+ runtime_turn_id=f"runtime-turn:{active_turn_id}",
+ native_turn_id=f"native:{active_turn_id}",
+ )
+ assert bound is not None
+ accepted = message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=active_turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+ assert accepted
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="accepted before delivery migration",
+ native_message_id="watch:def-watch:legacy-accepted",
+ )
session_id = session["id"]
async def _explode_dispatch_turn(*args, **kwargs):
@@ -3613,7 +4015,6 @@ def test_scheduled_gate_busy_duplicate_native_id_is_skipped(monkeypatch, tmp_pat
platform="avibe",
message_id="watch:def-watch:run-1",
platform_specific={
- "task_execution_id": "run-1",
"task_trigger_kind": "watch",
"task_definition_id": "def-watch",
},
@@ -3632,6 +4033,7 @@ def test_scheduled_gate_busy_duplicate_native_id_is_skipped(monkeypatch, tmp_pat
platform="avibe",
message_id="watch:def-watch:running",
),
+ logical_turn_id=active_turn_id,
)
try:
first = await controller.session_turn_gate.submit_scheduled(session_id, ctx, "first")
@@ -3647,16 +4049,268 @@ def test_scheduled_gate_busy_duplicate_native_id_is_skipped(monkeypatch, tmp_pat
running_ctx,
"running duplicate",
)
+ legacy_ctx = MessageContext(
+ user_id="workbench",
+ channel_id=session_id,
+ platform="avibe",
+ message_id="watch:def-watch:legacy-accepted",
+ )
+ legacy_duplicate = await controller.session_turn_gate.submit_scheduled(
+ session_id,
+ legacy_ctx,
+ "legacy accepted duplicate",
+ )
finally:
chat_task.cancel()
- return first, second, running_duplicate
+ return first, second, running_duplicate, legacy_duplicate
- assert asyncio.run(_go()) == ("enqueued", "duplicate", "duplicate")
+ assert asyncio.run(_go()) == ("enqueued", "duplicate", "duplicate", "duplicate")
with engine.connect() as conn:
- queued = messages_service.list_queued(conn, session_id)
+ queued = message_deliveries.list_queued(conn, session_id)
assert [row["text"] for row in queued] == ["first"]
+def test_scheduled_gate_retry_resumes_matching_reserved_delivery(monkeypatch, tmp_path):
+ """A retry resumes a pre-claim reservation instead of completing as duplicate."""
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_sched_reserved_retry",
+ )
+ session_id = session["id"]
+ dispatched: list[str] = []
+
+ async def _accept_dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):
+ dispatched.append(text)
+ _bind_test_native_start(engine, ctx)
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
+
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _accept_dispatch)
+
+ controller = _build_controller_double()
+ internal_server.create_app(controller)
+ manager = controller.session_turns
+ submit_scheduled = controller.session_turn_gate.submit_scheduled
+ resolve_backend = manager._delivery_backend
+ fail_before_claim = True
+
+ def _resolve_backend(session_id, context):
+ nonlocal fail_before_claim
+ if fail_before_claim:
+ fail_before_claim = False
+ raise RuntimeError("backend temporarily unresolved")
+ return resolve_backend(session_id, context)
+
+ monkeypatch.setattr(manager, "_delivery_backend", _resolve_backend)
+ ctx = MessageContext(
+ user_id="workbench",
+ channel_id=session_id,
+ platform="avibe",
+ message_id="watch:def-watch:reserved-retry",
+ platform_specific={
+ "agent_session_target": {"agent_backend": "claude"},
+ "task_trigger_kind": "watch",
+ "task_definition_id": "def-watch",
+ },
+ )
+
+ async def _go():
+ with pytest.raises(RuntimeError, match="temporarily unresolved"):
+ await submit_scheduled(session_id, ctx, "original prompt")
+ with engine.connect() as conn:
+ reserved = message_deliveries.get_delivery_by_dedupe(
+ conn,
+ "avibe:watch:def-watch:reserved-retry",
+ )
+ assert reserved is not None
+ assert reserved["state"] == "reserved"
+
+ resumed = await submit_scheduled(
+ session_id,
+ ctx,
+ "changed retry payload",
+ )
+ duplicate = await submit_scheduled(session_id, ctx, "duplicate")
+ return resumed, duplicate, reserved["id"]
+
+ resumed, duplicate, delivery_id = asyncio.run(_go())
+ assert (resumed, duplicate) == ("ran", "duplicate")
+ assert dispatched == ["original prompt"]
+ with engine.connect() as conn:
+ delivery = message_deliveries.get_delivery(conn, delivery_id)
+ assert delivery is not None
+ assert delivery["state"] == "accepted"
+ assert delivery["message_id"] == delivery_id
+
+
+def test_scheduled_gate_retry_preserves_existing_delivery_owner(monkeypatch, tmp_path):
+ from core.scheduled_tasks import TaskExecutionStore
+ from storage.background import (
+ attach_agent_run_delivery_in_connection,
+ run_update_event_transaction,
+ )
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_sched_owned_retry",
+ )
+ session_id = session["id"]
+ request_store = TaskExecutionStore()
+ run = request_store.enqueue_hook_send(
+ session_key="",
+ session_id=session_id,
+ prompt="owned watch result",
+ run_type="watch",
+ )
+ assert request_store.claim(run.id) is not None
+ delivery_id = message_deliveries.new_delivery_id()
+ with run_update_event_transaction(engine) as conn:
+ message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=session_id,
+ priority="p3",
+ state="queued",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="owned watch result",
+ native_message_id=f"watch:{run.id}",
+ ),
+ dispatch_text="owned watch result",
+ dedupe_key=f"avibe:watch:{run.id}",
+ )
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ run.id,
+ session_id=session_id,
+ delivery_id=delivery_id,
+ )
+
+ controller = _build_controller_double()
+ internal_server.create_app(controller)
+ context = MessageContext(
+ user_id="workbench",
+ channel_id=session_id,
+ platform="avibe",
+ message_id=f"watch:{run.id}",
+ platform_specific={
+ "task_execution_id": run.id,
+ "task_trigger_kind": "watch",
+ },
+ )
+
+ result = asyncio.run(
+ controller.session_turn_gate.submit_scheduled(
+ session_id,
+ context,
+ "owned watch result",
+ )
+ )
+
+ assert result == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ target_was_busy=False,
+ delivery_status="queued",
+ delivery_owner_transferred=True,
+ )
+ assert request_store.get_run(run.id)["status"] == "running"
+
+
+def test_scheduled_send_now_recovers_transferred_reservation(monkeypatch, tmp_path):
+ """After ownership transfer, a pre-claim failure belongs to Delivery recovery."""
+ from core.scheduled_tasks import TaskExecutionStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_sched_send_now_reserved_retry",
+ )
+ session_id = session["id"]
+ request_store = TaskExecutionStore()
+ run = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="original send-now prompt",
+ agent_name="worker",
+ delivery_intent="send_now",
+ )
+ assert request_store.claim(run.id) is not None
+ dispatched: list[str] = []
+
+ async def _accept_dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):
+ dispatched.append(text)
+ _bind_test_native_start(engine, ctx)
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
+
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _accept_dispatch)
+
+ controller = _build_controller_double()
+ internal_server.create_app(controller)
+ manager = controller.session_turns
+ submit_scheduled = controller.session_turn_gate.submit_scheduled
+ resolve_backend = manager._delivery_backend
+ fail_before_claim = True
+
+ def _resolve_backend(session_id, context):
+ nonlocal fail_before_claim
+ if fail_before_claim:
+ fail_before_claim = False
+ raise RuntimeError("backend temporarily unresolved")
+ return resolve_backend(session_id, context)
+
+ monkeypatch.setattr(manager, "_delivery_backend", _resolve_backend)
+ ctx = MessageContext(
+ user_id="workbench",
+ channel_id=session_id,
+ platform="avibe",
+ message_id=f"agent_run:{run.id}",
+ platform_specific={
+ "agent_session_target": {"agent_backend": "claude"},
+ "task_execution_id": run.id,
+ "task_trigger_kind": "agent_run",
+ },
+ )
+
+ async def _go():
+ deferred = await submit_scheduled(
+ session_id,
+ ctx,
+ "original send-now prompt",
+ delivery_intent="send_now",
+ )
+ assert isinstance(deferred, session_turns.TurnSubmissionResult)
+ assert deferred.route == "enqueued"
+ assert deferred.delivery_status == "reserved"
+ assert deferred.delivery_owner_transferred is True
+ held = request_store.get_run(run.id)
+ assert held is not None
+ assert held["status"] == "running"
+ assert held["delivery_id"] is not None
+ assert "workbench_queue_holds_run" not in held["metadata"]
+
+ await manager.recover_durable_delivery_state(session_id)
+ resumed_owner = await submit_scheduled(
+ session_id,
+ ctx,
+ "duplicate",
+ delivery_intent="send_now",
+ )
+ return resumed_owner
+
+ resumed_owner = asyncio.run(_go())
+ assert isinstance(resumed_owner, session_turns.TurnSubmissionResult)
+ assert resumed_owner.route == "ran"
+ assert resumed_owner.delivery_status == "claimed"
+ assert resumed_owner.delivery_owner_transferred is True
+ assert dispatched == ["original send-now prompt"]
+
+
def test_scheduled_gate_cancel_stops_scheduled_run(monkeypatch, tmp_path):
"""Stop works for a scheduled run: because the run goes through ``_run_turn``
it registers the scheduled ``context`` in ``in_flight``, so
@@ -3683,6 +4337,7 @@ def test_scheduled_gate_cancel_stops_scheduled_run(monkeypatch, tmp_path):
started = asyncio.Event()
async def _long_dispatch_turn(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):
+ _bind_test_native_start(engine, ctx)
started.set()
await asyncio.sleep(5) # held until the test cancels it
return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
@@ -3720,14 +4375,15 @@ def test_scheduled_gate_cancel_stops_scheduled_run(monkeypatch, tmp_path):
def _seed_avibe_session_with_queue(queued):
- """Create an isolated avibe session and seed its queue (oldest first). Each
- ``queued`` entry is ``(text, scheduled_provenance | None)`` — None => a user row,
- a dict => a scheduled row carrying that provenance under the marker key."""
+ """Create an isolated Session and seed independent Deliveries oldest first."""
from core.services import sessions as sessions_service
- from storage import messages_service
+ from storage import message_deliveries
+ from storage.background import attach_agent_run_delivery_in_connection
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
+ from storage.models import agent_runs
from storage.settings_service import upsert_scope
+ from sqlalchemy import update
ensure_sqlite_state()
engine = create_sqlite_engine()
@@ -3740,18 +4396,34 @@ def _seed_avibe_session_with_queue(queued):
conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
)
for text, prov in queued:
- messages_service.append(
+ delivery = message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id=session["id"],
platform="avibe",
author=("harness" if prov is not None else "user"),
source=("harness" if prov is not None else "user"),
- message_type=messages_service.QUEUED_TYPE,
+ message_type=("harness" if prov is not None else "user"),
text=text,
metadata=({session_turns.SCHEDULED_PROVENANCE_KEY: prov} if prov is not None else None),
native_message_id=(prov or {}).get("message_id") if prov is not None else None,
)
+ spec = (prov or {}).get("platform_specific") or {}
+ run_id = str(spec.get("task_execution_id") or "").strip()
+ if run_id and conn.execute(
+ select(agent_runs.c.id).where(agent_runs.c.id == run_id)
+ ).scalar_one_or_none():
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(session_id=session["id"])
+ )
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ run_id,
+ session_id=session["id"],
+ delivery_id=str(delivery["id"]),
+ )
return session["id"]
@@ -3766,13 +4438,50 @@ def _manager_capturing_runs():
),
)
- async def _fake_run(sid, context, text, *, source=SOURCE_HUMAN):
+ async def _fake_run(sid, context, text, *, source=SOURCE_HUMAN, **_kwargs):
runs.append((text, source, context))
mgr._run = _fake_run
return mgr, runs
+def _manager_accepting_runs():
+ """Capture durable starts while simulating exact native acceptance."""
+
+ manager, runs = _manager_capturing_runs()
+
+ async def _accept(
+ sid,
+ context,
+ text,
+ *,
+ source=SOURCE_HUMAN,
+ logical_turn_id=None,
+ delivery_id=None,
+ **_kwargs,
+ ):
+ runs.append((text, source, context))
+ _bind_test_native_start(manager._sqlite_engine(), context)
+ with manager._sqlite_engine().begin() as conn:
+ accepted = message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=logical_turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+ assert accepted
+ manager._publish_materialized_delivery(delivery_id)
+ settled = manager._terminalize_durable_turn(
+ logical_turn_id,
+ "completed",
+ settled_by="test",
+ evidence_kind="test_native_terminal",
+ )
+ assert settled["changed"] is True
+
+ manager._run = _accept
+ return manager, runs
+
+
def test_flush_runs_scheduled_row_as_scheduled_with_provenance(tmp_path, monkeypatch):
"""A queued scheduled run flushes as its OWN SOURCE_SCHEDULED turn with its
delivery provenance restored — not merged into a plain user turn (#84)."""
@@ -3808,12 +4517,10 @@ def test_flush_runs_scheduled_row_as_scheduled_with_provenance(tmp_path, monkeyp
from storage.db import create_sqlite_engine
with create_sqlite_engine().begin() as conn:
- assert messages_service.list_queued(conn, session_id) == []
+ assert message_deliveries.list_queued(conn, session_id) == []
-def test_flush_coalesces_same_scheduled_callbacks_within_window(tmp_path, monkeypatch):
- """Harness callback rows stay visible as separate queued messages, but same
- watch/task callbacks inside the rolling window dispatch as one Agent turn."""
+def test_flush_merges_compatible_scheduled_deliveries_into_one_turn(tmp_path, monkeypatch):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
def prov(execution_id: str, message_id: str = "watch:def-watch") -> dict:
@@ -3834,13 +4541,10 @@ def test_flush_coalesces_same_scheduled_callbacks_within_window(tmp_path, monkey
]
)
- from sqlalchemy import select
- from storage import messages_service
from storage.db import create_sqlite_engine
- from storage.models import messages
with create_sqlite_engine().begin() as conn:
- assert [row["text"] for row in messages_service.list_queued(conn, session_id)] == [
+ assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == [
"first callback",
"second callback",
"third callback",
@@ -3852,35 +4556,19 @@ def test_flush_coalesces_same_scheduled_callbacks_within_window(tmp_path, monkey
assert len(runs) == 1
text, source, ctx = runs[0]
assert source == SOURCE_SCHEDULED
- assert "first callback" in text
- assert "second callback" in text
- assert "third callback" in text
- assert "fired 3 times" in text
- assert "pause, remove, or update" in text
+ assert text == "first callback\n\n---\n\nsecond callback\n\n---\n\nthird callback"
assert ctx.platform_specific["task_definition_id"] == "def-watch"
- assert ctx.platform_specific["coalesced_queue"]["count"] == 3
- assert ctx.platform_specific["coalesced_queue"]["execution_ids"] == ["run-1", "run-2", "run-3"]
- assert ctx.platform_specific["coalesced_queue"]["native_message_ids"] == [
- "watch:def-watch:run-1",
- "watch:def-watch:run-2",
- "watch:def-watch:run-3",
- ]
+ assert len(ctx.platform_specific["delivery_ids"]) == 3
with create_sqlite_engine().begin() as conn:
- assert messages_service.list_queued(conn, session_id) == []
- dedupe_rows = conn.execute(select(messages)).mappings().all()
- dedupe_native_ids = {
- row["native_message_id"]
- for row in dedupe_rows
- if row["type"] == messages_service.HARNESS_DEDUPE_TYPE
- }
- assert dedupe_native_ids == {"watch:def-watch:run-2", "watch:def-watch:run-3"}
+ assert message_deliveries.list_queued(conn, session_id) == []
-def test_flush_claims_every_coalesced_agent_run(tmp_path, monkeypatch):
+def test_flush_claims_compatible_agent_run_deliveries_as_one_turn(tmp_path, monkeypatch):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
from core.scheduled_tasks import TaskExecutionStore
from storage.background import SQLiteBackgroundTaskStore
+ from storage.db import create_sqlite_engine
request_store = TaskExecutionStore()
@@ -3905,24 +4593,12 @@ def test_flush_claims_every_coalesced_agent_run(tmp_path, monkeypatch):
agent_name="codex",
)
assert request_store.claim(request.id) is not None
- request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})
+ request_store.requeue(request.id)
queued.append((f"cli agent message {index + 1}", prov(request.id)))
session_id = _seed_avibe_session_with_queue(queued)
- from sqlalchemy import update
- from storage import messages_service
from storage.db import create_sqlite_engine
- from storage.models import messages
-
- with create_sqlite_engine().begin() as conn:
- rows = messages_service.list_queued(conn, session_id)
- for index, row in enumerate(rows):
- conn.execute(
- update(messages)
- .where(messages.c.id == row["id"])
- .values(created_at=f"2026-06-22T00:00:0{index}Z")
- )
mgr, runs = _manager_capturing_runs()
@@ -3930,12 +4606,13 @@ def test_flush_claims_every_coalesced_agent_run(tmp_path, monkeypatch):
assert len(runs) == 1
text, source, ctx = runs[0]
assert source == SOURCE_SCHEDULED
- assert "cli agent message 1" in text
- assert "cli agent message 2" in text
- assert "cli agent message 3" in text
- assert "cli agent message 4" in text
- execution_ids = ctx.platform_specific["coalesced_queue"]["execution_ids"]
- assert len(execution_ids) == 4
+ assert text == (
+ "cli agent message 1\n\n---\n\ncli agent message 2\n\n---\n\n"
+ "cli agent message 3\n\n---\n\ncli agent message 4"
+ )
+ execution_ids = [item[1]["platform_specific"]["task_execution_id"] for item in queued]
+ assert ctx.platform_specific["task_execution_id"] == execution_ids[0]
+ assert ctx.platform_specific["accepted_agent_run_ids"] == execution_ids
bg = SQLiteBackgroundTaskStore()
try:
@@ -3943,34 +4620,21 @@ def test_flush_claims_every_coalesced_agent_run(tmp_path, monkeypatch):
finally:
bg.close()
- assert stored[execution_ids[0]]["status"] == "running"
- assert [stored[run_id]["status"] for run_id in execution_ids[1:]] == ["queued", "queued", "queued"]
- assert [stored[run_id]["metadata"]["effective_run_id"] for run_id in execution_ids] == [
- execution_ids[0],
- execution_ids[0],
- execution_ids[0],
- execution_ids[0],
- ]
- assert stored[execution_ids[0]]["metadata"].get("coalesced_into_run_id") is None
- assert [stored[run_id]["metadata"]["coalesced_into_run_id"] for run_id in execution_ids[1:]] == [
- execution_ids[0],
- execution_ids[0],
- execution_ids[0],
- ]
- assert stored[execution_ids[0]]["metadata"]["workbench_queue_holds_run"] is False
- assert [stored[run_id]["metadata"]["workbench_queue_holds_run"] for run_id in execution_ids[1:]] == [
- True,
- True,
- True,
- ]
+ assert [stored[run_id]["status"] for run_id in execution_ids] == ["running"] * 4
+ assert len({stored[run_id]["delivery_id"] for run_id in execution_ids}) == 4
+ assert all(stored[run_id]["delivery_id"] for run_id in execution_ids)
+ assert all(
+ "workbench_queue_holds_run" not in stored[run_id]["metadata"]
+ for run_id in execution_ids
+ )
+ with create_sqlite_engine().connect() as conn:
+ assert message_deliveries.list_queued(conn, session_id) == []
def test_flush_background_agent_run_preserves_primary_prompt(tmp_path, monkeypatch):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- from core.message_mirror import mirror_harness_inbound
from core.scheduled_tasks import TaskExecutionStore
- from storage import messages_service
from storage.db import create_sqlite_engine
from storage.models import messages
@@ -3981,7 +4645,7 @@ def test_flush_background_agent_run_preserves_primary_prompt(tmp_path, monkeypat
agent_name="codex",
)
assert request_store.claim(request.id) is not None
- request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})
+ request_store.requeue(request.id)
session_id = _seed_avibe_session_with_queue(
[
(
@@ -4001,11 +4665,27 @@ def test_flush_background_agent_run_preserves_primary_prompt(tmp_path, monkeypat
)
mgr, runs = _manager_capturing_runs()
- async def _mirror_run(sid, context, text, *, source=SOURCE_HUMAN):
- mirror_harness_inbound(context, text)
+ async def _accept_run(
+ sid,
+ context,
+ text,
+ *,
+ source=SOURCE_HUMAN,
+ logical_turn_id=None,
+ delivery_id=None,
+ **_kwargs,
+ ):
+ _bind_test_native_start(mgr._sqlite_engine(), context)
+ with mgr._sqlite_engine().begin() as conn:
+ accepted = message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=logical_turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+ assert accepted
runs.append((text, source, context))
- mgr._run = _mirror_run
+ mgr._run = _accept_run
assert asyncio.run(mgr.flush_queue(session_id)) is True
assert len(runs) == 1
@@ -4018,47 +4698,13 @@ def test_flush_background_agent_run_preserves_primary_prompt(tmp_path, monkeypat
assert [(row["native_message_id"], row["content_text"]) for row in harness_rows] == [
(f"agent_run:{request.id}", "background prompt")
]
- assert [row for row in rows if row["type"] == messages_service.HARNESS_DEDUPE_TYPE] == []
+ assert len(rows) == 1
-def test_coalesced_agent_run_claim_is_atomic(tmp_path, monkeypatch):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
-
- from core.scheduled_tasks import TaskExecutionStore
- from storage.background import SQLiteBackgroundTaskStore
-
- request_store = TaskExecutionStore()
- run_ids: list[str] = []
- for index in range(3):
- request = request_store.enqueue_agent_run(
- session_id="placeholder",
- message=f"cli agent message {index + 1}",
- agent_name="codex",
- )
- assert request_store.claim(request.id) is not None
- request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})
- run_ids.append(request.id)
-
- bg = SQLiteBackgroundTaskStore()
- try:
- assert bg.cancel_run(run_ids[1]) is True
- assert bg.claim_queued_runs_for_workbench(run_ids) == []
- stored = {run_id: bg.get_run(run_id) for run_id in run_ids}
- finally:
- bg.close()
-
- assert stored[run_ids[0]]["status"] == "queued"
- assert stored[run_ids[1]]["status"] == "canceled"
- assert stored[run_ids[2]]["status"] == "queued"
- assert {row["status"] for row in stored.values()} == {"queued", "canceled"}
- assert all(row["status"] != "running" for row in stored.values())
- assert stored[run_ids[0]]["metadata"]["workbench_queue_holds_run"] is True
- assert stored[run_ids[2]]["metadata"]["workbench_queue_holds_run"] is True
- assert stored[run_ids[0]]["metadata"].get("effective_run_id") is None
- assert stored[run_ids[2]]["metadata"].get("effective_run_id") is None
-
-
-def test_flush_removes_stale_coalesced_agent_run_row_and_dispatches_survivors(tmp_path, monkeypatch):
+def test_cancel_retires_exact_agent_run_delivery_without_reordering_survivors(
+ tmp_path,
+ monkeypatch,
+):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
from core.scheduled_tasks import TaskExecutionStore
@@ -4088,40 +4734,40 @@ def test_flush_removes_stale_coalesced_agent_run_row_and_dispatches_survivors(tm
agent_name="codex",
)
assert request_store.claim(request.id) is not None
- request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})
+ request_store.requeue(request.id)
queued.append((f"cli agent message {index + 1}", prov(request.id)))
run_ids.append(request.id)
session_id = _seed_avibe_session_with_queue(queued)
- from storage import messages_service
from storage.db import create_sqlite_engine
+ from core.inbox_events import bus
+
+ published: list[tuple[str, dict]] = []
+ monkeypatch.setattr(bus, "publish", lambda event, payload: published.append((event, payload)))
+
bg = SQLiteBackgroundTaskStore()
try:
assert bg.cancel_run(run_ids[1]) is True
finally:
bg.close()
- from core.inbox_events import bus
-
- published: list[tuple[str, dict]] = []
- monkeypatch.setattr(bus, "publish", lambda event, payload: published.append((event, payload)))
-
mgr, runs = _manager_capturing_runs()
assert asyncio.run(mgr.flush_queue(session_id)) is True
assert len(runs) == 1
text, source, ctx = runs[0]
assert source == SOURCE_SCHEDULED
- assert "cli agent message 1" in text
- assert "cli agent message 3" in text
- assert "cli agent message 2" not in text
- assert ctx.platform_specific["coalesced_queue"]["execution_ids"] == [run_ids[0], run_ids[2]]
+ assert text == "cli agent message 1\n\n---\n\ncli agent message 3"
+ assert ctx.platform_specific["task_execution_id"] == run_ids[0]
+ assert ctx.platform_specific["accepted_agent_run_ids"] == [
+ run_ids[0],
+ run_ids[2],
+ ]
with create_sqlite_engine().begin() as conn:
- queued_rows = messages_service.list_queued(conn, session_id)
- assert queued_rows == []
+ assert message_deliveries.list_queued(conn, session_id) == []
bg = SQLiteBackgroundTaskStore()
try:
@@ -4131,148 +4777,24 @@ def test_flush_removes_stale_coalesced_agent_run_row_and_dispatches_survivors(tm
assert stored[run_ids[0]]["status"] == "running"
assert stored[run_ids[1]]["status"] == "canceled"
- assert stored[run_ids[2]]["status"] == "queued"
- assert stored[run_ids[0]]["metadata"]["workbench_queue_holds_run"] is False
- assert stored[run_ids[2]]["metadata"]["workbench_queue_holds_run"] is True
- assert published.count(("queue.updated", {"session_id": session_id})) >= 2
-
-
-def test_flush_preserves_recovered_coalesced_agent_run_children(tmp_path, monkeypatch):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
-
- from core.scheduled_tasks import TaskExecutionStore
-
- request_store = TaskExecutionStore()
-
- def prov(execution_id: str, coalesced_ids: list[str] | None = None) -> dict:
- platform_specific = {
- "task_execution_id": execution_id,
- "task_trigger_kind": "agent_run",
- "task_definition_id": None,
- "vibe_agent_name": "codex",
- "source_kind": None,
- "callback_session_id": None,
- }
- if coalesced_ids:
- platform_specific["coalesced_queue"] = {"execution_ids": coalesced_ids}
- return {
- "message_id": f"agent_run:{execution_id}",
- "platform_specific": platform_specific,
- }
-
- recovered_ids: list[str] = []
- for index in range(2):
- request = request_store.enqueue_agent_run(
- session_id="placeholder",
- message=f"recovered message {index + 1}",
- agent_name="codex",
- )
- assert request_store.claim(request.id) is not None
- request_store.requeue(request.id, metadata={"workbench_queue_holds_run": index != 0})
- recovered_ids.append(request.id)
- new_request = request_store.enqueue_agent_run(
- session_id="placeholder",
- message="new message",
- agent_name="codex",
- )
- assert request_store.claim(new_request.id) is not None
- request_store.requeue(new_request.id, metadata={"workbench_queue_holds_run": True})
-
- session_id = _seed_avibe_session_with_queue(
- [
- ("recovered primary", prov(recovered_ids[0], recovered_ids)),
- ("new message", prov(new_request.id)),
- ]
- )
-
- mgr, runs = _manager_capturing_runs()
-
- assert asyncio.run(mgr.flush_queue(session_id)) is True
- assert len(runs) == 1
- _text, source, ctx = runs[0]
- assert source == SOURCE_SCHEDULED
- assert ctx.platform_specific["coalesced_queue"]["execution_ids"] == [
- recovered_ids[0],
- recovered_ids[1],
- new_request.id,
- ]
-
-
-def test_flush_retargets_recovered_coalesced_row_when_primary_is_stale(tmp_path, monkeypatch):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
-
- from core.scheduled_tasks import TaskExecutionStore
- from storage.background import SQLiteBackgroundTaskStore
-
- request_store = TaskExecutionStore()
-
- def prov(execution_id: str, coalesced_ids: list[str]) -> dict:
- return {
- "message_id": f"agent_run:{execution_id}",
- "platform_specific": {
- "task_execution_id": execution_id,
- "task_trigger_kind": "agent_run",
- "task_definition_id": None,
- "vibe_agent_name": "codex",
- "source_kind": None,
- "callback_session_id": None,
- "coalesced_queue": {
- "execution_ids": coalesced_ids,
- "messages": [
- {"execution_id": coalesced_ids[0], "message": "stale primary prompt"},
- {"execution_id": coalesced_ids[1], "message": "surviving child prompt"},
- ],
- },
- },
- }
-
- run_ids: list[str] = []
- for index in range(2):
- request = request_store.enqueue_agent_run(
- session_id="placeholder",
- message=f"coalesced message {index + 1}",
- agent_name="codex",
+ assert stored[run_ids[2]]["status"] == "running"
+ assert len({stored[run_ids[0]]["delivery_id"], stored[run_ids[2]]["delivery_id"]}) == 2
+ with create_sqlite_engine().connect() as conn:
+ canceled_delivery = message_deliveries.get_delivery(
+ conn,
+ stored[run_ids[1]]["delivery_id"],
)
- assert request_store.claim(request.id) is not None
- request_store.requeue(request.id, metadata={"workbench_queue_holds_run": index != 0})
- run_ids.append(request.id)
-
- session_id = _seed_avibe_session_with_queue(
- [("stale primary prompt", prov(run_ids[0], run_ids))]
- )
-
- bg = SQLiteBackgroundTaskStore()
- try:
- assert bg.cancel_run(run_ids[0]) is True
- finally:
- bg.close()
-
- mgr, runs = _manager_capturing_runs()
-
- assert asyncio.run(mgr.flush_queue(session_id)) is True
- assert len(runs) == 1
- text, source, ctx = runs[0]
- assert source == SOURCE_SCHEDULED
- assert text == "surviving child prompt"
- assert ctx.message_id == f"agent_run:{run_ids[1]}"
- assert ctx.platform_specific["task_execution_id"] == run_ids[1]
- assert ctx.platform_specific["coalesced_queue"]["execution_ids"] == [run_ids[1]]
-
- bg = SQLiteBackgroundTaskStore()
- try:
- stored = {run_id: bg.get_run(run_id) for run_id in run_ids}
- finally:
- bg.close()
- assert stored[run_ids[0]]["status"] == "canceled"
- assert stored[run_ids[1]]["status"] == "running"
+ assert canceled_delivery is not None
+ assert canceled_delivery["state"] == "retired"
+ assert published.count(("queue.updated", {"session_id": session_id})) >= 1
-def test_flush_retries_when_agent_run_claim_finds_late_stale_row(tmp_path, monkeypatch):
+def test_turn_claim_refuses_batch_with_terminal_agent_run_without_dispatch(tmp_path, monkeypatch):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
from core.scheduled_tasks import TaskExecutionStore
- from storage import background as background_module
from storage.background import SQLiteBackgroundTaskStore
+ from storage.db import create_sqlite_engine
from storage.models import agent_runs
from sqlalchemy import update
@@ -4300,38 +4822,27 @@ def test_flush_retries_when_agent_run_claim_finds_late_stale_row(tmp_path, monke
agent_name="codex",
)
assert request_store.claim(request.id) is not None
- request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})
+ request_store.requeue(request.id)
queued.append((f"cli agent message {index + 1}", prov(request.id)))
run_ids.append(request.id)
session_id = _seed_avibe_session_with_queue(queued)
- real_claim = background_module.claim_queued_runs_for_workbench_in_connection
- injected = {"done": False}
-
- def late_stale_claim(conn, pending_run_ids, *, started_at=None):
- if not injected["done"]:
- injected["done"] = True
- conn.execute(
- update(agent_runs)
- .where(agent_runs.c.id == run_ids[1])
- .values(status="canceled", cancel_requested=1, completed_at="2026-06-22T00:00:10Z")
+ with create_sqlite_engine().begin() as conn:
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_ids[1])
+ .values(
+ status="canceled",
+ cancel_requested=1,
+ completed_at="2026-06-22T00:00:10Z",
)
- return []
- return real_claim(conn, pending_run_ids, started_at=started_at)
-
- monkeypatch.setattr(background_module, "claim_queued_runs_for_workbench_in_connection", late_stale_claim)
- monkeypatch.setattr(session_turns, "claim_queued_runs_for_workbench_in_connection", late_stale_claim, raising=False)
+ )
mgr, runs = _manager_capturing_runs()
- assert asyncio.run(mgr.flush_queue(session_id)) is True
- assert len(runs) == 1
- text, source, ctx = runs[0]
- assert source == SOURCE_SCHEDULED
- assert "cli agent message 1" in text
- assert "cli agent message 3" in text
- assert "cli agent message 2" not in text
- assert ctx.platform_specific["coalesced_queue"]["execution_ids"] == [run_ids[0], run_ids[2]]
+ with pytest.raises(RuntimeError, match="unclaimable Agent Run"):
+ asyncio.run(mgr.flush_queue(session_id))
+ assert runs == []
bg = SQLiteBackgroundTaskStore()
try:
@@ -4339,12 +4850,18 @@ def test_flush_retries_when_agent_run_claim_finds_late_stale_row(tmp_path, monke
finally:
bg.close()
- assert stored[run_ids[0]]["status"] == "running"
+ assert stored[run_ids[0]]["status"] == "queued"
assert stored[run_ids[1]]["status"] == "canceled"
assert stored[run_ids[2]]["status"] == "queued"
+ with mgr._sqlite_engine().connect() as conn:
+ assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == [
+ "cli agent message 1",
+ "cli agent message 2",
+ "cli agent message 3",
+ ]
-def test_flush_does_not_coalesce_agent_runs_with_different_callback_targets(tmp_path, monkeypatch):
+def test_flush_merges_agent_runs_with_different_callback_targets(tmp_path, monkeypatch):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
from core.scheduled_tasks import TaskExecutionStore
@@ -4372,7 +4889,7 @@ def test_flush_does_not_coalesce_agent_runs_with_different_callback_targets(tmp_
callback_session_id=callback_session_id,
)
assert request_store.claim(request.id) is not None
- request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})
+ request_store.requeue(request.id)
queued.append((f"cli agent message {index + 1}", prov(request.id, callback_session_id)))
session_id = _seed_avibe_session_with_queue(queued)
@@ -4383,11 +4900,14 @@ def test_flush_does_not_coalesce_agent_runs_with_different_callback_targets(tmp_
assert len(runs) == 1
text, source, ctx = runs[0]
assert source == SOURCE_SCHEDULED
- assert text == "cli agent message 1"
+ assert text == "cli agent message 1\n\n---\n\ncli agent message 2"
+ assert len(ctx.platform_specific["accepted_agent_run_ids"]) == 2
assert "coalesced_queue" not in ctx.platform_specific
+ with mgr._sqlite_engine().connect() as conn:
+ assert message_deliveries.list_queued(conn, session_id) == []
-def test_flush_does_not_coalesce_callback_backed_agent_runs(tmp_path, monkeypatch):
+def test_flush_merges_callback_backed_agent_runs_by_delivery_compatibility(tmp_path, monkeypatch):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
from core.scheduled_tasks import TaskExecutionStore
@@ -4415,7 +4935,7 @@ def test_flush_does_not_coalesce_callback_backed_agent_runs(tmp_path, monkeypatc
callback_session_id="same-caller",
)
assert request_store.claim(request.id) is not None
- request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})
+ request_store.requeue(request.id)
queued.append((f"callback agent message {index + 1}", prov(request.id)))
session_id = _seed_avibe_session_with_queue(queued)
@@ -4426,11 +4946,12 @@ def test_flush_does_not_coalesce_callback_backed_agent_runs(tmp_path, monkeypatc
assert len(runs) == 1
text, source, ctx = runs[0]
assert source == SOURCE_SCHEDULED
- assert text == "callback agent message 1"
+ assert text == "callback agent message 1\n\n---\n\ncallback agent message 2"
+ assert len(ctx.platform_specific["accepted_agent_run_ids"]) == 2
assert "coalesced_queue" not in ctx.platform_specific
-def test_flush_isolates_legacy_agent_runs_without_source_provenance(tmp_path, monkeypatch):
+def test_flush_merges_agent_runs_without_redundant_provenance_metadata(tmp_path, monkeypatch):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
from core.scheduled_tasks import TaskExecutionStore
@@ -4457,7 +4978,7 @@ def test_flush_isolates_legacy_agent_runs_without_source_provenance(tmp_path, mo
callback_session_id=f"caller-{index + 1}",
)
assert request_store.claim(request.id) is not None
- request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})
+ request_store.requeue(request.id)
queued.append((f"legacy callback message {index + 1}", prov(request.id)))
session_id = _seed_avibe_session_with_queue(queued)
@@ -4468,7 +4989,8 @@ def test_flush_isolates_legacy_agent_runs_without_source_provenance(tmp_path, mo
assert len(runs) == 1
text, source, ctx = runs[0]
assert source == SOURCE_SCHEDULED
- assert text == "legacy callback message 1"
+ assert text == "legacy callback message 1\n\n---\n\nlegacy callback message 2"
+ assert len(ctx.platform_specific["accepted_agent_run_ids"]) == 2
assert "coalesced_queue" not in ctx.platform_specific
@@ -4502,7 +5024,7 @@ def test_flush_does_not_claim_agent_runs_when_context_build_fails(tmp_path, monk
agent_name="codex",
)
assert request_store.claim(request.id) is not None
- request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})
+ request_store.requeue(request.id)
queued.append((f"cli agent message {index + 1}", prov(request.id)))
run_ids.append(request.id)
@@ -4515,20 +5037,11 @@ def test_flush_does_not_claim_agent_runs_when_context_build_fails(tmp_path, monk
assert asyncio.run(mgr.flush_queue(session_id)) is False
- from storage import messages_service
from storage.db import create_sqlite_engine
- from storage.models import messages
-
with create_sqlite_engine().begin() as conn:
- queued_rows = messages_service.list_queued(conn, session_id)
- dedupe_rows = conn.execute(
- select(messages)
- .where(messages.c.session_id == session_id)
- .where(messages.c.type == messages_service.HARNESS_DEDUPE_TYPE)
- ).mappings().all()
+ queued_rows = message_deliveries.list_queued(conn, session_id)
assert [row["text"] for row in queued_rows] == ["cli agent message 1", "cli agent message 2"]
- assert dedupe_rows == []
bg = SQLiteBackgroundTaskStore()
try:
@@ -4536,11 +5049,14 @@ def test_flush_does_not_claim_agent_runs_when_context_build_fails(tmp_path, monk
finally:
bg.close()
- assert {row["status"] for row in stored.values()} == {"queued"}
- assert all(row["metadata"]["workbench_queue_holds_run"] is True for row in stored.values())
+ assert {row["status"] for row in stored.values()} == {"running"}
+ assert all(row["delivery_id"] for row in stored.values())
-def test_flush_resets_agent_run_claim_when_run_start_fails(tmp_path, monkeypatch):
+def test_flush_quarantines_agent_run_when_native_start_may_have_written(
+ tmp_path,
+ monkeypatch,
+):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
from core.scheduled_tasks import TaskExecutionStore
@@ -4568,7 +5084,7 @@ def test_flush_resets_agent_run_claim_when_run_start_fails(tmp_path, monkeypatch
agent_name="codex",
)
assert request_store.claim(request.id) is not None
- request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})
+ request_store.requeue(request.id)
queued.append((f"cli agent message {index + 1}", prov(request.id)))
run_ids.append(request.id)
@@ -4582,12 +5098,19 @@ def test_flush_resets_agent_run_claim_when_run_start_fails(tmp_path, monkeypatch
assert asyncio.run(mgr.flush_queue(session_id)) is False
- from storage import messages_service
from storage.db import create_sqlite_engine
with create_sqlite_engine().begin() as conn:
- queued_rows = messages_service.list_queued(conn, session_id)
- assert [row["text"] for row in queued_rows] == ["cli agent message 1", "cli agent message 2"]
+ queued_rows = message_deliveries.list_queued(conn, session_id)
+ unresolved_turn = message_deliveries.active_turn(conn, session_id)
+ assert unresolved_turn is not None
+ unresolved_batch = message_deliveries.initial_deliveries_for_turn(
+ conn,
+ unresolved_turn["id"],
+ )
+ assert queued_rows == []
+ assert unresolved_turn["start_receipt_outcome"] == "unknown"
+ assert [row["state"] for row in unresolved_batch] == ["claimed", "claimed"]
bg = SQLiteBackgroundTaskStore()
try:
@@ -4595,12 +5118,11 @@ def test_flush_resets_agent_run_claim_when_run_start_fails(tmp_path, monkeypatch
finally:
bg.close()
- assert {row["status"] for row in stored.values()} == {"queued"}
- assert all(row["metadata"]["workbench_queue_holds_run"] is True for row in stored.values())
- assert all(row["metadata"].get("effective_run_id") is None for row in stored.values())
+ assert [stored[run_id]["status"] for run_id in run_ids] == ["running", "running"]
+ assert len({stored[run_id]["delivery_id"] for run_id in run_ids}) == 2
-def test_flush_suppressed_segment_reserves_first_native_id_for_prompt(tmp_path, monkeypatch):
+def test_flush_suppressed_segment_claims_each_delivery_id_in_one_turn(tmp_path, monkeypatch):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
def prov(execution_id: str) -> dict:
@@ -4621,25 +5143,16 @@ def test_flush_suppressed_segment_reserves_first_native_id_for_prompt(tmp_path,
]
)
- from sqlalchemy import select
-
- from storage import messages_service
from storage.db import create_sqlite_engine
- from storage.models import messages
mgr, runs = _manager_capturing_runs()
assert asyncio.run(mgr.flush_queue(session_id)) is True
assert len(runs) == 1
assert runs[0][2].message_id == "watch:def-watch:run-1"
+ assert len(runs[0][2].platform_specific["delivery_ids"]) == 2
with create_sqlite_engine().begin() as conn:
- dedupe_rows = conn.execute(select(messages)).mappings().all()
- dedupe_native_ids = {
- row["native_message_id"]
- for row in dedupe_rows
- if row["type"] == messages_service.HARNESS_DEDUPE_TYPE
- }
- assert dedupe_native_ids == {"watch:def-watch:run-2"}
+ assert message_deliveries.list_queued(conn, session_id) == []
def test_flush_does_not_coalesce_scheduled_callbacks_with_different_delivery(tmp_path, monkeypatch):
@@ -4671,7 +5184,7 @@ def test_flush_does_not_coalesce_scheduled_callbacks_with_different_delivery(tmp
assert asyncio.run(mgr.flush_queue(session_id)) is True
assert [(text, source) for text, source, _ in runs] == [("first callback", SOURCE_SCHEDULED)]
with create_sqlite_engine().begin() as conn:
- remaining = messages_service.list_queued(conn, session_id)
+ remaining = message_deliveries.list_queued(conn, session_id)
assert [row["text"] for row in remaining] == ["different delivery"]
@@ -4704,9 +5217,9 @@ def test_flush_does_not_coalesce_scheduled_callbacks_with_different_agent(tmp_pa
assert asyncio.run(mgr.flush_queue(session_id)) is True
text, source, ctx = runs[0]
assert (text, source) == ("codex callback", SOURCE_SCHEDULED)
- assert ctx.platform_specific["vibe_agent_name"] == "codex"
+ assert "vibe_agent_name" not in ctx.platform_specific
with create_sqlite_engine().begin() as conn:
- remaining = messages_service.list_queued(conn, session_id)
+ remaining = message_deliveries.list_queued(conn, session_id)
assert [row["text"] for row in remaining] == ["claude callback"]
@@ -4743,41 +5256,12 @@ def test_capture_scheduled_target_agent_splits_coalescing_key(tmp_path, monkeypa
assert asyncio.run(mgr.flush_queue(session_id)) is True
text, source, ctx = runs[0]
assert (text, source) == ("codex target callback", SOURCE_SCHEDULED)
- assert ctx.platform_specific[session_turns.SCHEDULED_TARGET_AGENT_KEY] == "codex"
+ assert session_turns.SCHEDULED_TARGET_AGENT_KEY not in ctx.platform_specific
with create_sqlite_engine().begin() as conn:
- remaining = messages_service.list_queued(conn, session_id)
+ remaining = message_deliveries.list_queued(conn, session_id)
assert [row["text"] for row in remaining] == ["claude target callback"]
-def test_flush_coalesced_scheduled_copy_uses_i18n(tmp_path, monkeypatch):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
-
- def prov(execution_id: str) -> dict:
- return {
- "message_id": f"watch:def-watch:{execution_id}",
- "platform_specific": {
- "language": "zh",
- "task_execution_id": execution_id,
- "task_trigger_kind": "watch",
- "task_definition_id": "def-watch",
- },
- }
-
- session_id = _seed_avibe_session_with_queue(
- [
- ("第一次 callback", prov("run-1")),
- ("第二次 callback", prov("run-2")),
- ]
- )
-
- mgr, runs = _manager_capturing_runs()
-
- assert asyncio.run(mgr.flush_queue(session_id)) is True
- text = runs[0][0]
- assert "同一个 watch/task callback" in text
- assert "已合并的 callback 消息" in text
-
-
def test_flush_preserves_scheduled_prompt_whitespace(tmp_path, monkeypatch):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
session_id = _seed_avibe_session_with_queue(
@@ -4802,156 +5286,6 @@ def test_flush_preserves_scheduled_prompt_whitespace(tmp_path, monkeypatch):
assert runs[0][0] == " indented: true\n"
-def test_flush_skips_scheduled_callback_when_native_id_already_claimed(tmp_path, monkeypatch):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- session_id = _seed_avibe_session_with_queue(
- [
- (
- "duplicate callback",
- {
- "message_id": "watch:def-watch:run-2",
- "platform_specific": {
- "task_execution_id": "run-2",
- "task_trigger_kind": "watch",
- "task_definition_id": "def-watch",
- },
- },
- )
- ]
- )
-
- from storage import messages_service
- from storage.db import create_sqlite_engine
-
- with create_sqlite_engine().begin() as conn:
- queued = messages_service.list_queued(conn, session_id)
- messages_service.delete_queued(conn, [queued[0]["id"]])
- messages_service.append(
- conn,
- scope_id=queued[0]["scope_id"],
- session_id=session_id,
- platform="avibe",
- author="harness",
- source="harness",
- message_type=messages_service.HARNESS_DEDUPE_TYPE,
- text="",
- metadata={"coalesced_from": "older-row"},
- native_message_id="watch:def-watch:run-2",
- )
- messages_service.append(
- conn,
- scope_id=queued[0]["scope_id"],
- session_id=session_id,
- platform="avibe",
- author="harness",
- source="harness",
- message_type=messages_service.QUEUED_TYPE,
- text="duplicate callback",
- metadata={
- session_turns.SCHEDULED_PROVENANCE_KEY: {
- "message_id": "watch:def-watch:run-2",
- "platform_specific": {
- "task_execution_id": "run-2",
- "task_trigger_kind": "watch",
- "task_definition_id": "def-watch",
- },
- }
- },
- native_message_id=None,
- )
-
- mgr, runs = _manager_capturing_runs()
-
- assert asyncio.run(mgr.flush_queue(session_id)) is False
- assert runs == []
- with create_sqlite_engine().begin() as conn:
- assert messages_service.list_queued(conn, session_id) == []
-
-
-def test_flush_drops_only_claimed_scheduled_callbacks(tmp_path, monkeypatch):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
-
- def prov(execution_id: str) -> dict:
- return {
- "message_id": f"watch:def-watch:{execution_id}",
- "platform_specific": {
- "task_execution_id": execution_id,
- "task_trigger_kind": "watch",
- "task_definition_id": "def-watch",
- },
- }
-
- session_id = _seed_avibe_session_with_queue(
- [
- ("duplicate callback", prov("run-1")),
- ("fresh callback", prov("run-2")),
- ]
- )
-
- from storage import messages_service
- from storage.db import create_sqlite_engine
-
- with create_sqlite_engine().begin() as conn:
- from sqlalchemy import update
-
- from storage.models import messages
-
- queued = messages_service.list_queued(conn, session_id)
- duplicate = queued[0]
- fresh = queued[1]
- messages_service.delete_queued(conn, [duplicate["id"]])
- messages_service.append(
- conn,
- scope_id=duplicate["scope_id"],
- session_id=session_id,
- platform="avibe",
- author="harness",
- source="harness",
- message_type=messages_service.HARNESS_DEDUPE_TYPE,
- text="",
- metadata={"coalesced_from": "older-row"},
- native_message_id="watch:def-watch:run-1",
- )
- duplicate = messages_service.append(
- conn,
- scope_id=duplicate["scope_id"],
- session_id=session_id,
- platform="avibe",
- author="harness",
- source="harness",
- message_type=messages_service.QUEUED_TYPE,
- text="duplicate callback",
- metadata={
- session_turns.SCHEDULED_PROVENANCE_KEY: {
- "message_id": "watch:def-watch:run-1",
- "platform_specific": {
- "task_execution_id": "run-1",
- "task_trigger_kind": "watch",
- "task_definition_id": "def-watch",
- },
- }
- },
- native_message_id=None,
- )
- conn.execute(
- update(messages)
- .where(messages.c.id == duplicate["id"])
- .values(created_at="2026-06-22T00:00:00Z")
- )
- conn.execute(update(messages).where(messages.c.id == fresh["id"]).values(created_at="2026-06-22T00:00:01Z"))
-
- mgr, runs = _manager_capturing_runs()
-
- assert asyncio.run(mgr.flush_queue(session_id)) is True
- assert len(runs) == 1
- text, source, ctx = runs[0]
- assert (text, source) == ("fresh callback", SOURCE_SCHEDULED)
- assert ctx.message_id == "watch:def-watch:run-2"
- assert ctx.platform_specific["task_execution_id"] == "run-2"
- with create_sqlite_engine().begin() as conn:
- assert messages_service.list_queued(conn, session_id) == []
-
-
def test_flush_does_not_mark_native_ids_when_context_build_fails(tmp_path, monkeypatch):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
session_id = _seed_avibe_session_with_queue(
@@ -4971,7 +5305,6 @@ def test_flush_does_not_mark_native_ids_when_context_build_fails(tmp_path, monke
]
)
- from storage import messages_service
from storage.db import create_sqlite_engine
mgr = session_turns.SessionTurnManager(
@@ -4981,209 +5314,8 @@ def test_flush_does_not_mark_native_ids_when_context_build_fails(tmp_path, monke
assert asyncio.run(mgr.flush_queue(session_id)) is False
with create_sqlite_engine().begin() as conn:
- from sqlalchemy import select
-
- from storage.models import messages
-
- rows = conn.execute(select(messages).where(messages.c.session_id == session_id)).mappings().all()
- assert [row for row in rows if row["type"] == messages_service.HARNESS_DEDUPE_TYPE] == []
-
-
-def test_flush_continues_after_dropping_duplicate_scheduled_segment(tmp_path, monkeypatch):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- session_id = _seed_avibe_session_with_queue(
- [
- (
- "duplicate callback",
- {
- "message_id": "watch:def-watch:run-2",
- "platform_specific": {
- "task_execution_id": "run-2",
- "task_trigger_kind": "watch",
- "task_definition_id": "def-watch",
- },
- },
- ),
- ("queued user follow-up", None),
- ]
- )
-
- from storage import messages_service
- from storage.db import create_sqlite_engine
-
- with create_sqlite_engine().begin() as conn:
- from sqlalchemy import update
-
- from storage.models import messages
-
- queued = messages_service.list_queued(conn, session_id)
- messages_service.delete_queued(conn, [queued[0]["id"]])
- messages_service.append(
- conn,
- scope_id=queued[0]["scope_id"],
- session_id=session_id,
- platform="avibe",
- author="harness",
- source="harness",
- message_type=messages_service.HARNESS_DEDUPE_TYPE,
- text="",
- metadata={"coalesced_from": "older-row"},
- native_message_id="watch:def-watch:run-2",
- )
- messages_service.append(
- conn,
- scope_id=queued[0]["scope_id"],
- session_id=session_id,
- platform="avibe",
- author="harness",
- source="harness",
- message_type=messages_service.QUEUED_TYPE,
- text="duplicate callback",
- metadata={
- session_turns.SCHEDULED_PROVENANCE_KEY: {
- "message_id": "watch:def-watch:run-2",
- "platform_specific": {
- "task_execution_id": "run-2",
- "task_trigger_kind": "watch",
- "task_definition_id": "def-watch",
- },
- }
- },
- native_message_id=None,
- )
- queued = messages_service.list_queued(conn, session_id)
- for row in queued:
- created_at = "2026-06-22T00:00:00Z" if row["text"] == "duplicate callback" else "2026-06-22T00:01:00Z"
- conn.execute(update(messages).where(messages.c.id == row["id"]).values(created_at=created_at))
-
- mgr, runs = _manager_capturing_runs()
-
- assert asyncio.run(mgr.flush_queue(session_id)) is True
- assert [(text, source) for text, source, _ in runs] == [("queued user follow-up", SOURCE_HUMAN)]
- with create_sqlite_engine().begin() as conn:
- assert messages_service.list_queued(conn, session_id) == []
- visible = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
- assert runs[0][2].message_id == visible["messages"][0]["id"]
-
-
-def test_flush_does_not_coalesce_scheduled_callbacks_outside_window(tmp_path, monkeypatch):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
-
- def prov(execution_id: str) -> dict:
- return {
- "message_id": f"watch:def-watch:{execution_id}",
- "platform_specific": {
- "task_execution_id": execution_id,
- "task_trigger_kind": "watch",
- "task_definition_id": "def-watch",
- },
- }
-
- session_id = _seed_avibe_session_with_queue(
- [
- ("first callback", prov("run-1")),
- ("late callback", prov("run-2")),
- ]
- )
-
- from sqlalchemy import update
-
- from storage import messages_service
- from storage.db import create_sqlite_engine
- from storage.models import messages
-
- with create_sqlite_engine().begin() as conn:
- rows = messages_service.list_queued(conn, session_id)
- conn.execute(update(messages).where(messages.c.id == rows[0]["id"]).values(created_at="2026-06-22T00:00:00Z"))
- conn.execute(update(messages).where(messages.c.id == rows[1]["id"]).values(created_at="2026-06-22T00:02:01Z"))
-
- mgr, runs = _manager_capturing_runs()
-
- assert asyncio.run(mgr.flush_queue(session_id)) is True
- assert [(text, source) for text, source, _ in runs] == [("first callback", SOURCE_SCHEDULED)]
- with create_sqlite_engine().begin() as conn:
- remaining = messages_service.list_queued(conn, session_id)
- assert [row["text"] for row in remaining] == ["late callback"]
-
-
-def test_flush_segments_user_then_scheduled_in_order(tmp_path, monkeypatch):
- """A mixed queue drains one segment per flush, in order: leading user rows merge
- into one user turn; the scheduled row then runs separately with its provenance.
- The completion-reflush handles the next segment, so one flush runs only the first
- segment and leaves the rest (#84)."""
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- session_id = _seed_avibe_session_with_queue(
- [
- ("u1", None),
- ("u2", None),
- ("sched", {"message_id": "scheduled:x", "platform_specific": {"suppress_delivery": True}}),
- ]
- )
- mgr, runs = _manager_capturing_runs()
-
- from storage import messages_service
- from storage.db import create_sqlite_engine
-
- # First flush: leading user rows merge into one user turn; the scheduled row stays.
- assert asyncio.run(mgr.flush_queue(session_id)) is True
- assert [(t, s) for t, s, _ in runs] == [("u1\nu2", SOURCE_HUMAN)]
- assert "suppress_delivery" not in (runs[0][2].platform_specific or {})
- with create_sqlite_engine().begin() as conn:
- remaining = messages_service.list_queued(conn, session_id)
- assert [r["text"] for r in remaining] == ["sched"]
-
- # Second flush (what the turn completion triggers): the scheduled row runs as
- # SOURCE_SCHEDULED with its provenance.
- assert asyncio.run(mgr.flush_queue(session_id)) is True
- assert (runs[-1][0], runs[-1][1]) == ("sched", SOURCE_SCHEDULED)
- assert runs[-1][2].platform_specific["suppress_delivery"] is True
-
-
-def test_flush_mixed_owner_user_rows_preserves_owner_list(tmp_path, monkeypatch):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
-
- from core.services import sessions as sessions_service
- from storage import messages_service
- from storage.db import create_sqlite_engine
- from storage.importer import ensure_sqlite_state
- from storage.settings_service import upsert_scope
-
- ensure_sqlite_state()
- engine = create_sqlite_engine()
- with engine.begin() as conn:
- scope_id = upsert_scope(
- conn, platform="avibe", scope_type="project", native_id="proj_mixed_owner", now="2026-05-31T00:00:00Z"
- )
- _seed_project_workdir(conn, scope_id, tmp_path)
- session = sessions_service.create_session(
- conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
- )
- for text, owner in (("u1", "remote:user-a"), ("u2", "remote:user-b")):
- messages_service.append(
- conn,
- scope_id=scope_id,
- session_id=session["id"],
- platform="avibe",
- author="user",
- source="user",
- message_type=messages_service.QUEUED_TYPE,
- text=text,
- author_id=owner,
- metadata={"_web_push_user_key": owner},
- )
-
- mgr, runs = _manager_capturing_runs()
-
- assert asyncio.run(mgr.flush_queue(session["id"])) is True
- assert [(t, s) for t, s, _ in runs] == [("u1\nu2", SOURCE_HUMAN)]
- with engine.connect() as conn:
- transcript = messages_service.list_session_messages(conn, session_id=session["id"], types=("user",))
- assert transcript["messages"][0]["author_id"] is None
- assert transcript["messages"][0]["metadata"]["_web_push_user_keys"] == [
- "remote:user-a",
- "remote:user-b",
- ]
- assert "_web_push_user_key" not in transcript["messages"][0]["metadata"]
+ queued = message_deliveries.list_queued(conn, session_id)
+ assert [row["native_message_id"] for row in queued] == ["watch:def-watch:run-1"]
def test_capture_scheduled_provenance_keeps_delivery_drops_routing():
@@ -5221,3 +5353,109 @@ def test_capture_scheduled_provenance_keeps_delivery_drops_routing():
# Routing keys the flush rebuilds are NOT carried.
for routing in ("platform", "is_dm", "agent_session_id", "agent_session_target"):
assert routing not in spec
+
+
+def test_boot_queue_recovery_stops_when_durable_owner_recovery_fails(
+ monkeypatch,
+ tmp_path,
+):
+ import uvicorn
+
+ calls: list[str] = []
+
+ async def fail_delivery_recovery(*, service_restart=False):
+ assert service_restart is True
+ calls.append("delivery")
+ raise RuntimeError("owner recovery failed")
+
+ async def recover_queue():
+ calls.append("queue")
+ return []
+
+ manager = SimpleNamespace(
+ recover_durable_delivery_state=fail_delivery_recovery,
+ recover_persisted_agent_run_queue=recover_queue,
+ )
+ controller = SimpleNamespace(session_turns=manager)
+
+ class _Server:
+ def __init__(self, _config):
+ pass
+
+ async def serve(self, *, sockets):
+ assert len(sockets) == 1
+ calls.append("serve")
+
+ listener = SimpleNamespace(close=lambda: calls.append("close"))
+ monkeypatch.setattr(internal_server, "create_app", lambda _controller: object())
+ monkeypatch.setattr(
+ internal_server,
+ "_bind_socket",
+ lambda _path: (listener, tmp_path / "internal.sock"),
+ )
+ monkeypatch.setattr(uvicorn, "Config", lambda *_args, **_kwargs: object())
+ monkeypatch.setattr(uvicorn, "Server", _Server)
+
+ asyncio.run(internal_server.serve(controller))
+
+ assert calls == ["delivery", "serve", "close"]
+
+
+def test_boot_waits_for_backend_restore_before_delivery_recovery(
+ monkeypatch,
+ tmp_path,
+):
+ import uvicorn
+
+ calls: list[str] = []
+ restore_barrier = asyncio.Event()
+ recovery_complete = asyncio.Event()
+
+ async def recover_deliveries(*, service_restart=False):
+ assert service_restart is True
+ calls.append("delivery")
+ return []
+
+ async def recover_queue():
+ calls.append("queue")
+ return []
+
+ manager = SimpleNamespace(
+ recover_durable_delivery_state=recover_deliveries,
+ recover_persisted_agent_run_queue=recover_queue,
+ )
+ controller = SimpleNamespace(
+ session_turns=manager,
+ _delivery_recovery_barrier=restore_barrier,
+ _delivery_recovery_complete=recovery_complete,
+ )
+
+ class _Server:
+ def __init__(self, _config):
+ pass
+
+ async def serve(self, *, sockets):
+ assert len(sockets) == 1
+ assert recovery_complete.is_set()
+ calls.append("serve")
+
+ listener = SimpleNamespace(close=lambda: calls.append("close"))
+ monkeypatch.setattr(internal_server, "create_app", lambda _controller: object())
+ monkeypatch.setattr(
+ internal_server,
+ "_bind_socket",
+ lambda _path: (listener, tmp_path / "internal.sock"),
+ )
+ monkeypatch.setattr(uvicorn, "Config", lambda *_args, **_kwargs: object())
+ monkeypatch.setattr(uvicorn, "Server", _Server)
+
+ async def _run() -> None:
+ serving = asyncio.create_task(internal_server.serve(controller))
+ await asyncio.sleep(0)
+ assert calls == []
+ restore_barrier.set()
+ await serving
+
+ asyncio.run(_run())
+
+ assert calls == ["delivery", "queue", "serve", "close"]
diff --git a/tests/test_message_delivery_authority.py b/tests/test_message_delivery_authority.py
new file mode 100644
index 000000000..60c1b9a17
--- /dev/null
+++ b/tests/test_message_delivery_authority.py
@@ -0,0 +1,479 @@
+from __future__ import annotations
+
+import ast
+import json
+from pathlib import Path
+
+import pytest
+from sqlalchemy import select
+
+from storage.agent_session_rows import reserve_write_lock
+from storage.db import create_sqlite_engine
+from storage.models import agent_sessions, message_deliveries, messages, metadata, session_turns
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+PSEUDO_MESSAGE_TYPES = {
+ "queued",
+ "pending",
+ "draft",
+ "harness_dedupe",
+ "silent",
+ "tool_call",
+}
+
+
+def _seed_session(conn, session_id: str = "ses_authority") -> None:
+ now = "2026-08-01T00:00:00+00:00"
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=None,
+ agent_id=None,
+ agent_name="codex",
+ agent_backend="codex",
+ agent_variant="codex",
+ model=None,
+ reasoning_effort=None,
+ session_anchor=session_id,
+ workdir="/tmp",
+ native_session_id="",
+ title=None,
+ status="active",
+ visibility="foreground",
+ pinned=0,
+ agent_status="idle",
+ queue_hold_state="open",
+ queue_hold_version=1,
+ queue_held_at=None,
+ composer_draft_text=None,
+ composer_draft_updated_at=None,
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+
+def test_delivery_schema_has_one_queue_owner_and_turn_owns_native_start() -> None:
+ assert not (REPO_ROOT / "storage" / "session_deliveries.py").exists()
+ assert message_deliveries.name == "message_deliveries"
+ assert {
+ "start_attempt_id",
+ "start_receipt_outcome",
+ "start_receipt_json",
+ "dispatch_text",
+ "dispatch_sha256",
+ } <= set(session_turns.c.keys())
+ assert {
+ "snapshot_json",
+ "snapshot_sha256",
+ "dispatch_text",
+ "dispatch_sha256",
+ "current_attempt_id",
+ "turn_id",
+ "turn_role",
+ "turn_position",
+ "current_attempt_kind",
+ "current_target_turn_id",
+ "current_expected_native_turn_id",
+ "current_receipt_outcome",
+ "delivery_history_json",
+ "version",
+ } <= set(message_deliveries.c.keys())
+
+
+def test_batch_relationship_allows_many_deliveries_to_one_message_and_turn() -> None:
+ message_id_constraints = {
+ constraint.name
+ for constraint in message_deliveries.constraints
+ if getattr(constraint, "name", None)
+ }
+ assert "uq_message_deliveries_message" not in message_id_constraints
+ assert "ck_message_deliveries_stable_message_id" not in message_id_constraints
+
+
+def test_unaccepted_submission_has_no_message_and_materializes_once(tmp_path: Path) -> None:
+ from storage import message_deliveries as delivery_store
+
+ engine = create_sqlite_engine(tmp_path / "state.sqlite")
+ metadata.create_all(engine)
+ snapshot = delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_authority",
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="display text",
+ metadata={"origin": "test"},
+ )
+ with engine.begin() as conn:
+ _seed_session(conn)
+ delivery = delivery_store.insert_delivery(
+ conn,
+ delivery_id="msg_submission",
+ session_id="ses_authority",
+ priority="p3",
+ state="queued",
+ snapshot=snapshot,
+ dispatch_text="exact agent prompt",
+ )
+ delivery_store.claim_start_batch(
+ conn,
+ turn_id="turn_initial",
+ session_id="ses_authority",
+ backend="codex",
+ deliveries=[delivery],
+ dispatch_text="exact agent prompt",
+ attempt_id="atm_start",
+ )
+ with engine.connect() as conn:
+ assert conn.execute(select(messages.c.id)).all() == []
+
+ with engine.begin() as conn:
+ unproven = delivery_store.materialize_start_acceptance(
+ conn,
+ turn_id="turn_initial",
+ evidence={"kind": "terminal_result_without_start_receipt"},
+ )
+ turn = delivery_store.get_turn(conn, "turn_initial")
+ assert turn is not None
+ bound = delivery_store.bind_native_start(
+ conn,
+ "turn_initial",
+ expected_version=int(turn["version"]),
+ runtime_key="runtime-key",
+ runtime_turn_id="runtime-turn",
+ native_turn_id="native-turn",
+ )
+ assert bound is not None
+ materialized = delivery_store.materialize_start_acceptance(
+ conn,
+ turn_id="turn_initial",
+ evidence={"kind": "native_start"},
+ )
+ duplicate = delivery_store.materialize_start_acceptance(
+ conn,
+ turn_id="turn_initial",
+ evidence={"kind": "native_start_replay"},
+ )
+ assert unproven == []
+ assert materialized
+ assert duplicate
+ with engine.connect() as conn:
+ message_rows = conn.execute(select(messages)).mappings().all()
+ delivery = delivery_store.get_delivery(conn, "msg_submission")
+ assert [row["id"] for row in message_rows] == ["msg_submission"]
+ assert message_rows[0]["content_text"] == "display text"
+ assert delivery is not None
+ assert delivery["state"] == "accepted"
+ assert delivery["message_id"] == "msg_submission"
+ assert delivery["snapshot_json"] is None
+ assert delivery["dispatch_text"] is None
+ assert delivery["current_attempt_id"] is None
+
+
+def test_production_message_writers_do_not_create_operational_pseudo_types() -> None:
+ offenders: list[str] = []
+ for root_name in ("core", "modules", "storage", "vibe"):
+ for source_path in sorted((REPO_ROOT / root_name).rglob("*.py")):
+ if "alembic/versions" in source_path.as_posix():
+ continue
+ tree = ast.parse(source_path.read_text(encoding="utf-8"), filename=str(source_path))
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ for keyword in node.keywords:
+ if keyword.arg != "message_type" or not isinstance(keyword.value, ast.Constant):
+ continue
+ if keyword.value.value in PSEUDO_MESSAGE_TYPES:
+ offenders.append(f"{source_path.relative_to(REPO_ROOT)}:{node.lineno}")
+ assert offenders == []
+
+
+def test_legacy_queue_authority_symbols_have_no_production_call_sites() -> None:
+ forbidden = {
+ "session_deliveries",
+ "QUEUED_TYPE",
+ "PENDING_TYPE",
+ "HARNESS_DEDUPE_TYPE",
+ "SILENT_TYPE",
+ "QUEUED_DISPATCH_TEXT_KEY",
+ "messages_service.clear_queued",
+ "messages_service.clear_pending",
+ "messages_service.delete_queued",
+ "messages_service.remove_queued",
+ "persist_silent_completion_marker",
+ "workbench_queue_holds_run",
+ "coalesced_queue",
+ "coalesced_into_run_id",
+ "effective_run_id",
+ "claim_queued_runs_for_workbench",
+ "reset_workbench_claimed_runs",
+ "reset_running_agent_status",
+ "_recover_stale_session_status",
+ "flush_on_cancel",
+ "stop_no_flush",
+ }
+ offenders: list[str] = []
+ for root_name in ("core", "modules", "storage", "vibe"):
+ for source_path in sorted((REPO_ROOT / root_name).rglob("*.py")):
+ if "alembic/versions" in source_path.as_posix():
+ continue
+ source = source_path.read_text(encoding="utf-8")
+ found = sorted(symbol for symbol in forbidden if symbol in source)
+ if found:
+ offenders.append(f"{source_path.relative_to(REPO_ROOT)}: {', '.join(found)}")
+ assert offenders == []
+
+
+def test_messages_type_is_never_delivery_authority() -> None:
+ def is_messages_type(node: ast.AST) -> bool:
+ return (
+ isinstance(node, ast.Attribute)
+ and node.attr == "type"
+ and isinstance(node.value, ast.Attribute)
+ and node.value.attr == "c"
+ and isinstance(node.value.value, ast.Name)
+ and node.value.value.id == "messages"
+ )
+
+ forbidden = {"queued", "pending", "draft", "harness_dedupe", "silent"}
+ offenders: list[str] = []
+ for root_name in ("core", "modules", "storage", "vibe"):
+ for source_path in sorted((REPO_ROOT / root_name).rglob("*.py")):
+ if "alembic/versions" in source_path.as_posix():
+ continue
+ tree = ast.parse(source_path.read_text(encoding="utf-8"), filename=str(source_path))
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Compare):
+ continue
+ candidates = (node.left, *node.comparators)
+ if not any(is_messages_type(candidate) for candidate in candidates):
+ continue
+ compared_values = {
+ candidate.value
+ for candidate in candidates
+ if isinstance(candidate, ast.Constant) and isinstance(candidate.value, str)
+ }
+ if compared_values & forbidden:
+ offenders.append(f"{source_path.relative_to(REPO_ROOT)}:{node.lineno}")
+ assert offenders == []
+
+
+def test_turn_manager_routes_retirement_through_run_settlement_boundary() -> None:
+ source_path = REPO_ROOT / "core" / "session_turns.py"
+ tree = ast.parse(source_path.read_text(encoding="utf-8"), filename=str(source_path))
+ allowed = {
+ "_record_definitive_delivery_attempt",
+ "_retire_delivery_not_written",
+ }
+ offenders: list[str] = []
+ for function in (
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ ):
+ for call in (node for node in ast.walk(function) if isinstance(node, ast.Call)):
+ target = call.func
+ if not (
+ isinstance(target, ast.Attribute)
+ and isinstance(target.value, ast.Name)
+ and target.value.id == "delivery_store"
+ and target.attr in {"record_definitive_attempt", "retire_not_written"}
+ ):
+ continue
+ if function.name not in allowed:
+ offenders.append(f"{function.name}:{call.lineno}")
+ assert offenders == []
+
+
+def test_session_turn_storage_mutations_have_one_module_owner() -> None:
+ offenders: list[str] = []
+ for root_name in ("core", "modules", "storage", "vibe"):
+ for source_path in sorted((REPO_ROOT / root_name).rglob("*.py")):
+ relative = source_path.relative_to(REPO_ROOT).as_posix()
+ if relative == "storage/message_deliveries.py" or "alembic/versions" in relative:
+ continue
+ tree = ast.parse(source_path.read_text(encoding="utf-8"), filename=str(source_path))
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ function = node.func
+ if (
+ isinstance(function, ast.Name)
+ and function.id in {"update", "delete", "insert"}
+ and node.args
+ and isinstance(node.args[0], ast.Name)
+ and node.args[0].id == "session_turns"
+ ) or (
+ isinstance(function, ast.Attribute)
+ and function.attr in {"update", "delete", "insert"}
+ and isinstance(function.value, ast.Name)
+ and function.value.id == "session_turns"
+ ):
+ offenders.append(f"{relative}:{node.lineno}")
+ assert offenders == []
+
+
+def test_terminal_primitive_is_only_called_by_session_turn_manager() -> None:
+ offenders: list[str] = []
+ for root_name in ("core", "modules", "storage", "vibe"):
+ for source_path in sorted((REPO_ROOT / root_name).rglob("*.py")):
+ relative = source_path.relative_to(REPO_ROOT).as_posix()
+ if "alembic/versions" in relative:
+ continue
+ tree = ast.parse(source_path.read_text(encoding="utf-8"), filename=str(source_path))
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ function = node.func
+ is_terminal_call = (
+ isinstance(function, ast.Name)
+ and function.id == "terminalize_turn"
+ ) or (
+ isinstance(function, ast.Attribute)
+ and function.attr == "terminalize_turn"
+ )
+ if is_terminal_call and relative != "core/session_turns.py":
+ offenders.append(f"{relative}:{node.lineno}")
+ assert offenders == []
+
+
+def test_normal_product_paths_do_not_physically_delete_session_messages() -> None:
+ offenders: list[str] = []
+ for root_name in ("core", "modules", "storage", "vibe"):
+ for source_path in sorted((REPO_ROOT / root_name).rglob("*.py")):
+ relative = source_path.relative_to(REPO_ROOT).as_posix()
+ if "alembic/versions" in relative or relative == "storage/migrations.py":
+ continue
+ normalized = " ".join(source_path.read_text(encoding="utf-8").lower().split())
+ if "delete from messages" in normalized or "delete(messages)" in normalized or "messages.delete(" in normalized:
+ offenders.append(relative)
+ assert offenders == []
+
+
+def test_operational_graph_foreign_keys_are_deferred_no_action() -> None:
+ operational_tables = {"agent_sessions", "message_deliveries", "messages", "session_turns"}
+ inspected = 0
+ for table in (message_deliveries, session_turns):
+ for constraint in table.foreign_key_constraints:
+ if constraint.referred_table.name not in operational_tables:
+ continue
+ inspected += 1
+ assert constraint.ondelete == "NO ACTION"
+ assert constraint.deferrable is True
+ assert constraint.initially == "DEFERRED"
+ assert inspected == 8
+
+ message_session_fk = next(
+ constraint
+ for constraint in messages.foreign_key_constraints
+ if constraint.referred_table.name == "agent_sessions"
+ )
+ assert message_session_fk.ondelete == "NO ACTION"
+ assert message_session_fk.deferrable is True
+ assert message_session_fk.initially == "DEFERRED"
+
+
+def test_materialization_cas_loss_cannot_publish_a_message(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from storage import message_deliveries as delivery_store
+
+ engine = create_sqlite_engine(tmp_path / "state.sqlite")
+ metadata.create_all(engine)
+ with engine.begin() as conn:
+ _seed_session(conn)
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id="msg_cas_loser",
+ session_id="ses_authority",
+ priority="p1",
+ state="steering",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_authority",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="must stay private",
+ ),
+ dispatch_text="must stay private",
+ current_attempt_id="atm_cas_loser",
+ current_attempt_kind="steer",
+ current_target_turn_id="turn_target",
+ current_expected_native_turn_id="native_target",
+ )
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id="msg_target",
+ session_id="ses_authority",
+ priority="p3",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_authority",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="target",
+ ),
+ dispatch_text="target",
+ )
+ delivery_store.insert_turn(
+ conn,
+ turn_id="turn_target",
+ session_id="ses_authority",
+ initial_delivery_id="msg_target",
+ state="active",
+ backend="codex",
+ )
+
+ monkeypatch.setattr(delivery_store, "cas_delivery", lambda *args, **kwargs: None)
+ with engine.begin() as conn:
+ assert delivery_store.materialize_acceptance(
+ conn,
+ delivery_id="msg_cas_loser",
+ expected_attempt_id="atm_cas_loser",
+ turn_id="turn_target",
+ evidence={"kind": "accepted_receipt"},
+ ) is None
+ with engine.connect() as conn:
+ assert conn.execute(select(messages.c.id).where(messages.c.id == "msg_cas_loser")).first() is None
+
+
+def test_delivery_history_is_valid_versioned_json(tmp_path: Path) -> None:
+ from storage import message_deliveries as delivery_store
+
+ engine = create_sqlite_engine(tmp_path / "state.sqlite")
+ metadata.create_all(engine)
+ with engine.begin() as conn:
+ _seed_session(conn)
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id="retired_submission",
+ session_id="ses_authority",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_authority",
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="remove me",
+ ),
+ dispatch_text="remove me",
+ )
+ assert delivery_store.retire_queued(conn, "ses_authority", "retired_submission")
+ with engine.connect() as conn:
+ row = delivery_store.get_delivery(conn, "retired_submission")
+ assert conn.execute(select(messages.c.id)).all() == []
+ history = json.loads(str(row["delivery_history_json"]))
+ assert history["version"] == 1
+ assert history["events"][-1]["kind"] == "retire"
diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.py
index 6308a7111..8123dbf15 100644
--- a/tests/test_message_dispatcher_result_fallback.py
+++ b/tests/test_message_dispatcher_result_fallback.py
@@ -258,7 +258,21 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
[item[1] for item in controller.im_client.sent_messages],
["first output", "final output"],
)
- controller.session_turns.on_terminal_result.assert_called_once_with(context, is_error=False)
+ controller.session_turns.on_terminal_result.assert_called_once_with(
+ context,
+ is_error=False,
+ terminal_evidence={
+ "result_text": "final output",
+ "terminal_error": None,
+ "settles_run": True,
+ "output_provenance": {
+ "turn_id": "turn-1",
+ "sequence": 2,
+ "output_id": "output-2",
+ "detached": False,
+ },
+ },
+ )
controller.agent_service.release_runtime_turn.assert_called_once_with(context)
async def test_duplicate_terminal_output_still_settles_lifecycle(self):
@@ -313,7 +327,20 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
"agent-output:unknown:runtime-1:terminal-output",
)
self.assertEqual(controller.im_client.sent_messages, [])
- controller.session_turns.on_terminal_result.assert_called_once_with(context, is_error=False)
+ controller.session_turns.on_terminal_result.assert_called_once_with(
+ context,
+ is_error=False,
+ terminal_evidence={
+ "result_text": "already delivered",
+ "terminal_error": None,
+ "settles_run": True,
+ "output_provenance": {
+ "turn_id": "turn-1",
+ "output_id": "terminal-output",
+ "detached": False,
+ },
+ },
+ )
dispatcher._record_agent_run_terminal_result.assert_called_once_with(
context,
"already delivered",
@@ -408,6 +435,17 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
)
dispatcher._record_agent_run_terminal_result.assert_called_once()
+ async def test_silent_im_terminal_records_non_message_turn_evidence(self):
+ controller = self._terminal_lifecycle_controller()
+
+ with mock.patch("core.message_dispatcher.persist_silent_terminal") as persist:
+ _dispatcher, context = await self._emit_silent_terminal(
+ controller,
+ completes_run=False,
+ )
+
+ persist.assert_called_once_with(context, is_error=False)
+
async def test_stop_output_release_names_the_stop_and_records_no_run_terminal(self):
"""HFR-036: the synthetic result a user stop emits must NOT record the run.
@@ -422,11 +460,12 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
"""
controller = self._terminal_lifecycle_controller()
- dispatcher, context = await self._emit_silent_terminal(
- controller,
- completes_run=False,
- output=stop_output_for(None),
- )
+ with mock.patch("core.message_dispatcher.persist_silent_terminal") as persist:
+ dispatcher, context = await self._emit_silent_terminal(
+ controller,
+ completes_run=False,
+ output=stop_output_for(None),
+ )
controller.mark_turn_complete.assert_called_once_with(
context,
@@ -436,6 +475,7 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
self.assertIn(SETTLED_BY_STOPPED, SETTLEMENTS_WITHOUT_RESULT)
self.assertEqual(SETTLEMENT_TERMINAL_STATUS[SETTLED_BY_STOPPED], "canceled")
dispatcher._record_agent_run_terminal_result.assert_not_called()
+ persist.assert_not_called()
async def test_slack_result_uses_native_markdown_sender_when_available(self):
im_client = _NativeMarkdownIMClient()
@@ -628,6 +668,30 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("[✅ Yes]", persist.call_args.args[2])
self.assertIn("Pick one", persist.call_args.args[2])
+ async def test_visible_workbench_terminal_result_requires_durable_message(self):
+ controller = _StubController(platform="avibe")
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="U1",
+ channel_id="ses-1",
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": "ses-1",
+ "turn_token": "turn-1",
+ },
+ )
+ dispatcher._is_current_runtime_turn = mock.Mock(return_value=True)
+
+ with mock.patch(
+ "core.message_dispatcher.persist_agent_message",
+ return_value=None,
+ ):
+ with self.assertRaisesRegex(
+ RuntimeError,
+ "Workbench terminal output was not durably persisted",
+ ):
+ await dispatcher.emit_agent_message(context, "result", "done")
+
async def test_workbench_run_settles_only_after_result_persistence(self):
"""A callback child stays pending until its Workbench receipt exists."""
@@ -1004,66 +1068,21 @@ class MessageDispatcherStatusChokepointTests(unittest.IsolatedAsyncioTestCase):
async def test_terminal_result_settles_dot_idle(self):
controller = _AvibeStatusController()
dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = _avibe_ctx()
with mock.patch("core.message_dispatcher.persist_agent_message"):
- await dispatcher.emit_agent_message(_avibe_ctx(), "result", "")
+ await dispatcher.emit_agent_message(context, "result", "")
+ controller.session_turns.on_terminal_delivery_complete(context)
self.assertEqual(controller.status_calls, [("ses-1", "idle")])
async def test_terminal_error_result_settles_dot_failed(self):
controller = _AvibeStatusController()
dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = _avibe_ctx()
with mock.patch("core.message_dispatcher.persist_agent_message"):
- await dispatcher.emit_agent_message(_avibe_ctx(), "result", "", is_error=True)
+ await dispatcher.emit_agent_message(context, "result", "", is_error=True)
+ controller.session_turns.on_terminal_delivery_complete(context)
self.assertEqual(controller.status_calls, [("ses-1", "failed")])
- async def test_clean_silent_completion_writes_marker(self):
- # The fix: a clean (non-error) terminal result with no visible body — a
- # ``<silent>``-stripped / empty final reply — persists the invisible ``silent``
- # marker so the activity grouping closes the turn as DONE, not interrupted.
- controller = _AvibeStatusController()
- dispatcher = ConsolidatedMessageDispatcher(controller)
- ctx = _avibe_ctx()
- with mock.patch("core.message_dispatcher.persist_agent_message"), mock.patch(
- "core.message_dispatcher.persist_silent_completion_marker"
- ) as marker:
- await dispatcher.emit_agent_message(ctx, "result", "")
- marker.assert_called_once_with(ctx)
-
- async def test_user_stop_writes_no_marker(self):
- # The REAL stop paths (codex/claude/opencode) emit a terminal result with
- # ``level='silent'`` and ``is_error=False`` — a stop legitimately stays
- # interrupted, so NO silent marker. (``not is_error`` alone would wrongly mark
- # it — the gate keys on ``level != 'silent'`` too. P1.)
- controller = _AvibeStatusController()
- dispatcher = ConsolidatedMessageDispatcher(controller)
- with mock.patch("core.message_dispatcher.persist_agent_message"), mock.patch(
- "core.message_dispatcher.persist_silent_completion_marker"
- ) as marker:
- await dispatcher.emit_agent_message(_avibe_ctx(), "result", "", level="silent")
- marker.assert_not_called()
-
- async def test_error_completion_writes_no_marker(self):
- # An ``is_error`` terminal is a FAILURE, never a done marker.
- controller = _AvibeStatusController()
- dispatcher = ConsolidatedMessageDispatcher(controller)
- with mock.patch("core.message_dispatcher.persist_agent_message"), mock.patch(
- "core.message_dispatcher.persist_silent_completion_marker"
- ) as marker:
- await dispatcher.emit_agent_message(_avibe_ctx(), "result", "", is_error=True)
- marker.assert_not_called()
-
- async def test_suppress_delivery_writes_local_marker(self):
- controller = _AvibeStatusController()
- dispatcher = ConsolidatedMessageDispatcher(controller)
- ctx = MessageContext(
- user_id="U1", channel_id="ses-1", platform="avibe",
- platform_specific={"agent_session_id": "ses-1", "suppress_delivery": True},
- )
- with mock.patch("core.message_dispatcher.persist_agent_message"), mock.patch(
- "core.message_dispatcher.persist_silent_completion_marker"
- ) as marker:
- await dispatcher.emit_agent_message(ctx, "result", "")
- marker.assert_called_once_with(ctx)
-
async def test_silent_backend_failure_collapses_status_as_failed(self):
controller = _AvibeStatusController()
dispatcher = ConsolidatedMessageDispatcher(controller)
@@ -1120,6 +1139,7 @@ class MessageDispatcherStatusChokepointTests(unittest.IsolatedAsyncioTestCase):
)
with mock.patch("core.message_dispatcher.persist_agent_message"):
await dispatcher.emit_agent_message(ctx, "result", "")
+ controller.session_turns.on_terminal_delivery_complete(ctx)
self.assertEqual(controller.status_calls, [("ses-1", "idle")])
async def test_tokenless_result_does_not_settle_dot_when_live_turn_exists(self):
@@ -1148,10 +1168,12 @@ class MessageDispatcherStatusChokepointTests(unittest.IsolatedAsyncioTestCase):
# replacing the old "fake invisibility via empty text" trick.
controller = _AvibeStatusController()
dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = _avibe_ctx()
with mock.patch("core.message_dispatcher.persist_agent_message") as persist:
message_id = await dispatcher.emit_agent_message(
- _avibe_ctx(), "result", "🛑 stopped", level="silent"
+ context, "result", "🛑 stopped", level="silent"
)
+ controller.session_turns.on_terminal_delivery_complete(context)
self.assertIsNone(message_id)
self.assertEqual(controller.status_calls, [("ses-1", "idle")]) # dot still settles
persist.assert_not_called() # never recorded in history
diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.py
index 7ebdbe6af..dac8f79de 100644
--- a/tests/test_message_dispatcher_scheduled.py
+++ b/tests/test_message_dispatcher_scheduled.py
@@ -653,6 +653,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
platform="slack",
platform_specific={
"suppress_delivery": True,
+ "task_trigger_kind": "agent_run",
"task_execution_id": "run-1",
},
)
@@ -672,7 +673,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(
calls,
[
- ("record", "run-1", "private output", "suppressed:run-1", None),
+ ("record", "run-1", "private output", "suppressed:run-1", "succeeded"),
("close",),
],
)
@@ -762,7 +763,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
"suppress_delivery": True,
"task_trigger_kind": "agent_run",
"task_execution_id": "run-1",
- "coalesced_queue": {"execution_ids": ["run-1", "run-2", "run-3"]},
+ "accepted_agent_run_ids": ["run-1", "run-2", "run-3"],
},
)
calls = []
@@ -799,7 +800,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
"suppress_delivery": True,
"task_trigger_kind": "agent_run",
"task_execution_id": "run-1",
- "coalesced_queue": {"execution_ids": ["run-1", "run-2", "run-3"]},
+ "accepted_agent_run_ids": ["run-1", "run-2", "run-3"],
},
)
calls = []
@@ -839,7 +840,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
platform_specific={
"task_trigger_kind": "agent_run",
"task_execution_id": "run-1",
- "coalesced_queue": {"execution_ids": ["run-1", "run-2", "run-3"]},
+ "accepted_agent_run_ids": ["run-1", "run-2", "run-3"],
},
)
calls = []
@@ -865,6 +866,42 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
],
)
+ async def test_human_turn_result_settles_accepted_steer_agent_run(self):
+ controller = _StubController()
+ controller.session_turns = SimpleNamespace(
+ accepted_agent_run_ids_for_turn=lambda turn_id: (
+ ["run-steered"] if turn_id == "turn-active" else []
+ ),
+ on_terminal_result=lambda *_args, **_kwargs: None,
+ )
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="human",
+ channel_id="C123",
+ platform="slack",
+ platform_specific={"turn_token": "turn-active"},
+ )
+ calls = []
+
+ class _Store:
+ def record_run_message(self, run_id, *, text, message_id=None, terminal_status=None):
+ calls.append((run_id, text, message_id, terminal_status))
+
+ def close(self):
+ calls.append(("close",))
+
+ with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()):
+ message_id = await dispatcher.emit_agent_message(context, "result", "steered result")
+
+ self.assertEqual(message_id, "bot-msg-1")
+ self.assertEqual(
+ calls,
+ [
+ ("run-steered", "steered result", "bot-msg-1", "succeeded"),
+ ("close",),
+ ],
+ )
+
async def test_coalesced_agent_run_result_preserves_cancelled_child(self):
controller = _StubController()
dispatcher = ConsolidatedMessageDispatcher(controller)
@@ -875,7 +912,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
platform_specific={
"task_trigger_kind": "agent_run",
"task_execution_id": "run-1",
- "coalesced_queue": {"execution_ids": ["run-1", "run-2", "run-3"]},
+ "accepted_agent_run_ids": ["run-1", "run-2", "run-3"],
},
)
calls = []
@@ -915,7 +952,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
platform_specific={
"task_trigger_kind": "agent_run",
"task_execution_id": "run-1",
- "coalesced_queue": {"execution_ids": ["run-1", "run-2"]},
+ "accepted_agent_run_ids": ["run-1", "run-2"],
},
)
calls = []
@@ -995,6 +1032,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
platform="slack",
platform_specific={
"suppress_delivery": True,
+ "task_trigger_kind": "agent_run",
"task_execution_id": "run-1",
},
)
@@ -1012,13 +1050,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(message_id, "suppressed:run-1")
self.assertEqual(controller.im_client.sent, [])
- self.assertEqual(
- calls,
- [
- ("record", "run-1", "auth recovery required", "suppressed:run-1", None),
- ("close",),
- ],
- )
+ self.assertEqual(calls, [])
async def test_visible_agent_run_result_marks_run_terminal(self):
controller = _StubController()
diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.py
index 04832612e..f1cb882c7 100644
--- a/tests/test_message_handler_typing.py
+++ b/tests/test_message_handler_typing.py
@@ -1258,6 +1258,27 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(result, "boom")
self.assertEqual(controller.im_client.sent_messages, [("C1", "Error: boom")])
+ async def test_durable_scheduled_turn_does_not_mirror_before_acceptance(self):
+ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)
+ handler = MessageHandler(controller)
+ handler.set_session_handler(_StubSessionHandler())
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id="C1",
+ message_id="watch:native-1",
+ platform="slack",
+ platform_specific={
+ "delivery_id": "msg_delivery_1",
+ "delivery_ids": ["msg_delivery_1"],
+ },
+ )
+
+ with patch("core.message_mirror.mirror_harness_inbound") as mirror:
+ await handler.handle_scheduled_message(context, "hello")
+
+ mirror.assert_not_called()
+ self.assertEqual(len(controller.agent_service.requests), 1)
+
async def test_resume_session_callback_preserves_platform(self):
controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)
setattr(
diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.py
index 524a226cf..5c07733bf 100644
--- a/tests/test_message_mirror.py
+++ b/tests/test_message_mirror.py
@@ -30,7 +30,7 @@ from core.message_mirror import (
mirror_harness_inbound,
mirror_inbound,
persist_agent_message,
- persist_silent_completion_marker,
+ persist_silent_terminal,
)
from modules.im import MessageContext
from storage import messages_service
@@ -289,6 +289,62 @@ def test_persist_agent_im_uses_delivery_scope_not_session(isolated_state):
assert row["content_text"] == "routed answer"
+def test_silent_im_terminal_is_trace_evidence_not_transcript(isolated_state):
+ engine = create_sqlite_engine()
+ now = "2026-06-01T10:00:00Z"
+ with engine.begin() as conn:
+ source_scope = upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C_source_terminal",
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_im_terminal",
+ scope_id=source_scope,
+ agent_name="codex",
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="anchor_ses_im_terminal",
+ native_session_id="",
+ status="active",
+ visibility="foreground",
+ pinned=0,
+ agent_status="running",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ context = MessageContext(
+ user_id="U_terminal",
+ channel_id="C_delivery_terminal",
+ platform="slack",
+ platform_specific={
+ "agent_session_id": "ses_im_terminal",
+ "turn_token": "turn-im-terminal",
+ },
+ )
+
+ persist_silent_terminal(context, is_error=True)
+
+ with engine.connect() as conn:
+ event = conn.execute(
+ select(agent_events).where(
+ agent_events.c.session_id == "ses_im_terminal"
+ )
+ ).mappings().one()
+ transcript_row = conn.execute(
+ select(messages).where(messages.c.session_id == "ses_im_terminal")
+ ).first()
+ assert event["event_type"] == "silent_terminal"
+ assert json.loads(event["metadata_json"])["terminal_outcome"] == "failed"
+ assert transcript_row is None
+
+
def test_duplicate_native_message_id_is_swallowed(isolated_state):
ctx = _slack_ctx(message_id="dup_id")
mirror_inbound(ctx, "first")
@@ -987,89 +1043,3 @@ def test_avibe_inbound_is_noop(isolated_state):
with engine.connect() as conn:
rows = conn.execute(select(messages).where(messages.c.author == "user")).mappings().all()
assert rows == []
-
-
-def test_silent_completion_marker_persisted_but_invisible(isolated_state):
- """``persist_silent_completion_marker`` writes an agent-authored ``silent`` row
- (empty text, content.kind='silent') that is EXCLUDED from the transcript allowlist
- and from the inbox conversation clock, so the last visible message is unchanged."""
- engine = create_sqlite_engine()
- now = "2026-05-30T12:00:00Z"
- with engine.begin() as conn:
- scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_sil", now=now)
- conn.execute(
- agent_sessions.insert().values(
- id="ses_sil", scope_id=scope_id, agent_backend="claude", agent_variant="default",
- session_anchor="anchor_ses_sil", native_session_id="", status="active", metadata_json="{}",
- created_at=now, updated_at=now, last_active_at=now,
- )
- )
- # A real, visible reply for an earlier turn — must stay the "last visible" one.
- conn.execute(
- messages.insert().values(
- id="m_vis", scope_id=scope_id, session_id="ses_sil", platform="avibe", author="agent",
- type="result", source="agent", content_text="the visible answer", content_json="{}",
- metadata_json="{}", created_at=now, updated_at=now,
- )
- )
-
- ctx = MessageContext(
- user_id="workbench", channel_id="ses_sil", platform="avibe",
- platform_specific={"agent_session_id": "ses_sil"},
- )
- persist_silent_completion_marker(ctx)
-
- with engine.connect() as conn:
- rows = conn.execute(select(messages).where(messages.c.session_id == "ses_sil")).mappings().all()
- transcript = messages_service.list_session_messages(
- conn, session_id="ses_sil", limit=50, tail=True, types=messages_service.TRANSCRIPT_TYPES
- )["messages"]
-
- silent_rows = [r for r in rows if r["type"] == "silent"]
- assert len(silent_rows) == 1 # persisted
- assert silent_rows[0]["author"] == "agent"
- assert (silent_rows[0]["content_text"] or "") == ""
- assert json.loads(silent_rows[0]["content_json"]).get("kind") == "silent"
-
- # Invisible: excluded from the transcript allowlist; last visible row unchanged.
- assert "silent" not in [m["type"] for m in transcript]
- assert transcript[-1]["type"] == "result" and transcript[-1]["text"] == "the visible answer"
- # And kept out of the inbox conversation clock (never bumps last-activity/author).
- assert messages_service.SILENT_TYPE in messages_service.NON_CONVERSATION_TYPES
- assert messages_service.SILENT_TYPE not in messages_service.TRANSCRIPT_TYPES
-
-
-def test_silent_completion_marker_publishes_inbox_update_not_message(isolated_state):
- """The marker clears the inbox awaiting flag, so it publishes ``inbox.session.updated``
- (live sidebar refresh) — but NOT ``message.new`` (no transcript bubble)."""
- from unittest import mock
-
- engine = create_sqlite_engine()
- now = "2026-05-30T12:00:00Z"
- with engine.begin() as conn:
- scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_pub", now=now)
- conn.execute(
- agent_sessions.insert().values(
- id="ses_pub", scope_id=scope_id, agent_backend="claude", agent_variant="default",
- session_anchor="anchor_ses_pub", native_session_id="", status="active", metadata_json="{}",
- created_at=now, updated_at=now, last_active_at=now,
- )
- )
- conn.execute(
- messages.insert().values(
- id="m_vis", scope_id=scope_id, session_id="ses_pub", platform="avibe", author="agent",
- type="result", source="agent", content_text="visible", content_json="{}",
- metadata_json="{}", created_at=now, updated_at=now,
- )
- )
-
- ctx = MessageContext(
- user_id="workbench", channel_id="ses_pub", platform="avibe",
- platform_specific={"agent_session_id": "ses_pub"},
- )
- with mock.patch("core.inbox_events.bus.publish") as publish:
- persist_silent_completion_marker(ctx)
-
- published = [call.args[0] for call in publish.call_args_list]
- assert "inbox.session.updated" in published # sidebar awaiting clears live
- assert "message.new" not in published # invisible: no transcript bubble
diff --git a/tests/test_message_type_catalog.py b/tests/test_message_type_catalog.py
index a0f30f3cc..4b30c56f4 100644
--- a/tests/test_message_type_catalog.py
+++ b/tests/test_message_type_catalog.py
@@ -15,7 +15,6 @@ from vibe.message_types import (
input_author_type_pairs,
spec_for,
types_with,
- types_without,
)
@@ -102,9 +101,9 @@ def test_searchable_types_match_current_default_query() -> None:
def test_inbox_activity_types_match_current_constant() -> None:
- expected = ("queued", "draft", "pending", "harness_dedupe", "silent")
- assert types_without("inboxActivity") == expected
- assert messages_service.NON_CONVERSATION_TYPES == expected
+ expected = ("user", "harness", "annotation", "result", "notify", "error", "assistant")
+ assert types_with("inboxActivity") == expected
+ assert messages_service.INBOX_ACTIVITY_TYPES == expected
def test_inbox_preview_and_settlement_types_match_current_query() -> None:
@@ -113,13 +112,13 @@ def test_inbox_preview_and_settlement_types_match_current_query() -> None:
current_query_sets = _message_type_sequences(connection.statements[-1])
expected_preview = ("result", "notify", "error")
- expected_settlement = ("result", "notify", "error", "silent")
+ expected_settlement = ("result", "notify", "error")
expected_unread = ("result",)
assert types_with("inboxPreview") == expected_preview
assert types_with("inboxSettlesReply") == expected_settlement
assert types_with("unread") == expected_unread
assert current_query_sets == {
- messages_service.NON_CONVERSATION_TYPES,
+ messages_service.INBOX_ACTIVITY_TYPES,
expected_preview,
expected_settlement,
expected_unread,
@@ -162,7 +161,6 @@ def test_annotation_catalog_contract_is_explicit() -> None:
"unread": False,
"webPush": False,
"webPushWhenEvents": (),
- "acceptedReservation": True,
"render": "annotation",
}
@@ -180,7 +178,6 @@ def test_activity_fetch_and_terminal_semantics_match_current_service() -> None:
"result",
"notify",
"error",
- "silent",
"assistant",
)
assert derived_relevant == set(expected_relevant)
diff --git a/tests/test_message_type_python_consumers.py b/tests/test_message_type_python_consumers.py
index 3233393a8..8abe7b43e 100644
--- a/tests/test_message_type_python_consumers.py
+++ b/tests/test_message_type_python_consumers.py
@@ -1,8 +1,7 @@
from __future__ import annotations
-from core import backend_failure, internal_server, show_git
+from core import backend_failure, show_git
from core.services import session_fork
-from vibe import ui_server
from vibe.message_types import spec_for, types_with
@@ -41,24 +40,15 @@ def test_backend_failure_predicate_matches_legacy_type_and_event_pair() -> None:
)
-def test_reservation_acceptance_matches_legacy_consumers() -> None:
- expected = {"user", "harness", "annotation", "queued"}
- assert set(types_with("acceptedReservation")) == expected
- assert internal_server._ACCEPTED_RESERVATION_TYPES == expected
- assert ui_server._ACCEPTED_RESERVATION_TYPES == expected
-
-
def test_fork_activity_sets_match_legacy_values() -> None:
assert session_fork.TERMINAL_AGENT_OUTPUT_TYPES == {
"result",
"error",
- "silent",
}
assert session_fork.SOURCE_PROGRESS_AGENT_OUTPUT_TYPES == {
"assistant",
"result",
"error",
- "silent",
}
assert set(session_fork._FORK_ANCHOR_TYPES) == {
"user",
@@ -67,7 +57,6 @@ def test_fork_activity_sets_match_legacy_values() -> None:
"result",
"notify",
"error",
- "silent",
}
diff --git a/tests/test_messages_service.py b/tests/test_messages_service.py
index 057bc9deb..52779694f 100644
--- a/tests/test_messages_service.py
+++ b/tests/test_messages_service.py
@@ -13,7 +13,7 @@ from sqlalchemy import select
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from storage import messages_service
+from storage import message_deliveries, messages_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_runs, agent_sessions, messages, scopes
@@ -334,7 +334,7 @@ def test_list_session_messages_full_after_page_without_extra_row_has_no_cursor(i
def test_list_session_messages_filters_to_user_facing_types(isolated_state):
"""The chat transcript scopes to user-facing types so the intermediate
- assistant / tool_call / notify rows now persisted for avibe stay out of the
+ assistant / notify rows stay out of the
dialogue view (they're the process log, not the conversation)."""
engine = create_sqlite_engine()
with engine.begin() as conn:
@@ -344,7 +344,6 @@ def test_list_session_messages_filters_to_user_facing_types(isolated_state):
# second-resolution now would tie and fall back to random id order).
_insert_msg(conn, scope_id, "ses_tx", "user", "q", "2026-05-30T10:00:00Z", msg_type="user")
_insert_msg(conn, scope_id, "ses_tx", "agent", "thinking", "2026-05-30T10:00:01Z", msg_type="assistant")
- _insert_msg(conn, scope_id, "ses_tx", "agent", "ran tool", "2026-05-30T10:00:02Z", msg_type="tool_call")
_insert_msg(conn, scope_id, "ses_tx", "agent", "progress", "2026-05-30T10:00:03Z", msg_type="notify")
_insert_msg(conn, scope_id, "ses_tx", "agent", "final", "2026-05-30T10:00:04Z", msg_type="result")
@@ -354,7 +353,7 @@ def test_list_session_messages_filters_to_user_facing_types(isolated_state):
conn, session_id="ses_tx", types=("user", "result")
)
- assert [m["type"] for m in every["messages"]] == ["user", "assistant", "tool_call", "notify", "result"]
+ assert [m["type"] for m in every["messages"]] == ["user", "assistant", "notify", "result"]
assert [m["text"] for m in dialogue["messages"]] == ["q", "final"]
@@ -440,38 +439,33 @@ def test_append_normalizes_legacy_harness_identity(isolated_state):
@pytest.mark.parametrize(
- ("author", "source", "author_name", "expected"),
+ ("author", "source", "message_type", "expected"),
[
("user", "user", None, "user"),
- ("user", None, None, "user"),
- ("harness", "harness", "show_intent", "harness"),
- ("user", "harness", "show_intent", "harness"),
- ("harness", None, None, "harness"),
- ("harness", "harness", "show_annotation", "annotation"),
- ("user", "user", "show_annotation", "user"),
- ("user", "harness", "show_annotation", "harness"),
- ("harness", None, "show_annotation", "harness"),
+ ("user", "harness", None, "harness"),
+ ("harness", "harness", "harness", "harness"),
+ ("harness", "harness", "annotation", "annotation"),
],
)
-def test_pending_message_target_type_uses_row_origin(
+def test_delivery_snapshot_preserves_accepted_message_identity(
author,
source,
- author_name,
+ message_type,
expected,
):
- assert (
- messages_service.pending_message_target_type(
- author,
- source,
- author_name,
- )
- == expected
+ snapshot = message_deliveries.message_snapshot(
+ scope_id="scope",
+ session_id="session",
+ platform="avibe",
+ author=author,
+ source=source,
+ message_type=message_type,
+ text="input",
)
+ assert snapshot["type"] == expected
def test_show_annotation_reservation_flushes_as_annotation(isolated_state):
- from core import session_turns
-
engine = create_sqlite_engine()
legacy_prompt = (
"[show-annotation] comment\n\nLegacy body\n\n"
@@ -480,28 +474,54 @@ def test_show_annotation_reservation_flushes_as_annotation(isolated_state):
with engine.begin() as conn:
scope_id = _seed_scope(conn)
_seed_session(conn, scope_id, "ses_legacy_annotation")
- messages_service.append(
+ queued = message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id="ses_legacy_annotation",
- platform="avibe",
author="harness",
source="harness",
author_name="show_annotation",
- message_type=messages_service.QUEUED_TYPE,
+ message_type=messages_service.ANNOTATION_TYPE,
text=legacy_prompt,
- content={"text": legacy_prompt},
)
- segment = messages_service.list_queued(conn, "ses_legacy_annotation")
- visible = session_turns._promote_merged_user_segment(
+ turn_id = message_deliveries.new_turn_id()
+ message_deliveries.insert_turn(
conn,
- segment,
- text=legacy_prompt,
- attachments=[],
- metadata={},
- author_id=None,
+ turn_id=turn_id,
+ session_id="ses_legacy_annotation",
+ initial_delivery_id=queued["id"],
+ state="starting",
+ backend="opencode",
+ )
+ delivery = message_deliveries.get_delivery(conn, queued["id"])
+ assert delivery is not None
+ attempt_id = message_deliveries.new_attempt_id()
+ claimed = message_deliveries.open_start_attempt(
+ conn,
+ queued["id"],
+ expected_version=delivery["version"],
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ )
+ assert claimed is not None
+ turn = message_deliveries.get_turn(conn, turn_id)
+ assert turn is not None
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ runtime_key="annotation-runtime",
+ runtime_turn_id="annotation-runtime-turn",
+ native_turn_id="annotation-native-turn",
+ ) is not None
+ message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "native_start"},
)
+ visible = messages_service.get_message(conn, queued["id"])
+ assert visible is not None
assert visible["type"] == messages_service.ANNOTATION_TYPE
assert visible["text"] == legacy_prompt
assert "annotation" not in visible["content"]
@@ -558,19 +578,14 @@ def test_transcript_visibility_depends_only_on_message_type(isolated_state):
messages_service.append(
conn, scope_id=scope_id, session_id="ses_mark", platform="avibe",
author="harness", source="harness", author_name="show_annotation",
- message_type=messages_service.PENDING_TYPE, text="pending",
- metadata={"source": "show_page"},
- )
- messages_service.append(
- conn, scope_id=scope_id, session_id="ses_mark", platform="avibe",
- author="harness", source="harness", author_name="show_annotation",
- message_type=messages_service.QUEUED_TYPE, text="queued",
+ message_type=messages_service.ANNOTATION_TYPE, text="annotation",
metadata={"source": "show_page"},
)
- messages_service.append(
- conn, scope_id=scope_id, session_id="ses_mark", platform="avibe",
- author="agent", message_type=messages_service.ANNOTATION_TYPE,
- text="annotation", metadata={"source": "anything"},
+ message_deliveries.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_mark",
+ text="queued",
)
messages_service.append(
conn, scope_id=scope_id, session_id="ses_mark", platform="avibe",
@@ -582,7 +597,7 @@ def test_transcript_visibility_depends_only_on_message_type(isolated_state):
texts = [m["text"] for m in page["messages"]]
assert texts == ["q", "annotation", "final"]
assert messages_service.ANNOTATION_TYPE in messages_service.TRANSCRIPT_TYPES
- assert messages_service.ANNOTATION_TYPE not in messages_service.NON_CONVERSATION_TYPES
+ assert messages_service.ANNOTATION_TYPE in messages_service.INBOX_ACTIVITY_TYPES
def test_transcript_keeps_notify_terminal_marker(isolated_state):
@@ -596,7 +611,6 @@ def test_transcript_keeps_notify_terminal_marker(isolated_state):
for author, mtype, text in (
("user", "user", "go"),
("agent", "assistant", "thinking"),
- ("agent", "tool_call", "ran tool"),
("agent", "notify", "Agent run failed and stopped."),
):
messages_service.append(
@@ -647,16 +661,12 @@ def test_unread_counts_by_session_splits_within_a_scope(isolated_state):
conn, scope_id=scope_id, session_id="ses_b", platform="avibe",
author="agent", message_type="result", text="b",
)
- # An unread assistant + tool_call (intermediate) and a user message
+ # An unread assistant (intermediate) and a user message
# must NOT count toward the unread badge.
messages_service.append(
conn, scope_id=scope_id, session_id="ses_b", platform="avibe",
author="agent", message_type="assistant", text="thinking",
)
- messages_service.append(
- conn, scope_id=scope_id, session_id="ses_b", platform="avibe",
- author="agent", message_type="tool_call", text="ran tool",
- )
messages_service.append(
conn, scope_id=scope_id, session_id="ses_b", platform="avibe",
author="user", message_type="user", text="hi",
@@ -960,20 +970,58 @@ def test_list_inbox_sessions_awaiting_reply_persists_through_agent_stream(isolat
def test_list_inbox_sessions_silent_completion_clears_awaiting(isolated_state):
- """A turn that completes with only the INVISIBLE ``silent`` marker still counts as
- the agent having replied — ``replied`` (awaiting) clears — while the preview text
- stays the last VISIBLE reply (silent is not a preview type)."""
+ """A terminal Turn snapshot settles Inbox state without a pseudo Message."""
engine = create_sqlite_engine()
with engine.begin() as conn:
scope_id = _seed_scope(conn)
_seed_titled_session(conn, scope_id, "ses_sil", "Silent")
_insert_msg(conn, scope_id, "ses_sil", "user", "first", "2026-05-30T10:00:00Z")
_insert_msg(conn, scope_id, "ses_sil", "agent", "R1", "2026-05-30T10:01:00Z") # visible reply
- # turn 2: user follows up; the agent runs and finishes SILENTLY (marker only).
- _insert_msg(conn, scope_id, "ses_sil", "user", "second", "2026-05-30T10:05:00Z")
- _insert_msg(
- conn, scope_id, "ses_sil", "agent", "", "2026-05-30T10:07:00Z",
- read=False, msg_type=messages_service.SILENT_TYPE,
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="msg_silent_turn",
+ session_id="ses_sil",
+ priority="p1",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id="ses_sil",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="second",
+ ),
+ dispatch_text="second",
+ now="2026-05-30T10:05:00Z",
+ )
+ claimed = message_deliveries.claim_start_batch(
+ conn,
+ turn_id="trn_silent_turn",
+ session_id="ses_sil",
+ backend="opencode",
+ deliveries=[delivery],
+ dispatch_text="second",
+ attempt_id="atm_silent_turn",
+ )
+ assert message_deliveries.bind_native_start(
+ conn,
+ "trn_silent_turn",
+ expected_version=int(claimed["turn"]["version"]),
+ runtime_key="silent-runtime",
+ runtime_turn_id="silent-runtime-turn",
+ native_turn_id="silent-native-turn",
+ ) is not None
+ assert message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id="trn_silent_turn",
+ evidence={"kind": "native_start"},
+ )
+ message_deliveries.terminalize_turn(
+ conn,
+ "trn_silent_turn",
+ outcome="completed",
+ settled_by="terminal_result",
+ evidence_kind="result",
)
with engine.connect() as conn:
@@ -1102,33 +1150,31 @@ def test_list_inbox_sessions_pagination(isolated_state):
# --- Send-while-busy queue + per-session draft ------------------------------
-def test_enqueue_list_and_pop_queued(isolated_state):
- """Queued messages persist in order, stay OUT of the conversation transcript
- (different ``type``), and ``pop_queued`` reads-then-deletes them atomically."""
+def test_enqueue_list_and_retire_queued(isolated_state):
+ """Queued Deliveries persist FIFO, stay out of transcript, and retire in place."""
engine = create_sqlite_engine()
with engine.begin() as conn:
scope_id = _seed_scope(conn)
_seed_session(conn, scope_id, "ses_q")
- messages_service.enqueue_queued(conn, scope_id=scope_id, session_id="ses_q", text="first")
+ first = message_deliveries.enqueue_queued(conn, scope_id=scope_id, session_id="ses_q", text="first")
time.sleep(0.001)
- messages_service.enqueue_queued(conn, scope_id=scope_id, session_id="ses_q", text="second")
+ message_deliveries.enqueue_queued(conn, scope_id=scope_id, session_id="ses_q", text="second")
with engine.connect() as conn:
- queued = messages_service.list_queued(conn, "ses_q")
+ queued = message_deliveries.list_queued(conn, "ses_q")
# Queued rows never appear in the user/result/notify transcript.
transcript = messages_service.list_session_messages(
conn, session_id="ses_q", types=("user", "result", "notify")
)
assert [q["text"] for q in queued] == ["first", "second"]
- assert all(q["type"] == "queued" for q in queued)
+ assert all(q["state"] == "queued" for q in queued)
assert transcript["messages"] == []
- # pop returns them in order and clears the queue.
with engine.begin() as conn:
- popped = messages_service.pop_queued(conn, "ses_q")
- assert [p["text"] for p in popped] == ["first", "second"]
+ assert message_deliveries.retire_queued(conn, "ses_q", first["id"])
with engine.connect() as conn:
- assert messages_service.list_queued(conn, "ses_q") == []
+ assert [row["text"] for row in message_deliveries.list_queued(conn, "ses_q")] == ["second"]
+ assert message_deliveries.get_delivery(conn, first["id"])["state"] == "retired"
def test_remove_queued_targets_only_queued(isolated_state):
@@ -1136,26 +1182,30 @@ def test_remove_queued_targets_only_queued(isolated_state):
with engine.begin() as conn:
scope_id = _seed_scope(conn)
_seed_session(conn, scope_id, "ses_rm")
- a = messages_service.enqueue_queued(conn, scope_id=scope_id, session_id="ses_rm", text="a")
- messages_service.enqueue_queued(conn, scope_id=scope_id, session_id="ses_rm", text="b")
+ a = message_deliveries.enqueue_queued(conn, scope_id=scope_id, session_id="ses_rm", text="a")
+ message_deliveries.enqueue_queued(conn, scope_id=scope_id, session_id="ses_rm", text="b")
# A real user message must NOT be removable through remove_queued.
user_row = messages_service.append(
conn, scope_id=scope_id, session_id="ses_rm", platform="avibe", author="user", text="real"
)
with engine.begin() as conn:
- assert messages_service.remove_queued(conn, "ses_rm", a["id"]) is True
+ assert message_deliveries.retire_queued_with_run(conn, "ses_rm", a["id"]) is True
# Wrong session id must NOT delete the row (scoped delete).
- assert messages_service.remove_queued(conn, "ses_other", a["id"]) is False
+ assert message_deliveries.retire_queued_with_run(conn, "ses_other", a["id"]) is False
# A real user message is not removable through remove_queued.
- assert messages_service.remove_queued(conn, "ses_rm", user_row["id"]) is False
+ assert message_deliveries.retire_queued_with_run(conn, "ses_rm", user_row["id"]) is False
with engine.connect() as conn:
- assert [q["text"] for q in messages_service.list_queued(conn, "ses_rm")] == ["b"]
+ assert [q["text"] for q in message_deliveries.list_queued(conn, "ses_rm")] == ["b"]
-def test_remove_queued_cancels_its_held_agent_run_atomically(isolated_state):
+def test_remove_queued_cancels_only_its_exact_agent_run(isolated_state):
from core.scheduled_tasks import TaskExecutionStore
- from storage.background import run_update_event_transaction
+ from storage.background import (
+ attach_agent_run_delivery_in_connection,
+ claim_agent_runs_for_turn_in_connection,
+ run_update_event_transaction,
+ )
engine = create_sqlite_engine()
with engine.begin() as conn:
@@ -1163,59 +1213,114 @@ def test_remove_queued_cancels_its_held_agent_run_atomically(isolated_state):
_seed_session(conn, scope_id, "ses_rm_run")
store = TaskExecutionStore()
- request = store.enqueue_agent_run(
- session_id="ses_rm_run",
- message="obsolete delegated work",
- agent_name="worker",
- )
- assert store.claim(request.id) is not None
- store.requeue(
- request.id,
- metadata={"workbench_queue_holds_run": True},
- )
- with engine.begin() as conn:
- queued = messages_service.append(
- conn,
- scope_id=scope_id,
+ requests = [
+ store.enqueue_agent_run(
session_id="ses_rm_run",
- platform="avibe",
- author="harness",
- source="harness",
- message_type=messages_service.QUEUED_TYPE,
- text=request.message or "",
- metadata={
- "scheduled_provenance": {
- "platform_specific": {
- "task_trigger_kind": "agent_run",
- "task_execution_id": request.id,
- }
- }
- },
+ message=f"obsolete delegated work {index}",
+ agent_name="worker",
)
+ for index in range(2)
+ ]
+ primary, sibling = requests
+ deliveries = []
+ with engine.begin() as conn:
+ for request in requests:
+ delivery = message_deliveries.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_rm_run",
+ author="harness",
+ source="harness",
+ text=request.message or "",
+ native_message_id=f"agent_run:{request.id}",
+ )
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ request.id,
+ session_id="ses_rm_run",
+ delivery_id=str(delivery["id"]),
+ )
+ deliveries.append(delivery)
+ assert claim_agent_runs_for_turn_in_connection(conn, [primary.id]) == [
+ primary.id
+ ]
with run_update_event_transaction(engine) as conn:
assert (
- messages_service.remove_queued(
+ message_deliveries.retire_queued_with_run(
conn,
"ses_rm_run",
- queued["id"],
+ deliveries[0]["id"],
)
is True
)
- stored = store.get_run(request.id)
- assert stored is not None
- assert stored["status"] == "canceled"
- assert stored["cancel_requested"] is True
- assert stored["completed_at"]
+ canceled = store.get_run(primary.id)
+ retained = store.get_run(sibling.id)
+ assert canceled["status"] == "canceled"
+ assert canceled["cancel_requested"] is True
+ assert canceled["completed_at"]
+ assert retained["status"] == "queued"
+ assert retained["cancel_requested"] is False
with engine.connect() as conn:
- assert messages_service.list_queued(conn, "ses_rm_run") == []
+ assert [
+ row["id"] for row in message_deliveries.list_queued(conn, "ses_rm_run")
+ ] == [deliveries[1]["id"]]
+
+
+def test_bulk_delivery_run_cancellation_defers_updated_rows(isolated_state):
+ from core.scheduled_tasks import TaskExecutionStore
+ from storage.background import (
+ attach_agent_run_delivery_in_connection,
+ cancel_agent_runs_for_retired_deliveries_in_connection,
+ pop_deferred_run_event_rows_from_connection,
+ )
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_bulk_cancel")
+ store = TaskExecutionStore()
+ request = store.enqueue_agent_run(
+ session_id="ses_bulk_cancel",
+ message="retired delegated work",
+ agent_name="worker",
+ )
+ with engine.begin() as conn:
+ delivery = message_deliveries.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_bulk_cancel",
+ author="harness",
+ source="harness",
+ text=request.message or "",
+ )
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ request.id,
+ session_id="ses_bulk_cancel",
+ delivery_id=str(delivery["id"]),
+ )
+ assert cancel_agent_runs_for_retired_deliveries_in_connection(
+ conn,
+ session_id="ses_bulk_cancel",
+ delivery_ids=[str(delivery["id"])],
+ ) == [request.id]
+ deferred = pop_deferred_run_event_rows_from_connection(conn)
+
+ assert [(row["id"], row["status"]) for row in deferred] == [
+ (request.id, "canceled")
+ ]
def test_remove_queued_refuses_an_agent_run_no_longer_owned_by_queue(
isolated_state,
):
from core.scheduled_tasks import TaskExecutionStore
+ from storage.background import (
+ attach_agent_run_delivery_in_connection,
+ claim_agent_runs_for_turn_in_connection,
+ )
engine = create_sqlite_engine()
with engine.begin() as conn:
@@ -1228,23 +1333,37 @@ def test_remove_queued_refuses_an_agent_run_no_longer_owned_by_queue(
message="already claimed work",
agent_name="worker",
)
- assert store.claim(request.id) is not None
with engine.begin() as conn:
- queued = messages_service.append(
+ queued = message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id="ses_rm_claimed",
- platform="avibe",
author="harness",
source="harness",
- message_type=messages_service.QUEUED_TYPE,
text=request.message or "",
native_message_id=f"agent_run:{request.id}",
)
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ request.id,
+ session_id="ses_rm_claimed",
+ delivery_id=str(queued["id"]),
+ )
+ assert claim_agent_runs_for_turn_in_connection(conn, [request.id]) == [
+ request.id
+ ]
+ message_deliveries.claim_start_batch(
+ conn,
+ turn_id=message_deliveries.new_turn_id(),
+ session_id="ses_rm_claimed",
+ backend="worker",
+ deliveries=[queued],
+ dispatch_text=request.message or "",
+ )
with engine.begin() as conn:
assert (
- messages_service.remove_queued(
+ message_deliveries.retire_queued_with_run(
conn,
"ses_rm_claimed",
queued["id"],
@@ -1257,9 +1376,8 @@ def test_remove_queued_refuses_an_agent_run_no_longer_owned_by_queue(
assert stored["status"] == "running"
assert stored["cancel_requested"] is False
with engine.connect() as conn:
- assert [row["id"] for row in messages_service.list_queued(conn, "ses_rm_claimed")] == [
- queued["id"]
- ]
+ claimed = message_deliveries.get_delivery(conn, queued["id"])
+ assert claimed is not None and claimed["state"] == "claimed"
def test_list_queued_page_is_bounded_and_fifo(isolated_state):
@@ -1267,19 +1385,19 @@ def test_list_queued_page_is_bounded_and_fifo(isolated_state):
with engine.begin() as conn:
scope_id = _seed_scope(conn)
_seed_session(conn, scope_id, "ses_page")
- messages_service.enqueue_queued(
+ message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id="ses_page",
text="first",
)
- messages_service.enqueue_queued(
+ message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id="ses_page",
text="second",
)
- messages_service.enqueue_queued(
+ message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id="ses_page",
@@ -1287,12 +1405,12 @@ def test_list_queued_page_is_bounded_and_fifo(isolated_state):
)
with engine.connect() as conn:
- page1 = messages_service.list_queued_page(
+ page1 = message_deliveries.list_queued_page(
conn,
"ses_page",
page_request=PageRequest(page=1, limit=2),
)
- page2 = messages_service.list_queued_page(
+ page2 = message_deliveries.list_queued_page(
conn,
"ses_page",
page_request=PageRequest(page=2, limit=2),
@@ -1315,50 +1433,50 @@ def test_draft_upsert_get_and_clear(isolated_state):
with engine.begin() as conn:
scope_id = _seed_scope(conn)
_seed_session(conn, scope_id, "ses_d")
- messages_service.set_draft(conn, scope_id=scope_id, session_id="ses_d", text="half typed")
+ message_deliveries.set_draft(conn, "ses_d", "half typed")
with engine.connect() as conn:
- draft = messages_service.get_draft(conn, "ses_d")
- assert draft is not None and draft["text"] == "half typed" and draft["type"] == "draft"
+ draft = message_deliveries.get_draft(conn, "ses_d")
+ assert draft is not None and draft["text"] == "half typed"
# Setting again replaces in place (still exactly one draft row).
with engine.begin() as conn:
- messages_service.set_draft(conn, scope_id=scope_id, session_id="ses_d", text="rewritten")
+ message_deliveries.set_draft(conn, "ses_d", "rewritten")
with engine.connect() as conn:
- rows = conn.execute(
- select(messages).where(messages.c.session_id == "ses_d", messages.c.type == "draft")
- ).all()
- draft = messages_service.get_draft(conn, "ses_d")
- assert len(rows) == 1 and draft["text"] == "rewritten"
+ rows = conn.execute(select(messages).where(messages.c.session_id == "ses_d")).all()
+ draft = message_deliveries.get_draft(conn, "ses_d")
+ assert rows == [] and draft["text"] == "rewritten"
# Blank text clears the draft.
with engine.begin() as conn:
- assert messages_service.set_draft(conn, scope_id=scope_id, session_id="ses_d", text=" ") is None
+ assert message_deliveries.set_draft(conn, "ses_d", " ") is True
with engine.connect() as conn:
- assert messages_service.get_draft(conn, "ses_d") is None
+ assert message_deliveries.get_draft(conn, "ses_d") is None
# clear_draft is idempotent.
with engine.begin() as conn:
- messages_service.set_draft(conn, scope_id=scope_id, session_id="ses_d", text="again")
+ message_deliveries.set_draft(conn, "ses_d", "again")
with engine.begin() as conn:
- messages_service.clear_draft(conn, "ses_d")
+ message_deliveries.set_draft(conn, "ses_d", None)
with engine.connect() as conn:
- assert messages_service.get_draft(conn, "ses_d") is None
+ assert message_deliveries.get_draft(conn, "ses_d") is None
-def test_inbox_ignores_draft_and_queued_activity(isolated_state):
- """A saved draft / pending queued message lives in the messages table but
- must NOT bump the session in the inbox or flip its 'replied' badge — only
- sent conversation counts as activity (Codex P2)."""
+def test_inbox_ignores_draft_and_queued_delivery_activity(isolated_state):
engine = create_sqlite_engine()
with engine.begin() as conn:
scope_id = _seed_scope(conn)
_seed_session(conn, scope_id, "ses_inbox")
_insert_msg(conn, scope_id, "ses_inbox", "user", "hi", "2026-05-30T10:00:00Z")
_insert_msg(conn, scope_id, "ses_inbox", "agent", "reply", "2026-05-30T10:00:01Z")
- # A LATER draft + queued (newer created_at) must not count as activity.
- _insert_msg(conn, scope_id, "ses_inbox", "user", "typing", "2026-05-30T10:05:00Z", msg_type="draft")
- _insert_msg(conn, scope_id, "ses_inbox", "user", "queued", "2026-05-30T10:06:00Z", msg_type="queued")
+ message_deliveries.set_draft(conn, "ses_inbox", "typing")
+ message_deliveries.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_inbox",
+ text="queued",
+ now="2026-05-30T10:06:00Z",
+ )
with engine.connect() as conn:
rows = messages_service.list_inbox_sessions(conn, platform="avibe")["sessions"]
@@ -1370,6 +1488,154 @@ def test_inbox_ignores_draft_and_queued_activity(isolated_state):
assert row["replied"] is False
+def test_inbox_ignores_not_written_successor_as_terminal_evidence(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_titled_session(
+ conn,
+ scope_id,
+ "ses_not_written_inbox",
+ "Not written",
+ )
+ _insert_msg(
+ conn,
+ scope_id,
+ "ses_not_written_inbox",
+ "agent",
+ "previous reply",
+ "2026-05-30T10:00:00Z",
+ )
+ _insert_msg(
+ conn,
+ scope_id,
+ "ses_not_written_inbox",
+ "user",
+ "still running",
+ "2026-05-30T10:01:00Z",
+ )
+ successor = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="msg_not_written_inbox",
+ session_id="ses_not_written_inbox",
+ priority="p0",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id="ses_not_written_inbox",
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="refused replacement",
+ ),
+ dispatch_text="refused replacement",
+ now="2026-05-30T10:02:00Z",
+ )
+ message_deliveries.insert_turn(
+ conn,
+ turn_id="trn_not_written_inbox",
+ session_id="ses_not_written_inbox",
+ initial_delivery_id="msg_not_written_inbox",
+ state="waiting",
+ backend="codex",
+ now="2026-05-30T10:02:00Z",
+ )
+ assert message_deliveries.cas_delivery(
+ conn,
+ successor["id"],
+ expected_version=int(successor["version"]),
+ expected_states=("reserved",),
+ values={
+ "state": "interrupt_waiting",
+ "turn_id": "trn_not_written_inbox",
+ "turn_role": "initial",
+ "turn_position": 0,
+ },
+ ) is not None
+ message_deliveries.terminalize_turn(
+ conn,
+ "trn_not_written_inbox",
+ outcome="not_written",
+ settled_by="interrupt_refused",
+ evidence_kind="definitive_stop_receipt",
+ )
+
+ with engine.connect() as conn:
+ rows = messages_service.list_inbox_sessions(conn, platform="avibe")[
+ "sessions"
+ ]
+
+ assert len(rows) == 1
+ assert rows[0]["session_id"] == "ses_not_written_inbox"
+ assert rows[0]["replied"] is True
+
+
+def test_inbox_awaiting_uses_active_accepted_turn_not_submission_order(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_titled_session(conn, scope_id, "ses_delayed_accept", "Delayed acceptance")
+ _insert_msg(
+ conn,
+ scope_id,
+ "ses_delayed_accept",
+ "agent",
+ "previous reply",
+ "2026-05-30T10:02:00Z",
+ )
+ delivery_id = "msg_delayed_accept"
+ turn_id = "trn_delayed_accept"
+ attempt_id = "atm_delayed_accept"
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_delayed_accept",
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id="ses_delayed_accept",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="submitted before the previous turn completed",
+ ),
+ dispatch_text="submitted before the previous turn completed",
+ now="2026-05-30T10:01:00Z",
+ )
+ claimed = message_deliveries.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id="ses_delayed_accept",
+ backend="codex",
+ deliveries=[delivery],
+ dispatch_text="submitted before the previous turn completed",
+ attempt_id=attempt_id,
+ )
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(claimed["turn"]["version"]),
+ runtime_key="delayed-runtime",
+ runtime_turn_id="delayed-runtime-turn",
+ native_turn_id="delayed-native-turn",
+ ) is not None
+ assert message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "delayed_start_acceptance"},
+ )
+
+ with engine.connect() as conn:
+ row = messages_service.list_inbox_sessions(
+ conn,
+ platform="avibe",
+ )["sessions"][0]
+
+ assert row["replied"] is True
+
+
def test_list_session_messages_tail_returns_recent_window(isolated_state):
"""``tail=True`` returns the most-recent ``limit`` rows in chronological
order (not the oldest page), so the Chat page's gap recovery sees the latest
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index 504233758..87c0c5835 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -14,6 +14,11 @@ from modules.im.multi import IMClientRemovalError, MultiIMClient
from modules.settings_manager import MultiSettingsManager
from config.v2_sessions import ActivePollInfo
from core.message_dispatcher import ConsolidatedMessageDispatcher
+from core.native_dispatch_phase import (
+ DISPATCH_PHASE_PREWRITE,
+ backend_dispatch_attempted,
+ set_dispatch_phase,
+)
from core.processing_indicator import ProcessingIndicatorService
from modules.agents.base import AgentRequest
from modules.agents.model_hub import launch_for_context
@@ -678,6 +683,7 @@ def test_opencode_restored_ack_preserves_wechat_typing_context():
def test_opencode_prompt_disables_question_tool_for_all_platforms():
calls = []
active_polls = []
+ recovery_order = []
class _Server:
async def ensure_running(self):
@@ -701,6 +707,7 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():
}
async def prompt_async(self, **kwargs):
+ recovery_order.append("prompt")
calls.append(kwargs)
async def mark_run_active(self, session_id):
@@ -733,6 +740,7 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():
class _Sessions:
def add_active_poll(self, **kwargs):
+ recovery_order.append("poll")
active_polls.append(kwargs)
return None
@@ -802,6 +810,7 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():
platform_specific={
"agent_session_id": "ses_test",
"turn_token": "logical-turn",
+ "delivery_start_attempt_id": "atm_initial_start",
},
),
message="hello",
@@ -819,6 +828,8 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():
assert calls[0]["tools"] == {"question": False}
assert calls[0]["model"] == {"providerID": "openai", "modelID": "gpt-5.4"}
assert calls[0]["reasoning_effort"] == "high"
+ assert calls[0]["message_id"] == "atm_initial_start"
+ assert recovery_order[:2] == ["poll", "prompt"]
steering_snapshot = active_polls[0]["processing_indicator"]["opencode_native_steering"]
assert steering_snapshot["system"] == calls[0]["system"]
@@ -1240,6 +1251,14 @@ def test_opencode_process_message_removes_active_poll_when_question_tool_aborts(
removed = []
ack_removed = []
+ request_context = MessageContext(
+ user_id="u",
+ channel_id="c",
+ platform="slack",
+ platform_specific={"agent_session_id": "ses_test"},
+ )
+ set_dispatch_phase(request_context, DISPATCH_PHASE_PREWRITE)
+
class _Server:
async def ensure_running(self):
return None
@@ -1248,6 +1267,7 @@ def test_opencode_process_message_removes_active_poll_when_question_tool_aborts(
return []
async def prompt_async(self, **kwargs):
+ assert backend_dispatch_attempted(request_context) is True
return None
async def mark_run_active(self, session_id):
@@ -1334,12 +1354,7 @@ def test_opencode_process_message_removes_active_poll_when_question_tool_aborts(
agent._remove_ack_reaction = _remove_ack
request = AgentRequest(
- context=MessageContext(
- user_id="u",
- channel_id="c",
- platform="slack",
- platform_specific={"agent_session_id": "ses_test"},
- ),
+ context=request_context,
message="hello",
user_message="hello",
working_path="/tmp/work",
diff --git a/tests/test_opencode_restore_polls.py b/tests/test_opencode_restore_polls.py
index 3e1c5ea78..c1089ae48 100644
--- a/tests/test_opencode_restore_polls.py
+++ b/tests/test_opencode_restore_polls.py
@@ -1,11 +1,10 @@
-"""Tests for ``OpenCodeAgent.restore_active_polls`` status recovery.
+"""Tests for ``OpenCodeAgent.restore_active_polls`` durable identity recovery.
-On a controller restart mid-OpenCode-turn, ``_reset_stale_agent_status`` flips
-every ``running`` workbench session to ``idle``. ``restore_active_polls`` then
-RESUMES the still-active OpenCode poll — but the resumed poll does NOT re-enter
-``AgentService.handle_message`` (the inbound status chokepoint), so the avibe
-sidebar dot would stay idle/gray for a backend turn that is still live unless the
-restore path re-marks the session ``running`` itself. These tests lock that:
+On controller restart, durable Turn ownership stays running while OpenCode
+rebuilds its logical/runtime/native mapping. The restored poll must publish that
+mapping before Delivery reconciliation and then wait for the recovery-complete
+barrier. Legacy polls without durable Turn history still restore their status
+projection. These tests lock that:
* an avibe poll → ``controller.set_agent_status(session_id, "running")``;
* an IM poll → NO status write (only avibe sessions get a dot).
@@ -49,15 +48,21 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "en
class _Server:
def __init__(self):
self.messages = [{"info": {"role": "assistant", "time": {}}}]
+ self.messages_error = None
self.status = {"type": "busy"}
self.status_error = None
+ self.mark_run_active_error = None
async def list_messages(self, session_id, directory):
# One in-progress assistant message → the session is "still active",
# so the poll is restored (not pruned as stale).
+ if self.messages_error is not None:
+ raise self.messages_error
return list(self.messages)
async def mark_run_active(self, session_id):
+ if self.mark_run_active_error is not None:
+ raise self.mark_run_active_error
return None
async def mark_run_inactive(self, session_id):
@@ -135,6 +140,93 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "en
return agent, status_writes, removed, request_sessions
+def test_restore_registration_failure_terminalizes_exact_owner_before_release() -> None:
+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")
+ poll.processing_indicator = {
+ "platform": "avibe",
+ "opencode_native_steering": {
+ "target_session_id": "ses_wb",
+ "logical_turn_id": "turn-restore-failed",
+ },
+ }
+ agent, _, removed, _ = _build_agent({"oc-1": poll})
+ agent._test_server.mark_run_active_error = RuntimeError("registration failed")
+ failed: list[tuple[str, str, str]] = []
+
+ def _fail(turn_id: str, *, backend: str, reason: str) -> bool:
+ failed.append((turn_id, backend, reason))
+ return True
+
+ agent.controller.session_turns.fail_restored_backend_turn = _fail
+
+ assert asyncio.run(agent.restore_active_polls()) == 0
+ assert failed == [("turn-restore-failed", "opencode", "poll_registration_failed")]
+ assert removed == ["oc-1"]
+ assert agent._active_requests == {}
+
+
+def test_restore_registration_failure_keeps_poll_if_terminal_write_fails() -> None:
+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")
+ poll.processing_indicator = {
+ "platform": "avibe",
+ "opencode_native_steering": {
+ "target_session_id": "ses_wb",
+ "logical_turn_id": "turn-restore-failed",
+ },
+ }
+ agent, _, removed, _ = _build_agent({"oc-1": poll})
+ agent._test_server.mark_run_active_error = RuntimeError("registration failed")
+
+ def _fail(*_args, **_kwargs):
+ raise RuntimeError("terminal write failed")
+
+ agent.controller.session_turns.fail_restored_backend_turn = _fail
+
+ assert asyncio.run(agent.restore_active_polls()) == 0
+ assert removed == []
+ assert agent._active_requests == {}
+
+
+def test_restore_im_registration_failure_retries_before_releasing_poll() -> None:
+ poll = _make_poll(platform="slack", base_session_id="C123:thread", opencode_session_id="oc-im")
+ agent, _, removed, _ = _build_agent({"oc-im": poll})
+ attempts = 0
+ poll_started = asyncio.Event()
+ release_poll = asyncio.Event()
+
+ async def _flaky_mark_run_active(_session_id: str) -> None:
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ raise RuntimeError("temporary registration failure")
+
+ class _HeldPollLoop:
+ async def run_restored_poll_loop(self, _poll_info):
+ poll_started.set()
+ await release_poll.wait()
+
+ async def remove_restored_ack(self, _poll_info):
+ return None
+
+ agent._test_server.mark_run_active = _flaky_mark_run_active
+ agent._poll_loop = _HeldPollLoop()
+
+ async def _run() -> int:
+ restored = await agent.restore_active_polls()
+ if restored != 1:
+ return restored
+ await asyncio.wait_for(poll_started.wait(), timeout=1)
+ task = agent._active_requests[poll.base_session_id]
+ assert not task.done()
+ release_poll.set()
+ await task
+ return restored
+
+ assert asyncio.run(_run()) == 1
+ assert attempts == 2
+ assert removed == []
+
+
def test_restored_poll_exposes_the_persisted_guarded_steering_owner() -> None:
poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")
poll.model_dict = {"providerID": "openai", "modelID": "gpt-5"}
@@ -151,6 +243,8 @@ def test_restored_poll_exposes_the_persisted_guarded_steering_owner() -> None:
agent, _, _, _ = _build_agent({"oc-1": poll})
poll_started = asyncio.Event()
release_poll = asyncio.Event()
+ recovery_complete = asyncio.Event()
+ agent.controller._delivery_recovery_complete = recovery_complete
class _HeldPollLoop:
async def run_restored_poll_loop(self, poll_info):
@@ -164,7 +258,7 @@ def test_restored_poll_exposes_the_persisted_guarded_steering_owner() -> None:
async def _run():
restored = await agent.restore_active_polls()
- await poll_started.wait()
+ assert not poll_started.is_set()
identity = active_steer_identity(
agent.controller,
"opencode",
@@ -172,6 +266,8 @@ def test_restored_poll_exposes_the_persisted_guarded_steering_owner() -> None:
expected_logical_turn_id="logical-restored",
)
assert identity is not None
+ recovery_complete.set()
+ await poll_started.wait()
receipt = await steer_active_turn(
agent.controller,
"opencode",
@@ -204,6 +300,160 @@ def test_restored_poll_exposes_the_persisted_guarded_steering_owner() -> None:
]
+def test_restore_publishes_workbench_status_after_native_identity_registration() -> None:
+ poll = _make_poll(
+ platform="avibe",
+ base_session_id="ses_wb",
+ opencode_session_id="oc-1",
+ )
+ agent, _, _, _ = _build_agent({"oc-1": poll})
+ observed: list[tuple[bool, bool]] = []
+
+ def restore_running(session_id: str) -> None:
+ observed.append(
+ (
+ session_id in agent._active_requests,
+ agent._session_manager.get_request_session(session_id) is not None,
+ )
+ )
+
+ agent.controller.session_turns.restore_running = restore_running
+
+ async def _run() -> int:
+ restored = await agent.restore_active_polls()
+ await asyncio.gather(*agent._active_requests.values())
+ return restored
+
+ assert asyncio.run(_run()) == 1
+ assert observed == [(True, True)]
+
+
+def test_restore_preserves_durable_poll_when_verification_is_temporarily_unavailable() -> None:
+ poll = _make_poll(
+ platform="avibe",
+ base_session_id="ses_wb",
+ opencode_session_id="oc-unknown",
+ )
+ poll.processing_indicator = {
+ "platform": "avibe",
+ "delivery_start_attempt_id": "attempt-unknown",
+ "opencode_native_steering": {
+ "target_session_id": "ses_wb",
+ "logical_turn_id": "turn-unknown",
+ },
+ }
+ agent, _, removed, _ = _build_agent({"oc-unknown": poll})
+ agent._test_server.messages_error = TimeoutError("temporary verification failure")
+
+ class _RecoveredPollLoop:
+ async def run_restored_poll_loop(self, poll_info):
+ agent._test_server.messages_error = None
+
+ async def remove_restored_ack(self, poll_info):
+ raise AssertionError("unknown verification must not retire the durable poll")
+
+ agent._poll_loop = _RecoveredPollLoop()
+
+ async def _run() -> int:
+ restored = await agent.restore_active_polls()
+ await asyncio.gather(*agent._active_requests.values())
+ return restored
+
+ assert asyncio.run(_run()) == 1
+ assert removed == []
+
+
+def test_restore_rebuilds_completed_exact_start_attempt() -> None:
+ poll = _make_poll(
+ platform="avibe",
+ base_session_id="ses_wb",
+ opencode_session_id="oc-1",
+ )
+ poll.processing_indicator = {
+ "platform": "avibe",
+ "delivery_start_attempt_id": "atm-start",
+ "opencode_native_steering": {
+ "target_session_id": "ses_wb",
+ "logical_turn_id": "logical-start",
+ },
+ }
+ agent, _, removed, _ = _build_agent({"oc-1": poll})
+ agent._test_server.messages = [
+ {"info": {"id": "atm-start", "role": "user", "time": {}}},
+ {
+ "info": {
+ "id": "assistant-done",
+ "role": "assistant",
+ "time": {"completed": 1},
+ "finish": "stop",
+ }
+ },
+ ]
+ agent._test_server.status = {"type": "idle"}
+ poll_started = asyncio.Event()
+ release_poll = asyncio.Event()
+ recovery_complete = asyncio.Event()
+ agent.controller._delivery_recovery_complete = recovery_complete
+
+ class _HeldPollLoop:
+ async def run_restored_poll_loop(self, _poll_info):
+ poll_started.set()
+ await release_poll.wait()
+
+ async def remove_restored_ack(self, _poll_info):
+ return None
+
+ agent._poll_loop = _HeldPollLoop()
+
+ async def _run() -> int:
+ restored = await agent.restore_active_polls()
+ identity = active_steer_identity(
+ agent.controller,
+ "opencode",
+ "ses_wb",
+ expected_logical_turn_id="logical-start",
+ )
+ assert identity is not None
+ recovery_complete.set()
+ await poll_started.wait()
+ release_poll.set()
+ await asyncio.gather(*agent._active_requests.values())
+ return restored
+
+ assert asyncio.run(_run()) == 1
+ assert removed == []
+
+
+def test_restore_reconciles_definitive_missing_start_attempt() -> None:
+ poll = _make_poll(
+ platform="avibe",
+ base_session_id="ses_wb",
+ opencode_session_id="oc-1",
+ )
+ poll.processing_indicator = {
+ "platform": "avibe",
+ "delivery_start_attempt_id": "atm-missing",
+ "opencode_native_steering": {
+ "target_session_id": "ses_wb",
+ "logical_turn_id": "logical-missing",
+ },
+ }
+ agent, _, removed, _ = _build_agent({"oc-1": poll})
+ agent._test_server.messages = []
+ agent._test_server.status = {"type": "idle"}
+ reconciled: list[tuple[str, str, str]] = []
+
+ def _reconcile(turn_id: str, attempt_id: str, *, backend: str) -> bool:
+ reconciled.append((turn_id, attempt_id, backend))
+ return True
+
+ agent.controller.session_turns.reconcile_start_attempt_not_written = _reconcile
+
+ assert asyncio.run(agent.restore_active_polls()) == 0
+ assert reconciled == [("logical-missing", "atm-missing", "opencode")]
+ assert removed == ["oc-1"]
+
+
def test_restore_keeps_accepted_steer_with_post_assistant_user_evidence() -> None:
poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")
poll.baseline_message_ids = ["old-message"]
diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.py
index 0db93dbc1..7b712255d 100644
--- a/tests/test_opencode_server.py
+++ b/tests/test_opencode_server.py
@@ -419,6 +419,27 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
body = fake_session.posts[0]["json"]
self.assertEqual(body["tools"], {"question": False})
+ async def test_prompt_async_uses_durable_attempt_as_native_message_id(self):
+ manager = OpenCodeServerManager(binary="opencode", port=4096)
+ fake_session = _FakeSession()
+
+ async def _fake_get_http_session():
+ return fake_session
+
+ manager._get_http_session = _fake_get_http_session # type: ignore[method-assign]
+
+ await manager.prompt_async(
+ session_id="ses-1",
+ directory="/tmp/work",
+ text="hello",
+ message_id="atm_exact_evidence",
+ )
+
+ self.assertEqual(
+ fake_session.posts[0]["json"]["messageID"],
+ "atm_exact_evidence",
+ )
+
async def test_prompt_async_exposes_definitive_http_rejection(self):
manager = OpenCodeServerManager(binary="opencode", port=4096)
fake_session = _FakeSession()
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 4e49d2318..4d3ec9545 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -1379,7 +1379,7 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("Outside an Agent shell, a caller-less run", prompt)
self.assertIn("Pass `--sync` only when the current process must wait for the result", prompt)
self.assertIn(
- "That existing-Session send queues behind an active turn by default",
+ "That existing-Session send is a P1 delivery by default",
prompt,
)
self.assertIn(
@@ -1411,11 +1411,32 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
prompt,
)
self.assertIn(
- "the new message does not leapfrog it",
+ "`--send-now --message` is a content-P0 admission",
prompt,
)
self.assertIn(
- "If interruption is refused, the active turn and durable queue remain intact",
+ "starts that new instruction immediately even if older backlog is held",
+ prompt,
+ )
+ self.assertIn(
+ "adds no Message; it releases the hold and promotes the exact oldest queued P3 head",
+ prompt,
+ )
+ self.assertIn(
+ "steers that exact head into the active logical/native Turn",
+ prompt,
+ )
+ self.assertIn(
+ "if the Session is idle, it starts that head as a new Turn",
+ prompt,
+ )
+ self.assertNotIn(
+ "Both forms require a Web/Workbench Session, interrupt through the shared Stop path",
+ prompt,
+ )
+ self.assertNotIn("the new message does not leapfrog it", prompt)
+ self.assertIn(
+ "if that interruption is refused, the active Turn and durable queue remain intact",
prompt,
)
self.assertNotIn("Add `--same-scope` to require the caller/source scope", prompt)
diff --git a/tests/test_running_agents_service.py b/tests/test_running_agents_service.py
index ca3452874..f50ea9add 100644
--- a/tests/test_running_agents_service.py
+++ b/tests/test_running_agents_service.py
@@ -967,7 +967,7 @@ def test_end_active_agent_run_binds_stop_context_to_matching_turn_sink(monkeypat
"agent_session_id": session_id,
"task_trigger_kind": "agent_run",
"task_execution_id": "run-primary",
- "coalesced_queue": {"execution_ids": ["run-coalesced"]},
+ "accepted_agent_run_ids": ["run-primary", "run-coalesced"],
"agent_session_target": {
"id": session_id,
"agent_backend": "codex",
@@ -1001,7 +1001,10 @@ def test_end_active_agent_run_binds_stop_context_to_matching_turn_sink(monkeypat
assert stopped_context.platform_specific["turn_token"] == "sink-token"
assert stopped_context.platform_specific["task_trigger_kind"] == "agent_run"
assert stopped_context.platform_specific["task_execution_id"] == "run-primary"
- assert stopped_context.platform_specific["coalesced_queue"] == {"execution_ids": ["run-coalesced"]}
+ assert stopped_context.platform_specific["accepted_agent_run_ids"] == [
+ "run-primary",
+ "run-coalesced",
+ ]
assert stopped_context.platform_specific["agent_session_target"]["session_anchor"] == base_session_id
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index bb45b631d..2e93e3b68 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -38,15 +38,19 @@ from core.scheduled_tasks import (
ScheduledTaskService,
ScheduledTaskStore,
SessionBindingChange,
+ TaskDispatchResult,
TaskExecutionRequest,
TaskExecutionStore,
+ _TASK_RESULT_NOT_RECORDED_ERROR,
_agent_run_message_for_request,
build_session_key_for_context,
+ normalize_agent_run_delivery_intent,
parse_session_key,
resolve_session_id_target,
session_anchor_for_target,
)
from modules.im import MessageContext
+from storage import message_deliveries
from storage.db import create_sqlite_engine
from storage.background import SQLiteBackgroundTaskStore
from storage.models import (
@@ -1767,18 +1771,18 @@ def test_restart_recovers_running_row_and_preserves_same_session_fifo(monkeypatc
assert restarted_store.get_run(second.id)["status"] == "succeeded"
-def test_restart_recovers_persisted_workbench_run_queue_after_older_owner_settles(
+def test_restart_recovers_delivery_owned_run_without_unrelated_run_arbitration(
monkeypatch,
tmp_path,
) -> None:
- """HFR-004: durable queue ownership resumes once an older Run is terminal."""
+ """Only the Delivery FIFO can block recovery; an unlinked Run cannot."""
from core.session_turns import (
SCHEDULED_PROVENANCE_KEY,
SessionTurnManager,
capture_scheduled_provenance,
)
- from storage import messages_service
+ from storage.background import attach_agent_run_delivery_in_connection
from storage.models import agent_sessions
session_id = _make_avibe_session(monkeypatch, tmp_path)
@@ -1792,7 +1796,6 @@ def test_restart_recovers_persisted_workbench_run_queue_after_older_owner_settle
session_id=session_id,
message="persisted successor",
agent_name="codex",
- metadata={"workbench_queue_holds_run": True},
)
sqlite_store = request_store._sqlite
assert sqlite_store is not None
@@ -1814,14 +1817,13 @@ def test_restart_recovers_persisted_workbench_run_queue_after_older_owner_settle
session = conn.execute(
select(agent_sessions).where(agent_sessions.c.id == session_id)
).mappings().one()
- messages_service.append(
+ delivery = message_deliveries.enqueue_queued(
conn,
scope_id=session["scope_id"],
session_id=session_id,
- platform="avibe",
author="harness",
source="harness",
- message_type=messages_service.QUEUED_TYPE,
+ message_type="harness",
text="persisted successor",
metadata={
SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(
@@ -1830,6 +1832,12 @@ def test_restart_recovers_persisted_workbench_run_queue_after_older_owner_settle
},
native_message_id=f"agent_run:{successor.id}",
)
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ successor.id,
+ session_id=session_id,
+ delivery_id=str(delivery["id"]),
+ )
class _Controller:
def __init__(self) -> None:
@@ -1874,13 +1882,6 @@ def test_restart_recovers_persisted_workbench_run_queue_after_older_owner_settle
monkeypatch.setattr("core.session_turns.dispatch_turn_with_outcome", _dispatch)
async def _exercise() -> None:
- # The older scheduler-owned Run keeps its original FIFO position.
- assert await controller.session_turns.recover_persisted_agent_run_queue() == []
- assert started == []
- with engine.connect() as conn:
- assert len(messages_service.list_queued(conn, session_id)) == 1
-
- request_store.complete(older, ok=True)
assert await controller.session_turns.recover_persisted_agent_run_queue(
session_id
) == [session_id]
@@ -1890,9 +1891,10 @@ def test_restart_recovers_persisted_workbench_run_queue_after_older_owner_settle
await asyncio.sleep(0.005)
assert started == [successor.id]
+ assert request_store.get_run(older.id)["status"] == "queued"
assert request_store.get_run(successor.id)["status"] == "succeeded"
with engine.connect() as conn:
- assert messages_service.list_queued(conn, session_id) == []
+ assert message_deliveries.list_queued(conn, session_id) == []
assert await controller.session_turns.recover_persisted_agent_run_queue(
session_id
@@ -1916,7 +1918,7 @@ def test_restart_does_not_auto_send_pure_user_queue(monkeypatch, tmp_path) -> No
session = conn.execute(
select(agent_sessions).where(agent_sessions.c.id == session_id)
).mappings().one()
- messages_service.enqueue_queued(
+ message_deliveries.enqueue_queued(
conn,
scope_id=session["scope_id"],
session_id=session_id,
@@ -1936,7 +1938,7 @@ def test_restart_does_not_auto_send_pure_user_queue(monkeypatch, tmp_path) -> No
assert asyncio.run(manager.recover_persisted_agent_run_queue()) == []
with engine.connect() as conn:
- assert [row["text"] for row in messages_service.list_queued(conn, session_id)] == [
+ assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == [
"kept after explicit stop"
]
engine.dispose()
@@ -1981,20 +1983,19 @@ def test_restart_does_not_flush_user_queue_ahead_of_held_agent_run(
session = conn.execute(
select(agent_sessions).where(agent_sessions.c.id == session_id)
).mappings().one()
- messages_service.enqueue_queued(
+ message_deliveries.enqueue_queued(
conn,
scope_id=session["scope_id"],
session_id=session_id,
text="kept after explicit stop",
)
- messages_service.append(
+ message_deliveries.enqueue_queued(
conn,
scope_id=session["scope_id"],
session_id=session_id,
- platform="avibe",
author="harness",
source="harness",
- message_type=messages_service.QUEUED_TYPE,
+ message_type="harness",
text="held successor",
metadata={
SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(
@@ -2021,7 +2022,7 @@ def test_restart_does_not_flush_user_queue_ahead_of_held_agent_run(
with engine.connect() as conn:
assert [
row["text"]
- for row in messages_service.list_queued(conn, session_id)
+ for row in message_deliveries.list_queued(conn, session_id)
] == ["kept after explicit stop", "held successor"]
engine.dispose()
@@ -2978,9 +2979,7 @@ def test_sweep_skips_running_run_owned_by_workbench_turn(tmp_path: Path, monkeyp
platform="slack",
platform_specific={
"task_execution_id": run_id,
- # A coalesced turn settles several runs; it owns every one of them, not
- # just the primary, or the sweep fails the siblings out from under it.
- "coalesced_queue": {"execution_ids": [sibling_id]},
+ "accepted_agent_run_ids": [run_id, sibling_id],
},
)
session_turns.register_turn_sink(
@@ -3311,15 +3310,10 @@ def test_sweep_ignores_queued_run_skipped_only_for_capacity(tmp_path: Path, monk
assert request_store.get_run(run_id)["status"] == "queued"
-def test_sweep_expires_a_workbench_queue_hold_only_after_its_ttl(
+def test_legacy_queue_hold_metadata_has_no_sweep_authority(
tmp_path: Path, monkeypatch
) -> None:
- """The hold TTL is the longest one: a recovering queue must be allowed to recover.
-
- A run holding a workbench queue slot is waiting on the session's turn queue, which
- legitimately drains slowly. Only a hold nothing has touched for the full TTL is
- treated as a gate that never reopened.
- """
+ """Old metadata cannot recreate the removed Run-owned queue lifecycle."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
request_store = TaskExecutionStore()
@@ -3334,23 +3328,13 @@ def test_sweep_expires_a_workbench_queue_hold_only_after_its_ttl(
service._sweep_stale_runs()
assert request_store.get_run(recovering)["status"] == "queued"
- expired = request_store.get_run(abandoned)
- assert expired["status"] == "failed"
- assert expired["metadata"]["interrupt_reason"] == "queue_hold_expired"
+ assert request_store.get_run(abandoned)["status"] == "queued"
-def test_sweep_spares_an_aged_queue_hold_a_live_turn_still_owns(
+def test_legacy_hold_metadata_does_not_change_turn_or_run_ownership(
tmp_path: Path, monkeypatch
) -> None:
- """HFR-026: ownership outranks the queue TTLs too, not just the orphan grace.
-
- A coalesced workbench turn deliberately leaves its secondary runs ``queued`` with
- ``workbench_queue_holds_run`` while the primary settles them, and reports every one
- of them from ``owned_agent_run_ids``. A hold TTL that ignored ownership would fail
- those live siblings the moment the turn outran it — a turn-duration timeout by the
- back door, which this design explicitly does not have. The control row proves the
- class still works: same age, same flag, no owner.
- """
+ """Only explicit Turn attribution owns running work; legacy flags own nothing."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
request_store = TaskExecutionStore()
@@ -3376,7 +3360,7 @@ def test_sweep_spares_an_aged_queue_hold_a_live_turn_still_owns(
platform="slack",
platform_specific={
"task_execution_id": primary,
- "coalesced_queue": {"execution_ids": [held]},
+ "accepted_agent_run_ids": [primary],
},
),
)
@@ -3384,7 +3368,7 @@ def test_sweep_spares_an_aged_queue_hold_a_live_turn_still_owns(
service._sweep_stale_runs()
assert request_store.get_run(held)["status"] == "queued"
- assert request_store.get_run(unowned)["status"] == "failed"
+ assert request_store.get_run(unowned)["status"] == "queued"
def test_workbench_turn_settles_its_agent_run_when_no_result_arrives(
@@ -3432,7 +3416,7 @@ def test_workbench_turn_settles_its_agent_run_when_no_result_arrives(
platform_specific={
"task_execution_id": primary,
"task_trigger_kind": "agent_run",
- "coalesced_queue": {"execution_ids": [sibling]},
+ "accepted_agent_run_ids": [primary, sibling],
},
)
@@ -3531,6 +3515,106 @@ def test_backend_refresh_settles_its_run_as_a_refresh_not_a_user_stop(
assert "stop" not in settled["error"].lower()
+def test_backend_refresh_settles_restored_durable_agent_run(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ from storage.background import attach_agent_run_delivery_in_connection
+
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ service = _sweep_service(tmp_path, request_store)
+ run_id = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="restored before backend refresh",
+ agent_name="codex",
+ ).id
+ _force_run_columns(request_store, run_id, status="running", started_at=_ago(30))
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = conn.execute(
+ select(agent_sessions.c.scope_id).where(agent_sessions.c.id == session_id)
+ ).scalar_one()
+ delivery_id = message_deliveries.new_delivery_id()
+ turn_id = message_deliveries.new_turn_id()
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=session_id,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="restored before backend refresh",
+ native_message_id=f"agent_run:{run_id}",
+ metadata={
+ "scheduled_provenance": {
+ "task_execution_id": run_id,
+ "platform_specific": {
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": run_id,
+ },
+ }
+ },
+ ),
+ dispatch_text="restored before backend refresh",
+ )
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ run_id,
+ session_id=session_id,
+ delivery_id=delivery_id,
+ )
+ message_deliveries.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend="codex",
+ deliveries=[delivery],
+ dispatch_text="restored before backend refresh",
+ )
+ turn = message_deliveries.get_turn(conn, turn_id)
+ assert turn is not None
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ runtime_key="restored-runtime",
+ runtime_turn_id="restored-turn",
+ native_turn_id="restored-native",
+ ) is not None
+ assert message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "restored_native_acceptance"},
+ )
+
+ manager = SessionTurnManager(controller=None)
+ manager._engine = engine
+ manager.controller = SimpleNamespace(
+ scheduled_task_service=service,
+ set_agent_status=lambda *_args, **_kwargs: None,
+ )
+ assert run_id in manager.owned_agent_run_ids()
+
+ released = asyncio.run(
+ manager.release_for_backend_refresh(
+ backend="codex",
+ base_session_ids={session_id},
+ )
+ )
+
+ assert released == 1
+ settled = request_store.get_run(run_id)
+ assert settled["status"] == "failed"
+ assert settled["metadata"]["interrupt_reason"] == SETTLED_BY_BACKEND_REFRESH
+
+
def test_turn_only_result_leaves_an_activity_owned_run_alone(
tmp_path: Path, monkeypatch
) -> None:
@@ -3700,7 +3784,7 @@ def test_sweep_spares_a_hold_parked_behind_a_live_session_turn(
assert request_store.get_run(held)["status"] == "queued", "the gate will flush it"
assert request_store.get_run(live)["status"] == "running", "owned, so never swept"
- assert request_store.get_run(abandoned)["status"] == "failed", "no live turn => abandoned"
+ assert request_store.get_run(abandoned)["status"] == "queued"
turn = manager.in_flight.get(session_id)
assert turn is not None
@@ -3711,54 +3795,50 @@ def test_sweep_spares_a_hold_parked_behind_a_live_session_turn(
asyncio.run(_exercise())
-def test_sweep_retires_the_queue_segment_of_the_run_it_expired(
+def test_canceling_a_delivery_owned_run_retires_its_exact_queue_row(
tmp_path: Path, monkeypatch
) -> None:
- """HFR-028: terminalizing the row is not enough — the queued segment must go too.
+ """Run cancellation and exact Delivery retirement share one transaction."""
- ``recover_persisted_agent_run_queue`` ignores references whose run is no longer
- ``queued``, so a swept run's persisted ``messages`` row is nobody's to reclaim: the
- Session keeps showing stale pending input until an unrelated user send happens to
- force ``flush_queue`` to retire it. The sweep already knows the session, so it
- reconciles immediately.
- """
-
- from storage import messages_service
+ from storage.background import attach_agent_run_delivery_in_connection
from storage.models import agent_sessions
session_id = _make_avibe_session(monkeypatch, tmp_path)
request_store = TaskExecutionStore()
- held = request_store.enqueue_agent_run(
+ run = request_store.enqueue_agent_run(
session_id=session_id,
- message="held behind a gate that never reopened",
+ message="cancel this queued input",
agent_name="codex",
- metadata={"workbench_queue_holds_run": True},
- ).id
- _force_run_columns(request_store, held, updated_at=_ago(7200))
+ )
engine = create_sqlite_engine()
with engine.begin() as conn:
session = conn.execute(
select(agent_sessions).where(agent_sessions.c.id == session_id)
).mappings().one()
- messages_service.append(
+ delivery = message_deliveries.enqueue_queued(
conn,
scope_id=session["scope_id"],
session_id=session_id,
- platform="avibe",
author="harness",
source="harness",
- message_type=messages_service.QUEUED_TYPE,
- text="held behind a gate that never reopened",
- native_message_id=f"agent_run:{held}",
+ message_type="harness",
+ text="cancel this queued input",
+ native_message_id=f"agent_run:{run.id}",
)
- assert len(messages_service.list_queued(conn, session_id)) == 1
- service = _sweep_service(tmp_path, request_store)
-
- service._sweep_stale_runs()
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ run.id,
+ session_id=session_id,
+ delivery_id=str(delivery["id"]),
+ )
+ assert len(message_deliveries.list_queued(conn, session_id)) == 1
- assert request_store.get_run(held)["metadata"]["interrupt_reason"] == "queue_hold_expired"
+ assert request_store.cancel_run(run.id) is True
+ assert request_store.get_run(run.id)["status"] == "canceled"
with create_sqlite_engine().connect() as conn:
- assert messages_service.list_queued(conn, session_id) == []
+ assert message_deliveries.list_queued(conn, session_id) == []
+ retired = message_deliveries.get_delivery(conn, str(delivery["id"]))
+ assert retired is not None and retired["state"] == "retired"
def test_sweep_leaves_watch_runtime_and_deferred_rows_alone(tmp_path: Path, monkeypatch) -> None:
@@ -4016,7 +4096,7 @@ def test_agent_run_with_blank_message_fails_instead_of_hanging(tmp_path: Path, m
assert settled["completed_at"] is not None
-def test_duplicate_recovered_coalesced_agent_run_settles_held_children(tmp_path: Path, monkeypatch) -> None:
+def test_duplicate_result_settles_only_the_exact_agent_run(tmp_path: Path, monkeypatch) -> None:
session_id = _make_avibe_session(monkeypatch, tmp_path)
request_store = TaskExecutionStore()
run_ids: list[str] = []
@@ -4025,15 +4105,9 @@ def test_duplicate_recovered_coalesced_agent_run_settles_held_children(tmp_path:
session_id=session_id,
message=f"coalesced prompt {index + 1}",
agent_name="codex",
- metadata={"workbench_queue_holds_run": True},
)
run_ids.append(request.id)
- sqlite_store = request_store._sqlite
- assert sqlite_store is not None
- assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
- request_store.recover_processing()
-
async def _submit_scheduled(_sid, _ctx, _text):
return "duplicate"
@@ -4042,27 +4116,24 @@ def test_duplicate_recovered_coalesced_agent_run_settles_held_children(tmp_path:
gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})
controller = _avibe_controller_double(gate=gate, handle_scheduled_message=_handle_scheduled_message)
- recover_queue = AsyncMock(return_value=[])
- controller.session_turns = SimpleNamespace(
- recover_persisted_agent_run_queue=recover_queue,
- )
service = ScheduledTaskService(
controller=controller,
store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
request_store=request_store,
)
- asyncio.run(service._drain_requests())
+ claimed = request_store.claim(run_ids[0])
+ assert claimed is not None
+ asyncio.run(service._execute_claimed_request(claimed))
stored = {run_id: request_store.get_run(run_id) for run_id in run_ids}
assert stored[run_ids[0]]["status"] == "succeeded"
- assert stored[run_ids[1]]["status"] == "succeeded"
+ assert stored[run_ids[1]]["status"] == "queued"
assert stored[run_ids[0]]["completed_at"] is not None
- assert stored[run_ids[1]]["completed_at"] is not None
- recover_queue.assert_awaited_once_with(session_id)
+ assert stored[run_ids[1]]["completed_at"] is None
-def test_recover_processing_rebuilds_coalesced_metadata_without_queue_rows(
+def test_recover_processing_preserves_independent_agent_runs(
tmp_path: Path,
monkeypatch,
) -> None:
@@ -4074,133 +4145,220 @@ def test_recover_processing_rebuilds_coalesced_metadata_without_queue_rows(
session_id=session_id,
message=f"coalesced prompt {index + 1}",
agent_name="codex",
- metadata={"workbench_queue_holds_run": True},
)
run_ids.append(request.id)
- sqlite_store = request_store._sqlite
- assert sqlite_store is not None
- assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
+ for run_id in run_ids:
+ assert request_store.claim(run_id) is not None
request_store.recover_processing()
pending = request_store.list_pending()
- assert [request.id for request in pending] == [run_ids[0]]
- assert pending[0].metadata["coalesced_queue"]["execution_ids"] == run_ids
- assert _agent_run_message_for_request(pending[0]) == (
- "coalesced prompt 1\n\n---\n\ncoalesced prompt 2\n\n---\n\ncoalesced prompt 3"
- )
+ assert [request.id for request in pending] == run_ids
+ assert [_agent_run_message_for_request(request) for request in pending] == [
+ "coalesced prompt 1",
+ "coalesced prompt 2",
+ "coalesced prompt 3",
+ ]
+ assert all("coalesced_queue" not in request.metadata for request in pending)
-def test_recovered_agent_run_retires_stale_queued_native_rows_before_gate(
+def test_recovery_preserves_delivery_owned_agent_run_batch(
tmp_path: Path,
monkeypatch,
) -> None:
+ from storage.background import (
+ attach_agent_run_delivery_in_connection,
+ claim_agent_runs_for_turn_in_connection,
+ )
+
session_id = _make_avibe_session(monkeypatch, tmp_path)
request_store = TaskExecutionStore()
run_ids: list[str] = []
for index in range(2):
request = request_store.enqueue_agent_run(
session_id=session_id,
- message=f"coalesced prompt {index + 1}",
+ message=f"batched prompt {index + 1}",
agent_name="codex",
- metadata={"workbench_queue_holds_run": True},
)
run_ids.append(request.id)
- sqlite_store = request_store._sqlite
- assert sqlite_store is not None
- assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
- request_store.recover_processing()
-
- from storage import messages_service
- from storage.models import agent_sessions, messages
-
engine = create_sqlite_engine()
with engine.begin() as conn:
session = conn.execute(
select(agent_sessions).where(agent_sessions.c.id == session_id).limit(1)
).mappings().first()
assert session is not None
- scope_id = session["scope_id"]
+ deliveries = []
for run_id in run_ids:
- messages_service.append(
+ delivery = message_deliveries.enqueue_queued(
conn,
- scope_id=scope_id,
+ scope_id=session["scope_id"],
session_id=session_id,
- platform="avibe",
author="harness",
source="harness",
- message_type=messages_service.QUEUED_TYPE,
- text=f"stale queued row for {run_id}",
+ message_type="harness",
+ text=f"batched prompt {len(deliveries) + 1}",
native_message_id=f"agent_run:{run_id}",
)
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ run_id,
+ session_id=session_id,
+ delivery_id=str(delivery["id"]),
+ )
+ deliveries.append(delivery)
+ assert claim_agent_runs_for_turn_in_connection(conn, run_ids) == run_ids
+ claimed = message_deliveries.claim_start_batch(
+ conn,
+ turn_id=message_deliveries.new_turn_id(),
+ session_id=session_id,
+ backend="codex",
+ deliveries=deliveries,
+ dispatch_text="batched prompt 1\n\nbatched prompt 2",
+ )
- submitted: list[str] = []
+ request_store.recover_processing()
- async def _submit_scheduled(_sid, ctx, text):
- with engine.connect() as conn:
- if messages_service.native_message_exists(
- conn,
- platform="avibe",
- native_message_id=ctx.message_id,
- ):
- return "duplicate"
- submitted.append(text)
- return "ran"
+ assert request_store.list_pending() == []
+ stored = [request_store.get_run(run_id) for run_id in run_ids]
+ assert [row["status"] for row in stored] == ["running", "running"]
+ assert [row["delivery_id"] for row in stored] == [
+ delivery["id"] for delivery in deliveries
+ ]
+ with engine.connect() as conn:
+ retained = [
+ message_deliveries.get_delivery(conn, delivery["id"])
+ for delivery in deliveries
+ ]
+ assert all(row is not None and row["state"] == "claimed" for row in retained)
+ assert len({row["turn_id"] for row in retained}) == 1
+ assert retained[0]["turn_id"] == claimed["turn"]["id"]
- async def _handle_scheduled_message(context, message, parsed_session_key=None):
- return None
- gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})
- controller = _avibe_controller_double(gate=gate, handle_scheduled_message=_handle_scheduled_message)
+def test_recovered_agent_run_resubmits_through_real_session_gate(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ from core import internal_server, session_turns
+
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="recover through the durable gate",
+ agent_name="codex",
+ )
+ engine = create_sqlite_engine()
+
+ sinks: dict[str, dict] = {}
+
+ def _session_key(context):
+ return f"avibe::{(context.platform_specific or {}).get('agent_session_id')}"
+
+ def _register_sink(
+ key,
+ *,
+ on_chunk,
+ done_event,
+ turn_token=None,
+ context=None,
+ ):
+ sinks[key] = {
+ "on_chunk": on_chunk,
+ "done_event": done_event,
+ "turn_token": turn_token,
+ "context": context,
+ }
+
+ controller = SimpleNamespace(
+ platform_settings_managers={},
+ im_clients={"avibe": SimpleNamespace()},
+ get_im_client_for_context=lambda _context: SimpleNamespace(
+ should_use_thread_for_reply=lambda: True,
+ should_use_thread_for_dm_session=lambda: False,
+ ),
+ message_handler=SimpleNamespace(handle_scheduled_message=AsyncMock()),
+ command_handler=SimpleNamespace(handle_stop=AsyncMock(return_value=True)),
+ agent_service=SimpleNamespace(default_agent="codex", agents={}, _turn_gates={}),
+ config=SimpleNamespace(language="en"),
+ _get_lang=lambda: "en",
+ _get_session_key=_session_key,
+ register_turn_sink=_register_sink,
+ get_turn_sink=lambda key: sinks.get(key),
+ pop_turn_sink=lambda key, done_event=None: sinks.pop(key, None),
+ _session_id_from_context=lambda context: (
+ context.platform_specific or {}
+ ).get("agent_session_id"),
+ resolve_agent_for_context=lambda _context: "codex",
+ set_agent_status=lambda *_args: None,
+ emit_agent_message=AsyncMock(),
+ )
+ internal_server.create_app(controller)
+ dispatched: list[str] = []
+
+ async def _dispatch(_controller, _context, text, **_kwargs):
+ dispatched.append(text)
+ logical_turn_id = str(
+ (_context.platform_specific or {}).get("turn_token") or ""
+ )
+ assert logical_turn_id
+ _controller.session_turns.on_native_start(
+ _context,
+ backend="codex",
+ runtime_key=f"runtime:{logical_turn_id}",
+ runtime_turn_id=f"runtime-turn:{logical_turn_id}",
+ )
+ return TurnDispatchOutcome(
+ error=None,
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ )
+
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _dispatch)
service = ScheduledTaskService(
controller=controller,
store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
request_store=request_store,
)
+ controller.scheduled_task_service = service
async def _exercise() -> None:
await service._drain_requests()
- execution = service._inflight_executions.get(run_ids[0])
- if execution is not None:
- await execution
+ execution = service._inflight_executions.get(request.id)
+ assert execution is not None
+ await execution
+ for _ in range(100):
+ if not controller.session_turns.in_flight:
+ break
+ await asyncio.sleep(0)
asyncio.run(_exercise())
- assert len(submitted) == 1
- assert "coalesced prompt 1" in submitted[0]
- assert "coalesced prompt 2" in submitted[0]
+ assert dispatched == ["recover through the durable gate"]
with engine.connect() as conn:
- assert messages_service.list_queued(conn, session_id) == []
- dedupe_rows = conn.execute(
- select(messages.c.native_message_id, messages.c.type)
- .where(messages.c.session_id == session_id)
- .where(messages.c.type == messages_service.HARNESS_DEDUPE_TYPE)
- ).all()
- assert {row.native_message_id for row in dedupe_rows} == {f"agent_run:{run_ids[1]}"}
- stored = {run_id: request_store.get_run(run_id) for run_id in run_ids}
- assert stored[run_ids[0]]["status"] == "running"
- assert stored[run_ids[1]]["status"] == "queued"
+ stored_run = conn.execute(
+ select(agent_runs).where(agent_runs.c.id == request.id)
+ ).mappings().one()
+ owner = message_deliveries.get_delivery(conn, stored_run["delivery_id"])
+ accepted_message = conn.execute(
+ select(messages).where(messages.c.id == stored_run["delivery_id"])
+ ).mappings().one()
+ assert owner is not None
+ assert owner["state"] == "accepted"
+ assert owner["id"] == accepted_message["id"] == stored_run["delivery_id"]
-def test_recovered_coalesced_agent_run_early_failure_settles_children(tmp_path: Path, monkeypatch) -> None:
+def test_agent_run_early_failure_settles_only_the_exact_run(tmp_path: Path, monkeypatch) -> None:
session_id = _make_avibe_session(monkeypatch, tmp_path)
request_store = TaskExecutionStore()
run_ids: list[str] = []
for index in range(2):
request = request_store.enqueue_agent_run(
session_id=session_id,
- message=f"coalesced prompt {index + 1}",
+ message=f"independent prompt {index + 1}",
agent_name="codex",
- metadata={"workbench_queue_holds_run": True},
)
run_ids.append(request.id)
-
- sqlite_store = request_store._sqlite
- assert sqlite_store is not None
- assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
- request_store.recover_processing()
claimed = request_store.claim(run_ids[0])
assert claimed is not None
@@ -4227,11 +4385,10 @@ def test_recovered_coalesced_agent_run_early_failure_settles_children(tmp_path:
stored = {run_id: request_store.get_run(run_id) for run_id in run_ids}
assert stored[run_ids[0]]["status"] == "failed"
- assert stored[run_ids[1]]["status"] == "failed"
+ assert stored[run_ids[1]]["status"] == "queued"
assert stored[run_ids[0]]["completed_at"] is not None
- assert stored[run_ids[1]]["completed_at"] is not None
+ assert stored[run_ids[1]]["completed_at"] is None
assert stored[run_ids[0]]["error"] == "target session vanished"
- assert stored[run_ids[1]]["error"] == "target session vanished"
def _harness_turn_context(
@@ -4279,7 +4436,7 @@ def _harness_dispatcher() -> ConsolidatedMessageDispatcher:
release_runtime_turn=lambda _context: None,
),
session_turns=SimpleNamespace(
- on_terminal_result=lambda _context, is_error=False: None,
+ on_terminal_result=lambda _context, is_error=False, **_kwargs: None,
),
mark_turn_complete=lambda _context, **_kwargs: None,
)
@@ -4659,30 +4816,22 @@ def test_silent_terminal_skips_callback_and_keeps_directed_run(
agent_events.c.content_text,
).where(agent_events.c.session_id == target_session_id)
).mappings().all()
- assert [row["author"] for row in target_messages] == [
- "harness",
- "agent",
- "agent",
- ]
+ assert [row["author"] for row in target_messages] == ["harness", "agent"]
assert [row["type"] for row in target_messages] == [
"harness",
"assistant",
- "silent",
]
assert [row["source"] for row in target_messages] == [
"harness",
"agent",
- "agent",
]
assert [row["native_message_id"] for row in target_messages] == [
f"agent_run:{request.id}",
preamble_output.native_message_id(context),
- None,
]
assert [row["content_text"] for row in target_messages] == [
"escalation prompt",
"裁决如下:",
- "",
]
assert all(row["author"] != "user" and row["type"] != "user" for row in target_messages)
assert tool_events == [
@@ -6210,6 +6359,20 @@ def test_avibe_agent_run_routes_through_gate_without_completing_early(monkeypatc
message="run in workbench session",
agent_name="codex",
)
+ sqlite_backend = request_store.sqlite_backend
+ assert sqlite_backend is not None
+ with sqlite_backend.engine.begin() as conn:
+ metadata = json.loads(
+ conn.execute(
+ select(agent_runs.c.metadata_json).where(agent_runs.c.id == request.id)
+ ).scalar_one()
+ )
+ metadata["delivery_intent"] = "queue"
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == request.id)
+ .values(metadata_json=json.dumps(metadata))
+ )
submitted: list[tuple] = []
handler_calls: list = []
@@ -6245,7 +6408,11 @@ def test_avibe_agent_run_routes_through_gate_without_completing_early(monkeypatc
assert handler_calls == []
-def test_busy_avibe_agent_run_send_now_records_the_turn_owner_outcome(monkeypatch, tmp_path) -> None:
+def test_legacy_queue_delivery_intent_normalizes_to_current_steer() -> None:
+ assert normalize_agent_run_delivery_intent("queue") == "steer"
+
+
+def test_busy_avibe_agent_run_send_now_keeps_transferred_owner_running(monkeypatch, tmp_path) -> None:
session_id = _make_avibe_session(monkeypatch, tmp_path)
request_store = TaskExecutionStore()
request = request_store.enqueue_agent_run(
@@ -6273,6 +6440,7 @@ def test_busy_avibe_agent_run_send_now_records_the_turn_owner_outcome(monkeypatc
queue_persisted=True,
target_was_busy=True,
delivery_status="interrupted",
+ delivery_owner_transferred=True,
)
async def _handle_scheduled_message(context, message, parsed_session_key=None):
@@ -6298,16 +6466,11 @@ def test_busy_avibe_agent_run_send_now_records_the_turn_owner_outcome(monkeypatc
run = request_store.get_run(request.id)
assert run is not None
- assert run["status"] == "queued"
- assert run.get("started_at") is None
+ assert run["status"] == "running"
+ assert run.get("started_at") is not None
assert run.get("completed_at") is None
- assert (run.get("metadata") or {}).get("workbench_queue_holds_run") is True
+ assert "workbench_queue_holds_run" not in (run.get("metadata") or {})
assert run["metadata"]["delivery_intent"] == "send_now"
- assert run["metadata"]["delivery_outcome"] == {
- "intent": "send_now",
- "status": "interrupted",
- "target_was_busy": True,
- }
assert submitted == [
(session_id, "run behind active workbench turn", request.id, "send_now")
]
@@ -6344,7 +6507,7 @@ def test_idle_send_now_flush_failure_invokes_queue_recovery(monkeypatch, tmp_pat
queue_persisted=True,
target_was_busy=False,
delivery_status="flush_failed",
- queue_owner_transferred=True,
+ delivery_owner_transferred=True,
)
async def _recover_queue(sid):
@@ -6509,11 +6672,13 @@ def test_busy_avibe_agent_run_requeue_preserves_session_fork_metadata(monkeypatc
run = request_store.get_run(request.id)
assert run is not None
assert run["metadata"]["session_fork"]["source_native_session_id"] == "thread-source"
- assert run["metadata"]["workbench_queue_holds_run"] is True
+ assert "workbench_queue_holds_run" not in run["metadata"]
assert submitted[0][2]["source_native_session_id"] == "thread-source"
-def test_workbench_queue_flush_recovery_preserves_session_fork_metadata(monkeypatch, tmp_path) -> None:
+def test_delivery_claim_preserves_session_fork_metadata(monkeypatch, tmp_path) -> None:
+ from storage.background import attach_agent_run_delivery_in_connection
+
session_id = _make_avibe_session(monkeypatch, tmp_path)
request_store = TaskExecutionStore()
request = request_store.enqueue_agent_run(
@@ -6526,99 +6691,47 @@ def test_workbench_queue_flush_recovery_preserves_session_fork_metadata(monkeypa
"source_native_session_id": "thread-source",
"source_backend": "codex",
},
- "workbench_queue_holds_run": True,
},
)
sqlite_store = request_store._sqlite
assert sqlite_store is not None
- assert sqlite_store.claim_queued_run_for_workbench(request.id) is True
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ session = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == session_id)
+ ).mappings().one()
+ delivery = message_deliveries.enqueue_queued(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="recover fork after queue flush",
+ native_message_id=f"agent_run:{request.id}",
+ )
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ request.id,
+ session_id=session_id,
+ delivery_id=str(delivery["id"]),
+ )
+ assert sqlite_store.claim_agent_run_for_turn(request.id) is True
flushed = request_store.get_run(request.id)
assert flushed is not None
assert flushed["status"] == "running"
- assert flushed["metadata"]["workbench_queue_holds_run"] is False
+ assert flushed["delivery_id"] == delivery["id"]
+ assert "workbench_queue_holds_run" not in flushed["metadata"]
assert flushed["metadata"]["session_fork"]["source_native_session_id"] == "thread-source"
request_store.recover_processing()
- claimed = request_store.claim(request.id)
-
- assert claimed is not None
- assert claimed.metadata["workbench_queue_holds_run"] is False
- assert claimed.metadata["session_fork"]["source_native_session_id"] == "thread-source"
-
-
-def test_recover_processing_keeps_coalesced_agent_run_children_held(monkeypatch, tmp_path) -> None:
- session_id = _make_avibe_session(monkeypatch, tmp_path)
- request_store = TaskExecutionStore()
- run_ids: list[str] = []
- for index in range(3):
- request = request_store.enqueue_agent_run(
- session_id=session_id,
- message=f"coalesced prompt {index + 1}",
- agent_name="codex",
- metadata={"workbench_queue_holds_run": True},
- )
- run_ids.append(request.id)
-
- sqlite_store = request_store._sqlite
- assert sqlite_store is not None
- assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
-
- request_store.recover_processing()
- pending = request_store.list_pending()
-
- assert [request.id for request in pending] == [run_ids[0]]
- primary = request_store.get_run(run_ids[0])
- child = request_store.get_run(run_ids[1])
- assert primary is not None
- assert child is not None
- assert primary["status"] == "queued"
- assert child["status"] == "queued"
- assert primary["metadata"]["workbench_queue_holds_run"] is False
- assert primary["metadata"]["coalesced_queue"]["execution_ids"] == run_ids
- assert primary["metadata"]["coalesced_queue"]["messages"] == [
- {"execution_id": run_ids[0], "message": "coalesced prompt 1"},
- {"execution_id": run_ids[1], "message": "coalesced prompt 2"},
- {"execution_id": run_ids[2], "message": "coalesced prompt 3"},
- ]
- assert child["metadata"]["workbench_queue_holds_run"] is True
- assert child["metadata"]["coalesced_into_run_id"] == run_ids[0]
-
- claimed = request_store.claim(run_ids[0])
- assert claimed is not None
- recovered_message = _agent_run_message_for_request(claimed)
- assert "coalesced prompt 1" in recovered_message
- assert "coalesced prompt 2" in recovered_message
- assert "coalesced prompt 3" in recovered_message
-
-
-def test_recovered_coalesced_agent_run_message_filters_cancelled_child(monkeypatch, tmp_path) -> None:
- session_id = _make_avibe_session(monkeypatch, tmp_path)
- request_store = TaskExecutionStore()
- run_ids: list[str] = []
- for index in range(3):
- request = request_store.enqueue_agent_run(
- session_id=session_id,
- message=f"coalesced prompt {index + 1}",
- agent_name="codex",
- metadata={"workbench_queue_holds_run": True},
- )
- run_ids.append(request.id)
-
- sqlite_store = request_store._sqlite
- assert sqlite_store is not None
- assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
- request_store.recover_processing()
- assert sqlite_store.cancel_run(run_ids[1]) is True
-
- claimed = request_store.claim(run_ids[0])
- assert claimed is not None
- recovered_message = _agent_run_message_for_request(claimed)
-
- assert "coalesced prompt 1" in recovered_message
- assert "coalesced prompt 2" not in recovered_message
- assert "coalesced prompt 3" in recovered_message
+ recovered = request_store.get_run(request.id)
+ assert recovered is not None
+ assert recovered["status"] == "running"
+ assert recovered["delivery_id"] == delivery["id"]
+ assert recovered["metadata"]["session_fork"]["source_native_session_id"] == "thread-source"
def test_inspect_queued_runs_finalizes_cancel_requested_queued_agent_run(monkeypatch, tmp_path) -> None:
@@ -6640,7 +6753,7 @@ def test_inspect_queued_runs_finalizes_cancel_requested_queued_agent_run(monkeyp
cancel_requested_at="2026-06-22T00:00:01Z",
)
- queued_run_ids, stale_run_ids = bg.inspect_queued_runs_for_workbench([request.id])
+ queued_run_ids, stale_run_ids = bg.inspect_agent_runs_for_turn([request.id])
assert queued_run_ids == []
assert stale_run_ids == [request.id]
@@ -6652,17 +6765,37 @@ def test_inspect_queued_runs_finalizes_cancel_requested_queued_agent_run(monkeyp
def test_claim_queued_runs_publishes_after_commit(monkeypatch, tmp_path) -> None:
import storage.background as background_module
+ from storage.background import attach_agent_run_delivery_in_connection
- _make_avibe_session(monkeypatch, tmp_path)
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
request_store = TaskExecutionStore()
request = request_store.enqueue_agent_run(
- session_id="placeholder",
+ session_id=session_id,
message="queued run",
agent_name="codex",
- metadata={"workbench_queue_holds_run": True},
)
bg = request_store._sqlite
assert bg is not None
+ with create_sqlite_engine().begin() as conn:
+ session = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == session_id)
+ ).mappings().one()
+ delivery = message_deliveries.enqueue_queued(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="queued run",
+ native_message_id=f"agent_run:{request.id}",
+ )
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ request.id,
+ session_id=session_id,
+ delivery_id=str(delivery["id"]),
+ )
observed_statuses: list[str | None] = []
@@ -6672,7 +6805,7 @@ def test_claim_queued_runs_publishes_after_commit(monkeypatch, tmp_path) -> None
monkeypatch.setattr(background_module, "_publish_run_rows_updated", capture_publish)
- assert bg.claim_queued_runs_for_workbench([request.id]) == [request.id]
+ assert bg.claim_agent_runs_for_turn([request.id]) == [request.id]
assert observed_statuses == ["running"]
@@ -6727,6 +6860,7 @@ def test_drain_requests_reserves_watch_create_per_run_before_session_validation(
"task_id": "watch-1",
"trigger_kind": "watch",
"agent_name": "release-reviewer",
+ "_capture_dispatch_result": True,
}
]
payload = json.loads((request_store.completed_dir / f"{request.id}.json").read_text(encoding="utf-8"))
@@ -6735,6 +6869,62 @@ def test_drain_requests_reserves_watch_create_per_run_before_session_validation(
assert payload["session_key"] == ""
+def test_claimed_watch_stays_nonterminal_after_delivery_ownership_transfer(
+ monkeypatch,
+ tmp_path: Path,
+) -> None:
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_hook_send(
+ session_key="",
+ session_id=session_id,
+ prompt="watch result",
+ agent_name="release-reviewer",
+ run_type="watch",
+ )
+ submitted: list[tuple[str, str, str]] = []
+
+ async def _submit_scheduled(sid, ctx, text):
+ from core.session_turns import TurnSubmissionResult
+
+ submitted.append(
+ (sid, text, str(ctx.platform_specific.get("task_execution_id") or ""))
+ )
+ return TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ target_was_busy=True,
+ delivery_owner_transferred=True,
+ )
+
+ async def _handle_scheduled_message(*_args, **_kwargs):
+ raise AssertionError("Workbench Watch input must use the Delivery gate")
+
+ gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})
+ service = ScheduledTaskService(
+ controller=_avibe_controller_double(
+ gate=gate,
+ handle_scheduled_message=_handle_scheduled_message,
+ ),
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ async def _exercise() -> None:
+ await service._drain_requests()
+ execution = service._inflight_executions.get(request.id)
+ assert execution is not None
+ await execution
+
+ asyncio.run(_exercise())
+
+ stored = request_store.get_run(request.id)
+ assert stored is not None
+ assert stored["status"] == "running"
+ assert stored.get("completed_at") is None
+ assert submitted == [(session_id, "watch result", request.id)]
+
+
def test_drain_requests_records_scheduled_create_per_run_reserved_session(tmp_path: Path) -> None:
request_store = TaskExecutionStore(tmp_path / "task_requests")
store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
@@ -6783,6 +6973,7 @@ def test_drain_requests_records_scheduled_create_per_run_reserved_session(tmp_pa
"task_id": task.id,
"trigger_kind": "scheduled",
"agent_name": "release-reviewer",
+ "_capture_dispatch_result": True,
}
]
payload = json.loads((request_store.completed_dir / f"{request.id}.json").read_text(encoding="utf-8"))
@@ -6887,6 +7078,7 @@ def test_claimed_request_keeps_agent_identity_when_archive_lands_after_refresh(
"task_id": None,
"trigger_kind": "hook",
"agent_name": "pm",
+ "_capture_dispatch_result": True,
"agent_id": agent.id,
}
]
@@ -7774,6 +7966,12 @@ def test_dead_accepted_owner_converges_run_session_and_persisted_fifo(
)
sqlite_store = request_store._sqlite
assert sqlite_store is not None
+ engine = create_sqlite_engine()
+
+ def _delivery_state(delivery_id: str) -> str | None:
+ with engine.connect() as conn:
+ delivery = message_deliveries.get_delivery(conn, delivery_id)
+ return str(delivery["state"]) if delivery is not None else None
class _Controller:
primary_platform = "avibe"
@@ -7927,16 +8125,17 @@ def test_dead_accepted_owner_converges_run_session_and_persisted_fifo(
await scheduled._drain_requests()
await _wait_for(
- lambda: request_store.get_run(second.id)["metadata"].get(
- "workbench_queue_holds_run"
- )
- is True
+ lambda: request_store.get_run(second.id).get("delivery_id") is not None
+ )
+ second_delivery_id = request_store.get_run(second.id)["delivery_id"]
+ await _wait_for(
+ lambda: _delivery_state(second_delivery_id) == "pending_steer"
)
state = controller.session_turns.turn_state(session_id)
assert state["owner"]["run_id"] == first.id
- assert state["pending_input_count"] == 1
+ assert state["pending_input_count"] == 0
assert request_store.get_run(first.id)["status"] == "running"
- assert request_store.get_run(second.id)["status"] == "queued"
+ assert request_store.get_run(second.id)["status"] == "running"
backend.first_alive = False
await _wait_for(lambda: request_store.get_run(second.id)["status"] == "succeeded")
@@ -9864,6 +10063,55 @@ def test_a_refused_result_stamp_cannot_complete_the_run_ok(tmp_path: Path, monke
)
+def test_refused_task_stamp_fails_durable_run_and_reconciles_its_delivery(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_refusal")
+ task = store.add_task(
+ session_key="",
+ session_id=session_id,
+ session_policy="existing",
+ prompt="send digest",
+ schedule_type="at",
+ run_at="2026-07-28T09:00:00+00:00",
+ timezone_name="UTC",
+ metadata={"origin": "test"},
+ )
+ service = _scheduled_service_with_ledger(tmp_path, store, [])
+ reconciled: list[tuple[str, str]] = []
+
+ async def _execute_request(**_kwargs):
+ return TaskDispatchResult(error=None, complete_on_return=False)
+
+ async def _reconcile(run_id: str, *, session_id: str):
+ reconciled.append((run_id, session_id))
+ return {"changed": True, "state": "retired"}
+
+ service._execute_request = _execute_request
+ service.controller.session_turns = SimpleNamespace(
+ reconcile_terminal_run_delivery=_reconcile
+ )
+ monkeypatch.setattr(store, "mark_task_result", lambda *_args, **_kwargs: False)
+ queued = service.request_store.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=task,
+ )
+ claimed = service.request_store.claim(queued.id)
+ assert claimed is not None
+
+ asyncio.run(service._execute_claimed_request(claimed))
+
+ run = service.request_store.get_run(queued.id)
+ assert run is not None
+ assert run["status"] == "failed"
+ assert run["error"] == _TASK_RESULT_NOT_RECORDED_ERROR
+ assert reconciled == [(queued.id, session_id)]
+
+
def test_a_refused_recovery_record_does_not_notify_a_transition_it_cannot_dedup(
tmp_path: Path, monkeypatch
) -> None:
diff --git a/tests/test_session_activities.py b/tests/test_session_activities.py
index cc317a88c..daf8a0b9d 100644
--- a/tests/test_session_activities.py
+++ b/tests/test_session_activities.py
@@ -341,7 +341,7 @@ def test_turn_state_composes_foreground_inbox_activity_and_connection_axes():
manager._engine = SimpleNamespace(begin=lambda: nullcontext(object()))
with mock.patch(
- "core.session_turns.messages_service.list_queued",
+ "core.session_turns.delivery_store.list_queued",
return_value=[{"id": "queued-1"}],
):
state = manager.turn_state("ses-1")
@@ -379,7 +379,7 @@ def test_turn_state_reports_authoritative_live_owner_diagnostics():
started_at="2026-07-18T04:31:26+00:00",
)
- with mock.patch("core.session_turns.messages_service.list_queued", return_value=[{"id": "queued-1"}]):
+ with mock.patch("core.session_turns.delivery_store.list_queued", return_value=[{"id": "queued-1"}]):
state = manager.turn_state("ses-1")
assert state["in_flight"] is True
diff --git a/tests/test_session_archive.py b/tests/test_session_archive.py
index 8fa28ea14..96d9aea1a 100644
--- a/tests/test_session_archive.py
+++ b/tests/test_session_archive.py
@@ -18,12 +18,20 @@ from config import paths
from core.scheduled_tasks import resolve_session_id_target
from core.show_pages import ShowPageError, ShowPageStore
from core.show_session_events import ShowSessionEventError, ShowSessionEventStore
-from storage import messages_service
+from storage import message_deliveries, messages_service
from storage import vault_service as vs
from storage import workbench_sessions_service as wss
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
-from storage.models import agent_runs, agent_sessions, messages, run_definitions, show_pages, vault_grants, vault_requests
+from storage.models import (
+ agent_runs,
+ agent_sessions,
+ message_deliveries as delivery_rows,
+ run_definitions,
+ show_pages,
+ vault_grants,
+ vault_requests,
+)
from storage.vault_crypto import Sealed
from storage.session_reclaim import session_teardown_context
from storage.sessions_service import SQLiteSessionsService
@@ -57,13 +65,21 @@ def _insert_def(conn, *, def_id: str, session_id: str, definition_type: str, del
)
-def _insert_run(conn, *, run_id: str, session_id: str, status: str) -> None:
+def _insert_run(
+ conn,
+ *,
+ run_id: str,
+ session_id: str,
+ status: str,
+ delivery_id: str | None = None,
+) -> None:
conn.execute(
agent_runs.insert().values(
id=run_id,
run_type="agent",
status=status,
session_id=session_id,
+ delivery_id=delivery_id,
cancel_requested=0,
created_at=NOW,
updated_at=NOW,
@@ -318,9 +334,9 @@ def test_resolve_session_id_target_rejects_archived(tmp_path: Path) -> None:
def _pending_ids(conn, session_id: str) -> list[str]:
return list(
conn.execute(
- select(messages.c.id)
- .where(messages.c.session_id == session_id)
- .where(messages.c.type == messages_service.PENDING_TYPE)
+ select(delivery_rows.c.id)
+ .where(delivery_rows.c.session_id == session_id)
+ .where(delivery_rows.c.state == "reserved")
).scalars()
)
@@ -338,33 +354,58 @@ def test_archive_clears_queued_and_pending_messages(tmp_path: Path) -> None:
engine = create_sqlite_engine(db_path)
with engine.begin() as conn:
- messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=sid, text="q1")
- messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=sid, text="q2")
+ queued_run_delivery = message_deliveries.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id=sid,
+ text="q1",
+ )
+ message_deliveries.enqueue_queued(conn, scope_id=scope_id, session_id=sid, text="q2")
+ _insert_run(
+ conn,
+ run_id="run_delivery_archive",
+ session_id=sid,
+ status="running",
+ delivery_id=str(queued_run_delivery["id"]),
+ )
# A send mid-dispatch reserved its row as ``pending``; the user also has a
# saved composer draft.
- messages_service.append(
+ message_deliveries.insert_delivery(
conn,
- scope_id=scope_id,
+ delivery_id="msg_reserved_archive",
session_id=sid,
- platform="avibe",
- author="user",
- message_type=messages_service.PENDING_TYPE,
- text="reserved",
+ priority="p1",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=sid,
+ platform="avibe",
+ author="user",
+ source="user",
+ text="reserved",
+ ),
+ dispatch_text="reserved",
)
- messages_service.set_draft(conn, scope_id=scope_id, session_id=sid, text="half-typed")
+ message_deliveries.set_draft(conn, sid, "half-typed")
with engine.connect() as conn:
- assert len(messages_service.list_queued(conn, sid)) == 2
+ assert len(message_deliveries.list_queued(conn, sid)) == 2
assert len(_pending_ids(conn, sid)) == 1
- assert messages_service.get_draft(conn, sid)
+ assert message_deliveries.get_draft(conn, sid)
# Queued prompts are surfaced in the reclaim preview (not silently dropped).
assert wss.count_bound_resources(conn, sid)["queued"] == 2
with engine.begin() as conn:
wss.archive_session(conn, sid)
with engine.connect() as conn:
- assert messages_service.list_queued(conn, sid) == []
+ assert message_deliveries.list_queued(conn, sid) == []
assert _pending_ids(conn, sid) == []
- assert not messages_service.get_draft(conn, sid)
+ assert not message_deliveries.get_draft(conn, sid)
+ archived_run = conn.execute(
+ select(agent_runs).where(agent_runs.c.id == "run_delivery_archive")
+ ).mappings().one()
+ assert archived_run["status"] == "canceled"
+ assert archived_run["cancel_requested"] == 1
+ assert archived_run["completed_at"] is not None
def test_archived_show_page_cannot_be_republished(monkeypatch, tmp_path: Path) -> None:
diff --git a/tests/test_session_cli.py b/tests/test_session_cli.py
index ee84f12c4..1bf2ad27a 100644
--- a/tests/test_session_cli.py
+++ b/tests/test_session_cli.py
@@ -5,6 +5,8 @@ import json
import pytest
from config import paths
+from storage import message_deliveries
+from storage.background import attach_agent_run_delivery_in_connection
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_sessions, messages
@@ -392,20 +394,18 @@ def test_queue_list_is_paginated_in_fifo_order_and_exposes_run_identity(
engine = _setup(monkeypatch, tmp_path)
scope_id = _seed(engine, "sesaaa")
with engine.begin() as conn:
- messages_service.enqueue_queued(
+ message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id="sesaaa",
text="first",
)
- messages_service.append(
+ message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id="sesaaa",
- platform="avibe",
author="harness",
source="harness",
- message_type=messages_service.QUEUED_TYPE,
text="second",
metadata={
"scheduled_provenance": {
@@ -416,7 +416,7 @@ def test_queue_list_is_paginated_in_fifo_order_and_exposes_run_identity(
}
},
)
- messages_service.enqueue_queued(
+ message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id="sesaaa",
@@ -461,7 +461,7 @@ def test_queue_remove_deletes_only_the_named_session_row_and_notifies_web(
scope_id = _seed(engine, "sesaaa")
_seed(engine, "sesbbb", native="proj_b")
with engine.begin() as conn:
- queued = messages_service.enqueue_queued(
+ queued = message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id="sesaaa",
@@ -496,7 +496,7 @@ def test_queue_remove_deletes_only_the_named_session_row_and_notifies_web(
assert removed["status"] == "removed"
assert notified == ["sesaaa"]
with engine.connect() as conn:
- assert messages_service.list_queued(conn, "sesaaa") == []
+ assert message_deliveries.list_queued(conn, "sesaaa") == []
def test_queue_remove_cancels_the_agent_run_owned_by_that_row(
@@ -521,17 +521,21 @@ def test_queue_remove_cancels_the_agent_run_owned_by_that_row(
metadata={"workbench_queue_holds_run": True},
)
with engine.begin() as conn:
- queued = messages_service.append(
+ queued = message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id="sesrun",
- platform="avibe",
author="harness",
source="harness",
- message_type=messages_service.QUEUED_TYPE,
text=request.message or "",
native_message_id=f"agent_run:{request.id}",
)
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ request.id,
+ session_id="sesrun",
+ delivery_id=queued["id"],
+ )
monkeypatch.setattr(
cli,
"_post_session_queue_updated_to_live_ui",
@@ -551,7 +555,7 @@ def test_queue_remove_cancels_the_agent_run_owned_by_that_row(
assert stored["status"] == "canceled"
assert stored["cancel_requested"] is True
with engine.connect() as conn:
- assert messages_service.list_queued(conn, "sesrun") == []
+ assert message_deliveries.list_queued(conn, "sesrun") == []
def test_queue_commands_reject_an_archived_session(monkeypatch, tmp_path, capsys):
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
new file mode 100644
index 000000000..f7c239f2b
--- /dev/null
+++ b/tests/test_session_delivery_fsm.py
@@ -0,0 +1,3935 @@
+from __future__ import annotations
+
+import asyncio
+import json
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from sqlalchemy import select, update
+
+from core.services.agent_steering import SteerOutcome, result as steer_result
+from core.services.dispatch import TurnDispatchOutcome
+from core.native_dispatch_phase import (
+ DISPATCH_PHASE_ATTEMPTING,
+ DISPATCH_PHASE_PREWRITE,
+ set_dispatch_phase,
+)
+from core.run_settlement import SETTLED_BY_TERMINAL_RESULT
+from core.session_turns import (
+ SCHEDULED_PROVENANCE_KEY,
+ SOURCE_SCHEDULED,
+ DeliveryRequest,
+ SessionTurnManager,
+ Turn,
+)
+from modules.im import MessageContext
+from storage import message_deliveries as delivery_store
+from storage import messages_service
+from storage import workbench_sessions_service
+from storage.db import create_sqlite_engine
+from storage.models import (
+ agent_runs,
+ agent_sessions,
+ media_objects,
+ message_deliveries,
+ messages,
+ metadata,
+ session_turns,
+)
+
+
+def anyio_backend() -> str:
+ return "asyncio"
+
+
+class _Controller:
+ def __init__(self) -> None:
+ self.command_handler = SimpleNamespace(handle_stop=AsyncMock(return_value=True))
+ self.agent_service = SimpleNamespace(agents={}, _turn_gates={})
+ self.config = SimpleNamespace(language="en")
+ self.statuses: list[tuple[str, str]] = []
+
+ @staticmethod
+ def _session_id_from_context(context: MessageContext) -> str | None:
+ return str((context.platform_specific or {}).get("workbench_session_id") or "") or None
+
+ @staticmethod
+ def resolve_agent_for_context(_context: MessageContext) -> str:
+ return "codex"
+
+ def set_agent_status(self, session_id: str, status: str) -> None:
+ self.statuses.append((session_id, status))
+
+ @staticmethod
+ def _get_session_key(context: MessageContext) -> str:
+ return f"avibe::{(context.platform_specific or {}).get('agent_session_id')}"
+
+
+def _context(session_id: str = "ses_fsm") -> MessageContext:
+ return MessageContext(
+ user_id="user",
+ channel_id=session_id,
+ platform="avibe",
+ platform_specific={
+ "workbench_session_id": session_id,
+ "agent_session_id": session_id,
+ "agent_session_target": {
+ "id": session_id,
+ "agent_backend": "codex",
+ },
+ },
+ )
+
+
+def _seed_session(engine, session_id: str = "ses_fsm") -> None:
+ now = "2026-08-01T00:00:00+00:00"
+ with engine.begin() as conn:
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=None,
+ agent_id=None,
+ agent_name="codex",
+ agent_backend="codex",
+ agent_variant="codex",
+ model=None,
+ reasoning_effort=None,
+ session_anchor=session_id,
+ workdir="/tmp",
+ native_session_id="",
+ title=None,
+ status="active",
+ visibility="foreground",
+ pinned=0,
+ agent_status="idle",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+
+def managers(tmp_path: Path):
+ db_path = tmp_path / "fsm.sqlite"
+ engine_a = create_sqlite_engine(db_path)
+ engine_b = create_sqlite_engine(db_path)
+ metadata.create_all(engine_a)
+ _seed_session(engine_a)
+
+ controller_a = _Controller()
+ controller_b = _Controller()
+ manager_a = SessionTurnManager(controller_a, build_context=_context)
+ manager_b = SessionTurnManager(controller_b, build_context=_context)
+ manager_a._engine = engine_a
+ manager_b._engine = engine_b
+ starts: list[tuple[str, str]] = []
+ starts_lock = threading.Lock()
+
+ async def fake_run(_session_id, _context_value, text, **kwargs):
+ with starts_lock:
+ starts.append((str(kwargs.get("logical_turn_id") or ""), text))
+
+ manager_a._run = fake_run
+ manager_b._run = fake_run
+ yield manager_a, manager_b, engine_a, engine_b, starts
+ engine_a.dispose()
+ engine_b.dispose()
+
+
+async def _activate(
+ manager: SessionTurnManager,
+ *,
+ text: str = "primary",
+ priority: str = "p3",
+) -> tuple[str, MessageContext]:
+ context = _context()
+ admitted = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority=priority, content=text),
+ context=context,
+ )
+ assert admitted.turn_id
+ turn_id = admitted.turn_id
+ context.platform_specific["turn_token"] = turn_id
+ context.platform_specific["agent_runtime_turn_token"] = f"runtime-{turn_id}"
+ manager._active_identity = lambda _backend, _session_id, logical_id: (
+ logical_id,
+ f"native-{logical_id}",
+ )
+ manager.on_native_start(
+ context,
+ backend="codex",
+ runtime_key=f"runtime-key-{turn_id}",
+ runtime_turn_id=f"runtime-{turn_id}",
+ )
+ return turn_id, context
+
+
+def _rows(engine) -> list[dict]:
+ with engine.connect() as conn:
+ return [
+ dict(row)
+ for row in conn.execute(
+ select(message_deliveries).order_by(
+ message_deliveries.c.submitted_at,
+ message_deliveries.c.id,
+ )
+ ).mappings()
+ ]
+
+
+def _row(engine, delivery_id: str) -> dict:
+ with engine.connect() as conn:
+ row = delivery_store.get_delivery(conn, delivery_id)
+ assert row is not None
+ return row
+
+
+def test_fifo_segment_starts_one_turn_and_materializes_one_merged_message(managers) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ active_turn_id, _ = asyncio.run(_activate(manager, text="active"))
+ queued = [
+ asyncio.run(
+ manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content=text,
+ metadata={"_web_push_user_key": user_key},
+ ),
+ context=_context(),
+ )
+ )
+ for text, user_key in (
+ ("queued A", "remote:user-a"),
+ ("queued B", "remote:user-b"),
+ )
+ ]
+
+ assert asyncio.run(manager.terminalize_turn(active_turn_id))
+ queued_starts = [(turn_id, text) for turn_id, text in starts if turn_id != active_turn_id]
+ assert len(queued_starts) == 1
+ turn_id, dispatch_text = queued_starts[0]
+ assert dispatch_text == "queued A\nqueued B"
+
+ claimed = [_row(engine, str(item.delivery_id)) for item in queued]
+ assert [row["turn_id"] for row in claimed] == [turn_id, turn_id]
+ assert [row["turn_role"] for row in claimed] == ["initial", "initial"]
+ assert [row["turn_position"] for row in claimed] == [0, 1]
+ assert [row["state"] for row in claimed] == ["claimed", "claimed"]
+ assert all(row["current_attempt_id"] is None for row in claimed)
+
+ context = _context()
+ context.platform_specific["turn_token"] = turn_id
+ context.platform_specific["agent_runtime_turn_token"] = f"runtime-{turn_id}"
+ manager._active_identity = lambda _backend, _session_id, logical_id: (
+ logical_id,
+ f"native-{logical_id}",
+ )
+ manager.on_native_start(
+ context,
+ backend="codex",
+ runtime_key=f"runtime-key-{turn_id}",
+ runtime_turn_id=f"runtime-{turn_id}",
+ )
+
+ accepted = [_row(engine, str(item.delivery_id)) for item in queued]
+ assert accepted[0]["message_id"] == accepted[1]["message_id"]
+ assert accepted[0]["message_id"] is not None
+ with engine.connect() as conn:
+ stored = conn.execute(
+ select(messages).where(messages.c.id == accepted[0]["message_id"])
+ ).mappings().one()
+ merged_rows = conn.execute(
+ select(messages.c.id).where(
+ messages.c.session_id == "ses_fsm",
+ messages.c.content_text.in_(("queued A", "queued B", "queued A\nqueued B")),
+ )
+ ).all()
+ assert merged_rows == [(accepted[0]["message_id"],)]
+ assert stored["content_text"] == "queued A\nqueued B"
+ assert json.loads(stored["metadata_json"])["_web_push_user_keys"] == [
+ "remote:user-a",
+ "remote:user-b",
+ ]
+ assert stored["created_at"] == accepted[0]["submitted_at"]
+ assert stored["delivered_at"] == accepted[0]["materialized_at"]
+
+
+def test_fifo_segment_does_not_merge_different_message_authors(managers) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ active_turn_id, _ = asyncio.run(_activate(manager, text="active"))
+ queued = [
+ asyncio.run(
+ manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content=text,
+ author_id=author_id,
+ author_name=author_name,
+ ),
+ context=_context(),
+ )
+ )
+ for text, author_id, author_name in (
+ ("from Alice", "remote:alice", "Alice"),
+ ("from Bob", "remote:bob", "Bob"),
+ )
+ ]
+
+ assert asyncio.run(manager.terminalize_turn(active_turn_id))
+ queued_starts = [(turn_id, text) for turn_id, text in starts if turn_id != active_turn_id]
+ assert len(queued_starts) == 1
+ alice_turn_id, dispatch_text = queued_starts[0]
+ assert dispatch_text == "from Alice"
+
+ alice = _row(engine, str(queued[0].delivery_id))
+ bob = _row(engine, str(queued[1].delivery_id))
+ assert alice["turn_id"] == alice_turn_id
+ assert alice["state"] == "claimed"
+ assert bob["turn_id"] is None
+ assert bob["state"] == "queued"
+
+
+def test_persisted_start_attempt_reaches_dispatch_context(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ captured: dict[str, object] = {}
+
+ async def capture_run(_session_id, context, _text, **_kwargs):
+ captured.update(context.platform_specific or {})
+
+ manager._run = capture_run
+ admitted = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="start"),
+ context=_context(),
+ )
+ )
+ assert admitted.turn_id is not None
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, admitted.turn_id)
+ assert turn is not None
+ assert captured["delivery_start_attempt_id"] == turn["start_attempt_id"]
+
+
+def test_dispatch_uses_current_session_route_without_mutating_delivery_provenance(
+ managers,
+) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ captured: dict[str, object] = {}
+ current = _context()
+ current.platform_specific.update(
+ {
+ "vibe_agent_id": "agent-stable",
+ "vibe_agent_name": "_pm-archived",
+ "agent_session_target": {
+ "id": "ses_fsm",
+ "agent_id": "agent-stable",
+ "agent_name": "_pm-archived",
+ "agent_backend": "codex",
+ },
+ }
+ )
+ manager._build_context = lambda _session_id: current
+
+ async def capture_run(_session_id, context, _text, **_kwargs):
+ captured.update(context.platform_specific or {})
+
+ manager._run = capture_run
+ admitted = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content="scheduled",
+ metadata={
+ SCHEDULED_PROVENANCE_KEY: {
+ "message_id": "scheduled:old",
+ "platform_specific": {
+ "vibe_agent_id": "agent-stable",
+ "vibe_agent_name": "pm",
+ "scheduled_target_agent_name": "pm",
+ "agent_session_target": {
+ "agent_id": "agent-stable",
+ "agent_name": "pm",
+ },
+ "task_trigger_kind": "agent_run",
+ "task_definition_id": "run-definition",
+ },
+ }
+ },
+ ),
+ context=_context(),
+ )
+ )
+
+ assert admitted.turn_id is not None
+ assert captured["vibe_agent_id"] == "agent-stable"
+ assert captured["vibe_agent_name"] == "_pm-archived"
+ assert captured["agent_session_target"]["agent_name"] == "_pm-archived"
+ with engine.connect() as conn:
+ delivery = delivery_store.get_delivery(conn, str(admitted.delivery_id))
+ assert delivery is not None
+ provenance = json.loads(delivery["snapshot_json"])["metadata_json"]
+ persisted = json.loads(provenance)[SCHEDULED_PROVENANCE_KEY]["platform_specific"]
+ assert persisted["vibe_agent_name"] == "pm"
+
+
+def test_terminal_evidence_cannot_accept_an_unproven_native_start(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ first = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="unproven"),
+ context=_context(),
+ )
+ )
+ second = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="queued"),
+ context=_context(),
+ )
+ )
+ assert first.turn_id is not None
+ with engine.begin() as conn:
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == "ses_fsm")
+ .values(agent_status="running")
+ )
+
+ terminal = manager._terminalize_durable_turn(
+ first.turn_id,
+ "failed",
+ settled_by="terminal_result",
+ evidence_kind="terminal_result_without_start_receipt",
+ )
+
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, first.turn_id)
+ first_delivery = delivery_store.get_delivery(conn, str(first.delivery_id))
+ second_delivery = delivery_store.get_delivery(conn, str(second.delivery_id))
+ message_ids = list(conn.execute(select(messages.c.id)).scalars())
+ status = conn.execute(
+ select(agent_sessions.c.agent_status).where(
+ agent_sessions.c.id == "ses_fsm"
+ )
+ ).scalar_one()
+ assert terminal["changed"] is False
+ assert terminal["reason"] == "start_acceptance_unproven"
+ assert turn is not None and turn["state"] == "starting"
+ assert first_delivery is not None and first_delivery["state"] == "claimed"
+ assert second_delivery is not None and second_delivery["state"] == "queued"
+ assert message_ids == []
+ assert status == "running"
+
+
+def test_terminal_transaction_claims_fifo_and_projects_running_atomically(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ turn_id, _ = asyncio.run(_activate(manager, text="active"))
+ queued = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="next"),
+ context=_context(),
+ )
+ )
+ with engine.begin() as conn:
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == "ses_fsm")
+ .values(agent_status="running")
+ )
+
+ terminal = manager._terminalize_durable_turn(
+ turn_id,
+ "completed",
+ settled_by="test",
+ evidence_kind="test_terminal",
+ )
+
+ assert terminal["successor_turn_id"]
+ with engine.connect() as conn:
+ successor = delivery_store.active_turn(conn, "ses_fsm")
+ queued_row = delivery_store.get_delivery(conn, str(queued.delivery_id))
+ status = conn.execute(
+ select(agent_sessions.c.agent_status).where(
+ agent_sessions.c.id == "ses_fsm"
+ )
+ ).scalar_one()
+ assert successor is not None
+ assert successor["id"] == terminal["successor_turn_id"]
+ assert queued_row is not None and queued_row["turn_id"] == successor["id"]
+ assert status == "running"
+
+
+def test_post_native_terminal_storage_failure_retains_owner_and_running_projection(
+ managers,
+ monkeypatch,
+) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ turn_id, context = asyncio.run(_activate(manager, text="active"))
+ with engine.begin() as conn:
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == "ses_fsm")
+ .values(agent_status="running")
+ )
+
+ def fail_terminal_write(*_args, **_kwargs):
+ raise RuntimeError("injected terminal storage failure")
+
+ monkeypatch.setattr(manager, "_write_terminal_snapshot", fail_terminal_write)
+ manager.on_terminal_result(context, is_error=False)
+ manager.on_terminal_delivery_complete(context)
+
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ status = conn.execute(
+ select(agent_sessions.c.agent_status).where(
+ agent_sessions.c.id == "ses_fsm"
+ )
+ ).scalar_one()
+ assert turn is not None and turn["state"] == "active"
+ assert status == "running"
+
+
+def test_terminal_output_persistence_failure_does_not_emit_empty_fallback(
+ managers,
+ monkeypatch,
+) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ turn_id, context = asyncio.run(_activate(manager, text="visible native result"))
+ with engine.begin() as conn:
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == "ses_fsm")
+ .values(agent_status="running")
+ )
+ initial = delivery_store.initial_deliveries_for_turn(conn, turn_id)[0]
+
+ manager._run = SessionTurnManager._run.__get__(manager, SessionTurnManager)
+
+ async def terminal_persistence_failure(_controller, dispatch_context, *_args, **_kwargs):
+ set_dispatch_phase(dispatch_context, DISPATCH_PHASE_ATTEMPTING)
+ manager.on_terminal_result(
+ dispatch_context,
+ is_error=False,
+ terminal_evidence={"kind": "native_result"},
+ )
+ raise OSError("terminal output persistence failed")
+
+ async def empty_fallback(_context, _message_type, _text, **_kwargs):
+ manager.on_terminal_result(_context, is_error=True)
+ manager.on_terminal_delivery_complete(_context)
+
+ monkeypatch.setattr(
+ "core.session_turns.dispatch_turn_with_outcome",
+ terminal_persistence_failure,
+ )
+ manager.controller.emit_agent_message = AsyncMock(side_effect=empty_fallback)
+
+ async def run() -> None:
+ await manager._run(
+ "ses_fsm",
+ context,
+ "visible native result",
+ logical_turn_id=turn_id,
+ delivery_id=str(initial["id"]),
+ durable_preallocated=True,
+ )
+ await manager.in_flight["ses_fsm"].task
+
+ asyncio.run(run())
+
+ manager.controller.emit_agent_message.assert_not_awaited()
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ status = conn.execute(
+ select(agent_sessions.c.agent_status).where(
+ agent_sessions.c.id == "ses_fsm"
+ )
+ ).scalar_one()
+ assert turn is not None and turn["state"] == "active"
+ assert status == "running"
+
+
+def test_turn_state_repairs_only_an_exact_ownerless_running_projection(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ with engine.begin() as conn:
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == "ses_fsm")
+ .values(agent_status="running")
+ )
+
+ state = manager.turn_state("ses_fsm")
+
+ assert state["in_flight"] is False
+ assert state["recovered_agent_status"] is True
+ with engine.connect() as conn:
+ assert conn.execute(
+ select(agent_sessions.c.agent_status).where(
+ agent_sessions.c.id == "ses_fsm"
+ )
+ ).scalar_one() == "idle"
+
+
+def test_older_reserved_submission_fences_later_queue_drain(managers) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ with engine.begin() as conn:
+ for delivery_id, state, submitted_at in (
+ ("msg_reserved_first", "reserved", "2026-08-01T00:00:01Z"),
+ ("msg_queued_second", "queued", "2026-08-01T00:00:02Z"),
+ ):
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state=state,
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text=delivery_id,
+ ),
+ dispatch_text=delivery_id,
+ now=submitted_at,
+ )
+
+ assert not asyncio.run(manager.drain_delivery_queue("ses_fsm"))
+ assert starts == []
+ assert _row(engine, "msg_reserved_first")["state"] == "reserved"
+ assert _row(engine, "msg_queued_second")["state"] == "queued"
+
+
+def test_hold_bypass_still_respects_an_unresolved_reservation_fence(managers) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ with engine.begin() as conn:
+ for delivery_id, state, submitted_at in (
+ ("msg_held_backlog", "queued", "2026-08-01T00:00:01Z"),
+ ("msg_reserved_fence", "reserved", "2026-08-01T00:00:02Z"),
+ ):
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state=state,
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text=delivery_id,
+ ),
+ dispatch_text=delivery_id,
+ now=submitted_at,
+ )
+ assert delivery_store.set_queue_hold(conn, "ses_fsm", held=True)
+
+ admitted = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content="new held admission",
+ ),
+ context=_context(),
+ )
+ )
+
+ assert admitted.state == "queued"
+ assert starts == []
+ with engine.connect() as conn:
+ assert delivery_store.active_turn(conn, "ses_fsm") is None
+ assert _row(engine, "msg_reserved_fence")["state"] == "reserved"
+
+
+def test_terminal_between_p1_observation_and_claim_starts_same_submission_once(managers) -> None:
+ """MESSAGE-DELIVERY-009: a stale active observation cannot steer or duplicate."""
+
+ manager, terminal_manager, engine, _engine_b, starts = managers
+ turn_id, _ = asyncio.run(_activate(manager))
+ observed = threading.Event()
+ release = threading.Event()
+ steer_calls: list[str] = []
+
+ def blocked_identity(_backend, _session_id, logical_id):
+ observed.set()
+ assert release.wait(5)
+ return logical_id, f"native-{logical_id}"
+
+ async def unexpected_steer(_backend, request):
+ steer_calls.append(request.text)
+ return steer_result(SteerOutcome.ACCEPTED)
+
+ manager._active_identity = blocked_identity
+ manager._steer = unexpected_steer
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ future = pool.submit(
+ asyncio.run,
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content="follow-up"),
+ context=_context(),
+ ),
+ )
+ assert observed.wait(5)
+ assert asyncio.run(terminal_manager.terminalize_turn(turn_id))
+ release.set()
+ outcome = future.result(timeout=5)
+
+ delivery = _row(engine, str(outcome.delivery_id))
+ assert outcome.state == "claimed"
+ assert delivery["turn_id"] == outcome.turn_id
+ assert steer_calls == []
+ assert [text for started_turn, text in starts if started_turn == outcome.turn_id] == [
+ "follow-up"
+ ]
+ with engine.connect() as conn:
+ assert conn.execute(select(messages.c.id).where(messages.c.id == outcome.delivery_id)).first() is None
+
+
+def test_p1_stale_observed_turn_does_not_retarget_replacement(managers) -> None:
+ manager, replacement_manager, engine, _engine_b, starts = managers
+ old_turn_id, _ = asyncio.run(_activate(manager))
+ observed = threading.Event()
+ release = threading.Event()
+ steer_calls: list[tuple[str, str]] = []
+
+ def blocked_identity(_backend, _session_id, logical_id):
+ observed.set()
+ assert release.wait(5)
+ return logical_id, f"native-{logical_id}"
+
+ async def unexpected_steer(_backend, request):
+ steer_calls.append((request.expected_logical_turn_id, request.text))
+ return steer_result(SteerOutcome.ACCEPTED)
+
+ manager._active_identity = blocked_identity
+ manager._steer = unexpected_steer
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ future = pool.submit(
+ asyncio.run,
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content="stale-p1"),
+ context=_context(),
+ ),
+ )
+ assert observed.wait(5)
+ assert asyncio.run(replacement_manager.terminalize_turn(old_turn_id))
+ replacement_turn_id, _ = asyncio.run(
+ _activate(replacement_manager, text="replacement-owner")
+ )
+ release.set()
+ outcome = future.result(timeout=5)
+
+ delivery = _row(engine, str(outcome.delivery_id))
+ assert outcome.state == "queued"
+ assert delivery["current_target_turn_id"] is None
+ assert steer_calls == []
+ assert [text for turn_id, text in starts if turn_id == replacement_turn_id] == [
+ "replacement-owner"
+ ]
+ assert [text for _, text in starts].count("stale-p1") == 0
+
+
+def test_two_empty_p1_requests_claim_exact_same_head_only(managers) -> None:
+ """MESSAGE-DELIVERY-010: the losing head CAS cannot select head two."""
+
+ first, second, engine, _engine_b, _starts = managers
+ turn_id, _ = asyncio.run(_activate(first))
+ for text in ("head-one", "head-two"):
+ asyncio.run(
+ first.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content=text),
+ context=_context(),
+ )
+ )
+ barrier = threading.Barrier(2)
+ steer_calls: list[str] = []
+
+ def identity(_backend, _session, logical_id):
+ barrier.wait(timeout=5)
+ return logical_id, f"native-{logical_id}"
+
+ async def accepted(_backend, request):
+ steer_calls.append(request.text)
+ return steer_result(SteerOutcome.ACCEPTED)
+
+ for manager in (first, second):
+ manager._active_identity = identity
+ manager._steer = accepted
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ results = [
+ future.result(timeout=5)
+ for future in [
+ pool.submit(
+ asyncio.run,
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content=None),
+ context=_context(),
+ ),
+ )
+ for manager in (first, second)
+ ]
+ ]
+
+ assert sorted(result.state for result in results) == ["accepted", "refused"]
+ assert steer_calls == ["head-one\nhead-two"]
+ queued = [row for row in _rows(engine) if row["state"] == "queued"]
+ assert queued == []
+ assert _row(engine, str(results[0].delivery_id))["turn_id"] in {None, turn_id}
+
+
+def test_empty_p1_refuses_a_requested_delivery_that_is_not_the_head(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ asyncio.run(_activate(manager))
+ queued = [
+ asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content=text),
+ context=_context(),
+ )
+ )
+ for text in ("head-one", "head-two")
+ ]
+ manager._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
+
+ result = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p1",
+ content=None,
+ expected_delivery_id=str(queued[1].delivery_id),
+ ),
+ context=_context(),
+ )
+ )
+
+ assert result.state == "refused"
+ assert result.reason == "stale_head"
+ assert result.delivery_id == queued[1].delivery_id
+ manager._steer.assert_not_awaited()
+ assert [row["state"] for row in _rows(engine) if row["id"] in {
+ queued[0].delivery_id,
+ queued[1].delivery_id,
+ }] == ["queued", "queued"]
+
+
+def test_run_cancellation_retires_every_pre_write_delivery_state(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ turn_id, _ = asyncio.run(_activate(manager))
+ delivery_ids = [delivery_store.new_delivery_id() for _ in range(2)]
+ with engine.begin() as conn:
+ rows = []
+ for index, delivery_id in enumerate(delivery_ids):
+ rows.append(
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p1",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text=f"cancel-{index}",
+ ),
+ dispatch_text=f"cancel-{index}",
+ )
+ )
+ pending = delivery_store.open_pending_steer_batch(
+ conn,
+ deliveries=[rows[1]],
+ turn_id=turn_id,
+ attempt_id=delivery_store.new_attempt_id(),
+ )
+ assert len(pending) == 1
+ assert delivery_store.retire_for_run_cancellation(
+ conn, "ses_fsm", delivery_ids[0]
+ )
+ assert delivery_store.retire_for_run_cancellation(
+ conn, "ses_fsm", delivery_ids[1]
+ )
+
+ with engine.connect() as conn:
+ retired = [delivery_store.get_delivery(conn, delivery_id) for delivery_id in delivery_ids]
+ assert [row["state"] for row in retired] == ["retired", "retired"]
+ assert all(row["current_attempt_id"] is None for row in retired)
+ assert all(row["current_target_turn_id"] is None for row in retired)
+
+
+async def test_empty_p1_accepted_agent_run_joins_active_turn_ownership(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ turn_id, active_context = await _activate(manager)
+ holder = asyncio.Event()
+ holder_task = asyncio.create_task(holder.wait())
+ manager.in_flight["ses_fsm"] = Turn(
+ task=holder_task,
+ context=active_context,
+ logical_turn_id=turn_id,
+ )
+ sink_done = asyncio.Event()
+ manager.register_turn_sink(
+ "avibe::ses_fsm",
+ on_chunk=AsyncMock(),
+ done_event=sink_done,
+ turn_token=turn_id,
+ context=active_context,
+ )
+ run_id = "run-steered-fifo-head"
+ now = "2026-08-01T00: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",
+ created_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+
+ queued = await manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content="queued Agent Run prompt",
+ source="harness",
+ author="harness",
+ message_type="harness",
+ native_message_id=f"agent_run:{run_id}",
+ metadata={
+ "scheduled_provenance": {
+ "task_execution_id": run_id,
+ "platform_specific": {
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": run_id,
+ },
+ }
+ },
+ ),
+ context=_context(),
+ )
+ assert queued.state == "queued"
+ with engine.begin() as conn:
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(delivery_id=queued.delivery_id)
+ )
+ manager._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
+
+ accepted = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content=None),
+ context=_context(),
+ )
+
+ assert accepted.state == "accepted"
+ with engine.connect() as conn:
+ run = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id)).mappings().one()
+ assert run["status"] == "running"
+ assert run["delivery_id"] == queued.delivery_id
+ assert active_context.platform_specific["accepted_agent_run_ids"] == [run_id]
+ assert manager.get_turn_sink("avibe::ses_fsm")["accepted_agent_run_ids"] == [run_id]
+
+ manager.in_flight.pop("ses_fsm", None)
+ manager.pop_turn_sink("avibe::ses_fsm", sink_done)
+ holder_task.cancel()
+ await asyncio.gather(holder_task, return_exceptions=True)
+
+
+def test_empty_p1_refuses_when_exact_turn_changes_before_head_claim(managers) -> None:
+ manager, replacement_manager, engine, _engine_b, _starts = managers
+ old_turn_id, _ = asyncio.run(_activate(manager))
+ queued = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="exact-head"),
+ context=_context(),
+ )
+ )
+ observed = threading.Event()
+ release = threading.Event()
+ steer_calls: list[str] = []
+
+ def blocked_identity(_backend, _session_id, logical_id):
+ observed.set()
+ assert release.wait(5)
+ return logical_id, f"native-{logical_id}"
+
+ async def unexpected_steer(_backend, request):
+ steer_calls.append(request.text)
+ return steer_result(SteerOutcome.ACCEPTED)
+
+ manager._active_identity = blocked_identity
+ manager._steer = unexpected_steer
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ future = pool.submit(
+ asyncio.run,
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content=None),
+ context=_context(),
+ ),
+ )
+ assert observed.wait(5)
+ assert asyncio.run(replacement_manager.terminalize_turn(old_turn_id))
+ asyncio.run(
+ _activate(
+ replacement_manager,
+ text="replacement-owner",
+ priority="p1",
+ )
+ )
+ release.set()
+ outcome = future.result(timeout=5)
+
+ assert outcome.state == "refused"
+ assert outcome.reason == "stale_head"
+ assert _row(engine, str(queued.delivery_id))["state"] == "accepted"
+ assert steer_calls == []
+
+
+def test_p1_steer_uses_persisted_dispatch_text(managers, monkeypatch) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ turn_id, _ = asyncio.run(_activate(manager))
+ delivery_id = delivery_store.new_delivery_id()
+ with engine.begin() as conn:
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p1",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="display content",
+ ),
+ dispatch_text="canonical agent prompt",
+ )
+ manager._active_identity = lambda _b, _s, logical: (logical, f"native-{logical}")
+ steer_calls: list[str] = []
+
+ async def accepted(_backend, request):
+ steer_calls.append(request.text)
+ return steer_result(SteerOutcome.ACCEPTED)
+
+ published: list[tuple[str, dict]] = []
+ monkeypatch.setattr(
+ "core.inbox_events.bus.publish",
+ lambda event, payload: published.append((event, payload)),
+ )
+ manager._steer = accepted
+ result = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p1",
+ content="noncanonical retry payload",
+ delivery_id=delivery_id,
+ ),
+ context=_context(),
+ )
+ )
+
+ assert result.state == "accepted"
+ assert steer_calls == ["canonical agent prompt"]
+ row = _row(engine, delivery_id)
+ assert row["turn_id"] == turn_id
+ assert ("queue.updated", {"session_id": "ses_fsm"}) in published
+ with engine.connect() as conn:
+ materialized = conn.execute(
+ select(messages.c.content_text).where(messages.c.id == delivery_id)
+ ).scalar_one()
+ assert materialized == "display content"
+
+
+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."""
+
+ first, restarted, engine, _engine_b, _starts = managers
+ turn_id, _ = asyncio.run(_activate(first))
+ first._active_identity = lambda _b, _s, logical: (logical, f"native-{logical}")
+ calls = 0
+
+ async def accepted(_backend, _request):
+ nonlocal calls
+ 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")
+
+ monkeypatch.setattr(delivery_store, "materialize_steer_acceptance", lose_receipt)
+ outcome = asyncio.run(
+ first.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content="accepted once"),
+ 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):
+ 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
+ asyncio.run(restarted.recover_durable_delivery_state())
+
+ row = _row(engine, str(outcome.delivery_id))
+ assert calls == 1
+ assert row["state"] == "accepted"
+ assert row["turn_id"] == turn_id
+ assert row["current_attempt_id"] is None
+ with engine.connect() as conn:
+ message = conn.execute(
+ select(messages).where(messages.c.id == row["message_id"])
+ ).mappings().one()
+ assert message["content_text"] == "accepted once"
+
+
+def test_missing_restart_evidence_keeps_unknown_without_resteer(
+ managers,
+ monkeypatch,
+) -> None:
+ first, restarted, engine, _engine_b, _starts = managers
+ turn_id, _ = asyncio.run(_activate(first))
+ first._active_identity = lambda _b, _s, logical: (logical, f"native-{logical}")
+ steer_calls = 0
+ reconciliation_calls = 0
+
+ async def accepted(_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")
+
+ monkeypatch.setattr(delivery_store, "materialize_steer_acceptance", lose_receipt)
+ 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):
+ nonlocal reconciliation_calls
+ reconciliation_calls += 1
+ assert request.expected_logical_turn_id == turn_id
+ return steer_result(SteerOutcome.UNKNOWN, reason="evidence_unavailable")
+
+ restarted._reconcile_steer_attempt = reconcile
+ asyncio.run(restarted.recover_durable_delivery_state())
+
+ row = _row(engine, str(outcome.delivery_id))
+ assert steer_calls == 1
+ assert reconciliation_calls == 1
+ assert row["state"] == "reconciling_steer"
+ assert row["current_target_turn_id"] == turn_id
+ assert row["current_receipt_outcome"] == "unknown"
+ with engine.connect() as conn:
+ assert conn.execute(select(messages.c.id).where(messages.c.id == row["id"])).first() is None
+
+
+def test_definitive_refusal_racing_idle_drain_starts_same_delivery_once(managers) -> None:
+ """MESSAGE-DELIVERY-012: refusal fallback and drain share one writer claim."""
+
+ manager, drainer, engine, _engine_b, starts = managers
+ turn_id, _ = asyncio.run(_activate(manager))
+ manager._active_identity = lambda _b, _s, logical: (logical, f"native-{logical}")
+ adapter_called = threading.Event()
+ release_adapter = threading.Event()
+
+ async def refused(_backend, _request):
+ adapter_called.set()
+ await asyncio.to_thread(release_adapter.wait, 5)
+ return steer_result(SteerOutcome.REFUSED, reason="not_steerable")
+
+ manager._steer = refused
+
+ async def race():
+ task = asyncio.create_task(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content="fallback"),
+ context=_context(),
+ )
+ )
+ assert await asyncio.to_thread(adapter_called.wait, 5)
+ assert await drainer.terminalize_turn(turn_id)
+ concurrent_drain = asyncio.create_task(drainer.drain_delivery_queue("ses_fsm"))
+ release_adapter.set()
+ return await task, await concurrent_drain
+
+ outcome, _ = asyncio.run(race())
+ row = _row(engine, str(outcome.delivery_id))
+ assert row["state"] == "claimed"
+ matching_starts = [item for item in starts if item[1] == "fallback"]
+ assert len(matching_starts) == 1
+ assert matching_starts[0][0] == row["turn_id"]
+
+
+def test_definitive_p1_refusal_requeues_behind_existing_fifo_head(managers) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ turn_id, _ = asyncio.run(_activate(manager))
+ older = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="older backlog"),
+ context=_context(),
+ )
+ )
+ with engine.begin() as conn:
+ assert delivery_store.set_queue_hold(conn, "ses_fsm", held=True)
+ entered = threading.Event()
+ release = threading.Event()
+
+ async def refused(_backend, _request):
+ entered.set()
+ await asyncio.to_thread(release.wait, 5)
+ return steer_result(SteerOutcome.REFUSED, reason="not_steerable")
+
+ manager._steer = refused
+
+ async def race():
+ pending = asyncio.create_task(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content="fallback"),
+ context=_context(),
+ )
+ )
+ assert await asyncio.to_thread(entered.wait, 5)
+ assert await manager.terminalize_turn(turn_id)
+ with engine.begin() as conn:
+ assert delivery_store.set_queue_hold(conn, "ses_fsm", held=False)
+ release.set()
+ return await pending
+
+ fallback = asyncio.run(race())
+ older_row = _row(engine, str(older.delivery_id))
+ fallback_row = _row(engine, str(fallback.delivery_id))
+ assert older_row["state"] == "claimed"
+ assert fallback_row["state"] == "claimed"
+ assert fallback_row["turn_id"] == older_row["turn_id"]
+ assert [text for _turn, text in starts].count("older backlog\nfallback") == 1
+
+
+def test_p0_successor_persistence_failure_never_calls_stop(managers, monkeypatch) -> None:
+ """MESSAGE-DELIVERY-013: successor Delivery and Turn commit before Stop."""
+
+ manager, _other, engine, _engine_b, _starts = managers
+
+ async def run() -> None:
+ turn_id, context = await _activate(manager)
+ holder = asyncio.create_task(asyncio.Event().wait())
+ manager.in_flight["ses_fsm"] = Turn(
+ task=holder,
+ context=context,
+ logical_turn_id=turn_id,
+ )
+ original = delivery_store.insert_turn
+
+ def fail_waiting(conn, **kwargs):
+ if kwargs.get("state") == "waiting":
+ raise OSError("simulated successor persistence failure")
+ return original(conn, **kwargs)
+
+ monkeypatch.setattr(delivery_store, "insert_turn", fail_waiting)
+ try:
+ with pytest.raises(OSError, match="successor persistence"):
+ await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p0", content="replacement"),
+ context=_context(),
+ )
+ finally:
+ holder.cancel()
+ await asyncio.gather(holder, return_exceptions=True)
+
+ asyncio.run(run())
+ assert manager.controller.command_handler.handle_stop.await_count == 0
+ assert all(row["dispatch_text"] != "replacement" for row in _rows(engine))
+
+
+def test_definitive_p0_refusal_restores_preexisting_queue_hold(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+
+ async def run() -> None:
+ turn_id, context = await _activate(manager)
+ with engine.begin() as conn:
+ assert delivery_store.set_queue_hold(conn, "ses_fsm", held=True)
+ holder = asyncio.create_task(asyncio.Event().wait())
+ manager.in_flight["ses_fsm"] = Turn(
+ task=holder,
+ context=context,
+ logical_turn_id=turn_id,
+ )
+
+ async def refused(stop_context):
+ stop_context.platform_specific["stop_failure_reason"] = "refused"
+ return False
+
+ manager.controller.command_handler.handle_stop = AsyncMock(side_effect=refused)
+ try:
+ result = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p0", content=None),
+ context=context,
+ )
+ finally:
+ holder.cancel()
+ await asyncio.gather(holder, return_exceptions=True)
+ assert result.state == "refused"
+
+ asyncio.run(run())
+ with engine.connect() as conn:
+ assert delivery_store.queue_is_held(conn, "ses_fsm") is True
+
+
+def test_empty_p0_establishes_durable_hold_before_stop(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+
+ async def run() -> None:
+ turn_id, context = await _activate(manager)
+ holder = asyncio.create_task(asyncio.Event().wait())
+ manager.in_flight["ses_fsm"] = Turn(
+ task=holder,
+ context=context,
+ logical_turn_id=turn_id,
+ )
+ try:
+ result = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p0", content=None),
+ context=context,
+ )
+ assert result.state == "waiting_terminal"
+ with engine.connect() as conn:
+ assert delivery_store.queue_is_held(conn, "ses_fsm") is True
+ finally:
+ holder.cancel()
+ await asyncio.gather(holder, return_exceptions=True)
+
+ asyncio.run(run())
+
+
+def test_empty_p0_preserves_hold_when_observed_turn_terminalizes_before_claim(
+ managers,
+ monkeypatch,
+) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ turn_id, _context_value = asyncio.run(_activate(manager))
+ queued = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="backlog"),
+ context=_context(),
+ )
+ )
+ original_deliver = manager.deliver
+
+ async def terminal_race(request, *, context=None):
+ if request.priority == "p0" and request.content is None:
+ terminal = manager._terminalize_durable_turn(
+ turn_id,
+ "failed",
+ settled_by="terminal_result",
+ evidence_kind="terminal_before_stop_claim",
+ )
+ assert terminal["changed"] is True
+ return await original_deliver(request, context=context)
+
+ monkeypatch.setattr(manager, "deliver", terminal_race)
+ result = asyncio.run(manager.cancel("ses_fsm"))
+
+ assert result["ok"] is True
+ assert result["status"] == "stale_released"
+ with engine.connect() as conn:
+ assert delivery_store.queue_is_held(conn, "ses_fsm") is True
+ asyncio.run(manager._resume_post_terminal("ses_fsm"))
+ assert _row(engine, str(queued.delivery_id))["state"] == "queued"
+ assert [text for _turn, text in starts].count("backlog") == 0
+
+
+def test_content_p0_preserves_open_hold_and_claims_successor_once(managers) -> None:
+ """MESSAGE-DELIVERY-014: control, terminal, and restart converge once."""
+
+ manager, restarted, engine, _engine_b, starts = managers
+
+ async def run() -> tuple[str, str, str]:
+ turn_id, context = await _activate(manager)
+ holder = asyncio.create_task(asyncio.Event().wait())
+ manager.in_flight["ses_fsm"] = Turn(
+ task=holder,
+ context=context,
+ logical_turn_id=turn_id,
+ )
+ admitted = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p0", content="successor"),
+ context=_context(),
+ )
+ assert admitted.state == "waiting_terminal"
+ with engine.connect() as conn:
+ old = delivery_store.get_turn(conn, turn_id)
+ successor_id = str(old["control_successor_turn_id"])
+ assert successor_id not in [started for started, _ in starts]
+ await restarted.recover_durable_delivery_state()
+ terminal_resume = restarted.on_native_terminal(context, outcome="completed")
+ assert terminal_resume is not None
+ await terminal_resume
+ holder.cancel()
+ await asyncio.gather(holder, return_exceptions=True)
+ return successor_id, str(admitted.delivery_id)
+
+ successor_id, delivery_id = asyncio.run(run())
+ assert [turn for turn, text in starts if text == "successor"] == [successor_id]
+ assert manager.controller.command_handler.handle_stop.await_count == 1
+ delivery = _row(engine, delivery_id)
+ assert delivery["state"] == "claimed"
+ with engine.connect() as conn:
+ assert delivery_store.queue_is_held(conn, "ses_fsm") is False
+
+
+def test_empty_p0_supersedes_in_flight_content_replacement(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+
+ async def run() -> tuple[str, str, str, str]:
+ turn_id, context = await _activate(manager)
+ holder = asyncio.create_task(asyncio.Event().wait())
+ manager.in_flight["ses_fsm"] = Turn(
+ task=holder,
+ context=context,
+ logical_turn_id=turn_id,
+ )
+ entered = asyncio.Event()
+ release = asyncio.Event()
+
+ async def delayed_stop(_stop_context):
+ entered.set()
+ await release.wait()
+ return True
+
+ manager.controller.command_handler.handle_stop = AsyncMock(side_effect=delayed_stop)
+ replacement_task = asyncio.create_task(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p0", content="replacement"),
+ context=_context(),
+ )
+ )
+ await entered.wait()
+ with engine.connect() as conn:
+ replacement_control = delivery_store.get_turn(conn, turn_id)
+ assert replacement_control is not None
+ successor_turn_id = str(replacement_control["control_successor_turn_id"] or "")
+ replacement_delivery_id = str(
+ replacement_control["control_successor_delivery_id"] or ""
+ )
+ run_id = "run-replacement-superseded-by-stop"
+ now = "2026-08-01T00: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=replacement_delivery_id,
+ created_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+ stopped = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p0", content=None),
+ context=context,
+ )
+ release.set()
+ await replacement_task
+ holder.cancel()
+ await asyncio.gather(holder, return_exceptions=True)
+ assert stopped.reason == "joined_existing_interrupt"
+ return turn_id, successor_turn_id, replacement_delivery_id, run_id
+
+ turn_id, successor_turn_id, replacement_delivery_id, run_id = asyncio.run(run())
+ with engine.connect() as conn:
+ target = delivery_store.get_turn(conn, turn_id)
+ successor = delivery_store.get_turn(conn, successor_turn_id)
+ run_row = conn.execute(
+ select(agent_runs.c.status, agent_runs.c.cancel_requested).where(
+ agent_runs.c.id == run_id
+ )
+ ).one()
+ assert delivery_store.queue_is_held(conn, "ses_fsm") is True
+ assert target is not None and target["control_mode"] == "stop_only"
+ assert target["control_successor_turn_id"] is None
+ assert target["control_successor_delivery_id"] is None
+ assert successor is not None and successor["terminal_outcome"] == "not_written"
+ assert _row(engine, replacement_delivery_id)["state"] == "retired"
+ assert run_row == ("canceled", 1)
+ assert manager.controller.command_handler.handle_stop.await_count == 1
+
+
+def test_recovery_consumes_persisted_not_active_stop_receipt(managers) -> None:
+ manager, restarted, engine, _engine_b, starts = managers
+
+ async def run() -> tuple[str, str]:
+ turn_id, context = await _activate(manager)
+ holder = asyncio.create_task(asyncio.Event().wait())
+ manager.in_flight["ses_fsm"] = Turn(
+ task=holder,
+ context=context,
+ logical_turn_id=turn_id,
+ )
+
+ async def not_active(stop_context):
+ stop_context.platform_specific["stop_failure_reason"] = "not_active"
+ return False
+
+ manager.controller.command_handler.handle_stop = AsyncMock(
+ side_effect=not_active
+ )
+ original_terminalize = manager._terminalize_durable_turn
+
+ def crash_after_receipt(*args, **kwargs):
+ if kwargs.get("evidence_kind") == "stop_not_active":
+ raise OSError("crash after Stop receipt commit")
+ return original_terminalize(*args, **kwargs)
+
+ manager._terminalize_durable_turn = crash_after_receipt
+ with pytest.raises(OSError, match="Stop receipt"):
+ await manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p0",
+ content="restart successor",
+ ),
+ context=_context(),
+ )
+ with engine.connect() as conn:
+ old = delivery_store.get_turn(conn, turn_id)
+ assert old is not None
+ successor_turn_id = str(old["control_successor_turn_id"])
+ assert old["control_receipt_outcome"] == "not_active"
+
+ restarted._active_identity = lambda *_args: None
+ await restarted.recover_durable_delivery_state()
+ holder.cancel()
+ await asyncio.gather(holder, return_exceptions=True)
+ return turn_id, successor_turn_id
+
+ old_turn_id, successor_turn_id = asyncio.run(run())
+ with engine.connect() as conn:
+ old = delivery_store.get_turn(conn, old_turn_id)
+ successor = delivery_store.get_turn(conn, successor_turn_id)
+ assert old is not None and old["state"] == "terminal"
+ assert old["terminal_outcome"] == "canceled"
+ assert successor is not None and successor["state"] == "starting"
+ assert [turn for turn, text in starts if text == "restart successor"] == [
+ successor_turn_id
+ ]
+
+
+def test_two_idle_p3_admissions_leave_one_fifo_loser(managers) -> None:
+ """MESSAGE-DELIVERY-015: two connections cannot own two live Turns."""
+
+ first, second, engine, _engine_b, starts = managers
+ barrier = threading.Barrier(2)
+ original_a = first._delivery_backend
+ original_b = second._delivery_backend
+
+ def synchronized(original):
+ def wrapped(session_id, context):
+ barrier.wait(timeout=5)
+ return original(session_id, context)
+
+ return wrapped
+
+ first._delivery_backend = synchronized(original_a)
+ second._delivery_backend = synchronized(original_b)
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ outcomes = [
+ future.result(timeout=5)
+ for future in [
+ pool.submit(
+ asyncio.run,
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content=text),
+ context=_context(),
+ ),
+ )
+ for manager, text in ((first, "first"), (second, "second"))
+ ]
+ ]
+
+ assert sorted(result.state for result in outcomes) == ["claimed", "queued"]
+ assert len(starts) == 1
+ with engine.connect() as conn:
+ live = conn.execute(
+ select(session_turns.c.id).where(session_turns.c.state.in_(("starting", "active")))
+ ).all()
+ assert len(live) == 1
+
+
+def test_late_t1_terminal_cannot_clear_active_t2(managers) -> None:
+ """MESSAGE-DELIVERY-016: terminal identity is exact and versioned."""
+
+ manager, other, engine, _engine_b, _starts = managers
+ t1, context1 = asyncio.run(_activate(manager, text="t1"))
+ asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="t2"),
+ context=_context(),
+ )
+ )
+ assert asyncio.run(other.terminalize_turn(t1))
+ assert asyncio.run(other.drain_delivery_queue("ses_fsm")) is False
+ with engine.connect() as conn:
+ t2 = delivery_store.active_turn(conn, "ses_fsm")
+ assert t2 is not None and t2["id"] != t1
+ context2 = _context()
+ context2.platform_specific.update(
+ {
+ "turn_token": t2["id"],
+ "agent_runtime_turn_token": f"runtime-{t2['id']}",
+ }
+ )
+ other._active_identity = lambda _b, _s, logical: (logical, f"native-{logical}")
+ other.on_native_start(
+ context2,
+ backend="codex",
+ runtime_key=f"key-{t2['id']}",
+ runtime_turn_id=f"runtime-{t2['id']}",
+ )
+ assert other.on_native_terminal(context1, outcome="completed") is None
+ with engine.connect() as conn:
+ still_active = delivery_store.active_turn(conn, "ses_fsm")
+ assert still_active is not None and still_active["id"] == t2["id"]
+
+
+def test_start_write_ambiguity_replays_once_after_restart(managers) -> None:
+ """MESSAGE-DELIVERY-017: availability wins after an unresolvable start."""
+
+ first, restarted, engine, _engine_b, starts = managers
+
+ async def ambiguous(_session_id, _context_value, text, **kwargs):
+ starts.append((str(kwargs.get("logical_turn_id") or ""), text))
+ raise OSError("connection lost after native write")
+
+ first._run = ambiguous
+ outcome = asyncio.run(
+ first.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="once"),
+ context=_context(),
+ )
+ )
+ restarted._active_identity = lambda *_args: None
+ asyncio.run(restarted.recover_durable_delivery_state())
+
+ row = _row(engine, str(outcome.delivery_id))
+ assert row["state"] == "claimed"
+ assert len(starts) == 2
+ assert starts[0][1] == "once"
+ assert starts[1][1].endswith("once")
+ assert "may have been delivered before restart" in starts[1][1]
+ with engine.connect() as conn:
+ assert conn.execute(select(messages.c.id)).all() == []
+ turns = conn.execute(
+ select(session_turns)
+ .where(session_turns.c.initial_delivery_id == outcome.delivery_id)
+ .order_by(session_turns.c.created_at, session_turns.c.id)
+ ).mappings().all()
+ assert len(turns) == 2
+ assert turns[0]["state"] == "terminal"
+ assert turns[0]["terminal_outcome"] == "failed"
+ assert turns[0]["start_receipt_outcome"] == "unknown"
+ assert turns[1]["state"] == "starting"
+
+
+def test_accepted_codex_turn_without_runtime_settles_and_releases_queue(managers) -> None:
+ first, restarted, engine, _engine_b, starts = managers
+ turn_id, _context_value = asyncio.run(_activate(first, text="accepted before restart"))
+ queued = asyncio.run(
+ first.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content="continue after restart",
+ ),
+ context=_context(),
+ )
+ )
+ starts.clear()
+ restarted._active_identity = lambda *_args: None
+
+ asyncio.run(
+ restarted.recover_durable_delivery_state(
+ "ses_fsm",
+ service_restart=True,
+ )
+ )
+
+ with engine.connect() as conn:
+ settled = delivery_store.get_turn(conn, turn_id)
+ accepted = delivery_store.delivery_for_turn(conn, turn_id)
+ assert settled is not None and settled["state"] == "terminal"
+ assert settled["terminal_outcome"] == "failed"
+ assert settled["terminal_evidence_kind"] == "restart_runtime_missing"
+ assert accepted is not None and accepted["state"] == "accepted"
+ assert _row(engine, str(queued.delivery_id))["state"] == "claimed"
+ assert [text for _started_turn, text in starts] == ["continue after restart"]
+
+
+def test_accepted_opencode_turn_without_restored_identity_stays_live(managers) -> None:
+ first, restarted, engine, _engine_b, starts = managers
+ turn_id, _context_value = asyncio.run(_activate(first, text="restorable runtime"))
+ queued = asyncio.run(
+ first.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="wait"),
+ context=_context(),
+ )
+ )
+ with engine.begin() as conn:
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == "ses_fsm")
+ .values(agent_backend="opencode", agent_name="opencode")
+ )
+ conn.execute(
+ update(session_turns)
+ .where(session_turns.c.id == turn_id)
+ .values(backend="opencode")
+ )
+ starts.clear()
+ restarted._active_identity = lambda *_args: None
+
+ asyncio.run(
+ restarted.recover_durable_delivery_state(
+ "ses_fsm",
+ service_restart=True,
+ )
+ )
+
+ with engine.connect() as conn:
+ retained = delivery_store.get_turn(conn, turn_id)
+ assert retained is not None and retained["state"] == "active"
+ assert _row(engine, str(queued.delivery_id))["state"] == "queued"
+ assert starts == []
+
+
+def test_second_unknown_start_retires_delivery_and_unblocks_fifo(managers) -> None:
+ first, restarted, engine, _engine_b, starts = managers
+ settlements: list[tuple[list[str], str]] = []
+ settlement_service = SimpleNamespace(
+ settle_agent_runs_without_result=lambda run_ids, *, settled_by: settlements.append(
+ (list(run_ids), settled_by)
+ )
+ )
+ first.controller.scheduled_task_service = settlement_service
+ restarted.controller.scheduled_task_service = settlement_service
+
+ async def ambiguous(_session_id, _context_value, text, **kwargs):
+ starts.append((str(kwargs.get("logical_turn_id") or ""), text))
+ raise OSError("connection lost after native write")
+
+ first._run = ambiguous
+ restarted._run = ambiguous
+ outcome = asyncio.run(
+ first.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="retry once"),
+ context=_context(),
+ )
+ )
+ run_id = "run-unknown-start-retry"
+ now = "2026-08-01T00:00:00Z"
+ with engine.begin() as conn:
+ conn.execute(
+ agent_runs.insert().values(
+ id=run_id,
+ definition_id=None,
+ run_type="agent",
+ status="running",
+ cancel_requested=0,
+ session_id="ses_fsm",
+ delivery_id=str(outcome.delivery_id),
+ created_at=now,
+ started_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+ restarted._active_identity = lambda *_args: None
+ asyncio.run(restarted.recover_durable_delivery_state())
+ assert len(starts) == 2
+
+ with engine.begin() as conn:
+ following = delivery_store.enqueue_queued(
+ conn,
+ scope_id=None,
+ session_id="ses_fsm",
+ text="continue queue",
+ )
+
+ async def succeeds(_session_id, _context_value, text, **kwargs):
+ starts.append((str(kwargs.get("logical_turn_id") or ""), text))
+
+ first._run = succeeds
+ first._active_identity = lambda *_args: None
+ asyncio.run(first.recover_durable_delivery_state())
+
+ retired = _row(engine, str(outcome.delivery_id))
+ assert retired["state"] == "retired"
+ history = json.loads(retired["delivery_history_json"])["events"]
+ assert [
+ event["outcome"]
+ for event in history
+ if event["kind"] == "start" and event["outcome"].startswith("restart_")
+ ] == [
+ "restart_replayed",
+ "restart_retry_exhausted",
+ ]
+ assert _row(engine, str(following["id"]))["state"] == "claimed"
+ assert starts[-1][1] == "continue queue"
+ assert settlements == [([run_id], "no_terminal_result")]
+
+
+def test_exact_missing_start_attempt_requeues_only_its_own_delivery(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ admitted = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="retry exact"),
+ context=_context(),
+ )
+ )
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, str(admitted.turn_id))
+ assert turn is not None
+ attempt_id = str(turn["start_attempt_id"])
+
+ assert not manager.reconcile_start_attempt_not_written(
+ str(admitted.turn_id),
+ "different-attempt",
+ backend="opencode",
+ )
+ with engine.connect() as conn:
+ still_starting = delivery_store.get_turn(conn, str(admitted.turn_id))
+ assert still_starting is not None and still_starting["state"] == "starting"
+
+ assert manager.reconcile_start_attempt_not_written(
+ str(admitted.turn_id),
+ attempt_id,
+ backend="opencode",
+ )
+ assert _row(engine, str(admitted.delivery_id))["state"] == "queued"
+ with engine.connect() as conn:
+ terminal = delivery_store.get_turn(conn, str(admitted.turn_id))
+ assert terminal is not None
+ assert terminal["terminal_outcome"] == "not_written"
+
+
+def test_pre_dispatch_hydration_failure_is_definitively_recoverable(managers) -> None:
+ first, restarted, engine, _engine_b, starts = managers
+
+ def fail_before_dispatch(*_args, **_kwargs):
+ raise OSError("attachment lookup failed before dispatch")
+
+ first._hydrate_delivery_context = fail_before_dispatch
+ admitted = asyncio.run(
+ first.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="retry safely"),
+ context=_context(),
+ )
+ )
+
+ row = _row(engine, str(admitted.delivery_id))
+ assert row["state"] == "queued"
+ with engine.connect() as conn:
+ failed_turn = delivery_store.get_turn(conn, str(admitted.turn_id))
+ assert failed_turn is not None
+ assert failed_turn["terminal_outcome"] == "not_written"
+ assert starts == []
+
+ asyncio.run(restarted.recover_durable_delivery_state("ses_fsm"))
+
+ assert [text for _turn_id, text in starts] == ["retry safely"]
+ assert _row(engine, str(admitted.delivery_id))["state"] == "claimed"
+
+
+def test_submit_reports_the_requeued_state_after_prewrite_failure(
+ managers,
+ monkeypatch,
+) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ published: list[tuple[str, dict]] = []
+
+ def fail_before_dispatch(*_args, **_kwargs):
+ raise OSError("attachment lookup failed before dispatch")
+
+ manager._hydrate_delivery_context = fail_before_dispatch
+ monkeypatch.setattr(
+ "core.inbox_events.bus.publish",
+ lambda event, payload: published.append((event, payload)),
+ )
+
+ result = asyncio.run(
+ manager.submit(
+ "ses_fsm",
+ _context(),
+ "retry exact scheduled work",
+ source=SOURCE_SCHEDULED,
+ )
+ )
+
+ assert result.route == "enqueued"
+ assert result.queue_persisted is True
+ assert starts == []
+ rows = _rows(engine)
+ assert len(rows) == 1
+ assert rows[0]["state"] == "queued"
+ assert ("queue.updated", {"session_id": "ses_fsm"}) in published
+
+
+def test_terminal_agent_run_wins_after_start_claim_before_native_dispatch(managers) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ delivery_id = delivery_store.new_delivery_id()
+ surviving_delivery_id = delivery_store.new_delivery_id()
+ turn_id = delivery_store.new_turn_id()
+ attempt_id = delivery_store.new_attempt_id()
+ run_id = "run-canceled-after-start-claim"
+ now = "2026-08-01T00:00:00Z"
+ with engine.begin() as conn:
+ conn.execute(
+ agent_runs.insert().values(
+ id=run_id,
+ definition_id=None,
+ run_type="agent",
+ status="running",
+ cancel_requested=1,
+ session_id="ses_fsm",
+ created_at=now,
+ completed_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+ delivery = delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="must not run",
+ native_message_id=f"agent_run:{run_id}",
+ ),
+ dispatch_text="must not run",
+ )
+ surviving = delivery_store.insert_delivery(
+ conn,
+ delivery_id=surviving_delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="surviving batch input",
+ ),
+ dispatch_text="surviving batch input",
+ )
+ delivery_store.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id="ses_fsm",
+ backend="codex",
+ deliveries=[delivery, surviving],
+ dispatch_text="must not run\n\nsurviving batch input",
+ attempt_id=attempt_id,
+ )
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(delivery_id=delivery_id)
+ )
+
+ assert asyncio.run(manager._start_persisted_turn(turn_id, context=_context())) is False
+ assert [text for _turn_id, text in starts] == ["surviving batch input"]
+ assert _row(engine, delivery_id)["state"] == "retired"
+ surviving_after = _row(engine, surviving_delivery_id)
+ assert surviving_after["state"] == "claimed"
+ assert surviving_after["turn_id"] != turn_id
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ assert turn is not None and turn["terminal_outcome"] == "not_written"
+
+
+def test_terminal_run_wins_after_turn_launch_before_runner_dispatch(
+ managers,
+ monkeypatch,
+) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ manager._run = SessionTurnManager._run.__get__(manager, SessionTurnManager)
+ native_dispatch = AsyncMock()
+ monkeypatch.setattr("core.session_turns.dispatch_turn_with_outcome", native_dispatch)
+ delivery_id = delivery_store.new_delivery_id()
+ turn_id = delivery_store.new_turn_id()
+ run_id = "run-failed-after-turn-launch"
+ now = "2026-08-01T00:00:00Z"
+ with engine.begin() as conn:
+ delivery = delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="must still not run",
+ ),
+ dispatch_text="must still not run",
+ )
+ delivery_store.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id="ses_fsm",
+ backend="codex",
+ deliveries=[delivery],
+ dispatch_text="must still not run",
+ )
+ conn.execute(
+ agent_runs.insert().values(
+ id=run_id,
+ run_type="task_run",
+ status="failed",
+ session_id="ses_fsm",
+ delivery_id=delivery_id,
+ cancel_requested=0,
+ error="task result was not recorded",
+ created_at=now,
+ completed_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+
+ async def run() -> None:
+ await manager._run(
+ "ses_fsm",
+ _context(),
+ "must still not run",
+ source="scheduled",
+ logical_turn_id=turn_id,
+ delivery_id=delivery_id,
+ durable_preallocated=True,
+ )
+ await manager.in_flight["ses_fsm"].task
+
+ asyncio.run(run())
+
+ native_dispatch.assert_not_awaited()
+ assert _row(engine, delivery_id)["state"] == "retired"
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ assert turn is not None
+ assert turn["terminal_outcome"] == "not_written"
+ assert turn["settled_by"] == "terminal_run"
+
+
+def test_definite_handler_prewrite_exit_requeues_through_terminal_boundary(
+ managers,
+ monkeypatch,
+) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ manager._run = SessionTurnManager._run.__get__(manager, SessionTurnManager)
+ delivery_id = delivery_store.new_delivery_id()
+ turn_id = delivery_store.new_turn_id()
+ with engine.begin() as conn:
+ delivery = delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="retry after backend is enabled",
+ ),
+ dispatch_text="retry after backend is enabled",
+ )
+ delivery_store.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id="ses_fsm",
+ backend="opencode",
+ deliveries=[delivery],
+ dispatch_text="retry after backend is enabled",
+ )
+
+ async def definite_prewrite_exit(*_args, **_kwargs):
+ return TurnDispatchOutcome(
+ error="agent 'opencode' is not available",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ backend_dispatch_attempted=False,
+ )
+
+ monkeypatch.setattr(
+ "core.session_turns.dispatch_turn_with_outcome",
+ definite_prewrite_exit,
+ )
+
+ async def run() -> None:
+ await manager._run(
+ "ses_fsm",
+ _context(),
+ "retry after backend is enabled",
+ logical_turn_id=turn_id,
+ delivery_id=delivery_id,
+ durable_preallocated=True,
+ )
+ await manager.in_flight["ses_fsm"].task
+
+ asyncio.run(run())
+
+ assert _row(engine, delivery_id)["state"] == "queued"
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ assert turn is not None
+ assert turn["terminal_outcome"] == "not_written"
+ assert turn["settled_by"] == "no_terminal_result"
+
+
+def test_definite_handler_prewrite_exception_requeues_through_terminal_boundary(
+ managers,
+ monkeypatch,
+) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ manager._run = SessionTurnManager._run.__get__(manager, SessionTurnManager)
+ delivery_id = delivery_store.new_delivery_id()
+ turn_id = delivery_store.new_turn_id()
+ with engine.begin() as conn:
+ delivery = delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="retry after terminal persistence failure",
+ ),
+ dispatch_text="retry after terminal persistence failure",
+ )
+ delivery_store.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id="ses_fsm",
+ backend="opencode",
+ deliveries=[delivery],
+ dispatch_text="retry after terminal persistence failure",
+ )
+
+ async def definite_prewrite_exception(_controller, context, *_args, **_kwargs):
+ set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)
+ raise OSError("terminal error persistence failed")
+
+ monkeypatch.setattr(
+ "core.session_turns.dispatch_turn_with_outcome",
+ definite_prewrite_exception,
+ )
+
+ async def run() -> None:
+ await manager._run(
+ "ses_fsm",
+ _context(),
+ "retry after terminal persistence failure",
+ logical_turn_id=turn_id,
+ delivery_id=delivery_id,
+ durable_preallocated=True,
+ )
+ await manager.in_flight["ses_fsm"].task
+
+ asyncio.run(run())
+
+ assert _row(engine, delivery_id)["state"] == "queued"
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ assert turn is not None
+ assert turn["terminal_outcome"] == "not_written"
+ assert turn["start_receipt_outcome"] == "not_written"
+
+
+def test_forced_backend_refresh_fails_unresolved_start_instead_of_blocking(
+ managers,
+) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ delivery_id = delivery_store.new_delivery_id()
+ turn_id = delivery_store.new_turn_id()
+ with engine.begin() as conn:
+ delivery = delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="ambiguous during forced refresh",
+ ),
+ dispatch_text="ambiguous during forced refresh",
+ )
+ delivery_store.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id="ses_fsm",
+ backend="codex",
+ deliveries=[delivery],
+ dispatch_text="ambiguous during forced refresh",
+ )
+ manager.begin_backend_drain("codex")
+
+ released = asyncio.run(
+ manager.release_for_backend_refresh(
+ backend="codex",
+ base_session_ids={"ses_fsm"},
+ )
+ )
+
+ assert released == 1
+ assert _row(engine, delivery_id)["state"] == "retired"
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ status = conn.execute(
+ select(agent_sessions.c.agent_status).where(agent_sessions.c.id == "ses_fsm")
+ ).scalar_one()
+ assert turn is not None
+ assert turn["state"] == "terminal"
+ assert turn["terminal_outcome"] == "failed"
+ assert turn["terminal_evidence_kind"] == "backend_refresh_start_failed"
+ assert status == "failed"
+
+
+def test_backend_refresh_preserves_successor_activated_by_old_turn_cancellation(
+ managers,
+ monkeypatch,
+) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ manager._run = SessionTurnManager._run.__get__(manager, SessionTurnManager)
+ native_started = asyncio.Event()
+
+ async def long_native_turn(_controller, context, *_args, **_kwargs):
+ logical_turn_id = str(context.platform_specific["turn_token"])
+ context.platform_specific["agent_runtime_turn_token"] = (
+ f"runtime-{logical_turn_id}"
+ )
+ manager._active_identity = lambda _backend, _session_id, logical_id: (
+ logical_id,
+ f"native-{logical_id}",
+ )
+ manager.on_native_start(
+ context,
+ backend="codex",
+ runtime_key=f"runtime-key-{logical_turn_id}",
+ runtime_turn_id=f"runtime-{logical_turn_id}",
+ )
+ native_started.set()
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(
+ "core.session_turns.dispatch_turn_with_outcome",
+ long_native_turn,
+ )
+
+ async def run() -> tuple[str, str, str]:
+ admitted = await manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content="old backend work",
+ ),
+ context=_context(),
+ )
+ assert admitted.turn_id
+ await asyncio.wait_for(native_started.wait(), timeout=3)
+ replacement = await manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p0",
+ content="replacement after refresh",
+ ),
+ context=_context(),
+ )
+ assert replacement.state == "waiting_terminal"
+ with engine.connect() as conn:
+ old_turn = delivery_store.get_turn(conn, str(admitted.turn_id))
+ assert old_turn is not None and old_turn["control_successor_turn_id"]
+ successor_turn_id = str(old_turn["control_successor_turn_id"])
+
+ manager.begin_backend_drain("codex")
+ released = await manager.release_for_backend_refresh(
+ backend="codex",
+ base_session_ids={"ses_fsm"},
+ )
+ assert released == 1
+ return str(admitted.turn_id), successor_turn_id, str(replacement.delivery_id)
+
+ old_turn_id, successor_turn_id, replacement_delivery_id = asyncio.run(run())
+
+ with engine.connect() as conn:
+ old_turn = delivery_store.get_turn(conn, old_turn_id)
+ successor = delivery_store.get_turn(conn, successor_turn_id)
+ replacement = delivery_store.get_delivery(conn, replacement_delivery_id)
+ assert old_turn is not None and old_turn["state"] == "terminal"
+ assert successor is not None and successor["state"] == "starting"
+ assert replacement is not None and replacement["state"] == "claimed"
+ assert manager._deferred_restart_sessions == {"codex": {"ses_fsm"}}
+
+
+def test_restore_registration_failure_terminalizes_exact_start(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ delivery_id = delivery_store.new_delivery_id()
+ turn_id = delivery_store.new_turn_id()
+ with engine.begin() as conn:
+ delivery = delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="restore registration failure",
+ ),
+ dispatch_text="restore registration failure",
+ )
+ delivery_store.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id="ses_fsm",
+ backend="opencode",
+ deliveries=[delivery],
+ dispatch_text="restore registration failure",
+ )
+
+ assert manager.fail_restored_backend_turn(
+ turn_id,
+ backend="opencode",
+ reason="poll_registration_failed",
+ )
+
+ assert _row(engine, delivery_id)["state"] == "retired"
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ status = conn.execute(
+ select(agent_sessions.c.agent_status).where(
+ agent_sessions.c.id == "ses_fsm"
+ )
+ ).scalar_one()
+ assert turn is not None
+ assert turn["state"] == "terminal"
+ assert turn["terminal_outcome"] == "failed"
+ assert turn["terminal_evidence_kind"] == "backend_restore_failed"
+ assert status == "failed"
+
+
+def test_materialized_message_preserves_submission_and_acceptance_times(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ turn_id, _context_value = asyncio.run(_activate(manager, text="ordered input"))
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ assert turn is not None
+ delivery = conn.execute(
+ select(message_deliveries).where(
+ message_deliveries.c.id == turn["initial_delivery_id"]
+ )
+ ).mappings().one()
+ message = conn.execute(
+ select(messages).where(messages.c.id == delivery["id"])
+ ).mappings().one()
+ assert message["created_at"] == delivery["submitted_at"]
+ assert message["delivered_at"] == delivery["materialized_at"]
+
+
+def test_two_restart_recoveries_claim_reserved_submission_once(managers) -> None:
+ first, second, engine, _engine_b, starts = managers
+ delivery_id = delivery_store.new_delivery_id()
+ with engine.begin() as conn:
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="recover once",
+ ),
+ dispatch_text="recover once",
+ )
+ barrier = threading.Barrier(2)
+ original_first = first._delivery_backend
+ original_second = second._delivery_backend
+
+ def synchronized(original):
+ def wrapped(session_id, context):
+ barrier.wait(timeout=5)
+ return original(session_id, context)
+
+ return wrapped
+
+ first._delivery_backend = synchronized(original_first)
+ second._delivery_backend = synchronized(original_second)
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ _results = [
+ future.result(timeout=5)
+ for future in (
+ pool.submit(asyncio.run, first.recover_durable_delivery_state()),
+ pool.submit(asyncio.run, second.recover_durable_delivery_state()),
+ )
+ ]
+
+ assert [text for _, text in starts] == ["recover once"]
+ assert _row(engine, delivery_id)["state"] == "claimed"
+
+
+def test_reserved_attachment_only_submission_recovers_exact_dispatch_inputs(
+ managers,
+ tmp_path: Path,
+) -> None:
+ from storage import media_service
+
+ manager, _other, engine, _engine_b, _starts = managers
+ attachment = tmp_path / "input.txt"
+ attachment.write_text("durable attachment", encoding="utf-8")
+ delivery_id = delivery_store.new_delivery_id()
+ with engine.begin() as conn:
+ token = media_service.register(
+ conn,
+ scope_id=None,
+ session_id="ses_fsm",
+ kind="file",
+ source="user_upload",
+ local_path=str(attachment),
+ file_name="input.txt",
+ content_type="text/plain",
+ )
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="",
+ content={"attachments": [{"token": token}]},
+ ),
+ dispatch_text="",
+ )
+ dispatched: list[tuple[str, list[str]]] = []
+
+ async def capture(_session_id, context, text, **_kwargs):
+ dispatched.append(
+ (
+ text,
+ [str(item.local_path) for item in (context.files or [])],
+ )
+ )
+
+ manager._run = capture
+ asyncio.run(manager.recover_durable_delivery_state())
+
+ assert dispatched == [("", [str(attachment)])]
+ assert _row(engine, delivery_id)["state"] == "claimed"
+
+
[email protected]("invalid_reference", ["missing", "revoked", "wrong_session"])
+def test_reserved_attachment_only_submission_requires_a_resolvable_reference(
+ managers,
+ tmp_path: Path,
+ invalid_reference: str,
+) -> None:
+ from storage import media_service
+
+ manager, _other, engine, _engine_b, starts = managers
+ delivery_id = delivery_store.new_delivery_id()
+ token = "missing-attachment-token"
+ if invalid_reference == "wrong_session":
+ _seed_session(engine, "ses_other")
+ with engine.begin() as conn:
+ if invalid_reference != "missing":
+ attachment = tmp_path / f"{invalid_reference}.txt"
+ attachment.write_text("invalid durable attachment", encoding="utf-8")
+ attachment_session_id = "ses_fsm"
+ if invalid_reference == "wrong_session":
+ attachment_session_id = "ses_other"
+ token = media_service.register(
+ conn,
+ scope_id=None,
+ session_id=attachment_session_id,
+ kind="file",
+ source="user_upload",
+ local_path=str(attachment),
+ file_name=attachment.name,
+ content_type="text/plain",
+ )
+ if invalid_reference == "revoked":
+ conn.execute(
+ update(media_objects)
+ .where(media_objects.c.token == token)
+ .values(revoked_at="2026-08-01T00:00:01Z")
+ )
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="",
+ content={"attachments": [{"token": token}]},
+ ),
+ dispatch_text="",
+ )
+ conn.execute(
+ agent_runs.insert().values(
+ id=f"run_invalid_attachment_{invalid_reference}",
+ run_type="agent",
+ status="queued",
+ session_id="ses_fsm",
+ delivery_id=delivery_id,
+ cancel_requested=0,
+ created_at="2026-08-01T00:00:00Z",
+ updated_at="2026-08-01T00:00:00Z",
+ metadata_json="{}",
+ )
+ )
+
+ assert asyncio.run(manager.recover_durable_delivery_state()) == ["ses_fsm"]
+
+ assert starts == []
+ assert _row(engine, delivery_id)["state"] == "retired"
+ with engine.connect() as conn:
+ run = conn.execute(
+ select(agent_runs).where(
+ agent_runs.c.id == f"run_invalid_attachment_{invalid_reference}"
+ )
+ ).mappings().one()
+ assert run["status"] == "canceled"
+ assert run["cancel_requested"] == 1
+
+
+def test_fifo_claim_retires_invalid_attachment_head_and_starts_next(
+ managers,
+) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ invalid_id = delivery_store.new_delivery_id()
+ valid_id = delivery_store.new_delivery_id()
+ with engine.begin() as conn:
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=invalid_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="",
+ content={"attachments": [{"token": "deleted-token"}]},
+ ),
+ dispatch_text="",
+ now="2026-08-01T00:00:01Z",
+ )
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=valid_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="valid following input",
+ ),
+ dispatch_text="valid following input",
+ now="2026-08-01T00:00:02Z",
+ )
+
+ assert asyncio.run(manager.drain_delivery_queue("ses_fsm"))
+
+ assert _row(engine, invalid_id)["state"] == "retired"
+ assert _row(engine, valid_id)["state"] == "claimed"
+ assert [text for _turn_id, text in starts] == ["valid following input"]
+
+
+def test_final_dispatch_gate_retires_batch_when_attachment_expires_after_claim(
+ managers,
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ from core.inbox_events import bus
+ from storage import media_service
+
+ manager, _other, engine, _engine_b, starts = managers
+ published: list[tuple[str, dict]] = []
+ monkeypatch.setattr(bus, "publish", lambda event, payload: published.append((event, payload)))
+ attachment = tmp_path / "expires-after-claim.txt"
+ attachment.write_text("expires after claim", encoding="utf-8")
+ delivery_id = delivery_store.new_delivery_id()
+ with engine.begin() as conn:
+ token = media_service.register(
+ conn,
+ scope_id=None,
+ session_id="ses_fsm",
+ kind="file",
+ source="user_upload",
+ local_path=str(attachment),
+ file_name=attachment.name,
+ content_type="text/plain",
+ )
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="",
+ content={"attachments": [{"token": token}]},
+ ),
+ dispatch_text="",
+ )
+ turn_id = manager._claim_fifo_batch_in_transaction(
+ conn,
+ session_id="ses_fsm",
+ backend="codex",
+ )
+ assert turn_id is not None
+ with engine.begin() as conn:
+ conn.execute(
+ update(media_objects)
+ .where(media_objects.c.token == token)
+ .values(revoked_at="2026-08-01T00:00:01Z")
+ )
+
+ assert not asyncio.run(manager._start_persisted_turn(turn_id))
+
+ assert starts == []
+ assert _row(engine, delivery_id)["state"] == "retired"
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ assert turn is not None
+ assert turn["state"] == "terminal"
+ assert turn["terminal_evidence_kind"] == "invalid_input_before_native_dispatch"
+ assert ("queue.updated", {"session_id": "ses_fsm"}) in published
+
+
+def test_final_dispatch_gate_preserves_valid_batch_members(
+ managers,
+ tmp_path: Path,
+) -> None:
+ from storage import media_service
+
+ manager, _other, engine, _engine_b, starts = managers
+ attachment = tmp_path / "expired-batch-member.txt"
+ attachment.write_text("expires after claim", encoding="utf-8")
+ valid_id = delivery_store.new_delivery_id()
+ invalid_id = delivery_store.new_delivery_id()
+ with engine.begin() as conn:
+ token = media_service.register(
+ conn,
+ scope_id=None,
+ session_id="ses_fsm",
+ kind="file",
+ source="user_upload",
+ local_path=str(attachment),
+ file_name=attachment.name,
+ content_type="text/plain",
+ )
+ valid = delivery_store.insert_delivery(
+ conn,
+ delivery_id=valid_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="surviving text",
+ ),
+ dispatch_text="surviving text",
+ )
+ invalid = delivery_store.insert_delivery(
+ conn,
+ delivery_id=invalid_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="",
+ content={"attachments": [{"token": token}]},
+ ),
+ dispatch_text="",
+ )
+ turn_id = delivery_store.new_turn_id()
+ delivery_store.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id="ses_fsm",
+ backend="codex",
+ deliveries=[valid, invalid],
+ dispatch_text="surviving text",
+ )
+ conn.execute(
+ update(media_objects)
+ .where(media_objects.c.token == token)
+ .values(revoked_at="2026-08-01T00:00:01Z")
+ )
+
+ assert not asyncio.run(manager._start_persisted_turn(turn_id))
+
+ assert _row(engine, invalid_id)["state"] == "retired"
+ valid_after = _row(engine, valid_id)
+ assert valid_after["state"] == "claimed"
+ assert valid_after["turn_id"] != turn_id
+ assert [text for _turn_id, text in starts] == ["surviving text"]
+
+
+def test_empty_reserved_submission_is_retired_without_native_dispatch(managers) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ delivery_id = delivery_store.new_delivery_id()
+ with engine.begin() as conn:
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ text=" ",
+ content={"attachments": []},
+ ),
+ dispatch_text=" ",
+ )
+
+ assert asyncio.run(manager.recover_durable_delivery_state()) == ["ses_fsm"]
+
+ assert starts == []
+ assert _row(engine, delivery_id)["state"] == "retired"
+
+
+def test_terminal_run_retires_its_exact_prewrite_delivery(managers) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ delivery_id = delivery_store.new_delivery_id()
+ now = "2026-08-01T00:00:00Z"
+ with engine.begin() as conn:
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p1",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="scheduled input",
+ ),
+ dispatch_text="scheduled input",
+ )
+ conn.execute(
+ agent_runs.insert().values(
+ id="run_terminal_stamp_refused",
+ run_type="task_run",
+ status="failed",
+ session_id="ses_fsm",
+ delivery_id=delivery_id,
+ cancel_requested=0,
+ error="task result was not recorded",
+ created_at=now,
+ completed_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+
+ result = asyncio.run(
+ manager.reconcile_terminal_run_delivery(
+ "run_terminal_stamp_refused",
+ session_id="ses_fsm",
+ )
+ )
+
+ assert result == {"changed": True, "state": "retired"}
+ assert starts == []
+ assert _row(engine, delivery_id)["state"] == "retired"
+
+
+def test_unresolved_p1_fence_blocks_later_but_not_older_fifo(managers) -> None:
+ """MESSAGE-DELIVERY-101: fallback-capable unknown preserves submission order."""
+
+ manager, other, engine, _engine_b, starts = managers
+ t1, _ = asyncio.run(_activate(manager))
+ asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="older"),
+ context=_context(),
+ )
+ )
+ manager._steer = AsyncMock(return_value=steer_result(SteerOutcome.UNKNOWN))
+ unknown = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content="unknown"),
+ context=_context(),
+ )
+ )
+ asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="later"),
+ context=_context(),
+ )
+ )
+ assert asyncio.run(other.terminalize_turn(t1))
+ assert asyncio.run(other.drain_delivery_queue("ses_fsm")) is False
+ older_turn = _row(engine, next(row["id"] for row in _rows(engine) if row["dispatch_text"] == "older"))[
+ "turn_id"
+ ]
+ assert older_turn
+ older_context = _context()
+ older_context.platform_specific["turn_token"] = str(older_turn)
+ older_context.platform_specific["agent_runtime_turn_token"] = f"runtime-{older_turn}"
+ other._active_identity = lambda _backend, _session_id, logical_id: (
+ logical_id,
+ f"native-{logical_id}",
+ )
+ other.on_native_start(
+ older_context,
+ backend="codex",
+ runtime_key=f"runtime-key-{older_turn}",
+ runtime_turn_id=f"runtime-{older_turn}",
+ )
+ assert asyncio.run(other.terminalize_turn(str(older_turn)))
+ assert asyncio.run(other.drain_delivery_queue("ses_fsm")) is False
+
+ assert _row(engine, str(unknown.delivery_id))["state"] == "reconciling_steer"
+ assert [text for _, text in starts].count("older") == 1
+ assert [text for _, text in starts].count("later") == 0
+
+
+def test_held_old_backlog_does_not_block_new_idle_p3(managers) -> None:
+ """MESSAGE-DELIVERY-102: hold blocks autonomous backlog only."""
+
+ manager, other, engine, _engine_b, starts = managers
+
+ async def run() -> None:
+ turn_id, context = await _activate(manager)
+ await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="held-old"),
+ context=_context(),
+ )
+ holder = asyncio.create_task(asyncio.Event().wait())
+ manager.in_flight["ses_fsm"] = Turn(
+ task=holder,
+ context=context,
+ logical_turn_id=turn_id,
+ )
+ stopped = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p0", content=None),
+ context=context,
+ )
+ assert stopped.state == "waiting_terminal"
+ assert await other.terminalize_turn(turn_id)
+ holder.cancel()
+ await asyncio.gather(holder, return_exceptions=True)
+ admitted = await other.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="new-idle"),
+ context=_context(),
+ )
+ assert admitted.state == "claimed"
+
+ asyncio.run(run())
+ rows = _rows(engine)
+ assert next(row for row in rows if row["dispatch_text"] == "held-old")["state"] == "queued"
+ assert [text for _, text in starts].count("new-idle") == 1
+ with engine.connect() as conn:
+ assert delivery_store.queue_is_held(conn, "ses_fsm") is True
+
+
+def test_open_backlog_starts_oldest_before_new_idle_p3(managers) -> None:
+ """An open compatible FIFO segment is claimed as one native Turn."""
+
+ manager, _other, engine, _engine_b, starts = managers
+ started_contexts: list[dict[str, object]] = []
+
+ async def capture_start(_session_id, context, text, **kwargs):
+ starts.append((str(kwargs.get("logical_turn_id") or ""), text))
+ started_contexts.append(dict(context.platform_specific or {}))
+
+ manager._run = capture_start
+ with engine.begin() as conn:
+ older = delivery_store.enqueue_queued(
+ conn,
+ scope_id=None,
+ session_id="ses_fsm",
+ text="older-drain-head",
+ now="2026-07-31T23:59:00+00:00",
+ )
+
+ new_context = _context()
+ new_context.platform_specific["new_submission_only"] = True
+ admitted = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content="new-after-drain",
+ ),
+ context=new_context,
+ )
+ )
+
+ assert admitted.state == "claimed"
+ assert [text for _, text in starts] == ["older-drain-head\nnew-after-drain"]
+ assert "new_submission_only" not in started_contexts[0]
+ older_after = _row(engine, older["id"])
+ new_after = _row(engine, str(admitted.delivery_id))
+ assert older_after["state"] == "claimed"
+ assert new_after["state"] == "claimed"
+ assert new_after["turn_id"] == older_after["turn_id"]
+
+
+def test_accepted_steer_after_target_terminal_attaches_exact_terminal_turn(managers) -> None:
+ manager, terminal_manager, engine, _engine_b, _starts = managers
+
+ async def run():
+ turn_id, _ = await _activate(manager)
+ entered = asyncio.Event()
+ release = asyncio.Event()
+
+ async def accepted(_backend, _request):
+ entered.set()
+ await release.wait()
+ return steer_result(SteerOutcome.ACCEPTED)
+
+ manager._steer = accepted
+ pending = asyncio.create_task(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content="late receipt"),
+ context=_context(),
+ )
+ )
+ await entered.wait()
+ assert await terminal_manager.terminalize_turn(turn_id)
+ release.set()
+ return turn_id, await pending
+
+ turn_id, result = asyncio.run(run())
+ row = _row(engine, str(result.delivery_id))
+ assert result.state == "accepted"
+ assert row["turn_id"] == turn_id
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ message = conn.execute(select(messages).where(messages.c.id == row["id"])).mappings().one()
+ assert turn["state"] == "terminal"
+ assert message["content_text"] == "late receipt"
+
+
[email protected]("activity_blocks_settlement", [False, True])
+def test_late_accepted_agent_run_settles_from_terminal_turn_snapshot(
+ managers,
+ activity_blocks_settlement: bool,
+) -> None:
+ from core.scheduled_tasks import ScheduledTaskService, TaskExecutionStore
+ from storage.background import SQLiteBackgroundTaskStore
+
+ manager, _terminal_manager, engine, _engine_b, _starts = managers
+ db_path = Path(str(engine.url.database))
+ run_store = SQLiteBackgroundTaskStore(db_path)
+ request_store = TaskExecutionStore(root=db_path.parent / "unused-file-store")
+ request_store._sqlite = run_store
+ scheduled = ScheduledTaskService.__new__(ScheduledTaskService)
+ scheduled.controller = manager.controller
+ scheduled.request_store = request_store
+ scheduled._drain_dirty = False
+ manager.controller.scheduled_task_service = scheduled
+ manager.controller.agent_service.activities = SimpleNamespace(
+ has_blocking_run_activity=lambda _run_id: activity_blocks_settlement,
+ )
+
+ async def run() -> tuple[str, str, str]:
+ turn_id, active_context = await _activate(manager)
+ run_id = "run-late-terminal-steer"
+ now = "2026-08-01T00: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",
+ callback_session_id="ses_callback",
+ callback_status="pending",
+ created_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+ queued = await manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content="queued Agent Run prompt",
+ source="harness",
+ author="harness",
+ message_type="harness",
+ native_message_id=f"agent_run:{run_id}",
+ metadata={
+ "scheduled_provenance": {
+ "task_execution_id": run_id,
+ "platform_specific": {
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": run_id,
+ },
+ }
+ },
+ ),
+ context=_context(),
+ )
+ assert queued.state == "queued"
+ with engine.begin() as conn:
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(delivery_id=queued.delivery_id)
+ )
+ entered = asyncio.Event()
+ release = asyncio.Event()
+
+ async def accepted(_backend, _request):
+ entered.set()
+ await release.wait()
+ return steer_result(SteerOutcome.ACCEPTED)
+
+ manager._steer = accepted
+ promoted = asyncio.create_task(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content=None),
+ context=_context(),
+ )
+ )
+ await entered.wait()
+ manager.on_terminal_result(
+ active_context,
+ is_error=False,
+ terminal_evidence={
+ "result_text": "immutable terminal body",
+ "settles_run": True,
+ },
+ )
+ manager.on_terminal_delivery_complete(active_context)
+ release.set()
+ accepted_delivery = await promoted
+ assert accepted_delivery.state == "accepted"
+ return turn_id, run_id, str(queued.delivery_id)
+
+ try:
+ turn_id, run_id, delivery_id = asyncio.run(run())
+ with engine.connect() as conn:
+ run_row = conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id)
+ ).mappings().one()
+ delivery = conn.execute(
+ select(message_deliveries).where(
+ message_deliveries.c.id == delivery_id
+ )
+ ).mappings().one()
+ assert delivery["turn_id"] == turn_id
+ if activity_blocks_settlement:
+ assert run_row["status"] == "running"
+ payload = json.loads(run_row["result_payload_json"])
+ assert payload["deferred_terminal_status"] == "succeeded"
+ assert payload["deferred_terminal_result_text"] == "immutable terminal body"
+ manager.controller.agent_service.activities.has_blocking_run_activity = (
+ lambda _run_id: False
+ )
+ scheduled._recover_activity_lifecycle()
+ assert request_store.get_run(run_id)["status"] == "succeeded"
+ else:
+ assert run_row["status"] == "succeeded"
+ assert run_row["result_text"] == "immutable terminal body"
+ assert run_row["callback_status"] == "pending"
+ assert scheduled._drain_dirty is True
+ finally:
+ run_store.close()
+
+
+def test_restart_settles_agent_run_after_late_acceptance_commit(managers) -> None:
+ from core.scheduled_tasks import ScheduledTaskService, TaskExecutionStore
+ from storage.background import SQLiteBackgroundTaskStore
+
+ manager, restarted, engine, _engine_b, _starts = managers
+
+ async def settle_turn() -> str:
+ turn_id, active_context = await _activate(manager)
+ manager.on_terminal_result(
+ active_context,
+ is_error=False,
+ terminal_evidence={
+ "result_text": "recovered immutable terminal body",
+ "settles_run": True,
+ },
+ )
+ manager.on_terminal_delivery_complete(active_context)
+ return turn_id
+
+ turn_id = asyncio.run(settle_turn())
+ run_id = "run-recovered-late-terminal-steer"
+ delivery_id = delivery_store.new_delivery_id()
+ attempt_id = delivery_store.new_attempt_id()
+ now = "2026-08-01T00: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",
+ callback_session_id="ses_callback",
+ callback_status="pending",
+ created_at=now,
+ started_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p1",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="accepted before settlement crashed",
+ native_message_id=f"agent_run:{run_id}",
+ metadata={
+ "scheduled_provenance": {
+ "task_execution_id": run_id,
+ "platform_specific": {
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": run_id,
+ },
+ }
+ },
+ ),
+ dispatch_text="accepted before settlement crashed",
+ )
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(delivery_id=delivery_id)
+ )
+ delivery = delivery_store.get_delivery(conn, delivery_id)
+ assert delivery is not None
+ steering = delivery_store.open_steer_attempt(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ expected_native_turn_id=f"native-{turn_id}",
+ )
+ assert steering is not None
+ assert delivery_store.materialize_acceptance(
+ conn,
+ delivery_id=delivery_id,
+ expected_attempt_id=attempt_id,
+ turn_id=turn_id,
+ evidence={"kind": "steer_receipt", "receipt": {"outcome": "accepted"}},
+ ) is not None
+
+ db_path = Path(str(engine.url.database))
+ run_store = SQLiteBackgroundTaskStore(db_path)
+ request_store = TaskExecutionStore(root=db_path.parent / "unused-recovery-store")
+ request_store._sqlite = run_store
+ scheduled = ScheduledTaskService.__new__(ScheduledTaskService)
+ scheduled.request_store = request_store
+ scheduled._drain_dirty = False
+ restarted.controller.scheduled_task_service = scheduled
+ try:
+ asyncio.run(restarted.recover_durable_delivery_state())
+ with engine.connect() as conn:
+ run_row = conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id)
+ ).mappings().one()
+ assert run_row["status"] == "succeeded"
+ assert run_row["result_text"] == "recovered immutable terminal body"
+ assert run_row["callback_status"] == "pending"
+ assert scheduled._drain_dirty is True
+ finally:
+ run_store.close()
+
+
+def test_terminal_turn_without_positive_result_evidence_keeps_late_run_unsettled(
+ managers,
+) -> None:
+ from core.scheduled_tasks import ScheduledTaskService, TaskExecutionStore
+ from storage.background import SQLiteBackgroundTaskStore
+
+ manager, _restarted, engine, _engine_b, _starts = managers
+ run_id = "run-missing-terminal-result-evidence"
+ now = "2026-08-01T00: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",
+ callback_session_id="ses_callback",
+ callback_status="pending",
+ created_at=now,
+ started_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+
+ db_path = Path(str(engine.url.database))
+ run_store = SQLiteBackgroundTaskStore(db_path)
+ request_store = TaskExecutionStore(root=db_path.parent / "unused-no-evidence-store")
+ request_store._sqlite = run_store
+ scheduled = ScheduledTaskService.__new__(ScheduledTaskService)
+ scheduled.controller = manager.controller
+ scheduled.request_store = request_store
+ scheduled._drain_dirty = False
+ try:
+ scheduled.settle_agent_runs_from_terminal_turn(
+ [run_id],
+ turn_id="turn-without-result-evidence",
+ outcome="completed",
+ settled_by="terminal_result",
+ evidence_kind="agent_initiated_terminal",
+ evidence={},
+ )
+ stored = request_store.get_run(run_id)
+ assert stored is not None
+ assert stored["status"] == "running"
+ assert stored["result_text"] in {None, ""}
+ assert scheduled._drain_dirty is False
+ finally:
+ run_store.close()
+
+
+def test_owned_run_sweep_retries_terminal_turn_settlement_before_orphaning(
+ managers,
+) -> None:
+ manager, _restarted, engine, _engine_b, _starts = managers
+ turn_id, _context_value = asyncio.run(_activate(manager))
+ run_id = "run-terminal-settlement-retry"
+ now = "2026-08-01T00:00:00Z"
+ with engine.begin() as conn:
+ initial = delivery_store.initial_deliveries_for_turn(conn, turn_id)[0]
+ 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",
+ callback_session_id="ses_callback",
+ callback_status="pending",
+ delivery_id=initial["id"],
+ created_at=now,
+ started_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+
+ terminal = manager._terminalize_durable_turn(
+ turn_id,
+ "completed",
+ settled_by="terminal_result",
+ evidence_kind="terminal_result",
+ evidence={"settles_run": True, "result_text": "done"},
+ )
+ assert terminal["changed"] is True
+ with engine.connect() as conn:
+ terminal_turn = delivery_store.get_turn(conn, turn_id)
+ assert terminal_turn is not None
+
+ class _FlakyTerminalSettlement:
+ calls = 0
+
+ def settle_agent_runs_from_terminal_turn(self, execution_ids, **_kwargs):
+ self.calls += 1
+ if self.calls == 1:
+ raise OSError("transient settlement failure")
+ with engine.begin() as conn:
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id.in_(list(execution_ids)))
+ .values(status="succeeded", completed_at=now, updated_at=now)
+ )
+
+ settlement = _FlakyTerminalSettlement()
+ manager.controller.scheduled_task_service = settlement
+ manager._settle_agent_run_ids_from_terminal_turn([run_id], terminal_turn)
+ with engine.connect() as conn:
+ assert conn.execute(
+ select(agent_runs.c.status).where(agent_runs.c.id == run_id)
+ ).scalar_one() == "running"
+
+ assert run_id not in manager.owned_agent_run_ids()
+ assert settlement.calls == 2
+ with engine.connect() as conn:
+ assert conn.execute(
+ select(agent_runs.c.status).where(agent_runs.c.id == run_id)
+ ).scalar_one() == "succeeded"
+
+
+def test_restored_opencode_generation_rebinds_turn_control_and_steer(
+ managers,
+) -> None:
+ manager, _restarted, engine, _engine_b, _starts = managers
+ old_native_id = "opencode:native-session:old-generation"
+ new_native_id = "opencode:native-session:new-generation"
+ with engine.begin() as conn:
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == "ses_fsm")
+ .values(agent_backend="opencode")
+ )
+
+ context = _context()
+ context.platform_specific["agent_session_target"]["agent_backend"] = "opencode"
+ admitted = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="active"),
+ context=context,
+ )
+ )
+ assert admitted.turn_id is not None
+ turn_id = admitted.turn_id
+ context.platform_specific["turn_token"] = turn_id
+ context.platform_specific["agent_runtime_turn_token"] = f"runtime-{turn_id}"
+ manager._active_identity = lambda _backend, _session, logical: (
+ logical,
+ old_native_id,
+ )
+ manager.on_native_start(
+ context,
+ backend="opencode",
+ runtime_key="opencode:native-session",
+ runtime_turn_id=f"runtime-{turn_id}",
+ )
+
+ steer_delivery_id = delivery_store.new_delivery_id()
+ steer_attempt_id = delivery_store.new_attempt_id()
+ with engine.begin() as conn:
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=steer_delivery_id,
+ session_id="ses_fsm",
+ priority="p1",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="steer after restart",
+ ),
+ dispatch_text="steer after restart",
+ )
+ delivery = delivery_store.get_delivery(conn, steer_delivery_id)
+ assert delivery is not None
+ steering = delivery_store.open_steer_attempt(
+ conn,
+ steer_delivery_id,
+ expected_version=int(delivery["version"]),
+ turn_id=turn_id,
+ attempt_id=steer_attempt_id,
+ expected_native_turn_id=old_native_id,
+ )
+ assert steering is not None
+ assert delivery_store.mark_attempt_unknown(
+ conn,
+ steer_delivery_id,
+ expected_version=int(steering["version"]),
+ receipt={"reason": "restart"},
+ ) is not None
+ turn = delivery_store.get_turn(conn, turn_id)
+ assert turn is not None
+ assert delivery_store.cas_turn(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ expected_states=("active",),
+ values={
+ "control_state": "pending",
+ "control_mode": "stop_only",
+ "control_attempt_id": delivery_store.new_attempt_id(),
+ "control_expected_native_turn_id": old_native_id,
+ },
+ ) is not None
+
+ reconciled_native_ids: list[str] = []
+
+ async def reconcile(_backend, request):
+ reconciled_native_ids.append(request.expected_native_turn_id)
+ return steer_result(SteerOutcome.UNKNOWN, reason="still_unknown")
+
+ manager._active_identity = lambda _backend, _session, logical: (
+ logical,
+ new_native_id,
+ )
+ manager._reconcile_steer_attempt = reconcile
+ manager._run_pending_interrupt = AsyncMock(return_value={"state": "waiting_terminal"})
+
+ asyncio.run(manager.recover_durable_delivery_state())
+
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ steer = delivery_store.get_delivery(conn, steer_delivery_id)
+ assert turn is not None
+ assert turn["native_turn_id"] == new_native_id
+ assert turn["control_expected_native_turn_id"] == new_native_id
+ assert steer is not None
+ assert steer["current_expected_native_turn_id"] == new_native_id
+ assert reconciled_native_ids == [new_native_id]
+ manager._run_pending_interrupt.assert_awaited_once_with("ses_fsm", turn_id)
+
+
+def test_repeated_refusal_then_acceptance_preserves_attempt_history(managers) -> None:
+ manager, other, engine, _engine_b, _starts = managers
+ t1, _ = asyncio.run(_activate(manager, text="t1"))
+ manager._steer = AsyncMock(
+ return_value=steer_result(SteerOutcome.REFUSED, reason="not_steerable")
+ )
+ first_attempt = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content="retry me"),
+ context=_context(),
+ )
+ )
+ assert _row(engine, str(first_attempt.delivery_id))["state"] == "queued"
+ with engine.begin() as conn:
+ delivery_store.set_queue_hold(conn, "ses_fsm", held=True)
+ assert asyncio.run(other.terminalize_turn(t1))
+ t2, context2 = asyncio.run(
+ _activate(other, text="new priority work", priority="p1")
+ )
+ other._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
+ promoted = asyncio.run(
+ other.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content=None),
+ context=context2,
+ )
+ )
+ assert promoted.delivery_id == first_attempt.delivery_id
+ row = _row(engine, str(promoted.delivery_id))
+ history = json.loads(row["delivery_history_json"])
+ steer_events = [event for event in history["events"] if event["kind"] == "steer"]
+ assert [event["outcome"] for event in steer_events if event["outcome"] != "opened"] == [
+ "refused",
+ "accepted",
+ ]
+ assert row["turn_id"] == t2
+ assert row["current_attempt_id"] is None
+
+
+def test_stale_send_now_does_not_release_the_queue_hold(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ old_turn_id, _ = asyncio.run(_activate(manager, text="old turn"))
+ queued = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="held backlog"),
+ context=_context(),
+ )
+ )
+ with engine.connect() as conn:
+ old_turn = delivery_store.get_turn(conn, old_turn_id)
+ assert old_turn is not None
+ with engine.begin() as conn:
+ assert delivery_store.set_queue_hold(conn, "ses_fsm", held=True)
+ assert asyncio.run(manager.terminalize_turn(old_turn_id))
+ replacement_turn_id, replacement_context = asyncio.run(
+ _activate(manager, text="replacement turn", priority="p1")
+ )
+ manager._observe_active_delivery_turn = lambda _session_id: (
+ old_turn,
+ (old_turn_id, f"native-{old_turn_id}"),
+ )
+
+ result = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p1",
+ content=None,
+ expected_delivery_id=str(queued.delivery_id),
+ ),
+ context=replacement_context,
+ )
+ )
+
+ assert result.state == "refused"
+ assert result.reason == "stale_turn"
+ with engine.connect() as conn:
+ assert delivery_store.queue_is_held(conn, "ses_fsm")
+ current = delivery_store.active_turn(conn, "ses_fsm")
+ assert current is not None and current["id"] == replacement_turn_id
+ assert _row(engine, str(queued.delivery_id))["state"] == "queued"
+
+
+def test_send_now_keeps_attachment_head_for_the_next_turn(
+ managers,
+ tmp_path: Path,
+) -> None:
+ from storage import media_service
+
+ manager, _other, engine, _engine_b, _starts = managers
+ asyncio.run(_activate(manager, text="active turn"))
+ attachment = tmp_path / "queued-input.txt"
+ attachment.write_text("queued attachment", encoding="utf-8")
+ with engine.begin() as conn:
+ token = media_service.register(
+ conn,
+ scope_id=None,
+ session_id="ses_fsm",
+ kind="file",
+ source="user_upload",
+ local_path=str(attachment),
+ file_name=attachment.name,
+ content_type="text/plain",
+ )
+ queued = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content="review this file",
+ content_json={"attachments": [{"token": token}]},
+ ),
+ context=_context(),
+ )
+ )
+ with engine.begin() as conn:
+ assert delivery_store.set_queue_hold(conn, "ses_fsm", held=True)
+ manager._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
+
+ promoted = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p1",
+ content=None,
+ expected_delivery_id=str(queued.delivery_id),
+ ),
+ context=_context(),
+ )
+ )
+
+ assert promoted.state == "queued"
+ assert promoted.reason == "attachments_wait_for_new_turn"
+ manager._steer.assert_not_awaited()
+ assert _row(engine, str(queued.delivery_id))["state"] == "queued"
+ with engine.connect() as conn:
+ assert not delivery_store.queue_is_held(conn, "ses_fsm")
+
+
+def test_content_p1_with_attachment_queues_behind_an_active_turn(
+ managers,
+ tmp_path: Path,
+) -> None:
+ from storage import media_service
+
+ manager, _other, engine, _engine_b, _starts = managers
+ asyncio.run(_activate(manager, text="active turn"))
+ attachment = tmp_path / "priority-input.txt"
+ attachment.write_text("priority attachment", encoding="utf-8")
+ with engine.begin() as conn:
+ token = media_service.register(
+ conn,
+ scope_id=None,
+ session_id="ses_fsm",
+ kind="file",
+ source="user_upload",
+ local_path=str(attachment),
+ file_name=attachment.name,
+ content_type="text/plain",
+ )
+ manager._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
+
+ admitted = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p1",
+ content="review this first",
+ content_json={"attachments": [{"token": token}]},
+ ),
+ context=_context(),
+ )
+ )
+
+ assert admitted.state == "queued"
+ manager._steer.assert_not_awaited()
+ row = _row(engine, str(admitted.delivery_id))
+ assert row["priority"] == "p3"
+ assert row["state"] == "queued"
+
+
+def test_archive_keeps_unknown_and_materializes_late_positive_evidence(managers) -> None:
+ first, restarted, engine, _engine_b, starts = managers
+
+ async def ambiguous(_session_id, _context_value, text, **kwargs):
+ starts.append((str(kwargs.get("logical_turn_id") or ""), text))
+ raise OSError("unknown native start")
+
+ first._run = ambiguous
+ admitted = asyncio.run(
+ first.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="may be written"),
+ context=_context(),
+ )
+ )
+ with engine.begin() as conn:
+ workbench_sessions_service.archive_session(conn, "ses_fsm")
+ assert _row(engine, str(admitted.delivery_id))["state"] == "claimed"
+ restarted._active_identity = lambda _b, _s, logical: (logical, f"native-{logical}")
+ asyncio.run(restarted.recover_durable_delivery_state())
+
+ row = _row(engine, str(admitted.delivery_id))
+ assert row["state"] == "accepted"
+ with engine.connect() as conn:
+ message = conn.execute(select(messages).where(messages.c.id == row["id"])).mappings().one()
+ session_status = conn.execute(
+ select(agent_sessions.c.status, agent_sessions.c.agent_status).where(
+ agent_sessions.c.id == "ses_fsm"
+ )
+ ).one()
+ assert message["content_text"] == "may be written"
+ assert session_status == ("archived", "idle")
+ assert [text for _, text in starts] == ["may be written"]
+
+
+def test_definitive_steer_refusal_after_archive_retires_without_start(managers) -> None:
+ manager, _other, engine, _engine_b, starts = managers
+ delivery_id = delivery_store.new_delivery_id()
+ run_id = "run-archived-steer-refused"
+
+ async def run():
+ turn_id, _ = await _activate(manager)
+ entered = asyncio.Event()
+ release = asyncio.Event()
+
+ async def refused(_backend, _request):
+ entered.set()
+ await release.wait()
+ return steer_result(SteerOutcome.REFUSED, reason="not_steerable")
+
+ manager._steer = refused
+ pending = asyncio.create_task(
+ manager.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p1",
+ content="archived",
+ delivery_id=delivery_id,
+ ),
+ context=_context(),
+ )
+ )
+ await entered.wait()
+ with engine.begin() as conn:
+ now = "2026-08-01T00:00:00Z"
+ 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=delivery_id,
+ created_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+ workbench_sessions_service.archive_session(conn, "ses_fsm")
+ release.set()
+ return turn_id, await pending
+
+ turn_id, result = asyncio.run(run())
+ row = _row(engine, str(result.delivery_id))
+ assert result.state == "retired"
+ assert row["state"] == "retired"
+ assert row["current_attempt_id"] is None
+ assert [started for started, _ in starts] == [turn_id]
+ with engine.connect() as conn:
+ assert conn.execute(
+ select(messages.c.id).where(messages.c.id == result.delivery_id)
+ ).first() is None
+ run_row = conn.execute(
+ select(agent_runs.c.status, agent_runs.c.cancel_requested).where(
+ agent_runs.c.id == run_id
+ )
+ ).one()
+ assert run_row == ("canceled", 1)
+
+
+def test_archive_retires_unstarted_successor_without_creating_message(managers) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+
+ async def run() -> tuple[str, str]:
+ turn_id, context = await _activate(manager)
+ holder = asyncio.create_task(asyncio.Event().wait())
+ manager.in_flight["ses_fsm"] = Turn(
+ task=holder,
+ context=context,
+ logical_turn_id=turn_id,
+ )
+ admitted = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p0", content="unstarted"),
+ context=_context(),
+ )
+ holder.cancel()
+ await asyncio.gather(holder, return_exceptions=True)
+ return turn_id, str(admitted.delivery_id)
+
+ turn_id, delivery_id = asyncio.run(run())
+ with engine.begin() as conn:
+ workbench_sessions_service.archive_session(conn, "ses_fsm")
+ assert asyncio.run(manager.terminalize_turn(turn_id, outcome="canceled"))
+ row = _row(engine, delivery_id)
+ with engine.connect() as conn:
+ successor = conn.execute(
+ select(session_turns).where(session_turns.c.initial_delivery_id == delivery_id)
+ ).mappings().one()
+ message = conn.execute(select(messages.c.id).where(messages.c.id == delivery_id)).first()
+ assert row["state"] == "retired"
+ assert successor["terminal_outcome"] == "not_written"
+ assert message is None
+
+
+async def test_terminal_commit_publishes_replyless_inbox_settlement(
+ managers,
+ monkeypatch,
+) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ with engine.begin() as conn:
+ conn.execute(
+ messages.insert().values(
+ id="msg_prior_result",
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="agent",
+ type="result",
+ source="agent",
+ content_text="prior answer",
+ content_json="{}",
+ metadata_json="{}",
+ created_at="2026-07-31T23:59:00Z",
+ updated_at="2026-07-31T23:59:00Z",
+ )
+ )
+ turn_id, context = await _activate(manager, text="silent request")
+ done = asyncio.Event()
+ manager.register_turn_sink(
+ manager.controller._get_session_key(context),
+ on_chunk=manager._noop_chunk,
+ done_event=done,
+ turn_token=turn_id,
+ context=context,
+ )
+ published: list[tuple[str, dict]] = []
+ monkeypatch.setattr(
+ "core.inbox_events.bus.publish",
+ lambda event, payload: published.append((event, payload)),
+ )
+
+ manager.on_terminal_result(context, is_error=False)
+ done.set()
+ manager.on_terminal_delivery_complete(context)
+ for _ in range(4):
+ await asyncio.sleep(0)
+
+ updates = [payload for event, payload in published if event == "inbox.session.updated"]
+ assert updates
+ assert updates[-1]["session_id"] == "ses_fsm"
+ assert updates[-1]["replied"] is False
+ with engine.connect() as conn:
+ assert delivery_store.get_turn(conn, turn_id)["state"] == "terminal"
+
+
+async def test_agent_initiated_continuation_materializes_in_configured_language(
+ managers,
+) -> None:
+ manager, _other, engine, _engine_b, _starts = managers
+ manager.controller.config.language = "zh"
+ context = _context()
+
+ assert manager.register_agent_initiated_turn(context) is True
+ with engine.connect() as conn:
+ row = messages_service.get_message(conn, str(context.message_id))
+ assert row is not None
+ assert row["text"] == "Agent 主动发起的续接"
+
+ sink = manager.get_turn_sink(manager.controller._get_session_key(context))
+ assert sink is not None
+ manager.on_terminal_result(
+ context,
+ is_error=False,
+ terminal_evidence={
+ "result_text": "agent-initiated terminal body",
+ "settles_run": True,
+ },
+ )
+ sink["done_event"].set()
+ for _ in range(4):
+ await asyncio.sleep(0)
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(
+ conn,
+ str((context.platform_specific or {})["turn_token"]),
+ )
+ assert turn is not None
+ assert json.loads(turn["terminal_evidence_json"]) == {
+ "result_text": "agent-initiated terminal body",
+ "settles_run": True,
+ }
diff --git a/tests/test_session_fork.py b/tests/test_session_fork.py
index 70b223627..a1492ca72 100644
--- a/tests/test_session_fork.py
+++ b/tests/test_session_fork.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import json
import sqlite3
+from datetime import datetime, timezone
from pathlib import Path
import pytest
@@ -24,8 +25,8 @@ from core.vibe_agents import VibeAgentStore
from modules.im import MessageContext
from storage.agent_session_rows import create_agent_session_row
from storage.db import create_sqlite_engine
-from storage import messages_service
-from storage.models import agent_runs, agent_sessions, scope_settings
+from storage import message_deliveries, messages_service
+from storage.models import agent_events, agent_runs, agent_sessions, messages, scope_settings
from storage.sessions_service import SQLiteSessionsService
from storage.settings_service import upsert_scope
@@ -84,6 +85,52 @@ def _seed_source_session(db_path: Path, tmp_path: Path, *, backend: str = "codex
engine.dispose()
+def _seed_started_delivery(conn, *, scope_id: str, session_id: str, text: str) -> str:
+ delivery_id = message_deliveries.new_delivery_id()
+ turn_id = message_deliveries.new_turn_id()
+ attempt_id = message_deliveries.new_attempt_id()
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=session_id,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text=text,
+ ),
+ dispatch_text=text,
+ )
+ claimed = message_deliveries.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend="codex",
+ deliveries=[delivery],
+ dispatch_text=text,
+ attempt_id=attempt_id,
+ )
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(claimed["turn"]["version"]),
+ runtime_key=f"runtime:{turn_id}",
+ runtime_turn_id=f"runtime-turn:{turn_id}",
+ native_turn_id=f"native:{turn_id}",
+ ) is not None
+ assert message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+ return turn_id
+
+
def test_reserve_forked_session_copies_row_and_applies_overrides(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
source_id = _seed_source_session(db_path, tmp_path)
@@ -1329,16 +1376,22 @@ def test_fork_source_state_ignores_operational_rows_after_anchor(
message_type="user",
text="do the long task",
)
- for message_type in ("queued", "pending", "draft", "notify"):
- messages_service.append(
- conn,
- scope_id=row["scope_id"],
- session_id=source_id,
- platform="avibe",
- author="agent",
- message_type=message_type,
- text=message_type,
- )
+ message_deliveries.enqueue_queued(
+ conn,
+ scope_id=row["scope_id"],
+ session_id=source_id,
+ text="queued",
+ )
+ message_deliveries.set_draft(conn, source_id, "draft")
+ messages_service.append(
+ conn,
+ scope_id=row["scope_id"],
+ session_id=source_id,
+ platform="avibe",
+ author="agent",
+ message_type="notify",
+ text="notify",
+ )
state = fork_source_state({"source_session_id": source_id, "source_message_id": user["id"]})
@@ -1511,9 +1564,7 @@ def test_fork_metadata_from_session_metadata_preserves_trim_fields() -> None:
def test_reserve_forked_session_silent_completion_is_terminal_no_trim(tmp_path: Path) -> None:
- """A codex/opencode source whose latest turn completed SILENTLY (the invisible
- ``silent`` marker follows its input + activity) is TERMINAL — the fork must not
- trim/roll back the completed turn as if it were still running."""
+ """A reply-less durable terminal snapshot prevents running-Turn trimming."""
db_path = tmp_path / "vibe.sqlite"
source_id = _seed_source_session(db_path, tmp_path) # agent_backend='codex'
engine = create_sqlite_engine(db_path)
@@ -1522,17 +1573,22 @@ def test_reserve_forked_session_silent_completion_is_terminal_no_trim(tmp_path:
scope_id = conn.execute(
select(agent_sessions.c.scope_id).where(agent_sessions.c.id == source_id)
).mappings().one()["scope_id"]
- messages_service.append(
- conn, scope_id=scope_id, session_id=source_id, platform="avibe",
- author="user", message_type="user", text="do the thing",
+ turn_id = _seed_started_delivery(
+ conn,
+ scope_id=scope_id,
+ session_id=source_id,
+ text="do the thing",
)
messages_service.append(
conn, scope_id=scope_id, session_id=source_id, platform="avibe",
author="agent", message_type="assistant", text="working",
)
- messages_service.append(
- conn, scope_id=scope_id, session_id=source_id, platform="avibe",
- author="agent", message_type=messages_service.SILENT_TYPE, text="",
+ message_deliveries.terminalize_turn(
+ conn,
+ turn_id,
+ outcome="completed",
+ settled_by="terminal_result",
+ evidence_kind="test_replyless_completion",
)
finally:
engine.dispose()
@@ -1542,6 +1598,366 @@ def test_reserve_forked_session_silent_completion_is_terminal_no_trim(tmp_path:
assert result.fork.trim_latest_running_turn is False
+def test_not_written_successor_does_not_mask_accepted_source_turn(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ source_id = _seed_source_session(db_path, tmp_path)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ scope_id = conn.execute(
+ select(agent_sessions.c.scope_id).where(agent_sessions.c.id == source_id)
+ ).scalar_one()
+ turn_id = _seed_started_delivery(
+ conn,
+ scope_id=scope_id,
+ session_id=source_id,
+ text="keep working",
+ )
+ successor_id = message_deliveries.new_delivery_id()
+ successor_turn_id = message_deliveries.new_turn_id()
+ successor = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=successor_id,
+ session_id=source_id,
+ priority="p0",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=source_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="replacement",
+ ),
+ dispatch_text="replacement",
+ )
+ message_deliveries.insert_turn(
+ conn,
+ turn_id=successor_turn_id,
+ session_id=source_id,
+ initial_delivery_id=successor_id,
+ state="waiting",
+ backend="codex",
+ )
+ assert message_deliveries.cas_delivery(
+ conn,
+ successor_id,
+ expected_version=int(successor["version"]),
+ expected_states=("reserved",),
+ values={
+ "state": "interrupt_waiting",
+ "turn_id": successor_turn_id,
+ "turn_role": "initial",
+ "turn_position": 0,
+ },
+ ) is not None
+ message_deliveries.terminalize_turn(
+ conn,
+ successor_turn_id,
+ outcome="not_written",
+ settled_by="definitive_stop_receipt",
+ evidence_kind="stop_refused",
+ )
+ finally:
+ engine.dispose()
+
+ result = reserve_forked_session(source_session_id=source_id, db_path=db_path)
+
+ assert result.fork.trim_latest_running_turn is True
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ message_deliveries.terminalize_turn(
+ conn,
+ turn_id,
+ outcome="completed",
+ settled_by="terminal_result",
+ evidence_kind="replyless_completion",
+ )
+ finally:
+ engine.dispose()
+
+ completed = reserve_forked_session(source_session_id=source_id, db_path=db_path)
+
+ assert completed.fork.trim_latest_running_turn is False
+
+
+def test_fork_anchor_uses_active_turn_initial_delivery_before_transcript_order(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ source_id = _seed_source_session(db_path, tmp_path)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ scope_id = conn.execute(
+ select(agent_sessions.c.scope_id).where(agent_sessions.c.id == source_id)
+ ).scalar_one()
+ previous_result = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=source_id,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="previous result persisted after the queued submission",
+ )
+ conn.execute(
+ messages.update()
+ .where(messages.c.id == previous_result["id"])
+ .values(
+ created_at="2026-08-01T00:02:00Z",
+ updated_at="2026-08-01T00:02:00Z",
+ )
+ )
+ delivery_id = message_deliveries.new_delivery_id()
+ turn_id = message_deliveries.new_turn_id()
+ attempt_id = message_deliveries.new_attempt_id()
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=source_id,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=source_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="queued before the previous result",
+ ),
+ dispatch_text="queued before the previous result",
+ now="2026-08-01T00:01:00Z",
+ )
+ claimed = message_deliveries.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=source_id,
+ backend="codex",
+ deliveries=[delivery],
+ dispatch_text="queued before the previous result",
+ attempt_id=attempt_id,
+ )
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(claimed["turn"]["version"]),
+ runtime_key="runtime",
+ runtime_turn_id="runtime-turn",
+ native_turn_id="native-turn",
+ ) is not None
+ assert message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "delayed_start_acceptance"},
+ )
+ finally:
+ engine.dispose()
+
+ result = reserve_forked_session(source_session_id=source_id, db_path=db_path)
+
+ assert result.fork.source_message_id == delivery_id
+ assert result.fork.trim_latest_running_turn is True
+
+
[email protected]("start_receipt", ["unwritten", "unknown"])
+def test_fork_anchor_treats_pre_materialization_start_as_running(
+ tmp_path: Path,
+ start_receipt: str,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ source_id = _seed_source_session(db_path, tmp_path)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ scope_id = conn.execute(
+ select(agent_sessions.c.scope_id).where(agent_sessions.c.id == source_id)
+ ).scalar_one()
+ previous_result = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=source_id,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="previous terminal boundary",
+ )
+ delivery_id = message_deliveries.new_delivery_id()
+ turn_id = message_deliveries.new_turn_id()
+ attempt_id = message_deliveries.new_attempt_id()
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=source_id,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=source_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="possibly written native input",
+ ),
+ dispatch_text="possibly written native input",
+ )
+ claimed = message_deliveries.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=source_id,
+ backend="codex",
+ deliveries=[delivery],
+ dispatch_text="possibly written native input",
+ attempt_id=attempt_id,
+ )
+ if start_receipt == "unknown":
+ assert message_deliveries.mark_start_unknown(
+ conn,
+ turn_id,
+ expected_version=int(claimed["turn"]["version"]),
+ receipt={"reason": "restart_without_native_evidence"},
+ ) is not None
+ finally:
+ engine.dispose()
+
+ result = reserve_forked_session(source_session_id=source_id, db_path=db_path)
+
+ assert result.fork.source_message_id == previous_result["id"]
+ assert result.fork.trim_latest_running_turn is True
+
+
+def test_reserve_forked_session_migrated_silent_completion_is_terminal_no_trim(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A migrated legacy silent event remains a terminal fork boundary."""
+
+ db_path = tmp_path / "vibe.sqlite"
+ source_id = _seed_source_session(db_path, tmp_path)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ scope_id = conn.execute(
+ select(agent_sessions.c.scope_id).where(agent_sessions.c.id == source_id)
+ ).scalar_one()
+ message_micros = int(
+ datetime(2026, 8, 1, tzinfo=timezone.utc).timestamp() * 1_000_000
+ )
+ monkeypatch.setattr(
+ messages_service,
+ "_new_message_id",
+ lambda: f"msg_{message_micros:015x}{'0' * 8}",
+ )
+ message = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=source_id,
+ platform="avibe",
+ author="user",
+ message_type="user",
+ text="latest completed input",
+ )
+ conn.execute(
+ messages.update()
+ .where(messages.c.id == message["id"])
+ .values(
+ created_at="2026-08-01T00:00:00Z",
+ updated_at="2026-08-01T00:00:00Z",
+ )
+ )
+ conn.execute(
+ agent_events.insert().values(
+ id="evt_legacy_silent_fork_boundary",
+ scope_id=scope_id,
+ session_id=source_id,
+ turn_id=None,
+ run_id=None,
+ platform="avibe",
+ agent_name="worker",
+ backend="codex",
+ event_type="silent_terminal",
+ visibility="trace",
+ sequence=None,
+ content_text=None,
+ content_json="{}",
+ metadata_json=json.dumps(
+ {
+ "legacy_message_id": "msg_legacy_silent",
+ "migration_revision": "20260731_0043",
+ }
+ ),
+ source="agent",
+ created_at="2026-08-01T00:00:01Z",
+ updated_at="2026-08-01T00:00:01Z",
+ )
+ )
+ finally:
+ engine.dispose()
+
+ result = reserve_forked_session(source_session_id=source_id, db_path=db_path)
+
+ assert result.fork.trim_latest_running_turn is False
+
+
+def test_earlier_same_second_silent_terminal_does_not_close_latest_input(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ source_id = _seed_source_session(db_path, tmp_path)
+ engine = create_sqlite_engine(db_path)
+ base = 1_800_000_000_000_000
+ timestamp = "2026-08-01T00:00:00Z"
+ try:
+ with engine.begin() as conn:
+ scope_id = conn.execute(
+ select(agent_sessions.c.scope_id).where(
+ agent_sessions.c.id == source_id
+ )
+ ).scalar_one()
+ conn.execute(
+ agent_events.insert().values(
+ id=f"evt_{base + 1_000:015x}{'0' * 8}",
+ scope_id=scope_id,
+ session_id=source_id,
+ platform="avibe",
+ event_type="silent_terminal",
+ visibility="trace",
+ content_json="{}",
+ metadata_json="{}",
+ source="agent",
+ created_at=timestamp,
+ updated_at=timestamp,
+ )
+ )
+ conn.execute(
+ messages.insert().values(
+ id=f"msg_{base + 2_000:015x}{'0' * 8}",
+ scope_id=scope_id,
+ session_id=source_id,
+ platform="avibe",
+ author="user",
+ type="user",
+ source="user",
+ content_text="new still-running input",
+ content_json="{}",
+ metadata_json="{}",
+ created_at=timestamp,
+ updated_at=timestamp,
+ )
+ )
+ finally:
+ engine.dispose()
+
+ result = reserve_forked_session(source_session_id=source_id, db_path=db_path)
+
+ assert result.fork.trim_latest_running_turn is True
+
+
def test_forking_an_inherited_null_session_keeps_its_explicit_pins(
tmp_path: Path, monkeypatch
) -> None:
diff --git a/tests/test_show_git.py b/tests/test_show_git.py
index 36ee84739..31210d5e4 100644
--- a/tests/test_show_git.py
+++ b/tests/test_show_git.py
@@ -511,8 +511,9 @@ def test_turn_event_subscriber_uses_storage_context_without_payload_changes(reso
bus = InboxEventBus()
service.start(bus)
- bus.publish("turn.start", {"session_id": session_id})
- bus.publish("turn.end", {"session_id": session_id})
+ event = {"session_id": session_id, "turn_id": "turn-current"}
+ bus.publish("turn.start", event)
+ bus.publish("turn.end", event)
service.stop()
bus.publish("turn.end", {"session_id": session_id})
@@ -520,9 +521,10 @@ def test_turn_event_subscriber_uses_storage_context_without_payload_changes(reso
(PRE_TURN, {"run_id": "run-event"}),
(POST_TURN, {"message": "driving user message", "run_id": "run-event"}),
]
- assert lookups[0] == (session_id, {})
- assert lookups[1][0] == session_id
- assert set(lookups[1][1]) == {"after"}
+ assert lookups == [
+ (session_id, {"turn_id": "turn-current"}),
+ (session_id, {"turn_id": "turn-current"}),
+ ]
def test_turn_event_subscriber_keeps_start_message_when_next_pending_can_arrive(resolved_git, monkeypatch):
@@ -699,8 +701,8 @@ def test_agent_initiated_turn_reuses_fsm_bus_lifecycle(resolved_git, monkeypatch
service.stop()
assert lifecycle == [
- ("turn.start", {"session_id": session_id}),
- ("turn.end", {"session_id": session_id}),
+ ("turn.start", {"session_id": session_id, "turn_id": "turn-agent"}),
+ ("turn.end", {"session_id": session_id, "turn_id": "turn-agent"}),
]
assert calls == [
(PRE_TURN, {"run_id": None}),
@@ -760,7 +762,7 @@ def test_storage_lookup_uses_turn_boundary_instead_of_later_pending_message():
from storage import messages_service
from storage.db import get_cached_sqlite_engine
from storage.importer import ensure_sqlite_state
- from storage.models import agent_sessions, messages
+ from storage.models import agent_sessions, messages, session_turns
from storage.settings_service import upsert_scope
ensure_sqlite_state(primary_platform="avibe")
@@ -812,30 +814,73 @@ def test_storage_lookup_uses_turn_boundary_instead_of_later_pending_message():
assert show_git.load_turn_checkpoint_context(session_id) == TurnCheckpointContext()
with get_cached_sqlite_engine().begin() as conn:
- current = messages_service.append(
+ from storage import message_deliveries
+
+ current = message_deliveries.insert_delivery(
conn,
- scope_id=scope_id,
+ delivery_id=message_deliveries.new_delivery_id(),
session_id=session_id,
- platform="avibe",
- author="user",
- message_type="user",
- text="current driving message",
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ text="current driving message",
+ ),
+ dispatch_text="current driving message",
+ now="2099-01-01T00:00:01+00:00",
)
- later = messages_service.append(
+ message_deliveries.claim_start_batch(
conn,
- scope_id=scope_id,
+ turn_id="turn_storage_boundary",
session_id=session_id,
- platform="avibe",
- author="user",
- message_type="pending",
- text="later pending message",
+ backend="codex",
+ deliveries=[current],
+ dispatch_text="current driving message",
)
- conn.execute(update(messages).where(messages.c.id == current["id"]).values(created_at="2099-01-01T00:00:01+00:00"))
- conn.execute(update(messages).where(messages.c.id == later["id"]).values(created_at="2099-01-01T00:00:02+00:00"))
+ conn.execute(
+ update(session_turns)
+ .where(session_turns.c.id == "turn_storage_boundary")
+ .values(
+ created_at="2099-01-01T00:00:01+00:00",
+ started_at="2099-01-01T00:00:01+00:00",
+ )
+ )
+ later = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=message_deliveries.new_delivery_id(),
+ session_id=session_id,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ text="later pending message",
+ ),
+ dispatch_text="later pending message",
+ now="2099-01-01T00:00:02+00:00",
+ )
+ assert later["message_id"] is None
+ current_context = show_git.load_turn_checkpoint_context(session_id)
+ assert current_context.message == "current driving message"
+ assert current_context.message_id == current["id"]
context = show_git.load_turn_checkpoint_context(session_id, after="2099-01-01T00:00:00+00:00")
assert context.message == "current driving message"
assert context.message_id == current["id"]
+ exact_context = show_git.load_turn_checkpoint_context(
+ session_id,
+ turn_id="turn_storage_boundary",
+ after="2100-01-01T00:00:00+00:00",
+ )
+ assert exact_context.message == "current driving message"
+ assert exact_context.turn_id == "turn_storage_boundary"
def test_storage_lookup_includes_harness_driving_message():
diff --git a/tests/test_show_git_turn_entrypoints.py b/tests/test_show_git_turn_entrypoints.py
index 84f81c4b3..8df86c27e 100644
--- a/tests/test_show_git_turn_entrypoints.py
+++ b/tests/test_show_git_turn_entrypoints.py
@@ -20,7 +20,10 @@ from core.session_turns import SessionTurnManager, emit_matches_active_turn
from core.show_git import POST_TURN, PRE_TURN, ShowGitCheckpointService, TurnCheckpointContext
from modules.agents.service import AgentService
from modules.im import MessageContext
+from storage.agent_session_rows import create_agent_session_row
+from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
+from storage import message_deliveries
class _Settings:
@@ -211,6 +214,35 @@ def test_all_turn_entrypoints_reach_checkpoint_subscriber(monkeypatch, tmp_path)
"scheduled_task": _context("scheduled_task", platform="slack", trigger_kind="scheduled"),
"watch_callback": _context("watch_callback", platform="slack", trigger_kind="watch"),
}
+ engine = create_sqlite_engine()
+ show_delivery_id = "msg_show_page"
+ with engine.begin() as conn:
+ for context in contexts.values():
+ create_agent_session_row(
+ conn,
+ session_id=context.platform_specific["agent_session_id"],
+ scope_id=None,
+ session_anchor=None,
+ agent_backend="claude",
+ agent_variant="claude",
+ workdir=str(tmp_path),
+ )
+ message_deliveries.insert_delivery(
+ conn,
+ delivery_id=show_delivery_id,
+ session_id="ses_show_page",
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=None,
+ session_id="ses_show_page",
+ platform="avibe",
+ author="user",
+ source="user",
+ text="edit show page",
+ ),
+ dispatch_text="edit show page",
+ )
checkpoint_calls = defaultdict(list)
class _Repository:
@@ -279,7 +311,11 @@ def test_all_turn_entrypoints_reach_checkpoint_subscriber(monkeypatch, tmp_path)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
response = await client.post(
"/internal/dispatch_async",
- json={"session_id": "ses_show_page", "entrypoint": "show_page"},
+ json={
+ "session_id": "ses_show_page",
+ "user_message_id": show_delivery_id,
+ "entrypoint": "show_page",
+ },
)
assert response.status_code == 202
for _ in range(100):
@@ -316,14 +352,14 @@ def test_all_turn_entrypoints_reach_checkpoint_subscriber(monkeypatch, tmp_path)
bus.unsubscribe(subscription_id)
service.stop()
- expected_lifecycle = []
- for name, context in contexts.items():
+ assert len(lifecycle) == len(contexts) * 2
+ for index, (name, context) in enumerate(contexts.items()):
session_id = context.platform_specific["agent_session_id"]
- expected_lifecycle.extend(
- [
- ("turn.start", {"session_id": session_id}),
- ("turn.end", {"session_id": session_id}),
- ]
- )
+ start_event, end_event = lifecycle[index * 2 : index * 2 + 2]
+ assert start_event[0] == "turn.start", name
+ assert end_event[0] == "turn.end", name
+ assert start_event[1]["session_id"] == session_id, name
+ assert end_event[1]["session_id"] == session_id, name
+ assert start_event[1].get("turn_id"), name
+ assert end_event[1].get("turn_id") == start_event[1]["turn_id"], name
assert checkpoint_calls[session_id] == [PRE_TURN, POST_TURN], name
- assert lifecycle == expected_lifecycle
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 59855dfdf..f84a4a0a1 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -3293,7 +3293,7 @@ def test_show_event_cli_timeout_poll_reuses_one_event_store(monkeypatch):
class FakeStore:
def __init__(self):
- self.message_types = iter(("pending", "harness"))
+ self.delivery_states = iter(("reserved", "accepted"))
self.closed = False
instances.append(self)
@@ -3301,10 +3301,10 @@ def test_show_event_cli_timeout_poll_reuses_one_event_store(monkeypatch):
return {
"id": event_id,
"session_id": session_id,
- "message": {
+ "delivery": {
"id": "msg_poll_once",
"session_id": session_id,
- "type": next(self.message_types),
+ "state": next(self.delivery_states),
},
}
@@ -3323,10 +3323,10 @@ def test_show_event_cli_timeout_poll_reuses_one_event_store(monkeypatch):
assert resolved == {
"id": "show_evt_poll_once",
"session_id": "ses123",
- "message": {
+ "delivery": {
"id": "msg_poll_once",
"session_id": "ses123",
- "type": "harness",
+ "state": "accepted",
},
}
assert len(instances) == 1
@@ -3387,7 +3387,7 @@ def test_show_event_cli_pending_timeout_allows_same_reservation_retry(monkeypatc
return {
"id": event_id,
"session_id": session_id,
- "message": {"id": "msg_pending", "type": "pending"},
+ "delivery": {"id": "msg_pending", "state": "reserved"},
}
def close(self):
@@ -3405,6 +3405,29 @@ def test_show_event_cli_pending_timeout_allows_same_reservation_retry(monkeypatc
assert resolved is None
+def test_show_event_cli_retired_delivery_is_not_reported_as_accepted(monkeypatch):
+ class FakeStore:
+ def get_event(self, session_id, event_id):
+ return {
+ "id": event_id,
+ "session_id": session_id,
+ "delivery": {"id": "msg_retired", "state": "retired"},
+ }
+
+ def close(self):
+ return None
+
+ monkeypatch.setattr("core.show_session_events.ShowSessionEventStore", FakeStore)
+
+ resolved = cli._resolve_show_event_after_ambiguous_live_timeout(
+ "ses123",
+ {"id": "show_evt_retired"},
+ wait_seconds=1,
+ )
+
+ assert resolved is None
+
+
def test_show_event_cli_http_502_replays_same_event_identity_locally(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
diff --git a/tests/test_show_session_events.py b/tests/test_show_session_events.py
index 4e8784114..928fc45df 100644
--- a/tests/test_show_session_events.py
+++ b/tests/test_show_session_events.py
@@ -24,6 +24,7 @@ from core.show_session_events import (
localized_show_event_error,
show_event_requests_dispatch,
)
+from storage import message_deliveries
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_sessions, media_objects, messages, show_session_events
@@ -69,6 +70,45 @@ def _seed_session(session_id: str = "ses_mark") -> str:
return scope_id
+def _accept_delivery(payload: dict[str, object]) -> None:
+ with create_sqlite_engine().begin() as conn:
+ delivery_id = str(payload["user_message_id"])
+ delivery = message_deliveries.get_delivery(conn, delivery_id)
+ assert delivery is not None
+ turn_id = message_deliveries.new_turn_id()
+ message_deliveries.insert_turn(
+ conn,
+ turn_id=turn_id,
+ session_id=delivery["session_id"],
+ initial_delivery_id=delivery_id,
+ state="starting",
+ backend="codex",
+ )
+ attempt_id = message_deliveries.new_attempt_id()
+ assert message_deliveries.open_start_attempt(
+ conn,
+ delivery_id,
+ expected_version=delivery["version"],
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ )
+ turn = message_deliveries.get_turn(conn, turn_id)
+ assert turn is not None
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ runtime_key=f"runtime:{turn_id}",
+ runtime_turn_id=f"runtime-turn:{turn_id}",
+ native_turn_id=f"native:{turn_id}",
+ ) is not None
+ assert message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+
+
def _png_bytes(width: int, height: int) -> bytes:
def chunk(kind: bytes, data: bytes) -> bytes:
checksum = zlib.crc32(kind + data) & 0xFFFFFFFF
@@ -906,10 +946,13 @@ def test_show_event_store_records_intent_dispatch_payload(isolated_state):
assert event["payload"]["dispatch"] is True
assert "[show-intent] choose" in event["transcript_text"]
assert "Pick B." in event["transcript_text"]
- assert event["message"]["author"] == "harness"
- assert event["message"]["source"] == "harness"
- assert event["message"]["author_name"] == "show_intent"
- assert event["message"]["author_id"] == event["id"]
+ assert event["message"] is None
+ assert event["message_id"] is None
+ assert event["delivery"]["state"] == "reserved"
+ assert event["delivery"]["author"] == "harness"
+ assert event["delivery"]["source"] == "harness"
+ assert event["delivery"]["author_name"] == "show_intent"
+ assert event["delivery"]["author_id"] == event["id"]
def test_show_trigger_kind_is_closed_over_dispatching_event_types():
@@ -1305,7 +1348,7 @@ def test_show_event_store_lists_after_cursor(isolated_state):
assert [event["id"] for event in page["events"]] == [second["id"]]
-def test_dispatching_show_event_reserves_pending_transcript_row(isolated_state):
+def test_dispatching_show_event_reserves_delivery_outside_transcript(isolated_state):
from storage import messages_service
_seed_session("ses_show")
@@ -1329,11 +1372,13 @@ def test_dispatching_show_event_reserves_pending_transcript_row(isolated_state):
finally:
store.close()
- assert dispatching["message"]["type"] == messages_service.PENDING_TYPE
- assert dispatching["message"]["author"] == messages_service.HARNESS_TYPE
- assert dispatching["message"]["source"] == messages_service.HARNESS_TYPE
- assert dispatching["message"]["author_name"] == "show_annotation"
- assert dispatching["message"]["author_id"] == dispatching["id"]
+ assert dispatching["message"] is None
+ assert dispatching["message_id"] is None
+ assert dispatching["delivery"]["state"] == "reserved"
+ assert dispatching["delivery"]["author"] == messages_service.HARNESS_TYPE
+ assert dispatching["delivery"]["source"] == messages_service.HARNESS_TYPE
+ assert dispatching["delivery"]["author_name"] == "show_annotation"
+ assert dispatching["delivery"]["author_id"] == dispatching["id"]
assert non_dispatching["message"]["type"] == messages_service.ANNOTATION_TYPE
engine = create_sqlite_engine()
with engine.connect() as conn:
@@ -1344,14 +1389,12 @@ def test_dispatching_show_event_reserves_pending_transcript_row(isolated_state):
types=messages_service.TRANSCRIPT_TYPES,
tail=True,
)
- queued = messages_service.list_queued(conn, "ses_show")
+ queued = message_deliveries.list_queued(conn, "ses_show")
assert [message["text"] for message in visible["messages"]] == [non_dispatching["transcript_text"]]
assert queued == []
-def test_dispatching_show_event_retry_reuses_event_and_transcript_row(isolated_state):
- from storage import messages_service
-
+def test_dispatching_show_event_retry_reuses_event_and_delivery(isolated_state):
_seed_session("ses_show_retry")
payload = {
"id": "show_evt_retry_identity",
@@ -1370,8 +1413,9 @@ def test_dispatching_show_event_retry_reuses_event_and_transcript_row(isolated_s
store.close()
assert replay["id"] == first["id"]
- assert replay["message_id"] == first["message_id"]
- assert replay["message"]["type"] == messages_service.PENDING_TYPE
+ assert replay["message_id"] is None
+ assert replay["delivery_id"] == first["delivery_id"]
+ assert replay["delivery"]["state"] == "reserved"
engine = create_sqlite_engine()
with engine.connect() as conn:
event_rows = conn.execute(
@@ -1384,8 +1428,13 @@ def test_dispatching_show_event_retry_reuses_event_and_transcript_row(isolated_s
messages.c.native_message_id == "show:show_evt_retry_identity"
)
).mappings().all()
+ delivery_row = message_deliveries.get_delivery_by_dedupe(
+ conn,
+ "show:show_evt_retry_identity",
+ )
assert len(event_rows) == 1
- assert len(message_rows) == 1
+ assert len(message_rows) == 0
+ assert delivery_row is not None
def test_show_event_store_rejects_reused_id_with_different_contents(isolated_state):
@@ -1472,9 +1521,7 @@ def test_localized_show_event_errors_follow_configured_language(
assert str(pending) == "Show 事件可能仍在处理中,未在本地重复提交。"
-def test_direct_dispatching_show_event_is_visible_annotation_input(isolated_state):
- from storage import messages_service
-
+def test_direct_dispatching_show_event_requires_acceptance_before_visibility(isolated_state):
_seed_session("ses_show")
store = ShowSessionEventStore()
try:
@@ -1493,19 +1540,17 @@ def test_direct_dispatching_show_event_is_visible_annotation_input(isolated_stat
finally:
store.close()
- assert event["message"]["type"] == messages_service.ANNOTATION_TYPE
- assert event["message"]["author"] == messages_service.HARNESS_TYPE
- assert event["message"]["source"] == messages_service.HARNESS_TYPE
+ assert event["message"] is None
+ assert event["delivery"]["state"] == "reserved"
assert [item["id"] for item in events["events"]] == [event["id"]]
with create_sqlite_engine().connect() as conn:
- assert messages_service.list_queued(conn, "ses_show") == []
+ assert message_deliveries.list_queued(conn, "ses_show") == []
-def test_startup_repairs_stranded_pending_rows_by_origin(isolated_state):
- from storage import messages_service
+def test_startup_leaves_reserved_show_delivery_outside_transcript(isolated_state):
from vibe import ui_server
- scope_id = _seed_session("ses_show_restart")
+ _seed_session("ses_show_restart")
store = ShowSessionEventStore()
try:
show_event = store.append(
@@ -1523,38 +1568,22 @@ def test_startup_repairs_stranded_pending_rows_by_origin(isolated_state):
finally:
store.close()
- with create_sqlite_engine().begin() as conn:
- chat_message = messages_service.append(
- conn,
- scope_id=scope_id,
- session_id="ses_show_restart",
- platform="avibe",
- author="user",
- source="user",
- message_type=messages_service.PENDING_TYPE,
- text="Recover my chat prompt after restart.",
- )
-
- # Ordinary Chat becomes visible. Harness-owned Show input stays retryable
- # because startup has no queue drain that owns it.
- summary = ui_server._recover_stale_pending_messages()
- assert summary == {"promoted": 1, "deleted": 0, "skipped": 1}
+ assert not hasattr(ui_server, "_recover_stale_pending_messages")
with create_sqlite_engine().connect() as conn:
- repaired = {
- row["id"]: row
- for row in messages_service.list_session_messages(
- conn,
- session_id="ses_show_restart",
- limit=50,
- types=messages_service.TRANSCRIPT_TYPES,
- tail=True,
- )["messages"]
- }
- queued = messages_service.list_queued(conn, "ses_show_restart")
- assert repaired[chat_message["id"]]["type"] == "user"
- assert repaired[chat_message["id"]]["author"] == "user"
- assert show_event["message_id"] not in repaired
+ from storage import messages_service
+
+ visible = messages_service.list_session_messages(
+ conn,
+ session_id="ses_show_restart",
+ limit=50,
+ types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
+ )["messages"]
+ reserved = message_deliveries.get_delivery(conn, show_event["delivery_id"])
+ queued = message_deliveries.list_queued(conn, "ses_show_restart")
+ assert visible == []
+ assert reserved is not None and reserved["state"] == "reserved"
assert queued == []
store = ShowSessionEventStore()
@@ -1563,10 +1592,10 @@ def test_startup_repairs_stranded_pending_rows_by_origin(isolated_state):
finally:
store.close()
assert retryable is not None
- assert retryable["message"]["type"] == messages_service.PENDING_TYPE
- assert retryable["message"]["metadata"][
- messages_service.QUEUED_DISPATCH_TEXT_KEY
- ].startswith("[show-annotation] comment")
+ assert retryable["message"] is None
+ assert retryable["delivery"]["dispatch_text"].startswith(
+ "[show-annotation] comment"
+ )
def test_record_local_show_event_uses_synchronous_unified_entry(
@@ -1584,6 +1613,7 @@ def test_record_local_show_event_uses_synchronous_unified_entry(
async def fake_dispatch_async(payload, **_kwargs):
dispatches.append(payload)
+ _accept_delivery(payload)
return {"status_code": 202, "body": {"ok": True}}
monkeypatch.setattr(internal_client, "dispatch_async", fake_dispatch_async)
@@ -1604,21 +1634,14 @@ def test_record_local_show_event_uses_synchronous_unified_entry(
"[show-annotation] comment\n\nDeliver this."
)
assert f"Show event id: {event['id']}" in dispatches[0]["text"]
- assert (
- messages_service.QUEUED_DISPATCH_TEXT_KEY
- not in event["message"]["metadata"]
- )
+ assert event["delivery"]["state"] == "accepted"
+ assert event["delivery"]["dispatch_text"] == ""
assert "dispatch_owner" not in dispatches[0]
assert event["message"]["type"] == "annotation"
- assert [name for name, _data in published] == [
- "show.event",
- "message.new",
- "session.activity",
- ]
- assert published[1][1]["id"] == event["message_id"]
+ assert [name for name, _data in published] == ["show.event"]
-def test_failed_local_show_dispatch_keeps_row_pending_so_replay_retries(
+def test_definitive_local_show_dispatch_failure_retires_without_replay(
isolated_state,
monkeypatch,
):
@@ -1633,6 +1656,7 @@ def test_failed_local_show_dispatch_keeps_row_pending_so_replay_retries(
attempts += 1
if attempts == 1:
raise internal_client.InternalServerUnavailable("controller unavailable")
+ _accept_delivery(_payload)
return {"status_code": 202, "body": {"ok": True}}
monkeypatch.setattr(internal_client, "dispatch_async", fake_dispatch_async)
@@ -1659,19 +1683,19 @@ def test_failed_local_show_dispatch_keeps_row_pending_so_replay_retries(
)
assert stranded["messages"] == []
- replay = ui_server.record_local_show_event("ses_show", payload)
+ store = ui_server._show_session_event_store()
+ try:
+ failed_event = store.get_event("ses_show", "show_evt_failed_once")
+ finally:
+ store.close()
+ assert failed_event is not None
+ assert failed_event["delivery"]["state"] == "retired"
- assert attempts == 2
- assert replay["message"]["type"] == messages_service.ANNOTATION_TYPE
- with create_sqlite_engine().connect() as conn:
- visible = messages_service.list_session_messages(
- conn,
- session_id="ses_show",
- limit=50,
- types=messages_service.TRANSCRIPT_TYPES,
- tail=True,
- )
- assert [row["id"] for row in visible["messages"]] == [replay["message_id"]]
+ with pytest.raises(ShowSessionEventError) as replay_error:
+ ui_server.record_local_show_event("ses_show", payload)
+
+ assert replay_error.value.code == "show_event_dispatch_failed"
+ assert attempts == 1
def test_ambiguous_local_show_dispatch_replays_under_the_same_reservation(
@@ -1688,6 +1712,7 @@ def test_ambiguous_local_show_dispatch_replays_under_the_same_reservation(
seen_message_ids.append(dispatch_payload["user_message_id"])
if len(seen_message_ids) == 1:
raise internal_client.InternalServerTimeout("acceptance unknown")
+ _accept_delivery(dispatch_payload)
return {"status_code": 202, "body": {"ok": True, "duplicate": True}}
monkeypatch.setattr(internal_client, "dispatch_async", fake_dispatch_async)
@@ -1750,163 +1775,36 @@ def test_annotation_dispatch_text_adds_event_id_and_optional_reply_guidance(inte
assert dispatch_text.endswith(guidance)
-def test_annotation_builders_match_frozen_examples():
- from storage import messages_service
-
- # This docs fixture is the single authoritative row copy shared by both lanes.
- fixture_path = (
- Path(__file__).parents[1]
- / "docs/plans/show-annotation-message-type/examples.json"
- )
- fixture = json.loads(fixture_path.read_text(encoding="utf-8"))
- frozen_fields = fixture["_frozen_fields"]
- frozen_rows = [
- example["row"]
- for example in fixture["examples"]
- ]
-
- forward = frozen_rows[0]
- forward_anchor = {
- "selector": forward["metadata"]["anchor_selector"],
- "text": forward["content"]["annotation"]["quote"],
- }
- forward_payload = {
- "scope": forward["metadata"]["show_event_scope"],
- "intent": "comment",
- "comment": forward["text"],
- "primaryAnchor": forward["metadata"]["anchor_kind"],
- }
-
- queued = frozen_rows[1]
- queued_attachment = queued["content"]["attachments"][0]
- queued_dispatch = queued["metadata"][messages_service.QUEUED_DISPATCH_TEXT_KEY]
- screenshot_line = next(
- line for line in queued_dispatch.splitlines() if line.startswith("Screenshot: ")
- )
- assert screenshot_line == (
- "Screenshot: state/media/med_9a71c33f8b2e.png (1240x620)"
- )
- origin_x, origin_y, dimensions = queued["metadata"]["screenshot_region"].split(
- ", "
- )
- width, height = dimensions.split("x", 1)
- screenshot_region = {
- "x": int(origin_x.removeprefix("x:")),
- "y": int(origin_y.removeprefix("y:")),
- "width": int(width),
- "height": int(height),
- }
- queued_payload = {
- "scope": queued["metadata"]["show_event_scope"],
+def test_annotation_display_and_dispatch_text_are_independent_facts():
+ payload = {
"intent": "comment",
- "comment": queued["text"],
- "primaryAnchor": queued["metadata"]["anchor_kind"],
+ "comment": "Review the selected region.",
+ "primaryAnchor": "screenshot",
"screenshot": {
- "attachmentId": queued_attachment["url"].removeprefix("/api/media/"),
+ "attachmentId": "med_9a71c33f8b2e",
"path": "state/media/med_9a71c33f8b2e.png",
- "mimeType": queued_attachment["mime"],
- "width": queued_attachment["width"],
- "height": queued_attachment["height"],
- "region": screenshot_region,
+ "mimeType": "image/png",
+ "width": 1240,
+ "height": 620,
+ "region": {"x": 20, "y": 30, "width": 400, "height": 180},
},
}
+ display_text = _format_transcript_text(
+ "human.annotation.created",
+ payload,
+ {},
+ )
+ dispatch_text = _format_dispatch_text(
+ "human.annotation.created",
+ payload,
+ {},
+ event_id="show_evt_strict_delivery",
+ )
- produced_rows = [
- {
- "type": messages_service.ANNOTATION_TYPE,
- "author": messages_service.HARNESS_TYPE,
- "content": {
- "text": _format_transcript_text(
- forward["metadata"]["show_event_type"],
- forward_payload,
- forward_anchor,
- ),
- "annotation": _annotation_display(
- forward["metadata"]["show_event_type"],
- forward_anchor,
- ),
- },
- "metadata": {
- messages_service.QUEUED_DISPATCH_TEXT_KEY: _format_dispatch_text(
- forward["metadata"]["show_event_type"],
- forward_payload,
- forward_anchor,
- event_id=forward["metadata"]["show_event_id"],
- )
- },
- },
- {
- "type": messages_service.QUEUED_TYPE,
- "author": messages_service.HARNESS_TYPE,
- "content": {
- "text": _format_transcript_text(
- queued["metadata"]["show_event_type"],
- queued_payload,
- {},
- ),
- "annotation": _annotation_display(
- queued["metadata"]["show_event_type"],
- {},
- ),
- "attachments": _annotation_attachments(queued_payload),
- },
- "metadata": {
- messages_service.QUEUED_DISPATCH_TEXT_KEY: _format_dispatch_text(
- queued["metadata"]["show_event_type"],
- queued_payload,
- {},
- event_id=queued["metadata"]["show_event_id"],
- )
- },
- },
- ]
-
- for frozen in frozen_rows[2:]:
- event_type = frozen["metadata"]["show_event_type"]
- quote = frozen["content"]["annotation"].get("quote")
- anchor = {"text": quote} if quote else {}
- produced_rows.append(
- {
- "type": messages_service.ANNOTATION_TYPE,
- "author": "agent",
- "content": {
- "text": _format_transcript_text(
- event_type,
- {"body": frozen["text"]},
- anchor,
- ),
- "annotation": _annotation_display(event_type, anchor),
- },
- "metadata": {},
- }
- )
-
- def frozen_value(row, path):
- current = row
- for part in path.split("."):
- if not isinstance(current, dict) or part not in current:
- return False, None
- current = current[part]
- return True, current
-
- assert frozen_fields == [
- "type",
- "author",
- "content.text",
- "content.annotation",
- "content.attachments",
- "metadata._queued_dispatch_text",
- ]
- for produced, frozen in zip(produced_rows, frozen_rows, strict=True):
- for field in frozen_fields:
- produced_present, produced_value = frozen_value(produced, field)
- frozen_present, frozen_value_at_path = frozen_value(frozen, field)
- assert produced_present is frozen_present, field
- if field == "metadata._queued_dispatch_text":
- # The prompt body is machine-only; its presence is the contract.
- continue
- assert produced_value == frozen_value_at_path, field
-
+ assert display_text == "Review the selected region."
+ assert display_text in dispatch_text
+ assert "Screenshot: state/media/med_9a71c33f8b2e.png (1240x620)" in dispatch_text
+ assert "Show event id: show_evt_strict_delivery" in dispatch_text
machine_markers = (
"[show-annotation]",
"Anchor kind:",
@@ -1917,10 +1815,4 @@ def test_annotation_builders_match_frozen_examples():
"Show event id:",
"vibe show reply",
)
- for produced in produced_rows[:2]:
- display_text = produced["content"]["text"]
- dispatch_text = produced["metadata"][
- messages_service.QUEUED_DISPATCH_TEXT_KEY
- ]
- assert display_text in dispatch_text
- assert all(marker not in display_text for marker in machine_markers)
+ assert all(marker not in display_text for marker in machine_markers)
diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.py
index 8288e9749..d3bb1e6b4 100644
--- a/tests/test_sqlite_sessions_store.py
+++ b/tests/test_sqlite_sessions_store.py
@@ -2581,6 +2581,112 @@ def test_sqlite_sessions_service_delete_agent_sessions_escapes_anchor_prefix(tmp
service.close()
+def test_new_session_teardown_archives_durable_history_and_releases_anchor(
+ tmp_path: Path,
+) -> None:
+ from storage import message_deliveries
+ from storage.models import agent_sessions, messages, session_turns
+
+ service = SQLiteSessionsService(tmp_path / "vibe.sqlite")
+ try:
+ session_id = service.bind_agent_session(
+ scope_key="slack::C_DELIVERY_PURGE",
+ agent_name="codex",
+ session_anchor="slack_delivery_purge",
+ native_session_id="native-delivery-purge",
+ )
+ assert session_id is not None
+ delivery_id = message_deliveries.new_delivery_id()
+ turn_id = message_deliveries.new_turn_id()
+ attempt_id = message_deliveries.new_attempt_id()
+ with service.engine.begin() as conn:
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=session_id,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=None,
+ session_id=session_id,
+ platform="slack",
+ author="user",
+ source="user",
+ text="accepted history",
+ ),
+ dispatch_text="accepted history",
+ )
+ message_deliveries.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend="codex",
+ deliveries=[delivery],
+ dispatch_text="accepted history",
+ attempt_id=attempt_id,
+ )
+ turn = message_deliveries.get_turn(conn, turn_id)
+ assert turn is not None
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ runtime_key=f"runtime:{turn_id}",
+ runtime_turn_id=f"runtime-turn:{turn_id}",
+ native_turn_id=f"native:{turn_id}",
+ ) is not None
+ assert message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "test"},
+ )
+ assert message_deliveries.terminalize_turn(
+ conn,
+ turn_id,
+ outcome="completed",
+ settled_by="test",
+ evidence_kind="test",
+ )["changed"]
+
+ assert service.delete_agent_sessions(
+ scope_key="slack::C_DELIVERY_PURGE",
+ agent_name="codex",
+ ) == 1
+ with service.engine.connect() as conn:
+ archived = conn.execute(
+ select(
+ agent_sessions.c.status,
+ agent_sessions.c.session_anchor,
+ ).where(agent_sessions.c.id == session_id)
+ ).one()
+ assert archived[0] == "archived"
+ assert ":superseded:" in archived[1]
+ assert conn.execute(
+ select(session_turns.c.id).where(session_turns.c.session_id == session_id)
+ ).all() == [(turn_id,)]
+ assert conn.execute(
+ select(message_deliveries.message_deliveries.c.id).where(
+ message_deliveries.message_deliveries.c.session_id == session_id
+ )
+ ).all() == [(delivery_id,)]
+ assert conn.execute(
+ select(messages.c.id, messages.c.session_id).where(
+ messages.c.id == delivery_id
+ )
+ ).one() == (delivery_id, session_id)
+
+ replacement = service.bind_agent_session(
+ scope_key="slack::C_DELIVERY_PURGE",
+ agent_name="codex",
+ session_anchor="slack_delivery_purge",
+ native_session_id="native-delivery-replacement",
+ )
+ assert replacement is not None
+ assert replacement != session_id
+ finally:
+ service.close()
+
+
def test_delete_agent_sessions_by_backend_removes_custom_variant_rows(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
service = SQLiteSessionsService(db_path)
@@ -4699,6 +4805,32 @@ _UPDATE_SESSION_FAST_PATH_SELECT = (
)
+def _block_competing_update_after(engine, db_path: Path, *, read: str, values: dict) -> dict:
+ state = {"fired": 0, "blocked": 0}
+
+ @event.listens_for(engine, "after_cursor_execute")
+ def _race(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ if state["fired"] or " ".join(statement.split()) != read:
+ return
+ state["fired"] += 1
+ other = create_sqlite_engine(db_path)
+ try:
+ try:
+ with other.begin() as other_conn:
+ other_conn.exec_driver_sql("PRAGMA busy_timeout = 1")
+ other_conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == values["id"])
+ .values(**{key: value for key, value in values.items() if key != "id"})
+ )
+ except OperationalError as exc:
+ state["blocked"] += int("database is locked" in str(exc))
+ finally:
+ other.dispose()
+
+ return state
+
+
def _seed_update_session_row(service: SQLiteSessionsService, tmp_path: Path, anchor: str) -> str:
with service.engine.begin() as conn:
scope_id = resolve_scope_from_legacy_key(
@@ -4719,126 +4851,80 @@ def _seed_update_session_row(service: SQLiteSessionsService, tmp_path: Path, anc
)
-def test_update_session_cannot_rename_a_session_archived_inside_its_window(
+def test_update_session_serializes_rename_before_archive(
tmp_path: Path,
) -> None:
- """HFR-280 — a Workbench PATCH loses to an archive that commits after its read.
-
- The production interleaving is the one round 5d of this PR already documented in
- the route: ``archive_session`` cannot cancel an in-flight chat turn inside its
- transaction, so the DELETE endpoint commits the archive FIRST and cancels
- best-effort afterwards. A stale tab's rename lands in exactly that window --
- ``ui_server.sessions_update``'s own ``is_session_archived`` pre-flight is a
- separate connection and an even wider window than this one.
-
- The bare-``id`` UPDATE this call emits (no backend change, so the backend-lock
- predicate is not added) is the same dangerous shape HFR-252's idempotent-re-bind
- half covers: nothing but the id, on a row another connection has just made
- terminal. Its ``status != 'archived'`` predicate is what refuses it, and the
- rowcount-0 branch is what turns that refusal into ``SessionArchivedError``
- instead of a bogus ``LookupError``.
- """
- from storage.workbench_sessions_service import SessionArchivedError, update_session
+ """HFR-280 — the writer reservation removes the read/archive/write window."""
+ from storage.workbench_sessions_service import update_session
db_path = tmp_path / "vibe.sqlite"
service = SQLiteSessionsService(db_path)
try:
session_id = _seed_update_session_row(service, tmp_path, "slack_C123:race_patch_rename")
- # The user archives the session the instant after the fast-path read said
- # "not archived".
- race = _commit_competing_bind_after(
+ archive_values = _archive_write(session_id)
+ race = _block_competing_update_after(
service.engine,
db_path,
read=_UPDATE_SESSION_FAST_PATH_SELECT,
- values=_archive_write(session_id),
+ values=archive_values,
)
- with pytest.raises(SessionArchivedError) as raised:
- with service.engine.begin() as conn:
- update_session(conn, session_id, title="Renamed by a stale tab")
- assert raised.value.session_id == session_id
+ with service.engine.begin() as conn:
+ update_session(conn, session_id, title="Renamed before archive")
+ with service.engine.begin() as conn:
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == session_id)
+ .values(**{key: value for key, value in archive_values.items() if key != "id"})
+ )
row = service.get_agent_session_by_id(session_id)
finally:
service.close()
- assert race["fired"] == 1, (
- "the archive never landed inside the window, so this test proved nothing "
- "about the read — the keyed read is no longer the SQL the code emits"
- )
+ assert race == {"fired": 1, "blocked": 1}
assert row is not None
- assert row["title"] == "Before", (
- f"the stale PATCH renamed an archived session to {row['title']!r}; the "
- "terminal transcript is no longer the one the user archived"
- )
- assert row["status"] == "archived", (
- f"the stale PATCH flipped a terminal session back to {row['status']!r}"
- )
- assert row["session_anchor"] == f"archived:{session_id}", (
- "the stale PATCH undid the archive's anchor vacation, so the next inbound "
- "message on that thread resolves to the archived row"
- )
+ assert row["title"] == "Renamed before archive"
+ assert row["status"] == "archived"
+ assert row["session_anchor"] == f"archived:{session_id}"
assert row["agent_status"] == "idle"
-def test_update_session_archive_race_outranks_the_backend_lock(tmp_path: Path) -> None:
- """HFR-280, precedence half — a rowcount of 0 must name the ARCHIVE.
-
- With two predicates on one statement, ``rowcount == 0`` no longer says which one
- refused, and the backend-lock branch already owned that branch. Which error comes
- out is not cosmetic: round 5d of this PR deliberately made the route answer the
- TERMINAL ``session_archived`` ahead of the RETRYABLE ``backend_locked``, so a
- client can recognize a permanent refusal and converge instead of retrying a dead
- row forever. A service that reports ``backend_locked`` for an archived row undoes
- that from underneath the route.
-
- Both predicates fail here, from one real competing commit: the in-flight turn
- binds its native id (which locks the backend -- bound native AND concrete
- backend) while the user's archive lands, which is the same async-cancel window as
- the case above. The requested backend differs from the row's, so the
- ``agent_backend == requested`` escape cannot match either.
- """
- from storage.workbench_sessions_service import SessionArchivedError, update_session
+def test_update_session_serializes_route_change_before_archive(tmp_path: Path) -> None:
+ """HFR-280, route half — the same reservation serializes both predicates."""
+ from storage.workbench_sessions_service import update_session
db_path = tmp_path / "vibe.sqlite"
service = SQLiteSessionsService(db_path)
try:
session_id = _seed_update_session_row(service, tmp_path, "slack_C123:race_patch_route")
- race = _commit_competing_bind_after(
+ archive_values = {**_archive_write(session_id), "native_session_id": "native-late"}
+ race = _block_competing_update_after(
service.engine,
db_path,
read=_UPDATE_SESSION_FAST_PATH_SELECT,
- # One commit, both facts: the finishing turn's native bind and the
- # archive. Ordering between them is irrelevant to the caller -- it read
- # the row before either.
- values={**_archive_write(session_id), "native_session_id": "native-late"},
+ values=archive_values,
)
- with pytest.raises(SessionArchivedError) as raised:
- with service.engine.begin() as conn:
- update_session(
- conn, session_id, agent_backend="codex", agent_name="nightly-codex"
- )
- assert raised.value.session_id == session_id
+ with service.engine.begin() as conn:
+ update_session(conn, session_id, agent_backend="codex", agent_name="nightly-codex")
+ with service.engine.begin() as conn:
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == session_id)
+ .values(**{key: value for key, value in archive_values.items() if key != "id"})
+ )
row = service.get_agent_session_by_id(session_id)
finally:
service.close()
- assert race["fired"] == 1, (
- "the archive never landed inside the window, so this test proved nothing — "
- "the keyed read is no longer the SQL the code emits"
- )
+ assert race == {"fired": 1, "blocked": 1}
assert row is not None
assert row["status"] == "archived"
- assert row["agent_backend"] == "opencode", (
- f"the stale PATCH re-routed an archived row to {row['agent_backend']!r}; the "
- "archived transcript is now attributed to a backend that never produced it"
- )
- assert row["agent_name"] == "review-opencode"
- assert row["native_session_id"] == "native-late", (
- "the stale PATCH overwrote the winner's native id"
- )
+ assert row["agent_backend"] == "codex"
+ assert row["agent_name"] == "nightly-codex"
+ assert row["native_session_id"] == "native-late"
# --- HFR-253 / HFR-254: the other two read-then-write session writers ---
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 1c80f9c42..8ffee249b 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -2,6 +2,7 @@ from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
from importlib import import_module
+import hashlib
import json
import re
import sqlite3
@@ -26,11 +27,11 @@ from storage.settings_service import SQLiteSettingsService
from vibe.message_types import build_partial_index_predicate
-HEAD_REVISION = "20260731_0043"
+HEAD_REVISION = "20260801_0044"
MESSAGE_PARTIAL_INDEX_PREDICATES = {
"ix_messages_inbox_activity": (
- "session_id is not null and type not in "
- "('queued', 'draft', 'pending', 'harness_dedupe', 'silent')"
+ "session_id is not null and type in "
+ "('user', 'harness', 'annotation', 'result', 'notify', 'error', 'assistant')"
),
"ix_messages_inbox_agent_reply": (
"session_id is not null and type in ('result', 'notify', 'error')"
@@ -99,6 +100,811 @@ def test_alembic_script_directory_has_exactly_one_head() -> None:
assert heads[0] == HEAD_REVISION
+def test_session_delivery_fsm_upgrade_and_downgrade_preserve_existing_rows(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260729_0042")
+ now = "2026-07-31T00:00:00Z"
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ insert into agent_sessions (
+ id, scope_id, agent_id, agent_name, agent_backend, agent_variant,
+ model, reasoning_effort, session_anchor, workdir, native_session_id,
+ title, status, visibility, pinned, agent_status, created_at,
+ updated_at, last_active_at, metadata_json
+ ) values (
+ 'ses_fsm', null, null, 'codex', 'codex', 'codex', null, null,
+ 'ses_fsm', '/tmp', '', null, 'active', 'foreground', 0, 'idle',
+ ?, ?, ?, '{}'
+ )
+ """,
+ (now, now, now),
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_id,
+ author_name, source, native_message_id, parent_native_message_id,
+ content_text, content_json, metadata_json, created_at, updated_at,
+ delivered_at, read_at
+ ) values (
+ 'msg_fsm', null, 'ses_fsm', 'avibe', 'user', 'queued', null,
+ null, 'user', null, null, 'hello', '{"text":"hello"}', '{}',
+ ?, ?, null, null
+ )
+ """,
+ (now, now),
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_id,
+ author_name, source, native_message_id, parent_native_message_id,
+ content_text, content_json, metadata_json, created_at, updated_at,
+ delivered_at, read_at
+ ) values (
+ 'msg_fsm_agent_run', null, 'ses_fsm', 'avibe', 'harness',
+ 'queued', null, null, 'harness', 'agent_run:run-legacy',
+ null, 'run prompt', '{"text":"run prompt"}', '{}', ?, ?, null, null
+ )
+ """,
+ (now, now),
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_id,
+ author_name, source, native_message_id, parent_native_message_id,
+ content_text, content_json, metadata_json, created_at, updated_at,
+ delivered_at, read_at
+ ) values (
+ 'msg_fsm_dedupe', null, 'ses_fsm', 'avibe', 'harness',
+ 'harness_dedupe', null, null, 'harness', 'watch:legacy:run-1',
+ null, '', '{}', '{}', ?, ?, null, null
+ )
+ """,
+ (now, now),
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_id,
+ author_name, source, native_message_id, parent_native_message_id,
+ content_text, content_json, metadata_json, created_at, updated_at,
+ delivered_at, read_at
+ ) values (
+ 'msg_fsm_draft', null, 'ses_fsm', 'avibe', 'user', 'draft', null,
+ null, 'user', null, null, 'unfinished thought',
+ '{"text":"unfinished thought"}', '{}', ?, ?, null, null
+ )
+ """,
+ (now, now),
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+ with sqlite3.connect(db_path) as conn:
+ tables = {
+ row[0]
+ for row in conn.execute("select name from sqlite_master where type = 'table'")
+ }
+ turn_columns = {
+ row[1] for row in conn.execute("pragma table_info(session_turns)")
+ }
+ delivery_columns = {
+ row[1] for row in conn.execute("pragma table_info(message_deliveries)")
+ }
+ existing = conn.execute(
+ "select content_text, type from messages where id = 'msg_fsm'"
+ ).fetchone()
+ delivery = conn.execute(
+ "select state, dispatch_text, snapshot_json from message_deliveries where id = 'msg_fsm'"
+ ).fetchone()
+ migrated_dedupe = conn.execute(
+ "select state, dedupe_key, snapshot_json from message_deliveries "
+ "where id = 'msg_fsm_dedupe'"
+ ).fetchone()
+ migrated_agent_run = conn.execute(
+ "select state, dedupe_key, snapshot_json from message_deliveries "
+ "where id = 'msg_fsm_agent_run'"
+ ).fetchone()
+ hold_state = conn.execute(
+ "select queue_hold_state from agent_sessions where id = 'ses_fsm'"
+ ).fetchone()
+ draft_state = conn.execute(
+ "select composer_draft_text, composer_draft_updated_at "
+ "from agent_sessions where id = 'ses_fsm'"
+ ).fetchone()
+ message_session_fk = next(
+ row
+ for row in conn.execute("pragma foreign_key_list(messages)")
+ if row[2] == "agent_sessions" and row[3] == "session_id"
+ )
+ version = conn.execute("select version_num from alembic_version").fetchone()
+ assert {"session_turns", "message_deliveries"}.issubset(tables)
+ assert {
+ "initial_delivery_id",
+ "runtime_turn_id",
+ "native_turn_id",
+ "terminal_outcome",
+ "version",
+ }.issubset(turn_columns)
+ assert {
+ "message_id",
+ "dispatch_text",
+ "priority",
+ "current_target_turn_id",
+ "current_attempt_id",
+ "current_expected_native_turn_id",
+ "current_receipt_outcome",
+ "delivery_history_json",
+ "version",
+ }.issubset(delivery_columns)
+ assert existing is None
+ assert delivery[0:2] == ("queued", "hello")
+ assert json.loads(delivery[2])["content_text"] == "hello"
+ assert migrated_dedupe[0:2] == ("retired", "avibe:watch:legacy:run-1")
+ assert json.loads(migrated_dedupe[2])["type"] == "harness"
+ assert migrated_agent_run[0:2] == ("queued", "avibe:agent_run:run-legacy")
+ assert json.loads(migrated_agent_run[2])["type"] == "harness"
+ assert hold_state == ("held",)
+ assert draft_state == ("unfinished thought", now)
+ assert message_session_fk[6] == "NO ACTION"
+ assert version == (HEAD_REVISION,)
+
+ from storage import message_deliveries
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ assert message_deliveries.queued_session_ids_without_live_turns(conn) == []
+ assert message_deliveries.queued_session_ids_without_live_turns(
+ conn,
+ include_held=True,
+ ) == ["ses_fsm"]
+ finally:
+ engine.dispose()
+
+ command.downgrade(migrations.alembic_config(db_path), "20260729_0042")
+ with sqlite3.connect(db_path) as conn:
+ tables = {
+ row[0]
+ for row in conn.execute("select name from sqlite_master where type = 'table'")
+ }
+ existing = conn.execute(
+ "select content_text, type, session_id from messages where id = 'msg_fsm'"
+ ).fetchone()
+ restored_draft = conn.execute(
+ "select content_text, type from messages "
+ "where session_id = 'ses_fsm' and type = 'draft'"
+ ).fetchone()
+ restored_dedupe = conn.execute(
+ "select type, native_message_id from messages where id = 'msg_fsm_dedupe'"
+ ).fetchone()
+ restored_agent_run = conn.execute(
+ "select type, native_message_id from messages "
+ "where id = 'msg_fsm_agent_run'"
+ ).fetchone()
+ message_session_fk = next(
+ row
+ for row in conn.execute("pragma foreign_key_list(messages)")
+ if row[2] == "agent_sessions" and row[3] == "session_id"
+ )
+ version = conn.execute("select version_num from alembic_version").fetchone()
+ assert "session_turns" not in tables
+ assert "message_deliveries" not in tables
+ assert existing == ("hello", "queued", "ses_fsm")
+ assert restored_draft == ("unfinished thought", "draft")
+ assert restored_dedupe == ("harness_dedupe", "watch:legacy:run-1")
+ assert restored_agent_run == ("queued", "agent_run:run-legacy")
+ assert message_session_fk[6] == "SET NULL"
+ assert version == ("20260729_0042",)
+
+
+def test_session_delivery_migration_uses_live_dedupe_for_harness_provenance(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260729_0042")
+ now = "2026-07-31T00:00:00Z"
+ cases = [
+ (
+ "human",
+ "user",
+ "user",
+ None,
+ "human:1",
+ "user",
+ "legacy:avibe:human:1",
+ ),
+ (
+ "task",
+ "harness",
+ "harness",
+ None,
+ "task:1",
+ "harness",
+ "avibe:task:1",
+ ),
+ (
+ "watch",
+ "harness",
+ "harness",
+ None,
+ "watch:1",
+ "harness",
+ "avibe:watch:1",
+ ),
+ (
+ "webhook",
+ "harness",
+ "harness",
+ None,
+ "webhook:1",
+ "harness",
+ "avibe:webhook:1",
+ ),
+ (
+ "show",
+ "harness",
+ "harness",
+ "show_annotation",
+ "show:1",
+ "annotation",
+ "avibe:show:1",
+ ),
+ ]
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ insert into agent_sessions (
+ id, scope_id, agent_id, agent_name, agent_backend, agent_variant,
+ model, reasoning_effort, session_anchor, workdir, native_session_id,
+ title, status, visibility, pinned, agent_status, created_at,
+ updated_at, last_active_at, metadata_json
+ ) values (
+ 'ses_dedupe_classifier', null, null, 'codex', 'codex', 'codex',
+ null, null, 'ses_dedupe_classifier', '/tmp', '', null, 'active',
+ 'foreground', 0, 'idle', ?, ?, ?, '{}'
+ )
+ """,
+ (now, now, now),
+ )
+ for name, author, source, author_name, native_id, _type, _dedupe in cases:
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_id,
+ author_name, source, native_message_id, parent_native_message_id,
+ content_text, content_json, metadata_json, created_at, updated_at,
+ delivered_at, read_at
+ ) values (
+ ?, null, 'ses_dedupe_classifier', 'avibe', ?, 'queued', null,
+ ?, ?, ?, null, ?, json_object('text', ?), '{}', ?, ?, null, null
+ )
+ """,
+ (
+ f"msg_{name}",
+ author,
+ author_name,
+ source,
+ native_id,
+ name,
+ name,
+ now,
+ now,
+ ),
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ migrated = conn.execute(
+ "select id, dedupe_key, snapshot_json from message_deliveries "
+ "where session_id = 'ses_dedupe_classifier' order by id"
+ ).fetchall()
+ by_id = {
+ row_id: (dedupe_key, json.loads(snapshot_json)["type"])
+ for row_id, dedupe_key, snapshot_json in migrated
+ }
+ assert by_id == {
+ f"msg_{name}": (expected_dedupe, expected_type)
+ for (
+ name,
+ _author,
+ _source,
+ _author_name,
+ _native_id,
+ expected_type,
+ expected_dedupe,
+ ) in cases
+ }
+
+
+def test_session_delivery_migration_binds_each_live_scheduled_run(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260729_0042")
+ now = "2026-07-31T00:00:00Z"
+ cases = (
+ ("task", "scheduled", "queued"),
+ ("watch", "watch", "pending"),
+ ("webhook", "hook", "processing"),
+ )
+ with sqlite3.connect(db_path) as conn:
+ for name, trigger_kind, run_status in cases:
+ session_id = f"ses_{name}_migration"
+ run_id = f"run_{name}_migration"
+ message_id = f"msg_{name}_migration"
+ native_id = f"{name}:migration"
+ conn.execute(
+ """
+ insert into agent_sessions (
+ id, scope_id, agent_id, agent_name, agent_backend, agent_variant,
+ model, reasoning_effort, session_anchor, workdir, native_session_id,
+ title, status, visibility, pinned, agent_status, created_at,
+ updated_at, last_active_at, metadata_json
+ ) values (
+ ?, null, null, 'codex', 'codex', 'codex', null, null,
+ ?, '/tmp', '', null, 'active', 'foreground', 0, 'idle',
+ ?, ?, ?, '{}'
+ )
+ """,
+ (session_id, session_id, now, now, now),
+ )
+ conn.execute(
+ """
+ insert into agent_runs (
+ id, run_type, status, session_id, cancel_requested,
+ created_at, updated_at, metadata_json
+ ) values (?, ?, ?, ?, 0, ?, ?, '{}')
+ """,
+ (run_id, name, run_status, session_id, now, now),
+ )
+ metadata_json = json.dumps(
+ {
+ "scheduled_provenance": {
+ "platform_specific": {
+ "task_execution_id": run_id,
+ "task_trigger_kind": trigger_kind,
+ }
+ }
+ }
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_id,
+ author_name, source, native_message_id, parent_native_message_id,
+ content_text, content_json, metadata_json, created_at, updated_at,
+ delivered_at, read_at
+ ) values (
+ ?, null, ?, 'avibe', 'harness', 'queued', null, ?, 'harness',
+ ?, null, ?, json_object('text', ?), ?, ?, ?, null, null
+ )
+ """,
+ (
+ message_id,
+ session_id,
+ name,
+ native_id,
+ name,
+ name,
+ metadata_json,
+ now,
+ now,
+ ),
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ migrated = conn.execute(
+ """
+ select r.id, r.delivery_id, d.state, d.dedupe_key,
+ s.queue_hold_state
+ from agent_runs r
+ join message_deliveries d on d.id = r.delivery_id
+ join agent_sessions s on s.id = r.session_id
+ where r.id like 'run_%_migration'
+ order by r.id
+ """
+ ).fetchall()
+ assert migrated == [
+ (
+ f"run_{name}_migration",
+ f"msg_{name}_migration",
+ "queued",
+ f"avibe:{name}:migration",
+ "open",
+ )
+ for name, _trigger_kind, _run_status in sorted(cases)
+ ]
+
+
+def test_session_delivery_migration_dedupes_and_avoids_legacy_event_id_collisions(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260729_0042")
+ now = "2026-07-31T00:00:00Z"
+ tool_message_id = "msg_tool_collision"
+ silent_message_id = "msg_silent_existing"
+ tool_event_id = (
+ "evt_legacy_"
+ + hashlib.sha256(f"tool_call:{tool_message_id}".encode()).hexdigest()[:24]
+ )
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ insert into scopes (
+ id, platform, scope_type, native_id, is_private, supports_threads,
+ metadata_json, first_seen_at, last_seen_at, updated_at
+ ) values ('scope_fsm_trace', 'avibe', 'project', 'trace', 0, 0,
+ '{}', ?, ?, ?)
+ """,
+ (now, now, now),
+ )
+ conn.execute(
+ """
+ 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_fsm_trace', 'scope_fsm_trace', 'codex', 'codex',
+ 'codex', 'trace', '/tmp', '', 'active', 'foreground', 0,
+ 'idle', '{}', ?, ?, ?)
+ """,
+ (now, now, now),
+ )
+ conn.executemany(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, content_text,
+ content_json, metadata_json, created_at, updated_at
+ ) values (?, 'scope_fsm_trace', 'ses_fsm_trace', 'avibe', 'agent',
+ ?, ?, '{}', '{}', ?, ?)
+ """,
+ (
+ (tool_message_id, "tool_call", "tool trace", now, now),
+ (silent_message_id, "silent", "silent trace", now, now),
+ ),
+ )
+ conn.executemany(
+ """
+ insert into agent_events (
+ id, scope_id, session_id, platform, event_type, visibility,
+ content_json, metadata_json, created_at, updated_at
+ ) values (?, 'scope_fsm_trace', 'ses_fsm_trace', 'avibe', ?,
+ 'trace', '{}', ?, ?, ?)
+ """,
+ (
+ (tool_event_id, "unrelated", "{}", now, now),
+ (
+ "evt_existing_silent",
+ "silent_terminal",
+ json.dumps({"legacy_message_id": silent_message_id}),
+ now,
+ now,
+ ),
+ ),
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, content_text,
+ content_json, metadata_json, created_at, updated_at
+ ) values ('msg_accepted_ref', 'scope_fsm_trace', 'ses_fsm_trace',
+ 'avibe', 'agent', 'result', 'accepted', '{}', '{}', ?, ?)
+ """,
+ (now, now),
+ )
+ conn.execute(
+ """
+ insert into show_session_events (
+ id, session_id, event_type, actor, scope, anchor_json,
+ payload_json, message_id, created_at
+ ) values ('show_accepted_ref', 'ses_fsm_trace', 'annotation',
+ 'agent', 'session', '{}', '{}', 'msg_accepted_ref', ?)
+ """,
+ (now,),
+ )
+ conn.execute(
+ """
+ insert into media_objects (
+ token, scope_id, session_id, message_id, kind, source,
+ local_path, created_at
+ ) values ('media_accepted_ref', 'scope_fsm_trace', 'ses_fsm_trace',
+ 'msg_accepted_ref', 'file', 'agent', '/tmp/accepted.txt', ?)
+ """,
+ (now,),
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ pseudo_count = conn.execute(
+ "select count(*) from messages where id in (?, ?)",
+ (tool_message_id, silent_message_id),
+ ).fetchone()[0]
+ tool_events = conn.execute(
+ "select id from agent_events where event_type = 'tool_call' "
+ "and json_extract(metadata_json, '$.legacy_message_id') = ?",
+ (tool_message_id,),
+ ).fetchall()
+ silent_events = conn.execute(
+ "select id from agent_events where event_type = 'silent_terminal' "
+ "and json_extract(metadata_json, '$.legacy_message_id') = ?",
+ (silent_message_id,),
+ ).fetchall()
+ collision = conn.execute(
+ "select event_type from agent_events where id = ?",
+ (tool_event_id,),
+ ).fetchone()
+ accepted_refs = (
+ conn.execute(
+ "select message_id from show_session_events "
+ "where id = 'show_accepted_ref'"
+ ).fetchone(),
+ conn.execute(
+ "select message_id from media_objects "
+ "where token = 'media_accepted_ref'"
+ ).fetchone(),
+ )
+ assert pseudo_count == 0
+ assert tool_events == [(f"{tool_event_id}_1",)]
+ assert silent_events == [("evt_existing_silent",)]
+ assert collision == ("unrelated",)
+ assert accepted_refs == (("msg_accepted_ref",), ("msg_accepted_ref",))
+
+ from storage import agent_activity_service
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ groups = agent_activity_service.list_turn_groups(
+ conn,
+ session_id="ses_fsm_trace",
+ )["groups"]
+ finally:
+ engine.dispose()
+ assert [group["status"] for group in groups] == ["done"]
+ assert groups[0]["steps"] == 1
+
+ command.downgrade(migrations.alembic_config(db_path), "20260729_0042")
+ with sqlite3.connect(db_path) as conn:
+ restored_trace = conn.execute(
+ "select id, type, content_text from messages "
+ "where id in (?, ?) order by id",
+ (tool_message_id, silent_message_id),
+ ).fetchall()
+ remaining_events = conn.execute(
+ "select id, metadata_json from agent_events order by id"
+ ).fetchall()
+ downgraded_refs = (
+ conn.execute(
+ "select message_id from show_session_events "
+ "where id = 'show_accepted_ref'"
+ ).fetchone(),
+ conn.execute(
+ "select message_id from media_objects "
+ "where token = 'media_accepted_ref'"
+ ).fetchone(),
+ )
+ assert restored_trace == [
+ (silent_message_id, "silent", "silent trace"),
+ (tool_message_id, "tool_call", "tool trace"),
+ ]
+ assert {row[0] for row in remaining_events} == {
+ tool_event_id,
+ "evt_existing_silent",
+ }
+ metadata_by_id = {row[0]: json.loads(row[1]) for row in remaining_events}
+ assert metadata_by_id["evt_existing_silent"] == {
+ "legacy_message_id": silent_message_id
+ }
+ assert downgraded_refs == (("msg_accepted_ref",), ("msg_accepted_ref",))
+
+
+def test_session_delivery_migration_refuses_preexisting_operational_tables(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260731_0043")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table message_deliveries (id text primary key)")
+ conn.execute("create table session_turns (id text primary key)")
+ conn.commit()
+
+ with pytest.raises(RuntimeError, match="interrupted 0044 migration"):
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ assert conn.execute("select version_num from alembic_version").fetchone() == (
+ "20260731_0043",
+ )
+
+
+def test_session_delivery_migration_completes_precreated_operational_tables(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260731_0043")
+ now = "2026-07-31T00:00:00Z"
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ 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_interrupted', null, 'codex', 'codex', 'codex',
+ 'interrupted', '/tmp', '', 'active', 'foreground', 0,
+ 'idle', '{}', ?, ?, ?)
+ """,
+ (now, now, now),
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, source,
+ content_text, content_json, metadata_json, created_at, updated_at
+ ) values (
+ 'msg_interrupted', null, 'ses_interrupted', 'avibe', 'user',
+ 'queued', 'user', 'resume me', '{"text":"resume me"}', '{}', ?, ?
+ )
+ """,
+ (now, now),
+ )
+ conn.commit()
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ metadata.create_all(
+ engine,
+ tables=[
+ metadata.tables["message_deliveries"],
+ metadata.tables["session_turns"],
+ ],
+ )
+ finally:
+ engine.dispose()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ assert conn.execute(
+ "select 1 from messages where id = 'msg_interrupted'"
+ ).fetchone() is None
+ assert conn.execute(
+ "select state, session_id from message_deliveries "
+ "where id = 'msg_interrupted'"
+ ).fetchone() == ("queued", "ses_interrupted")
+ assert conn.execute(
+ "select 1 from pragma_table_info('agent_runs') where name = 'delivery_id'"
+ ).fetchone() == (1,)
+ assert conn.execute(
+ "select 1 from pragma_index_list('agent_runs') "
+ "where name = 'uq_agent_runs_delivery'"
+ ).fetchone() == (1,)
+
+
+def test_session_delivery_migration_resolves_legacy_pending_by_its_real_owner(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260729_0042")
+ now = "2026-07-31T00:00:00Z"
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ 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_pending', null, 'codex', 'codex', 'codex',
+ 'pending', '/tmp', '', 'active', 'foreground', 0,
+ 'idle', '{}', ?, ?, ?)
+ """,
+ (now, now, now),
+ )
+ conn.executemany(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_name,
+ source, content_text, content_json, metadata_json, created_at,
+ updated_at
+ ) values (?, null, 'ses_pending', 'avibe', ?, 'pending', ?, ?, ?,
+ json_object('text', ?), '{}', ?, ?)
+ """,
+ (
+ ("msg_pending_human", "user", None, "user", "human", "human", now, now),
+ (
+ "msg_pending_harness",
+ "harness",
+ "watch",
+ "harness",
+ "scheduled",
+ "scheduled",
+ now,
+ now,
+ ),
+ (
+ "msg_pending_annotation",
+ "harness",
+ "show_annotation",
+ "harness",
+ "annotation",
+ "annotation",
+ now,
+ now,
+ ),
+ ),
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ remaining_messages = conn.execute(
+ "select id from messages where id in "
+ "('msg_pending_human', 'msg_pending_harness', 'msg_pending_annotation')"
+ ).fetchall()
+ deliveries = conn.execute(
+ "select id, state, current_attempt_kind, current_receipt_outcome, "
+ "snapshot_json from message_deliveries where id in "
+ "('msg_pending_human', 'msg_pending_harness', 'msg_pending_annotation') "
+ "order by id"
+ ).fetchall()
+ assert remaining_messages == []
+ assert [(row[0], row[1], row[2], row[3]) for row in deliveries] == [
+ ("msg_pending_annotation", "retired", None, None),
+ ("msg_pending_harness", "retired", None, None),
+ ("msg_pending_human", "retired", None, None),
+ ]
+ snapshots = {row[0]: json.loads(row[4]) for row in deliveries}
+ assert snapshots["msg_pending_annotation"]["type"] == "annotation"
+ assert snapshots["msg_pending_annotation"]["author"] == "harness"
+ assert snapshots["msg_pending_harness"]["type"] == "harness"
+ assert snapshots["msg_pending_harness"]["author"] == "harness"
+ assert snapshots["msg_pending_harness"]["author_name"] == "watch"
+ assert snapshots["msg_pending_harness"]["source"] == "harness"
+ assert snapshots["msg_pending_human"]["type"] == "user"
+ assert snapshots["msg_pending_human"]["author"] == "user"
+ assert snapshots["msg_pending_human"]["source"] == "user"
+ from storage import message_deliveries
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ assert message_deliveries.recoverable_reservations(conn, "ses_pending") == []
+ assert message_deliveries.ordering_head(conn, "ses_pending") is None
+ finally:
+ engine.dispose()
+
+ command.downgrade(migrations.alembic_config(db_path), "20260729_0042")
+ with sqlite3.connect(db_path) as conn:
+ restored = conn.execute(
+ "select id, type, author from messages where id in "
+ "('msg_pending_human', 'msg_pending_harness', 'msg_pending_annotation') "
+ "order by id"
+ ).fetchall()
+ assert restored == [
+ ("msg_pending_annotation", "pending", "harness"),
+ ("msg_pending_harness", "pending", "harness"),
+ ("msg_pending_human", "pending", "user"),
+ ]
+
+
def test_upgrade_keeps_historical_conflated_callback_rows_sent(
tmp_path: Path,
) -> None:
@@ -269,7 +1075,12 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
assert "ix_messages_inbox_activity" in message_indexes
assert "ix_messages_inbox_agent_reply" in message_indexes
assert "ix_messages_inbox_user_send" in message_indexes
- assert "harness_dedupe" in _index_sql(conn, "ix_messages_inbox_activity")
+ assert "session_id is not null" in _index_sql(
+ conn, "ix_messages_inbox_activity"
+ )
+ assert "harness_dedupe" not in _index_sql(
+ conn, "ix_messages_inbox_activity"
+ )
assert "author = 'harness'" in _index_sql(conn, "ix_messages_inbox_user_send")
assert "uq_vault_secrets_name_folded" in vault_secret_indexes
assert "lower(name)" in _index_sql(conn, "uq_vault_secrets_name_folded").lower()
@@ -452,8 +1263,17 @@ def test_show_dispatch_state_removal_migration_preserves_existing_events(
")"
).fetchall()
}
+ retryable_trace = conn.execute(
+ "select event_type, json_extract(metadata_json, '$.legacy_message_id') "
+ "from agent_events where json_extract(metadata_json, '$.legacy_message_id') "
+ "= 'msg_upgrade_retryable'"
+ ).fetchone()
+ chat_trace = conn.execute(
+ "select event_type, json_extract(metadata_json, '$.legacy_message_id') "
+ "from agent_events where json_extract(metadata_json, '$.legacy_message_id') "
+ "= 'msg_upgrade_chat'"
+ ).fetchone()
for message_id, message_type, event_id in (
- ("msg_pending_show", "pending", "show_evt_pending"),
("msg_accepted_show", "harness", "show_evt_accepted"),
):
conn.execute(
@@ -469,10 +1289,7 @@ def test_show_dispatch_state_removal_migration_preserves_existing_events(
""",
(message_id, message_type, event_id, now, now),
)
- for event_id, message_id in (
- ("show_evt_pending", "msg_pending_show"),
- ("show_evt_accepted", "msg_accepted_show"),
- ):
+ for event_id, message_id in (("show_evt_accepted", "msg_accepted_show"),):
conn.execute(
"""
insert into show_session_events (
@@ -497,13 +1314,8 @@ def test_show_dispatch_state_removal_migration_preserves_existing_events(
"show_annotation",
"show_evt_upgrade_accepted",
)
- assert upgraded_messages["msg_upgrade_retryable"] == (
- "harness",
- "pending",
- "harness",
- "show_intent",
- "show_evt_upgrade_retryable",
- )
+ assert "msg_upgrade_retryable" not in upgraded_messages
+ assert retryable_trace == ("tool_call", "msg_upgrade_retryable")
assert upgraded_messages["msg_upgrade_visible"] == (
"harness",
"harness",
@@ -518,13 +1330,8 @@ def test_show_dispatch_state_removal_migration_preserves_existing_events(
None,
None,
)
- assert upgraded_messages["msg_upgrade_chat"] == (
- "user",
- "pending",
- None,
- None,
- None,
- )
+ assert "msg_upgrade_chat" not in upgraded_messages
+ assert chat_trace == ("tool_call", "msg_upgrade_chat")
command.downgrade(migrations.alembic_config(db_path), "20260726_0036")
@@ -532,7 +1339,7 @@ def test_show_dispatch_state_removal_migration_preserves_existing_events(
downgraded = dict(
conn.execute(
"select id, dispatch_state from show_session_events "
- "where id in ('show_evt_legacy', 'show_evt_pending', 'show_evt_accepted')"
+ "where id in ('show_evt_legacy', 'show_evt_accepted')"
).fetchall()
)
downgraded_messages = {
@@ -540,20 +1347,12 @@ def test_show_dispatch_state_removal_migration_preserves_existing_events(
for row in conn.execute(
"select id, author, type, source, author_name, author_id "
"from messages "
- "where id in ('msg_pending_show', 'msg_accepted_show')"
+ "where id = 'msg_accepted_show'"
).fetchall()
}
assert json.loads(downgraded["show_evt_legacy"]) == {"state": "accepted"}
assert json.loads(downgraded["show_evt_accepted"]) == {"state": "accepted"}
- assert json.loads(downgraded["show_evt_pending"]) == {"state": "none"}
- assert downgraded_messages["msg_pending_show"] == (
- "user",
- "pending",
- None,
- None,
- None,
- )
assert downgraded_messages["msg_accepted_show"] == (
"user",
"user",
@@ -1091,7 +1890,12 @@ def test_run_migrations_repairs_head_indexes_before_stamping_head(tmp_path: Path
assert "ix_messages_inbox_agent_reply" in message_indexes
assert "ix_messages_inbox_user_send" in message_indexes
with sqlite3.connect(db_path) as conn:
- assert "harness_dedupe" in _index_sql(conn, "ix_messages_inbox_activity")
+ assert "session_id is not null" in _index_sql(
+ conn, "ix_messages_inbox_activity"
+ )
+ assert "harness_dedupe" not in _index_sql(
+ conn, "ix_messages_inbox_activity"
+ )
assert "author = 'harness'" in _index_sql(conn, "ix_messages_inbox_user_send")
assert "ix_agent_sessions_scope_status_activity" in agent_session_indexes
@@ -1523,7 +2327,8 @@ def test_run_migrations_rebuilds_inbox_indexes_for_harness_inputs(tmp_path: Path
with sqlite3.connect(db_path) as conn:
version = conn.execute("select version_num from alembic_version").fetchone()
assert version == (HEAD_REVISION,)
- assert "harness_dedupe" in _index_sql(conn, "ix_messages_inbox_activity")
+ assert "session_id is not null" in _index_sql(conn, "ix_messages_inbox_activity")
+ assert "harness_dedupe" not in _index_sql(conn, "ix_messages_inbox_activity")
assert "author = 'harness'" in _index_sql(conn, "ix_messages_inbox_user_send")
@@ -2040,13 +2845,10 @@ def test_run_migrations_deletes_historical_message_tool_calls(tmp_path: Path) ->
def test_run_migrations_deletes_tool_calls_when_stamping_unversioned_head_schema(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
- engine = create_sqlite_engine(db_path)
- try:
- metadata.create_all(engine)
- finally:
- engine.dispose()
+ run_migrations(db_path, revision="20260729_0042")
with sqlite3.connect(db_path) as conn:
+ conn.execute("drop table alembic_version")
conn.execute(
"""
insert into scopes (
@@ -2324,24 +3126,10 @@ def test_background_tables_ready_requires_messages_type(tmp_path: Path) -> None:
must report NOT ready so SQLiteBackgroundTaskStore triggers the migration;
otherwise messages_service.append would write a column that doesn't exist."""
db_path = tmp_path / "vibe.sqlite"
- engine = create_sqlite_engine(db_path)
- try:
- metadata.create_all(engine)
- finally:
- engine.dispose()
+ run_migrations(db_path, revision="20260530_0009")
with sqlite3.connect(db_path) as conn:
- conn.execute("drop index if exists ix_messages_session_type")
- conn.execute("drop index if exists ix_messages_session_type_created_id")
- conn.execute("drop index if exists ix_messages_unread_session")
- conn.execute("drop index if exists ix_messages_inbox_activity")
- conn.execute("drop index if exists ix_messages_inbox_agent_reply")
- conn.execute("drop index if exists ix_messages_inbox_user_send")
- conn.execute('alter table "messages" drop column "type"')
- conn.execute("create table if not exists alembic_version (version_num varchar(32) not null)")
- conn.execute("delete from alembic_version")
- conn.execute("insert into alembic_version values ('20260530_0009')")
- conn.commit()
+ assert "type" not in {row[1] for row in conn.execute("pragma table_info(messages)")}
assert background_tables_ready(db_path) is False
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index a0cdbd422..3f004d5fb 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -800,8 +800,8 @@ def test_messages_post_into_the_reserved_system_session_dispatches_nothing(monke
# Refused BEFORE the reservation and BEFORE the controller: no row, no turn.
assert _message_count(WORKSPACE_NOTICE_SESSION_ID) == 0
assert dispatch.await_count == 1
- assert accepted.status_code == 201
- assert _message_count(ordinary) == 1
+ assert accepted.status_code == 202
+ assert _message_count(ordinary) == 0
def test_messages_post_reserved_refusal_follows_configured_language(monkeypatch, tmp_path):
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 4ba544f42..fb4940a39 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -24,7 +24,7 @@ from sqlalchemy import select, update
from storage.importer import ensure_sqlite_state
from storage.db import create_sqlite_engine
-from storage import messages_service
+from storage import message_deliveries, messages_service
from storage.models import agent_sessions, messages
from storage.models import scope_settings
from storage.settings_service import upsert_scope
@@ -122,6 +122,56 @@ def _seed_opencode_messages(xdg_home: Path, native_session_id: str, roles: list[
)
+def _settle_reserved_delivery(payload: dict, *, state: str) -> dict:
+ with create_sqlite_engine().begin() as conn:
+ delivery = message_deliveries.get_delivery(conn, payload["user_message_id"])
+ assert delivery is not None and delivery["state"] == "reserved"
+ if state == "queued":
+ settled = message_deliveries.cas_delivery(
+ conn,
+ delivery["id"],
+ expected_version=delivery["version"],
+ expected_states=("reserved",),
+ values={"state": "queued"},
+ )
+ else:
+ turn_id = message_deliveries.new_turn_id()
+ message_deliveries.insert_turn(
+ conn,
+ turn_id=turn_id,
+ session_id=delivery["session_id"],
+ initial_delivery_id=delivery["id"],
+ state="starting",
+ backend="claude",
+ )
+ attempt_id = message_deliveries.new_attempt_id()
+ message_deliveries.open_start_attempt(
+ conn,
+ delivery["id"],
+ expected_version=delivery["version"],
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ )
+ turn = message_deliveries.get_turn(conn, turn_id)
+ assert turn is not None
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ runtime_key=f"runtime:{turn_id}",
+ runtime_turn_id=f"runtime-turn:{turn_id}",
+ native_turn_id=f"native:{turn_id}",
+ ) is not None
+ accepted = message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+ settled = accepted[0] if accepted else None
+ assert settled is not None
+ return settled
+
+
def test_route_fire_and_forgets_dispatch(isolated_state, tmp_path):
"""The web Chat POST persists the user row AND fire-and-forgets the turn via
``/internal/dispatch_async``. The reply arrives over the persistent
@@ -133,9 +183,18 @@ def test_route_fire_and_forgets_dispatch(isolated_state, tmp_path):
_, session_id = _make_session(tmp_path)
- dispatch_mock = AsyncMock(
- return_value={"status_code": 202, "body": {"ok": True, "session_id": session_id}}
- )
+ async def dispatch(payload):
+ settled = _settle_reserved_delivery(payload, state="accepted")
+ return {
+ "status_code": 202,
+ "body": {
+ "ok": True,
+ "session_id": session_id,
+ "delivery_state": settled["state"],
+ },
+ }
+
+ dispatch_mock = AsyncMock(side_effect=dispatch)
with (
patch("vibe.internal_client.dispatch_async", dispatch_mock),
patch("vibe.ui_server._web_push_user_key", return_value="remote:user-a"),
@@ -160,6 +219,95 @@ def test_route_fire_and_forgets_dispatch(isolated_state, tmp_path):
assert sent["text"] == "no stream"
+def test_route_reads_the_materialized_message_id_for_a_merged_batch(
+ isolated_state,
+ tmp_path,
+) -> None:
+ from vibe.ui_server import app
+
+ scope_id, session_id = _make_session(tmp_path)
+ older_delivery_id = "msg_merged_segment_head"
+
+ async def dispatch(payload):
+ with create_sqlite_engine().begin() as conn:
+ current = message_deliveries.get_delivery(conn, payload["user_message_id"])
+ assert current is not None and current["state"] == "reserved"
+ older = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=older_delivery_id,
+ session_id=session_id,
+ priority="p3",
+ state="queued",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ text="older queued input",
+ metadata={"_web_push_user_key": "remote:user-a"},
+ author_id="remote:user-a",
+ ),
+ dispatch_text="older queued input",
+ now="2026-01-01T00:00:00Z",
+ )
+ turn_id = message_deliveries.new_turn_id()
+ claimed = message_deliveries.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend="claude",
+ deliveries=[older, current],
+ dispatch_text="older queued input\nnew input",
+ )
+ turn = claimed["turn"]
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ runtime_key=f"runtime:{turn_id}",
+ runtime_turn_id=f"runtime-turn:{turn_id}",
+ native_turn_id=f"native:{turn_id}",
+ ) is not None
+ accepted = message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+ current_after = message_deliveries.get_delivery(
+ conn,
+ payload["user_message_id"],
+ )
+ assert accepted and current_after is not None
+ return {
+ "status_code": 202,
+ "body": {
+ "ok": True,
+ "session_id": session_id,
+ "delivery_id": payload["user_message_id"],
+ "message_id": accepted[0]["message_id"],
+ "delivery_state": current_after["state"],
+ },
+ }
+
+ with (
+ patch("vibe.internal_client.dispatch_async", AsyncMock(side_effect=dispatch)),
+ patch("vibe.ui_server._web_push_user_key", return_value="remote:user-a"),
+ ):
+ client = app.test_client()
+ response = client.post(
+ f"/api/sessions/{session_id}/messages",
+ json={"text": "new input"},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 201
+ body = response.get_json()
+ assert body["id"] == older_delivery_id
+ assert body["message_id"] == older_delivery_id
+ assert body["delivery_id"] != older_delivery_id
+
+
def test_route_enqueues_when_turn_in_progress(isolated_state, tmp_path):
"""When the controller reports a turn already running (202 {queued}), the
route persists the user row, hands its id to the controller to re-type as
@@ -171,16 +319,15 @@ def test_route_enqueues_when_turn_in_progress(isolated_state, tmp_path):
_, session_id = _make_session(tmp_path)
async def dispatch(payload):
- from core.session_turns import queue_pending_user_message
- from storage.db import create_sqlite_engine
-
- with create_sqlite_engine().begin() as conn:
- assert queue_pending_user_message(
- conn,
- payload["user_message_id"],
- payload["text"],
- )
- return {"status_code": 202, "body": {"ok": True, "queued": True}}
+ settled = _settle_reserved_delivery(payload, state="queued")
+ return {
+ "status_code": 202,
+ "body": {
+ "ok": True,
+ "queued": True,
+ "delivery_state": settled["state"],
+ },
+ }
dispatch_mock = AsyncMock(side_effect=dispatch)
with patch("vibe.internal_client.dispatch_async", dispatch_mock):
@@ -204,15 +351,21 @@ def test_route_enqueues_when_turn_in_progress(isolated_state, tmp_path):
@pytest.mark.parametrize(
- ("error_kind", "expected_status"),
- (("timeout", 504), ("ambiguous", 502)),
+ ("error_kind", "expected_status", "expected_error", "expected_delivery_state"),
+ (
+ ("timeout", 504, "dispatch_pending", "reserved"),
+ ("ambiguous", 502, "dispatch_pending", "reserved"),
+ ("unavailable", 502, "internal_unavailable", "retired"),
+ ),
)
-def test_route_ambiguous_failure_settles_unowned_pending_visible_without_queueing(
+def test_route_dispatch_failure_classifies_unclaimed_delivery_outside_transcript(
isolated_state,
tmp_path,
monkeypatch,
error_kind,
expected_status,
+ expected_error,
+ expected_delivery_state,
):
from vibe import internal_client
from vibe.ui_server import app
@@ -223,6 +376,8 @@ def test_route_ambiguous_failure_settles_unowned_pending_visible_without_queuein
async def fail_after_connect(_payload):
if error_kind == "timeout":
raise internal_client.InternalServerTimeout("acceptance unknown")
+ if error_kind == "unavailable":
+ raise internal_client.InternalServerUnavailable("socket missing")
raise RuntimeError("ambiguous response")
monkeypatch.setattr(
@@ -240,12 +395,12 @@ def test_route_ambiguous_failure_settles_unowned_pending_visible_without_queuein
assert response.status_code == expected_status
body = response.get_json()
- assert body["dispatch_error"] == "dispatch_pending"
+ assert body["dispatch_error"] == expected_error
assert body["type"] == "user"
dispatch_mock.assert_awaited_once()
with create_sqlite_engine().connect() as conn:
- queued = messages_service.list_queued(conn, session_id)
+ queued = message_deliveries.list_queued(conn, session_id)
visible = messages_service.list_session_messages(
conn,
session_id=session_id,
@@ -253,9 +408,40 @@ def test_route_ambiguous_failure_settles_unowned_pending_visible_without_queuein
limit=1,
types=messages_service.TRANSCRIPT_TYPES,
)
+ delivery = message_deliveries.get_delivery(conn, body["id"])
assert queued == []
- assert [row["id"] for row in visible["messages"]] == [body["id"]]
- assert [event_type for event_type, _data in published].count("message.new") == 1
+ assert visible["messages"] == []
+ assert delivery is not None and delivery["state"] == expected_delivery_state
+ assert "message.new" not in [event_type for event_type, _data in published]
+
+
+def test_route_definitive_dispatch_rejection_retires_reserved_delivery(
+ isolated_state,
+ tmp_path,
+):
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ dispatch_mock = AsyncMock(
+ return_value={
+ "status_code": 500,
+ "body": {"error": "backend resolution failed"},
+ }
+ )
+ with patch("vibe.internal_client.dispatch_async", dispatch_mock):
+ client = app.test_client()
+ response = client.post(
+ f"/api/sessions/{session_id}/messages",
+ json={"text": "definitively rejected"},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 502
+ body = response.get_json()
+ assert body["dispatch_error"] == "dispatch_failed"
+ with create_sqlite_engine().connect() as conn:
+ delivery = message_deliveries.get_delivery(conn, body["id"])
+ assert delivery is not None and delivery["state"] == "retired"
def test_route_timeout_observes_controller_queue_without_republishing(
@@ -263,7 +449,6 @@ def test_route_timeout_observes_controller_queue_without_republishing(
tmp_path,
monkeypatch,
):
- from core.session_turns import queue_pending_user_message
from vibe import internal_client
from vibe.ui_server import app
@@ -271,12 +456,8 @@ def test_route_timeout_observes_controller_queue_without_republishing(
published = []
async def timeout_after_controller_queues(payload):
- with create_sqlite_engine().begin() as conn:
- assert queue_pending_user_message(
- conn,
- payload["user_message_id"],
- payload["text"],
- )
+ _settle_reserved_delivery(payload, state="queued")
+ published.append(("queue.updated", {"session_id": session_id}))
raise internal_client.InternalServerTimeout("response lost after enqueue")
monkeypatch.setattr(
@@ -295,185 +476,47 @@ def test_route_timeout_observes_controller_queue_without_republishing(
assert response.status_code == 504
body = response.get_json()
assert body["dispatch_error"] == "dispatch_pending"
- assert body["type"] == messages_service.QUEUED_TYPE
+ assert body["type"] == "queued"
dispatch_mock.assert_awaited_once()
with create_sqlite_engine().connect() as conn:
- queued = messages_service.list_queued(conn, session_id)
+ queued = message_deliveries.list_queued(conn, session_id)
assert [row["id"] for row in queued] == [body["id"]]
assert "message.new" not in [event_type for event_type, _data in published]
assert [event_type for event_type, _data in published].count("queue.updated") == 1
-def test_recover_stale_pending_promotes_visible_user(isolated_state, tmp_path):
+def test_startup_has_no_type_owned_pending_recovery(isolated_state, tmp_path):
from vibe import ui_server
scope_id, session_id = _make_session(tmp_path)
engine = create_sqlite_engine()
with engine.begin() as conn:
- pending = messages_service.append(
+ pending = message_deliveries.insert_delivery(
conn,
- scope_id=scope_id,
+ delivery_id="msg_reserved_startup",
session_id=session_id,
- platform="avibe",
- author="user",
- source="user",
- message_type=messages_service.PENDING_TYPE,
- text="stuck pending",
- )
-
- with patch("vibe.sse_broker.broker.publish") as publish:
- summary = ui_server._recover_stale_pending_messages()
-
- assert summary == {"promoted": 1, "deleted": 0, "skipped": 0}
- with engine.connect() as conn:
- stored = conn.execute(
- select(messages.c.type, messages.c.content_text).where(messages.c.id == pending["id"])
- ).first()
- assert stored == ("user", "stuck pending")
- published_events = [call.args[0] for call in publish.call_args_list]
- assert "message.new" in published_events
- assert "session.activity" in published_events
-
-
-def test_recover_stale_pending_deletes_archived_session_rows(isolated_state, tmp_path):
- from vibe import ui_server
-
- scope_id, session_id = _make_session(tmp_path)
- engine = create_sqlite_engine()
- with engine.begin() as conn:
- pending = messages_service.append(
- conn,
- scope_id=scope_id,
- session_id=session_id,
- platform="avibe",
- author="user",
- source="user",
- message_type=messages_service.PENDING_TYPE,
- text="archived pending",
- )
- conn.execute(
- update(agent_sessions)
- .where(agent_sessions.c.id == session_id)
- .values(status="archived", session_anchor=f"archived:{session_id}")
- )
-
- with patch("vibe.sse_broker.broker.publish") as publish:
- summary = ui_server._recover_stale_pending_messages()
-
- assert summary == {"promoted": 0, "deleted": 1, "skipped": 0}
- with engine.connect() as conn:
- stored = conn.execute(select(messages.c.id).where(messages.c.id == pending["id"])).scalar_one_or_none()
- assert stored is None
- publish.assert_not_called()
-
-
-def test_recover_stale_pending_deletes_rows_without_session(isolated_state, tmp_path):
- from vibe import ui_server
-
- scope_id, _ = _make_session(tmp_path)
- engine = create_sqlite_engine()
- with engine.begin() as conn:
- pending = messages_service.append(
- conn,
- scope_id=scope_id,
- session_id=None,
- platform="avibe",
- author="user",
- source="user",
- message_type=messages_service.PENDING_TYPE,
- text="orphaned pending",
+ priority="p1",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ text="stuck reserved",
+ ),
+ dispatch_text="stuck reserved",
)
- with patch("vibe.sse_broker.broker.publish") as publish:
- summary = ui_server._recover_stale_pending_messages()
-
- assert summary == {"promoted": 0, "deleted": 1, "skipped": 0}
+ assert not hasattr(ui_server, "_recover_stale_pending_messages")
with engine.connect() as conn:
- stored = conn.execute(
+ stored = message_deliveries.get_delivery(conn, pending["id"])
+ materialized = conn.execute(
select(messages.c.id).where(messages.c.id == pending["id"])
).scalar_one_or_none()
- assert stored is None
- publish.assert_not_called()
-
-
-def test_recover_stale_pending_skips_rows_already_retyped(isolated_state, tmp_path):
- from vibe import ui_server
-
- scope_id, session_id = _make_session(tmp_path)
- engine = create_sqlite_engine()
- with engine.begin() as conn:
- pending = messages_service.append(
- conn,
- scope_id=scope_id,
- session_id=session_id,
- platform="avibe",
- author="user",
- source="user",
- message_type=messages_service.PENDING_TYPE,
- text="already queued",
- )
- conn.execute(
- update(messages)
- .where(messages.c.id == pending["id"])
- .values(type=messages_service.QUEUED_TYPE)
- )
-
- with patch("vibe.sse_broker.broker.publish") as publish:
- summary = ui_server._recover_stale_pending_messages()
-
- assert summary == {"promoted": 0, "deleted": 0, "skipped": 0}
- with engine.connect() as conn:
- stored = conn.execute(
- select(messages.c.type).where(messages.c.id == pending["id"])
- ).scalar_one()
- assert stored == messages_service.QUEUED_TYPE
- publish.assert_not_called()
-
-
-def test_recover_stale_pending_keeps_show_owned_rows_retryable(
- isolated_state,
- tmp_path,
-):
- """Startup must not claim an unaccepted Show reservation was queued."""
-
- from core.show_session_events import ShowSessionEventStore
- from vibe import ui_server
-
- _, session_id = _make_session(tmp_path)
- store = ShowSessionEventStore()
- try:
- event = store.append(
- session_id,
- {
- "id": "show_evt_pending_recovery_owner",
- "type": "human.annotation.created",
- "annotation": {
- "comment": "Keep this reservation under Show ownership.",
- "dispatch": True,
- },
- },
- reserve_dispatch=True,
- )
- finally:
- store.close()
- assert event["message"]["type"] == messages_service.PENDING_TYPE
-
- with patch("vibe.sse_broker.broker.publish") as publish:
- summary = ui_server._recover_stale_pending_messages()
-
- assert summary == {"promoted": 0, "deleted": 0, "skipped": 1}
- store = ShowSessionEventStore()
- try:
- recovered = store.get_event(session_id, event["id"])
- finally:
- store.close()
- assert recovered is not None
- assert recovered["message"]["type"] == messages_service.PENDING_TYPE
- assert recovered["message"]["metadata"][
- messages_service.QUEUED_DISPATCH_TEXT_KEY
- ].startswith("[show-annotation] comment")
- publish.assert_not_called()
+ assert stored is not None and stored["state"] == "reserved"
+ assert materialized is None
def test_create_session_without_backend_defers_to_default_agent(isolated_state, tmp_path):
@@ -924,15 +967,6 @@ def test_chat_bootstrap_returns_first_screen_payload(isolated_state, tmp_path):
message_type="assistant",
text="thinking",
)
- messages_service.append(
- conn,
- scope_id=scope_id,
- session_id=session_id,
- platform="avibe",
- author="agent",
- message_type="tool_call",
- text="ran tool",
- )
messages_service.append(
conn,
scope_id=scope_id,
@@ -942,18 +976,13 @@ def test_chat_bootstrap_returns_first_screen_payload(isolated_state, tmp_path):
message_type="result",
text="answer",
)
- messages_service.enqueue_queued(
+ message_deliveries.enqueue_queued(
conn,
scope_id=scope_id,
session_id=session_id,
text="follow-up",
)
- messages_service.set_draft(
- conn,
- scope_id=scope_id,
- session_id=session_id,
- text="draft text",
- )
+ message_deliveries.set_draft(conn, session_id, "draft text")
async def in_flight(session_id_inner):
assert session_id_inner == session_id
@@ -1007,6 +1036,31 @@ def test_chat_bootstrap_returns_first_screen_payload(isolated_state, tmp_path):
assert body["turn_state"]["connection"] == "connected"
+def test_queue_row_send_now_passes_the_exact_delivery_id(isolated_state, tmp_path):
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ send_now = AsyncMock(
+ return_value={
+ "status_code": 409,
+ "body": {"ok": False, "code": "stale_head"},
+ }
+ )
+ with patch("vibe.internal_client.send_now", send_now):
+ client = app.test_client()
+ response = client.post(
+ f"/api/sessions/{session_id}/queue/del_requested/send-now",
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 409
+ assert response.get_json()["code"] == "stale_head"
+ send_now.assert_awaited_once_with(
+ session_id,
+ expected_delivery_id="del_requested",
+ )
+
+
def test_chat_bootstrap_keeps_timeout_turn_state_unknown(isolated_state, tmp_path):
from vibe import internal_client
from vibe.ui_server import app
@@ -1065,7 +1119,7 @@ def test_cancel_route_returns_503_when_socket_unavailable(isolated_state, tmp_pa
assert body["code"] == "internal_unavailable"
-def test_cancel_route_recovers_stale_running_status_on_not_in_flight(isolated_state, tmp_path):
+def test_cancel_route_forwards_controller_status_recovery(isolated_state, tmp_path):
from core.services import sessions as sessions_service
from storage.db import create_sqlite_engine
from vibe.ui_server import app
@@ -1076,7 +1130,14 @@ def test_cancel_route_recovers_stale_running_status_on_not_in_flight(isolated_st
assert sessions_service.set_agent_status(conn, session_id, "running") is True
cancel_mock = AsyncMock(
- return_value={"status_code": 404, "body": {"ok": False, "code": "not_in_flight"}}
+ return_value={
+ "status_code": 404,
+ "body": {
+ "ok": False,
+ "code": "not_in_flight",
+ "recovered_agent_status": True,
+ },
+ }
)
with patch("vibe.internal_client.cancel_dispatch", cancel_mock):
client = app.test_client()
@@ -1088,7 +1149,7 @@ def test_cancel_route_recovers_stale_running_status_on_not_in_flight(isolated_st
assert body["code"] == "not_in_flight"
assert body["recovered_agent_status"] is True
with engine.connect() as conn:
- assert sessions_service.get_session(conn, session_id)["agent_status"] == "idle"
+ assert sessions_service.get_session(conn, session_id)["agent_status"] == "running"
def test_cancel_route_does_not_recover_failed_status_on_not_in_flight(isolated_state, tmp_path):
@@ -1151,7 +1212,7 @@ def test_turn_state_route_returns_504_on_probe_timeout(isolated_state, tmp_path)
assert response.get_json()["error"]["code"] == "turn_state_timeout"
-def test_turn_state_idle_recovers_stale_running_status(isolated_state, tmp_path):
+def test_turn_state_forwards_controller_status_recovery(isolated_state, tmp_path):
from core.services import sessions as sessions_service
from storage.db import create_sqlite_engine
from vibe.ui_server import app
@@ -1163,7 +1224,10 @@ def test_turn_state_idle_recovers_stale_running_status(isolated_state, tmp_path)
async def idle(session_id_inner):
assert session_id_inner == session_id
- return {"status_code": 200, "body": {"in_flight": False}}
+ return {
+ "status_code": 200,
+ "body": {"in_flight": False, "recovered_agent_status": True},
+ }
with patch("vibe.internal_client.turn_state", idle):
client = app.test_client()
@@ -1174,7 +1238,7 @@ def test_turn_state_idle_recovers_stale_running_status(isolated_state, tmp_path)
assert body["in_flight"] is False
assert body["recovered_agent_status"] is True
with engine.connect() as conn:
- assert sessions_service.get_session(conn, session_id)["agent_status"] == "idle"
+ assert sessions_service.get_session(conn, session_id)["agent_status"] == "running"
def test_turn_state_route_preserves_orthogonal_runtime_axes(isolated_state, tmp_path):
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 73a6100ff..7d044936a 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -37,6 +37,7 @@ from tests.test_ui_remote_access_auth import _mock_interface, _remote_peer, _sav
from tests.ui_server_test_helpers import csrf_headers
from vibe import remote_access, ui_server
from vibe.ui_server import app
+from storage import message_deliveries
class _FakeShowRuntimeManager:
@@ -178,17 +179,53 @@ def _create_agent_session(session_id: str, *, status: str = "active") -> None:
def _accept_dispatch(payload: dict, message_type: str = "harness") -> None:
- from core.session_turns import queue_pending_user_message
- from storage import messages_service
+ from storage import message_deliveries
from storage.db import create_sqlite_engine
- if message_type == messages_service.QUEUED_TYPE:
- with create_sqlite_engine().begin() as conn:
- assert queue_pending_user_message(
+ with create_sqlite_engine().begin() as conn:
+ delivery = message_deliveries.get_delivery(conn, payload["user_message_id"])
+ assert delivery is not None
+ if message_type == "queued":
+ assert message_deliveries.cas_delivery(
conn,
- payload["user_message_id"],
- payload["text"],
+ delivery["id"],
+ expected_version=delivery["version"],
+ expected_states=("reserved",),
+ values={"state": "queued"},
)
+ return
+ turn_id = message_deliveries.new_turn_id()
+ message_deliveries.insert_turn(
+ conn,
+ turn_id=turn_id,
+ session_id=delivery["session_id"],
+ initial_delivery_id=delivery["id"],
+ state="starting",
+ backend="codex",
+ )
+ attempt_id = message_deliveries.new_attempt_id()
+ assert message_deliveries.open_start_attempt(
+ conn,
+ delivery["id"],
+ expected_version=delivery["version"],
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ )
+ turn = message_deliveries.get_turn(conn, turn_id)
+ assert turn is not None
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ runtime_key=f"runtime:{turn_id}",
+ runtime_turn_id=f"runtime-turn:{turn_id}",
+ native_turn_id=f"native:{turn_id}",
+ ) is not None
+ assert message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
def _write_runtime_archive(tmp_path: Path, *, text: str = "#!/usr/bin/env node\n") -> Path:
@@ -2100,13 +2137,7 @@ def test_private_show_page_idle_dispatch_promotes_visible_harness_row(monkeypatc
assert dispatches[0]["user_message_id"] == response.get_json()["event"]["message_id"]
assert dispatches[0]["files"] == []
assert "dispatch_owner" not in dispatches[0]
- assert [event_type for event_type, _data in published] == [
- "show.event",
- "message.new",
- "session.activity",
- ]
- assert published[1][1]["type"] == "harness"
- assert published[1][1]["author_name"] == "show_intent"
+ assert [event_type for event_type, _data in published] == ["show.event"]
from storage import messages_service
from storage.db import create_sqlite_engine
@@ -2177,12 +2208,10 @@ def test_private_show_page_waits_for_turn_acceptance_before_responding(monkeypat
assert dispatch_kwargs == {"timeout": None}
-def test_private_show_page_unavailable_dispatch_keeps_row_pending_and_returns_502(
+def test_private_show_page_definitive_dispatch_rejection_retires_and_returns_502(
monkeypatch,
tmp_path,
):
- from vibe import internal_client
-
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
_create_agent_session("ses123")
@@ -2196,7 +2225,7 @@ def test_private_show_page_unavailable_dispatch_keeps_row_pending_and_returns_50
)
async def fake_dispatch_async(payload, **kwargs):
- raise internal_client.InternalServerUnavailable("controller unavailable")
+ return {"status_code": 500, "body": {"ok": False}}
with patch("vibe.internal_client.dispatch_async", fake_dispatch_async):
response = app.test_client().post(
@@ -2221,18 +2250,18 @@ def test_private_show_page_unavailable_dispatch_keeps_row_pending_and_returns_50
body = response.get_json()
assert body["ok"] is False
assert body["code"] == "show_event_dispatch_failed"
- # No turn started, so the reservation remains outside the transcript.
- assert body["event"]["message"]["type"] == "pending"
- assert body["event"]["message"]["author_name"] == "show_annotation"
+ # No turn started, so the retired submission remains outside the transcript.
+ assert body["event"]["message"] is None
+ assert body["event"]["message_id"] is None
+ assert body["event"]["delivery"]["state"] == "retired"
+ assert body["event"]["delivery"]["author_name"] == "show_annotation"
assert [event_type for event_type, _data in published] == ["show.event"]
-def test_private_show_page_concurrent_dispatch_replay_returns_pending(
+def test_private_show_page_concurrent_dispatch_replay_returns_reserved_delivery(
monkeypatch,
tmp_path,
):
- from storage import messages_service
-
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
_create_agent_session("ses123")
@@ -2269,63 +2298,32 @@ def test_private_show_page_concurrent_dispatch_replay_returns_pending(
body = response.get_json()
assert body["ok"] is True
assert body["dispatch_pending"] is True
- assert body["event"]["message"]["type"] == messages_service.PENDING_TYPE
+ assert body["event"]["message"] is None
+ assert body["event"]["delivery"]["state"] == "reserved"
-def test_legacy_settled_show_dispatch_replay_does_not_require_reserved_prompt(
- monkeypatch,
-):
- from storage import messages_service
+def test_dispatching_show_event_requires_delivery_authority(monkeypatch):
async def unexpected_dispatch(*_args, **_kwargs):
- pytest.fail("a settled legacy Show input must not dispatch again")
+ pytest.fail("a current annotation without its reserved prompt must not dispatch")
monkeypatch.setattr("vibe.internal_client.dispatch_async", unexpected_dispatch)
outcome = asyncio.run(
ui_server._run_show_event_dispatch(
{
- "id": "show_evt_legacy_settled",
- "session_id": "ses123",
- "message": {
- "id": "msg_legacy_settled",
- "type": messages_service.HARNESS_TYPE,
- "metadata": {},
- },
- }
- )
- )
-
- assert outcome is ui_server._ShowEventDispatchOutcome.ACCEPTED
-
-
-def test_legacy_pending_show_dispatch_replays_stored_prompt(monkeypatch):
- from storage import messages_service
-
- dispatched = {}
-
- async def accept_dispatch(payload, **_kwargs):
- dispatched.update(payload)
- return {"status_code": 202, "body": {"ok": True}}
-
- monkeypatch.setattr("vibe.internal_client.dispatch_async", accept_dispatch)
- monkeypatch.setattr(
- ui_server,
- "_settle_show_event_message",
- lambda _event: {"type": messages_service.HARNESS_TYPE},
- )
- outcome = asyncio.run(
- ui_server._run_show_event_dispatch(
- {
- "id": "show_evt_legacy_pending",
+ "id": "show_evt_missing_prompt",
"session_id": "ses123",
"type": "human.annotation.created",
- "transcript_text": "[show-annotation] comment\n\nLegacy prompt",
- "payload": {"intent": "comment"},
+ "transcript_text": "Visible words only",
"message": {
- "id": "msg_legacy_pending",
- "type": messages_service.PENDING_TYPE,
+ "id": "msg_missing_prompt",
+ "type": "annotation",
"content": {
- "text": "[show-annotation] comment\n\nLegacy prompt",
+ "text": "Visible words only",
+ "annotation": {
+ "direction": "user",
+ "action": "created",
+ },
},
"metadata": {},
},
@@ -2333,41 +2331,23 @@ def test_legacy_pending_show_dispatch_replays_stored_prompt(monkeypatch):
)
)
- assert outcome is ui_server._ShowEventDispatchOutcome.ACCEPTED
- assert dispatched["text"] == (
- "[show-annotation] comment\n\nLegacy prompt\n\n"
- "Show event id: show_evt_legacy_pending\n\n"
- "如需在页面上原位回应,可执行:\n"
- " vibe show reply show_evt_legacy_pending --message '<你的回答>'\n"
- "(也可以直接修改页面内容来响应,按场景选择。)"
- )
+ assert outcome is ui_server._ShowEventDispatchOutcome.FAILED
-def test_current_pending_annotation_never_dispatches_display_body(monkeypatch):
- from storage import messages_service
-
+def test_reserved_show_dispatch_rejects_whitespace_only_dispatch_text(monkeypatch):
async def unexpected_dispatch(*_args, **_kwargs):
- pytest.fail("a current annotation without its reserved prompt must not dispatch")
+ pytest.fail("a blank Show prompt must not start a turn")
monkeypatch.setattr("vibe.internal_client.dispatch_async", unexpected_dispatch)
outcome = asyncio.run(
ui_server._run_show_event_dispatch(
{
- "id": "show_evt_missing_prompt",
+ "id": "show_evt_blank_prompt",
"session_id": "ses123",
- "type": "human.annotation.created",
- "transcript_text": "Visible words only",
- "message": {
- "id": "msg_missing_prompt",
- "type": messages_service.PENDING_TYPE,
- "content": {
- "text": "Visible words only",
- "annotation": {
- "direction": "user",
- "action": "created",
- },
- },
- "metadata": {},
+ "delivery": {
+ "id": "msg_blank_prompt",
+ "state": "reserved",
+ "dispatch_text": " \n\t ",
},
}
)
@@ -2376,33 +2356,40 @@ def test_current_pending_annotation_never_dispatches_display_body(monkeypatch):
assert outcome is ui_server._ShowEventDispatchOutcome.FAILED
-def test_pending_show_dispatch_rejects_whitespace_only_reserved_prompt(monkeypatch):
- from storage import messages_service
-
+ "delivery_state",
+ [
+ "queued",
+ "claimed",
+ "pending_steer",
+ "steering",
+ "reconciling_steer",
+ "interrupt_waiting",
+ ],
+)
+def test_show_dispatch_replay_accepts_existing_admission(monkeypatch, delivery_state):
async def unexpected_dispatch(*_args, **_kwargs):
- pytest.fail("a blank Show prompt must not start a turn")
+ pytest.fail("an admitted Show Delivery must not be dispatched twice")
monkeypatch.setattr("vibe.internal_client.dispatch_async", unexpected_dispatch)
outcome = asyncio.run(
ui_server._run_show_event_dispatch(
{
- "id": "show_evt_blank_prompt",
+ "id": "show_evt_admitted",
"session_id": "ses123",
- "message": {
- "id": "msg_blank_prompt",
- "type": messages_service.PENDING_TYPE,
- "metadata": {
- messages_service.QUEUED_DISPATCH_TEXT_KEY: " \n\t ",
- },
+ "delivery": {
+ "id": "msg_admitted",
+ "state": delivery_state,
+ "dispatch_text": "already admitted",
},
}
)
)
- assert outcome is ui_server._ShowEventDispatchOutcome.FAILED
+ assert outcome is ui_server._ShowEventDispatchOutcome.ACCEPTED
-def test_private_show_page_returns_promoted_row_after_synchronous_queue_drain(
+def test_private_show_page_materializes_same_submission_after_synchronous_acceptance(
monkeypatch,
tmp_path,
):
@@ -2420,29 +2407,8 @@ def test_private_show_page_returns_promoted_row_after_synchronous_queue_drain(
settled = {}
async def fake_dispatch_async(payload, **kwargs):
- from core import session_turns
- from storage import messages_service
- from storage.db import create_sqlite_engine
-
- with create_sqlite_engine().begin() as conn:
- assert session_turns.queue_pending_user_message(
- conn,
- payload["user_message_id"],
- payload["text"],
- )
- segment = messages_service.list_queued(conn, "ses123")
- metadata = dict(segment[0]["metadata"])
- metadata.pop(session_turns.QUEUED_DISPATCH_TEXT_KEY)
- visible = session_turns._promote_merged_user_segment(
- conn,
- segment,
- text=segment[0]["text"],
- attachments=[],
- metadata=metadata,
- author_id=None,
- )
_accept_dispatch(payload)
- settled.update(original_id=payload["user_message_id"], visible=visible)
+ settled["submission_id"] = payload["user_message_id"]
return {"status_code": 202, "body": {"ok": True, "drained": True}}
with patch("vibe.internal_client.dispatch_async", fake_dispatch_async):
@@ -2466,9 +2432,8 @@ def test_private_show_page_returns_promoted_row_after_synchronous_queue_drain(
assert response.status_code == 201
event = response.get_json()["event"]
- assert settled["visible"]["id"] != settled["original_id"]
- assert event["message_id"] == settled["visible"]["id"]
- assert event["message"]["id"] == settled["visible"]["id"]
+ assert event["message_id"] == settled["submission_id"]
+ assert event["message"]["id"] == settled["submission_id"]
assert event["message"]["type"] == "annotation"
assert event["message"]["author_name"] == "show_annotation"
# The real manager already publishes the promoted row. The route only
@@ -2489,9 +2454,7 @@ def test_private_show_page_busy_dispatch_queues_without_message_new(monkeypatch,
dispatch_done = asyncio.Event()
async def fake_dispatch_async(payload, **kwargs):
- from storage import messages_service
-
- _accept_dispatch(payload, messages_service.QUEUED_TYPE)
+ _accept_dispatch(payload, "queued")
dispatch_done.set()
return {"status_code": 202, "body": {"ok": True, "queued": True}}
@@ -2516,13 +2479,13 @@ def test_private_show_page_busy_dispatch_queues_without_message_new(monkeypatch,
assert response.status_code == 201
asyncio.run(asyncio.wait_for(dispatch_done.wait(), timeout=1))
- message_id = response.get_json()["event"]["message_id"]
+ delivery_id = response.get_json()["event"]["delivery"]["id"]
from storage import messages_service
from storage.db import create_sqlite_engine
with create_sqlite_engine().connect() as conn:
- queued = messages_service.list_queued(conn, "ses123")
+ queued = message_deliveries.list_queued(conn, "ses123")
transcript = messages_service.list_session_messages(
conn,
session_id="ses123",
@@ -2531,7 +2494,7 @@ def test_private_show_page_busy_dispatch_queues_without_message_new(monkeypatch,
tail=True,
)
assert [(message["id"], message["text"]) for message in queued] == [
- (message_id, response.get_json()["event"]["transcript_text"])
+ (delivery_id, response.get_json()["event"]["transcript_text"])
]
assert transcript["messages"] == []
assert [event_type for event_type, _data in published] == ["show.event", "queue.updated"]
@@ -3047,12 +3010,13 @@ def test_public_show_page_events_redact_internal_ids(monkeypatch, tmp_path):
event = store.append(
"ses123",
{
- "type": "assistant.mark.created",
- "mark": {
- "target": "summary",
- "body": "body",
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "body",
+ "dispatch": True,
},
},
+ reserve_dispatch=True,
)
finally:
store.close()
@@ -3062,12 +3026,14 @@ def test_public_show_page_events_redact_internal_ids(monkeypatch, tmp_path):
assert response.status_code == 200
public_event = response.get_json()["events"][0]
assert public_event["id"] == event["id"]
- assert public_event["type"] == "assistant.mark.created"
- assert public_event["payload"]["body"] == "body"
+ assert public_event["type"] == "human.annotation.created"
+ assert public_event["payload"]["comment"] == "body"
assert "session_id" not in public_event
assert "scope_id" not in public_event
assert "message_id" not in public_event
assert "message" not in public_event
+ assert "delivery_id" not in public_event
+ assert "delivery" not in public_event
def test_public_show_events_stream_redacts_internal_ids(monkeypatch, tmp_path):
@@ -3084,12 +3050,13 @@ def test_public_show_events_stream_redacts_internal_ids(monkeypatch, tmp_path):
"ses123",
{
"id": "show_evt_public",
- "type": "assistant.mark.created",
- "mark": {
- "target": "summary",
- "body": "body",
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "body",
+ "dispatch": True,
},
},
+ reserve_dispatch=True,
)
finally:
store.close()
@@ -3113,6 +3080,8 @@ def test_public_show_events_stream_redacts_internal_ids(monkeypatch, tmp_path):
assert '"scope_id"' not in body
assert '"message_id"' not in body
assert '"message"' not in body
+ assert '"delivery_id"' not in body
+ assert '"delivery"' not in body
def test_public_show_events_stream_redacts_screenshot_path(monkeypatch, tmp_path):
diff --git a/tests/test_vibe_agent_archive.py b/tests/test_vibe_agent_archive.py
index b9af67799..9c2d2f611 100644
--- a/tests/test_vibe_agent_archive.py
+++ b/tests/test_vibe_agent_archive.py
@@ -22,10 +22,12 @@ from storage.background import (
SQLiteBackgroundTaskStore,
definition_state_unchanged,
)
+from storage import message_deliveries as delivery_store
from storage.models import (
agent_runs,
agent_sessions,
agents,
+ message_deliveries,
messages,
run_definitions,
scope_settings,
@@ -189,32 +191,212 @@ def _seed_references(store: VibeAgentStore, agent_name: str) -> None:
metadata_json="{}",
)
)
- conn.execute(
- messages.insert().values(
- id="msg_queued_archive",
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id="msg_queued_archive",
+ session_id="ses_archive",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
scope_id=SCOPE_ID,
session_id="ses_archive",
platform="avibe",
author="harness",
- type="queued",
source="harness",
- content_text="continue",
- content_json=json.dumps({"text": "continue"}),
- metadata_json=json.dumps(
- {
- "scheduled_provenance": {
- "platform_specific": {
- "vibe_agent_name": agent_name,
- "scheduled_target_agent_name": agent_name,
- "agent_session_target": {"agent_name": agent_name},
- }
+ message_type="harness",
+ text="continue",
+ metadata={
+ "scheduled_provenance": {
+ "platform_specific": {
+ "vibe_agent_name": agent_name,
+ "scheduled_target_agent_name": agent_name,
+ "agent_session_target": {"agent_name": agent_name},
}
}
- ),
- created_at=NOW,
- updated_at=NOW,
+ },
+ ),
+ dispatch_text="continue",
+ now=NOW,
+ )
+
+
+def _seed_dispatchable_delivery_states(store: VibeAgentStore, agent_name: str) -> dict[str, str]:
+ states = (
+ "reserved",
+ "queued",
+ "claimed",
+ "pending_steer",
+ "steering",
+ "interrupt_waiting",
+ "reconciling_steer",
+ )
+ seeded: dict[str, str] = {}
+
+ def snapshot(session_id: str) -> dict[str, object]:
+ return delivery_store.message_snapshot(
+ scope_id=SCOPE_ID,
+ session_id=session_id,
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="continue",
+ metadata={
+ "scheduled_provenance": {
+ "platform_specific": {
+ "vibe_agent_name": agent_name,
+ "scheduled_target_agent_name": agent_name,
+ "agent_session_target": {"agent_name": agent_name},
+ }
+ }
+ },
+ )
+
+ with store.engine.begin() as conn:
+ for state in states:
+ session_id = f"ses_archive_{state}"
+ delivery_id = f"del_archive_{state}"
+ seeded[state] = delivery_id
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=SCOPE_ID,
+ agent_id=None,
+ agent_name=None,
+ agent_backend="claude",
+ agent_variant="claude",
+ model=None,
+ reasoning_effort=None,
+ session_anchor=session_id,
+ workdir="/tmp/archive-test",
+ native_session_id="",
+ title=None,
+ status="active",
+ visibility="background",
+ pinned=0,
+ agent_status="idle",
+ metadata_json="{}",
+ created_at=NOW,
+ updated_at=NOW,
+ last_active_at=NOW,
+ )
+ )
+ target = delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=session_id,
+ priority="p1",
+ state="queued" if state == "queued" else "reserved",
+ snapshot=snapshot(session_id),
+ dispatch_text="continue",
+ now=NOW,
)
+
+ if state == "claimed":
+ delivery_store.claim_start_batch(
+ conn,
+ turn_id=f"turn_archive_{state}",
+ session_id=session_id,
+ backend="claude",
+ deliveries=[target],
+ dispatch_text="continue",
+ )
+ elif state in {"pending_steer", "steering", "reconciling_steer"}:
+ anchor_id = f"anchor_archive_{state}"
+ anchor = delivery_store.insert_delivery(
+ conn,
+ delivery_id=anchor_id,
+ session_id=session_id,
+ priority="p3",
+ state="reserved",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=SCOPE_ID,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="anchor",
+ ),
+ dispatch_text="anchor",
+ now=NOW,
+ )
+ turn_id = f"turn_archive_{state}"
+ claimed = delivery_store.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend="claude",
+ deliveries=[anchor],
+ dispatch_text="anchor",
+ )
+ attempt_id = f"attempt_archive_{state}"
+ if state == "pending_steer":
+ delivery_store.open_pending_steer_batch(
+ conn,
+ deliveries=[target],
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ )
+ else:
+ turn = delivery_store.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(claimed["turn"]["version"]),
+ runtime_key=f"runtime-{state}",
+ runtime_turn_id=f"runtime-turn-{state}",
+ native_turn_id=f"native-{state}",
+ )
+ assert turn is not None
+ steering = delivery_store.open_steer_attempt(
+ conn,
+ delivery_id,
+ expected_version=int(target["version"]),
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ expected_native_turn_id=f"native-{state}",
+ )
+ assert steering is not None
+ if state == "reconciling_steer":
+ assert delivery_store.mark_attempt_unknown(
+ conn,
+ delivery_id,
+ expected_version=int(steering["version"]),
+ receipt={"kind": "lost_receipt"},
+ ) is not None
+ elif state == "interrupt_waiting":
+ turn_id = f"turn_archive_{state}"
+ delivery_store.insert_turn(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ initial_delivery_id=delivery_id,
+ state="waiting",
+ backend="claude",
+ now=NOW,
+ )
+ assert delivery_store.cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(target["version"]),
+ expected_states=("reserved",),
+ values={
+ "state": "interrupt_waiting",
+ "turn_id": turn_id,
+ "turn_role": "initial",
+ "turn_position": 0,
+ },
+ ) is not None
+
+ observed = set(
+ conn.execute(
+ select(message_deliveries.c.state).where(
+ message_deliveries.c.id.in_(tuple(seeded.values()))
+ )
+ ).scalars()
)
+ assert observed == set(states)
+ return seeded
def test_archive_atomically_moves_live_references_and_hides_agent(tmp_path) -> None:
@@ -265,9 +447,11 @@ def test_archive_atomically_moves_live_references_and_hides_agent(tmp_path) -> N
session = conn.execute(select(agent_sessions)).mappings().one()
definitions = conn.execute(select(run_definitions).order_by(run_definitions.c.id)).mappings().all()
runs = conn.execute(select(agent_runs.c.status, agent_runs.c.agent_name)).mappings().all()
- queued_metadata = json.loads(
+ queued_snapshot = json.loads(
conn.execute(
- select(messages.c.metadata_json).where(messages.c.id == "msg_queued_archive")
+ select(message_deliveries.c.snapshot_json).where(
+ message_deliveries.c.id == "msg_queued_archive"
+ )
).scalar_one()
)
assert scope["agent_name"] == result.archived_name
@@ -295,10 +479,12 @@ def test_archive_atomically_moves_live_references_and_hides_agent(tmp_path) -> N
for row in runs
if row["status"] in {"succeeded", "failed", "canceled"}
} == {"pm"}
- queued_spec = queued_metadata["scheduled_provenance"]["platform_specific"]
- assert queued_spec["vibe_agent_name"] == result.archived_name
- assert queued_spec["scheduled_target_agent_name"] == result.archived_name
- assert queued_spec["agent_session_target"]["agent_name"] == result.archived_name
+ queued_spec = json.loads(queued_snapshot["metadata_json"])["scheduled_provenance"][
+ "platform_specific"
+ ]
+ assert queued_spec["vibe_agent_name"] == "pm"
+ assert queued_spec["scheduled_target_agent_name"] == "pm"
+ assert queued_spec["agent_session_target"]["agent_name"] == "pm"
replacement = store.create(name="pm", backend="claude")
assert replacement.id != original.id
@@ -306,6 +492,46 @@ def test_archive_atomically_moves_live_references_and_hides_agent(tmp_path) -> N
store.close()
+def test_archive_never_rewrites_immutable_delivery_snapshots(tmp_path) -> None:
+ store = VibeAgentStore(tmp_path / "state" / "vibe.sqlite")
+ try:
+ store.create(name="claude-fallback", backend="claude")
+ store.create(name="pm", backend="claude")
+ _seed_references(store, "pm")
+ seeded = _seed_dispatchable_delivery_states(store, "pm")
+
+ with store.engine.connect() as conn:
+ before = {
+ str(row["id"]): str(row["snapshot_json"])
+ for row in conn.execute(
+ select(
+ message_deliveries.c.id,
+ message_deliveries.c.snapshot_json,
+ ).where(message_deliveries.c.id.in_(tuple(seeded.values())))
+ ).mappings()
+ }
+
+ result = store.archive("pm")
+
+ assert result is not None
+ with store.engine.connect() as conn:
+ rows = conn.execute(
+ select(
+ message_deliveries.c.id,
+ message_deliveries.c.state,
+ message_deliveries.c.snapshot_json,
+ ).where(message_deliveries.c.id.in_(tuple(seeded.values())))
+ ).mappings()
+ after = {
+ str(row["id"]): str(row["snapshot_json"])
+ for row in rows
+ }
+ assert result is not None
+ assert after == before
+ finally:
+ store.close()
+
+
def test_update_holds_the_write_lock_before_checking_archived_state(tmp_path) -> None:
db_path = tmp_path / "state" / "vibe.sqlite"
primary = VibeAgentStore(db_path)
@@ -1120,8 +1346,10 @@ def test_archive_moves_normalized_equivalent_references(tmp_path, stored_name: s
agent_runs.c.status.in_(("pending", "queued", "processing", "running"))
)
).scalars().all()
- queued_metadata = conn.execute(
- select(messages.c.metadata_json).where(messages.c.id == "msg_queued_archive")
+ queued_snapshot = conn.execute(
+ select(message_deliveries.c.snapshot_json).where(
+ message_deliveries.c.id == "msg_queued_archive"
+ )
).scalar_one()
assert scope["agent_name"] == result.archived_name
assert json.loads(scope["settings_json"])["routing"] == {
@@ -1139,10 +1367,12 @@ def test_archive_moves_normalized_equivalent_references(tmp_path, stored_name: s
"session_settings_snapshot"
]["agent_name"] == stored_name
assert set(live_runs) == {result.archived_name}
- queued_spec = json.loads(queued_metadata)["scheduled_provenance"]["platform_specific"]
- assert queued_spec["vibe_agent_name"] == result.archived_name
- assert queued_spec["scheduled_target_agent_name"] == result.archived_name
- assert queued_spec["agent_session_target"]["agent_name"] == result.archived_name
+ queued_spec = json.loads(json.loads(queued_snapshot)["metadata_json"])[
+ "scheduled_provenance"
+ ]["platform_specific"]
+ assert queued_spec["vibe_agent_name"] == stored_name
+ assert queued_spec["scheduled_target_agent_name"] == stored_name
+ assert queued_spec["agent_session_target"]["agent_name"] == stored_name
finally:
store.close()
diff --git a/tests/test_watches.py b/tests/test_watches.py
index b41e17bc7..f32a7564f 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -1085,7 +1085,12 @@ def test_managed_watch_service_forever_retries_only_allowed_exit_code(tmp_path:
async def _run() -> None:
await _start_watch_service(service)
- await asyncio.sleep(0.08)
+ deadline = asyncio.get_running_loop().time() + 2
+ while asyncio.get_running_loop().time() < deadline:
+ saved = store.get_watch(watch.id)
+ if saved is not None and saved.last_exit_code == 75:
+ break
+ await asyncio.sleep(0.01)
await service.stop()
asyncio.run(_run())
diff --git a/tests/test_web_push_notifications.py b/tests/test_web_push_notifications.py
index af9b167e4..0c7bf86bb 100644
--- a/tests/test_web_push_notifications.py
+++ b/tests/test_web_push_notifications.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from core import web_push_notifications
-from storage import messages_service, web_push_service
+from storage import message_deliveries, messages_service, web_push_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_sessions
@@ -642,16 +642,22 @@ def test_send_to_enabled_subscriptions_ignores_queued_owner(monkeypatch, tmp_pat
last_active_at=now,
)
)
- messages_service.append(
+ message_deliveries.insert_delivery(
conn,
- scope_id=scope_id,
+ delivery_id="msg_queued_owner",
session_id="ses_queued_owner",
- platform="avibe",
- author="user",
- source="user",
- message_type=messages_service.QUEUED_TYPE,
- metadata={"_web_push_user_key": "remote:user-b"},
- text="queued while prior turn runs",
+ priority="p3",
+ state="queued",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id="ses_queued_owner",
+ platform="avibe",
+ author="user",
+ source="user",
+ metadata={"_web_push_user_key": "remote:user-b"},
+ text="queued while prior turn runs",
+ ),
+ dispatch_text="queued while prior turn runs",
)
message = messages_service.append(
conn,
diff --git a/tests/test_workspace_system_session.py b/tests/test_workspace_system_session.py
index e8926ea94..1620d4850 100644
--- a/tests/test_workspace_system_session.py
+++ b/tests/test_workspace_system_session.py
@@ -26,6 +26,7 @@ from pathlib import Path
import pytest
from sqlalchemy import select, text
+from sqlalchemy.exc import IntegrityError
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -668,28 +669,22 @@ def test_a_scoped_clear_cannot_reach_the_reserved_row(monkeypatch, tmp_path: Pat
assert messages_service.get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID) is not None
-def test_a_deleted_reserved_row_heals_back_to_system(monkeypatch, tmp_path: Path) -> None:
- """Round-12 doctrine: DURABILITY BY LAZY RECREATION, not by a delete exemption.
-
- No new guard is added for raw deletes. If any machinery removes the row, the next
- notice recreates it — under its reserved primary key, its reserved anchor, and now
- ``system``, so the recreated row is projected exactly like the original.
- """
+def test_an_accepted_notice_prevents_raw_session_deletion(monkeypatch, tmp_path: Path) -> None:
+ """Accepted communication keeps its Session graph intact."""
db_path = _migrated_db(monkeypatch, tmp_path)
engine = _reserved_with_one_notice(db_path)
- with engine.begin() as conn:
- conn.execute(
- text("DELETE FROM agent_sessions WHERE id = :sid"), {"sid": WORKSPACE_NOTICE_SESSION_ID}
- )
- with engine.begin() as conn:
- assert resolve_workspace_notice_session(conn, title="Workspace notifications") == (
- WORKSPACE_NOTICE_SESSION_ID
- )
+ with pytest.raises(IntegrityError):
+ with engine.begin() as conn:
+ conn.execute(
+ text("DELETE FROM agent_sessions WHERE id = :sid"),
+ {"sid": WORKSPACE_NOTICE_SESSION_ID},
+ )
with engine.connect() as conn:
row = conn.execute(
select(agent_sessions.c.visibility, agent_sessions.c.session_anchor, agent_sessions.c.status)
.where(agent_sessions.c.id == WORKSPACE_NOTICE_SESSION_ID)
).mappings().one()
+ assert messages_service.get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID) is not None
assert row["visibility"] == "system"
assert row["session_anchor"] == WORKSPACE_NOTICE_SESSION_ANCHOR
assert row["status"] == "active"
diff --git a/ui/src/lib/agentActivity.test.ts b/ui/src/lib/agentActivity.test.ts
index ed4126c56..ff66f70b5 100644
--- a/ui/src/lib/agentActivity.test.ts
+++ b/ui/src/lib/agentActivity.test.ts
@@ -247,9 +247,9 @@ describe('shouldShowRunningCard', () => {
});
describe('isActivityMessageType', () => {
- it('is true only for assistant + tool_call', () => {
+ it('recognizes only Message-backed assistant activity', () => {
expect(isActivityMessageType('assistant')).toBe(true);
- expect(isActivityMessageType('tool_call')).toBe(true);
+ expect(isActivityMessageType('tool_call')).toBe(false);
expect(isActivityMessageType('result')).toBe(false);
expect(isActivityMessageType('user')).toBe(false);
});
diff --git a/ui/src/lib/messageTypes.test.ts b/ui/src/lib/messageTypes.test.ts
index 7cc844e1b..588b623a1 100644
--- a/ui/src/lib/messageTypes.test.ts
+++ b/ui/src/lib/messageTypes.test.ts
@@ -26,21 +26,10 @@ describe('message type catalog reader', () => {
});
});
-// ===== One-time equivalence oracle =====
-// The five predicates as they read BEFORE this lane replaced their inline type-name
-// lists with catalog lookups. This is frozen historical behavior, NOT a catalog
-// mirror to maintain: it is asserted only over ``PRE_REFACTOR_TYPES`` — the names
-// that existed at the refactor — so a type added to the catalog later is out of its
-// scope by construction. A failure here means a catalog value and the frontend's
-// former behavior disagree, which is a drift finding to raise, not a snapshot to
-// quietly update.
-const PRE_REFACTOR_TYPES = [
- 'user',
- 'harness',
- 'result',
- 'notify',
- 'error',
- 'assistant',
+// Operational state and process events no longer masquerade as Session Messages.
+// Keep this list as a migration boundary: these names must resolve to neutral catalog
+// defaults even when an old browser or deep link presents one.
+const RETIRED_PSEUDO_MESSAGE_TYPES = [
'tool_call',
'queued',
'draft',
@@ -49,29 +38,37 @@ const PRE_REFACTOR_TYPES = [
'silent',
] as const;
-// Unknown / non-type strings the predicates must also agree on. ``show_annotation``
-// is one of them on purpose: it is an ``author_name``, never a message type, and
-// keeping it here pins that it does not become one by the back door.
-//
-// ``annotation`` is deliberately absent. This block is an equivalence oracle
-// against pre-refactor behavior, and ``annotation`` is behavior that did not
-// exist then — it had no type, so the transcript reached it through
-// ``metadata.source``. Its behavior is pinned by the tests that own it
-// (chatMessageTypes / AnnotationMessage), not by an oracle it postdates.
-const PROBE_TYPES: readonly string[] = [...PRE_REFACTOR_TYPES, 'show_annotation', 'future_type', ''];
+const CANONICAL_MESSAGE_TYPES = [
+ 'user',
+ 'harness',
+ 'annotation',
+ 'result',
+ 'notify',
+ 'error',
+ 'assistant',
+] as const;
+
+const PROBE_TYPES: readonly string[] = [
+ ...CANONICAL_MESSAGE_TYPES,
+ ...RETIRED_PSEUDO_MESSAGE_TYPES,
+ 'show_annotation',
+ 'future_type',
+ '',
+];
const wasTranscript = (type: string): boolean =>
type === 'user' ||
type === 'harness' ||
+ type === 'annotation' ||
type === 'result' ||
type === 'error' ||
type === 'notify';
const wasNotify = (type: string): boolean => type === 'notify' || type === 'error';
-const wasActivity = (type: string): boolean => type === 'assistant' || type === 'tool_call';
+const wasActivity = (type: string): boolean => type === 'assistant';
-const wasHarnessInputType = (type: string): boolean => type === 'harness';
+const wasHarnessInputType = (type: string): boolean => type === 'harness' || type === 'annotation';
type TerminalCandidate = { author: string; type: string; metadata?: Record<string, unknown> | null };
@@ -81,7 +78,14 @@ const wasTerminalAgentMessage = (message: TerminalCandidate): boolean =>
message.type === 'error' ||
(message.type === 'notify' && message.metadata?.event === 'backend_failure'));
-describe('catalog-derived predicates match pre-refactor behavior', () => {
+describe('catalog-derived predicates match the communication-record boundary', () => {
+ it('does not declare retired pseudo-message types', () => {
+ for (const type of RETIRED_PSEUDO_MESSAGE_TYPES) {
+ expect(messageTypeNames(), type).not.toContain(type);
+ expect(specFor(type), type).toEqual(specFor(''));
+ }
+ });
+
it('transcript visibility (ChatPage isTranscriptMessage)', () => {
// ``isTranscriptMessage`` is now ``specFor(type).transcript`` and nothing
// else — the ``metadata.source`` side channel it used to be OR'd with is
@@ -110,7 +114,8 @@ describe('catalog-derived predicates match pre-refactor behavior', () => {
// agent before the catalog is consulted, because a harness-input type can
// still carry agent-written rows (a reverse annotation is one).
const match = { author: 'system', source: 'system', type };
- expect(messageSearchRole(match), type).toBe(wasHarnessInputType(type) ? 'automated' : 'agent');
+ const expectedRole = type === 'annotation' ? 'you' : wasHarnessInputType(type) ? 'automated' : 'agent';
+ expect(messageSearchRole(match), type).toBe(expectedRole);
expect(specFor(type).inputAuthors.includes('harness'), type).toBe(wasHarnessInputType(type));
}
});
@@ -136,11 +141,8 @@ describe('catalog-derived predicates match pre-refactor behavior', () => {
}
});
- it('keeps silent out of the visible-terminal set even though it is terminal', () => {
- // ``silent`` carries ``activityRole: terminal`` for activity bookkeeping but is
- // not transcript-visible, which is why the visible-terminal predicate is the
- // intersection of the two properties rather than the role alone.
- expect(specFor('silent').activityRole).toBe('terminal');
+ it('treats retired silent markers as neutral unknown types', () => {
+ expect(specFor('silent').activityRole).toBe('none');
expect(specFor('silent').transcript).toBe(false);
expect(isTerminalAgentMessage({ author: 'agent', type: 'silent' })).toBe(false);
});
diff --git a/vibe/cli.py b/vibe/cli.py
index d387eafe3..337156f64 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -35,7 +35,7 @@ from sqlalchemy import select
from config import SettingsStore, paths
from config.v2_config import V2Config
from core.scheduled_tasks import (
- AGENT_RUN_DELIVERY_QUEUE,
+ AGENT_RUN_DELIVERY_STEER,
AGENT_RUN_DELIVERY_SEND_NOW,
BINDING_FOLLOWS_SESSION_METADATA_KEY,
ScheduledTaskStore,
@@ -1179,8 +1179,9 @@ def _agent_run_examples_text() -> str:
"""\
Session target:
Use --session-id to continue an existing Agent Session.
- Add --send-now to persist the new Run, interrupt its active turn, and dispatch the FIFO queue head.
- If work is already queued and no new message is needed, use: vibe session send-now <session-id>
+ The default is P1: steer an active native Turn, start when idle, or fall back to the durable P3 queue.
+ Add --send-now to admit this new Run as content P0 and replace the active Turn.
+ To promote the exact existing P3 queue head without a new message, use: vibe session send-now <session-id>
Inspect queued work with: vibe session queue list <session-id>
Remove one exact queued row with: vibe session queue remove <session-id> <message-id>
Omit --session-id/--fork-self/--fork-session to create a background Session for --agent.
@@ -4857,7 +4858,7 @@ def cmd_agent_run(args):
delivery_intent = (
AGENT_RUN_DELIVERY_SEND_NOW
if bool(getattr(args, "send_now", False))
- else AGENT_RUN_DELIVERY_QUEUE
+ else AGENT_RUN_DELIVERY_STEER
)
if delivery_intent == AGENT_RUN_DELIVERY_SEND_NOW and session_policy != "existing":
raise TaskCliError(
@@ -5082,10 +5083,7 @@ def cmd_agent_run(args):
"parent_run_id": parent_run_id,
},
}
- if delivery_intent != AGENT_RUN_DELIVERY_QUEUE:
- # Keep the long-standing default-queue envelope byte-compatible.
- # The explicit control intent is surfaced only when the caller opted
- # into the new behavior.
+ if delivery_intent != AGENT_RUN_DELIVERY_STEER:
payload["delivery_intent"] = delivery_intent
payload["run"]["delivery_intent"] = delivery_intent
if fork_result:
@@ -5663,7 +5661,7 @@ def _session_queue_row(row: dict, *, position: int) -> dict:
def cmd_session_queue_list(args):
from core.services import sessions as sessions_service
- from storage import messages_service
+ from storage import message_deliveries
session_id = str(getattr(args, "session_id", "") or "").strip()
try:
@@ -5684,7 +5682,7 @@ def cmd_session_queue_list(args):
"platform": target.session_key.platform,
},
)
- result = messages_service.list_queued_page(
+ result = message_deliveries.list_queued_page(
conn,
session_id,
page_request=page_request,
@@ -5723,7 +5721,7 @@ def cmd_session_queue_list(args):
def cmd_session_queue_remove(args):
from core.services import sessions as sessions_service
- from storage import messages_service
+ from storage import message_deliveries
from storage.background import run_update_event_transaction
session_id = str(getattr(args, "session_id", "") or "").strip()
@@ -5731,6 +5729,9 @@ def cmd_session_queue_remove(args):
try:
engine = _open_session_engine()
with run_update_event_transaction(engine) as conn:
+ from storage.agent_session_rows import reserve_write_lock
+
+ reserve_write_lock(conn)
sessions_service.get_active_session(conn, session_id)
target = resolve_session_id_target(session_id)
if target.session_key.platform != "avibe":
@@ -5742,7 +5743,7 @@ def cmd_session_queue_remove(args):
"platform": target.session_key.platform,
},
)
- removed = messages_service.remove_queued(
+ removed = message_deliveries.retire_queued_with_run(
conn,
session_id,
message_id,
@@ -11695,8 +11696,7 @@ def _resolve_show_event_after_ambiguous_live_timeout(
) -> dict | None:
"""Wait for acceptance, then let the caller replay the same reservation."""
from core.show_session_events import ShowSessionEventStore
- from storage import messages_service
-
+ from storage.delivery_states import ADMITTED_DELIVERY_STATES
event_id = payload.get("id")
if not isinstance(event_id, str) or not event_id:
return None
@@ -11707,12 +11707,13 @@ def _resolve_show_event_after_ambiguous_live_timeout(
event = store.get_event(session_id, event_id)
if event is None:
return None
- message = event.get("message")
- if (
- isinstance(message, dict)
- and message.get("type") != messages_service.PENDING_TYPE
- ):
- return event
+ delivery = event.get("delivery")
+ if isinstance(delivery, dict):
+ state = delivery.get("state")
+ if state in ADMITTED_DELIVERY_STATES:
+ return event
+ if state == "retired":
+ return None
if time.monotonic() >= deadline:
return None
time.sleep(0.05)
@@ -13125,7 +13126,7 @@ def build_parser():
agent_run_parser.add_argument(
"--send-now",
action="store_true",
- help="Interrupt the existing Session's active turn and dispatch its FIFO queue head",
+ help="Replace the active Turn with this new Run; start it immediately when idle",
)
agent_run_parser.add_argument("--fork-session", help="Existing Agent Session ID to fork into a new Session")
agent_run_parser.add_argument("--fork-self", action="store_true", help="Fork this current Agent Session")
@@ -13215,7 +13216,7 @@ def build_parser():
help="Inspect, control, and update Agent sessions",
description=(
"Manage Avibe Agent sessions. 'list' and 'get' are read-only views; "
- "'send-now' applies Workbench's queued-head interrupt transition; "
+ "'send-now' promotes the exact queued head, steering it when active; "
"'update' changes title, visibility, or scope. Archived sessions are "
"soft-deleted and never surfaced."
),
@@ -13255,12 +13256,12 @@ def build_parser():
_add_json_noop(session_get_parser)
session_send_now_parser = session_subparsers.add_parser(
"send-now",
- help="Interrupt a busy Session and dispatch its existing FIFO queue head",
+ help="Promote the exact existing FIFO queue head",
description=(
- "Apply the same Session-level Send now transition as Workbench without "
- "adding another message. If the Session is busy, Avibe interrupts the "
- "active turn and starts the durable FIFO queue head as a new turn. If "
- "the Session is idle, Avibe starts the queue head directly."
+ "Promote the exact current P3 queue head without adding a message. "
+ "If a native Turn is active, Avibe steers that head into it; if the "
+ "Session is idle, Avibe starts that head as a new Turn. A stale head "
+ "is refused rather than replaced by the next queued item."
),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe session send-now --help",
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 6f6cb4e58..31c3def77 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -20,6 +20,7 @@
}
},
"harness": {
+ "agentInitiatedContinuation": "Agent-initiated continuation",
"watch": {
"supervisorFailed": "Watch worker supervisor failed: {detail}",
"supervisorExitedDuringStartup": "Watch worker supervisor exited during startup.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 20bbcb553..676c83839 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -20,6 +20,7 @@
}
},
"harness": {
+ "agentInitiatedContinuation": "Agent 主动发起的续接",
"watch": {
"supervisorFailed": "Watch 监控进程失败:{detail}",
"supervisorExitedDuringStartup": "Watch 监控进程在启动期间退出。",
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 8e7b6a338..94219ab52 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -379,7 +379,12 @@ async def end_running_agent(payload: dict[str, Any], *, socket_path: Optional[Pa
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
-async def send_now(session_id: str, *, socket_path: Optional[Path] = None) -> dict[str, Any]:
+async def send_now(
+ session_id: str,
+ *,
+ expected_delivery_id: str | None = None,
+ socket_path: Optional[Path] = None,
+) -> dict[str, Any]:
"""Ask the controller to run a session's send-while-busy queue immediately
("立即发送"): interrupt any running turn + flush the queue. Returns
``{status_code, body}``; raises ``InternalServerUnavailable`` on socket
@@ -399,7 +404,14 @@ async def send_now(session_id: str, *, socket_path: Optional[Path] = None) -> di
# slow-but-successful interrupt isn't read-timed-out.
timeout=httpx.Timeout(30.0, connect=1.0),
) as client:
- resp = await client.post(f"/internal/send-now/{session_id}")
+ resp = await client.post(
+ f"/internal/send-now/{session_id}",
+ params=(
+ {"expected_delivery_id": expected_delivery_id}
+ if expected_delivery_id
+ else None
+ ),
+ )
except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
diff --git a/vibe/message_types.json b/vibe/message_types.json
index bddbd8023..f0e6ead5a 100644
--- a/vibe/message_types.json
+++ b/vibe/message_types.json
@@ -3,7 +3,7 @@
"transcript": false,
"searchable": false,
"inputAuthors": [],
- "inboxActivity": true,
+ "inboxActivity": false,
"inboxPreview": false,
"inboxSettlesReply": false,
"activityRole": "none",
@@ -11,40 +11,40 @@
"unread": false,
"webPush": false,
"webPushWhenEvents": [],
- "acceptedReservation": false,
"render": "none"
},
"types": {
"user": {
"transcript": true,
"searchable": true,
+ "inboxActivity": true,
"inputAuthors": [
"user"
],
"activityRole": "turn_start",
- "acceptedReservation": true,
"render": "user"
},
"harness": {
"transcript": true,
"searchable": true,
+ "inboxActivity": true,
"inputAuthors": [
"harness"
],
"activityRole": "turn_start",
- "acceptedReservation": true,
"render": "harness"
},
"annotation": {
"transcript": true,
"searchable": true,
+ "inboxActivity": true,
"inputAuthors": ["harness"],
- "acceptedReservation": true,
"render": "annotation"
},
"result": {
"transcript": true,
"searchable": true,
+ "inboxActivity": true,
"inboxPreview": true,
"inboxSettlesReply": true,
"activityRole": "terminal",
@@ -54,6 +54,7 @@
},
"notify": {
"transcript": true,
+ "inboxActivity": true,
"inboxPreview": true,
"inboxSettlesReply": true,
"terminalWhenEvents": [
@@ -66,6 +67,7 @@
},
"error": {
"transcript": true,
+ "inboxActivity": true,
"inboxPreview": true,
"inboxSettlesReply": true,
"activityRole": "terminal",
@@ -73,29 +75,9 @@
"render": "status"
},
"assistant": {
+ "inboxActivity": true,
"activityRole": "activity",
"render": "activity"
- },
- "tool_call": {
- "render": "activity"
- },
- "queued": {
- "inboxActivity": false,
- "acceptedReservation": true
- },
- "draft": {
- "inboxActivity": false
- },
- "pending": {
- "inboxActivity": false
- },
- "harness_dedupe": {
- "inboxActivity": false
- },
- "silent": {
- "inboxActivity": false,
- "inboxSettlesReply": true,
- "activityRole": "terminal"
}
}
}
diff --git a/vibe/message_types.py b/vibe/message_types.py
index 197e44ba5..852872a22 100644
--- a/vibe/message_types.py
+++ b/vibe/message_types.py
@@ -15,7 +15,6 @@ _BOOL_PROPERTIES = {
"inboxSettlesReply",
"unread",
"webPush",
- "acceptedReservation",
}
_LIST_PROPERTIES = {
"inputAuthors",
@@ -112,18 +111,6 @@ def types_with(property_name: str) -> tuple[str, ...]:
)
-def types_without(property_name: str) -> tuple[str, ...]:
- """Return catalog types for which *property_name* is disabled, in catalog order."""
-
- if property_name not in _PROPERTY_NAMES:
- raise KeyError(property_name)
- return tuple(
- message_type
- for message_type, spec in _TYPE_SPECS.items()
- if not _property_enabled(property_name, spec[property_name])
- )
-
-
def input_author_type_pairs() -> tuple[tuple[str, str], ...]:
"""Return accepted ``(author, message_type)`` input-turn pairs in catalog order.
@@ -161,8 +148,8 @@ def build_partial_index_predicate(index_name: str) -> str:
if index_name == "ix_messages_inbox_activity":
return (
- "session_id is not null and type not in "
- f"({_sql_values(types_without('inboxActivity'))})"
+ "session_id is not null and type in "
+ f"({_sql_values(types_with('inboxActivity'))})"
)
if index_name == "ix_messages_inbox_agent_reply":
return (
@@ -186,5 +173,4 @@ __all__ = [
"input_author_type_pairs",
"spec_for",
"types_with",
- "types_without",
]
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 72fa6c806..db417ee28 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -61,9 +61,9 @@ from vibe.logging_config import application_log_paths
from vibe.message_types import types_with
from vibe.runtime import get_ui_dist_path, get_working_dir
from vibe.sentry_integration import init_sentry
+from storage.delivery_states import ADMITTED_DELIVERY_STATES
logger = logging.getLogger(__name__)
-_ACCEPTED_RESERVATION_TYPES = set(types_with("acceptedReservation"))
class _ShowEventDispatchOutcome(str, Enum):
@@ -205,102 +205,6 @@ def _parse_explicit_bool(value: Any) -> bool:
return False
-def _recover_stale_session_status(session_id: str) -> bool:
- """Clear a persisted ``running`` dot after the controller proves idle.
-
- The UI process owns the browser-facing API, while the controller owns the
- in-memory turn registry. If the controller reports no in-flight turn (or the
- user Stop reaches a stale turn), a ``running`` row in SQLite is only a stale
- projection and must be repaired so reloads/sidebar state stop showing a
- phantom run.
- """
-
- from core.services import sessions as workbench_sessions_service
- from storage.db import create_sqlite_engine
- from vibe.sse_broker import broker
-
- engine = create_sqlite_engine()
- try:
- with engine.begin() as conn:
- try:
- session = workbench_sessions_service.get_session(conn, session_id)
- except LookupError:
- return False
- if not session or session.get("agent_status") != "running":
- return False
- changed = workbench_sessions_service.set_agent_status(conn, session_id, "idle")
- finally:
- engine.dispose()
- if changed:
- broker.publish("session.status", {"session_id": session_id, "agent_status": "idle"})
- return changed
-
-
-def _recover_stale_pending_messages() -> dict[str, int]:
- """Repair hidden ``pending`` send reservations left behind by UI interruption.
-
- Ordinary Chat rows are made visible without redispatching. Harness-owned rows
- stay ``pending`` because no startup queue drain owns them; their originating
- event can retry the same reservation and start the turn. Rows whose session is
- missing or archived are deleted.
- """
-
- from core.services import sessions as workbench_sessions_service
- from storage import messages_service
-
- summary = {"promoted": 0, "deleted": 0, "skipped": 0}
- engine = _projects_engine()
- try:
- with engine.connect() as conn:
- pending_rows = messages_service.list_recoverable_pending(conn)
-
- for row in pending_rows:
- session_id = str(row.get("session_id") or "").strip()
- with engine.begin() as conn:
- session = None
- if session_id:
- try:
- session = workbench_sessions_service.get_session(conn, session_id)
- except LookupError:
- pass
- if not session or session.get("status") == "archived":
- if messages_service.delete_pending(conn, str(row["id"])):
- summary["deleted"] += 1
- continue
- target_type = messages_service.pending_message_target_type(
- row.get("author"),
- row.get("source"),
- row.get("author_name"),
- )
- if target_type in {
- messages_service.HARNESS_TYPE,
- messages_service.ANNOTATION_TYPE,
- }:
- summary["skipped"] += 1
- continue
- promoted = messages_service.promote_pending(
- conn,
- str(row["id"]),
- target_type,
- )
- if not promoted:
- summary["skipped"] += 1
- continue
- settled = _load_session_message(session_id, str(row["id"]))
- if settled is None or settled.get("type") != target_type:
- summary["skipped"] += 1
- continue
- summary["promoted"] += 1
- _publish_visible_input_message(
- settled,
- session_id=session_id,
- scope_id=session.get("scope_id"),
- )
- finally:
- engine.dispose()
- return summary
-
-
def _is_continuation_line(line: str, previous_message: str | None = None) -> bool:
stripped = line.lstrip()
return (
@@ -6648,8 +6552,10 @@ async def sessions_bootstrap(session_id: str):
types=messages_service.TRANSCRIPT_TYPES,
tail=True,
)
- queued = messages_service.list_queued(conn, session_id)
- draft = messages_service.get_draft(conn, session_id)
+ from storage import message_deliveries
+
+ queued = message_deliveries.list_queued(conn, session_id)
+ draft = message_deliveries.get_draft(conn, session_id)
try:
agents_payload = vibe_api.get_vibe_agents(include_disabled=False, include_archived=True)
@@ -8154,35 +8060,6 @@ def _publish_visible_input_message(
return row
-def _promote_and_publish_pending_user_message(
- row: dict[str, Any],
- *,
- session_id: str,
- scope_id: str | None,
- activity_event: str = "user_message",
-) -> dict[str, Any] | None:
- """Settle one reserved row without publishing a stale or pending snapshot."""
- from storage import messages_service
- from vibe.sse_broker import broker
-
- with _projects_engine().begin() as conn:
- promoted = messages_service.promote_pending(conn, row["id"], "user")
- settled = _load_session_message(session_id, row["id"])
- if settled is None:
- return None
- if settled.get("type") == messages_service.QUEUED_TYPE:
- broker.publish("queue.updated", {"session_id": session_id, "scope_id": scope_id})
- return settled
- if promoted and settled.get("type") == "user":
- return _publish_visible_input_message(
- settled,
- session_id=session_id,
- scope_id=scope_id,
- activity_event=activity_event,
- )
- return settled
-
-
@app.route("/api/sessions/<session_id>/messages", methods=["POST"])
async def sessions_messages_create(session_id: str):
"""Persist a user message and fire-and-forget the agent turn.
@@ -8263,59 +8140,60 @@ async def sessions_messages_create(session_id: str):
)
def _persist_user_row() -> dict | None:
- """Reserve the user's row as ``pending`` (hidden from transcript/queue/
- inbox) + clear any saved draft, WITHOUT publishing. This locks the row's
- ``(created_at, id)`` BEFORE the turn dispatches (so a fast reply can't
- sort ahead of its prompt) yet keeps it invisible during the dispatch
- window, so another tab can't briefly see it as a sent prompt (Codex P2).
- The caller promotes it (→ user / queued) once the outcome is known.
- Returns ``None`` if the session was archived in the meantime."""
+ """Atomically persist one unaccepted submission as a Delivery."""
+ from storage import message_deliveries
+ from storage.agent_session_rows import reserve_write_lock
+
with engine.begin() as conn:
- # Re-check archive ATOMICALLY with the reservation: a concurrent archive
- # may have committed since the pre-flight check above, and the session
- # must stay terminal — no new row, no turn.
+ reserve_write_lock(conn)
if workbench_sessions_service.is_session_archived(conn, session_id):
return None
- row = messages_service.append(
+ delivery_id = message_deliveries.new_delivery_id()
+ row = message_deliveries.insert_delivery(
conn,
- scope_id=session["scope_id"],
+ delivery_id=delivery_id,
session_id=session_id,
- platform="avibe",
- author="user",
- source="user",
- message_type=messages_service.PENDING_TYPE,
- text=text if isinstance(text, str) else None,
- content=content if isinstance(content, dict) else None,
- metadata={
- **(payload.get("metadata") or {}),
- "_web_push_user_key": web_push_user_key,
- },
- author_id=web_push_user_key,
- author_name=payload.get("author_name"),
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ text=text if isinstance(text, str) else None,
+ content=content if isinstance(content, dict) else None,
+ metadata={
+ **(payload.get("metadata") or {}),
+ "_web_push_user_key": web_push_user_key,
+ },
+ author_id=web_push_user_key,
+ author_name=payload.get("author_name"),
+ ),
+ dispatch_text=dispatch_text,
+ history_event={"kind": "admission", "priority": "p3", "state": "reserved"},
)
- # A quick-reply click is a side action, not the user submitting their
- # composer text — keep any saved draft intact for it.
if not quick_reply_for:
- messages_service.clear_draft(conn, session_id)
+ message_deliveries.set_draft(conn, session_id, None)
workbench_sessions_service.touch_session(conn, session_id)
- return row
+ return message_deliveries.delivery_payload(row)
# Reserve the row FIRST (pending), then decide by the dispatch outcome.
message = _persist_user_row()
if message is None:
# Archived between the pre-flight check and the reservation — stay terminal.
return _session_archived_response()
- # No text AND no attachments: nothing for the agent to act on, so just
- # promote + publish the row, no turn. Attachments WITHOUT text still run a
- # turn (the agent reads the files), so they aren't caught here.
if not dispatch_text.strip() and not attachment_specs:
- return jsonify(
- _promote_and_publish_pending_user_message(
- message,
- session_id=session_id,
- scope_id=session["scope_id"],
+ from storage import message_deliveries
+
+ with engine.begin() as conn:
+ message_deliveries.retire_reserved(
+ conn,
+ session_id,
+ str(message["id"]),
+ reason="empty_submission",
)
- ), 201
+ return jsonify({"error": "empty submission"}), 400
# Session/page-scoped model (the web Chat): fire-and-forget the turn; the
# reply arrives over ``message.new``. The controller atomically either lets
# the turn start (we then promote the row to user) or — if a turn is already
@@ -8326,32 +8204,57 @@ async def sessions_messages_create(session_id: str):
"text": dispatch_text,
"scope_id": session["scope_id"],
"user_message_id": message.get("id"),
+ "display_text": message.get("text") or "",
+ "content": content if isinstance(content, dict) else None,
+ "metadata": payload.get("metadata") or {},
+ "author_id": web_push_user_key,
+ "author_name": payload.get("author_name"),
"files": attachment_specs,
}
+
+ def _current_delivery_response() -> dict:
+ from storage import message_deliveries
+
+ with engine.connect() as conn:
+ current = message_deliveries.get_delivery(conn, str(message["id"]))
+ if current is None:
+ return dict(message)
+ payload = message_deliveries.delivery_payload(current)
+ if current["state"] == "queued":
+ payload["type"] = "queued"
+ payload["queued"] = True
+ return payload
+
+ def _retire_unclaimed_delivery(reason: str) -> dict:
+ from storage import message_deliveries
+ from storage.agent_session_rows import reserve_write_lock
+
+ with engine.begin() as conn:
+ reserve_write_lock(conn)
+ message_deliveries.retire_reserved(
+ conn,
+ session_id,
+ str(message["id"]),
+ reason=reason,
+ )
+ return _current_delivery_response()
+
try:
result = await internal_client.dispatch_async(dispatch_payload)
except internal_client.InternalServerTimeout as exc:
- observed = _promote_and_publish_pending_user_message(
- message,
- session_id=session_id,
- scope_id=session["scope_id"],
- ) or message
+ current = _current_delivery_response()
return jsonify(
{
- **observed,
+ **current,
"dispatch_error": "dispatch_pending",
"detail": str(exc),
}
), 504
except internal_client.InternalServerUnavailable as exc:
- published = _promote_and_publish_pending_user_message(
- message,
- session_id=session_id,
- scope_id=session["scope_id"],
- ) or message
+ current = _retire_unclaimed_delivery("internal_dispatch_unavailable")
return jsonify(
{
- **published,
+ **current,
"dispatch_error": "internal_unavailable",
"detail": str(exc),
}
@@ -8363,14 +8266,10 @@ async def sessions_messages_create(session_id: str):
exc,
exc_info=True,
)
- observed = _promote_and_publish_pending_user_message(
- message,
- session_id=session_id,
- scope_id=session["scope_id"],
- ) or message
+ current = _current_delivery_response()
return jsonify(
{
- **observed,
+ **current,
"dispatch_error": "dispatch_pending",
"detail": str(exc),
}
@@ -8384,40 +8283,31 @@ async def sessions_messages_create(session_id: str):
if status == 202 and quick_reply_for:
with engine.begin() as conn:
messages_service.set_quick_reply_chosen(conn, session_id, quick_reply_for, dispatch_text)
- if status == 202 and body.get("drained"):
- # The row joined an idle pre-existing queue and was synchronously merged
- # before acceptance returned. ``flush_queue`` already published the
- # freshly ordered replacement; do not append the retired reservation.
- return jsonify({"drained": True}), 202
- if status == 202 and body.get("queued"):
- # Enqueued behind a running turn: the controller already promoted the
- # row pending→queued, so it stays OUT of the transcript (no
- # message.new); show it above the composer via queue.updated.
- queued = _promote_and_publish_pending_user_message(
- message,
- session_id=session_id,
- scope_id=session["scope_id"],
- ) or message
- return jsonify({**queued, "queued": True}), 202
if status == 202:
- # Turn started: the caller owns the rendering transition, while the
- # unified manager owns only the turn/queue decision.
- settled = _promote_and_publish_pending_user_message(
- message,
- session_id=session_id,
- scope_id=session["scope_id"],
- ) or message
- return jsonify(
- settled
- ), 201
- published = _promote_and_publish_pending_user_message(
- message,
- session_id=session_id,
- scope_id=session["scope_id"],
- ) or message
+ delivery_state = str(body.get("delivery_state") or "")
+ current = _current_delivery_response()
+ if delivery_state == "accepted":
+ accepted_message_id = str(
+ body.get("message_id")
+ or current.get("message_id")
+ or message["id"]
+ )
+ with engine.connect() as conn:
+ accepted = messages_service.get_message(conn, accepted_message_id)
+ if accepted is None:
+ return jsonify(
+ {
+ **current,
+ **body,
+ "dispatch_error": "dispatch_pending",
+ }
+ ), 502
+ return jsonify({**accepted, **body}), 201
+ return jsonify({**current, **body}), 202
+ current = _retire_unclaimed_delivery(f"internal_dispatch_rejected_{status}")
return jsonify(
{
- **published,
+ **current,
"dispatch_error": "dispatch_failed",
"detail": body,
}
@@ -8443,10 +8333,7 @@ async def sessions_cancel(session_id: str):
status = result.get("status_code", 500)
body = result.get("body") or {}
body.setdefault("ok", status == 200)
- if status == 404 and body.get("code") == "not_in_flight":
- body["recovered_agent_status"] = _recover_stale_session_status(session_id)
- elif status == 200 and body.get("status") == "stale_released":
- body["recovered_agent_status"] = _recover_stale_session_status(session_id)
+ body.setdefault("recovered_agent_status", False)
return jsonify(body), status
@@ -8518,35 +8405,35 @@ async def sessions_turn_state(session_id: str):
)
body = result.get("body") or {}
projection = _session_runtime_projection(body)
- in_flight = projection["foreground"] == "running"
- recovered = False
- if not in_flight:
- recovered = _recover_stale_session_status(session_id)
- projection["recovered_agent_status"] = recovered
+ projection["recovered_agent_status"] = bool(
+ body.get("recovered_agent_status", False)
+ )
return jsonify(projection)
@app.route("/api/sessions/<session_id>/queue", methods=["GET"])
def sessions_queue_list(session_id: str):
"""Pending send-while-busy messages for a session (shown above the composer)."""
- from storage import messages_service
+ from storage import message_deliveries
engine = _projects_engine()
with engine.connect() as conn:
- queued = messages_service.list_queued(conn, session_id)
+ queued = message_deliveries.list_queued(conn, session_id)
return jsonify({"queued": queued})
@app.route("/api/sessions/<session_id>/queue/<message_id>", methods=["DELETE"])
def sessions_queue_remove(session_id: str, message_id: str):
"""Drop one queued message (the per-item delete in the queue strip)."""
- from storage import messages_service
+ from storage import message_deliveries
+ from storage.agent_session_rows import reserve_write_lock
from storage.background import run_update_event_transaction
from vibe.sse_broker import broker
engine = _projects_engine()
with run_update_event_transaction(engine) as conn:
- removed = messages_service.remove_queued(conn, session_id, message_id)
+ reserve_write_lock(conn)
+ removed = message_deliveries.retire_queued_with_run(conn, session_id, message_id)
if removed:
broker.publish("queue.updated", {"session_id": session_id})
return jsonify({"removed": bool(removed)})
@@ -8554,13 +8441,14 @@ def sessions_queue_remove(session_id: str, message_id: str):
@app.route("/api/sessions/<session_id>/queue/<message_id>/send-now", methods=["POST"])
async def sessions_queue_send_now(session_id: str, message_id: str):
- """Run the queue now ("立即发送"): interrupt the running turn + flush. The
- queue flushes as one merged turn, so ``message_id`` identifies the button's
- item but the whole queue runs (the merge is the user's chosen behavior)."""
+ """Promote the exact queue head represented by the clicked row."""
from vibe import internal_client
try:
- result = await internal_client.send_now(session_id)
+ result = await internal_client.send_now(
+ session_id,
+ expected_delivery_id=message_id,
+ )
except internal_client.InternalServerUnavailable as exc:
return jsonify({"ok": False, "code": "internal_unavailable", "detail": str(exc)}), 503
status = result.get("status_code", 500)
@@ -8572,11 +8460,11 @@ async def sessions_queue_send_now(session_id: str, message_id: str):
@app.route("/api/sessions/<session_id>/draft", methods=["GET"])
def sessions_draft_get(session_id: str):
"""The session's saved unsent compose text (restored on open / device switch)."""
- from storage import messages_service
+ from storage import message_deliveries
engine = _projects_engine()
with engine.connect() as conn:
- draft = messages_service.get_draft(conn, session_id)
+ draft = message_deliveries.get_draft(conn, session_id)
return jsonify({"text": (draft or {}).get("text") or ""})
@@ -8584,7 +8472,7 @@ def sessions_draft_get(session_id: str):
def sessions_draft_set(session_id: str):
"""Upsert the session's draft (debounced from the composer). Blank clears it."""
from core.services import sessions as workbench_sessions_service
- from storage import messages_service
+ from storage import message_deliveries
payload = request.json or {}
text = payload.get("text")
@@ -8597,8 +8485,10 @@ def sessions_draft_set(session_id: str):
# recreate a draft on a session whose drafts were just reclaimed.
if session.get("status") == "archived":
return jsonify({"ok": True})
- messages_service.set_draft(
- conn, scope_id=session["scope_id"], session_id=session_id, text=text if isinstance(text, str) else None
+ message_deliveries.set_draft(
+ conn,
+ session_id,
+ text if isinstance(text, str) else None,
)
except LookupError as err:
return jsonify({"error": str(err)}), 404
@@ -9827,7 +9717,6 @@ def _publish_show_session_event(event_payload: dict[str, Any]) -> None:
async def _run_show_event_dispatch(
event_payload: dict[str, Any],
) -> _ShowEventDispatchOutcome:
- from storage import messages_service
from vibe import internal_client
session_id = event_payload.get("session_id")
@@ -9841,24 +9730,28 @@ async def _run_show_event_dispatch(
):
return _ShowEventDispatchOutcome.FAILED
- message = event_payload.get("message")
- if not isinstance(message, dict):
+ delivery = event_payload.get("delivery")
+ if not isinstance(delivery, dict):
return _ShowEventDispatchOutcome.FAILED
- message_type = message.get("type")
- if message_type in _ACCEPTED_RESERVATION_TYPES:
+ delivery_state = str(delivery.get("state") or "")
+ if delivery_state in ADMITTED_DELIVERY_STATES:
return _ShowEventDispatchOutcome.ACCEPTED
- if message_type != messages_service.PENDING_TYPE:
+ if delivery_state != "reserved":
return _ShowEventDispatchOutcome.FAILED
dispatch_text = _show_event_dispatch_text(event_payload)
if not dispatch_text.strip():
+ _retire_show_event_reservation(event_payload, reason="empty_dispatch")
return _ShowEventDispatchOutcome.FAILED
dispatch_payload = {
"session_id": session_id,
"text": dispatch_text,
"scope_id": scope_id,
- "user_message_id": message["id"],
+ "user_message_id": delivery["id"],
+ "display_text": delivery.get("text") or "",
+ "content": delivery.get("content") or {},
+ "metadata": delivery.get("metadata") or {},
"show_event_id": event_id,
"files": [],
}
@@ -9883,6 +9776,7 @@ async def _run_show_event_dispatch(
session_id,
exc,
)
+ _retire_show_event_reservation(event_payload, reason="dispatch_unavailable")
return _ShowEventDispatchOutcome.FAILED
except Exception: # pragma: no cover - defensive
logger.exception("show event dispatch acceptance is unknown")
@@ -9897,20 +9791,55 @@ async def _run_show_event_dispatch(
status,
body,
)
+ _retire_show_event_reservation(
+ event_payload,
+ reason=f"dispatch_rejected_{status}",
+ )
return _ShowEventDispatchOutcome.FAILED
settled = _settle_show_event_message(event_payload)
- if settled and settled.get("type") in _ACCEPTED_RESERVATION_TYPES:
+ state = str((settled or {}).get("state") or body.get("delivery_state") or "")
+ if state in ADMITTED_DELIVERY_STATES:
return _ShowEventDispatchOutcome.ACCEPTED
- return _ShowEventDispatchOutcome.FAILED
+ return _ShowEventDispatchOutcome.IN_FLIGHT
+
+
+def _retire_show_event_reservation(
+ event_payload: dict[str, Any],
+ *,
+ reason: str,
+) -> bool:
+ from storage import message_deliveries
+
+ session_id = str(event_payload.get("session_id") or "").strip()
+ delivery = event_payload.get("delivery")
+ delivery_id = str(delivery.get("id") or "").strip() if isinstance(delivery, dict) else ""
+ referenced_delivery_id = str(event_payload.get("delivery_id") or "").strip()
+ if (
+ not session_id
+ or not delivery_id
+ or referenced_delivery_id != delivery_id
+ ):
+ return False
+ engine = _projects_engine()
+ try:
+ with engine.begin() as conn:
+ retired = message_deliveries.retire_reserved(
+ conn,
+ session_id,
+ delivery_id,
+ reason=reason,
+ )
+ finally:
+ engine.dispose()
+ if retired:
+ _settle_show_event_message(event_payload)
+ return retired
def _settle_show_event_message(
event_payload: dict[str, Any],
) -> dict[str, Any] | None:
from core.show_session_events import ShowSessionEventStore
- from sqlalchemy import select
- from storage import messages_service
- from storage.models import messages, show_session_events
session_id = event_payload.get("session_id")
event_id = event_payload.get("id")
@@ -9919,42 +9848,6 @@ def _settle_show_event_message(
if not isinstance(event_id, str) or not event_id:
return None
- with _projects_engine().begin() as conn:
- message_id = conn.execute(
- select(messages.c.id)
- .select_from(
- show_session_events.join(
- messages,
- messages.c.id == show_session_events.c.message_id,
- )
- )
- .where(
- show_session_events.c.id == event_id,
- show_session_events.c.session_id == session_id,
- )
- ).scalar_one_or_none()
- row = (
- messages_service.get_message(
- conn,
- str(message_id),
- session_id=session_id,
- )
- if message_id
- else None
- )
- promoted = bool(
- row
- and messages_service.promote_pending(
- conn,
- str(row["id"]),
- messages_service.pending_message_target_type(
- row.get("author"),
- row.get("source"),
- row.get("author_name"),
- ),
- )
- )
-
store = ShowSessionEventStore()
try:
settled_event = store.get_event(session_id, event_id)
@@ -9962,27 +9855,9 @@ def _settle_show_event_message(
store.close()
if settled_event is None:
return None
- message = settled_event.get("message")
- if not isinstance(message, dict):
- return None
-
- event_payload["message_id"] = message["id"]
- event_payload["message"] = message
- if promoted and message.get("type") in {
- messages_service.HARNESS_TYPE,
- messages_service.ANNOTATION_TYPE,
- }:
- _publish_visible_input_message(
- message,
- session_id=session_id,
- scope_id=(
- str(event_payload["scope_id"])
- if isinstance(event_payload.get("scope_id"), str)
- else None
- ),
- activity_event="show_event",
- )
- elif message.get("type") == messages_service.QUEUED_TYPE:
+ event_payload.update(settled_event)
+ delivery = settled_event.get("delivery")
+ if isinstance(delivery, dict) and delivery.get("state") == "queued":
from vibe.sse_broker import broker
broker.publish(
@@ -9992,7 +9867,7 @@ def _settle_show_event_message(
"scope_id": event_payload.get("scope_id"),
},
)
- return message
+ return delivery if isinstance(delivery, dict) else None
def _show_event_dispatch_error() -> ShowSessionEventError:
@@ -10020,24 +9895,9 @@ def _load_session_message(session_id: str, message_id: str) -> dict[str, Any] |
def _show_event_dispatch_text(event_payload: dict[str, Any]) -> str:
- from storage import messages_service
-
- message = event_payload.get("message")
- if not isinstance(message, dict):
- return ""
- metadata = message.get("metadata")
- if not isinstance(metadata, dict):
- return ""
- if messages_service.QUEUED_DISPATCH_TEXT_KEY in metadata:
- return str(
- metadata.get(messages_service.QUEUED_DISPATCH_TEXT_KEY) or ""
- ).strip()
-
- # Pre-upgrade reservations stored the machine prompt on the Show event.
- # Current annotation rows must never replay their stripped display body.
- content = message.get("content")
- if isinstance(content, dict) and isinstance(content.get("annotation"), dict):
- return ""
+ delivery = event_payload.get("delivery")
+ if isinstance(delivery, dict):
+ return str(delivery.get("dispatch_text") or "").strip()
return _legacy_show_event_dispatch_text(event_payload)
@@ -10077,7 +9937,15 @@ def _show_event_response_payload(
public_event = {
key: value
for key, value in event_payload.items()
- if key not in {"session_id", "scope_id", "message_id", "message"}
+ if key
+ not in {
+ "session_id",
+ "scope_id",
+ "message_id",
+ "message",
+ "delivery_id",
+ "delivery",
+ }
}
payload = public_event.get("payload")
if isinstance(payload, dict):
@@ -11384,27 +11252,6 @@ async def _start_startup_dependency_reconcile() -> None:
)
-async def _recover_stale_pending_messages_on_startup() -> None:
- start = time.monotonic()
- try:
- summary = await asyncio.to_thread(_recover_stale_pending_messages)
- except Exception:
- duration_ms = int((time.monotonic() - start) * 1000)
- logger.warning("Pending-message recovery raised after %sms", duration_ms, exc_info=True)
- return
- duration_ms = int((time.monotonic() - start) * 1000)
- if any(summary.values()):
- logger.info(
- "Recovered stale pending messages in %sms: promoted=%s deleted=%s skipped=%s",
- duration_ms,
- summary["promoted"],
- summary["deleted"],
- summary["skipped"],
- )
- else:
- logger.info("No stale pending messages to recover (%sms)", duration_ms)
-
-
async def _stop_startup_dependency_reconcile() -> None:
global _startup_dependency_reconcile_task
task, _startup_dependency_reconcile_task = _startup_dependency_reconcile_task, None
@@ -11419,7 +11266,6 @@ async def _stop_startup_dependency_reconcile() -> None:
app.add_event_handler("startup", sweep_orphan_show_runtime_servers_on_startup)
-app.add_event_handler("startup", _recover_stale_pending_messages_on_startup)
app.add_event_handler("startup", _start_startup_dependency_reconcile)
app.add_event_handler("shutdown", _stop_startup_dependency_reconcile)
app.add_event_handler("shutdown", stop_show_runtime_on_shutdown)