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): atomic persistence, atomic locking, and honest failure reporting (#706)

Raghav Chamadiya640bffab47fd
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md
index cae5826ae..9fa04e0f2 100644
--- a/docs/CLI_REFERENCE.md
+++ b/docs/CLI_REFERENCE.md
@@ -117,6 +117,13 @@ plus the exported `knowledge-graph.json`. In docs mode it also regenerates the
affected wiki pages. Index-only updates carry forward the previously generated
layer names and node summaries, so no LLM call is ever made without docs mode.
+If any best-effort step fails (git metadata, decisions, dead code, ...), the
+run still exits 0 but lists the degraded steps in the completion panel (and in
+the `done` event's `degraded` array with `--progress json`); the next update
+retries them. In docs mode each regenerated page is persisted as it completes,
+so an interrupted run never pays for the finished pages again — the rerun's
+prompt-hash check skips them.
+
**Options:**
| Flag | Description |
@@ -133,6 +140,7 @@ layer names and node summaries, so no LLM call is ever made without docs mode.
| `--full` | Upgrade a fast (`--mode fast`) index to a full one — see below. Single-repo only. |
| `--agents / --no-agents` | Generate or skip managed `AGENTS.md` after update. Persists the preference. |
| `-v`, `--verbose` | Show the full changed-file list and per-phase internals (cascade budget, decision-marker/evolution counts, best-effort skip warnings, detailed generation report). Off by default for a compact summary. |
+| `--progress` | `rich` (default) for the interactive progress bar, or `json` for newline-delimited JSON events on stdout (for driving update from another process) |
**First-time indexing:** as of v0.8, `update --workspace` now runs full first-time indexing for workspace entries that have no `.repowise/` dir yet (previously skipped with `"not_indexed"`). The pipeline runs index-only — no LLM cost — and writes a state.json marker so `repowise update --repo <alias> --docs` later picks up doc generation cleanly.
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 9edcc84c7..80922dcb8 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -17,7 +17,6 @@ import click
import structlog
from repowise.cli.helpers import (
- acquire_update_lock,
clear_update_pending,
clear_update_queued,
console,
@@ -26,7 +25,6 @@ from repowise.cli.helpers import (
get_head_commit,
load_config,
load_state,
- read_update_lock,
read_update_pending,
release_update_lock,
resolve_command_target,
@@ -36,6 +34,7 @@ from repowise.cli.helpers import (
run_async,
save_state,
silence_logs_for_machine_output,
+ try_acquire_update_lock,
write_update_pending,
)
from repowise.core.reasoning import REASONING_MODES
@@ -48,9 +47,7 @@ from .incremental import (
)
from .mode import _infer_legacy_docs_enabled, _resolve_index_only_mode
from .persistence import (
- _persist_incremental_commits,
_persist_index_only_update,
- _persist_partial_health,
_run_full_health_rescore,
stamp_head_commit,
)
@@ -67,7 +64,9 @@ from .workspace import _workspace_update
log = structlog.get_logger(__name__)
-def _refresh_editor_stamp(repo_path: Any, agents_md: bool | None) -> None:
+def _refresh_editor_stamp(
+ repo_path: Any, agents_md: bool | None, degraded: list[str] | None = None
+) -> None:
"""Re-stamp managed editor files (CLAUDE.md / AGENTS.md), best-effort.
Runs on every update outcome — including the "already up to date" and
@@ -85,8 +84,11 @@ def _refresh_editor_stamp(repo_path: Any, agents_md: bool | None) -> None:
project_file_overrides=get_default_project_file_overrides(agents_md=agents_md),
)
refresh_editor_project_files(console, repo_path, options=options)
- except Exception:
- pass # editor project-file refresh must never fail the update command
+ except Exception as exc:
+ # Editor project-file refresh must never fail the update command,
+ # but a stale CLAUDE.md stamp is worth an honest mention.
+ if degraded is not None:
+ degraded.append(f"Editor file refresh: {exc}")
def _surface_release_news(*, written_by: str | None) -> None:
@@ -407,16 +409,18 @@ def update_command(
)
return
- # --- Single-flight check ------------------------------------------------
- # A fresh lock from another process means a `repowise update` is already
+ # --- Single-flight lock ---------------------------------------------
+ # A live lock from another process means a `repowise update` is already
# running on this repo. Two updates racing on save_state was the actual
# root cause of "wiki keeps going stale": post-commit hooks fired during
# rapid-fire commits would each redo full ingestion + generation from the
# same outdated base, take 10+ minutes, then save_state out of order so
# state.json never reflected reality. Bail cleanly instead — and leave
# the new HEAD in ``.update.pending`` so the running update can roll
- # forward to it at the end of its current pass.
- existing_lock = read_update_lock(repo_path)
+ # forward to it at the end of its current pass. Check + acquire are one
+ # atomic exclusive create, so two updates arriving together can no
+ # longer both pass a separate read check and race anyway.
+ existing_lock = try_acquire_update_lock(repo_path, head)
if existing_lock is not None:
import time as _time
@@ -438,6 +442,19 @@ def update_command(
)
return
+ # We own the lock from here on: the augment hook suppresses its
+ # stale-wiki warning while this run is in flight (typical case: the
+ # post-commit hook fires `repowise update` in the background, then a
+ # follow-on tool call would otherwise warn that HEAD has moved).
+ import atexit
+
+ # Drop the queued marker now that the real lock owns the suppression
+ # window. Leaving both behind would cause the augment hook to keep
+ # suppressing for the queued-stale-after duration even past a failed run.
+ clear_update_queued(repo_path)
+ atexit.register(release_update_lock, repo_path)
+ atexit.register(clear_update_queued, repo_path)
+
# Backfill docs_enabled on legacy state files using the same
# shape-based inference the resolver uses, so the post-commit hook
# and future runs stop relying on the inference. Done before mode
@@ -457,20 +474,6 @@ def update_command(
# --- Resolve effective mode (index-only vs full LLM regen) ---
index_only = _resolve_index_only_mode(index_only=index_only, docs_flag=docs_flag, state=state)
- # --- Acquire update lock so the augment hook can suppress its
- # stale-wiki warning while this run is in flight (typical case: the
- # post-commit hook fires `repowise update` in the background, then a
- # follow-on tool call would otherwise warn that HEAD has moved). ---
- import atexit
-
- acquire_update_lock(repo_path, head)
- # Drop the queued marker now that the real lock owns the suppression
- # window. Leaving both behind would cause the augment hook to keep
- # suppressing for the queued-stale-after duration even past a failed run.
- clear_update_queued(repo_path)
- atexit.register(release_update_lock, repo_path)
- atexit.register(clear_update_queued, repo_path)
-
# --- Store-format upgrade assessment --------------------------------
# Single decision point for "does upgrading repowise need to touch this
# store". Runs any no-LLM auto actions (e.g. re-embed after an embedding
@@ -556,6 +559,11 @@ def update_command(
render_changed_files(file_diffs, verbose=verbose)
+ # Best-effort steps that fail from here on are collected (not swallowed)
+ # and rendered in the completion panel + `--progress json` done event, so
+ # "update complete" is only ever claimed when it is actually true.
+ degraded: list[str] = []
+
# Re-parse changed files and rebuild graph for affected pages
cfg = load_config(repo_path)
@@ -642,15 +650,20 @@ def update_command(
[fd.path for fd in file_diffs],
file_diffs=file_diffs,
knowledge_graph_result=knowledge_graph_result,
+ degraded=degraded,
)
except Exception as exc:
if emitter is not None:
emitter.error(str(exc))
raise
- _refresh_editor_stamp(repo_path, agents_md)
+ _refresh_editor_stamp(repo_path, agents_md, degraded)
if emitter is not None:
emitter.done(
- ok=True, pages_generated=0, cost_usd=0.0, duration_s=time.monotonic() - start
+ ok=True,
+ pages_generated=0,
+ cost_usd=0.0,
+ duration_s=time.monotonic() - start,
+ degraded=degraded,
)
return
@@ -709,6 +722,7 @@ def update_command(
f"New decision markers found: [green]{len(new_decision_markers)}[/green]"
)
except Exception as exc:
+ degraded.append(f"Decision re-scan: {exc}")
if verbose:
console.print(f"[yellow]Decision re-scan skipped: {exc}[/yellow]")
@@ -798,6 +812,7 @@ def update_command(
f"+{len(evo_regen)} governed page(s) queued for regen."
)
except Exception as exc:
+ degraded.append(f"Decision evolution: {exc}")
if verbose:
console.print(f"[yellow]Decision evolution skipped: {exc}[/yellow]")
@@ -827,7 +842,10 @@ def update_command(
try:
prior_pages = run_async(_load_prior())
- except Exception:
+ except Exception as exc:
+ # Without prior pages the prompt-hash skip is off and every affected
+ # page re-bills; surface that instead of silently paying it.
+ degraded.append(f"Prior-page reuse: {exc}")
prior_pages = {}
# Generate affected pages. The vector store (shared with the decision
@@ -878,6 +896,32 @@ def update_command(
else:
gen_progress.update(gen_task, advance=1, cost=cost_tracker.session_cost)
+ # Checkpoint each page to the DB as it lands: a crash mid-generation used
+ # to lose every finished page (persist ran only at the very end), so the
+ # rerun re-billed all of them. With the row persisted, the rerun's
+ # prompt-hash skip sees the fresh content and never re-calls the LLM.
+ from .persistence import PageCheckpointer
+
+ checkpointer = PageCheckpointer(repo_path, repo_name)
+
+ async def _generate_with_checkpoint() -> list:
+ await checkpointer.start()
+ try:
+ return await generator.generate_all(
+ affected_parsed,
+ affected_source,
+ graph_builder,
+ repo_structure,
+ repo_name,
+ on_page_done=_on_page_done,
+ on_total_known=_on_total_known,
+ git_meta_map=git_meta_map,
+ repo_path=repo_path,
+ on_page_ready=checkpointer.on_page_ready,
+ )
+ finally:
+ await checkpointer.close()
+
with make_generation_progress() if emitter is None else nullcontext() as gen_progress:
gen_task = (
gen_progress.add_task("Generating pages...", total=None, cost=0.0)
@@ -886,24 +930,15 @@ def update_command(
)
try:
- generated_pages = run_async(
- generator.generate_all(
- affected_parsed,
- affected_source,
- graph_builder,
- repo_structure,
- repo_name,
- on_page_done=_on_page_done,
- on_total_known=_on_total_known,
- git_meta_map=git_meta_map,
- repo_path=repo_path,
- )
- )
+ generated_pages = run_async(_generate_with_checkpoint())
except Exception as exc:
if emitter is not None:
emitter.error(str(exc))
raise
+ if checkpointer.failure:
+ degraded.append(f"Per-page crash checkpointing: {checkpointer.failure}")
+
# Flush the buffered LLM cost rows now that generation is done — a single
# transaction outside the contended generation window (issue #326).
from repowise.cli.providers import flush_cost_tracker
@@ -931,224 +966,37 @@ def update_command(
)
except Exception as exc:
console.print(f"[yellow]Knowledge-graph enrichment skipped: {exc}[/yellow]")
+ degraded.append(f"Knowledge-graph enrichment: {exc}")
- # Persist
- async def _persist() -> None:
- from repowise.cli.helpers import get_db_url_for_repo
- from repowise.core.persistence import (
- FullTextSearch,
- create_engine,
- create_session_factory,
- get_session,
- init_db,
- upsert_page_from_generated,
- upsert_repository,
- )
-
- url = get_db_url_for_repo(repo_path)
- engine = create_engine(url)
- await init_db(engine)
- sf = create_session_factory(engine)
-
- async with get_session(sf) as session:
- repo = await upsert_repository(session, name=repo_name, local_path=str(repo_path))
- repo_id = repo.id
- for page in generated_pages:
- await upsert_page_from_generated(session, page, repo_id)
- # Tombstone pages for deleted/renamed files — regeneration only
- # rewrites pages for files that still exist.
- try:
- from repowise.core.pipeline.persist import (
- mark_tombstone_pages,
- tombstone_candidates,
- )
-
- await mark_tombstone_pages(session, repo_id, tombstone_candidates(file_diffs))
- except Exception as exc:
- if verbose:
- console.print(f"[yellow]Tombstone marking skipped: {exc}[/yellow]")
-
- # Refreshed knowledge graph — same writers as the init pipeline
- # (full-replace layers/tour/curated meta).
- if knowledge_graph_result is not None:
- try:
- from repowise.core.pipeline.persist import persist_kg
-
- await persist_kg(knowledge_graph_result, session, repo_id)
- except Exception as exc:
- console.print(f"[yellow]Knowledge-graph persist skipped: {exc}[/yellow]")
-
- # Persist updated git metadata + recompute percentiles
- if git_meta_map:
- try:
- from repowise.core.persistence.crud import (
- recompute_git_percentiles,
- upsert_git_metadata_bulk,
- )
-
- async with get_session(sf) as session:
- await upsert_git_metadata_bulk(
- session,
- repo_id,
- list(git_meta_map.values()),
- )
- await recompute_git_percentiles(session, repo_id)
- await _persist_incremental_commits(session, repo_id, repo_path)
- except Exception:
- pass # git persistence is best-effort
-
- # Decision records: persist new markers + harvested decisions, detect
- # supersession, recompute staleness.
- try:
- decision_dicts: list[dict] = []
- if new_decision_markers:
- import dataclasses as _dc
-
- decision_dicts.extend(_dc.asdict(d) for d in new_decision_markers)
- # Phase-2 follow-up: also harvest decisions emitted by the page
- # generator during this update (each gated at generation time).
- for page in generated_pages:
- harvested = page.metadata.get("harvested_decisions")
- if harvested:
- decision_dicts.extend(harvested)
-
- if decision_dicts:
- from repowise.core.persistence.crud import bulk_upsert_decisions
-
- async with get_session(sf) as session:
- touched_ids = await bulk_upsert_decisions(
- session,
- repo_id,
- decision_dicts,
- vector_store=decision_vector_store,
- )
- # Phase 3B: supersede/conflict detection over the touched
- # records (gated LLM judge available on this path).
- if touched_ids and decision_vector_store is not None:
- from repowise.core.analysis.decision_evolution import (
- detect_supersessions_and_conflicts,
- )
-
- await detect_supersessions_and_conflicts(
- session,
- repo_id,
- touched_ids=touched_ids,
- vector_store=decision_vector_store,
- provider=provider,
- )
-
- if git_meta_map:
- from repowise.core.persistence.crud import recompute_decision_staleness
-
- async with get_session(sf) as session:
- await recompute_decision_staleness(session, repo_id, git_meta_map)
-
- # Governance findings pass: runs after decisions + staleness are
- # up to date. Best-effort — never breaks the update.
- try:
- from sqlalchemy import select as _sel_dec
-
- from repowise.core.analysis.health.governance import build_governance_findings
- from repowise.core.persistence.crud import (
- get_decision_health_summary,
- replace_governance_findings,
- )
- from repowise.core.persistence.models import DecisionRecord
-
- async with get_session(sf) as session:
- _dr = await session.execute(
- _sel_dec(DecisionRecord).where(DecisionRecord.repository_id == repo_id)
- )
- _decisions = list(_dr.scalars().all())
- _summary = await get_decision_health_summary(session, repo_id)
- _gov = build_governance_findings(
- health_summary=_summary,
- decisions=_decisions,
- )
- await replace_governance_findings(session, repo_id, _gov)
- except Exception:
- pass # governance findings are best-effort
- except Exception:
- pass # never fail update due to decision processing
-
- # Persist code-health findings + metrics (partial — upsert only)
- if partial_health_report is not None:
- try:
- async with get_session(sf) as session:
- await _persist_partial_health(session, repo_id, partial_health_report)
- except Exception:
- pass # health persistence is best-effort
-
- # Scoped to changed files so unchanged files keep their findings (#295).
- if dead_code_report is not None:
- try:
- import dataclasses as _dc_dead
-
- from repowise.core.persistence.crud import upsert_dead_code_findings
-
- async with get_session(sf) as session:
- await upsert_dead_code_findings(
- session,
- repo_id,
- [_dc_dead.asdict(f) for f in dead_code_report.findings],
- file_paths=[fd.path for fd in file_diffs],
- )
- except Exception:
- pass # dead code persistence is best-effort
-
- # Re-persist graph_nodes so symbol-level PageRank / betweenness
- # / community ids reflect the current build. Same rationale as
- # the index-only branch above — without this every per-symbol
- # metric stays at its original value forever.
- try:
- from repowise.core.pipeline.persist import persist_graph_nodes
-
- async with get_session(sf) as session:
- await persist_graph_nodes(session, repo_id, graph_builder)
- except Exception:
- pass # graph node persistence is best-effort
-
- # Record a GenerationJob so the web UI "last synced" timestamp updates
- try:
- from datetime import UTC as _UTC
- from datetime import datetime
-
- from repowise.core.persistence.crud import upsert_generation_job
-
- async with get_session(sf) as session:
- now = datetime.now(_UTC)
- page_count = len(generated_pages)
- job = await upsert_generation_job(
- session,
- repository_id=repo_id,
- status="completed",
- total_pages=page_count,
- config={"mode": "incremental", "source": "cli_update"},
- )
- job.completed_pages = page_count
- job.started_at = now
- job.finished_at = now
- except Exception:
- pass # job recording is best-effort
-
- fts = FullTextSearch(engine)
- await fts.ensure_index()
- for page in generated_pages:
- await fts.index(page.page_id, page.title, page.content)
-
- await engine.dispose()
+ # Persist everything in one transaction (pages fail loudly, derived
+ # layers degrade into the collected list) — see _persist_full_update.
+ from .persistence import _persist_full_update
if emitter is not None:
emitter.stage("persist")
try:
- run_async(_persist())
+ _persist_full_update(
+ repo_path=repo_path,
+ repo_name=repo_name,
+ generated_pages=generated_pages,
+ file_diffs=file_diffs,
+ git_meta_map=git_meta_map,
+ new_decision_markers=new_decision_markers,
+ decision_vector_store=decision_vector_store,
+ provider=provider,
+ partial_health_report=partial_health_report,
+ dead_code_report=dead_code_report,
+ graph_builder=graph_builder,
+ knowledge_graph_result=knowledge_graph_result,
+ degraded=degraded,
+ )
except Exception as exc:
if emitter is not None:
emitter.error(str(exc))
raise
# ---- Editor project files (best-effort) ----
- _refresh_editor_stamp(repo_path, agents_md)
+ _refresh_editor_stamp(repo_path, agents_md, degraded)
# Update state
from repowise.cli.helpers import config_fingerprint
@@ -1161,6 +1009,7 @@ def update_command(
state["knowledge_graph"] = build_kg_state(knowledge_graph_result)
except Exception as exc:
console.print(f"[yellow]Knowledge-graph export skipped: {exc}[/yellow]")
+ degraded.append(f"Knowledge-graph export: {exc}")
state["last_sync_commit"] = head
state["total_pages"] = state.get("total_pages", 0) + len(generated_pages)
@@ -1198,8 +1047,10 @@ def update_command(
console.print("Running cross-repo analysis...")
run_async(run_cross_repo_hooks(ws_config, ws_root, [alias]))
console.print("[green]Cross-repo analysis updated.[/green]")
- except Exception:
- pass # cross-repo hooks must never fail the update
+ except Exception as exc:
+ # Cross-repo hooks must never fail the update, but a stale cross-repo
+ # layer should not masquerade as a fully clean run.
+ degraded.append(f"Cross-repo analysis: {exc}")
elapsed = time.monotonic() - start
if emitter is not None:
@@ -1208,6 +1059,7 @@ def update_command(
pages_generated=len(generated_pages),
cost_usd=cost_tracker.session_cost,
duration_s=elapsed,
+ degraded=degraded,
)
return
show_full_completion(
@@ -1218,6 +1070,7 @@ def update_command(
cost=cost_tracker.session_cost,
tokens=cost_tracker.session_tokens,
elapsed=elapsed,
+ degraded=degraded,
)
if verbose:
_render_update_report(generated_pages, affected, new_decision_markers, elapsed)
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 9959cc11b..6bd4b7315 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -12,10 +12,14 @@ import time
from pathlib import Path
from typing import Any
+import structlog
+
from repowise.cli.helpers import console, run_async, save_state
from .incremental import _build_repo_graph
+log = structlog.get_logger(__name__)
+
async def _coverage_for_rescore(
session: Any,
@@ -135,15 +139,18 @@ def _persist_index_only_update(
changed_paths: list[str],
file_diffs: list | None = None,
knowledge_graph_result: Any | None = None,
+ degraded: list[str] | None = None,
) -> None:
"""Persist the index-only update (graph + git + dead-code + health + KG),
save state, and print the completion line. No LLM regeneration.
DB persistence delegates to :mod:`repowise.core.pipeline.incremental`;
- state-file updates and console reporting stay here.
+ state-file updates and console reporting stay here. Best-effort steps
+ that fail land in ``degraded`` and surface in the completion panel.
"""
from repowise.core.pipeline.incremental import persist_incremental_index
+ degraded = degraded if degraded is not None else []
run_async(
persist_incremental_index(
repo_path,
@@ -155,6 +162,7 @@ def _persist_index_only_update(
file_diffs=file_diffs,
knowledge_graph_result=knowledge_graph_result,
log=console.print,
+ degraded=degraded,
)
)
from repowise.cli.helpers import config_fingerprint
@@ -172,6 +180,7 @@ def _persist_index_only_update(
new_state["knowledge_graph"] = build_kg_state(knowledge_graph_result)
except Exception as exc:
console.print(f"[yellow]Knowledge-graph export skipped: {exc}[/yellow]")
+ degraded.append(f"Knowledge-graph export: {exc}")
save_state(repo_path, new_state)
elapsed = time.monotonic() - start
from .reporting import show_index_only_completion
@@ -182,9 +191,354 @@ def _persist_index_only_update(
changed_count=len(changed_paths),
git_files=len(git_meta_map or {}),
elapsed=elapsed,
+ degraded=degraded,
)
+class PageCheckpointer:
+ """Best-effort per-page persistence during update-time generation.
+
+ The final persist runs only after ALL pages are generated, so a crash
+ midway used to re-bill every already-generated page on the next run:
+ nothing durable recorded them. This sink upserts each page's DB row as
+ it lands; on the rerun the generator's prompt-hash skip sees the
+ persisted content and never re-calls the LLM for it.
+
+ Purely a checkpoint: the final persist re-upserts every page anyway
+ (idempotent), so any failure here flips the sink off, records one
+ degraded entry, and the run continues exactly as before. Writes are
+ serialized through a queue consumed by a single task, one short
+ transaction per page, on a dedicated engine — generation itself only
+ writes the vector store, so wiki.db is uncontended during this window.
+ """
+
+ def __init__(self, repo_path: Any, repo_name: str) -> None:
+ self.repo_path = repo_path
+ self.repo_name = repo_name
+ self.failure: str | None = None
+ self.persisted = 0
+ self._queue: Any | None = None
+ self._task: Any | None = None
+ self._engine: Any | None = None
+ self._session_factory: Any | None = None
+
+ async def start(self) -> None:
+ import asyncio
+
+ try:
+ from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.core.persistence import create_engine, create_session_factory
+
+ self._engine = create_engine(get_db_url_for_repo(self.repo_path))
+ self._session_factory = create_session_factory(self._engine)
+ self._queue = asyncio.Queue()
+ self._task = asyncio.create_task(self._drain())
+ except Exception as exc:
+ self.failure = str(exc)
+
+ def on_page_ready(self, page: Any) -> None:
+ """Sync callback handed to ``generate_all`` — enqueue, never block."""
+ if self._queue is not None and self.failure is None:
+ self._queue.put_nowait(page)
+
+ async def _drain(self) -> None:
+ from repowise.core.persistence import (
+ get_session,
+ upsert_page_from_generated,
+ upsert_repository,
+ )
+
+ repo_id: str | None = None
+ while True:
+ page = await self._queue.get()
+ if page is None:
+ return
+ if self.failure is not None:
+ continue # keep consuming so close() never hangs
+ try:
+ async with get_session(self._session_factory) as session:
+ if repo_id is None:
+ repo = await upsert_repository(
+ session, name=self.repo_name, local_path=str(self.repo_path)
+ )
+ repo_id = repo.id
+ await upsert_page_from_generated(session, page, repo_id)
+ self.persisted += 1
+ except Exception as exc:
+ self.failure = str(exc)
+ log.warning("page_checkpoint_disabled", error=str(exc))
+
+ async def close(self) -> None:
+ if self._queue is not None and self._task is not None:
+ self._queue.put_nowait(None)
+ await self._task
+ if self._engine is not None:
+ await self._engine.dispose()
+
+
+def _persist_full_update(
+ *,
+ repo_path: Any,
+ repo_name: str,
+ generated_pages: list,
+ file_diffs: list,
+ git_meta_map: dict,
+ new_decision_markers: list,
+ decision_vector_store: Any | None,
+ provider: Any,
+ partial_health_report: Any,
+ dead_code_report: Any,
+ graph_builder: Any,
+ knowledge_graph_result: Any | None,
+ degraded: list[str],
+) -> None:
+ """Persist a full (LLM-regenerating) update in one transaction.
+
+ Mirrors :func:`repowise.core.pipeline.incremental.persist_incremental_index`:
+ one engine, one session, so a crash rolls the whole batch back instead of
+ leaving pages committed but health/git/graph rows from the previous
+ commit (the old shape here was eight separate auto-committing sessions).
+ Page upserts fail loudly — pages are the point of docs mode; every other
+ step degrades into ``degraded`` with a logged warning. FTS indexing stays
+ outside the transaction: it is rebuildable and non-transactional anyway.
+ """
+ run_async(
+ _persist_full_update_async(
+ repo_path=repo_path,
+ repo_name=repo_name,
+ generated_pages=generated_pages,
+ file_diffs=file_diffs,
+ git_meta_map=git_meta_map,
+ new_decision_markers=new_decision_markers,
+ decision_vector_store=decision_vector_store,
+ provider=provider,
+ partial_health_report=partial_health_report,
+ dead_code_report=dead_code_report,
+ graph_builder=graph_builder,
+ knowledge_graph_result=knowledge_graph_result,
+ degraded=degraded,
+ )
+ )
+
+
+async def _persist_full_update_async(
+ *,
+ repo_path: Any,
+ repo_name: str,
+ generated_pages: list,
+ file_diffs: list,
+ git_meta_map: dict,
+ new_decision_markers: list,
+ decision_vector_store: Any | None,
+ provider: Any,
+ partial_health_report: Any,
+ dead_code_report: Any,
+ graph_builder: Any,
+ knowledge_graph_result: Any | None,
+ degraded: list[str],
+) -> None:
+ from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.core.persistence import (
+ FullTextSearch,
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_page_from_generated,
+ upsert_repository,
+ )
+
+ def _skip(step: str, exc: Exception) -> None:
+ log.warning("update_persist_step_degraded", step=step, error=str(exc))
+ degraded.append(f"{step}: {exc}")
+
+ url = get_db_url_for_repo(repo_path)
+ engine = create_engine(url)
+ try:
+ await init_db(engine)
+ sf = create_session_factory(engine)
+
+ async with get_session(sf) as session:
+ repo = await upsert_repository(session, name=repo_name, local_path=str(repo_path))
+ repo_id = repo.id
+
+ # Pages first and without a net: everything else is derived
+ # metadata, but a docs-mode update that can't write pages failed.
+ for page in generated_pages:
+ await upsert_page_from_generated(session, page, repo_id)
+
+ # Tombstone pages for deleted/renamed files — regeneration only
+ # rewrites pages for files that still exist.
+ try:
+ from repowise.core.pipeline.persist import (
+ mark_tombstone_pages,
+ tombstone_candidates,
+ )
+
+ await mark_tombstone_pages(session, repo_id, tombstone_candidates(file_diffs))
+ except Exception as exc:
+ _skip("Tombstone marking", exc)
+
+ # Refreshed knowledge graph — same writers as the init pipeline
+ # (full-replace layers/tour/curated meta).
+ if knowledge_graph_result is not None:
+ try:
+ from repowise.core.pipeline.persist import persist_kg
+
+ await persist_kg(knowledge_graph_result, session, repo_id)
+ except Exception as exc:
+ _skip("Knowledge-graph persist", exc)
+
+ # Updated git metadata + recomputed percentiles + new commit rows.
+ if git_meta_map:
+ try:
+ from repowise.core.persistence.crud import (
+ recompute_git_percentiles,
+ upsert_git_metadata_bulk,
+ )
+
+ await upsert_git_metadata_bulk(session, repo_id, list(git_meta_map.values()))
+ await recompute_git_percentiles(session, repo_id)
+ except Exception as exc:
+ _skip("Git persist", exc)
+ try:
+ await _persist_incremental_commits(session, repo_id, repo_path)
+ except Exception as exc:
+ _skip("Commit capture", exc)
+
+ # Decision records: new markers + harvested decisions, supersession
+ # detection, staleness recompute.
+ try:
+ decision_dicts: list[dict] = []
+ if new_decision_markers:
+ import dataclasses as _dc
+
+ decision_dicts.extend(_dc.asdict(d) for d in new_decision_markers)
+ for page in generated_pages:
+ harvested = page.metadata.get("harvested_decisions")
+ if harvested:
+ decision_dicts.extend(harvested)
+
+ if decision_dicts:
+ from repowise.core.persistence.crud import bulk_upsert_decisions
+
+ touched_ids = await bulk_upsert_decisions(
+ session,
+ repo_id,
+ decision_dicts,
+ vector_store=decision_vector_store,
+ )
+ if touched_ids and decision_vector_store is not None:
+ from repowise.core.analysis.decision_evolution import (
+ detect_supersessions_and_conflicts,
+ )
+
+ await detect_supersessions_and_conflicts(
+ session,
+ repo_id,
+ touched_ids=touched_ids,
+ vector_store=decision_vector_store,
+ provider=provider,
+ )
+
+ if git_meta_map:
+ from repowise.core.persistence.crud import recompute_decision_staleness
+
+ await recompute_decision_staleness(session, repo_id, git_meta_map)
+ except Exception as exc:
+ _skip("Decision persist", exc)
+
+ # Governance findings pass: runs after decisions + staleness.
+ try:
+ from sqlalchemy import select as _sel_dec
+
+ from repowise.core.analysis.health.governance import build_governance_findings
+ from repowise.core.persistence.crud import (
+ get_decision_health_summary,
+ replace_governance_findings,
+ )
+ from repowise.core.persistence.models import DecisionRecord
+
+ _dr = await session.execute(
+ _sel_dec(DecisionRecord).where(DecisionRecord.repository_id == repo_id)
+ )
+ _decisions = list(_dr.scalars().all())
+ _summary = await get_decision_health_summary(session, repo_id)
+ _gov = build_governance_findings(
+ health_summary=_summary,
+ decisions=_decisions,
+ )
+ await replace_governance_findings(session, repo_id, _gov)
+ except Exception as exc:
+ _skip("Governance findings", exc)
+
+ # Code-health findings + metrics (partial — upsert only).
+ if partial_health_report is not None:
+ try:
+ await _persist_partial_health(session, repo_id, partial_health_report)
+ except Exception as exc:
+ _skip("Health persist", exc)
+
+ # Scoped to changed files so unchanged files keep their findings (#295).
+ if dead_code_report is not None:
+ try:
+ import dataclasses as _dc_dead
+
+ from repowise.core.persistence.crud import upsert_dead_code_findings
+
+ await upsert_dead_code_findings(
+ session,
+ repo_id,
+ [_dc_dead.asdict(f) for f in dead_code_report.findings],
+ file_paths=[fd.path for fd in file_diffs],
+ )
+ except Exception as exc:
+ _skip("Dead-code persist", exc)
+
+ # Re-persist graph_nodes so symbol-level PageRank / betweenness /
+ # community ids reflect the current build.
+ try:
+ from repowise.core.pipeline.persist import persist_graph_nodes
+
+ await persist_graph_nodes(session, repo_id, graph_builder)
+ except Exception as exc:
+ _skip("Graph nodes persist", exc)
+
+ # Record a GenerationJob so the web UI "last synced" timestamp updates.
+ try:
+ from datetime import UTC as _UTC
+ from datetime import datetime
+
+ from repowise.core.persistence.crud import upsert_generation_job
+
+ now = datetime.now(_UTC)
+ page_count = len(generated_pages)
+ job = await upsert_generation_job(
+ session,
+ repository_id=repo_id,
+ status="completed",
+ total_pages=page_count,
+ config={"mode": "incremental", "source": "cli_update"},
+ )
+ job.completed_pages = page_count
+ job.started_at = now
+ job.finished_at = now
+ except Exception as exc:
+ _skip("Generation job record", exc)
+
+ # FTS outside the transaction — rebuildable, and its writer manages
+ # its own connection state.
+ try:
+ fts = FullTextSearch(engine)
+ await fts.ensure_index()
+ for page in generated_pages:
+ await fts.index(page.page_id, page.title, page.content)
+ except Exception as exc:
+ _skip("Full-text search indexing", exc)
+ finally:
+ await engine.dispose()
+
+
def _git_metadata_to_dict(gm: Any) -> dict[str, Any]:
"""Convert a GitMetadata ORM row to the dict format HealthAnalyzer expects."""
return {
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py b/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py
index a7647fa67..c2cab5f01 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py
@@ -123,7 +123,15 @@ class JsonProgressEmitter:
{"event": "page_done", "completed": completed, "total": total, "cost_usd": cost_usd}
)
- def done(self, *, ok: bool, pages_generated: int, cost_usd: float, duration_s: float) -> None:
+ def done(
+ self,
+ *,
+ ok: bool,
+ pages_generated: int,
+ cost_usd: float,
+ duration_s: float,
+ degraded: list[str] | None = None,
+ ) -> None:
self._emit(
{
"event": "done",
@@ -131,6 +139,7 @@ class JsonProgressEmitter:
"pages_generated": pages_generated,
"cost_usd": cost_usd,
"duration_s": duration_s,
+ "degraded": degraded or [],
}
)
@@ -143,6 +152,26 @@ class JsonProgressEmitter:
# ---------------------------------------------------------------------------
+def render_degraded(degraded: list[str] | None) -> None:
+ """Warn about best-effort steps that failed during this update.
+
+ These used to be swallowed (``except Exception: pass``), so the update
+ claimed clean success while, say, git metadata or graph nodes silently
+ stayed at the previous commit. The run still exits 0 — every listed step
+ is retried by the next update — but the panel must not say "complete"
+ without this block when something was skipped.
+ """
+ if not degraded:
+ return
+ console.print()
+ console.print(
+ f"[yellow]Update completed with {len(degraded)} degraded step(s) "
+ "(will retry on the next update):[/yellow]"
+ )
+ for entry in degraded:
+ console.print(f" [yellow]-[/yellow] {entry}")
+
+
def _dead_code_counts(dead_code_report: Any) -> tuple[int, int]:
"""Return ``(unreachable_files, unused_exports)`` from a dead-code report."""
findings = dead_code_report.findings if dead_code_report else []
@@ -160,9 +189,13 @@ def show_full_completion(
cost: float,
tokens: int,
elapsed: float,
+ degraded: list[str] | None = None,
) -> None:
"""Render the completion panel for a full (LLM-regenerating) update."""
+ render_degraded(degraded)
metrics: list[tuple[str, str]] = [("Pages updated", str(len(generated_pages)))]
+ if degraded:
+ metrics.append(("Degraded", f"{len(degraded)} step(s)"))
if decay_count:
metrics.append(("Pages decayed", str(decay_count)))
if decisions_changed:
@@ -191,8 +224,10 @@ def show_index_only_completion(
changed_count: int,
git_files: int,
elapsed: float,
+ degraded: list[str] | None = None,
) -> None:
"""Render the completion panel for an index-only update (no LLM regen)."""
+ render_degraded(degraded)
graph = graph_builder.graph()
unreachable, unused = _dead_code_counts(dead_code_report)
@@ -201,6 +236,8 @@ def show_index_only_completion(
("Graph", f"{graph.number_of_nodes():,} nodes · {graph.number_of_edges():,} edges"),
("Dead code", f"{unreachable} unreachable · {unused} unused exports"),
]
+ if degraded:
+ metrics.append(("Degraded", f"{len(degraded)} step(s)"))
if git_files:
metrics.append(("Git history", f"{git_files} files refreshed"))
metrics.append(("Elapsed", format_elapsed(elapsed)))
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 48cdf9428..1b8c5ad9c 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -31,15 +31,15 @@ from repowise.core.update_lock import (
from repowise.core.update_lock import (
UPDATE_LOCK_STALE_AFTER_SECONDS as UPDATE_LOCK_STALE_AFTER_SECONDS,
)
-from repowise.core.update_lock import (
- acquire_update_lock as acquire_update_lock,
-)
from repowise.core.update_lock import (
read_update_lock as read_update_lock,
)
from repowise.core.update_lock import (
release_update_lock as release_update_lock,
)
+from repowise.core.update_lock import (
+ try_acquire_update_lock as try_acquire_update_lock,
+)
T = TypeVar("T")
@@ -229,8 +229,12 @@ def save_state(repo_path: Path, state: dict[str, Any]) -> None:
_stamp_store_version(state, package_version=_pkg_version)
except Exception: # never let stamping block a persist
pass
+ from repowise.core.fsutils import atomic_write_text
+
+ # Atomic so a crash mid-write can never leave a truncated state.json —
+ # every later update would fail to parse it and demand a full re-init.
state_path = get_repowise_dir(repo_path) / STATE_FILENAME
- state_path.write_text(json.dumps(state, indent=2), encoding="utf-8")
+ atomic_write_text(state_path, json.dumps(state, indent=2))
# ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/fsutils.py b/packages/core/src/repowise/core/fsutils.py
new file mode 100644
index 000000000..328e690b3
--- /dev/null
+++ b/packages/core/src/repowise/core/fsutils.py
@@ -0,0 +1,24 @@
+"""Small filesystem helpers shared across core and the CLI."""
+
+from __future__ import annotations
+
+import tempfile
+from pathlib import Path
+
+
+def atomic_write_text(path: Path, content: str, *, newline: str | None = None) -> None:
+ """Write *content* to *path* atomically via a temp file + rename.
+
+ Readers never observe a truncated or half-written file: the temp file is
+ created in the destination directory (same filesystem, so the rename is
+ atomic) and either replaces *path* wholesale or is cleaned up on failure.
+ """
+ parent = path.parent
+ fd, tmp = tempfile.mkstemp(dir=parent, suffix=".tmp")
+ try:
+ with open(fd, "w", encoding="utf-8", newline=newline) as f:
+ f.write(content)
+ Path(tmp).replace(path)
+ except Exception:
+ Path(tmp).unlink(missing_ok=True)
+ raise
diff --git a/packages/core/src/repowise/core/generation/editor_files/base.py b/packages/core/src/repowise/core/generation/editor_files/base.py
index 50e3b5568..3547e3ba2 100644
--- a/packages/core/src/repowise/core/generation/editor_files/base.py
+++ b/packages/core/src/repowise/core/generation/editor_files/base.py
@@ -12,12 +12,13 @@ Merge rules:
from __future__ import annotations
import re
-import tempfile
from abc import ABC, abstractmethod
from pathlib import Path
import jinja2
+from repowise.core.fsutils import atomic_write_text
+
from .data import EditorFileData
@@ -97,7 +98,7 @@ class BaseEditorFileGenerator(ABC):
# Append managed section; preserve all existing content
content = existing.rstrip() + "\n\n" + wrapped + "\n"
- _atomic_write(target, content)
+ atomic_write_text(target, content, newline="\n")
return target
def render_full(self, repo_path: Path, data: EditorFileData) -> str:
@@ -114,16 +115,3 @@ class BaseEditorFileGenerator(ABC):
pattern = re.escape(marker_start) + r".*?" + re.escape(marker_end)
return re.sub(pattern, wrapped, existing, flags=re.DOTALL)
return existing.rstrip() + "\n\n" + wrapped + "\n"
-
-
-def _atomic_write(path: Path, content: str) -> None:
- """Write *content* to *path* atomically via a temp file + rename."""
- parent = path.parent
- fd, tmp = tempfile.mkstemp(dir=parent, suffix=".tmp")
- try:
- with open(fd, "w", encoding="utf-8", newline="\n") as f:
- f.write(content)
- Path(tmp).replace(path)
- except Exception:
- Path(tmp).unlink(missing_ok=True)
- raise
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 87f6204f9..82c1d97fd 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -539,12 +539,17 @@ async def persist_incremental_index(
file_diffs: list[Any] | None = None,
knowledge_graph_result: Any | None = None,
log: LogFn | None = None,
+ degraded: list[str] | None = None,
) -> None:
"""Persist an incremental index refresh (graph + git + dead-code + health).
Upsert-only: unchanged files keep their existing rows, unlike
``persist_pipeline_result``'s delete-then-insert. State-file updates stay
with the caller — this writes the DB only.
+
+ ``degraded`` (when supplied) collects a one-line entry for every
+ best-effort step that failed, so the caller can render an honest
+ completion report instead of silently claiming success.
"""
from repowise.core.persistence import (
create_engine,
@@ -557,6 +562,11 @@ async def persist_incremental_index(
log = log or _noop_log
+ def _skip(step: str, exc: Exception) -> None:
+ log(f"[yellow]{step} skipped: {exc}[/yellow]")
+ if degraded is not None:
+ degraded.append(f"{step}: {exc}")
+
url = resolve_db_url(repo_path)
engine = create_engine(url)
try:
@@ -573,7 +583,7 @@ async def persist_incremental_index(
await _prune_stale_file_rows(session, repo_id, current_graph_file_paths, set())
except Exception as exc:
- log(f"[yellow]Stale row prune skipped: {exc}[/yellow]")
+ _skip("Stale row prune", exc)
# Tombstone pages for deleted/renamed files FIRST — a fresh page
# for a file that no longer exists misleads every retrieval
@@ -587,7 +597,7 @@ async def persist_incremental_index(
await mark_tombstone_pages(session, repo_id, tombstone_candidates(file_diffs))
except Exception as exc:
- log(f"[yellow]Tombstone marking skipped: {exc}[/yellow]")
+ _skip("Tombstone marking", exc)
if git_meta_map:
try:
@@ -599,12 +609,12 @@ async def persist_incremental_index(
await upsert_git_metadata_bulk(session, repo_id, list(git_meta_map.values()))
await recompute_git_percentiles(session, repo_id)
except Exception as exc:
- log(f"[yellow]Git persist skipped: {exc}[/yellow]")
+ _skip("Git persist", exc)
try:
await persist_incremental_commits(session, repo_id, repo_path)
except Exception as exc:
- log(f"[yellow]Commit capture skipped: {exc}[/yellow]")
+ _skip("Commit capture", exc)
if dead_code_report is not None:
try:
@@ -616,13 +626,13 @@ async def persist_incremental_index(
session, repo_id, dead_code_report.findings, file_paths=changed_paths
)
except Exception as exc:
- log(f"[yellow]Dead-code persist skipped: {exc}[/yellow]")
+ _skip("Dead-code persist", exc)
if partial_health_report is not None:
try:
await persist_partial_health(session, repo_id, partial_health_report)
except Exception as exc:
- log(f"[yellow]Health persist skipped: {exc}[/yellow]")
+ _skip("Health persist", exc)
# Re-persist graph_nodes so symbol-level PageRank /
# betweenness / community ids stay in sync with the
@@ -635,7 +645,7 @@ async def persist_incremental_index(
await persist_graph_nodes(session, repo_id, graph_builder)
except Exception as exc:
- log(f"[yellow]Graph nodes persist skipped: {exc}[/yellow]")
+ _skip("Graph nodes persist", exc)
if knowledge_graph_result is not None:
try:
@@ -643,6 +653,6 @@ async def persist_incremental_index(
await persist_kg(knowledge_graph_result, session, repo_id)
except Exception as exc:
- log(f"[yellow]Knowledge-graph persist skipped: {exc}[/yellow]")
+ _skip("Knowledge-graph persist", exc)
finally:
await engine.dispose()
diff --git a/packages/core/src/repowise/core/update_lock.py b/packages/core/src/repowise/core/update_lock.py
index 59643bd56..92c63fee2 100644
--- a/packages/core/src/repowise/core/update_lock.py
+++ b/packages/core/src/repowise/core/update_lock.py
@@ -28,16 +28,24 @@ def update_lock_path(repo_path: Path) -> Path:
return Path(repo_path) / ".repowise" / UPDATE_LOCK_FILENAME
-def acquire_update_lock(repo_path: Path, target_commit: str | None) -> Path:
- """Write the update lock file. Returns its path.
-
- The lock contains the PID and target commit so the augment hook can
+def try_acquire_update_lock(repo_path: Path, target_commit: str | None) -> dict[str, Any] | None:
+ """Atomically acquire the update lock. ``None`` means acquired.
+
+ Returns the live owner's payload when another update already holds the
+ lock, so the caller can report who it lost to and bail. The check and
+ the write are one exclusive create (``O_EXCL``) — the previous
+ read-then-write pair left a window where two updates racing past the
+ read would both "acquire" and then race on save_state, the exact
+ failure the lock exists to prevent. A stale lock (dead or recycled PID,
+ or past the wall-clock ceiling) is cleared and the create retried.
+
+ The payload contains the PID and target commit so the augment hook can
decide whether a stale-wiki warning is redundant, plus the writing
process's creation-time token so ``read_update_lock`` can tell a live
lock owner apart from an unrelated process that recycled the PID.
- Best-effort: if write fails (read-only fs, permissions), returns the
- path anyway — callers must still call ``release_update_lock`` in a
- finally block.
+ Best-effort: unexpected ``OSError`` (read-only fs, permissions) counts
+ as acquired — the lock is advisory and must never block an update.
+ Callers must still call ``release_update_lock`` in a finally block.
"""
from repowise.core.procutils import process_create_token
@@ -48,12 +56,27 @@ def acquire_update_lock(repo_path: Path, target_commit: str | None) -> Path:
"target_commit": target_commit,
"started_at": time.time(),
}
- try:
- lock_path.parent.mkdir(parents=True, exist_ok=True)
- lock_path.write_text(json.dumps(payload), encoding="utf-8")
- except OSError:
- pass
- return lock_path
+ data = json.dumps(payload)
+ for _ in range(2):
+ try:
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ fd = os.open(lock_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
+ except FileExistsError:
+ existing = read_update_lock(repo_path)
+ if existing is not None:
+ return existing
+ # Stale or corrupt lock: clear it and retry the exclusive create.
+ with contextlib.suppress(OSError):
+ lock_path.unlink(missing_ok=True)
+ continue
+ except OSError:
+ return None
+ with contextlib.suppress(OSError), os.fdopen(fd, "w", encoding="utf-8") as f:
+ f.write(data)
+ return None
+ # Lost the create race twice in a row: someone else just acquired a
+ # fresh lock — report it. A still-unreadable lock degrades to acquired.
+ return read_update_lock(repo_path)
def release_update_lock(repo_path: Path) -> None:
diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.py
index 6d275702a..9d19acf01 100644
--- a/packages/core/src/repowise/core/workspace/update.py
+++ b/packages/core/src/repowise/core/workspace/update.py
@@ -25,13 +25,10 @@ from typing import Any
# bypassing the CLI lock acquisition in update_cmd, so workspace updates are
# themselves single-flight per repo.
from repowise.core.update_lock import (
- acquire_update_lock as _acquire_lock,
-)
-from repowise.core.update_lock import (
- read_update_lock as _read_lock,
+ release_update_lock as _release_lock,
)
from repowise.core.update_lock import (
- release_update_lock as _release_lock,
+ try_acquire_update_lock as _try_acquire_lock,
)
from .config import WorkspaceConfig
@@ -630,11 +627,12 @@ async def update_workspace(
# first-time indexing has a place to put wiki.db and state.json.
(path / ".repowise").mkdir(parents=True, exist_ok=True)
- # Per-repo single-flight check. The post-commit hook fires a
+ # Per-repo single-flight lock. The post-commit hook fires a
# new ``repowise update`` for every commit; without this guard,
# rapid-fire commits race on save_state, each pass starts from
# the same stale base, and the wiki never converges to HEAD.
- existing = _read_lock(path)
+ # Check + acquire are one atomic exclusive create.
+ existing = _try_acquire_lock(path, new_head)
if existing is not None:
elapsed = int(time.time() - existing.get("started_at", time.time()))
target_short = (existing.get("target_commit") or "")[:8]
@@ -655,7 +653,6 @@ async def update_workspace(
skipped_reason="in_flight",
)
- _acquire_lock(path, new_head)
try:
result = await update_single_repo_index(
path,
@@ -695,11 +692,10 @@ async def update_workspace(
"first-time index via update; run "
"`repowise update --repo " + alias + " --docs` to generate docs"
)
+ from ..fsutils import atomic_write_text
+
state_path.parent.mkdir(parents=True, exist_ok=True)
- state_path.write_text(
- _json.dumps(state, indent=2),
- encoding="utf-8",
- )
+ atomic_write_text(state_path, _json.dumps(state, indent=2))
# Keep the DB freshness stamp in lockstep with last_sync_commit.
# The no-relevant-changes incremental path returns updated=True
# without re-running DB persistence, so the row would otherwise
diff --git a/tests/unit/cli/test_helpers.py b/tests/unit/cli/test_helpers.py
index e8320191b..b49d151ce 100644
--- a/tests/unit/cli/test_helpers.py
+++ b/tests/unit/cli/test_helpers.py
@@ -261,9 +261,9 @@ class TestConfigFingerprint:
class TestUpdateLock:
def test_acquire_writes_payload(self, tmp_path):
- from repowise.cli.helpers import acquire_update_lock, read_update_lock
+ from repowise.cli.helpers import read_update_lock, try_acquire_update_lock
- acquire_update_lock(tmp_path, "abc123def")
+ assert try_acquire_update_lock(tmp_path, "abc123def") is None
payload = read_update_lock(tmp_path)
assert payload is not None
assert payload["target_commit"] == "abc123def"
@@ -272,12 +272,12 @@ class TestUpdateLock:
def test_release_removes_lock(self, tmp_path):
from repowise.cli.helpers import (
- acquire_update_lock,
read_update_lock,
release_update_lock,
+ try_acquire_update_lock,
)
- acquire_update_lock(tmp_path, "abc")
+ try_acquire_update_lock(tmp_path, "abc")
release_update_lock(tmp_path)
assert read_update_lock(tmp_path) is None
diff --git a/tests/unit/cli/test_update_lock.py b/tests/unit/cli/test_update_lock.py
index 5f2bf7f06..9d5b16e4f 100644
--- a/tests/unit/cli/test_update_lock.py
+++ b/tests/unit/cli/test_update_lock.py
@@ -41,7 +41,7 @@ def _write_lock(repo: Path, payload: dict) -> None:
def test_acquire_records_pid_and_create_token(tmp_path: Path) -> None:
- helpers.acquire_update_lock(tmp_path, "abc123")
+ assert helpers.try_acquire_update_lock(tmp_path, "abc123") is None
payload = json.loads(
(tmp_path / ".repowise" / ".update.lock").read_text(encoding="utf-8")
@@ -52,13 +52,47 @@ def test_acquire_records_pid_and_create_token(tmp_path: Path) -> None:
def test_fresh_lock_with_live_pid_is_honored(tmp_path: Path) -> None:
- helpers.acquire_update_lock(tmp_path, "abc123")
+ assert helpers.try_acquire_update_lock(tmp_path, "abc123") is None
payload = helpers.read_update_lock(tmp_path)
assert payload is not None
assert payload["pid"] == os.getpid()
+def test_second_acquire_returns_live_owner(tmp_path: Path) -> None:
+ """Check + acquire are one atomic step: a live lock blocks the second
+ caller and hands back the owner's payload instead of overwriting."""
+ assert helpers.try_acquire_update_lock(tmp_path, "first") is None
+
+ blocked_by = helpers.try_acquire_update_lock(tmp_path, "second")
+ assert blocked_by is not None
+ assert blocked_by["target_commit"] == "first"
+ # The original lock file was not clobbered by the losing caller.
+ payload = helpers.read_update_lock(tmp_path)
+ assert payload is not None
+ assert payload["target_commit"] == "first"
+
+
+def test_acquire_replaces_stale_lock(tmp_path: Path) -> None:
+ """A dead owner's lock is cleared and the exclusive create retried."""
+ _write_lock(
+ tmp_path,
+ {"pid": _dead_pid(), "target_commit": "crashed", "started_at": time.time()},
+ )
+
+ assert helpers.try_acquire_update_lock(tmp_path, "fresh") is None
+ payload = helpers.read_update_lock(tmp_path)
+ assert payload is not None
+ assert payload["target_commit"] == "fresh"
+ assert payload["pid"] == os.getpid()
+
+
+def test_release_then_reacquire(tmp_path: Path) -> None:
+ assert helpers.try_acquire_update_lock(tmp_path, "one") is None
+ helpers.release_update_lock(tmp_path)
+ assert helpers.try_acquire_update_lock(tmp_path, "two") is None
+
+
def test_fresh_lock_with_dead_pid_is_stale(tmp_path: Path) -> None:
"""The headline fix: a crashed update's lock no longer blocks for 30 min."""
_write_lock(
@@ -138,36 +172,21 @@ def test_unknown_probe_results_fall_back_to_wall_clock(
# ---------------------------------------------------------------------------
-# Workspace mirror (repowise.core.workspace.update) — format must stay in sync
+# Workspace path — must use the exact same shared core implementation
# ---------------------------------------------------------------------------
-def test_workspace_lock_round_trip_matches_cli_format(tmp_path: Path) -> None:
- ws_update._acquire_lock(tmp_path, "abc123")
+def test_workspace_uses_shared_core_lock(tmp_path: Path) -> None:
+ from repowise.core.update_lock import release_update_lock, try_acquire_update_lock
+
+ assert ws_update._try_acquire_lock is try_acquire_update_lock
+ assert ws_update._release_lock is release_update_lock
+
+ # Round-trip through the workspace aliases against the CLI view.
+ assert ws_update._try_acquire_lock(tmp_path, "abc123") is None
try:
- cli_view = helpers.read_update_lock(tmp_path)
- ws_view = ws_update._read_lock(tmp_path)
- assert cli_view is not None
- assert ws_view is not None
- assert cli_view["pid"] == ws_view["pid"] == os.getpid()
- assert cli_view["pid_create_token"] == ws_view["pid_create_token"]
+ payload = helpers.read_update_lock(tmp_path)
+ assert payload is not None
+ assert payload["pid"] == os.getpid()
finally:
ws_update._release_lock(tmp_path)
-
-
-def test_workspace_lock_with_dead_pid_is_stale(tmp_path: Path) -> None:
- _write_lock(
- tmp_path,
- {"pid": _dead_pid(), "target_commit": "abc", "started_at": time.time()},
- )
-
- assert ws_update._read_lock(tmp_path) is None
-
-
-def test_workspace_legacy_lock_without_token_still_honored(tmp_path: Path) -> None:
- _write_lock(
- tmp_path,
- {"pid": os.getpid(), "target_commit": "abc", "started_at": time.time()},
- )
-
- assert ws_update._read_lock(tmp_path) is not None
diff --git a/tests/unit/cli/test_update_progress_json.py b/tests/unit/cli/test_update_progress_json.py
index 55b263fdf..28a514863 100644
--- a/tests/unit/cli/test_update_progress_json.py
+++ b/tests/unit/cli/test_update_progress_json.py
@@ -59,8 +59,20 @@ class TestJsonProgressEmitter:
"pages_generated": 5,
"cost_usd": 0.42,
"duration_s": 12.3,
+ "degraded": [],
}
+ def test_done_reports_degraded_steps(self, capsys):
+ JsonProgressEmitter().done(
+ ok=True,
+ pages_generated=5,
+ cost_usd=0.42,
+ duration_s=12.3,
+ degraded=["Git persist: disk I/O error"],
+ )
+ (event,) = self._lines(capsys)
+ assert event["degraded"] == ["Git persist: disk I/O error"]
+
def test_error(self, capsys):
JsonProgressEmitter().error("boom")
(event,) = self._lines(capsys)
@@ -136,6 +148,7 @@ class TestUpdateProgressJsonCli:
"pages_generated": 0,
"cost_usd": 0.0,
"duration_s": events[-1]["duration_s"],
+ "degraded": [],
}
# Informational Rich output (repo header, "No changed files detected.")
# went to stderr, not stdout.