Files
ai-resume/corpus/loader.py
Sam Rolfe f9dc574172 Phase 4: corpus and retrieval — chunks, Qdrant, FTS5, freshness audit
Satisfies docs/phase-4-corpus.md. content/ stays the single source of truth:
one pass over it writes both indexes, so the static pages and the retrieval
corpus cannot drift.

- corpus/: stdlib-only pipeline. validate -> chunk -> enrich -> embed -> upsert.
  Chunking is block-based, so a boundary cannot fall inside a fenced block, a
  table or front-matter (verified structurally, not by inspection).
- Deterministic ids: sha256(source_path + chunk_index + content_hash), rendered
  as a UUID. Re-running updates points; re-chunking deletes the old ones by
  source filter, so duplicates and orphans are both impossible.
- Incremental by content hash against a SQLite manifest. A provider, dimension
  or chunker change is refused instead of mixed: it needs a rebuild.
- Payloads per section 4.2 plus provenance, validated before any vector is
  written; a missing field fails the run and names the document and chunk.
- SQLite FTS5 over chunks (the keyword half of hybrid retrieval, decision D10)
  with area/confidence filters and a `terms` column so front-matter tech and
  tags are findable.
- Freshness audit: stale documents, due soon, index drift, contract drift;
  optional Apprise alert; exit code for Prefect.
- Embeddings behind one interface: omniroute (OpenAI-compatible, retries, key
  from the environment only) and local-hashing (offline placeholder). The
  provider decision is still Sam's; the pipeline does not depend on it.
- deploy/qdrant.yml: mem_limit = memswap_limit = 400m, loopback only.
- docs/phase-4-notes.md: operator manual, DoD evidence, measured memory.
- 76 unit tests, no container and no network.

Measured, Qdrant 1.20.0 under a 400 m cap at 1024 dimensions: 500 / 5,000 /
20,000 chunks settle at 128 / 138 / 151 MiB, peaking at 149 / 305 / 292 MiB
during ingest. Qdrant's default settings are OOM-killed between 5,000 and
20,000, so the collection is created with HNSW and payloads on disk; recorded in
reference/stack.md with the ceiling and the escalation order.

Note: the `make corpus*` targets were swept into the Phase 3 deploy commit
24590cc by concurrent work in this tree; the Makefile content is correct, and
this commit contains the pipeline they call.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-10-26 21:04:52 +11:00

163 lines
5.5 KiB
Python

"""Load `content/` into documents, reusing the Phase 1 validator's parser.
There is exactly one front-matter dialect in this repository and exactly one
parser for it: `tools/validate_content.py`. This module imports that parser
rather than reimplementing it, so the corpus can never disagree with the gate
about what a document says.
The gate itself is `validate_tree` from the same file. The pipeline runs it
before it chunks anything: an invalid content tree stops the run, it never
reaches the vector store.
"""
from __future__ import annotations
import hashlib
import importlib.util
import os
import sys
from dataclasses import dataclass, field
VALIDATOR_NAME = "validate_content"
class ContentError(RuntimeError):
"""The content tree is unreadable or invalid; the run must stop."""
def load_validator(root: str):
"""Import tools/validate_content.py as a module (cached per root)."""
cached = sys.modules.get(VALIDATOR_NAME)
if cached is not None and getattr(cached, "__validator_root__", None) == root:
return cached
path = os.path.join(root, "tools", "validate_content.py")
if not os.path.exists(path):
raise ContentError(f"validator not found at {path}")
spec = importlib.util.spec_from_file_location(VALIDATOR_NAME, path)
if spec is None or spec.loader is None:
raise ContentError(f"cannot load validator at {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
module.__validator_root__ = root # type: ignore[attr-defined]
sys.modules[VALIDATOR_NAME] = module
return module
def to_python(node):
"""Convert a validator front-matter Node into plain Python values."""
if node is None or node.kind == "null":
return None
if node.kind == "scalar":
return node.value
if node.kind == "seq":
return [to_python(item) for item in node.value]
if node.kind == "map":
return {key: to_python(value) for key, value in node.value.items()}
raise ContentError(f"unexpected front-matter node kind {node.kind!r}")
@dataclass
class Document:
"""One Markdown file plus the front-matter the schema guarantees."""
path: str # repository-relative, posix, e.g. "content/edge/l3/edge-zigbee.md"
source_id: str
area: str
level: int
title: str
claim: str
confidence: str
period: str
tech: list
metrics: list
artefacts: list
public: bool
last_verified: str
tags: list
body: str
digest: str # sha256 of the file bytes: the incremental-mode key
url: str # canonical page URL, matching internal/content.PageURL
# Filled in by the pipeline as it goes; not part of the schema.
chunk_count: int = field(default=0)
@property
def artefact_urls(self) -> list:
return [str(a.get("url", "")) for a in self.artefacts if a.get("url")]
def page_url(area: str, doc_id: str, level: int) -> str:
"""Canonical URL for a document. Mirrors internal/content.PageURL exactly."""
if level == 1:
return f"/{area}/"
if level == 2:
return f"/{area}/{doc_id}/"
return f"/{area}/a/{doc_id}/"
def digest_of(path: str) -> str:
"""sha256 of the raw file bytes — the same digest for any platform."""
with open(path, "rb") as handle:
return hashlib.sha256(handle.read()).hexdigest()
def load_documents(cfg) -> list:
"""Load every document under content/, sorted by path.
Raises ContentError when the gate fails, so a broken content tree never
produces a half-correct index.
"""
validator = load_validator(cfg.root)
violations, count = validator.validate_tree(cfg.root, cfg.content_dir, quiet=True)
if violations:
detail = "\n ".join(violations[:20])
more = "" if len(violations) <= 20 else f"\n … and {len(violations) - 20} more"
raise ContentError(
f"content gate failed with {len(violations)} violation(s) "
f"across {count} document(s). Run `make validate`:\n {detail}{more}"
)
documents = []
for path in validator.iter_documents(cfg.content_dir):
documents.append(_load_one(cfg, validator, path))
documents.sort(key=lambda d: d.path)
if not documents:
raise ContentError(f"no documents found under {cfg.content_dir}")
return documents
def _load_one(cfg, validator, path: str) -> Document:
rel = os.path.relpath(path, cfg.root).replace(os.sep, "/")
fm_lines, body, problem = validator.split_front_matter(path)
if problem:
raise ContentError(f"{rel}: {problem}")
try:
root_node = validator.parse_front_matter(fm_lines)
except validator.YamlError as exc:
raise ContentError(f"{rel}:{exc.line}: invalid YAML: {exc.msg}") from exc
fields = to_python(root_node)
if not isinstance(fields, dict):
raise ContentError(f"{rel}: front-matter must be a mapping")
level = int(fields["level"])
doc = Document(
path=rel,
source_id=str(fields["id"]),
area=str(fields["area"]),
level=level,
title=str(fields["title"]),
claim=str(fields["claim"]),
confidence=str(fields["confidence"]),
period=str(fields["period"]),
tech=list(fields.get("tech") or []),
metrics=list(fields.get("metrics") or []),
artefacts=list(fields.get("artefacts") or []),
public=bool(fields.get("public")),
last_verified=str(fields["last_verified"]),
tags=list(fields.get("tags") or []),
body=body,
digest=digest_of(path),
url=page_url(str(fields["area"]), str(fields["id"]), level),
)
return doc