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(update): stop four repeated costs in the update prologue (#1376)

Raghav Chamadiya46ae50e1fd0e
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index 5e3e85e44..dd4a1a84e 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -34,6 +34,7 @@ from repowise.cli.helpers import (
console,
ensure_repowise_dir,
get_head_commit,
+ head_commit_ts,
load_config,
load_state,
resolve_max_file_pages,
@@ -1560,6 +1561,20 @@ def init_command(
# their stamp. Without it `health_analyzer_changed` reads absent-as-
# unchanged and the version trigger never fires for them.
base_state["health_analyzer_version"] = HEALTH_ANALYZER_VERSION
+ # This run just scored every file, so the periodic re-score cadence
+ # starts now. Without the stamp the gate reads "never re-scored" and the
+ # very next update re-scores the whole repo init had only just scored.
+ #
+ # Only when there really is a report. The health phase swallows its own
+ # failures and returns None, and nothing is persisted for a None report,
+ # so stamping there would suppress the first update's re-score - the
+ # only thing that would have repopulated the missing rows. Same rule the
+ # two update-side writers follow: they stamp only on a re-score that
+ # returned True. None (no git) is left unstamped too: the gate cannot
+ # fire without a head_ts either, so there is nothing to suppress.
+ _head_ts = head_commit_ts(repo_path) if getattr(result, "health_report", None) else None
+ if _head_ts is not None:
+ base_state["last_full_rescore_at"] = _head_ts
# Index-only still renders the full concept tree (deterministically, from
# templates), so the store has the current capability — stamp the terminal
# version rather than clamping it below the reindex gate and falsely
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
index 5022ebe5e..ee5c3dbe0 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
@@ -17,6 +17,7 @@ from repowise.cli._repo_session import open_repo_db
from repowise.cli.helpers import (
config_fingerprint,
get_head_commit,
+ head_commit_ts,
load_config,
load_state,
run_async,
@@ -394,4 +395,18 @@ def save_full_state_and_config(
# tracking it here — otherwise a fresh install carries no stamp and the
# first analyzer change after it cannot tell it needs a re-score.
state["health_analyzer_version"] = HEALTH_ANALYZER_VERSION
+ # This run just scored every file, so the periodic re-score cadence starts
+ # now. Without the stamp the gate reads "never re-scored" and the very next
+ # update re-scores the whole repo that init had only just finished scoring.
+ #
+ # Only when there really is a report. The health phase swallows its own
+ # failures and returns None, and nothing is persisted for a None report, so
+ # stamping there would suppress the first update's re-score - the only thing
+ # that would have repopulated the missing rows. Same rule the two
+ # update-side writers follow: they stamp only on a re-score that returned
+ # True. None (no git) is left unstamped too: the gate cannot fire without a
+ # head_ts either, so there is nothing to suppress.
+ _head_ts = head_commit_ts(repo_path) if getattr(result, "health_report", None) else None
+ if _head_ts is not None:
+ state["last_full_rescore_at"] = _head_ts
save_state(repo_path, state, full_index=True)
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 13c24d6d7..ad2c9b0a7 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -426,20 +426,14 @@ def _renderer_inputs(repo_path):
def _head_commit_ts(repo_path) -> float | None:
"""Committer timestamp of the repo's HEAD, or None when git is unavailable.
- Anchors the periodic idle-file health re-score gate (#728) to repo time
- rather than wall clock, so the cadence is deterministic under
- ``REPOWISE_GIT_WINDOW_ANCHOR`` and correct for historical checkouts.
+ Lives in ``cli.helpers`` so ``init`` stamps the re-score gate in the units
+ this path reads back. Kept as a thin module-level name because this module
+ is where the gate is evaluated, and a caller reading ``_head_commit_ts``
+ here should not have to know it resolves elsewhere.
"""
- try:
- import git
+ from repowise.cli.helpers import head_commit_ts
- repo = git.Repo(repo_path, search_parent_directories=True)
- try:
- return float(repo.head.commit.committed_date)
- finally:
- repo.close()
- except Exception:
- return None
+ return head_commit_ts(repo_path)
def _current_renderer_fingerprint(repo_path) -> str:
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py b/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py
index 1d702df02..800e082fb 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py
@@ -279,14 +279,17 @@ async def _persist_async(
except Exception as exc:
degraded.append(f"Stale-page decay: {exc}")
- # Placement depends on the whole page set, which on an incremental
- # run lives in the store rather than in the pages just generated.
- try:
- from repowise.core.pipeline.page_tree_sync import rebuild_page_tree
-
- await rebuild_page_tree(session, repo_id)
- except Exception as exc:
- degraded.append(f"Page tree rebuild: {exc}")
+ # No page-tree rebuild here. ``persist_incremental_index`` runs one
+ # unconditionally right after this call returns (see the caller in
+ # ``update_cmd/command.py``), and it runs it *after* the sweeps and
+ # tombstones this session cannot see — so it is strictly the better
+ # placed of the two, and doing it twice only pays for a repo-wide
+ # page read that the second pass immediately repeats. Same reason as
+ # the related-pages backfill above. The cost of deferring is
+ # atomicity: placement no longer commits in the same session as the
+ # pages, so if the process dies between the two, this run's pages
+ # sit unplaced until the next update. Recovery needs nothing to
+ # re-render, since that rebuild runs unconditionally.
# Real DB total, not an accumulation: regeneration upserts, so
# adding len(generated_pages) each run inflates the count forever.
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 6b1b0935a..bedbd3cb0 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -16,7 +16,7 @@ from typing import Any
import structlog
-from repowise.cli.helpers import console, run_async, save_state
+from repowise.cli.helpers import console, head_commit_ts, run_async, save_state
from repowise.core.analysis.health import HEALTH_ANALYZER_VERSION
from .incremental import _build_repo_graph
@@ -1101,16 +1101,20 @@ def _run_full_health_rescore(
console.print(f"[yellow]Health re-score failed: {exc}[/yellow]")
return
- save_state(
- repo_path,
- {
- **state,
- "last_sync_commit": head,
- "config_fingerprint": curr_fingerprint,
- # These rows were just rewritten by this analyzer.
- "health_analyzer_version": HEALTH_ANALYZER_VERSION,
- },
- )
+ # Same full-replace re-score the periodic gate runs, so it restarts the same
+ # cadence. Left unstamped when git is unreadable: the gate cannot fire
+ # without a head_ts either.
+ new_state = {
+ **state,
+ "last_sync_commit": head,
+ "config_fingerprint": curr_fingerprint,
+ # These rows were just rewritten by this analyzer.
+ "health_analyzer_version": HEALTH_ANALYZER_VERSION,
+ }
+ rescored_at = head_commit_ts(repo_path)
+ if rescored_at is not None:
+ new_state["last_full_rescore_at"] = rescored_at
+ save_state(repo_path, new_state)
elapsed = time.monotonic() - start
console.print(f"[green]Config-triggered health re-score complete[/green] in {elapsed:.1f}s")
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 3754257c4..0b6cfadc3 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -494,6 +494,28 @@ def get_head_commit(repo_path: Path) -> str | None:
return _core_head(Path(repo_path))
+def head_commit_ts(repo_path: Path) -> float | None:
+ """Committer timestamp of the repo's HEAD, or None when git is unavailable.
+
+ Anchors the periodic idle-file health re-score gate (#728) to repo time
+ rather than wall clock, so the cadence is deterministic under
+ ``REPOWISE_GIT_WINDOW_ANCHOR`` and correct for historical checkouts.
+
+ Shared with ``init`` so a fresh index can stamp ``last_full_rescore_at`` in
+ the same units the gate reads it back in.
+ """
+ try:
+ import git
+
+ repo = git.Repo(repo_path, search_parent_directories=True)
+ try:
+ return float(repo.head.commit.committed_date)
+ finally:
+ repo.close()
+ except Exception:
+ return None
+
+
# ---------------------------------------------------------------------------
# Config (provider / model / embedder persisted after init)
# ---------------------------------------------------------------------------
diff --git a/packages/cli/src/repowise/cli/upgrade.py b/packages/cli/src/repowise/cli/upgrade.py
index f81f25e93..b52cde5d1 100644
--- a/packages/cli/src/repowise/cli/upgrade.py
+++ b/packages/cli/src/repowise/cli/upgrade.py
@@ -124,15 +124,24 @@ def _vector_dims(repo_path: Path) -> tuple[int | None, int | None]:
it truly is) and cannot be wrong (no real embedder emits 8 dimensions).
Re-embedding *down* to the mock is never proposed either — it destroys a
working index and gains nothing.
+
+ The pin is checked before the table. Reading the stored width costs an
+ ``import lancedb`` (1.7s measured, versus 0.09s for the connect and schema
+ read it exists for), and ``assess_store`` runs on every ``update`` including
+ the no-op path a post-commit hook fires on. Keyless repos resolve the mock
+ here and never pay it. A repo that does pin a real embedder now builds it
+ where it used to short-circuit, which imports that provider's module, but
+ that replaces the lancedb import rather than adding to it. The order is
+ free to change because both guards are
+ conjuncts of one predicate: past ``stored == MockEmbedder.dimensions``, the
+ ``current == stored`` refusal below is exactly ``current == 8``, so neither
+ guard reads the other's value.
"""
from repowise.core.providers.embedding.base import MockEmbedder
from .providers.embedders import build_embedder, resolve_embedder_for_repo
from .providers.vector_store import existing_vector_dim
- stored = existing_vector_dim(repo_path / REPOWISE_DIR / "lancedb")
- if stored != MockEmbedder.dimensions:
- return None, None
try:
embedder = build_embedder(resolve_embedder_for_repo(repo_path))
except Exception:
@@ -140,7 +149,10 @@ def _vector_dims(repo_path: Path) -> tuple[int | None, int | None]:
if isinstance(embedder, MockEmbedder):
return None, None
current = getattr(embedder, "dimensions", None)
- if not isinstance(current, int) or current <= 0 or current == stored:
+ if not isinstance(current, int) or current <= 0 or current == MockEmbedder.dimensions:
+ return None, None
+ stored = existing_vector_dim(repo_path / REPOWISE_DIR / "lancedb")
+ if stored != MockEmbedder.dimensions:
return None, None
return stored, current
diff --git a/packages/core/src/repowise/core/generation/editor_files/tech_stack.py b/packages/core/src/repowise/core/generation/editor_files/tech_stack.py
index 3af5eee47..8ccdb0350 100644
--- a/packages/core/src/repowise/core/generation/editor_files/tech_stack.py
+++ b/packages/core/src/repowise/core/generation/editor_files/tech_stack.py
@@ -117,12 +117,98 @@ def _find_dotnet_projects(repo_path: Path) -> list[Path]:
return found
+# Every root-level path the scan below reads by name. The memo key stats all of
+# them, so adding a read here means adding it there or the memo goes stale on
+# the signal you just added.
+_MANIFEST_FILES = (
+ "package.json",
+ "tsconfig.json",
+ "pyproject.toml",
+ "setup.py",
+ "Cargo.toml",
+ "go.mod",
+ "pom.xml",
+ "build.gradle",
+ "build.gradle.kts",
+ "Gemfile",
+ "composer.json",
+ "Dockerfile",
+ "docker-compose.yml",
+ "docker-compose.yaml",
+ # .NET evidence read at the root, same as the rest.
+ "Directory.Build.props",
+ "Directory.Packages.props",
+)
+
+# repo_path -> (manifest fingerprint, detected stack).
+_STACK_CACHE: dict[str, tuple[tuple, list[TechStackItem]]] = {}
+
+
+def _manifest_fingerprint(repo_path: Path) -> tuple:
+ """Cheap stat-based signature of the root inputs this scan reads.
+
+ Sixteen stats plus one root glob, versus the bounded .csproj walk that
+ dominates the real scan (0.18s on hugo, 0.47s on PowerToys, measured). The
+ ``*.sln`` glob is in the key because the scan reads solutions by pattern
+ rather than by name, so no fixed entry can stand in for them.
+
+ The trailing directory-mtime entry is a bonus, not the mechanism: on Windows
+ file timestamps come from the ~15.6ms system timer tick, so two changes
+ inside one tick can leave it byte-identical. Every root path the scan reads
+ is stat'd by name or globbed above, so the key does not depend on it.
+
+ CEILING: it does not see a nested change - a ``.csproj`` appearing under an
+ existing subdirectory, or a workspace ``tsconfig.json`` one or two levels
+ down (``glob("*/tsconfig.json")`` and ``"*/*/tsconfig.json"``). Covering
+ those means walking, which is the cost this exists to avoid. In one CLI
+ command the window is seconds, so it is unreachable there; a long-lived
+ process (the server's job executor, or a test suite driving several
+ ``CliRunner`` invocations in one interpreter) can re-index the same repo
+ later and be served a stale stack. Blast radius is contextual metadata only:
+ framework edges, the knowledge-graph tech list, the editor file table. To
+ close it, key on a traversal snapshot instead of the root.
+ """
+ sig: list = []
+ for name in _MANIFEST_FILES:
+ try:
+ st = (repo_path / name).stat()
+ sig.append((name, st.st_mtime_ns, st.st_size))
+ except OSError:
+ sig.append((name, None, None))
+ try:
+ sig.extend(sorted((p.name, p.stat().st_mtime_ns) for p in repo_path.glob("*.sln")))
+ except OSError:
+ sig.append(("*.sln", None))
+ try:
+ sig.append(("", repo_path.stat().st_mtime_ns, None))
+ except OSError:
+ sig.append(("", None, None))
+ return tuple(sig)
+
+
def detect_tech_stack(repo_path: Path) -> list[TechStackItem]:
"""Detect languages, frameworks, and infra tools from manifest files.
Scans repo root and one level deep for common manifest files.
Returns items sorted by category then name.
+
+ Memoized on the root inputs' stat signature: a single ``repowise update``
+ asks twice (the graph's framework edges, then the knowledge-graph refresh)
+ and gets the same answer both times off an unchanged tree. See
+ :func:`_manifest_fingerprint` for what the key does and does not cover.
"""
+ key = str(Path(repo_path).resolve())
+ fingerprint = _manifest_fingerprint(Path(repo_path))
+ cached = _STACK_CACHE.get(key)
+ if cached is not None and cached[0] == fingerprint:
+ return list(cached[1])
+ items_list = _detect_tech_stack_uncached(Path(repo_path))
+ _STACK_CACHE[key] = (fingerprint, items_list)
+ return list(items_list)
+
+
+def _detect_tech_stack_uncached(repo_path: Path) -> list[TechStackItem]:
+ """The real scan. See :func:`detect_tech_stack` for the contract."""
items: dict[str, TechStackItem] = {}
def add(name: str, version: str | None, category: str) -> None:
diff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.py
index 73043797c..ea14f923c 100644
--- a/tests/integration/test_cli.py
+++ b/tests/integration/test_cli.py
@@ -742,6 +742,37 @@ class TestUpdateConfigChangeDetection:
assert "Config files changed" in r2.output
assert "health re-score complete" in r2.output.lower()
+ def test_init_stamps_the_rescore_cadence_so_the_next_update_skips_it(
+ self, runner, git_work_repo
+ ):
+ """A fresh index must not be re-scored by the update right after it.
+
+ ``init`` scores every file. Until it stamped ``last_full_rescore_at``,
+ the first update read the missing stamp as "never re-scored" and scored
+ every file again — about 30s on a 2k-file repo, on every fresh install.
+ Asserted against HEAD's committer timestamp rather than "is present",
+ because the gate compares it to exactly that and a wall-clock value
+ would drift under ``REPOWISE_GIT_WINDOW_ANCHOR``.
+ """
+ r0 = runner.invoke(
+ cli, ["init", str(git_work_repo), "--index-only"], catch_exceptions=False
+ )
+ assert r0.exit_code == 0, r0.output
+
+ import subprocess
+
+ head_ts = float(
+ subprocess.check_output(
+ ["git", "log", "-1", "--format=%ct"], cwd=git_work_repo, text=True
+ ).strip()
+ )
+ assert self._state(git_work_repo)["last_full_rescore_at"] == head_ts
+
+ # And the gate agrees, which is the behaviour the stamp exists for.
+ from repowise.cli.commands.update_cmd.persistence import full_rescore_due
+
+ assert full_rescore_due(self._state(git_work_repo), head_ts) is False
+
def test_dry_run_does_not_rescore_or_advance_fingerprint(self, runner, git_work_repo):
"""`update --dry-run` after a config change must not mutate state/DB."""
@@ -792,10 +823,11 @@ class TestUpdateConfigChangeDetection:
args = ["--index-only"] if mode == "index-only" else ["--docs", "--provider", "mock"]
runner.invoke(cli, ["init", str(git_work_repo), "--index-only"], catch_exceptions=False)
- # Switch the *periodic* re-score gate off. `init` writes no
- # ``last_full_rescore_at``, so without this the #728 time gate is due on
- # the very first update and fires the full re-score on its own — which
- # would let this test pass even with the config-forced re-score deleted.
+ # Switch the *periodic* re-score gate off, so a passing run can only be
+ # the config-forced re-score. ``init`` now stamps ``last_full_rescore_at``
+ # itself, which already suppresses the #728 time gate here; this seeding
+ # stays because "far future" is the stronger statement of the two and it
+ # is what makes the assertion below about the *config* trigger alone.
state_file = git_work_repo / ".repowise" / "state.json"
seeded = json.loads(state_file.read_text(encoding="utf-8"))
seeded["last_full_rescore_at"] = 9e18 # far future: never "due"
diff --git a/tests/unit/cli/test_embedder_resolution.py b/tests/unit/cli/test_embedder_resolution.py
index 8a25e1826..3f6f92c2f 100644
--- a/tests/unit/cli/test_embedder_resolution.py
+++ b/tests/unit/cli/test_embedder_resolution.py
@@ -469,6 +469,59 @@ def test_mock_pin_never_proposes_re_embedding_a_real_store(
assert _vector_dims(tmp_path) == (None, None)
+def test_a_mock_pin_never_reads_the_stored_table(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The keyless default must not open LanceDB to learn nothing.
+
+ Reading the stored width costs an ``import lancedb`` (1.7s measured, versus
+ 0.09s for the connect and schema read it is there for), and ``assess_store``
+ runs on every ``update`` including the no-op path a post-commit hook fires
+ on. A mock pin can never produce a verdict, so the read is pure waste and
+ the guards are ordered to skip it. Asserting the call count rather than the
+ timing: this is the invariant, the seconds are its consequence.
+ """
+ from repowise.cli.upgrade import _vector_dims
+
+ _write_config(tmp_path, embedder="mock")
+ monkeypatch.delenv("REPOWISE_EMBEDDER", raising=False)
+
+ calls: list[Path] = []
+
+ def _spy(lance_dir):
+ calls.append(lance_dir)
+ return 8
+
+ monkeypatch.setattr("repowise.cli.providers.vector_store.existing_vector_dim", _spy)
+
+ assert _vector_dims(tmp_path) == (None, None)
+ assert calls == []
+
+
+def test_a_real_pin_still_reads_the_stored_table(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The saving must not have been bought by skipping the check that matters."""
+ from repowise.cli.upgrade import _vector_dims
+
+ _write_config(tmp_path, embedder="openai")
+ monkeypatch.delenv("REPOWISE_EMBEDDER", raising=False)
+
+ calls: list[Path] = []
+
+ def _spy(lance_dir):
+ calls.append(lance_dir)
+ return 8
+
+ monkeypatch.setattr("repowise.cli.providers.vector_store.existing_vector_dim", _spy)
+ monkeypatch.setattr(
+ "repowise.cli.providers.embedders.build_embedder", lambda _n: _WideEmbedder()
+ )
+
+ assert _vector_dims(tmp_path) == (8, 1536)
+ assert len(calls) == 1
+
+
async def test_auto_reembed_refuses_to_run_with_a_mock_embedder(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
diff --git a/tests/unit/cli/test_health_rescore_gate.py b/tests/unit/cli/test_health_rescore_gate.py
index 49645e970..2a5482fde 100644
--- a/tests/unit/cli/test_health_rescore_gate.py
+++ b/tests/unit/cli/test_health_rescore_gate.py
@@ -72,3 +72,92 @@ class TestFullRescoreDue:
through to the ``head_ts`` guard rather than short-circuiting True."""
state = {"health_analyzer_version": HEALTH_ANALYZER_VERSION}
assert full_rescore_due(state, None) is False
+
+ @pytest.mark.parametrize("stamp", [None, "", "not-a-number"])
+ def test_a_missing_or_unusable_stamp_is_due(self, stamp):
+ """"Never re-scored" has to establish the baseline rather than skip it.
+
+ This is why ``init`` stamps: the branch is correct, and a fresh index
+ that left it unset walked straight into it (see
+ ``test_a_fresh_index_is_not_due_for_a_re_score``).
+ """
+ state = {"health_analyzer_version": HEALTH_ANALYZER_VERSION}
+ if stamp is not None:
+ state["last_full_rescore_at"] = stamp
+ assert full_rescore_due(state, 1_000_000.0) is True
+
+
+class TestInitStampsTheCadence:
+ """A fresh index must not be re-scored by the update that follows it.
+
+ ``init`` scores every file, then the first ``update`` used to find no
+ ``last_full_rescore_at``, read it as "never re-scored", and score every file
+ again — about 30s on a 2k-file repo, on every fresh install.
+ """
+
+ def test_a_fresh_index_is_not_due_for_a_re_score(self):
+ head_ts = 1_000_000.0
+ # Exactly what init now writes.
+ state = {
+ "health_analyzer_version": HEALTH_ANALYZER_VERSION,
+ "last_full_rescore_at": head_ts,
+ }
+ assert full_rescore_due(state, head_ts) is False
+
+ def test_the_cadence_still_comes_due_later(self):
+ """Stamping starts the clock, it does not stop it."""
+ head_ts = 1_000_000.0
+ state = {
+ "health_analyzer_version": HEALTH_ANALYZER_VERSION,
+ "last_full_rescore_at": head_ts,
+ }
+ assert full_rescore_due(state, head_ts + (8 * 86400.0)) is True
+
+ def test_an_analyzer_bump_still_forces_it(self):
+ """The stamp must not be able to suppress the version trigger."""
+ head_ts = 1_000_000.0
+ state = {
+ "health_analyzer_version": HEALTH_ANALYZER_VERSION - 1,
+ "last_full_rescore_at": head_ts,
+ }
+ assert full_rescore_due(state, head_ts) is True
+
+
+ "module_name",
+ [
+ "repowise.cli.commands.init_cmd.command",
+ "repowise.cli.commands.init_cmd.persistence",
+ ],
+)
+def test_init_never_stamps_the_cadence_for_a_run_that_scored_nothing(module_name):
+ """The stamp says "these rows are current", so it must not outrun the rows.
+
+ The health phase swallows its own failures and returns ``None``
+ (``pipeline/phases/analysis.py``), and a ``None`` report persists nothing
+ (``pipeline/persist.py``, ``if getattr(result, "health_report", None)``). An
+ unconditional stamp would then suppress the first update's re-score, which
+ is the only thing that would have written the missing rows, for a repo-week
+ and indefinitely on an idle repo, since the cadence is anchored to HEAD's
+ committer time rather than wall clock. Both update-side writers already
+ stamp only on a re-score that returned True; init has to match.
+
+ Source-level for the same reason ``test_page_tree_wiring`` is: the failure
+ is "somebody added a stamp and did not know the rule", the rows only exist
+ after a real pipeline run, and an unconditional stamp raises nothing and
+ reads as working right up until a health failure makes it permanent.
+ """
+ import inspect
+
+ lines = inspect.getsource(__import__(module_name, fromlist=["*"])).splitlines()
+ assert any("last_full_rescore_at" in line for line in lines), (
+ f"{module_name} no longer stamps the cadence at all, so a fresh index is "
+ "back to being re-scored by the update right after it"
+ )
+ sources = [line for line in lines if "= head_commit_ts(" in line]
+ assert sources, f"{module_name} no longer resolves a stamp value"
+ for line in sources:
+ assert "health_report" in line, (
+ f"{module_name} resolves the cadence stamp without checking that this "
+ f"run produced a health report: {line.strip()}"
+ )
diff --git a/tests/unit/generation/test_tech_stack.py b/tests/unit/generation/test_tech_stack.py
index ec43ae6cb..2ec0463ee 100644
--- a/tests/unit/generation/test_tech_stack.py
+++ b/tests/unit/generation/test_tech_stack.py
@@ -4,6 +4,9 @@ from __future__ import annotations
import json
+import pytest
+
+from repowise.core.generation.editor_files import tech_stack as tech_stack_mod
from repowise.core.generation.editor_files.tech_stack import (
detect_build_commands,
detect_tech_stack,
@@ -266,6 +269,96 @@ def test_malformed_composer_does_not_crash(tmp_path):
assert "PHP" in names # PHP language still added (file existed)
+# ---------------------------------------------------------------------------
+# detect_tech_stack memoisation
+# ---------------------------------------------------------------------------
+
+
+def test_a_repeat_scan_of_an_unchanged_tree_does_not_rewalk(tmp_path, monkeypatch):
+ """One ``repowise update`` asks twice; the second must be free.
+
+ The bounded .csproj walk is the whole cost of a scan (0.18s on hugo, 0.47s
+ on PowerToys, measured), and the graph's framework edges and the
+ knowledge-graph refresh both ask for the same repo in the same run.
+ """
+ (tmp_path / "go.mod").write_text("module example.com/app\n\ngo 1.22\n", encoding="utf-8")
+
+ walks = []
+ real = tech_stack_mod._find_dotnet_projects
+ monkeypatch.setattr(
+ tech_stack_mod,
+ "_find_dotnet_projects",
+ lambda p: (walks.append(p), real(p))[1],
+ )
+
+ first = detect_tech_stack(tmp_path)
+ second = detect_tech_stack(tmp_path)
+
+ assert [i.name for i in first] == [i.name for i in second]
+ assert "Go" in [i.name for i in first]
+ assert len(walks) == 1
+
+
+def test_editing_a_manifest_re_detects(tmp_path):
+ """The memo must not outlive the answer it cached."""
+ (tmp_path / "pyproject.toml").write_text('[project]\nname = "app"\n', encoding="utf-8")
+ assert "Django" not in [i.name for i in detect_tech_stack(tmp_path)]
+
+ (tmp_path / "pyproject.toml").write_text(
+ '[project]\ndependencies = ["django>=5.0"]\n', encoding="utf-8"
+ )
+ assert "Django" in [i.name for i in detect_tech_stack(tmp_path)]
+
+
+def test_adding_a_manifest_re_detects(tmp_path):
+ """A root add moves the directory mtime, which is part of the key."""
+ (tmp_path / "go.mod").write_text("module example.com/app\n\ngo 1.22\n", encoding="utf-8")
+ assert "Docker" not in [i.name for i in detect_tech_stack(tmp_path)]
+
+ (tmp_path / "Dockerfile").write_text("FROM scratch\n", encoding="utf-8")
+ assert "Docker" in [i.name for i in detect_tech_stack(tmp_path)]
+
+
[email protected]("filename", ["App.sln", "Directory.Build.props"])
+def test_a_root_signal_moves_the_key_without_help_from_the_directory_mtime(tmp_path, filename):
+ """Every root path the scan reads must be in the key on its own.
+
+ These two are the ones a fixed name list misses: ``.sln`` is globbed rather
+ than read by name, and ``Directory.Build.props`` was absent from the first
+ version of the key. Either alone makes the scan report C#.
+
+ The directory mtime is restored before re-reading, which is the whole point:
+ that leg is quantized to Windows' ~15.6ms timer tick, so a test that let it
+ change would pass whether or not the signal itself is keyed.
+ """
+ import os
+
+ from repowise.core.generation.editor_files.tech_stack import _manifest_fingerprint
+
+ (tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n", encoding="utf-8")
+ before = _manifest_fingerprint(tmp_path)
+ dir_stat = tmp_path.stat()
+
+ (tmp_path / filename).write_text("", encoding="utf-8")
+ os.utime(tmp_path, ns=(dir_stat.st_atime_ns, dir_stat.st_mtime_ns))
+
+ assert _manifest_fingerprint(tmp_path) != before, (
+ f"{filename} is not in the memo key, so a repo that grows one is served "
+ "a stale tech stack"
+ )
+ assert "C#" in [i.name for i in detect_tech_stack(tmp_path)]
+
+
+def test_the_caller_cannot_corrupt_the_memo(tmp_path):
+ """Callers get their own list, so a mutation cannot poison the next reader."""
+ (tmp_path / "go.mod").write_text("module example.com/app\n\ngo 1.22\n", encoding="utf-8")
+
+ first = detect_tech_stack(tmp_path)
+ first.clear()
+
+ assert [i.name for i in detect_tech_stack(tmp_path)] == ["Go"]
+
+
def test_detects_ruff_from_pyproject(tmp_path):
(tmp_path / "pyproject.toml").write_text("[tool.ruff]\nline-length = 88\n", encoding="utf-8")
cmds = detect_build_commands(tmp_path)
diff --git a/tests/unit/persistence/test_page_tree_wiring.py b/tests/unit/persistence/test_page_tree_wiring.py
index 2317def52..4f2ed6727 100644
--- a/tests/unit/persistence/test_page_tree_wiring.py
+++ b/tests/unit/persistence/test_page_tree_wiring.py
@@ -26,10 +26,25 @@ _PERSIST_PATHS = [
("repowise.core.pipeline.incremental", "the incremental index"),
("repowise.core.pipeline.scoped_generation", "a scoped regeneration"),
("repowise.cli.commands.update_cmd.persistence", "the docs update"),
- ("repowise.cli.commands.update_cmd.deterministic", "the template update"),
("repowise.cli.commands.upgrade_flow", "the fast-to-full upgrade"),
]
+# The template update (``update_cmd.deterministic``) writes pages and does NOT
+# rebuild, which is the one exemption to the rule above. It is allowed because
+# its caller runs ``persist_incremental_index`` unconditionally straight after
+# it, in the same command, and that rebuild sees strictly more than this one
+# could (it runs after the sweeps and tombstones). The exemption is not taken on
+# trust: ``test_the_template_update_defers_to_the_persist_that_follows_it`` below
+# asserts the call ordering that makes it safe, so deleting or reordering that
+# caller fails here rather than silently unplacing every re-rendered page.
+_DEFERRED_PATHS = [
+ (
+ "repowise.cli.commands.update_cmd.deterministic",
+ "the template update",
+ "repowise.cli.commands.update_cmd.command",
+ ),
+]
+
@pytest.mark.parametrize("module_name,description", _PERSIST_PATHS)
def test_persist_path_rebuilds_the_tree(module_name: str, description: str):
@@ -45,7 +60,34 @@ def test_persist_path_rebuilds_the_tree(module_name: str, description: str):
def test_the_writer_list_is_not_silently_empty():
"""Guards the parametrisation itself."""
- assert len(_PERSIST_PATHS) >= 6
+ assert len(_PERSIST_PATHS) + len(_DEFERRED_PATHS) >= 6
+
+
[email protected]("module_name,description,caller_name", _DEFERRED_PATHS)
+def test_the_template_update_defers_to_the_persist_that_follows_it(
+ module_name: str, description: str, caller_name: str
+):
+ """A deferred writer is only safe while its caller still rebuilds after it.
+
+ Two things have to hold, and both are checked: the writer really does not
+ rebuild (otherwise the exemption is stale and the work is being done twice
+ again), and the caller invokes it *before* the persist that does rebuild.
+ Reordering those two calls, or dropping the second, silently leaves every
+ re-rendered page unplaced — exactly the failure this module exists for.
+ """
+ writer = inspect.getsource(__import__(module_name, fromlist=["*"]))
+ assert "rebuild_page_tree(" not in writer, (
+ f"{description} ({module_name}) rebuilds the tree after all, so it no "
+ "longer belongs in the deferred list — move it back to _PERSIST_PATHS"
+ )
+
+ caller = inspect.getsource(__import__(caller_name, fromlist=["*"]))
+ writes = caller.index("persist_deterministic_pages(\n")
+ rebuilds = caller.index("_persist_index_only_update(\n")
+ assert writes < rebuilds, (
+ f"{caller_name} no longer runs the rebuilding persist after "
+ f"{description}, so its pages never get placed"
+ )
def test_the_scoped_path_sweeps_superseded_rows():