Running it · Documents after 10 idle days, kept rows after 25 months · stage 7 of 10
Idle purge and expiry
Once a day, the Worker's scheduled handler runs dailyHealth, purge(), expire() and forgetHits(), in that order. purge() finds every demo account (a visitor's row in the demos table) with no upload, removal, question or MCP call for 10 days. For each one it deletes the vectors, disconnects the MCP apps, and then deletes the chunks, files and unconsented questions in one D1 batch. The account's row, its access key and what was kept with consent stay. expire() then deletes every question and archived page older than 25 months.
demo/src/app.ts67 / 67 lines on this page explainedlines 41-44,863-925 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
How long a demo account may go unused before its documents are deleted.
/** A demo's documents are deleted after this many days with no upload, removal or question on the page and no call to its MCP server. */exportconstIDLE_DAYS = 10
10 days without use Module load
WhatIDLE_DAYS is 10. Its comment names four kinds of use: an upload and a removal (both set demos.used_at), a question on the page (the reservation at ASK 2 sets it), and a call to the MCP server for the account. Any MCP call counts, including one that asks nothing, once it passes the token check and the per-minute limit (mcp.ts:502).
WhyExtracted document text is the most sensitive data the demo app holds, so it is kept only while the visitor is using it. purge() interpolates the value into SQLite's datetime('now', '-10 days') modifier.
How long questions and archived page text are retained.
/** Kept questions and archived page text are deleted after this many months. */exportconstKEEP_MONTHS = 25
25 months for what was kept Module load
WhatKEEP_MONTHS is 25. expire() deletes questions and archived_pages rows older than this.
WhyQuestions asked with consent (keep = 1) and archived page text outlive the idle purge so they can be analysed and turned into golden sets, and this constant limits how long. It matches the 25 months stated in schema.sql and in the header comment of app.ts.
/** * Deletes the documents of every demo unused for IDLE_DAYS: its vectors first, then its * chunks and files, and the questions asked without consent (keep = 0). The demo, its key, * its count of questions used, its kept questions and its archived page text stay; it is * asked for its PDFs again. A demo whose every file was removed is picked for its unconsented * questions alone, and is not told its documents were deleted. */
What goes and what stays Never runs
WhatThe doc comment lists what is deleted (vectors, chunks, files, unconsented questions) and what stays (the account's row, its access key, asks_used, kept questions, archived page text).
WhyBecause the row and its key stay, the visitor's cookie still signs them in. The page tells them their documents were cleared and asks for the PDFs again, and asks_used is unchanged, so they have the same number of questions left. An account whose files were all removed by hand is picked only for its unconsented questions and gets no cleared notice.
WhatTakes the bindings and the model clients (it uses only models.vectors) and returns how many accounts were purged.
WhycreateApp's scheduled handler calls it daily, after dailyHealth, which rolls up yesterday's questions before any are deleted, and before expire() and forgetHits(). demo/wrangler.toml sets the cron to 17 4 * * *, 04:17 UTC.
// A demo is picked once it has been idle IDLE_DAYS and still has files or unconsented questions to delete.const old = await env.DB.prepare(`SELECT id FROM demos WHERE purged_at IS NULL AND COALESCE(used_at, created_at) <= datetime('now', ?) AND (files > 0 OR EXISTS (SELECT 1 FROM questions q WHERE q.demo_id = demos.id AND q.keep = 0))`, ).bind(`-${IDLE_DAYS} days`).all<{ id: string }>()
Pick the idle accounts Scheduled
WhatSelects the demo accounts that are not purged (purged_at IS NULL), whose last use, COALESCE(used_at, created_at), is at least 10 days ago, and that still have files or at least one question with keep = 0.
Whycreated_at stands in for the last use of an account that was never used. The files-or-questions condition stops the job from processing an already cleared account again every day. datetime() returns 'YYYY-MM-DD HH:MM:SS', the format the columns are written in, so a plain string comparison orders the times correctly.
// How many demos were purged, for the scheduled job.let purged = 0// Each demo on its own, so one failure does not stop the rest.for (const { id } of old.results) {try {
One account at a time Scheduled
Whatpurged counts the accounts purged. Each account is purged in its own try block.
WhyA failure for one account (Vectorize, the OAuth store or D1) is caught inside its iteration, so the other accounts are still purged.
// Its chunk ids are its vector ids: the vectors go first, while the rows still say which ones to delete.const ids = (await env.DB.prepare('SELECT id FROM chunks WHERE demo_id = ?').bind(id).all<{ id: string }>()).results.map((row) => row.id)if (models.vectors !== undefined) {for (let i = 0; i < ids.length; i += 500) await models.vectors.deleteByIds(ids.slice(i, i + 500)) }
Vectors first, while the rows name them Scheduled
WhatReads every chunk id of the account and, when a vector index is bound, deletes those ids from Vectorize in slices of 500.
WhyThe chunk ids are the vector ids (INGEST 6), and D1 is the only record of them. Deleting the vectors first means a failure leaves the rows, so the next day's run still knows what to delete. The reverse order could orphan vectors that no row names.
// Every app connected to the demo is disconnected first (demo/src/oauth.ts): if that fails, nothing below// has run, so the demo is still idle with documents and tomorrow's run tries again.awaitrevokeGrants(env, id)
Disconnect every MCP app Scheduled
WhatrevokeGrants lists the account's grants (the records the OAuth library writes when the visitor lets an app connect) in the library's KV store and revokes each one, which also invalidates its access and refresh tokens. Without OAUTH_KV it does nothing.
WhyAn app connected through the MCP server should not keep a working token to an account whose documents are gone. Revocation runs before the D1 deletes, so if it throws, the account keeps its rows and is retried the next day.
// One transaction, and only while the demo is still idle: an upload since the SELECT// above keeps its chunks and files (searched by their words until it is idle again).const idle = `EXISTS (SELECT 1 FROM demos WHERE id = ?1 AND COALESCE(used_at, created_at) <= datetime('now', ?2))`const cutoff = `-${IDLE_DAYS} days`
The idle guard Scheduled
Whatidle is an EXISTS subquery that is true only while the account's last use is still at least 10 days old. Every statement in the purge's D1 batch includes it.
WhyTime passes between the SELECT and the batch, while the vectors are deleted and the grants revoked. If the visitor uploads or asks in between, used_at moves, the guard turns false and every statement matches nothing, so the new file survives. The vectors already deleted are not restored; the code comment says those chunks are searched by their words until the account is idle again. The apps that revokeGrants disconnected also stay disconnected.
await env.DB.batch([ env.DB.prepare(`DELETE FROM chunks WHERE demo_id = ?1 AND ${idle}`).bind(id, cutoff), env.DB.prepare(`DELETE FROM files WHERE demo_id = ?1 AND ${idle}`).bind(id, cutoff), env.DB.prepare(`DELETE FROM questions WHERE demo_id = ?1 AND keep = 0 AND ${idle}`).bind(id, cutoff),// The room is reset; cleared_at is set only if there were files, so the page says its documents were deleted. env.DB.prepare(`UPDATE demos SET files = 0, pages = 0, chars = 0, cleared_at = CASE WHEN files > 0 THEN datetime('now') ELSE cleared_at END WHERE id = ?1 AND ${idle}`).bind(id, cutoff), ])
Delete and reset in one transaction Scheduled
WhatOne D1 batch deletes the account's chunks, files and keep = 0 questions, and sets files, pages and chars to 0. cleared_at is set to now only if files was above 0; otherwise it keeps its value.
WhyBecause the batch is one transaction, the counts can never disagree with the rows. In an UPDATE, SQLite evaluates CASE WHEN files > 0 against the row before the update, so an account that had files is marked cleared and the page shows the notice, while an account picked only for unconsented questions is not. archived_pages and keep = 1 questions are not touched.
// Counted only once every delete has gone through. purged++
Count the account Scheduled
Whatpurged is incremented after the batch returns.
WhyOnly an account whose every step succeeded is counted. An account whose batch matched nothing because the idle guard turned false is still counted, because the batch itself succeeded.
} catch (error) {// The rows stay, so tomorrow's run still knows which vectors to delete.console.error(`demo purge: ${id} could not be purged; retried tomorrow`, error) } }
Retry tomorrow Scheduled
WhatAny error for this account is logged with its id, and the loop continues with the next account.
WhyEvery step before the batch is safe to repeat (deleting vector ids that are gone, revoking no grants), and the batch is all-or-nothing, so the next day's run can start this account again from the beginning.
// Both by age alone: an unconsented question still here (its demo never idle 10 days) goes too.await env.DB.batch([ env.DB.prepare("DELETE FROM questions WHERE asked_at <= datetime('now', ?)").bind(cutoff), env.DB.prepare("DELETE FROM archived_pages WHERE archived_at <= datetime('now', ?)").bind(cutoff), ])}
Delete by age alone Scheduled
WhatOne D1 batch deletes every questions row whose asked_at is at least 25 months old, and every archived_pages row whose archived_at is that old.
WhyThe delete needs no keep filter. By this age nearly every remaining question is a kept one, and an unconsented question of an account that was never idle for 10 days (a visitor who keeps using theirs) is deleted too. The canary's questions never reach this age, because runCanary deletes them after two days. The delete applies to accounts still in use as well, so an answer older than 25 months also drops out of the page's history (session reads questions).