Metadata, Indexing, Quality and Lineage

Good retrieval starts long before the query: describe content, check it, trace it and manage the index like any other release.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

Agents retrieve well when every item has useful metadata, passes quality checks before publication and can be traced to its source. Treat the search index as a versioned, rebuildable product: test a new version beside the old one, switch only when results do not get worse, and keep measuring freshness and completeness after release.

What you will learn: metadata design, quality dimensions and gates, lineage and traceability, vector index choices and lifecycle, and ways to measure freshness and completeness.
Prerequisites: RAG Explained and Agentic RAG and Knowledge Ingestion and Real-Time Pipelines.

Beginner Describe your content

Metadata: the facts about a fact

Metadata describes content: who owns it, who may see it, when it was written, what it covers and where it came from. Similarity search compares meaning, but it cannot tell that a policy was replaced last month or that it applies only in one country. Metadata can.

FieldUsed forExample
Stable identifier and versionUpdates, deletion, citationspolicy-leave, version 4
Source locationLetting people verifyDocument system path or URL
OwnerFixing errors and reviewingA team, not only a person
Audience and sensitivityPermission filteringAll staff, restricted
Effective and review datesExcluding expired contentEffective from 1 January
ScopeChoosing the right variantRegion, product, customer type
Type and statusPreferring authoritative sourcesApproved policy, draft, chat note
LanguageMatching and translationen, es

Design rules

  1. Start from filters and decisions. Add a field when something will use it.
  2. Use controlled values. "UK", "U.K." and "United Kingdom" split one group into three.
  3. Inherit where sensible. Chunks inherit the document's audience and dates.
  4. Record where the value came from. A human-assigned label deserves more trust than a guessed one.
  5. Fail closed on permissions. Unknown audience means not published.

What quality means

DimensionQuestionExample check
AccuracyIs it true?Owner review of a sample
CompletenessIs anything missing?Expected documents and fields are present
ConsistencyDoes it contradict itself?Two current policies with different limits
TimelinessIs it current?Review date not passed
UniquenessIs it duplicated?Same text under two identifiers
ValidityDoes it follow rules?Allowed values and formats
Readability for retrievalDid extraction work?No empty pages or scrambled tables
Intermediate Gates, lineage and indexes

A publication gate

Automated checks should decide what can enter the knowledge base. Some problems must block publication, others should warn an owner. This example applies both kinds.

"""A publication gate for a knowledge base: block, warn or pass."""
from datetime import date

TODAY = date(2026, 6, 1)
docs = [
    {"id": "d1", "owner": "hr", "text": "Leave is 25 days.",
     "review_by": date(2027, 1, 1), "audience": "staff"},
    {"id": "d2", "owner": "", "text": "Expenses need receipts.",
     "review_by": date(2027, 1, 1), "audience": "staff"},
    {"id": "d3", "owner": "it", "text": "Leave is  25 days.",
     "review_by": date(2026, 9, 1), "audience": "staff"},
    {"id": "d4", "owner": "it", "text": "Use the old VPN.",
     "review_by": date(2025, 12, 31), "audience": "staff"},
    {"id": "d5", "owner": "fin", "text": "Budget draft.",
     "review_by": date(2027, 1, 1), "audience": None},
]

def check(doc, seen):
    blocks, warns = [], []
    if not doc["audience"]:
        blocks.append("no audience, so permissions cannot be applied")
    key = " ".join(doc["text"].lower().split())
    if key in seen:
        blocks.append(f"duplicate of {seen[key]}")
    if not doc["owner"]:
        warns.append("no owner")
    if doc["review_by"] < TODAY:
        warns.append("review date passed")
    seen.setdefault(key, doc["id"])
    return blocks, warns

seen, published = {}, []
for doc in docs:
    blocks, warns = check(doc, seen)
    state = "BLOCK" if blocks else "WARN " if warns else "PASS "
    print(state, doc["id"], "; ".join(blocks + warns))
    if not blocks:
        published.append(doc)

complete = sum(bool(d["owner"]) for d in published) / len(published)
fresh = sum(d["review_by"] >= TODAY for d in published) / len(published)
print(f"published {len(published)}/{len(docs)}  "
      f"owner coverage {complete:.0%}  in-date {fresh:.0%}")

Output:

PASS  d1 
WARN  d2 no owner
BLOCK d3 duplicate of d1
WARN  d4 review date passed
BLOCK d5 no audience, so permissions cannot be applied
published 3/5  owner coverage 67%  in-date 67%

The duplicate was caught although its spacing differs, because the comparison normalizes whitespace and case. The document without an audience is blocked: publishing it would force a guess about who may read it. The expired and unowned documents are published with warnings, which is a policy choice. For a safety manual you might block expired content instead. The coverage figures show the quality of what was actually published, which is the number worth tracking over time.

Blocking has a cost

If a gate blocks too much, the knowledge base silently loses coverage and the agent answers from whatever remains. Report blocked counts by source and owner, and set a time limit for fixing them.

