Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(server): offload blocking git inspection (#2103)
Just One More Nightcf15f1252974
diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.pyindex 0344a05db..310fe5661 100644--- a/packages/server/src/repowise/server/job_executor.py+++ b/packages/server/src/repowise/server/job_executor.py@@ -593,7 +593,8 @@ async def execute_job(# mode, config) that `repowise init` would have written.try:if is_initial_index:- _persist_initial_index_state(+ await asyncio.to_thread(+ _persist_initial_index_state,Path(repo_path),llm_client=llm_client,# With a provider the pages are model-written ("llm"); with@@ -612,7 +613,7 @@ async def execute_job(exclude_patterns=exclude_patterns,)else:- _stamp_last_sync_commit(Path(repo_path))+ await asyncio.to_thread(_stamp_last_sync_commit, Path(repo_path))except Exception:logger.debug("state_json_update_failed", job_id=job_id, exc_info=True)@@ -830,6 +831,24 @@ def _persist_initial_index_state(_save_state(repo_path, state)+def _persist_generate_job_state(+ repo_path: Path,+ *,+ total_pages: int,+ remaining_templates: int,+ pages_generated: int,+) -> None:+ """Persist a scoped generation's Git baseline and page metadata."""+ head = _read_head_sha(repo_path)+ state = _load_state(repo_path)+ if head:+ state["last_sync_commit"] = head+ state["total_pages"] = total_pages+ if remaining_templates == 0 and pages_generated and resolve_docs_mode(state) != "llm":+ state.update(docs_mode_state_fields("llm"))+ _save_state(repo_path, state)++# ---------------------------------------------------------------------------# Incremental page regeneration helper# ---------------------------------------------------------------------------@@ -1096,14 +1115,13 @@ async def _run_generate_job(# page count, and docs_mode — which flips to "llm" only once no template page# remains, mirroring the CLI so a later `repowise update` reads the same mode.try:- head = _read_head_sha(repo_path)- state = _load_state(repo_path)- if head:- state["last_sync_commit"] = head- state["total_pages"] = total_pages- if remaining_templates == 0 and pages_generated and resolve_docs_mode(state) != "llm":- state.update(docs_mode_state_fields("llm"))- _save_state(repo_path, state)+ await asyncio.to_thread(+ _persist_generate_job_state,+ repo_path,+ total_pages=total_pages,+ remaining_templates=remaining_templates,+ pages_generated=pages_generated,+ )except Exception:logger.debug("state_json_update_failed", job_id=job_id, exc_info=True)@@ -1173,52 +1191,11 @@ async def _incremental_page_regen(be empty if nothing changed or no base ref is available)."""try:- # Read base ref from state.json (the commit we last synced to)- state_path = repo_path / ".repowise" / "state.json"- base_ref: str | None = None- if state_path.is_file():- state = json.loads(state_path.read_text(encoding="utf-8"))- base_ref = state.get("last_sync_commit")-- # Webhook jobs may carry explicit before/after refs- if not base_ref:- base_ref = job_config.get("before")-- if not base_ref:- logger.info("incremental_page_regen_skipped", reason="no_base_ref")- return []-- import subprocess as _sp-- head_result = _sp.run(- ["git", "rev-parse", "HEAD"],- cwd=str(repo_path),- capture_output=True,- text=True,- timeout=10,- )- if head_result.returncode != 0:- return []- head = head_result.stdout.strip()-- if head == base_ref:- logger.info("incremental_page_regen_skipped", reason="no_new_commits")- return []-- from repowise.core.ingestion import ChangeDetector- from repowise.core.ingestion.change_detector import compute_adaptive_budget-- detector = ChangeDetector(repo_path)- file_diffs = detector.get_changed_files(base_ref, head)- if not file_diffs:- return []-- cascade_budget = compute_adaptive_budget(file_diffs, result.file_count)-# Feed existing stale-page ages into the cascade so a constrained# budget spends its LLM calls on the oldest stale pages rather than- # reordering purely by importance (issues #847 / #851). Best effort:- # a missing session/repo just falls back to the historical ordering.+ # reordering purely by importance (issues #847 / #851). Keep the DB+ # lookup async; the synchronous Git/graph planning below is the unit+ # that belongs in a worker thread.stale_pages: dict[str, float] = {}if session_factory is not None and repo_id is not None:try:@@ -1232,32 +1209,26 @@ async def _incremental_page_regen(except Exception as exc: # pragma: no cover - defensivelogger.warning("incremental_page_regen_stale_lookup_failed", error=str(exc))- affected = detector.get_affected_pages(- file_diffs,- result.graph_builder.graph(),- cascade_budget,- pagerank=result.graph_builder.pagerank(),- stale_pages=stale_pages,+ plan = await asyncio.to_thread(+ _plan_incremental_page_regen,+ repo_path,+ result,+ job_config,+ stale_pages,)-- if not affected.regenerate:- logger.info("incremental_page_regen_skipped", reason="no_affected_pages")+ if plan is None:return []+ affected_parsed, affected_source, changed_count, affected_count, cascade_budget = planlogger.info("incremental_page_regen_start",- changed_files=len(file_diffs),- affected_pages=len(affected.regenerate),+ changed_files=changed_count,+ affected_pages=affected_count,cascade_budget=cascade_budget,)if progress:- progress.on_phase_start("generation", len(affected.regenerate))-- # Filter parsed files to only affected ones- regen_set = set(affected.regenerate)- affected_parsed = [pf for pf in result.parsed_files if pf.file_info.path in regen_set]- affected_source = {p: s for p, s in result.source_map.items() if p in regen_set}+ progress.on_phase_start("generation", affected_count)from repowise.core.generation import ContextAssembler, GenerationConfig, PageGenerator@@ -1316,3 +1287,60 @@ async def _incremental_page_regen(except Exception as exc:logger.warning("incremental_page_regen_failed", error=str(exc))return []+++def _plan_incremental_page_regen(+ repo_path: Path,+ result: Any,+ job_config: dict,+ stale_pages: dict[str, float],+) -> tuple[list[Any], dict[str, Any], int, int, int] | None:+ """Build an incremental regeneration plan without blocking the event loop.++ The caller runs this synchronous unit in a worker thread. Keeping the Git+ command, GitPython-backed ``ChangeDetector``, graph ranking, and related+ filesystem reads together avoids moving only the cheapest operation while+ leaving the rest of change detection on the async server thread.+ """+ base_ref = _load_state(repo_path).get("last_sync_commit") or job_config.get("before")+ if not base_ref:+ logger.info("incremental_page_regen_skipped", reason="no_base_ref")+ return None++ head = _read_head_sha(repo_path)+ if not head:+ return None+ if head == base_ref:+ logger.info("incremental_page_regen_skipped", reason="no_new_commits")+ return None++ from repowise.core.ingestion import ChangeDetector+ from repowise.core.ingestion.change_detector import compute_adaptive_budget++ detector = ChangeDetector(repo_path)+ file_diffs = detector.get_changed_files(base_ref, head)+ if not file_diffs:+ return None++ cascade_budget = compute_adaptive_budget(file_diffs, result.file_count)+ affected = detector.get_affected_pages(+ file_diffs,+ result.graph_builder.graph(),+ cascade_budget,+ pagerank=result.graph_builder.pagerank(),+ stale_pages=stale_pages,+ )+ if not affected.regenerate:+ logger.info("incremental_page_regen_skipped", reason="no_affected_pages")+ return None++ regen_set = set(affected.regenerate)+ affected_parsed = [pf for pf in result.parsed_files if pf.file_info.path in regen_set]+ affected_source = {p: s for p, s in result.source_map.items() if p in regen_set}+ return (+ affected_parsed,+ affected_source,+ len(file_diffs),+ len(affected.regenerate),+ cascade_budget,+ )diff --git a/packages/server/src/repowise/server/scheduler.py b/packages/server/src/repowise/server/scheduler.pyindex 311ee2ccf..bb8d415a6 100644--- a/packages/server/src/repowise/server/scheduler.py+++ b/packages/server/src/repowise/server/scheduler.py@@ -20,6 +20,40 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)+def _inspect_repository(repo_path: str) -> tuple[str | None, str] | None:+ """Read the persisted baseline and current HEAD for one repository.++ This helper is intentionally synchronous so the scheduler can offload the+ complete filesystem + Git inspection as one unit with ``asyncio.to_thread``.+ """+ import json+ import subprocess+ from pathlib import Path++ state_path = Path(repo_path) / ".repowise" / "state.json"+ stored_commit = None+ if state_path.is_file():+ try:+ state_data = json.loads(state_path.read_text(encoding="utf-8"))+ stored_commit = state_data.get("last_sync_commit")+ except Exception:+ pass++ try:+ head_result = subprocess.run(+ ["git", "rev-parse", "HEAD"],+ cwd=repo_path,+ capture_output=True,+ text=True,+ timeout=10,+ )+ except Exception:+ return None+ if head_result.returncode != 0:+ return None+ return stored_commit, head_result.stdout.strip()++def setup_scheduler(session_factory: async_sessionmaker[AsyncSession],*,@@ -76,10 +110,6 @@ def setup_scheduler(stored ``last_sync_commit`` in state.json, unless a job is alreadypending or running."""- import json as _json- import subprocess- from pathlib import Path as _Path-from sqlalchemy import selectfrom repowise.core.persistence import crud@@ -95,30 +125,12 @@ def setup_scheduler(if not repo.local_path:continue- # Read last_sync_commit from state.json- state_path = _Path(repo.local_path) / ".repowise" / "state.json"- stored_commit = None- if state_path.is_file():- try:- state_data = _json.loads(state_path.read_text(encoding="utf-8"))- stored_commit = state_data.get("last_sync_commit")- except Exception:- pass-- # Get current git HEAD- try:- head_result = subprocess.run(- ["git", "rev-parse", "HEAD"],- cwd=repo.local_path,- capture_output=True,- text=True,- timeout=10,- )- if head_result.returncode != 0:- continue- current_head = head_result.stdout.strip()- except Exception:+ # Keep each repo sequential, but move its complete+ # filesystem + Git inspection off the server event loop.+ inspection = await asyncio.to_thread(_inspect_repository, repo.local_path)+ if inspection is None:continue+ stored_commit, current_head = inspectionif stored_commit and current_head == stored_commit:continuediff --git a/tests/unit/server/test_job_executor.py b/tests/unit/server/test_job_executor.pyindex dfd19e111..8eb4d8be5 100644--- a/tests/unit/server/test_job_executor.py+++ b/tests/unit/server/test_job_executor.py@@ -18,6 +18,7 @@ from repowise.core.persistence.crud import upsert_generation_job, upsert_repositfrom repowise.server.job_executor import (_build_generation_config,_incremental_page_regen,+ _plan_incremental_page_regen,_repo_exclude_patterns,execute_job,)@@ -339,6 +340,40 @@ async def test_incremental_page_regen_passes_repo_path(tmp_path):assert generator.generate_all.await_args.kwargs["repo_path"] == Path(repo_path)+async def test_incremental_page_regen_offloads_change_detection(session_factory, tmp_path):+ """Async stale lookup feeds the offloaded Git and graph planning unit."""+ result = SimpleNamespace()+ to_thread = AsyncMock(return_value=None)+ stale_pages = {"foo.py": 123.0}++ with (+ patch("repowise.server.job_executor.asyncio.to_thread", to_thread),+ patch(+ "repowise.core.persistence.get_stale_file_page_ages",+ AsyncMock(return_value=stale_pages),+ ),+ ):+ pages = await _incremental_page_regen(+ tmp_path,+ result,+ llm_client=object(),+ job_config={"before": "base-sha"},+ progress=None,+ session_factory=session_factory,+ repo_id="repo-id",+ )++ assert pages == []+ to_thread.assert_awaited_once_with(+ _plan_incremental_page_regen,+ tmp_path,+ result,+ {"before": "base-sha"},+ stale_pages,+ )++@pytest.mark.asyncioasync def test_incremental_page_regen_sets_file_pages_only(tmp_path):"""A server sync must scope generation to file pages (the D4 fix).@@ -696,4 +731,3 @@ async def test_execute_job_dispatches_generate_mode(session_factory, tmp_path):await execute_job(job_id, app_state)run_generate_mock.assert_awaited_once()-diff --git a/tests/unit/server/test_scheduler.py b/tests/unit/server/test_scheduler.pyindex 86277f693..76ea32cd2 100644--- a/tests/unit/server/test_scheduler.py+++ b/tests/unit/server/test_scheduler.py@@ -12,7 +12,7 @@ from sqlalchemy import selectfrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GenerationJob-from repowise.server.scheduler import setup_scheduler+from repowise.server.scheduler import _inspect_repository, setup_schedulerasync def test_polling_fallback_launches_persisted_job(session_factory, tmp_path) -> None:@@ -62,3 +62,22 @@ async def test_polling_fallback_launches_persisted_job(session_factory, tmp_path"before": "old-sha","after": "new-sha",}+++async def test_polling_fallback_offloads_repository_inspection(session_factory, tmp_path) -> None:+ """The scheduler must not inspect state or run Git on the event loop."""+ async with get_session(session_factory) as session:+ await crud.upsert_repository(+ session,+ name="test-repo",+ local_path=str(tmp_path),+ )++ scheduler = setup_scheduler(session_factory)+ polling_job = next(job for job in scheduler.get_jobs() if job.id == "polling_fallback")+ to_thread = AsyncMock(return_value=None)++ with patch("repowise.server.scheduler.asyncio.to_thread", to_thread):+ await polling_job.func()++ to_thread.assert_awaited_once_with(_inspect_repository, str(tmp_path))