Joel Stevick

Running it · Six fixed questions a day · stage 4 of 10

The canary

Every day, after the roll-up, the scheduled job asks six fixed questions about a fixed, invented 16-page document. The document goes through the real upload handler and the questions through the real ask handler, with the real models. Five questions have a known answer, which code checks for required substrings. The sixth has no answer in the document and passes only if the pipeline falls back. The results are written to canary_runs, and a day with any failure gets a canary flag in pipeline_flags. A change in the model, the embeddings, retrieval, the reranker or the check therefore shows even on a day with no visitors.

Runs in: Demo Worker, the private Worker behind the DEMO service binding, demo/src/. New to Cloudflare? How these fit together
demo/src/canary.ts55 / 55 lines on this page explainedevery line of the file
demo/src/health.ts89 / 89 lines on this page explainedlines 176-264 of 316; 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/canary.ts The canary's data: the invented document, its file name and the six cases.

Module scope

module scope · lines 1–16View on GitHub

The licence, why the canary exists, and the file name of its document.

// 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 MIT; the SPDX line is the machine-readable form licence scanners read.

/** * The canary (README.md, "Watching the pipeline"): a fixed, invented document and fixed questions about it, * asked through the real pipeline every day by the demo Worker's daily job (health.ts). The document and * its answers never change, so a canary that starts failing means the pipeline changed: the model, the * embeddings, retrieval, the reranker or the check. It is longer than the passages one answer is written from * (ANSWER_CHUNKS in models.ts, 12), so ask() takes the partial path, not the whole-document read; widening * still lets most pages reach the model. Each page is one passage. Nothing in it is anyone's real data. */

A fixed input, so any change is the pipeline's Never runs

WhatThe doc comment: an invented document and fixed questions, asked through the real pipeline every day by health.ts. Because the input and the expected answers never change, a canary that starts failing means the pipeline changed.

WhyReal traffic varies with who is asking, so its rates cannot separate a pipeline change from a change in visitors. The canary holds the input constant. Retrieval and the reranker run on every question on either path. The document has 16 chunks, more than ANSWER_CHUNKS (12), so ask() takes the partial path instead of reading the whole document. On that path the candidate pool is the fusion output (up to POOL, 48, passages), the reranker picks passages and pads the list to 12, widening adds neighbours, and the fallback message is NOT_IN_PASSAGES. Because the pages are short and widening has a 10,800-character budget, most or all pages usually still reach the answer model. Each page is under CHUNK_CHARS (900), so chunkPage keeps it as one chunk.

16 pages → 16 chunksANSWER_CHUNKS = 12 (models.ts)CHUNK_CHARS = 900 (chunks.ts)WIDEN_CHARS = 10,800 (widen.ts)

// The name the canary's document is stored under, as if it were an uploaded PDF.export const CANARY_FILE = 'canary-policy.pdf'

CANARY_FILE: the document's file name Module load

WhatThe document is stored under the name 'canary-policy.pdf'.

Whyupload() requires a file name, and the files table's primary key is the account id and the name. The .pdf suffix gives the stored name the same form as a visitor's file names (upload() does not check it), although no PDF exists; the canary sends the page texts directly.

CANARY_FILE = 'canary-policy.pdf'

CANARY_PAGES

constant · lines 17–36View on GitHub

The invented document, one string per page.

