The knowledge pipeline
Part of the free LogicWiz Data Engineering course, Module 16: Databases for AI agents. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 8:30 on Friday. Tess forwards last night's bill from the embedding provider: the pipeline sent all 400 help articles to the model again, 880,000 tokens, and only 6 articles had changed. Ten minutes later a customer sends a screenshot. The assistant has promised her "free returns for 90 days", an offer that was deleted on 31 May. Nora reads both: "Two bugs, one pipeline."
You'll learn to
- Cut an article into chunks with a size and an overlap
- Count chunks, vectors and tokens before you pay for them
- Embed only changed text by keying chunks on a content hash
- Remove chunks whose article was edited or deleted
Learn
Two bugs, one pipeline
Both problems come from the same job. Search can only find what is in the index, and the job that keeps the index in step with the help centre is called the knowledge pipeline.
It is a normal pipeline, with stages you know from Module 6. It takes the articles that changed, turns them into clean text, cuts the text into chunks, asks the embedding model for a vector per chunk, and writes chunks and vectors to the index.
SwiftKart's version has two holes. It embeds everything every night, and embedding is the step you pay for. And it never removes anything.
The nightly knowledge pipeline
Five steps left to right: extract the documents changed since the watermark, parse them to text with headings, chunk on structure, embed only new content hashes in batches, and upsert and delete keyed by document and hash.
Read it left to right. Amber is the step you pay for. Red is the step that decides whether old text stays in the index. This lesson rebuilds the last three.
Cut the article into pieces
Start with the cutting. Why not one vector per article?
Because one vector cannot hold ten ideas. The meanings get averaged, and a search returns a long page where one sentence mattered. One vector per sentence is too small the other way: a sentence alone loses the context that makes sense of it.
So you cut text into pieces of a few hundred tokens (a token is about three quarters of a word). And you let each chunk repeat the end of the one before. That repeat is called the overlap. An idea that falls on a cut still appears whole in one chunk.
Think of photos of a long wall. Each photo overlaps the last a little, so nothing falls into the gap.
A 12-word window with a 3-word overlap
Four steps over a 33-word article: chunk 1 covers words 1 to 12, chunk 2 words 10 to 21, chunk 3 words 19 to 30 and chunk 4 words 28 to 33, each repeating the last three words of the chunk before.
The first window: words 1 to 12. It runs past the end of sentence 1 and stops at "Start a", in the middle of sentence 2.
Step back 3 words, take 12. Chunk 2 starts at word 10, so "delivery. Start a" is in both chunks. Sentence 2 now sits whole inside chunk 2.
The same again. Chunk 3 is words 19 to 30. It repeats "print the label." and stops in the middle of the refund sentence.
The last window is short. Words 28 to 33: the text ran out. Four chunks from 33 words, and 9 of the words are stored twice.
Each row is one chunk, laid over the word positions of the article. The violet pieces are the overlap.
A word-window chunker
def chunk_words(text, size, overlap):
"""Split text into windows of `size` words; each starts `size - overlap` words after the last."""
words = text.split()
step = size - overlap
chunks = []
for start in range(0, len(words), step):
chunks.append(" ".join(words[start:start + size]))
if start + size >= len(words):
break
return chunks
article = ("You can return most items within 30 days of delivery. "
"Start a return from the Orders page and print the label. "
"Refunds go back to the original payment method within 5 business days.")
for n, chunk in enumerate(chunk_words(article, 12, 3), start=1):
print(n, chunk)
Words stand in for tokens here. The four lines it prints are the four rows of the picture above. Change 12, 3 to 12, 0 and the overlap disappears, or to 40, 5 and you get one chunk.
Count before you pay
Before you pick a chunk size, count what it costs. A chunker with size S and overlap O starts a new chunk every S − O tokens.
Take one help article of 2,000 tokens, with S = 500 and O = 50:
- A new chunk starts every 500 − 50 = 450 tokens.
- After the first chunk, 1,500 tokens are left. 1,500 / 450 = 3.33, rounded up to 4 more chunks: 5 chunks.
- Each of the 4 cuts repeats 50 tokens: 2,000 + 4 × 50 = 2,200 tokens sent to the embedding model, 10% more than the text.
All 400 articles: 400 × 5 = 2,000 vectors, and 400 × 2,200 = 880,000 tokens. That is the number on Tess's bill.
Three chunk sizes for the same 400 articles
| Chunk size | Chunks per article | Vectors | Tokens embedded | Prompt tokens per question | Context cost per 1,000 questions |
|---|---|---|---|---|---|
| 200 (overlap 20) | 11 | 4,400 | 880,000 | 1,000 | $3.00 |
| 500 (overlap 50) | 5 | 2,000 | 880,000 | 2,500 | $7.50 |
| 1,000 (overlap 100) | 3 | 1,200 | 880,000 | 5,000 | $15.00 |
Read down "Tokens embedded": the same in every row. A 10% overlap adds about 10% whatever the size, so chunk size barely moves the embedding bill. It moves the number of vectors you store, and the prompt: every question carries its top k chunks to the model, k × size tokens each time (here k = 5, at Lesson 16.7's made-up price of $3 per million input tokens). Small chunks are cheap and precise, but an answer may need several of them. Big chunks carry more context but blur the vector. Pick the size with the best recall@k on your evaluation set (Lesson 16.7), not by taste.
Cut where the writer cut
The word window has a flaw you saw in step 1: it cuts wherever the count lands, even in the middle of a sentence.
Good chunkers cut on the document's own structure first: headings, then paragraphs, then sentences. They only cut by size when a piece is still too big. LangChain calls this a recursive splitter.
You gain two things. A paragraph under its heading is about one thing, so its vector is sharp. And when someone edits one paragraph, only that chunk changes. Keep each chunk's heading with it too: "within 14 days" means little without "Northwind returns" above it.
Watch what one small edit does to each kind of chunker.
One new paragraph at the top
Three steps comparing a fixed 12-word window chunker and a paragraph chunker on the returns article: before the edit both have three stored chunks; after a new first paragraph every fixed window shifts and all four chunks are new, while the paragraph chunker has one new chunk and three unchanged.
Last night. The returns article is in the index both ways: three fixed windows on the left, three paragraphs on the right. Every chunk has its embedding.
An editor adds a first paragraph. "Holiday orders can be returned until 31 January." Eight words at the top push every window eight words along. No window holds the text it held yesterday.
The same edit, cut on paragraphs. The new paragraph is one new chunk. The three old paragraphs are word for word the same, so nothing else needs an embedding.
Compare the two boxes on the last step: four embeddings on the left, one on the right, for the same eight new words.
A fingerprint for every chunk
Now the bill. To embed only what changed, you need a cheap way to ask: "have I seen this exact text before?"
A hash is a short fingerprint of a text. The same text always gives the same hash, and any change, even one space, gives a different one. SHA-256 is the usual choice.
Store each chunk's hash next to it. Tonight, hash the new chunks and compare:
- hash already stored: keep it, no new embedding;
- hash not stored: embed and insert;
- stored hash the article no longer produces: delete.
Tidy the text first (trim it, collapse double spaces), or a stray space looks like a change.
Plan tonight's sync
import hashlib
def fingerprint(text):
clean = " ".join(text.split()) # normalise spaces first
return hashlib.sha256(clean.encode("utf-8")).hexdigest()[:12]
# What the index holds today for the "Returns and refunds" article
stored = {fingerprint(t) for t in [
"You can return most items within 30 days of delivery.",
"Refunds go back to the original payment method within 5 business days.",
"Gift cards cannot be returned.",
]}
# Tonight's version: one paragraph unchanged (but with extra spaces), one edited, one new
tonight = [
"You can return most items within 30 days of delivery. ",
"Refunds go back to the original payment method within 3 business days.",
"Start a return from the Orders page.",
]
new = {fingerprint(t): " ".join(t.split()) for t in tonight}
keep = [h for h in new if h in stored]
embed = [new[h] for h in new if h not in stored]
delete = [h for h in stored if h not in new]
print("keep:", len(keep))
print("embed:", embed)
print("delete:", len(delete))
One kept, two to embed, two to delete. The first text has extra spaces and still counts as unchanged, because fingerprint tidies it before hashing. The hashes are cut to 12 characters only to print nicely: store the full 64. In a real pipeline embed is the list you send to the model.
Tonight's plan for one article
| Paragraph | Hash stored? | Action | Embedding calls |
|---|---|---|---|
| You can return most items within 30 days... | yes (the extra spaces are normalised away) | keep | 0 |
| Refunds ... within 3 business days | no: the text changed | embed and insert | 1 |
| Start a return from the Orders page. | no: new paragraph | embed and insert | 1 |
| Refunds ... within 5 business days (old) | not produced tonight | delete | 0 |
| Gift cards cannot be returned. (old) | not produced tonight | delete | 0 |
Two embedding calls instead of three, and two dead chunks removed. Across the help centre it is the difference between 2,000 chunks a night and a few dozen: only the paragraphs that really changed in 6 articles.
Remember: key a chunk by what it says, not by where it sits. Same text, same hash, no new embedding.
Tonight's sync, one step at a time
Five steps of the nightly sync for the returns article: the index before the run, two chunks deleted because their text is gone, two new chunks inserted without an embedding while the unchanged paragraph keeps its embedding, the chunk of a deleted document removed, and the embedding job filling the two new rows.
Before the run. Tonight's batch holds the new version of the returns article, document 2. The index still has yesterday's three chunks, and one chunk of the 90-day offer that was deleted on 31 May.
Step 1: delete what the article no longer says. Two stored texts of document 2 are not in tonight's batch: the 5-day refund sentence and the gift card sentence. They go.
Step 2: insert what is new. Two texts have a hash the index has never seen. They go in with an empty embedding. The 30-day paragraph is already there: it keeps its embedding and only its position changes.
Step 3: clean up deleted documents. Document 9 was deleted at the source, so its chunk leaves the index. The assistant can no longer quote the 90-day offer.
Later: the embedding job. It picks up the rows with no embedding and sends those two texts to the model. Every other live chunk was never sent.
The left box is tonight's batch and never changes. Watch the right box: each step changes the colour of the rows it touched.
The same sync in Postgres
-- 1. Remove chunks whose text is gone from the documents in tonight's batch
DELETE FROM chunks AS c
WHERE c.doc_id IN (SELECT doc_id FROM incoming)
AND NOT EXISTS (
SELECT 1
FROM incoming AS i
WHERE i.doc_id = c.doc_id AND md5(i.content) = c.content_hash
);
-- 2. Insert new text with no embedding yet; known text only gets its new position
INSERT INTO chunks (doc_id, content_hash, chunk_no, content, embedding)
SELECT doc_id, md5(content), chunk_no, content, NULL
FROM incoming
ON CONFLICT (doc_id, content_hash) DO UPDATE SET chunk_no = EXCLUDED.chunk_no;
-- 3. Documents deleted at the source lose their chunks
DELETE FROM chunks
WHERE doc_id IN (SELECT doc_id FROM documents WHERE deleted_at IS NOT NULL);
SELECT doc_id, chunk_no, content, embedding IS NULL AS needs_embedding
FROM chunks
ORDER BY doc_id, chunk_no;
Three statements, the three steps you walked through. The key is (doc_id, content_hash), not the position, so the unchanged paragraph that moved from 1 to 2 keeps its embedding. New rows wait with embedding NULL. Step 3 removes the deleted 90-day offer: it is the step teams forget.
The embedding job is a queue
The new rows sit in the table with an empty embedding. That is the to-do list. A separate embedding job reads the rows WHERE embedding IS NULL, sends the texts to the model and writes the vectors back. A table used as a to-do list like this is called a queue.
Four habits keep it boring:
- Batch. Send tens to hundreds of chunks per request, not one.
- Back off. Providers cap requests and tokens per minute. On a 429 error, wait and retry (Module 3).
- Share fairly.
FOR UPDATE SKIP LOCKEDlets each worker lock its own batch and skip rows another worker holds. - Write only if nothing changed. Store the vector only if the row still has the same hash and no embedding.
One worker takes a batch, then writes back safely
BEGIN;
-- Lock 2 rows to embed; a second worker running this now would get the next 2
SELECT c.doc_id, c.chunk_no, c.content
FROM chunks AS c
WHERE c.embedding IS NULL
AND EXISTS (SELECT 1 FROM documents AS d WHERE d.doc_id = c.doc_id AND d.deleted_at IS NULL)
ORDER BY c.doc_id, c.chunk_no
LIMIT 2
FOR UPDATE SKIP LOCKED;
-- The model returned a vector for the refund sentence: write it only if nothing changed
UPDATE chunks
SET embedding = '{0.1,0.6,0.7,0}'
WHERE doc_id = 2
AND content_hash = md5('Refunds go back to the original payment method within 3 business days.')
AND embedding IS NULL;
COMMIT;
SELECT doc_id, chunk_no, embedding IS NULL AS needs_embedding
FROM chunks
ORDER BY doc_id, chunk_no;
With SKIP LOCKED, no two workers embed the same chunk and nobody waits. The late chunk of the deleted document is never picked up, because its document is gone. The content_hash condition in the UPDATE is the safety check: if the paragraph changed again while the model was working, the old vector is not stored, so a retry or a slow worker does no harm.
When the model changes
One change does force you to embed everything again: a new embedding model. Vectors from two models cannot be compared, so you cannot swap them a few at a time.
Build the new index next to the old one, fill it in the background, test it, then switch every reader over in one step.
Changing the embedding model without downtime
Two versions of the chunks table side by side: version 1 with model A serves reads through a view, version 2 with model B is backfilled and indexed, and the view is switched in one transaction once the evaluation set passes.
Read it left to right. Write new chunks to both versions, fill v2, build its index, compare recall on the evaluation set, then switch the view. In Postgres a schema change runs inside a transaction, so readers see v1 or v2, never a mix. You pay for two copies during the switch, and the provider's tokens-per-minute limit sets how long the fill takes.
What to store with every chunk
| Column | Why |
|---|---|
| docid, chunkno, heading | Find the source, show a citation, rebuild the order |
| tenant, access level | Filter so a search only sees what this user may see (Lessons 16.4 and 16.6) |
| sourceurl, title | Let the answer link to the page it came from |
| the source's updatedat | Date filters, and freshness checks (Lesson 16.7) |
| contenthash | Skip unchanged text; find duplicates |
| embeddingmodel, embeddedat | Know which vectors to rebuild when the model changes |
Copy the columns you filter on (tenant, product, language, date) onto every chunk row, even though the document has them too. Vector databases call these columns metadata or the payload.
Deleted at the source, alive in the index. The most embarrassing agent bug is quoting a policy that no longer exists. A pipeline that only inserts and updates never removes anything. Handle deletes on purpose: a deleted_at on documents (or a comparison with the list of live documents), their chunks removed with them, and a daily check for chunks whose document is gone. The same path serves a customer's request to erase their data.
Numbers to remember
| What | Value | Good to know |
|---|---|---|
| Usual chunk size | 200 to 800 tokens, with an overlap of 10 to 20% | A token is about three quarters of a word |
| Chunks from a document of T tokens | 1 + ceil((T − S) / (S − O)), or 1 when T ≤ S | S is the size, O the overlap |
| Tokens embedded | T + (chunks − 1) × O | The overlap is paid once per cut |
| Prompt tokens per question | k × S | Top 5 chunks of 500 tokens: 2,500 |
| SHA-256 in Python | hashlib.sha256(text.encode("utf-8")).hexdigest() | 64 hex characters. digest() gives 32 raw bytes instead |
| SHA-256 in Postgres | sha256(convertto(content, 'UTF8')) | It hashes bytes. md5(content) is fine for spotting changes, but not for security |
| FOR UPDATE SKIP LOCKED | Postgres 9.5 and later | What makes a table a fair work queue |
| Embedding 50 million chunks of 500 tokens again | 25 billion tokens to send | Why a model change is planned, not done overnight |
Frameworks ship the hash pattern: LangChain's indexing API keeps a record manager of content hashes and cleans up chunks of deleted documents, and LlamaIndex's ingestion pipeline skips text it has seen. Databricks Vector Search keeps an index in sync with a Delta table, and the open-source pgai Vectorizer does the same inside Postgres.
What changed at SwiftKart
Friday night's run looks different. Six articles changed, so the pipeline chunks six articles, finds the handful of paragraphs with a new hash and embeds only those. The 90-day offer leaves the index with its document, and a daily check lists any deleted document that still has chunks.
Tess's next bill is for a few thousand tokens, not 880,000.
The index is now right. The search over it is not yet: a customer types the error code "PAY-402" and gets a page about cards in general. Lesson 16.4 adds keyword search and filters to the vectors.
In one line
Cut text on its own structure with a little overlap, key each chunk by a hash of its content so only changed text is embedded, and delete chunks whose source is gone.
Interview corner
How do you choose chunk size and overlap?
Start from the document structure: split on headings and paragraphs, then cap the size, typically a few hundred tokens with 10 to 20% overlap so boundary ideas stay whole. Then do the arithmetic: a 2,000-token article at 500/50 gives 5 chunks and 2,200 embedded tokens, so the embedding bill moves little with size, while the vector count and the prompt (k × size tokens per question) move a lot. Finally decide with data: run an evaluation set at two or three settings and compare recall@k at the prompt size you can afford.
How do you keep a RAG index up to date without re-embedding everything?
Load only documents that changed since the last run (a watermark or change feed), chunk them, and hash each normalised chunk. Insert chunks whose hash is new with a NULL embedding, keep chunks whose hash is already stored, and delete stored chunks the document no longer produces. Documents deleted at the source lose all their chunks. An embedding job then fills only the NULLs, in batches.
What happens when you change embedding model?
Every vector has to be rebuilt, because vectors from different models are not comparable, and the question must be embedded with the same model as the chunks. Build a new index or column alongside the old one, fill it in the background, check recall on the evaluation set, then switch reads over in one step and drop the old one. Storing the model name with each chunk makes this safe.
Several workers embed chunks from the same table. How do you stop them doing the same work or overwriting each other?
Treat the table as a queue: each worker opens a transaction and takes a batch with SELECT ... WHERE embedding IS NULL ... LIMIT 100 FOR UPDATE SKIP LOCKED, so rows locked by another worker are skipped instead of waited on. It sends the batch to the model in one request, then updates each row only if its content hash is unchanged and it still has no embedding, which makes retries and slow workers harmless. Rate-limit errors back off and retry, and a monitor watches the count of rows waiting and the age of the oldest.