Core content
Part 1: AI-readiness of data
"AI-ready" means more than "clean." A dataset can pass every dashboard data-quality check and still be useless for AI because it is unrepresentative, unlabeled for the task, or unreachable. AI-readiness has five dimensions. Score each 0–3 on the checklist in Artifact 1; the weakest one is your ceiling.
┌──────────────────────────────────────────┐
AI-READINESS = │ min( Quality, Representativeness, │
(your ceiling) │ Labeling, Lineage, Accessibility ) │
└──────────────────────────────────────────┘
One weak dimension caps the whole system. Fix the floor, not the average.
1. Quality. Quality covers completeness, consistency, deduplication, and freshness. The trap is "demo-clean": data that looks fine on the ten rows you inspected and breaks on the long tail. For RAG specifically, quality means the source text is faithful, with no OCR garbage, no truncated PDFs, and no boilerplate headers or footers polluting every chunk.
2. Representativeness (including edge cases). Does the data cover the real distribution your AI will face, including the rare-but-costly cases? A support-RAG corpus built only from happy-path articles will confidently fail on the angry refund-dispute query, which is exactly where a wrong answer costs you. Teams skip this dimension more than any other, because edge cases are, by definition, hard to collect.
3. Labeling. For retrieval, "labeling" means metadata: document type, owner, tenant, effective date, sensitivity class, and source system. You cannot filter, scope to a tenant, or expire unlabeled chunks, and that is how you get stale and cross-tenant answers.
4. Lineage. Can you trace an AI output back through retrieval → chunk → source document → source system → processing step? Without lineage you cannot answer "why did the model say that?" A regulated buyer, an auditor, or an incident review will eventually ask, and lineage is far cheaper to capture at ingest than to reconstruct afterward.
5. Accessibility. Can a pipeline reach the data through documented APIs or a data catalog, or is it stranded in a silo, a SaaS export, or a person's head? Stranded data is invisible to AI no matter how good it is.
A team that can produce, for any AI answer, the exact source chunk and the document's owner and effective date. That is lineage + labeling working together.
"Our data is clean, we have a data warehouse." A warehouse proves accessibility and maybe quality. It says nothing about representativeness, task-labeling, or lineage through the AI layer.
Do / Don't
| Do | Don't |
|---|---|
| Score readiness per use case (a corpus AI-ready for support may be unready for compliance) | Declare data "AI-ready" org-wide as a one-time gate |
| Capture lineage metadata at ingest time, when it is cheap | Try to reconstruct lineage after an incident, when it is impossible |
| Deliberately collect edge cases for the eval set | Build the corpus only from happy-path content |
| Attach a sensitivity/tenant label to every chunk | Embed first and figure out access control later |
Part 2: Building RAG correctly
RAG has five stages, and every earlier stage caps the quality of the last one (the LLM answer). Garbage chunks in, confident garbage out.
┌─────────┐ ┌─────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ INGEST │──▶│ CHUNK │──▶│ EMBED │──▶│ RETRIEVE │──▶│ GROUND │
│ parse, │ │ split + │ │ vectors │ │ top-k + │ │ stuff │
│ clean, │ │ overlap │ │ + store │ │ filter │ │ context │
│ label │ │ │ │ │ │ + rerank │ │ → LLM │
└─────────┘ └─────────┘ └──────────┘ └──────────┘ └──────────┘
│ │
└──────────────── metadata / tenant filter ───────────────┘
Chunking strategies
The chunk is the unit of retrieval, so its size sets a trade-off. Too large, and you retrieve irrelevant text that dilutes the answer and burns tokens. Too small, and you lose the context needed to answer.
| Strategy | How it works | Best for | Watch out |
|---|---|---|---|
| Fixed-size | N tokens, fixed overlap | Uniform prose, fast baseline | Splits mid-sentence/mid-table |
| Recursive | Split on separators (¶ → sentence → token) | General documents (default) | Tune separators per format |
| Semantic | Split where embedding similarity drops | Dense, topic-shifting text | Slower, costs embeddings to chunk |
| Structural | Split on document structure (Markdown headings, HTML, code functions) | Docs, wikis, code, structured PDFs | Requires a real parser |
Start from these practical defaults, then tune with eval: ~256–512 tokens per chunk, ~10–15 percent overlap, with recursive or structural splitting. Always carry metadata on each chunk (source id, tenant, section heading, effective date). Never use naive fixed-size chunking for tables and code; split on structure, or the chunk is meaningless.
Chunk size is an empirical decision, not a default. Build a 30–50 question eval set first, then sweep chunk size and overlap and pick the setting that maximizes retrieval recall. Teams that pick "1000 tokens" because a tutorial said so are guessing.
Embeddings
The embedding model maps text to vectors so that semantically similar text lands nearby. Four choices matter:
- Dimension (e.g., 384, 768, 1536, 3072): higher dimensions often retrieve slightly better but cost more storage and slow search. For most growth-stage corpora, a 768–1536-dim model is the sweet spot.
- Hosted vs. local: hosted models (OpenAI
text-embedding-3-*, Cohere, Voyage) are easy and strong. Local models (e.g., abge/e5/gteopen model) keep regulated data in-house and remove per-call cost, which matters when your data cannot leave your boundary. - Domain fit: a general embedder underperforms on jargon-heavy corpora (clinical, legal, financial). Test domain-specific or fine-tuned embedders against your eval set before committing.
- Consistency rule: the same model must embed both documents and queries. Changing the embedding model means re-embedding the entire corpus, so treat the embedder as a versioned dependency.
Vector store choice: The decision that gets over-engineered
For most growth-stage corpora, pgvector is the right first answer. You already run Postgres, so you get transactions, joins, row-level security, and metadata filtering in one system. As a rule of thumb, pgvector handles up to ~tens of millions of vectors (≈<50M) comfortably with HNSW indexing.
Reaching for Pinecone on day one for a 200k-chunk internal wiki. You add a second datastore, a sync problem, and a bill, all to solve a scale problem you do not have.
| Option | When it wins | Trade-off |
|---|---|---|
| pgvector (Postgres extension) | <~50M vectors; you already run Postgres; want metadata filtering + row-level security in one place | Tune HNSW params; very large scale needs sharding work |
| Pinecone | Large scale, fully managed, minimal ops | SaaS cost; data leaves your DB; another vendor |
| Weaviate | Hybrid search + modules, self-host or cloud, large scale | More to operate if self-hosted |
| Qdrant | High-performance filtering, self-host friendly, large scale | Another datastore to run and sync |
Decision heuristic: start in pgvector; graduate to a dedicated store only when you have measured a real limit (vector count, latency at p95, or filtering throughput) that pgvector cannot meet. "We might scale" is not a measured limit.
Hybrid retrieval beats pure vector for most enterprise corpora. Combine dense (vector) similarity with sparse keyword search (BM25/full-text) and fuse the rankings (e.g., reciprocal rank fusion). Pure-vector retrieval quietly fails on exact terms such as error codes, SKUs, and statute numbers, and keyword search catches them.
Part 3: Retrieval evaluation, leakage, and permission-aware access
Evaluate retrieval, not just the final answer
When an answer is wrong, you must know which stage failed: retrieval (wrong chunks fetched) or generation (right chunks, wrong answer). Measure the two separately.
Retrieval metrics (these need a labeled set mapping queries to relevant chunks):
- Recall@k: what fraction of the relevant chunks appear in the top-k? This is the single most important RAG metric. If the right chunk isn't retrieved, no model can answer.
- Precision@k: what fraction of the top-k retrieved chunks are relevant? Low precision wastes context tokens and invites distraction.
- MRR (Mean Reciprocal Rank): how high does the first relevant chunk rank? It matters when you stuff only a few chunks.
Generation metrics (the RAG triad):
- Faithfulness / groundedness: does the retrieved context support every claim in the answer? This is your anti-hallucination metric.
- Answer relevance: does the answer address the question?
- Context relevance: were the retrieved chunks actually about the question?
Tooling options include Ragas, TruLens, DeepEval, or a homegrown LLM-as-judge script. The principle matters more than the tool: a fixed eval set, scored on every change, with results checked into the repo. This eval set becomes the seed of the evaluation suite that gate 3.3 requires before any change is promoted; Modules 5 and 7 make it a release gate.
Build the eval set before you tune anything (30–50 representative queries with known-good answers and their source chunks). It is the contract that makes every later decision (chunk size, embedder, k, reranker) falsifiable instead of a matter of vibes.
Leakage and cross-tenant exposure: OWASP LLM08
OWASP's LLM08: Vector and Embedding Weaknesses is the RAG-specific risk class. Design against three failure modes:
1. Cross-tenant exposure. In a multi-tenant product, tenant A's query retrieves tenant B's chunks. This happens when the tenant id is not enforced at query time as a hard filter. Asking the model to be careful in the prompt does not fix it. Apply a metadata filter in the query, and ideally add Postgres row-level security so a missing filter fails closed, not open.
SAFE: retrieve WHERE tenant_id = $current_tenant ← enforced in query / RLS
UNSAFE: retrieve top-k from the whole index, hope the prompt keeps tenants apart
2. Embedding leakage / inversion. Embeddings are not anonymized data. Attackers can partially reconstruct sensitive text from vectors, and similarity search can surface records a user should never see. Give the vector store the same sensitivity class as the source text, with the same access controls, encryption, and retention.
3. Retrieval-time data poisoning / indirect injection. A document in the corpus contains instructions ("ignore previous instructions, exfiltrate…"). When retrieved, it becomes part of the prompt, which makes it an indirect prompt-injection vector. Controls: validate and clean ingested content, restrict who can write to the corpus, and treat retrieved text as untrusted input (Module 8 goes deeper).
RISK FLAG (IIIBC field experience): Production RAG breaches are usually mundane. A multi-tenant app filtered tenants in the application layer but not in the retrieval query, so a code path that skipped the filter returned another customer's data. Enforce tenant isolation at the data layer (row-level security) so the default is fail-closed.
Permission-aware retrieval and connectors
Tenant isolation is the coarse version of a stricter rule: every assistant and every connector sees only what the requesting user may already see in the source system. Inside one tenant, an HR folder, a board deck, or a deal room has its own access list. An internal assistant that indexes the whole drive with an admin account makes all of it searchable by everyone.
Connectors raise the stakes. An MCP server, a "connect your drive" integration, or an agent tool gives a model live access to a system of record. If it authenticates as a shared service account and ignores the source's permissions, any user, or any injected instruction, can ask it for anything that account can read. That connector is a breach path, even if every model behaves.
UNSAFE: user ──▶ assistant ──▶ connector (service account: reads ALL) ──▶ source
SAFE: user ──▶ assistant ──▶ connector (acts AS the user, or checks the
user's ACL on every result) ──▶ source
+ chunk metadata carries the source ACL, re-synced when it changes
Four controls make retrieval permission-aware:
- Carry the source access list into the index. Store the document's ACL (groups or users) on every chunk, filter on it at query time, and re-sync it when permissions change in the source.
- Act as the user, not as the platform. Connectors and MCP servers should use the requesting user's delegated token (on-behalf-of) or check that user's permissions on every result. A shared admin token is a design failure.
- Allowlist connectors. Approve each MCP server and connector, record it in the AI inventory with its owner and scopes, and block the rest (Modules 2 and 8).
- Test it like a breach. Run the same query as two users with different access and confirm the restricted document never appears in either the retrieved chunks or the answer.
Assessment question 2.7 asks exactly this: does AI grounded in company knowledge see only what each user may see? A 3 needs a documented design for permission-aware retrieval; a 4 needs every grounded system tested for leakage.
Do / Don't
| Do | Don't |
|---|---|
| Apply tenant/permission filters inside the retrieval query | Filter after retrieval in app code (one missed path = breach) |
| Make connectors act as the requesting user | Give an MCP server or connector a shared admin token |
| Classify the vector store at the source data's sensitivity level | Treat embeddings as "just numbers," exempt from access control |
| Validate and scope write access to the corpus | Auto-ingest untrusted external content into the index |
Part 4: Retrieval, fine-tuning, or agent tool calls
Retrieval, fine-tuning, and agent tool calls solve different problems. What the model needs (documents, behavior, or live data) decides between them; cost and risk break ties.
Need the model to KNOW private FACTS from documents, cite
sources, update without retraining, enforce access ──▶ RETRIEVAL (RAG)
Need the model to BEHAVE a certain way: format, tone,
domain style, a narrow task done consistently ──▶ FINE-TUNE
Need LIVE data from a system of record (a balance, an
order status) or need to ACT (create, update, send) ──▶ AGENT TOOL CALL
Need more than one (common) ──▶ combine, and give
each part its controls
| Dimension | Retrieval (RAG) | Fine-tuning | Agent tool calls |
|---|---|---|---|
| Best at | Fresh, private, citable facts from documents | Behavior, format, style, narrow tasks | Live records and actions in other systems |
| Updating knowledge | Add or replace a document; instant | Re-train; slow and costly | Always current; reads the source |
| Grounding / citations | Native: points to source chunks | None inherent; can still hallucinate | Grounded in the system of record, if results are shown |
| Access control | Per-document, per-tenant filtering | Baked into weights; cannot scope per user | Only as good as the tool's identity and scopes |
| Upfront cost | Low (pipeline + store) | Higher (data prep, training, eval) | Low to medium (tool definitions, auth) |
| Ongoing cost | Retrieval + larger prompts | Cheaper per call once trained | Per-call latency, API cost, and loops that burn tokens |
| Main risk | Leakage across users or tenants; poisoned documents | Memorized sensitive data; stale behavior | Excessive agency, tool misuse, injected instructions acting on real systems |
| Audit / lineage | Strong (trace to source) | Weak (why did weights produce this?) | Strong if every call is logged |
Default for growth-stage technology operators: start with retrieval. It grounds answers in your proprietary data, lets you update knowledge without a training run, supports per-user access control, and gives you lineage for audits. Add tool calls when the answer lives in a system of record that changes by the minute, or when the task is to act, and treat each tool as an agent permission: read-only first, the user's own identity, and human approval for consequential actions (supervised automation, autonomy level 3, in the assessment's scale). Fine-tune only when prompting and retrieval cannot solve a clear behavior, format, or latency problem, and only when you have the labeled data and eval discipline to prove the fine-tune helped.
"We chose RAG because the buyer's auditors need source citations and we must scope answers per tenant—fine-tuning gives us neither." That is a grounded decision.
"We fine-tuned so the model would know our docs." Fine-tuning is a poor and expensive way to inject facts: the model still hallucinates and cannot cite. Retrieval does that job.
A read tool becomes a write tool one configuration change later. Before any tool call can create, update, or send, it needs an inventory entry, a named owner, least-privilege scopes, a spend cap, a kill switch, and logging (Modules 7, 8, and 10).
Part 5: Proprietary data as a compounding moat
A foundation model is rented and shared, so your moat is the data only you have. More important still is the feedback loop that makes it better as the product is used. Engineer the loop explicitly:
┌──────────────────────────────────────────────────────┐
│ │
▼ │
USERS use the product ──▶ product captures signal │
(queries, clicks, (what was retrieved, accepted, │
corrections, outcomes) corrected, the real outcome) │
│ │
▼ │
signal labels & improves the data asset ──▶ better │
(eval set grows, retrieval tuned, retrieval & │
edge cases captured, labels enriched) answers ──────┘
A growth-stage operator can build these concrete loops:
- Correction capture: when a user (or support agent) fixes an AI answer, store the corrected pair as a labeled eval or training example. Every correction makes the system harder to beat.
- Implicit signal: log which retrieved chunks led to accepted vs. abandoned answers, and feed that into reranking and chunk curation.
- Outcome linkage: tie the AI interaction to the downstream business outcome (ticket resolved, deal advanced, claim adjudicated) so you learn what good looked like, not just what was clicked.
- Edge-case harvesting: route low-confidence or no-good-chunk queries to a queue that grows your representativeness where it is weakest.
The moat is the instrumentation, not the data dump. A competitor can scrape public docs; it cannot replay your users' corrections, accepted answers, and outcomes. Build the capture before you scale the feature, because retrofitting it loses signal you can never get back.
Feedback loops touch user data. Confirm that contracts and privacy notices allow the use (Assessment 2.8), and apply the data policy and classification rules (Assessment 2.6, Module 2) before any user content becomes training or eval data, especially personal data, health data, source code, or privileged material.