Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(harness): retire detached run deliveries

cyh01bcc06d6707
diff --git a/storage/background.py b/storage/background.py
index a408395c1..fa54ef3c2 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -883,6 +883,7 @@ _RUN_PROJECTIONS: tuple[_RunProjection, ...] = (
),
)
_DEFERRED_RUN_EVENT_ROWS_KEY = "avibe.deferred_run_event_rows"
+_DEFERRED_QUEUE_UPDATED_SESSION_IDS_KEY = "avibe.deferred_queue_updated_session_ids"
_TERMINAL_STATUS_PRIORITY = {
"succeeded": 0,
"canceled": 1,
@@ -2094,6 +2095,21 @@ def _publish_queue_updated(session_id: str) -> None:
)
+def _defer_queue_updated_from_connection(conn: Any, session_id: str) -> None:
+ normalized_session_id = str(session_id or "").strip()
+ if not normalized_session_id:
+ return
+ pending = conn.info.setdefault(_DEFERRED_QUEUE_UPDATED_SESSION_IDS_KEY, set())
+ pending.add(normalized_session_id)
+
+
+def _pop_deferred_queue_updated_session_ids_from_connection(conn: Any) -> list[str]:
+ pending = conn.info.pop(_DEFERRED_QUEUE_UPDATED_SESSION_IDS_KEY, set())
+ if not isinstance(pending, set):
+ return []
+ return sorted(str(session_id) for session_id in pending if session_id)
+
+
def _defer_run_rows_updated_from_connection(conn: Any, rows: list[Any]) -> None:
if not rows:
return
@@ -2119,14 +2135,21 @@ def run_update_event_transaction(engine: Any):
"""Commit DB writes before publishing deferred ``runs.updated`` snapshots."""
pending_rows: list[dict[str, Any]] = []
+ pending_queue_session_ids: list[str] = []
with engine.begin() as conn:
try:
yield conn
pending_rows = pop_deferred_run_event_rows_from_connection(conn)
+ pending_queue_session_ids = (
+ _pop_deferred_queue_updated_session_ids_from_connection(conn)
+ )
except Exception:
conn.info.pop(_DEFERRED_RUN_EVENT_ROWS_KEY, None)
+ conn.info.pop(_DEFERRED_QUEUE_UPDATED_SESSION_IDS_KEY, None)
raise
_publish_run_rows_updated(pending_rows)
+ for session_id in pending_queue_session_ids:
+ _publish_queue_updated(session_id)
def _run_rows_for_ids(conn: Any, run_ids: list[str]) -> list[Any]:
@@ -2447,9 +2470,10 @@ def apply_live_agent_run_cancellation_in_connection(
"""Record one live Run cancellation inside the Turn owner's transaction.
``detach`` is the outcome of the shared-Turn ownership check made under the
- same SQLite writer reservation. A detached participant becomes terminal and
- suppresses its callback before any terminal writer or callback drain can run;
- an exclusive owner only records the cancellation request before P0 Stop.
+ same SQLite writer reservation. A detached participant becomes terminal,
+ retires its exact input when the Delivery state proves no native side effect,
+ and suppresses its callback before any terminal writer or callback drain can
+ run; an exclusive owner only records the cancellation request before P0 Stop.
"""
normalized_run_id = str(run_id or "").strip()
@@ -2478,6 +2502,16 @@ def apply_live_agent_run_cancellation_in_connection(
"updated_at": now,
}
if detach:
+ delivery_id = str(row["delivery_id"] or "").strip()
+ if delivery_id:
+ from storage import message_deliveries as delivery_store
+
+ if delivery_store.retire_for_run_cancellation(
+ conn,
+ normalized_session_id,
+ delivery_id,
+ ):
+ _defer_queue_updated_from_connection(conn, normalized_session_id)
values.update(status="canceled", completed_at=now)
callback_session_id = str(row["callback_session_id"] or "").strip()
callback_status = str(row["callback_status"] or "").strip()
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 952262ebd..97a61be2e 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -4979,6 +4979,120 @@ def test_run_cancel_without_an_active_turn_settles_atomically(monkeypatch, tmp_p
assert request_store.list_pending_callbacks() == []
+def test_run_cancel_retires_every_pre_native_delivery_atomically(monkeypatch, tmp_path):
+ """A canceled Run cannot leave any not-yet-written input eligible to dispatch."""
+
+ from core.inbox_events import bus
+ from core.scheduled_tasks import TaskExecutionStore
+ from storage.background import attach_agent_run_delivery_in_connection
+ from storage.delivery_states import RUN_CANCEL_RETIRE_STATES
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session, turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_pre_native_run_cancel",
+ )
+ session_id = session["id"]
+ request_store = TaskExecutionStore()
+ runs_and_deliveries: list[tuple[str, str]] = []
+ runs_by_state = []
+ for delivery_state in RUN_CANCEL_RETIRE_STATES:
+ run = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message=f"cancel {delivery_state} input",
+ agent_name="worker",
+ callback_session_id="ses_callback",
+ )
+ assert request_store.claim(run.id) is not None
+ runs_by_state.append((delivery_state, run))
+
+ with engine.begin() as conn:
+ for delivery_state, run in runs_by_state:
+ delivery = _reserve_submission(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ text=f"cancel {delivery_state} input",
+ )
+ if delivery_state == "queued":
+ delivery = message_deliveries.cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={"state": "queued"},
+ )
+ assert delivery is not None
+ elif delivery_state == "pending_steer":
+ pending = message_deliveries.open_pending_steer_batch(
+ conn,
+ deliveries=[delivery],
+ turn_id=turn_id,
+ attempt_id=message_deliveries.new_attempt_id(),
+ )
+ assert len(pending) == 1
+ delivery = pending[0]
+ else:
+ assert delivery_state == "reserved"
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ run.id,
+ session_id=session_id,
+ delivery_id=str(delivery["id"]),
+ )
+ runs_and_deliveries.append((run.id, str(delivery["id"])))
+
+ 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)
+ transport = httpx.ASGITransport(app=app)
+
+ async def _go():
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ ) as client:
+ return [
+ await client.post(
+ f"/internal/cancel/{session_id}",
+ params={"run_id": run_id},
+ )
+ for run_id, _delivery_id in runs_and_deliveries
+ ]
+
+ responses = asyncio.run(_go())
+
+ assert all(response.status_code == 200 for response in responses)
+ assert [response.json()["status"] for response in responses] == [
+ "run_detached"
+ ] * len(RUN_CANCEL_RETIRE_STATES)
+ controller.command_handler.handle_stop.assert_not_awaited()
+ with engine.connect() as conn:
+ retired = [
+ message_deliveries.get_delivery(conn, delivery_id)
+ for _run_id, delivery_id in runs_and_deliveries
+ ]
+ assert [row["state"] for row in retired] == [
+ "retired"
+ ] * len(RUN_CANCEL_RETIRE_STATES)
+ 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)
+ for run_id, _delivery_id in runs_and_deliveries:
+ saved = request_store.get_run(run_id)
+ assert saved is not None
+ assert saved["status"] == "canceled"
+ assert saved["callback_status"] == "skipped"
+ assert request_store.list_pending_callbacks() == []
+ assert published.count(("queue.updated", {"session_id": session_id})) == len(
+ RUN_CANCEL_RETIRE_STATES
+ )
+
+
def test_run_cancel_guard_allows_the_sole_initial_run_owner(monkeypatch, tmp_path):
"""A Run remains allowed to stop the backend when it owns the whole Turn."""