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.

perf(ci): reduce repeated database fixture work (#1896)

Call Whiteeebd519a866b
diff --git a/docs/plans/ci-database-seeding.md b/docs/plans/ci-database-seeding.md
new file mode 100644
index 000000000..ca18cc716
--- /dev/null
+++ b/docs/plans/ci-database-seeding.md
@@ -0,0 +1,107 @@
+# CI Database Seeding
+
+## Scope and Order
+
+The owner approved removing measured repeated database work in this order:
+chat discovery setup, Harness history seeding, then incidental preparation in
+migration and scheduling tests. Start from master `1ee2e1973`.
+
+The initial scope is `tests/test_chat_discovery.py` and this plan. Reuse the
+existing exclusive, per-test `sqlite_db_factory` with an explicit template built
+by the original `run_migrations` recipe, not the importer-initialized default
+template. Leave legacy import tests on their original initialization path.
+
+Next inspect and profile Harness fixture transactions, then migration and
+scheduling preparation. Expand the scope only with a measured, bounded cause.
+Do not change application code, dependencies, runners, timeouts, selection,
+real migration/locking behavior, or fail-closed CI aggregation.
+
+## Invariants
+
+- Every ordinary test gets a private copy in its isolated temporary directory.
+- The template is closed and checkpointed before copying. Schema, every initial
+ table row, persisted pragmas and integrity match real initialization.
+- Mutating one copy cannot change the template or another copy; copying cannot
+ overwrite existing state or escape the test directory.
+- Original behavior assertions remain intact. Large-history query tests retain
+ their complete data volume, real query plans and row/decode bounds.
+- Historical upgrades, downgrades, legacy imports and real lock faults remain
+ real operations. Only preparation outside the property under test may change.
+
+## Evidence
+
+Latest master CI `33981278943` passed all 17 checks and all 400 Python files in
+6m52s. Its critical Python shard took 6m44s; chat discovery took 31.79s.
+Recent green samples vary, so no runner-cause or stable speedup is inferred.
+
+Local unmodified chat discovery: 32 passed in 18.14s. Thirty direct migrations
+initialize the same empty schema; 28 belong to ordinary behavior tests. The
+remaining two prepare actual legacy-import cases and are deliberately unchanged.
+Local unmodified Harness: 224 passed in 25.90s; streak history 3.33s, predecessor
+history 0.64s. Linux CI is slower, so local timing is not a CI speedup claim.
+
+## Scope Decisions
+
+### Step Two Scope Decision
+
+Extend scope to `tests/test_harness_failure_visibility.py` only. A profile of
+the two query regressions recorded 7,701 `enqueue_run` calls costing 8.00s,
+versus 0.027s for the streak decision reads (profiling adds overhead). Static
+history setup can share a transaction without changing the queries being tested.
+Use the existing production serializer, connection writer and deferred-event
+transaction owner; do not duplicate upsert or backend-identity logic. Cover
+exact persisted-row equivalence, including an overwritten run, and one commit
+for a batch. Reads, query/decode budgets and history sizes stay unchanged.
+
+Step one passed 44 chat/fixture tests in 7.29s, including full schema/row/pragma
+equivalence and private-copy mutation checks. This is not a CI speedup result.
+
+### Step Three Scope Decision
+
+Extend scope to `tests/test_sqlite_state_migration.py` for read-only reference
+values only. The full original suite passed 128 cases under profiling in 47.61s;
+21 `_upgraded_db` calls took 7.41s, and three identical index-reference builds
+took 1.09s. Seven schema-reference builds repeat three revisions. Cache those
+reference values as immutable sets and the index reference as a read-only map,
+within this test module only. Every database under test still starts on its
+original path and performs its original real migration calls. Do not cache
+tested upgrade results or alter the historical revision inventory.
+
+Harness after transaction batching: 225 passed in 20.80s; streak query case
+3.33s to 2.75s locally. The whole-file comparison also contains unrelated import
+variance and is not wholly attributable to batching. CI must establish I/O gains.
+
+The added reference contract originally compared raw whole-schema DDL from two
+fresh builds and caught nondeterministic Alembic foreign-key declaration ordering
+in `message_deliveries` and `media_objects`. Existing `_schema_fingerprint` already
+models structural equivalence for template tests. The reference cache contract now
+pins immutable single-build reuse; all original migration-result comparisons remain
+unchanged, rather than redefining their equality or migration behavior.
+
+Scheduling profile: all 489 cases passed in 63.48s, including the real lock fault
+(10.95s) and refused-result notice (5.47s). Remaining migration calls include real
+importer/Agent-store entrypoints, not only fixture preparation. Leave this file
+unchanged: bypassing these paths or reducing SQLite's production lock timeout would
+change coverage for an unproven benefit. No blanket template rollout is justified.
+
+## Review and Delivery
+
+Final local checks: chat 33 passed in 6.80s (observer wall 6.97s), Harness 225
+passed, real migrations 129 passed in 28.22s, workflow/shard/fixture/lifecycle
+contracts 119 passed. All 340 original test definitions retain their 1,829
+original assertions by AST comparison. Ruff 0.4.9 and dependency check passed.
+No test file selection changes. Only these three test modules and this plan
+are in scope; shared fixtures and production code remain unchanged.
+
+Before review, integrate master `b5972b68c` (#1891, #1893, #1895). Inspection
+of changed Model Hub/prompt APIs and consuming tests, and the chat paging
+consumer confirms no overlap with this scope. Retest relevant Python consumers
+after integration; production UI and all installation gates run in CI.
+Post-integration chat/Harness/migration/Model Hub/prompt validation: 542 passed
+in 63.32s. All local test processes finished; the task uses a private virtualenv
+and temporary dependency cache, with no production environment changes.
+
+Initial findings-bearing review heads: zero. Keep one durable PR/CI watch and
+its cursor through all heads; require exact-head review, all 17 checks, every
+matching lint run, no unresolved whole-PR threads, and CLEAN integration before
+guarded merge. Verify the merged source's own CI before final delivery.
diff --git a/tests/test_chat_discovery.py b/tests/test_chat_discovery.py
index 034dac0d8..fcd56d8e9 100644
--- a/tests/test_chat_discovery.py
+++ b/tests/test_chat_discovery.py
@@ -1,8 +1,12 @@
from __future__ import annotations
import json
+import sqlite3
+from contextlib import closing
from pathlib import Path
+import pytest
+
from config.v2_settings import ChannelSettings, SettingsState
from core import chat_discovery
from storage.migrations import run_migrations
@@ -11,6 +15,43 @@ from storage.workbench_sessions_service import create_session
from storage.settings_service import SQLiteSettingsService
[email protected](scope="module")
+def _chat_schema_template(tmp_path_factory):
+ path = tmp_path_factory.mktemp("chat-schema") / "empty.sqlite"
+ run_migrations(path)
+ with closing(sqlite3.connect(path)) as connection:
+ connection.execute("PRAGMA wal_checkpoint(TRUNCATE)")
+ return path
+
+
+def db_path(tmp_path, sqlite_db_factory, _chat_schema_template):
+ return sqlite_db_factory(tmp_path / "vibe.sqlite", template=_chat_schema_template)
+
+
+def test_chat_template_matches_real_migration_and_keeps_copies_private(
+ tmp_path, db_path, sqlite_db_factory, _chat_schema_template,
+):
+ from tests.test_sqlite_state_migration import _schema_fingerprint
+
+ reference = tmp_path / "reference.sqlite"
+ run_migrations(reference)
+ with closing(sqlite3.connect(reference)) as fresh, closing(sqlite3.connect(db_path)) as clone:
+ assert _schema_fingerprint(fresh) == _schema_fingerprint(clone)
+ assert sorted(row for row in fresh.iterdump() if row.startswith("INSERT INTO")) == sorted(
+ row for row in clone.iterdump() if row.startswith("INSERT INTO")
+ )
+ for pragma in ("journal_mode", "user_version", "application_id"):
+ assert fresh.execute(f"PRAGMA {pragma}").fetchall() == clone.execute(f"PRAGMA {pragma}").fetchall()
+ assert clone.execute("PRAGMA integrity_check").fetchone() == ("ok",)
+ original = _chat_schema_template.read_bytes()
+ with closing(sqlite3.connect(db_path)) as connection, connection:
+ connection.execute("CREATE TABLE fixture_mutation (value TEXT)")
+ connection.execute("INSERT INTO fixture_mutation VALUES ('private')")
+ other = sqlite_db_factory(tmp_path / "other.sqlite", template=_chat_schema_template)
+ assert other.read_bytes() == _chat_schema_template.read_bytes() == original
+
+
def _auth_context(platform: str, **kwargs) -> str:
value = chat_discovery._auth_context_for(platform, kwargs)
assert value is not None
@@ -37,10 +78,7 @@ def test_metadata_merge_preserves_unknown_keys_and_sticky_true_flags() -> None:
assert merged[chat_discovery.METADATA_VISIBILITY_STATUS] == chat_discovery.VISIBILITY_VISIBLE
-def test_remember_chat_lists_inventory_with_configured_state(tmp_path: Path) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
-
+def test_remember_chat_lists_inventory_with_configured_state(db_path: Path) -> None:
chat_discovery.remember_chat(
"telegram",
"123",
@@ -71,9 +109,7 @@ def test_remember_chat_lists_inventory_with_configured_state(tmp_path: Path) ->
assert chats[0].visibility_status == chat_discovery.VISIBILITY_VISIBLE
-def test_remember_thread_lists_discovered_and_configured_topics(tmp_path: Path) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_remember_thread_lists_discovered_and_configured_topics(db_path: Path) -> None:
chat_discovery.remember_chat(
"telegram",
"-1001",
@@ -113,10 +149,8 @@ def test_remember_thread_lists_discovered_and_configured_topics(tmp_path: Path)
assert topics[0]["name"] == "Releases"
-def test_passively_discovered_topics_leave_fallback_names_to_ui(tmp_path: Path) -> None:
+def test_passively_discovered_topics_leave_fallback_names_to_ui(db_path: Path) -> None:
# Scenario: TELEGRAM-TOPIC-004
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
chat_discovery.remember_chat(
"telegram",
"-1001",
@@ -145,9 +179,7 @@ def test_passively_discovered_topics_leave_fallback_names_to_ui(tmp_path: Path)
assert [(topic["id"], topic["name"]) for topic in topics] == [("1", ""), ("42", "")]
-def test_remember_chat_debounce_does_not_suppress_retry_after_persist_failure(tmp_path: Path, monkeypatch) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_remember_chat_debounce_does_not_suppress_retry_after_persist_failure(db_path: Path, monkeypatch) -> None:
original_upsert_scope = chat_discovery.upsert_scope
calls = 0
@@ -220,9 +252,7 @@ def test_legacy_migration_rename_tolerates_missing_source(tmp_path: Path) -> Non
assert target.exists() is False
-def test_refresh_marks_absent_rows_not_returned_without_deleting_settings(tmp_path: Path, monkeypatch) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_refresh_marks_absent_rows_not_returned_without_deleting_settings(db_path: Path, monkeypatch) -> None:
chat_discovery.remember_chat(
"slack",
"C_OLD",
@@ -261,9 +291,7 @@ def test_refresh_marks_absent_rows_not_returned_without_deleting_settings(tmp_pa
assert chats["C_OLD"].configured is True
-def test_refresh_failure_keeps_stale_cache_and_records_error(tmp_path: Path, monkeypatch) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_refresh_failure_keeps_stale_cache_and_records_error(db_path: Path, monkeypatch) -> None:
chat_discovery.remember_chat(
"slack",
"C_KEEP",
@@ -290,9 +318,7 @@ def test_refresh_failure_keeps_stale_cache_and_records_error(tmp_path: Path, mon
assert response["error"] == "boom"
-def test_empty_cache_channel_response_respects_refresh_backoff(tmp_path: Path, monkeypatch) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_empty_cache_channel_response_respects_refresh_backoff(db_path: Path, monkeypatch) -> None:
calls = 0
from vibe import api
@@ -314,9 +340,7 @@ def test_empty_cache_channel_response_respects_refresh_backoff(tmp_path: Path, m
assert second["error"] == "bad token"
-def test_stale_cache_schedules_only_one_background_refresh(tmp_path: Path, monkeypatch) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_stale_cache_schedules_only_one_background_refresh(db_path: Path, monkeypatch) -> None:
auth_context = _auth_context("slack", bot_token="x")
chat_discovery.remember_chat(
"slack",
@@ -358,9 +382,7 @@ def test_stale_cache_schedules_only_one_background_refresh(tmp_path: Path, monke
assert second["refreshing"] is True
-def test_slack_cached_response_respects_member_only_browse_mode(tmp_path: Path) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_slack_cached_response_respects_member_only_browse_mode(db_path: Path) -> None:
auth_context = _auth_context("slack", bot_token="x")
chat_discovery.remember_chat(
"slack",
@@ -389,9 +411,7 @@ def test_slack_cached_response_respects_member_only_browse_mode(tmp_path: Path)
assert {channel["id"] for channel in browse_all["channels"]} == {"C_MEMBER", "C_OTHER"}
-def test_slack_member_only_response_excludes_not_returned_member_channels(tmp_path: Path) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_slack_member_only_response_excludes_not_returned_member_channels(db_path: Path) -> None:
auth_context = _auth_context("slack", bot_token="x")
chat_discovery.remember_chat(
"slack",
@@ -425,9 +445,7 @@ def test_slack_member_only_response_excludes_not_returned_member_channels(tmp_pa
assert [channel["id"] for channel in response["channels"]] == ["C_PRESENT"]
-def test_slack_member_only_opt_in_exposes_not_returned_member_channels(tmp_path: Path) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_slack_member_only_opt_in_exposes_not_returned_member_channels(db_path: Path) -> None:
auth_context = _auth_context("slack", bot_token="x")
chat_discovery.remember_chat(
"slack",
@@ -466,9 +484,7 @@ def test_slack_member_only_opt_in_exposes_not_returned_member_channels(tmp_path:
assert response["summary"]["not_returned_count"] == 1
-def test_slack_browse_all_refreshes_after_member_only_cache_hit(tmp_path: Path, monkeypatch) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_slack_browse_all_refreshes_after_member_only_cache_hit(db_path: Path, monkeypatch) -> None:
calls: list[bool] = []
from vibe import api
@@ -510,9 +526,7 @@ def test_slack_browse_all_refreshes_after_member_only_cache_hit(tmp_path: Path,
assert {channel["id"] for channel in cached_browse_all["channels"]} == {"C_MEMBER", "C_OTHER"}
-def test_slack_channel_cache_is_scoped_by_auth_context(tmp_path: Path, monkeypatch) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_slack_channel_cache_is_scoped_by_auth_context(db_path: Path, monkeypatch) -> None:
calls: list[str] = []
from vibe import api
@@ -538,9 +552,7 @@ def test_slack_channel_cache_is_scoped_by_auth_context(tmp_path: Path, monkeypat
assert [channel["id"] for channel in cached_first["channels"]] == ["C_A"]
-def test_active_channel_response_rejects_missing_auth_context_without_cache_read(tmp_path: Path) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_active_channel_response_rejects_missing_auth_context_without_cache_read(db_path: Path) -> None:
chat_discovery.remember_chat(
"slack",
"C_OLD",
@@ -556,9 +568,7 @@ def test_active_channel_response_rejects_missing_auth_context_without_cache_read
assert response["error"] == "Missing slack channel refresh credentials"
-def test_discord_refresh_state_is_scoped_by_guild(tmp_path: Path, monkeypatch) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_discord_refresh_state_is_scoped_by_guild(db_path: Path, monkeypatch) -> None:
calls: list[str] = []
from vibe import api
@@ -597,10 +607,7 @@ def test_discord_refresh_state_is_scoped_by_guild(tmp_path: Path, monkeypatch) -
assert chat_discovery.refresh_state("discord", db_path=db_path).last_success_at is None
-def test_discord_cached_payload_preserves_numeric_channel_type(tmp_path: Path, monkeypatch) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
-
+def test_discord_cached_payload_preserves_numeric_channel_type(db_path: Path, monkeypatch) -> None:
from vibe import api
monkeypatch.setattr(
@@ -659,9 +666,7 @@ def _seed_not_returned_discord(db_path: Path) -> None:
)
-def test_channels_response_hides_not_returned_by_default_and_opts_in(tmp_path: Path) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_channels_response_hides_not_returned_by_default_and_opts_in(db_path: Path) -> None:
_seed_not_returned_discord(db_path)
# Mark already fetched so no live refresh is attempted.
chat_discovery.set_state_meta(
@@ -691,9 +696,7 @@ def test_channels_response_hides_not_returned_by_default_and_opts_in(tmp_path: P
assert shown["summary"]["not_returned_count"] == 1
-def test_all_not_returned_does_not_trigger_refresh_each_call(tmp_path: Path, monkeypatch) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_all_not_returned_does_not_trigger_refresh_each_call(db_path: Path, monkeypatch) -> None:
auth_context = _auth_context("slack", bot_token="x")
chat_discovery.remember_chat(
"slack",
@@ -734,9 +737,7 @@ def test_all_not_returned_does_not_trigger_refresh_each_call(tmp_path: Path, mon
assert first["summary"]["not_returned_count"] == 1
-def test_refresh_skips_not_returned_marking_when_lark_truncated(tmp_path: Path, monkeypatch) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_refresh_skips_not_returned_marking_when_lark_truncated(db_path: Path, monkeypatch) -> None:
auth_context = _auth_context("lark", app_id="a", app_secret="s", domain="feishu")
chat_discovery.remember_chat(
"lark",
@@ -770,9 +771,7 @@ def test_refresh_skips_not_returned_marking_when_lark_truncated(tmp_path: Path,
assert chats["oc_new"].visibility_status == chat_discovery.VISIBILITY_VISIBLE
-def test_background_refresh_skips_marking_when_lark_truncated(tmp_path: Path, monkeypatch) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_background_refresh_skips_marking_when_lark_truncated(db_path: Path, monkeypatch) -> None:
auth_context = _auth_context("lark", app_id="a", app_secret="s", domain="feishu")
chat_discovery.remember_chat(
"lark",
@@ -822,9 +821,7 @@ def test_background_refresh_skips_marking_when_lark_truncated(tmp_path: Path, mo
assert chats["oc_keepbg"].visibility_status != chat_discovery.VISIBILITY_NOT_RETURNED
-def test_delete_scope_removes_scope_and_settings(tmp_path: Path) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_delete_scope_removes_scope_and_settings(db_path: Path) -> None:
chat_discovery.remember_chat("telegram", "999", name="Gone", db_path=db_path)
service = SQLiteSettingsService(db_path)
try:
@@ -851,9 +848,7 @@ def test_delete_scope_removes_scope_and_settings(tmp_path: Path) -> None:
}
-def test_delete_scope_cascades_child_thread_settings(tmp_path: Path) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_delete_scope_cascades_child_thread_settings(db_path: Path) -> None:
chat_discovery.remember_chat("telegram", "-1001", name="Forum", db_path=db_path)
chat_discovery.remember_thread(
"telegram",
@@ -893,13 +888,11 @@ def test_delete_scope_cascades_child_thread_settings(tmp_path: Path) -> None:
reloaded.close()
-def test_delete_scope_preserves_child_thread_history(tmp_path: Path) -> None:
+def test_delete_scope_preserves_child_thread_history(db_path: Path) -> None:
from datetime import datetime, timezone
from storage.models import messages
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
chat_discovery.remember_chat("telegram", "-1001", name="Forum", db_path=db_path)
chat_discovery.remember_thread(
"telegram",
@@ -997,13 +990,11 @@ def test_delete_scope_preserves_child_thread_history(tmp_path: Path) -> None:
reloaded.close()
-def test_delete_scope_with_history_dismisses_instead_of_deleting(tmp_path: Path) -> None:
+def test_delete_scope_with_history_dismisses_instead_of_deleting(db_path: Path) -> None:
from datetime import datetime, timezone
from storage.models import messages
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
chat_discovery.remember_chat("telegram", "777", name="HasHistory", db_path=db_path)
scope_id = chat_discovery.make_scope_id("telegram", chat_discovery.CHANNEL_SCOPE_TYPE, "777")
@@ -1046,9 +1037,7 @@ def test_delete_scope_with_history_dismisses_instead_of_deleting(tmp_path: Path)
assert kept is not None
-def test_delete_scope_with_pending_delivery_dismisses_instead_of_deleting(tmp_path: Path) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_delete_scope_with_pending_delivery_dismisses_instead_of_deleting(db_path: Path) -> None:
chat_discovery.remember_chat("telegram", "pending", name="Pending", db_path=db_path)
scope_id = chat_discovery.make_scope_id(
"telegram",
@@ -1097,9 +1086,7 @@ def test_delete_scope_with_pending_delivery_dismisses_instead_of_deleting(tmp_pa
engine.dispose()
-def test_delete_scope_ignores_retired_delivery_snapshots(tmp_path: Path) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_delete_scope_ignores_retired_delivery_snapshots(db_path: Path) -> None:
chat_discovery.remember_chat("telegram", "retired", name="Retired", db_path=db_path)
scope_id = chat_discovery.make_scope_id(
"telegram",
@@ -1147,13 +1134,11 @@ def test_delete_scope_ignores_retired_delivery_snapshots(tmp_path: Path) -> None
}
-def test_remember_chat_clears_dismissed_on_passive_rediscovery(tmp_path: Path) -> None:
+def test_remember_chat_clears_dismissed_on_passive_rediscovery(db_path: Path) -> None:
from datetime import datetime, timezone
from storage.models import messages
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
chat_discovery.remember_chat("telegram", "tg_redisc", name="Gone", db_path=db_path)
scope_id = chat_discovery.make_scope_id("telegram", chat_discovery.CHANNEL_SCOPE_TYPE, "tg_redisc")
@@ -1190,9 +1175,7 @@ def test_remember_chat_clears_dismissed_on_passive_rediscovery(tmp_path: Path) -
assert [c.chat_id for c in chat_discovery.list_chats("telegram", db_path=db_path)] == ["tg_redisc"]
-def test_refresh_clears_dismissed_flag_on_rediscovery(tmp_path: Path, monkeypatch) -> None:
- db_path = tmp_path / "vibe.sqlite"
- run_migrations(db_path)
+def test_refresh_clears_dismissed_flag_on_rediscovery(db_path: Path, monkeypatch) -> None:
auth_context = _auth_context("slack", bot_token="x")
chat_discovery.remember_chat(
"slack",
diff --git a/tests/test_harness_failure_visibility.py b/tests/test_harness_failure_visibility.py
index afd3b5f43..28f52dc92 100644
--- a/tests/test_harness_failure_visibility.py
+++ b/tests/test_harness_failure_visibility.py
@@ -36,7 +36,9 @@ from storage.background import (
RUN_INTERRUPTION_REASONS,
SQLiteBackgroundTaskStore,
TASK_RETIREMENT_SCHEDULE_CONSUMED,
+ enqueue_run_in_connection,
owed_notice_eligible,
+ run_update_event_transaction,
)
@@ -55,6 +57,53 @@ def _store(tmp_path: Path) -> tuple[SQLiteBackgroundTaskStore, TaskExecutionStor
return sqlite, requests
+def _seed_query_history(sqlite: SQLiteBackgroundTaskStore, payloads: list[dict]) -> None:
+ # Static query fixtures need the same durable rows, not one commit per row.
+ with run_update_event_transaction(sqlite.engine) as connection:
+ for payload in payloads:
+ enqueue_run_in_connection(connection, sqlite._run_values(payload))
+
+
+def test_query_history_batch_matches_individual_writes(tmp_path, sqlite_db_factory):
+ from storage.models import agent_runs
+
+ sqlite_db_factory(tmp_path / "reference" / "state" / "vibe.sqlite")
+ reference, _ = _store(tmp_path / "reference")
+ batched, _ = _store(tmp_path)
+ payloads = [
+ {
+ "id": f"run-{index % 2}", "definition_id": "fixture",
+ "request_type": "scheduled", "status": status,
+ "created_at": _EPOCH, "completed_at": _EPOCH,
+ "agent_backend": "codex" if index == 0 else None,
+ "metadata": {"owed_failure_notice": {"state": "pending", "attempts": index}},
+ }
+ for index, status in enumerate(("failed", "succeeded", "running"))
+ ]
+ commits = []
+
+ def committed(connection):
+ commits.append(True)
+
+ try:
+ for store in (reference, batched):
+ _task(store, "fixture")
+ for payload in payloads:
+ reference.enqueue_run(payload)
+ event.listen(batched.engine, "commit", committed)
+ try:
+ _seed_query_history(batched, payloads)
+ finally:
+ event.remove(batched.engine, "commit", committed)
+ assert commits == [True]
+ with reference.engine.connect() as fresh, batched.engine.connect() as clone:
+ statement = select(agent_runs).order_by(agent_runs.c.id)
+ assert fresh.execute(statement).fetchall() == clone.execute(statement).fetchall()
+ finally:
+ reference.close()
+ batched.close()
+
+
_EPOCH = "2026-07-01T00:00:00+00:00"
@@ -1203,8 +1252,9 @@ def test_the_predecessor_read_is_bounded_and_seeks_rather_than_scans(tmp_path: P
sqlite, _ = _store(tmp_path)
_task(sqlite, "task-pred-plan", session_policy="create_per_run")
backlog = 1200
+ history = []
for index in range(backlog):
- sqlite.enqueue_run(
+ history.append(
{
"id": f"run-backlog-{index:05d}",
"request_type": "scheduled",
@@ -1216,6 +1266,8 @@ def test_the_predecessor_read_is_bounded_and_seeks_rather_than_scans(tmp_path: P
}
)
+ _seed_query_history(sqlite, history)
+
anchor_created = "2026-07-29T00:00:00+00:00"
now = "2026-07-29T00:05:00+00:00"
@@ -8545,12 +8597,13 @@ def _seed_streak_history(
"""
_task(sqlite_store, definition_id)
+ history = []
for index in range(total):
# Successes every seventh run, so the streak containing any given failure is
# at most six rows long while the lifetime is ``total``.
status = "succeeded" if ever_succeeded and index % 7 == 0 else "failed"
instant = f"2026-07-01T{index // 3600:02d}:{(index // 60) % 60:02d}:{index % 60:02d}+00:00"
- sqlite_store.enqueue_run(
+ history.append(
{
"id": f"run-{index:05d}",
"request_type": "scheduled",
@@ -8562,6 +8615,7 @@ def _seed_streak_history(
"metadata": {"owed_failure_notice": {"state": "pending", "attempts": 0}},
}
)
+ _seed_query_history(sqlite_store, history)
def test_the_streak_read_is_bounded_and_seeks_rather_than_scans(tmp_path: Path) -> None:
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 51dca55ce..f2934d992 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -2,6 +2,7 @@ from __future__ import annotations
from collections.abc import Iterable
from concurrent.futures import ThreadPoolExecutor
+from contextlib import closing
from importlib import import_module
import hashlib
import json
@@ -9,6 +10,7 @@ import re
import sqlite3
import threading
from pathlib import Path
+from types import MappingProxyType
import pytest
from alembic import command
@@ -863,6 +865,29 @@ def _upgraded_db(db_path: Path, revision: str) -> Path:
return db_path
[email protected](scope="module")
+def reference_schema(tmp_path_factory):
+ references = {}
+ root = tmp_path_factory.mktemp("migration-reference-schemas")
+
+ def schema(revision: str):
+ if revision not in references:
+ path = _upgraded_db(root / f"reference-{len(references)}.sqlite", revision)
+ references[revision] = frozenset(_schema_of(path))
+ return references[revision]
+
+ return schema
+
+
+def test_schema_reference_is_immutable_and_built_once(reference_schema):
+ reference = reference_schema("head")
+ assert isinstance(reference, frozenset)
+ assert reference_schema("head") is reference
+ assert reference
+ with pytest.raises(AttributeError):
+ reference.clear()
+
+
def _revisions_the_repair_must_cover() -> list[str]:
"""Every released revision a database can still be sitting on below the repair.
@@ -881,7 +906,7 @@ def _revisions_the_repair_must_cover() -> list[str]:
def test_repair_completes_a_replay_interrupted_between_two_branch_revisions(
- tmp_path: Path,
+ tmp_path: Path, reference_schema,
) -> None:
# Every branch table being present does not mean the branch was applied. A repair
# interrupted after 20260725_0038 recreated the table but before 20260815_0054
@@ -889,7 +914,7 @@ def test_repair_completes_a_replay_interrupted_between_two_branch_revisions(
# stamped below the repair. Skipping the replay on a table-presence check would
# stamp the repair over the short table, and a stamped revision never runs again:
# the columns would then be missing for the life of the database.
- expected = {obj for obj in _schema_of(_upgraded_db(tmp_path / "fresh.sqlite", "head")) if obj[1] == _INTERRUPTED_TABLE}
+ expected = {obj for obj in reference_schema("head") if obj[1] == _INTERRUPTED_TABLE}
assert expected, "the interrupted table must exist at head"
# Take the interrupted shape from the revision that creates it instead of writing
@@ -924,7 +949,7 @@ def test_repair_completes_a_replay_interrupted_between_two_branch_revisions(
]
-def test_repair_restores_branch_indexes_whose_tables_survived(tmp_path: Path) -> None:
+def test_repair_restores_branch_indexes_whose_tables_survived(tmp_path: Path, reference_schema) -> None:
# A table is not the unit of interruption; a schema object is. Each branch
# revision creates its table and then its index as two statements, so a run
# interrupted between them leaves the table present and the index missing --
@@ -934,9 +959,9 @@ def test_repair_restores_branch_indexes_whose_tables_survived(tmp_path: Path) ->
# never runs again. Derive the objects from the two sides of the merge rather
# than naming them, so an index added to the branch later is covered here
# without editing the test.
- reference = _schema_of(_upgraded_db(tmp_path / "fresh.sqlite", "head"))
- without_branch = _schema_of(_upgraded_db(tmp_path / "pre-merge.sqlite", "20260804_0046"))
- with_branch = _schema_of(_upgraded_db(tmp_path / "merged.sqlite", _SPLICED_MERGE_REVISION))
+ reference = reference_schema("head")
+ without_branch = reference_schema("20260804_0046")
+ with_branch = reference_schema(_SPLICED_MERGE_REVISION)
branch_names = {name for _, name, _ in with_branch} - {name for _, name, _ in without_branch}
branch_indexes = {name for kind, name, _ in with_branch if kind == "index"} & branch_names
assert branch_indexes, "the spliced branch must own at least one index"
@@ -1023,15 +1048,15 @@ def test_repair_refuses_to_stamp_a_schema_it_could_not_restore(tmp_path: Path) -
]
-def test_spliced_branch_schema_is_restored_from_every_released_revision(tmp_path: Path) -> None:
+def test_spliced_branch_schema_is_restored_from_every_released_revision(tmp_path: Path, reference_schema) -> None:
# The property: whatever released revision a database is on, upgrading to head
# leaves every schema object the spliced branch owns in the shape a fresh install
# has. Deriving that set from the two sides of the merge, instead of sharing a
# hand-written list with the migration, means a table added to the branch later
# cannot fall out of both at once.
- reference = _schema_of(_upgraded_db(tmp_path / "fresh.sqlite", "head"))
- without_branch = _schema_of(_upgraded_db(tmp_path / "pre-merge.sqlite", "20260804_0046"))
- with_branch = _schema_of(_upgraded_db(tmp_path / "merged.sqlite", _SPLICED_MERGE_REVISION))
+ reference = reference_schema("head")
+ without_branch = reference_schema("20260804_0046")
+ with_branch = reference_schema(_SPLICED_MERGE_REVISION)
# Compare by name: an object's recorded DDL text also varies with the rebuild
# path a table took, which says nothing about who created it.
@@ -3862,16 +3887,17 @@ def _head_shaped_unversioned_db(tmp_path: Path, name: str = "vibe.sqlite") -> Pa
return db_path
-def _reference_agent_runs_index_sql(tmp_path: Path) -> dict[str, str]:
[email protected](scope="module")
+def reference_agent_runs_index_sql(tmp_path_factory):
"""The three indexes as a full 0001-to-head replay writes them, byte for byte."""
- reference_db = tmp_path / "reference.sqlite"
+ reference_db = tmp_path_factory.mktemp("migration-index-reference") / "reference.sqlite"
run_migrations(reference_db)
- with sqlite3.connect(reference_db) as conn:
- return {name: _index_sql(conn, name) for name in _agent_runs_index_names()}
+ with closing(sqlite3.connect(reference_db)) as conn:
+ return MappingProxyType({name: _index_sql(conn, name) for name in _agent_runs_index_names()})
-def test_head_shaped_stamp_replays_agent_runs_expression_indexes(tmp_path: Path) -> None:
+def test_head_shaped_stamp_replays_agent_runs_expression_indexes(tmp_path: Path, reference_agent_runs_index_sql) -> None:
"""The migration ENTRYPOINT leaves a head-shaped database with the 0039-0042 indexes.
This test is GREEN FROM BIRTH — it is a refutation pin, not a fix; red-first does
@@ -3899,7 +3925,7 @@ def test_head_shaped_stamp_replays_agent_runs_expression_indexes(tmp_path: Path)
replayed_indexes = _agent_runs_index_names()
# Reference: an empty path replays 0001 -> head with no stamping shortcut at all.
- reference_sql = _reference_agent_runs_index_sql(tmp_path)
+ reference_sql = reference_agent_runs_index_sql
db_path = _head_shaped_unversioned_db(tmp_path)
_seed_settled_history(db_path)
@@ -3922,7 +3948,7 @@ def test_head_shaped_stamp_replays_agent_runs_expression_indexes(tmp_path: Path)
_assert_live_reads_seek_agent_runs_indexes(db_path, route="the migration entrypoint")
-def test_head_schema_repair_installs_agent_runs_expression_indexes(tmp_path: Path) -> None:
+def test_head_schema_repair_installs_agent_runs_expression_indexes(tmp_path: Path, reference_agent_runs_index_sql) -> None:
"""The head-schema REPAIR path installs the 0039-0042 indexes by itself.
``_ensure_head_indexes`` promises a head-shaped database every index head has, and
@@ -3946,7 +3972,7 @@ def test_head_schema_repair_installs_agent_runs_expression_indexes(tmp_path: Pat
"""
settled_index, owed_notice_index, streak_index = _agent_runs_index_names()
superseded = import_module(SUPERSEDED_OWED_NOTICE_MIGRATION_MODULE)
- reference_sql = _reference_agent_runs_index_sql(tmp_path)
+ reference_sql = reference_agent_runs_index_sql
db_path = _head_shaped_unversioned_db(tmp_path)
_seed_settled_history(db_path)
@@ -3987,10 +4013,10 @@ def test_head_schema_repair_installs_agent_runs_expression_indexes(tmp_path: Pat
_assert_live_reads_seek_agent_runs_indexes(db_path, route="the head-schema repair path")
-def test_background_store_repairs_indexes_on_an_already_ready_schema(tmp_path: Path) -> None:
+def test_background_store_repairs_indexes_on_an_already_ready_schema(tmp_path: Path, reference_agent_runs_index_sql) -> None:
"""Store construction reaches index repair even when no migration is needed."""
- reference_sql = _reference_agent_runs_index_sql(tmp_path)
+ reference_sql = reference_agent_runs_index_sql
db_path = _head_shaped_unversioned_db(tmp_path, "store-ready.sqlite")
assert background_tables_ready(db_path)