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(generation): overlap knowledge-graph enrichment with page generation (#912)

Raghav Chamadiyaf64054ebe78b
diff --git a/packages/core/src/repowise/core/generation/knowledge_graph.py b/packages/core/src/repowise/core/generation/knowledge_graph.py
index e42386ed4..27d6a0f77 100644
--- a/packages/core/src/repowise/core/generation/knowledge_graph.py
+++ b/packages/core/src/repowise/core/generation/knowledge_graph.py
@@ -52,7 +52,40 @@ async def enrich_knowledge_graph(
progress: Any | None = None,
reasoning: str = "auto",
) -> Any:
- """Enrich deterministic KG with LLM-generated layer names and tour."""
+ """Enrich deterministic KG with LLM-generated layer names and tour.
+
+ Thin serial wrapper: runs the page-independent structural enrichment
+ (layer naming + tour), then the page-dependent finalize (summary backfill,
+ floor, review). The init orchestrator drives the two halves separately so
+ the structural half overlaps page generation; other callers (update path,
+ init CLI) keep this simple serial entry point.
+ """
+ enriched_layers, tour = await enrich_knowledge_graph_structural(
+ kg_skeleton,
+ llm_client,
+ graph_builder,
+ repo_structure,
+ tech_stack,
+ reasoning=reasoning,
+ )
+ return finalize_knowledge_graph(kg_skeleton, enriched_layers, tour, generated_pages)
+
+
+async def enrich_knowledge_graph_structural(
+ kg_skeleton: Any,
+ llm_client: Any,
+ graph_builder: Any,
+ repo_structure: Any,
+ tech_stack: list[dict],
+ reasoning: str = "auto",
+) -> tuple[list[dict], list[dict]]:
+ """Page-independent KG enrichment: LLM layer naming + guided tour.
+
+ Reads only the skeleton, warmed graph metrics, and tech stack — never the
+ generated wiki pages — so it is safe to run concurrently with page
+ generation. Returns ``(enriched_layers, tour)``; the caller applies them to
+ the skeleton via :func:`finalize_knowledge_graph` once pages are ready.
+ """
enriched_layers = await _enrich_layers(
kg_skeleton.layers, llm_client, graph_builder, repo_structure, tech_stack,
reasoning=reasoning,
@@ -72,6 +105,21 @@ async def enrich_knowledge_graph(
reasoning=reasoning,
)
+ return enriched_layers, tour
+
+
+def finalize_knowledge_graph(
+ kg_skeleton: Any,
+ enriched_layers: list[dict],
+ tour: list[dict],
+ generated_pages: list[Any] | None = None,
+) -> Any:
+ """Apply structural enrichment + page-derived summaries to the skeleton.
+
+ Runs after both structural enrichment and page generation complete. Order
+ matches the original serial path: page backfill, then the deterministic
+ summary floor, then the layer/tour assignment, then the review gate.
+ """
if generated_pages:
_backfill_summaries(kg_skeleton, generated_pages)
@@ -79,6 +127,8 @@ async def enrich_knowledge_graph(
# page summaries always win and only never-paged files fall back. Gated by
# the curation flag (the seam already floored FAST-mode output; this covers
# the generate-mode path where the seam deferred to let backfill run first).
+ from repowise.core.analysis.kg_curation import curation_enabled
+
if curation_enabled():
from repowise.core.analysis.kg_curation import apply_summary_floor
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.py
index f04891eab..33c3c956c 100644
--- a/packages/core/src/repowise/core/pipeline/orchestrator.py
+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py
@@ -15,6 +15,7 @@ Callers:
from __future__ import annotations
import asyncio
+import contextlib
import time
from dataclasses import dataclass, field
from pathlib import Path
@@ -563,7 +564,7 @@ async def run_pipeline(
try:
# In generate mode the summary floor is deferred to run after
- # the wiki-page backfill (in ``enrich_knowledge_graph``), so
+ # the wiki-page backfill (in ``finalize_knowledge_graph``), so
# rich page summaries win; FAST mode floors here.
will_generate = generate_docs and llm_client is not None
knowledge_graph_result = curate_knowledge_graph(
@@ -635,37 +636,84 @@ async def run_pipeline(
except Exception as _api_err:
logger.warning("api_contract_detection_failed", error=str(_api_err))
- generated_pages = await run_generation(
- repo_path=repo_path,
- parsed_files=parsed_files,
- source_map=source_map,
- graph_builder=graph_builder,
- repo_structure=repo_structure,
- git_meta_map=git_meta_map,
- llm_client=llm_client,
- embedder=embedder,
- vector_store=vector_store,
- concurrency=concurrency,
- progress=progress,
- resume=resume,
- generation_config=resolved_generation_config,
- dead_code_report=gen_dead_code_report,
- decision_report=gen_decision_report,
- external_systems=external_systems,
- on_page_ready=on_page_ready,
- # In-memory KG — the artifact file is written after generation,
- # so it cannot carry layers/tour/modules on a fresh init.
- kg_modules=(
- knowledge_graph_result.modules or None
- if knowledge_graph_result is not None
- else None
- ),
- kg_data=(
- knowledge_graph_result.to_dict()
- if knowledge_graph_result is not None
- else None
- ),
- )
+ # Launch the page-independent half of KG enrichment (LLM layer naming +
+ # tour) so it overlaps page generation instead of running strictly
+ # after it. The two do not read each other's live output: run_generation
+ # receives a to_dict() snapshot of the skeleton (kg_data/kg_modules
+ # below), and structural enrichment reads only the skeleton layers plus
+ # the warmed graph metrics. Layer/tour results are applied to the
+ # skeleton only in finalize_knowledge_graph (after generation), so the
+ # in-place layer-name mutation inside enrichment can never reach the
+ # snapshot generation is already holding. The page-dependent finalize
+ # (summary backfill) runs after both complete.
+ kg_structural_task = None
+ if knowledge_graph_result is not None:
+ from repowise.core.generation.knowledge_graph import (
+ enrich_knowledge_graph_structural,
+ )
+
+ _kg_reasoning = (
+ getattr(resolved_generation_config, "reasoning", "auto")
+ if resolved_generation_config
+ else "auto"
+ )
+ # Warm the pagerank cache on this thread before the concurrent
+ # launch so both the structural task and generation only ever read
+ # it. It is already populated during ingestion; this makes the
+ # no-race invariant explicit rather than incidental.
+ graph_builder.pagerank()
+ kg_structural_task = asyncio.create_task(
+ enrich_knowledge_graph_structural(
+ kg_skeleton=knowledge_graph_result,
+ llm_client=llm_client,
+ graph_builder=graph_builder,
+ repo_structure=repo_structure,
+ tech_stack=tech_stack_dicts,
+ reasoning=_kg_reasoning,
+ )
+ )
+
+ try:
+ generated_pages = await run_generation(
+ repo_path=repo_path,
+ parsed_files=parsed_files,
+ source_map=source_map,
+ graph_builder=graph_builder,
+ repo_structure=repo_structure,
+ git_meta_map=git_meta_map,
+ llm_client=llm_client,
+ embedder=embedder,
+ vector_store=vector_store,
+ concurrency=concurrency,
+ progress=progress,
+ resume=resume,
+ generation_config=resolved_generation_config,
+ dead_code_report=gen_dead_code_report,
+ decision_report=gen_decision_report,
+ external_systems=external_systems,
+ on_page_ready=on_page_ready,
+ # In-memory KG — the artifact file is written after generation,
+ # so it cannot carry layers/tour/modules on a fresh init.
+ kg_modules=(
+ knowledge_graph_result.modules or None
+ if knowledge_graph_result is not None
+ else None
+ ),
+ kg_data=(
+ knowledge_graph_result.to_dict()
+ if knowledge_graph_result is not None
+ else None
+ ),
+ )
+ except BaseException:
+ # Generation aborted the run: cancel the concurrent enrichment task
+ # so it stops issuing LLM calls and never surfaces as a stray
+ # "Task exception was never retrieved" during teardown.
+ if kg_structural_task is not None:
+ kg_structural_task.cancel()
+ with contextlib.suppress(BaseException):
+ await kg_structural_task
+ raise
# Record which structural page types this run authoritatively decided,
# so the sweep can retire prior rows of a type even when this run
@@ -686,37 +734,33 @@ async def run_pipeline(
if kg_layers_present:
authoritative_page_types.add("layer_page")
- # ---- Knowledge Graph LLM enrichment (layer naming + tour) -----------------
- if knowledge_graph_result is not None and generate_docs and llm_client is not None:
- try:
- from repowise.core.generation.knowledge_graph import enrich_knowledge_graph
+ # ---- Knowledge Graph enrichment: join + finalize ----------------------
+ # The structural half (layer naming + tour) ran concurrently with
+ # generation above; join it now and apply the page-derived summary
+ # backfill. Same try/except envelope as before: a KG failure logs and
+ # leaves the skeleton in place, never aborting the run.
+ if kg_structural_task is not None:
+ from repowise.core.generation.knowledge_graph import finalize_knowledge_graph
if progress:
progress.on_phase_start("knowledge_graph.enrich", None)
- _kg_reasoning = (
- getattr(resolved_generation_config, "reasoning", "auto")
- if resolved_generation_config
- else "auto"
- )
- knowledge_graph_result = await enrich_knowledge_graph(
- kg_skeleton=knowledge_graph_result,
- llm_client=llm_client,
- graph_builder=graph_builder,
- repo_structure=repo_structure,
- tech_stack=tech_stack_dicts,
- generated_pages=generated_pages,
- progress=progress,
- reasoning=_kg_reasoning,
- )
- if progress:
- progress.on_message(
- "info",
- f" ↳ KG enriched: {len(knowledge_graph_result.layers)} layers, "
- f"{len(knowledge_graph_result.tour)} tour steps",
+ try:
+ enriched_layers, tour = await kg_structural_task
+ knowledge_graph_result = finalize_knowledge_graph(
+ kg_skeleton=knowledge_graph_result,
+ enriched_layers=enriched_layers,
+ tour=tour,
+ generated_pages=generated_pages,
)
- _phase_done(progress, "knowledge_graph.enrich")
- except (ValueError, KeyError, OSError, RuntimeError) as exc:
- logger.error("knowledge_graph_enrichment_failed", error=str(exc), exc_info=True)
+ if progress:
+ progress.on_message(
+ "info",
+ f" ↳ KG enriched: {len(knowledge_graph_result.layers)} layers, "
+ f"{len(knowledge_graph_result.tour)} tour steps",
+ )
+ _phase_done(progress, "knowledge_graph.enrich")
+ except (ValueError, KeyError, OSError, RuntimeError) as exc:
+ logger.error("knowledge_graph_enrichment_failed", error=str(exc), exc_info=True)
# ---- Execution flow tracing -----------------------------------------------
execution_flow_report = None
diff --git a/tests/unit/generation/test_knowledge_graph_enrichment.py b/tests/unit/generation/test_knowledge_graph_enrichment.py
index 64e6cecea..d5294f037 100644
--- a/tests/unit/generation/test_knowledge_graph_enrichment.py
+++ b/tests/unit/generation/test_knowledge_graph_enrichment.py
@@ -8,11 +8,14 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
+from repowise.core.analysis.knowledge_graph import KnowledgeGraphResult
from repowise.core.generation.knowledge_graph import (
_backfill_summaries,
_parse_json_response,
build_deterministic_tour,
enrich_knowledge_graph,
+ enrich_knowledge_graph_structural,
+ finalize_knowledge_graph,
)
# ---------------------------------------------------------------------------
@@ -343,3 +346,102 @@ class TestParseJsonResponse:
def test_empty_string(self):
result = _parse_json_response("")
assert result is None
+
+
+# ---------------------------------------------------------------------------
+# Structural / finalize split (the init overlap seam)
+# ---------------------------------------------------------------------------
+
+
+class TestEnrichmentSplit:
+ """The orchestrator runs the page-independent half (layer naming + tour)
+ concurrently with page generation, then finalizes with the pages. These
+ pin that the split is behavior-preserving vs the serial wrapper and that
+ the structural half never depends on generated pages."""
+
+ @pytest.mark.asyncio
+ async def test_structural_returns_layers_and_tour_without_pages(self):
+ llm = _make_llm_client(
+ '{"layers": [{"id": "layer:core", "name": "Core Pipeline", "description": "d"}], '
+ '"tour": [{"order": 1, "title": "Start", "description": "s", "files": ["src/main.py"]}]}'
+ )
+ skeleton = _make_kg_skeleton()
+ builder = _make_graph_builder({"src/core.py": 0.5, "src/main.py": 0.3})
+ repo = _make_repo_structure()
+
+ enriched_layers, tour = await enrich_knowledge_graph_structural(
+ skeleton, llm, builder, repo, []
+ )
+ # Layer naming applied…
+ assert enriched_layers[0]["name"] == "Core Pipeline"
+ # …tour produced…
+ assert tour and tour[0]["title"] == "Start"
+ # …but the structural half has no pages, so no summary was backfilled
+ # and it did not assign layers/tour onto the skeleton (finalize's job).
+ assert all(n["summary"] == "" for n in skeleton.nodes)
+
+ def test_finalize_backfills_assigns_and_returns_skeleton(self):
+ skeleton = _make_kg_skeleton()
+ enriched_layers = [{"id": "layer:core", "name": "Renamed", "description": "d", "nodeIds": []}]
+ tour = [{"order": 1, "title": "T", "description": "", "nodeIds": []}]
+ pages = [SimpleNamespace(target_path="src/core.py", summary="Core logic")]
+
+ result = finalize_knowledge_graph(skeleton, enriched_layers, tour, pages)
+
+ assert result is skeleton
+ assert result.layers == enriched_layers
+ assert result.tour == tour
+ core = next(n for n in result.nodes if n["filePath"] == "src/core.py")
+ assert core["summary"] == "Core logic"
+
+ @pytest.mark.asyncio
+ async def test_split_matches_serial_wrapper(self):
+ # Equivalence: structural + finalize must produce the same skeleton the
+ # single-call wrapper does, given identical (deterministic) LLM output.
+ response = (
+ '{"layers": [{"id": "layer:core", "name": "Core Pipeline", "description": "d"}, '
+ '{"id": "layer:cli", "name": "CLI", "description": "c"}], '
+ '"tour": [{"order": 1, "title": "Start", "description": "s", "files": ["src/main.py"]}]}'
+ )
+ pages = [SimpleNamespace(target_path="src/core.py", summary="Core logic")]
+ builder = _make_graph_builder({"src/core.py": 0.5, "src/main.py": 0.3})
+ repo = _make_repo_structure()
+
+ wrapper_skel = _make_kg_skeleton()
+ wrapped = await enrich_knowledge_graph(
+ wrapper_skel, _make_llm_client(response), builder, repo, [], pages
+ )
+
+ split_skel = _make_kg_skeleton()
+ layers, tour = await enrich_knowledge_graph_structural(
+ split_skel, _make_llm_client(response), builder, repo, []
+ )
+ split = finalize_knowledge_graph(split_skel, layers, tour, pages)
+
+ assert split.layers == wrapped.layers
+ assert split.tour == wrapped.tour
+ assert [n["summary"] for n in split.nodes] == [n["summary"] for n in wrapped.nodes]
+
+ @pytest.mark.asyncio
+ async def test_generation_snapshot_insulated_from_concurrent_layer_naming(self):
+ # The orchestrator hands generation a to_dict() snapshot of the skeleton
+ # and lets structural enrichment run concurrently. Enrichment renames
+ # layers in place, so the snapshot generation holds must be a copy that
+ # a later rename cannot mutate.
+ result = KnowledgeGraphResult(
+ layers=[{"id": "layer:core", "name": "heuristic-core", "description": "", "nodeIds": ["file:src/core.py"]}],
+ nodes=[{"id": "file:src/core.py", "type": "file", "filePath": "src/core.py", "summary": ""}],
+ )
+ snapshot = result.to_dict()
+
+ llm = _make_llm_client(
+ '{"layers": [{"id": "layer:core", "name": "Renamed Core", "description": "d"}]}'
+ )
+ await enrich_knowledge_graph_structural(
+ result, llm, _make_graph_builder({"src/core.py": 0.5}), _make_repo_structure(), []
+ )
+
+ # In-place rename landed on the live skeleton…
+ assert result.layers[0]["name"] == "Renamed Core"
+ # …but the snapshot generation already holds is untouched.
+ assert snapshot["layers"][0]["name"] == "heuristic-core"