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(storage): seek callback children and watch heartbeats by their keys (#2653)

Call White6e7624215a93
diff --git a/storage/alembic/versions/20261015_0066_agent_runs_callback_parent_index.py b/storage/alembic/versions/20261015_0066_agent_runs_callback_parent_index.py
new file mode 100644
index 000000000..ce91f1852
--- /dev/null
+++ b/storage/alembic/versions/20261015_0066_agent_runs_callback_parent_index.py
@@ -0,0 +1,67 @@
+"""index a callback child by the parent Run and actor it answers
+
+Enqueueing a Run's callback finds an existing child for the same parent and
+actor before it writes one (``SQLiteBackgroundTaskStore.enqueue_callback_run``).
+No index covered ``parent_run_id``, so the lookup walked every ``agent_run`` row
+through ``ix_agent_runs_type_status_created (run_type=?)`` and sorted them,
+while holding SQLite's write lock (#2524)::
+
+ SEARCH agent_runs USING INDEX ix_agent_runs_type_status_created (run_type=?)
+ USE TEMP B-TREE FOR ORDER BY
+
+On a long-running host that was 11,441 rows per callback enqueue, every other
+writer waiting behind it. The partial index makes it a seek on one parent's
+children, ordered as the lookup reads them: the query states both literals of
+the predicate, so SQLite uses it (``SEARCH agent_runs USING INDEX
+ix_agent_runs_callback_parent (parent_run_id=? AND source_actor=?)``, no temp
+B-tree). Only callback children carry it, so other Runs cost it nothing.
+
+Index only: downgrade drops it, and an older build reads the same rows without
+it.
+
+Revision ID: 20261015_0066
+Revises: 20261013_0065
+Create Date: 2026-10-15
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "20261015_0066"
+down_revision = "20261013_0065"
+branch_labels = None
+depends_on = None
+MIGRATION_SAFETY = "additive"
+
+_INDEX = "ix_agent_runs_callback_parent"
+# Exported so the head-schema repair path in ``storage/migrations.py`` executes THIS
+# statement rather than a retyped copy.
+DROP_INDEX_SQL = f"drop index if exists {_INDEX}"
+CREATE_INDEX_SQL = (
+ f"create index {_INDEX} on agent_runs "
+ "(parent_run_id, source_actor, created_at, id) "
+ "where run_type = 'agent_run' and source_kind = 'callback'"
+)
+
+
+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 upgrade() -> None:
+ bind = op.get_bind()
+ if "agent_runs" not in _tables(bind):
+ return
+ 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)
diff --git a/storage/background.py b/storage/background.py
index 519016aec..efd4656ac 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -519,6 +519,12 @@ NO_EVENT_EXIT_CODE = 64
# read as "running" and leave "waiting" unreachable. Waiter liveness is a
# separate field (``process_alive``), not a state.
_WATCH_RUNTIME_RUN_TYPE = "watch_runtime"
+
+
+def _watch_runtime_run_id(watch_id: str) -> str:
+ """A watch's one supervisor heartbeat row: written as, and read by, this primary key."""
+
+ return f"runtime:{watch_id}"
# The Agent turn a ``--on-failure agent`` command fire queues to REPORT its failure.
# It carries the failing definition's own ``definition_id`` -- that link is how the
# Harness shows the turn beside the task -- and it settles ``succeeded`` whenever the
@@ -8789,7 +8795,7 @@ class SQLiteBackgroundTaskStore:
for watch_id, runtime_payload in watches.items():
if not isinstance(runtime_payload, dict):
continue
- run_id = f"runtime:{watch_id}"
+ run_id = _watch_runtime_run_id(watch_id)
values = self._run_values(
{
"id": run_id,
@@ -9367,6 +9373,9 @@ class SQLiteBackgroundTaskStore:
runtimes: dict[str, dict[str, Any]] = {}
for batch in _id_batches(watch_ids):
+ # A watch has one heartbeat row, ``runtime:<watch id>``: read it by primary
+ # key, so the lookup seeks those rows instead of walking every heartbeat a
+ # watch ever wrote (#2524).
rows = conn.execute(
select(
agent_runs.c.definition_id,
@@ -9376,8 +9385,8 @@ class SQLiteBackgroundTaskStore:
agent_runs.c.updated_at,
agent_runs.c.metadata_json,
)
+ .where(agent_runs.c.id.in_([_watch_runtime_run_id(watch_id) for watch_id in batch]))
.where(agent_runs.c.run_type == _WATCH_RUNTIME_RUN_TYPE)
- .where(agent_runs.c.definition_id.in_(batch))
).mappings()
for row in rows:
payload = _json_loads(row["metadata_json"], {})
diff --git a/storage/migrations.py b/storage/migrations.py
index b52ce6a4d..95de40c60 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -823,6 +823,7 @@ _AGENT_RUNS_INDEX_REVISION_MODULES = (
"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",
+ "storage.alembic.versions.20261015_0066_agent_runs_callback_parent_index",
)
#: 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
@@ -837,6 +838,9 @@ _AGENT_RUNS_INDEX_COLUMNS = frozenset(
"session_id",
"run_type",
"source_kind",
+ "parent_run_id",
+ "source_actor",
+ "id",
}
)
diff --git a/storage/models.py b/storage/models.py
index 5e25a4181..4478ecc03 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -375,6 +375,15 @@ agent_runs = Table(
"and callback_terminal_turn_id is not null and session_id is not null"
),
),
+ # A callback child by the parent Run and actor it answers (migration 0066).
+ Index(
+ "ix_agent_runs_callback_parent",
+ "parent_run_id",
+ "source_actor",
+ "created_at",
+ "id",
+ sqlite_where=text("run_type = 'agent_run' and source_kind = 'callback'"),
+ ),
# 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/test_agent_context_seq_migration.py b/tests/test_agent_context_seq_migration.py
index 296a914eb..a1d95f612 100644
--- a/tests/test_agent_context_seq_migration.py
+++ b/tests/test_agent_context_seq_migration.py
@@ -56,7 +56,7 @@ def test_context_seq_upgrade_and_downgrade_keep_released_rows(tmp_path):
migrations.run_migrations(path)
with sqlite3.connect(path) as conn:
- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261013_0065",)
+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261015_0066",)
assert_released_rows_unchanged(conn)
assert _index_sql(conn, "ix_agent_events_turn_sequence_id") is not None
for table, (first, same_session, other_session) in _IDS.items():
diff --git a/tests/test_harness_failure_visibility.py b/tests/test_harness_failure_visibility.py
index 06fd5b1ca..ef6fb8b82 100644
--- a/tests/test_harness_failure_visibility.py
+++ b/tests/test_harness_failure_visibility.py
@@ -14711,3 +14711,56 @@ def test_an_escalated_command_failure_is_never_delivered_a_notice(
"the suppression leaked to un-escalated failures; every failed command fire "
"would go silent"
)
+
+
+def test_a_callback_childs_lookup_seeks_its_parent_rather_than_walking_every_agent_run(tmp_path: Path) -> None:
+ """#2524: enqueueing a callback first looks for an existing child of the same parent and actor, holding SQLite's
+ write lock. The lookup seeks that parent's callback children in order, never every ``agent_run`` and a sort."""
+
+ sqlite, _ = _store(tmp_path)
+ sqlite.enqueue_run(
+ {
+ "id": "run-parent",
+ "request_type": "agent_run",
+ "status": "succeeded",
+ "session_id": "session-callee",
+ "created_at": "2026-10-15T00:00:00+00:00",
+ }
+ )
+ child = {
+ "id": "run-callback-child",
+ "request_type": "agent_run",
+ "status": "queued",
+ "source_kind": "callback",
+ "source_actor": "vibe",
+ "parent_run_id": "run-parent",
+ "session_id": "session-caller",
+ "created_at": "2026-10-15T00:01:00+00:00",
+ }
+ plans = _agent_run_query_plans(
+ sqlite,
+ tmp_path / "state" / "vibe.sqlite",
+ lambda: sqlite.enqueue_callback_run(child, parent_run_id="run-parent", source_actor="vibe"),
+ )
+ (plan,) = [lines for statement, lines in plans if "agent_runs.parent_run_id = " in statement]
+ assert any("INDEX ix_agent_runs_callback_parent (parent_run_id=? AND source_actor=?)" in line for line in plan), plan
+ assert not any("TEMP B-TREE" in line for line in plan), plan
+
+
+def test_a_watchs_heartbeat_is_read_by_its_row_rather_than_every_heartbeat(tmp_path: Path) -> None:
+ """#2524: a watch's details read its supervisor heartbeat on the loop's paths; one row per watch ever run
+ accumulates, so the read seeks that watch's row by primary key."""
+
+ sqlite, _ = _store(tmp_path)
+ _watch(sqlite, "watch-1")
+ sqlite.write_watch_runtime(
+ {"watches": {"watch-1": {"running": True, "started_at": "2026-10-15T00:00:00+00:00"}}},
+ updated_at="2026-10-15T00:00:00+00:00",
+ )
+ watch: dict = {}
+ plans = _agent_run_query_plans(
+ sqlite, tmp_path / "state" / "vibe.sqlite", lambda: watch.update(sqlite.get_watch("watch-1") or {}),
+ )
+ (plan,) = [lines for statement, lines in plans if "agent_runs.pid" in statement]
+ assert plan and all("(id=?)" in line for line in plan if line.startswith("SEARCH agent_runs")), plan
+ assert watch["runtime"]["running"] is True
diff --git a/tests/test_skill_observability_migration.py b/tests/test_skill_observability_migration.py
index 9eb7a510b..e3b862d18 100644
--- a/tests/test_skill_observability_migration.py
+++ b/tests/test_skill_observability_migration.py
@@ -35,7 +35,7 @@ def test_skill_schema_upgrade_downgrade_preserves_existing_events(tmp_path):
migrations.run_migrations(path)
with sqlite3.connect(path) as conn:
assert conn.execute(f"SELECT {columns} FROM agent_events ORDER BY id").fetchall() == original
- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261013_0065",)
+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261015_0066",)
assert conn.execute("SELECT count(*) FROM skill_usage_daily").fetchone() == (0,)
assert {row[2] for row in conn.execute("PRAGMA foreign_key_list(skill_usage_daily)")} == {
"scopes",
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 92dacdf82..4c73d6131 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -38,7 +38,7 @@ from vibe.message_types import build_partial_index_predicate
pytestmark = pytest.mark.no_sqlite_template
-HEAD_REVISION = "20261013_0065"
+HEAD_REVISION = "20261015_0066"
# ``storage.models`` builds a bare ``MetaData()``, so its foreign keys are unnamed and
# Alembic cannot re-emit them when batch mode recreates a table. Every migration that
# rebuilds one therefore passes this convention; the rebuild simulated below has to pass
diff --git a/tests/test_web_push_provider_invalidation_migration.py b/tests/test_web_push_provider_invalidation_migration.py
index ad7f9f8b1..36d0e0ba8 100644
--- a/tests/test_web_push_provider_invalidation_migration.py
+++ b/tests/test_web_push_provider_invalidation_migration.py
@@ -69,7 +69,7 @@ def test_upgrade_keeps_legacy_disabled_failure_opted_out(tmp_path):
web_push_service.mark_send_failure(conn, endpoint=enabled["endpoint"], disable=True)
with sqlite3.connect(path) as conn:
assert conn.execute("select version_num from alembic_version").fetchone() == (
- "20261013_0065",
+ "20261015_0066",
)
command.downgrade(migrations.alembic_config(path), "20260907_0061")