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(update): run the up-to-date self-heal under the single-flight lock (#1528)
Felix-Ayushcfabe843fc88
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex 5c6b07fb6..3f9f7d912 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -841,28 +841,42 @@ def run_update(# rather than a change, silently skipping the regeneration it should# trigger.needs_backfill = prev_config_fp is None or prev_renderer_fp is None- if needs_backfill and not dry_run:- save_state(- repo_path,- {- **state,- "config_fingerprint": curr_config_fp,- "renderer_fingerprint": curr_renderer_fp,- },- )# Self-heal a row a pre-fix run left behind: state.json can already be# current here while the DB head_commit is still the last full index.+ #+ # These state/DB writes must sit under the single-flight lock below+ # just like a content-changing update, or two updates racing on the+ # "already up to date" path could stomp each other's save_state — the+ # exact race the lock exists to prevent. If another update holds the+ # lock, its run will perform this heal; skip ours rather than write+ # from outside the lock.if not dry_run:- stamp_head_commit(repo_path, head)- # A capture added after this repo was indexed would otherwise wait- # for the next commit to land, which on a quiet repo is never.- heal_commit_offsets(repo_path)- _refresh_editor_stamp(repo_path, agents_md)- # The index is current, so any pending marker a bailed update left- # is by definition caught-up (or older); drop it here too rather- # than waiting for the next content-changing update. This is the- # quiescent state a stale marker was observed lingering in.- consume_update_pending(repo_path, head)+ heal_lock = try_acquire_update_lock(repo_path, head)+ if heal_lock is not None:+ log.debug("self_heal_skipped", reason="another update holds the lock")+ else:+ try:+ if needs_backfill:+ save_state(+ repo_path,+ {+ **state,+ "config_fingerprint": curr_config_fp,+ "renderer_fingerprint": curr_renderer_fp,+ },+ )+ stamp_head_commit(repo_path, head)+ # A capture added after this repo was indexed would otherwise wait+ # for the next commit to land, which on a quiet repo is never.+ heal_commit_offsets(repo_path)+ _refresh_editor_stamp(repo_path, agents_md)+ # The index is current, so any pending marker a bailed update left+ # is by definition caught-up (or older); drop it here too rather+ # than waiting for the next content-changing update. This is the+ # quiescent state a stale marker was observed lingering in.+ consume_update_pending(repo_path, head)+ finally:+ release_update_lock(repo_path)# Up-to-date code does not mean an up-to-date store: a wiki indexed by an# older release may still benefit from a re-index (concept tree, written# prose). That is the common upgrade path, so surface the once-per-storediff --git a/tests/unit/cli/test_update_up_to_date_lock.py b/tests/unit/cli/test_update_up_to_date_lock.pynew file mode 100644index 000000000..45d6a6689--- /dev/null+++ b/tests/unit/cli/test_update_up_to_date_lock.py@@ -0,0 +1,132 @@+"""The "already up to date" self-heal must respect the single-flight lock.++Regression anchor for #1486: on the up-to-date shortcut, ``repowise update``+backfilled state fingerprints and stamped the DB head commit *before* acquiring+the single-flight lock, so two updates racing on the up-to-date path could stomp+each other's ``save_state`` — the exact race the lock exists to prevent. The heal+writes must run only while holding the lock, and must be skipped when another+update already holds it.+"""++from __future__ import annotations++import asyncio+import subprocess+from pathlib import Path++import pytest++from repowise.cli.commands.update_cmd import command as upd_cmd+from repowise.cli.helpers import save_state, write_update_pending+++def _git(repo: Path, *args: str) -> str:+ return subprocess.run(+ ["git", *args], cwd=str(repo), capture_output=True, text=True+ ).stdout.strip()+++def _repo_with_three_commits(tmp_path: Path) -> tuple[Path, str, str, str]:+ repo = tmp_path / "repo"+ repo.mkdir()+ _git(repo, "init")+ _git(repo, "config", "user.email", "[email protected]")+ _git(repo, "config", "user.name", "T")+ (repo / "a.txt").write_text("0")+ _git(repo, "add", ".")+ _git(repo, "commit", "-m", "c0")+ c0 = _git(repo, "rev-parse", "HEAD")+ (repo / "a.txt").write_text("1")+ _git(repo, "commit", "-am", "c1")+ c1 = _git(repo, "rev-parse", "HEAD")+ (repo / "a.txt").write_text("2")+ _git(repo, "commit", "-am", "c2")+ c2 = _git(repo, "rev-parse", "HEAD")+ (repo / ".repowise").mkdir()+ return repo, c0, c1, c2+++def _invoke_update(repo: Path) -> str:+ from click.testing import CliRunner++ from repowise.cli.main import cli++ result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace"])+ assert result.exit_code == 0, result.output+ return result.output+++def _indexed_repo(tmp_path: Path) -> tuple[Path, str]:+ """An up-to-date repo: state at HEAD, so update takes the no-op path."""+ from repowise.core.pipeline.full_index import index_repo_full++ repo, _c0, _c1, c2 = _repo_with_three_commits(tmp_path)+ asyncio.run(index_repo_full(repo))+ # index_repo_full does not persist state.json in the test harness; record+ # the sync/docs pointers at HEAD so the update resolves to "already current".+ save_state(repo, {"last_sync_commit": c2, "last_docs_commit": c2, "docs_enabled": False})+ return repo, c2+++def _install_recorders(monkeypatch: pytest.MonkeyPatch, calls: dict[str, int]) -> None:+ def _make(name: str):+ def _recorder(*a: object, **k: object) -> None:+ calls[name] = calls.get(name, 0) + 1++ return _recorder++ monkeypatch.setattr(upd_cmd, "stamp_head_commit", _make("stamp_head_commit"))+ monkeypatch.setattr(upd_cmd, "heal_commit_offsets", _make("heal_commit_offsets"))+ monkeypatch.setattr(upd_cmd, "consume_update_pending", _make("consume_update_pending"))+ monkeypatch.setattr(upd_cmd, "save_state", _make("save_state"))+ monkeypatch.setattr(upd_cmd, "release_update_lock", _make("release_update_lock"))+++def test_up_to_date_self_heal_skipped_when_lock_held(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Another update owns the lock -> the heal must not write anything."""+ repo, c2 = _indexed_repo(tmp_path)+ write_update_pending(repo, c2)++ calls: dict[str, int] = {}++ def _held_lock(repo_path: Path, target: str | None) -> dict:+ calls["acquire"] = calls.get("acquire", 0) + 1+ return {"pid": 9999, "target_commit": "x", "held_since": 0.0} # not None = held++ _install_recorders(monkeypatch, calls)+ monkeypatch.setattr(upd_cmd, "try_acquire_update_lock", _held_lock)++ _invoke_update(repo)++ assert calls.get("acquire", 0) > 0, "update must try the single-flight lock"+ assert calls.get("stamp_head_commit", 0) == 0+ assert calls.get("heal_commit_offsets", 0) == 0+ assert calls.get("consume_update_pending", 0) == 0+ assert calls.get("save_state", 0) == 0+ assert calls.get("release_update_lock", 0) == 0+++def test_up_to_date_self_heal_runs_and_releases_under_lock(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Lock free -> the heal runs once, and the lock is released afterwards."""+ repo, _c2 = _indexed_repo(tmp_path)++ calls: dict[str, int] = {}++ def _free_lock(repo_path: Path, target: str | None) -> dict | None:+ calls["acquire"] = calls.get("acquire", 0) + 1+ return None # acquired++ _install_recorders(monkeypatch, calls)+ monkeypatch.setattr(upd_cmd, "try_acquire_update_lock", _free_lock)++ _invoke_update(repo)++ assert calls.get("acquire", 0) > 0+ assert calls.get("stamp_head_commit", 0) == 1+ assert calls.get("heal_commit_offsets", 0) == 1+ assert calls.get("consume_update_pending", 0) == 1+ assert calls.get("release_update_lock", 0) == 1