/** Sixteen pages of an invented equipment-rental company's policy: three that hold the answers, thirteen that do not. */export const CANARY_PAGES = [

Sixteen pages, three with answers Module load

WhatThe doc comment and the start of the array: the policy of an invented equipment-rental company, Brightwater Rentals.

WhyInvented text holds nobody's data, and its facts cannot be in the model's training data, so a right answer must come from retrieval.

  'Brightwater Rentals: Customer Policy. Rentals are charged by the day. A day starts when the equipment leaves the depot and ends at closing time, 5:30 p.m. Equipment returned after 5:30 p.m. is charged for one more day. Every rental needs a deposit of 200 dollars, taken on the customer\'s card when the equipment is collected.',  'Damage and cleaning. The deposit is returned within 5 working days of the return, less the cost of any damage. Equipment returned dirty is charged a cleaning fee of 45 dollars. Customers must report a breakdown within 2 hours by calling the depot; a breakdown reported later is treated as damage.',  'Delivery and cancellation. Delivery is free within 10 miles of the depot and costs 3 dollars a mile beyond that. A booking cancelled at least 48 hours before collection is refunded in full; a later cancellation forfeits one day\'s charge. The depot is closed on Sundays.',

The three answering pages Module load

WhatPage 1: a rental day ends at 5:30 p.m., and the deposit is 200 dollars. Page 2: the cleaning fee is 45 dollars, and a breakdown must be reported within 2 hours. Page 3: a booking cancelled at least 48 hours before collection is refunded in full.

WhyEach answer is a distinctive number, so code can score it with a substring test and no model judge. Pages 1 and 2 each hold two answers, so the answer model and the citation check must pick the right fact from a page that holds another number too.

  'Opening hours. The depot opens at 7 a.m. from Monday to Saturday. Staff load equipment into customer vehicles on request, and a forklift is available for pallets.',  'Identification. A first-time customer shows a photo driving licence and a utility bill with the same address. Trade accounts are opened by the office manager after a credit check.',  'Safety briefings. Every powered tool is handed over with a short safety briefing. Customers sign the briefing sheet, and goggles and gloves are lent free with saws and grinders.',  'Fuel. Petrol and diesel machines leave the depot with a full tank. A machine returned with less fuel is refilled at the pump price plus a handling charge shown on the receipt.',  'Trade accounts. Account holders are invoiced monthly and pay within 30 days. An account more than 60 days overdue is put on hold until it is settled.',  'Long hires. Hires of four weeks or more get a weekly rate, agreed in writing before collection. Equipment on a long hire is serviced at the depot every two weeks.',  'Loyalty. Customers who hire ten times in a year receive a voucher for one free day on any hand tool. Vouchers expire at the end of the following year.',  'Accessories. Blades, drill bits and sanding discs are sold, not hired. Unused accessories in their packaging may be returned for a refund within 14 days.',  'Lost equipment. Equipment not returned within 7 days of the agreed date is reported to the police, and the customer is charged its replacement cost.',  'Weekends. Equipment collected on Saturday afternoon and returned on Monday morning is charged as one day, because the depot does not open in between.',  'Complaints. A complaint is acknowledged within one working day and answered in full within ten. Customers who are not satisfied may ask for the area manager to review it.',  'Environment. Waste oil and old batteries are collected free from customers who return them to the depot. Machines are cleaned with biodegradable detergent.',  'Training. The depot runs a free half-day course on using a mini digger every first Saturday of the month. Places are booked at the counter.',]

Thirteen distractor pages Module load

WhatPages 4–16 cover opening hours, identification, safety, fuel, trade accounts, long hires, loyalty, accessories, lost equipment, weekends, complaints, environment and training. None of them answers a canary question.

WhyThey share the domain's vocabulary with the answering pages (day, return, charged, depot, refund, customer). All 16 chunks fit within POOL (48), and the reranker pads its list to 12, so a right page ranked low usually still reaches the answer model. The distractors therefore mainly test whether the answer model and the check pick the right page from a context that holds most of the document. Several of them hold other numbers (7 a.m., 30 days, 14 days), so an answer taken from the wrong page fails the substring check. None mentions insurance, which the unanswerable case relies on.

CanaryCase

interface · lines 37–46View on GitHub

One canary question and how it is scored.

/** One canary question: an answerable one names the words a right answer must contain; an unanswerable one must fall back. */export interface CanaryCase {  name: string  question: string  /** Every one of these must appear in the answer (case-insensitive). Empty for a question that must fall back. */  must: string[]  /** True when the answer is not in the document, so the pipeline must say it could not find it. */  fallback?: boolean}

A case's four fields Type only

Whatname keys the result in canary_runs. must lists strings that must all appear in the answer, compared case-insensitively; it is empty for a question that must fall back. fallback is true when the document has no answer.

WhyScoring by required substrings makes the canary deterministic and needs no second model call. The cost is a loose test, since '45' would also match '450'.

CANARY_CASES

constant · lines 47–55View on GitHub

The six questions.

// Five questions the document answers, and one it does not.export const CANARY_CASES: CanaryCase[] = [

Five answerable, one not Module load

WhatThe comment and the start of the array.

