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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(harness): deduplicate callbacks by terminal turn
cyhc105d73e086d
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex ad1cfca78..ef06e7d0c 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -94,6 +94,7 @@ from core.process_isolation import ()from core.watch_worker import decode_watch_worker_error, localize_worker_errorfrom storage.background import (+ CALLBACK_TERMINAL_TURN_ID_METADATA_KEY,COMMAND_SNAPSHOT_METADATA_KEY,COMMAND_TIMED_OUT_METADATA_KEY,COMMAND_WORKER_METADATA_KEY,@@ -2574,9 +2575,14 @@ class TaskExecutionStore:stored = self._sqlite.get_run(callback_run_id)return TaskExecutionRequest.from_dict(stored) if stored is not None else requestif normalized_callback_parent:+ terminal_turn_id = str(+ run_metadata.get(CALLBACK_TERMINAL_TURN_ID_METADATA_KEY) or ""+ ).strip()existing = self.find_callback_run(parent_run_id=normalized_callback_parent,source_actor=str(source_actor or ""),+ terminal_turn_id=terminal_turn_id or None,+ callback_session_id=session_id,)if existing is not None:self.update_callback_status(@@ -2784,13 +2790,30 @@ class TaskExecutionStore:*,parent_run_id: str,source_actor: str,+ terminal_turn_id: Optional[str] = None,+ callback_session_id: Optional[str] = None,) -> Optional[dict[str, Any]]:if self._sqlite is not None:return self._sqlite.find_callback_run(parent_run_id=parent_run_id,source_actor=source_actor,+ terminal_turn_id=terminal_turn_id,+ callback_session_id=callback_session_id,)+ normalized_turn_id = str(terminal_turn_id or "").strip()+ normalized_session_id = str(callback_session_id or "").strip()for run in self._list_file_runs():+ metadata = run.get("metadata")+ if (+ normalized_turn_id+ and normalized_session_id+ and run.get("request_type") == "agent_run"+ and run.get("source_kind") == "callback"+ and run.get("session_id") == normalized_session_id+ and isinstance(metadata, dict)+ and metadata.get(CALLBACK_TERMINAL_TURN_ID_METADATA_KEY) == normalized_turn_id+ ):+ return runif (run.get("request_type") == "agent_run"and run.get("source_kind") == "callback"@@ -7247,6 +7270,17 @@ class ScheduledTaskService:status = _normalize_requested_run_status(run.get("status")) or str(run.get("status") or "")+ run_metadata = run.get("metadata")+ terminal_turn_id = (+ str(run_metadata.get("turn_id") or "").strip()+ if isinstance(run_metadata, dict)+ else ""+ )+ callback_metadata = (+ {CALLBACK_TERMINAL_TURN_ID_METADATA_KEY: terminal_turn_id}+ if terminal_turn_id+ else None+ )if status in {"failed", "canceled"}:terminal_message = self._fallback_callback_result(run, status=status)terminal_callback = enqueue_session_callback(@@ -7256,6 +7290,7 @@ class ScheduledTaskService:source_actor=f"{run_id}:terminal:{status}",source_session_id=str(run.get("session_id") or "").strip() or None,parent_run_id=run_id or None,+ metadata=callback_metadata,)if terminal_callback is not None:return terminal_callback@@ -7266,6 +7301,7 @@ class ScheduledTaskService:source_actor=run_id,source_session_id=str(run.get("session_id") or "").strip() or None,parent_run_id=run_id or None,+ metadata=callback_metadata,)def _build_callback_message(self, run: dict[str, Any]) -> str:diff --git a/storage/alembic/versions/20260811_0051_callback_terminal_turn_identity.py b/storage/alembic/versions/20260811_0051_callback_terminal_turn_identity.pynew file mode 100644index 000000000..b576d2d39--- /dev/null+++ b/storage/alembic/versions/20260811_0051_callback_terminal_turn_identity.py@@ -0,0 +1,65 @@+"""deduplicate callbacks by callee terminal turn and callback session++A terminal Agent Turn is one callback event even when several accepted Agent+Runs participate in that Turn. The callback Session is the event recipient, so+the durable identity is ``(callback_terminal_turn_id, session_id)`` on callback+child Runs. Parent Runs remain separate audit records and each points to the+shared child through ``callback_run_id``.++Historical callback children are intentionally left with a null terminal Turn.+That avoids inventing provenance and lets the partial unique index coexist with+older per-Run callbacks.++Revision ID: 20260811_0051+Revises: 20260811_0050+Create Date: 2026-08-11+"""++from __future__ import annotations++import sqlalchemy as sa+from alembic import op++revision = "20260811_0051"+down_revision = "20260811_0050"+branch_labels = None+depends_on = None++_INDEX = "uq_agent_runs_callback_terminal_turn_session"+DROP_INDEX_SQL = f"drop index if exists {_INDEX}"+CREATE_INDEX_SQL = (+ f"create unique index {_INDEX} on agent_runs "+ "(callback_terminal_turn_id, session_id) "+ "where run_type = 'agent_run' and source_kind = 'callback' "+ "and callback_terminal_turn_id is not null and session_id is not null"+)+++def _tables(bind) -> set[str]:+ return {str(row[0]) for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")}+++def _columns(bind) -> set[str]:+ return {str(column["name"]) for column in sa.inspect(bind).get_columns("agent_runs")}+++def upgrade() -> None:+ bind = op.get_bind()+ if "agent_runs" not in _tables(bind):+ return+ if "callback_terminal_turn_id" not in _columns(bind):+ op.add_column(+ "agent_runs",+ sa.Column("callback_terminal_turn_id", sa.String(), nullable=True),+ )+ bind.exec_driver_sql(DROP_INDEX_SQL)+ bind.exec_driver_sql(CREATE_INDEX_SQL)+++def downgrade() -> None:+ bind = op.get_bind()+ if "agent_runs" not in _tables(bind):+ return+ bind.exec_driver_sql(DROP_INDEX_SQL)+ # Keep the nullable provenance column so rollback never destroys callback+ # identity data. Older binaries ignore additive columns.diff --git a/storage/background.py b/storage/background.pyindex f52288e8c..272960c16 100644--- a/storage/background.py+++ b/storage/background.py@@ -61,6 +61,8 @@ from storage.session_reclaim import (logger = logging.getLogger(__name__)+CALLBACK_TERMINAL_TURN_ID_METADATA_KEY = "callback_terminal_turn_id"+def _json_dumps(value: Any) -> str:return json.dumps(value, ensure_ascii=False, separators=(",", ":"))@@ -3229,15 +3231,29 @@ class SQLiteBackgroundTaskStore:).mappings().first()if parent is None:raise ValueError(f"callback parent Run not found: {parent_run_id}")- callback_run_id = conn.execute(- select(agent_runs.c.id)- .where(agent_runs.c.run_type == "agent_run")- .where(agent_runs.c.source_kind == "callback")- .where(agent_runs.c.parent_run_id == parent_run_id)- .where(agent_runs.c.source_actor == source_actor)- .order_by(agent_runs.c.created_at, agent_runs.c.id)- .limit(1)- ).scalar_one_or_none()+ terminal_turn_id = str(values.get("callback_terminal_turn_id") or "").strip()+ callback_session_id = str(values.get("session_id") or "").strip()+ callback_run_id = None+ if terminal_turn_id and callback_session_id:+ callback_run_id = conn.execute(+ select(agent_runs.c.id)+ .where(agent_runs.c.run_type == "agent_run")+ .where(agent_runs.c.source_kind == "callback")+ .where(agent_runs.c.callback_terminal_turn_id == terminal_turn_id)+ .where(agent_runs.c.session_id == callback_session_id)+ .order_by(agent_runs.c.created_at, agent_runs.c.id)+ .limit(1)+ ).scalar_one_or_none()+ if callback_run_id is None:+ callback_run_id = conn.execute(+ select(agent_runs.c.id)+ .where(agent_runs.c.run_type == "agent_run")+ .where(agent_runs.c.source_kind == "callback")+ .where(agent_runs.c.parent_run_id == parent_run_id)+ .where(agent_runs.c.source_actor == source_actor)+ .order_by(agent_runs.c.created_at, agent_runs.c.id)+ .limit(1)+ ).scalar_one_or_none()parent_status = normalize_run_status(parent["status"])parent_refuses_new_child = bool(parent["cancel_requested"]) and (parent_status != "canceled"@@ -5821,10 +5837,41 @@ class SQLiteBackgroundTaskStore:*,parent_run_id: str,source_actor: str,+ terminal_turn_id: Optional[str] = None,+ callback_session_id: Optional[str] = None,) -> Optional[dict[str, Any]]:- """Return the callback Run for one parent callback identity."""+ """Return the callback Run referenced by one parent callback ledger."""with self.engine.connect() as conn:+ callback_run_id = conn.execute(+ select(agent_runs.c.callback_run_id)+ .where(agent_runs.c.id == parent_run_id)+ .limit(1)+ ).scalar_one_or_none()+ if callback_run_id:+ row = conn.execute(+ select(agent_runs)+ .where(agent_runs.c.id == callback_run_id)+ .where(agent_runs.c.run_type == "agent_run")+ .where(agent_runs.c.source_kind == "callback")+ .limit(1)+ ).mappings().first()+ if row is not None:+ return self._run_from_row(row)+ normalized_turn_id = str(terminal_turn_id or "").strip()+ normalized_session_id = str(callback_session_id or "").strip()+ if normalized_turn_id and normalized_session_id:+ row = conn.execute(+ select(agent_runs)+ .where(agent_runs.c.run_type == "agent_run")+ .where(agent_runs.c.source_kind == "callback")+ .where(agent_runs.c.callback_terminal_turn_id == normalized_turn_id)+ .where(agent_runs.c.session_id == normalized_session_id)+ .order_by(agent_runs.c.created_at, agent_runs.c.id)+ .limit(1)+ ).mappings().first()+ if row is not None:+ return self._run_from_row(row)row = conn.execute(select(agent_runs).where(agent_runs.c.run_type == "agent_run")@@ -7585,6 +7632,8 @@ class SQLiteBackgroundTaskStore:def _run_values(self, payload: dict[str, Any]) -> dict[str, Any]:created_at = payload.get("created_at") or payload.get("updated_at")message = payload.get("message") or payload.get("prompt")+ raw_metadata = payload.get("metadata")+ metadata = raw_metadata if isinstance(raw_metadata, dict) else {}return {"id": payload["id"],"definition_id": payload.get("definition_id") or payload.get("task_id"),@@ -7615,6 +7664,10 @@ class SQLiteBackgroundTaskStore:"callback_error": payload.get("callback_error"),"callback_run_id": payload.get("callback_run_id"),"callback_completed_at": payload.get("callback_completed_at"),+ "callback_terminal_turn_id": str(+ metadata.get(CALLBACK_TERMINAL_TURN_ID_METADATA_KEY) or ""+ ).strip()+ or None,"cancel_requested": 1 if payload.get("cancel_requested") else 0,"cancel_requested_at": payload.get("cancel_requested_at"),"pid": payload.get("pid"),@@ -7626,7 +7679,7 @@ class SQLiteBackgroundTaskStore:"started_at": payload.get("started_at"),"completed_at": payload.get("completed_at"),"updated_at": payload.get("updated_at") or created_at,- "metadata_json": _json_dumps(payload.get("metadata") or {}),+ "metadata_json": _json_dumps(raw_metadata or {}),}@staticmethod@@ -7740,6 +7793,7 @@ class SQLiteBackgroundTaskStore:"callback_error": row["callback_error"],"callback_run_id": row["callback_run_id"],"callback_completed_at": row["callback_completed_at"],+ "callback_terminal_turn_id": row["callback_terminal_turn_id"],"cancel_requested": bool(row["cancel_requested"]),"cancel_requested_at": row["cancel_requested_at"],"pid": row["pid"],diff --git a/storage/migrations.py b/storage/migrations.pyindex b7397d93d..7a8e896cf 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -108,6 +108,7 @@ PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS = {"callback_error","callback_run_id","callback_completed_at",+ "callback_terminal_turn_id","cancel_requested","cancel_requested_at",},@@ -252,10 +253,10 @@ def ensure_background_indexes(db_path: Path | None = None) -> None:"""Repair head indexes even when the tables already pass readiness checks.``metadata.create_all`` can produce every required table and column without- the expression indexes owned by migrations 0039/0041/0042. Such a database- correctly skips schema migration, so store construction must still enter the- index repair path. Correct expression indexes are detected byte-for-byte- against their owning migration DDL and are not rebuilt on ordinary opens.+ migration-owned indexes. Such a database correctly skips schema migration,+ so store construction must still enter the index repair path. Correct indexes+ are detected byte-for-byte against their owning migration DDL and are not+ rebuilt on ordinary opens."""target_db = (db_path or paths.get_sqlite_state_path()).expanduser().resolve()@@ -263,8 +264,8 @@ def ensure_background_indexes(db_path: Path | None = None) -> None:returnwith sqlite3.connect(target_db) as conn:tables = _table_names(conn)- if {"run_definitions", "agent_runs"}.issubset(tables) and not _agent_runs_expression_indexes_ready(conn):- _ensure_agent_runs_expression_indexes(conn)+ if {"run_definitions", "agent_runs"}.issubset(tables) and not _agent_runs_managed_indexes_ready(conn):+ _ensure_agent_runs_managed_indexes(conn)conn.commit()@@ -543,6 +544,7 @@ def _repair_head_required_columns(conn: sqlite3.Connection, tables: set[str]) ->"callback_error": "TEXT","callback_run_id": "VARCHAR","callback_completed_at": "VARCHAR",+ "callback_terminal_turn_id": "VARCHAR","cancel_requested": "INTEGER not null default 0","cancel_requested_at": "VARCHAR",}.items():@@ -686,8 +688,8 @@ def _ensure_new_background_indexes(conn: sqlite3.Connection) -> None:conn.execute('create index if not exists ix_agent_runs_agent_created on agent_runs (agent_name, created_at)')conn.execute('create index if not exists ix_agent_runs_callback_status on agent_runs (callback_status, completed_at)')conn.execute('create index if not exists ix_agent_runs_updated on agent_runs (updated_at)')- if not _agent_runs_expression_indexes_ready(conn):- _ensure_agent_runs_expression_indexes(conn)+ if not _agent_runs_managed_indexes_ready(conn):+ _ensure_agent_runs_managed_indexes(conn)#: The ``agent_runs`` index migrations whose DDL the head-schema repair path must also@@ -698,18 +700,30 @@ _AGENT_RUNS_INDEX_REVISION_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",+ "storage.alembic.versions.20260811_0051_callback_terminal_turn_identity",)-#: Columns the three index expressions read. A head-shaped database has all of them, but+#: Columns the managed indexes read. A head-shaped database has all of them, but#: this helper is also reached from ``_repair_head_required_columns`` on older drifted#: shapes, and ``create index`` on a missing column raises rather than skipping.-_AGENT_RUNS_INDEX_COLUMNS = frozenset({"definition_id", "created_at", "completed_at", "metadata_json"})+_AGENT_RUNS_INDEX_COLUMNS = frozenset(+ {+ "definition_id",+ "created_at",+ "completed_at",+ "metadata_json",+ "callback_terminal_turn_id",+ "session_id",+ "run_type",+ "source_kind",+ }+)def _normalized_index_sql(value: object) -> str:return " ".join(str(value or "").split()).casefold()-def _agent_runs_expression_indexes_ready(conn: sqlite3.Connection) -> bool:+def _agent_runs_managed_indexes_ready(conn: sqlite3.Connection) -> bool:if not _AGENT_RUNS_INDEX_COLUMNS.issubset(_column_names(conn, "agent_runs")):return Truefor module_name in _AGENT_RUNS_INDEX_REVISION_MODULES:@@ -723,11 +737,12 @@ def _agent_runs_expression_indexes_ready(conn: sqlite3.Connection) -> bool:return True-def _ensure_agent_runs_expression_indexes(conn: sqlite3.Connection) -> None:- """Install the 0039/0041/0042 ``agent_runs`` indexes on a head-shaped database.+def _ensure_agent_runs_managed_indexes(conn: sqlite3.Connection) -> None:+ """Install migration-owned ``agent_runs`` indexes on a head-shaped database.``_ensure_head_indexes`` promises that a head-shaped unversioned database ends up- with every index head has, and until now it silently lagged head by these three.+ with every index head has. It once silently lagged the three performance indexes;+ the same repair path now owns the callback identity index too.Two lanes make that gap reachable without any migration ever running: a databaseborn from ``metadata.create_all`` satisfies ``background_tables_ready`` (tables andcolumns only — never indexes), so ``SQLiteBackgroundTaskStore`` accepts it as readydiff --git a/storage/models.py b/storage/models.pyindex 079ffdb79..f4c870b0b 100644--- a/storage/models.py+++ b/storage/models.py@@ -266,6 +266,7 @@ agent_runs = Table(Column("callback_error", Text, nullable=True),Column("callback_run_id", String, nullable=True),Column("callback_completed_at", String, nullable=True),+ Column("callback_terminal_turn_id", String, nullable=True),Column("cancel_requested", Integer, nullable=False, default=0),Column("cancel_requested_at", String, nullable=True),Column("pid", Integer, nullable=True),@@ -290,6 +291,16 @@ agent_runs = Table(),Index("ix_agent_runs_agent_created", "agent_name", "created_at"),Index("ix_agent_runs_callback_status", "callback_status", "completed_at"),+ Index(+ "uq_agent_runs_callback_terminal_turn_session",+ "callback_terminal_turn_id",+ "session_id",+ unique=True,+ sqlite_where=text(+ "run_type = 'agent_run' and source_kind = 'callback' "+ "and callback_terminal_turn_id is not null and session_id is not null"+ ),+ ),# Leading-timestamp index for the run-graph window scan: updated_at bumps on# every state change, so it is the single column that scan filters on.Index("ix_agent_runs_updated", "updated_at"),diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yamlindex 65796af1c..871aaaa65 100644--- a/tests/scenarios/message_delivery/catalog.yaml+++ b/tests/scenarios/message_delivery/catalog.yaml@@ -61,7 +61,7 @@ scenarios:status: coveredkind: concurrencylayer: contract- test: tests/test_scheduled_tasks.py::test_one_terminal_turn_fans_out_each_accepted_run_callback_once+ test: tests/test_scheduled_tasks.py::test_directed_run_and_callback_remain_distinct_while_target_busy- id: MESSAGE-DELIVERY-009name: P1 terminal race produces one accepted attachment or one P3 fallback ownerstatus: covered@@ -242,5 +242,11 @@ scenarios:kind: recoverylayer: contracttest: tests/test_session_delivery_fsm.py::test_accepted_receipt_recovery_preserves_attempt_batch_and_run_attachment+ - id: MESSAGE-DELIVERY-314+ name: One callee terminal Turn callbacks each callback Session once+ status: covered+ kind: concurrency+ layer: contract+ test: tests/test_scheduled_tasks.py::test_one_terminal_turn_callbacks_once_per_callback_sessionnext_priority:- - MESSAGE-DELIVERY-314+ - MESSAGE-DELIVERY-315diff --git a/tests/scenarios/message_delivery/observations.yaml b/tests/scenarios/message_delivery/observations.yamlindex fcedc1d97..f382b5ac4 100644--- a/tests/scenarios/message_delivery/observations.yaml+++ b/tests/scenarios/message_delivery/observations.yaml@@ -35,3 +35,14 @@ observations:- derive callback payloads only from the parent Run terminal result- keep directed child Runs as separate durable queue objects with their own callback policy- preserve intermediate assistant and tool activity in the target Session only+ - id: OBS-MESSAGE-DELIVERY-004+ source: live_local_diagnosis+ related_scenarios:+ - MESSAGE-DELIVERY-314+ summary: Four Agent Runs accepted into one callee Turn produced four identical callbacks to one callback Session.+ previous_assumption: Callback idempotency belonged to each parent Run and its source actor.+ observed_behavior: The four parent Runs settled from the same terminal Turn and each created a separate callback Run carrying the same terminal result.+ required_updates:+ - identify callback events by callee terminal Turn and callback Session+ - point every participating parent Run ledger to the shared callback Run+ - keep callbacks for different terminal Turns or callback Sessions independentdiff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex 2053b781a..70368f9b4 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -6728,22 +6728,25 @@ def test_agent_run_callback_enqueues_only_result_to_caller_session(tmp_path: Patassert callback_run["metadata"]["source_session_id"] == "target-session"-def test_one_terminal_turn_fans_out_each_accepted_run_callback_once(+def test_one_terminal_turn_callbacks_once_per_callback_session(tmp_path: Path,monkeypatch,) -> None:- """Scenario: MESSAGE-DELIVERY-008 closed-loop subscriber fan-out."""+ """Scenario: MESSAGE-DELIVERY-314 terminal Turn callback identity."""monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- caller_session_id = _make_avibe_session(- monkeypatch,- tmp_path,- scope_native_id="callback-fanout-caller",- )+ caller_session_ids = [+ _make_avibe_session(+ monkeypatch,+ tmp_path,+ scope_native_id=f"callback-turn-caller-{index}",+ )+ for index in range(2)+ ]target_session_id = _make_avibe_session(monkeypatch,tmp_path,- scope_native_id="callback-fanout-target",+ scope_native_id="callback-turn-target",)request_store = TaskExecutionStore()requests = [@@ -6751,9 +6754,13 @@ def test_one_terminal_turn_fans_out_each_accepted_run_callback_once(session_id=target_session_id,message=message,agent_name="codex",- callback_session_id=caller_session_id,+ callback_session_id=callback_session_id,+ )+ for message, callback_session_id in (+ ("participant one", caller_session_ids[0]),+ ("participant two", caller_session_ids[0]),+ ("participant three", caller_session_ids[1]),)- for message in ("participant one", "participant two")]for request in requests:assert request_store.claim(request.id) is not None@@ -6761,7 +6768,7 @@ def test_one_terminal_turn_fans_out_each_accepted_run_callback_once(service = _callback_service(tmp_path=tmp_path, request_store=request_store)service.settle_agent_runs_from_terminal_turn([request.id for request in requests],- turn_id="turn-shared-by-two-runs",+ turn_id="turn-shared-by-three-runs",outcome="completed",settled_by="terminal_result",evidence_kind="terminal_result",@@ -6782,15 +6789,81 @@ def test_one_terminal_turn_fans_out_each_accepted_run_callback_once(if run.get("source_kind") == "callback"]assert len(callbacks) == 2- assert {run["parent_run_id"] for run in callbacks} == {- request.id for request in requests- }+ assert {run["session_id"] for run in callbacks} == set(caller_session_ids)assert {run["message"] for run in callbacks} == {"shared immutable terminal result"}assert {run["metadata"]["delivery_intent"] for run in callbacks} == {"steer"}+ assert {+ run["metadata"]["callback_terminal_turn_id"] for run in callbacks+ } == {"turn-shared-by-three-runs"}++ callback_ids_by_parent = {+ str(row["id"]): str(row["callback_run_id"]) for row in originals+ }+ assert callback_ids_by_parent[requests[0].id] == callback_ids_by_parent[requests[1].id]+ assert callback_ids_by_parent[requests[2].id] != callback_ids_by_parent[requests[0].id]+++def test_distinct_terminal_turns_callback_same_session_independently(+ tmp_path: Path,+ monkeypatch,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ caller_session_id = _make_avibe_session(+ monkeypatch,+ tmp_path,+ scope_native_id="callback-distinct-turn-caller",+ )+ target_session_id = _make_avibe_session(+ monkeypatch,+ tmp_path,+ scope_native_id="callback-distinct-turn-target",+ )+ request_store = TaskExecutionStore()+ requests = [+ request_store.enqueue_agent_run(+ session_id=target_session_id,+ message=f"participant {index}",+ agent_name="codex",+ callback_session_id=caller_session_id,+ )+ for index in range(2)+ ]+ service = _callback_service(tmp_path=tmp_path, request_store=request_store)++ for index, request in enumerate(requests):+ assert request_store.claim(request.id) is not None+ service.settle_agent_runs_from_terminal_turn(+ [request.id],+ turn_id=f"turn-distinct-{index}",+ outcome="completed",+ settled_by="terminal_result",+ evidence_kind="terminal_result",+ evidence={+ "settles_run": True,+ "result_text": f"terminal result {index}",+ },+ )++ asyncio.run(service._drain_callbacks())+ callbacks = [+ run+ for run in request_store.list_runs()+ if run.get("source_kind") == "callback"+ ]++ assert len(callbacks) == 2+ assert {run["session_id"] for run in callbacks} == {caller_session_id}+ assert {run["message"] for run in callbacks} == {+ "terminal result 0",+ "terminal result 1",+ }+ assert {+ run["metadata"]["callback_terminal_turn_id"] for run in callbacks+ } == {"turn-distinct-0", "turn-distinct-1"}def test_hfr_439_turn_failure_metadata_reaches_every_linked_run(diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex d04ca5abf..7cda5dfb1 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -31,7 +31,7 @@ from vibe.message_types import build_partial_index_predicatepytestmark = pytest.mark.no_sqlite_template-HEAD_REVISION = "20260811_0050"+HEAD_REVISION = "20260811_0051"MESSAGE_PARTIAL_INDEX_PREDICATES = {"ix_messages_inbox_activity": ("session_id is not null and type in "@@ -243,6 +243,85 @@ def test_accepted_steer_receipt_migration_preserves_upgrade_and_downgrade_invari)+def test_callback_terminal_turn_identity_migration_preserves_rows_and_scope(+ tmp_path: Path,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision="20260811_0050")+ command.upgrade(migrations.alembic_config(db_path), "head")+ now = "2026-08-11T00:00:00Z"++ def insert_callback(+ conn,+ *,+ run_id: str,+ terminal_turn_id: str,+ session_id: str,+ ) -> None:+ conn.execute(+ """+ insert into agent_runs (+ id, run_type, status, source_kind, session_id,+ callback_terminal_turn_id, cancel_requested,+ created_at, updated_at, metadata_json+ ) values (?, 'agent_run', 'queued', 'callback', ?, ?, 0, ?, ?, '{}')+ """,+ (run_id, session_id, terminal_turn_id, now, now),+ )++ with sqlite3.connect(db_path) as conn:+ columns = {row[1] for row in conn.execute("pragma table_info('agent_runs')")}+ assert "callback_terminal_turn_id" in columns+ assert "where run_type = 'agent_run'" in _index_sql(+ conn, "uq_agent_runs_callback_terminal_turn_session"+ ).lower()+ insert_callback(+ conn,+ run_id="callback-one",+ terminal_turn_id="turn-one",+ session_id="session-one",+ )+ conn.commit()++ with pytest.raises(sqlite3.IntegrityError):+ with sqlite3.connect(db_path) as conn:+ insert_callback(+ conn,+ run_id="callback-duplicate",+ terminal_turn_id="turn-one",+ session_id="session-one",+ )++ with sqlite3.connect(db_path) as conn:+ insert_callback(+ conn,+ run_id="callback-other-turn",+ terminal_turn_id="turn-two",+ session_id="session-one",+ )+ insert_callback(+ conn,+ run_id="callback-other-session",+ terminal_turn_id="turn-one",+ session_id="session-two",+ )+ conn.commit()++ command.downgrade(migrations.alembic_config(db_path), "20260811_0050")+ with sqlite3.connect(db_path) as conn:+ assert conn.execute(+ "select name from sqlite_master where type = 'index' and name = ?",+ ("uq_agent_runs_callback_terminal_turn_session",),+ ).fetchone() is None+ assert conn.execute(+ "select id from agent_runs where source_kind = 'callback' order by id"+ ).fetchall() == [+ ("callback-one",),+ ("callback-other-session",),+ ("callback-other-turn",),+ ]++def test_agent_lifecycle_message_index_migration_upgrades_and_downgrades(tmp_path: Path,) -> None: