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
perf(persist): bulk-insert new checkpoint rows and give SQLite a larger page cache (#2874)
Raghav Chamadiya68d6c1d87a0a
diff --git a/packages/core/src/repowise/core/persistence/crud/_shared.py b/packages/core/src/repowise/core/persistence/crud/_shared.pyindex dd4b2801a..689637641 100644--- a/packages/core/src/repowise/core/persistence/crud/_shared.py+++ b/packages/core/src/repowise/core/persistence/crud/_shared.py@@ -11,9 +11,10 @@ from __future__ import annotationsfrom collections.abc import Callable, Iterablefrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime+from functools import cachefrom typing import Any-from sqlalchemy import delete, inspect, select+from sqlalchemy import delete, insert, inspect, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.persistence.models import _new_uuid, _now_utc@@ -133,7 +134,7 @@ async def _batch_upsert_keyed(item_key_fn: Callable[[Any], Any],row_key_fn: Callable[[Any], Any],update_fn: Callable[[Any, Any], None],- insert_fn: Callable[[Any], Any],+ insert_fn: Callable[[Any], dict[str, Any]],batch_size: int | None = None,gate: UpsertGate | None = None,) -> None:@@ -148,9 +149,12 @@ async def _batch_upsert_keyed(exactly when the legacy ``key_fn`` filter would have found that row.Within-batch duplicate keys keep the legacy outcome: the first item- inserts, later ones update the pending object (the per-item SELECT used- to see the autoflushed insert), or the reloaded row once that insert has- been flushed and released.+ inserts, later ones update the not-yet-inserted row (the per-item SELECT+ used to see the autoflushed insert), or the reloaded row once that insert+ has been written.++ *insert_fn* returns the new row's column values by attribute name,+ primary key included, exactly as they would be passed to ``model(...)``.*gate*, when given, skips items whose stored row already matches (see:class:`UpsertGate`). Only the surviving items are hydrated as ORM rows.@@ -216,15 +220,20 @@ async def _batch_upsert_keyed(.all())by_key: dict[Any, Any] = {row_key_fn(row): row for row in existing_rows}-- # Rows this call inserted and already flushed, by key -> ORM identity. Only- # the identity is kept: holding every inserted object until the end pinned- # the whole table in memory at once (1.8M graph edges took ~5 GiB). A- # later duplicate key reloads its row through the identity map instead.- flushed: dict[Any, Any] = {}+ mapper = inspect(model)++ # Rows this call inserted, by key -> primary key. Only the key is kept:+ # holding every inserted row until the end pinned the whole table in memory+ # at once (1.8M graph edges took ~5 GiB). A later duplicate key reloads its+ # row through session.get instead.+ flushed: dict[Any, tuple] = {}+ pk_keys = [prop.key for prop in mapper.column_attrs if prop.columns[0].primary_key]size = batch_size or _BATCH_SIZEfor start in range(0, len(materialized), size):- inserted: list[tuple[Any, Any]] = []+ # New rows go out as one executemany INSERT of plain column values, never+ # as ORM objects: building them and the unit of work's per-object state,+ # identity map and flush bookkeeping cost more than the SQL itself.+ pending: dict[Any, dict[str, Any]] = {}for item in materialized[start : start + size]:key = item_key_fn(item)existing = by_key.get(key)@@ -232,15 +241,63 @@ async def _batch_upsert_keyed(existing = await session.get(model, flushed[key])if existing is not None:update_fn(existing, item)+ elif key in pending:+ # Same key twice in one chunk: replay the update on a transient+ # copy, as it used to land on the still-pending insert.+ obj = model(**pending[key])+ update_fn(obj, item)+ pending[key] = _column_values(+ model, {k: v for k, v in vars(obj).items() if not k.startswith("_sa_")}+ )else:- obj = insert_fn(item)- session.add(obj)- by_key[key] = obj- inserted.append((key, obj))+ pending[key] = _column_values(model, insert_fn(item))+ if pending:+ await session.execute(+ insert(model).execution_options(render_nulls=True), list(pending.values())+ )+ for key, values in pending.items():+ flushed[key] = tuple(values[k] for k in pk_keys)await session.flush()- for key, obj in inserted:- flushed[key] = inspect(obj).identity- del by_key[key]+++@cache+def _insert_columns(model: type[Any]) -> tuple[tuple[str, Any, bool], ...]:+ """Per mapped column: attribute key, Python default, server-default-only flag."""+ return tuple(+ (+ prop.key,+ prop.columns[0].default,+ prop.columns[0].default is None and prop.columns[0].server_default is not None,+ )+ for prop in inspect(model).column_attrs+ )+++def _column_values(model: type[Any], values: dict[str, Any]) -> dict[str, Any]:+ """The INSERT parameters a flush of ``model(**values)`` would send.++ A flush gives a column left unset or None its default, so that is resolved+ here too. Every row of a model then carries the same keys, which is what+ lets the bulk INSERT go out as one executemany (rows with differing keys+ are split into separate statements). The INSERT renders the remaining+ Nones as NULL, the value a flush writes for a column without a default.+ """+ row: dict[str, Any] = {}+ used = 0+ for key, default, server_only in _insert_columns(model):+ if key in values:+ used += 1+ value = values.get(key)+ if value is None:+ if server_only:+ continue # left to the database, as a flush would+ if default is not None:+ value = default.arg if default.is_scalar else default.arg(None)+ row[key] = value+ if used != len(values):+ unknown = sorted(set(values) - {c[0] for c in _insert_columns(model)})+ raise TypeError(f"{unknown!r} are not columns of {model.__name__}")+ return rowasync def _batch_delete_in(@@ -287,18 +344,18 @@ def _row_updater(*natural_key: str) -> Callable[[Any, dict], None]:return update-def _row_inserter(model: type[Any], repository_id: str) -> Callable[[dict], Any]:+def _row_inserter(model: type[Any], repository_id: str) -> Callable[[dict], dict]:"""Build the matching ``insert_fn``: the same columns, on a fresh row."""- def insert(row: dict) -> Any:- return model(- id=_new_uuid(),- repository_id=repository_id,+ def insert(row: dict) -> dict:+ return {+ "id": _new_uuid(),+ "repository_id": repository_id,**{k: vfor k, v in row.items()if k not in ("id", "repository_id") and hasattr(model, k)},- )+ }return insertdiff --git a/packages/core/src/repowise/core/persistence/crud/external_systems.py b/packages/core/src/repowise/core/persistence/crud/external_systems.pyindex 54b5be397..96f66886d 100644--- a/packages/core/src/repowise/core/persistence/crud/external_systems.py+++ b/packages/core/src/repowise/core/persistence/crud/external_systems.py@@ -197,26 +197,26 @@ def _symbol_id(sym: Any) -> str:return getattr(sym, "id", None) or f"{sym.file_path}::{sym.name}"-def _new_wiki_symbol(repository_id: str, sym: Any) -> WikiSymbol:- """Build a WikiSymbol row from an ingestion Symbol (shared insert recipe)."""- return WikiSymbol(- id=_new_uuid(),- repository_id=repository_id,- file_path=getattr(sym, "file_path", ""),- symbol_id=_symbol_id(sym),- name=sym.name,- qualified_name=getattr(sym, "qualified_name", sym.name),- kind=sym.kind,- signature=getattr(sym, "signature", ""),- start_line=getattr(sym, "start_line", 0),- end_line=getattr(sym, "end_line", 0),- docstring=getattr(sym, "docstring", None),- visibility=getattr(sym, "visibility", "public"),- is_async=getattr(sym, "is_async", False),- complexity_estimate=getattr(sym, "complexity_estimate", 0),- language=getattr(sym, "language", ""),- parent_name=getattr(sym, "parent_name", None),- )+def _wiki_symbol_values(repository_id: str, sym: Any) -> dict:+ """Column values for a WikiSymbol row from an ingestion Symbol (shared insert recipe)."""+ return {+ "id": _new_uuid(),+ "repository_id": repository_id,+ "file_path": getattr(sym, "file_path", ""),+ "symbol_id": _symbol_id(sym),+ "name": sym.name,+ "qualified_name": getattr(sym, "qualified_name", sym.name),+ "kind": sym.kind,+ "signature": getattr(sym, "signature", ""),+ "start_line": getattr(sym, "start_line", 0),+ "end_line": getattr(sym, "end_line", 0),+ "docstring": getattr(sym, "docstring", None),+ "visibility": getattr(sym, "visibility", "public"),+ "is_async": getattr(sym, "is_async", False),+ "complexity_estimate": getattr(sym, "complexity_estimate", 0),+ "language": getattr(sym, "language", ""),+ "parent_name": getattr(sym, "parent_name", None),+ }def _update_wiki_symbol(existing: WikiSymbol, sym: Any) -> None:@@ -254,7 +254,7 @@ async def batch_upsert_symbols(item_key_fn=_symbol_id,row_key_fn=lambda row: row.symbol_id,update_fn=_update_wiki_symbol,- insert_fn=lambda sym: _new_wiki_symbol(repository_id, sym),+ insert_fn=lambda sym: _wiki_symbol_values(repository_id, sym),)@@ -315,7 +315,7 @@ async def reconcile_symbols_for_files(if existing is not None:_update_wiki_symbol(existing, sym)else:- obj = _new_wiki_symbol(repository_id, sym)+ obj = WikiSymbol(**_wiki_symbol_values(repository_id, sym))session.add(obj)by_id[sid] = objdiff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.pyindex 71995e123..67db3d2ab 100644--- a/packages/core/src/repowise/core/persistence/crud/git.py+++ b/packages/core/src/repowise/core/persistence/crud/git.py@@ -251,15 +251,7 @@ async def upsert_git_metadata_bulk(item_key_fn=lambda meta: meta.get("file_path", ""),row_key_fn=lambda row: row.file_path,update_fn=_update_git_metadata,- insert_fn=lambda meta: GitMetadata(- id=_new_uuid(),- repository_id=repository_id,- **{- k: v- for k, v in meta.items()- if k not in ("id", "repository_id") and hasattr(GitMetadata, k)- },- ),+ insert_fn=_row_inserter(GitMetadata, repository_id),batch_size=_BATCH_SIZE,)diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.pyindex bc54eb26c..19f38cc66 100644--- a/packages/core/src/repowise/core/persistence/crud/graph.py+++ b/packages/core/src/repowise/core/persistence/crud/graph.py@@ -105,6 +105,22 @@ def _update_graph_edge(existing: GraphEdge, edge_data: dict) -> None:existing.confidence = max(existing.confidence or 0.0, confidence)+def _edge_values(repository_id: str, e: dict) -> dict:+ """Column values for a new ``graph_edges`` row built from an edge payload."""+ return {+ "id": _new_uuid(),+ "repository_id": repository_id,+ "source_node_id": e.get("source_node_id", ""),+ "target_node_id": e.get("target_node_id", ""),+ "imported_names_json": e.get("imported_names_json", "[]"),+ "edge_type": e.get("edge_type", "imports"),+ "confidence": e.get("confidence", 1.0),+ "hint_source": e.get("hint_source"),+ "resolution_origin": e.get("resolution_origin"),+ "call_lines_json": e.get("call_lines_json", "[]"),+ }++def _update_graph_metric(existing: GraphMetric, m: dict) -> None:for key in _METRIC_FIELDS:if key in m:@@ -155,11 +171,11 @@ async def batch_upsert_graph_nodes(float_columns=_CENTRALITY_COLUMNS,float_atol=_CENTRALITY_ATOL,),- insert_fn=lambda n: GraphNode(- id=_new_uuid(),- repository_id=repository_id,+ insert_fn=lambda n: {+ "id": _new_uuid(),+ "repository_id": repository_id,**{k: v for k, v in n.items() if k not in ("id", "repository_id")},- ),+ },)@@ -189,18 +205,7 @@ async def batch_upsert_graph_edges(),row_key_fn=lambda row: (row.source_node_id, row.target_node_id, row.edge_type),update_fn=_update_graph_edge,- insert_fn=lambda e: GraphEdge(- id=_new_uuid(),- repository_id=repository_id,- source_node_id=e.get("source_node_id", ""),- target_node_id=e.get("target_node_id", ""),- imported_names_json=e.get("imported_names_json", "[]"),- edge_type=e.get("edge_type", "imports"),- confidence=e.get("confidence", 1.0),- hint_source=e.get("hint_source"),- resolution_origin=e.get("resolution_origin"),- call_lines_json=e.get("call_lines_json", "[]"),- ),+ insert_fn=lambda e: _edge_values(repository_id, e),)@@ -283,20 +288,7 @@ async def reconcile_edges_for_files(# Every fresh edge's source was just cleared, so these are all plain inserts# — no need for the repo-wide upsert (which reloads every edge row).for e in edges:- session.add(- GraphEdge(- id=_new_uuid(),- repository_id=repository_id,- source_node_id=e.get("source_node_id", ""),- target_node_id=e.get("target_node_id", ""),- imported_names_json=e.get("imported_names_json", "[]"),- edge_type=e.get("edge_type", "imports"),- confidence=e.get("confidence", 1.0),- hint_source=e.get("hint_source"),- resolution_origin=e.get("resolution_origin"),- call_lines_json=e.get("call_lines_json", "[]"),- )- )+ session.add(GraphEdge(**_edge_values(repository_id, e)))await session.flush()return deleted@@ -329,16 +321,16 @@ async def batch_upsert_graph_metrics(float_columns=_CENTRALITY_COLUMNS,float_atol=_CENTRALITY_ATOL,),- insert_fn=lambda kv: GraphMetric(- id=_new_uuid(),- repository_id=repository_id,- node_id=kv[0],- pagerank=float(kv[1].get("pagerank", 0.0)),- betweenness=float(kv[1].get("betweenness", 0.0)),- community_id=int(kv[1].get("community_id", 0)),- in_degree=int(kv[1].get("in_degree", 0)),- out_degree=int(kv[1].get("out_degree", 0)),- ),+ insert_fn=lambda kv: {+ "id": _new_uuid(),+ "repository_id": repository_id,+ "node_id": kv[0],+ "pagerank": float(kv[1].get("pagerank", 0.0)),+ "betweenness": float(kv[1].get("betweenness", 0.0)),+ "community_id": int(kv[1].get("community_id", 0)),+ "in_degree": int(kv[1].get("in_degree", 0)),+ "out_degree": int(kv[1].get("out_degree", 0)),+ },)@@ -404,19 +396,19 @@ async def batch_upsert_graph_node_membership(row[0]: row[1:] for row in existing_rows if row[0] in current},),- insert_fn=lambda kv: GraphNodeMembership(- id=_new_uuid(),- repository_id=repository_id,- node_id=kv[0],- node_type=str(kv[1].get("node_type", "file")),- scc_id=(None if kv[1].get("scc_id") is None else int(kv[1]["scc_id"])),- scc_size=int(kv[1].get("scc_size", 0)),- symbol_community_id=(+ insert_fn=lambda kv: {+ "id": _new_uuid(),+ "repository_id": repository_id,+ "node_id": kv[0],+ "node_type": str(kv[1].get("node_type", "file")),+ "scc_id": (None if kv[1].get("scc_id") is None else int(kv[1]["scc_id"])),+ "scc_size": int(kv[1].get("scc_size", 0)),+ "symbol_community_id": (Noneif kv[1].get("symbol_community_id") is Noneelse int(kv[1]["symbol_community_id"])),- ),+ },)diff --git a/packages/core/src/repowise/core/persistence/database.py b/packages/core/src/repowise/core/persistence/database.pyindex 3c9b3f24c..eba23438b 100644--- a/packages/core/src/repowise/core/persistence/database.py+++ b/packages/core/src/repowise/core/persistence/database.py@@ -44,6 +44,13 @@ log = structlog.get_logger(__name__)# for large repos. SQLite blocks (doesn't busy-loop) so this is cheap._SQLITE_BUSY_TIMEOUT_MS = 30000+# Page cache per connection, in KiB (negative = size, not pages). The 2 MiB+# default makes every insert into a large index miss: writing 1.8M graph edges+# (random-uuid primary key plus the unique edge key) took 77s at the default+# and 44s at 64 MiB in raw sqlite3. The cache fills only as pages are touched,+# so a small store pays nothing for the ceiling.+_SQLITE_CACHE_KIB = 65536+def _sqlite_pragmas(busy_timeout_ms: int) -> tuple[tuple[str, str], ...]:"""Return the pragma list to apply to a SQLite connection.@@ -57,6 +64,7 @@ def _sqlite_pragmas(busy_timeout_ms: int) -> tuple[tuple[str, str], ...]:("journal_mode", "WAL"),("synchronous", "NORMAL"),("foreign_keys", "ON"),+ ("cache_size", str(-_SQLITE_CACHE_KIB)),)diff --git a/tests/unit/persistence/test_batch_upsert_keyed.py b/tests/unit/persistence/test_batch_upsert_keyed.pyindex b567ec616..0e895cced 100644--- a/tests/unit/persistence/test_batch_upsert_keyed.py+++ b/tests/unit/persistence/test_batch_upsert_keyed.py@@ -170,48 +170,56 @@ async def test_duplicate_key_across_a_flush_boundary_updates_one_row(async_sessiassert next(r for r in rows if r.source_node_id == "s0.py").confidence == 0.9-async def test_inserted_rows_are_released_after_each_flush(async_session):- """Inserted objects must not all stay alive until the call returns.+async def test_inserted_rows_are_never_tracked_by_the_session(async_session):+ """New rows go out as a bulk INSERT, not as session-held ORM objects.- Holding them pinned a whole table in memory at once; on a 1.8M-edge graph- that was ~5 GiB on top of the run.+ Holding every inserted object pinned a whole table in memory at once; on a+ 1.8M-edge graph that was ~5 GiB on top of the run."""- import gc- import weakref-- from repowise.core.persistence.crud._shared import _BATCH_SIZE, _batch_upsert_keyed- from repowise.core.persistence.models import _new_uuid+ from repowise.core.persistence.crud._shared import _BATCH_SIZErepo = await insert_repo(async_session)total = _BATCH_SIZE * 3- made: list[weakref.ref] = []- alive_at_end: list[int] = []-- def insert(e: dict) -> GraphEdge:- if len(made) == total - 1:- gc.collect()- alive_at_end.append(sum(ref() is not None for ref in made))- obj = GraphEdge(- id=_new_uuid(),- repository_id=repo.id,- source_node_id=e["source_node_id"],- target_node_id=e["target_node_id"],- edge_type=e["edge_type"],- )- made.append(weakref.ref(obj))- return obj+ await batch_upsert_graph_edges(async_session, repo.id, [_edge(f"s{i}.py") for i in range(total)])++ assert not [o for o in async_session.identity_map.values() if isinstance(o, GraphEdge)]+ assert len((await session_exec(async_session, repo.id)).scalars().all()) == total+- await _batch_upsert_keyed(+async def test_bulk_insert_writes_what_a_flush_would(async_session):+ """Unset and None columns get their defaults; other Nones stay NULL."""+ repo = await insert_repo(async_session)+ await batch_upsert_graph_nodes(async_session,- GraphEdge,- [_edge(f"s{i}.py") for i in range(total)],- prefilter=(GraphEdge.repository_id == repo.id,),- item_key_fn=lambda e: (e["source_node_id"], e["target_node_id"], e["edge_type"]),- row_key_fn=lambda row: (row.source_node_id, row.target_node_id, row.edge_type),- update_fn=lambda existing, e: None,- insert_fn=insert,+ repo.id,+ [{"node_id": "a.py", "language": None, "pagerank": None}, {"node_id": "b.py", "name": "B"}],)await async_session.commit()- assert alive_at_end and alive_at_end[0] < _BATCH_SIZE- assert len((await session_exec(async_session, repo.id)).scalars().all()) == total+ rows = await _node_rows(async_session, repo.id)+ a, b = rows["a.py"], rows["b.py"]+ assert (a.node_type, a.language, a.pagerank, a.symbol_count) == ("file", "", 0.0, 0)+ assert a.is_reachability_root is False and a.created_at is not None+ assert a.name is None and b.name == "B"+++async def test_within_batch_duplicate_replays_the_update(async_session):+ """A key repeated before its row is written merges like an update would."""+ repo = await insert_repo(async_session)+ await batch_upsert_graph_edges(+ async_session, repo.id, [_edge("a.py", confidence=0.9), _edge("a.py", confidence=0.4)]+ )+ await async_session.commit()++ rows = (await session_exec(async_session, repo.id)).scalars().all()+ assert len(rows) == 1+ # The edge update keeps the max confidence, as it did on the pending object.+ assert rows[0].confidence == 0.9+++async def test_unknown_column_is_rejected(async_session):+ import pytest++ repo = await insert_repo(async_session)+ with pytest.raises(TypeError):+ await batch_upsert_graph_nodes(async_session, repo.id, [{"node_id": "a.py", "bogus": 1}])diff --git a/tests/unit/persistence/test_database_pragmas.py b/tests/unit/persistence/test_database_pragmas.pyindex 223a41104..9e6bc9b13 100644--- a/tests/unit/persistence/test_database_pragmas.py+++ b/tests/unit/persistence/test_database_pragmas.py@@ -50,6 +50,17 @@ async def test_file_sqlite_engine_sets_busy_timeout(tmp_path: Path) -> None:await engine.dispose()+async def test_file_sqlite_engine_sets_page_cache(tmp_path: Path) -> None:+ """Large index writes need more than SQLite's 2 MiB default page cache."""+ engine = create_engine(f"sqlite+aiosqlite:///{tmp_path / 'wiki.db'}")+ try:+ await init_db(engine)+ assert int(await _read_pragma(engine, "cache_size")) == -65536+ finally:+ await engine.dispose()++@pytest.mark.asyncioasync def test_busy_timeout_override_is_applied(tmp_path: Path) -> None:"""A custom ``busy_timeout_ms`` must reach the connection pragma so the