WhyThe five answerable cases catch a pipeline that stops finding or stating answers. The unanswerable case catches the opposite failure, a pipeline that starts answering from outside the document.

  { name: 'deposit', question: 'How much is the deposit for a rental?', must: ['200'] },  { name: 'late-return', question: 'When does a rental day end?', must: ['5:30'] },  { name: 'cleaning-fee', question: 'What is the cleaning fee for equipment returned dirty?', must: ['45'] },  { name: 'breakdown', question: 'How soon must a breakdown be reported?', must: ['2 hours'] },  { name: 'cancellation', question: 'How long before collection must a booking be cancelled for a full refund?', must: ['48'] },

The five answerable questions Module load

Whatdeposit (the answer must contain '200'), late-return ('5:30'), cleaning-fee ('45'), breakdown ('2 hours') and cancellation ('48').

WhyMost questions reuse their page's words (deposit, cleaning fee, breakdown, cancelled, refund), so BM25 alone can find them. Only late-return is partly reworded ("When does a rental day end?" against "ends at closing time, 5:30 p.m."). The canary therefore watches the answer model and the check more closely than it watches vector search.

  { name: 'absent', question: 'Does Brightwater Rentals offer insurance for the equipment?', must: [], fallback: true },]

The unanswerable question Module load

Whatabsent asks whether Brightwater offers insurance; must is empty and fallback is true.

WhyIt passes only when the response has found: false. A model that starts filling gaps from general knowledge, or a check that stops refusing uncited sentences, would answer it and fail.

demo/src/health.ts The pipeline's health.

canaryDemo()

async function · lines 176–205View on GitHub

Finds or creates the canary's demo account (its row in the demos table), which holds its uploaded document.

Called by runCanary()Calls upload(): doc comment and signature Worker router

/** The canary demo, made the first time, with its document uploaded when it has none. */async function canaryDemo(env: Env, models: Models): Promise<Demo> {

Signature Scheduled

WhatTakes the bindings and the models and returns the canary's Demo row. It is not exported; only runCanary calls it.

WhyIt needs the models because uploading the document embeds it.

  // Look up the canary demo, if it exists.  const read = () => env.DB.prepare('SELECT id, asks_used, files, pages, chars, company, contact, cleared_at FROM demos WHERE card_fingerprint = ? AND purged_at IS NULL')    .bind(CANARY_FINGERPRINT).first<Demo>()  let demo = await read()

Look it up by fingerprint Scheduled

Whatread() selects the columns signedIn reads, for the live demo account (purged_at IS NULL) whose card_fingerprint is 'canary:v1'.

WhyThe canary's demo account is found by its fingerprint because it has no access key, so no browser cookie can reach it through signedIn. read is a closure because canaryDemo calls it up to three times.

  // Create it the first time.  if (demo === null) {    // No key: no browser can ever sign in to it. No contact: no email names it.    await env.DB.prepare("INSERT INTO demos (id, card_fingerprint, company) VALUES (?, ?, 'Canary')").bind(`canary${crypto.randomUUID().replace(/-/g, '').slice(0, 10)}`, CANARY_FINGERPRINT).run()    demo = (await read()) as Demo  }

Create it the first time Scheduled

WhatInserts a demos row whose id is 'canary' plus the first 10 hex digits of a random UUID, with the fingerprint and company 'Canary', then reads the row back.

WhyThe row has no key_hash and no contact, so no one can sign in to it and no email names it. The canary prefix makes its rows, chunk ids and Vectorize namespace easy to recognise. The UNIQUE card_fingerprint stops a second canary row from being created.

id: canary + 10 hex digits (16 characters)

  // Give it its document if it has none yet.  if (demo.files === 0) {    // The page's own upload, without the mailer: the canary is not a prospect starting a demo.    const response = await upload(new Request('https://demo/api/files', {      method: 'POST',      body: JSON.stringify({ name: CANARY_FILE, page_count: CANARY_PAGES.length, pages: CANARY_PAGES.map((text, i) => ({ page: i + 1, text })) }),    }), { ...env, MAILER: undefined }, models, demo)

Upload through the real handler Scheduled

WhatIf the account has no files, calls upload() with a synthetic POST /api/files whose JSON body holds the file name, the page count and the pages numbered from 1, the same shape the page's pdf.js extraction sends. env is passed with MAILER removed.

WhyGoing through upload() runs INGEST 1–6 (validation, the limits, chunking, storing, embedding into Vectorize) exactly as for a visitor's document. Without MAILER, INGEST 7 sends no 'demo started' email. The files = 0 test also covers the idle purge. If the canary is switched off for 10 days, the purge deletes its document, and the next run uploads it again.

    // Stop if the upload failed; otherwise read the demo back with its file.    if (!response.ok) throw new Error(`canary: the document could not be uploaded (${response.status})`)    demo = (await read()) as Demo  }

A failed upload throws Scheduled

WhatA non-2xx response throws an error with its status. Otherwise the account is read again, now with its file counted.

WhyAsking questions of an account with no document would prove nothing. The throw sends control to dailyHealth's catch, which writes a canary flag for the day with value 0 (baseline 6), and no canary_runs rows are written. A failed embedding inside upload does not throw, because upload then leaves the file searched by BM25 alone; the canary's answers show the effect.

  return demo}

