From 9d726ad5978d3c718f80037d89615c3f339f0a4c Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Tue, 17 Nov 2026 22:12:27 +0530 Subject: [PATCH 1/2] feat(ingest): orchestration with idempotent chunk diff and summary json (T07) run_ingest(cfg) wires fetch -> extract -> parse -> chunk -> hash -> diff -> embed -> summarize per ARCHITECTURE 7.4/10.3: chunk_hash = SHA-256 of the normalized body + url + heading path (NUL-joined) drives the insert/orphan diff that makes double-ingest idempotent (FR-02/A8); inserted chunks embed in batches of <=100 via the provider backends' own 429 backoff; the 9.4 summary is returned and stored in ingest_runs. caliper ingest --version v1|v2|v3 [--refresh] prints the summary JSON and maps typed errors to the 9 envelope (exit 2/4/5). ARCHITECTURE 7.4 now names the CHARS_PER_TOKEN=4 estimator (paying off T06's recorded deviation) and the hash normalization T08 re-derives. --- docs/ARCHITECTURE.md | 4 +- src/caliper/cli.py | 101 ++++++- src/caliper/ingest/__init__.py | 368 ++++++++++++++++++++++++- tests/integration/test_ingest.py | 456 +++++++++++++++++++++++++++++++ tests/unit/test_ingest_hash.py | 85 ++++++ 5 files changed, 1007 insertions(+), 7 deletions(-) create mode 100644 tests/integration/test_ingest.py create mode 100644 tests/unit/test_ingest_hash.py diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d07a270..8cde5e3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -305,8 +305,8 @@ Implementation notes (binding): Implementation notes (binding): - Source: `https://github.com/MicrosoftDocs/azure-docs` tarball at a **pinned ref recorded at first ingest** (`source_ref` in `ingest_runs`). Read `articles/azure-functions/**.md` and `articles/service-bus-messaging/**.md`, excluding any path containing `/includes/` and files starting with `_`. URL mapping per A1. The tarball is cached in `data/cache/`; re-ingest reuses the cache (no refetch) unless `--refresh` is passed. - Heading path: first H1 in the file is the page title; the chunk's heading path is `" >

>

