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(update): stop rewriting the graph rows an update did not change (#1381)
Raghav Chamadiya689d014d9e3f
diff --git a/packages/core/src/repowise/core/ingestion/git_commit_index.py b/packages/core/src/repowise/core/ingestion/git_commit_index.pyindex 68ee2a0f7..809cbc229 100644--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py@@ -138,9 +138,42 @@ def load_commit_index(if provenance_classifier is None:provenance_classifier = AgentProvenanceClassifier()+ # With *since_ts* the walk still asked git for the whole window's numstat+ # and threw almost all of it away in the loop below — 1.5s per update on a+ # 9.3k-commit repo to return nothing. A ``%ct``-only pass over the same+ # walk costs 0.06s and says exactly how deep the surviving prefix goes:+ # both logs traverse the same revisions in the same order under the same+ # filters, so every commit past that depth is one the ``ts <= since_ts``+ # check below would have dropped. The check stays — this only stops git+ # from diffing commits whose fate is already known.+ depth = commit_limit+ if since_ts is not None:+ try:+ stamps = repo.git.log( # type: ignore[attr-defined]+ f"-{commit_limit}", "--no-merges", "--format=%ct"+ ).split()+ except Exception as exc:+ logger.warning("repo_commit_index_failed", error=str(exc))+ return {}+ depth = 0+ for position, stamp in enumerate(stamps):+ try:+ if int(stamp) > since_ts:+ depth = position + 1+ except ValueError: # unparseable stamp: keep it in the window+ depth = position + 1+ if depth == 0:+ logger.debug(+ "repo_commit_index_built",+ commits_parsed=0,+ files_with_history=0,+ indexable_files=len(indexable_files),+ )+ return {}+try:raw = repo.git.log( # type: ignore[attr-defined]- f"-{commit_limit}",+ f"-{depth}","--numstat","--no-merges",f"--format={_LOG_FORMAT}",@@ -153,7 +186,9 @@ def load_commit_index(return {}# git-ai authorship notes for this window (``{}`` unless the repo uses them).- note_agents = load_git_ai_note_agents(repo, commit_limit)+ # Bounded to the same depth as the walk above: the map is read by sha, only+ # for commits that walk parsed, so a wider notes pass buys nothing.+ note_agents = load_git_ai_note_agents(repo, depth)# Agent-trace records (empty after one stat call unless the repo has them).# The orchestrator may pass a shared instance so the trace file is read once# per index rather than once per walk.diff --git a/packages/core/src/repowise/core/persistence/crud/_shared.py b/packages/core/src/repowise/core/persistence/crud/_shared.pyindex 695887334..01a275fff 100644--- a/packages/core/src/repowise/core/persistence/crud/_shared.py+++ b/packages/core/src/repowise/core/persistence/crud/_shared.py@@ -9,6 +9,7 @@ Private to the package.from __future__ import annotationsfrom collections.abc import Callable, Iterable+from dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom typing import Any@@ -38,6 +39,89 @@ def _parse_dt(ts: str) -> datetime:return dt+_GATE_LOAD_CHUNK = 400 # keys per IN (...) reload — under SQLite's parameter limit++# Above this share of the table, reload the rows in one unfiltered SELECT rather+# than as chunked IN (...) lookups. Measured on a 21,696-row membership snapshot+# where 91% of the rows moved: 54 chunked lookups cost 1.64s against 1.10s for+# the single scan they replaced, so a gate that skips almost nothing was paying+# for the privilege.+_GATE_FULL_LOAD_FRACTION = 0.5+++@dataclass(frozen=True)+class UpsertGate:+ """Declares how to tell "this item is already what the row says".++ Opt-in for the callers whose payload is a full recomputation of a wide+ table: the graph node / metric / membership snapshots rewrite every row+ every update, and on a steady-state update almost none of them moved.+ With a gate, :func:`_batch_upsert_keyed` reads the comparison columns as+ plain tuples first (no ORM hydration), and hydrates + touches only the+ rows that actually differ.++ - *columns* are the comparison columns, keyed positionally; the key column+ is not one of them.+ - *item_values_fn* returns exactly the fields ``update_fn`` would write for+ that item. A field it returns that is not in *columns* makes the item+ unconditionally "changed": the gate can never suppress a write it cannot+ prove is redundant, so a payload that grows a field degrades to the+ ungated behaviour instead of silently dropping it.+ - *float_columns* are compared with ``float_atol`` absolute tolerance. See+ :func:`_gate_unchanged` for why that is not the same thing as sloppiness.+ - *prefetched* lets a caller that already scans the table for its own+ reasons hand the comparison data over, so the gate costs no extra read.+ Keys are the row keys; values are tuples ordered like *columns*. It must+ describe the table as the upsert will find it: supplying it is the one way+ to reach the gate without issuing a statement, so nothing autoflushes, and+ a map read before a pending change to the same table would skip exactly+ the rows that change was about. Build it from a SELECT in the same call,+ after any write the caller makes to that table, and exclude any key the+ caller then deletes.+ """++ key_column: Any+ columns: tuple[str, ...]+ item_values_fn: Callable[[Any], dict[str, Any]]+ float_columns: frozenset[str] = field(default_factory=frozenset)+ float_atol: float = 0.0+ prefetched: dict[Any, tuple] | None = None+++def _gate_unchanged(gate: UpsertGate, index: dict[str, int], item: Any, stored: tuple) -> bool:+ """True when writing *item* over *stored* would not move any column.++ Float columns compare with an absolute tolerance because the centrality+ kernels are not bit-stable across processes: PageRank sums in graph+ iteration order, which the resolvers do not fix, so an unchanged repo+ re-persists every file node with a value that moved in the 17th decimal.+ Exact equality therefore skips almost nothing on the table where the+ skipping is worth the most.++ The tolerance does not accumulate. The comparison is always against the+ *stored* value, never against the previous run's fresh value, so a real drift+ that creeps by less than the tolerance per run still crosses it once the+ total distance from the stored number exceeds ``float_atol`` — at which+ point the row is written and the anchor resets. The stored value is+ therefore never further than ``float_atol`` from the truth.+ """+ for name, new in gate.item_values_fn(item).items():+ pos = index.get(name)+ if pos is None:+ return False+ old = stored[pos]+ if old == new:+ continue+ if name in gate.float_columns and old is not None and new is not None:+ try:+ if abs(float(old) - float(new)) <= gate.float_atol:+ continue+ except (TypeError, ValueError):+ return False+ return False+ return True++async def _batch_upsert_keyed(session: AsyncSession,model: type[Any],@@ -49,6 +133,7 @@ async def _batch_upsert_keyed(update_fn: Callable[[Any, Any], None],insert_fn: Callable[[Any], Any],batch_size: int | None = None,+ gate: UpsertGate | None = None,) -> None:"""Generic batch upsert with ONE existence query for the whole batch.@@ -63,6 +148,11 @@ async def _batch_upsert_keyed(Within-batch duplicate keys keep the legacy outcome: the first iteminserts, later ones update the pending object (the per-item SELECT usedto see the autoflushed insert).++ *gate*, when given, skips items whose stored row already matches (see+ :class:`UpsertGate`). Only the surviving items are hydrated as ORM rows.+ It is disabled for a batch with duplicate keys, where "already matches"+ would have to reason about the whole run of items sharing that key."""materialized = list(items)if not materialized:@@ -70,7 +160,59 @@ async def _batch_upsert_keyed(await session.flush()return- existing_rows = (await session.execute(select(model).where(*prefilter))).scalars().all()+ gated_keys: list[Any] | None = None+ stored_count = 0+ if gate is not None:+ keys = [item_key_fn(item) for item in materialized]+ if len(set(keys)) == len(keys):+ index = {name: pos for pos, name in enumerate(gate.columns)}+ if gate.prefetched is not None:+ stored = gate.prefetched+ else:+ stored_rows = (+ await session.execute(+ select(gate.key_column, *[getattr(model, c) for c in gate.columns]).where(+ *prefilter+ )+ )+ ).all()+ stored = {row[0]: row[1:] for row in stored_rows}+ stored_count = len(stored)+ surviving: list[Any] = []+ gated_keys = []+ for item, key in zip(materialized, keys, strict=True):+ current = stored.get(key)+ if current is None:+ surviving.append(item) # new row — nothing to compare against+ continue+ if _gate_unchanged(gate, index, item, current):+ continue+ surviving.append(item)+ gated_keys.append(key)+ materialized = surviving+ if not materialized:+ await session.flush()+ return++ existing_rows: list[Any] = []+ if gated_keys is None or len(gated_keys) >= stored_count * _GATE_FULL_LOAD_FRACTION:+ existing_rows = list(+ (await session.execute(select(model).where(*prefilter))).scalars().all()+ )+ else:+ # Only the rows this batch will actually write. Hydrating the whole+ # table as ORM objects is the other half of the cost the gate removes.+ for i in range(0, len(gated_keys), _GATE_LOAD_CHUNK):+ chunk_keys = gated_keys[i : i + _GATE_LOAD_CHUNK]+ existing_rows.extend(+ (+ await session.execute(+ select(model).where(*prefilter, gate.key_column.in_(chunk_keys)) # type: ignore[union-attr]+ )+ )+ .scalars()+ .all()+ )by_key: dict[Any, Any] = {row_key_fn(row): row for row in existing_rows}if batch_size is None:diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.pyindex c82298c26..a60f62aca 100644--- a/packages/core/src/repowise/core/persistence/crud/graph.py+++ b/packages/core/src/repowise/core/persistence/crud/graph.py@@ -18,7 +18,7 @@ from ..models import (GraphNodeMembership,_new_uuid,)-from ._shared import _BATCH_SIZE, _batch_upsert_keyed+from ._shared import _BATCH_SIZE, UpsertGate, _batch_upsert_keyed# ---------------------------------------------------------------------------# Graph CRUD (batch)@@ -26,6 +26,17 @@ from ._shared import _BATCH_SIZE, _batch_upsert_keyed_METRIC_FIELDS = ("pagerank", "betweenness", "community_id", "in_degree", "out_degree")+# Absolute tolerance for the centrality columns' skip test. The observed+# process-to-process spread on an unchanged repo is ~1e-17 (bench probe+# `probe_graph_determinism.py --cmp`), so this sits five orders above the+# noise it exists to absorb and six below the smallest difference any reader+# of these columns can act on — the rankings they feed are read as an order,+# and no two distinct files sit 1e-12 apart in it. A backend that stored these+# at lower precision than the payload computes them would push every row past+# the tolerance and write it, which is today's behaviour, not a wrong one.+_CENTRALITY_ATOL = 1e-12+_CENTRALITY_COLUMNS = frozenset({"pagerank", "betweenness"})+def _update_graph_node(existing: GraphNode, node_data: dict) -> None:for key, val in node_data.items():@@ -33,6 +44,40 @@ def _update_graph_node(existing: GraphNode, node_data: dict) -> None:setattr(existing, key, val)+# Every column ``_update_graph_node`` can write from a node payload. A payload+# field missing here turns the gate off for that node rather than skipping it+# (see UpsertGate), so adding a field to persist_graph_nodes without adding it+# here costs a write, never a lost one. The direction that is NOT self-healing+# is the reverse: an update_fn that writes something the payload does not carry+# (a timestamp, a counter) would be skipped along with the row, so keep these+# three update_fns strictly payload-driven.+_NODE_FIELDS = (+ "node_type",+ "language",+ "symbol_count",+ "has_error",+ "is_test",+ "is_entry_point",+ "pagerank",+ "betweenness",+ "community_id",+ "community_meta_json",+ "kind",+ "name",+ "qualified_name",+ "file_path",+ "start_line",+ "end_line",+ "visibility",+ "signature",+ "parent_symbol_id",+)+++def _node_gate_values(node_data: dict) -> dict:+ return {k: v for k, v in node_data.items() if k != "node_id"}++def _update_graph_edge(existing: GraphEdge, edge_data: dict) -> None:imported = edge_data.get("imported_names_json")if imported is not None:@@ -79,6 +124,11 @@ async def batch_upsert_graph_nodes((excluding id and repository_id which are set here).Uses SELECT-then-INSERT/UPDATE for dialect portability.++ *nodes* is a full snapshot of the repo's graph on every call, including the+ incremental update path, where a one-file change leaves the overwhelming+ majority of it identical. The gate skips those rows before they are+ hydrated as ORM objects."""await _batch_upsert_keyed(session,@@ -88,6 +138,13 @@ async def batch_upsert_graph_nodes(item_key_fn=lambda n: n.get("node_id", ""),row_key_fn=lambda row: row.node_id,update_fn=_update_graph_node,+ gate=UpsertGate(+ key_column=GraphNode.node_id,+ columns=_NODE_FIELDS,+ item_values_fn=_node_gate_values,+ float_columns=_CENTRALITY_COLUMNS,+ float_atol=_CENTRALITY_ATOL,+ ),insert_fn=lambda n: GraphNode(id=_new_uuid(),repository_id=repository_id,@@ -250,6 +307,13 @@ async def batch_upsert_graph_metrics(item_key_fn=lambda kv: kv[0],row_key_fn=lambda row: row.node_id,update_fn=lambda existing, kv: _update_graph_metric(existing, kv[1]),+ gate=UpsertGate(+ key_column=GraphMetric.node_id,+ columns=_METRIC_FIELDS,+ item_values_fn=lambda kv: {k: v for k, v in kv[1].items() if k in _METRIC_FIELDS},+ float_columns=_CENTRALITY_COLUMNS,+ float_atol=_CENTRALITY_ATOL,+ ),insert_fn=lambda kv: GraphMetric(id=_new_uuid(),repository_id=repository_id,@@ -284,18 +348,19 @@ async def batch_upsert_graph_node_membership(on screen indefinitely."""current = set(membership)- existing_ids = (- (- await session.execute(- select(GraphNodeMembership.node_id).where(- GraphNodeMembership.repository_id == repository_id- )- )+ # The stale scan already has to walk every row this repo owns, so it reads+ # the comparison columns at the same time and hands them to the gate. A+ # second narrow scan measured slower than the writes it was saving on a+ # snapshot where most rows genuinely moved.+ existing_rows = (+ await session.execute(+ select(+ GraphNodeMembership.node_id,+ *[getattr(GraphNodeMembership, c) for c in _MEMBERSHIP_FIELDS],+ ).where(GraphNodeMembership.repository_id == repository_id))- .scalars()- .all()- )- stale = [nid for nid in existing_ids if nid not in current]+ ).all()+ stale = [row[0] for row in existing_rows if row[0] not in current]for i in range(0, len(stale), _MEMBERSHIP_PRUNE_CHUNK):await session.execute(delete(GraphNodeMembership).where(@@ -312,6 +377,18 @@ async def batch_upsert_graph_node_membership(item_key_fn=lambda kv: kv[0],row_key_fn=lambda row: row.node_id,update_fn=lambda existing, kv: _update_graph_node_membership(existing, kv[1]),+ gate=UpsertGate(+ key_column=GraphNodeMembership.node_id,+ columns=_MEMBERSHIP_FIELDS,+ item_values_fn=lambda kv: {+ k: v for k, v in kv[1].items() if k in _MEMBERSHIP_FIELDS+ },+ # Pruned keys are excluded: their rows are gone by the time the+ # upsert runs, and a snapshot never sends a key it just pruned.+ prefetched={+ 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,diff --git a/packages/core/src/repowise/core/persistence/crud/pages.py b/packages/core/src/repowise/core/persistence/crud/pages.pyindex 7a0dd4949..1073e9d87 100644--- a/packages/core/src/repowise/core/persistence/crud/pages.py+++ b/packages/core/src/repowise/core/persistence/crud/pages.py@@ -460,13 +460,29 @@ async def backfill_related_pages(from repowise.core.generation.related_pages import attach_related_pages+ # Five columns, not whole ORM rows. The recompute reads nothing but the+ # id, type, title, target path and metadata, while ``select(Page)`` also+ # drags every page's rendered ``content`` across the wire — megabytes on a+ # repo of any size, for a metadata field. The whole live page set is still+ # read: ``attach_related_pages`` resolves neighbours against the page set it+ # is handed, so narrowing the *rows* (to the affected pages and one hop)+ # rather than the *columns* would silently resolve fewer neighbours and+ # need a periodic full pass to heal itself. Narrowing columns costs nothing+ # in accuracy.result = await session.execute(- select(Page).where(+ select(+ Page.id,+ Page.page_type,+ Page.title,+ Page.target_path,+ Page.metadata_json,+ ).where(Page.repository_id == repository_id,Page.freshness_status != "tombstone",))- rows = [r for r in result.scalars() if r.id not in (skip_page_ids or set())]+ skip = skip_page_ids or set()+ rows = [r for r in result.all() if r.id not in skip]if not rows:return 0@@ -495,7 +511,7 @@ async def backfill_related_pages(pagerank=pagerank,)- changed = 0+ updates: dict[str, str] = {}for row, shim, before in zip(rows, shims, prior_related, strict=True):after = shim.metadata.get("related_pages")if after is None:@@ -512,8 +528,28 @@ async def backfill_related_pages()if after == before:continue- row.metadata_json = json.dumps(shim.metadata)- changed += 1+ updates[row.id] = json.dumps(shim.metadata)++ # ORM rows are hydrated only for the pages whose metadata actually moved,+ # which on a steady-state update is usually none of them.+ changed = 0+ ids = list(updates)+ for i in range(0, len(ids), _PAGE_SELECT_CHUNK):+ batch = ids[i : i + _PAGE_SELECT_CHUNK]+ page_rows = (+ (+ await session.execute(+ select(Page).where(+ Page.repository_id == repository_id, Page.id.in_(batch)+ )+ )+ )+ .scalars()+ .all()+ )+ for page in page_rows:+ page.metadata_json = updates[page.id]+ changed += 1if changed:await session.flush()return changeddiff --git a/tests/unit/persistence/test_graph_upsert_gate.py b/tests/unit/persistence/test_graph_upsert_gate.pynew file mode 100644index 000000000..d983acc1c--- /dev/null+++ b/tests/unit/persistence/test_graph_upsert_gate.py@@ -0,0 +1,580 @@+"""The graph snapshot upserts skip rows that already say what the payload says.++``persist_graph_nodes`` hands ``batch_upsert_graph_nodes`` /+``batch_upsert_graph_metrics`` / ``batch_upsert_graph_node_membership`` a full+snapshot of the repo's graph on every update, so a one-file change arrives as+tens of thousands of rewrites of rows that did not move. The gate skips those+before they are hydrated as ORM objects.++A gate that skips a write it should have made is indistinguishable from a+correct no-op at the call site, so the two-database parity run at the bottom+compares the gated path against the same path with the gate removed, and the+one deliberate divergence (the centrality tolerance) is kept out of that+scenario and tested on its own.++Read the green here for what it is. Most of these are no-regression guards: they+pass against a build with no gate at all, which is the point, since the gate is+supposed to be invisible. The ones that actually fail when the feature is+removed or weakened, and are therefore the evidence it works, are:++- ``test_subtolerance_centrality_drift_is_not_written`` (gate present at all),+ paired with ``..._is_the_gate_and_not_the_storage`` (the same move lands+ without the gate, so the first is not testing a lossy float column),+- ``test_repeated_subtolerance_drift_cannot_accumulate`` (both bounds),+- ``test_unknown_payload_field_disables_the_skip`` (a field the gate cannot+ compare must never be skipped),+- ``test_duplicate_keys_keep_last_write_wins`` (the duplicate-key opt-out).+"""++from __future__ import annotations++import json++from sqlalchemy import select++from repowise.core.persistence.crud.graph import (+ _CENTRALITY_ATOL,+ batch_upsert_graph_node_membership,+ batch_upsert_graph_nodes,+)+from repowise.core.persistence.models import GraphMetric, GraphNode, GraphNodeMembership+from tests.unit.persistence.helpers import insert_repo+++def file_node(node_id: str, **over) -> dict:+ base = dict(+ node_id=node_id,+ node_type="file",+ language="python",+ symbol_count=3,+ has_error=False,+ is_test=False,+ is_entry_point=False,+ pagerank=0.25,+ betweenness=0.5,+ community_id=1,+ community_meta_json=json.dumps({"label": "core", "cohesion": 0.5}),+ )+ base.update(over)+ return base+++def symbol_node(node_id: str, **over) -> dict:+ base = dict(+ node_id=node_id,+ node_type="symbol",+ language="python",+ symbol_count=0,+ has_error=False,+ is_test=False,+ is_entry_point=False,+ pagerank=0.01,+ betweenness=0.0,+ community_id=0,+ community_meta_json=json.dumps({"symbol_community_id": 7}),+ kind="function",+ name="f",+ qualified_name="m.f",+ file_path="m.py",+ start_line=1,+ end_line=9,+ visibility="public",+ signature="def f()",+ parent_symbol_id=None,+ )+ base.update(over)+ return base+++async def _nodes(session, rid) -> dict[str, dict]:+ rows = (+ (await session.execute(select(GraphNode).where(GraphNode.repository_id == rid)))+ .scalars()+ .all()+ )+ return {+ r.node_id: {+ c.name: getattr(r, c.name)+ for c in GraphNode.__table__.columns+ if c.name not in ("id", "created_at")+ }+ for r in rows+ }+++async def _metrics(session, rid) -> dict[str, dict]:+ rows = (+ (await session.execute(select(GraphMetric).where(GraphMetric.repository_id == rid)))+ .scalars()+ .all()+ )+ return {+ r.node_id: {+ c.name: getattr(r, c.name)+ for c in GraphMetric.__table__.columns+ if c.name not in ("id", "created_at")+ }+ for r in rows+ }+++async def _membership(session, rid) -> dict[str, dict]:+ rows = (+ (+ await session.execute(+ select(GraphNodeMembership).where(GraphNodeMembership.repository_id == rid)+ )+ )+ .scalars()+ .all()+ )+ return {+ r.node_id: {+ c.name: getattr(r, c.name)+ for c in GraphNodeMembership.__table__.columns+ if c.name not in ("id", "created_at")+ }+ for r in rows+ }+++# ---------------------------------------------------------------------------+# The intentional delta: what "unchanged" means for a centrality float+# ---------------------------------------------------------------------------+++async def test_subtolerance_centrality_drift_is_not_written(async_session):+ """A move smaller than the tolerance leaves the stored value alone.++ This is the whole point of an absolute tolerance rather than exact+ equality: the kernels are not bit-stable across processes, so exact+ equality would rewrite every file node on a repo where nothing changed.+ """+ repo = await insert_repo(async_session)+ await batch_upsert_graph_nodes(async_session, repo.id, [file_node("a.py")])+ await async_session.commit()++ await batch_upsert_graph_nodes(+ async_session, repo.id, [file_node("a.py", pagerank=0.25 + _CENTRALITY_ATOL / 10)]+ )+ await async_session.commit()++ assert (await _nodes(async_session, repo.id))["a.py"]["pagerank"] == 0.25+++async def test_subtolerance_drift_is_the_gate_and_not_the_storage(async_session):+ """The same sub-tolerance move, with the gate removed, does land.++ Without this the test above would pass just as happily against a build+ that has no gate at all, or against a float column that silently rounds.+ """+ from repowise.core.persistence.crud import graph as graph_crud++ repo = await insert_repo(async_session)+ original = graph_crud._batch_upsert_keyed++ async def no_gate(*args, **kwargs):+ kwargs.pop("gate", None)+ return await original(*args, **kwargs)++ graph_crud._batch_upsert_keyed = no_gate+ try:+ await graph_crud.batch_upsert_graph_nodes(async_session, repo.id, [file_node("a.py")])+ await async_session.commit()+ moved = 0.25 + _CENTRALITY_ATOL / 10+ await graph_crud.batch_upsert_graph_nodes(+ async_session, repo.id, [file_node("a.py", pagerank=moved)]+ )+ await async_session.commit()+ finally:+ graph_crud._batch_upsert_keyed = original++ assert (await _nodes(async_session, repo.id))["a.py"]["pagerank"] == moved+++async def test_supratolerance_centrality_move_is_written(async_session):+ repo = await insert_repo(async_session)+ await batch_upsert_graph_nodes(async_session, repo.id, [file_node("a.py")])+ await async_session.commit()++ moved = 0.25 + _CENTRALITY_ATOL * 100+ await batch_upsert_graph_nodes(async_session, repo.id, [file_node("a.py", pagerank=moved)])+ await async_session.commit()++ assert (await _nodes(async_session, repo.id))["a.py"]["pagerank"] == moved+++async def test_repeated_subtolerance_drift_cannot_accumulate(async_session):+ """A drift that creeps by a quarter of the tolerance per run still lands.++ Every comparison is against the *stored* value, never the previous run's+ fresh value, so the distance from storage grows until it crosses the+ tolerance and forces a write. Asserting only the final value would pass+ against a build with no gate, which writes every step and therefore also+ ends up correct: the per-step trace below is what separates them. Storage+ holds still for the first four steps and jumps on the fifth.+ """+ repo = await insert_repo(async_session)+ await batch_upsert_graph_nodes(async_session, repo.id, [file_node("a.py")])+ await async_session.commit()++ step = _CENTRALITY_ATOL / 4+ trace = []+ for i in range(1, 11):+ await batch_upsert_graph_nodes(+ async_session, repo.id, [file_node("a.py", pagerank=0.25 + step * i)]+ )+ await async_session.commit()+ trace.append((await _nodes(async_session, repo.id))["a.py"]["pagerank"])++ assert trace[:4] == [0.25] * 4, "a sub-tolerance move was written"+ assert trace[4] == 0.25 + step * 5, "the crossing step was not written"+ # Never further from the truth than the tolerance, at any point.+ assert all(abs(trace[i] - (0.25 + step * (i + 1))) <= _CENTRALITY_ATOL for i in range(10))+++# ---------------------------------------------------------------------------+# The gate must never be the reason a write goes missing+# ---------------------------------------------------------------------------+++async def test_non_float_change_is_always_written(async_session):+ """Integers and strings get no tolerance: a community relabel lands."""+ repo = await insert_repo(async_session)+ await batch_upsert_graph_nodes(async_session, repo.id, [file_node("a.py")])+ await async_session.commit()++ await batch_upsert_graph_nodes(+ async_session,+ repo.id,+ [file_node("a.py", community_id=2, community_meta_json='{"label": "cli"}')],+ )+ await async_session.commit()++ row = (await _nodes(async_session, repo.id))["a.py"]+ assert row["community_id"] == 2+ assert row["community_meta_json"] == '{"label": "cli"}'+++def test_node_gate_columns_account_for_every_writable_column():+ """``_NODE_FIELDS`` is a hand-kept mirror of the model's columns.++ A new ``GraphNode`` column that the node payload starts carrying, without a+ matching entry here, turns the gate off for every node — a silent loss of+ the whole win rather than of a write. This forces the decision at the point+ the column is added.+ """+ from repowise.core.persistence.crud.graph import _NODE_FIELDS++ managed_elsewhere = {+ "id",+ "repository_id",+ "created_at", # never written by _update_graph_node+ "node_id", # the match key+ "external_system_id", # owned by the external-systems linker+ }+ assert set(_NODE_FIELDS) | managed_elsewhere == {+ c.name for c in GraphNode.__table__.columns+ }+++async def test_unknown_payload_field_disables_the_skip(async_session):+ """A field the gate cannot compare must cost a write, never lose one.++ Guards the failure mode where someone adds a column to the node payload+ and the gate quietly stops persisting it because everything else matched.+ """+ repo = await insert_repo(async_session)+ await batch_upsert_graph_nodes(async_session, repo.id, [file_node("a.py")])+ await async_session.commit()++ await batch_upsert_graph_nodes(+ async_session, repo.id, [file_node("a.py", external_system_id=42)]+ )+ await async_session.commit()++ assert (await _nodes(async_session, repo.id))["a.py"]["external_system_id"] == 42+++async def test_duplicate_keys_keep_last_write_wins(async_session):+ """Two items with the same key: the gate steps aside and the legacy+ last-write-wins outcome is preserved.++ The ordering matters. The second item is the one that matches the stored+ row, so a gate that ran per item would skip it, apply only the first, and+ invert the outcome. An ordering where both items differ from storage would+ pass with the duplicate-key check deleted.+ """+ repo = await insert_repo(async_session)+ await batch_upsert_graph_nodes(async_session, repo.id, [file_node("a.py", community_id=1)])+ await async_session.commit()++ await batch_upsert_graph_nodes(+ async_session,+ repo.id,+ [file_node("a.py", community_id=5), file_node("a.py", community_id=1)],+ )+ await async_session.commit()++ assert (await _nodes(async_session, repo.id))["a.py"]["community_id"] == 1+++async def test_new_rows_still_insert_when_everything_else_is_unchanged(async_session):+ repo = await insert_repo(async_session)+ await batch_upsert_graph_nodes(async_session, repo.id, [file_node("a.py")])+ await async_session.commit()++ await batch_upsert_graph_nodes(+ async_session, repo.id, [file_node("a.py"), file_node("b.py")]+ )+ await async_session.commit()++ assert set(await _nodes(async_session, repo.id)) == {"a.py", "b.py"}+++async def test_sparse_and_dense_change_sets_land_the_same_rows(async_session):+ """The gate reloads survivors by key when few rows moved and falls back to+ one unfiltered scan when most did. Both branches must write the same thing."""+ repo = await insert_repo(async_session)+ await batch_upsert_graph_nodes(+ async_session, repo.id, [file_node(f"m{i}.py", community_id=0) for i in range(10)]+ )+ await async_session.commit()++ # sparse: one row of ten moves+ await batch_upsert_graph_nodes(+ async_session,+ repo.id,+ [file_node(f"m{i}.py", community_id=1 if i == 3 else 0) for i in range(10)],+ )+ await async_session.commit()+ rows = await _nodes(async_session, repo.id)+ assert [rows[f"m{i}.py"]["community_id"] for i in range(10)] == [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]++ # dense: nine of ten move+ await batch_upsert_graph_nodes(+ async_session,+ repo.id,+ [file_node(f"m{i}.py", community_id=0 if i == 3 else 7) for i in range(10)],+ )+ await async_session.commit()+ rows = await _nodes(async_session, repo.id)+ assert [rows[f"m{i}.py"]["community_id"] for i in range(10)] == [7, 7, 7, 0, 7, 7, 7, 7, 7, 7]+++async def test_membership_prune_still_runs_when_nothing_else_changed(async_session):+ """The absent-node delete is upstream of the gate and must survive it."""+ repo = await insert_repo(async_session)+ snapshot = {+ "a.py": {"node_type": "file", "scc_id": 0, "scc_size": 2, "symbol_community_id": None},+ "b.py": {"node_type": "file", "scc_id": 0, "scc_size": 2, "symbol_community_id": None},+ }+ await batch_upsert_graph_node_membership(async_session, repo.id, snapshot)+ await async_session.commit()++ await batch_upsert_graph_node_membership(+ async_session, repo.id, {"a.py": snapshot["a.py"]}+ )+ await async_session.commit()++ assert set(await _membership(async_session, repo.id)) == {"a.py"}+++async def test_empty_snapshot_prunes_everything(async_session):+ repo = await insert_repo(async_session)+ await batch_upsert_graph_node_membership(+ async_session,+ repo.id,+ {"a.py": {"node_type": "file", "scc_id": 1, "scc_size": 2, "symbol_community_id": None}},+ )+ await async_session.commit()++ await batch_upsert_graph_node_membership(async_session, repo.id, {})+ await async_session.commit()++ assert await _membership(async_session, repo.id) == {}+++async def test_gate_is_scoped_to_the_repository(async_session):+ """Two repos can hold the same node_id; the gate must not read one repo's+ values as the other's."""+ a = await insert_repo(async_session, name="a", local_path="/tmp/a")+ b = await insert_repo(async_session, name="b", local_path="/tmp/b")+ await batch_upsert_graph_nodes(async_session, a.id, [file_node("x.py", community_id=1)])+ await async_session.commit()+ # Different values, so a gate reading repo A's row for repo B fails on the+ # value rather than only on the row being absent.+ await batch_upsert_graph_nodes(async_session, b.id, [file_node("x.py", community_id=2)])+ await async_session.commit()+ await batch_upsert_graph_nodes(async_session, b.id, [file_node("x.py", community_id=1)])+ await async_session.commit()++ assert (await _nodes(async_session, b.id))["x.py"]["community_id"] == 1+ assert (await _nodes(async_session, a.id))["x.py"]["community_id"] == 1+++# ---------------------------------------------------------------------------+# Row-for-row parity against the ungated path+# ---------------------------------------------------------------------------+++async def _fresh_db():+ from repowise.core.persistence.database import (+ create_engine,+ create_session_factory,+ init_db,+ )++ engine = create_engine("sqlite+aiosqlite:///:memory:")+ await init_db(engine)+ return engine, create_session_factory(engine)+++def _scenario_round1() -> tuple[list[dict], dict, dict]:+ nodes = [file_node(f"m{i}.py", community_id=i) for i in range(4)]+ nodes += [symbol_node(f"m{i}.py::f", pagerank=0.01 * i) for i in range(4)]+ metrics = {+ f"m{i}.py": {+ "pagerank": 0.1 * i,+ "betweenness": 0.2 * i,+ "community_id": i,+ "in_degree": i,+ "out_degree": i + 1,+ }+ for i in range(4)+ }+ membership = {+ f"m{i}.py": {+ "node_type": "file",+ "scc_id": 0,+ "scc_size": 4,+ "symbol_community_id": None,+ }+ for i in range(4)+ } | {+ f"m{i}.py::f": {+ "node_type": "symbol",+ "scc_id": None,+ "scc_size": 0,+ "symbol_community_id": 3,+ }+ for i in range(4)+ }+ return nodes, metrics, membership+++def _scenario_round2() -> tuple[list[dict], dict, dict]:+ """m0 untouched, m1 relabelled, m2 centrality moves well past tolerance,+ m3 loses its symbol, and a new m4 arrives. No sub-tolerance moves: those+ are a deliberate divergence and are tested on their own."""+ nodes = [+ file_node("m0.py", community_id=0),+ file_node("m1.py", community_id=99, community_meta_json='{"label": "moved"}'),+ file_node("m2.py", community_id=2, pagerank=0.99, betweenness=0.77),+ file_node("m3.py", community_id=3, is_test=True, language="go"),+ file_node("m4.py", community_id=4),+ ]+ nodes += [symbol_node(f"m{i}.py::f", pagerank=0.01 * i) for i in range(3)]+ nodes += [symbol_node("m4.py::g", name="g", qualified_name="m4.g", file_path="m4.py")]+ metrics = {+ "m0.py": {+ "pagerank": 0.0,+ "betweenness": 0.0,+ "community_id": 0,+ "in_degree": 0,+ "out_degree": 1,+ },+ "m1.py": {+ "pagerank": 0.1,+ "betweenness": 0.2,+ "community_id": 99,+ "in_degree": 1,+ "out_degree": 2,+ },+ "m2.py": {+ "pagerank": 0.55,+ "betweenness": 0.66,+ "community_id": 2,+ "in_degree": 2,+ "out_degree": 3,+ },+ "m4.py": {+ "pagerank": 0.4,+ "betweenness": 0.4,+ "community_id": 4,+ "in_degree": 0,+ "out_degree": 0,+ },+ }+ membership = {+ "m0.py": {+ "node_type": "file",+ "scc_id": 0,+ "scc_size": 4,+ "symbol_community_id": None,+ },+ "m1.py": {+ "node_type": "file",+ "scc_id": 1,+ "scc_size": 2,+ "symbol_community_id": None,+ },+ "m4.py::g": {+ "node_type": "symbol",+ "scc_id": None,+ "scc_size": 0,+ "symbol_community_id": 11,+ },+ }+ return nodes, metrics, membership+++async def _run_scenario(session_factory, rid_name: str, *, ungated: bool):+ from repowise.core.persistence import get_session, upsert_repository+ from repowise.core.persistence.crud import graph as graph_crud++ original = graph_crud._batch_upsert_keyed++ async def no_gate(*args, **kwargs):+ kwargs.pop("gate", None)+ return await original(*args, **kwargs)++ if ungated:+ graph_crud._batch_upsert_keyed = no_gate+ try:+ async with get_session(session_factory) as s:+ repo = await upsert_repository(s, name=rid_name, local_path=f"/tmp/{rid_name}")+ rid = repo.id+ for nodes, metrics, membership in (_scenario_round1(), _scenario_round2()):+ async with get_session(session_factory) as s:+ await graph_crud.batch_upsert_graph_nodes(s, rid, nodes)+ await graph_crud.batch_upsert_graph_metrics(s, rid, metrics)+ await graph_crud.batch_upsert_graph_node_membership(s, rid, membership)+ return rid+ finally:+ graph_crud._batch_upsert_keyed = original+++async def test_gated_and_ungated_paths_leave_identical_rows():+ from repowise.core.persistence import get_session++ eng_a, sf_a = await _fresh_db()+ eng_b, sf_b = await _fresh_db()+ try:+ rid_a = await _run_scenario(sf_a, "gated", ungated=False)+ rid_b = await _run_scenario(sf_b, "ungated", ungated=True)++ async with get_session(sf_a) as sa, get_session(sf_b) as sb:+ for reader in (_nodes, _metrics, _membership):+ rows_a = await reader(sa, rid_a)+ rows_b = await reader(sb, rid_b)+ assert set(rows_a) == set(rows_b), reader.__name__+ for key in rows_a:+ a = dict(rows_a[key])+ b = dict(rows_b[key])+ a.pop("repository_id")+ b.pop("repository_id")+ assert a == b, f"{reader.__name__}:{key}"+ finally:+ await eng_a.dispose()+ await eng_b.dispose()diff --git a/tests/unit/test_git_commit_rows.py b/tests/unit/test_git_commit_rows.pyindex 6754b31ce..c7ba04f06 100644--- a/tests/unit/test_git_commit_rows.py+++ b/tests/unit/test_git_commit_rows.py@@ -90,50 +90,87 @@ def test_commit_sink_collects_full_footprint_including_non_indexable() -> None:]+def _mock_repo(commits: list[dict]):+ """A repo whose ``git log`` answers both passes the loader makes.++ With ``since_ts`` the loader first asks for ``%ct`` only, to learn how deep+ the surviving prefix goes, and only then asks for the numstat block bounded+ to that depth. A mock that returned the same string to both would let the+ bound go untested.+ """+ repo = MagicMock()+ calls: list[tuple] = []++ def log(*args, **kwargs):+ calls.append(args)+ depth = int(str(args[0]).lstrip("-"))+ if "--format=%ct" in args:+ return "\n".join(str(c["ct"]) for c in commits[:depth])+ return _build_log(commits[:depth])++ repo.git.log.side_effect = log+ repo._log_calls = calls+ return repo++def test_commit_sink_since_ts_drops_old_commits() -> None:"""``since_ts`` filters the sink to commits strictly newer than the bound —the incremental capture path's freshness guarantee."""- raw = _build_log(- [- {- "sha": "new",- "an": "A",- "ae": "a@x",- "ct": 3000,- "subj": "new",- "files": [(1, 0, "src/a.py")],- },- {- "sha": "mid",- "an": "A",- "ae": "a@x",- "ct": 2000,- "subj": "mid",- "files": [(1, 0, "src/a.py")],- },- {- "sha": "old",- "an": "A",- "ae": "a@x",- "ct": 1000,- "subj": "old",- "files": [(1, 0, "src/a.py")],- },- ]- )- repo = MagicMock()- repo.git.log.return_value = raw-+ commits = [+ {"sha": "new", "an": "A", "ae": "a@x", "ct": 3000, "subj": "new",+ "files": [(1, 0, "src/a.py")]},+ {"sha": "mid", "an": "A", "ae": "a@x", "ct": 2000, "subj": "mid",+ "files": [(1, 0, "src/a.py")]},+ {"sha": "old", "an": "A", "ae": "a@x", "ct": 1000, "subj": "old",+ "files": [(1, 0, "src/a.py")]},+ ]+ repo = _mock_repo(commits)sink: list[dict] = []load_commit_index(repo, 100, {"src/a.py"}, commit_sink=sink, since_ts=1500)# Only commits with ts > 1500 survive (3000, 2000).assert sorted(c["sha"] for c in sink) == ["mid", "new"]+ repo2 = _mock_repo(commits)sink2: list[dict] = []- load_commit_index(repo, 100, {"src/a.py"}, commit_sink=sink2, since_ts=3000)+ load_commit_index(repo2, 100, {"src/a.py"}, commit_sink=sink2, since_ts=3000)assert sink2 == []+def test_since_ts_bounds_the_numstat_walk_to_the_surviving_prefix() -> None:+ """The expensive pass must not diff commits the ts filter would drop.++ Without this the loader can ask git to produce ``--numstat`` for the whole+ window and throw it away, which is invisible to every behavioural test+ above: the returned rows are identical either way.+ """+ commits = [+ {"sha": f"c{i}", "an": "A", "ae": "a@x", "ct": 5000 - i * 100, "subj": f"c{i}",+ "files": [(1, 0, "src/a.py")]}+ for i in range(20)+ ]+ repo = _mock_repo(commits)+ sink: list[dict] = []+ # ts > 4800 keeps c0..c1 (5000, 4900); c2 is exactly 4800 and is excluded.+ load_commit_index(repo, 100, {"src/a.py"}, commit_sink=sink, since_ts=4800)++ assert sorted(c["sha"] for c in sink) == ["c0", "c1"]+ numstat_calls = [c for c in repo._log_calls if "--numstat" in c]+ assert len(numstat_calls) == 1+ assert numstat_calls[0][0] == "-2"+++def test_since_ts_newer_than_every_commit_skips_the_numstat_walk() -> None:+ commits = [+ {"sha": "only", "an": "A", "ae": "a@x", "ct": 1000, "subj": "x",+ "files": [(1, 0, "src/a.py")]}+ ]+ repo = _mock_repo(commits)+ sink: list[dict] = []+ assert load_commit_index(repo, 100, {"src/a.py"}, commit_sink=sink, since_ts=9999) == {}+ assert sink == []+ assert [c for c in repo._log_calls if "--numstat" in c] == []++def test_commit_sink_default_none_is_noop() -> None:"""Without a sink the return value and behaviour are unchanged."""raw = _build_log(