Return the account Scheduled

WhatReturns the row, now with its document.

WhyrunCanary passes it to ask() as the signed-in demo account.

canaryPassed()

function · lines 206–215View on GitHub

Scores one canary answer: the unanswerable case by its fallback, every other case by its required substrings.

Called by runCanary()

/** Whether one canary answer is right: the words a right answer holds, or a fallback where the document has no answer. */export function canaryPassed(test: CanaryCase, found: boolean, answer: string): boolean {  // A question with no answer in the document passes only by falling back.  if (test.fallback === true) return !found

The unanswerable case passes by falling back Scheduled

WhatFor a case with fallback true, the result is !found.

WhyAny fallback counts: not_found (no candidate) or refused (the model wrote nothing citable, or the code check rejected the first sentence). The canary cannot tell those apart; it only knows that no unsupported answer was shown. A model failure is caught by the caller, which also requires response.ok.

  // Otherwise every expected word must be in the answer.  const text = answer.toLowerCase()  return found && test.must.every((word) => text.includes(word.toLowerCase()))}

Every required string, case-insensitively Scheduled

WhatOtherwise the answer must have been found and must contain every string in must, with both sides lower-cased.

WhyRequiring found means a fallback message cannot pass by accident. The test reads only the answer's text and ignores which page it cited, so a right number cited to the wrong page would still pass.

runCanary()

async function · lines 216–264View on GitHub

STEP 3: asks each case through ask(), scores the answer, stores the result and flags the day if any case failed.

Called by dailyHealth() Daily healthCalls canaryDemo() canaryPassed() ask(): ASK 1–2, then JSON or server-sent events Worker router asText() Answer with sources

/** * STEP 3 · the canary's run for `day`: each question through the page's own ask, with the real models, * marked `via = 'canary'` so step 1 never counts it. A day with a failure is flagged. */export async function runCanary(env: Env, models: Models, options: Options, day: string, cases: CanaryCase[] = CANARY_CASES): Promise<{ passed: number; of: number } | null> {

Signature Scheduled

WhatTakes the bindings, the models, the ask options, the day to file results under and the cases (CANARY_CASES by default). Returns { passed, of }, the number of cases passed and asked, or null when the canary is switched off.

Whycases is a parameter so tests can run a smaller or deliberately failing set. options are the ones createApp passes to every visitor's ask, so widening is on for the canary as it is in production.

  // The canary can be switched off.  if (env.CANARY_ENABLED === '0') return null

The off switch Scheduled

WhatCANARY_ENABLED = '0' returns null before anything runs. Any other value, or no value, leaves the canary on.

WhyEach run costs six reranker calls and six answer calls on the Anthropic key, plus the question embeddings. The switch stops that spend and leaves the rest of the daily job running.

  // Find or create the canary demo.  let demo = await canaryDemo(env, models)

Find or create the account Scheduled

WhatCalls canaryDemo.

WhyIts errors are not caught here. They propagate to dailyHealth, which flags the day.

  // Its allowance is reset each run: the canary is not a visitor.  await env.DB.prepare('UPDATE demos SET asks_used = 0 WHERE id = ?').bind(demo.id).run()  demo = { ...demo, asks_used: 0 }

Reset its ten questions Scheduled

WhatSets asks_used to 0 in D1 and in the local copy.

Whyask() enforces LIMITS.asks (10) at ASK 2 with an atomic UPDATE. Without the reset, the last two cases would get a 429 on the second day, and every case from the third day on.

  // Ask each question as the page would, and score the answer.  let passed = 0  for (const test of cases) {    const started = Date.now()    const response = await ask(new Request('https://demo/api/ask', {      method: 'POST',      headers: { 'Content-Type': 'application/json', 'X-Demo-Via': 'canary', 'X-Demo-Keep': '0' },      body: JSON.stringify({ question: test.question }),    }), env, models, demo, options)

Each question through ask() Scheduled

WhatFor each case, records the start time and calls ask() with a synthetic POST /api/ask carrying the question as JSON, X-Demo-Via: canary and X-Demo-Keep: 0. The request has no Accept: text/event-stream header, so ask() drains its async generator and replies with one JSON body.

WhyThis is the full query path, ASK 1–8, with the real Claude reranker and answer model. X-Demo-Via makes the questions row record via 'canary', which the roll-up excludes, and X-Demo-Keep: 0 marks the question unconsented. The JSON reply runs the generator to its end, so the row is recorded before ask() returns.

X-Demo-Via: canaryX-Demo-Keep: 0

    // Read the answer as plain text and check it.    const body = (await response.json().catch(() => ({}))) as { answer?: string; items?: string[]; found?: boolean }    const answer = asText(body.answer ?? '', body.items ?? [])    const ok = response.ok && canaryPassed(test, body.found === true, answer)    if (ok) passed++

Read and score the reply Scheduled

WhatParses the JSON body (an unparseable body becomes {}), joins answer and items into one text with asText, and counts a pass when the status is 2xx and canaryPassed agrees.

WhyWhen the answer model fails before anything is shown, ask() returns 503 and gives the question back. response.ok then fails the case. Without that check the unanswerable case would pass, because the 503 body has no found: true.

    // Keep the result, with the first 300 characters of the answer (stored for reading the table; healthRoute does not serve it).    await env.DB.prepare('INSERT OR REPLACE INTO canary_runs (day, name, passed, found, ms, answer) VALUES (?, ?, ?, ?, ?, ?)')      .bind(day, test.name, ok ? 1 : 0, body.found === true ? 1 : 0, Date.now() - started, answer.slice(0, 300)).run()  }

Keep each result Scheduled

WhatINSERT OR REPLACE into canary_runs, keyed by day and case name: passed, found, the time in milliseconds and the first 300 characters of the answer.

WhyOR REPLACE makes a rerun on the same day overwrite the row instead of failing on the primary key. The stored answer is about the invented document, so it exposes no one, and healthRoute does not serve it.

answer: first 300 charactersprimary key (day, name)

  // Replace the day's canary flag, writing one only when a question failed.  await env.DB.batch([    env.DB.prepare("DELETE FROM pipeline_flags WHERE day = ? AND via = 'canary'").bind(day),    ...(passed < cases.length      ? [env.DB.prepare("INSERT INTO pipeline_flags (day, via, metric, value, baseline, threshold) VALUES (?, 'canary', 'canary', ?, ?, ?)").bind(day, passed, cases.length, cases.length)]      : []),

Flag the day only on a failure Scheduled

WhatOne D1 batch deletes the day's canary flag and, if any case failed, inserts a new one with value = passed, and baseline and threshold = the number of cases.

WhyDeleting first means a rerun that now passes clears the earlier flag. A single failure is enough to flag, because the input is fixed and, unlike traffic, has no noise to allow for.

flag: via 'canary', metric 'canary', value passed, threshold 6

    // The canary's own questions are kept two days, for /admin to read; they are never anyone's.    env.DB.prepare("DELETE FROM questions WHERE via = 'canary' AND asked_at < datetime('now', '-2 days')"),  ])

Its questions kept two days Scheduled

WhatIn the same batch, deletes the canary's questions rows older than two days.

Whyask() records every outcome, so each canary question is also a row in questions, six a day. Deleting rows older than two days keeps at most two days of them. The idle purge would never delete them, because the canary's demo account is used daily.

  return { passed, of: cases.length }}

Return the score Scheduled

WhatReturns passed and of.

WhydailyHealth ignores the result; the tests read it.