05.8 Metadata Design

RetrievalLesson 8 of 1014,367 words10 parts
Module 05 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

By the time 05.6 finishes (and 05.7, if you took that optional lesson), your corpus is a pile of clean, well-cut chunks. This lesson is about the other half of every stored record: the metadata — the structured fields that say what a chunk is, where it came from, who may see it, when it was true, and how it was produced. Done well, metadata is what lets a retrieval system answer "only the 2025 contracts", enforce permissions, cite a page number, debug a bad answer, and update one paragraph without re-embedding a whole document. Done badly, it is the silent cause of most "why did it retrieve that?" mysteries. This lesson designs the schema, the identifiers, the dates, the access rules, the enrichment steps and the quality checks that make metadata a first-class part of the pipeline — and hands you runnable models and validators to take into 05.9.

What you'll learn

  • Why metadata is a first-class feature of an AI data pipeline, and the metadata-vs-text decision: what belongs in the embedded text and what belongs in a filterable field
  • A complete layered metadata schema in Pydantic — document-level, section-level, chunk-level, lineage and quality fields — that extends the Chunk model of 05.6
  • How to design IDs and keys: stable, deterministic, content-addressed chunk IDs that survive document edits, slugs vs UUIDs, and composite keys
  • The five dates every document needs (created_at, modified_at, effective_date, ingested_at, valid_until), time-zone handling, "as of" queries and superseded documents
  • Access-control metadata: ACLs per document and chunk, propagating permissions from source systems, filtering before retrieval, and multi-tenant isolation patterns
  • How to choose filterable vs searchable vs display-only fields, and what vector stores actually accept (types, flatness, size limits, index costs)
  • Enrichment: deterministic enrichment with rules and spaCy, LLM enrichment with schema-constrained output and controlled vocabularies, and how to version it against drift
  • What citations and provenance need to show a user, and how to trace a bad answer back through lineage to the parse
  • Metadata quality: validation rules, completeness metrics, schema evolution without re-embedding, and privacy minimisation

What you don't need

  • API keys. Every code sample runs locally: the Pydantic models need only pydantic, the ID/date/ACL/audit samples are pure standard library, and the one LLM-shaped call uses an injectable function you can fake. If you want a real model call later, the mechanics are 03.4 and 03.9 — this lesson doesn't re-teach them.
  • Chunking internals. 05.6 and 05.7 own how chunks are cut; this lesson consumes their output (chunk_index, offsets, page numbers).
  • Embedding models and vector-database internals. Module 06 owns those; here you only learn what metadata the store accepts and why.
  • Pipeline orchestration. 05.9 owns manifests, incremental updates and reindexing; this lesson gives it the ID and versioning scheme those depend on.

Setup

Module 05's lessons can share the data-pipeline uv project created in 05.1 together with the data/ layout for the running corpus; each lesson also works in a project of its own. If you are starting fresh, uv init data-engineering --bare --python 3.13 && cd data-engineering (see 03.1, Part 4). This lesson needs Pydantic, plus two optional helpers:

bash
uv add pydantic
# or: pip install pydantic

# optional — only for the spaCy entity example (7.2) and messy date parsing (4.2)
uv add spacy python-dateutil
uv run python -m spacy download en_core_web_sm

The samples were checked against pydantic 2.14.3, the version the whole path standardises on (the latest 2.14.x patch on PyPI as of November 2026; the API used here is the same across 2.14.x), spacy 3.8.18 (for the entity example in 7.2) and python-dateutil 3.0.0 (released 21 October 2026), the version the date examples in 4.2 were checked against. A plain uv add installs the newest releases, and python-dateutil 4.0.0 followed on 1 November 2026, so expect to get 4.x. Its release notes list Python 3.11+ as the new minimum, the removal of six, and a stricter parser.isoparse, and say nothing about parser.parse, which is the call used here; the examples in 4.2 were not re-run on 4.0.0, so if a date comes out differently, check the changelog (release notes read on GitHub, 11 November 2026). No .env file or keys are needed for anything in this lesson.


What you must be able to do after this lesson#

  • Decide what belongs in embedded text and what in metadata
  • Define a layered metadata schema in Pydantic
  • Create stable, deterministic chunk IDs
  • Store the dates a document needs and query as of a date
  • Filter by access control before retrieval

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Just filter the results after the vector search." 5.3 Filter before you rank
"Put the page number in the chunk text so the model can cite it." 1.3 The metadata-vs-text decision
"Give every chunk a UUID at ingest time." 3.1 What an ID must do and 3.3 Content-addressed chunk IDs
"Which date do we filter on — created or modified?" 4.1 Five dates, five questions
"The policy says it's effective 1 June, but search shows the old one." 4.3 "As of" queries and superseded documents
"Users in different companies share one index." 5.4 Multi-tenant isolation patterns
"Add a topics field and let the LLM fill it." 7.4 Controlled vocabularies and LLM tags
"The upsert failed: metadata value null is not supported." 6.3 What the store actually accepts
"Why did re-ingesting one paragraph re-embed the whole PDF?" 3.3 Content-addressed chunk IDs
"How do we show which page a quote came from?" Part 8: Citations and provenance
"We added a field — do we have to re-embed everything?" 9.2 Schema evolution without re-embedding

Part 1: What metadata is for#

1.1 A stored chunk is not just text#

The naive picture of a retrieval pipeline is text → embedding → vector store → query → chunks. In production, every record that comes back is really two things glued together:

flowchart LR
    subgraph rec ["One stored record (one per chunk)"]
        T["chunk text<br/>(embedded + searched)"]
        M["metadata<br/>(filtered + displayed + traced)"]
    end
    T --> E["embedding model<br/>(Module 06)"]
    M --> F["metadata filters<br/>(this lesson)"]
    M --> C["citation UI"]
    M --> D["debugging / eval"]

The text answers "what does this chunk say?" — it is what gets embedded and what the model reads. The metadata answers everything else: which document, which page, which version, who may see it, when it was true, how it was produced. Neither substitutes for the other: you cannot embed "page 4 of the returns policy" into a vector and retrieve it reliably, and you cannot filter a vector on text it was never given.

1.2 The six jobs metadata does#

Every field you add should serve at least one of these jobs. If it serves none, it is probably payload you are paying to store and index for nothing.

Job What it enables Example fields
Filtering / selection Narrow candidates before ranking, so top-k isn't wasted on irrelevant or inaccessible chunks doc_type, effective_year, language, tags, tenant_id
Access control Decide who may retrieve a chunk at all acl, confidentiality, tenant_id
Freshness and versioning Answer "the policy as of March", keep old and new versions straight effective_date, valid_until, version, superseded_by
Citation Show the user where an answer came from title, source_uri, page_start, section_path, regions
Debugging and evaluation Trace a bad answer back to its parse, chunk and source chunk_id, lineage.*, quality.*
Enrichment hooks Feed retrieval and ranking with extra signals topics, summary, keywords, hypothetical questions

Notice that the same field often serves two jobs — doc_type filters and powers per-type eval slices; effective_date filters and drives freshness ranking. Design fields once, for all their jobs.

1.3 The metadata-vs-text decision#

Every piece of information about a chunk has exactly two possible channels, and putting it in the wrong one is a classic source of bugs:

  • The embedded/searched text — the string that gets embedded, BM25-indexed and shown to the model. Good for meaning: things a user's question would semantically match ("how do I return shoes?" should match text about returns).
  • A structured field — a typed value that code filters, sorts, displays or joins on. Good for facts with exact answers: dates, IDs, page numbers, permissions, enums.

The test: would a user express this as a constraint ("only", "after", "from", "tagged") or as part of the question itself? Constraints become fields; question content becomes text.

Information Right channel Why the other channel fails
Document title ("Returns Policy") Both: field for display/filter, and usually prepended to the embedded text as a breadcrumb (05.6) Field-only: the model never sees the topic. Text-only: can't filter or display it
Effective date (2026-01-01) Field (ISO timestamp); may also appear in text for readability Text-only: "contracts effective in Q1" can't be filtered; embedding a raw date adds noise
Page number / bounding box Field only In text it pollutes the embedding and the model's reading; nobody searches "4"
ACL / confidentiality Field only, and never sent to the model In text it wastes tokens, pollutes semantics, and can leak into citations or logs
Author name Field (filterable: "from this author"), optionally in text Text-only: exact-match author queries are unreliable
Topic tags (returns, billing) Field (controlled vocabulary), plus the underlying words stay in text Free-text "tags" in the prompt can't be filtered reliably
A summary of the chunk Enrichment field; may also be embedded instead of the raw text (05.7 covers contextual/summary indexing) Putting long summaries in the stored text duplicates content and confuses citations

1.4 Metadata is the contract between stages#

Look at where each layer of metadata is produced:

Layer Produced by Consumed by
source_uri, source_hash fetch/crawl stage (05.1, 05.3) change detection (05.9)
page_start, regions, parse_warnings parsers (05.2, 05.4) citations, quality gates
content_hash, language cleaning/normalisation (05.5) dedup, chunk IDs, routing
chunk_index, section_path, offsets, token_count chunkers (05.6, 05.7) retrieval windows, display
topics, summary, keywords enrichment (Part 7) filters, ranking, prompts
everything you, now the vector store, the citation UI, the eval harness

If any stage produces a field inconsistently — a page_start that is sometimes 0-based and sometimes 1-based, a doc_type that is "Contract" in one parser and "contract" in another — every consumer downstream inherits the bug, silently. That is why Part 2 defines the schema once, in code, and Part 9 builds the audit that enforces it.


Part 2: The layered metadata schema#

2.1 Five layers at a glance#

Real corpora need metadata at five different granularities. The trick is that they are not five separate stores — they are five layers of one record, denormalised so each stored chunk carries everything a query or a citation needs without a join.

flowchart TB
    subgraph doc ["DocumentMeta — one per source document"]
        D1["identity: doc_id, slug, tenant_id, source_uri"]
        D2["content: title, author, doc_type, language, tags"]
        D3["dates: created/modified/effective/valid_until/ingested"]
        D4["governance: acl, confidentiality, owner, licence"]
    end
    subgraph sec ["SectionMeta — one per heading section"]
        S1["section_id, heading_path, level, char range"]
    end
    subgraph chk ["ChunkMeta — one per stored chunk"]
        C1["chunk_id, chunk_index, offsets, token_count"]
        C2["page_start/end, regions (bboxes), start_ms/end_ms"]
        C3["prev/next chunk ids, chunk_text_hash"]
        C4["derived: topics, summary, entities, questions"]
    end
    subgraph lin ["Lineage — how it was built"]
        L1["parser/cleaner/chunker/enrichment versions"]
        L2["embedding model, ingestion_run_id, schema_version"]
    end
    subgraph q ["Quality — how good it is"]
        Q1["ocr_confidence, parse_warnings, language_confidence, needs_review"]
    end
    doc --> sec --> chk
    lin -.-> chk
    q -.-> chk
    chk --> store["vector store record<br/>(flat payload, Part 6.3)"]
  • Document-level fields describe the source. Every chunk of a document shares them.
  • Section-level fields describe where inside the document the chunk sits — the heading path a citation or a "table of contents" filter needs.
  • Chunk-level fields describe the retrievable unit itself: its ID, position, page span, neighbours.
  • Lineage records how the record was produced: which parser, cleaner, chunker, enrichment and (later) embedding model, under which pipeline run. This is what turns "the answer was wrong" into "the OCR layer dropped a table on page 4 of contract X, parsed by marker 2.1.0".
  • Quality records how trustworthy the text is: OCR confidence, parse warnings, language confidence, review flags.
  • Derived fields are enrichment output stored on the chunk — topics, summary, entities, generated_title, hypothetical_questions, sentiment (the ChunkDerived model, 2.7). They sit inside ChunkMeta rather than a sixth layer because every chunk carries its own; only the short filterable ones reach the vector-store payload (6.3, 7.6).

2.2 Document-level fields#

These answer "what document is this?" — stable facts about the source, mostly produced before parsing even starts.

Field Type Why it exists
doc_id doc_ + 24 hex Stable identity across content versions (Part 3)
slug string ≤ 80 Human-readable name for URLs and debugging
tenant_id string Isolation boundary; on every record (Part 5)
source_system string Where it came from: filesystem, zendesk, sharepoint, postgres… enables per-source debugging and re-fetch
source_uri string Canonical URI/path — the thing doc_id was hashed from; needed to re-fetch the source
source_id string? The source system's own canonical ID (Confluence page ID, Drive file ID, ticket key) — survives URL changes; source_uri is derived from it at display time (8.2)
title, author string? Display and "from this author" filters
doc_type enum handbook, help_article, ticket, contract, transcript, spreadsheet, policy, email, chat, other — the highest-value filter in most corpora
language ISO 639-1 (+ optional region) Routing, eval slices, tokenizer choice downstream
version int ≥ 1 Business-level revision counter, separate from content_hash
created_at, modified_at datetime? What the source claims; often unreliable — see Part 4
effective_date, valid_until datetime? When the content is in force — the "as of" axis
ingested_at datetime When our pipeline saw it; always known, always UTC
effective_year int? Derived from effective_date at enrichment — the cheap integer range filter behind "contracts in 2025" (6.4); a validator keeps it in sync with the date
content_hash 64-hex SHA-256 of the canonical cleaned text that is fed to the chunker — document identity for dedup
source_hash 64-hex? SHA-256 of the raw source bytes — change detection (05.9)
tags list[str] Normalised, controlled vocabulary (Part 7.4)
owner string? Who is accountable for the document
confidentiality enum public < internal < confidential < restricted — a coarse ACL shortcut
acl list[AclEntry] Fine-grained allow/deny rules (Part 5)
acl_synced_at datetime? When permissions were last re-synced from the source system — staleness is a security signal (5.5)
licence string? Usage terms for the content (copyright, scraping terms)
superseded_by doc_id? Pointer to the replacement version

2.3 Section-level fields#

Sections are the document's own structure — headings the parser recovered (05.2 builds a section tree from outlines and font heuristics; 05.3 gets them from HTML/docx styles). You store them on the chunk, denormalised:

Field Type Why
section_path list[str] ["Billing", "Refunds", "EU customers"] — the breadcrumb; display, filtering by section, and the "prepend title" trick for embeddings
section_id string? Stable ID of the section across re-chunking, if your chunker assigns one

section_path doubles as the citation breadcrumb: a UI can render "Contracts › Vendor MSAs › Termination" without a second lookup.

2.4 Chunk-level fields#

