chunkPage cuts each page's text into chunks of at most 900 characters, cutting at a sentence end where it can. No chunk crosses a page, and each chunk is a verbatim slice of its page's text. upload() gives every chunk an id of the form <account id>-<upload>-<n> (the demo account's id, a random prefix for this upload, and a counter) and a seq, its position in the file, and passes the list to INGEST 5.
demo/src/app.ts10 / 10 lines on this page explainedlines 328-337 of 1124; the rest are on other stage pages
demo/src/chunks.ts46 / 46 lines on this page explainedevery line of the file
In the browser
runs in the visitor's browser, on the demo page
Ingestion
runs when a PDF's text is uploaded
Query time
runs when the Worker answers a question or a search_documents call from the MCP server, and in the request handling every route shares, in the Worker and in the site's functions, which uploads and removals pass through too
MCP request
runs on a request to the MCP server or its OAuth endpoints
Site request
runs on a site request that is not a question, an upload, an MCP call or the cron: a page load, a session read, the demo page's /api/grants calls, an admin read, a file's removal
Scheduled
runs in the Worker's daily cron job
Eval run
runs when the eval harness runs on a developer's machine
MCP host
runs in an MCP host outside the Worker: the search loop example, on a developer's machine (npm run search) or in its test
Module load
runs once, when the module is loaded
Type only
erased by the TypeScript compiler; never runs
Never runs
a comment, a licence or markup with no behaviour of its own
// INGEST 4 · chunk each page// A random prefix per upload: `n` restarts at 0 for each file, so no two uploads (at once or not) mint the same chunk id.const upload = randomKey(6).toLowerCase().replace(/[^a-z0-9]/g, 'x')
A random prefix per upload Ingestion
WhatrandomKey(6) returns 6 random bytes as 8 URL-safe base64 characters, which are lower-cased, with any - or _ replaced by x.
Whyn restarts at 0 for every upload. Without a per-upload part, every file in a demo account would number its chunks from 0, and the second file's ids would collide with the first's in D1, where id is the primary key, and in Vectorize. The random prefix keeps them apart, including for two uploads running at once. It uses the same alphabet as the account id (line 146), a–z and 0–9, which also keeps _, a LIKE wildcard, out of the pattern INGEST 5's undo deletes by.
// A chunk id is <demo>-<upload>-<n>: the demo's id, this upload's random prefix, the chunk's place in the file (`seq`, which widen walks).constchunks: Chunk[] = pages.flatMap((p) =>chunkPage(p.text).map((text) => ({ id: `${demo.id}-${upload}-${n}`, file: name, page: p.page, text, seq: n++ })))
Pages to chunks Ingestion
WhatEach page's text goes through chunkPage, and each piece becomes a chunk whose id ends in n and whose seq is n. flatMap joins the pages' chunks into one list.
WhyASK 5's widening walks seq to find a chunk's neighbours, across a page break too, because consecutive seq values are adjacent text. The account id at the start of every chunk id makes the ids unique across demo accounts. INGEST 6 reuses the chunk id as the vector's id, so a vector hit maps directly to its row.
/** * A page's text, cut into the pieces the demo retrieves. * * The shape of Howard's Lantern's worker/src/code-chunks.ts: about * CHUNK_CHARS a piece, cut at a sentence end where one is near, else at a * space. A piece never crosses a page, so every source names one page, and * every piece is a verbatim slice of that page's text, so "Show the passage" * shows the words as they were extracted. */
Two guarantees Never runs
WhatThe doc comment states the chunker's rule, which follows the shape of Howard's Lantern's code-chunks.ts, and its two guarantees: a piece never crosses a page, and every piece is a verbatim slice of its page's text.
WhyBecause a chunk holds text from one page, every citation names exactly one page. Because chunks are verbatim, "Show the passage" displays the words as pdf.js extracted them. The answer check (ASK 6–7) looks for every figure an answer states in the chunks it cites or in the question, so a figure found in a cited chunk is in the page's own words.
/** Roughly a paragraph: long enough for a whole point, short enough that five are a page. */exportconstCHUNK_CHARS = 900
CHUNK_CHARS = 900 Module load
WhatA chunk holds at most 900 characters.
WhyThe comment gives the reason: roughly a paragraph, long enough for a whole point and short enough that five make a page. In general, smaller chunks give BM25 and the embedding a more specific match but split points across chunks; ASK 5's widening rejoins neighbouring chunks when an answer spans them.
// The pieces so far, and the text not yet cut.constpieces: string[] = []let rest = text.trim()
The pieces and the text not yet cut Ingestion
Whatpieces collects the output; rest is the trimmed text not yet cut.
Whyupload() already passes text trimmed at INGEST 1; trimming again keeps the guarantees for any other caller, such as the tests in demo/tests/health.test.ts.
// Cut pieces off the front of `rest` until what is left fits; that remainder is the last piece.while (rest.length > CHUNK_CHARS) {// The most one piece can hold, from the front of what is left.constwindow = rest.slice(0, CHUNK_CHARS)
While the rest is too long, look at the first 900 Ingestion
WhatWhile rest is longer than CHUNK_CHARS, window holds its first 900 characters.
WhyEvery cut point is chosen inside the window, which keeps every piece within 900 characters.
The same idea, shown in the course's code: Chunking: one subject per chunk, split at headings, then by size From From engineer to AI engineer, Ep 6: Ingestion is ETL
Explained in Ep 2: Chunking a page: 900 characters, cut at a sentence end From RAG deep dive, Ep 2: RAG Embeddings Explained: BM25, Vector Search and Cosine Similarity
// The page sends each line of the PDF on its own line, so a sentence can end in ".\n" as well as ". ".const sentence = Math.max(...['. ', '? ', '! ', '.\n', '?\n', '!\n'].map((end) =>window.lastIndexOf(end)))
The last sentence end Ingestion
Whatsentence is the largest index in the window of any of the six sentence endings, or -1 when there is none.
WhyThe page sends each PDF line on its own line (demo.html appends \n to every item where pdf.js sets hasEOL), so a sentence that ends a line ends in ".\n", with no space after the dot. A decimal point ("3.5") never matches, because a digit follows the dot.
// Cut after the last sentence end if it is past the halfway mark (so no piece is a stub), else at the last space, else mid-word at the limit.const cut = sentence > CHUNK_CHARS / 2 ? sentence + 1 : space > 0 ? space : CHUNK_CHARS
Choose the cut Ingestion
WhatIf the sentence end is past index 450 (half of CHUNK_CHARS), the cut falls right after the punctuation mark; else at the last space, if there is one after index 0; else at exactly 900, mid-word.
WhyThe halfway rule stops a sentence end near the start of the window from producing a stub of a few words, so a long sentence is cut at a space instead. A mid-word cut happens only when 900 characters contain no space at all.
// The piece goes out trimmed, and the rest starts after the cut, its leading space or line break dropped. pieces.push(rest.slice(0, cut).trim()) rest = rest.slice(cut).trim() }
Emit the piece, keep the rest Ingestion
WhatThe text before the cut is trimmed and pushed. rest becomes the text after the cut, trimmed, which drops the space or line break at the cut.
WhyTrimming only the ends keeps each piece a contiguous substring of the page, so the verbatim guarantee holds. Pieces do not overlap.