Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `"<page title> > <H2> > <H3>"` 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: <url>\nHeading: <heading path>`. 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: <url>\nHeading: <heading path>`. 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
Expand Down
14 changes: 12 additions & 2 deletions docs/TASKS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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<version>.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).
Expand Down
101 changes: 97 additions & 4 deletions src/caliper/cli.py
Original file line number Diff line number Diff line change
@@ -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__":
Expand Down
Loading
Loading