Joel Stevick

Ingestion · INGEST 4 · stage 4 of 7

Chunk each page

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.

Runs in: Demo Worker, the private Worker behind the DEMO service binding, demo/src/. New to Cloudflare? How these fit together
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

Pinned to joelstevick-demo-rag-pipeline at 6a9c6c7.

demo/src/app.ts The demo Worker.

upload(): INGEST 4

segment · lines 328–337View on GitHub

Draws this upload's id prefix and turns every page into numbered chunks.

Calls chunkPage() randomKey() Shared helpers

  // 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.

6 random bytes → 8 characters

  // Counts the chunks across the whole file, so each one knows its place.  let n = 0

One counter for the whole file Ingestion

Whatn starts at 0 and is not reset between pages.

Whyn becomes both the id's last part and seq, so chunks are numbered in reading order across the whole file.

  // 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).  const chunks: 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.

id: <account id>-<upload>-<n>seq = n

demo/src/chunks.ts The chunker: one pure function and its size constant.

Module scope

module scope · lines 1–14View on GitHub

The licence, and the two guarantees the chunker makes.

// Copyright (c) 2026 Joel Stevick// SPDX-License-Identifier: MIT// Licensed under the MIT License: https://opensource.org/licenses/MIT

Licence Never runs

WhatThe copyright and the MIT licence, with an SPDX identifier.

WhyThe repository is public under the MIT licence, and the SPDX line lets tools read the licence automatically.

/** * 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.

CHUNK_CHARS

constant · lines 15–17View on GitHub

The longest a chunk may be, in characters.

/** Roughly a paragraph: long enough for a whole point, short enough that five are a page. */export const CHUNK_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.

CHUNK_CHARS = 900

chunkPage()

function · lines 18–46View on GitHub

Cuts one page's text into pieces of at most 900 characters, in reading order.

Called by upload(): INGEST 4

/** `text` cut into pieces of at most CHUNK_CHARS, in reading order; a blank page gives none. */export function chunkPage(text: string): string[] {

Signature: one page in, pieces out Ingestion

WhatTakes one page's text and returns its pieces in order; a blank page returns an empty array.

WhyIt is a pure function of a string, so tests call it without any binding, and the same text always gives the same chunks.

  // The pieces so far, and the text not yet cut.  const pieces: 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.    const window = 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.

    // The fallback: the last space in the window, so a word is not split in two.    const space = window.lastIndexOf(' ')

The last space Ingestion

WhatThe index of the last space in the window.

WhyThe last space is the fallback when no sentence end is usable, so no word is split. Only a space counts here; a line break is not searched for.

    // 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.

CHUNK_CHARS / 2 = 450

    // 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.

  // What is left fits in one piece; nothing is left only when the page was blank.  if (rest.length > 0) pieces.push(rest)  return pieces}

The remainder Ingestion

WhatWhat is left, at most 900 characters, is the last piece; nothing is pushed when it is empty.

WhyOnly a blank page yields no chunk, and INGEST 1 has already dropped blank pages, so every page that reaches chunkPage yields at least one chunk.