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): bind create-per-run delivery to reserved session (#1368)

qihan-bot9765a960e0a6
diff --git a/storage/background.py b/storage/background.py
index 5efc86606..22820e322 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -2651,10 +2651,16 @@ def attach_agent_run_delivery_in_connection(
metadata = {}
if bool(row["cancel_requested"]):
return False
- if str(row["session_id"] or "").strip() != normalized_session_id:
+ existing_session_id = str(row["session_id"] or "").strip()
+ session_policy = str(row["session_policy"] or "").strip()
+ can_adopt_session = not existing_session_id and session_policy == "create_per_run"
+ if existing_session_id != normalized_session_id and not can_adopt_session:
return False
existing_delivery_id = str(row["delivery_id"] or "").strip()
- if existing_delivery_id == normalized_delivery_id:
+ if (
+ existing_delivery_id == normalized_delivery_id
+ and existing_session_id == normalized_session_id
+ ):
return True
if existing_delivery_id:
return False
@@ -2664,7 +2670,18 @@ def attach_agent_run_delivery_in_connection(
result = conn.execute(
update(agent_runs)
.where(agent_runs.c.id == normalized_run_id)
- .where(agent_runs.c.session_id == normalized_session_id)
+ .where(
+ or_(
+ agent_runs.c.session_id == normalized_session_id,
+ and_(
+ agent_runs.c.session_policy == "create_per_run",
+ or_(
+ agent_runs.c.session_id.is_(None),
+ agent_runs.c.session_id == "",
+ ),
+ ),
+ )
+ )
.where(
agent_runs.c.status.in_(
_status_query_values("running") + _status_query_values("queued")
@@ -2673,6 +2690,7 @@ def attach_agent_run_delivery_in_connection(
.where(agent_runs.c.cancel_requested == 0)
.where(agent_runs.c.delivery_id.is_(None))
.values(
+ session_id=normalized_session_id,
delivery_id=normalized_delivery_id,
updated_at=now,
metadata_json=_json_dumps(metadata),
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index ed23e557b..c057d8e42 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -4305,6 +4305,16 @@ scenarios:
# blocked, while dead Watch supervision and upcoming Task inventory remain in
# the same bounded operator response.
test: tests/test_harness_live_status.py::test_hfr_481_unified_view_marks_workdir_conflict_and_watch_failure
+ - id: HFR-482
+ name: create-per-run Delivery binding adopts its freshly reserved Session
+ status: covered
+ kind: lifecycle
+ layer: scenario
+ backend: shared
+ # A create-per-run row starts without a Session. Its first durable Delivery
+ # atomically records the runtime reservation while mismatched bound Runs stay
+ # protected by the existing hard refusal.
+ test: tests/test_internal_server.py::test_hfr_482_create_per_run_delivery_adopts_reserved_session
manual_evidence:
- local Incus backend process death after prompt acceptance
- local Incus controller restart with persisted queued successor
diff --git a/tests/scenarios/harness_failure_recovery/observations.yaml b/tests/scenarios/harness_failure_recovery/observations.yaml
index 6a8e752f9..89c5f7278 100644
--- a/tests/scenarios/harness_failure_recovery/observations.yaml
+++ b/tests/scenarios/harness_failure_recovery/observations.yaml
@@ -300,3 +300,14 @@ observations:
producer has already asserted 274 distinct events. The event lifecycle must
include its Agent follow-up, and the Watch owner must stop admitting events
when successful exits remain implausibly dense.
+ - id: HFR-OBS-025
+ date: 2026-08-12
+ source: Avibe 3.0.10 runtime evidence plus deterministic admission reproduction
+ result: confirmed
+ detail: >-
+ A create_per_run definition reserves its runtime Session after the Run row is
+ created. The first durable Delivery then tried to bind against that new Session,
+ but the Run still had an empty session_id and the strict equality guard rejected
+ the handoff before any backend started. The binding transaction must atomically
+ adopt the freshly reserved Session only for create_per_run rows; a Run already
+ bound to another Session must remain a hard refusal.
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index bd72e99a3..adaf69707 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -4003,6 +4003,135 @@ def test_scheduled_gate_idle_runs_turn_with_lifecycle(monkeypatch, tmp_path):
assert session_id not in app.state.in_flight_dispatches, "slot released after the turn"
+def test_hfr_482_create_per_run_delivery_adopts_reserved_session(monkeypatch, tmp_path):
+ """A create-per-run Run adopts its freshly reserved Session at admission."""
+ from core.scheduled_tasks import TaskExecutionStore
+ from core.services import sessions as sessions_service
+ from storage.background import attach_agent_run_delivery_in_connection
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_create_per_run_delivery",
+ )
+ session_id = session["id"]
+ request_store = TaskExecutionStore()
+ run = request_store.enqueue_definition_run(
+ definition_id="scheduled-create-per-run",
+ run_type="scheduled",
+ source_kind="scheduler",
+ session_key="",
+ session_id=None,
+ post_to=None,
+ deliver_key=None,
+ prompt="fresh session prompt",
+ agent_name="worker",
+ session_policy="create_per_run",
+ )
+ assert request_store.claim(run.id) is not None
+
+ started = asyncio.Event()
+
+ async def _fake_dispatch_turn(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):
+ started.set()
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
+
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _fake_dispatch_turn)
+
+ controller = _build_controller_double()
+ internal_server.create_app(controller)
+ ctx = MessageContext(
+ user_id="workbench",
+ channel_id=session_id,
+ platform="avibe",
+ message_id=f"scheduled:scheduled-create-per-run:{run.id}",
+ platform_specific={
+ "agent_session_id": session_id,
+ "agent_session_target": {"agent_backend": "claude"},
+ "task_execution_id": run.id,
+ "task_trigger_kind": "scheduled",
+ "task_definition_id": "scheduled-create-per-run",
+ },
+ )
+
+ async def _go():
+ result = await controller.session_turn_gate.submit_scheduled(
+ session_id,
+ ctx,
+ "fresh session prompt",
+ delivery_intent="queue",
+ )
+ await asyncio.wait_for(started.wait(), timeout=3)
+ return result
+
+ result = asyncio.run(_go())
+
+ assert result.delivery_owner_transferred is True
+ stored = request_store.get_run(run.id)
+ assert stored is not None
+ assert stored["session_id"] == session_id
+ assert stored["delivery_id"]
+ assert stored["metadata"]["delivery_outcome"] == {
+ "intent": "queue",
+ "status": "claimed",
+ "target_was_busy": False,
+ }
+ with engine.connect() as conn:
+ delivery = message_deliveries.get_delivery(conn, stored["delivery_id"])
+ assert delivery is not None
+ assert delivery["session_id"] == session_id
+
+ unbound_existing = request_store.enqueue_definition_run(
+ definition_id="scheduled-existing",
+ run_type="scheduled",
+ source_kind="scheduler",
+ session_key="",
+ session_id=None,
+ post_to=None,
+ deliver_key=None,
+ prompt="must not adopt",
+ agent_name="worker",
+ session_policy="existing",
+ )
+ bound_create_per_run = request_store.enqueue_definition_run(
+ definition_id="scheduled-bound-create-per-run",
+ run_type="scheduled",
+ source_kind="scheduler",
+ session_key="",
+ session_id=session_id,
+ post_to=None,
+ deliver_key=None,
+ prompt="must not rebind",
+ agent_name="worker",
+ session_policy="create_per_run",
+ )
+ with engine.begin() as conn:
+ other_session = sessions_service.create_session(
+ conn,
+ scope_id=session["scope_id"],
+ agent_backend="claude",
+ agent_name="worker",
+ )
+ other_delivery = _reserve_submission(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=other_session["id"],
+ text="foreign delivery",
+ )
+ assert not attach_agent_run_delivery_in_connection(
+ conn,
+ unbound_existing.id,
+ session_id=other_session["id"],
+ delivery_id=other_delivery["id"],
+ )
+ assert not attach_agent_run_delivery_in_connection(
+ conn,
+ bound_create_per_run.id,
+ session_id=other_session["id"],
+ delivery_id=other_delivery["id"],
+ )
+
+
def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatch, tmp_path):
"""A scheduled run for a session that already has a turn in flight ENQUEUES a
harness-attributed ``queued`` row (so it runs AFTER the active turn via the