Joel Stevick

Ingestion · INGEST 5 · stage 5 of 7

Store the chunks

Each chunk is written to D1 with one INSERT. With the visitor's consent, which the site sends as X-Demo-Keep: 1, the INSERTs are preceded by a DELETE of this file's old archive and a copy of each page's text in archived_pages. The statements run through D1's batch API, 100 at a time, and the chunk list continues to INGEST 6.

Runs in: Demo Worker, the private Worker behind the DEMO service binding, demo/src/. New to Cloudflare? How these fit together
demo/src/app.ts32 / 32 lines on this page explainedlines 338-369 of 1124; the rest are on other stage pages
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 5

segment · lines 338–369View on GitHub

Writes the archive and the chunks in D1 batches.

Calls json() Shared helpers keeps() Consent and the archive

  // INGEST 5 · store the chunks (and archived pages) in D1  // With consent, each page's text is archived beside its chunks; a re-upload of the file replaces it.

Chunks, and the archive with consent Never runs

WhatThe stage marker, and a comment stating the archive rule.

WhyThe chunks are deleted with the documents after 10 idle days. The archive is the copy kept for up to 25 months for analysis and golden sets, so it is written only for visitors the site may record.

  const archive = keeps(request)    ? [        env.DB.prepare('DELETE FROM archived_pages WHERE demo_id = ? AND file = ?').bind(demo.id, name),        ...pages.map((p) => env.DB.prepare('INSERT INTO archived_pages (demo_id, file, page, text) VALUES (?, ?, ?, ?)').bind(demo.id, name, p.page, p.text)),      ]    : []

The archive statements Ingestion

WhatWhen keeps(request) is true (X-Demo-Keep is exactly '1'), the list holds a DELETE of this file's archived pages followed by one INSERT INTO archived_pages per page with text; otherwise the list is empty. The statements are prepared here and run in the batches at line 355.

WhyThe idle purge deletes chunks and file rows but never archived_pages, so a file uploaded again after a purge would violate the archive's PRIMARY KEY (demo_id, file, page). Running the DELETE first makes the re-upload replace the old archive. In this repository the site's mayRecord (functions/_lib/track.ts) always returns false, so the site's Pages Function always sends X-Demo-Keep: 0 and the list is always empty.

table: archived_pagesPRIMARY KEY (demo_id, file, page)KEEP_MONTHS = 25

  try {    // The archive first, then one insert per chunk.    const statements = [      ...archive,      ...chunks.map((c) => env.DB.prepare('INSERT INTO chunks (id, demo_id, file, page, text, seq) VALUES (?, ?, ?, ?, ?, ?)').bind(c.id, demo.id, c.file, c.page, c.text, c.seq)),    ]

One INSERT per chunk Ingestion

WhatInside a try, the statement list is the archive statements followed by one INSERT INTO chunks per chunk.

WhyThe archive's DELETE must run before its INSERTs, and putting the archive first places the DELETE in the first batch. The chunk ids are new (INGEST 4's random prefix), so the INSERTs need no conflict clause.

table: chunksindex: chunks_demo ON chunks(demo_id)

The same idea, shown in the course's code: Each chunk stored with its source: file, page and position From From engineer to AI engineer, Ep 6: Ingestion is ETL
    // In batches of 100 statements; a failure part-way, whichever batch, is undone below.    for (let i = 0; i < statements.length; i += 100) await env.DB.batch(statements.slice(i, i + 100))

Batches of 100 Ingestion

WhatThe statements go to env.DB.batch 100 at a time, and each batch is awaited before the next.

WhyD1 runs a batch as one SQL transaction, so a failing statement rolls back its whole batch. Consecutive batches are separate transactions, so a failure in the third batch leaves the first two committed, and the catch at line 356 undoes them. A demo account may hold 500,000 characters (LIMITS.chars) at up to 900 a chunk (CHUNK_CHARS), so a large upload can need several hundred chunk INSERTs and several batches.

  } catch (error) {    console.error('demo upload: the chunks could not be stored', error)

Log the failure Ingestion

WhatAny error in the try, from preparing and binding the statements or from a batch, is caught and logged with console.error.

WhyThe log line names the stage, so a storage failure can be told apart from an embedding failure (INGEST 6), which has its own log line and does not fail the upload.

    // Undo everything of this upload: its archive, its chunks (by the upload's prefix), its file row and its room.    await env.DB.batch([      ...(archive.length > 0 ? [env.DB.prepare('DELETE FROM archived_pages WHERE demo_id = ? AND file = ?').bind(demo.id, name)] : []),      env.DB.prepare('DELETE FROM chunks WHERE demo_id = ? AND id LIKE ?').bind(demo.id, `${demo.id}-${upload}-%`),      env.DB.prepare('DELETE FROM files WHERE demo_id = ? AND name = ?').bind(demo.id, name),      env.DB.prepare('UPDATE demos SET files = files - 1, pages = pages - ?, chars = chars - ?, uploads = uploads - 1 WHERE id = ?').bind(pageCount, chars, demo.id),    ])

Undo the whole upload, in one transaction Ingestion

WhatOne batch deletes this file's archive (only when an archive was attempted), the chunks whose id starts with this upload's prefix, and the file row, and takes the file, its pages, its characters and the upload back off the demo account's totals.

WhyBecause the undo is one batch, it is atomic: the room is never given back without the rows going, and the rows never go without the room. The LIKE on the upload's prefix deletes exactly the chunks this upload committed and no other file's. uploads is decremented so that, after a failed first upload, the next upload still counts as the account's first at INGEST 7. used_at and cleared_at are not restored. An older archive of the same file name is gone either way. If the first batch failed, its DELETE was rolled back and this DELETE removes the old archive; if a later batch failed, the first batch's DELETE already removed it. If this undo batch itself throws, the error reaches createApp's fetch, which answers a generic 500 and leaves the partial upload in place.

    return json(500, { error: `${name} could not be stored. Please try again.` })  }

500, try again Ingestion

WhatAnswers 500 "<name> could not be stored. Please try again."

WhyAfter the undo, the upload's chunks, file row and room are gone, the claim on its name included, so the same file can be uploaded again at once. Only used_at and cleared_at keep the values INGEST 3 set.