Conflicting and duplicate content

Retrieval often returns two versions of the truth. Prevent it upstream: mark superseded documents, keep one authoritative copy and give status and effective date to the ranker as filters. Where a genuine conflict remains, the agent should report both with their sources and dates, not blend them into a new rule that nobody wrote.

Lineage and source traceability

Lineage records what each item was made from: file to text, text to chunk, chunk to vector, chunks to summary, summary to answer. It serves two directions. Backward, it explains an answer. Forwards, it shows everything affected when a source changes or must be withdrawn.

Sourceid and version
Parsed textparser version
Chunkspage and offsets
Vectorsembedding model
Answerchunks cited
Record each link when the item is created. Reconstructing it later is unreliable.
"""Record what each artifact was made from, then ask what a change affects."""
from collections import defaultdict

made_from = {
    "policy.pdf@v3": [],
    "text:policy@v3": ["policy.pdf@v3"],
    "chunk:policy#1": ["text:policy@v3"],
    "chunk:policy#2": ["text:policy@v3"],
    "vector:policy#1": ["chunk:policy#1"],
    "vector:policy#2": ["chunk:policy#2"],
    "faq.md@v7": [],
    "chunk:faq#1": ["faq.md@v7"],
    "summary:benefits": ["chunk:policy#2", "chunk:faq#1"],
    "answer:8841": ["summary:benefits", "vector:policy#2"],
}
used_by = defaultdict(list)
for item, parents in made_from.items():
    for parent in parents:
        used_by[parent].append(item)

def walk(start, edges):
    found, queue = [], [start]
    while queue:
        for nxt in edges.get(queue.pop(0), []):
            if nxt not in found:
                found.append(nxt)
                queue.append(nxt)
    return found

print("If policy.pdf@v3 is withdrawn, rebuild or remove:")
for item in walk("policy.pdf@v3", used_by):
    print("  ", item)
sources = [i for i in walk("answer:8841", made_from) if not made_from[i]]
print("answer:8841 rests on:", ", ".join(sorted(sources)))

Output:

If policy.pdf@v3 is withdrawn, rebuild or remove:
   text:policy@v3
   chunk:policy#1
   chunk:policy#2
   vector:policy#1
   vector:policy#2
   summary:benefits
   answer:8841
answer:8841 rests on: faq.md@v7, policy.pdf@v3

Withdrawing one policy affects its text, both chunks, both vectors, a summary that mixed it with another source and an answer already given. The summary is the easy one to forget, because it lives in a different store and still looks valid. The backward walk shows that the answer rested on two sources, so a complaint about it can be investigated precisely.

Open standards help systems share this information. OpenLineage defines events describing jobs, runs and datasets, and the W3C PROV family provides a general vocabulary of entities, activities and agents. For agent answers, also record the model, prompt version and retrieval query, linked to the trace described in Agent Tracing and OpenTelemetry.

Vector index design

Exact search compares the query with every vector. It is accurate and perfectly adequate for modest collections. Approximate nearest neighbor indexes trade a little recall for much faster search.

ChoiceHow it worksTrade-off
Exact scanCompare with all vectorsPerfect recall, cost grows with size
HNSW graphWalk a layered neighbor graphFast and accurate, uses much memory, slower to build
IVF partitionsSearch the nearest clusters onlyCompact, needs training data and retuning as data shifts
QuantizationStore compressed vectorsSaves memory, loses precision unless rescored

Measure recall against exact search on your own data, with your real filters. Filtering interacts with approximate search: some systems filter after finding candidates and can return too few results for a selective filter. Test the narrowest permission group, not only an administrator.

Record the embedding model and its version with every vector. Vectors from different models are not comparable, even when their dimensions match.

Expert Lifecycle and continuous measurement

Index lifecycle: build beside, then switch

Never rebuild a live index in place. Create a new version, fill it, evaluate it, then move an alias or pointer. Keep the old version until you are confident, so rollback takes seconds.

"""Build a new index beside the old one; switch only if tests do not regress."""
import re

docs = {"d1": "Resetting your password", "d2": "Password policy rules",
        "d3": "Claiming travel expenses", "d4": "Error E1234 on the printer"}
tests = {"reset password": "d1", "expense claim": "d3",
         "E1234": "d4", "password rules": "d2"}

def words(text):
    return set(re.findall(r"[a-z0-9]+", text.lower()))

def trigrams(text):
    joined = " ".join(re.findall(r"[a-z0-9]+", text.lower()))
    return {joined[i:i + 3] for i in range(len(joined) - 2)}

def build(features):
    return {"features": features,
            "rows": {key: features(text) for key, text in docs.items()}}

def search(index, query):
    q = index["features"](query)
    def score(key):
        row = index["rows"][key]
        return len(q & row) / len(q | row)
    return max(sorted(index["rows"]), key=score)

def evaluate(index):
    return {q: search(index, q) == want for q, want in tests.items()}

