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: bound the betweenness pool, keep live update locks, and count failed pages once (#1262)
Raghav Chamadiya7d55cfe68478
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py b/packages/cli/src/repowise/cli/commands/init_cmd/generation.pyindex d9a0a1e8f..0dbcc6e37 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py@@ -38,6 +38,7 @@ from repowise.cli.providers import (flush_cost_tracker,)from repowise.cli.ui import BRAND_STYLE, OWL_SPINNER, MaybeCountColumn, RichProgressCallback+from repowise.core.generation.models import count_stub_fallbacks__all__ = ["COST_GATE_USD",@@ -366,22 +367,43 @@ def run_repo_generation(result.generated_pages = generated_pagesresult.failed_page_ids = failed_page_ids+ # A page whose provider call failed is still handed back, as a stub rendered+ # from structure alone, so that the row exists and a later run can find it+ # and refill it. That makes it a member of ``generated_pages`` like any+ # other page, and counting the list is what let the summary report the same+ # page as generated and as failed at once.+ stub_count = count_stub_fallbacks(generated_pages)+ written_count = len(generated_pages) - stub_count+if failed_page_ids:type_counts = Counter(pid.split(":")[0] for pid in failed_page_ids)console.print(- f" [yellow]⚠[/yellow] Generated [bold]{len(generated_pages)}[/bold] pages "+ f" [yellow]⚠[/yellow] Generated [bold]{written_count}[/bold] pages "f"([bold yellow]{len(failed_page_ids)} failed[/bold yellow])\n")console.print(" [bold yellow]Failed pages by type:[/bold yellow]")for page_type, count in sorted(type_counts.items(), key=lambda x: -x[1]):console.print(f" • {page_type}: {count}")+ # Saying only "missing" sends the user looking for absent pages and+ # finding present ones, which reads as the report being wrong. Most+ # failures leave a placeholder behind; --resume replaces those too,+ # because a placeholder is deliberately kept out of the record of what+ # is already done.+ placeholder_note = (+ f" [dim]{stub_count} of them left a placeholder page rendered from "+ "structure alone, so the wiki has a page there but not a written "+ "one. The rest produced no page at all.[/dim]\n"+ if stub_count+ else ""+ )console.print("\n [yellow]The wiki is incomplete due to provider failures.[/yellow]\n"- " [dim]Run [bold]repowise init --resume[/bold] to generate missing pages "- "without re-spending on completed ones.[/dim]\n"+ f"{placeholder_note}"+ " [dim]Run [bold]repowise init --resume[/bold] to generate the pages that "+ "failed, without re-spending on the ones that succeeded.[/dim]\n")elif verbose:- console.print(f" [green]✓[/green] Generated [bold]{len(generated_pages)}[/bold] pages")+ console.print(f" [green]✓[/green] Generated [bold]{written_count}[/bold] pages")# KG enrichment is layer naming and the guided tour, both pure prompting.# A deterministic run has no model to ask, and the skeleton's structuraldiff --git a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.pyindex 7d3d1ed65..5d976b455 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py@@ -243,13 +243,20 @@ def show_completion(total_tokens = sum(p.total_tokens for p in _pages)# Split model-written from the zero-LLM deterministic coverage tail so# broad coverage reads as thoroughness, not padding.+ # A stub standing in for a failed provider call is in ``_pages`` like+ # any other page, so counting the list here reported it as generated+ # while the same run reported it as failed one line down.+ from repowise.core.generation.models import count_stub_fallbacks++ _stubs = count_stub_fallbacks(_pages)+ _written = len(_pages) - _stubs_det = sum(1 for p in _pages if getattr(p, "provider_name", "") == "template")_ai = len(_pages) - _det- _pages_label = str(len(_pages))+ _pages_label = str(_written)if _failed_ids:- _pages_label = f"{len(_pages)} ({len(_failed_ids)} failed)"+ _pages_label = f"{_written} ({len(_failed_ids)} failed)"elif _det:- _pages_label = f"{len(_pages)} ({_ai} model-written · {_det} from structure)"+ _pages_label = f"{_written} ({_ai} model-written · {_det} from structure)"# The ledger has the real figure; before this the panel reported# millions of tokens and no dollars, on a run the user had just# approved a dollar estimate for.diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.pyindex c07b0de89..5f639fe0e 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py@@ -408,9 +408,14 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCtresult.generated_pages = generated_pages# (result.vector_store is set inside _run_workspace_generation# so the Phase-2C decision dedup can reuse the same store.)- pages_generated = len(generated_pages)+ # Excludes placeholders left behind by failed provider calls, which+ # are members of this list like any other page. The single-repo+ # flow reports the same split.+ from repowise.core.generation.models import count_stub_fallbacks++ pages_generated = len(generated_pages) - count_stub_fallbacks(generated_pages)docs_mode = "llm"- console.print(f" [green]✓[/green] Generated {len(generated_pages)} pages\n")+ console.print(f" [green]✓[/green] Generated {pages_generated} pages\n")except CostGateDeclined:# Declining only ever meant "not at that price". Fall back to the# free template renderer rather than leaving the repo with no wikidiff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex 4c05b9743..135bd54ba 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -816,16 +816,30 @@ def run_update(# 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+ from repowise.core.update_lock import (+ UPDATE_LOCK_SUSPECT_AFTER_SECONDS,+ format_lock_age,+ lock_age_seconds,+ )- elapsed = int(_time.time() - existing_lock.get("started_at", _time.time()))+ age = lock_age_seconds(existing_lock)target_short = (existing_lock.get("target_commit") or "")[:8]write_update_pending(repo_path, head)console.print(f"[yellow]Another `repowise update` is already running "f"(pid {existing_lock.get('pid')}, target {target_short}, "- f"started {elapsed}s ago).[/yellow]"+ f"holding the lock {format_lock_age(age)}).[/yellow]")+ # An owner we can see running is never evicted on age alone, so a run+ # that has stopped progressing would otherwise block every later update+ # with nothing to act on. Say how long it has been and where to look.+ if age is not None and age > UPDATE_LOCK_SUSPECT_AFTER_SECONDS:+ console.print(+ "[yellow]That is longer than an update normally takes. If "+ "[bold].repowise/.update.log[/bold] has not been written to in "+ f"that time, pid {existing_lock.get('pid')} is stuck and can be "+ "stopped; this repo will update on the next run.[/yellow]"+ )console.print(f"[dim]HEAD {head[:8] if head else 'HEAD'} marked as pending; ""the running update will roll forward to it. This run regenerated "diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.pyindex c0ef0432a..6645a99a9 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py@@ -11,6 +11,40 @@ import clickfrom repowise.cli.helpers import CommandTarget, console, run_async+def _print_repo_result(result: Any) -> None:+ """Print one repo's outcome. Shared by both workspace passes.++ The index-only pass and the docs pass report identically, and keeping two+ copies of this is what let the deferral line drift into saying only that+ something else was running, without saying for how long.+ """+ from repowise.core.update_lock import UPDATE_LOCK_SUSPECT_AFTER_SECONDS, format_lock_age++ if result.error:+ console.print(f" [red]✗ {result.alias}: {result.error}[/red]")+ elif result.skipped_reason == "in_flight":+ # Surface skipped-because-in-flight as a yellow note rather than a+ # silent skip. Single-flight is the noise-fix path, so the user+ # benefits from seeing it actually trigger — and the age is what tells+ # a normal overlap apart from an update that has stopped progressing.+ age = result.lock_age_seconds+ held = format_lock_age(age)+ note = (+ ""+ if age is None or age <= UPDATE_LOCK_SUSPECT_AFTER_SECONDS+ else " That is long enough to be worth checking on."+ )+ console.print(+ f" [yellow]↻ {result.alias}: another update has held the lock "+ f"{held}; this commit was queued for it to pick up.{note}[/yellow]"+ )+ elif result.updated:+ console.print(+ f" [green]✓[/green] {result.alias}: "+ f"{result.file_count} files, {result.symbol_count:,} symbols"+ )++def _workspace_update(target: CommandTarget,*,@@ -177,24 +211,6 @@ def _workspace_update(def _on_start(alias: str) -> None:console.print(f" Updating [bold]{alias}[/bold]...")- def _on_done(result: RepoUpdateResult) -> None:- if result.error:- console.print(f" [red]\u2717 {result.alias}: {result.error}[/red]")- elif result.skipped_reason == "in_flight":- # Surface skipped-because-in-flight as a yellow note rather than- # a silent skip. Single-flight is the noise-fix path, so the- # user benefits from seeing it actually trigger.- console.print(- f" [yellow]\u21bb {result.alias}: another update is already "- "in flight; this commit was queued for it to pick up.[/yellow]"- )- elif result.updated:- console.print(- f" [green]\u2713[/green] {result.alias}: "- f"{result.file_count} files, {result.symbol_count:,} symbols"- )-- from repowise.core.workspace import RepoUpdateResultresults = run_async(update_workspace(@@ -203,7 +219,7 @@ def _workspace_update(repo_filter=repo_alias,dry_run=False,on_repo_start=_on_start,- on_repo_done=_on_done,+ on_repo_done=_print_repo_result,))@@ -305,20 +321,6 @@ def _workspace_docs_update(def _on_start(alias: str) -> None:console.print(f" Updating [bold]{alias}[/bold]...")- def _on_done(result: RepoUpdateResult) -> None:- if result.error:- console.print(f" [red]✗ {result.alias}: {result.error}[/red]")- elif result.skipped_reason == "in_flight":- console.print(- f" [yellow]↻ {result.alias}: another update is already "- "in flight; this commit was queued for it to pick up.[/yellow]"- )- elif result.updated:- console.print(- f" [green]✓[/green] {result.alias}: "- f"{result.file_count} files, {result.symbol_count:,} symbols"- )-core_results = run_async(update_workspace(ws_root,@@ -327,7 +329,7 @@ def _workspace_docs_update(run_hooks=False,dry_run=False,on_repo_start=_on_start,- on_repo_done=_on_done,+ on_repo_done=_print_repo_result,))changed_aliases.extend(r.alias for r in core_results if r.updated)@@ -434,10 +436,29 @@ def _workspace_docs_update(# work), "complete" would overclaim — the real regeneration is still# running elsewhere. Say so, and point at the log the hook writes.if deferred and not (docs_updated or core_updated):+ from repowise.core.update_lock import UPDATE_LOCK_SUSPECT_AFTER_SECONDS, format_lock_age++ # The oldest lock is the one worth naming: it is the run most likely to+ # have stopped progressing, and "still running" with no age attached is+ # exactly the message that leaves a wedged update looking healthy.+ ages = [r.lock_age_seconds for r in core_results if r.lock_age_seconds is not None]+ oldest = max(ages) if ages else None+ if oldest is not None and oldest > UPDATE_LOCK_SUSPECT_AFTER_SECONDS:+ tail = (+ f"An update has held the lock {format_lock_age(oldest)}, which is "+ "longer than an update normally takes. Check "+ "[bold].repowise/.update.log[/bold]: if it has not been written to "+ "in that time, that update is stuck and can be stopped."+ )+ elif oldest is not None:+ tail = (+ f"A background update has been running {format_lock_age(oldest)}; "+ "watch [bold].repowise/.update.log[/bold]."+ )+ else:+ tail = "A background update is still running; watch [bold].repowise/.update.log[/bold]."console.print(- f"[yellow]Workspace update deferred[/yellow]: {summary}. "- "A background update is still running; watch "- "[bold].repowise/.update.log[/bold]. "+ f"[yellow]Workspace update deferred[/yellow]: {summary}. {tail} "f"[dim]({time.monotonic() - start:.1f}s)[/dim]")else:diff --git a/packages/core/src/repowise/core/ingestion/graph/_betweenness.py b/packages/core/src/repowise/core/ingestion/graph/_betweenness.pyindex dac56324c..dab58b0b7 100644--- a/packages/core/src/repowise/core/ingestion/graph/_betweenness.py+++ b/packages/core/src/repowise/core/ingestion/graph/_betweenness.py@@ -23,6 +23,7 @@ from __future__ import annotationsimport multiprocessingimport os+import threadingfrom concurrent.futures import ProcessPoolExecutorimport networkx as nx@@ -38,6 +39,37 @@ log = structlog.get_logger(__name__)# ``pipeline/phases/ingestion.py`` (issue #678)._MP_SPAWN = multiprocessing.get_context("spawn")+# Upper bound on pool size, independent of how many cores the host has.+#+# Every worker is a fresh interpreter under ``spawn``, and on Windows they are+# brought up strictly one at a time: the parent runs CreateProcess, then+# pickles ``initargs`` and writes them down that child's pipe, and only then+# starts the next one. That write blocks until the brand-new child drains it,+# so the parent's per-spawn cost grows with the number of interpreters already+# competing for CPU and page-in bandwidth. A 32-thread host therefore paid 32+# serial spawns and 32 full copies of the edge list before the first source+# node was processed, and a single spawn that never got its reader scheduled+# stalled the whole update with no way to notice.+#+# Brandes parallelizes over source nodes and chunk count is derived from the+# worker count, so a lower cap means slightly larger chunks rather than idle+# cores; the measured win flattens out well before this many workers. Capping+# also makes the float summation order (fixed by chunk count) identical on+# every host with at least this many cores instead of varying per machine.+_MAX_POOL_WORKERS = 8++# Wall-clock budget for the entire parallel attempt: pool construction, the+# spawn of every worker, and the map. Exceeding it means the pool is not+# making progress, and the sequential path is taken instead.+#+# A hang here is not an exception, so the ``except`` below can never see it.+# The budget is what turns "no progress" into a fallback, which is the promise+# the module docstring already makes and previously only kept for failures+# that raised. Sized well above a healthy run (pool startup is seconds, and+# the sequential path this protects is itself a ~1 minute job) so a merely+# slow host is never cut off mid-computation.+_POOL_TIMEOUT_SECONDS = 600.0+# Parallelize only when the estimated Brandes cost (~nodes x edges) is large# enough to amortize process startup (~2-3s for pool spawn + imports).# Measured rates on the repowise graph: file subgraph (1.8k x 5.2k ~ 1e7)@@ -102,24 +134,108 @@ def _rescale(return betweenness+def pool_worker_count(max_workers: int | None = None) -> int:+ """How many workers this module will ask a pool for.++ Separate from the caller's request so the bound is stated once and can be+ asserted on directly. An explicit ``max_workers`` is still capped: the+ limit exists to bound serial spawns on the host, which no caller is in a+ position to judge better than this module.+ """+ return min(max_workers or os.cpu_count() or 1, _MAX_POOL_WORKERS)+++def _run_pool(+ *,+ n: int,+ edges: list[tuple[int, int]],+ directed: bool,+ chunks: list[list[int]],+ workers: int,+) -> list[float]:+ """Build the pool, run every chunk through it, and sum the partials."""+ totals = [0.0] * n+ with ProcessPoolExecutor(+ max_workers=workers,+ mp_context=_MP_SPAWN,+ initializer=_init_worker,+ initargs=(n, edges, directed),+ ) as pool:+ # ``map`` preserves chunk order, keeping float summation+ # deterministic for a given worker count.+ for partial in pool.map(_partial_betweenness, chunks):+ for v, b in partial.items():+ totals[v] += b+ return totals+++def _run_pool_within_budget(+ *,+ n: int,+ edges: list[tuple[int, int]],+ directed: bool,+ chunks: list[list[int]],+ workers: int,+ timeout: float,+) -> list[float] | None:+ """Run the pool under a wall-clock budget. ``None`` means give up on it.++ The work runs on a daemon thread so that a spawn wedged inside a blocking+ pipe write cannot outlive the interpreter. There is no way to interrupt a+ thread parked in ``CreateProcess`` or ``reduction.dump`` from Python, so a+ timed-out attempt is abandoned rather than cancelled: the caller falls back+ to the sequential path and the stuck thread, plus any workers it managed to+ bring up, are left for process exit to reap. Leaking that is the lesser+ outcome against an update that never returns and holds its lock forever.+ """+ outcome: dict[str, object] = {}++ def _work() -> None:+ try:+ outcome["totals"] = _run_pool(+ n=n, edges=edges, directed=directed, chunks=chunks, workers=workers+ )+ except BaseException as exc: # reported to the caller below+ outcome["error"] = exc++ worker = threading.Thread(target=_work, name="betweenness-pool", daemon=True)+ worker.start()+ worker.join(timeout)++ if worker.is_alive():+ log.warning(+ "betweenness_parallel_timed_out_falling_back",+ timeout_seconds=timeout,+ workers=workers,+ )+ return None+ error = outcome.get("error")+ if error is not None:+ log.warning("betweenness_parallel_failed_falling_back", error=str(error))+ return None+ totals = outcome.get("totals")+ return totals if isinstance(totals, list) else None++def betweenness_centrality_fast(g: nx.DiGraph,*,normalized: bool = True,max_workers: int | None = None,+ timeout: float | None = None,) -> dict[str, float]:"""Exact betweenness centrality, parallelized over sources when worthwhile.Drop-in equivalent of ``nx.betweenness_centrality(g, normalized=...)``- for unweighted graphs without endpoint counting. Small graphs (or any- pool failure) take the sequential NetworkX path, so callers never need- a fallback of their own.+ for unweighted graphs without endpoint counting. Small graphs, any pool+ failure, and a pool that stops making progress within ``timeout`` all take+ the sequential NetworkX path, so callers never need a fallback of their own."""n = g.number_of_nodes()e = g.number_of_edges()if n == 0:return {}- workers = max_workers or os.cpu_count() or 1+ workers = pool_worker_count(max_workers)if n * e < _PARALLEL_COST_THRESHOLD or workers < 2:return nx.betweenness_centrality(g, normalized=normalized)@@ -148,21 +264,15 @@ def betweenness_centrality_fast(chunk_size = max(1, (n + chunk_count - 1) // chunk_count)chunks = [list(range(i, min(i + chunk_size, n))) for i in range(0, n, chunk_size)]- totals = [0.0] * n- try:- with ProcessPoolExecutor(- max_workers=workers,- mp_context=_MP_SPAWN,- initializer=_init_worker,- initargs=(n, edges, g.is_directed()),- ) as pool:- # ``map`` preserves chunk order, keeping float summation- # deterministic for a given worker count.- for partial in pool.map(_partial_betweenness, chunks):- for v, b in partial.items():- totals[v] += b- except Exception as exc: # pragma: no cover - depends on host environment- log.warning("betweenness_parallel_failed_falling_back", error=str(exc))+ totals = _run_pool_within_budget(+ n=n,+ edges=edges,+ directed=g.is_directed(),+ chunks=chunks,+ workers=workers,+ timeout=_POOL_TIMEOUT_SECONDS if timeout is None else timeout,+ )+ if totals is None:return nx.betweenness_centrality(g, normalized=normalized)raw = dict(enumerate(totals))diff --git a/packages/core/src/repowise/core/pipeline/phases/generation.py b/packages/core/src/repowise/core/pipeline/phases/generation.pyindex df8f14f9f..f4b982979 100644--- a/packages/core/src/repowise/core/pipeline/phases/generation.py+++ b/packages/core/src/repowise/core/pipeline/phases/generation.py@@ -12,6 +12,7 @@ from typing import Anyimport structlog+from repowise.core.generation.models import count_stub_fallbacksfrom repowise.core.pipeline.progress import ProgressCallbackfrom ._common import _phase_done@@ -173,7 +174,13 @@ async def run_generation("info",f"Onboarding: {len(slots_made)}/8 slots — {', '.join(slots_made)}",)- progress.on_message("info", f"Generated {len(generated_pages)} pages")+ # Placeholders left behind by a failed provider call are in this list+ # like any other page, and the run reports them as failures a line+ # later. Counting the list here made the two lines disagree.+ progress.on_message(+ "info",+ f"Generated {len(generated_pages) - count_stub_fallbacks(generated_pages)} pages",+ )# Surface the FAQ-weighted budget tilt when session demand shaped it# (silent on fresh repos with no history — nothing to weight yet)._phase_done(progress, "onboarding")diff --git a/packages/core/src/repowise/core/update_lock.py b/packages/core/src/repowise/core/update_lock.pyindex 669264254..e4f4e5660 100644--- a/packages/core/src/repowise/core/update_lock.py+++ b/packages/core/src/repowise/core/update_lock.py@@ -19,11 +19,24 @@ from typing import AnyUPDATE_LOCK_FILENAME = ".update.lock"-# Locks older than this are considered stale (a crashed update); the hook-# will ignore them and the next update will overwrite. Generous enough to-# cover a slow full-update on a large repo.+# Wall-clock ceiling, applied only when the owner's liveness cannot be+# established: no PID in the payload (legacy writer) or a probe that could not+# decide. A lock this old whose owner we cannot find is treated as abandoned.+#+# It is deliberately NOT applied to an owner we can positively see running.+# Breaking a live owner's lock puts two updates on one index at once, and both+# write the same state and the same page rows; a full update on a large repo+# can legitimately outrun any ceiling worth setting, so age alone is not+# evidence of abandonment. A provably dead or recycled owner is a different+# matter and is still cleared immediately, which is the common crash case.UPDATE_LOCK_STALE_AFTER_SECONDS = 30 * 60+# Past this age a live owner is reported as suspect rather than broken. It+# changes no behaviour, only what the user is told: "held for 9 hours" is the+# fact that makes a wedged update actionable, where a bare "still running"+# leaves them with nothing to act on.+UPDATE_LOCK_SUSPECT_AFTER_SECONDS = 30 * 60+def update_lock_path(repo_path: Path) -> Path:return Path(repo_path) / ".repowise" / UPDATE_LOCK_FILENAME@@ -95,17 +108,58 @@ def release_update_lock(repo_path: Path) -> None:update_lock_path(repo_path).unlink(missing_ok=True)+def lock_age_seconds(payload: dict[str, Any] | None) -> float | None:+ """Wall-clock age of a lock payload, or ``None`` when it cannot be told.++ One implementation because every reporting site needs the same number and+ each one deriving it separately is how the deferral message ended up+ quoting no age at all.+ """+ if not payload:+ return None+ started = payload.get("started_at")+ if not isinstance(started, (int, float)):+ return None+ return max(0.0, time.time() - started)+++def format_lock_age(age: float | None) -> str:+ """Human phrasing for how long a lock has been held.++ Takes the seconds rather than the payload so a caller that already carries+ the age (a deferred repo result) does not have to rebuild a payload to ask.++ Coarsens with age on purpose: a lock held for seconds is normal and the+ seconds are the interesting part, while one held for hours is the whole+ point of the message and "32700s" buries it.+ """+ if age is None:+ return "for an unknown time"+ if age < 90:+ return f"for {int(age)}s"+ if age < 90 * 60:+ return f"for {int(age / 60)}m"+ return f"for {age / 3600:.1f}h"++def read_update_lock(repo_path: Path) -> dict[str, Any] | None:"""Return the lock payload if present and not stale, else ``None``.- A lock is stale when its wall-clock age exceeds- ``UPDATE_LOCK_STALE_AFTER_SECONDS`` (a hung-but-alive update must not- block forever) — or, much sooner, when its owning PID is positively- dead or has been recycled by an unrelated process. The PID probe means- a crashed/killed update (SIGKILL, power loss — paths atexit can't- cover) no longer blocks further updates for the full 30-minute window.- Probes that can't decide ("unknown") fall back to the wall clock, so a- live update is never treated as stale by mistake.+ A lock is stale when its owning PID is positively dead or has been+ recycled by an unrelated process. That probe is what stops a crashed or+ killed update (SIGKILL, power loss — paths atexit cannot cover) from+ blocking every later update.++ An owner we can positively see running is honoured no matter how old the+ lock is. The wall clock applies only when liveness cannot be established:+ a payload with no usable PID (written by an older version) or a probe that+ returned "unknown". Age on its own is not evidence that an update has+ stopped: a full update on a large repo can outrun any ceiling worth+ setting, and clearing the lock underneath it would put two updates on one+ index, both writing the same state and the same page rows. A live owner+ that has held the lock unreasonably long is surfaced to the user by the+ callers instead (see :func:`lock_is_suspect`), which is the reporting half+ of the same problem and cannot corrupt anything."""from repowise.core.procutils import pid_alive, process_create_token@@ -117,10 +171,8 @@ def read_update_lock(repo_path: Path) -> dict[str, Any] | None:except (json.JSONDecodeError, OSError):return None- started = payload.get("started_at")- if not isinstance(started, (int, float)):- return None- if time.time() - started > UPDATE_LOCK_STALE_AFTER_SECONDS:+ age = lock_age_seconds(payload)+ if age is None:return Nonepid = payload.get("pid")@@ -130,10 +182,15 @@ def read_update_lock(repo_path: Path) -> dict[str, Any] | None:return Noneif alive is True:stored_token = payload.get("pid_create_token")- # Legacy locks (pre-token) skip the identity check and rely on- # liveness + wall clock alone.+ # Legacy locks (pre-token) skip the identity check: liveness is+ # all we have, and it is still better evidence than the clock.if isinstance(stored_token, str) and stored_token:current_token = process_create_token(pid)if current_token is not None and current_token != stored_token:return None+ return payload++ # Liveness unknown: fall back to the wall clock.+ if age > UPDATE_LOCK_STALE_AFTER_SECONDS:+ return Nonereturn payloaddiff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.pyindex 7fdc9ed6f..41d79c0cf 100644--- a/packages/core/src/repowise/core/workspace/update.py+++ b/packages/core/src/repowise/core/workspace/update.py@@ -11,7 +11,6 @@ import json as _jsonimport loggingimport sqlite3import subprocess-import timefrom collections.abc import Callablefrom contextlib import suppressfrom dataclasses import dataclass@@ -24,6 +23,9 @@ from typing import Any# a hand-synced copy). ``update_single_repo_index`` calls these directly,# bypassing the CLI lock acquisition in update_cmd, so workspace updates are# themselves single-flight per repo.+from repowise.core.update_lock import (+ lock_age_seconds as _lock_age_seconds,+)from repowise.core.update_lock import (release_update_lock as _release_lock,)@@ -75,6 +77,10 @@ class RepoUpdateResult:alias: strupdated: bool # True if an update was performedskipped_reason: str | None = None # "up_to_date", "missing_directory", etc.+ # How long the winning update had held the lock, when this repo deferred to+ # one. Carried on the result because the caller reports the deferral and+ # the age is the part that tells a slow update apart from a wedged one.+ lock_age_seconds: float | None = Nonefile_count: int = 0symbol_count: int = 0error: str | None = None@@ -696,15 +702,15 @@ async def update_workspace(# 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()))+ age = _lock_age_seconds(existing)target_short = (existing.get("target_commit") or "")[:8]_log.info("workspace_update: skipping %s — update already in flight "- "(pid=%s target=%s elapsed=%ds)",+ "(pid=%s target=%s elapsed=%ss)",alias,existing.get("pid"),target_short,- elapsed,+ int(age) if age is not None else "?",)# Record pending so the running update can roll forward.with suppress(OSError):@@ -713,6 +719,7 @@ async def update_workspace(alias=alias,updated=False,skipped_reason="in_flight",+ lock_age_seconds=age,)try:diff --git a/tests/unit/cli/test_init_failure_reporting.py b/tests/unit/cli/test_init_failure_reporting.pyindex 6644e986b..af74e9754 100644--- a/tests/unit/cli/test_init_failure_reporting.py+++ b/tests/unit/cli/test_init_failure_reporting.py@@ -361,6 +361,134 @@ class TestInitRendersGenerationChecks:assert "checks did not run" in output+def _stub_page(page_id: str) -> GeneratedPage:+ """A page whose provider call failed and fell back to a structural render."""+ from repowise.core.generation.models import STUB_FALLBACK_ERROR++ page = _page(page_id)+ page.metadata[STUB_FALLBACK_ERROR] = "provider exploded"+ return page+++class TestStubsAreNotCountedTwice:+ """A failed page that left a placeholder is one page, not two outcomes.++ A provider failure still hands back a row, rendered from structure alone,+ so the page exists and a later run can find and refill it. That row is in+ ``generated_pages`` like any other, so the summary counted it as generated+ and, from the job checkpoint, as failed. On a real build that read as 3762+ generated and 10 failed out of a 92-page plan: three numbers that cannot+ all describe the same run.+ """++ def _run(self, tmp_path, monkeypatch, pages, failures):+ jobs_dir = tmp_path / ".repowise" / "jobs"+ jobs_dir.mkdir(parents=True, exist_ok=True)+ js = JobSystem(jobs_dir)+ job_id = js.create_job(str(tmp_path), SimpleNamespace(max_concurrency=1), "mock", "m")+ for page_id in failures:+ js.fail_page(job_id, page_id, "Provider error")++ printed: list[str] = []+ monkeypatch.setattr(+ "repowise.cli.commands.init_cmd.generation.console.print",+ lambda *a, **k: printed.append(" ".join(str(x) for x in a)),+ )+ monkeypatch.setattr(+ "repowise.cli.commands.init_cmd.generation.run_async", lambda coro: pages+ )+ monkeypatch.setattr(+ "repowise.cli.commands.init_cmd.generation._enrich_knowledge_graph",+ lambda **kw: None,+ )+ monkeypatch.setattr(+ "repowise.cli.commands.init_cmd.generation.flush_cost_tracker", lambda t: None+ )++ run_repo_generation(+ repo_path=tmp_path,+ result=SimpleNamespace(+ job_id=job_id,+ repo_name="test_repo",+ parsed_files=[],+ source_map={},+ graph_builder=MagicMock(),+ repo_structure=MagicMock(),+ git_meta_map={},+ ),+ provider=SimpleNamespace(provider_name="mock", model_name="mock-model"),+ gen_config=SimpleNamespace(max_concurrency=1, deterministic=False),+ concurrency=1,+ embedder_name_resolved="mock",+ resume=False,+ verbose=True,+ )+ return "\n".join(printed)++ def test_placeholder_pages_are_excluded_from_the_generated_count(self, tmp_path, monkeypatch):+ """Two written pages plus two placeholders is "2 generated", not 4."""+ pages = [+ _page("module_page:a"),+ _page("module_page:b"),+ _stub_page("module_page:c"),+ _stub_page("module_page:d"),+ ]+ output = self._run(tmp_path, monkeypatch, pages, ["module_page:c", "module_page:d"])++ assert "Generated [bold]2[/bold] pages" in output+ assert "2 failed" in output+ assert "Generated [bold]4[/bold] pages" not in output++ def test_the_placeholder_is_named_so_a_present_page_is_not_a_surprise(+ self, tmp_path, monkeypatch+ ):+ """Calling a page that exists "missing" reads as the report being wrong."""+ pages = [_page("module_page:a"), _stub_page("module_page:c")]+ output = self._run(tmp_path, monkeypatch, pages, ["module_page:c"])++ assert "1 of them left a placeholder page" in output+ assert "repowise init --resume" in output++ def test_hard_failures_alone_mention_no_placeholder(self, tmp_path, monkeypatch):+ """A failure that produced no row at all has nothing to explain away."""+ output = self._run(tmp_path, monkeypatch, [_page("module_page:a")], ["module_page:z"])++ assert "Generated [bold]1[/bold] pages" in output+ assert "placeholder" not in output++ def test_a_clean_run_is_unaffected(self, tmp_path, monkeypatch):+ output = self._run(tmp_path, monkeypatch, [_page("module_page:a")], [])++ assert "Generated [bold]1[/bold] pages" in output+ assert "failed" not in output+++def test_completion_panel_excludes_placeholders_from_the_page_count(monkeypatch):+ """The panel derives the same split from the same helper, not its own count."""+ printed_panels = []+ monkeypatch.setattr(+ "repowise.cli.commands.init_cmd.reporting.build_completion_panel",+ lambda title, metrics, next_steps=None: printed_panels.append(metrics) or "PANEL",+ )+ monkeypatch.setattr(+ "repowise.cli.commands.init_cmd.reporting.console.print", lambda *a, **kw: None+ )++ result = _completion_result([_page("module_page:a"), _stub_page("module_page:b")])+ result.failed_page_ids = ["module_page:b"]++ show_completion(+ repo_path="/fake",+ result=result,+ start=0.0,+ effective_index_only=False,+ run_mode="standard",+ provider=SimpleNamespace(provider_name="mock", model_name="mock-model"),+ )++ assert dict(printed_panels[0]).get("Pages generated") == "1 (1 failed)"++def test_run_repo_generation_uses_exact_job_id_when_provided(tmp_path, monkeypatch):"""When result has a job_id attached, run_repo_generation queries that exact job checkpoint."""jobs_dir = tmp_path / ".repowise" / "jobs"diff --git a/tests/unit/cli/test_update_lock.py b/tests/unit/cli/test_update_lock.pyindex 9d5b16e4f..125c6f89f 100644--- a/tests/unit/cli/test_update_lock.py+++ b/tests/unit/cli/test_update_lock.py@@ -43,9 +43,7 @@ def _write_lock(repo: Path, payload: dict) -> None:def test_acquire_records_pid_and_create_token(tmp_path: Path) -> None:assert helpers.try_acquire_update_lock(tmp_path, "abc123") is None- payload = json.loads(- (tmp_path / ".repowise" / ".update.lock").read_text(encoding="utf-8")- )+ payload = json.loads((tmp_path / ".repowise" / ".update.lock").read_text(encoding="utf-8"))assert payload["pid"] == os.getpid()assert payload["target_commit"] == "abc123"assert payload["pid_create_token"] == process_create_token(os.getpid())@@ -143,8 +141,14 @@ def test_lock_without_pid_falls_back_to_wall_clock(tmp_path: Path) -> None:assert helpers.read_update_lock(tmp_path) is None-def test_old_lock_is_stale_even_with_live_pid(tmp_path: Path) -> None:- """A hung-but-alive update must still hit the wall-clock ceiling."""+def test_old_lock_with_live_pid_is_honored(tmp_path: Path) -> None:+ """Age alone never evicts an owner we can positively see running.++ The wall clock cannot tell a slow full update on a large repo apart from a+ wedged one, and guessing wrong puts two updates on one index, both writing+ the same state and the same page rows. Liveness is the better evidence, so+ it wins; a long-held live lock is reported to the user instead.+ """_write_lock(tmp_path,{@@ -155,9 +159,90 @@ def test_old_lock_is_stale_even_with_live_pid(tmp_path: Path) -> None:},)+ payload = helpers.read_update_lock(tmp_path)+ assert payload is not None+ assert payload["target_commit"] == "abc"+++def test_old_lock_with_dead_pid_is_still_stale(tmp_path: Path) -> None:+ """Honouring live owners must not resurrect dead ones."""+ _write_lock(+ tmp_path,+ {+ "pid": _dead_pid(),+ "target_commit": "abc",+ "started_at": time.time() - helpers.UPDATE_LOCK_STALE_AFTER_SECONDS - 60,+ },+ )+assert helpers.read_update_lock(tmp_path) is None+def test_a_live_owner_is_never_evicted_by_a_contender(tmp_path: Path) -> None:+ """The end-to-end consequence: no acquire can steal from a live owner."""+ _write_lock(+ tmp_path,+ {+ "pid": os.getpid(),+ "pid_create_token": process_create_token(os.getpid()),+ "target_commit": "wedged",+ "started_at": time.time() - 9 * 3600,+ },+ )++ blocked_by = helpers.try_acquire_update_lock(tmp_path, "contender")+ assert blocked_by is not None+ assert blocked_by["target_commit"] == "wedged"+++# ---------------------------------------------------------------------------+# Age reporting — the half of a wedged update the user can act on+# ---------------------------------------------------------------------------+++def test_lock_age_reads_started_at() -> None:+ from repowise.core.update_lock import lock_age_seconds++ assert lock_age_seconds({"started_at": time.time() - 120}) == pytest.approx(120, abs=5)+ assert lock_age_seconds({}) is None+ assert lock_age_seconds(None) is None+ assert lock_age_seconds({"started_at": "not-a-number"}) is None+++def test_lock_age_never_reports_negative() -> None:+ """A clock that moved backwards must not print a negative age."""+ from repowise.core.update_lock import lock_age_seconds++ assert lock_age_seconds({"started_at": time.time() + 600}) == 0.0+++def test_format_lock_age_coarsens_with_age() -> None:+ """The nine-hour case has to read as hours, not as a five-digit second count."""+ from repowise.core.update_lock import format_lock_age++ assert format_lock_age(12) == "for 12s"+ assert format_lock_age(20 * 60) == "for 20m"+ assert format_lock_age(9 * 3600) == "for 9.0h"+ assert format_lock_age(None) == "for an unknown time"+++def test_suspect_threshold_flags_a_long_held_lock() -> None:+ from repowise.core.update_lock import UPDATE_LOCK_SUSPECT_AFTER_SECONDS++ assert 60 < UPDATE_LOCK_SUSPECT_AFTER_SECONDS < 9 * 3600+++def test_deferred_repo_result_carries_the_lock_age(tmp_path: Path) -> None:+ """The workspace summary can only report the age if the result carries it."""+ from repowise.core.workspace.update import RepoUpdateResult++ assert RepoUpdateResult(alias="a", updated=False).lock_age_seconds is None+ assert (+ RepoUpdateResult(alias="a", updated=False, lock_age_seconds=32400.0).lock_age_seconds+ == 32400.0+ )++def test_unknown_probe_results_fall_back_to_wall_clock(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/unit/ingestion/test_parallel_betweenness.py b/tests/unit/ingestion/test_parallel_betweenness.pyindex 4d88e8375..abdbce6e0 100644--- a/tests/unit/ingestion/test_parallel_betweenness.py+++ b/tests/unit/ingestion/test_parallel_betweenness.py@@ -6,6 +6,8 @@ The parallel path must reproduce ``nx.betweenness_centrality`` exactlyfrom __future__ import annotations+import threading+import networkx as nximport pytest@@ -72,6 +74,108 @@ class TestParallelPath:assert ours["lonely.py"] == 0.0+class TestWorkerCap:+ """The pool size is bounded regardless of how many cores the host has.++ Every worker costs one serial spawn plus one full copy of the edge list+ written down its pipe, so an uncapped count is what turned a high-core+ host into a 32-spawn serial startup that stalled partway through.+ """++ def test_cap_applies_to_host_core_count(self, monkeypatch):+ monkeypatch.setattr(bw.os, "cpu_count", lambda: 32)+ assert bw.pool_worker_count() == bw._MAX_POOL_WORKERS++ def test_cap_applies_to_explicit_request(self):+ assert bw.pool_worker_count(64) == bw._MAX_POOL_WORKERS++ def test_below_cap_is_left_alone(self, monkeypatch):+ monkeypatch.setattr(bw.os, "cpu_count", lambda: 4)+ assert bw.pool_worker_count() == 4+ assert bw.pool_worker_count(2) == 2++ def test_unknown_core_count_degrades_to_one(self, monkeypatch):+ monkeypatch.setattr(bw.os, "cpu_count", lambda: None)+ assert bw.pool_worker_count() == 1++ def test_pool_is_constructed_with_the_capped_count(self, monkeypatch):+ """The cap reaches the executor, not just the helper."""+ monkeypatch.setattr(bw, "_PARALLEL_COST_THRESHOLD", 0)+ monkeypatch.setattr(bw.os, "cpu_count", lambda: 32)+ seen: dict = {}++ real_executor = bw.ProcessPoolExecutor++ def _recording_executor(*args, **kwargs):+ seen.update(kwargs)+ # Honour the cap under test but keep the pool small enough that the+ # assertion does not cost 8 interpreters to make.+ kwargs["max_workers"] = 2+ return real_executor(*args, **kwargs)++ monkeypatch.setattr(bw, "ProcessPoolExecutor", _recording_executor)+ bw.betweenness_centrality_fast(_random_digraph(40, 0.1, seed=7))++ assert seen["max_workers"] == bw._MAX_POOL_WORKERS+++class TestTimeoutFallback:+ """A pool that stops making progress must fall back, not hang.++ The failure this closes raises nothing: the parent parks inside a blocking+ pipe write while spawning a worker, so the ``except`` around the pool never+ fires and the update hangs forever holding its lock. Only a wall-clock+ budget can turn that into a fallback.+ """++ @pytest.fixture()+ def force_parallel(self, monkeypatch):+ monkeypatch.setattr(bw, "_PARALLEL_COST_THRESHOLD", 0)++ def test_stalled_pool_falls_back_to_sequential(self, force_parallel, monkeypatch):+ """A pool construction that never returns yields the sequential answer.++ The stall is injected and the budget is injected, so the test proves the+ fallback without waiting out a real timeout.+ """+ started = threading.Event()++ class _StalledExecutor:+ def __init__(self, *args, **kwargs):+ started.set()+ # Never returns within the injected budget. Daemon-threaded by+ # the code under test, so it cannot outlive the interpreter.+ threading.Event().wait(30)++ monkeypatch.setattr(bw, "ProcessPoolExecutor", _StalledExecutor)++ g = _random_digraph(60, 0.08, seed=8)+ ours = bw.betweenness_centrality_fast(g, normalized=True, timeout=0.2)++ assert started.is_set(), "the parallel path was never attempted"+ _assert_close(ours, nx.betweenness_centrality(g, normalized=True))++ def test_raising_pool_still_falls_back(self, force_parallel, monkeypatch):+ """The pre-existing exception path survives the move onto a thread."""++ def _boom(*args, **kwargs):+ raise OSError("pool unavailable")++ monkeypatch.setattr(bw, "ProcessPoolExecutor", _boom)++ g = _random_digraph(60, 0.08, seed=9)+ _assert_close(+ bw.betweenness_centrality_fast(g, normalized=True),+ nx.betweenness_centrality(g, normalized=True),+ )++ def test_budget_not_consumed_by_a_healthy_pool(self, force_parallel):+ """A pool that completes inside the budget returns the parallel result."""+ g = _random_digraph(80, 0.06, seed=10)+ ours = bw.betweenness_centrality_fast(g, normalized=True, max_workers=2, timeout=120)+ _assert_close(ours, nx.betweenness_centrality(g, normalized=True))++class TestRescale:"""The inlined rescale must match NetworkX for our (k=None, no-endpoint) use."""