Joel Stevick

Running it · DELETE /api/files · stage 6 of 10

Removing a file

When the visitor presses a file's Remove button, or an MCP client calls remove_file, the Worker deletes the file as if it had never been uploaded. It deletes the file's vectors from Vectorize first, then one D1 batch returns the file's pages and characters to the visitor's demo account (their row in the demos table, which holds their allowance) and deletes its chunks, archived pages and file row. Questions already asked, and the count of questions left, are unchanged.

Browser: the visitor's page: demo.html and its module scriptDemo Worker: the private Worker behind the DEMO service binding, demo/src/New to Cloudflare? How these fit together
demo/src/app.ts45 / 45 lines on this page explainedlines 394-438 of 1124; the rest are on other stage pages
demo.html27 / 27 lines on this page explainedlines 152-178 of 505; 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: remove(), the handler for DELETE /api/files.

remove()

async function · lines 394–438View on GitHub

Deletes one file's vectors, then its rows, and returns its share of the allowance. It runs on a site request, DELETE /api/demo/files from the page, so its blocks are marked Site request; the MCP server's remove_file tool runs the same code on an MCP request.

Called by build(): TOOL 3 remove_file route(): the visitor's routes Worker routerCalls about() Shared helpers json() Shared helpers Vectors The Models interface

/** * Removes one file as if it was never uploaded: its vectors first (a failure there leaves * every row, and the visitor is asked to try again), then in one transaction its pages and * text given back to the demo's room, and its chunks, file row and archived pages deleted. * The questions already asked stay, and the count left is unchanged. */

The order, and what stays Never runs

WhatThe doc comment states the order: vectors first, then one transaction that returns the file's pages and characters to the demo account and deletes its chunks, file row and archived pages. Questions already asked and the count left are unchanged.

WhyVectorize and D1 are separate stores with no shared transaction, so the order makes a failure safe. While the D1 rows exist, the file is still listed, and a retry knows which vectors to delete.

export async function remove(request: Request, env: Env, models: Models, demo: Demo): Promise<Response> {

Signature Site request

WhatTakes the request, the bindings, the model clients (only models.vectors is used) and the visitor's demo account row, which the router found by the access key's hash.

Whyremove is exported because the MCP server's remove_file tool calls it in process with a synthetic DELETE request (mcp.ts:368), so the page and an MCP client remove a file through the same code.

  // The name of the file to remove, trimmed and capped as on upload.  const body = (await request.json().catch(() => null)) as { name?: unknown } | null  const name = typeof body?.name === 'string' ? body.name.trim().slice(0, 200) : ''

The file's name Site request

WhatThe JSON body's name, trimmed and cut to 200 characters. A missing or non-string name, or a body that is not JSON, becomes the empty string.

WhyUpload normalises the name the same way (INGEST 1), so the name matches the files row's primary key (demo_id, name) exactly as it was stored.

max name: 200 characters

  // The file's page and character counts are read first, so the same amounts can be given back to the demo.  const file = name === '' ? null : await env.DB.prepare('SELECT pages, chars FROM files WHERE demo_id = ? AND name = ?').bind(demo.id, name).first<{ pages: number; chars: number }>()  // No such file in this demo: nothing to remove.  if (file === null) return json(404, { error: `${name || 'That file'} is not in your demo.` })

Read the file's size, or 404 Site request

WhatA D1 prepared statement reads the file's pages and chars, scoped to this account. An empty name skips the query, and no matching row answers 404 with the name in the message.

WhyThese counts are what the upload added to the account's usage (files.chars was added for this in migration 0004), so remove subtracts the same amounts. The demo_id condition means a visitor can never name another visitor's file.

  // The file's chunk ids, which are also the ids of its vectors in Vectorize.  const ids = (await env.DB.prepare('SELECT id FROM chunks WHERE demo_id = ? AND file = ?').bind(demo.id, name).all<{ id: string }>()).results.map((row) => row.id)

The chunk ids are the vector ids Site request

WhatReads the ids of every chunk of this file in this account.

WhyINGEST 6 upserted each vector under its chunk's id (<account id>-<upload>-<n>), so these ids are exactly the vectors to delete, and no lookup in Vectorize is needed.

  // The vectors go first: if that fails, nothing else has been touched.  if (models.vectors !== undefined && ids.length > 0) {    try {      // Deleted by id, 500 ids per call.      for (let i = 0; i < ids.length; i += 500) await models.vectors.deleteByIds(ids.slice(i, i + 500))

Vectors first, 500 ids a call Site request

WhatWhen there is a vector index and the file has chunks, the ids go to Vectorize's deleteByIds in slices of 500.

WhyA file can have more than 500 chunks (500,000 characters at up to 900 a chunk). Deleting the vectors while the rows still exist means no vector is orphaned: if the rows went first and this call then failed, nothing would record which vectors remained. A deleted vector can still be returned by a query for a short time, but it cannot be cited, because fusion drops ids that have no chunk in D1.

500 ids per deleteByIds callCHUNK_CHARS = 900

    } catch (error) {      console.error('demo remove: the vectors could not be deleted; nothing removed', error)      return json(500, { error: `${name} could not be removed. Please try again.` })    }  }

A Vectorize failure removes nothing from D1 Site request

WhatAny error is logged, and the request answers 500 and asks the visitor to try again. No D1 statement has run.

