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(generation): prioritize oldest stale pages when the budget is constrained (#1845)
Nehal kanak kuniyil thottathil34ae6de6f8e5
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex 2b88bf4fd..24acef231 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -1232,11 +1232,14 @@ def run_update(console.print(f"Adaptive cascade budget: [cyan]{cascade_budget}[/cyan]")# Pass the builder's cached file pagerank so the cascade ordering does# not recompute a full-graph pagerank pass on every update.+ from .deterministic import load_stale_file_page_ages+affected = detector.get_affected_pages(file_diffs,graph_builder.graph(),cascade_budget,pagerank=graph_builder.pagerank(),+ stale_pages=load_stale_file_page_ages(repo_path),)# File pages a newer renderer would write differently. The cascade abovediff --git a/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py b/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.pyindex ac3133e4d..685f30d52 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py@@ -339,6 +339,43 @@ def load_file_page_render_keys(repo_path: Path) -> dict[str, str]:return run_async(_load_file_page_render_keys(repo_path))+def load_stale_file_page_ages(repo_path: Path) -> dict[str, float]:+ """``{file_path: staleness_age_seconds}`` for already-stale file pages.++ Drives the cascade-budget ordering in+ :func:`~repowise.core.ingestion.change_detector.ChangeDetector.get_affected_pages`+ so a constrained docs run spends its LLM calls on the oldest stale pages+ rather than reordering purely by importance (issues #847 / #851). Best+ effort, like the render-key load: an unreadable store yields ``{}``, which+ keeps the historical pure-importance ordering.+ """+ return run_async(_load_stale_file_page_ages(repo_path))+++async def _load_stale_file_page_ages(repo_path: Path) -> dict[str, float]:+ from repowise.cli.helpers import get_db_url_for_repo+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ get_stale_file_page_ages,+ )++ engine = create_engine(get_db_url_for_repo(repo_path))+ try:+ async with get_session(create_session_factory(engine)) as session:+ from repowise.core.persistence.crud import get_repository_by_path++ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ return {}+ return await get_stale_file_page_ages(session, repo.id)+ except Exception:+ return {}+ finally:+ await engine.dispose()++async def _load_file_page_render_keys(repo_path: Path) -> dict[str, str]:from repowise.cli.helpers import get_db_url_for_repofrom repowise.core.persistence import create_engine, create_session_factory, get_sessiondiff --git a/packages/core/src/repowise/core/ingestion/change_detector.py b/packages/core/src/repowise/core/ingestion/change_detector.pyindex 2fb1ad65d..aee8c52c1 100644--- a/packages/core/src/repowise/core/ingestion/change_detector.py+++ b/packages/core/src/repowise/core/ingestion/change_detector.py@@ -383,6 +383,7 @@ class ChangeDetector:graph: object, # nx.DiGraphcascade_budget: int = 30,pagerank: dict[str, float] | None = None,+ stale_pages: dict[str, float] | None = None,) -> AffectedPages:"""Compute which wiki pages need action after a set of file changes.@@ -394,6 +395,14 @@ class ChangeDetector:passes GraphBuilder's cached file pagerank so this functiondoes not recompute a full-graph pass). Falls back to aninternal computation when omitted.+ stale_pages: ``{file_path: staleness_age_seconds}`` for pages whose+ prose is already stale, oldest-stale mapping to the largest+ value. When the cascade budget is constrained, these bubble to+ the top of the regenerate slice so the run spends its LLM calls+ on the pages that actually lag the code rather than the+ highest-importance pages that may already be current (issues+ #847 / #851). Pages with no entry count as fresh and sort last.+ Absent (or empty) keeps the historical pure-importance order."""import networkx as nx@@ -457,7 +466,16 @@ class ChangeDetector:all_pages_needing_regen = sorted(directly_changed | one_hop,- key=lambda p: pr.get(p, 0.0),+ key=lambda p: (+ # Staleness-first: an already-stale page (larger age) outranks a+ # fresh page no matter how central the fresh one is, so a+ # constrained budget spends its LLM calls on the pages that+ # actually lag the code (issues #847 / #851). Fresh pages sort+ # below every stale page, importance then breaking the tie+ # within each staleness class.+ 0.0 if not stale_pages else float(stale_pages.get(p, -1.0)),+ pr.get(p, 0.0),+ ),reverse=True,)diff --git a/packages/core/src/repowise/core/persistence/__init__.py b/packages/core/src/repowise/core/persistence/__init__.pyindex 52e64d5e3..8da06a792 100644--- a/packages/core/src/repowise/core/persistence/__init__.py+++ b/packages/core/src/repowise/core/persistence/__init__.py@@ -60,6 +60,7 @@ from .crud import (get_repository_by_path,get_scc_members,get_stale_decisions,+ get_stale_file_page_ages,get_stale_pages,get_top_entry_points,link_graph_nodes_to_external_systems,@@ -255,6 +256,7 @@ __all__ = ["get_scc_members","get_session","get_stale_decisions",+ "get_stale_file_page_ages","get_stale_pages","get_top_entry_points","init_db",diff --git a/packages/core/src/repowise/core/persistence/crud/pages.py b/packages/core/src/repowise/core/persistence/crud/pages.pyindex 8a60a1e4c..5f157a910 100644--- a/packages/core/src/repowise/core/persistence/crud/pages.py+++ b/packages/core/src/repowise/core/persistence/crud/pages.py@@ -7,7 +7,7 @@ every public name, so existing imports are unaffected.from __future__ import annotationsimport json-from datetime import datetime+from datetime import UTC, datetimefrom typing import Anyfrom sqlalchemy import select@@ -659,3 +659,45 @@ async def get_stale_pages())return list(result.scalars().all())+++async def get_stale_file_page_ages(+ session: AsyncSession,+ repository_id: str,+) -> dict[str, float]:+ """``{file_path: staleness_age_seconds}`` for stale/expired file pages.++ The cascade-budget ordering in+ :meth:`~repowise.core.ingestion.change_detector.ChangeDetector.get_affected_pages`+ consumes this so a constrained regeneration run bubbles the *oldest* stale+ pages to the top rather than reordering purely by importance (issues #847 /+ #851). Staleness age is measured from ``updated_at`` — the last time the+ page was regenerated — so the page whose prose lagged the code longest+ carries the largest value.++ Only ``file_page`` rows are returned: the cascade reaches file paths, and+ the module / SCC / repo-wide containers are derived from the selected files+ rather than selected themselves. Returns an empty dict when nothing is+ stale (or the repository has no file pages), which keeps the pure-importance+ ordering.+ """+ result = await session.execute(+ select(Page.id, Page.target_path, Page.updated_at).where(+ Page.repository_id == repository_id,+ Page.page_type == "file_page",+ Page.freshness_status.in_(["stale", "expired"]),+ )+ )+ now = datetime.now(UTC)+ ages: dict[str, float] = {}+ for _pid, target_path, updated_at in result:+ if not target_path:+ continue+ if updated_at is None:+ ages[target_path] = float("inf")+ continue+ dt = updated_at+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=UTC)+ ages[target_path] = max(0.0, (now - dt).total_seconds())+ return agesdiff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.pyindex a277e70f6..0344a05db 100644--- a/packages/server/src/repowise/server/job_executor.py+++ b/packages/server/src/repowise/server/job_executor.py@@ -495,6 +495,8 @@ async def execute_job(repo_wiki_style=wiki_style,vector_store=vector_store,prior_pages=prior_pages,+ session_factory=session_factory,+ repo_id=repo_id,)# ---- Persist results -----------------------------------------------@@ -1161,6 +1163,8 @@ async def _incremental_page_regen(*,vector_store: Any | None = None,prior_pages: dict[str, Any] | None = None,+ session_factory: Any | None = None,+ repo_id: str | None = None,) -> list:"""Regenerate only wiki pages affected by recent changes.@@ -1210,11 +1214,30 @@ async def _incremental_page_regen(return []cascade_budget = compute_adaptive_budget(file_diffs, result.file_count)++ # Feed existing stale-page ages into the cascade so a constrained+ # budget spends its LLM calls on the oldest stale pages rather than+ # reordering purely by importance (issues #847 / #851). Best effort:+ # a missing session/repo just falls back to the historical ordering.+ stale_pages: dict[str, float] = {}+ if session_factory is not None and repo_id is not None:+ try:+ from repowise.core.persistence import (+ get_session,+ get_stale_file_page_ages,+ )++ async with get_session(session_factory) as session:+ stale_pages = await get_stale_file_page_ages(session, repo_id)+ except Exception as exc: # pragma: no cover - defensive+ logger.warning("incremental_page_regen_stale_lookup_failed", error=str(exc))+affected = detector.get_affected_pages(file_diffs,result.graph_builder.graph(),cascade_budget,pagerank=result.graph_builder.pagerank(),+ stale_pages=stale_pages,)if not affected.regenerate:diff --git a/tests/unit/ingestion/test_change_detector.py b/tests/unit/ingestion/test_change_detector.pyindex 56bb00454..55b896c69 100644--- a/tests/unit/ingestion/test_change_detector.py+++ b/tests/unit/ingestion/test_change_detector.py@@ -357,3 +357,93 @@ class TestAffectedPagesPagerankParam:assert set(result.regenerate) | set(result.decay_only) == {f"f{i}.py" for i in range(6)}+++class TestAffectedPagesStalenessPriority:+ """A constrained cascade budget must spend its LLM calls on the oldest stale+ pages first, not merely the highest-importance pages (issues #847 / #851).++ Historically the budget slice was ordered purely by pagerank (importance),+ so a run could regenerate pages that were already current while leaving+ genuinely stale prose untouched. Staleness is the more useful tiebreak for+ an update: an already-stale page outranks a fresh page no matter how+ central the fresh one is.+ """++ def _diff(self, path: str):+ from repowise.core.ingestion.change_detector import FileDiff++ return FileDiff(+ path=path,+ status="modified",+ old_path=None,+ old_parsed=None,+ new_parsed=_parsed([], path=path),+ symbol_diff=None,+ )++ def test_stale_pages_bubble_above_fresh_importance(self, tmp_path: Path) -> None:+ """A stale page is regenerated ahead of a more important but fresh one."""+ d = ChangeDetector(tmp_path)+ g = nx.DiGraph()+ g.add_node("authority.py")+ g.add_node("legacy.py")+ g.add_node("trigger.py")+ # Both authority.py and legacy.py are directly changed (import trigger);+ # authority.py is the far more central file.+ g.add_edge("authority.py", "trigger.py")+ g.add_edge("legacy.py", "trigger.py")++ pr = {"authority.py": 0.95, "legacy.py": 0.1, "trigger.py": 0.2}+ # legacy.py is stale (old prose), authority.py is fresh.+ stale_pages = {"legacy.py": 3600.0}++ diffs = [self._diff("authority.py"), self._diff("legacy.py"), self._diff("trigger.py")]+ result = d.get_affected_pages(+ diffs, graph=g, cascade_budget=1, pagerank=pr, stale_pages=stale_pages+ )+ # The stale page is regenerated even though it is far less important.+ assert result.regenerate == ["legacy.py"]+ assert "authority.py" in result.decay_only++ def test_oldest_stale_first_within_budget(self, tmp_path: Path) -> None:+ """Among stale pages, the oldest stale page regenerates before a newer one."""+ d = ChangeDetector(tmp_path)+ g = nx.DiGraph()+ g.add_node("old_stale.py")+ g.add_node("new_stale.py")+ g.add_node("trigger.py")+ g.add_edge("old_stale.py", "trigger.py")+ g.add_edge("new_stale.py", "trigger.py")++ pr = {"old_stale.py": 0.1, "new_stale.py": 0.9, "trigger.py": 0.2}+ # Both stale, but old_stale has the larger age (older prose).+ stale_pages = {"old_stale.py": 86400.0, "new_stale.py": 3600.0}++ result = d.get_affected_pages(+ [self._diff("old_stale.py"), self._diff("new_stale.py"), self._diff("trigger.py")],+ graph=g,+ cascade_budget=1,+ pagerank=pr,+ stale_pages=stale_pages,+ )+ assert result.regenerate[0] == "old_stale.py"++ def test_absent_stale_pages_keeps_importance_order(self, tmp_path: Path) -> None:+ """No stale_pages passed -> historical pure-importance ordering holds."""+ d = ChangeDetector(tmp_path)+ g = nx.DiGraph()+ g.add_node("a.py")+ g.add_node("b.py")+ g.add_node("trigger.py")+ g.add_edge("a.py", "trigger.py")+ g.add_edge("b.py", "trigger.py")++ pr = {"a.py": 0.8, "b.py": 0.3, "trigger.py": 0.2}+ result = d.get_affected_pages(+ [self._diff("a.py"), self._diff("b.py"), self._diff("trigger.py")],+ graph=g,+ cascade_budget=1,+ pagerank=pr,+ )+ assert result.regenerate[0] == "a.py"diff --git a/tests/unit/persistence/test_stale_file_page_ages.py b/tests/unit/persistence/test_stale_file_page_ages.pynew file mode 100644index 000000000..111b66093--- /dev/null+++ b/tests/unit/persistence/test_stale_file_page_ages.py@@ -0,0 +1,128 @@+"""``get_stale_file_page_ages`` maps stale/expired file pages to their age.++The cascade-budget ordering in ChangeDetector.get_affected_pages consumes this+so a constrained docs run bubbles the oldest stale pages to the top instead of+reordering purely by importance (issues #847 / #851). These tests pin the+contract: which rows count, what "age" means, and what comes back when nothing+is stale.+"""++from __future__ import annotations++import pytest+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine+from sqlalchemy.pool import StaticPool++from repowise.core.persistence.crud import (+ get_stale_file_page_ages,+ upsert_page,+ upsert_repository,+)+from repowise.core.persistence.database import init_db+++async def engine():+ eng = create_async_engine(+ "sqlite+aiosqlite:///:memory:",+ connect_args={"check_same_thread": False},+ poolclass=StaticPool,+ )+ await init_db(eng)+ yield eng+ await eng.dispose()+++async def session(engine):+ factory = async_sessionmaker(engine, expire_on_commit=False)+ async with factory() as sess:+ yield sess+++async def _seed(session, *paths: str) -> str:+ """One file page per path (fresh unless noted). Returns the repo id."""+ repo = await upsert_repository(session, name="r", local_path="/tmp/r")+ await session.commit()+ for path in paths:+ await upsert_page(+ session,+ page_id=f"file_page:{path}",+ repository_id=repo.id,+ page_type="file_page",+ title=f"File: {path}",+ content=f"# Overview\n\nWhat {path} does.",+ summary=f"What {path} does.",+ target_path=path,+ source_hash=f"hash:{path}",+ model_name="test",+ provider_name="template",+ )+ await session.commit()+ return repo.id+++async def _seed_stale(session, repo_id: str, path: str) -> None:+ """Re-upsert one page as stale/expired so its row is a stale file page."""+ await upsert_page(+ session,+ page_id=f"file_page:{path}",+ repository_id=repo_id,+ page_type="file_page",+ title=f"File: {path}",+ content=f"# Overview\n\nWhat {path} does.",+ summary=f"What {path} does.",+ target_path=path,+ source_hash=f"hash:{path}",+ model_name="test",+ provider_name="provider",+ freshness_status="stale",+ )+ await session.commit()+++async def test_empty_when_nothing_stale(session) -> None:+ repo_id = await _seed(session, "a.py")+ ages = await get_stale_file_page_ages(session, repo_id)+ assert ages == {}+++async def test_stale_file_pages_are_returned(session) -> None:+ repo_id = await _seed(session, "a.py", "b.py")+ await _seed_stale(session, repo_id, "b.py")+ ages = await get_stale_file_page_ages(session, repo_id)+ assert "b.py" in ages+ assert "a.py" not in ages # fresh page is excluded+ assert ages["b.py"] >= 0.0+++async def test_non_file_pages_are_ignored(session) -> None:+ repo = await upsert_repository(session, name="r2", local_path="/tmp/r2")+ await session.commit()+ # A stale non-file page (module_page) must not appear in the file-path map.+ await upsert_page(+ session,+ page_id="module_page:core",+ repository_id=repo.id,+ page_type="module_page",+ title="Core",+ content="body",+ summary="sum",+ target_path="core",+ source_hash="h",+ model_name="m",+ provider_name="p",+ freshness_status="stale",+ )+ await session.commit()+ ages = await get_stale_file_page_ages(session, repo.id)+ assert ages == {}+++async def test_other_repository_is_isolated(session) -> None:+ repo_id = await _seed(session, "a.py")+ await _seed_stale(session, repo_id, "a.py")+ other = await upsert_repository(session, name="other", local_path="/tmp/other")+ await session.commit()+ ages = await get_stale_file_page_ages(session, other.id)+ assert ages == {}