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
feat(health): trace bug fixes to the commits that introduced them (#939)
Raghav Chamadiyae7727b3ed43a
diff --git a/packages/core/alembic/versions/0040_fix_events.py b/packages/core/alembic/versions/0040_fix_events.pynew file mode 100644index 000000000..05eb76ecf--- /dev/null+++ b/packages/core/alembic/versions/0040_fix_events.py@@ -0,0 +1,62 @@+"""``fix_events``: one row per bug-fix commit x file, with SZZ candidates.++``prior_defect_count`` is a bare number; this table is the evidence under it.+Each row carries what a fix commit did to one file (shape kind, the old-side+line ranges it replaced, changed LOC) and the ranked commits ``git blame`` puts+on those lines at ``fix^``.++``committed_at`` is stored undecayed on purpose: every recency weight is derived+at read time, so changing a half-life never requires a reindex.++New indexes only — no existing table is touched, so a pre-0040 wiki.db upgrades+without rewriting anything and reads an empty table until the next index.++Revision ID: 0040+Revises: 0039+Create Date: 2026-07-19+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0040"+down_revision: str | None = "0039"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.create_table(+ "fix_events",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("fix_sha", sa.String(40), nullable=False),+ sa.Column("file_path", sa.Text, nullable=False),+ sa.Column("shape_kind", sa.String(16), nullable=False, server_default="code_fix"),+ sa.Column("old_ranges_json", sa.Text, nullable=False, server_default="[]"),+ sa.Column("changed_loc", sa.Integer, nullable=False, server_default="0"),+ sa.Column("inducing_shas_json", sa.Text, nullable=False, server_default="[]"),+ sa.Column("taxonomy_json", sa.Text, nullable=False, server_default="{}"),+ sa.Column("committed_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),+ sa.UniqueConstraint("repository_id", "fix_sha", "file_path", name="uq_fix_event"),+ )+ op.create_index("ix_fix_events_repo_path", "fix_events", ["repository_id", "file_path"])+ op.create_index("ix_fix_events_repo_time", "fix_events", ["repository_id", "committed_at"])+++def downgrade() -> None:+ op.drop_index("ix_fix_events_repo_time", table_name="fix_events")+ op.drop_index("ix_fix_events_repo_path", table_name="fix_events")+ op.drop_table("fix_events")diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.pyindex 6ed20aebb..4fe1b85b0 100644--- a/packages/core/src/repowise/core/analysis/changed_lines.py+++ b/packages/core/src/repowise/core/analysis/changed_lines.py@@ -38,12 +38,15 @@ class FileDiff:deletion. *old_ranges* are inclusive ``(start, end)`` line spans on thepre-change file - the space ``git blame <sha>^`` is keyed in. A hunk withan old count of 0 is a pure insertion and contributes no range (there is- nothing to blame).+ nothing it replaced); it records its *insert_anchors* instead - the old-side+ line the new lines went in after, which is the only handle SZZ has on code+ that was added rather than rewritten. 0 means "inserted at the top"."""path: strnew_lines: set[int] = field(default_factory=set)old_ranges: list[tuple[int, int]] = field(default_factory=list)+ insert_anchors: list[int] = field(default_factory=list)removed: list[str] = field(default_factory=list)added: list[str] = field(default_factory=list)@@ -97,6 +100,11 @@ def parse_unified_diff(diff: str) -> dict[str, FileDiff]:new_count = int(m.group(4)) if m.group(4) is not None else 1if old_count > 0:current.old_ranges.append((old_start, old_start + old_count - 1))+ elif new_count > 0:+ # ``@@ -N,0 +M,k @@``: git names the old-side line the block+ # was inserted *after*, which is 0 for an insertion at the+ # top of the file.+ current.insert_anchors.append(old_start)if new_count > 0:current.new_lines.update(range(new_start, new_start + new_count))elif current is not None:diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.pyindex ec02d0d6f..97a2336a5 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py@@ -36,10 +36,17 @@ from .enrich import (meets_hotspot_floors,)from .file_history import index_file+from .fix_events import build_fix_eventsfrom .fix_shape import SHAPE_KINDS, classify_fix_shapefrom .identity import build_identity_resolver, canonicalize_author_emailfrom .indexer import GitIndexer-from .prior_defects import PriorDefects, compute_prior_defects+from .prior_defects import (+ FixCommit,+ FixWalk,+ PriorDefects,+ collect_fix_commits,+ compute_prior_defects,+)from .records import (_FIELD_SEP,_LOG_FORMAT,@@ -50,6 +57,7 @@ from .records import (_parse_commit_record,_should_skip_index,)+from .szz import InducingCandidate, SzzTracer, rank_candidatesfrom .tiers import GitIndexTier__all__ = [@@ -62,19 +70,25 @@ __all__ = ["_RECORD_SEP","AgentProvenance","AgentProvenanceClassifier",+ "FixCommit",+ "FixWalk","GitIndexSummary","GitIndexTier","GitIndexer",+ "InducingCandidate","PriorDefects",+ "SzzTracer","_CommitRec","_extract_rename_paths","_parse_commit_record","_should_skip_index","backfill_full_tier",+ "build_fix_events","build_identity_resolver","canonicalize_author_email","classifier_from_repo_config","classify_fix_shape",+ "collect_fix_commits","compute_co_changes","compute_co_changes_and_entropy","compute_percentiles",@@ -86,4 +100,5 @@ __all__ = ["is_fix_commit","is_significant_commit","meets_hotspot_floors",+ "rank_candidates",]diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/fix_events.py b/packages/core/src/repowise/core/ingestion/git_indexer/fix_events.pynew file mode 100644index 000000000..062f1ff5d--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/git_indexer/fix_events.py@@ -0,0 +1,112 @@+"""Per-file bug-fix events, ready for the ``fix_events`` table.++``prior_defect_count`` collapses a repo's fix history into one number per file.+This module keeps the history itself: one record per fix-commit x file, carrying+the diff shape, the old-side line ranges the fix replaced, its changed LOC, and+- for ``code_fix`` rows - the ranked bug-introducing candidates :mod:`szz` traced.++Two entry points, one for each half of the indexing lifecycle:++* :func:`build_fix_events` runs over a whole :class:`~.prior_defects.FixWalk`,+ which is what a full index produces for the trailing defect window;+* the same function over a walk narrowed by ``skip_shas`` is the incremental+ path, so an update traces only the fix commits it has never seen.++Rows are stored undecayed with their ``committed_at``. Nothing here weighs+recency: that is a read-time decision, so a half-life change never costs a+reindex.+"""++from __future__ import annotations++import json+from concurrent.futures import ThreadPoolExecutor+from datetime import UTC, datetime+from typing import Any++import structlog++from .fix_shape import is_code_path+from .prior_defects import FixCommit, FixWalk+from .szz import SzzTracer++logger = structlog.get_logger(__name__)++__all__ = ["build_fix_events"]++# The blame pass is subprocess-bound, so it scales with workers rather than+# cores. Matches the per-file git workers the indexer already runs.+_TRACE_WORKERS = 20+++def build_fix_events(walk: FixWalk, get_repo: Any) -> list[dict]:+ """Rows for every fix-commit x file in *walk*, SZZ-traced where it applies.++ *get_repo* is a callable returning a gitpython ``Repo`` usable from the+ calling thread (blame runs across a worker pool). An update passes a walk+ already narrowed to the fix commits it has never seen+ (:func:`~.prior_defects.collect_fix_commits`'s ``skip_shas``), so nothing is+ re-blamed.++ Blame runs only for ``code_fix`` commits on production-code paths: tests,+ docs and config carry no defect the ``prior_defect`` signal cares about, and+ blaming them would be the expensive way to learn nothing.+ """+ if not walk.fixes:+ return []++ tracer = SzzTracer(get_repo)+ units = [(fix, path) for fix in walk.fixes for path in fix.paths]++ with ThreadPoolExecutor(max_workers=_TRACE_WORKERS, thread_name_prefix="szz") as pool:+ # ``map`` re-raises the first failure and discards every other result,+ # so isolation lives inside the mapped call: one unlucky file must not+ # cost the whole window's events.+ rows = [row for row in pool.map(lambda unit: _safe_row(tracer, *unit), units) if row]++ # Deterministic order so a replayed capture writes the same rows in the same+ # sequence as a fresh one.+ rows.sort(key=lambda row: (row["fix_sha"], row["file_path"]))+ return rows+++def _safe_row(tracer: SzzTracer, fix: FixCommit, path: str) -> dict | None:+ try:+ return _build_row(tracer, fix, path)+ except Exception as exc:+ logger.debug("fix_event_row_failed", fix=fix.sha[:12], path=path, error=str(exc))+ return None+++def _build_row(tracer: SzzTracer, fix: FixCommit, path: str) -> dict:+ diff = fix.files.get(path)+ old_ranges = list(diff.old_ranges) if diff is not None else []+ changed_loc = len(diff.removed) + len(diff.added) if diff is not None else 0++ candidates: list[dict] = []+ if fix.shape_kind == "code_fix" and diff is not None and is_code_path(path):+ try:+ candidates = [c.as_dict() for c in tracer.trace_file(fix.sha, path, diff)]+ except Exception as exc:+ # A tracing failure must never cost the event row itself: the shape+ # and ranges are still true, only the attribution is missing.+ logger.debug("szz_trace_failed", fix=fix.sha[:12], path=path, error=str(exc))++ return {+ "fix_sha": fix.sha,+ "file_path": path,+ "shape_kind": fix.shape_kind,+ "old_ranges_json": json.dumps([list(r) for r in old_ranges]),+ "changed_loc": changed_loc,+ "inducing_shas_json": json.dumps(candidates),+ "committed_at": _as_datetime(fix.ts),+ }+++def _as_datetime(ts: int) -> datetime | None:+ if ts <= 0:+ return None+ try:+ return datetime.fromtimestamp(ts, tz=UTC)+ except (OverflowError, OSError, ValueError):+ return Nonediff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.pyindex 57d5034af..55d2a5ecb 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py@@ -31,7 +31,7 @@ from ._constants import (from .co_change import compute_co_changes, compute_co_changes_and_entropyfrom .enrich import compute_percentilesfrom .file_history import index_file-from .prior_defects import PriorDefects, compute_prior_defects+from .prior_defects import FixWalk, PriorDefects, collect_fix_commits, compute_prior_defectsfrom .records import GitIndexSummary, _CommitRec, _should_skip_index, capture_repo_totalsfrom .tiers import GitIndexTier@@ -260,11 +260,22 @@ class GitIndexer:# exactly the ones this signal flags). Bounded to the trailing window,# so it's cheap regardless of total repo age and leakage-free at T0.prior_defects = PriorDefects()+ fix_walk = FixWalk()try:- prior_defects = compute_prior_defects(repo, set(indexable_files), as_of_ts=as_of_ts)+ fix_walk = collect_fix_commits(repo, set(indexable_files), as_of_ts=as_of_ts)+ prior_defects = compute_prior_defects(+ repo, set(indexable_files), as_of_ts=as_of_ts, walk=fix_walk+ )except Exception as exc:logger.debug("prior_defect_pass_failed", error=str(exc))+ # Per-file fix events + SZZ tracing ride the same walk: the diffs are+ # already parsed, so this pass only adds blame. Off the event loop, since+ # it fans blame subprocesses out across its own pool for long enough that+ # progress callbacks would visibly stall. Failure-isolated — the counts+ # above stand on their own if tracing breaks.+ fix_event_rows, traced_ok = await asyncio.to_thread(self._trace_fix_events, fix_walk)+# Per-file AI line share from the agent-trace records. Keyed by path# like the aggregates below, so it merges in the same pass and# works regardless of which commit-index walk (if any) ran.@@ -312,6 +323,9 @@ class GitIndexer:stable_files=stable,duration_seconds=duration,commit_rows=commit_rows,+ fix_event_rows=fix_event_rows,+ fix_oldest_ts=fix_walk.oldest_fix_ts,+ fix_events_traced=traced_ok,# Whole-history totals from cheap git calls on the still-open repo —# true project age / commit / contributor counts for the stats page,# which must not read them off the depth-capped sample (issue #730).@@ -509,6 +523,69 @@ class GitIndexer:finally:repo.close()+ def capture_new_fix_events(+ self, *, known_shas: set[str] | None = None+ ) -> tuple[list[dict], int, set[str]]:+ """Build ``fix_events`` rows for fix commits not already persisted.++ The incremental counterpart to the tracing ``index_repo`` runs inline,+ and the same shape as :meth:`capture_new_commit_rows`: walk the trailing+ window once, drop the fix commits *known_shas* already covers, and blame+ the rest. An update with no new fix commits does the walk and stops,+ which is why it stays inside the +1s budget.++ Returns ``(rows, oldest_fix_ts, tracked_paths)``. Both trailing values+ come back even when there are no new rows, because the caller still has+ two prunes to do: events that aged out of the window, and events for+ files that no longer exist. A fresh index never produces the latter, so+ without that second prune an update accumulates rows for deleted files+ and drifts away from what a re-index would hold.+ """+ repo = self._get_repo()+ if repo is None:+ return [], 0, set()+ try:+ tracked = {fp for fp in self._get_tracked_files(repo) if not _should_skip_index(fp)}+ walk = collect_fix_commits(+ repo,+ tracked,+ as_of_ts=self._resolve_as_of_ts(repo),+ skip_shas=known_shas,+ )+ rows, ok = self._trace_fix_events(walk)+ return rows, (walk.oldest_fix_ts if ok else 0), tracked+ except Exception as exc:+ logger.debug("incremental_fix_events_failed", error=str(exc))+ return [], 0, set()+ finally:+ with contextlib.suppress(Exception):+ repo.close()++ def _trace_fix_events(self, walk: FixWalk) -> tuple[list[dict], bool]:+ """SZZ-trace *walk*'s fix commits into ``(rows, traced_ok)``.++ Blame needs its own thread-local repo handles (gitpython handles are not+ shareable on Windows), so this opens a short-lived pool of its own rather+ than reusing the per-file one, which is already closed by this point.++ Failure-isolated: tracing never breaks the git phase. The flag matters+ because "no rows" is ambiguous - a window with no new fixes and a pass+ that blew up look the same from the outside, and only one of them should+ let the caller prune.+ """+ if not walk.fixes:+ return [], True+ get_thread_repo, close_thread_repos = self._thread_repo_pool()+ try:+ from .fix_events import build_fix_events++ return build_fix_events(walk, get_thread_repo), True+ except Exception as exc:+ logger.debug("fix_event_trace_failed", error=str(exc))+ return [], False+ finally:+ close_thread_repos()+def capture_repo_totals(self) -> Any:"""Whole-history :class:`RepoTotals` for this repo (opens its own repo).diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/prior_defects.py b/packages/core/src/repowise/core/ingestion/git_indexer/prior_defects.pyindex d4b101702..05c2cbff9 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/prior_defects.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/prior_defects.py@@ -33,7 +33,7 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime, timedelta-from typing import Any+from typing import TYPE_CHECKING, Anyimport structlog@@ -41,13 +41,18 @@ from ._constants import PRIOR_DEFECT_WINDOW_DAYS, is_fix_commitfrom .fix_shape import classify_fix_shapefrom .records import _RECORD_SEP, _extract_rename_paths+if TYPE_CHECKING:+ # Type-only: ``analysis.change_risk`` imports back into this package, so a+ # runtime import would close an import cycle.+ from ...analysis.changed_lines import FileDiff+logger = structlog.get_logger(__name__)-__all__ = ["PriorDefects", "compute_prior_defects"]+__all__ = ["FixCommit", "FixWalk", "PriorDefects", "collect_fix_commits", "compute_prior_defects"]-# sha <US> subject, one record per commit (NUL-separated); --name-only then-# emits the touched paths on the lines that follow.-_PRIOR_LOG_FORMAT = "%x00%H%x1f%s"+# sha <US> committer-time <US> subject, one record per commit (NUL-separated);+# --name-only then emits the touched paths on the lines that follow.+_PRIOR_LOG_FORMAT = "%x00%H%x1f%ct%x1f%s"_FIELD_SEP = "\x1f"# Fix commits per ``git log --no-walk`` batch in the diff pass. One subprocess@@ -71,11 +76,99 @@ class PriorDefects:@dataclass(frozen=True)-class _FixCommit:- """A subject-matched fix commit and the indexable files it touched."""+class FixCommit:+ """A subject-matched fix commit: what it touched and what its diff looks like.++ *paths* is the indexable subset of the files it changed. *files* is its+ parsed ``-U0`` diff keyed by path — the old-side ranges and changed line text+ the shape classifier reads and SZZ blames. *shape_kind* falls back to+ ``code_fix`` when the diff pass failed for this commit, which keeps the count+ on the pre-filter (safe) side of the change.+ """sha: str+ ts: intpaths: list[str]+ shape_kind: str = "code_fix"+ files: dict[str, FileDiff] = field(default_factory=dict)+++@dataclass(frozen=True)+class FixWalk:+ """Every fix commit in the trailing window, plus the walk's own trailing edge.++ *oldest_fix_ts* is the committer time of the oldest fix the walk found, taken+ BEFORE any ``skip_shas`` narrowing (unix seconds; 0 when the walk found+ nothing). Callers that persist per-commit rows prune below it, so what they+ keep is exactly what the walk contains.++ Deriving the cutoff from the walk rather than from the window's date matters,+ and both halves of that are load-bearing. The rev range is+ ``prior_sha..head``, which is reachability, not time: a merged long-lived+ branch contributes commits older than the date boundary, and a date-based+ prune would delete them immediately after every index inserted them, then+ re-blame them on the next update, forever. And ``git log --before`` reads its+ argument in local time while a Python timestamp is UTC, so the two cutoffs+ would not even agree on the same instant.+ """++ fixes: list[FixCommit] = field(default_factory=list)+ oldest_fix_ts: int = 0+++def collect_fix_commits(+ repo: Any,+ indexable_files: set[str],+ *,+ as_of_ts: float | None,+ window_days: int = PRIOR_DEFECT_WINDOW_DAYS,+ skip_shas: set[str] | None = None,+) -> FixWalk:+ """Walk the trailing window's fix commits and open each one's diff.++ The shared front half of the defect pass: :func:`compute_prior_defects`+ counts these, and :mod:`fix_events` turns them into per-file rows and blames+ them. One walk, one batched diff pass, two consumers.++ *skip_shas* drops commits before the diff pass, which is what keeps an update+ cheap: the name-only walk is a single ``git log``, while opening 200 patches+ is the part that costs real time, and an update with no new fix commits+ should not pay for it. Counting callers must not pass it - a skipped commit+ is missing from the walk entirely, not merely un-diffed.++ Ceiling: the returned walk holds every fix commit's parsed patch, changed+ line text included, for as long as the caller keeps it. Bounded in practice+ by the window (a few hundred commits), but a repo whose fixes routinely touch+ multi-megabyte generated files will hold all of that at once. If that ever+ bites, drop ``removed``/``added`` after classification and carry the LOC+ counts instead - the shape classifier is the only thing that needs the text+ for non-code paths.+ """+ rev_range = _resolve_rev_range(repo, as_of_ts=as_of_ts, window_days=window_days)+ if rev_range is None:+ return FixWalk()++ fixes = _walk_fix_commits(repo, rev_range, indexable_files)+ # Taken before the skip, so an update and a full index at the same HEAD agree+ # on the trailing edge even though they trace different commits.+ oldest = min((f.ts for f in fixes if f.ts > 0), default=0)+ if skip_shas:+ fixes = [f for f in fixes if f.sha not in skip_shas]+ if not fixes:+ return FixWalk(oldest_fix_ts=oldest)++ diffs = _parse_fix_diffs(repo, [f.sha for f in fixes])+ resolved_fixes = [+ FixCommit(+ sha=fix.sha,+ ts=fix.ts,+ paths=fix.paths,+ shape_kind=classify_fix_shape(diffs[fix.sha]) if fix.sha in diffs else "code_fix",+ files=diffs.get(fix.sha, {}),+ )+ for fix in fixes+ ]+ return FixWalk(fixes=resolved_fixes, oldest_fix_ts=oldest)def compute_prior_defects(@@ -84,6 +177,7 @@ def compute_prior_defects(*,as_of_ts: float | None,window_days: int = PRIOR_DEFECT_WINDOW_DAYS,+ walk: FixWalk | None = None,) -> PriorDefects:"""Return per-file bug-fix counts over the trailing window.@@ -91,26 +185,23 @@ def compute_prior_defects(``REPOWISE_GIT_WINDOW_ANCHOR``, else wall-clock now). Only commits reachablefrom HEAD are walked, so a historical T0 checkout never sees post-T0 fixes.Files outside *indexable_files* are ignored.- """- rev_range = _resolve_rev_range(repo, as_of_ts=as_of_ts, window_days=window_days)- if rev_range is None:- return PriorDefects()- fixes = _walk_fix_commits(repo, rev_range, indexable_files)- if not fixes:+ *walk* lets a caller that already ran :func:`collect_fix_commits` reuse it+ instead of paying for a second walk and diff pass.+ """+ if walk is None:+ walk = collect_fix_commits(+ repo, indexable_files, as_of_ts=as_of_ts, window_days=window_days+ )+ if not walk.fixes:return PriorDefects()raw_counts: dict[str, int] = {}- for fix in fixes:+ counts: dict[str, int] = {}+ for fix in walk.fixes:for path in fix.paths:raw_counts[path] = raw_counts.get(path, 0) + 1-- shapes = _classify_shapes(repo, [f.sha for f in fixes])- counts: dict[str, int] = {}- for fix in fixes:- # Unknown shape (the diff pass failed) counts as a fix: falling back to- # the raw behaviour is the safe direction for a defect signal.- if shapes.get(fix.sha, "code_fix") != "code_fix":+ if fix.shape_kind != "code_fix":continuefor path in fix.paths:counts[path] = counts.get(path, 0) + 1@@ -151,7 +242,7 @@ def _resolve_rev_range(repo: Any, *, as_of_ts: float | None, window_days: int) -return f"{prior_sha}..{head_sha}" if prior_sha else head_sha-def _walk_fix_commits(repo: Any, rev_range: str, indexable_files: set[str]) -> list[_FixCommit]:+def _walk_fix_commits(repo: Any, rev_range: str, indexable_files: set[str]) -> list[FixCommit]:"""Subject-matched fix commits in *rev_range*, each with its indexable paths.Commits that touched nothing indexable are dropped here so the diff pass@@ -171,21 +262,29 @@ def _walk_fix_commits(repo: Any, rev_range: str, indexable_files: set[str]) -> lif not raw:return []- fixes: list[_FixCommit] = []+ fixes: list[FixCommit] = []for record in raw.split(_RECORD_SEP):record = record.strip("\n")if not record:continueheader, _, body = record.partition("\n")- sha, _, subject = header.partition(_FIELD_SEP)+ sha, _, rest = header.partition(_FIELD_SEP)+ committed, _, subject = rest.partition(_FIELD_SEP)if not is_fix_commit(subject):continuepaths = [p for p in _record_paths(body) if p in indexable_files]if paths:- fixes.append(_FixCommit(sha=sha, paths=paths))+ fixes.append(FixCommit(sha=sha, ts=_as_ts(committed), paths=paths))return fixes+def _as_ts(raw: str) -> int:+ try:+ return int(raw.strip())+ except ValueError:+ return 0++def _record_paths(body: str) -> list[str]:"""The ``--name-only`` path lines of one log record, renames resolved."""paths: list[str] = []@@ -205,15 +304,16 @@ def _record_paths(body: str) -> list[str]:# ----------------------------------------------------------------------------def _classify_shapes(repo: Any, shas: list[str]) -> dict[str, str]:- """Map each fix sha to its :mod:`fix_shape` kind.+def _parse_fix_diffs(repo: Any, shas: list[str]) -> dict[str, dict[str, FileDiff]]:+ """Map each fix sha to its parsed ``-U0`` diff, keyed by file path.Batched: one ``git log --no-walk -p`` subprocess per :data:`_SHAPE_BATCH_SIZE`commits rather than a ``git show`` spawn each, which is what keeps the passaffordable on Windows (where process spawn dominates git's own cost).- Failures degrade to an empty map, and the caller then counts the commit.+ Failures degrade to a missing entry, and the caller then treats the commit as+ a code fix."""- shapes: dict[str, str] = {}+ diffs: dict[str, dict[str, FileDiff]] = {}for start in range(0, len(shas), _SHAPE_BATCH_SIZE):batch = shas[start : start + _SHAPE_BATCH_SIZE]try:@@ -228,17 +328,17 @@ def _classify_shapes(repo: Any, shas: list[str]) -> dict[str, str]:except Exception as exc:logger.debug("prior_defect_shape_batch_failed", error=str(exc), commits=len(batch))continue- shapes.update(_parse_shape_batch(raw))- return shapes+ diffs.update(_parse_diff_batch(raw))+ return diffs-def _parse_shape_batch(raw: str) -> dict[str, str]:- """Split a batched ``--format=%x00%H --patch`` log into per-sha shape kinds."""+def _parse_diff_batch(raw: str) -> dict[str, dict[str, FileDiff]]:+ """Split a batched ``--format=%x00%H --patch`` log into per-sha parsed diffs."""# Imported here, not at module scope: ``analysis.change_risk`` imports back# into this package, so a top-level import would close an import cycle.from ...analysis.changed_lines import parse_unified_diff- shapes: dict[str, str] = {}+ diffs: dict[str, dict[str, FileDiff]] = {}for record in raw.split(_RECORD_SEP):record = record.strip("\n")if not record:@@ -247,5 +347,5 @@ def _parse_shape_batch(raw: str) -> dict[str, str]:sha = sha.strip()if len(sha) != 40:continue- shapes[sha] = classify_fix_shape(parse_unified_diff(diff))- return shapes+ diffs[sha] = parse_unified_diff(diff)+ return diffsdiff --git a/packages/core/src/repowise/core/ingestion/git_indexer/records.py b/packages/core/src/repowise/core/ingestion/git_indexer/records.pyindex f5ca87851..adefd8050 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/records.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/records.py@@ -139,6 +139,15 @@ class GitIndexSummary:# for ``upsert_git_commits_bulk``. Empty in rename-tracking mode (which uses# the per-file walk instead of the batched commit index).commit_rows: list[dict] = field(default_factory=list)+ # Per fix-commit x file rows for ``upsert_fix_events_bulk``, plus the+ # committer time of the oldest fix the walk saw (unix seconds). The cutoff+ # rides along so the persist step can prune events that have aged out and+ # keep the stored set equal to what a fresh index at this HEAD produces.+ # ``fix_events_traced`` says the pass actually ran, so a failed trace does+ # not prune rows it never replaced.+ fix_event_rows: list[dict] = field(default_factory=list)+ fix_oldest_ts: int = 0+ fix_events_traced: bool = False# Whole-history git totals captured via cheap ``git rev-list``/``shortlog``# calls that ignore ``commit_limit`` (unlike ``commit_rows``). Persisted to# the Repository row so the stats page reports true project age / commit /diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/szz.py b/packages/core/src/repowise/core/ingestion/git_indexer/szz.pynew file mode 100644index 000000000..be32daad7--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/git_indexer/szz.py@@ -0,0 +1,425 @@+"""SZZ: which commit introduced the bug this fix commit repaired.++The classic SZZ heuristic (Śliwerski-Zimmermann-Zeller): the lines a fix+*deleted* are the buggy lines, so ``git blame`` them at the fix's parent and the+commits that wrote them are the bug-introducing candidates.++Concretely, per ``code_fix`` file:++* take the old-side ranges of the fix's diff (:func:`analysis.changed_lines.+ parse_unified_diff` already produces them);+* one batched ``git blame -w -M --porcelain`` with every range as its own+ ``-L`` at ``<fix>^`` — ``-w`` ignores whitespace-only reformatting, ``-M``+ follows moves inside the file, the two standard SZZ noise filters;+* rank the resulting commits by how many blamed lines each owns.++Blame runs against **full history**, never the fix-detection window: measured bug+latency is 41 to 203 days at the median, so the inducing commit routinely+predates the 180-day window the fix itself was found in.++## Refactor-aware blame++The plain heuristic's dominant error mode, and it is not subtle: in the frozen+48-commit judgment set, *all 14* wrong top candidates were behaviour-preserving+refactors that had simply inherited the lines by moving them. ``-M`` follows+moves within one file; it does nothing for a block lifted from another file, an+import reshuffle, or a rename.++So candidates get a second look, and the question asked is deliberately narrow:+did this candidate *carry the lines it is blamed for through unchanged*? If each+of them appears on both sides of the candidate's own diff, the candidate+relocated that code rather than writing it, and the blame re-runs in a mode that+can see past it: ``-C -C`` copy detection, the mover on ``--ignore-rev``, and the+``-L`` ranges padded outward.++Per-blamed-line, not per-commit, because no real refactor is a byte-exact move.+Measured on this repo's own package splits - the ones the frozen judgments call+"verbatim", "no logic changes" - a 1,131-line move comes back as 1,332 lines: new+module headers, re-sorted imports, an ``__all__``. A whole-commit multiset test+calls every one of them an edit and the mitigation never fires. Asking only about+the lines actually being blamed is both stricter (a candidate that touched one of+them keeps the blame) and the question SZZ is really asking.++The padding is not cosmetic. Copy detection matches a *block* against the+parent's files, so a one-line ``-L`` gives it nothing to match on and it silently+falls back to naming the mover; with a dozen lines of context it finds the+original file and reaches the true author. The extra lines are only ever context+for the match - overlap is still counted over the fix's own lines, so a padded+re-blame cannot inflate a candidate's rank.++Bounded on purpose: only the top few candidates per file are diff-checked, and+the walk re-blames at most twice, so a pathological chain of refactors costs a+fixed handful of subprocesses instead of an unbounded recursion.++Zero LLM, pure git plumbing, deterministic: ties break on committer time then+sha, so the same repo always yields the same ranking.+"""++from __future__ import annotations++import re+import threading+from collections.abc import Callable+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any++import structlog++from .fix_shape import _is_inert++if TYPE_CHECKING:+ from ...analysis.changed_lines import FileDiff++logger = structlog.get_logger(__name__)++__all__ = ["InducingCandidate", "SzzTracer", "rank_candidates"]++# Tuning knobs. All three exist to keep one pathological commit from dominating+# the git phase; raising them costs wall-clock, never correctness.+#+# A mass reorganization blames as "everything, everywhere" and tells you nothing,+# so files past this many changed lines are skipped outright.+MAX_FILE_CHANGED_LOC: int = 500+# ``-L`` ranges per blame call. Past this the command line grows without the+# ranking changing (the tail hunks are a rounding error on the overlap counts).+MAX_RANGES_PER_FILE: int = 20+# How many top candidates get their own diff fetched for the pure-move test,+# and how many times the blame may be re-run after ignoring one.+MAX_REFACTOR_CHECKS: int = 5+MAX_REFACTOR_ROUNDS: int = 2+# Context lines added on each side of a range for the refactor-aware re-blame.+# Copy detection needs a block to match; measured on a 6-function move, three+# lines was already enough, so this is comfortably past the cliff.+REFACTOR_PAD_LINES: int = 15+# A candidate whose own diff is bigger than this is not read at all. Past a+# megabyte the multiset test is decided by generated files, and holding the+# patch in memory costs more than the answer is worth.+MAX_MOVE_CHECK_BYTES: int = 1_000_000++# Porcelain header: ``<sha> <orig-line> <final-line> [<num-lines>]``. Content+# lines are tab-prefixed, so they can never match.+_BLAME_HEADER_RE = re.compile(r"^([0-9a-f]{40}) \d+ (\d+)")+++@dataclass(frozen=True)+class InducingCandidate:+ """One bug-introducing candidate for a fix event.++ *lines* is how many of the fix's deleted lines blame attributes to this+ commit — the overlap that ranks it. *ts* is its committer time (0 when the+ porcelain output did not carry one), kept so a consumer can re-rank by age+ without another git call.+ """++ sha: str+ lines: int+ ts: int++ def as_dict(self) -> dict[str, Any]:+ return {"sha": self.sha, "lines": self.lines, "ts": self.ts}+++def rank_candidates(+ totals: dict[str, tuple[int, int]], *, by: str = "overlap"+) -> list[InducingCandidate]:+ """Order raw ``{sha: (blamed_lines, ts)}`` blame totals into a ranked list.++ ``by="overlap"`` (the shipped ranking) puts the commit that wrote most of the+ buggy lines first; ``by="earliest"`` puts the oldest first, the other ranking+ the SZZ literature uses. Both fall through to the remaining keys, so the+ order is total and content-derived — no run-to-run drift.+ """+ cands = [InducingCandidate(sha, n, ts) for sha, (n, ts) in totals.items()]+ if by == "earliest":+ cands.sort(key=lambda c: (c.ts or 1 << 62, -c.lines, c.sha))+ else:+ cands.sort(key=lambda c: (-c.lines, c.ts, c.sha))+ return cands+++class SzzTracer:+ """Traces fix diffs to bug-introducing commits against one repository.++ Constructed with *get_repo*, a callable returning a gitpython ``Repo`` usable+ from the calling thread — the git indexer runs this pass across its worker+ pool and gitpython handles are not thread-safe on Windows. The candidate-diff+ cache is shared across threads behind a lock, because the same refactor+ commit shows up as a candidate for many files at once.+ """++ def __init__(self, get_repo: Callable[[], Any], *, refactor_aware: bool = True) -> None:+ self._get_repo = get_repo+ self._refactor_aware = refactor_aware+ self._diff_cache: dict[str, tuple[frozenset[str], frozenset[str]]] = {}+ self._lock = threading.Lock()++ # -- public ---------------------------------------------------------++ def trace_file(self, fix_sha: str, path: str, diff: FileDiff) -> list[InducingCandidate]:+ """Ranked inducing candidates for one file of one fix commit.++ Empty when there is nothing to blame: a hunk set whose removed lines are+ all comments or blanks, a file too large to say anything useful about,+ or a blame that failed (the file did not exist at ``fix^``).+ """+ if len(diff.removed) + len(diff.added) > MAX_FILE_CHANGED_LOC:+ return []+ # Deleting only comments and blank lines says nothing about who wrote the+ # bug; the cheapest precision win available without parsing the language.+ if diff.removed and all(_is_inert(line) for line in diff.removed):+ return []++ ranges = diff.old_ranges[:MAX_RANGES_PER_FILE]+ anchored = False+ if not ranges:+ ranges = _anchor_ranges(diff.insert_anchors)+ anchored = bool(ranges)+ if not ranges:+ return []++ # What each blamed line actually says, so the refactor test can ask about+ # the lines a given candidate owns rather than the whole file's.+ texts = _line_texts(diff)++ ignored: list[str] = []+ totals, owners = self._blame(fix_sha, path, ranges, ranges)+ if anchored and not totals:+ # An anchor pair can run one line past the end of the file, which+ # fails the whole call. Retry on the anchors alone.+ ranges = [(start, start) for start, _ in ranges]+ totals, owners = self._blame(fix_sha, path, ranges, ranges)+ for _ in range(MAX_REFACTOR_ROUNDS):+ if not self._refactor_aware or not totals:+ break+ movers = self._movers(totals, owners, texts, ignored)+ if not movers:+ break+ ignored.extend(movers)+ retraced, retraced_owners = self._blame(+ fix_sha,+ path,+ ranges,+ self._padded(fix_sha, path, ranges),+ ignored=ignored,+ detect_copies=True,+ )+ if not retraced:+ # Ignoring everything blamed can leave git with nothing to+ # attribute; the pre-walk answer beats an empty one.+ break+ totals, owners = retraced, retraced_owners++ return rank_candidates(totals)++ # -- git ------------------------------------------------------------++ def _blame(+ self,+ fix_sha: str,+ path: str,+ ranges: list[tuple[int, int]],+ query_ranges: list[tuple[int, int]],+ *,+ ignored: list[str] | None = None,+ detect_copies: bool = False,+ ) -> tuple[dict[str, tuple[int, int]], dict[int, str]]:+ """Blame *ranges* at ``fix^``: totals plus which commit owns which line.++ Returns ``({inducing_sha: (blamed_lines, committer_ts)}, {line: sha})``.+ The per-line map is what lets the refactor test ask a candidate about the+ lines it is actually blamed for instead of every line the fix deleted.++ *query_ranges* is what git is asked to blame and *ranges* is what counts:+ the refactor-aware pass widens the former for copy detection while+ keeping attribution scored over the fix's own lines only.+ """+ args: list[str] = ["-w", "-M", "--porcelain"]+ if detect_copies:+ # Twice: look for the line's origin in files the commit touched, and+ # then in the parent commit at large. Once is not enough for the+ # module-split case, which is the common one.+ args += ["-C", "-C"]+ for start, end in query_ranges:+ args += ["-L", f"{start},{end}"]+ for rev in ignored or ():+ args += ["--ignore-rev", rev]+ try:+ raw = self._get_repo().git.blame(*args, f"{fix_sha}^", "--", path)+ except Exception as exc:+ logger.debug("szz_blame_failed", fix=fix_sha[:12], path=path, error=str(exc))+ return {}, {}++ counted = {line for start, end in ranges for line in range(start, end + 1)}+ hits: dict[str, tuple[int, int]] = {}+ owners: dict[int, str] = {}+ current: str | None = None+ for line in raw.splitlines():+ match = _BLAME_HEADER_RE.match(line)+ if match is not None:+ current = match.group(1)+ blamed = int(match.group(2))+ count, ts = hits.get(current, (0, 0))+ # Context lines from a padded query still need their commit+ # header parsed (the committer-time follows it), but they must+ # not add to anyone's overlap.+ if blamed in counted:+ owners[blamed] = current+ count += 1+ hits[current] = (count, ts)+ elif current is not None and line.startswith("committer-time "):+ count, _ = hits[current]+ _, _, value = line.partition(" ")+ hits[current] = (count, _as_int(value))+ return {sha: v for sha, v in hits.items() if v[0] > 0}, owners++ def _padded(+ self, fix_sha: str, path: str, ranges: list[tuple[int, int]]+ ) -> list[tuple[int, int]]:+ """*ranges* widened by :data:`REFACTOR_PAD_LINES`, clamped to the file.++ The clamp matters: ``git blame -L`` fails outright on a range that runs+ past the end of the file, and losing the whole re-blame to an off-by-a-few+ would quietly turn refactor-awareness off on every short file.+ """+ limit = self._line_count(fix_sha, path)+ padded: list[tuple[int, int]] = []+ for start, end in ranges:+ low = max(1, start - REFACTOR_PAD_LINES)+ high = end + REFACTOR_PAD_LINES+ if limit:+ high = min(high, limit)+ padded.append((low, max(low, high)))+ return padded++ def _line_count(self, fix_sha: str, path: str) -> int:+ """Lines in *path* at ``fix^``, or 0 when it cannot be read."""+ try:+ blob = self._get_repo().git.show(f"{fix_sha}^:{path}")+ except Exception:+ return 0+ return blob.count("\n") + (0 if blob.endswith("\n") or not blob else 1)++ def _movers(+ self,+ totals: dict[str, tuple[int, int]],+ owners: dict[int, str],+ texts: dict[int, str],+ already_ignored: list[str],+ ) -> list[str]:+ """The top candidates that carried their blamed lines through, not wrote them."""+ movers = []+ for cand in rank_candidates(totals)[:MAX_REFACTOR_CHECKS]:+ if cand.sha in already_ignored:+ continue+ owned = {+ texts[line]+ for line, sha in owners.items()+ if sha == cand.sha and texts.get(line) and not _is_inert(texts[line])+ }+ if owned and self._relocated(cand.sha, owned):+ movers.append(cand.sha)+ return movers++ def _relocated(self, sha: str, owned: set[str]) -> bool:+ """Whether *sha* moved every one of the lines it is blamed for.++ A line that appears on BOTH sides of a commit's diff went out of one+ place and back into another unchanged: relocated, not authored. Requiring+ it of every line the candidate owns keeps the test conservative - a+ candidate that actually wrote any of the blamed lines keeps the blame,+ and the mitigation cannot run away with a commit that did real work.++ Judged across the commit's whole diff, not the file being blamed: the+ common refactor lifts a block out of one file and into another, which+ reads as a plain insertion in the receiving file and would look exactly+ like authorship if each side were judged alone.+ """+ removed, added = self._line_sets(sha)+ return all(line in removed and line in added for line in owned)++ def _line_sets(self, sha: str) -> tuple[frozenset[str], frozenset[str]]:+ """``(removed, added)`` line text for a commit's whole diff, cached.++ Cached per sha because one refactor commit turns up as a candidate for+ many files of many fixes, and its diff is the expensive part.+ """+ with self._lock:+ cached = self._diff_cache.get(sha)+ if cached is not None:+ return cached++ result = self._compute_line_sets(sha)+ with self._lock:+ self._diff_cache[sha] = result+ return result++ def _compute_line_sets(self, sha: str) -> tuple[frozenset[str], frozenset[str]]:+ # Imported here, not at module scope: ``analysis.change_risk`` imports+ # back into this package, so a top-level import would close a cycle.+ from ...analysis.changed_lines import parse_unified_diff++ empty: tuple[frozenset[str], frozenset[str]] = (frozenset(), frozenset())+ try:+ # ``--no-renames`` on purpose, the opposite of everywhere else here.+ # With rename detection on, git collapses a moved file into a rename+ # header and its lines appear on NEITHER side of the diff, so the+ # carried-through test can never see the very moves it exists to+ # catch. Off, a move is a full delete plus a full add, which is+ # exactly the shape the test reads.+ raw = self._get_repo().git.show("-U0", "--no-renames", "--no-color", "--format=", sha)+ except Exception as exc:+ logger.debug("szz_move_check_failed", sha=sha[:12], error=str(exc))+ return empty+ if not raw.strip() or len(raw) > MAX_MOVE_CHECK_BYTES:+ return empty++ files = parse_unified_diff(raw)+ return (+ frozenset(line.strip() for f in files.values() for line in f.removed if line.strip()),+ frozenset(line.strip() for f in files.values() for line in f.added if line.strip()),+ )+++def _line_texts(diff: FileDiff) -> dict[int, str]:+ """``{old-side line number: its text}`` for the lines the fix deleted.++ A ``-U0`` diff lists old-side ranges and removed lines in the same order, and+ a range of n old lines is exactly n removed lines, so the two zip positionally.+ That mapping is what lets a blame result be read back as content rather than+ line numbers.+ """+ texts: dict[int, str] = {}+ index = 0+ for start, end in diff.old_ranges:+ for line in range(start, end + 1):+ if index < len(diff.removed):+ texts[line] = diff.removed[index].strip()+ index += 1+ return texts+++def _anchor_ranges(anchors: list[int]) -> list[tuple[int, int]]:+ """Blame ranges for a fix that only ADDED lines.++ A fix that deletes nothing has no buggy line to blame, which on squash-merge+ repos is a large share of them (a fifth of repowise's, measured): the repair+ is a guard, an early return, a missing branch. The code it is guarding is+ still evidence, so blame straddles the insertion point - the line above and+ the line below - rather than giving up on the commit entirely.++ Attribution from an anchor is weaker than from a deleted line, and it stays+ distinguishable downstream: these rows persist an empty ``old_ranges_json``+ beside their candidates.+ """+ ranges = []+ for anchor in sorted(set(anchors))[:MAX_RANGES_PER_FILE]:+ start = max(1, anchor)+ ranges.append((start, start + 1))+ return ranges+++def _as_int(value: str) -> int:+ try:+ return int(value.strip())+ except ValueError:+ return 0diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.pyindex ed02b621d..51ce99ad3 100644--- a/packages/core/src/repowise/core/persistence/crud/git.py+++ b/packages/core/src/repowise/core/persistence/crud/git.py@@ -6,10 +6,13 @@ every public name, so existing imports are unaffected.from __future__ import annotations-from sqlalchemy import delete, func, select, text+from datetime import datetime++from sqlalchemy import delete, func, or_, select, textfrom sqlalchemy.ext.asyncio import AsyncSessionfrom ..models import (+ FixEvent,GitCommit,GitFunctionBlame,GitMetadata,@@ -282,9 +285,7 @@ async def count_git_commits() -> int:"""Count persisted commits for a repository."""stmt = (- select(func.count())- .select_from(GitCommit)- .where(GitCommit.repository_id == repository_id)+ select(func.count()).select_from(GitCommit).where(GitCommit.repository_id == repository_id))clause = _commit_authorship_clause(authorship)if clause is not None:@@ -446,3 +447,114 @@ async def get_git_function_blames(q = q.order_by(GitFunctionBlame.mod_count.desc()).limit(limit).offset(offset)result = await session.execute(q)return list(result.scalars().all())+++# ---------------------------------------------------------------------------+# FixEvent CRUD (per fix-commit x file, with SZZ candidates)+# ---------------------------------------------------------------------------+++def _update_fix_event(existing: FixEvent, row: dict) -> None:+ for key, val in row.items():+ # ``fix_sha`` + ``file_path`` are the natural key — never reassigned.+ if key not in ("id", "repository_id", "fix_sha", "file_path") and hasattr(existing, key):+ setattr(existing, key, val)+ existing.updated_at = _now_utc()+++async def upsert_fix_events_bulk(+ session: AsyncSession,+ repository_id: str,+ rows: list[dict],+) -> None:+ """Bulk upsert fix events (keyed ``repository_id`` + ``fix_sha`` + ``file_path``).++ Idempotent, so re-running an index or replaying the same update twice+ converges on the same table rather than duplicating rows.+ """+ await _batch_upsert_keyed(+ session,+ FixEvent,+ rows,+ prefilter=(FixEvent.repository_id == repository_id,),+ item_key_fn=lambda row: (row.get("fix_sha", ""), row.get("file_path", "")),+ row_key_fn=lambda row: (row.fix_sha, row.file_path),+ update_fn=_update_fix_event,+ insert_fn=lambda row: FixEvent(+ id=_new_uuid(),+ repository_id=repository_id,+ **{+ k: v+ for k, v in row.items()+ if k not in ("id", "repository_id") and hasattr(FixEvent, k)+ },+ ),+ batch_size=_BATCH_SIZE,+ )+++async def prune_fix_events_before(+ session: AsyncSession, repository_id: str, cutoff: datetime+) -> int:+ """Drop fix events that have aged out of the trailing defect window.++ The full index seeds exactly the fix commits inside the window; updates+ append newer ones. Without this the persisted set would keep growing past+ the window's trailing edge and diverge from what a fresh index produces —+ which is precisely what ``validate_p2_incremental.py`` asserts against.+ Rows are pruned by their own ``committed_at``, never decayed in place.+ """+ result = await session.execute(+ delete(FixEvent).where(+ FixEvent.repository_id == repository_id,+ # A NULL timestamp (an unreadable ``%ct``) would otherwise make the+ # row immortal and invisible to every window.+ or_(FixEvent.committed_at < cutoff, FixEvent.committed_at.is_(None)),+ )+ )+ await session.flush()+ return int(result.rowcount or 0)+++async def prune_fix_events_for_missing_paths(+ session: AsyncSession, repository_id: str, tracked_paths: set[str]+) -> int:+ """Drop fix events for files that are no longer tracked.++ A full index only ever sees files that exist at HEAD, so it never produces+ these rows; an update, which appends and never revisits, keeps them forever+ once a file is deleted. Without this the two paths diverge by exactly the+ repo's deletions, which is what ``validate_p2_incremental.py`` caught.++ Diffs the stored paths in Python rather than sending the whole tracked set+ into a ``NOT IN``: the stored set is hundreds of paths, the tracked set is+ thousands.+ """+ result = await session.execute(+ select(FixEvent.file_path).where(FixEvent.repository_id == repository_id).distinct()+ )+ stale = [path for path in result.scalars().all() if path not in tracked_paths]+ if not stale:+ return 0+ deleted = await session.execute(+ delete(FixEvent).where(+ FixEvent.repository_id == repository_id,+ FixEvent.file_path.in_(stale),+ )+ )+ await session.flush()+ return int(deleted.rowcount or 0)+++async def get_fix_event_shas(session: AsyncSession, repository_id: str) -> set[str]:+ """Every fix sha already persisted for a repo.++ Bounds the incremental capture: an update traces only the fix commits not in+ this set. A sha set rather than a "newest committed_at" cutoff because a+ merge can land fix commits older than rows already stored, and a timestamp+ bound would skip those forever.+ """+ result = await session.execute(+ select(FixEvent.fix_sha).where(FixEvent.repository_id == repository_id).distinct()+ )+ return {sha for sha in result.scalars().all() if sha}diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex b9f254f8a..40105e15c 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -56,9 +56,7 @@ class Repository(Base):# from that sample — otherwise a multi-year repo reads as a few months old# (issue #730). NULL until the first index writes them / for non-git repos.total_commit_count: Mapped[int | None] = mapped_column(Integer, nullable=True)- first_commit_at: Mapped[datetime | None] = mapped_column(- DateTime(timezone=True), nullable=True- )+ first_commit_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)# All-time unique authors (mailmap-folded) and the founding author's name.# Contributor count shares the #730 bug when read off the bounded sample;# the founder rides along free (the root commit is already loaded for the@@ -566,6 +564,72 @@ class GitCommit(Base):)+class FixEvent(Base):+ """One bug-fix commit's effect on one file, with its bug-introducing candidates.++ ``GitMetadata.prior_defect_count`` is the aggregate of these rows; this table+ is the evidence underneath it. Each row records what a fix commit did to one+ file (:mod:`ingestion.git_indexer.fix_shape` kind, the old-side line ranges it+ replaced, how many lines it changed) and, for ``code_fix`` rows, the ranked+ commits that ``git blame`` puts on those lines at ``fix^`` — the SZZ+ bug-introducing candidates.++ ``committed_at`` is load-bearing. Rows are stored **undecayed**: every recency+ weight downstream (biomarker mass, bug-magnet flag, rollups) is derived at read+ time from this column, so changing a half-life is a read-time decision and+ never needs a reindex.++ Joins: ``fix_sha`` and each inducing sha to :class:`GitCommit` (which already+ carries agent provenance), and ``file_path`` + ``old_ranges_json`` to+ :class:`WikiSymbol` / :class:`GitFunctionBlame` line ranges.++ Retention mirrors the ``prior_defect`` window: a full index seeds the trailing+ window, updates append newer fix commits and prune rows that have aged out, so+ the table always holds exactly the window a fresh index would produce.+ """++ __tablename__ = "fix_events"+ __table_args__ = (+ UniqueConstraint("repository_id", "fix_sha", "file_path", name="uq_fix_event"),+ Index("ix_fix_events_repo_path", "repository_id", "file_path"),+ Index("ix_fix_events_repo_time", "repository_id", "committed_at"),+ )++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ fix_sha: Mapped[str] = mapped_column(String(40), nullable=False)+ file_path: Mapped[str] = mapped_column(Text, nullable=False)++ # fix_shape kind for the WHOLE commit, repeated on each of its file rows:+ # the classification is a property of the diff, not of one file in it.+ shape_kind: Mapped[str] = mapped_column(String(16), nullable=False, default="code_fix")++ # Inclusive ``[[start, end], ...]`` spans on the PRE-fix file — the space+ # ``git blame fix^`` is keyed in. Empty for a pure insertion (nothing to blame).+ old_ranges_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ changed_loc: Mapped[int] = mapped_column(Integer, nullable=False, default=0)++ # Ranked SZZ candidates, ``[{"sha", "lines", "ts"}, ...]``, most blamed lines+ # first. Stored ranked but complete, so a different ranking (earliest-commit,+ # say) stays a read-time re-sort. Empty for non-code_fix rows, for pure+ # insertions, and for fixes the tracer skipped (comment-only or oversized).+ inducing_shas_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")++ # Per-bucket changed-line counts from the fix taxonomy. Empty until Phase 5.+ taxonomy_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")++ committed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )++class GitFunctionBlame(Base):"""Per-function blame rollup: function-granular git signals derived from theper-line ``BlameIndex`` during FULL-tier health analysis.diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex ddd7827ed..069c1fc42 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -24,6 +24,10 @@ from collections.abc import Callablefrom pathlib import Pathfrom typing import Any+import structlog++logger = structlog.get_logger(__name__)+LogFn = Callable[[str], None]@@ -551,6 +555,10 @@ async def persist_incremental_commits(session: Any, repo_id: str, repo_path: Anyrepo_path,commit_limit=cfg.get("commit_limit"),follow_renames=cfg.get("follow_renames", False),+ # The fix-event capture walks the tracked-file set itself, so without+ # the repo's excludes an update would store events for files a full+ # index never sees, and they would never age out.+ exclude_patterns=cfg.get("exclude_patterns"),)newest = await get_latest_commit_committed_at(session, repo_id)since_ts: int | None = None@@ -578,6 +586,45 @@ async def persist_incremental_commits(session: Any, repo_id: str, repo_path: Anyfirst_commit_author=totals.first_commit_author,)+ await persist_incremental_fix_events(session, repo_id, indexer)+++async def persist_incremental_fix_events(session: Any, repo_id: str, indexer: Any) -> None:+ """Trace + upsert ``fix_events`` for fix commits this index has not seen.++ Two halves, and both are needed for an update to converge on what a fresh+ index would produce: append the fix commits missing from the table, then drop+ the ones that have aged out of the trailing defect window. Without the prune+ the stored set only ever grows past the window's trailing edge; without the+ append it goes stale. Failure-isolated, like every other git-phase refresh.+ """+ from repowise.core.persistence.crud import (+ get_fix_event_shas,+ prune_fix_events_before,+ prune_fix_events_for_missing_paths,+ upsert_fix_events_bulk,+ )++ try:+ known = await get_fix_event_shas(session, repo_id)+ rows, oldest_ts, tracked = await asyncio.to_thread(+ indexer.capture_new_fix_events, known_shas=known+ )+ except Exception as exc:+ logger.debug("incremental_fix_events_failed", error=str(exc))+ return++ if rows:+ await upsert_fix_events_bulk(session, repo_id, rows)+ # A zero cutoff means the walk or the trace failed; pruning then would drop+ # rows nothing replaced.+ if oldest_ts:+ from datetime import UTC, datetime++ await prune_fix_events_before(session, repo_id, datetime.fromtimestamp(oldest_ts, tz=UTC))+ if tracked:+ await prune_fix_events_for_missing_paths(session, repo_id, tracked)+async def refresh_external_systems(session: Any,diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 7283f6f7a..c7c375497 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -670,7 +670,9 @@ async def persist_git(result: Any, session: Any, repo_id: str) -> None:``(repo_id, sha)`` — safe to call incrementally and on resume."""from repowise.core.persistence.crud import (+ prune_fix_events_before,update_repo_git_totals,+ upsert_fix_events_bulk,upsert_git_commits_bulk,upsert_git_metadata_bulk,)@@ -685,6 +687,18 @@ async def persist_git(result: Any, session: Any, repo_id: str) -> None:if commit_rows:await upsert_git_commits_bulk(session, repo_id, commit_rows)+ # Per fix-commit x file rows (with their SZZ candidates). The prune keeps a+ # re-index of an already-indexed repo from leaving behind events that have+ # since aged out of the defect window.+ fix_event_rows = getattr(summary, "fix_event_rows", None)+ if fix_event_rows:+ await upsert_fix_events_bulk(session, repo_id, fix_event_rows)+ oldest_ts = getattr(summary, "fix_oldest_ts", 0)+ if oldest_ts and getattr(summary, "fix_events_traced", False):+ from datetime import UTC, datetime++ await prune_fix_events_before(session, repo_id, datetime.fromtimestamp(oldest_ts, tz=UTC))+# Whole-history totals (true age / commit / contributor counts) also ride on# the summary — stamp them on the Repository row so the stats page reads them# instead of deriving them from the bounded ``git_commits`` sample (#730).diff --git a/tests/unit/ingestion/test_fix_events_szz.py b/tests/unit/ingestion/test_fix_events_szz.pynew file mode 100644index 000000000..eadf7ce39--- /dev/null+++ b/tests/unit/ingestion/test_fix_events_szz.py@@ -0,0 +1,343 @@+"""SZZ tracing and ``fix_events`` row building, on real temporary repositories.++Blame is the whole point of this pass, and blame has no useful mock: the things+that go wrong (``-M`` following a move, ``--ignore-rev`` walking through a+refactor, a range that predates the file) are git behaviours, not ours. So these+build small repos and run the real thing.+"""++from __future__ import annotations++import json++import pytest++from repowise.core.ingestion.git_indexer import GitIndexer, GitIndexTier+from repowise.core.ingestion.git_indexer.fix_events import build_fix_events+from repowise.core.ingestion.git_indexer.prior_defects import collect_fix_commits+from repowise.core.ingestion.git_indexer.szz import SzzTracer, rank_candidates+++def _write(repo, tmp_path, name, content, message):+ (tmp_path / name).write_text(content)+ repo.index.add([name])+ return repo.index.commit(message).hexsha+++def _helpers(count: int = 6) -> str:+ """A block big enough for git's copy detection to recognise when it moves.++ Copy detection matches on content, so a two-line function is below its+ threshold and a move of it is indistinguishable from authorship. Real+ refactors move real blocks; the fixtures have to as well.+ """+ return "".join(+ f"def helper_{i}(alpha, beta):\n return alpha + beta + {i}\n\n" for i in range(count)+ )+++def _repo(tmp_path):+ import git as gitpython++ return gitpython.Repo.init(tmp_path)+++def _tracer(tmp_path, *, refactor_aware: bool = True) -> SzzTracer:+ import git as gitpython++ return SzzTracer(lambda: gitpython.Repo(tmp_path), refactor_aware=refactor_aware)+++def _walk(tmp_path, paths):+ import git as gitpython++ return collect_fix_commits(gitpython.Repo(tmp_path), set(paths), as_of_ts=None)+++def _file_diff(fix_sha: str, tmp_path, path: str):+ import git as gitpython++ from repowise.core.analysis.changed_lines import parse_unified_diff++ raw = gitpython.Repo(tmp_path).git.show("-U0", "--no-color", "--format=", fix_sha)+ return parse_unified_diff(raw)[path]+++# ---------------------------------------------------------------------------+# The blame itself+# ---------------------------------------------------------------------------+++class TestSzzTracer:+ def test_blames_the_commit_that_wrote_the_fixed_line(self, tmp_path) -> None:+ repo = _repo(tmp_path)+ _write(repo, tmp_path, "a.py", "def f():\n return 1\n", "feat: add f")+ culprit = _write(+ repo, tmp_path, "a.py", "def f():\n return None\n", "feat: return nothing"+ )+ fix = _write(repo, tmp_path, "a.py", "def f():\n return 0\n", "fix: bad return")++ cands = _tracer(tmp_path).trace_file(fix, "a.py", _file_diff(fix, tmp_path, "a.py"))++ assert cands, "expected an inducing candidate"+ assert cands[0].sha == culprit+ assert cands[0].lines == 1+ assert cands[0].ts > 0++ def test_pure_insertion_is_blamed_at_its_anchor(self, tmp_path) -> None:+ """A fix that only ADDS lines has no deleted line, so blame the anchor.++ A guard or an early return deletes nothing, which on squash-merge repos+ is a fifth of all fixes. The code it was inserted next to is still the+ evidence available, and the row stays distinguishable downstream by its+ empty ``old_ranges``.+ """+ repo = _repo(tmp_path)+ _write(repo, tmp_path, "a.py", "def f():\n return 1\n", "feat: add f")+ anchor_author = _write(+ repo, tmp_path, "a.py", "def f():\n x = 2\n return 1\n", "feat: add x"+ )+ fix = _write(+ repo, tmp_path, "a.py", "def f():\n x = 2\n y = 3\n return 1\n", "fix: add y"+ )++ diff = _file_diff(fix, tmp_path, "a.py")+ assert diff.old_ranges == []+ assert diff.insert_anchors == [2]+ # Both anchor lines are blamed, one each, so which one ranks first is a+ # tie-break rather than a claim. The contract is that the code the fix+ # was inserted next to shows up at all.+ cands = _tracer(tmp_path).trace_file(fix, "a.py", diff)+ assert anchor_author in {c.sha for c in cands}++ def test_a_brand_new_file_has_nothing_to_blame(self, tmp_path) -> None:+ """The anchor fallback cannot invent history that does not exist yet."""+ repo = _repo(tmp_path)+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")+ fix = _write(repo, tmp_path, "b.py", "y = 2\n", "fix: add b")++ assert _tracer(tmp_path).trace_file(fix, "b.py", _file_diff(fix, tmp_path, "b.py")) == []++ def test_comment_only_deletions_are_skipped(self, tmp_path) -> None:+ repo = _repo(tmp_path)+ _write(repo, tmp_path, "a.py", "# note\nx = 1\n", "feat: add a")+ fix = _write(repo, tmp_path, "a.py", "# fixed note\nx = 1\n", "fix: comment")++ assert _tracer(tmp_path).trace_file(fix, "a.py", _file_diff(fix, tmp_path, "a.py")) == []++ def test_oversized_file_diff_is_skipped(self, tmp_path) -> None:+ """A mass rewrite blames as 'everyone, everywhere' and is left untraced."""+ repo = _repo(tmp_path)+ _write(repo, tmp_path, "a.py", "".join(f"x{i} = {i}\n" for i in range(400)), "feat: add a")+ fix = _write(+ repo, tmp_path, "a.py", "".join(f"y{i} = {i}\n" for i in range(400)), "fix: rewrite"+ )++ assert _tracer(tmp_path).trace_file(fix, "a.py", _file_diff(fix, tmp_path, "a.py")) == []++ def test_refactor_aware_blame_walks_through_a_cross_file_move(self, tmp_path) -> None:+ """A commit that only relocated the line must not be named as its author.++ This is the failure mode the frozen judgment set was made of: every one+ of its 14 wrong calls was a behaviour-preserving refactor that inherited+ the buggy line by moving it. ``-M`` covers moves inside one file; lifting+ a block from one file into another is what it cannot follow, so that is+ what this builds.+ """+ block = _helpers()+ repo = _repo(tmp_path)+ _write(repo, tmp_path, "old.py", "keep = 1\n", "feat: add old")+ culprit = _write(repo, tmp_path, "old.py", "keep = 1\n\n\n" + block, "feat: add helpers")+ # The block moves to new.py verbatim. Across the commit, nothing is written.+ (tmp_path / "old.py").write_text("keep = 1\n")+ (tmp_path / "new.py").write_text(block)+ repo.index.add(["old.py", "new.py"])+ mover = repo.index.commit("refactor: split out the helpers").hexsha+ fix = _write(+ repo,+ tmp_path,+ "new.py",+ block.replace("alpha + beta + 3\n", "alpha + beta + 33\n"),+ "fix: off by one",+ )++ diff = _file_diff(fix, tmp_path, "new.py")+ naive = _tracer(tmp_path, refactor_aware=False).trace_file(fix, "new.py", diff)+ aware = _tracer(tmp_path, refactor_aware=True).trace_file(fix, "new.py", diff)++ assert naive[0].sha == mover, "baseline should blame the refactor"+ assert aware[0].sha == culprit, "refactor-aware blame should reach the real author"+ assert all(c.sha != mover for c in aware)++ def test_a_commit_that_edits_while_moving_keeps_the_blame(self, tmp_path) -> None:+ """The multiset test is the guard: change a line and you own it."""+ block = _helpers()+ repo = _repo(tmp_path)+ _write(repo, tmp_path, "old.py", "keep = 1\n", "feat: add old")+ _write(repo, tmp_path, "old.py", "keep = 1\n\n\n" + block, "feat: add helpers")+ (tmp_path / "old.py").write_text("keep = 1\n")+ (tmp_path / "new.py").write_text(block.replace("beta + 3\n", "beta + 99\n"))+ repo.index.add(["old.py", "new.py"])+ editor = repo.index.commit("refactor: split out the helpers, and tweak one").hexsha+ fix = _write(+ repo, tmp_path, "new.py", block.replace("beta + 3\n", "beta + 4\n"), "fix: off by one"+ )++ aware = _tracer(tmp_path).trace_file(fix, "new.py", _file_diff(fix, tmp_path, "new.py"))+ assert aware[0].sha == editor++ def test_missing_file_at_parent_yields_no_candidates(self, tmp_path) -> None:+ """A fix commit that also creates the file has nothing to blame at ``fix^``."""+ repo = _repo(tmp_path)+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")+ fix = _write(repo, tmp_path, "b.py", "y = 2\n", "fix: add b")++ import git as gitpython++ from repowise.core.analysis.changed_lines import FileDiff++ gitpython.Repo(tmp_path) # sanity: repo is readable+ fabricated = FileDiff(path="b.py", old_ranges=[(1, 1)], removed=["y = 1"])+ assert _tracer(tmp_path).trace_file(fix, "b.py", fabricated) == []+++class TestRankCandidates:+ def test_overlap_ranking_prefers_the_most_blamed_lines(self) -> None:+ ranked = rank_candidates({"a" * 40: (1, 100), "b" * 40: (5, 200)})+ assert [c.sha[0] for c in ranked] == ["b", "a"]++ def test_earliest_ranking_prefers_the_oldest_commit(self) -> None:+ ranked = rank_candidates({"a" * 40: (1, 100), "b" * 40: (5, 200)}, by="earliest")+ assert [c.sha[0] for c in ranked] == ["a", "b"]++ def test_ranking_is_total_and_deterministic(self) -> None:+ """Equal overlap and equal time still order the same way every run."""+ totals = {"b" * 40: (2, 50), "a" * 40: (2, 50)}+ assert rank_candidates(totals) == rank_candidates(dict(reversed(list(totals.items()))))+++# ---------------------------------------------------------------------------+# Row building+# ---------------------------------------------------------------------------+++class TestBuildFixEvents:+ def test_one_row_per_fix_commit_and_file(self, tmp_path) -> None:+ import git as gitpython++ repo = _repo(tmp_path)+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")+ (tmp_path / "b.py").write_text("y = 1\n")+ (tmp_path / "a.py").write_text("x = 2\n")+ repo.index.add(["a.py", "b.py"])+ repo.index.commit("fix: correct both")++ walk = _walk(tmp_path, ["a.py", "b.py"])+ rows = build_fix_events(walk, lambda: gitpython.Repo(tmp_path))++ assert [r["file_path"] for r in rows] == ["a.py", "b.py"]+ assert {r["shape_kind"] for r in rows} == {"code_fix"}+ assert all(r["committed_at"] is not None for r in rows)+ # a.py replaced a line, so it carries an old-side range; b.py is new.+ by_path = {r["file_path"]: r for r in rows}+ assert json.loads(by_path["a.py"]["old_ranges_json"]) == [[1, 1]]+ assert json.loads(by_path["b.py"]["old_ranges_json"]) == []+ assert by_path["a.py"]["changed_loc"] == 2++ def test_non_code_fixes_keep_their_row_but_are_never_blamed(self, tmp_path) -> None:+ import git as gitpython++ repo = _repo(tmp_path)+ _write(repo, tmp_path, "README.md", "hello\n", "docs: add readme")+ _write(repo, tmp_path, "README.md", "hello there\n", "fix: wrong wording")++ walk = _walk(tmp_path, ["README.md"])+ rows = build_fix_events(walk, lambda: gitpython.Repo(tmp_path))++ assert len(rows) == 1+ assert rows[0]["shape_kind"] == "doc_only"+ assert rows[0]["inducing_shas_json"] == "[]"++ def test_rows_are_ordered_deterministically(self, tmp_path) -> None:+ import git as gitpython++ repo = _repo(tmp_path)+ for name in ("c.py", "b.py", "a.py"):+ _write(repo, tmp_path, name, "x = 1\n", f"feat: add {name}")+ for name in ("c.py", "b.py", "a.py"):+ (tmp_path / name).write_text("x = 2\n")+ repo.index.add(["a.py", "b.py", "c.py"])+ repo.index.commit("fix: bump all three")++ rows = build_fix_events(+ _walk(tmp_path, ["a.py", "b.py", "c.py"]), lambda: gitpython.Repo(tmp_path)+ )+ assert rows == sorted(rows, key=lambda r: (r["fix_sha"], r["file_path"]))+++# ---------------------------------------------------------------------------+# Full index + incremental capture+# ---------------------------------------------------------------------------+++async def test_index_repo_emits_fix_events_and_window_boundary(tmp_path) -> None:+ repo = _repo(tmp_path)+ _write(repo, tmp_path, "a.py", "def f():\n return None\n", "feat: add f")+ _write(repo, tmp_path, "a.py", "def f():\n return 0\n", "fix: bad return")++ summary, _ = await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_repo("repo1")++ assert len(summary.fix_event_rows) == 1+ row = summary.fix_event_rows[0]+ assert row["file_path"] == "a.py"+ assert json.loads(row["inducing_shas_json"])[0]["lines"] == 1+ assert summary.fix_oldest_ts > 0+ assert summary.fix_events_traced is True+++async def test_capture_new_fix_events_skips_known_commits(tmp_path) -> None:+ """The update path traces only the fix commits it has not already stored.++ Skipping by sha rather than by timestamp is what makes an update converge on+ a full index: this asserts the known commit is gone and the new one arrives,+ with the window boundary still reported so the caller can prune.+ """+ repo = _repo(tmp_path)+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")+ first = _write(repo, tmp_path, "a.py", "x = 2\n", "fix: first")+ second = _write(repo, tmp_path, "a.py", "x = 3\n", "fix: second")++ indexer = GitIndexer(tmp_path, tier=GitIndexTier.FULL)++ everything, oldest, tracked = indexer.capture_new_fix_events()+ assert {r["fix_sha"] for r in everything} == {first, second}+ assert oldest > 0+ assert tracked == {"a.py"}++ new_only, oldest_again, _ = indexer.capture_new_fix_events(known_shas={first})+ assert {r["fix_sha"] for r in new_only} == {second}+ # The cutoff is taken before the skip, so narrowing the trace must not move it.+ assert oldest_again == oldest+++async def test_update_capture_matches_a_full_index(tmp_path) -> None:+ """Seed at an old commit, step forward, and land on the full-index answer.++ The miniature of ``validate_p2_incremental.py``: whatever route the rows+ take, the set has to be the one a fresh index at this HEAD would produce.+ """+ repo = _repo(tmp_path)+ _write(repo, tmp_path, "a.py", "x = 1\n", "feat: add a")+ _write(repo, tmp_path, "a.py", "x = 2\n", "fix: first")+ indexer = GitIndexer(tmp_path, tier=GitIndexTier.FULL)+ seeded, _, _ = indexer.capture_new_fix_events()++ _write(repo, tmp_path, "a.py", "x = 3\n", "fix: second")+ incremental, _, _ = indexer.capture_new_fix_events(known_shas={r["fix_sha"] for r in seeded})+ merged = sorted(seeded + incremental, key=lambda r: (r["fix_sha"], r["file_path"]))++ summary, _ = await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_repo("repo1")+ assert merged == summary.fix_event_rowsdiff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.pyindex 71a517173..979b37291 100644--- a/tests/unit/persistence/test_models.py+++ b/tests/unit/persistence/test_models.py@@ -302,6 +302,7 @@ def test_base_includes_all_models():"git_metadata","git_commits","git_function_blame",+ "fix_events","dead_code_findings","decision_records","decision_evidence",diff --git a/tests/unit/test_git_indexer.py b/tests/unit/test_git_indexer.pyindex f1065d6ff..3df6b1b34 100644--- a/tests/unit/test_git_indexer.py+++ b/tests/unit/test_git_indexer.py@@ -539,7 +539,7 @@ class TestPriorDefectCount:for i, (subject, paths) in enumerate(records):sha = f"{i:040d}"body = "\n".join(paths)- chunks.append(f"\x00{sha}\x1f{subject}\n{body}")+ chunks.append(f"\x00{sha}\x1f{1_700_000_000 - i}\x1f{subject}\n{body}")patches[sha] = (diffs or {}).get(i, self._code_diff(paths))log_out = "\n".join(chunks)@@ -645,7 +645,7 @@ class TestPriorDefectCount:return "PRIORSHA"if "--no-walk" in args:raise RuntimeError("git exploded")- return "\x00" + "0" * 40 + "\x1ffix: crash\nsrc/app.py"+ return "\x00" + "0" * 40 + "\x1f1700000000\x1ffix: crash\nsrc/app.py"repo.git.log.side_effect = _logresult = compute_prior_defects(repo, {"src/app.py"}, as_of_ts=1_700_000_000.0)