indexes = {"v1": build(words), "v2": build(trigrams)}
alias = "v1"
before, after = evaluate(indexes[alias]), evaluate(indexes["v2"])
for query in tests:
    print(f"{query:<15} v1={'ok' if before[query] else 'MISS':<5}"
          f"v2={'ok' if after[query] else 'MISS'}")
regressed = [q for q in tests if before[q] and not after[q]]
if not regressed and sum(after.values()) > sum(before.values()):
    alias = "v2"
print("regressions:", regressed, "-> live index:", alias)

Output:

reset password  v1=ok   v2=ok
expense claim   v1=MISS v2=ok
E1234           v1=ok   v2=ok
password rules  v1=ok   v2=ok
regressions: [] -> live index: v2

The two toy indexes stand in for two embedding or indexing configurations. Version 2 uses character fragments, so "claim" can match "claiming". The release rule requires both an overall improvement and no query that used to work and now fails. An average alone could hide a lost exact match on a product code. Real test sets need many more queries, grouped by type, and should be checked with the permission filters in place.

Lifecycle eventWhat to do
New embedding model or chunkingFull rebuild beside the live index, compare, switch
Normal content changesIncremental upsert and delete by identifier
Many deletionsCheck the engine's guidance on compaction or rebuild
GrowthRecheck recall, latency and memory at the new size
RetirementRemove old versions, including their backups according to policy

During a rebuild, send live changes to both versions, or replay them to the new one before switching. Otherwise the switch loses everything that changed during the build.

Measuring freshness and completeness

A knowledge base can pass every check on the day it is built and decay afterward. Measure it continuously.

MeasureDefinition
Update delayTime from source change to searchable change, reported at high percentiles
Staleness rateShare of indexed items whose source has a newer version
Orphan rateIndexed items whose source no longer exists
CoverageShare of expected sources that are present, against an independent inventory
Review currencyShare of items within their review date
Unanswered questionsReal requests with no suitable evidence

Completeness needs an outside reference. An index cannot tell you what it never received, so compare it with the source system's own list. Unanswered questions are a second valuable signal: group them weekly and ask owners whether the content is missing, hidden by permissions or written in words users do not use.

Weight quality by use

A stale page that nobody retrieves matters less than a slightly outdated one cited a hundred times a day. Join quality measures with retrieval logs and send owners the list ordered by impact.

Who fixes what

RoleResponsibility
Content ownerAccuracy, review dates, audience
Pipeline teamComplete and timely processing, lineage
Search teamIndex quality, tests and releases
Agent teamCitations, conflict handling, feedback collection

Give users a simple way to report a wrong answer, and route the report through lineage to the content owner. Close the loop by telling the reporter what changed.

Illustrative example: duplicate travel rules

An assistant sometimes quotes an old hotel limit. Lineage shows the answers come from a copy of the policy saved in a team folder. The owner marks the folder copy as superseded, the gate begins blocking near duplicates from non-authoritative sources, and the test set gains the question so the fault cannot return unnoticed.

Where to start

You do not need every control at once. Introduce them in the order that removes the most risk for the least work.

  1. Identifiers, source links and audience. Without these you cannot update, delete, cite or protect anything.
  2. Blocking checks for unknown audience and empty or failed extraction.
  3. A small test set of real questions with expected sources, run before each index change.
  4. Owners and review dates, with a weekly list of overdue items ordered by how often they are retrieved.
  5. Reconciliation with the source inventory to find missing and orphaned entries.
  6. Finer lineage through summaries and answers, once derived content appears.

Each step produces a number you can report, which helps justify the next one. If metadata must be added to a large backlog, begin with the most retrieved material. Automated tagging can propose values, but sample its accuracy by field and keep guessed values distinguishable from confirmed ones. Never let a guessed audience grant access.

Common mistakes

  • Adding dozens of metadata fields that nothing reads.
  • Publishing items with unknown permissions.
  • No link from chunk back to a source version.
  • Forgetting summaries and caches when withdrawing a source.
  • Switching embedding models in place.
  • Judging a new index only by an average score.
  • Measuring completeness from the index itself.

Checklist

  • Required metadata fields and allowed values are defined.
  • Blocking and warning rules are written and owned.
  • Lineage links sources, derived items and answers.
  • Embedding model and pipeline versions are stored.
  • Recall is measured with real filters.
  • New index versions pass regression tests before switching.
  • Rollback has been tried.
  • Freshness, orphans and coverage are monitored.

Frequently asked questions

Can a model generate the metadata?

It can suggest topics, summaries and types. Measure accuracy on a sample, mark the values as generated and keep permissions and legal status under human or system-of-record control.

Do I need an approximate index?

Not while exact search meets your latency target. Moving to an approximate index adds tuning and recall testing, so do it for a measured reason.

How often should content be reviewed?

According to how fast it changes and what an error would cost. Set a review date per type and prioritize heavily used items.

Is lineage only for compliance?

No. It is also the fastest way to debug a wrong answer and to know what to rebuild after a change.

References and further reading

Next steps