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(server): resolve primary vector store for postgresql databases (#2140) (#2144)
Rishabh Mishra8a59a3fef2ca
diff --git a/packages/server/src/repowise/server/search_helpers.py b/packages/server/src/repowise/server/search_helpers.pyindex 24dbdb153..5bcedfe0c 100644--- a/packages/server/src/repowise/server/search_helpers.py+++ b/packages/server/src/repowise/server/search_helpers.py@@ -53,13 +53,18 @@ def _build_repo_vector_store(repo_path: Path, embedder: Any, *, create: bool) ->async def build_primary_vector_store(- session_factory, db_url: str, embedder: Any+ session_factory,+ db_url: str,+ embedder: Any,+ *,+ create: bool = False,) -> tuple[Any, str | None]:"""Build the primary repo's durable vector store when it can be identified.A repo-local SQLite database normally contains one repository row. For ashared registry database, only a row whose ``wiki.db`` matches ``db_url`` is- treated as primary. The returned repo id lets startup seed the per-repo+ treated as primary. Identifies the primary repo by checking ``db_url``,+ workspace configuration, current working directory, or single-row fallback.cache so jobs and searches reuse the same connection."""from sqlalchemy import select@@ -83,12 +88,40 @@ async def build_primary_vector_store(if local_db in normalized_url:selected = (repo_id, local_path)break++ if selected is None:+ try:+ from repowise.core.workspace.config import WorkspaceConfig, find_workspace_root++ ws_root = find_workspace_root()+ if ws_root is not None:+ ws_config = WorkspaceConfig.load(ws_root)+ primary_entry = ws_config.get_primary()+ if primary_entry is not None:+ primary_path = (ws_root / primary_entry.path).resolve()+ for repo_id, local_path in rows:+ if Path(local_path).resolve() == primary_path:+ selected = (repo_id, local_path)+ break+ except Exception:+ logger.debug("workspace_config_primary_lookup_failed", exc_info=True)++ if selected is None:+ try:+ cwd = Path.cwd().resolve()+ for repo_id, local_path in rows:+ if Path(local_path).resolve() == cwd:+ selected = (repo_id, local_path)+ break+ except Exception:+ logger.debug("cwd_primary_lookup_failed", exc_info=True)+if selected is None and len(rows) == 1:selected = rows[0]if selected is not None:repo_id, local_path = selected- store = _build_repo_vector_store(Path(local_path).resolve(), embedder, create=True)+ store = _build_repo_vector_store(Path(local_path).resolve(), embedder, create=create)if store is not None:logger.info("primary_vector_store_loaded",diff --git a/tests/unit/server/test_search_persistence.py b/tests/unit/server/test_search_persistence.pyindex ba781f48e..7ceeba2ce 100644--- a/tests/unit/server/test_search_persistence.py+++ b/tests/unit/server/test_search_persistence.py@@ -10,6 +10,7 @@ from repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.vector_store import LanceDBVectorStorefrom repowise.core.providers.embedding.base import MockEmbedder+from repowise.core.workspace.config import RepoEntry, WorkspaceConfigfrom repowise.server.search_helpers import (build_primary_vector_store,resolve_repo_vector_store,@@ -107,3 +108,225 @@ async def test_repo_vector_stores_are_isolated(tmp_path) -> None:finally:await store_a.close()await store_b.close()+++async def test_build_primary_vector_store_postgres_multiple_repos_workspace_config(+ session_factory,+ tmp_path,+ monkeypatch,+) -> None:+ """PostgreSQL URL with multiple repos should resolve primary from workspace config."""+ ws_root = tmp_path / "workspace"+ ws_root.mkdir()+ repo_a = ws_root / "services" / "primary-svc"+ repo_b = ws_root / "services" / "secondary-svc"+ (repo_a / ".repowise" / "lancedb").mkdir(parents=True)+ (repo_b / ".repowise" / "lancedb").mkdir(parents=True)++ ws_config = WorkspaceConfig(+ default_repo="primary",+ repos=[+ RepoEntry(path="services/primary-svc", alias="primary", is_primary=True),+ RepoEntry(path="services/secondary-svc", alias="secondary"),+ ],+ )+ ws_config.save(ws_root)++ async with get_session(session_factory) as session:+ await crud.upsert_repository(+ session,+ name="secondary-svc",+ local_path=str(repo_b),+ )+ r_a = await crud.upsert_repository(+ session,+ name="primary-svc",+ local_path=str(repo_a),+ )++ embedder = MockEmbedder()+ lance_store = LanceDBVectorStore(str(repo_a / ".repowise" / "lancedb"), embedder=embedder)+ await lance_store.embed_and_upsert("p1", "content", {"title": "P1"})+ await lance_store.close()++ monkeypatch.chdir(ws_root)+ postgres_url = "postgresql+asyncpg://postgres:secret@localhost:5432/repowise"++ loaded_store, loaded_repo_id = await build_primary_vector_store(+ session_factory,+ postgres_url,+ embedder,+ )+ try:+ assert loaded_repo_id == r_a.id+ assert isinstance(loaded_store, LanceDBVectorStore)+ assert await loaded_store.list_page_ids() == {"p1"}+ finally:+ await loaded_store.close()+++async def test_build_primary_vector_store_postgres_multiple_repos_cwd_match(+ session_factory,+ tmp_path,+ monkeypatch,+) -> None:+ """PostgreSQL URL with multiple repos should resolve primary matching process CWD."""+ repos_dir = tmp_path / "repos"+ repos_dir.mkdir()+ repo_a = repos_dir / "service-a"+ repo_b = repos_dir / "service-b"+ (repo_a / ".repowise" / "lancedb").mkdir(parents=True)+ (repo_b / ".repowise" / "lancedb").mkdir(parents=True)++ async with get_session(session_factory) as session:+ await crud.upsert_repository(+ session,+ name="service-a",+ local_path=str(repo_a),+ )+ r_b = await crud.upsert_repository(+ session,+ name="service-b",+ local_path=str(repo_b),+ )++ embedder = MockEmbedder()+ lance_store = LanceDBVectorStore(str(repo_b / ".repowise" / "lancedb"), embedder=embedder)+ await lance_store.embed_and_upsert("p2", "content-b", {"title": "P2"})+ await lance_store.close()++ monkeypatch.chdir(repo_b)+ postgres_url = "postgresql+asyncpg://postgres:secret@localhost:5432/repowise"++ loaded_store, loaded_repo_id = await build_primary_vector_store(+ session_factory,+ postgres_url,+ embedder,+ )+ try:+ assert loaded_repo_id == r_b.id+ assert isinstance(loaded_store, LanceDBVectorStore)+ assert await loaded_store.list_page_ids() == {"p2"}+ finally:+ await loaded_store.close()+++async def test_build_primary_vector_store_postgres_single_repo_fallback(+ session_factory,+ tmp_path,+ monkeypatch,+) -> None:+ """PostgreSQL URL with single repo falls back to rows[0]."""+ standalone_dir = tmp_path / "standalone"+ standalone_dir.mkdir()+ repo_path = tmp_path / "single-repo"+ (repo_path / ".repowise" / "lancedb").mkdir(parents=True)++ async with get_session(session_factory) as session:+ repo = await crud.upsert_repository(+ session,+ name="single-repo",+ local_path=str(repo_path),+ )++ embedder = MockEmbedder()+ lance_store = LanceDBVectorStore(str(repo_path / ".repowise" / "lancedb"), embedder=embedder)+ await lance_store.embed_and_upsert("p-single", "single-content", {"title": "Single"})+ await lance_store.close()++ monkeypatch.chdir(standalone_dir)+ postgres_url = "postgresql+asyncpg://postgres:secret@localhost:5432/repowise"++ loaded_store, loaded_repo_id = await build_primary_vector_store(+ session_factory,+ postgres_url,+ embedder,+ )+ try:+ assert loaded_repo_id == repo.id+ assert isinstance(loaded_store, LanceDBVectorStore)+ assert await loaded_store.list_page_ids() == {"p-single"}+ finally:+ await loaded_store.close()+++async def test_build_primary_vector_store_create_false_does_not_create_empty_dir(+ session_factory,+ tmp_path,+ monkeypatch,+) -> None:+ """create=False should return InMemoryVectorStore and avoid creating empty LanceDB dir."""+ repo_path = tmp_path / "unindexed-repo"+ repo_path.mkdir(parents=True)++ async with get_session(session_factory) as session:+ await crud.upsert_repository(+ session,+ name="unindexed-repo",+ local_path=str(repo_path),+ )++ embedder = MockEmbedder()+ monkeypatch.chdir(repo_path)+ postgres_url = "postgresql+asyncpg://postgres:secret@localhost:5432/repowise"++ loaded_store, loaded_repo_id = await build_primary_vector_store(+ session_factory,+ postgres_url,+ embedder,+ create=False,+ )+ try:+ from repowise.core.persistence.vector_store import InMemoryVectorStore++ assert loaded_repo_id is None+ assert isinstance(loaded_store, InMemoryVectorStore)+ assert not (repo_path / ".repowise" / "lancedb").exists()+ finally:+ await loaded_store.close()+++async def test_build_primary_vector_store_shared_sqlite_registry_db_url_match(+ session_factory,+ tmp_path,+ monkeypatch,+) -> None:+ """SQLite db_url pointing at wiki.db resolves primary repo even when cwd does not match."""+ standalone_dir = tmp_path / "standalone"+ standalone_dir.mkdir()+ repo_a = tmp_path / "repo-a"+ repo_b = tmp_path / "repo-b"+ (repo_a / ".repowise" / "lancedb").mkdir(parents=True)+ (repo_b / ".repowise" / "lancedb").mkdir(parents=True)++ async with get_session(session_factory) as session:+ r_a = await crud.upsert_repository(+ session,+ name="repo-a",+ local_path=str(repo_a),+ )+ await crud.upsert_repository(+ session,+ name="repo-b",+ local_path=str(repo_b),+ )++ embedder = MockEmbedder()+ lance_store = LanceDBVectorStore(str(repo_a / ".repowise" / "lancedb"), embedder=embedder)+ await lance_store.embed_and_upsert("p-db-match", "db-content", {"title": "DbMatch"})+ await lance_store.close()++ monkeypatch.chdir(standalone_dir)+ sqlite_url = f"sqlite+aiosqlite:///{repo_a.as_posix()}/.repowise/wiki.db"++ loaded_store, loaded_repo_id = await build_primary_vector_store(+ session_factory,+ sqlite_url,+ embedder,+ )+ try:+ assert loaded_repo_id == r_a.id+ assert isinstance(loaded_store, LanceDBVectorStore)+ assert await loaded_store.list_page_ids() == {"p-db-match"}+ finally:+ await loaded_store.close()