Skip to content

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

feat(indexing): make Git history sampling reliable (#2244)

Raghav Chamadiya88de1e7ceeb9
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index ee29d15e2..7ff712d2c 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -93,6 +93,7 @@ from .generation import (
structural_page_summary,
)
from .persistence import (
+ apply_git_history_coverage_state,
build_resume_controller,
effective_run_mode_for_resume,
git_tier_for_run_mode,
@@ -1756,6 +1757,7 @@ def init_command(
# same tier instead of silently upgrading ESSENTIAL → FULL (issue #341).
base_state["run_mode"] = run_mode
base_state["git_tier"] = git_tier_for_run_mode(run_mode)
+ apply_git_history_coverage_state(base_state, result)
# Record whether submodules were indexed so `repowise update` rebuilds
# the graph with the same boundary semantics (same pattern as git_tier:
# missing → False keeps legacy behavior for old state files).
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
index 10439bfbd..8daa7b6b0 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
@@ -327,6 +327,18 @@ def effective_run_mode_for_resume(repo_path: Path, run_mode: str, resume: bool)
# ---------------------------------------------------------------------------
+def apply_git_history_coverage_state(state: dict[str, Any], result: Any) -> None:
+ """Replace achieved Git coverage, clearing stale data when unavailable."""
+ summary = getattr(result, "git_summary", None)
+ if summary is None:
+ return
+ coverage = getattr(summary, "history_coverage", None)
+ if coverage is None:
+ state.pop("git_history_coverage", None)
+ else:
+ state["git_history_coverage"] = coverage.to_dict()
+
+
def save_full_state_and_config(
*,
repo_path: Path,
@@ -380,6 +392,7 @@ def save_full_state_and_config(
# Full-mode docs runs always index the FULL git tier.
state["run_mode"] = "standard"
state["git_tier"] = "full"
+ apply_git_history_coverage_state(state, result)
# Same pattern as git_tier: `repowise update` reads this back so its
# graph rebuild keeps the init run's submodule boundary semantics.
state["include_submodules"] = include_submodules
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
index 3ea4839ea..70413b8e2 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -78,7 +78,7 @@ from .generation import (
run_repo_generation,
structural_page_summary,
)
-from .persistence import persist_result
+from .persistence import apply_git_history_coverage_state, persist_result
from .reporting import show_workspace_completion
@@ -503,6 +503,7 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCt
repo_phase_timings: dict[str, float] = callback.timings
if repo_phase_timings:
state["phase_timings"] = repo_phase_timings
+ apply_git_history_coverage_state(state, result)
kg = getattr(result, "knowledge_graph_result", None)
if kg is not None:
state["knowledge_graph"] = build_kg_state(kg)
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 3f607d2d1..b199b53e1 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -2288,6 +2288,12 @@ def run_update(
# paths' ``run`` rows measure the same span.
timings.stop("run")
state["phase_timings"] = timings.totals
+ if full_git_summaries:
+ coverage = getattr(full_git_summaries[0], "history_coverage", None)
+ if coverage is not None:
+ state["git_history_coverage"] = coverage.to_dict()
+ else:
+ state.pop("git_history_coverage", None)
save_state(repo_path, state)
# --- Pending-marker cleanup --------------------------------------------
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index d8cbd845a..9ac80dde5 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -479,6 +479,12 @@ def _persist_index_only_update(
# here is exactly the cost the mode exists to avoid.
"renderer_fingerprint": _current_renderer_fingerprint(repo_path),
}
+ if full_git_summary is not None:
+ coverage = getattr(full_git_summary, "history_coverage", None)
+ if coverage is not None:
+ new_state["git_history_coverage"] = coverage.to_dict()
+ else:
+ new_state.pop("git_history_coverage", None)
# Before save_state, and reading ``state`` (the pre-update dict) for the old
# pointer: this is what keeps a degraded run recoverable now that the
# pointer below advances to head regardless.
diff --git a/packages/core/src/repowise/core/ingestion/git_commit_index.py b/packages/core/src/repowise/core/ingestion/git_commit_index.py
index 90ff23ec6..9fe1ccb05 100644
--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py
+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py
@@ -19,6 +19,7 @@ input file, not retro-fittable from a repo-wide log.
from __future__ import annotations
+from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING
@@ -30,16 +31,44 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
-def load_git_ai_note_agents(repo: object, commit_limit: int) -> dict[str, str]:
+@dataclass
+class HistorySample:
+ """One monotonic per-file history sample and its achieved coverage.
+
+ Every eligible file keeps its newest
+ ``min(per_file_limit, available_non_merge_history)`` commits. The recent and deep
+ repo-wide walks are only optimisations for satisfying that contract;
+ files they cannot prove complete use the per-file fallback.
+ """
+
+ commits: dict[str, list[_CommitRec]] = field(default_factory=dict)
+ fallback_files: set[str] = field(default_factory=set)
+ recent_files: set[str] = field(default_factory=set)
+ deep_files: set[str] = field(default_factory=set)
+ global_commits: int = 0
+ deep_commits: int = 0
+ history_complete_through_depth: int = 0
+
+
+def _count_non_merge_commits(repo: object) -> int | None:
+ """Return reachable non-merge commits, or ``None`` when unavailable."""
+ try:
+ return int(repo.git.rev_list("--count", "--no-merges", "HEAD").strip()) # type: ignore[attr-defined]
+ except Exception:
+ return None
+
+
+def load_git_ai_note_agents(repo: object, commit_limit: int | None) -> dict[str, str]:
"""Map ``commit_sha → agent`` from git-ai authorship notes (``refs/notes/ai``).
Returns an empty dict when the ref is absent — the common case, gated by a
single cheap ``for-each-ref`` so 99.9% of repos pay nothing and add no git
- pass. Only repos actually using git-ai incur the one bounded
- ``git log --notes=ai`` walk here, whose ``sha → agent`` result the commit
- walk then reads by-key (no re-parse per touched file). Any failure returns
- ``{}`` — a notes read must never break the git index. See the git-ai
- standard v3.0.0 for the note format.
+ pass. Only repos actually using git-ai incur a ``git log --notes=ai`` walk
+ here, whose ``sha → agent`` result the commit walk then reads by-key (no
+ re-parse per touched file). The walk is bounded when *commit_limit* is an
+ integer; ``None`` covers the complete history for the rare per-file
+ fallback lane. Any failure returns ``{}`` — a notes read must never break
+ the git index. See the git-ai standard v3.0.0 for the note format.
"""
from .git_indexer import _FIELD_SEP, _RECORD_SEP
from .git_indexer.agent_provenance import _agent_from_git_ai_note
@@ -53,12 +82,10 @@ def load_git_ai_note_agents(repo: object, commit_limit: int) -> dict[str, str]:
try:
# ``%N`` is the note body; the leading ``%x00``/``%x1f`` mirror the main
# walk's record/field separators so multi-line notes parse unambiguously.
- raw = repo.git.log( # type: ignore[attr-defined]
- f"-{commit_limit}",
- "--no-merges",
- "--notes=ai",
- "--format=%x00%H%x1f%N",
- )
+ args = ["--no-merges", "--notes=ai", "--format=%x00%H%x1f%N"]
+ if commit_limit is not None:
+ args.insert(0, f"-{commit_limit}")
+ raw = repo.git.log(*args) # type: ignore[attr-defined]
except Exception as exc:
logger.warning("git_ai_notes_load_failed", error=str(exc))
return {}
@@ -191,6 +218,7 @@ def load_commit_index(
provenance_classifier: object | None = None,
trace_index: object | None = None,
cache_dir: Path | None = None,
+ stats_sink: dict[str, int | bool] | None = None,
) -> dict[str, list[_CommitRec]]:
"""Bucket every commit in the recent history by the files it touched.
@@ -247,6 +275,8 @@ def load_commit_index(
if provenance_classifier is None:
provenance_classifier = AgentProvenanceClassifier()
+ if stats_sink is not None:
+ stats_sink.update(succeeded=False, commits=0)
# 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
@@ -273,6 +303,8 @@ def load_commit_index(
except ValueError: # unparseable stamp: keep it in the window
depth = position + 1
if depth == 0:
+ if stats_sink is not None:
+ stats_sink.update(succeeded=True, commits=0)
logger.debug(
"repo_commit_index_built",
commits_parsed=0,
@@ -288,6 +320,8 @@ def load_commit_index(
return {}
if not records:
+ if stats_sink is not None:
+ stats_sink.update(succeeded=True, commits=0)
return {}
# git-ai authorship notes for this window (``{}`` unless the repo uses them).
@@ -420,6 +454,8 @@ def load_commit_index(
files_with_history=len(bucket),
indexable_files=len(indexable_files),
)
+ if stats_sink is not None:
+ stats_sink.update(succeeded=True, commits=commits_parsed)
return bucket
@@ -432,6 +468,7 @@ def load_deep_commit_index(
deep_limit: int,
provenance_classifier: object | None = None,
trace_index: object | None = None,
+ stats_sink: dict[str, int | bool] | None = None,
) -> dict[str, list[_CommitRec]]:
"""Bucket commits OLDER than the recent window for *wanted_files* only.
@@ -448,11 +485,10 @@ def load_deep_commit_index(
repos whose history is much deeper than the window (a 9k-commit
monorepo left 3,295 of 4,857 files to the fallback).
- The records differ from the per-file fallback in one documented way:
- churn comes from the repo-wide diff (rename rows attribute edit churn
- through the rename) rather than the pathspec-limited diff (which
- shows a rename as a whole-file addition), and simplification-rare
- merge commits never appear (``--no-merges``, like the window walk).
+ Churn comes from the repo-wide diff (rename rows attribute edit churn
+ through the rename) rather than the pathspec-limited fallback diff (which
+ shows a rename as a whole-file addition). All three rename-free lanes use
+ ``--no-merges`` so changing lanes cannot change the retained commit set.
That makes deep-bucketed files CONSISTENT with window-indexed files,
which always had repo-walk semantics. Files absent from this bucket
(pre-rename names the marker parser cannot resolve, or history deeper
@@ -472,6 +508,8 @@ def load_deep_commit_index(
if not wanted_files:
return {}
+ if stats_sink is not None:
+ stats_sink.update(succeeded=False, commits=0)
if provenance_classifier is None:
provenance_classifier = AgentProvenanceClassifier()
@@ -488,6 +526,8 @@ def load_deep_commit_index(
return {}
if not raw:
+ if stats_sink is not None:
+ stats_sink.update(succeeded=True, commits=0)
return {}
# git-ai notes across the deep region (``{}`` unless the repo uses them).
@@ -589,4 +629,113 @@ def load_deep_commit_index(
wanted_files=len(wanted_files),
skip=skip,
)
+ if stats_sink is not None:
+ stats_sink.update(succeeded=True, commits=commits_parsed)
return bucket
+
+
+def load_sampled_commit_index(
+ repo: object,
+ per_file_limit: int,
+ indexable_files: set[str],
+ *,
+ deep_limit: int,
+ deep_threshold: int,
+ commit_sink: list[dict] | None = None,
+ provenance_classifier: object | None = None,
+ trace_index: object | None = None,
+ cache_dir: Path | None = None,
+) -> HistorySample:
+ """Resolve the recent, deep, and fallback sampling lanes once.
+
+ Increasing ``per_file_limit`` can only add retained commits for a file.
+ A recent-window hit never makes a file complete by itself: the deep walk
+ tops it up, and a per-file walk remains required when the shared walks
+ neither fill the cap nor reach the repository root.
+ """
+ recent_stats: dict[str, int | bool] = {}
+ recent = load_commit_index(
+ repo,
+ per_file_limit,
+ indexable_files,
+ commit_sink=commit_sink,
+ provenance_classifier=provenance_classifier,
+ trace_index=trace_index,
+ cache_dir=cache_dir,
+ stats_sink=recent_stats,
+ )
+ sample = HistorySample(
+ commits={path: list(records[:per_file_limit]) for path, records in recent.items()},
+ recent_files=set(recent),
+ global_commits=int(recent_stats.get("commits", 0)),
+ )
+ if not recent_stats.get("succeeded"):
+ sample.fallback_files = set(indexable_files)
+ return sample
+
+ total_commits = _count_non_merge_commits(repo)
+ underfilled = {
+ path for path in indexable_files if len(sample.commits.get(path, ())) < per_file_limit
+ }
+ deep_stats: dict[str, int | bool] = {}
+ deep_walk_succeeded = False
+ deep_cursor = per_file_limit
+ recent_walk_complete = total_commits is not None and total_commits <= sample.global_commits
+ while (
+ not recent_walk_complete
+ and len(underfilled) >= deep_threshold
+ and (total_commits is None or deep_cursor < total_commits)
+ ):
+ deep_stats = {}
+ deep = load_deep_commit_index(
+ repo,
+ per_file_limit,
+ underfilled,
+ skip=deep_cursor,
+ deep_limit=deep_limit,
+ provenance_classifier=provenance_classifier,
+ trace_index=trace_index,
+ stats_sink=deep_stats,
+ )
+ for path, records in deep.items():
+ remaining = per_file_limit - len(sample.commits.get(path, ()))
+ if remaining > 0 and records:
+ sample.commits.setdefault(path, []).extend(records[:remaining])
+ sample.deep_files.add(path)
+ if not deep_stats.get("succeeded"):
+ break
+ deep_walk_succeeded = True
+ sample.deep_commits += int(deep_stats.get("commits", 0))
+ deep_cursor += deep_limit
+ underfilled = {
+ path
+ for path in indexable_files
+ if len(sample.commits.get(path, ())) < per_file_limit
+ }
+ # Without a reliable history total, one bounded deep walk is the safe
+ # limit; unresolved files retain the per-file fallback.
+ if total_commits is None:
+ break
+
+ shared_walk_complete = bool(
+ recent_walk_complete
+ or (
+ deep_walk_succeeded
+ and total_commits is not None
+ and deep_cursor >= total_commits
+ )
+ )
+ walked_depth = sample.global_commits + sample.deep_commits
+ sample.history_complete_through_depth = (
+ min(total_commits, walked_depth) if total_commits is not None else walked_depth
+ )
+ underfilled = {
+ path for path in indexable_files if len(sample.commits.get(path, ())) < per_file_limit
+ }
+ if not shared_walk_complete:
+ sample.fallback_files = underfilled
+ sample.deep_files.difference_update(sample.fallback_files)
+
+ for path in indexable_files - sample.fallback_files:
+ sample.commits.setdefault(path, [])
+ return sample
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
index ac9b72a5d..3e02af245 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
@@ -157,7 +157,9 @@ def _parse_per_file_log(
commit_limit: int,
follow_renames: bool,
provenance_classifier: Any | None = None,
-) -> tuple[list[_CommitRec], str | None]:
+ note_agents: dict[str, str] | None = None,
+ trace_index: Any | None = None,
+) -> tuple[list[_CommitRec] | None, str | None]:
"""Run a per-file ``git log --numstat`` and parse it into commit records.
Returns ``(commits, original_path)``. Only used when no precomputed commit
@@ -166,6 +168,16 @@ def _parse_per_file_log(
log_args: list[str] = []
if follow_renames:
log_args.append("--follow")
+ else:
+ # Match the recent/deep repo-wide lanes. Without one shared non-merge
+ # contract, a file moving between fallback and shared sampling could
+ # lose a retained merge even while ``commit_limit`` increased.
+ log_args.append("--no-merges")
+ # A pathspec normally restricts numstat to this file, which represents
+ # a rename differently from the repo-wide lanes. Full-diff keeps commit
+ # selection per-file but makes churn and changed-path provenance use
+ # the same complete diff as the recent/deep walks.
+ log_args.append("--full-diff")
log_args += [
f"-{commit_limit}",
"--numstat",
@@ -176,7 +188,7 @@ def _parse_per_file_log(
try:
raw = repo.git.log(*log_args)
except Exception:
- return [], None
+ return None, None
if not raw.strip():
return [], None
@@ -207,17 +219,8 @@ def _parse_per_file_log(
subject=header["subject"],
body=header["body"],
)
- if provenance_classifier is not None:
- prov = provenance_classifier.classify(
- header["author_name"],
- header["author_email"],
- header["committer_name"],
- header["committer_email"],
- f"{header['subject']}\n{header['body']}",
- )
- current.agent = prov.agent
- current.agent_tier = prov.autonomy_tier
commits.append(current)
+ changed_paths: set[str] = set()
for line in numstat_lines:
numstat_parts = line.split("\t")
if len(numstat_parts) < 3:
@@ -227,12 +230,31 @@ def _parse_per_file_log(
if "=>" in stat_path:
_old, _new = _extract_rename_paths(stat_path, known_paths)
match_path = _new or stat_path
+ changed_paths.add(match_path)
if match_path in known_paths or match_path == file_path:
try:
current.added += int(numstat_parts[0]) if numstat_parts[0] != "-" else 0
current.deleted += int(numstat_parts[1]) if numstat_parts[1] != "-" else 0
except ValueError:
pass
+ if provenance_classifier is not None:
+ trace_hit = (
+ trace_index.resolve(header["sha"], header["parents"], changed_paths)
+ if trace_index
+ else None
+ )
+ prov = provenance_classifier.classify(
+ header["author_name"],
+ header["author_email"],
+ header["committer_name"],
+ header["committer_email"],
+ f"{header['subject']}\n{header['body']}",
+ note_agent=(note_agents or {}).get(header["sha"]),
+ trace_agent=trace_hit[0] if trace_hit else None,
+ trace_confidence=trace_hit[1] if trace_hit else "high",
+ )
+ current.agent = prov.agent
+ current.agent_tier = prov.autonomy_tier
return commits, orig_path
@@ -247,6 +269,8 @@ def index_file(
precomputed_commits: list[_CommitRec] | None = None,
as_of_ts: float | None = None,
provenance_classifier: Any | None = None,
+ note_agents: dict[str, str] | None = None,
+ trace_index: Any | None = None,
) -> dict:
"""Index a single file's git history. Runs in executor.
@@ -282,7 +306,11 @@ def index_file(
commit_limit=commit_limit,
follow_renames=follow_renames,
provenance_classifier=provenance_classifier,
+ note_agents=note_agents,
+ trace_index=trace_index,
)
+ if commits is None:
+ return {"file_path": file_path}
if not commits:
return meta
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
index aba54d6ae..cdf4ba443 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -33,6 +33,7 @@ from .enrich import compute_percentiles
from .file_history import DECAY_REFRESH_KEYS, index_file
from .prior_defects import FixWalk, PriorDefects, collect_fix_commits, compute_prior_defects
from .records import (
+ GitHistoryCoverage,
GitIndexSummary,
_CommitRec,
_should_skip_index,
@@ -43,19 +44,95 @@ from .tiers import GitIndexTier
logger = structlog.get_logger(__name__)
-__all__ = ["GitIndexer"]
+__all__ = ["GitIndexer", "git_worker_count"]
# Shas per ``git log --no-walk`` call when backfilling commit offsets. Each sha
# is a 40-char argv entry, and Windows caps a command line near 32k characters —
# 200 leaves generous headroom while keeping the subprocess count low.
_OFFSET_LOOKUP_CHUNK = 200
+_GIT_WORKERS_ENV = "REPOWISE_GIT_WORKERS"
+_MAX_GIT_WORKERS = 8
+_GIT_WORKER_MEMORY_BYTES = 384 * 1024 * 1024
+_GIT_MEMORY_RESERVE_BYTES = 512 * 1024 * 1024
+
+
+def _available_memory_bytes() -> int | None:
+ """Best-effort available physical memory without an optional dependency."""
+ if os.name == "nt":
+ try:
+ import ctypes
+
+ class _MemoryStatus(ctypes.Structure):
+ _fields_ = [
+ ("length", ctypes.c_ulong),
+ ("memory_load", ctypes.c_ulong),
+ ("total_physical", ctypes.c_ulonglong),
+ ("available_physical", ctypes.c_ulonglong),
+ ("total_page_file", ctypes.c_ulonglong),
+ ("available_page_file", ctypes.c_ulonglong),
+ ("total_virtual", ctypes.c_ulonglong),
+ ("available_virtual", ctypes.c_ulonglong),
+ ("available_extended_virtual", ctypes.c_ulonglong),
+ ]
+
+ status = _MemoryStatus()
+ status.length = ctypes.sizeof(status)
+ if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
+ return int(status.available_physical)
+ except (AttributeError, OSError, TypeError, ValueError):
+ return None
+ try:
+ pages = os.sysconf("SC_AVPHYS_PAGES")
+ page_size = os.sysconf("SC_PAGE_SIZE")
+ return int(pages) * int(page_size)
+ except (AttributeError, OSError, TypeError, ValueError):
+ return None
+
+
+def git_worker_count(
+ pending: int,
+ *,
+ requested: int | None = None,
+ cpu_count: int | None = None,
+ available_memory_bytes: int | None = None,
+) -> int:
+ """Resolve one deterministic CPU/memory ceiling for Git subprocess fan-out.
+
+ ``requested`` and ``REPOWISE_GIT_WORKERS`` are safe caps, not ways around
+ the resource ceiling. Invalid values are ignored with a warning.
+ """
+ affinity_count = getattr(os, "process_cpu_count", None)
+ cpus = cpu_count or (affinity_count() if affinity_count else None) or os.cpu_count() or 1
+ available = (
+ available_memory_bytes
+ if available_memory_bytes is not None
+ else _available_memory_bytes()
+ )
+ memory_workers = _MAX_GIT_WORKERS
+ if available is not None:
+ usable = max(0, available - _GIT_MEMORY_RESERVE_BYTES)
+ memory_workers = max(1, usable // _GIT_WORKER_MEMORY_BYTES)
+ resource_ceiling = max(1, min(cpus, memory_workers, _MAX_GIT_WORKERS, max(1, pending)))
+
+ override: int | None = requested
+ raw_override = os.environ.get(_GIT_WORKERS_ENV) if requested is None else None
+ if raw_override:
+ try:
+ override = int(raw_override)
+ except ValueError:
+ override = 0
+ if override is not None and override <= 0:
+ logger.warning("invalid_git_workers", value=raw_override or override)
+ override = None
+ return min(resource_ceiling, override) if override is not None else resource_ceiling
+
class GitIndexer:
"""Mines git history into the git_metadata table.
Uses gitpython (already a dependency) for git operations.
- Parallelizes per-file git log calls with asyncio.Semaphore(20).
+ Parallelizes per-file Git work behind one CPU/memory-aware worker ceiling.
Non-blocking: if git is unavailable or repo has no history, log a warning
and return an empty summary. All downstream features degrade gracefully.
@@ -74,6 +151,7 @@ class GitIndexer:
tier: GitIndexTier = GitIndexTier.FULL,
exclude_patterns: list[str] | None = None,
record_episodes: bool = False,
+ max_workers: int | None = None,
) -> None:
self.repo_path = Path(repo_path)
self.commit_limit = commit_limit or _DEFAULT_COMMIT_LIMIT
@@ -85,6 +163,7 @@ class GitIndexer:
# episodes would make two nominally read-only commands persist rows
# naming files the repo excludes, and those rows outlive every prune.
self.record_episodes = record_episodes
+ self.max_workers = max_workers
import pathspec
@@ -140,8 +219,7 @@ class GitIndexer:
from concurrent.futures import ThreadPoolExecutor
- executor = ThreadPoolExecutor(max_workers=20, thread_name_prefix="git-idx")
- semaphore = asyncio.Semaphore(20)
+ workers = git_worker_count(len(indexable_files), requested=self.max_workers)
loop = asyncio.get_event_loop()
# Build a repo-wide commit index in ONE git log subprocess when
@@ -151,7 +229,10 @@ class GitIndexer:
commit_index: dict[str, list[_CommitRec]] = {}
commit_sink: list[dict] = []
prov_clf = self._provenance_classifier()
- deep_index: dict[str, list[_CommitRec]] = {}
+ fallback_files = set(indexable_files)
+ recent_files: set[str] = set()
+ deep_files: set[str] = set()
+ global_commits = deep_commits = complete_through_depth = 0
# Agent-trace records read ONCE per index (one stat call for repos
# without a .agent-trace/ dir). Shared with both commit-index walks so
# the file isn't re-read per walk, and reused below for the per-file
@@ -159,36 +240,37 @@ class GitIndexer:
# where neither commit-index walk runs.
trace_index = self._load_trace_index(repo)
if not self.follow_renames:
- from ..git_commit_index import load_commit_index, load_deep_commit_index
+ from ..git_commit_index import load_sampled_commit_index
- commit_index = load_commit_index(
+ sample = load_sampled_commit_index(
repo,
self.commit_limit,
set(indexable_files),
+ deep_limit=_DEEP_WALK_COMMIT_LIMIT,
+ deep_threshold=_DEEP_WALK_MIN_FALLBACK,
commit_sink=commit_sink,
provenance_classifier=prov_clf,
trace_index=trace_index,
cache_dir=self._window_cache_dir(),
)
+ commit_index = sample.commits
+ fallback_files = sample.fallback_files
+ recent_files = sample.recent_files
+ deep_files = sample.deep_files
+ global_commits = sample.global_commits
+ deep_commits = sample.deep_commits
+ complete_through_depth = sample.history_complete_through_depth
- # Files the recent window never saw would each spawn a per-file
- # ``git log`` fallback below. When there are many (deep-history
- # repos), one --skip walk over the older region replaces them;
- # files it still misses keep the per-file path.
- missed = {fp for fp in indexable_files if fp not in commit_index}
- if len(missed) >= _DEEP_WALK_MIN_FALLBACK:
- deep_index = load_deep_commit_index(
- repo,
- self.commit_limit,
- missed,
- skip=self.commit_limit,
- deep_limit=_DEEP_WALK_COMMIT_LIMIT,
- provenance_classifier=prov_clf,
- trace_index=trace_index,
- )
+ fallback_note_agents: dict[str, str] = {}
+ if fallback_files:
+ from ..git_commit_index import load_git_ai_note_agents
+
+ fallback_note_agents = load_git_ai_note_agents(repo, None)
include_blame = self.tier.includes_blame
as_of_ts = self._resolve_as_of_ts(repo, commit_index)
+ executor = ThreadPoolExecutor(max_workers=workers, thread_name_prefix="git-idx")
+ semaphore = asyncio.Semaphore(workers)
get_thread_repo, close_thread_repos = self._thread_repo_pool()
def _index_one_sync(file_path: str) -> dict:
@@ -201,9 +283,9 @@ class GitIndexer:
"""
try:
thread_repo = get_thread_repo()
- precomputed = commit_index.get(file_path) if commit_index else None
- if precomputed is None:
- precomputed = deep_index.get(file_path)
+ precomputed = (
+ None if file_path in fallback_files else commit_index.get(file_path, [])
+ )
return index_file(
thread_repo,
file_path,
@@ -214,6 +296,8 @@ class GitIndexer:
precomputed_commits=precomputed,
as_of_ts=as_of_ts,
provenance_classifier=prov_clf,
+ note_agents=fallback_note_agents,
+ trace_index=trace_index,
)
except Exception:
return {"file_path": file_path}
@@ -266,15 +350,16 @@ class GitIndexer:
on_co_change_done()
return result
- metadata_list, (co_changes, change_entropy) = await asyncio.gather(
- asyncio.gather(*file_tasks, return_exceptions=True),
- _co_change_task(),
- )
-
- # Abandon any timed-out threads immediately instead of letting
- # asyncio.run() block for minutes during default-executor cleanup.
- executor.shutdown(wait=False, cancel_futures=True)
- close_thread_repos()
+ try:
+ metadata_list, (co_changes, change_entropy) = await asyncio.gather(
+ asyncio.gather(*file_tasks, return_exceptions=True),
+ _co_change_task(),
+ )
+ finally:
+ # Abandon timed-out threads immediately instead of letting
+ # asyncio.run() block for minutes during executor cleanup.
+ executor.shutdown(wait=False, cancel_futures=True)
+ close_thread_repos()
results: list[dict] = []
for r in metadata_list:
@@ -362,6 +447,24 @@ class GitIndexer:
# true project age / commit / contributor counts for the stats page,
# which must not read them off the depth-capped sample (issue #730).
repo_totals=capture_repo_totals(repo),
+ history_coverage=GitHistoryCoverage(
+ eligible_files=len(indexable_files),
+ files_with_history=sum(
+ 1 for row in results if int(row.get("commit_count_total", 0)) > 0
+ ),
+ unavailable_files=sum(1 for row in results if "commit_count_total" not in row),
+ retained_commits=sum(
+ int(row.get("commit_count_total", 0)) for row in results
+ ),
+ per_file_limit=self.commit_limit,
+ global_commits=global_commits,
+ deep_commits=deep_commits,
+ recent_files=len(recent_files),
+ deep_files=len(deep_files),
+ fallback_files=len(fallback_files),
+ complete_through_depth=complete_through_depth,
+ workers=workers,
+ ),
)
repo.close()
@@ -371,6 +474,7 @@ class GitIndexer:
files=summary.files_indexed,
hotspots=summary.hotspots,
stable=summary.stable_files,
+ history_coverage=summary.history_coverage.to_dict(),
duration=f"{summary.duration_seconds:.1f}s",
)
return summary, results
@@ -447,7 +551,6 @@ class GitIndexer:
return []
loop = asyncio.get_event_loop()
- semaphore = asyncio.Semaphore(20)
include_blame = self.tier.includes_blame
# Whether to refresh idle files' decay fields this run. Requires the
@@ -460,31 +563,63 @@ class GitIndexer:
and not self.follow_renames
and self.tier.includes_co_change
)
+ target_files = set(all_files) if refresh_idle else set(changed_file_paths)
+ workers = git_worker_count(len(changed_file_paths), requested=self.max_workers)
+ from concurrent.futures import ThreadPoolExecutor
prov_clf = self._provenance_classifier()
+ trace_index = self._load_trace_index(repo)
commit_index: dict[str, list[_CommitRec]] = {}
+ fallback_files = set(target_files)
if not self.follow_renames:
- from ..git_commit_index import load_commit_index
+ from ..git_commit_index import load_sampled_commit_index
# Bucket every tracked file (not just the changed ones) when an idle
# refresh is due, so idle files carry their own precomputed commits.
# The git subprocess is identical either way — only the in-memory
# bucketing set widens.
with timed(timings, "rebuild.git.commit_index"):
- commit_index = load_commit_index(
+ sample = load_sampled_commit_index(
repo,
self.commit_limit,
- set(all_files) if refresh_idle else set(changed_file_paths),
+ target_files,
+ deep_limit=_DEEP_WALK_COMMIT_LIMIT,
+ deep_threshold=(1 if refresh_idle else _DEEP_WALK_MIN_FALLBACK),
provenance_classifier=prov_clf,
+ trace_index=trace_index,
cache_dir=self._window_cache_dir(),
)
+ commit_index = sample.commits
+ fallback_files = sample.fallback_files
+ fallback_note_agents: dict[str, str] = {}
+ if fallback_files:
+ from ..git_commit_index import load_git_ai_note_agents
+
+ fallback_note_agents = load_git_ai_note_agents(repo, None)
as_of_ts = self._resolve_as_of_ts(repo, commit_index)
+ executor = ThreadPoolExecutor(max_workers=workers, thread_name_prefix="git-idx")
+ semaphore = asyncio.Semaphore(workers)
get_thread_repo, close_thread_repos = self._thread_repo_pool()
+ executor_closed = False
+
+ def _cleanup_executor(_task: asyncio.Task | None = None) -> None:
+ nonlocal executor_closed
+ if executor_closed:
+ return
+ executor_closed = True
+ executor.shutdown(wait=False, cancel_futures=True)
+ close_thread_repos()
+
+ owner_task = asyncio.current_task()
+ if owner_task is not None:
+ owner_task.add_done_callback(_cleanup_executor)
def _index_one_sync(file_path: str) -> dict:
try:
thread_repo = get_thread_repo()
- precomputed = commit_index.get(file_path) if commit_index else None
+ precomputed = (
+ None if file_path in fallback_files else commit_index.get(file_path, [])
+ )
return index_file(
thread_repo,
file_path,
@@ -495,6 +630,8 @@ class GitIndexer:
precomputed_commits=precomputed,
as_of_ts=as_of_ts,
provenance_classifier=prov_clf,
+ note_agents=fallback_note_agents,
+ trace_index=trace_index,
)
except Exception:
return {"file_path": file_path}
@@ -503,7 +640,7 @@ class GitIndexer:
async with semaphore:
try:
return await asyncio.wait_for(
- loop.run_in_executor(None, _index_one_sync, file_path),
+ loop.run_in_executor(executor, _index_one_sync, file_path),
timeout=_FILE_INDEX_TIMEOUT_SECS,
)
except (TimeoutError, Exception) as exc:
@@ -518,8 +655,14 @@ class GitIndexer:
try:
with timed(timings, "rebuild.git.changed_files"):
results_raw = await asyncio.gather(*tasks, return_exceptions=True)
- finally:
- close_thread_repos()
+ except BaseException:
+ # Cancellation is a BaseException on supported Python versions.
+ # Release the private pool immediately even when the caller catches
+ # the cancellation and keeps its own task alive.
+ _cleanup_executor()
+ with contextlib.suppress(Exception):
+ repo.close()
+ raise
results: list[dict] = []
for r in results_raw:
@@ -532,7 +675,15 @@ class GitIndexer:
# fields we will refresh — computed here so the prior-defect pass below
# covers them in its single windowed walk.
changed_set = set(changed_file_paths)
- idle_paths = [fp for fp in commit_index if fp not in changed_set] if refresh_idle else []
+ idle_paths = (
+ [
+ fp
+ for fp, commits in commit_index.items()
+ if commits and fp not in changed_set and fp not in fallback_files
+ ]
+ if refresh_idle
+ else []
+ )
# Recompute prior-defect counts (same dedicated windowed pass as the
# full index — the per-file commit list can't carry this signal
@@ -564,7 +715,7 @@ class GitIndexer:
try:
with timed(timings, "rebuild.git.co_change"):
co_changes, change_entropy = await loop.run_in_executor(
- None,
+ executor,
compute_co_changes_and_entropy,
repo,
set(all_files),
@@ -607,7 +758,15 @@ class GitIndexer:
)
except Exception as exc:
logger.debug("co_change_pass_failed", error=str(exc))
+ except BaseException:
+ _cleanup_executor()
+ with contextlib.suppress(Exception):
+ repo.close()
+ raise
+ if owner_task is not None:
+ owner_task.remove_done_callback(_cleanup_executor)
+ _cleanup_executor()
repo.close()
return results
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/records.py b/packages/core/src/repowise/core/ingestion/git_indexer/records.py
index b3e013742..df48afd5c 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/records.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/records.py
@@ -15,6 +15,7 @@ __all__ = [
"_FIELD_SEP",
"_LOG_FORMAT",
"_RECORD_SEP",
+ "GitHistoryCoverage",
"GitIndexSummary",
"RepoTotals",
"_CommitRec",
@@ -169,6 +170,41 @@ def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:
return header, numstat_lines
+@dataclass
+class GitHistoryCoverage:
+ """Achieved file-history coverage for one Git indexing run."""
+
+ eligible_files: int = 0
+ files_with_history: int = 0
+ unavailable_files: int = 0
+ retained_commits: int = 0
+ per_file_limit: int = 0
+ global_commits: int = 0
+ deep_commits: int = 0
+ recent_files: int = 0
+ deep_files: int = 0
+ fallback_files: int = 0
+ complete_through_depth: int = 0
+ workers: int = 1
+
+ def to_dict(self) -> dict[str, int]:
+ """Stable JSON shape used by state/progress provenance."""
+ return {
+ "eligible_files": self.eligible_files,
+ "files_with_history": self.files_with_history,
+ "unavailable_files": self.unavailable_files,
+ "retained_commits": self.retained_commits,
+ "per_file_limit": self.per_file_limit,
+ "global_commits": self.global_commits,
+ "deep_commits": self.deep_commits,
+ "recent_files": self.recent_files,
+ "deep_files": self.deep_files,
+ "fallback_files": self.fallback_files,
+ "complete_through_depth": self.complete_through_depth,
+ "workers": self.workers,
+ }
+
+
@dataclass
class GitIndexSummary:
files_indexed: int
@@ -194,6 +230,7 @@ class GitIndexSummary:
# contributor counts instead of deriving them from the bounded sample
# (issue #730). None when git is unavailable or the repo has no commits.
repo_totals: RepoTotals | None = None
+ history_coverage: GitHistoryCoverage | None = None
_RENAME_RE = re.compile(r"\{(.*?) => (.*?)\}")
diff --git a/tests/unit/cli/test_update_phase_timings.py b/tests/unit/cli/test_update_phase_timings.py
index 63ef68bb8..251e0c8a3 100644
--- a/tests/unit/cli/test_update_phase_timings.py
+++ b/tests/unit/cli/test_update_phase_timings.py
@@ -26,19 +26,26 @@ def _quiet(monkeypatch) -> None:
monkeypatch.setattr(reporting, "show_index_only_completion", lambda **_k: None)
-def _persist(tmp_path: Path, timings: PhaseTimings | None) -> dict:
+def _persist(
+ tmp_path: Path, timings: PhaseTimings | None, *, full_git_summary=None
+) -> dict:
from repowise.cli.commands.update_cmd.persistence import _persist_index_only_update
+ state = {
+ "last_sync_commit": "0" * 40,
+ "git_history_coverage": {"eligible_files": 99},
+ }
_persist_index_only_update(
tmp_path,
object(),
{},
None,
None,
- {"last_sync_commit": "0" * 40},
+ state,
"1" * 40,
time.monotonic(),
[],
+ full_git_summary=full_git_summary,
timings=timings,
)
return json.loads((tmp_path / ".repowise" / "state.json").read_text(encoding="utf-8"))
@@ -81,3 +88,27 @@ def test_rescore_gets_its_own_row(tmp_path: Path, monkeypatch) -> None:
assert "rescore" in state["phase_timings"]
assert state["health_analyzer_version"]
+
+
+def test_incremental_update_preserves_last_full_git_coverage(
+ tmp_path: Path, monkeypatch
+) -> None:
+ (tmp_path / ".repowise").mkdir()
+ _quiet(monkeypatch)
+
+ state = _persist(tmp_path, None)
+
+ assert state["git_history_coverage"] == {"eligible_files": 99}
+
+
+def test_unavailable_full_git_refresh_clears_stale_coverage(
+ tmp_path: Path, monkeypatch
+) -> None:
+ from repowise.core.ingestion.git_indexer.records import GitIndexSummary
+
+ (tmp_path / ".repowise").mkdir()
+ _quiet(monkeypatch)
+
+ state = _persist(tmp_path, None, full_git_summary=GitIndexSummary(0, 0, 0, 0.0))
+
+ assert "git_history_coverage" not in state
diff --git a/tests/unit/cli/test_workspace_init_provider.py b/tests/unit/cli/test_workspace_init_provider.py
index 44d807a8c..1269ee64e 100644
--- a/tests/unit/cli/test_workspace_init_provider.py
+++ b/tests/unit/cli/test_workspace_init_provider.py
@@ -18,6 +18,7 @@ import pytest
from repowise.cli.commands.init_cmd import workspace as ws_mod
from repowise.cli.commands.init_cmd.workspace import _ingest_and_generate_repo, _WorkspaceCtx
+from repowise.core.ingestion.git_indexer.records import GitHistoryCoverage, GitIndexSummary
def _fake_result() -> SimpleNamespace:
@@ -27,6 +28,14 @@ def _fake_result() -> SimpleNamespace:
generated_pages=[],
knowledge_graph_result=None,
repo_name="repo",
+ git_summary=SimpleNamespace(
+ history_coverage=GitHistoryCoverage(
+ eligible_files=3,
+ files_with_history=2,
+ global_commits=10,
+ per_file_limit=10,
+ )
+ ),
)
@@ -80,7 +89,11 @@ def captured(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
monkeypatch.setattr("repowise.core.pipeline.run_pipeline", fake_pipeline)
monkeypatch.setattr(ws_mod, "persist_result", noop_async)
monkeypatch.setattr(ws_mod, "get_head_commit", lambda *_a, **_k: "c0ffee")
- monkeypatch.setattr(ws_mod, "save_state", lambda *_a, **_k: None)
+ monkeypatch.setattr(
+ ws_mod,
+ "save_state",
+ lambda _path, state, **_k: seen.update(saved_state=state),
+ )
monkeypatch.setattr(ws_mod, "write_editor_project_files", lambda *_a, **_k: None)
return seen
@@ -102,6 +115,40 @@ def test_the_index_phase_is_given_the_resolved_provider(
assert captured["llm_client"] is provider
+def test_workspace_member_persists_the_shared_git_coverage(
+ tmp_path: Path, captured: dict[str, Any]
+) -> None:
+ _run(tmp_path, SimpleNamespace(provider_name="omp", model_name="omp/default"))
+
+ assert captured["saved_state"]["git_history_coverage"] == {
+ "eligible_files": 3,
+ "files_with_history": 2,
+ "unavailable_files": 0,
+ "retained_commits": 0,
+ "per_file_limit": 10,
+ "global_commits": 10,
+ "deep_commits": 0,
+ "recent_files": 0,
+ "deep_files": 0,
+ "fallback_files": 0,
+ "complete_through_depth": 0,
+ "workers": 1,
+ }
+
+
+def test_unavailable_git_history_clears_stale_coverage() -> None:
+ from repowise.cli.commands.init_cmd.persistence import (
+ apply_git_history_coverage_state,
+ )
+
+ state = {"git_history_coverage": {"eligible_files": 99}}
+ result = SimpleNamespace(git_summary=GitIndexSummary(0, 0, 0, 0.0))
+
+ apply_git_history_coverage_state(state, result)
+
+ assert "git_history_coverage" not in state
+
+
def test_a_repo_path_provider_is_rebound_to_the_repo_being_indexed(
tmp_path: Path, captured: dict[str, Any], monkeypatch: pytest.MonkeyPatch
) -> None:
diff --git a/tests/unit/ingestion/test_git_deep_commit_index.py b/tests/unit/ingestion/test_git_deep_commit_index.py
index 178099e13..b07235834 100644
--- a/tests/unit/ingestion/test_git_deep_commit_index.py
+++ b/tests/unit/ingestion/test_git_deep_commit_index.py
@@ -19,6 +19,9 @@ from repowise.core.ingestion.git_commit_index import (
load_deep_commit_index,
)
from repowise.core.ingestion.git_indexer import GitIndexer
+from repowise.core.ingestion.git_indexer.agent_provenance import (
+ AgentProvenanceClassifier,
+)
from repowise.core.ingestion.git_indexer.file_history import _parse_per_file_log
from repowise.core.ingestion.git_indexer.tiers import GitIndexTier
@@ -84,13 +87,10 @@ def test_deep_bucket_matches_per_file_fallback(tmp_path) -> None:
fp,
commit_limit=2,
follow_renames=False,
- provenance_classifier=None,
+ provenance_classifier=AgentProvenanceClassifier(),
)
- # The oracle path classifies provenance only when given a classifier;
- # compare structure first, then provenance separately below.
- assert [(c.sha, c.ts, c.is_merge, c.added, c.deleted) for c in deep[fp]] == [
- (c.sha, c.ts, c.is_merge, c.added, c.deleted) for c in oracle
- ], fp
+ assert oracle is not None
+ assert [_rec_tuple(c) for c in deep[fp]] == [_rec_tuple(c) for c in oracle], fp
# Agent provenance was classified during the deep walk.
agents = [c.agent for c in deep["old_0.py"]]
diff --git a/tests/unit/ingestion/test_git_sampling_and_workers.py b/tests/unit/ingestion/test_git_sampling_and_workers.py
new file mode 100644
index 000000000..8da9c461c
--- /dev/null
+++ b/tests/unit/ingestion/test_git_sampling_and_workers.py
@@ -0,0 +1,184 @@
+"""Regression tests for monotonic Git sampling and bounded fan-out."""
+
+from __future__ import annotations
+
+import asyncio
+from concurrent.futures import Future
+
+import pytest
+
+from repowise.core.ingestion.git_commit_index import load_sampled_commit_index
+from repowise.core.ingestion.git_indexer import GitIndexer
+from repowise.core.ingestion.git_indexer.indexer import git_worker_count
+from repowise.core.ingestion.git_indexer.tiers import GitIndexTier
+
+
+def _commit(repo, root, path: str, value: int, subject: str) -> None:
+ target = root / path
+ target.write_text(f"value = {value}\n")
+ repo.index.add([path])
+ repo.index.commit(subject)
+
+
+def _build_crossing_repo(tmp_path):
+ import git as gitpython
+
+ repo = gitpython.Repo.init(tmp_path)
+ with repo.config_writer() as config:
+ config.set_value("user", "name", "Alice")
+ config.set_value("user", "email", "[email protected]")
+
+ _commit(repo, tmp_path, "crossing.py", 1, "feat: add crossing")
+ _commit(repo, tmp_path, "crossing.py", 2, "fix: crossing two")
+ _commit(repo, tmp_path, "crossing.py", 3, "fix: crossing three")
+ _commit(repo, tmp_path, "recent.py", 1, "feat: recent one")
+ _commit(repo, tmp_path, "crossing.py", 4, "fix: crossing four")
+ _commit(repo, tmp_path, "recent.py", 2, "feat: recent two")
+ return repo
+
+
+def test_per_file_history_is_monotonic_when_file_crosses_into_recent_window(tmp_path) -> None:
+ repo = _build_crossing_repo(tmp_path)
+ retained: list[list[str]] = []
+
+ for limit in (1, 2, 4):
+ commit_sink: list[dict] = []
+ sample = load_sampled_commit_index(
+ repo,
+ limit,
+ {"crossing.py", "recent.py"},
+ deep_limit=100,
+ deep_threshold=1,
+ commit_sink=commit_sink,
+ )
+ retained.append([record.sha for record in sample.commits["crossing.py"]])
+ assert sample.global_commits == len(commit_sink) == limit
+ assert len({row["sha"] for row in commit_sink}) == limit
+ assert all(row["changes"] for row in commit_sink)
+
+ assert retained[1][: len(retained[0])] == retained[0]
+ assert retained[2][: len(retained[1])] == retained[1]
+ assert len(retained) == len({tuple(rows) for rows in retained})
+ repo.close()
+
+
+def test_underfilled_recent_file_keeps_deep_evidence_contract(tmp_path) -> None:
+ repo = _build_crossing_repo(tmp_path)
+ sample = load_sampled_commit_index(
+ repo,
+ 4,
+ {"crossing.py", "recent.py"},
+ deep_limit=100,
+ deep_threshold=1,
+ )
+
+ assert "crossing.py" in sample.recent_files
+ assert "crossing.py" in sample.deep_files
+ assert len(sample.commits["crossing.py"]) == 4
+ assert sample.fallback_files == set()
+ repo.close()
+
+
+async def test_summary_reports_achieved_coverage_and_commit_provenance(
+ tmp_path, monkeypatch
+) -> None:
+ repo = _build_crossing_repo(tmp_path)
+ repo.close()
+ monkeypatch.setattr(
+ "repowise.core.ingestion.git_indexer.indexer._DEEP_WALK_MIN_FALLBACK", 1
+ )
+ summary, rows = await GitIndexer(
+ tmp_path, commit_limit=2, tier=GitIndexTier.ESSENTIAL, max_workers=2
+ ).index_repo("repo")
+
+ coverage = summary.history_coverage
+ assert coverage is not None
+ assert coverage.eligible_files == len(rows) == 2
+ assert coverage.files_with_history == 2
+ assert coverage.unavailable_files == 0
+ assert coverage.retained_commits == sum(row["commit_count_total"] for row in rows)
+ assert coverage.global_commits == len(summary.commit_rows) == 2
+ assert coverage.recent_files == 2
+ assert coverage.deep_files == 2
+ assert coverage.fallback_files == 0
+ assert coverage.workers <= 2
+ assert all(row["sha"] and row["files_changed"] for row in summary.commit_rows)
+
+
+def test_worker_resolution_is_deterministic_and_resource_bounded(monkeypatch) -> None:
+ gib = 1024**3
+ assert git_worker_count(100, cpu_count=2, available_memory_bytes=16 * gib) == 2
+ assert git_worker_count(100, cpu_count=32, available_memory_bytes=gib) == 1
+ assert (
+ git_worker_count(
+ 100, requested=50, cpu_count=4, available_memory_bytes=16 * gib
+ )
+ == 4
+ )
+ assert git_worker_count(3, cpu_count=32, available_memory_bytes=16 * gib) == 3
+
+ monkeypatch.setenv("REPOWISE_GIT_WORKERS", "2")
+ assert git_worker_count(100, cpu_count=8, available_memory_bytes=16 * gib) == 2
+ monkeypatch.setenv("REPOWISE_GIT_WORKERS", "invalid")
+ assert git_worker_count(100, cpu_count=2, available_memory_bytes=16 * gib) == 2
+
+
+async def test_fallback_git_failure_is_reported_as_unavailable(tmp_path, monkeypatch) -> None:
+ repo = _build_crossing_repo(tmp_path)
+ repo.close()
+ monkeypatch.setattr(
+ "repowise.core.ingestion.git_indexer.indexer._DEEP_WALK_MIN_FALLBACK", 10**9
+ )
+ monkeypatch.setattr(
+ "repowise.core.ingestion.git_indexer.file_history._parse_per_file_log",
+ lambda *args, **kwargs: (None, None),
+ )
+
+ summary, rows = await GitIndexer(
+ tmp_path, commit_limit=1, tier=GitIndexTier.ESSENTIAL, max_workers=2
+ ).index_repo("repo")
+
+ coverage = summary.history_coverage
+ assert coverage is not None
+ unavailable = [row for row in rows if "commit_count_total" not in row]
+ assert {row["file_path"] for row in unavailable} == {"crossing.py"}
+ assert coverage.unavailable_files == len(unavailable) == 1
+ assert coverage.files_with_history == 1
+
+
+async def test_incremental_cancellation_closes_private_executor(tmp_path, monkeypatch) -> None:
+ repo = _build_crossing_repo(tmp_path)
+ repo.close()
+ submitted = asyncio.Event()
+ executors = []
+
+ class BlockingExecutor:
+ def __init__(self, *args, **kwargs):
+ self.future = Future()
+ self.shutdown_calls = []
+ executors.append(self)
+
+ def submit(self, fn, *args, **kwargs):
+ submitted.set()
+ return self.future
+
+ def shutdown(self, wait=True, *, cancel_futures=False):
+ self.shutdown_calls.append((wait, cancel_futures))
+ self.future.cancel()
+
+ monkeypatch.setattr("concurrent.futures.ThreadPoolExecutor", BlockingExecutor)
+ task = asyncio.create_task(
+ GitIndexer(
+ tmp_path, commit_limit=2, tier=GitIndexTier.ESSENTIAL, max_workers=1
+ ).index_changed_files(["recent.py"])
+ )
+ await submitted.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert len(executors) == 1
+ assert executors[0].shutdown_calls == [(False, True)]