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.

perf(decisions): check decision evolution only against this update's evidence, concurrently (#3524)

Raghav Chamadiya3e96a89a118f
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 7bc814f16..c03cad94f 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -642,6 +642,67 @@ def _stale_renderer_paths(repo_path, parsed_files) -> list[str]:
return []
+def _run_decision_evolution(
+ repo_path: Path,
+ file_diffs: list,
+ git_meta_map: dict,
+ *,
+ base_ref: str,
+ head: str | None,
+ provider: Any,
+ cost_tracker: Any,
+ max_concurrency: int,
+) -> dict | None:
+ """Run the update's decision-evolution pass, or ``None`` with no changed file.
+
+ Pass 1 sees only the commits in ``base_ref..head``: older ones were judged
+ by the update that brought them in. The judge calls are booked as decision
+ spend, not page generation.
+ """
+ changed_set = {fd.path for fd in file_diffs if fd.status in ("added", "modified")}
+ if not changed_set:
+ return None
+
+ from repowise.core.analysis.decision_evolution import (
+ commits_in_range,
+ run_update_evolution,
+ update_evidence_by_file,
+ )
+
+ evidence_by_file = update_evidence_by_file(
+ file_diffs, git_meta_map, commits_in_range(repo_path, base_ref, head)
+ )
+
+ async def _run() -> dict:
+ from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_repository,
+ )
+
+ engine = create_engine(get_db_url_for_repo(repo_path))
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))
+ res = await run_update_evolution(
+ session,
+ repo.id,
+ changed_files=changed_set,
+ evidence_by_file=evidence_by_file,
+ provider=provider,
+ max_concurrency=max_concurrency,
+ )
+ await engine.dispose()
+ return res
+
+ with cost_tracker.record_as("decision_extraction"):
+ return run_async(_run())
+
+
def run_update(
path: str | None,
provider_name: str | None,
@@ -1995,6 +2056,9 @@ def run_update(
"fingerprint was retained so the next update retries."
) from exc
+ # Sub-rows of ``decisions``; each step is best-effort and catches its own
+ # errors, so a plain start/stop pair brackets it.
+ timings.start("decisions.rescan")
try:
from repowise.core.analysis.decision_extractor import DecisionExtractor
@@ -2024,6 +2088,10 @@ def run_update(
degraded.append(f"Decision re-scan: {exc}")
if verbose:
console.print(f"[yellow]Decision re-scan skipped: {exc}[/yellow]")
+ timings.stop("decisions.rescan")
+
+ # Session mining, session discovery, injection feedback and hook efficacy.
+ timings.start("decisions.sessions")
# Session-sourced decisions: mine agent transcript lines appended since
# the last update, structure new candidates in one batched LLM pass, and
@@ -2162,18 +2230,20 @@ def run_update(
degraded.append(f"Hook efficacy: {exc}")
if verbose:
console.print(f"[yellow]Hook efficacy classification skipped: {exc}[/yellow]")
+ timings.stop("decisions.sessions")
# Count of decision records touched by evolution, surfaced in the panel.
decisions_evolved = 0
# Build the shared vector store once: reused by the supersession detector
# below and by the decision upsert in _persist (semantic dedup + search).
- decision_vector_store = _build_update_vector_store(
- repo_path,
- cfg,
- degraded,
- required=(traversal_config_changed or generation_config_changed),
- )
+ with timed(timings, "decisions.vector_store"):
+ decision_vector_store = _build_update_vector_store(
+ repo_path,
+ cfg,
+ degraded,
+ required=(traversal_config_changed or generation_config_changed),
+ )
# --- Two-pass decision evolution (Phase 3C), BEFORE page regeneration ----
# Cross-reference the diff + new commit bodies against existing decisions
@@ -2181,61 +2251,19 @@ def run_update(
# survivor is amended/superseded/reaffirmed (Pass 2, gated). Governed pages
# of an evolved decision are folded into ``affected.regenerate`` so they
# re-render in this same run — the cascade-coupling the design calls for.
+ timings.start("decisions.evolution")
try:
- import json as _json_evo
-
- evidence_by_file: dict[str, str] = {}
- for fd in file_diffs:
- if fd.status not in ("added", "modified"):
- continue
- parts: list[str] = []
- if fd.trigger_commit_message:
- parts.append(fd.trigger_commit_message)
- if fd.diff_text:
- parts.append(fd.diff_text)
- meta = git_meta_map.get(fd.path)
- if meta:
- for c in _json_evo.loads(meta.get("significant_commits_json", "[]") or "[]"):
- msg = c.get("message") or ""
- body = c.get("body") or ""
- if msg or body:
- parts.append(f"{msg}\n{body}")
- if parts:
- evidence_by_file[fd.path] = "\n\n".join(parts)
-
- changed_set = {fd.path for fd in file_diffs if fd.status in ("added", "modified")}
- if changed_set:
- from repowise.core.analysis.decision_evolution import run_update_evolution
-
- async def _run_evolution() -> dict:
- from repowise.cli.helpers import get_db_url_for_repo
- from repowise.core.persistence import (
- create_engine,
- create_session_factory,
- get_session,
- init_db,
- 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_path.name, local_path=str(repo_path)
- )
- res = await run_update_evolution(
- session,
- repo.id,
- changed_files=changed_set,
- evidence_by_file=evidence_by_file,
- provider=provider,
- )
- await engine.dispose()
- return res
-
- evo = run_async(_run_evolution())
+ evo = _run_decision_evolution(
+ repo_path,
+ file_diffs,
+ git_meta_map,
+ base_ref=base_ref,
+ head=head,
+ provider=provider,
+ cost_tracker=cost_tracker,
+ max_concurrency=config.max_concurrency,
+ )
+ if evo is not None:
decisions_evolved = (
evo.get("superseded", 0) + evo.get("amended", 0) + evo.get("reaffirmed", 0)
)
@@ -2257,6 +2285,7 @@ def run_update(
degraded.append(f"Decision evolution: {exc}")
if verbose:
console.print(f"[yellow]Decision evolution skipped: {exc}[/yellow]")
+ timings.stop("decisions.evolution")
timings.stop("decisions")
# Filter to only affected files
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 195b2f429..83507a986 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -195,14 +195,17 @@ async def _persist_partial_health(
await persist_partial_health(session, repo_id, report, repo_path)
-async def _persist_incremental_commits(session: Any, repo_id: str, repo_path: Any) -> None:
+async def _persist_incremental_commits(
+ session: Any, repo_id: str, repo_path: Any, *, timings: PhaseTimings | None = None
+) -> None:
"""Capture + upsert ``git_commits`` rows for commits new since the last index.
- Delegates to :mod:`repowise.core.pipeline.incremental`.
+ Delegates to :mod:`repowise.core.pipeline.incremental`. ``timings`` carries
+ its ``persist.commits.*`` sub-rows into the run's phase table.
"""
from repowise.core.pipeline.incremental import persist_incremental_commits
- await persist_incremental_commits(session, repo_id, repo_path)
+ await persist_incremental_commits(session, repo_id, repo_path, timings=timings)
def stamp_head_commit(repo_path: Any, head: str | None) -> None:
@@ -1053,7 +1056,9 @@ async def _persist_full_update_async(
try:
with timed(timings, "persist.commits"):
if full_git_summary is None:
- await _persist_incremental_commits(session, repo_id, repo_path)
+ await _persist_incremental_commits(
+ session, repo_id, repo_path, timings=timings
+ )
except Exception as exc:
_skip("Commit capture", exc)
diff --git a/packages/core/src/repowise/core/analysis/decisions/evolution.py b/packages/core/src/repowise/core/analysis/decisions/evolution.py
index 8919d9237..226326902 100644
--- a/packages/core/src/repowise/core/analysis/decisions/evolution.py
+++ b/packages/core/src/repowise/core/analysis/decisions/evolution.py
@@ -31,8 +31,10 @@ walk that consumes these edges is bounded elsewhere.
from __future__ import annotations
+import asyncio
import json
import re
+import subprocess
from functools import lru_cache
from typing import Any
@@ -52,6 +54,7 @@ __all__ = [
"RELATED_TAU",
"SEMANTIC_SUPERSESSION_ENABLED",
"SUPERSEDE_AUTOFLIP_CONFIDENCE",
+ "commits_in_range",
"contradicts",
"detect_supersessions_and_conflicts",
"is_reversal",
@@ -59,6 +62,7 @@ __all__ = [
"run_update_evolution",
"scan_evolution_signals",
"supersession_confidence",
+ "update_evidence_by_file",
]
# ---------------------------------------------------------------------------
@@ -601,6 +605,72 @@ def pass1_evolution_candidates(
return out
+def commits_in_range(repo_path: Any, base_ref: str, head: str | None) -> set[str]:
+ """8-char prefixes of the commits in ``base_ref..head``.
+
+ The prefix length matches the ``sha`` the git indexer stores in
+ ``significant_commits_json``. Empty when git fails, which leaves Pass 1
+ without commit evidence for this run rather than falling back to history.
+ """
+ try:
+ out = subprocess.run(
+ [
+ "git",
+ "-C",
+ str(repo_path),
+ "rev-list",
+ "--end-of-options",
+ f"{base_ref}..{head or 'HEAD'}",
+ ],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ logger.warning("decision_evolution.range_failed", error=str(exc))
+ return set()
+ if out.returncode != 0:
+ logger.warning("decision_evolution.range_failed", error=out.stderr.strip()[:200])
+ return set()
+ return {sha[:8] for sha in out.stdout.split()}
+
+
+def update_evidence_by_file(
+ file_diffs: list[Any],
+ git_meta_map: dict[str, dict],
+ range_shas: set[str],
+) -> dict[str, str]:
+ """Pass 1 evidence per changed file, limited to this update's commits.
+
+ A file's ``significant_commits_json`` is its whole history. Feeding all of
+ it made every update re-judge decisions against commits an earlier update
+ (or the initial index) had already seen, so only commits whose sha is in
+ *range_shas* count here. A commit outside the range was in the range of
+ the update that first brought it in, and its verdict was applied then.
+ """
+ evidence: dict[str, str] = {}
+ for fd in file_diffs:
+ if fd.status not in ("added", "modified"):
+ continue
+ parts: list[str] = []
+ if fd.trigger_commit_message:
+ parts.append(fd.trigger_commit_message)
+ if fd.diff_text:
+ parts.append(fd.diff_text)
+ meta = git_meta_map.get(fd.path)
+ if meta and range_shas:
+ for c in json.loads(meta.get("significant_commits_json", "[]") or "[]"):
+ if (c.get("sha") or "")[:8] not in range_shas:
+ continue
+ msg = c.get("message") or ""
+ body = c.get("body") or ""
+ if msg or body:
+ parts.append(f"{msg}\n{body}")
+ if parts:
+ evidence[fd.path] = "\n\n".join(parts)
+ return evidence
+
+
_EVOLUTION_JUDGE_SYSTEM = (
"You assess whether a code change evolves a previously recorded "
"architectural decision. Return only valid JSON. "
@@ -631,6 +701,12 @@ Respond with a JSON object:
Quote only text that appears verbatim in the change evidence."""
+# The answer is ~150 tokens of JSON, but reasoning models count their thinking
+# against the same budget (OpenAI's max_completion_tokens). At 400, 17 of 121
+# real calls hit the cap and returned truncated JSON, which the parser drops.
+_JUDGE_MAX_TOKENS = 2000
+
+
class _JudgeCandidate:
"""Minimal duck-typed shape for :func:`apply_substring_gate`."""
@@ -665,7 +741,7 @@ async def _judge_evolution(
)
try:
response = await provider.generate(
- _EVOLUTION_JUDGE_SYSTEM, prompt, max_tokens=400, temperature=0.1
+ _EVOLUTION_JUDGE_SYSTEM, prompt, max_tokens=_JUDGE_MAX_TOKENS, temperature=0.1
)
except Exception:
return None
@@ -731,9 +807,13 @@ async def run_update_evolution(
changed_files: set[str],
evidence_by_file: dict[str, str],
provider: Any | None = None,
+ max_concurrency: int = 1,
) -> dict[str, Any]:
"""Two-pass evolution for ``repowise update``, run *before* page regen.
+ ``max_concurrency`` bounds the Pass 2 judge calls in flight; the update
+ passes the generation config's ``max_concurrency``.
+
Returns ``{"regen_files": set[str], "superseded": n, "amended": n,
"reaffirmed": n}``. ``regen_files`` are the governed files of every decision
the change superseded or amended — the caller folds them into the
@@ -764,27 +844,50 @@ async def run_update_evolution(
regen: set[str] = result["regen_files"]
now = datetime.now(UTC)
- for dec, evidence_text, _signals in candidates:
+ def _governed(dec: Any) -> list[str]:
try:
- governed = list(json.loads(dec.affected_files_json or "[]"))
+ return list(json.loads(dec.affected_files_json or "[]"))
except (TypeError, ValueError):
- governed = []
+ return []
- if provider is None:
- # No LLM available: a signal touched a governed file — re-render the
- # governed pages so docs stay fresh, but don't change status.
- regen.update(governed)
- continue
+ if provider is None:
+ # No LLM available: a signal touched a governed file — re-render the
+ # governed pages so docs stay fresh, but don't change status.
+ for dec, _evidence, _signals in candidates:
+ regen.update(_governed(dec))
+ return result
- verdict = await _judge_evolution(
- provider,
- title=dec.title,
- decision=dec.decision,
- rationale=dec.rationale,
- evidence_text=evidence_text,
- )
+ # The judge calls are independent, so they run concurrently under the same
+ # limit page generation uses. Only the calls overlap: verdicts are applied
+ # below one at a time, in candidate order, because the session is not safe
+ # for concurrent writes.
+ semaphore = asyncio.Semaphore(max(1, max_concurrency))
+
+ async def _judge_one(dec: Any, evidence_text: str) -> dict | None:
+ async with semaphore:
+ try:
+ return await _judge_evolution(
+ provider,
+ title=dec.title,
+ decision=dec.decision,
+ rationale=dec.rationale,
+ evidence_text=evidence_text,
+ )
+ except Exception as exc:
+ # One bad candidate must not cost the others their verdicts.
+ logger.warning(
+ "decision_evolution.judge_failed",
+ decision_id=getattr(dec, "id", None),
+ error=str(exc),
+ )
+ return None
+
+ verdicts = await asyncio.gather(*(_judge_one(dec, ev) for dec, ev, _s in candidates))
+
+ for (dec, _evidence, _signals), verdict in zip(candidates, verdicts, strict=True):
if verdict is None:
continue
+ governed = _governed(dec)
kind = verdict["verdict"]
if kind == "superseded":
diff --git a/tests/unit/cli/test_update_decision_evolution.py b/tests/unit/cli/test_update_decision_evolution.py
new file mode 100644
index 000000000..c0c8fde75
--- /dev/null
+++ b/tests/unit/cli/test_update_decision_evolution.py
@@ -0,0 +1,72 @@
+"""The update's decision-evolution step: evidence scope, concurrency knob, cost label."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+from repowise.cli.commands.update_cmd.command import _run_decision_evolution
+from repowise.core.generation.cost_tracker import CostTracker
+
+
+def _diff(path: str, status: str = "modified") -> SimpleNamespace:
+ return SimpleNamespace(path=path, status=status, trigger_commit_message=None, diff_text=None)
+
+
+def test_evolution_judge_calls_are_booked_as_decision_spend(tmp_path, monkeypatch):
+ import repowise.core.analysis.decision_evolution as evo_mod
+
+ seen: dict = {}
+ tracker = CostTracker()
+
+ async def fake_run(session, repo_id, *, evidence_by_file, max_concurrency, **kw):
+ # The label a provider would read at record() time, mid-judge.
+ seen["operation"] = tracker.operation
+ seen["evidence"] = evidence_by_file
+ seen["max_concurrency"] = max_concurrency
+ return {"regen_files": set(), "superseded": 0, "amended": 0, "reaffirmed": 0}
+
+ monkeypatch.setattr(evo_mod, "run_update_evolution", fake_run)
+ monkeypatch.setattr(evo_mod, "commits_in_range", lambda *a: {"aaaaaaaa"})
+ meta = {
+ "src/a.py": {
+ "significant_commits_json": json.dumps(
+ [
+ {"sha": "aaaaaaaa", "message": "migrate a"},
+ {"sha": "bbbbbbbb", "message": "replace b"},
+ ]
+ )
+ }
+ }
+
+ out = _run_decision_evolution(
+ tmp_path,
+ [_diff("src/a.py")],
+ meta,
+ base_ref="HEAD~1",
+ head="HEAD",
+ provider=object(),
+ cost_tracker=tracker,
+ max_concurrency=7,
+ )
+
+ assert out is not None
+ assert seen["operation"] == "decision_extraction"
+ assert tracker.operation == "doc_generation" # restored afterwards
+ assert seen["max_concurrency"] == 7
+ assert "migrate a" in seen["evidence"]["src/a.py"]
+ assert "replace b" not in seen["evidence"]["src/a.py"]
+
+
+def test_no_changed_file_skips_evolution(tmp_path):
+ out = _run_decision_evolution(
+ tmp_path,
+ [_diff("x.py", "deleted")],
+ {},
+ base_ref="HEAD~1",
+ head="HEAD",
+ provider=None,
+ cost_tracker=CostTracker(),
+ max_concurrency=1,
+ )
+ assert out is None
diff --git a/tests/unit/persistence/test_decision_evolution_update.py b/tests/unit/persistence/test_decision_evolution_update.py
index 44d76b1ce..d0e4432ef 100644
--- a/tests/unit/persistence/test_decision_evolution_update.py
+++ b/tests/unit/persistence/test_decision_evolution_update.py
@@ -8,16 +8,20 @@ evolved decision are returned for regeneration so they re-render in the same run
from __future__ import annotations
+import asyncio
import json
+import subprocess
from types import SimpleNamespace
from repowise.core.analysis.decision_evolution import (
+ commits_in_range,
contradicts,
is_reversal,
pass1_evolution_candidates,
run_update_evolution,
scan_evolution_signals,
supersession_confidence,
+ update_evidence_by_file,
)
from repowise.core.persistence.crud import bulk_upsert_decisions, get_decision
from tests.unit.persistence.helpers import accept, insert_repo
@@ -200,3 +204,184 @@ async def test_run_update_evolution_without_provider_queues_regen_only(async_ses
assert "src/db.py" in result["regen_files"]
assert result["superseded"] == 0
assert (await get_decision(async_session, did)).status == "active"
+
+
+# ---------------------------------------------------------------------------
+# Scope: only this update's commits feed Pass 1
+# ---------------------------------------------------------------------------
+
+
+def test_update_evidence_keeps_only_commits_in_this_update_range():
+ history = [
+ {"sha": "aaaaaaaa", "message": "feat: migrate the cache because of load"},
+ {"sha": "bbbbbbbb", "message": "refactor: replace MySQL with Postgres", "body": "why"},
+ ]
+ diffs = [
+ SimpleNamespace(
+ path="src/db.py", status="modified", trigger_commit_message=None, diff_text=None
+ ),
+ # Deleted files carry no evidence.
+ SimpleNamespace(
+ path="src/gone.py", status="deleted", trigger_commit_message=None, diff_text=None
+ ),
+ ]
+ meta = {
+ "src/db.py": {"significant_commits_json": json.dumps(history)},
+ "src/gone.py": {"significant_commits_json": json.dumps(history)},
+ }
+
+ evidence = update_evidence_by_file(diffs, meta, {"aaaaaaaa"})
+ assert set(evidence) == {"src/db.py"}
+ assert "migrate the cache" in evidence["src/db.py"]
+ # The older commit was judged by the update that brought it in.
+ assert "replace MySQL" not in evidence["src/db.py"]
+
+ # No commit in range (working-tree only, or git failed): no evidence at all.
+ assert update_evidence_by_file(diffs, meta, set()) == {}
+
+
+def test_commits_in_range_lists_short_shas_between_refs(tmp_path):
+ def git(*args: str) -> str:
+ return subprocess.run(
+ ["git", "-C", str(tmp_path), *args], check=True, capture_output=True, text=True
+ ).stdout.strip()
+
+ git("init", "-q")
+ git("config", "user.email", "[email protected]")
+ git("config", "user.name", "t")
+ git("config", "commit.gpgsign", "false")
+ shas = []
+ for i in range(3):
+ (tmp_path / "f.txt").write_text(str(i))
+ git("add", "f.txt")
+ git("commit", "-q", "-m", f"c{i}")
+ shas.append(git("rev-parse", "HEAD"))
+
+ assert commits_in_range(tmp_path, shas[0], shas[2]) == {shas[1][:8], shas[2][:8]}
+ assert commits_in_range(tmp_path, shas[2], None) == set()
+ # A ref git cannot resolve yields nothing rather than whole-history evidence.
+ assert commits_in_range(tmp_path, "no-such-ref", None) == set()
+
+
+# ---------------------------------------------------------------------------
+# Pass 2 runs concurrently, keeps each verdict on its own decision, and
+# isolates a failing call
+# ---------------------------------------------------------------------------
+
+
+async def _seed_many(session, repo_id: str, titles: list[str]) -> dict[str, str]:
+ rows = [
+ {
+ "title": title,
+ "decision": f"keep the {title.lower()} approach",
+ "rationale": f"{title} was measured to be the simplest option",
+ "source": "inline_marker",
+ "status": "proposed",
+ "affected_files": [f"src/{i}.py"],
+ "evidence_file": f"src/{i}.py",
+ "confidence": 0.6,
+ "verification": "exact",
+ "source_quote": title,
+ }
+ for i, title in enumerate(titles)
+ ]
+ ids = await bulk_upsert_decisions(session, repo_id, rows)
+ return dict(zip(titles, ids, strict=True))
+
+
+class _ScriptedProvider:
+ """Answers per decision title after a per-title delay; tracks overlap."""
+
+ def __init__(self, script: dict[str, tuple[float, str | Exception]]) -> None:
+ self._script = script
+ self.in_flight = 0
+ self.peak = 0
+
+ async def generate(self, system: str, prompt: str, **kwargs) -> SimpleNamespace:
+ title = next(t for t in self._script if f"Title: {t}\n" in prompt)
+ delay, answer = self._script[title]
+ self.in_flight += 1
+ self.peak = max(self.peak, self.in_flight)
+ try:
+ await asyncio.sleep(delay)
+ finally:
+ self.in_flight -= 1
+ if isinstance(answer, Exception):
+ raise answer
+ return SimpleNamespace(content=answer)
+
+
+def _verdict(kind: str, quote: str) -> str:
+ return json.dumps({"verdict": kind, "rationale": quote, "source_quote": quote})
+
+
+def _evidence_for(titles: list[str]) -> dict[str, str]:
+ return {
+ f"src/{i}.py": f"refactor: replace {t.lower()} because it is slow"
+ for i, t in enumerate(titles)
+ }
+
+
+async def test_run_update_evolution_judges_concurrently_in_candidate_order(async_session):
+ repo = await insert_repo(async_session)
+ titles = ["Alpha", "Bravo", "Charlie", "Delta"]
+ ids = await _seed_many(async_session, repo.id, titles)
+ evidence = _evidence_for(titles)
+ # The first candidate is the slowest, so calls finish out of order; each
+ # verdict must still land on its own decision.
+ provider = _ScriptedProvider(
+ {
+ "Alpha": (0.08, _verdict("superseded", "replace alpha")),
+ "Bravo": (0.01, _verdict("reaffirmed", "")),
+ "Charlie": (0.02, RuntimeError("provider exploded")),
+ "Delta": (0.0, _verdict("amended", "replace delta")),
+ }
+ )
+
+ result = await run_update_evolution(
+ async_session,
+ repo.id,
+ changed_files=set(evidence),
+ evidence_by_file=evidence,
+ provider=provider,
+ max_concurrency=2,
+ )
+
+ assert provider.peak == 2 # concurrent, and never above the limit
+ assert result["superseded"] == 1
+ assert result["amended"] == 1
+ assert result["reaffirmed"] == 1
+ # Charlie's failure dropped only Charlie's verdict.
+ assert result["regen_files"] == {"src/0.py", "src/3.py"}
+ assert (await get_decision(async_session, ids["Alpha"])).status == "superseded"
+ for title in ("Bravo", "Charlie", "Delta"):
+ assert (await get_decision(async_session, ids[title])).status == "proposed"
+
+
+async def test_run_update_evolution_isolates_an_unexpected_judge_error(async_session, monkeypatch):
+ from repowise.core.analysis.decisions import evolution
+
+ repo = await insert_repo(async_session)
+ titles = ["Alpha", "Bravo"]
+ await _seed_many(async_session, repo.id, titles)
+ real_judge = evolution._judge_evolution
+
+ async def judge(provider, *, title, **kwargs):
+ if title == "Alpha":
+ raise ValueError("gate blew up")
+ return await real_judge(provider, title=title, **kwargs)
+
+ monkeypatch.setattr(evolution, "_judge_evolution", judge)
+ evidence = _evidence_for(titles)
+ provider = _ScriptedProvider({"Bravo": (0.0, _verdict("amended", "replace bravo"))})
+
+ result = await run_update_evolution(
+ async_session,
+ repo.id,
+ changed_files=set(evidence),
+ evidence_by_file=evidence,
+ provider=provider,
+ max_concurrency=4,
+ )
+ assert result["amended"] == 1
+ assert result["regen_files"] == {"src/1.py"}