Stable IDs and Source Metadata
Give every chunk a deterministic ID derived from its document and content, a UUID for vector stores, and the source metadata that citations, filters and evaluation need; then prove that ingestion is repeatable and re-embed only what changed.
Contentsand lesson path
On this page
- The problem
- Step 1: Two ways to derive a chunk ID
- Step 2: See which IDs survive an edit
- Step 3: Write a complete record for every chunk
- Step 4: Prove that ingestion is deterministic
- Step 5: Update only what changed
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Chunking
- Why Chunk Boundaries Matter Concept · 15 min
- Parsing Documents, Scans and Tables into Clean Text Worked example · 20 min
- Lab: Three Chunkers, One Corpus Lab · 25 min
- Stable IDs and Source Metadata Worked example · 15 min
- Measuring Chunking by Retrieval Recall Lab · 20 min
- Check: Choose a Chunking Strategy Knowledge check · 6 questions
What you will learn
- Apply fixed-size, recursive and structure-aware chunking with overlap, and attach a stable ID and source metadata to every chunk.
01. The problem
The chunkers from the lab return offsets, not identities. The obvious next move, calling uuid.uuid4() for each chunk as it goes into the vector store, quietly breaks three things:
- References. Anything that stores a chunk ID, such as a cached answer, a user's feedback on a passage or a saved evaluation run, points at nothing after the next ingestion, because every ID is new.
- Citations. An answer from last week that cites a chunk ID can no longer be resolved to its source once the index has been rebuilt.
- Updates. Re-running ingestion adds a second copy of every chunk, because nothing tells the store that two different random IDs hold the same text. And when one page changes, you cannot tell which chunks to re-embed, so you re-embed everything.
The fix is deterministic ingestion: the same input and configuration always produce the same chunks, the same IDs and byte-identical output. This worked example builds it in the chunk-lab folder from the lab, reusing corpus/ and chunkers.py.
02. Step 1: Two ways to derive a chunk ID
A chunk ID has a document part and a chunk part. For the document part, use the name of the source plus the file's path relative to the corpus root, with forward slashes: larkspur-docs/retries.md. Never use an absolute path, which differs between machines, or a URL with tracking parameters. For the chunk part there are two common choices:
- Position: the chunk's number within the document, such as
#0003. Simple and readable. - Content hash: a hash of the chunk's exact text, such as
#76bf008d086e9a61. It changes exactly when the text changes.
import hashlib
from chunkers import Chunk
def positional_ids(doc_id: str, chunks: list[Chunk]) -> list[str]:
return [f"{doc_id}#{i:04d}" for i in range(len(chunks))]
def content_ids(doc_id: str, text: str, chunks: list[Chunk]) -> list[str]:
ids, seen = [], {}
for c in chunks:
digest = hashlib.sha256(text[c.start:c.end].encode("utf-8")).hexdigest()[:16]
seen[digest] = seen.get(digest, 0) + 1 # the same text twice in one document
suffix = "" if seen[digest] == 1 else f"-{seen[digest]}"
ids.append(f"{doc_id}#{digest}{suffix}")
return idscontent_ids() hashes the UTF-8 bytes of the chunk with SHA-256 and keeps the first 16 hex characters (64 bits), far more than enough to tell apart the chunks of one document. Hashing is why lesson 2 normalised Unicode: two spellings of the same character would otherwise give two IDs. If the same text appears twice in one document, a repeated warning box for instance, the later copies get -2, -3 and so on, in document order.
03. Step 2: See which IDs survive an edit
A writer adds one sentence to the first section of retries.md. The script below chunks the page before and after the edit, with the fixed-size and the structure-aware chunker, under both ID schemes, and counts which IDs survive and whether they still name the same text. It edits a copy in memory, so the file on disk is unchanged.
from pathlib import Path
from chunkers import fixed_chunks, structure_chunks
from ids import content_ids, positional_ids
DOC_ID = "larkspur-docs/retries.md"
old = Path("corpus/retries.md").read_text(encoding="utf-8")
new = old.replace( # a writer adds one sentence to the first section
"non-zero code.\n",
"non-zero code. Jobs that\nare cancelled by a user do not count as failed.\n")
CHUNKERS = {"fixed": lambda t: fixed_chunks(t, 96, 16),
"structure": lambda t: structure_chunks(t, 96)}
print("chunker ids before same id same id, other text new id")
for chunker_name, chunker in CHUNKERS.items():
for scheme in ("position", "content"):
versions = []
for text in (old, new):
chunks = chunker(text)
ids = (positional_ids(DOC_ID, chunks) if scheme == "position"
else content_ids(DOC_ID, text, chunks))
versions.append({i: text[c.start:c.end] for i, c in zip(ids, chunks)})
before, after = versions
same = before.keys() & after.keys()
moved = sum(before[i] != after[i] for i in same)
print(f"{chunker_name:<10} {scheme:<9} {len(before):>6} {len(same):>8} "
f"{moved:>20} {len(after.keys() - same):>7}")python edit_test.pychunker ids before same id same id, other text new id
fixed position 3 3 3 0
fixed content 3 0 0 3
structure position 4 4 1 0
structure content 4 3 0 1Read it row by row:
- fixed, position: all three IDs still exist, and all three now name different text. This is the dangerous case. Nothing fails, and every citation or reference that used these IDs silently points at the wrong passage.
- fixed, content: no ID survives. The new sentence shifted every window, so every chunk's text and hash changed. That is correct, but you re-embed the whole page for one sentence.
- structure, position: the IDs survive and only one names new text, but only because the edit fell inside an existing section. Add a section near the top and every later number shifts, which puts you back in the first row.
- structure, content: the three untouched sections keep their IDs, and only the edited section gets a new one.
Content-hash IDs on structure-aware chunks are the combination to aim for: an ID changes exactly when the text it names changes. Positional IDs are fine for corpora that are rebuilt from scratch and never edited in place, such as a frozen snapshot of a dataset.
04. Step 3: Write a complete record for every chunk
build_chunks.py chunks the corpus, gives each chunk its IDs and metadata, and writes one JSON record per line. The namespace UUID was generated once with uuid.uuid4() and is now a constant in the code; generate your own the same way and commit it.
import json
import re
import sys
import uuid
from dataclasses import asdict, dataclass
from pathlib import Path
from chunkers import structure_chunks
from ids import content_ids
ROOT = Path("corpus")
SOURCE = "larkspur-docs"
BASE_URL = "https://docs.example.org/larkspur/"
CHUNKER = "structure v1, size=96, o200k_base" # change it when chunking changes
NAMESPACE = uuid.UUID("4a891bba-c078-45a5-91bf-3a1bb34dd043") # made once, then fixed
@dataclass(frozen=True)
class ChunkRecord:
chunk_id: str
point_id: str # a UUID for vector stores that only accept UUIDs or integers
doc_id: str
source_url: str
heading_path: list[str]
char_start: int
char_end: int
chunker: str
text: str
def anchor(heading: str) -> str:
"""A GitHub-style heading anchor; check the rules of your own docs site."""
return re.sub(r"[^a-z0-9 _-]", "", heading.lower()).replace(" ", "-")
def records_for(path: Path) -> list[ChunkRecord]:
text = path.read_text(encoding="utf-8")
doc_id = f"{SOURCE}/{path.relative_to(ROOT).as_posix()}" # never absolute
chunks = structure_chunks(text, size=96)
records = []
for chunk_id, c in zip(content_ids(doc_id, text, chunks), chunks):
url = BASE_URL + path.relative_to(ROOT).with_suffix("").as_posix()
if len(c.headings) > 1:
url += "#" + anchor(c.headings[-1])
records.append(ChunkRecord(
chunk_id=chunk_id,
point_id=str(uuid.uuid5(NAMESPACE, chunk_id)),
doc_id=doc_id,
source_url=url,
heading_path=list(c.headings),
char_start=c.start,
char_end=c.end,
chunker=CHUNKER,
text=text[c.start:c.end],
))
return records
if __name__ == "__main__":
out_path = Path(sys.argv[1] if len(sys.argv) > 1 else "chunks.jsonl")
records = [r for p in sorted(ROOT.rglob("*.md")) for r in records_for(p)]
with out_path.open("w", encoding="utf-8", newline="\n") as out:
for r in records:
out.write(json.dumps(asdict(r), ensure_ascii=False, sort_keys=True) + "\n")
print(f"wrote {len(records)} chunks to {out_path}")Each field has a job:
chunk_idis the readable, stable ID you log, cite and diff.point_idexists because some vector databases accept only unsigned integers or UUIDs as point IDs (Qdrant is one).uuid.uuid5()maps the same name in the same namespace to the same UUID on every run, so it is as stable aschunk_id.doc_idandsource_urllet you filter by document and link a citation to the rendered page and section. The anchor rule here imitates GitHub; site generators differ, so check two anchors against your live site.heading_pathfeeds the contextual header and tells a reader where the passage sits.char_startandchar_endlet you highlight the passage, fetch its neighbours for small-to-big retrieval, and score retrieval against labelled spans in lesson 5.chunkerrecords the configuration, including the tokenizer, that produced the chunk. Change it whenever chunking changes, so old and new chunks never mix unnoticed.textkeeps the chunk itself. A store that holds only vectors cannot show or quote what it retrieved.
For PDFs, add the page number, computed from the page_starts saved while parsing. For any source, a version, such as a commit hash or last-modified date, tells you which revision a citation refers to. Print the record of one chunk to see the result:
import json
with open("chunks.jsonl", encoding="utf-8") as f:
records = [json.loads(line) for line in f]
for r in records:
if r["heading_path"][-1] == "Dead-letter queue":
for key in ("chunk_id", "point_id", "source_url", "heading_path",
"char_start", "char_end", "chunker"):
print(f"{key:<13} {r[key]}")python build_chunks.py
python show.pywrote 17 chunks to chunks.jsonl
chunk_id larkspur-docs/retries.md#76bf008d086e9a61
point_id 1f1dd033-ccbb-50cb-a2d7-6a604c574734
source_url https://docs.example.org/larkspur/retries#dead-letter-queue
heading_path ['Retries and failures', 'Dead-letter queue']
char_start 329
char_end 558
chunker structure v1, size=96, o200k_base05. Step 4: Prove that ingestion is deterministic
Determinism is a property you test, not one you assume. Build the index twice and compare the two files byte for byte; cmp prints nothing when they match, so the echo runs only on success. On Windows, use fc /b run1.jsonl run2.jsonl instead.
python build_chunks.py run1.jsonl
python build_chunks.py run2.jsonl
cmp run1.jsonl run2.jsonl && echo "identical"wrote 17 chunks to run1.jsonl
wrote 17 chunks to run2.jsonl
identicalThe result comes from a handful of habits in build_chunks.py: sorted() around the file listing, because directory order differs between file systems; sort_keys=True and a fixed newline in the JSON output; no timestamps or random values inside records; and IDs hashed from exact text. Keep run information, such as when ingestion ran, in a separate manifest file. Pin your library versions too, because a new tokenizer or parser release can move boundaries; that is why the chunker field names the tokenizer. Put this two-run comparison in your tests so that a change that breaks determinism fails the build.
06. Step 5: Update only what changed
Now make the edit on disk, rebuild, and compare the new index with the first run by chunk_id. In a real pipeline the result is the work list for the vector store: delete the IDs that disappeared, embed and upsert the new ones, leave the rest alone.
from pathlib import Path
page = Path("corpus/retries.md")
text = page.read_text(encoding="utf-8")
page.write_text(text.replace(
"non-zero code.\n",
"non-zero code. Jobs that\nare cancelled by a user do not count as failed.\n",
), encoding="utf-8")import json
import sys
def load(path: str) -> dict[str, dict]:
with open(path, encoding="utf-8") as f:
return {r["chunk_id"]: r for r in map(json.loads, f)}
old, new = load(sys.argv[1]), load(sys.argv[2])
print("unchanged:", len(old.keys() & new.keys()))
print("delete: ", sorted(old.keys() - new.keys()))
print("upsert: ", sorted(new.keys() - old.keys()))python edit_doc.py
python build_chunks.py run3.jsonl
python diff_index.py run1.jsonl run3.jsonlwrote 17 chunks to run3.jsonl
unchanged: 16
delete: ['larkspur-docs/retries.md#2629a7706f1cf02c']
upsert: ['larkspur-docs/retries.md#14d3e84c8f5dd9d7']One sentence changed, so one chunk is deleted and one is embedded; the other 16 keep their vectors. Upserting by ID also makes re-runs safe, because writing the same ID twice replaces the point instead of adding a copy. One subtlety: the sections of retries.md after the edit kept their IDs, but their character offsets moved. Rewrite the metadata of every chunk in a changed document, which is cheap, and re-embed only the new IDs. Run python make_corpus.py afterwards to restore the original page for the next lab.
07. Common mistakes
08. Check your understanding
09. Apply it
In your practice project, give every chunk of your documentation set a content-hash chunk_id, a point_id from uuid5, its relative source path, its heading path and offsets, and the URL of the rendered page with the section anchor; check two anchors against the live site. Run ingestion twice and compare the files byte for byte. Then edit one page and confirm that diff_index.py lists changes for that page only. Commit the namespace UUID and the chunker string together with the code.
10. Review prompt
Without looking back:
- What breaks when chunk IDs are random? Name three things that hold on to IDs.
- After a sentence is inserted near the top of a page, what happens to positional and to content-hash IDs, with fixed-size and with structure-aware chunks?
- List the fields of a chunk record and what each is for.
- Which habits make ingestion byte-for-byte repeatable, and how do you test it?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.