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.

fix(update): run update --full under the single-flight lock (#1529)

Felix-Ayush29e09634ef6c
diff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
index ea2c33b85..6799aa531 100644
--- a/packages/cli/src/repowise/cli/commands/upgrade_flow.py
+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
@@ -46,6 +46,7 @@ from repowise.cli.helpers import (
)
from repowise.core.analysis.health import HEALTH_ANALYZER_VERSION
from repowise.core.docs_mode import docs_mode_state_fields
+from repowise.core.update_lock import release_update_lock, try_acquire_update_lock
def _gate_cost(
@@ -480,58 +481,80 @@ def upgrade_to_full(
console.print(f"Embedder: [cyan]{resolved}[/cyan] (was mock, index-only's default).")
embedder_name = resolved
+ # A full upgrade is the same class of state/DB writer as an incremental
+ # update, so it must sit under the same single-flight lock: without it, a
+ # concurrent `repowise update` could race this run's save_state (the exact
+ # race the lock exists to prevent). If another update holds the lock, the
+ # full upgrade defers the same way update_cmd does — the running update
+ # will roll forward to HEAD.
+ existing_lock = try_acquire_update_lock(repo_path, head)
+ if existing_lock is not None:
+ from repowise.cli.helpers import write_update_pending
+
+ write_update_pending(repo_path, head)
+ raise click.ClickException(
+ "Another `repowise update` is already running on this repo. "
+ "The full upgrade is deferred; it will run on the next pass."
+ )
+
+ # We own the lock from here on; release it when this function returns
+ # (success, cost-gate Abort, or unexpected failure) rather than at process
+ # exit — atexit would leave the lock held for the rest of the CLI process.
try:
- generated_pages, total_pages = run_async(
- _run_upgrade(
- repo_path,
- provider,
- config,
- exclude_patterns=exclude_patterns,
- commit_limit=commit_limit,
- follow_renames=follow_renames,
- embedder_name=embedder_name,
- yes=yes,
+ try:
+ generated_pages, total_pages = run_async(
+ _run_upgrade(
+ repo_path,
+ provider,
+ config,
+ exclude_patterns=exclude_patterns,
+ commit_limit=commit_limit,
+ follow_renames=follow_renames,
+ embedder_name=embedder_name,
+ yes=yes,
+ )
)
+ except click.Abort:
+ # Declined at the cost gate. The git backfill that ran before it is
+ # kept (it costs nothing to keep and everything to redo), and the
+ # persisted docs mode is left alone so the repo keeps whatever wiki it
+ # already had.
+ console.print("[yellow]Nothing generated.[/yellow] The index is unchanged.")
+ return
+
+ # Flip persisted state to full so subsequent `repowise update` runs the
+ # normal incremental LLM path rather than offering upgrade.
+ state["last_sync_commit"] = head
+ state.update(docs_mode_state_fields("llm"))
+ state["git_tier"] = "full"
+ state["total_pages"] = total_pages
+ # Record who wrote the pages. Without this, `repowise status` on a repo
+ # upgraded this way reports its provider and model as unknown, which reads
+ # as "nothing wrote this wiki" right after a run that did.
+ state["provider"] = provider.provider_name
+ state["model"] = provider.model_name
+ # `update --full` regenerates the whole wiki (concept tree included), so it
+ # brings the store to the terminal store format the same way a full init
+ # does. Stamp it as such rather than clamping at the reindex gate.
+ #
+ # This is also the run that answers the missing-slot notice: it evaluates
+ # every registered onboarding slot against whole-repo signals, so after it
+ # there is nothing left for the notice to report.
+ stamp_offered_slots(state, enabled=config.enable_onboarding)
+ # This run re-ran health analysis over the whole repo, so its rows come
+ # from the current analyzer. Without the stamp the next plain `update`
+ # would read a stale version and pay a redundant full re-score.
+ state["health_analyzer_version"] = HEALTH_ANALYZER_VERSION
+ save_state(repo_path, state, full_index=True)
+ if embedder_name and embedder_name != cfg.get("embedder"):
+ from repowise.cli.helpers import save_config_partial
+
+ save_config_partial(repo_path, embedder=embedder_name)
+
+ elapsed = time.monotonic() - start
+ console.print(
+ f"[bold green]Upgrade complete[/bold green] in {elapsed:.1f}s — "
+ f"{len(generated_pages)} pages generated, git tier now FULL."
)
- except click.Abort:
- # Declined at the cost gate. The git backfill that ran before it is
- # kept (it costs nothing to keep and everything to redo), and the
- # persisted docs mode is left alone so the repo keeps whatever wiki it
- # already had.
- console.print("[yellow]Nothing generated.[/yellow] The index is unchanged.")
- return
-
- # Flip persisted state to full so subsequent `repowise update` runs the
- # normal incremental LLM path rather than offering upgrade.
- state["last_sync_commit"] = head
- state.update(docs_mode_state_fields("llm"))
- state["git_tier"] = "full"
- state["total_pages"] = total_pages
- # Record who wrote the pages. Without this, `repowise status` on a repo
- # upgraded this way reports its provider and model as unknown, which reads
- # as "nothing wrote this wiki" right after a run that did.
- state["provider"] = provider.provider_name
- state["model"] = provider.model_name
- # `update --full` regenerates the whole wiki (concept tree included), so it
- # brings the store to the terminal store format the same way a full init
- # does. Stamp it as such rather than clamping at the reindex gate.
- #
- # This is also the run that answers the missing-slot notice: it evaluates
- # every registered onboarding slot against whole-repo signals, so after it
- # there is nothing left for the notice to report.
- stamp_offered_slots(state, enabled=config.enable_onboarding)
- # This run re-ran health analysis over the whole repo, so its rows come
- # from the current analyzer. Without the stamp the next plain `update`
- # would read a stale version and pay a redundant full re-score.
- state["health_analyzer_version"] = HEALTH_ANALYZER_VERSION
- save_state(repo_path, state, full_index=True)
- if embedder_name and embedder_name != cfg.get("embedder"):
- from repowise.cli.helpers import save_config_partial
-
- save_config_partial(repo_path, embedder=embedder_name)
-
- elapsed = time.monotonic() - start
- console.print(
- f"[bold green]Upgrade complete[/bold green] in {elapsed:.1f}s — "
- f"{len(generated_pages)} pages generated, git tier now FULL."
- )
+ finally:
+ release_update_lock(repo_path)
diff --git a/tests/unit/cli/test_full_upgrade_lock.py b/tests/unit/cli/test_full_upgrade_lock.py
new file mode 100644
index 000000000..95e1dd684
--- /dev/null
+++ b/tests/unit/cli/test_full_upgrade_lock.py
@@ -0,0 +1,116 @@
+"""``repowise update --full`` must respect the single-flight lock.
+
+Regression anchor for #1485: the ``--full`` fast-to-full upgrade ran before the
+incremental update's single-flight lock and called ``save_state`` (plus the DB
+writes inside ``_run_upgrade``) without ever acquiring it — a concurrent
+``repowise update`` could race the full upgrade's state writes exactly the way
+the lock exists to prevent.
+
+The full upgrade must acquire the lock itself; when another update holds it,
+the run defers (raises a clear ClickException and leaves a pending marker)
+instead of writing state from outside the lock.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+from types import SimpleNamespace
+
+import click
+import pytest
+
+from repowise.cli.commands import upgrade_flow as up_mod
+
+
+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_state(tmp_path: Path) -> Path:
+ 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")
+ (repo / ".repowise").mkdir()
+ from repowise.cli.helpers import save_state
+
+ save_state(repo, {"last_sync_commit": _git(repo, "rev-parse", "HEAD")})
+ return repo
+
+
+def _stub_provider_and_upgrade(monkeypatch: pytest.MonkeyPatch) -> None:
+ provider = SimpleNamespace(provider_name="openai", model_name="gpt-4o")
+ monkeypatch.setattr(up_mod, "resolve_provider", lambda *a, **k: provider)
+
+ async def _stub_upgrade(*a: object, **k: object) -> tuple[list[str], int]:
+ return (["p1", "p2"], 2)
+
+ monkeypatch.setattr(up_mod, "_run_upgrade", _stub_upgrade)
+
+
+def _call_upgrade(repo: Path, yes: bool = True) -> None:
+ up_mod.upgrade_to_full(
+ repo,
+ provider_name=None,
+ model=None,
+ reasoning=None,
+ concurrency=1,
+ yes=yes,
+ )
+
+
+def test_full_upgrade_acquires_and_releases_lock(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ repo = _repo_with_state(tmp_path)
+ _stub_provider_and_upgrade(monkeypatch)
+
+ acquired: list[bool] = []
+
+ def _fake_acquire(repo_path: Path, target: str | None) -> dict | None:
+ acquired.append(True)
+ return None
+
+ monkeypatch.setattr(up_mod, "try_acquire_update_lock", _fake_acquire)
+ released: list[Path] = []
+ monkeypatch.setattr(up_mod, "release_update_lock", lambda p: released.append(p))
+
+ _call_upgrade(repo)
+
+ assert acquired == [True], "the full upgrade must acquire the single-flight lock"
+ assert released == [repo], "the full upgrade must release the lock when it returns"
+
+
+def test_full_upgrade_defers_when_lock_held(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ repo = _repo_with_state(tmp_path)
+ _stub_provider_and_upgrade(monkeypatch)
+
+ held = {"pid": 4242, "target_commit": "x", "started_at": 0.0}
+
+ def _held_lock(repo_path: Path, target: str | None) -> dict:
+ return held
+
+ monkeypatch.setattr(up_mod, "try_acquire_update_lock", _held_lock)
+ ran_upgrade: list[bool] = []
+
+ async def _held_stub_upgrade(*a: object, **k: object) -> tuple[list[str], int]:
+ ran_upgrade.append(True)
+ return ([], 0)
+
+ monkeypatch.setattr(up_mod, "_run_upgrade", _held_stub_upgrade)
+ from repowise.cli.helpers import read_update_pending
+
+ with pytest.raises(click.ClickException, match="Another `repowise update` is already running"):
+ _call_upgrade(repo)
+
+ assert ran_upgrade == [], "the upgrade must not run while another update holds the lock"
+ assert read_update_pending(repo) is not None, "the deferred run must leave a pending marker"