Field Type Why
chunk_id chk_ + 24 hex The primary key everywhere (Part 3)
chunk_index int ≥ 0 Position within the document — ordering and display; deliberately not part of the ID
char_start, char_end int? Offsets into the canonical document text — lets you recover the exact source span
token_count int? Size accounting, cost estimates, eval stratification
page_start, page_end int? 1-based inclusive page span for citations (05.2 owns page numbering conventions — pick one and enforce it)
regions list[TextRegion] Per-page bounding boxes {page, page_label?, coord_space, x0, y0, x1, y1} when the parser produced them — enables highlight overlays; coord_space records the unit (pdf_points, image_px, normalized) so overlays never mix coordinate systems (2.7)
start_ms, end_ms int? Transcript/audio chunks: position in the recording, for citations and seeking (8.1); mutually ordered like char offsets
speaker string? Dominant speaker label on transcript chunks (a chunk spanning turns takes the first or is split by the chunker)
prev_chunk_id, next_chunk_id string? Neighbour pointers for window expansion at query time (05.7)
chunk_text_hash 64-hex Hash of this chunk's text — dedup and integrity checks
derived ChunkDerived? Enrichment output — topics, summary, entities, questions (Part 7); only short filterable fields reach the store payload

2.5 Lineage fields#

Lineage answers "how was this record built?" — the difference between a debugging session and an archaeology dig.

Field Type Why
schema_version int Which version of this metadata schema wrote the record (9.2)
parser_name, parser_version string e.g. pymupdf 2.1.x — parser upgrades change output; you must know which produced a chunk
cleaning_version string Which cleaning pipeline version (05.5) ran
chunker_name, chunker_version string Which chunking strategy and version (05.6) cut it
enrichment_name, enrichment_version, enrichment_model string? Which enrichment step, prompt and model produced tags/summaries (7.5)
embedding_model, embedding_dimensions string?/int? Filled by the Module 06 stage; recorded so you know which space a vector lives in
ingestion_run_id string Which pipeline run wrote it — batch-level debugging and rollback

2.6 Quality fields#

Field Type Why
ocr_mean_confidence float 0–1? Mean OCR confidence for scanned pages (05.4); below a threshold → review or VLM escalation
parse_warnings list[str] Machine-readable warnings: "hyphenation_repaired", "table_detected_low_confidence", "possible_missing_page"
language_confidence float 0–1? From the language identifier (05.5); low confidence → flag for review
needs_review bool Human-review queue flag; set by audits, OCR thresholds, enrichment validation failures

2.7 The models, in code#

Here is the complete schema as a Pydantic file. It validates on write, embeds DocumentMeta inside every ChunkMeta (denormalisation — the store can't join), and knows how to flatten itself into a store payload (the mechanics are Part 6.3; the standalone version is pure stdlib and runnable below).

python
# meta_models.py — the metadata schema for the running corpus.
# Requires: pydantic
#
# Design rules this file demonstrates:
#   * one DocumentMeta per source document; one ChunkMeta per stored chunk
#   * ChunkMeta embeds its DocumentMeta: the vector store gets one flat
#     record per chunk and cannot join back to a documents table
#   * everything is validated on write; the store payload is a *flattened,
#     null-free* projection (store_payload() below)
#   * schema_version travels inside lineage so old records stay readable

from __future__ import annotations

from datetime import datetime
from enum import Enum
from typing import ClassVar, Literal

from pydantic import (
    BaseModel, ConfigDict, Field,
    field_validator, model_validator,
)

SCHEMA_VERSION = 1

# The only ChunkDerived fields short enough and useful enough to filter on;
# summary, entities, titles and questions stay in the side table (6.3, 7.6).
DERIVED_FILTER_FIELDS = ("topics", "audience", "sentiment", "keywords")


class DocType(str, Enum):
    HANDBOOK = "handbook"
    HELP_ARTICLE = "help_article"
    TICKET = "ticket"
    CONTRACT = "contract"
    TRANSCRIPT = "transcript"
    SPREADSHEET = "spreadsheet"
    POLICY = "policy"
    EMAIL = "email"
    CHAT = "chat"
    OTHER = "other"


class Confidentiality(str, Enum):
    PUBLIC = "public"
    INTERNAL = "internal"
    CONFIDENTIAL = "confidential"
    RESTRICTED = "restricted"


class AclEntry(BaseModel):
    """One grant or denial. Deny always wins; no matching entry means deny."""
    model_config = ConfigDict(extra="forbid", frozen=True)

    principal_type: Literal["user", "group", "role"]
    principal_id: str = Field(min_length=1, max_length=128)
    effect: Literal["allow", "deny"] = "allow"


class TextRegion(BaseModel):
    """Where on a page a chunk's text came from (05.2 produces these).

    `coord_space` is required on purpose: PDF points, image pixels and
    normalised 0-1 coordinates are three different spaces, and a highlight
    overlay silently breaks when they are mixed. `page_label` keeps the
    *printed* page number ("iv", "12A") when it differs from the physical
    1-based `page` index — 05.2 warns they are three different numbers.
    """
    model_config = ConfigDict(extra="forbid")

    page: int = Field(ge=1)                     # 1-based physical page
    page_label: str | None = None               # printed label, e.g. "iv"
    coord_space: Literal["pdf_points", "image_px", "normalized"]
    x0: float
    y0: float
    x1: float
    y1: float


class Lineage(BaseModel):
    model_config = ConfigDict(extra="forbid")

    schema_version: int = SCHEMA_VERSION
    parser_name: str
    parser_version: str
    cleaning_version: str
    chunker_name: str
    chunker_version: str
    enrichment_name: str | None = None
    enrichment_version: str | None = None
    enrichment_model: str | None = None
    embedding_model: str | None = None       # filled by the Module 06 stage
    embedding_dimensions: int | None = None
    ingestion_run_id: str


class QualityFlags(BaseModel):
    model_config = ConfigDict(extra="forbid")

    ocr_mean_confidence: float | None = Field(default=None, ge=0.0, le=1.0)
    parse_warnings: list[str] = Field(default_factory=list)
    language_confidence: float | None = Field(default=None, ge=0.0, le=1.0)
    needs_review: bool = False


class EntityGroup(BaseModel):
    """Entities from a deterministic pass (7.2), grouped by label."""
    model_config = ConfigDict(extra="forbid")

    label: str = Field(min_length=1)
    values: list[str] = Field(default_factory=list)


class ChunkDerived(BaseModel):
    """Enrichment output stored on the chunk (Part 7).

    Everything here is *derived*, not copied from the source, and is
    versioned through lineage.enrichment_*. Only DERIVED_FILTER_FIELDS
    reach the vector-store payload; the rest lives in the side table
    keyed by chunk_id (6.3, 7.6).
    """
    model_config = ConfigDict(extra="forbid")

    suggested_doc_type: DocType | None = None  # the model's guess — a
    # proposal, not truth; promotion to doc.doc_type is a review decision
    topics: list[str] = Field(default_factory=list)
    keywords: list[str] = Field(default_factory=list)
    audience: Literal["customer", "internal", "partner"] | None = None
    sentiment: Literal["positive", "neutral", "negative"] | None = None
    summary: str | None = Field(default=None, max_length=600)
    entities: list[EntityGroup] = Field(default_factory=list)
    generated_title: str | None = Field(default=None, max_length=200)
    hypothetical_questions: list[str] = Field(default_factory=list,
                                            max_length=5)


class DocumentMeta(BaseModel):
    """Metadata for one source document, shared by all its chunks."""
    model_config = ConfigDict(extra="forbid")

    doc_id: str = Field(pattern=r"^doc_[0-9a-f]{24}$")
    slug: str = Field(min_length=1, max_length=80)
    tenant_id: str = Field(min_length=1)
    source_system: str
    source_uri: str
    source_id: str | None = None      # canonical ID in the source system (8.2)
    title: str | None = None
    author: str | None = None
    doc_type: DocType
    language: str = Field(pattern=r"^[a-z]{2}(-[A-Z]{2})?$")
    version: int = Field(default=1, ge=1)

    created_at: datetime | None = None
    modified_at: datetime | None = None
    effective_date: datetime | None = None
    valid_until: datetime | None = None
    ingested_at: datetime
    effective_year: int | None = Field(default=None, ge=1900, le=2200)

    content_hash: str = Field(pattern=r"^[0-9a-f]{64}$")
    source_hash: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")

    owner: str | None = None
    confidentiality: Confidentiality = Confidentiality.INTERNAL
    acl: list[AclEntry] = Field(default_factory=list)
    acl_synced_at: datetime | None = None   # last permission re-sync (5.5)
    licence: str | None = None
    tags: list[str] = Field(default_factory=list)

    superseded_by: str | None = Field(default=None,
                                    pattern=r"^doc_[0-9a-f]{24}$")

    @field_validator("tags")
    @classmethod
    def _normalise_tags(cls, v: list[str]) -> list[str]:
        # one normal form, sorted, deduplicated — filtering depends on it
        return sorted({t.strip().lower() for t in v if t.strip()})

    @model_validator(mode="after")
    def _year_matches_effective_date(self):
        # effective_year is derived, not independent — keep them consistent
        if (self.effective_year is not None
                and self.effective_date is not None
                and self.effective_date.year != self.effective_year):
            raise ValueError("effective_year disagrees with effective_date")
        return self


class ChunkMeta(BaseModel):
    """Metadata for one retrievable unit. Embeds its DocumentMeta."""
    model_config = ConfigDict(extra="forbid")

    chunk_id: str = Field(pattern=r"^chk_[0-9a-f]{24}$")
    doc: DocumentMeta

    chunk_index: int = Field(ge=0)
    section_path: list[str] = Field(default_factory=list)
    char_start: int | None = Field(default=None, ge=0)
    char_end: int | None = Field(default=None, ge=0)
    token_count: int | None = Field(default=None, ge=0)
    page_start: int | None = Field(default=None, ge=1)
    page_end: int | None = Field(default=None, ge=1)
    regions: list[TextRegion] = Field(default_factory=list)
    start_ms: int | None = Field(default=None, ge=0)   # transcript/audio only
    end_ms: int | None = Field(default=None, ge=0)
    speaker: str | None = None                          # dominant speaker
    prev_chunk_id: str | None = None
    next_chunk_id: str | None = None
    chunk_text_hash: str = Field(pattern=r"^[0-9a-f]{64}$")

    lineage: Lineage
    quality: QualityFlags = Field(default_factory=QualityFlags)
    derived: ChunkDerived | None = None

    @model_validator(mode="after")
    def _consistent_ranges(self):
        if (self.char_start is not None and self.char_end is not None
                and self.char_end < self.char_start):
            raise ValueError("char_end is before char_start")
        if (self.page_start is not None and self.page_end is not None
                and self.page_end < self.page_start):
            raise ValueError("page_end is before page_start")
        if (self.start_ms is not None and self.end_ms is not None
                and self.end_ms < self.start_ms):
            raise ValueError("end_ms is before start_ms")
        return self

    # document-level fields that must exist at top level of the store
    # payload for filtering (Part 6.4); audit.py (9.1) checks the same names.
    # ClassVar: a constant, not a model field.
    FILTER_FIELDS: ClassVar[tuple[str, ...]] = (
        "tenant_id", "doc_type", "language", "confidentiality",
        "effective_date", "effective_year", "valid_until",
        "author", "source_system", "slug", "doc_id", "version",
        "tags")

    def store_payload(self) -> dict:
        """Flat, null-free projection for the vector store (Part 6.3).

        Each layer dumps itself to plain keys and the layers merge at top
        level — `doc_type`, `chunker_name`, `ocr_mean_confidence`, never
        `doc_doc_type` — because the store has no namespaces and the audit
        (9.1) and filters (6.4) read exactly these names. From `derived`,
        only DERIVED_FILTER_FIELDS are projected; summary, entities,
        titles and questions stay in the side table. Lists of objects
        become '<key>_count'; nulls never appear. A field-name collision
        between layers raises rather than silently overwriting.
        """
        layers = [
            self.model_dump(mode="json", exclude_none=True,
                            exclude={"doc", "lineage", "quality", "derived"}),
            self.doc.model_dump(mode="json", exclude_none=True),
            self.lineage.model_dump(mode="json", exclude_none=True),
            self.quality.model_dump(mode="json", exclude_none=True),
        ]
        if self.derived is not None:
            derived = self.derived.model_dump(mode="json", exclude_none=True)
            layers.append({k: v for k, v in derived.items()
                           if k in DERIVED_FILTER_FIELDS})

        payload: dict = {}
        for layer in layers:
            for key, value in layer.items():
                if isinstance(value, list) and any(
                        isinstance(x, dict) for x in value):
                    key, value = f"{key}_count", len(value)
                if key in payload:
                    raise ValueError(f"store payload key collision: {key!r}")
                payload[key] = value

        # ACL -> flat string lists. Caveat: this keeps allow-groups and
        # allow-users only — it drops deny rules and role principals; a
        # serious ACL store keeps the full list in a side table keyed by
        # doc_id (Part 5.3).
        payload["allowed_groups"] = sorted({
            e.principal_id for e in self.doc.acl
            if e.effect == "allow" and e.principal_type == "group"
        })
        payload["allowed_users"] = sorted({
            e.principal_id for e in self.doc.acl
            if e.effect == "allow" and e.principal_type == "user"
        })
        return payload

Four details worth noticing:

  • extra="forbid" everywhere. A typo'd field name fails loudly at write time instead of silently vanishing. The cost — old readers rejecting new fields — is handled by schema_version and migrations (9.2), not by letting garbage in.
  • exclude_none=True in store_payload. Vector stores reject nulls (Part 6.3), so absent means absent — never "effective_date": null.
  • Enums are str subclasses. model_dump(mode="json") emits the plain string values ("contract", not "DocType.CONTRACT"), which is what filters and stores want.
  • Layers merge to clean top-level names. store_payload() dumps each layer separately and merges them — doc_type, chunker_name, ocr_mean_confidence, never doc_doc_type — because the store has no namespaces and the audit (9.1) and filters (6.4) read exactly these keys. A field-name collision between layers raises ValueError instead of silently overwriting. From derived, only DERIVED_FILTER_FIELDS (topics, audience, sentiment, keywords) are projected; summary, entities, generated_title, hypothetical_questions and suggested_doc_type live in the side table (7.6).

A worked construction, with the output a real run would print (illustrative — your doc_id/hashes will differ):

python
# build_example.py — assemble one ChunkMeta for the running corpus.
from datetime import datetime, timezone

from meta_models import (
    ChunkDerived, ChunkMeta, Confidentiality, DocType, DocumentMeta,
    Lineage, QualityFlags, TextRegion,
)

doc = DocumentMeta(
    doc_id="doc_872c28241f9da1d42ac8e354",
    slug="acme-returns-policy-uk-eu-v3",
    tenant_id="acme",
    source_system="filesystem",
    source_uri="policies/returns-policy.md",
    source_id="conf-returns-policy-2026",
    title="Returns Policy",
    author="Legal",
    doc_type=DocType.POLICY,
    language="en",
    effective_date=datetime(2026, 1, 1, tzinfo=timezone.utc),
    effective_year=2026,                  # derived; validator checks it
    ingested_at=datetime(2026, 11, 1, 9, 12, 44, tzinfo=timezone.utc),
    acl_synced_at=datetime(2026, 11, 1, 8, 0, 0, tzinfo=timezone.utc),
    content_hash="ab" * 32,
    confidentiality=Confidentiality.INTERNAL,
    tags=["Returns", " refunds ", "REFUNDS"],   # validator normalises these
    acl=[{"principal_type": "group", "principal_id": "legal"},
         {"principal_type": "group", "principal_id": "all-staff"}],
)

chunk = ChunkMeta(
    chunk_id="chk_0c8fe9498c64505a2e0927cc",
    doc=doc,
    chunk_index=1,
    section_path=["Returns", "Eligibility"],
    char_start=412, char_end=690,
    token_count=84,
    page_start=4, page_end=4,
    regions=[TextRegion(page=4, page_label="4", coord_space="pdf_points",
                        x0=72.0, y0=640.0, x1=520.0, y1=700.0)],
    chunk_text_hash="cd" * 32,
    lineage=Lineage(
        parser_name="pymupdf", parser_version="2.1",
        cleaning_version="clean-2.1", chunker_name="heading",
        chunker_version="1.0", ingestion_run_id="run_2026-11-01_0912",
    ),
    quality=QualityFlags(language_confidence=0.98),
    derived=ChunkDerived(
        suggested_doc_type=DocType.POLICY,
        topics=["returns", "refunds"],
        keywords=["return window", "refund"],
        audience="customer",
        sentiment="neutral",
        summary="States the 14-day return window and which items qualify.",
    ),
)

print("tags after validation:", doc.tags)
print("payload keys:", sorted(chunk.store_payload())[:8], "...")
Example output · illustrative2 lines
tags after validation: ['refunds', 'returns']
payload keys: ['acl_count', 'acl_synced_at', 'allowed_groups', 'allowed_users', 'audience', 'author', 'char_end', 'char_start'] ...

Part 3: IDs and keys#

3.1 What an ID must do#

An ID in a retrieval system is not just a label — it is the join key between the vector store, the chunk store, the citation UI, the eval harness and the pipeline manifest. It has to satisfy several constraints at once:

Requirement Why
Stable The same logical thing gets the same ID on every run, or incremental updates can't tell "unchanged" from "new" (05.9)
Deterministic Two runs over identical input produce identical IDs — no uuid4() at ingest time
Content-addressed where it matters When content changes, the ID should change predictably so stale records can be found and replaced
Unique No two different chunks share an ID (upserts would silently overwrite each other)
Compact It is stored and sent on every record; 24 hex chars is plenty
Debuggable You will paste it into logs, tickets and eval reports at 2 a.m.

The tension: identity vs content. A document's ID should be stable across its own edits (it is "the returns policy"), while a chunk's ID should change when its text changes (it is "this exact passage"). One ID can't do both jobs — which is why the schema has doc_id and chunk_id doing different things.

3.2 Content hashing#

The workhorse is a cryptographic hash: hashlib.sha256(text.encode("utf-8")).hexdigest() gives 64 lowercase hex characters — a fingerprint of the exact bytes. Three rules make it useful:

  1. Hash the canonical cleaned text, not the raw file. Hash the exact string that is fed to the chunker — the canonical cleaned text, post-cleaning and pre-chunking — UTF-8 encoded. Hash raw PDF bytes and a whitespace-only change looks like a new document.
  2. Hashes are one-way. You cannot recover text from a hash — which is exactly why hashes are safe to store and log where the content itself might be sensitive.
  3. Collisions are a non-issue at our scale — with a caveat. Finding two inputs with the same SHA-256 output by chance needs ~2¹²⁸ tries (the "birthday bound"); even adversarially it is infeasible today. The caveat: content-addressed IDs assume a non-adversarial corpus. If a user can upload documents and choose IDs, they could try to craft collisions or pre-images — don't let untrusted input influence ID generation beyond hashing its content.

Why truncate to 24 hex chars (96 bits) for IDs? Birthday-bound collision risk at 96 bits is still astronomically small for any corpus you'll ever build (you'd need ~2⁴⁸ documents), and shorter IDs are cheaper to store, index and read. Keep the full 64-char hash where you need it (content_hash); truncate only inside generated IDs.

