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): clean up stale .update.pending markers (#1004)
Raghav Chamadiya0e86c5daa77a
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex 72330109a..26f4a6c2e 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -19,15 +19,14 @@ import structlogfrom repowise.cli._setup import configure_cli_loggingfrom repowise.cli.helpers import (- clear_update_pending,clear_update_queued,console,+ consume_update_pending,ensure_repowise_dir,find_workspace_root,get_head_commit,load_config,load_state,- read_update_pending,release_update_lock,resolve_command_target,resolve_provider_or_prompt,@@ -605,6 +604,11 @@ def run_update(if not dry_run:stamp_head_commit(repo_path, head)_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)if emitter is not None:emitter.done(ok=True,@@ -739,6 +743,9 @@ def run_update(# /repos endpoint reads head_commit from the row, not the state file.stamp_head_commit(repo_path, head)_refresh_editor_stamp(repo_path, agents_md)+ # We hold the lock and have advanced to head; drop any stale pending+ # marker a bailed update left behind.+ consume_update_pending(repo_path, head)if emitter is not None:emitter.done(ok=True,@@ -775,6 +782,7 @@ def run_update(emitter.error(str(exc))raise_refresh_editor_stamp(repo_path, agents_md)+ consume_update_pending(repo_path, head)if emitter is not None:emitter.done(ok=True,@@ -1031,6 +1039,9 @@ def run_update(emitter.error(str(exc))raise_refresh_editor_stamp(repo_path, agents_md, degraded)+ # Index-only is the post-commit hook's hot path; clear any stale pending+ # marker here too, not just on the full-docs path.+ consume_update_pending(repo_path, head)_record_update_outcome(index_only=True,changed_count=len(file_diffs),@@ -1520,16 +1531,12 @@ def run_update(state["config_fingerprint"] = config_fingerprint(repo_path)save_state(repo_path, state)- # --- Roll forward to any commit that landed during this run ------------+ # --- Pending-marker cleanup --------------------------------------------# Another `repowise update` (from a post-commit hook) may have written a- # ``.update.pending`` marker while we were generating pages. If the new- # HEAD points past where we just finished, clear the marker only if it's- # already caught up; otherwise leave it in place as a signal to the- # augment hook so its message can be "update done, new commits since"- # instead of the bare stale-wiki warning.- pending_head = read_update_pending(repo_path)- if pending_head and pending_head == head:- clear_update_pending(repo_path)+ # ``.update.pending`` marker while we were generating pages. Drop it now+ # that we've caught up; it is only kept when it points to a commit strictly+ # newer than the one we just indexed.+ consume_update_pending(repo_path, head)# Trigger cross-repo hooks if this repo is part of a workspace. The# workspace docs flow suppresses this per-repo and runs the hooks oncediff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex 23824eac0..544bb520c 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -344,6 +344,53 @@ def clear_update_pending(repo_path: Path) -> None:pass+def _pending_commit_still_ahead(+ repo_path: Path, pending_head: str, indexed_head: str | None+) -> bool:+ """True only when ``pending_head`` is a resolvable commit strictly ahead of+ ``indexed_head`` — a newer commit the index has not caught up to yet.++ Equal commits, ancestors of ``indexed_head``, and commits that no longer+ resolve (rebased or gc'd away) all return ``False``, so the caller clears+ them instead of leaving the marker behind forever.+ """+ if not indexed_head or pending_head == indexed_head:+ return False+ import subprocess++ try:+ # ``indexed_head`` is an ancestor of ``pending_head`` => pending is+ # newer than what we indexed and worth keeping. A non-zero exit+ # (including an unresolvable pending commit) means "not ahead".+ result = subprocess.run(+ ["git", "merge-base", "--is-ancestor", indexed_head, pending_head],+ cwd=str(repo_path),+ capture_output=True,+ timeout=10,+ )+ return result.returncode == 0+ except Exception:+ return False+++def consume_update_pending(repo_path: Path, indexed_head: str | None) -> None:+ """Clear the ``.update.pending`` marker once the index has caught up to it.++ A bailed update writes the latest HEAD to ``.update.pending`` (see+ :func:`write_update_pending`) so the in-flight update can tell more commits+ landed. The update that actually holds the lock calls this when it+ finishes: the marker is obsolete unless it points to a commit strictly+ *ahead* of the one just indexed. The previous consumer only cleared on an+ exact ``pending == head`` match, so once HEAD advanced past the pending+ commit (or that commit was rebased away) the marker leaked indefinitely.+ """+ pending_head = read_update_pending(repo_path)+ if pending_head is None:+ return+ if not _pending_commit_still_ahead(repo_path, pending_head, indexed_head):+ clear_update_pending(repo_path)++# ---------------------------------------------------------------------------# Hook output log — capped, single-file rotation so the user can diagnose# why the post-commit hook didn't catch up without needing to chase down adiff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.pyindex 72d9a0a14..1a4a207e6 100644--- a/packages/core/src/repowise/core/workspace/update.py+++ b/packages/core/src/repowise/core/workspace/update.py@@ -144,6 +144,41 @@ def commit_exists(repo_path: Path, sha: str) -> bool:return False+def clear_stale_update_pending(repo_path: Path, indexed_head: str | None) -> None:+ """Drop ``.repowise/.update.pending`` once the index has caught up to it.++ The core in-flight bail (:func:`_update_one`) records the latest HEAD in+ this marker, mirroring the CLI's ``write_update_pending``. The update that+ holds the lock calls this on success: the marker is kept only when it+ points to a commit strictly *ahead* of ``indexed_head`` (a newer commit not+ yet indexed). Equal, ancestor, and no-longer-resolvable commits (rebased or+ gc'd away) are cleared, so a bailed core update never leaves the marker+ behind forever — the symmetric half of the CLI ``consume_update_pending``+ fix.+ """+ pending_path = repo_path / ".repowise" / ".update.pending"+ try:+ pending_head = pending_path.read_text(encoding="utf-8").strip()+ except OSError:+ return+ if pending_head and indexed_head and pending_head != indexed_head:+ try:+ # indexed_head is an ancestor of pending_head => strictly ahead,+ # keep it. Non-zero (incl. unresolvable pending) => safe to clear.+ ahead = subprocess.run(+ ["git", "merge-base", "--is-ancestor", indexed_head, pending_head],+ cwd=str(repo_path),+ capture_output=True,+ timeout=10,+ )+ if ahead.returncode == 0:+ return+ except Exception:+ pass+ with suppress(OSError):+ pending_path.unlink(missing_ok=True)++def read_repo_state(repo_path: Path) -> dict[str, Any]:"""Return the parsed ``<repo>/.repowise/state.json``, or ``{}``."""state_path = repo_path / ".repowise" / "state.json"@@ -722,6 +757,9 @@ async def update_workspace(# without re-running DB persistence, so the row would otherwise# lag HEAD; a no-op when persistence already stamped it.await reconcile_repo_head_commit(path, new_head)+ # Drop any stale pending marker now that we've advanced to+ # new_head (a bailed sibling update may have written one).+ clear_stale_update_pending(path, new_head)# Update workspace config entryif result.updated:diff --git a/tests/unit/cli/test_update_pending_cleanup.py b/tests/unit/cli/test_update_pending_cleanup.pynew file mode 100644index 000000000..4effd84f0--- /dev/null+++ b/tests/unit/cli/test_update_pending_cleanup.py@@ -0,0 +1,131 @@+"""`.update.pending` marker lifecycle: stale markers must get cleaned up.++The consumer used to clear the marker only on an exact ``pending == head``+match, so once HEAD advanced past the pending commit (or that commit was+rebased away) the marker leaked forever. These tests pin the ancestry-aware+cleanup: keep a strictly-newer marker, clear everything else.+"""++from __future__ import annotations++import subprocess+from pathlib import Path++from repowise.cli.helpers import (+ consume_update_pending,+ read_update_pending,+ 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 test_pending_equal_to_head_is_cleared(tmp_path: Path) -> None:+ repo, _c0, c1, _c2 = _repo_with_three_commits(tmp_path)+ write_update_pending(repo, c1)+ consume_update_pending(repo, c1)+ assert read_update_pending(repo) is None+++def test_pending_behind_head_is_cleared(tmp_path: Path) -> None:+ """Index advanced past the pending commit (the real leak): must clear."""+ repo, c0, _c1, c2 = _repo_with_three_commits(tmp_path)+ write_update_pending(repo, c0)+ consume_update_pending(repo, c2)+ assert read_update_pending(repo) is None+++def test_pending_strictly_ahead_is_kept(tmp_path: Path) -> None:+ """A pending commit newer than what we indexed is real un-indexed work."""+ repo, c0, _c1, c2 = _repo_with_three_commits(tmp_path)+ write_update_pending(repo, c2)+ consume_update_pending(repo, c0)+ assert read_update_pending(repo) == c2+++def test_unresolvable_pending_is_cleared(tmp_path: Path) -> None:+ """A rebased/gc'd-away commit no longer resolves; drop the garbage marker."""+ repo, _c0, c1, _c2 = _repo_with_three_commits(tmp_path)+ write_update_pending(repo, "0" * 40)+ consume_update_pending(repo, c1)+ assert read_update_pending(repo) is None+++def test_no_marker_is_a_noop(tmp_path: Path) -> None:+ repo, _c0, c1, _c2 = _repo_with_three_commits(tmp_path)+ consume_update_pending(repo, c1) # must not raise+ assert read_update_pending(repo) is None+++def test_none_indexed_head_clears(tmp_path: Path) -> None:+ """No resolvable indexed head to compare against -> treat marker as stale."""+ repo, _c0, c1, _c2 = _repo_with_three_commits(tmp_path)+ write_update_pending(repo, c1)+ consume_update_pending(repo, None)+ assert read_update_pending(repo) is None+++def test_core_clear_stale_update_pending_matches_cli(tmp_path: Path) -> None:+ """The core-side helper (used by the workspace updater, which can't import+ CLI helpers) applies the same ancestry rules as the CLI consumer."""+ from repowise.core.workspace.update import clear_stale_update_pending++ repo, c0, _c1, c2 = _repo_with_three_commits(tmp_path)++ write_update_pending(repo, c0) # behind head -> cleared+ clear_stale_update_pending(repo, c2)+ assert read_update_pending(repo) is None++ write_update_pending(repo, c2) # ahead of head -> kept+ clear_stale_update_pending(repo, c0)+ assert read_update_pending(repo) == c2+++def test_real_update_clears_stale_marker(tmp_path: Path) -> None:+ """End to end: a `repowise update` that catches up drops a stale pending+ marker a bailed update left behind (the observed leak)."""+ import asyncio++ from click.testing import CliRunner++ from repowise.cli.helpers import save_state+ from repowise.cli.main import cli+ 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})++ # A bailed sibling update left a marker pointing at an older commit; the+ # index has since moved to HEAD (c2), so the marker is obsolete.+ write_update_pending(repo, c0)++ result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace"])+ assert result.exit_code == 0, result.output+ assert read_update_pending(repo) is None, "a caught-up update must drop the stale marker"