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
perf(generation): buffer job checkpoint writes behind a bounded atomic flush (#2053)
Raghav Chamadiya8fa62ce78e4f
diff --git a/packages/core/src/repowise/core/generation/job_system.py b/packages/core/src/repowise/core/generation/job_system.pyindex 1e45702af..6b36d022f 100644--- a/packages/core/src/repowise/core/generation/job_system.py+++ b/packages/core/src/repowise/core/generation/job_system.py@@ -3,7 +3,25 @@JobSystem manages long-running generation jobs via JSON checkpoint files.Each job maps to a single {job_id}.json file in the configured jobs_dir.The checkpoint records progress (completed/failed pages), current level, and-job status so generation can be resumed after interruption.+job status.++Durability contract+-------------------+A job's state lives in memory and is flushed to disk atomically. Page+completions are flushed on a bound (``_FLUSH_EVERY_PAGES``), at each level+boundary, and whenever a run ends or is interrupted; everything else is+flushed as it happens. So an unclean kill can lose at most the last+``_FLUSH_EVERY_PAGES`` entries of ``completed_page_ids``.++That window is safe because *nothing reads this field to decide what to+generate*. A resumed run derives its skip set from the vector store (see+``_GenerationRun._seed_resume``), never from this file, so a lost entry+cannot make a resume skip a page or regenerate one it should have kept.+``failed_page_ids`` and every status transition are flushed immediately,+because the post-run failure report reads them back off disk.++Writes go through ``atomic_write_text``: a reader now never sees the+truncated file a crash used to be able to leave behind mid-write.Phase 4 will replace this with a full SQLAlchemy-backed job table."""@@ -20,8 +38,15 @@ from typing import Any, Literalimport structlog+from repowise.core.fsutils import atomic_write_text+log = structlog.get_logger(__name__)+# Page completions buffered before a flush. Bounds both the write amplification+# (one whole-file rewrite per page rebuilt a list that grows by one each time)+# and the state a kill can lose.+_FLUSH_EVERY_PAGES = 128+JobStatus = Literal["pending", "running", "completed", "failed", "paused"]@@ -76,6 +101,21 @@ class Checkpoint:)+@dataclass+class _LiveJob:+ """A job's in-memory state between flushes.++ ``completed`` indexes ``checkpoint.completed_page_ids`` for membership.+ The list stays the on-disk shape and keeps completion order; scanning it+ per page was quadratic in the page count on its own, separately from the+ I/O.+ """++ checkpoint: Checkpoint+ completed: set[str]+ unflushed: int = 0++# ---------------------------------------------------------------------------# JobSystem# ---------------------------------------------------------------------------@@ -92,6 +132,7 @@ class JobSystem:def __init__(self, jobs_dir: Path) -> None:self._jobs_dir = jobs_dirjobs_dir.mkdir(parents=True, exist_ok=True)+ self._live: dict[str, _LiveJob] = {}# ------------------------------------------------------------------# Job lifecycle@@ -115,6 +156,12 @@ class JobSystem:except TypeError:config_dict = {}+ # Normalise to the JSON shapes (tuples become lists) up front. The+ # snapshot used to acquire them by way of the disk round-trip every+ # read did; now that a reader can be served from memory, doing it here+ # is what keeps both answers the same.+ config_dict = json.loads(json.dumps(config_dict))+now = _now_iso()checkpoint = Checkpoint(job_id=job_id,@@ -144,17 +191,30 @@ class JobSystem:self._save(cp)def complete_page(self, job_id: str, page_id: str) -> None:- """Record a successfully generated page."""- cp = self._load(job_id)- if page_id not in cp.completed_page_ids:+ """Record a successfully generated page.++ Buffered: this is the one per-page write, and it is the field no+ reader consults to decide what to generate. See the module docstring+ for the window this leaves.+ """+ live = self._job(job_id)+ cp = live.checkpoint+ if page_id not in live.completed:+ live.completed.add(page_id)cp.completed_page_ids.append(page_id)cp.completed_pages = len(cp.completed_page_ids)cp.total_pages = max(cp.total_pages, cp.completed_pages)+ live.unflushed += 1cp.updated_at = _now_iso()- self._save(cp)+ if live.unflushed >= _FLUSH_EVERY_PAGES:+ self._flush(live)def fail_page(self, job_id: str, page_id: str, error: str) -> None:- """Record a failed page (job stays running)."""+ """Record a failed page (job stays running).++ Flushed immediately, unlike a completion: failures are rare, and the+ CLI reads this field back off disk to report them after the run.+ """cp = self._load(job_id)if page_id not in cp.failed_page_ids:cp.failed_page_ids.append(page_id)@@ -205,7 +265,14 @@ class JobSystem:return set(self._load(job_id).completed_page_ids)def list_jobs(self) -> list[Checkpoint]:- """Return all jobs sorted by created_at descending."""+ """Return all jobs sorted by created_at descending.++ Flushes first: this reads the directory rather than the live state, so+ without it the listing would report the one job this instance is+ writing as behind by up to a flush bound.+ """+ for job_id in list(self._live):+ self.flush(job_id)checkpoints: list[Checkpoint] = []for json_path in self._jobs_dir.glob("*.json"):try:@@ -220,20 +287,58 @@ class JobSystem:# Internals# ------------------------------------------------------------------- def _load(self, job_id: str) -> Checkpoint:+ def _job(self, job_id: str) -> _LiveJob:+ """This instance's live state for *job_id*, read from disk once.++ A second JobSystem over the same directory (the CLI opens one to read+ the failure report back) still sees a current file, because every+ write this one buffers is flushed by the time a run ends.+ """+ live = self._live.get(job_id)+ if live is None:+ checkpoint = self._read(job_id)+ live = _LiveJob(checkpoint, set(checkpoint.completed_page_ids))+ self._live[job_id] = live+ return live++ def _read(self, job_id: str) -> Checkpoint:path = self._jobs_dir / f"{job_id}.json"if not path.exists():raise FileNotFoundError(f"Job checkpoint not found: {job_id}")data = json.loads(path.read_text(encoding="utf-8"))return Checkpoint.from_dict(data)- def _save(self, checkpoint: Checkpoint) -> None:- checkpoint.updated_at = _now_iso()+ def _load(self, job_id: str) -> Checkpoint:+ """The current checkpoint, buffered writes included."""+ return self._job(job_id).checkpoint++ def _flush(self, live: _LiveJob) -> None:+ checkpoint = live.checkpointpath = self._jobs_dir / f"{checkpoint.job_id}.json"- path.write_text(+ atomic_write_text(+ path,json.dumps(dataclasses.asdict(checkpoint), indent=2),- encoding="utf-8",)+ live.unflushed = 0++ def _save(self, checkpoint: Checkpoint) -> None:+ """Stamp and flush *checkpoint* now. For everything but page counts."""+ checkpoint.updated_at = _now_iso()+ live = self._live.get(checkpoint.job_id)+ if live is None:+ live = _LiveJob(checkpoint, set(checkpoint.completed_page_ids))+ self._live[checkpoint.job_id] = live+ self._flush(live)++ def flush(self, job_id: str) -> None:+ """Make this job's buffered page completions durable.++ Called at every level boundary and on interruption, so the window a+ kill can lose is one level rather than a whole run.+ """+ live = self._live.get(job_id)+ if live is not None and live.unflushed:+ self._flush(live)def _transition(self,diff --git a/packages/core/src/repowise/core/generation/page_generator/core.py b/packages/core/src/repowise/core/generation/page_generator/core.pyindex 0f273d73f..251def6e2 100644--- a/packages/core/src/repowise/core/generation/page_generator/core.py+++ b/packages/core/src/repowise/core/generation/page_generator/core.py@@ -248,6 +248,7 @@ class PageGenerator(PerTypeGenerationMixin, StructuralRenderMixin):kg_data: dict | None = None,only_page_ids: set[str] | None = None,preserved_page_ids: set[str] | None = None,+ timings: Any | None = None,) -> list[GeneratedPage]:"""Generate all wiki pages for a repository.@@ -268,6 +269,10 @@ class PageGenerator(PerTypeGenerationMixin, StructuralRenderMixin):caller hands the set to persistence, which must not sweep those ids asstale. Harmless to pass on a non-resume run (nothing is skipped for thatreason, so nothing is added); None when the caller has no use for it.++ ``timings`` is the run's shared ``PhaseTimings`` table. Generation+ records its per-level and checkpoint spans into it so they report+ beside the top-level phases; None disables those spans."""from .orchestrate import run_generate_all@@ -302,6 +307,7 @@ class PageGenerator(PerTypeGenerationMixin, StructuralRenderMixin):kg_data=kg_data,only_page_ids=only_page_ids,preserved_page_ids=preserved_page_ids,+ timings=timings,)# ------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py b/packages/core/src/repowise/core/generation/page_generator/orchestrate.pyindex a5896d79f..384b6088b 100644--- a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py+++ b/packages/core/src/repowise/core/generation/page_generator/orchestrate.py@@ -20,6 +20,7 @@ from typing import TYPE_CHECKING, Anyimport structlogfrom ...persistence.vector_store import embed_item+from ...pipeline.phase_timing import timedfrom ..context_assembler import FilePageContextfrom ..models import (STRUCTURALLY_KEYED_PAGE_TYPES,@@ -108,6 +109,7 @@ class _GenerationRun:kg_data: dict | None = None,only_page_ids: set[str] | None = None,preserved_page_ids: set[str] | None = None,+ timings: Any | None = None,) -> None:self.gen = genself.config = gen._config@@ -187,6 +189,10 @@ class _GenerationRun:self.kg_ctx = KnowledgeGraphContext(kg_path)# ---- Run bookkeeping ----+ # Shared PhaseTimings table, or None outside a timed run. Generation is+ # one opaque phase without it, and its levels differ by orders of+ # magnitude in cost, so a regression in one hides inside the total.+ self.timings = timingsself.semaphore = asyncio.Semaphore(self.config.max_concurrency)self.completed_page_summaries: dict[str, str] = {}self.completed_ids: set[str] = set()@@ -610,137 +616,160 @@ class _GenerationRun:self, named_coros: list[tuple[str, Any]], level: int) -> list[GeneratedPage]:"""Run one level's coroutines under the shared semaphore + embed batch."""- if self.job_system is not None and self.job_id is not None:- self.job_system.update_level(self.job_id, level)-- # Pages finished during this level, collected for a single batched- # embed at the end. Embedding the whole wave in one call amortises the- # embedder round-trip and the level drains before the next level's RAG- # search runs, so there is no freshness regression.- embed_items: list[tuple[str, str, dict]] = []-- async def guarded_named(page_id: str, coro: Any) -> Any:- try:- async with self.semaphore:- result = await coro-- if isinstance(result, GeneratedPage):- # A page whose provider call raised comes back as its- # structural stub rather than being dropped (issue #1089),- # so the row exists and `repowise generate` can refill it.- # It is still a failure: the job checkpoint has to say so,- # or a run that lost half its pages reports a clean sweep.- stub_error = result.metadata.get(STUB_FALLBACK_ERROR)- if (- stub_error is not None- and self.job_system is not None- and self.job_id is not None- ):- self.job_system.fail_page(self.job_id, page_id, stub_error)- # Summary capture is cheap (string ops) — keep inline so- # the next page's context assembly sees it immediately.- self.completed_page_summaries[result.target_path] = overview_summary(- result.content- )- # Progress tick fires the moment the page is ready.- if self.on_page_done is not None:- self.on_page_done(result.page_type)- # Hand the full page to a streaming sink (incremental- # persistence). Best-effort: a sink error must not drop the- # page or abort the level.- if self.on_page_ready is not None:- try:- self.on_page_ready(result)- except Exception as exc:- log.debug("on_page_ready.failed", error=str(exc))- # A page reused verbatim from the prior run already has an- # identical vector in any store that survives across runs;- # re-embedding it re-bills the embedder for every unchanged- # page on every update. Ephemeral stores start empty each- # run and still need it.- #- # A stub standing in for a failed page is held back. Not to- # save the embedding call: ``_seed_resume`` reads the store- # back as the list of pages already done, so embedding the- # stub is what would tell the next ``--resume`` there is- # nothing left to write here. The page is still persisted- # and full-text indexed; only the resume ledger is spared.- if (- self.vector_store is not None- and stub_error is None- and not (- result.metadata.get("reused_from_prior_run")- and getattr(self.vector_store, "persists_across_runs", False)+ try:+ with timed(self.timings, f"generation.level{level}"):+ with timed(self.timings, "generation.checkpoint"):+ if self.job_system is not None and self.job_id is not None:+ self.job_system.update_level(self.job_id, level)++ # Pages finished during this level, collected for a single batched+ # embed at the end. Embedding the whole wave in one call amortises the+ # embedder round-trip and the level drains before the next level's RAG+ # search runs, so there is no freshness regression.+ embed_items: list[tuple[str, str, dict]] = []++ async def guarded_named(page_id: str, coro: Any) -> Any:+ try:+ async with self.semaphore:+ result = await coro++ if isinstance(result, GeneratedPage):+ # A page whose provider call raised comes back as its+ # structural stub rather than being dropped (issue #1089),+ # so the row exists and `repowise generate` can refill it.+ # It is still a failure: the job checkpoint has to say so,+ # or a run that lost half its pages reports a clean sweep.+ stub_error = result.metadata.get(STUB_FALLBACK_ERROR)+ if (+ stub_error is not None+ and self.job_system is not None+ and self.job_id is not None+ ):+ with timed(self.timings, "generation.checkpoint"):+ self.job_system.fail_page(self.job_id, page_id, stub_error)+ # Summary capture is cheap (string ops) — keep inline so+ # the next page's context assembly sees it immediately.+ self.completed_page_summaries[result.target_path] = overview_summary(+ result.content+ )+ # Progress tick fires the moment the page is ready.+ if self.on_page_done is not None:+ self.on_page_done(result.page_type)+ # Hand the full page to a streaming sink (incremental+ # persistence). Best-effort: a sink error must not drop the+ # page or abort the level.+ if self.on_page_ready is not None:+ try:+ self.on_page_ready(result)+ except Exception as exc:+ log.debug("on_page_ready.failed", error=str(exc))+ # A page reused verbatim from the prior run already has an+ # identical vector in any store that survives across runs;+ # re-embedding it re-bills the embedder for every unchanged+ # page on every update. Ephemeral stores start empty each+ # run and still need it.+ #+ # A stub standing in for a failed page is held back. Not to+ # save the embedding call: ``_seed_resume`` reads the store+ # back as the list of pages already done, so embedding the+ # stub is what would tell the next ``--resume`` there is+ # nothing left to write here. The page is still persisted+ # and full-text indexed; only the resume ledger is spared.+ if (+ self.vector_store is not None+ and stub_error is None+ and not (+ result.metadata.get("reused_from_prior_run")+ and getattr(self.vector_store, "persists_across_runs", False)+ )+ ):+ # None below the information floor: the page is kept and+ # still resolves as a link target, it just gets no+ # vector. ``embed_item`` tallies those itself, so the+ # run can report how much it held back instead of+ # leaving the index quietly smaller than the wiki.+ item = _embed_item(result)+ if item is not None:+ embed_items.append(item)+ return result+ except Exception as exc:+ if self.job_system is not None and self.job_id is not None:+ with timed(self.timings, "generation.checkpoint"):+ self.job_system.fail_page(self.job_id, page_id, str(exc))+ log.error(+ "page_generation_failed",+ page_id=page_id,+ level=level,+ error=str(exc),)- ):- # None below the information floor: the page is kept and- # still resolves as a link target, it just gets no- # vector. ``embed_item`` tallies those itself, so the- # run can report how much it held back instead of- # leaving the index quietly smaller than the wiki.- item = _embed_item(result)- if item is not None:- embed_items.append(item)- return result- except Exception as exc:- if self.job_system is not None and self.job_id is not None:- self.job_system.fail_page(self.job_id, page_id, str(exc))- log.error(- "page_generation_failed",- page_id=page_id,- level=level,- error=str(exc),- )- return exc # return as value so gather works- except BaseException:- # Cancellation (Ctrl+C teardown): CancelledError is a- # BaseException, so it skips the handler above. If the cancel- # landed while this page was still queued on the semaphore,- # ``coro`` was never started — close it so interpreter- # shutdown doesn't spray one "coroutine ... was never- # awaited" RuntimeWarning per pending page (issue #358).- # close() is a no-op on a coroutine that already ran.- coro.close()- raise-- tasks = [guarded_named(pid, c) for pid, c in named_coros]- results = await asyncio.gather(*tasks)- # Embed the whole level in one batch before declaring it done — the- # next level's RAG search depends on these landing in the store.- # Embedding is a RAG enhancement, not load-bearing, so a failure must- # not abort generation — but it MUST be visible: a debug-level- # swallow here hid a 300k-token request rejection that silently lost- # every file-page embedding on init (`repowise reindex` repairs).- if embed_items and self.vector_store is not None:- try:- await self.vector_store.embed_batch(embed_items)- except Exception as e:- log.warning(- "rag.embed_batch_failed",- level=level,- count=len(embed_items),- error=str(e),- hint="semantic search will miss these pages; run `repowise reindex` to repair",- )- pages = [r for r in results if isinstance(r, GeneratedPage)]- if self.job_system is not None and self.job_id is not None:- for r in pages:- # Already recorded as failed above. A page cannot be both, and- # "completed" is the half a reader would believe.- if r.metadata.get(STUB_FALLBACK_ERROR) is None:- self.job_system.complete_page(self.job_id, r.page_id)- return pages+ return exc # return as value so gather works+ except BaseException:+ # Cancellation (Ctrl+C teardown): CancelledError is a+ # BaseException, so it skips the handler above. If the cancel+ # landed while this page was still queued on the semaphore,+ # ``coro`` was never started — close it so interpreter+ # shutdown doesn't spray one "coroutine ... was never+ # awaited" RuntimeWarning per pending page (issue #358).+ # close() is a no-op on a coroutine that already ran.+ coro.close()+ raise++ tasks = [guarded_named(pid, c) for pid, c in named_coros]+ results = await asyncio.gather(*tasks)+ # Embed the whole level in one batch before declaring it done — the+ # next level's RAG search depends on these landing in the store.+ # Embedding is a RAG enhancement, not load-bearing, so a failure must+ # not abort generation — but it MUST be visible: a debug-level+ # swallow here hid a 300k-token request rejection that silently lost+ # every file-page embedding on init (`repowise reindex` repairs).+ if embed_items and self.vector_store is not None:+ with timed(self.timings, "generation.embed"):+ try:+ await self.vector_store.embed_batch(embed_items)+ except Exception as e:+ log.warning(+ "rag.embed_batch_failed",+ level=level,+ count=len(embed_items),+ error=str(e),+ hint="semantic search will miss these pages; run `repowise reindex` to repair",+ )+ pages = [r for r in results if isinstance(r, GeneratedPage)]+ with timed(self.timings, "generation.checkpoint"):+ if self.job_system is not None and self.job_id is not None:+ for r in pages:+ # Already recorded as failed above. A page cannot be both,+ # and "completed" is the half a reader would believe.+ if r.metadata.get(STUB_FALLBACK_ERROR) is None:+ self.job_system.complete_page(self.job_id, r.page_id)+ return pages+ finally:+ # Level completion is the durability boundary for page+ # completions, and a cancelled level flushes what it did finish+ # rather than discarding it.+ #+ # Swallowed because this runs in a finally: a raise here would+ # replace the level's result, or the CancelledError being+ # delivered, with a disk error. The checkpoint is a progress+ # record and nothing resumes from it, so losing one is worth+ # strictly less than the outcome it would mask.+ if self.job_system is not None and self.job_id is not None:+ try:+ self.job_system.flush(self.job_id)+ except Exception as exc:+ log.warning("job.checkpoint_flush_failed", level=level, error=str(exc))# ------------------------------------------------------------------# Orchestration# ------------------------------------------------------------------async def execute(self) -> list[GeneratedPage]:- self._setup_job()- await self._seed_resume()- await self._compute_selection()- self._announce_total()- self._compute_ia()+ with timed(self.timings, "generation.setup"):+ self._setup_job()+ await self._seed_resume()+ await self._compute_selection()+ self._announce_total()+ self._compute_ia()all_pages: list[GeneratedPage] = []@@ -813,98 +842,99 @@ class _GenerationRun:deterministic run still gets mermaid repair, interlinking, relatedpages and tour links over the pages it did produce."""- _stamp_structural_keys(all_pages)+ with timed(self.timings, "generation.finalize"):+ _stamp_structural_keys(all_pages)++ # Place every page in the tree that MCP, the web app and the editor+ # extension all read, instead of each deriving its own from paths.+ #+ # Skipped whenever this run holds only part of the wiki. Placement+ # depends on the pages that are NOT in hand (which module a file sits+ # under, who its siblings are), so a partial answer here would+ # overwrite a correct stored one. Both partial shapes have to be+ # named: a scoped run sets only_page_ids, and an incremental docs+ # update stops the ladder after level 2 with file_pages_only, which+ # leaves no overview, no modules and no layers to resolve against.+ # Those runs are placed by the post-persist rebuild instead.+ partial_run = bool(self.only_page_ids) or bool(+ getattr(self.config, "file_pages_only", False)+ )+ if not partial_run:+ try:+ from ..page_tree import assign_page_tree- # Place every page in the tree that MCP, the web app and the editor- # extension all read, instead of each deriving its own from paths.- #- # Skipped whenever this run holds only part of the wiki. Placement- # depends on the pages that are NOT in hand (which module a file sits- # under, who its siblings are), so a partial answer here would- # overwrite a correct stored one. Both partial shapes have to be- # named: a scoped run sets only_page_ids, and an incremental docs- # update stops the ladder after level 2 with file_pages_only, which- # leaves no overview, no modules and no layers to resolve against.- # Those runs are placed by the post-persist rebuild instead.- partial_run = bool(self.only_page_ids) or bool(- getattr(self.config, "file_pages_only", False)- )- if not partial_run:+ assign_page_tree(all_pages, self.layer_order_ids)+ except Exception as exc:+ log.debug("page_tree.failed", error=str(exc))++ # Post-generation: repair mermaid diagrams so illegal node IDs / unquoted+ # labels in LLM output don't break the whole diagram in the renderer.try:- from ..page_tree import assign_page_tree+ from ..mermaid_safety import sanitize_pages- assign_page_tree(all_pages, self.layer_order_ids)+ fixed = sanitize_pages(all_pages)+ if fixed:+ log.info("mermaid_safety.applied", pages_changed=fixed)except Exception as exc:- log.debug("page_tree.failed", error=str(exc))-- # Post-generation: repair mermaid diagrams so illegal node IDs / unquoted- # labels in LLM output don't break the whole diagram in the renderer.- try:- from ..mermaid_safety import sanitize_pages-- fixed = sanitize_pages(all_pages)- if fixed:- log.info("mermaid_safety.applied", pages_changed=fixed)- except Exception as exc:- log.debug("mermaid_safety.failed", error=str(exc))-- # Post-generation: resolve backtick refs into wiki links + backlinks.- try:- from ..interlinking import attach_wiki_links_and_backlinks-- attach_wiki_links_and_backlinks(- all_pages,- self.parsed_files,- # On incremental updates only the affected pages are in- # all_pages; the persisted ids keep resolution repo-wide.- prior_page_ids=list(self.gen._prior_pages or {}),- )- except Exception as exc:- log.debug("interlinking.failed", error=str(exc))-- # Post-generation: graph-derived related pages. Runs AFTER- # interlinking so prose-derived wiki_links win dedup and related- # entries only fill the gaps.- try:- from ..related_pages import attach_related_pages-- attach_related_pages(- all_pages,- import_edges=self._file_import_edges(),- git_meta_map=self.git_meta_map,- module_groups=self.sel_module_groups,- pagerank=self.pagerank,- # On incremental updates only the affected pages are in- # all_pages; the persisted ids keep resolution repo-wide.- prior_page_ids=list(self.gen._prior_pages or {}),- )- except Exception as exc:- log.debug("related_pages.failed", error=str(exc))+ log.debug("mermaid_safety.failed", error=str(exc))- # Post-generation: link KG tour steps to wiki page IDs.- if self.kg_ctx.available and self.repo_path:+ # Post-generation: resolve backtick refs into wiki links + backlinks.try:- from ..kg_enrichment import enrich_tour_with_wiki_links+ from ..interlinking import attach_wiki_links_and_backlinks++ attach_wiki_links_and_backlinks(+ all_pages,+ self.parsed_files,+ # On incremental updates only the affected pages are in+ # all_pages; the persisted ids keep resolution repo-wide.+ prior_page_ids=list(self.gen._prior_pages or {}),+ )+ except Exception as exc:+ log.debug("interlinking.failed", error=str(exc))- rp = (- Path(self.repo_path) if not isinstance(self.repo_path, Path) else self.repo_path+ # Post-generation: graph-derived related pages. Runs AFTER+ # interlinking so prose-derived wiki_links win dedup and related+ # entries only fill the gaps.+ try:+ from ..related_pages import attach_related_pages++ attach_related_pages(+ all_pages,+ import_edges=self._file_import_edges(),+ git_meta_map=self.git_meta_map,+ module_groups=self.sel_module_groups,+ pagerank=self.pagerank,+ # On incremental updates only the affected pages are in+ # all_pages; the persisted ids keep resolution repo-wide.+ prior_page_ids=list(self.gen._prior_pages or {}),)- kg_path = rp / ".repowise" / "knowledge-graph.json"- if kg_path.exists():- enrich_tour_with_wiki_links(kg_path, all_pages)except Exception as exc:- log.debug("kg_enrichment.failed", error=str(exc))+ log.debug("related_pages.failed", error=str(exc))- if self.job_system is not None and self.job_id is not None:- self.job_system.complete_job(self.job_id)+ # Post-generation: link KG tour steps to wiki page IDs.+ if self.kg_ctx.available and self.repo_path:+ try:+ from ..kg_enrichment import enrich_tour_with_wiki_links- log.info(- "Generation complete",- total_pages=len(all_pages),- provider=self.gen._provider.provider_name,- model=self.gen._provider.model_name,- )- return all_pages+ rp = (+ Path(self.repo_path) if not isinstance(self.repo_path, Path) else self.repo_path+ )+ kg_path = rp / ".repowise" / "knowledge-graph.json"+ if kg_path.exists():+ enrich_tour_with_wiki_links(kg_path, all_pages)+ except Exception as exc:+ log.debug("kg_enrichment.failed", error=str(exc))++ if self.job_system is not None and self.job_id is not None:+ self.job_system.complete_job(self.job_id)++ log.info(+ "Generation complete",+ total_pages=len(all_pages),+ provider=self.gen._provider.provider_name,+ model=self.gen._provider.model_name,+ )+ return all_pages# How each structurally-keyed type derives its identity. Member-keyed typesdiff --git a/packages/core/src/repowise/core/pipeline/phases/generation.py b/packages/core/src/repowise/core/pipeline/phases/generation.pyindex 7e31e6477..0d4b989b5 100644--- a/packages/core/src/repowise/core/pipeline/phases/generation.py+++ b/packages/core/src/repowise/core/pipeline/phases/generation.py@@ -179,6 +179,9 @@ async def run_generation(repo_path=repo_path,)+ # The recorder carries the run's shared totals table; generation's own+ # sub-spans write into it so they sit beside the top-level phases rather+ # than in a second table nothing reads.generated_pages = await generator.generate_all(parsed_files,source_map,@@ -200,6 +203,7 @@ async def run_generation(kg_data=kg_data,only_page_ids=only_page_ids,preserved_page_ids=preserved_page_ids,+ timings=getattr(progress, "table", None),)# Onboarding summary — count generated slots and surface which onesdiff --git a/tests/unit/generation/test_job_checkpoint_durability.py b/tests/unit/generation/test_job_checkpoint_durability.pynew file mode 100644index 000000000..668c5627b--- /dev/null+++ b/tests/unit/generation/test_job_checkpoint_durability.py@@ -0,0 +1,110 @@+"""What an interrupted run loses from the job checkpoint, and what it cannot.++``complete_page`` buffers, so a kill between a page landing and the next flush+drops that page from ``completed_page_ids``. These tests pin the two halves of+that trade: the window is real, and it cannot cost a resumed run any coverage,+because resume derives its skip set from the vector store rather than from this+file.+"""++from __future__ import annotations++import json+from types import SimpleNamespace++import pytest++from repowise.core.generation.job_system import JobSystem+from repowise.core.generation.models import GenerationConfig+from repowise.core.generation.page_generator.orchestrate import _GenerationRun+from repowise.core.persistence.vector_store.in_memory import InMemoryVectorStore+++class _StubEmbedder:+ """Fixed-width vectors; these tests never rank, they only count ids."""++ async def embed(self, texts: list[str]) -> list[list[float]]:+ return [[0.0, 1.0] for _ in texts]+++def _job(tmp_path) -> tuple[JobSystem, str]:+ js = JobSystem(tmp_path / "jobs")+ job_id = js.create_job(".", GenerationConfig(), "mock", "mock-model-1")+ js.start_job(job_id, 2)+ return js, job_id+++def _on_disk(tmp_path, job_id: str) -> dict:+ return json.loads((tmp_path / "jobs" / f"{job_id}.json").read_text(encoding="utf-8"))+++async def test_interrupt_between_page_and_flush_costs_no_resume_coverage(tmp_path):+ store = InMemoryVectorStore(_StubEmbedder())+ js, job_id = _job(tmp_path)++ # The durable rows land first — this is the ordering a real level uses.+ await store.embed_batch(+ [("file_page:a.py", "a", {}), ("file_page:b.py", "b", {})]+ )+ js.complete_page(job_id, "file_page:a.py")+ js.complete_page(job_id, "file_page:b.py")++ # The process dies here: after the pages persisted, before any flush.+ del js++ # The window is real - the checkpoint kept neither page.+ assert _on_disk(tmp_path, job_id)["completed_page_ids"] == []++ # A resumed run still covers both, because it asks the store, not the file.+ run = SimpleNamespace(+ job_system=JobSystem(tmp_path / "jobs"),+ resume=True,+ vector_store=store,+ completed_ids=set(),+ preserved_page_ids=set(),+ only_page_ids=None,+ )+ await _GenerationRun._seed_resume(run)++ assert run.completed_ids == {"file_page:a.py", "file_page:b.py"}+ assert _GenerationRun._emit(run, "file_page:a.py") is False+ assert _GenerationRun._emit(run, "file_page:b.py") is False+ # Skipped pages are held out of the sweep, so a resume does not delete them.+ assert run.preserved_page_ids == {"file_page:a.py", "file_page:b.py"}+++async def test_a_page_whose_rows_never_landed_is_regenerated(tmp_path):+ """The other side: no durable row means resume must not skip it."""+ store = InMemoryVectorStore(_StubEmbedder())+ js, job_id = _job(tmp_path)++ await store.embed_batch([("file_page:a.py", "a", {})])+ js.complete_page(job_id, "file_page:a.py")+ # b was generated but its rows never reached the store before the kill.+ js.complete_page(job_id, "file_page:b.py")+ del js++ run = SimpleNamespace(+ job_system=JobSystem(tmp_path / "jobs"),+ resume=True,+ vector_store=store,+ completed_ids=set(),+ preserved_page_ids=set(),+ only_page_ids=None,+ )+ await _GenerationRun._seed_resume(run)++ assert _GenerationRun._emit(run, "file_page:b.py") is True+++def test_a_flushed_level_survives_the_same_kill(tmp_path):+ """The bound in reverse: what a level boundary made durable stays durable."""+ js, job_id = _job(tmp_path)+ js.complete_page(job_id, "file_page:a.py")+ js.flush(job_id)+ js.complete_page(job_id, "file_page:b.py")+ del js++ assert _on_disk(tmp_path, job_id)["completed_page_ids"] == ["file_page:a.py"]diff --git a/tests/unit/generation/test_job_system.py b/tests/unit/generation/test_job_system.pyindex 9b05f7b48..9ae766c08 100644--- a/tests/unit/generation/test_job_system.py+++ b/tests/unit/generation/test_job_system.py@@ -2,6 +2,7 @@from __future__ import annotations+import jsonfrom pathlib import Pathimport pytest@@ -109,12 +110,77 @@ def test_complete_page_json_persisted(tmp_path):job_id = _create(js)js.start_job(job_id, 5)js.complete_page(job_id, "file_page:x.py")+ js.flush(job_id)# New instance — reads from diskjs2 = JobSystem(tmp_path / "jobs")cp = js2.get_checkpoint(job_id)assert "file_page:x.py" in cp.completed_page_ids+def test_completions_are_buffered_until_flushed(tmp_path):+ """The window the durability contract names, asserted rather than assumed."""+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 5)+ js.complete_page(job_id, "file_page:x.py")++ on_disk = json.loads((tmp_path / "jobs" / f"{job_id}.json").read_text(encoding="utf-8"))+ assert on_disk["completed_page_ids"] == []+ # ...while the owning instance still reports it.+ assert "file_page:x.py" in js.get_checkpoint(job_id).completed_page_ids++ js.flush(job_id)+ on_disk = json.loads((tmp_path / "jobs" / f"{job_id}.json").read_text(encoding="utf-8"))+ assert on_disk["completed_page_ids"] == ["file_page:x.py"]+++def test_completions_flush_on_their_own_at_the_bound(tmp_path):+ """A level larger than the bound cannot buffer without limit."""+ from repowise.core.generation.job_system import _FLUSH_EVERY_PAGES++ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, _FLUSH_EVERY_PAGES)+ for i in range(_FLUSH_EVERY_PAGES):+ js.complete_page(job_id, f"file_page:{i}.py")++ on_disk = json.loads((tmp_path / "jobs" / f"{job_id}.json").read_text(encoding="utf-8"))+ assert len(on_disk["completed_page_ids"]) == _FLUSH_EVERY_PAGES+++def test_complete_job_flushes_buffered_pages(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 2)+ js.complete_page(job_id, "file_page:a.py")+ js.complete_job(job_id)++ cp = JobSystem(tmp_path / "jobs").get_checkpoint(job_id)+ assert cp.status == "completed"+ assert "file_page:a.py" in cp.completed_page_ids+++def test_failed_pages_are_durable_without_a_flush(tmp_path):+ """The failure report reads this field off disk after the run."""+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 2)+ js.fail_page(job_id, "file_page:bad.py", "upstream 529")++ cp = JobSystem(tmp_path / "jobs").get_checkpoint(job_id)+ assert cp.failed_page_ids == ["file_page:bad.py"]+++def test_flush_leaves_no_temp_files_behind(tmp_path):+ js = _make_system(tmp_path)+ job_id = _create(js)+ js.start_job(job_id, 2)+ js.complete_page(job_id, "file_page:a.py")+ js.flush(job_id)++ assert list((tmp_path / "jobs").glob("*.tmp")) == []++# ---------------------------------------------------------------------------# fail_page# ---------------------------------------------------------------------------@@ -219,6 +285,7 @@ def test_json_round_trip_persistence(tmp_path):js.start_job(job_id, 3)js.complete_page(job_id, "file_page:a.py")js.complete_page(job_id, "file_page:b.py")+ js.flush(job_id)# Reload from disk with a new instancejs2 = JobSystem(tmp_path / "jobs")diff --git a/tests/unit/generation/test_run_level_cancellation.py b/tests/unit/generation/test_run_level_cancellation.pyindex abdcc5575..70057f53b 100644--- a/tests/unit/generation/test_run_level_cancellation.py+++ b/tests/unit/generation/test_run_level_cancellation.py@@ -53,6 +53,7 @@ def _fake_run(max_concurrency: int = 1) -> SimpleNamespace:on_page_ready=None,vector_store=None,completed_page_summaries={},+ timings=None,)diff --git a/tests/unit/generation/test_run_level_embed_gating.py b/tests/unit/generation/test_run_level_embed_gating.pyindex 3fd6f47bf..6fc1a0180 100644--- a/tests/unit/generation/test_run_level_embed_gating.py+++ b/tests/unit/generation/test_run_level_embed_gating.py@@ -59,6 +59,7 @@ def _fake_run(store) -> SimpleNamespace:on_page_ready=None,vector_store=store,completed_page_summaries={},+ timings=None,)diff --git a/tests/unit/generation/test_run_level_stub_fallback.py b/tests/unit/generation/test_run_level_stub_fallback.pyindex 331dac4cd..aec3c3dcb 100644--- a/tests/unit/generation/test_run_level_stub_fallback.py+++ b/tests/unit/generation/test_run_level_stub_fallback.py@@ -55,10 +55,14 @@ class _RecordingJobSystem:self.completed: list[str] = []self.failed: list[tuple[str, str]] = []self.levels: list[int] = []+ self.flushes = 0def update_level(self, job_id, level):self.levels.append(level)+ def flush(self, job_id):+ self.flushes += 1+def complete_page(self, job_id, page_id):self.completed.append(page_id)@@ -85,6 +89,7 @@ def _run_level() -> tuple[list[GeneratedPage], _RecordingJobSystem, _RecordingSton_page_ready=None,vector_store=store,completed_page_summaries={},+ timings=None,)return await _GenerationRun.run_level(run,@@ -102,6 +107,13 @@ def test_stub_fallback_is_recorded_as_a_failed_page() -> None:assert jobs.failed == [("module_page:lost", "upstream 529 overloaded")]+def test_a_finished_level_flushes_its_checkpoint() -> None:+ """Page completions buffer, so the level boundary has to make them durable."""+ _pages, jobs, _store = _run_level()++ assert jobs.flushes == 1++def test_stub_fallback_is_not_recorded_as_completed() -> None:"""A page cannot be both, and "completed" is the half a reader believes."""_pages, jobs, _store = _run_level()