"` as of the chunk's position. Stored on every chunk (FR-01). -- Chunkers (FR-02, ≥2 configs): `heading` (V1) splits at H2 boundaries, merging undersized neighbors up to `max_tokens`; `fixed` (V2/V3) windows the body at `size_tokens` with `overlap_tokens`, prefixing each chunk with `Page: \nHeading: `. All chunks cap at 1,900 tokens (embedding input limit is 2,048). -- Idempotency: `chunk_hash = SHA-256(normalized body + url + heading path)` with a UNIQUE index; re-ingest upserts changed chunks and deletes chunks whose pages disappeared upstream. Index tables are explicitly **not** append-only. +- Chunkers (FR-02, ≥2 configs): `heading` (V1) splits at H2 boundaries, merging undersized neighbors up to `max_tokens`; `fixed` (V2/V3) windows the body at `size_tokens` with `overlap_tokens`, prefixing each chunk with `Page: \nHeading: `. All chunks cap at 1,900 **estimated** tokens (embedding input limit is 2,048); estimated tokens are `ceil(len(text) / 4)` — the `CHARS_PER_TOKEN = 4` estimator frozen in `chunkers.py` (T06 decision, docs/TASKS.md Notes). +- Idempotency: `chunk_hash = SHA-256(normalized body + url + heading path)` — normalized = LF lines with per-line trailing and outer whitespace stripped, the three fields NUL-separated before hashing (T07 definition, `ingest/__init__.py`) — with a UNIQUE index; re-ingest upserts changed chunks and deletes chunks whose pages disappeared upstream. Index tables are explicitly **not** append-only. - Embedding quota: batches of ≤100 texts/request; on 429 back off exponentially (1s → 2s → 4s → ... max 60s, 5 tries) and persist a resume checkpoint (last processed chunk rowid) so an interrupted ingest resumes without redoing completed batches. ### 7.5 `retrieval` — search and rank-to-5 diff --git a/src/caliper/cli.py b/src/caliper/cli.py index c20f923..fa652e0 100644 --- a/src/caliper/cli.py +++ b/src/caliper/cli.py @@ -1,22 +1,115 @@ -"""Caliper command surface (skeleton). +"""Caliper command surface (§7.9, §9.1). -Subcommands land with their owning tasks per ARCHITECTURE §14.2: -ingest (T07), ask (T12), eval/report/spotcheck (T14/T15/T19), setup/serve (T22). -The only argument parsing in the project lives here (§7.9). +Subcommands land with their owning tasks per ARCHITECTURE §14.2: ingest (T07), +ask (T12), eval/report/spotcheck (T14/T15/T19), setup/serve (T22). The only +argument parsing in the project lives here (§7.9). Every subcommand maps typed +component errors to the §9 envelope exactly once at this edge (§16), prints +machine-readable JSON to stdout, and logs human prose to stderr (§11.3). """ +from __future__ import annotations + +import json +import logging +import os +import sys +from enum import StrEnum +from pathlib import Path +from typing import Annotated + import typer +from caliper.config import ConfigError, load_config +from caliper.db import DbError +from caliper.ingest import run_ingest +from caliper.ingest.source import SourceError +from caliper.providers import ProviderError + app = typer.Typer( name="caliper", help="Local Q&A assistant over one frozen documentation set, with measured quality.", no_args_is_help=True, ) +# §11.2: paths and log level live in the environment, never in the config model. +_USER_CONFIG_ENV_VAR = "CALIPER_CONFIG" +_DEFAULT_USER_CONFIG = "configs/caliper.sample.toml" +_PRESETS_DIR = Path("configs") +_LOG_LEVEL_ENV_VAR = "CALIPER_LOG_LEVEL" + +# §9 error-code table: the CLI exit codes this surface maps to. +_EXIT_CONFIG_INVALID = 2 +_EXIT_PROVIDER_UNAVAILABLE = 4 +_EXIT_QUOTA_EXHAUSTED = 5 + + +class Version(StrEnum): + """The three measured versions (§9.7); selects the committed preset file.""" + + V1 = "v1" + V2 = "v2" + V3 = "v3" + + +def _configure_logging() -> None: + """§11.3: Python logging to stderr in the standard format, level from + CALIPER_LOG_LEVEL (default INFO). Machine-readable JSON goes to stdout.""" + level = os.environ.get(_LOG_LEVEL_ENV_VAR, "INFO").upper() + logging.basicConfig( + level=level, + format="%(asctime)s %(levelname)s %(name)s %(message)s", + stream=sys.stderr, + ) + + +def _print_error(code: str, message: str) -> None: + """Print the §9 error envelope as JSON to stderr (§9).""" + typer.echo(json.dumps({"error": {"code": code, "message": message}}), err=True) + + +def _map_error(exc: Exception) -> tuple[str, int]: + """Map one typed component exception to its §9 envelope code and CLI exit + code (§9 error-code table). `SourceError`/`DbError` have no dedicated §9 + code (recorded in docs/TASKS.md Notes): they map to `provider_unavailable` + — an ingest whose corpus source or local store is unavailable.""" + if isinstance(exc, ConfigError): + return "config_invalid", _EXIT_CONFIG_INVALID + if isinstance(exc, ProviderError): + if exc.code == "quota_exhausted": + return "quota_exhausted", _EXIT_QUOTA_EXHAUSTED + return "provider_unavailable", _EXIT_PROVIDER_UNAVAILABLE + if isinstance(exc, SourceError | DbError): + return "provider_unavailable", _EXIT_PROVIDER_UNAVAILABLE + raise AssertionError(f"unmapped error type: {type(exc).__name__}") + @app.callback() def main() -> None: """Caliper: ask questions, get cited answers, measure quality.""" + _configure_logging() + + +@app.command() +def ingest( + version: Annotated[ + Version, typer.Option("--version", help="Version preset to ingest (§9.7).") + ] = Version.V1, + refresh: Annotated[ + bool, typer.Option("--refresh", help="Re-resolve and refetch the corpus even when cached.") + ] = False, +) -> None: + """Fetch, parse, chunk, embed, and index the frozen corpus (§10.3).""" + try: + cfg = load_config( + Path(os.environ.get(_USER_CONFIG_ENV_VAR, _DEFAULT_USER_CONFIG)), + _PRESETS_DIR / f"{version.value}.toml", + ) + summary = run_ingest(cfg, refresh=refresh) + except (ConfigError, ProviderError, SourceError, DbError) as exc: + code, exit_code = _map_error(exc) + _print_error(code, str(exc)) + raise typer.Exit(code=exit_code) from exc + typer.echo(json.dumps(summary.as_dict())) if __name__ == "__main__": diff --git a/src/caliper/ingest/__init__.py b/src/caliper/ingest/__init__.py index 6fba73e..27a7095 100644 --- a/src/caliper/ingest/__init__.py +++ b/src/caliper/ingest/__init__.py @@ -1 +1,367 @@ -"""`ingest` component package (§7.4) — T05 marker only; implementation lands with T07.""" +"""Ingest orchestration (§7.4, §10.3): corpus → parsed pages → chunks → index. + +`run_ingest(cfg)` is the §7.4 public entry point. It fetches the frozen corpus +once through source.py's pinned-ref cache, extracts the tarball (stripping the +upstream top-level `azure-docs-/` directory — T05's recorded handoff), +parses and chunks every discovered page with the configured chunker, hashes +chunks per §7.4 (`SHA-256(normalized body + url + heading path)`, `chunk_hash` +below), diffs the planned rows against the stored index (re-ingest inserts +new/changed chunks and deletes orphans — FR-02 idempotency), embeds the +inserted chunks in batches of ≤100 texts with the configured backend (HTTP 429 +backoff is the backends' own bounded retry, §7.2/T04), stores the +L2-normalized vectors in the per-fingerprint `vec0` table, and records the +completed run in `ingest_runs` with the §9.4 summary JSON. + +The §9.4 summary is both the return value and the JSON body `caliper ingest` +prints. Keyword-only seams (`fetcher`, `embeddings`) follow the established +injection pattern (source.py's Fetcher, T09's embeddings seam): tests inject +fakes, production uses the defaults. Transaction discipline: all writes commit +once at the end — a crashed ingest leaves the previous complete state intact +and a re-run starts from scratch; resume checkpoints are T08's job (§14.2). +""" + +from __future__ import annotations + +import hashlib +import json +import logging +import os +import sqlite3 +import tarfile +import tempfile +import time +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path + +from caliper.config import CaliperConfig, fingerprint, fingerprint_payload +from caliper.db import ( + ChunkRow, + IngestRunRow, + connect, + delete_chunks, + ensure_chunks_tables, + ensure_schema, + finish_ingest_run, + insert_chunk_embeddings, + insert_chunks, + record_fingerprint, + upsert_ingest_run, +) +from caliper.ingest.chunkers import make_chunker +from caliper.ingest.parse import ParseError, parse_page +from caliper.ingest.source import ( + ARTICLE_TREES, + Fetcher, + SourceError, + discover_pages, + fetch_corpus, + read_cache_meta, +) +from caliper.providers import EmbeddingBackend, get_embeddings +from caliper.providers.base import EMBED_BATCH_SIZE + +_LOGGER = logging.getLogger(__name__) + +#: §11.2: the DB path lives in the environment, never in the fingerprinted +#: config model — read directly here, mirroring source.py's CALIPER_CACHE_DIR +#: precedent (recorded in docs/TASKS.md Notes). +DB_ENV_VAR = "CALIPER_DB" +DEFAULT_DB_PATH = "data/caliper.db" + + +# --- §9.4 summary contract ------------------------------------------------------- + + +@dataclass(frozen=True, slots=True) +class SkippedPage: + """One §9.4 skipped entry: a corpus-relative path and a stable reason.""" + + path: str + reason: str + + +@dataclass(frozen=True, slots=True) +class IngestSummary: + """The §9.4 ingestion summary: `run_ingest`'s return value and the JSON + `caliper ingest` prints. `fingerprint` is the 8-hex `config.fp8(cfg)` + suffix (§9.4's example is 8 chars); `pages_ok` counts discovered pages + that parsed (H1-only pages included, zero chunks); `pages_skipped` counts + every other `.md` under the trees (excluded patterns + parse errors).""" + + fingerprint: str + source_ref: str + pages_ok: int + pages_skipped: int + skipped: list[SkippedPage] + chunks_written: int + chunks_removed: int + embed_requests: int + elapsed_s: float + + def as_dict(self) -> dict[str, object]: + """The §9.4 JSON object in its contract key order (json.dumps preserves + insertion order).""" + return { + "fingerprint": self.fingerprint, + "source_ref": self.source_ref, + "pages_ok": self.pages_ok, + "pages_skipped": self.pages_skipped, + "skipped": [{"path": skip.path, "reason": skip.reason} for skip in self.skipped], + "chunks_written": self.chunks_written, + "chunks_removed": self.chunks_removed, + "embed_requests": self.embed_requests, + "elapsed_s": round(self.elapsed_s, 3), + } + + +# --- Chunk identity (§7.4 idempotency; re-derived by T08's resume logic) --------- + + +def _normalize_body(body: str) -> str: + """The "normalized body" of §7.4's chunk_hash composition: LF lines with + per-line trailing whitespace and outer whitespace stripped. Bodies + themselves stay verbatim (parse.py keeps the canonical quote source, §17); + this normalization only makes hashes stable against insignificant + whitespace churn and platform line endings.""" + return "\n".join(line.rstrip() for line in body.strip().splitlines()) + + +def chunk_hash(page_url: str, heading_path: str, body: str) -> str: + """SHA-256 of the §7.4 composition `normalized body + url + heading path`. + + The three fields are joined with NUL separators so no field's content can + bleed into a neighbor's (a "url" ending where the body "begins" must not + collide with a different split). Deterministic across runs and platforms; + `chunk_hash` is UNIQUE in `chunks_` (§8.3) and is the diff key that + makes re-ingest idempotent (FR-02). + """ + payload = "\x00".join((_normalize_body(body), page_url, heading_path)) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +# --- Orchestration helpers ------------------------------------------------------- + + +def _db_path() -> Path: + """The database path: CALIPER_DB env var, default `data/caliper.db` (§11.2).""" + return Path(os.environ.get(DB_ENV_VAR, DEFAULT_DB_PATH)) + + +def _extract(tarball: Path, workdir: Path) -> Path: + """Extract the corpus tarball under `workdir`; return the directory that + contains `articles/`. The upstream tarball carries exactly one top-level + `azure-docs-/` directory, which is stripped here (T05's recorded + handoff in docs/TASKS.md Notes); a tarball that is not itself a corpus + root and holds no single such top-level directory is a SourceError — the + loud A1-breakage signal (§7.4).""" + with tarfile.open(tarball, "r:gz") as tar: + tar.extractall(workdir, filter="data") # stdlib safe-extract filter (Python 3.12) + if (workdir / "articles").is_dir(): + return workdir + top_level = sorted(entry for entry in workdir.iterdir() if entry.is_dir()) + if len(top_level) == 1 and (top_level[0] / "articles").is_dir(): + return top_level[0] + raise SourceError( + "unexpected corpus tarball layout: expected the extracted root — or " + f"exactly one top-level directory under {workdir} — to contain 'articles/'" + ) + + +def _excluded_pages(extracted_root: Path, pages: Sequence[str]) -> list[str]: + """`.md` files under the article trees that `discover_pages` dropped. + + discover_pages applies the exclusion rules and is the single source of + truth (source.py is T05-owned/frozen, §14.4), so exclusion is computed as + the complement against a raw scan. Each excluded file becomes a §9.4 skip + with reason `excluded-pattern`. + """ + all_md: set[str] = set() + for tree in ARTICLE_TREES: + for path in (extracted_root / tree).rglob("*.md"): + all_md.add(path.relative_to(extracted_root).as_posix()) + return sorted(all_md.difference(pages)) + + +def _plan_chunks( + cfg: CaliperConfig, extracted_root: Path, pages: Sequence[str] +) -> tuple[list[ChunkRow], list[SkippedPage]]: + """Parse and chunk every page; return hash-tagged insert rows plus skips. + + Rows are built positionally from T06's frozen `Chunk` field order + (docs/TASKS.md Notes: "Chunk field order mirrors db.ChunkRow minus + chunk_hash"). A ParseError skips the page with the §9.4 reason + `parse-error: `; H1-only pages parse to zero chunks and stay + pages_ok (T06 freeze).""" + chunker = make_chunker(cfg) + rows: list[ChunkRow] = [] + skips: list[SkippedPage] = [] + for rel_path in pages: + try: + text = (extracted_root / rel_path).read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError) as exc: + raise SourceError(f"could not read corpus page {rel_path}: {exc}") from exc + try: + page = parse_page(rel_path, text) + except ParseError as exc: + _LOGGER.warning("skipped %s: parse-error: %s", rel_path, exc.reason) + skips.append(SkippedPage(path=rel_path, reason=f"parse-error: {exc.reason}")) + continue + for chunk in chunker.chunk_page(page): + rows.append( + ChunkRow( + page_url=chunk.page_url, + heading_path=chunk.heading_path, + body=chunk.body, + body_tokens=chunk.body_tokens, + chunk_hash=chunk_hash(chunk.page_url, chunk.heading_path, chunk.body), + ordinal=chunk.ordinal, + ) + ) + return rows, skips + + +def _diff_chunks( + conn: sqlite3.Connection, suffix: str, rows: Sequence[ChunkRow] +) -> tuple[list[ChunkRow], list[int]]: + """Diff the planned rows against the stored index (§7.4 idempotency). + + Returns the rows to insert (new or changed content — a changed page + orphans its old chunks and inserts its new ones, the §7.4 "upsert") and + the orphan chunk ids to delete (stored chunks whose (page_url, chunk_hash) + the plan no longer contains: pages disappeared upstream or changed). Reads + the table directly on the passed connection — db.py is T03-owned (§14.4), + mirroring T09's KNN precedent; `suffix` always derives from + `config.fp8(cfg)` here.""" + existing: dict[tuple[str, str], int] = {} + for chunk_id, page_url, stored_hash in conn.execute( + f"SELECT chunk_id, page_url, chunk_hash FROM chunks_{suffix}" + ): + existing[(str(page_url), str(stored_hash))] = int(chunk_id) + planned = {(row.page_url, row.chunk_hash) for row in rows} + orphans = sorted(orphan_id for key, orphan_id in existing.items() if key not in planned) + inserts = [row for row in rows if (row.page_url, row.chunk_hash) not in existing] + return inserts, orphans + + +def _store_embeddings( + conn: sqlite3.Connection, + suffix: str, + chunk_ids: Sequence[int], + bodies: Sequence[str], + backend: EmbeddingBackend, +) -> int: + """Embed the inserted chunks and store their vectors; return the call count. + + Batches of ≤ `EMBED_BATCH_SIZE` (100) texts per request (§7.4, §10.3), + vectors L2-normalized by the backend (ADR-003) and keyed by rowid = + chunk_id (§8.3). The bounded 429 backoff lives inside the backends + (§7.2/T04 — every embed call is wrapped in `call_with_backoff` there), so + this loop only counts the batch requests for §9.4's `embed_requests`.""" + embed_requests = 0 + for start in range(0, len(chunk_ids), EMBED_BATCH_SIZE): + batch_ids = list(chunk_ids[start : start + EMBED_BATCH_SIZE]) + batch_bodies = list(bodies[start : start + EMBED_BATCH_SIZE]) + vectors = backend.embed_documents(batch_bodies) + embed_requests += 1 + _LOGGER.debug("embedded batch %d (%d chunks)", embed_requests, len(batch_ids)) + insert_chunk_embeddings(conn, suffix, list(zip(batch_ids, vectors, strict=True))) + return embed_requests + + +def run_ingest( + cfg: CaliperConfig, + *, + refresh: bool = False, + fetcher: Fetcher | None = None, + embeddings: EmbeddingBackend | None = None, +) -> IngestSummary: + """Fetch, parse, chunk, diff, embed, and index the frozen corpus (§7.4). + + `refresh` re-resolves and refetches the corpus even when cached (§7.4); + `fetcher` and `embeddings` are the §15 injection seams (defaults: the httpx + fetcher and `providers.get_embeddings(cfg)`). The §9.4 summary is returned + and stored in `ingest_runs` (`upsert_ingest_run` + `finish_ingest_run` + happen at completion per §10.3, so a crashed ingest leaves the previous + completed row for the fingerprint untouched). All index writes commit once + at the end; resume checkpoints are T08's job (§14.2).""" + backend = embeddings if embeddings is not None else get_embeddings(cfg) + started_wall = datetime.now(UTC).isoformat() + started = time.monotonic() + + tarball = fetch_corpus(cfg, refresh=refresh, fetcher=fetcher) + meta = read_cache_meta(cfg) + full_fingerprint = fingerprint(cfg) + suffix = full_fingerprint[:8] + + with tempfile.TemporaryDirectory(prefix="caliper-ingest-") as work: + extracted_root = _extract(tarball, Path(work)) + pages = discover_pages(extracted_root) + skipped = [ + SkippedPage(path=path, reason="excluded-pattern") + for path in _excluded_pages(extracted_root, pages) + ] + rows, parse_skips = _plan_chunks(cfg, extracted_root, pages) + skipped.extend(parse_skips) + skipped.sort(key=lambda skip: skip.path) + pages_ok = len(pages) - len(parse_skips) + + conn = connect(_db_path()) + try: + ensure_schema(conn) + ensure_chunks_tables(conn, suffix) + record_fingerprint( + conn, + fingerprint=full_fingerprint, + config_json=json.dumps(fingerprint_payload(cfg), sort_keys=True, separators=(",", ":")), + ) + inserts, orphans = _diff_chunks(conn, suffix, rows) + delete_chunks(conn, suffix, orphans) + chunk_ids = insert_chunks(conn, suffix, inserts) + embed_requests = _store_embeddings( + conn, suffix, chunk_ids, [row.body for row in inserts], backend + ) + summary = IngestSummary( + fingerprint=suffix, + source_ref=meta.source_ref, + pages_ok=pages_ok, + pages_skipped=len(skipped), + skipped=skipped, + chunks_written=len(inserts), + chunks_removed=len(orphans), + embed_requests=embed_requests, + elapsed_s=time.monotonic() - started, + ) + ingest_run_id = upsert_ingest_run( + conn, + IngestRunRow( + fingerprint=full_fingerprint, + source_ref=meta.source_ref, + summary_json=json.dumps(summary.as_dict()), + started_at=started_wall, + ), + ) + finish_ingest_run( + conn, + ingest_run_id, + finished_at=datetime.now(UTC).isoformat(), + pages_ok=summary.pages_ok, + pages_skipped=summary.pages_skipped, + ) + conn.commit() + finally: + conn.close() + + _LOGGER.info( + "ingest %s complete: %d pages ok, %d skipped, %d chunks written, " + "%d removed, %d embed requests in %.1fs", + suffix, + summary.pages_ok, + summary.pages_skipped, + summary.chunks_written, + summary.chunks_removed, + summary.embed_requests, + summary.elapsed_s, + ) + return summary diff --git a/tests/integration/test_ingest.py b/tests/integration/test_ingest.py new file mode 100644 index 0000000..6e66590 --- /dev/null +++ b/tests/integration/test_ingest.py @@ -0,0 +1,456 @@ +"""T07 integration tests: run_ingest on a mini-corpus + `caliper ingest` (§14.2, §15). + +Covers the task's acceptance criteria end-to-end with the suite's fakes and a +test-local Fetcher fake (the established test_source.py pattern — no network, +no patch() on internals; monkeypatch only for env/cwd isolation): + +- double-ingest on the mini-corpus yields identical index state (A8/FR-02); +- orphan chunks are removed with the FTS and vec tables kept in sync; +- the §9.4 summary contract holds: key set, fingerprint, source_ref, skip + reasons (`excluded-pattern`, `parse-error: no H1`), batch-bound embed_requests; +- `caliper ingest` prints the summary JSON on stdout (exit 0) and maps a bad + config to the §9 envelope with exit 2 (§9 error-code table). + +The CLI success path runs offline by pre-seeding the corpus cache through the +public fetcher seam (cache hit ⇒ zero network) and using a corpus whose pages +are all excluded or unparseable — zero chunks, zero embed calls, so the +constructed (ollama) backend is never contacted. +""" + +import io +import json +import math +import tarfile +from pathlib import Path + +import pytest +from fakes import FakeEmbeddings +from typer.testing import CliRunner + +from caliper.cli import app +from caliper.config import CaliperConfig, ChunkingConfig, fingerprint, fp8 +from caliper.db import connect, get_ingest_run +from caliper.ingest import DB_ENV_VAR, IngestSummary, SkippedPage, run_ingest +from caliper.ingest.source import ( + CACHE_DIR_ENV_VAR, + SourceError, + fetch_corpus, + format_source_ref, + page_to_url, +) +from caliper.providers.base import EMBEDDING_DIMENSIONS + +# --- fixture corpus + seams ------------------------------------------------------------ + +FIXED_SHA_A = "9f3ab12e4d5c6b7a8f9e0d1c2b3a495867766554" +FIXED_SHA_B = "0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e" +ROOT_NAME = f"azure-docs-{FIXED_SHA_A[:7]}" +COMMITS_URL = "https://api.github.com/repos/MicrosoftDocs/azure-docs/commits/main" + + +def _codeload(sha: str) -> str: + return f"https://codeload.github.com/MicrosoftDocs/azure-docs/tar.gz/{sha}" + + +#: 6 markdown files (§15's scaled fixture): 4 discovered (1 unparseable) and +#: 2 excluded (`_` prefix, `/includes/` segment). The three parseable pages +#: each merge into exactly one chunk under the default 800-token heading unit. +MINI_CORPUS: dict[str, str] = { + "articles/azure-functions/durable-functions.md": ( + "# Durable Functions\n\n" + "Durable intro text.\n\n" + "## Orchestrations\n\n" + "Orchestrations coordinate agent activity.\n\n" + "## Timers\n\n" + "Timers schedule durable work.\n" + ), + "articles/azure-functions/timer-trigger.md": ( + "# Timer Trigger\n\nTimer intro text.\n\n## Usage\n\nUsage notes for the timer trigger.\n" + ), + "articles/service-bus-messaging/queues.md": ( + "# Service Bus queues\n\n" + "Queue intro text.\n\n" + "## Peek\n\n" + "Peek at messages without locking.\n" + ), + "articles/azure-functions/broken.md": "no heading anywhere in here\n", + "articles/azure-functions/_shared.md": "# Shared\n\nunderscore-excluded.\n", + "articles/azure-functions/includes/snip.md": "# Snip\n\nincludes-excluded.\n", +} + +#: v2 of the mini-corpus: queues.md disappeared upstream, timer-trigger.md +#: gained a section (its single chunk changes), durable-functions.md is +#: untouched, plus a brand-new page. +MINI_CORPUS_V2: dict[str, str] = { + "articles/azure-functions/durable-functions.md": MINI_CORPUS[ + "articles/azure-functions/durable-functions.md" + ], + "articles/azure-functions/timer-trigger.md": ( + "# Timer Trigger\n\n" + "Timer intro text.\n\n" + "## Usage\n\n" + "Usage notes for the timer trigger.\n\n" + "## Retry\n\n" + "Retry policy notes.\n" + ), + "articles/azure-functions/bindings.md": "# Bindings\n\nBinding intro text.\n", + "articles/azure-functions/broken.md": MINI_CORPUS["articles/azure-functions/broken.md"], + "articles/azure-functions/_shared.md": MINI_CORPUS["articles/azure-functions/_shared.md"], + "articles/azure-functions/includes/snip.md": MINI_CORPUS[ + "articles/azure-functions/includes/snip.md" + ], + # queues.md disappeared upstream, but the tree itself must still exist + # (discover_pages raises SourceError when either article tree is missing). + "articles/service-bus-messaging/includes/snip.md": "# Snip\n\nx\n", +} + +#: A corpus with no parseable page at all: the CLI success path can run it +#: offline (zero chunks ⇒ zero embed calls ⇒ no backend contact). +SKIP_ONLY_CORPUS: dict[str, str] = { + "articles/azure-functions/broken.md": MINI_CORPUS["articles/azure-functions/broken.md"], + "articles/azure-functions/_shared.md": MINI_CORPUS["articles/azure-functions/_shared.md"], + "articles/service-bus-messaging/includes/snip.md": "# Snip\n\nx\n", +} + +_SUMMARY_CONTRACT_KEYS = { + "fingerprint", + "source_ref", + "pages_ok", + "pages_skipped", + "skipped", + "chunks_written", + "chunks_removed", + "embed_requests", + "elapsed_s", +} + + +def _expected_skips() -> list[SkippedPage]: + """The expected §9.4 skip list for MINI_CORPUS (sorted by path).""" + return [ + SkippedPage(path="articles/azure-functions/_shared.md", reason="excluded-pattern"), + SkippedPage(path="articles/azure-functions/broken.md", reason="parse-error: no H1"), + SkippedPage(path="articles/azure-functions/includes/snip.md", reason="excluded-pattern"), + ] + + +def _tarball(pages: dict[str, str]) -> bytes: + """A real .tar.gz shaped like the upstream one (one top-level + `azure-docs-/` directory, which run_ingest strips).""" + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:gz") as tar: + for rel_path, content in pages.items(): + data = content.encode("utf-8") + info = tarfile.TarInfo(name=f"{ROOT_NAME}/{rel_path}") + info.size = len(data) + info.mtime = 0 + tar.addfile(info, io.BytesIO(data)) + return buffer.getvalue() + + +class FakeFetcher: + """Serves the commits-API JSON for FIXED_SHA_A and its tarball; records + every URL so tests can assert cache hits cause zero fetches.""" + + def __init__(self, tarball_bytes: bytes) -> None: + self._tarball = tarball_bytes + self.calls: list[str] = [] + + def __call__(self, url: str) -> bytes: + self.calls.append(url) + if url == COMMITS_URL: + return json.dumps({"sha": FIXED_SHA_A}).encode("utf-8") + if url == _codeload(FIXED_SHA_A): + return self._tarball + raise AssertionError(f"unexpected url {url}") + + +class TwoShaFetcher: + """Serves sha A then sha B from the same instance (commits API), each with + its own tarball — lets a `refresh=True` re-ingest present a changed corpus + into the same database, exactly the FR-02 re-index scenario.""" + + def __init__(self, tarball_a: bytes, tarball_b: bytes) -> None: + self._tarballs = {FIXED_SHA_A: tarball_a, FIXED_SHA_B: tarball_b} + self._pending = [FIXED_SHA_A, FIXED_SHA_B] + self._last: str | None = None + self.calls: list[str] = [] + + def __call__(self, url: str) -> bytes: + self.calls.append(url) + if url == COMMITS_URL: + assert self._pending, "TwoShaFetcher: shas exhausted" + self._last = self._pending.pop(0) + return json.dumps({"sha": self._last}).encode("utf-8") + if self._last is not None and url == _codeload(self._last): + return self._tarballs[self._last] + raise AssertionError(f"unexpected url {url}") + + +@pytest.fixture() +def corpus_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path: + """§11.2 paths pointed at tmp_path, cwd pinned there for the CLI tests + (monkeypatch for env/cwd isolation only, mirroring test_source.py).""" + monkeypatch.setenv(CACHE_DIR_ENV_VAR, str(tmp_path / "cache")) + monkeypatch.setenv(DB_ENV_VAR, str(tmp_path / "caliper.db")) + monkeypatch.chdir(tmp_path) + return tmp_path + + +def _index_state(db_path: Path, suffix: str) -> list[tuple[object, ...]]: + """Full chunk-table content, ordered — the FR-02 idempotency snapshot.""" + conn = connect(db_path) + try: + return [ + tuple(row) + for row in conn.execute( + "SELECT chunk_id, page_url, heading_path, body, body_tokens, chunk_hash, ordinal " + f"FROM chunks_{suffix} ORDER BY chunk_id" + ) + ] + finally: + conn.close() + + +def _table_count(db_path: Path, table: str) -> int: + """Row count of a fully named table (`chunks_`, `chunks__vec`, …).""" + conn = connect(db_path) + try: + row = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone() + assert row is not None + return int(row[0]) + finally: + conn.close() + + +# --- first ingest: summary contract + index state -------------------------------------- + + +def test_first_ingest_matches_summary_contract(corpus_env: Path) -> None: + cfg = CaliperConfig() + summary = run_ingest( + cfg, fetcher=FakeFetcher(_tarball(MINI_CORPUS)), embeddings=FakeEmbeddings() + ) + + assert summary.fingerprint == fp8(cfg) + assert summary.source_ref == format_source_ref(FIXED_SHA_A) + assert summary.pages_ok == 3 + assert summary.pages_skipped == 3 + assert summary.skipped == _expected_skips() + assert summary.chunks_written == 3 + assert summary.chunks_removed == 0 + assert summary.embed_requests == 1 # 3 chunks ⇒ one ≤100-text batch + assert summary.elapsed_s >= 0.0 + assert set(summary.as_dict()) == _SUMMARY_CONTRACT_KEYS + + +def test_first_ingest_writes_index_and_run_record(corpus_env: Path) -> None: + cfg = CaliperConfig() + suffix = fp8(cfg) + db_path = corpus_env / "caliper.db" + run_ingest(cfg, fetcher=FakeFetcher(_tarball(MINI_CORPUS)), embeddings=FakeEmbeddings()) + + conn = connect(db_path) + try: + rows = conn.execute( + f"SELECT page_url, heading_path, ordinal FROM chunks_{suffix} " + "ORDER BY page_url, ordinal" + ).fetchall() + record = get_ingest_run(conn, fingerprint(cfg)) + finally: + conn.close() + + assert [row[0] for row in rows] == [ + page_to_url("articles/azure-functions/durable-functions.md"), + page_to_url("articles/azure-functions/timer-trigger.md"), + page_to_url("articles/service-bus-messaging/queues.md"), + ] + # The trio stays in sync on a fresh ingest: chunks == vec rows == FTS rows. + assert _table_count(db_path, f"chunks_{suffix}") == 3 + assert _table_count(db_path, f"chunks_{suffix}_vec") == 3 + assert _table_count(db_path, f"chunks_{suffix}_fts") == 3 + assert record is not None + assert record.finished_at is not None + assert record.pages_ok == 3 + assert record.pages_skipped == 3 + assert json.loads(record.summary_json)["skipped"] == [ + {"path": skip.path, "reason": skip.reason} for skip in _expected_skips() + ] + + +def test_embeddings_are_stored_per_chunk(corpus_env: Path) -> None: + cfg = CaliperConfig() + suffix = fp8(cfg) + db_path = corpus_env / "caliper.db" + run_ingest(cfg, fetcher=FakeFetcher(_tarball(MINI_CORPUS)), embeddings=FakeEmbeddings()) + + conn = connect(db_path) + try: + rows = conn.execute(f"SELECT embedding FROM chunks_{suffix}_vec ORDER BY rowid").fetchall() + finally: + conn.close() + + assert len(rows) == 3 + # Stored as serialized float32: 768 dims × 4 bytes. + assert len(rows[0][0]) == EMBEDDING_DIMENSIONS * 4 + + +# --- FR-02/A8: idempotent double-ingest ------------------------------------------------- + + +def test_double_ingest_yields_identical_index_and_stable_counts(corpus_env: Path) -> None: + cfg = CaliperConfig() + suffix = fp8(cfg) + db_path = corpus_env / "caliper.db" + embeddings = FakeEmbeddings() + fetcher = FakeFetcher(_tarball(MINI_CORPUS)) + + summary1 = run_ingest(cfg, fetcher=fetcher, embeddings=embeddings) + state1 = _index_state(db_path, suffix) + embed_calls_after_run1 = len(embeddings.calls) + fetches_after_run1 = len(fetcher.calls) + + summary2: IngestSummary = run_ingest(cfg, fetcher=fetcher, embeddings=embeddings) + state2 = _index_state(db_path, suffix) + + assert summary1.chunks_written == 3 + assert summary2.chunks_written == 0 + assert summary2.chunks_removed == 0 + assert summary2.embed_requests == 0 + assert summary2.pages_ok == summary1.pages_ok + assert summary2.pages_skipped == summary1.pages_skipped + assert state2 == state1 # identical index state (FR-02) + assert len(embeddings.calls) == embed_calls_after_run1 # nothing re-embedded + assert len(fetcher.calls) == fetches_after_run1 # cache hit, zero refetch + + +# --- orphan removal (pages disappeared / changed upstream) ------------------------------- + + +def test_orphans_removed_and_tables_stay_in_sync(corpus_env: Path) -> None: + cfg = CaliperConfig() + suffix = fp8(cfg) + db_path = corpus_env / "caliper.db" + timer_url = page_to_url("articles/azure-functions/timer-trigger.md") + fetcher = TwoShaFetcher(_tarball(MINI_CORPUS), _tarball(MINI_CORPUS_V2)) + + run_ingest(cfg, fetcher=fetcher, embeddings=FakeEmbeddings()) + state1 = _index_state(db_path, suffix) + old_timer_hashes = {row[5] for row in state1 if row[1] == timer_url} + + # refresh=True presents the changed corpus (sha B) to the same database. + summary2 = run_ingest(cfg, refresh=True, fetcher=fetcher, embeddings=FakeEmbeddings()) + state2 = _index_state(db_path, suffix) + + # queues.md disappeared (1 orphan) and timer-trigger.md changed (old chunk + # orphaned, new inserted); durable-functions.md is untouched (zero churn). + assert summary2.chunks_removed == 2 + assert summary2.chunks_written == 2 # new timer chunk + bindings.md + page_urls = {row[1] for row in state2} + assert page_to_url("articles/service-bus-messaging/queues.md") not in page_urls + new_timer_hashes = {row[5] for row in state2 if row[1] == timer_url} + assert old_timer_hashes.isdisjoint(new_timer_hashes) + assert len(new_timer_hashes) == 1 + assert _table_count(db_path, f"chunks_{suffix}") == 3 + assert _table_count(db_path, f"chunks_{suffix}_vec") == 3 + assert _table_count(db_path, f"chunks_{suffix}_fts") == 3 + # Only the new/changed chunks were embedded (2 texts ⇒ one batch). + assert summary2.embed_requests == 1 + + +def test_untouched_page_keeps_its_chunks_and_ids(corpus_env: Path) -> None: + cfg = CaliperConfig() + suffix = fp8(cfg) + db_path = corpus_env / "caliper.db" + durable_url = page_to_url("articles/azure-functions/durable-functions.md") + fetcher = TwoShaFetcher(_tarball(MINI_CORPUS), _tarball(MINI_CORPUS_V2)) + + run_ingest(cfg, fetcher=fetcher, embeddings=FakeEmbeddings()) + state1 = _index_state(db_path, suffix) + run_ingest(cfg, refresh=True, fetcher=fetcher, embeddings=FakeEmbeddings()) + state2 = _index_state(db_path, suffix) + + durable1 = [row for row in state1 if row[1] == durable_url] + durable2 = [row for row in state2 if row[1] == durable_url] + assert durable1 == durable2 # same chunk_id: the row was never touched + + +# --- embedding batch bound (§7.4: ≤100 texts/request) ------------------------------------ + + +def test_embed_requests_respect_the_batch_cap(corpus_env: Path) -> None: + cfg = CaliperConfig(chunking=ChunkingConfig(size_tokens=1)) + # size_tokens=1 forbids merging, so every H2 section becomes its own chunk: + # 120 sections ⇒ >100 chunks ⇒ two batches. + sections = "".join(f"## Section {index:03d}\n\nBody {index} text.\n\n" for index in range(120)) + pages = { + "articles/azure-functions/many-sections.md": f"# Many sections\n\n{sections}", + # discover_pages requires both article trees to exist (§7.4/OQ3). + "articles/service-bus-messaging/queues.md": "# Queues\n\nQueue text.\n", + } + embeddings = FakeEmbeddings() + + summary = run_ingest(cfg, fetcher=FakeFetcher(_tarball(pages)), embeddings=embeddings) + + assert summary.chunks_written >= 101 + assert summary.embed_requests == math.ceil(summary.chunks_written / 100) + assert all(len(call.texts) <= 100 for call in embeddings.calls) + assert sum(len(call.texts) for call in embeddings.calls) == summary.chunks_written + assert all(call.task_type == "document" for call in embeddings.calls) + + +# --- loud failure on a broken corpus layout ---------------------------------------------- + + +def test_unexpected_tarball_layout_raises_source_error(corpus_env: Path) -> None: + cfg = CaliperConfig() + bad_layout = {"wrong-tree/foo.md": "# Foo\n\nbody\n"} + with pytest.raises(SourceError, match="articles"): + run_ingest(cfg, fetcher=FakeFetcher(_tarball(bad_layout)), embeddings=FakeEmbeddings()) + + +# --- `caliper ingest` (§9.1): JSON on stdout, §9 envelope on error ------------------------ + + +def _write_cli_configs(root: Path) -> None: + """Minimal (all-defaults) user config + v1 preset, per §11.2's paths.""" + configs = root / "configs" + configs.mkdir(exist_ok=True) + (configs / "v1.toml").write_text("", encoding="utf-8") + (configs / "caliper.sample.toml").write_text("", encoding="utf-8") + + +def test_cli_ingest_prints_summary_json(corpus_env: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("CALIPER_PROVIDER", "ollama") # offline transport build + _write_cli_configs(corpus_env) + cfg = CaliperConfig() + fetch_corpus(cfg, fetcher=FakeFetcher(_tarball(SKIP_ONLY_CORPUS))) # seed cache + + result = CliRunner().invoke(app, ["ingest", "--version", "v1"]) + + assert result.exit_code == 0 + payload = json.loads(result.output) + assert set(payload) == _SUMMARY_CONTRACT_KEYS + assert payload["fingerprint"] == fp8(cfg) + assert payload["source_ref"] == format_source_ref(FIXED_SHA_A) + assert payload["pages_ok"] == 0 # nothing parseable — offline by construction + assert payload["pages_skipped"] == 3 + assert payload["chunks_written"] == 0 + assert payload["chunks_removed"] == 0 + assert payload["embed_requests"] == 0 + + +def test_cli_ingest_config_error_maps_to_envelope( + corpus_env: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _write_cli_configs(corpus_env) + bad = corpus_env / "bad.toml" + bad.write_text("chunking = { size_tokens = 999999 }\n", encoding="utf-8") + monkeypatch.setenv("CALIPER_CONFIG", str(bad)) + + result = CliRunner().invoke(app, ["ingest"]) + + assert result.exit_code == 2 + envelope = json.loads(result.stderr) + assert envelope["error"]["code"] == "config_invalid" + assert "chunking.size_tokens" in envelope["error"]["message"] diff --git a/tests/unit/test_ingest_hash.py b/tests/unit/test_ingest_hash.py new file mode 100644 index 0000000..392b8b9 --- /dev/null +++ b/tests/unit/test_ingest_hash.py @@ -0,0 +1,85 @@ +"""Unit tests: ingest/__init__.py — chunk_hash and the §9.4 summary shape (§7.4, §15). + +The hash composition is a frozen contract: T08's resume logic re-derives the +same hashes and the UNIQUE `chunk_hash` column makes re-ingest idempotent +(FR-02). run_ingest itself is covered through its public interface in +tests/integration/test_ingest.py (§15: components tested through their public +interfaces). +""" + +import json + +import pytest + +from caliper.ingest import IngestSummary, SkippedPage, chunk_hash + +BODY = "Orchestrators coordinate activity.\n\nTimers schedule work.\n" +URL = "https://learn.microsoft.com/en-us/azure/azure-functions/durable-functions" +HEADING = "Durable Functions > Timers" + + +def test_chunk_hash_is_deterministic() -> None: + assert chunk_hash(URL, HEADING, BODY) == chunk_hash(URL, HEADING, BODY) + + +@pytest.mark.parametrize( + ("url", "heading", "body"), + [ + (URL + "-x", HEADING, BODY), # different url + (URL, HEADING + " > Deep", BODY), # different heading path + (URL, HEADING, BODY + "extra"), # different body + ], +) +def test_chunk_hash_changes_on_any_field_change(url: str, heading: str, body: str) -> None: + assert chunk_hash(url, heading, body) != chunk_hash(URL, HEADING, BODY) + + +def test_chunk_hash_normalizes_line_endings_and_trailing_whitespace() -> None: + """The normalization keeps hashes stable against line-ending and trailing + whitespace churn (bodies themselves stay verbatim in the index).""" + churned = "Orchestrators coordinate activity. \r\n\r\nTimers schedule work.\r\n \n" + assert chunk_hash(URL, HEADING, churned) == chunk_hash(URL, HEADING, BODY) + + +def test_chunk_hash_separates_fields() -> None: + """NUL separators: no re-split of (body, url, heading) may collide with a + different split of the same characters.""" + a = chunk_hash("https://x", "b", "c") + b = chunk_hash("https://x", "bc", "") + c = chunk_hash("https://xb", "c", "") + assert len({a, b, c}) == 3 + + +def test_summary_as_dict_matches_the_9_4_contract() -> None: + summary = IngestSummary( + fingerprint="a1b2c3d4", + source_ref="main@9f3ab12", + pages_ok=297, + pages_skipped=2, + skipped=[ + SkippedPage(path="articles/azure-functions/_footer.md", reason="excluded-pattern"), + SkippedPage(path="articles/azure-functions/broken.md", reason="parse-error: no H1"), + ], + chunks_written=3108, + chunks_removed=12, + embed_requests=34, + elapsed_s=2140.0004, + ) + data = summary.as_dict() + assert list(data) == [ # §9.4 key order + "fingerprint", + "source_ref", + "pages_ok", + "pages_skipped", + "skipped", + "chunks_written", + "chunks_removed", + "embed_requests", + "elapsed_s", + ] + assert data["skipped"] == [ + {"path": "articles/azure-functions/_footer.md", "reason": "excluded-pattern"}, + {"path": "articles/azure-functions/broken.md", "reason": "parse-error: no H1"}, + ] + assert data["elapsed_s"] == 2140.0 # rounded for the printed JSON + json.dumps(data) # the contract body must serialize cleanly From 468b4fde3fac66954da67e9b9e03464ceca84d5e Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Tue, 17 Nov 2026 22:12:52 +0530 Subject: [PATCH 2/2] docs(tasks): track t07 doing with verification and decisions --- docs/TASKS.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/TASKS.md b/docs/TASKS.md index b869e41..30dd69b 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -23,7 +23,11 @@ Statuses: ✅ done · 🔄 doing · ⬜ remaining · ✂️ cut (stretch only, p ## Doing -_(none — next up: **T07** (needs T03+T06, both ✅ — P1 critical path), **T11** (needs T09 ✅), **T13** (needs T03 ✅); **T08** unblocks after T07; **T10** ✅ done — parallelizable per §14.3)_ +| ID | Branch | PR | Verification | +|---|---|---|---| +| T07 | `arch/caliper/t07` | #12 | `uv run pytest` — 240 passed (223 prior + 17 new: chunk-hash/§9.4-shape unit tests; mini-corpus integration covering double-ingest identity, orphan removal with FTS/vec sync, ≤100 batch bound, tarball-layout failure, and `caliper ingest` JSON stdout + config-error envelope exit 2); `ruff check` + `ruff format --check` + `mypy` strict clean; `caliper ingest --help` renders. | + +_(PR #12 open — T07 moves to Done only at merge. Next up after T07: **T08** (needs T07 ✅ on merge), **T11** (needs T09 ✅), **T13** (needs T03 ✅))_ ## Remaining @@ -93,7 +97,13 @@ _(none — next up: **T07** (needs T03+T06, both ✅ — P1 critical path), **T1 ### Decisions recorded during the build -- **T06 — token estimator frozen: `tokens = ceil(len(text) / 4)`** (user decision, plan session 2026-11-17): chars-per-token rule of thumb; zero deps, deterministic; documented in `chunkers.py`'s docstring (`CHARS_PER_TOKEN = 4`). Binds T07 (chunk bounds), T16 (real-corpus chunk counts), and all token-bound tests. ⚠ Deviation from §14.4: the binding §7.4 text still says "1,900 tokens" without naming the estimator — fold the estimator sentence into §7.4 via the next contract-touching PR (T07) rather than a dedicated doc PR. +- **T07 — public API frozen for T08/T22:** `run_ingest(cfg, *, refresh=False, fetcher=None, embeddings=None) -> IngestSummary` in `ingest/__init__.py`; `IngestSummary.as_dict()` renders the §9.4 body in contract key order; `chunk_hash(page_url, heading_path, body)` is public — T08's resume logic re-derives the same hashes. Seams follow the established injection pattern (`fetcher` → `source.Fetcher`, `embeddings` → `EmbeddingBackend` defaulting to `get_embeddings(cfg)`); the DB path is read from `CALIPER_DB` directly (source.py's `CALIPER_CACHE_DIR` precedent — no `config.py` edit). `cli.py` owns only the `ingest` subcommand + the §9 envelope/exit-code mapping helper (shared by later subcommands). +- **T07 — §9.4 semantics decided:** `fingerprint` in the summary is the 8-hex `fp8` (the contract example is 8 chars; the full 64-hex fingerprint is stored in `ingest_runs`/`config_fingerprints`); `chunks_written`/`chunks_removed` are per-run action counts — an unchanged re-ingest reports 0/0 and embeds nothing — while A8/FR-02's "double-ingest yields identical counts" is asserted on identical index state plus stable `pages_*` fields; `pages_ok` counts discovered-and-parsed pages, `pages_skipped` = excluded-pattern + parse-error pages (the two sum to every `.md` under the trees). Binds T08 (resume must keep the counts consistent) and T16 (real-corpus run record). +- **T07 — chunk_hash normalization binding for T08:** normalized body = LF lines with per-line trailing and outer whitespace stripped; body/url/heading NUL-joined before SHA-256 (`chunk_hash` docstring). §7.4 updated in this PR — T06's recorded deviation below is paid off here. +- **T07 — embedding boundary with T08:** inserted chunks embed in batches of ≤100 via `backend.embed_documents`; the bounded 429 backoff is the backends' own (`call_with_backoff` wraps every embed call inside providers, T04) — deliberately NOT re-wrapped in ingest. Only inserted chunks are embedded; repairing chunks left without vectors by an interrupted run is T08's checkpoint/resume scope. All writes commit once at the end (a crash leaves the previous complete state; T08 splits this with per-batch checkpoints). +- **T07 — `ingest_runs` lifecycle:** `upsert_ingest_run` + `finish_ingest_run` run at completion (§10.3's final step), so a crashed ingest leaves the prior completed row for the fingerprint intact; `started_at`/`finished_at` span the actual run. +- **T07 — CLI edge decisions:** excluded-pattern skips are reported by complement-scanning the trees against `discover_pages`' output (source.py stays untouched/frozen); `SourceError`/`DbError` map to `provider_unavailable` (exit 4) — §9's code table has no local-infrastructure code, smallest choice; the command reads the user config from `CALIPER_CONFIG` (default `configs/caliper.sample.toml`, §11.2) merged over `configs/v.toml`. +- **T06 — token estimator frozen: `tokens = ceil(len(text) / 4)`** (user decision, plan session 2026-11-17): chars-per-token rule of thumb; zero deps, deterministic; documented in `chunkers.py`'s docstring (`CHARS_PER_TOKEN = 4`). Binds T07 (chunk bounds), T16 (real-corpus chunk counts), and all token-bound tests. ✅ Deviation from §14.4 paid off in T07's PR: §7.4 now names the estimator. - **T06 — cap mechanics:** every chunk ≤ 1,900 tokens (`MAX_CHUNK_TOKENS`); split, never truncated. Heading unit: H2-boundary groups (H3+ attach to their H2; intro under the title is its own group), greedy neighbor merge up to `size_tokens`; a single section > `size_tokens` is emitted alone and whole up to the cap (the §14.2 "single section exceeds it" exception); only beyond 1,900 is it split into sequential whitespace-aligned windows of ≤ `min(size_tokens, 1900)` tokens, no overlap. Fixed unit: window body budget = `size_tokens` − prefix tokens (prefix counted), advance = window length − `overlap_tokens`; cuts prefer the latest line/whitespace break, hard cuts last resort. - **T06 — public API frozen for T07:** `parse_page(rel_path, text) -> ParsedPage` (`rel_path`, `page_url` via T05's `page_to_url`, `title` = first ATX H1, `segments: list[BodySegment]`); `BodySegment(heading_path, level, body)`; `ParseError(rel_path, reason="no H1")`; `Chunk(page_url, heading_path, body, body_tokens, ordinal)` (field order mirrors `db.ChunkRow` minus chunk_hash — T07 builds rows positionally); `Chunker` Protocol with `chunk_page(page) -> list[Chunk]`; `make_chunker(cfg)`; `count_tokens`. parse.py does no file I/O — T07 owns reads + the tarball top-dir strip. H1-only pages are `pages_ok` with zero chunks (not skips); skips surface as `f"parse-error: {exc.reason}"`. - **T06 — micro-decisions documented in module docstrings:** H4+ headings extend the heading-path pattern (not truncated at H3); fixed-window chunk heading path = path as of the window's first character; heading unit ignores `overlap_tokens` (warning logged if set > 0).