Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(cli): dispose the cost-tracker engine so a later loop doesn't reuse a dead connection (#2083)

Amir Fathi86f12ec07461
diff --git a/packages/cli/src/repowise/cli/providers/cost_tracking.py b/packages/cli/src/repowise/cli/providers/cost_tracking.py
index f11f91317..3f75579f9 100644
--- a/packages/cli/src/repowise/cli/providers/cost_tracking.py
+++ b/packages/cli/src/repowise/cli/providers/cost_tracking.py
@@ -40,9 +40,13 @@ async def make_cost_tracker(repo_path: Path, repo_name: str) -> CostTracker:
"""Build a DB-backed :class:`CostTracker` for the repo-local database.
Resolves (or creates) the repository row so every LLM call made during
- this run is persisted to the ``llm_costs`` table. The engine is
- intentionally left open: it lives for the duration of generation and is
- disposed later by the persistence path that reuses the same database.
+ this run is persisted to the ``llm_costs`` table.
+
+ The engine is disposed before returning: this coroutine and ``flush()``
+ each run inside their own ``asyncio.run()``, and a connection left pooled
+ here would be bound to a dead loop by the time ``flush`` runs in a later
+ one. Disposing clears the pool, not ``sf``, so the next checkout opens a
+ fresh connection there instead (issue #2062).
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
@@ -50,14 +54,15 @@ async def make_cost_tracker(repo_path: Path, repo_name: str) -> CostTracker:
"""
from repowise.cli._repo_session import open_repo_db
- _engine, sf, repo_id = await open_repo_db(
+ 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.
+ await engine.dispose()
+ # buffered=True avoids write contention (issue #326) and, just as load
+ # bearing now, keeps the pool empty so nothing refills it before flush
+ # runs and reintroduces the cross-loop reuse from issue #2062.
return CostTracker(session_factory=sf, repo_id=repo_id, buffered=True)
diff --git a/tests/integration/test_cost_tracker_cross_loop_engine.py b/tests/integration/test_cost_tracker_cross_loop_engine.py
new file mode 100644
index 000000000..b7fb70fe7
--- /dev/null
+++ b/tests/integration/test_cost_tracker_cross_loop_engine.py
@@ -0,0 +1,86 @@
+"""PostgreSQL regression for issue #2062: the cost tracker's engine does not
+survive the ``asyncio.run()`` boundary it is built in, but ``run_repo_generation``
+opens it, generates, and flushes across three separate ``asyncio.run()`` calls.
+
+SQLite's ``NullPool`` never holds a live connection between checkouts, so this
+only shows up against a real Postgres pool.
+
+Skipped unless a PostgreSQL URL is configured::
+
+ REPOWISE_TEST_PG_URL=postgresql+asyncpg://user@localhost:5432/repowise_test \\
+ uv run pytest tests/integration/test_cost_tracker_cross_loop_engine.py
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+
+import pytest
+import sqlalchemy as sa
+from sqlalchemy.ext.asyncio import create_async_engine
+
+from repowise.core.persistence.models import Base
+
+PG_URL = os.environ.get("REPOWISE_TEST_PG_URL")
+
+pytestmark = pytest.mark.skipif(
+ not PG_URL, reason="REPOWISE_TEST_PG_URL not set: PostgreSQL-only regression"
+)
+
+
+def pg_repo(tmp_path, monkeypatch):
+ # Same refusal as test_postgres_symbol_lengths.py's pg_session: this
+ # fixture drops every table, so it insists on a scratch-named database.
+ database = (PG_URL or "").rsplit("/", 1)[-1].split("?")[0]
+ if "test" not in database and "scratch" not in database:
+ pytest.skip(f"refusing to drop tables in {database!r}: name it *test* or *scratch*")
+
+ async def _reset() -> None:
+ engine = create_async_engine(PG_URL or "", poolclass=None)
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.drop_all)
+ await engine.dispose()
+
+ asyncio.run(_reset())
+ monkeypatch.setenv("REPOWISE_DB_URL", PG_URL or "")
+ return tmp_path
+
+
+def test_flush_persists_rows_recorded_after_a_separate_build_loop(pg_repo) -> None:
+ """Exercises the real sequence ``run_repo_generation`` uses: ``build_cost_tracker``
+ (asyncio.run #1, opens the engine), a buffered ``record()`` call standing in for
+ generation (asyncio.run #2), then ``flush_cost_tracker`` (asyncio.run #3). Fails on
+ main: the pooled asyncpg connection ``build_cost_tracker`` opened dies with its
+ event loop, and the flush silently drops the row instead of raising."""
+ from repowise.cli.providers.cost_tracking import build_cost_tracker, flush_cost_tracker
+
+ tracker = build_cost_tracker(pg_repo, "repo")
+ assert tracker._session_factory is not None # sanity: a real Postgres engine was built
+
+ asyncio.run(
+ tracker.record(
+ model="claude-sonnet-5",
+ input_tokens=100,
+ output_tokens=50,
+ operation="doc_generation",
+ )
+ )
+
+ written = flush_cost_tracker(tracker)
+ assert written == 1
+
+ # A fresh engine/connection, deliberately not `tracker._session_factory`:
+ # reusing the tracker's engine here would be a fourth asyncio.run() reusing
+ # a connection flush's third one pooled, which is the same cross-loop
+ # pattern the fix addresses, not a check on it.
+ async def _count() -> int:
+ engine = create_async_engine(PG_URL or "", poolclass=None)
+ try:
+ async with engine.connect() as conn:
+ return (await conn.execute(sa.text("SELECT COUNT(*) FROM llm_costs"))).scalar()
+ finally:
+ await engine.dispose()
+
+ assert asyncio.run(_count()) == 1
diff --git a/tests/unit/cli/test_cost_tracking_optout.py b/tests/unit/cli/test_cost_tracking_optout.py
index 01c71c60f..844c73c80 100644
--- a/tests/unit/cli/test_cost_tracking_optout.py
+++ b/tests/unit/cli/test_cost_tracking_optout.py
@@ -92,9 +92,13 @@ class TestEnabledTrackerUsesShortBusyTimeout:
captured: dict = {}
+ class _FakeEngine:
+ async def dispose(self) -> None:
+ pass
+
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")
+ return (_FakeEngine(), object(), "repo-id")
import repowise.cli._repo_session as session_mod