Build a versioned support corpus for retrieval
Create a small synthetic corpus with stable document and section IDs, versions, source URIs, visibility and effective dates.
By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 11 minutes to read.
In short
A RAG system can only be as good as the documents it searches, so the first job is a small, well-labelled corpus. Every document gets a stable ID, stable section IDs, a version number, a source URI, a visibility label and an effective date. Those fields later let you cite sources, filter by permission, pick the newest rule and delete cleanly.
Think of it like this: A corpus without IDs and versions is like a library with no catalogue: the books are there, but nobody can say which edition you quoted.
Explained simply
Retrieval-augmented generation, or RAG, means the assistant looks up relevant documents first and then answers using them. The set of documents it may look in is called the corpus. If the corpus is messy, out of date or unlabelled, no clever search or prompt can fix the answers that come out.
For this path you build a small corpus for a fictional company, Contoso, whose support team answers questions about refunds, invoices and accounts. You write 10 to 20 short documents yourself, so there are no copyright or privacy problems. Real customer emails or tickets never go into a lab corpus.
Each document gets an ID that never changes, such as KB-0042. When someone edits it, the ID stays and the version number goes up. Each heading inside it gets a section ID, such as KB-0042#refund-window. Later, an answer can cite exactly that section, and you can always find which version it came from.
Two more labels matter. Visibility says who may read the document, for example public, internal or billing. The effective date says from when the content applies. A refund rule that changed on 1 March should not be quoted for a question about February, and a billing-only page should never reach a support agent.
Press Play on a diagram to walk through it one step at a time.
- Identity
- doc_id: KB-0042
- version: 3
- content_hash
- Provenance
- source_uri
- owner team
- licence or 'synthetic'
- Access
- visibility: internal
- allowed scopes
- Time
- effective_from
- effective_to (nullable)
- Sections
- KB-0042#refund-window
- KB-0042#exceptions
- 1Read file
kb/refunds.md in Git
- 2Parse front matter
doc_id, version, visibility, dates
- 3Split by heading
One section per H2
- 4Hash content
SHA-256 of the body
- 5Insert rows
documents and sections tables
In depth
Writing a synthetic corpus that tests something
A useful lab corpus is small but tricky on purpose. Write documents that overlap, so retrieval has to choose. Include two versions of the same policy with different effective dates, so you can test freshness. Add one billing-only document with a unique phrase, so you can test that permissions hold. Add a page full of error codes, which keyword search should find and vector search may miss.
Keep the source files in Git as Markdown with a small front matter block at the top. Git then gives you history and review for free, and the ingest job reads the same files on every machine. If you use licensed text instead, record the licence in the metadata and check that it allows storing and quoting.
- 10 to 20 documents, 2 to 6 sections each
- At least one document with two dated versions
- At least one billing-only canary document
- One page of exact codes and product names
- Licence field: synthetic, or the real licence name
Choosing IDs that survive edits
Document IDs should be assigned once by a person or a counter and written into the file, not computed from the title or file name. Titles change and files move; the ID must not. Section IDs can be derived from a slug of the heading, such as refund-window, because a heading change usually means the meaning changed too. If you need sections to survive heading edits, store an explicit anchor in the source.
The full address of a passage is then doc_id, version and section_id. Chunk IDs built later extend that, for example KB-0042:v3:refund-window:0. Because every part is deterministic, re-running ingestion on the same files produces the same IDs, which is what makes upserts and citation checks possible.
- 1Chunk
KB-0042:v3:refund-window:0
- 2Section
refund-window (slug of the heading)
- 3Version
3, increases on every content change
- 4Document
KB-0042, assigned once, never reused
Modelling the tables
Store one row per document version in a documents table with a composite primary key of doc_id and version. Keep title, source URI, visibility, effective_from, an optional effective_to, a status (active, superseded or deleted) and a SHA-256 content hash. Put flexible extras such as owner team or product line in a jsonb metadata column, but keep anything you filter on often as a real column with a CHECK constraint.
A sections table holds doc_id, version, section_id, heading, ordinal and body, with a foreign key to documents. Later modules add chunks and embeddings that point to sections. Copy visibility and status onto chunks too, so the retrieval query can filter without extra joins, and keep them in sync inside the ingest transaction.
- documents: PRIMARY KEY (doc_id, version)
- sections: PRIMARY KEY (doc_id, version, section_id)
- CHECK constraints on visibility and status
- jsonb for optional metadata only
Effective dates and visibility as data
Effective dates answer the question: which rule applied on a given day? effective_from is required; effective_to is empty while the rule is current. When version 4 starts on 1 March, version 3 gets effective_to set to 28 February. A query about a date picks the version whose range contains that date, and a query about today picks the one with no end date.
Visibility is deliberately coarse in this path: public, internal and billing. A caller's scopes come from their verified identity, and retrieval keeps only rows whose visibility is in that list. Keeping the label as a column, rather than as logic in code, means the database, tests and audits all read the same truth.
Learn it in 4 short steps
About 40m each. Track them with a timer in your plan.
- 1Write or license source documents~40m
- 2Assign stable document and section IDs~40m
- 3Store version, source URI and effective date~40m
- 4Record visibility for each document~40m
Key points
- Use synthetic or properly licensed text only; never copy real customer data into a lab corpus.
- IDs must not change when the text changes; the version number changes instead.
- Section IDs derived from a slug of the heading give citations that point to a specific passage.
- Visibility and effective dates are data, stored next to the text, not rules hidden in code.
- A content hash tells you whether a new upload really changed anything.
Key terms
Tap a card to flip it. 0/6 known
Examples
CREATE TABLE documents (
doc_id text NOT NULL,
version int NOT NULL CHECK (version > 0),
title text NOT NULL,
source_uri text NOT NULL,
visibility text NOT NULL CHECK (visibility IN ('public','internal','billing')),
effective_from date NOT NULL,
effective_to date,
status text NOT NULL DEFAULT 'active',
content_hash text NOT NULL,
metadata jsonb NOT NULL DEFAULT '{}',
PRIMARY KEY (doc_id, version)
);One row per document version. Old versions stay for audit; status marks the current one.
A source file with front matter
Contoso's refund policy changed on 1 March 2026. Step 1: copy the old file to keep history in Git, or simply edit it and let Git track the change. Step 2: bump version from 3 to 4 and set effective_from to 2026-03-01. Step 3: keep doc_id KB-0042 unchanged. Step 4: commit. The ingest job will see a new hash and a new version, add version 4 and end version 3 the day before.
---
doc_id: KB-0042
version: 4
title: Refund policy
source_uri: kb/refunds.md
visibility: internal
effective_from: 2026-03-01
licence: synthetic
---
## Refund window
Customers can request a refund within 30 days of purchase.
## Exceptions
Annual plans are refunded pro rata after 30 days.Parsing it into rows in Python
Prerequisites: Python 3.12 and the PyYAML package. Step 1: split the file at the front matter markers. Step 2: load the YAML into a dictionary. Step 3: split the body on level-two headings and slugify each heading into a section ID. Step 4: hash the body. Expected evidence: printing the result shows KB-0042, version 4 and two section IDs, refund-window and exceptions. Running it twice prints identical output.
import hashlib, re, yaml
def parse(text: str) -> dict:
_, front, body = text.split("---\n", 2)
meta = yaml.safe_load(front)
parts = re.split(r"^## (.+)$", body, flags=re.M)[1:]
sections = [
{"section_id": re.sub(r"[^a-z0-9]+", "-", h.lower()).strip("-"),
"heading": h, "body": b.strip()}
for h, b in zip(parts[0::2], parts[1::2])
]
meta["content_hash"] = hashlib.sha256(body.encode()).hexdigest()
return {**meta, "sections": sections}Quick reference
- Document address: doc_id + version + section_id; chunk IDs extend it
- Never derive doc_id from a title or file name; assign it once
- Bump version on every content change; keep old versions for audit
- effective_to stays NULL while a version is current
- Visibility values in this path: public, internal, billing
- SHA-256 content hash detects real changes cheaply
- Synthetic text only in labs; record the licence for anything else
Common mistakes
- Using the file name or database row number as the ID, so a rename or reload breaks every saved citation.
- Overwriting a document in place, which loses the version a past answer was based on.
- Leaving visibility out of the first schema and trying to add permissions after retrieval is built.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write three synthetic Contoso documents in Markdown with front matter: one public, one internal, one billing-only. Give each a stable doc_id and two sections.
- Exercise 2medium
Create the documents and sections tables in a local PostgreSQL database with constraints that reject an unknown visibility and a duplicate section.
- Exercise 3hard
Add version 2 of KB-0042 starting 2026-03-01 and write a query that returns the version in force on any given date.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Can I use real company documents for practice?
- Only if you are allowed to store and process them and they contain no personal data. Synthetic documents are safer and let you design the tricky cases you want to test.
- Why not store everything in one jsonb column?
- You can, but fields you filter on, such as visibility and status, are easier to constrain, index and audit as real columns.
- How many documents does a useful lab corpus need?
- Ten to twenty short documents are enough if they include overlapping topics, dated versions and a restricted canary.