WhyThe file stays listed and fully searchable by keywords, so a retry starts from a consistent state. If a later slice fails after an earlier one succeeded, the earlier slices' vectors are already gone. The file is still searched by BM25, and a retry deletes the rest, because deleting a missing id is harmless.

  // The room is given back only while the file's row is still there, so two removes of one  // file at once give it back once; the deletes follow in the same transaction.  await env.DB.batch([    env.DB.prepare(      `UPDATE demos SET files = files - 1, pages = pages - ?2, chars = chars - ?3, used_at = datetime('now')       WHERE id = ?1 AND EXISTS (SELECT 1 FROM files WHERE demo_id = ?1 AND name = ?4)`,    ).bind(demo.id, file.pages, file.chars, name),

Return the file's share, once Site request

WhatThe batch's first statement subtracts one file and the file's pages and chars from the account's row, and sets used_at, but only while the file's row still EXISTS.

WhyTwo concurrent removes of the same file both pass the earlier read of the file's row. The EXISTS condition lets only the first batch to commit return the allowance, so the file's pages and characters are subtracted once. Setting used_at restarts the 10-day idle clock. uploads and asks_used are unchanged, so removing a file never re-sends the first-upload email and never refunds a question.

    env.DB.prepare('DELETE FROM chunks WHERE demo_id = ? AND file = ?').bind(demo.id, name),    env.DB.prepare('DELETE FROM archived_pages WHERE demo_id = ? AND file = ?').bind(demo.id, name),    env.DB.prepare('DELETE FROM files WHERE demo_id = ? AND name = ?').bind(demo.id, name),  ])

Delete the rows in the same transaction Site request

WhatThe same D1 batch deletes every chunk of the file, its archived pages and its files row.

WhyA D1 batch runs as one SQL transaction, so if any statement fails, all of them roll back. The account is never left with the allowance returned and the chunks still there, or the reverse. The archived pages, kept with consent for golden sets, are deleted too, which is what "as if never uploaded" means. The files row is deleted after the UPDATE, so the UPDATE's EXISTS still finds it.

tables: chunks, archived_pages, files

  // The reply says which file went and how many questions are left.  return json(200, { name, left: LIMITS.asks - demo.asks_used }, about(demo))}

The reply Site request

What200 with the file's name and the questions left, plus about()'s headers: X-Demo-Id, and X-Demo-Email when the account's contact has an address.

WhyThe site's proxy reads the headers and the name to record a demo_remove event, then removes the headers before the response reaches the browser.

demo.html The demo page: removeFile(), the function each file's Remove button calls.

removeFile()

async function · lines 152–178View on GitHub

Sends the removal, and removes the file's row from the list once the DELETE answers.

Called by listFile() File list and stream readerCalls Module scope The demo page showConnect() Listing and disconnecting apps

  // One click, no confirmation: a removal is a mistake undone or a new try, and the PDF is  // still on the visitor's disk. The row goes only once the server says the file is gone.

No confirmation dialog Never runs

WhatThe comment gives the design: one click removes the file, and the list row is removed only after the DELETE answers that the file is gone.

WhyThe PDF is still on the visitor's disk and uploading it again is cheap, so a confirmation step would only add friction. Removing the row only on success keeps the list consistent with the account's file rows in D1.

  async function removeFile(name, li, button) {    const status = $("upload-status");    button.disabled = true;    status.textContent = `Removing ${name}…`;

Disable the button, say what is happening In the browser

WhatremoveFile receives the file's name, its list row and its Remove button. It disables the button and sets the upload status line to "Removing <name>…".

WhyDisabling the button stops a double click from sending two DELETE requests. If a second request were sent anyway, it would answer 404 after the first had finished, or 200 if both passed the read at the same time, and the EXISTS guard would still return the allowance only once.

    try {      const response = await fetch("/api/demo/files", {        method: "DELETE",        headers: { "Content-Type": "application/json" },        body: JSON.stringify({ name }),      });

DELETE /api/demo/files In the browser

Whatfetch sends DELETE to the site's /api/demo/files with a JSON body that holds only the name. The browser sends the demo cookie because the request is same-origin.

WhyThe body does not identify the account. The Pages Function reads the access key from the HttpOnly demo cookie and sends it as X-Demo-Key, and the Worker finds the account by the key's hash, so the page cannot address another account's files.

      const body = await response.json().catch(() => ({}));      if (!response.ok && response.status !== 404) {        status.textContent = body.error || `${name} could not be removed.`;        button.disabled = false;        return;      }

A failure keeps the row In the browser

WhatThe body is parsed as JSON, and an unparseable body becomes {}. On any error status other than 404, the page shows the reply's error field (or a generic message) and re-enables the button.

WhyA 500 from a Vectorize failure means nothing was removed, so the row stays and the visitor can press Remove again.

      li.remove();      status.textContent = response.ok ? `${name} removed.` : body.error;      showConnect();

Gone, or already gone In the browser

WhatOn 200 or 404 the row is removed. A 200 shows "<name> removed." and a 404 shows the reply's error field. showConnect then checks again whether the "Use it from Claude Code" box should still show.

WhyA 404 means the file's row is no longer in D1, because it was removed from another tab, by an MCP client or by the idle purge, so the row was stale. The box is shown only while the account has a PDF, so showConnect hides it once the last file is gone.

    } catch {      status.textContent = `${name} could not be removed.`;      button.disabled = false;    }  }

Network failure In the browser

WhatIf fetch itself rejects (offline, a reset connection), the status says the file could not be removed and the button is re-enabled.

WhyThe page cannot know whether the Worker removed the file, so it keeps the row. A retry is safe because a second removal of a removed file answers 404, which the page treats as removed.