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): make run detachment atomic

cyh01973d1e1490
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 74757dba4..c0f9bc681 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -3158,13 +3158,7 @@ class TaskExecutionStore:
return True
return False
- def mark_run_canceled(
- self,
- run_id: str,
- *,
- completed_at: Optional[str] = None,
- skip_callback: bool = False,
- ) -> bool:
+ def mark_run_canceled(self, run_id: str, *, completed_at: Optional[str] = None) -> bool:
now = completed_at or _utc_now_iso()
existing = self.get_run(run_id)
if existing is None:
@@ -3178,8 +3172,6 @@ class TaskExecutionStore:
updated_at=now,
cancel_requested=True,
cancel_requested_at=cancel_requested_at,
- callback_status="skipped" if skip_callback else None,
- callback_completed_at=now if skip_callback else None,
)
return True
@@ -3203,9 +3195,6 @@ class TaskExecutionStore:
"updated_at": now,
}
)
- if skip_callback:
- payload["callback_status"] = "skipped"
- payload["callback_completed_at"] = now
completed_path = self._request_path(run_id, state="completed")
with tempfile.NamedTemporaryFile(
mode="w",
diff --git a/core/session_turns.py b/core/session_turns.py
index 3f1ee64cb..2ee3bded5 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -60,7 +60,12 @@ 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 OWED_FAILURE_NOTICE_KEY, normalize_run_status
+from storage.background import (
+ OWED_FAILURE_NOTICE_KEY,
+ apply_live_agent_run_cancellation_in_connection,
+ normalize_run_status,
+ run_update_event_transaction,
+)
from storage.session_reclaim import reconcile_explicit_overrides
from storage.models import (
agent_runs,
@@ -2988,7 +2993,10 @@ class SessionTurnManager:
interrupt_target_id: str | None = None
should_interrupt = False
joined = False
- with self._runtime_start_owner(request.session_id, backend) as start_owner, self._sqlite_engine().begin() as conn:
+ with self._runtime_start_owner(
+ request.session_id,
+ backend,
+ ) as start_owner, run_update_event_transaction(self._sqlite_engine()) as conn:
reserve_write_lock(conn)
session_status = conn.execute(
select(agent_sessions.c.status).where(
@@ -2996,6 +3004,9 @@ class SessionTurnManager:
)
).scalar_one_or_none()
current = delivery_store.active_turn(conn, request.session_id)
+ expected_exclusive_run_id = str(
+ request.expected_exclusive_agent_run_id or ""
+ ).strip()
if request.content is not None and session_status != "active":
existing = (
delivery_store.get_delivery(conn, request.delivery_id)
@@ -3014,6 +3025,23 @@ class SessionTurnManager:
current_id = str((current or {}).get("id") or "") or None
if current is None:
if request.content is None:
+ if expected_exclusive_run_id:
+ cancellation = apply_live_agent_run_cancellation_in_connection(
+ conn,
+ expected_exclusive_run_id,
+ session_id=request.session_id,
+ detach=True,
+ )
+ return DeliveryResult(
+ None,
+ None,
+ (
+ "run_detached"
+ if cancellation == "run_detached"
+ else "settled"
+ ),
+ reason=cancellation,
+ )
return DeliveryResult(None, None, "settled", reason="not_active")
delivery = self._insert_delivery(
conn,
@@ -3043,6 +3071,24 @@ class SessionTurnManager:
and expected_turn_id
and current_id != expected_turn_id
):
+ if expected_exclusive_run_id:
+ cancellation = apply_live_agent_run_cancellation_in_connection(
+ conn,
+ expected_exclusive_run_id,
+ session_id=request.session_id,
+ detach=True,
+ )
+ return DeliveryResult(
+ None,
+ None,
+ (
+ "run_detached"
+ if cancellation == "run_detached"
+ else "settled"
+ ),
+ current_id,
+ cancellation,
+ )
return DeliveryResult(
None,
None,
@@ -3050,22 +3096,37 @@ class SessionTurnManager:
current_id,
"target_turn_changed",
)
- expected_exclusive_run_id = str(
- request.expected_exclusive_agent_run_id or ""
- ).strip()
if request.content is None and expected_exclusive_run_id:
exclusive, reason = delivery_store.agent_run_exclusively_owns_turn(
conn,
run_id=expected_exclusive_run_id,
turn_id=str(current_id or ""),
)
+ cancellation = apply_live_agent_run_cancellation_in_connection(
+ conn,
+ expected_exclusive_run_id,
+ session_id=request.session_id,
+ detach=not exclusive,
+ )
if not exclusive:
return DeliveryResult(
None,
None,
- "run_detached",
+ (
+ "run_detached"
+ if cancellation == "run_detached"
+ else "settled"
+ ),
+ current_id,
+ reason if cancellation == "run_detached" else cancellation,
+ )
+ if cancellation != "cancel_requested":
+ return DeliveryResult(
+ None,
+ None,
+ "settled",
current_id,
- reason,
+ cancellation,
)
control_in_progress = current.get("control_state") in {
"pending",
@@ -7370,22 +7431,15 @@ class SessionTurnManager:
if not self._durable_schema_available():
if agent_run_id:
return {
- "ok": True,
+ "ok": False,
+ "code": "atomic_run_cancel_unavailable",
"session_id": session_id,
- "status": "run_detached",
"reason": "durable_turn_ownership_unavailable",
}
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:
- if agent_run_id:
- return {
- "ok": True,
- "session_id": session_id,
- "status": "run_detached",
- "reason": "not_in_flight",
- }
+ if owner is None and not agent_run_id:
return {
"ok": False,
"code": "not_in_flight",
@@ -7399,7 +7453,7 @@ class SessionTurnManager:
session_id=session_id,
priority="p0",
content=None,
- expected_turn_id=str(owner["id"]),
+ expected_turn_id=(str(owner["id"]) if owner is not None else None),
expected_exclusive_agent_run_id=(
str(agent_run_id).strip() if agent_run_id else None
),
@@ -7420,7 +7474,7 @@ class SessionTurnManager:
return {
"ok": True,
"session_id": session_id,
- "status": "run_detached",
+ "status": "run_settled",
"reason": result.reason or "already_terminal",
}
return {
diff --git a/storage/background.py b/storage/background.py
index 272960c16..a408395c1 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -2436,6 +2436,74 @@ def attach_agent_run_delivery_in_connection(
return True
+def apply_live_agent_run_cancellation_in_connection(
+ conn: Any,
+ run_id: str,
+ *,
+ session_id: str,
+ detach: bool,
+ updated_at: Optional[str] = None,
+) -> str:
+ """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.
+ """
+
+ 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:
+ return "missing_run_identity"
+ row = conn.execute(
+ select(agent_runs)
+ .where(agent_runs.c.id == normalized_run_id)
+ .limit(1)
+ ).mappings().first()
+ if row is None:
+ return "run_not_found"
+ if str(row["session_id"] or "").strip() != normalized_session_id:
+ return "run_session_mismatch"
+ status = normalize_run_status(row["status"])
+ if status in TERMINAL_RUN_STATUSES:
+ return "run_already_terminal"
+ if status not in {"queued", "running"}:
+ return "run_not_cancelable"
+
+ now = updated_at or _utc_now_iso()
+ values: dict[str, Any] = {
+ "cancel_requested": 1,
+ "cancel_requested_at": row["cancel_requested_at"] or now,
+ "updated_at": now,
+ }
+ if detach:
+ 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()
+ if callback_session_id and callback_status not in {"sent", "skipped"}:
+ values.update(
+ callback_status="skipped",
+ callback_error=None,
+ callback_completed_at=now,
+ )
+ result = conn.execute(
+ 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") + _status_query_values("running")
+ )
+ )
+ .values(**values)
+ )
+ if not result.rowcount:
+ return "run_transition_lost"
+ _defer_run_ids_updated_from_connection(conn, [normalized_run_id])
+ return "run_detached" if detach else "cancel_requested"
+
+
def agent_run_cancellation_won_in_connection(conn: Any, run_id: str) -> bool:
"""Whether cancellation already owns a refused queue handoff."""
diff --git a/storage/message_deliveries.py b/storage/message_deliveries.py
index 66614c6f0..cf311b412 100644
--- a/storage/message_deliveries.py
+++ b/storage/message_deliveries.py
@@ -1830,17 +1830,30 @@ def agent_run_exclusively_owns_turn(
"processing",
}:
return False, "run_not_running"
- accepted_delivery_ids = [
+ participant_delivery_ids = [
str(value)
for value in conn.execute(
select(message_deliveries.c.id)
- .where(message_deliveries.c.turn_id == normalized_turn_id)
- .where(message_deliveries.c.state == "accepted")
+ .where(
+ or_(
+ and_(
+ message_deliveries.c.turn_id == normalized_turn_id,
+ message_deliveries.c.state == "accepted",
+ ),
+ and_(
+ message_deliveries.c.current_target_turn_id
+ == normalized_turn_id,
+ message_deliveries.c.state.in_(
+ ("pending_steer", "steering", "reconciling_steer")
+ ),
+ ),
+ )
+ )
.order_by(message_deliveries.c.turn_position, message_deliveries.c.id)
).scalars()
]
- if accepted_delivery_ids != [str(row["delivery_id"])]:
- return False, "turn_has_other_accepted_inputs"
+ if participant_delivery_ids != [str(row["delivery_id"])]:
+ return False, "turn_has_other_participants"
return True, "exclusive_run_owner"
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index 977238347..34f32de7f 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -2526,17 +2526,20 @@ def test_runs_cancel_shared_turn_detaches_only_the_requested_run(
callback_session_id="ses_callback",
)
assert request_store.claim(request.id) is not None
- cancel_dispatch = AsyncMock(
- return_value={
+ async def detach_in_controller(*_args, **_kwargs):
+ request_store.update_callback_status(request.id, status="skipped")
+ request_store.mark_run_canceled(request.id)
+ return {
"status_code": 200,
"body": {
"ok": True,
"session_id": "ses_shared_turn",
"status": "run_detached",
- "reason": "turn_has_other_accepted_inputs",
+ "reason": "turn_has_other_participants",
},
}
- )
+
+ cancel_dispatch = AsyncMock(side_effect=detach_in_controller)
with (
patch("vibe.cli._task_request_store", return_value=request_store),
@@ -2684,12 +2687,22 @@ def test_runs_cancel_running_agent_run_does_not_overwrite_already_finished_turn(
agent_name="worker",
)
assert request_store.claim(request.id) is not None
- cancel_dispatch = AsyncMock(
- return_value={
+ async def settle_before_cancel(*_args, **_kwargs):
+ assert request_store.settle_without_result(
+ request.id,
+ terminal_status="succeeded",
+ ) == "succeeded"
+ return {
"status_code": 200,
- "body": {"ok": True, "session_id": "ses_already_finished", "status": "already_finished"},
+ "body": {
+ "ok": True,
+ "session_id": "ses_already_finished",
+ "status": "run_settled",
+ "reason": "run_already_terminal",
+ },
}
- )
+
+ cancel_dispatch = AsyncMock(side_effect=settle_before_cancel)
with (
patch("vibe.cli._task_request_store", return_value=request_store),
@@ -2701,14 +2714,13 @@ def test_runs_cancel_running_agent_run_does_not_overwrite_already_finished_turn(
cancel_dispatch.assert_awaited_once_with("ses_already_finished", run_id=request.id)
saved = request_store.get_run(request.id)
assert saved is not None
- assert saved["status"] == "running"
- assert saved["completed_at"] is None
- assert saved["cancel_requested"] is True
+ assert saved["status"] == "succeeded"
+ assert saved["completed_at"] is not None
+ assert saved["cancel_requested"] is False
payload = json.loads(capsys.readouterr().out)
- assert payload["cancel_code"] == "cancel_request_recorded_only"
- assert payload["cancel_result"]["reason_code"] == "already_finished"
+ assert payload["cancel_code"] == "run_already_settled"
assert payload["cancel_result"]["live_cancel_confirmed"] is False
- assert payload["run"]["status"] == "running"
+ assert payload["run"]["status"] == "succeeded"
def test_runs_cancel_queued_agent_run_does_not_call_live_controller(
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index c9622d3cc..952262ebd 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -4829,6 +4829,154 @@ def test_hfr_476_run_cancel_does_not_stop_a_shared_turn(monkeypatch, tmp_path):
assert turn is not None
assert turn["state"] == "active"
assert turn["control_state"] is None
+ saved = request_store.get_run(run.id)
+ assert saved is not None
+ assert saved["status"] == "canceled"
+ assert saved["callback_status"] == "skipped"
+ assert saved["callback_completed_at"] is not None
+ assert request_store.list_pending_callbacks() == []
+
+
+def test_run_cancel_guard_counts_an_unresolved_steer_as_a_participant(
+ monkeypatch,
+ tmp_path,
+):
+ """A native steer in flight prevents the initial Run from stopping the Turn."""
+
+ from core.scheduled_tasks import TaskExecutionStore
+ from storage.background import attach_agent_run_delivery_in_connection
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session, turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_unresolved_steer_cancel",
+ )
+ session_id = session["id"]
+ request_store = TaskExecutionStore()
+ owner_run = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="initial owner",
+ agent_name="worker",
+ callback_session_id="ses_callback",
+ )
+ assert request_store.claim(owner_run.id) is not None
+
+ with engine.begin() as conn:
+ turn = message_deliveries.get_turn(conn, turn_id)
+ initial = message_deliveries.delivery_for_turn(conn, turn_id)
+ assert turn is not None
+ assert initial is not None
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ owner_run.id,
+ session_id=session_id,
+ delivery_id=initial["id"],
+ )
+ steer = _reserve_submission(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ text="second input already steering",
+ )
+ steer_id = str(steer["id"])
+ claimed = message_deliveries.open_steer_attempt(
+ conn,
+ steer["id"],
+ expected_version=int(steer["version"]),
+ turn_id=turn_id,
+ attempt_id=message_deliveries.new_attempt_id(),
+ expected_native_turn_id=str(turn["native_turn_id"]),
+ )
+ assert claimed is not None
+ assert claimed["state"] == "steering"
+
+ 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": owner_run.id},
+ )
+
+ response = asyncio.run(_go())
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "ok": True,
+ "session_id": session_id,
+ "status": "run_detached",
+ "reason": "turn_has_other_participants",
+ }
+ controller.command_handler.handle_stop.assert_not_awaited()
+ saved = request_store.get_run(owner_run.id)
+ assert saved is not None
+ assert saved["status"] == "canceled"
+ assert saved["callback_status"] == "skipped"
+ assert request_store.list_pending_callbacks() == []
+ with engine.connect() as conn:
+ turn = message_deliveries.get_turn(conn, turn_id)
+ steer = message_deliveries.get_delivery(conn, steer_id)
+ assert turn is not None
+ assert turn["state"] == "active"
+ assert turn["control_state"] is None
+ assert steer is not None
+ assert steer["state"] == "steering"
+
+
+def test_run_cancel_without_an_active_turn_settles_atomically(monkeypatch, tmp_path):
+ """An orphaned live projection is canceled without inventing a Session Stop."""
+
+ from core.scheduled_tasks import TaskExecutionStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_ownerless_run_cancel",
+ )
+ request_store = TaskExecutionStore()
+ run = request_store.enqueue_agent_run(
+ session_id=session["id"],
+ message="orphaned live projection",
+ agent_name="worker",
+ callback_session_id="ses_callback",
+ )
+ assert request_store.claim(run.id) is not None
+
+ 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},
+ )
+
+ response = asyncio.run(_go())
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "ok": True,
+ "session_id": session["id"],
+ "status": "run_detached",
+ "reason": "run_detached",
+ }
+ controller.command_handler.handle_stop.assert_not_awaited()
+ 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() == []
def test_run_cancel_guard_allows_the_sole_initial_run_owner(monkeypatch, tmp_path):
diff --git a/vibe/cli.py b/vibe/cli.py
index 4d21fe2f6..1a065b69a 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -6180,6 +6180,17 @@ def _recorded_only_cancel_result(*, reason_code: str, detail: object | None = No
return result
+def _record_live_cancel_fallback(
+ store: TaskExecutionStore,
+ run_id: str,
+ *,
+ reason_code: str,
+ detail: object | None = None,
+) -> dict:
+ store.cancel_run(run_id)
+ return _recorded_only_cancel_result(reason_code=reason_code, detail=detail)
+
+
def _initial_cancel_result(run: dict | None) -> dict:
if not isinstance(run, dict):
return _recorded_only_cancel_result(reason_code="run_not_found")
@@ -6246,9 +6257,19 @@ def _cancel_live_agent_run(store: TaskExecutionStore, run: dict) -> dict:
try:
controller_result = asyncio.run(_request_live_run_cancel(session_id, run_id))
except internal_client.InternalServerUnavailable as exc:
- return _recorded_only_cancel_result(reason_code="internal_unavailable", detail=str(exc))
+ return _record_live_cancel_fallback(
+ store,
+ run_id,
+ reason_code="internal_unavailable",
+ detail=str(exc),
+ )
except Exception as exc: # noqa: BLE001
- return _recorded_only_cancel_result(reason_code="live_cancel_failed", detail=str(exc))
+ return _record_live_cancel_fallback(
+ store,
+ run_id,
+ reason_code="live_cancel_failed",
+ detail=str(exc),
+ )
status_code = controller_result.get("status_code")
try:
@@ -6262,18 +6283,37 @@ def _cancel_live_agent_run(store: TaskExecutionStore, run: dict) -> dict:
and isinstance(body, dict)
and str(body.get("status") or "").strip() == "run_detached"
):
- run_terminalized = store.mark_run_canceled(run_id, skip_callback=True)
+ saved = store.get_run(run_id)
return {
"code": "run_canceled_without_live_stop",
"live_cancel_attempted": False,
"live_cancel_confirmed": False,
- "run_terminalized": run_terminalized,
+ "run_terminalized": bool(
+ saved and normalize_run_status(saved.get("status")) == "canceled"
+ ),
"controller_status_code": normalized_status_code,
"controller_response": body,
"message": "Run was canceled without stopping the shared Session turn.",
}
+ if (
+ normalized_status_code is not None
+ and 200 <= normalized_status_code < 300
+ and isinstance(body, dict)
+ and str(body.get("status") or "").strip() == "run_settled"
+ ):
+ return {
+ "code": "run_already_settled",
+ "live_cancel_attempted": False,
+ "live_cancel_confirmed": False,
+ "run_terminalized": False,
+ "controller_status_code": normalized_status_code,
+ "controller_response": body,
+ "message": "Run had already settled before cancellation acquired ownership.",
+ }
if not _live_cancel_was_confirmed(normalized_status_code, body):
- return _recorded_only_cancel_result(
+ return _record_live_cancel_fallback(
+ store,
+ run_id,
reason_code=_live_cancel_failure_code(normalized_status_code, body),
detail={
"controller_status_code": normalized_status_code,
@@ -6299,13 +6339,14 @@ def cmd_runs_cancel(args):
if existing is None:
_print_task_error(TaskCliError(f"run '{args.run_id}' not found", code="run_not_found", details={"run_id": args.run_id}))
return 1
- canceled = store.cancel_run(args.run_id)
- if not canceled:
- _print_task_error(TaskCliError(f"run '{args.run_id}' not found", code="run_not_found", details={"run_id": args.run_id}))
- return 1
- cancel_result = _initial_cancel_result(existing)
if _should_attempt_live_run_cancel(existing):
cancel_result = _cancel_live_agent_run(store, existing)
+ else:
+ canceled = store.cancel_run(args.run_id)
+ if not canceled:
+ _print_task_error(TaskCliError(f"run '{args.run_id}' not found", code="run_not_found", details={"run_id": args.run_id}))
+ return 1
+ cancel_result = _initial_cancel_result(existing)
run = store.get_run(args.run_id)
_print_cli_payload(
"agent_run",