3.3 Content-addressed chunk IDs#

Here is the design decision that saves real money. The obvious chunk ID is hash(doc_id + chunk_index + chunker_version). It is stable within a run — but insert one paragraph at the top of a 200-page handbook and every chunk after it gets a new ID, so 05.9 re-embeds the entire tail of the document. At corpus scale that is a five-figure embedding bill for a one-paragraph edit.

The fix: leave position out of the ID. chunk_id = hash(doc_id + chunker_version + hash(chunk_text) + occurrence), where occurrence is the 0-based count of how many times that exact text has already appeared in the document (it disambiguates repeated boilerplate like "Contact support."). Now:

  • Edit one sentence → only the chunks containing it get new IDs; their neighbours keep theirs → only changed chunks re-embed.
  • Insert a paragraph → all surviving chunks keep their IDs; only the new chunk is embedded.
  • Change the chunker version → all IDs change → clean re-chunk, which is what you want anyway.
  • Position is still stored — as chunk_index metadata — because ordering is a display concern, not an identity concern.
python
# ids.py — deterministic, content-addressed IDs for documents and chunks.
# Standard library only: hashlib, unicodedata, re.

import hashlib
import re
import unicodedata


def content_hash(text: str) -> str:
    """SHA-256 of the canonical cleaned text fed to the chunker,
    UTF-8 encoded. 64 lowercase hex characters."""
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def slugify(text: str, max_length: int = 60) -> str:
    """Human-readable slug: lowercase ASCII, punctuation collapsed to dashes."""
    text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode()
    text = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
    return text[:max_length].strip("-") or "untitled"


def make_doc_id(tenant_id: str, source_system: str, source_uri: str) -> str:
    """Stable identity for a *source* document.

    Same (tenant, system, URI) -> same doc_id forever, even when the file's
    content changes; content changes are tracked separately by content_hash.
    The URI must already be canonicalised by the ingestion layer (05.1/05.9):
    this function hashes exactly what it is given.
    """
    key = f"{tenant_id}|{source_system}|{source_uri}"
    return f"doc_{hashlib.sha256(key.encode('utf-8')).hexdigest()[:24]}"


def make_chunk_id(doc_id: str, chunker_version: str, chunk_text: str,
                  occurrence: int) -> str:
    """Content-addressed chunk ID.

    Deliberately excludes the chunk's position in the document: inserting or
    deleting a paragraph only changes the IDs of chunks whose *text* changed,
    so unchanged chunks keep their IDs (and their embeddings) across edits.
    `occurrence` disambiguates identical chunks inside one document.
    """
    digest = hashlib.sha256(
        f"{doc_id}|{chunker_version}|{content_hash(chunk_text)}|{occurrence}"
        .encode("utf-8")
    ).hexdigest()
    return f"chk_{digest[:24]}"


def chunk_ids_for(texts: list[str], doc_id: str, chunker_version: str) -> list[str]:
    """Assign IDs to a list of chunk texts, numbering repeats 0, 1, 2, ..."""
    seen: dict[str, int] = {}
    ids = []
    for text in texts:
        n = seen.get(content_hash(text), 0)
        seen[content_hash(text)] = n + 1
        ids.append(make_chunk_id(doc_id, chunker_version, text, n))
    return ids


# --- demo: a policy doc edited three ways ------------------------------------

doc_id = make_doc_id("acme", "filesystem", "policies/returns-policy.md")
print("doc_id:", doc_id)
print("slug :", slugify("Acme Returns Policy — UK & EU, v3"))

v1 = ["Returns are accepted within 30 days of delivery.",
      "Items must be unused and in original packaging.",
      "Refunds are issued to the original payment method."]

# edit: one sentence changes
v2 = ["Returns are accepted within 14 days of delivery.",
      "Items must be unused and in original packaging.",
      "Refunds are issued to the original payment method."]

# edit: a paragraph is inserted at the top
v3 = ["This policy applies to all orders placed after 1 January 2026.",
      *v1]

ids1 = chunk_ids_for(v1, doc_id, "chunker-1.0")
ids2 = chunk_ids_for(v2, doc_id, "chunker-1.0")
ids3 = chunk_ids_for(v3, doc_id, "chunker-1.0")

print("\nv1 -> v2 (one sentence edited):")
for a, b in zip(ids1, ids2):
    print(f"  {'same' if a == b else 'NEW '}  {b}")

print("\nv1 -> v3 (paragraph inserted at top):")
kept = sum(1 for i in ids1 if i in ids3)
print(f"  {kept} of {len(ids1)} chunk IDs survived the insertion")
for i in ids3:
    print(f"  {'same' if i in ids1 else 'NEW '}  {i}")

# identical chunks inside one document still get distinct IDs
dup = chunk_ids_for(["Contact support.", "Contact support."], doc_id, "chunker-1.0")
print("\nduplicate chunks get distinct IDs:", dup[0] != dup[1])

# --- tests -------------------------------------------------------------------
assert len(content_hash("x")) == 64
assert make_doc_id("acme", "fs", "a.md") == make_doc_id("acme", "fs", "a.md")
assert make_doc_id("acme", "fs", "a.md") != make_doc_id("acme", "fs", "b.md")
assert len(set(ids1)) == 3
assert dup[0] != dup[1]
assert kept == 3  # every v1 chunk survives the insertion unchanged
print("\nall assertions passed")
Output · real — this is pure standard library, safe to run18 lines
doc_id: doc_872c28241f9da1d42ac8e354
slug : acme-returns-policy-uk-eu-v3

v1 -> v2 (one sentence edited):
  NEW   chk_8926b52526b53f2bbef343d7
  same  chk_52f22cd290d4b60182481956
  same  chk_dea7f523dcd4a7504e89c26d

v1 -> v3 (paragraph inserted at top):
  3 of 3 chunk IDs survived the insertion
  NEW   chk_82f8f68e71c5653b2030c9f5
  same  chk_0c8fe9498c64505a2e0927cc
  same  chk_52f22cd290d4b60182481956
  same  chk_dea7f523dcd4a7504e89c26d

duplicate chunks get distinct IDs: True

all assertions passed

Two edge cases the demo hints at:

  • The occurrence counter is per document. Two different documents may legitimately contain the same chunk text (a shared disclaimer) — that's fine, because doc_id is in the hash, so their chunk IDs differ. Within one document, occurrence keeps them distinct.
  • Chunk boundaries are the chunker's job, not the ID's. If the chunker merges two chunks into one, both old texts disappear → both IDs are retired and the merged chunk gets a new one. 05.9 deletes retired IDs; nothing here needs to know.

3.4 Slugs, UUIDs and composite keys#

Scheme Example Good for Bad for
Content hash (what we use) chk_0c8fe949… Uniqueness, dedup, change detection Not human-meaningful; position-free (by design)
Slug acme-returns-policy-uk-eu-v3 URLs, debugging, ops conversations Not unique (two docs can slugify identically), breaks on rename
UUID4 9f1c…-…-…-… Globally unique opaque IDs Random → not deterministic, can't dedup, hostile to debugging
UUID5 / name-based uuid.uuid5(NAMESPACE_URL, key) Deterministic UUIDs from a name SHA-1 based (fine for IDs, not for security); less controllable format than a hash prefix
Composite key acme:filesystem:policies/returns-policy.md#v3 Debugging, logs, cross-system joins Leaks structure; must be parsed to be useful; store as display field, not primary key

The pattern that works: hash-derived primary keys + a slug field for humans + composite display strings for logs. The doc_id/slug/source_uri triple in DocumentMeta is exactly that.

3.5 IDs across updates and deletions#

