Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(cost-tracking): stop second cost engine from wedging `repowise update` on 'database is locked' (#326) (#330)
Raghav Chamadiyab55e3c5a66cd
diff --git a/packages/cli/src/repowise/cli/_repo_session.py b/packages/cli/src/repowise/cli/_repo_session.pyindex 1158e0c0d..af8983882 100644--- a/packages/cli/src/repowise/cli/_repo_session.py+++ b/packages/cli/src/repowise/cli/_repo_session.py@@ -16,12 +16,17 @@ async def open_repo_db(*,repo_name: str | None = None,init: bool = True,+ busy_timeout_ms: int | None = None,) -> tuple[Any, Any, str]:"""Open the repo-local database and ensure the repository row exists.Returns ``(engine, session_factory, repo_id)``. The engine is **not**disposed — the caller owns its lifetime (cost trackers keep it open for theduration of generation; persistence paths dispose it when done).++ ``busy_timeout_ms`` overrides the SQLite ``busy_timeout`` for this engine —+ used by best-effort secondary writers (the cost tracker) that must fail+ fast under contention rather than stall the primary writer (issue #326)."""from repowise.cli.helpers import get_db_url_for_repofrom repowise.core.persistence import (@@ -33,7 +38,7 @@ async def open_repo_db()url = get_db_url_for_repo(repo_path)- engine = create_engine(url)+ engine = create_engine(url, busy_timeout_ms=busy_timeout_ms)if init:await init_db(engine)sf = create_session_factory(engine)diff --git a/packages/cli/src/repowise/cli/commands/init_cmd.py b/packages/cli/src/repowise/cli/commands/init_cmd.pyindex ab3857074..106ae2bc8 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd.py@@ -40,6 +40,7 @@ from repowise.cli.providers import (build_cost_tracker,build_embedder,build_vector_store,+ flush_cost_tracker,resolve_embedder,)from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_json@@ -448,6 +449,11 @@ def _run_workspace_generation(except Exception:pass+ # Persist the buffered LLM cost rows in one transaction now that all LLM+ # work (generation + KG enrichment) is done — keeps cost writes out of the+ # contended generation window (issue #326).+ flush_cost_tracker(cost_tracker)+return generated_pages@@ -1261,6 +1267,11 @@ def _run_generation_phase(except Exception as _kg_enrich_err:console.print(f" [yellow]KG enrichment skipped: {_kg_enrich_err}[/yellow]")+ # Persist the buffered LLM cost rows in one transaction now that all LLM+ # work (generation + KG enrichment) is done — keeps cost writes out of+ # the contended generation window (issue #326).+ flush_cost_tracker(cost_tracker)+return False, cost_declineddiff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.pyindex ae353b380..11800f62d 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py@@ -606,6 +606,18 @@ def _render_update_report("re-parsing and re-resolving it. Single-repo only."),)+ "--no-cost-tracking",+ is_flag=True,+ default=False,+ help=(+ "Skip DB-backed LLM cost tracking for this run. Avoids opening a second "+ "engine on wiki.db, so cost writes can never contend with the "+ "generation writer. The live cost readout still works; only historical "+ "`repowise costs` rows are skipped. Also settable via the "+ "REPOWISE_NO_COST_TRACKING env var."+ ),+)def update_command(path: str | None,provider_name: str | None,@@ -621,6 +633,7 @@ def update_command(docs_flag: bool | None = None,full: bool = False,concurrency: int = 5,+ no_cost_tracking: bool = False,) -> None:"""Incrementally update wiki pages for files changed since last sync.@@ -858,7 +871,9 @@ def update_command(# all subsequent updates.from repowise.cli.providers import build_cost_tracker- cost_tracker = build_cost_tracker(repo_path, repo_path.name)+ cost_tracker = build_cost_tracker(+ repo_path, repo_path.name, no_cost_tracking=no_cost_tracking+ )provider._cost_tracker = cost_tracker# (dead_code_report computed above, before the index-only branch)@@ -1014,6 +1029,12 @@ def update_command())+ # Flush the buffered LLM cost rows now that generation is done — a single+ # transaction outside the contended generation window (issue #326).+ from repowise.cli.providers import flush_cost_tracker++ flush_cost_tracker(cost_tracker)+# Persistasync def _persist() -> None:from repowise.cli.helpers import get_db_url_for_repodiff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.pyindex 8b2ce0c18..bf5c7c88a 100644--- a/packages/cli/src/repowise/cli/commands/upgrade_flow.py+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py@@ -185,8 +185,17 @@ async def _run_upgrade("(graph reused from index — not re-resolved).")- # 5. Generate the docs the fast index skipped.- cost_tracker = CostTracker(session_factory=sf, repo_id=repo_id)+ # 5. Generate the docs the fast index skipped. Honor the cost-tracking+ # opt-out (issue #326) so REPOWISE_NO_COST_TRACKING is respected here too;+ # an in-memory tracker still powers the live cost readout.+ from repowise.cli.providers import cost_tracking_disabled++ if cost_tracking_disabled():+ cost_tracker = CostTracker()+ else:+ # buffered=True defers cost INSERTs to a single post-generation flush so+ # they never contend with the generation writer (issue #326).+ cost_tracker = CostTracker(session_factory=sf, repo_id=repo_id, buffered=True)provider._cost_tracker = cost_trackergenerated_pages = await run_generation(repo_path=repo_path,@@ -204,6 +213,9 @@ async def _run_upgrade(generation_config=config,)+ # Flush buffered cost rows now generation is done (best-effort).+ await cost_tracker.flush()+# 6. Persist pages + a GenerationJob marker, then build the FTS index.async with get_session(sf) as session:for page in generated_pages:diff --git a/packages/cli/src/repowise/cli/providers/__init__.py b/packages/cli/src/repowise/cli/providers/__init__.pyindex c985e5da6..b0ebd55f9 100644--- a/packages/cli/src/repowise/cli/providers/__init__.py+++ b/packages/cli/src/repowise/cli/providers/__init__.py@@ -7,7 +7,12 @@ command builds them the same way.from __future__ import annotations-from repowise.cli.providers.cost_tracking import build_cost_tracker, make_cost_tracker+from repowise.cli.providers.cost_tracking import (+ build_cost_tracker,+ cost_tracking_disabled,+ flush_cost_tracker,+ make_cost_tracker,+)from repowise.cli.providers.embedders import build_embedder, resolve_embedderfrom repowise.cli.providers.vector_store import build_vector_store@@ -15,6 +20,8 @@ __all__ = ["build_cost_tracker","build_embedder","build_vector_store",+ "cost_tracking_disabled",+ "flush_cost_tracker","make_cost_tracker","resolve_embedder",]diff --git a/packages/cli/src/repowise/cli/providers/cost_tracking.py b/packages/cli/src/repowise/cli/providers/cost_tracking.pyindex 7043e027f..f11f91317 100644--- a/packages/cli/src/repowise/cli/providers/cost_tracking.py+++ b/packages/cli/src/repowise/cli/providers/cost_tracking.py@@ -2,10 +2,39 @@from __future__ import annotations+import osfrom pathlib import Pathfrom repowise.core.generation.cost_tracker import CostTracker+# Env var that disables DB-backed cost tracking entirely (issue #326). When set+# to a truthy value, ``build_cost_tracker`` returns an in-memory tracker that+# never opens a second engine on ``wiki.db`` — so cost persistence can never+# contend with the generation writer. Mirrors the ``--no-cost-tracking`` flag.+NO_COST_TRACKING_ENV = "REPOWISE_NO_COST_TRACKING"++# Cost rows are best-effort telemetry, not part of the index. The DB-backed+# tracker opens a *second* engine on ``wiki.db``, so during generation its+# per-call ``INSERT INTO llm_costs`` loses WAL's single-writer race against the+# held page writer. With the normal 30s ``busy_timeout`` each contended insert+# stalls generation for the full window (issue #326). A short timeout makes the+# insert fail fast; ``CostTracker._persist`` swallows the error and drops the+# row, so a contended cost write costs at most this many ms instead of 30s.+_COST_TRACKER_BUSY_TIMEOUT_MS = 2000++_TRUTHY = {"1", "true", "yes", "on"}+++def cost_tracking_disabled(no_cost_tracking_flag: bool = False) -> bool:+ """Return whether DB-backed cost tracking should be skipped.++ Disabled when the ``--no-cost-tracking`` flag is passed *or* the+ ``REPOWISE_NO_COST_TRACKING`` env var is truthy.+ """+ if no_cost_tracking_flag:+ return True+ return os.environ.get(NO_COST_TRACKING_ENV, "").strip().lower() in _TRUTHY+async def make_cost_tracker(repo_path: Path, repo_name: str) -> CostTracker:"""Build a DB-backed :class:`CostTracker` for the repo-local database.@@ -14,18 +43,58 @@ async def make_cost_tracker(repo_path: Path, repo_name: str) -> CostTracker:this run is persisted to the ``llm_costs`` table. The engine isintentionally left open: it lives for the duration of generation and isdisposed later by the persistence path that reuses the same database.++ The engine uses a short ``busy_timeout`` so a cost insert that loses the+ write race against the generation writer fails fast and is dropped rather+ than stalling generation for the full 30s window (issue #326)."""from repowise.cli._repo_session import open_repo_db- _engine, sf, repo_id = await open_repo_db(repo_path, repo_name=repo_name)- return CostTracker(session_factory=sf, repo_id=repo_id)+ _engine, sf, repo_id = await open_repo_db(+ repo_path,+ repo_name=repo_name,+ busy_timeout_ms=_COST_TRACKER_BUSY_TIMEOUT_MS,+ )+ # buffered=True defers every per-call INSERT to a single ``flush()`` after+ # generation, so cost writes never contend with the generation writer+ # (issue #326). Call ``flush_cost_tracker`` once heavy DB work is done.+ return CostTracker(session_factory=sf, repo_id=repo_id, buffered=True)+++def build_cost_tracker(+ repo_path: Path,+ repo_name: str,+ *,+ no_cost_tracking: bool = False,+) -> CostTracker:+ """Construct a cost tracker, falling back to an in-memory one on failure.+ Returns an in-memory :class:`CostTracker` (no second engine, no DB writes)+ when cost tracking is disabled via the ``--no-cost-tracking`` flag or the+ ``REPOWISE_NO_COST_TRACKING`` env var. In-memory tracking still powers the+ live cost readout; only historical ``repowise costs`` rows are skipped.+ """+ if cost_tracking_disabled(no_cost_tracking):+ return CostTracker()-def build_cost_tracker(repo_path: Path, repo_name: str) -> CostTracker:- """Construct a cost tracker, falling back to an in-memory one on failure."""from repowise.cli.helpers import run_asynctry:return run_async(make_cost_tracker(repo_path, repo_name))except Exception:return CostTracker()+++def flush_cost_tracker(cost_tracker: CostTracker) -> int:+ """Persist any buffered cost rows from a synchronous CLI context.++ Call once generation (and any other LLM work) is done. Best-effort — never+ raises into the caller; a contended or failed flush drops the rows. Returns+ the number of rows persisted (0 for in-memory / disabled trackers).+ """+ from repowise.cli.helpers import run_async++ try:+ return run_async(cost_tracker.flush())+ except Exception:+ return 0diff --git a/packages/core/src/repowise/core/generation/cost_tracker.py b/packages/core/src/repowise/core/generation/cost_tracker.pyindex 234df4e63..189287609 100644--- a/packages/core/src/repowise/core/generation/cost_tracker.py+++ b/packages/core/src/repowise/core/generation/cost_tracker.py@@ -75,17 +75,31 @@ class CostTracker:tracking is performed.repo_id:Repository primary key to associate with persisted rows.+ buffered:+ When ``True``, ``record()`` accumulates rows in memory instead of+ writing each one immediately; the caller persists them in a single+ transaction via :meth:`flush` once heavy DB work is done. This keeps+ cost writes out of the doc-generation window, where a per-call+ ``INSERT`` opened on a *second* engine loses WAL's single-writer race+ against the generation writer and stalls for the full ``busy_timeout``+ (issue #326). Defaults to ``False`` so existing callers that rely on+ immediate persistence are unaffected; the CLI opts in."""def __init__(self,session_factory: Any | None = None,repo_id: str | None = None,+ *,+ buffered: bool = False,) -> None:self._session_factory = session_factoryself._repo_id = repo_idself._session_cost: float = 0.0self._session_tokens: int = 0+ self._buffered = buffered+ # Pending rows when buffered; flushed in one transaction by ``flush``.+ self._pending: list[dict[str, Any]] = []# ------------------------------------------------------------------# Properties@@ -151,46 +165,70 @@ class CostTracker:)if self._session_factory is not None and self._repo_id is not None:- await self._persist(- model=model,- input_tokens=input_tokens,- output_tokens=output_tokens,- cost_usd=cost,- operation=operation,- file_path=file_path,- )+ row = {+ "model": model,+ "operation": operation,+ "input_tokens": input_tokens,+ "output_tokens": output_tokens,+ "cost_usd": cost,+ "file_path": file_path,+ }+ if self._buffered:+ # Defer the write — flushed in one transaction later, outside the+ # contended generation window (issue #326).+ self._pending.append(row)+ else:+ await self._persist_rows([row])return cost- async def _persist(- self,- *,- model: str,- input_tokens: int,- output_tokens: int,- cost_usd: float,- operation: str,- file_path: str | None,- ) -> None:- """Write a row to the ``llm_costs`` table."""+ async def flush(self) -> int:+ """Persist any buffered cost rows in a single transaction.++ Best-effort: a contended or failed flush drops the buffered rows (cost+ telemetry is non-critical) rather than raising into the caller. Safe to+ call on an in-memory or non-buffered tracker — it is then a no-op.+ Returns the number of rows persisted.+ """+ if not self._pending:+ return 0+ rows = self._pending+ self._pending = []+ return await self._persist_rows(rows)++ async def _persist_rows(self, rows: list[dict[str, Any]]) -> int:+ """Write *rows* to the ``llm_costs`` table. Best-effort.++ Returns the number of rows written (0 if the write was dropped on+ contention or error). A single transaction is used so a buffered flush+ of hundreds of rows takes one write-lock acquisition, not one per row.+ """+ if self._session_factory is None or self._repo_id is None or not rows:+ return 0try:- from repowise.core.persistence.models import LlmCostfrom repowise.core.persistence import get_session+ from repowise.core.persistence.models import LlmCostasync with get_session(self._session_factory) as session:- row = LlmCost(- repository_id=self._repo_id,- model=model,- operation=operation,- input_tokens=input_tokens,- output_tokens=output_tokens,- cost_usd=cost_usd,- file_path=file_path,+ session.add_all(+ [+ LlmCost(+ repository_id=self._repo_id,+ model=r["model"],+ operation=r["operation"],+ input_tokens=r["input_tokens"],+ output_tokens=r["output_tokens"],+ cost_usd=r["cost_usd"],+ file_path=r["file_path"],+ )+ for r in rows+ ])- session.add(row)await session.commit()+ return len(rows)except Exception as exc:- log.warning("cost_tracker.persist_failed", error=str(exc))+ log.warning("cost_tracker.persist_failed", error=str(exc), dropped=len(rows))+ return 0# ------------------------------------------------------------------# Querying@@ -221,8 +259,9 @@ class CostTracker:try:import sqlalchemy as sa- from repowise.core.persistence.models import LlmCost+from repowise.core.persistence import get_session+ from repowise.core.persistence.models import LlmCostasync with get_session(self._session_factory) as session:if group_by == "model":diff --git a/packages/core/src/repowise/core/persistence/database.py b/packages/core/src/repowise/core/persistence/database.pyindex fd0d260d6..309ab40fe 100644--- a/packages/core/src/repowise/core/persistence/database.py+++ b/packages/core/src/repowise/core/persistence/database.py@@ -40,32 +40,48 @@ from .models import Base# for large repos. SQLite blocks (doesn't busy-loop) so this is cheap._SQLITE_BUSY_TIMEOUT_MS = 30000-_SQLITE_PRAGMAS: tuple[tuple[str, str], ...] = (- ("journal_mode", "WAL"),- ("synchronous", "NORMAL"),- ("busy_timeout", str(_SQLITE_BUSY_TIMEOUT_MS)),- ("foreign_keys", "ON"),-)+def _sqlite_pragmas(busy_timeout_ms: int) -> tuple[tuple[str, str], ...]:+ """Return the pragma list to apply to a SQLite connection."""+ return (+ ("journal_mode", "WAL"),+ ("synchronous", "NORMAL"),+ ("busy_timeout", str(busy_timeout_ms)),+ ("foreign_keys", "ON"),+ )+++def _make_pragma_listener(busy_timeout_ms: int):+ """Build a ``connect`` event listener that applies our SQLite pragmas.++ The listener is a closure so the ``busy_timeout`` can be tuned per engine.+ Most engines use the default 30s headroom (needed for bulk graph-edge+ writes), but short-lived best-effort writers — e.g. the cost tracker's+ secondary engine — pass a small timeout so a contended write fails fast and+ is dropped instead of stalling the primary writer for the full window+ (issue #326).+ """-def _apply_sqlite_pragmas(dbapi_connection: object, _connection_record: object) -> None:- """Apply WAL, busy_timeout, and FK pragmas on every new SQLite connection.+ def _apply_sqlite_pragmas(dbapi_connection: object, _connection_record: object) -> None:+ """Apply WAL, busy_timeout, and FK pragmas on every new SQLite connection.++ Registered as a ``connect`` event listener so it runs once per physical+ connection, including the first one opened after the engine is created and+ every reconnect afterward. WAL is a database-level setting that persists in+ the file, but we re-issue it defensively in case the file was created by an+ older repowise version, by ``alembic``, or by a third-party tool that left+ journal_mode at the default ``delete``.+ """+ cursor = dbapi_connection.cursor() # type: ignore[attr-defined]+ try:+ for name, value in _sqlite_pragmas(busy_timeout_ms):+ # journal_mode returns the new mode and must be queried, not assigned,+ # because in :memory: databases it silently downgrades to MEMORY.+ cursor.execute(f"PRAGMA {name}={value}")+ finally:+ cursor.close()- Registered as a ``connect`` event listener so it runs once per physical- connection, including the first one opened after the engine is created and- every reconnect afterward. WAL is a database-level setting that persists in- the file, but we re-issue it defensively in case the file was created by an- older repowise version, by ``alembic``, or by a third-party tool that left- journal_mode at the default ``delete``.- """- cursor = dbapi_connection.cursor() # type: ignore[attr-defined]- try:- for name, value in _SQLITE_PRAGMAS:- # journal_mode returns the new mode and must be queried, not assigned,- # because in :memory: databases it silently downgrades to MEMORY.- cursor.execute(f"PRAGMA {name}={value}")- finally:- cursor.close()+ return _apply_sqlite_pragmas__all__ = [@@ -159,6 +175,7 @@ def create_engine(# StaticPool is required for :memory: SQLite so all connections share the same DB.# Pass use_static_pool=True explicitly when creating in-memory test engines.use_static_pool: bool = False,+ busy_timeout_ms: int | None = None,) -> AsyncEngine:"""Create an AsyncEngine for the given database URL.@@ -166,6 +183,11 @@ def create_engine(url: Raw or async-prefixed database URL. Defaults to SQLite.echo: Log all SQL statements (useful for debugging).use_static_pool: Force StaticPool (required for in-memory SQLite tests).+ busy_timeout_ms: Override the SQLite ``busy_timeout`` (milliseconds) for+ connections from this engine. Defaults to 30s. Pass a+ small value for best-effort secondary writers that must+ never stall the primary writer (issue #326). Ignored+ for non-SQLite backends."""db_url = get_db_url(url)is_sqlite = db_url.startswith("sqlite")@@ -189,7 +211,8 @@ def create_engine(if is_sqlite:# The ``connect`` event fires for the underlying DBAPI connection, so we# listen on the sync engine that backs the AsyncEngine.- event.listen(engine.sync_engine, "connect", _apply_sqlite_pragmas)+ timeout = busy_timeout_ms if busy_timeout_ms is not None else _SQLITE_BUSY_TIMEOUT_MS+ event.listen(engine.sync_engine, "connect", _make_pragma_listener(timeout))return enginediff --git a/tests/unit/cli/test_cost_tracking_optout.py b/tests/unit/cli/test_cost_tracking_optout.pynew file mode 100644index 000000000..01c71c60f--- /dev/null+++ b/tests/unit/cli/test_cost_tracking_optout.py@@ -0,0 +1,330 @@+"""Tests for the cost-tracking opt-out and best-effort persistence (issue #326).++DB-backed cost tracking opens a *second* SQLAlchemy engine on ``wiki.db``. During+doc generation a writer is held on that file, so each per-call+``INSERT INTO llm_costs`` loses WAL's single-writer race and — with the default+30s ``busy_timeout`` — stalls generation for the full window. These tests cover+the two guards that fix that:++ 1. ``--no-cost-tracking`` / ``REPOWISE_NO_COST_TRACKING`` skip the second+ engine entirely, returning an in-memory tracker.+ 2. When tracking *is* enabled, the CLI tracker is *buffered*: per-call rows are+ held in memory and flushed in one transaction after generation, so cost+ writes never land inside the contended generation window. A short+ ``busy_timeout`` bounds the one flush as a last-resort defense.+"""++from __future__ import annotations++import sqlite3+import time+from pathlib import Path++import pytest++from repowise.cli.providers.cost_tracking import (+ _COST_TRACKER_BUSY_TIMEOUT_MS,+ NO_COST_TRACKING_ENV,+ build_cost_tracker,+ cost_tracking_disabled,+)+from repowise.core.generation.cost_tracker import CostTracker+++class TestCostTrackingDisabled:+ def test_flag_disables(self):+ assert cost_tracking_disabled(no_cost_tracking_flag=True) is True++ def test_default_enabled(self, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.delenv(NO_COST_TRACKING_ENV, raising=False)+ assert cost_tracking_disabled() is False++ @pytest.mark.parametrize("value", ["1", "true", "TRUE", "yes", "on", " On "])+ def test_env_truthy_disables(self, monkeypatch: pytest.MonkeyPatch, value: str):+ monkeypatch.setenv(NO_COST_TRACKING_ENV, value)+ assert cost_tracking_disabled() is True++ @pytest.mark.parametrize("value", ["0", "false", "no", "off", "", " "])+ def test_env_falsy_keeps_enabled(self, monkeypatch: pytest.MonkeyPatch, value: str):+ monkeypatch.setenv(NO_COST_TRACKING_ENV, value)+ assert cost_tracking_disabled() is False+++class TestBuildCostTracker:+ def test_flag_returns_in_memory_tracker(self, tmp_path: Path):+ # Disabled → no second engine is opened, so the tracker has no+ # session_factory (in-memory only).+ tracker = build_cost_tracker(tmp_path, "repo", no_cost_tracking=True)+ assert isinstance(tracker, CostTracker)+ assert tracker._session_factory is None+ assert tracker._repo_id is None++ def test_env_returns_in_memory_tracker(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv(NO_COST_TRACKING_ENV, "1")+ tracker = build_cost_tracker(tmp_path, "repo")+ assert tracker._session_factory is None++ def test_disabled_build_opens_no_engine(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ # When disabled we must never touch open_repo_db / create_engine.+ import repowise.cli.providers.cost_tracking as ct++ def _boom(*args, **kwargs): # pragma: no cover - must not be called+ raise AssertionError("open_repo_db must not be called when disabled")++ monkeypatch.setattr(ct, "make_cost_tracker", _boom)+ tracker = build_cost_tracker(tmp_path, "repo", no_cost_tracking=True)+ assert tracker._session_factory is None+++class TestEnabledTrackerUsesShortBusyTimeout:+ def test_short_busy_timeout_is_small(self):+ # Must be well under the 30s default so a contended cost insert can't+ # stall the generation writer for the full window.+ assert _COST_TRACKER_BUSY_TIMEOUT_MS < 30000+ assert _COST_TRACKER_BUSY_TIMEOUT_MS > 0++ @pytest.mark.asyncio+ async def test_make_cost_tracker_applies_short_timeout(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ):+ # make_cost_tracker must thread the short busy_timeout into open_repo_db.+ import repowise.cli.providers.cost_tracking as ct++ captured: dict = {}++ async def _fake_open_repo_db(repo_path, *, repo_name=None, busy_timeout_ms=None):+ captured["busy_timeout_ms"] = busy_timeout_ms+ return (object(), object(), "repo-id")++ import repowise.cli._repo_session as session_mod++ monkeypatch.setattr(session_mod, "open_repo_db", _fake_open_repo_db)+ tracker = await ct.make_cost_tracker(tmp_path, "repo")+ assert captured["busy_timeout_ms"] == _COST_TRACKER_BUSY_TIMEOUT_MS+ assert tracker._repo_id == "repo-id"+++class TestContendedPersistIsBestEffort:+ @pytest.mark.asyncio+ async def test_record_drops_row_under_held_write_lock(self, tmp_path: Path) -> None:+ """With a competing writer holding the write lock, a DB-backed+ ``record()`` must still return without raising (the contended insert is+ dropped) and bound its wait to the short cost busy_timeout — never the+ 30s default that wedged generation in issue #326."""+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )++ db_path = tmp_path / ".repowise" / "wiki.db"+ db_path.parent.mkdir(parents=True, exist_ok=True)+ db_url = f"sqlite+aiosqlite:///{db_path.as_posix()}"++ # Short busy_timeout so the test stays fast while still proving the+ # fail-fast behavior.+ short_timeout_ms = 400+ engine = create_engine(db_url, busy_timeout_ms=short_timeout_ms)+ await init_db(engine)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo = await upsert_repository(session, name="repo", local_path=str(tmp_path))+ repo_id = repo.id++ tracker = CostTracker(session_factory=sf, repo_id=repo_id)++ # Hold the write lock on a separate raw connection.+ blocker = sqlite3.connect(db_path)+ blocker.execute("PRAGMA busy_timeout=0")+ blocker.execute("BEGIN IMMEDIATE")+ try:+ started = time.monotonic()+ # Must NOT raise even though the insert can't acquire the lock.+ cost = await tracker.record(+ model="deepseek-v4-flash",+ input_tokens=100,+ output_tokens=50,+ operation="doc_generation",+ )+ elapsed = time.monotonic() - started+ finally:+ blocker.rollback()+ blocker.close()++ # In-memory accounting still happened.+ assert cost > 0+ assert tracker.session_tokens == 150+ # Bounded by the short cost timeout, nowhere near the 30s default.+ assert elapsed < 5.0++ # The contended row was dropped, not persisted.+ async with get_session(sf) as session:+ import sqlalchemy as sa++ count = (await session.execute(sa.text("SELECT COUNT(*) FROM llm_costs"))).scalar()+ assert count == 0++ await engine.dispose()++ @pytest.mark.asyncio+ async def test_record_persists_when_uncontended(self, tmp_path: Path) -> None:+ """Sanity check: without contention the row IS written, so the live+ ``repowise costs`` history keeps working when tracking is enabled."""+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )++ db_path = tmp_path / ".repowise" / "wiki.db"+ db_path.parent.mkdir(parents=True, exist_ok=True)+ db_url = f"sqlite+aiosqlite:///{db_path.as_posix()}"+ engine = create_engine(db_url, busy_timeout_ms=_COST_TRACKER_BUSY_TIMEOUT_MS)+ await init_db(engine)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo = await upsert_repository(session, name="repo", local_path=str(tmp_path))+ repo_id = repo.id++ tracker = CostTracker(session_factory=sf, repo_id=repo_id)+ await tracker.record(+ model="deepseek-v4-flash",+ input_tokens=100,+ output_tokens=50,+ operation="doc_generation",+ )++ async with get_session(sf) as session:+ import sqlalchemy as sa++ count = (await session.execute(sa.text("SELECT COUNT(*) FROM llm_costs"))).scalar()+ assert count == 1++ await engine.dispose()+++async def _open_repo_engine(tmp_path: Path):+ """Open an initialised repo DB and return (engine, session_factory, repo_id, db_path)."""+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )++ db_path = tmp_path / ".repowise" / "wiki.db"+ db_path.parent.mkdir(parents=True, exist_ok=True)+ db_url = f"sqlite+aiosqlite:///{db_path.as_posix()}"+ engine = create_engine(db_url, busy_timeout_ms=_COST_TRACKER_BUSY_TIMEOUT_MS)+ await init_db(engine)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo = await upsert_repository(session, name="repo", local_path=str(tmp_path))+ repo_id = repo.id+ return engine, sf, repo_id, db_path+++async def _count_cost_rows(sf) -> int:+ import sqlalchemy as sa++ from repowise.core.persistence import get_session++ async with get_session(sf) as session:+ return (await session.execute(sa.text("SELECT COUNT(*) FROM llm_costs"))).scalar()+++class TestBufferedTrackerDefersWrites:+ @pytest.mark.asyncio+ async def test_record_writes_nothing_until_flush(self, tmp_path: Path) -> None:+ """The whole point of the fix: a buffered ``record()`` performs NO DB+ write, so nothing can contend with the generation writer. Rows only+ land on ``flush()`` — in a single transaction."""+ engine, sf, repo_id, _ = await _open_repo_engine(tmp_path)+ tracker = CostTracker(session_factory=sf, repo_id=repo_id, buffered=True)++ for _ in range(5):+ await tracker.record(+ model="deepseek-v4-flash",+ input_tokens=100,+ output_tokens=50,+ operation="doc_generation",+ )++ # Nothing written yet — all five rows are buffered in memory.+ assert await _count_cost_rows(sf) == 0+ assert tracker.session_tokens == 5 * 150 # live accounting still works++ written = await tracker.flush()+ assert written == 5+ assert await _count_cost_rows(sf) == 5++ # Flush is idempotent — buffer is drained.+ assert await tracker.flush() == 0+ assert await _count_cost_rows(sf) == 5++ await engine.dispose()++ @pytest.mark.asyncio+ async def test_buffered_flush_succeeds_after_writer_releases(self, tmp_path: Path) -> None:+ """Even if a writer is held for the *entire* generation window, buffered+ records accumulate with zero contention and the post-generation flush+ (run after the writer releases) persists every row."""+ engine, sf, repo_id, db_path = await _open_repo_engine(tmp_path)+ tracker = CostTracker(session_factory=sf, repo_id=repo_id, buffered=True)++ blocker = sqlite3.connect(db_path)+ blocker.execute("BEGIN IMMEDIATE") # hold the write lock during "generation"+ try:+ for _ in range(3):+ # Must not block or raise — buffered records never touch the DB.+ await tracker.record(+ model="deepseek-v4-flash",+ input_tokens=10,+ output_tokens=10,+ operation="doc_generation",+ )+ assert await _count_cost_rows(sf) == 0+ finally:+ blocker.rollback() # generation done → writer released+ blocker.close()++ assert await tracker.flush() == 3+ assert await _count_cost_rows(sf) == 3+ await engine.dispose()++ @pytest.mark.asyncio+ async def test_flush_is_noop_for_in_memory_tracker(self) -> None:+ tracker = CostTracker() # no session_factory+ await tracker.record(+ model="deepseek-v4-flash",+ input_tokens=10,+ output_tokens=10,+ operation="doc_generation",+ )+ assert await tracker.flush() == 0++ def test_flush_cost_tracker_helper_drives_flush(self, tmp_path: Path) -> None:+ """The sync ``flush_cost_tracker`` helper persists buffered rows from+ Click's synchronous context and never raises."""+ import asyncio++ from repowise.cli.providers import flush_cost_tracker++ engine, sf, repo_id, _ = asyncio.run(_open_repo_engine(tmp_path))+ tracker = CostTracker(session_factory=sf, repo_id=repo_id, buffered=True)+ asyncio.run(+ tracker.record(+ model="deepseek-v4-flash",+ input_tokens=10,+ output_tokens=10,+ operation="doc_generation",+ )+ )+ assert flush_cost_tracker(tracker) == 1+ assert asyncio.run(_count_cost_rows(sf)) == 1+ asyncio.run(engine.dispose())diff --git a/tests/unit/persistence/test_database_pragmas.py b/tests/unit/persistence/test_database_pragmas.pyindex 839f5b46e..57a7cf279 100644--- a/tests/unit/persistence/test_database_pragmas.py+++ b/tests/unit/persistence/test_database_pragmas.py@@ -46,6 +46,35 @@ async def test_file_sqlite_engine_sets_busy_timeout(tmp_path: Path) -> None:await engine.dispose()+async def test_busy_timeout_override_is_applied(tmp_path: Path) -> None:+ """A custom ``busy_timeout_ms`` must reach the connection pragma so the+ cost tracker's best-effort engine fails fast under contention instead of+ blocking the full 30s default window (issue #326)."""+ db_url = f"sqlite+aiosqlite:///{tmp_path / 'wiki.db'}"+ engine = create_engine(db_url, busy_timeout_ms=2000)+ try:+ await init_db(engine)+ timeout = await _read_pragma(engine, "busy_timeout")+ assert int(timeout) == 2000+ finally:+ await engine.dispose()+++async def test_default_busy_timeout_unchanged(tmp_path: Path) -> None:+ """Without an override the engine keeps the 30s default — the headroom that+ legitimate bulk graph-edge writes rely on."""+ db_url = f"sqlite+aiosqlite:///{tmp_path / 'wiki.db'}"+ engine = create_engine(db_url)+ try:+ await init_db(engine)+ timeout = await _read_pragma(engine, "busy_timeout")+ assert int(timeout) == 30000+ finally:+ await engine.dispose()++@pytest.mark.asyncioasync def test_file_sqlite_engine_enforces_foreign_keys(tmp_path: Path) -> None:db_url = f"sqlite+aiosqlite:///{tmp_path / 'wiki.db'}"@@ -71,7 +100,9 @@ async def test_concurrent_writers_do_not_lock(tmp_path: Path) -> None:await init_db(engine)# Seed one row so the second writer has something to update.async with engine.begin() as conn:- await conn.execute(text("CREATE TABLE IF NOT EXISTS t (k INTEGER PRIMARY KEY, v INTEGER)"))+ await conn.execute(+ text("CREATE TABLE IF NOT EXISTS t (k INTEGER PRIMARY KEY, v INTEGER)")+ )await conn.execute(text("INSERT INTO t (k, v) VALUES (1, 0)"))finally:await engine.dispose()