remove()
async function · lines 394–438View on GitHubDeletes 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.