The ID scheme only pays off when the update machinery uses it correctly, which is 05.9's job — but the contract is worth stating here:

  • Unchanged chunk (same chunk_id seen again) → keep the record and its embedding; just refresh mutable metadata if needed.
  • New chunk ID → embed and insert.
  • Missing chunk ID (was in the doc before, isn't now) → the chunk was edited away or deleted → remove its record (a tombstone in the manifest, then delete from the store).
  • doc_id seen with a new content_hash → the document changed: re-chunk it, diff the chunk IDs as above.
  • doc_id never seen again (source deleted) → tombstone the document and all its chunks.

Because doc_id is derived from source identity (tenant + system + URI) rather than content, a renamed file is a new document — which is usually what you want (the old path's chunks should be tombstoned, not silently inherited). If your source system has real document IDs (a Zendesk ticket ID, a Drive file ID), prefer hashing that over the URI: it survives renames and moves for free. Note it in source_uri either way.


Part 4: Dates, versions and "as of"#

4.1 Five dates, five questions#

"When was this document written?" is five different questions wearing one coat — and real sources pose a few more (published_at, expires_at) that fold into them. Each stored field answers a different query:

Field Question it answers Trust level
created_at When did the author say it was created? Often missing or wrong — PDFs lie, web pages guess
modified_at When did the source last change? Reasonably reliable for files/DBs; unreliable for web (CMS rebuilds touch everything)
published_at (source concept — folds into effective_date) When did it go public? Only meaningful for articles/posts
effective_date When does the content take effect? The business axis: contract start, policy effective date, price valid-from
ingested_at When did our pipeline ingest it? Always known, always UTC — the only date you fully control
valid_until / expires_at When does it stop being true? Optional; absence means open-ended

Count the fields, not the rows: published_at and expires_at are source-system concepts, not DocumentMeta columns — a publication date folds into effective_date when you don't need it separately, and expires_at is valid_until under another name. The schema stores five date fields; the table maps the questions they answer.

The dangerous confusion is between event time (when the content is true in the world: effective_date) and processing time (when your pipeline saw it: ingested_at). A contract signed in January but ingested in November must be retrievable as "effective January" — freshness and "as of" queries live on effective_date, never on ingested_at.

4.2 Time zones and formats#

Two rules, both learned from production scars:

  1. Store UTC, always, as ISO-8601. datetime.now(timezone.utc).isoformat() → "2026-11-05T14:23:07.183204+00:00". ISO-8601 sorts lexicographically, which is why stores can range-filter it as a string.
  2. Never accept a naive datetime. "2026-01-01 09:00:00" with no offset is ambiguous — is that London, New York, UTC? Real systems have shipped bugs where a naive timestamp was silently treated as UTC and "as of" queries were off by hours. Reject it or make the assumption explicit (assume_timezone="UTC" and record that you did).

Python 3.11+ makes this easy: datetime.fromisoformat accepts Z and any ±HH:MM offset. For messier source formats ("March 3rd, 2026", "03/04/26"), python-dateutil's parser.parse is the standard tool — but always pass dayfirst/yearfirst explicitly for ambiguous numeric dates, because 03/04/2026 means 3 April in most of the world and 4 March in the US, and the parser will guess wrong silently:

python
# messy_dates.py — dateutil copes with formats fromisoformat rejects, but
# `dayfirst` changes how EVERY numeric date is read — even year-first ones.
import re
from datetime import datetime

from dateutil import parser

YEAR_FIRST = re.compile(r"^\d{4}\D")   # 2026.03.04, 2026/03/04 ...


def parse_date(text: str, dayfirst: bool) -> datetime:
    """ISO-8601 first (unambiguous), then year-first strings, then dateutil.
    `dayfirst` is a per-source setting, not a guess: UK/EU exports -> True,
    US exports -> False. It must never reach a year-first string, because
    dateutil would then read 2026.03.04 as 3 April."""
    try:
        return datetime.fromisoformat(text)
    except ValueError:
        pass
    if YEAR_FIRST.match(text):
        return parser.parse(text, yearfirst=True, dayfirst=False)
    return parser.parse(text, dayfirst=dayfirst)


for s in ["3 March 2026", "03/04/2026", "2026.03.04"]:
    uk = parse_date(s, dayfirst=True).date()
    us = parse_date(s, dayfirst=False).date()
    naive = parser.parse(s, dayfirst=True).date()   # the trap: dayfirst on everything
    print(f"{s:13} UK -> {uk}   US -> {us}   naive dayfirst=True -> {naive}")
Example output · illustrative3 lines
3 March 2026  UK -> 2026-03-03   US -> 2026-03-03   naive dayfirst=True -> 2026-03-03
03/04/2026    UK -> 2026-04-03   US -> 2026-03-04   naive dayfirst=True -> 2026-04-03
2026.03.04    UK -> 2026-03-04   US -> 2026-03-04   naive dayfirst=True -> 2026-04-03

Look at the last line: dayfirst=True does not only matter for 03/04/2026. dateutil also applies it to year-first strings, so a plain parser.parse("2026.03.04", dayfirst=True) returns 3 April, not 4 March. That is why the function routes ISO and year-first strings around dayfirst and why the flag belongs to the source (one setting per exporter), never to a global default. Spell it out per source and record which one you used. Also note that these results are naive datetimes (no offset): rule 2 above still applies, so attach the source's time zone explicitly (for example dt.replace(tzinfo=ZoneInfo("Europe/London")), then convert to UTC) before storing them.

python
# dates.py — the five dates, time zones, and "as of" filtering.
# Standard library only: datetime, zoneinfo.

from datetime import datetime, timezone


def parse_instant(text: str) -> datetime:
    """Parse an ISO-8601 timestamp into an aware datetime in UTC.

    Python 3.11+'s fromisoformat accepts 'Z' and any ±HH:MM offset.
    A *naive* timestamp (no offset) is rejected: it is ambiguous, and
    silently assuming UTC has caused real bugs.
    """
    dt = datetime.fromisoformat(text)
    if dt.tzinfo is None:
        raise ValueError(f"naive timestamp rejected: {text!r}")
    return dt.astimezone(timezone.utc)


def is_effective_on(effective_date, valid_until, as_of: datetime) -> bool:
    """Is a document version the one in force at `as_of`?

    effective_date <= as_of < valid_until   (valid_until=None means open-ended)
    """
    if effective_date is not None and as_of < effective_date:
        return False
    if valid_until is not None and as_of >= valid_until:
        return False
    return True


# --- demo --------------------------------------------------------------------

raw = ["2026-01-01T00:00:00Z", "2026-06-01T09:30:00+05:30", "2025-12-31T19:00:00-05:00"]
for s in raw:
    print(f"{s:32} -> {parse_instant(s).isoformat()}")

policy_v1 = (parse_instant("2026-01-01T00:00:00Z"), parse_instant("2026-06-01T00:00:00Z"))
policy_v2 = (parse_instant("2026-06-01T00:00:00Z"), None)   # open-ended

for label, as_of in [("2026-03-15", "2026-03-15T12:00:00Z"),
                     ("2026-06-01", "2026-06-01T00:00:00Z"),
                     ("2026-09-30", "2026-09-30T23:59:59Z")]:
    d = parse_instant(as_of)
    print(f"as of {label}: v1 effective={is_effective_on(*policy_v1, d)}, "
          f"v2 effective={is_effective_on(*policy_v2, d)}")

# naive input must fail loudly
try:
    parse_instant("2026-01-01 09:00:00")
except ValueError as e:
    print("rejected:", e)

# --- tests -------------------------------------------------------------------
assert parse_instant("2026-01-01T00:00:00Z").tzinfo is not None
assert is_effective_on(*policy_v1, parse_instant("2026-03-15T00:00:00Z")) is True
assert is_effective_on(*policy_v1, parse_instant("2026-06-01T00:00:00Z")) is False
assert is_effective_on(*policy_v2, parse_instant("2026-09-30T00:00:00Z")) is True
print("all assertions passed")
Output · real — standard library only8 lines
2026-01-01T00:00:00Z             -> 2026-01-01T00:00:00+00:00
2026-06-01T09:30:00+05:30        -> 2026-06-01T04:00:00+00:00
2025-12-31T19:00:00-05:00        -> 2026-01-01T00:00:00+00:00
as of 2026-03-15: v1 effective=True, v2 effective=False
as of 2026-06-01: v1 effective=False, v2 effective=True
as of 2026-09-30: v1 effective=False, v2 effective=True
rejected: naive timestamp rejected: '2026-01-01 09:00:00'
all assertions passed

4.3 "As of" queries and superseded documents#

The query that breaks naive systems: "What did the returns policy say on 15 March?" Three metadata behaviours make it work:

  1. Keep every version. How you mark the old one depends on how the policy is re-issued. If the new version is a new file (a new path, so a new doc_id), set the old document's superseded_by to the new doc_id and keep both. If it overwrites the same file (same path, so the same doc_id, but a new content_hash), bump version, set valid_until on the old version's chunks and keep them; superseded_by is not needed because the date range and version already tell the versions apart. Deleting the old version makes history unrecoverable; keeping it unmarked makes search return contradictory answers.
  2. Filter on the business date, not ingest date. effective_date <= as_of AND (valid_until IS NULL OR valid_until > as_of) AND superseded_by IS NULL (or superseded_by = <the version in force> if you index versions explicitly). Note the boundary: at exactly 2026-06-01T00:00:00Z the new version wins — valid_until is exclusive, effective_date inclusive.
  3. Decide per product whether history is queryable. Some products want "current truth only" (default filter hides superseded); legal/compliance products want "what did we tell customers in March" (explicit as_of parameter). Support both: default to current, expose as_of as an explicit query parameter.

Part 5: Access control metadata#

5.1 Permissions are data too#

A vector store happily embeds and returns anything you put in it. It has no idea that chunk 4812 of the contracts folder is "Legal eyes only". If permissions live only in the source system (SharePoint, Drive, a filing cabinet), your RAG system will cheerfully quote the confidential MSA to any user who asks the right question. Access control therefore has to be copied into metadata at ingestion time — propagated from the source, stored per record, and enforced at query time.

5.2 The ACL model#

Keep it deliberately simple — three principal types cover almost every real system:

Principal type Example Resolves to
user u_101 One person
group legal, all-staff, eu-support A set of users, managed in your IdP/HR system
role support-agent, finance-reviewer A job function, often mapped to groups anyway

An AclEntry is {principal_type, principal_id, effect} where effect is allow or deny. The semantics, which the code below implements:

  • Default-deny. A record with no matching allow is invisible. An empty ACL means "nobody" (or "everybody", if you choose public-by-default — pick one per field and document it; we choose default-deny).
  • Deny wins. Any matching deny overrides all allows, regardless of order — so you can grant a whole group and carve out exceptions (the CEO who must not see the legal memo about them).
  • tenant_id is checked first and separately. Even a perfect ACL must never cross tenants.

The confidentiality enum from Part 2 is the coarse version of this: public/internal/confidential/restricted maps to implicit group memberships (all-staff, managers, legal, exec). Use it when the org chart is simple; use acl when it isn't. Most real systems need both — confidentiality as a display badge, ACL as the enforcement.

5.3 Filter before you rank#

This is the single most important rule in the lesson, so it gets its own heading:

flowchart LR
    Q["user query + principal"] --> EXP["expand groups/roles<br/>(from your IdP, fresh)"]
    EXP --> PF["metadata pre-filter:<br/>tenant + ACL + any user filters"]
    PF --> VS["vector/BM25 search<br/>over allowed candidates only"]
    VS --> RR["rank + rerank"]
    RR --> ANS["answer + citations"]
    PF -. "wrong order:" .-> BAD["search top-k, then drop<br/>inaccessible results"]

Why post-filtering fails, concretely: vector search returns the top-k most similar chunks. If you retrieve 10 and then delete the 8 the user can't see, you're left with 2 — and the 3 accessible chunks that ranked 11th–13th never got a chance. Widen k and you pay more for results you'll throw away; keep k small and users get "I don't know" answers to questions the corpus could answer. The ACL predicate must be part of the candidate-generation filter, which every serious store supports (Pinecone $in on allowed_groups, Qdrant must on a payload field — Part 6.3).

python
# acl.py — access-control checks over chunk metadata. Standard library only.
#
# Model: every stored record carries a tenant_id and an `acl` list of entries:
#   {"principal_type": "user" | "group" | "role",
#    "principal_id":   "u_123" | "legal" | "support-agent",
#    "effect":         "allow" | "deny"}        # default when omitted: "allow"
#
# Semantics: default-deny. A record is visible only when at least one allow
# matches and no deny matches (deny always wins, whatever the order).

from dataclasses import dataclass, field


@dataclass(frozen=True)
class Principal:
    """Who is asking. Resolved fresh per request from your auth system —
    group membership changes must not require re-indexing."""
    user_id: str
    tenant_id: str
    groups: frozenset[str] = field(default_factory=frozenset)
    roles: frozenset[str] = field(default_factory=frozenset)


def _matches(entry: dict, principal: Principal) -> bool:
    pid, ptype = entry["principal_id"], entry["principal_type"]
    if ptype == "user":
        return pid == principal.user_id
    if ptype == "group":
        return pid in principal.groups
    if ptype == "role":
        return pid in principal.roles
    raise ValueError(f"unknown principal_type: {ptype!r}")


def acl_allows(record_tenant: str, acl: list[dict], principal: Principal) -> bool:
    """May `principal` see a record with this tenant and ACL?"""
    if record_tenant != principal.tenant_id:
        return False
    saw_allow = False
    for entry in acl:
        if not _matches(entry, principal):
            continue
        if entry.get("effect", "allow") == "deny":
            return False          # deny wins, regardless of position
        saw_allow = True
    return saw_allow               # no allow matched -> default deny


# --- demo --------------------------------------------------------------------

legal_memo = {
    "tenant_id": "acme",
    "acl": [
        {"principal_type": "group", "principal_id": "legal"},
        {"principal_type": "user", "principal_id": "u_ceo",
         "effect": "deny"},          # explicit exception inside the group
    ],
}
handbook = {
    "tenant_id": "acme",
    "acl": [{"principal_type": "group", "principal_id": "all-staff"}],
}
globex_doc = {
    "tenant_id": "globex",
    "acl": [{"principal_type": "group", "principal_id": "globex-staff"}],
}

alice = Principal(user_id="u_101", tenant_id="acme",
                  groups=frozenset({"legal", "all-staff"}))
bob = Principal(user_id="u_102", tenant_id="acme",
                groups=frozenset({"all-staff"}))
ceo = Principal(user_id="u_ceo", tenant_id="acme",
                groups=frozenset({"legal", "all-staff"}))
# note: globex_user IS in the "legal" group — the only thing denying them
# the acme legal memo is the tenant check, not the ACL
globex_user = Principal(user_id="u_999", tenant_id="globex",
                        groups=frozenset({"legal", "globex-staff"}))

checks = [
    ("alice reads legal memo",        acl_allows(legal_memo["tenant_id"], legal_memo["acl"], alice)),
    ("bob reads legal memo",          acl_allows(legal_memo["tenant_id"], legal_memo["acl"], bob)),
    ("ceo (denied) reads memo",       acl_allows(legal_memo["tenant_id"], legal_memo["acl"], ceo)),
    ("bob reads handbook",            acl_allows(handbook["tenant_id"], handbook["acl"], bob)),
    ("globex user reads acme memo",   acl_allows(legal_memo["tenant_id"], legal_memo["acl"], globex_user)),
    ("globex user reads globex doc",  acl_allows(globex_doc["tenant_id"], globex_doc["acl"], globex_user)),
]
for name, ok in checks:
    print(f"{name:32} -> {'ALLOW' if ok else 'deny'}")

# --- tests -------------------------------------------------------------------
assert acl_allows(legal_memo["tenant_id"], legal_memo["acl"], alice) is True
assert acl_allows(legal_memo["tenant_id"], legal_memo["acl"], bob) is False
assert acl_allows(legal_memo["tenant_id"], legal_memo["acl"], ceo) is False
assert acl_allows(handbook["tenant_id"], handbook["acl"], bob) is True
assert acl_allows(legal_memo["tenant_id"], legal_memo["acl"], globex_user) is False
assert acl_allows(globex_doc["tenant_id"], globex_doc["acl"], globex_user) is True
assert acl_allows("acme", [], bob) is False          # empty ACL: default deny
print("all assertions passed")
Output · real — standard library only7 lines
alice reads legal memo           -> ALLOW
bob reads legal memo             -> deny
ceo (denied) reads memo          -> deny
bob reads handbook               -> ALLOW
globex user reads acme memo      -> deny
globex user reads globex doc     -> ALLOW
all assertions passed

Read the last two lines together: globex_user is in the legal group, so the group entry would have allowed the acme memo — the deny comes from the tenant check alone, which is exactly why tenant_id is evaluated first and separately. And the globex doc proves the same principal isn't just locked out of everything.

Two production details the toy hides:

  • Group expansion happens per request, not per record. The store filter is "allowed_groups intersects the user's current groups" — so when someone joins legal on Monday, they see legal docs immediately with zero re-indexing. That's why Principal.groups is resolved fresh and the stored field is allowed_groups, not a baked-in user list.
  • The deny case needs care in the store filter. The flattened allowed_groups/allowed_users payload (2.7) encodes allows only. A record with a deny needs the deny evaluated too — either keep the full ACL in a side table keyed by doc_id and post-check denies (cheap, since denies are rare), or encode denies as a denied_users/denied_groups field and add a $nin clause. Document which strategy you chose; silent deny-drops are privilege escalations.

5.4 Multi-tenant isolation patterns#

When one deployment serves many customers, "tenant" becomes the hard boundary. Three patterns, in increasing isolation:

Pattern How it works Cost When
Shared index + tenant filter One index; every record has tenant_id; every query filters on it Cheapest; one set of indexes Many small tenants, uniform data — the default
Namespace/partition per tenant Store's own partitioning: Pinecone namespaces, Qdrant is_tenant payload index Moderate; per-tenant stats and sometimes per-tenant graphs Medium tenants; you want per-tenant BM25/IDF statistics to be clean
Separate index per tenant One index (or cluster) per customer Most expensive; N× infra Regulated isolation, per-tenant encryption keys, or very large tenants

Verified specifics (as of November 2026): Qdrant documents payload-partitioned multitenancy as the recommended default — a keyword payload index on the tenant field with is_tenant: true (available since v1.11.0) makes Qdrant store each tenant's vectors together for sequential reads, and warns that a query without the tenant filter searches every tenant's data. Pinecone's equivalent is the namespace: all reads and writes target one namespace, and its docs explicitly recommend namespaces for tenant isolation and note queries scan the whole namespace regardless of filters. Module 06 owns the index internals; the takeaway here is that tenant_id is a first-class metadata field on every record in every pattern — it is your last line of defence when a filter is forgotten.

One more store you will meet (as of November 2026).

  • Postgres with pgvector lets the database enforce permissions. Enable row-level security on the chunks table (ALTER TABLE chunks ENABLE ROW LEVEL SECURITY; plus CREATE POLICY ... USING (tenant_id = current_setting('app.tenant_id'))) and every SELECT, including your similarity query, is filtered by policy. With RLS on and no policy, no rows are visible (default-deny, like this lesson's ACL model). Know the exemptions: superusers, roles with BYPASSRLS, and by default the table owner (unless FORCE ROW LEVEL SECURITY) skip the policies, so your application must connect as an ordinary role (PostgreSQL docs, row security policies). For many tenants, pgvector also suggests partitioning or separate tables (pgvector README).

5.5 When ACL metadata goes wrong#

Failure Symptom Prevention
Missing tenant_id on new record type Cross-tenant leak in evals Audit requires tenant_id (Part 9); CI test asserts it on every fixture
Source permissions changed, metadata stale User sees doc they lost access to Re-sync ACLs on a schedule; store acl_synced_at; treat staleness as a security bug
ACL copied into chunk text or prompts Permissions leak to logs/model context ACL lives only in store payloads and the side DB — never in embedded text or LLM prompts
Post-filter instead of pre-filter "No results" for restricted users; timing leaks Part 5.3 — predicate inside candidate generation
Deny entries dropped in flattening Privilege escalation Encode denies explicitly or keep full ACL in side table (5.3)

Part 6: Field design for real queries#

Deep-dive

6.1 Three audiences for a field#

Every field you store has exactly one primary audience, and confusing them is the root of most "metadata is too big / can't filter it" problems:

Audience What it means Examples Store treatment
Filterable Code must match it exactly or by range at query time doc_type, tenant_id, effective_date, language, tags, confidentiality Typed, indexed, flat
Searchable The lexical/semantic index should find it chunk text, title, section_path, keywords Goes into text fields / full-text index, not metadata
Display-only Humans read it; machines ignore it slug, full source_uri, author bio, licence text Stored but not indexed

A field can serve two audiences (author filters and displays), but it cannot be "sort of filterable" — if a user will ever type "only X", it needs a real typed field, not a string you LIKE-match later.

6.2 Types, cardinality, enums vs free text#

Three questions decide a field's shape:

Cardinality — how many distinct values will it have?

  • Low (2–100): doc_type, language, confidentiality, year → perfect filter/index candidates.
  • Medium (hundreds–thousands): tags, author, section_path → filterable but watch index cost.
  • High (millions): chunk_id, content_hash, source_uri → keys, not filters. Indexing them wastes resources; you look them up by equality, not scan.

Typing — match the store's types:

  • Dates as ISO-8601 strings sort and range correctly as strings (lexicographic = chronological for fixed-format UTC). Qdrant additionally has a native datetime payload type.
  • Booleans as real booleans, counts as integers — not "true"/"42" strings, which break range filters.
  • Watch the integer trap: Pinecone converts integer metadata values to 64-bit floats. A ticket_id of 9007199254740993 loses precision silently. Anything needing exact integer identity (big IDs, account numbers) belongs in a string field.
  • Lists of strings are fine (tags, allowed_groups) and match with "any of" semantics — but a list of objects (acl entries, regions) cannot be filtered and must be flattened, encoded, or kept in the side DB.

Enums vs free text — the single biggest data-quality lever:

  • Closed set (you can name every legal value): doc_type, confidentiality, audience → model as Enum/Literal, validate on write, reject anything else. Filtering on enums is exact and fast.
  • Controlled vocabulary (a large but finite set: topics, product names): same idea, bigger list — keep the canonical list in one file, validate against it (7.4).
  • Open text (titles, summaries, free tags): normalise (lowercase, trim, collapse whitespace) and accept that it is searchable, not reliably filterable. "Billing" vs "billing" vs "Billing!" as three different filter values is the classic failure — the tags validator in meta_models.py exists precisely to prevent it.

6.3 What the store actually accepts#

Metadata design doesn't end at your Pydantic model — it ends at what the vector store will take. Verified against official docs (as of November 2026; Module 06 covers index internals):

Constraint Pinecone Qdrant
Shape Flat JSON object only — nested objects rejected Payload is arbitrary JSON; nested objects allowed but need nested indexing to filter
Value types string, number (integers → 64-bit float), boolean, list of strings; nulls not supported keyword/integer/float/bool/geo/datetime/text/uuid payload types
Size 40 KB metadata per record No fixed per-point cap; payload indexes cost RAM/disk
Indexing All metadata fields indexed by default (opt out via configure-metadata-indexing) Index per field before ingesting; max ~100 payload indexes per collection on Cloud; strict mode rejects filtering on unindexed fields
Filter language $eq/$ne/$gt/$gte/$lt/$lte/$in/$nin/$exists/$and/$or/$not; $in arrays ≤ 10,000 values must/should/must_not clauses over indexed fields; is_tenant flag for tenant fields
Tenancy namespaces per tenant is_tenant: true keyword index on tenant field

The engineering conclusions:

  1. Design store-agnostic, flatten on write. Your ChunkMeta is rich and nested; store_payload() produces the flat, null-free projection each store accepts, with every layer's fields merged to clean top-level names. Swapping Pinecone for Qdrant changes the flattener, not the schema.
  2. Never put text in metadata. A 2 KB summary × 100k chunks is 200 MB of duplicated, indexed payload you pay for twice. Summaries for the model go in the text channel or a side table; metadata keeps a short summary_text only if a UI truly displays it.
  3. Index only what you filter. Every indexed field costs memory and write time. content_hash, source_uri, slug are lookup keys — keep them in the payload but unindexed where the store allows.
  4. Denormalise doc fields onto every chunk. The store has no join; tenant_id, doc_type, effective_date, allowed_groups must be on each chunk record. That's why ChunkMeta embeds DocumentMeta.

6.4 Design for the queries you expect#

Before finalising fields, write down the actual queries. From the plan's running corpus:

Expected query Fields it needs
"Only 2025 contracts" doc_type=contract + effective_date in [2025-01-01, 2026-01-01)
"Only the EU handbook" doc_type=handbook + tags contains eu (or a region field if geography is a first-class axis)
"From this author" author exact match
"Tickets about billing" tags/topics contains billing — or leave it searchable if tags aren't reliable enough
"The current version of the returns policy" slug/title match + superseded_by IS NULL + confidentiality ≤ user's level
"What did the policy say in March?" as_of on effective_date/valid_until (4.3)
"Chunks I can actually show this user" tenant_id + allowed_groups ∩ user.groups + deny check

The other direction — turning a user's sentence into these filters ("only 2025 contracts" → doc_type=contract, effective_year=2025) — is query-time metadata extraction, taught in 06.6, Part 6 and as self-querying in 07.3, Part 6. It only works if the fields you designed here are typed, closed-vocabulary and present on every record.

Two rules fall out:

  • Every filterable field must exist on every record — a doc_type missing on 5% of chunks silently excludes them from "only contracts" forever. The audit (9.1) enforces coverage.
  • Precompute what you filter on. "Contracts effective in 2025" is easier as effective_year: 2025 (an int, range-filterable everywhere) than parsing ISO strings in every query — though ISO strings do range correctly, derived scalar fields are cheaper and clearer. effective_year is a real optional field on DocumentMeta (2.2), derived at enrichment time and kept consistent with effective_date by a validator; filters.py prefers it and falls back to the date prefix on older records.
python
# filters.py — the "queries you expect" as plain predicates over flat metadata.
# Standard library only. In production these become the store's filter
# expression; here they run on plain dicts in the shape store_payload()
# emits (6.3) so you can test them offline.


def matches(meta: dict, *, doc_type=None, year=None, author=None,
            tags_any=None, confidentiality_max=None) -> bool:
    """AND-combined filters. Unspecified arguments match everything."""
    if doc_type is not None and meta.get("doc_type") != doc_type:
        return False
    if author is not None and meta.get("author") != author:
        return False
    if year is not None:
        # prefer the precomputed integer; fall back to the ISO date prefix
        eff_year = meta.get("effective_year")
        if eff_year is not None:
            if eff_year != year:
                return False
        else:
            eff = meta.get("effective_date") or ""
            if not eff.startswith(f"{year}-"):
                return False
    if tags_any is not None:
        tags = set(meta.get("tags") or [])
        if not tags & set(tags_any):
            return False
    if confidentiality_max is not None:
        order = ["public", "internal", "confidential", "restricted"]
        got = meta.get("confidentiality", "internal")
        if order.index(got) > order.index(confidentiality_max):
            return False
    return True


# --- demo: three records from the running corpus -----------------------------

records = [
    {"chunk_id": "chk_a1", "doc_type": "contract", "author": "Legal",
     "effective_date": "2025-03-01T00:00:00Z", "effective_year": 2025,
     "tags": ["vendor", "msa"], "confidentiality": "confidential"},
    {"chunk_id": "chk_b2", "doc_type": "contract", "author": "Legal",
     "effective_date": "2026-02-15T00:00:00Z", "effective_year": 2026,
     "tags": ["vendor", "nda"], "confidentiality": "confidential"},
    {"chunk_id": "chk_c3", "doc_type": "handbook", "author": "Product",
     "effective_date": "2026-01-01T00:00:00Z", "effective_year": 2026,
     "tags": ["onboarding", "eu"], "confidentiality": "internal"},
]

queries = [
    ("only 2025 contracts",
     dict(doc_type="contract", year=2025)),
    ("handbook tagged eu",
     dict(doc_type="handbook", tags_any=["eu"])),
    ("contracts up to confidential level",
     dict(doc_type="contract", confidentiality_max="confidential")),
    ("internal docs only",
     dict(confidentiality_max="internal")),
]

for name, kwargs in queries:
    hits = [r["chunk_id"] for r in records if matches(r, **kwargs)]
    print(f"{name:36} -> {hits}")
Output · real — standard library only4 lines
only 2025 contracts                  -> ['chk_a1']
handbook tagged eu                   -> ['chk_c3']
contracts up to confidential level   -> ['chk_a1', 'chk_b2']
internal docs only                   -> ['chk_c3']
python
# store_payload.py — turn a nested metadata dict into a flat key/value payload
# a vector store accepts. Same convention as ChunkMeta.store_payload() (2.7):
#   * the schema nests one level — chunk fields beside `doc`, `lineage`,
#     `quality` and `derived` objects — and layer fields merge to TOP LEVEL
#     under their own names (`doc_type`, `chunker_name`, never `doc_doc_type`)
#     because the store has no namespaces and audit/filters read those keys
#   * from `derived`, only DERIVED_FILTER_FIELDS are kept; summary, entities,
#     titles and questions stay in the side table
#   * nulls are not allowed — omit the key instead
#   * lists of objects can't be filtered — '<key>_count' integer
# Standard library only.

import json

MAX_PAYLOAD_BYTES = 40 * 1024   # Pinecone: 40 KB per record (as of Nov 2026)

LAYERS = ("doc", "lineage", "quality", "derived")

# derived fields short enough and useful enough to filter on (7.6)
DERIVED_FILTER_FIELDS = ("topics", "audience", "sentiment", "keywords")


def flatten(meta: dict, prefix: str = "") -> dict:
    """Nested record -> flat payload.

    Layer dicts merge to top level under their own field names; anything
    nested deeper keeps a prefix so keys stay unique. Lists of objects
    become '<key>_count'; nulls are dropped entirely.
    """
    out: dict = {}
    for key, value in meta.items():
        flat_key = f"{prefix}{key}"
        if isinstance(value, dict):
            if not prefix and key == "derived":
                value = {k: v for k, v in value.items()
                         if k in DERIVED_FILTER_FIELDS}
            sub_prefix = ("" if not prefix and key in LAYERS
                          else flat_key + "_")
            out.update(flatten(value, sub_prefix))
        elif isinstance(value, list):
            if any(isinstance(x, dict) for x in value):
                out[f"{flat_key}_count"] = len(value)
            else:
                out[flat_key] = value
        elif value is None:
            continue                      # stores reject null: drop the key
        else:
            out[flat_key] = value
    return out


def check_payload_size(payload: dict, limit: int = MAX_PAYLOAD_BYTES) -> str:
    size = len(json.dumps(payload, separators=(",", ":")).encode("utf-8"))
    return f"{size} bytes ({size / limit:.0%} of {limit // 1024} KB limit)"


# --- demo: a nested chunk record, the shape ChunkMeta.store_payload() emits -

chunk_meta = {
    "chunk_id": "chk_0c8fe9498c64505a2e0927cc",
    "chunk_index": 1,
    "token_count": 84,
    "section_path": ["Returns", "Eligibility"],
    "page_start": 4, "page_end": 4,
    "start_ms": None, "end_ms": None,          # transcript fields: null -> dropped
    "doc": {
        "doc_id": "doc_872c28241f9da1d42ac8e354",
        "slug": "acme-returns-policy-uk-eu-v3",
        "tenant_id": "acme",
        "source_id": "conf-returns-policy-2026",
        "doc_type": "policy",
        "language": "en",
        "title": "Returns Policy",
        "effective_date": "2026-01-01T00:00:00Z",
        "effective_year": 2026,
        "valid_until": None,                   # null -> key dropped
        "confidentiality": "internal",
        "acl": [                                # list of objects -> can't filter
            {"principal_type": "group", "principal_id": "legal"},
            {"principal_type": "group", "principal_id": "all-staff"},
        ],
        "acl_synced_at": "2026-11-01T08:00:00Z",
        "owner": None,                          # null -> key dropped
    },
    "lineage": {
        "parser_name": "pymupdf", "parser_version": "2.1",
        "chunker_name": "heading", "chunker_version": "1.0",
    },
    "derived": {
        "suggested_doc_type": "policy",         # not a filter field -> dropped
        "topics": ["returns", "refunds"],
        "keywords": ["return window", "refund"],
        "audience": "customer",
        "sentiment": "neutral",
        "summary": "States the 14-day return window and which items qualify.",
        "entities": [{"label": "ORG", "values": ["Acme"]}],
        "generated_title": "Returns Policy",
        "hypothetical_questions": ["How long do I have to return it?"],
    },
}

payload = flatten(chunk_meta)

# denormalised filter fields the model adds explicitly (5.3, 6.4):
payload["allowed_groups"] = ["legal", "all-staff"]   # list-of-strings: filterable

print(json.dumps(payload, indent=2))
print("\npayload size:", check_payload_size(payload))

Output (real — standard library only; json.dumps(indent=2) puts every list item on its own line, so short lists are joined onto one line here for width):

text
{
  "chunk_id": "chk_0c8fe9498c64505a2e0927cc",
  "chunk_index": 1,
  "token_count": 84,
  "section_path": ["Returns", "Eligibility"],
  "page_start": 4,
  "page_end": 4,
  "doc_id": "doc_872c28241f9da1d42ac8e354",
  "slug": "acme-returns-policy-uk-eu-v3",
  "tenant_id": "acme",
  "source_id": "conf-returns-policy-2026",
  "doc_type": "policy",
  "language": "en",
  "title": "Returns Policy",
  "effective_date": "2026-01-01T00:00:00Z",
  "effective_year": 2026,
  "confidentiality": "internal",
  "acl_count": 2,
  "acl_synced_at": "2026-11-01T08:00:00Z",
  "parser_name": "pymupdf",
  "parser_version": "2.1",
  "chunker_name": "heading",
  "chunker_version": "1.0",
  "topics": ["returns", "refunds"],
  "keywords": ["return window", "refund"],
  "audience": "customer",
  "sentiment": "neutral",
  "allowed_groups": ["legal", "all-staff"]
}

payload size: 734 bytes (2% of 40 KB limit)

Read the output as a design review. Every layer's fields sit at top level under their own names — doc_type, chunker_name, ocr_mean_confidence — because the store has no namespaces and the audit (9.1) and filters (6.4) read exactly these keys; these are the same names ChunkMeta.store_payload() produces. acl became acl_count (the entries can't be filtered — the full ACL lives in the side table, 5.3) while allowed_groups was added explicitly as its filterable projection. valid_until, start_ms/end_ms and owner vanished entirely (nulls dropped). From derived, only topics, keywords, audience and sentiment were projected — suggested_doc_type, summary, entities, generated_title and hypothetical_questions are text and review material that belongs in the side table or the text channel (6.3, 7.6), not in an indexed payload.


Part 7: Enrichment#

Deep-dive

7.1 Two engines: rules and models#

Enrichment is the stage that adds derived metadata — fields computed from the chunk or document rather than copied from the source. Two engines, cheapest first:

Engine What it does well Cost Failure mode
Deterministic (regex, lookup tables, spaCy NER, dates) Exact patterns: dates, SKUs, phone numbers, entity spans, taxonomy lookups ~free, milliseconds Brittle on messy text; NER is noisy on short chunks
LLM (schema-constrained call per chunk/doc) Judgement tasks: doc type, topics, audience, sentiment, summary, keywords, hypothetical questions, titles Tokens × chunks — real money at scale Hallucinated tags, drift when prompt/model changes, needs validation

The pipeline order matters: deterministic first (it is free and catches the easy 80%), LLM second (only for fields rules can't produce), validation last (both engines' output passes through the same schema checks — Part 9).

7.2 Deterministic enrichment#

Everything that is a pattern belongs here, not in an LLM call:

  • Dates and numbers: regex for Q[1-4], fiscal years, version strings (v3.2.1), SKUs, invoice numbers → normalised fields (effective_year, version_tag).
  • Lookup tables: department codes → names, country codes → regions, product SKUs → categories. Cheap, exact, auditable.
  • Entity extraction with spaCy: en_core_web_sm gives PERSON/ORG/GPE/DATE/MONEY/etc. spans — useful for entities fields and for "which orgs appear in this corpus" analytics. Treat NER output as hints: it mislabels on short or unusual text, so store entities as {label, text} pairs with the model version in lineage, and never let an NER span alone decide a security-relevant field.
python
# entities.py — deterministic enrichment with spaCy (NER).
# Requires: spacy and `python -m spacy download en_core_web_sm`
import spacy

nlp = spacy.load("en_core_web_sm")


def extract_entities(text: str) -> list[dict]:
    """Named entities grouped by label. Input is capped: spaCy's small
    models are not built for whole documents."""
    doc = nlp(text[:100_000])
    grouped: dict[str, set[str]] = {}
    for ent in doc.ents:
        grouped.setdefault(ent.label_, set()).add(ent.text.strip())
    return [{"label": label, "values": sorted(values)}
            for label, values in sorted(grouped.items())]
Example output · illustrative6 lines
extract_entities("Nordwind Logistics renewed its MSA with Acme on 3 March 2026 for €1.2M.")
# [
#   {"label": "DATE",  "values": ["3 March 2026"]},
#   {"label": "MONEY", "values": ["€1.2M"]},
#   {"label": "ORG",   "values": ["Acme", "Nordwind Logistics"]},
# ]

spaCy is MIT-licensed and runs fully local — a good default for deterministic enrichment. Alternatives (Stanza, GLiNER, cloud NER APIs) trade accuracy, languages and cost differently; the pattern — local model → {label, values} → validated field — is what matters.

Relations and the graph preview. Entities say who and what; relations say how they connect — "Nordwind Logistics —[renewed]→ MSA —[with]→ Acme". Extracting (subject, predicate, object) triples is the same enrichment slot with a pickier schema: predicates need a controlled vocabulary too, or you get renewed/renew/signed renewal fragments — the 7.4 problem again. The payoff is optional: triples can feed a property-graph store for multi-hop questions ("which vendors share outside counsel?"), but for most corpora flat metadata plus good chunks beats a graph you have to keep consistent. Treat it as a preview — store triples in side tables keyed by chunk_id, version them like everything else, and let Module 07 decide whether traversal beats plain retrieval for your queries.

7.3 LLM enrichment#

The fields rules can't produce — doc_type confirmation, topics, audience, summary, keywords, a generated title for untitled docs, hypothetical questions per chunk — come from an LLM. The mechanics are owned elsewhere and only linked:

  • Schema-constrained output so the reply is guaranteed to match your ChunkEnrichment model: 03.4.
  • Batch APIs and bounded concurrency for corpus-scale runs: 03.9.
  • Cost estimation: n_chunks × (input_tokens × input_price + output_tokens × output_price) — providers price the two directions differently, so don't blend them into one rate; count tokens with the provider's tools per 03.7. A 100k-chunk corpus at ~500 in / ~80 out tokens per chunk is ~58M tokens — real money, which is why deterministic-first and doc-level (not chunk-level) enrichment are the default.

One output deserves special mention: hypothetical questions. A question generated from a chunk ("how do I return shoes?") is not a filter — it is extra embedded text that resolves back to the same chunk_id, the multi-vector technique owned by 05.7, §3.2 (the doc2query/HyDE lineage). Generate them with a dedicated prompt at enrichment time, store them in ChunkDerived.hypothetical_questions (7.6), and let the embedding stage expand them into additional vectors; they never belong in the store payload.

The important design choice here is injectable: the enrichment step takes the model call as a function argument. Tests pass a fake; production passes a thin wrapper around a provider's schema-constrained call. Nothing in the validation or lineage logic knows or cares which.

python
# enrich.py — LLM enrichment step with an injectable model call.
# Requires: pydantic
#
# The LLM call itself is a plain callable so the whole step is testable
# without a key: pass a fake in tests, a real provider wrapper in prod
# (the wrapper is where 03.4's schema-constrained call and 03.9's batch
# mechanics plug in — this lesson doesn't re-teach them).

from typing import Callable, Literal

from pydantic import (
    BaseModel, ConfigDict, Field, ValidationError, field_validator,
)

from meta_models import ChunkDerived, DocType

ENRICHMENT_NAME = "topic-tagger"
ENRICHMENT_VERSION = "1.0"          # bump when the prompt or model changes

# The controlled vocabulary — see 7.4. One canonical list, validated here.
TOPICS = frozenset({
    "billing", "shipping", "returns", "warranty", "installation",
    "troubleshooting", "account", "pricing", "other",
})


class EnrichmentError(Exception):
    """Raised when the model's reply fails validation. The pipeline decides
    retry vs quarantine — that policy belongs to 05.9."""


class ChunkEnrichment(BaseModel):
    """What the model is allowed to return. Closed vocabularies are
    enforced here, not trusted to the prompt."""
    model_config = ConfigDict(extra="forbid")

    doc_type: DocType
    topics: list[str] = Field(default_factory=list, max_length=5)
    audience: Literal["customer", "internal", "partner"] = "customer"
    sentiment: Literal["positive", "neutral", "negative"] | None = None
    summary: str = Field(min_length=20, max_length=400)
    keywords: list[str] = Field(default_factory=list, max_length=10)

    @field_validator("topics")
    @classmethod
    def _known_topics(cls, v):
        # normalise first — " Returns " is the same tag as "returns";
        # only the canonical form is stored (7.4)
        v = sorted({t.strip().lower() for t in v if t.strip()})
        bad = [t for t in v if t not in TOPICS]
        if bad:
            raise ValueError(f"topics outside vocabulary: {bad}")
        return v

    @field_validator("keywords")
    @classmethod
    def _normalise_keywords(cls, v):
        return sorted({k.strip().lower() for k in v if k.strip()})


def enrich_chunk(chunk_text: str,
                 llm_fn: Callable[[str], dict]) -> ChunkEnrichment:
    """One enrichment call, validated. `llm_fn` returns a dict (in
    production: parsed JSON from a schema-constrained provider call).
    Raises EnrichmentError on invalid output — retry/quarantine is the
    pipeline's decision (05.9)."""
    raw = llm_fn(chunk_text)
    try:
        return ChunkEnrichment.model_validate(raw)
    except ValidationError as e:
        raise EnrichmentError(f"enrichment failed validation: {e}") from e


def fake_llm(text: str) -> dict:
    """Stand-in returning a plausible payload. In production this slot holds
    a thin wrapper around a schema-constrained provider call (03.4) submitted
    in batch (03.9)."""
    return {
        "doc_type": "help_article",
        "topics": ["returns", "shipping"],
        "audience": "customer",
        "sentiment": "neutral",
        "summary": "Explains how to start a return and which shipping "
                   "options apply to the label.",
        "keywords": ["Return", " shipping ", "label"],
    }


# --- demo --------------------------------------------------------------------

chunk_text = ("To start a return, open Orders, pick the item and choose "
              "Return. Print the prepaid label and drop the parcel at any "
              "partner point within 14 days.")

enrichment = enrich_chunk(chunk_text, fake_llm)
print(enrichment.model_dump_json(indent=2))

# what gets stamped into lineage on the stored record:
print("\nlineage stamp:",
      {"enrichment_name": ENRICHMENT_NAME,
       "enrichment_version": ENRICHMENT_VERSION})

# and what lands on ChunkMeta.derived — the model's doc_type becomes a
# *suggestion*, never an overwrite of the canonical DocumentMeta.doc_type
# (7.6); everything else maps across field-for-field:
derived = ChunkDerived(
    suggested_doc_type=enrichment.doc_type,
    topics=enrichment.topics,
    audience=enrichment.audience,
    sentiment=enrichment.sentiment,
    summary=enrichment.summary,
    keywords=enrichment.keywords,
)
print("\nderived:", derived.model_dump(mode="json", exclude_none=True))

# a model that hallucinates an out-of-vocabulary topic is rejected:
def bad_llm(text: str) -> dict:
    return {**fake_llm(text), "topics": ["returns", "vibes"]}

try:
    enrich_chunk(chunk_text, bad_llm)
except EnrichmentError as e:
    print("\nrejected out-of-vocabulary topic")
Example output · illustrative14 lines
{
  "doc_type": "help_article",
  "topics": ["returns", "shipping"],
  "audience": "customer",
  "sentiment": "neutral",
  "summary": "Explains how to start a return and which shipping options apply to the label.",
  "keywords": ["label", "return", "shipping"]
}

lineage stamp: {'enrichment_name': 'topic-tagger', 'enrichment_version': '1.0'}

derived: {'suggested_doc_type': 'help_article', 'topics': ['returns', 'shipping'], 'keywords': ['label', 'return', 'shipping'], 'audience': 'customer', 'sentiment': 'neutral', 'summary': 'Explains how to start a return and which shipping options apply to the label.', 'entities': [], 'hypothetical_questions': []}

rejected out-of-vocabulary topic

7.4 Controlled vocabularies and LLM tags#

Free-text tags are the enrichment equivalent of "Billing" vs "billing!" — they look useful and quietly destroy filtering. The fix is a controlled vocabulary: one canonical list of allowed values, enforced at three points:

  1. In the prompt/schema — tell the model the allowed set (the topics field description lists TOPICS; better still, use a schema enum/Literal so constrained decoding can only emit legal values — 03.4).
  2. In validation — ChunkEnrichment._known_topics rejects anything outside TOPICS. Out-of-vocabulary output becomes an EnrichmentError, not a stored tag.
  3. In normalisation — synonyms map to canonical forms before validation ("invoice" → billing, "send back" → returns) via a small alias table; the raw model output is kept in lineage for audit.

Keep the vocabulary file (topics.yaml or a frozenset in code) under review: adding a topic is a product decision, not a model decision. When the LLM keeps inventing a concept you don't have, that's signal to add it deliberately — not to loosen validation. And keep a human review queue for the borderline cases validation can't decide — records flagged needs_review (9.1) get a person, not a guess; each reviewed item feeds the alias table or the vocabulary file, so every correction makes the next batch better.

7.5 Enrichment drift and versioning#

Enrichment output depends on the prompt, the model and the vocabulary — any of which can change. When they do, two failure modes appear:

  • Distribution drift: a new prompt makes the model tag returns chunks as shipping more often; your "billing issues" filter silently misses them.
  • Comparability drift: eval slices by doc_type/topics compare records enriched under different regimes as if they were equal.

The defence is the same as everywhere else in this lesson: version everything. enrichment_name/enrichment_version/enrichment_model in lineage (2.5), ENRICHMENT_VERSION bumped on every prompt or model change, and re-enrichment treated as a backfill — a pipeline job (05.9) that recomputes fields for existing records under the new version. You don't need to re-embed anything: enrichment fields live in metadata, and metadata updates don't touch vectors. Audit a random sample (say 50 chunks) after every enrichment version bump; that's your drift detector.

7.6 Where enrichment output lives#

ChunkEnrichment is the boundary schema — what the model may return. What gets stored is ChunkDerived on ChunkMeta.derived (2.7): the same topics/keywords/audience/sentiment/summary, plus entities, generated_title, hypothetical_questions and suggested_doc_type. Two deliberate choices:

  • doc_type is stored as suggested_doc_type, not doc_type. The canonical type lives on DocumentMeta; the model's guess is a proposal. Agreement between the two is a quality signal; disagreement sets quality.needs_review and waits for a human (7.4). Promoting a suggestion into doc.doc_type is a data decision, not an automatic write — a mistyped policy is worse than an untyped one.
  • Only DERIVED_FILTER_FIELDS reach the vector payload (topics, audience, sentiment, keywords). summary, entities, generated_title, hypothetical_questions and suggested_doc_type are text or review material — they live in the side table keyed by chunk_id and reach the model through the text channel or serving layer, never as indexed payload (6.3). store_payload() enforces this whitelist; it is not a convention you can forget.

Deterministic enrichment output lands in the same place: entities.py's {label, values} groups become ChunkDerived.entities (EntityGroup), dates/SKUs/lookups become the scalar derived fields like effective_year on DocumentMeta. One derived object per chunk, one lineage stamp per enrichment run — that is the whole contract.


Part 8: Citations and provenance#

8.1 What a citation needs to show#

When the model says "according to the returns policy…", the UI must be able to prove it. A citation needs enough metadata to answer what, where, which version, may I see it:

Element Fields Notes
Title doc.title, slug Display; fall back to generated title (7.3) for untitled sources
Source source_system, source_uri Human label ("Help centre", "Contracts folder") + canonical link
Location section_path, page_start/page_end, regions Breadcrumb + page + optional highlight box
Version doc.version, effective_date "Returns Policy v3, effective 1 Jan 2026" — users must see which policy answered
Snippet first ~200 chars of chunk text Preview text — display-only, and watch for PII (Part 10)
Deep link constructed URL (8.2) Clickable jump to the exact spot
Time start_ms/end_ms/speaker for A/V Audio/video transcripts use the chunk-level timestamp fields instead of pages — ChunkMeta carries them (2.4); preview Module 09

Two of these are deliberately not metadata: the snippet comes from the chunk text at serve time, and the deep link is constructed from source_uri + locators — storing pre-built URLs rots when sites reorganise.

A citation URL is source_uri + a locator fragment: ?page=4, #section-2.1, ?t=123 for audio. The fragility is in source_uri itself — help-centre URLs change, PDFs move, tickets get renumbered. Mitigations, in order of robustness:

  1. Store the canonical identifier, not just the URL. A Confluence page ID or Drive file ID survives URL changes; keep it in the source_id field (2.2) and rebuild the URL from it at display time.
  2. Record source_uri + ingested_at together. If the link 404s, you know which snapshot of the URL you indexed and can look for a redirect or an archived copy.
  3. For your own docs site, generate locators you control (/handbook/returns#eligibility) so links are stable by construction.

8.3 From a bad answer back to the parse#

This is where lineage pays rent. A wrong answer traces backwards:

text
answer → cited chunk_id → chunk record (text + all metadata)
       → doc_id → DocumentMeta (source, dates, ACL)
       → lineage.parser_name/version, cleaning_version, chunker_version
       → quality.parse_warnings, ocr_mean_confidence
       → ingestion_run_id → the pipeline run that produced it

Each hop is a metadata field you already stored. "The bot quoted the wrong refund window" becomes "chunk chk_0c8f… of doc_872c…, parsed by pymupdf 2.1 with warning hyphenation_repaired, in run run_2026-11-01_0912" — which is a bug report, not a mystery. Module 10A and Module 11A build the eval and tracing systems on top of exactly these fields.


Part 9: Metadata quality and schema evolution#

Deep-dive

9.1 Validation and completeness#

Pydantic validates each record at write time, but corpus-level problems — a whole document type missing effective_date, tags drifting out of vocabulary — only show up in aggregate. The audit function is deliberately boring: a required-fields list, per-field coverage, and a few sanity checks, run over every record before it reaches the store.

python
# audit.py — completeness and sanity checks over flat metadata dicts.
# Standard library only. Run this over every record before it goes to the store.

import json

# Fields every chunk record must carry — the same top-level names
# store_payload() emits (6.3), so the audit runs directly on store payloads.
# Tune per corpus; the list lives in one place and the audit enforces it.
REQUIRED_FIELDS = [
    "chunk_id", "doc_id", "tenant_id", "doc_type", "language",
    "chunker_name", "chunker_version", "ingested_at",
]

# Soft fields: missing is a warning, not a failure.
RECOMMENDED_FIELDS = [
    "title", "author", "effective_date", "content_hash", "section_path",
]


def audit_record(meta: dict) -> dict:
    """Check one flat metadata dict. Returns a small report dict."""
    missing = [k for k in REQUIRED_FIELDS if meta.get(k) in (None, "")]
    missing_recommended = [k for k in RECOMMENDED_FIELDS if meta.get(k) in (None, "")]
    warnings = []

    # chunk_id must look like an id, not a sentence
    cid = meta.get("chunk_id", "")
    if cid and (" " in cid or len(cid) > 64):
        warnings.append(f"chunk_id looks wrong: {cid!r}")

    # dates must be ISO-8601 strings (what the store accepts and sorts on)
    for k in ("effective_date", "ingested_at", "valid_until"):
        v = meta.get(k)
        if v is not None and not (isinstance(v, str) and "T" in v):
            warnings.append(f"{k}: expected ISO-8601 string, got {v!r}")

    # free-text tags must be normalised: lowercase, no surrounding space
    for tag in meta.get("tags", []) or []:
        if tag != tag.strip().lower():
            warnings.append(f"tag not normalised: {tag!r}")
            break

    return {
        "ok": not missing,
        "missing": missing,
        "missing_recommended": missing_recommended,
        "warnings": warnings,
    }


def audit_corpus(records: list[dict]) -> dict:
    """Aggregate audit: how complete is the whole corpus?"""
    reports = [audit_record(r) for r in records]
    n = len(records)
    complete = sum(1 for r in reports if not r["missing"] and not r["missing_recommended"])
    field_coverage = (
        {k: round(sum(1 for r in records if r.get(k) not in (None, "")) / n, 3)
         for k in REQUIRED_FIELDS + RECOMMENDED_FIELDS}
        if n else {}
    )
    return {
        "records": n,
        "fully_populated": complete,
        "completeness": round(complete / n, 3) if n else 0.0,
        "field_coverage": field_coverage,
        "failures": [r for r in reports if not r["ok"]],
        "warning_count": sum(len(r["warnings"]) for r in reports),
    }


# --- demo --------------------------------------------------------------------

good = {
    "chunk_id": "chk_0c8fe9498c64505a2e0927cc",
    "doc_id": "doc_872c28241f9da1d42ac8e354",
    "tenant_id": "acme", "doc_type": "policy", "language": "en",
    "title": "Returns Policy", "author": "Legal",
    "effective_date": "2026-01-01T00:00:00Z",
    "content_hash": "ab" * 32,
    "section_path": ["Returns", "Eligibility"],
    "chunker_name": "heading", "chunker_version": "1.0",
    "ingested_at": "2026-11-01T09:12:44Z",
    "tags": ["returns", "refunds"],
}

bad = {
    "chunk_id": "chunk number seven of the returns policy",
    "doc_id": "doc_872c28241f9da1d42ac8e354",
    "tenant_id": "acme", "doc_type": "policy", "language": "en",
    "effective_date": "01/01/2026",          # not ISO
    "tags": ["Returns", " refunds "],        # not normalised
    "chunker_name": "heading", "chunker_version": "1.0",
    "ingested_at": "2026-11-01T09:12:44Z",
    # missing: title, author, content_hash, section_path
}

broken = {
    "chunk_id": "chk_d4",
    # missing required: doc_id, tenant_id, doc_type, language,
    #                  chunker_name, chunker_version, ingested_at
}

summary = audit_corpus([good, bad, broken])
print(json.dumps(summary, indent=2))

Output (real — standard library only; the json.dumps(indent=2) output is re-wrapped so short lists share a line):

text
{
  "records": 3,
  "fully_populated": 1,
  "completeness": 0.333,
  "field_coverage": {
    "chunk_id": 1.0, "doc_id": 0.667, "tenant_id": 0.667,
    "doc_type": 0.667, "language": 0.667, "chunker_name": 0.667,
    "chunker_version": 0.667, "ingested_at": 0.667,
    "title": 0.333, "author": 0.333, "effective_date": 0.667,
    "content_hash": 0.333, "section_path": 0.333
  },
  "failures": [
    {"ok": false,
     "missing": ["doc_id", "tenant_id", "doc_type", "language",
                 "chunker_name", "chunker_version", "ingested_at"],
     "missing_recommended": ["title", "author", "effective_date",
                             "content_hash", "section_path"],
     "warnings": []}
  ],
  "warning_count": 3
}

Read it as three verdicts: good passes, bad passes the hard checks but earns 3 warnings (bad chunk_id, non-ISO date, un-normalised tags) plus 4 missing recommended fields, and broken fails outright. In production this runs as a pipeline gate (05.9) and as a scheduled corpus audit — a completeness score that drops below your threshold is an incident, not a metric.

9.2 Schema evolution without re-embedding#

Metadata schemas change — you will add region, product_line, sentiment. The rules that keep old records usable:

  • Add fields with defaults or nullable. Old records simply lack the key; readers treat absence as "unknown", never as a wrong value.
  • Bump schema_version in lineage. It records which schema wrote the record; migrations key off it.
  • Never change a field's meaning or type. effective_date going from "contract start" to "invoice date" corrupts every historical query. New meaning → new field name.
  • Migrate lazily or by backfill. Two options: transform on read (cheap, forever-taxing) or a backfill job that rewrites payloads (one-time cost, clean result). For vector-store payloads, backfill is usually right — metadata updates don't require re-embedding, which is the whole point of separating the channels.
  • Deprecate, don't delete. Keep the old field populated for one schema version so dashboards don't break mid-migration.

9.3 Metadata in evaluation and debugging#

Two downstream consumers deserve explicit design:

  • Eval slicing (Module 10A): "our retrieval is 92% overall but 61% on scanned contracts" is only answerable if every eval item carries doc_type, quality.ocr_mean_confidence, language. Metadata turns one aggregate score into a diagnostic map.
  • Tracing (Module 11A): every LLM call in the serving path should log the chunk_ids it was grounded on. A bad answer becomes a join: trace → chunk IDs → full metadata → lineage → the exact pipeline run. Without chunk IDs in traces, debugging is guesswork.

Part 10: Privacy and minimisation#

Deep-dive

Metadata is copied data, and copied data leaks twice: once into the vector store, once wherever else you put it. The rules:

  • ACL/confidentiality/owner/licence are store-layer fields. They exist so the query layer can enforce access — they never belong in chunk text, prompts, or logs that the model or a third party sees.
  • Titles, snippets and author names can contain PII ("Jane Doe's visa application", "hr-termination-memo.docx"). If the corpus has sensitive documents, assume titles are sensitive too — they end up in citations, logs and eval reports.
  • Enrichment sends chunk text to a provider. The same privacy rules as any prompt apply (02.9, Part 9): minimisation before the call, and check whether your provider's terms allow the data class you're sending. PII detection/redaction itself is 05.5's job — by enrichment time it should already have run.
  • Deletions must reach metadata too. A "right to erasure" request that deletes chunk text but leaves author, title and ACL entries in the store and in logs is not erasure. 05.9 owns the deletion machinery; the metadata fields are what make it findable.
  • source_uri can itself be sensitive (a URL containing a customer name or ticket ID). Store the canonical ID where possible; treat URIs as quasi-sensitive in multi-tenant logs.

The metadata decision table#

The design choices above collapse into five recurring decisions. Defaults first; verify on your own queries and store limits.

Decision Choose this When Cost / watch out for
Where a value lives Typed filterable field Code must match it exactly or by range: "only 2025 contracts", "internal only", "from this author" Indexed storage + write cost; must be flat, typed, null-free (6.2–6.3)
Embedded / searchable text The value answers questions, not filters: "what does the warranty cover?" Not filterable; belongs in chunk text or title/section_path, never duplicated into the payload (6.1)
Side table / display-only Needed for display, audit or debugging but never filtered: full ACL entries, regions boxes, licence text Second lookup by chunk_id; stays out of the vector payload (5.3, 6.3)
Enrichment engine Deterministic rules Exact patterns: dates, SKUs, phone numbers, NER spans, taxonomy lookups ~free; brittle on messy text, NER noisy on short chunks — run it first (7.1–7.2)
LLM Judgement fields rules can't produce: doc_type, topics, audience, sentiment, summaries, hypothetical questions Tokens × chunks; hallucinated tags and prompt drift — schema-constrain, validate against a controlled vocabulary, version it (7.3–7.5)
Tenant isolation Shared index + tenant_id filter Many small tenants, uniform data — the default Cheapest; every query must carry the predicate or it searches all tenants (5.4)
Namespace / is_tenant partition You want per-tenant statistics (clean BM25/IDF) or moderate isolation Moderate cost; tenant_id still required as the last line of defence
Separate index per tenant Regulated isolation, per-tenant keys, very large tenants N× infrastructure and operational surface
Schema change Backfill job Adding or repairing a filterable field at corpus scale One-time rewrite; metadata updates never re-embed (9.2)
Transform on read Rarely-read derived fields, tiny corpora Cheap now, a forever-tax on every read — fine until it isn't
Identifier chunk_id content hash Chunk identity — stable across edits so unchanged chunks keep embeddings Keep position (chunk_index) out of the hash — position in the hash makes a one-paragraph edit re-embed the tail (3.3)
doc_id source-identity hash Document identity — stable across content edits Rename/move = new document; prefer the source system's own ID when it has one (3.5)
slug Humans: display names, URLs, ops conversations Not unique, breaks on rename — never a key (3.4)
Random UUID Almost never, for stored chunks Every re-run looks like all-new data; breaks idempotent updates and dedup (3.4)
# What went wrong What the user saw Root cause The fix
1 ACL applied after vector search Restricted users got "no results" or leaked counts Post-filtering starved top-k Predicate inside candidate generation (5.3)
2 effective_date stored naive "As of" queries off by hours; wrong policy version served Naive datetime silently assumed UTC Reject naive; store UTC ISO-8601 (4.2)
3 Nested acl object upserted to Pinecone Upsert rejected: metadata must be flat Nested JSON unsupported store_payload() flattening (6.3)
4 "owner": null sent to the store Upsert rejected: null not supported Nulls aren't a value stores accept exclude_none / drop the key
5 ticket_id: 9007199254740993 as integer Lookups returned the wrong ticket Pinecone ints → 64-bit float, precision lost Big IDs as strings (6.2)
6 Free-text tags from an LLM "billing issues" filter matched 12 of 400 billing chunks "Billing", "billing!", "invoice stuff" fragmented the vocabulary Controlled vocabulary + validation (7.4)
7 chunk_index inside the chunk-ID hash One-paragraph edit re-embedded a 200-page handbook Position-sensitive IDs Position-free content-addressed IDs (3.3)
8 New record type forgot tenant_id Cross-tenant chunks in eval results Coverage gap Audit requires the field (9.1)
9 ACL copied into chunk text Permissions visible in prompts, citations, logs Wrong channel Store-layer fields never enter text (1.3, 10)
10 Enrichment prompt changed silently doc_type distribution shifted; eval slices incomparable Unversioned enrichment enrichment_version + backfill + sample audit (7.5)
11 Two identical chunks, same ID Second upsert overwrote the first Missing occurrence disambiguator occurrence counter in chunk_ids_for (3.3)
12 Old policy version still searchable Bot quoted the superseded refund window Versions kept but not marked/filtered superseded_by + valid_until + as-of filter (4.3)
13 doc_type present on 95% of chunks "Only contracts" silently excluded the other 5% Incomplete denormalisation Audit coverage metric + pipeline gate (9.1)
14 Summary text stored in metadata Payload hit the 40 KB limit; indexing cost doubled Text in the wrong channel Summaries in text/side table, not payload (6.3)

Common misconceptions#

Misconception Reality
"Metadata is just extra columns on the chunk." It is the contract between ingestion, retrieval, citation, eval and access control. Wrong metadata fails silently in all of them at once.
"Put everything in metadata — more fields can't hurt." Every field costs storage, index memory and write time; text in metadata duplicates payload and can't be filtered well anyway. Filterable ≠ everything.
"Retrieve top-k, then filter out what the user can't see." Post-filtering starves results (top-k was chosen before permissions) and leaks timing/existence signals. ACL predicates go inside candidate generation.
"A random UUID per chunk at ingest is fine." Random IDs make every re-run look like all-new data — incremental updates, dedup and debugging all break. IDs must be deterministic and content-aware.
"Position belongs in the chunk ID." Including chunk_index in the hash means one inserted paragraph re-IDs the whole document tail → full re-embedding. Keep position as metadata, not identity.
"More tags = better retrieval." Uncontrolled vocabularies fragment into near-duplicates (billing, Billing!, invoice stuff) that no filter matches. Closed sets or nothing.
"Dates are just strings." Five different dates answer five different questions; naive timestamps and ingest-time-vs-effective-time confusion are the classic "wrong policy version" bugs.
"Enrichment is free accuracy." LLM tags drift with prompt/model changes and hallucinate out-of-vocabulary values; deterministic-first + validation + versioning is what makes it trustworthy.
"Schema changes require re-embedding." Metadata lives outside the vector; adding a field is a payload update or backfill — vectors are untouched.
"If it validates, it's correct." Pydantic proves shape, not truth — a schema-valid doc_type: contract on a help article is still wrong. Semantic checks and audits cover what schemas can't.

Key takeaways#

  • A stored chunk is text + metadata; the text answers "what does it say", the fields answer everything else — filter, ACL, freshness, citation, debugging.
  • The metadata-vs-text decision: constraints ("only", "after", "from") become typed fields; question content stays in the embedded text. ACLs never enter text or prompts.
  • The schema has five layers — document, section, chunk, lineage, quality — denormalised so each stored chunk is self-contained. ChunkMeta embeds DocumentMeta because the store can't join.
  • doc_id is identity (stable across edits, hashed from source identity); chunk_id is content (hashed from chunk text + chunker version + occurrence, deliberately position-free so edits reuse embeddings).
  • Five dates, five questions — created_at, modified_at, effective_date, ingested_at, valid_until; store UTC ISO-8601, reject naive timestamps, and run "as of" queries on business dates.
  • ACLs are data: default-deny, deny-wins, tenant checked first, and the predicate goes inside candidate generation — never post-filter.
  • Design for the store: flat JSON, no nulls, typed values, ~40 KB budgets, index only filter fields — verified per-store in 6.3 and deferred to Module 06 for depth. Test a restrictive filter and check you still get k results: some approximate indexes filter after the scan (pgvector, 5.4).
  • Enrichment is deterministic-first (regex, lookups, spaCy), LLM-second (schema-constrained, injectable, validated against a controlled vocabulary), and versioned so drift is detectable and re-runs are backfills, not re-embeds. Its output lands in ChunkDerived: only DERIVED_FILTER_FIELDS reach the payload, the rest stays in the side table.
  • Citations need title, source, location (section/page/bbox), version, snippet and a stable deep link; lineage turns "bad answer" into "parser X, run Y, chunk Z".
  • Metadata is minimised data: store-layer fields stay in the store; anything reaching a model or a log follows the same privacy rules as the text.

Terms introduced in this lesson#

Term Meaning
Metadata Structured fields stored alongside chunk text: identity, provenance, permissions, dates, quality
Document-level / chunk-level metadata Fields describing the whole source document vs the individual retrievable chunk
Lineage The record of how a chunk was produced: parser, cleaner, chunker, enrichment, embedding versions and run ID
Provenance Where content came from and how it was derived — the citation/debugging view of lineage
Content hash SHA-256 fingerprint of canonical text; identifies content independent of location
Content-addressed ID An ID derived from content (not position or randomness), so identical content gets identical IDs
doc_id / chunk_id / slug Stable document identity / content-derived chunk key / human-readable name
Section path The heading breadcrumb (["Billing", "Refunds"]) locating a chunk in its document
Text region / bounding box Page + coordinates locating text on a page, for citation highlights
Effective date / valid-until When content is in force / when it stops being true — the "as of" axis
Superseded document An old version kept for history, marked by superseded_by
Ingested-at When the pipeline saw the document — processing time, always UTC
ACL / principal / tenant Access-control entries / the user-group-role asking / the isolation boundary
Default-deny / deny-wins No matching allow ⇒ invisible; any matching deny overrides all allows
Metadata pre-filter Applying tenant/ACL/user predicates before vector ranking
Multi-tenancy patterns Shared+filter vs namespace/partition vs separate index
Row-level security (RLS) A database feature (PostgreSQL) that filters every query by policy, so permissions are enforced by the store itself; default-deny when no policy applies
Filterable / searchable / display-only field The three audiences a metadata field can serve
Cardinality Number of distinct values a field takes — decides index-worthiness
Controlled vocabulary A canonical, validated set of allowed tag/topic values
Enrichment Deriving metadata from content: deterministic rules or LLM calls
Enrichment drift Tag/output distribution shifting when prompts or models change
Schema version / migration Versioning the metadata schema so old records stay interpretable
Metadata audit Corpus-level completeness and sanity checks over stored fields
Deep link A stable URL (source URI + locator) jumping to the cited passage
Denormalisation Copying document fields onto every chunk record because the store can't join
Store payload The flat, null-free projection of ChunkMeta written to the vector store — layer fields merged to clean top-level names, derived fields whitelisted
ChunkDerived / derived fields Enrichment output stored on the chunk (topics, summary, entities, hypothetical_questions…); only short filterable fields reach the payload
suggested_doc_type The enrichment model's doc-type guess — a proposal reviewed by a human, never an automatic overwrite of doc.doc_type
Hypothetical questions LLM-generated questions stored per chunk and embedded as extra vectors resolving to the same chunk_id (05.7)
Relation extraction / graph preview (subject, predicate, object) triples from enrichment, optionally feeding a property graph — usually not worth it vs flat metadata

All terms are also collected in the glossary.


Exercises#

Use the code from this lesson (ids.py, dates.py, acl.py, audit.py, filters.py, store_payload.py, meta_models.py, enrich.py) and the running corpus:

  1. ID stability (3.3): take the v1 chunk list from ids.py and simulate a deletion in the middle ([A, C]). Which IDs survive? Then simulate the chunker merging B and C into one chunk — what happens to their IDs, and what does 05.9 have to do about it?
  2. As-of queries (4.3): write a current_versions(records, as_of) function over three versions of the returns policy and verify the boundary behaviour at exactly 2026-06-01T00:00:00Z.
  3. ACL design (5): the contracts folder has an NDA visible only to legal + the counterparty's external-counsel group, except one user who left. Express it as AclEntry dicts and prove acl_allows gets all three cases right.
  4. Expected queries (6.4): pick two sources from the running corpus (e.g. support tickets JSON, meeting transcripts) and write the filter predicates + required fields for three realistic queries each. Which fields are missing from DocumentMeta?
  5. Payload budget (6.3, 7.6): extend store_payload.py's demo — add a regions list of 50 boxes at chunk level and a 2 KB summary inside derived. Which fields reach the payload and which stay in the side table? At what point does the payload threaten the 40 KB limit?
  6. Enrichment validation (7): write a fake_llm variant that returns a topic outside TOPICS and one that returns a 10-word summary (below min_length). Confirm both raise EnrichmentError, then decide what the pipeline should do with each (retry? quarantine? default-fill?).
  7. Audit a real folder (9.1): run audit_corpus over metadata dicts you construct for five running-corpus documents. Introduce one deliberate coverage gap (e.g. all transcripts missing language) and watch field_coverage catch it.
  8. Citation payload (8): design the JSON your citation UI needs for a chunk from the scanned contracts folder (OCR'd pages, page-level bboxes) versus a chunk from a meeting transcript (timestamps, speakers). Which fields overlap, which differ?

Hints and worked answers (the invariants each answer must satisfy — your exact records will differ):

  1. Deletion [A, C]: all surviving IDs are unchanged — chunk_id covers only doc_id + chunker_version + text + occurrence, so removing B touches nothing. Merging B+C produces a new text → one new ID; A keeps its own. 05.9's diff then does: A = reused (embedding kept), merged = chunks_new (embedded once), B and C = retired (manifest rows + vectors tombstoned).
  2. current_versions keeps records where effective_date <= as_of AND (valid_until is null OR as_of < valid_until) AND superseded_by is null — or, if you index every version, picks the one in force at as_of. Boundary: at exactly 2026-06-01T00:00:00Z the new version wins, because valid_until is exclusive and effective_date inclusive (4.3).
  3. One AclEntry per principal (the model has a single principal per entry): {"principal_type": "group", "principal_id": "legal"}, {"principal_type": "group", "principal_id": "external-counsel"} and {"principal_type": "user", "principal_id": "u_departed", "effect": "deny"}. Prove three cases with acl_allows: a legal member is allowed, an external-counsel member is allowed, and u_departed is refused even if they are still in legal (deny wins) — plus a stranger refused by default-deny. tenant_id is checked before any of this.
  4. Example: tickets — "open P1 billing tickets from this week" needs status, priority, category, created_at range; DocumentMeta has the date but not status/priority/category → those are source-specific fields for ChunkDerived/a side table or an extended doc schema, not new core fields. Transcripts — "standup notes from Monday" needs a meeting date (effective_date/created_at may cover it) and possibly attendees/meeting_title; check which already exist before adding.
  5. regions is a list of objects → unfilterable → stays in the side table (or flattened only if you genuinely filter on it); a 2 KB summary in derived is text → only DERIVED_FILTER_FIELDS reach the payload, so it stays in the side table/text channel. The payload barely grows; the 40 KB threat comes from long text or huge lists inside filterable fields, not from side-table data.
  6. Out-of-vocabulary topic → EnrichmentError from vocabulary validation; a 10-word summary → EnrichmentError from min_length. Pipeline response: retry once (stricter prompt or a different model); if it still fails, quarantine the chunk or default-fill nullable fields and set needs_review — never store unvalidated enrichment output.
  7. audit_corpus's field_coverage["language"] drops below 1.0 (0.6 if two of your five documents are transcripts without it) and those records appear in failures, because language is in REQUIRED_FIELDS. Fix upstream: run deterministic language ID at ingestion (or mark the source exempt in the audit's required-fields config) — don't hand-edit records.
  8. Overlap: doc_id, title/source_uri, chunk_id, section_path or timestamps, version/effective_date, display snippet. Differ: scanned contract → page_start/page_end + regions (bbox); transcript → start_ms/end_ms (or cue timestamps) + speaker. The UI contract is "locate the passage" — page+bbox vs time+speaker are two renderings of the same idea.

Check yourself#

  1. Why is metadata "a first-class feature" rather than an afterthought in an AI data pipeline?
  2. A user asks "only contracts from 2025". Should doc_type and the date live in the chunk text, in fields, or both? Why?
  3. What are the five layers of the metadata schema, and which stage produces each?
  4. Why does doc_id hash source identity while chunk_id hashes chunk content?
  5. What goes wrong if chunk_index is included in the chunk-ID hash?
  6. Name the five date fields and the question each answers. Which one drives "as of" queries?
  7. Why must ACL filtering happen before vector ranking rather than after?
  8. What does "deny wins" mean in the ACL model, and why is tenant_id checked separately?
  9. List three constraints Pinecone puts on metadata (shape, types, size) and one Qdrant-specific one.
  10. Why is allowed_groups a list-of-strings field rather than the raw acl list?
  11. What is the difference between deterministic and LLM enrichment, and why does deterministic run first?
  12. How does a controlled vocabulary prevent the "Billing" vs "billing!" problem?
  13. What three things must be versioned to detect enrichment drift?
  14. Why doesn't adding a metadata field require re-embedding the corpus?
  15. Give two examples of metadata that must never reach the model or logs.

Further resources#

  • Pinecone, Index data overview and Filter by metadata: metadata format, 40 KB limit, filter operators, namespaces for multitenancy (verified as of November 2026).
  • Qdrant, Payload, Indexing and Multitenancy: payload types, index-before-ingest, is_tenant (verified as of November 2026).
  • Anthropic, Contextual Retrieval (September 2024): chunk-level contextual enrichment — the canonical example of metadata-like signals improving retrieval (49% fewer failed retrievals, 67% with reranking).
  • PostgreSQL, row security policies and the pgvector README (filtering with approximate indexes, iterative scans): store-side isolation and the post-filtering catch (verified as of November 2026).
  • Pydantic, Models and Validation: Field constraints, validators, model_dump.
  • spaCy, Models and Linguistic Features: en_core_web_sm and NER usage.
  • Python docs: hashlib, uuid (uuid5 for name-based IDs), datetime and zoneinfo.
  • python-dateutil, parser: parsing messy date strings (read the release notes before moving to a new major version).

← 05.7 — Advanced and Document-Specific Chunking | Module 05 overview | 05.9 — Ingestion Pipelines and Incremental Updates →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close