Running it · Daily roll-up and drift check · stage 3 of 10
Daily health
Once a day, the Worker's scheduled handler rolls up each recent UTC day's questions into pipeline_days, one row per route (the page or the MCP server). A row holds how many questions were asked and answered, a count for each fallback reason, and the p50 and p95 time to answer. The drift check then compares each day with the 14 days before it. A fallback rate is flagged when it is above the pooled baseline rate by more than 3 standard errors of a binomial proportion and by more than 5 percentage points. The p95 time is flagged when it exceeds 1.5 times the median of the baseline days' p95s. Flags are written to pipeline_flags. /internal/admin/health serves the last 30 days of both tables, and the last 14 days of canary runs, to the site's admin page.
demo/src/health.ts227 / 227 lines on this page explainedlines 1-175,265-316 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
/** * The demo pipeline's health (README.md, "Watching the pipeline"), run by the Worker's daily job: * * 1. ROLL UP each day's questions into counts, fallback rates and times (`pipeline_days`), per `via`; * 2. DRIFT compare each day with the 14 days before it and flag a rate or a time that moved * further than noise explains (`pipeline_flags`); * 3. CANARY ask fixed questions of a fixed document through the real pipeline, so a change in the * model or retrieval shows even on a day with no visitors (`canary_runs`). * * `/internal/admin/health` serves all three to /admin's Stats tab, and the mailer alerts Joel on a flag. * Counts and times only: no visitor's question or answer is copied anywhere. */
The three steps Never runs
WhatThe doc comment names the module's three steps and the table each one writes: ROLL UP writes pipeline_days, DRIFT writes pipeline_flags and CANARY writes canary_runs. It says /internal/admin/health serves all three to /admin's Stats tab, and that the module keeps counts and times only and copies no visitor's question or answer.
WhyBecause the roll-up keeps aggregates only, the health history outlives the questions it counts; unconsented questions are deleted once their demo account (the visitor's row in the demos table) has been idle 10 days. Apart from the canary's own runs, the module stores no text: the canary's answers, up to 300 characters each, go to canary_runs, and its questions are rows in questions for two days. The mailer alert the comment mentions is part of the site, outside this repository (README, "Watching the pipeline").
WhatFrom app.ts: ask and upload (the route handlers the canary calls), asText, json, and the Demo, Env and Options types. From canary.ts: the fixed document and the cases. From models.ts: the Models type.
WhyThe canary calls the same ask and upload functions that a visitor's request reaches, so a regression in either one shows up in the canary. app.ts imports dailyHealth and healthRoute from this module, so the imports are circular. ES modules allow the cycle because neither module uses the other's exports at load time.
/** The routes a question can come through. The canary's are never counted as traffic. */exportconstVIAS = ['page', 'mcp'] asconst
VIAS: the page and the MCP server Module load
WhatThe two routes traffic is counted for: 'page' (a NULL questions.via is read as 'page') and 'mcp' (the MCP server's ask_documents).
WhyEach route is rolled up and judged against its own history, because MCP callers ask differently from visitors on the page. 'canary' is left out on purpose, because the canary's questions are synthetic and would hide the rates of real traffic.
/** How far back a missed day is still rolled up: unconsented questions go once their demo has been idle 10 days. */exportconstCATCH_UP_DAYS = 9
CATCH_UP_DAYS = 9: how far back a missed day is rolled up Module load
WhatHow many days back dailyHealth looks for a day that was never rolled up, after a missed or failed cron run.
WhyThe idle purge deletes a demo account's unconsented questions (keep = 0) once the account has been idle 10 days, so every purged question is at least 10 days old. Every question asked in the last 9 days is therefore still in the table to be counted.
/** The baseline: this many days before the day being checked, pooled. */exportconstBASELINE_DAYS = 14
BASELINE_DAYS = 14: the days each day is compared with Module load
WhatThe baseline is the 14 days before the day being checked, pooled.
WhyTwo full weeks contain each weekday twice, so a weekly traffic pattern does not skew the baseline. Pooling 14 days also gives far more questions than one day has, so the baseline rate is a steadier estimate than the rate of the day it judges.
/** A day needs this many questions before its rates or times are judged. */exportconstMIN_DAY = 10
MIN_DAY = 10: the questions a day needs to be judged Module load
WhatA route with fewer than 10 questions on a day is not judged at all, on rates or on time.
WhyBelow 10 questions, one question moves a rate by more than 10 points, and the normal approximation behind the 3-standard-error rule breaks down for a binomial with so few trials. The gate does not make the p95 reliable: by nearest rank, the p95 of fewer than 20 timed questions is the slowest one.
/** A baseline needs this many questions (rates) or days with questions (times) before it judges anything. */exportconstMIN_BASELINE_ASKS = 30exportconstMIN_BASELINE_DAYS = 5
MIN_BASELINE_ASKS = 30, MIN_BASELINE_DAYS = 5: the smallest baseline that judges Module load
WhatRates are judged only when the baseline days hold at least 30 questions in total. Times are judged only when at least 5 baseline days have a p95.
WhyThe rate test treats the baseline rate p as the true rate and ignores p's own standard error, sqrt(p(1 − p)/N) over the N baseline questions. Below 30 questions that error is too large to ignore. A median of fewer than 5 daily p95s can be moved by a single slow day.
/** A rate is flagged above the baseline by more than this many standard errors… */exportconstSIGMAS = 3/** …and by at least this much: a floor for a tiny baseline rate (on a day under 20 questions one miss still clears it). */exportconstMIN_RATE_JUMP = 0.05
WhatA rate is flagged only when it exceeds the baseline by more than 3 standard errors and by more than 5 percentage points.
WhyThe 3-standard-error rule is a one-sided test. Under the normal approximation, a day on which nothing changed crosses the threshold (a false flag) with probability about 0.13%. With 4 rates on each of 2 routes, a false flag would come about once in 90 days if the approximation held. At small n or small p the binomial is skewed and the approximation is loose, which is what the minimums and the 5-point floor are for. The floor matters when p is near 0, where the standard error is near 0. The comment states the floor's limit. With p = 0 the threshold is 0.05, so on a day of 10 to 19 questions a single miss (1/n ≥ 0.0526) still clears it. From 20 questions, one miss does not.
/** The 95th-percentile time is flagged above this multiple of the baseline days' median p95. */exportconstSLOW_FACTOR = 1.5
SLOW_FACTOR = 1.5: the slow-day multiple Module load
WhatThe day's 95th-percentile time is flagged when it is more than 1.5 times the median of the baseline days' p95s.
WhyTimes are not binomial and have no simple standard error, so the rule is a ratio against a median, which a few outliers barely move. The rule watches the tail (p95) instead of the median because a slow model or a slow Vectorize query shows there first.
/** The rates the drift check watches: each a count in `pipeline_days`. */exportconstRATES = ['refused', 'trouble', 'stopped', 'not_found'] asconst
RATES: the four fallback counts watched Module load
WhatThe four fallback counts the drift check turns into rates. refused: nothing passed the code check, or the model wrote nothing citable. trouble: the answer model failed before anything was shown. stopped: part of an answer was shown, then a later unit (a sentence or list item) failed the check or the model's stream failed partway. not_found: retrieval returned no candidate at all.
WhyEach rate points at a different part of the pipeline: refused at the answer model or the check, trouble at the Claude API, stopped at a mid-answer failure of either kind, and not_found at retrieval or the stored chunks. answered is stored but not watched, because it is whatever the four fallbacks leave.
/** The canary demo's identity in `demos.card_fingerprint`. */exportconstCANARY_FINGERPRINT = 'canary:v1'
CANARY_FINGERPRINT: the canary account's identity Module load
WhatThe value 'canary:v1' in demos.card_fingerprint identifies the canary's demo account row.
Whycard_fingerprint is UNIQUE (schema.sql), so this value finds exactly one account. adminDemos (app.ts) leaves the canary out of the list of visitors' accounts by the same literal. The v1 suffix lets a changed document get a fresh account under a new value, but the literal in adminDemos would have to change with it, or the new canary would appear among visitors' accounts.
exportinterfaceDayRow {day: stringvia: stringasks: numberanswered: numbernot_found: numberrefused: numbertrouble: numberstopped: numberms_p50: number | nullms_p95: number | nullfirst_p50: number | null}
DayRow: one route's day in pipeline_days Type only
WhatOne row of pipeline_days: the UTC day ('YYYY-MM-DD'), the via, asks, answered, the four fallback counts and three times in milliseconds. ms_p50 and ms_p95 time the whole ask; first_p50 times the wait for the first released unit (a sentence or list item). Each time is null when no time was recorded.
WhyThe table stores counts instead of rates, so a baseline can pool days correctly (the sum of counts over the sum of asks) instead of averaging rates from days of different sizes.
WhatOne row of pipeline_flags: the day, the via, the metric, the day's value, the baseline it was compared with and the threshold it passed.
WhyStoring the baseline and the threshold with the value lets the admin page show how far over the line a day was without recomputing the baseline. The canary's flag reuses this shape, with via and metric both 'canary'.
/** The `q` percentile of `values` by the nearest-rank method: the smallest value with at least q of them at or below it. */exportfunctionpercentile(values: number[], q: number): number | null {if (values.length === 0) returnnull
Nearest rank, and the empty list Scheduled
WhatThe doc comment defines nearest rank: the smallest value with at least a fraction q of the values at or below it. An empty list returns null, which rollUp stores as a NULL time.
WhyNearest rank always returns one of the observed values and never interpolates, so a p95 is a real question's time.
// Sort a copy and take the value at rank ceil(q × n).const sorted = [...values].sort((a, b) => a - b)return sorted[Math.max(0, Math.ceil(q * sorted.length) - 1)]}
Sort a copy, take rank ceil(q × n) Scheduled
WhatSorts a copy in ascending order and returns the element at 1-based rank ceil(q × n). The comparator is numeric because the default sort compares values as strings. Math.max(0, …) keeps q = 0 from indexing −1.
WhySorting a copy leaves the caller's array untouched. Two consequences of the rank rule are worth knowing. For 10 to 19 times the p95 is the maximum (ceil(0.95 × 19) = 19). For an even count the median is the lower of the two middle values.
/** The day `n` days before `day`, as 'YYYY-MM-DD'. */exportfunctiondaysBefore(day: string, n: number): string {returnnewDate(Date.parse(`${day}T00:00:00Z`) - n * 86_400_000).toISOString().slice(0, 10)}
n days earlier, as a UTC date Scheduled
WhatParses the day as midnight UTC, subtracts n × 86,400,000 ms and keeps the first 10 characters of the ISO string.
WhyUTC has no daylight-saving changes, so subtracting whole days of milliseconds is exact. The 'YYYY-MM-DD' result sorts correctly as text, which the SQL comparisons (day >= ?, BETWEEN) rely on. healthRoute also calls it, for the start of /admin's 30-day and 14-day windows.
/** STEP 1 · one day's questions rolled up, per via; the day's rows are replaced. Canary questions are left out. */exportasyncfunctionrollUp(env: Env, day: string): Promise<DayRow[]> {// Read the day's questions, leaving out the canary's.
Signature Scheduled
WhatTakes the Worker's bindings and a UTC day, and returns the rows it wrote.
WhyThe day is a parameter instead of a fixed 'yesterday', so dailyHealth can use the same function to catch up on missed days.
const rows = (await env.DB.prepare(`SELECT COALESCE(via, 'page') AS via, checked, fallback, ms, first_ms FROM questions WHERE substr(asked_at, 1, 10) = ? AND COALESCE(via, 'page') <> 'canary'`, ).bind(day).all<{ via: string; checked: number; fallback: string | null; ms: number | null; first_ms: number | null }>()).results
The day's questions, canary excluded Scheduled
WhatOne D1 prepared statement reads via (NULL read as 'page'), checked, fallback, ms and first_ms for every question whose asked_at falls on the day, leaving out rows with via 'canary'.
WhySQLite's datetime('now') writes asked_at as UTC 'YYYY-MM-DD HH:MM:SS', so its first 10 characters are the UTC day. The indexes on questions start with id or demo_id, so none serves a filter on the day alone, and the query scans the whole table once a day. It reads metadata only, never the question or answer text.
// One row per route that had questions that day.constout: DayRow[] = []for (const via ofVIAS) {const mine = rows.filter((row) => row.via === via)if (mine.length === 0) continue
One row per route with traffic Scheduled
WhatFor each of 'page' and 'mcp', takes that route's rows. A route with no questions that day gets no row.
WhyA row of zeros would change nothing in the drift check, since its asks would be under MIN_DAY and its p95 NULL. Writing no row has a cost in dailyHealth: a day without traffic never appears among the days already rolled up, so every run within reach rolls it up again.
// Count each kind of fallback and gather the timings.constcount = (fallback: string) => mine.filter((row) => row.fallback === fallback).lengthconst times = mine.map((row) => row.ms).filter((ms): ms is number => ms !== null)const firsts = mine.map((row) => row.first_ms).filter((ms): ms is number => ms !== null)
Count the fallbacks, gather the times Scheduled
Whatcount(reason) counts the rows with that fallback. times collects every non-null ms, which ask() records on every outcome. firsts collects every first_ms, which is set only when at least one unit was released.
WhyFallbacks are timed too, so a slow fallback still shows in the p95. first_p50 measures what streaming is for, the wait before the first checked sentence, so it covers answered and stopped questions only. refused, trouble and not_found release nothing and have no first_ms.
// A question counts as answered when it passed the check and did not fall back. out.push({ day, via, asks: mine.length,answered: mine.filter((row) => row.checked === 1 && row.fallback === null).length,not_found: count('not_found'), refused: count('refused'), trouble: count('trouble'), stopped: count('stopped'),ms_p50: percentile(times, 0.5), ms_p95: percentile(times, 0.95), first_p50: percentile(firsts, 0.5), }) }
Answered, the counts and the percentiles Scheduled
Whatanswered counts rows with checked = 1 and no fallback. The row also carries the four fallback counts, p50 and p95 of ms, and p50 of first_ms.
WhyA stopped answer has checked = 1 and fallback 'stopped', so it is not counted as answered, because part of it was withheld. Every row ask() writes has either a fallback or checked = 1, so answered and the four fallback counts add up to asks.
// Swap the day's old rows for the new ones in one go.await env.DB.batch([ env.DB.prepare('DELETE FROM pipeline_days WHERE day = ?').bind(day), ...out.map((r) => env.DB.prepare('INSERT INTO pipeline_days (day, via, asks, answered, not_found, refused, trouble, stopped, ms_p50, ms_p95, first_p50) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', ).bind(r.day, r.via, r.asks, r.answered, r.not_found, r.refused, r.trouble, r.stopped, r.ms_p50, r.ms_p95, r.first_p50)), ])
Replace the day's rows atomically Scheduled
WhatOne D1 batch deletes every pipeline_days row for the day and inserts the new ones.
WhyD1 runs a batch as one transaction, so a reader never sees the day half-replaced. Rolling the same day up again is idempotent, which matters because every run redoes yesterday. Deleting first also removes a route's old row when that route has no questions in the new roll-up.
/** * STEP 2 · the drift rules, as a pure function of one day and its baseline days (same via). * * A rate is a count out of the day's questions. The baseline rate p is pooled over the baseline days * (their counts summed over their questions summed). Under "nothing changed", the day's rate is a * binomial proportion around p with standard error sqrt(p(1-p)/n), so a rate more than SIGMAS standard * errors above p is unlikely to be noise; MIN_RATE_JUMP adds a floor of 5 points (one miss clears it below 20 questions). * Time is flagged against the median of the baseline days' p95s, a robust centre one slow day cannot drag. */
The statistics, stated Never runs
WhatThe doc comment states the model. The baseline rate p is pooled: the summed counts over the summed questions. If nothing changed, the day's rate is a binomial proportion around p with standard error sqrt(p(1 − p)/n), so a rate more than SIGMAS standard errors above p is unlikely to be noise. Time is judged against the median of the baseline days' p95s.
WhyAs a pure function, the rules can be tested with plain rows and no D1. The standard error uses the day's n because it describes the spread of a single day's rate. As this comment and MIN_RATE_JUMP's comment say, the 5-point floor stops a single miss from raising a flag only on days of 20 questions or more.
// Rates: compare each fallback rate with the pooled baseline, once the baseline is big enough.const baseAsks = baseline.reduce((sum, row) => sum + row.asks, 0)if (baseAsks >= MIN_BASELINE_ASKS) {
Pool the baseline's questions Scheduled
WhatbaseAsks sums asks over the baseline rows. Rates are judged only when it reaches MIN_BASELINE_ASKS (30).
WhyPooling counts weights each baseline day by its traffic. Averaging daily rates instead would give a 3-question day as much weight as a 300-question day.
for (const metric ofRATES) {const p = baseline.reduce((sum, row) => sum + row[metric], 0) / baseAsksconst rate = today[metric] / today.asksconst threshold = Math.max(p + SIGMAS * Math.sqrt((p * (1 - p)) / today.asks), p + MIN_RATE_JUMP)
p, the day's rate, and the threshold Scheduled
WhatFor each of the four metrics: p = baseline count / baseAsks, rate = today's count / today's asks, threshold = max(p + 3 × sqrt(p(1 − p)/n), p + 0.05) with n = today's asks.
WhyThe test is one-sided because only a rise means something broke; a falling fallback rate is good news. The standard error shrinks as 1/sqrt(n), so a busy day is held to a tighter threshold than a quiet one.
p = 0.05, n = 20 → 0.196 (demo/tests/health.test.ts)p = 0.10, n = 10 → 0.385p = 0.10, n = 100 → 0.19p = 0, any n → 0.05
// Times: flag a slow day against the middle of the baseline days' p95s.const p95s = baseline.map((row) => row.ms_p95).filter((ms): ms is number => ms !== null)if (p95s.length >= MIN_BASELINE_DAYS && today.ms_p95 !== null) {
Enough baseline days with a p95 Scheduled
WhatCollects the baseline rows' non-null ms_p95 values. The time rule runs only when there are at least MIN_BASELINE_DAYS (5) of them and the day has a p95.
WhyThis minimum counts days because the centre is a median of daily values, and a median of fewer than five values moves easily.
const centre = percentile(p95s, 0.5) asnumberif (today.ms_p95 > SLOW_FACTOR * centre) flags.push({ day: today.day, via: today.via, metric: 'ms_p95', value: today.ms_p95, baseline: centre, threshold: SLOW_FACTOR * centre }) }
Median of p95s, times 1.5 Scheduled
Whatcentre is the nearest-rank median of the baseline p95s. A day's p95 above 1.5 × centre is flagged with metric 'ms_p95'.
WhyWhile fewer than half the baseline days are slow, the median stays within the normal days' p95s, so one bad day in the last two weeks does not raise the threshold and hide a second one. The `as number` cast is safe because the list is not empty at this point.
centre 2,000 ms → threshold 3,000 ms (demo/tests/health.test.ts)
/** STEP 2 · checks one rolled-up day against the 14 days before it, and stores its flags (replacing that day's traffic flags). */exportasyncfunctioncheckDrift(env: Env, day: string): Promise<Flag[]> {// Load the day and the 14 days before it.const rows = (await env.DB.prepare('SELECT * FROM pipeline_days WHERE day BETWEEN ? AND ?').bind(daysBefore(day, BASELINE_DAYS), day).all<DayRow>()).results
The day and the 14 days before Scheduled
WhatOne query reads every pipeline_days row from 14 days before the day through the day itself, for both routes.
WhyOne round trip serves both routes, the day and its baseline. The range covers 15 days: the day plus BASELINE_DAYS before it.
// Judge each route against its own history.const flags = VIAS.flatMap((via) => {const today = rows.find((row) => row.day === day && row.via === via)return today === undefined ? [] : driftFlags(today, rows.filter((row) => row.via === via && row.day < day)) })
Each route against its own history Scheduled
WhatFor each via, finds the day's row and passes driftFlags the same via's rows from earlier days. A route with no row had no traffic and gets no flags.
WhyThe filter row.day < day keeps the day out of its own baseline, so a bad day cannot raise the threshold it is judged against.
// Replace the day's traffic flags; canary flags are left alone.await env.DB.batch([ env.DB.prepare("DELETE FROM pipeline_flags WHERE day = ? AND via <> 'canary'").bind(day), ...flags.map((f) => env.DB.prepare('INSERT INTO pipeline_flags (day, via, metric, value, baseline, threshold) VALUES (?, ?, ?, ?, ?, ?)') .bind(f.day, f.via, f.metric, f.value, f.baseline, f.threshold)), ])
Replace the day's traffic flags Scheduled
WhatOne D1 batch deletes the day's flags whose via is not 'canary' and inserts the new ones.
WhyRe-checking a day (a second run on the same date redoes yesterday) leaves exactly the current flags, and a flag that no longer applies is removed. runCanary writes the canary's flag for the same day, and this batch leaves it alone.
/** * The daily job's part: yesterday rolled up and checked, any missed day within reach too, then the canary. * Each step on its own, so one failing does not stop the rest. */
Each step on its own Never runs
WhatThe doc comment gives the order (yesterday's roll-up and drift check, any missed days, then the canary) and says each step runs on its own.
WhyThe health job is a monitor, and a monitor that failed silently along with the pipeline would report nothing. Keeping the steps apart means a D1 error in the roll-up still lets the canary run and report.
// Roll up and check every recent day not done yet, and always yesterday.try {// The days already rolled up.const have = newSet((await env.DB.prepare('SELECT DISTINCT day FROM pipeline_days WHERE day >= ?').bind(daysBefore(today, CATCH_UP_DAYS)).all<{ day: string }>()).results.map((row) => row.day))
Days already rolled up Scheduled
WhatReads the distinct days in pipeline_days from 9 days ago onward into a Set.
WhyA day with no questions on either route has no row, so it is never in the Set and every run redoes it. Each redo costs a scan of questions, a 15-day read of pipeline_days and two DELETE batches that remove nothing.
// Oldest first, so each day's baseline already holds the days before it.for (let n = CATCH_UP_DAYS; n >= 1; n--) {const day = daysBefore(today, n)if (day !== yesterday && have.has(day)) continueawaitrollUp(env, day)awaitcheckDrift(env, day) }
Oldest first, yesterday always Scheduled
WhatLoops n from 9 down to 1. A day already in the Set is skipped unless it is yesterday; every other day is rolled up and then checked for drift.
WhyGoing oldest first means each day's baseline already includes the caught-up days before it when it is checked. Yesterday is redone even when present, so a second run on the same date (a retried or manually triggered cron) recomputes it from the questions. For every older day, a row in pipeline_days means it is done.
} catch (error) {console.error('health: the roll-up or the drift check failed', error) }
A failed roll-up is logged Scheduled
WhatAny error from the read of rolled-up days, a roll-up or a drift check is logged, and the loop stops.
WhyA day 1 to 8 days back whose roll-up never ran is retried by the next day's run, because it is still missing from the Set. A day whose roll-up succeeded but whose drift check failed is never retried, because its rows put it in the Set; later runs skip it and its flags are never computed. A failure on the day 9 days back loses that day, because by the next run it is 10 days back, outside CATCH_UP_DAYS.
// Run the canary on its own, so a failed roll-up does not stop it.try {awaitrunCanary(env, models, options, yesterday)
The canary, on its own Scheduled
WhatRuns the canary for yesterday in its own try block.
WhyThe canary needs D1, the models and the pipeline, and does not depend on the roll-up, so a roll-up failure must not stop it. Its results are stored under yesterday's date, the same day as the traffic rows the admin page shows with them, although its questions are asked today.
} catch (error) {// A canary that cannot run is itself a sign something broke (the upload, the embeddings, D1): it is flagged// as no case passing, so it reaches Joel like any failure, never as silence.console.error('health: the canary failed to run', error)if (env.CANARY_ENABLED !== '0') {await env.DB.prepare("INSERT OR REPLACE INTO pipeline_flags (day, via, metric, value, baseline, threshold) VALUES (?, 'canary', 'canary', 0, ?, ?)") .bind(yesterday, CANARY_CASES.length, CANARY_CASES.length).run().catch((again) =>console.error('health: the canary flag could not be written', again)) } }}
A canary that cannot run is a failure Scheduled
WhatIf runCanary throws (the upload failed, a D1 error, or any other exception from ask()), the error is logged. Unless CANARY_ENABLED is '0', a canary flag is then written for yesterday with value 0 out of 6. INSERT OR REPLACE overwrites any canary flag already there, and a failure to write the flag is only logged.
WhyA crash must be flagged as a failed canary, never left with no flag. Because a crash writes the same flag row as a failed run, the admin page and the site's alert treat the two alike. The final .catch stops an error in writing the flag from escaping into the scheduled handler, where it would stop the purge, the expiry and forgetHits.
/** `/internal/admin/health`: the last 30 days, their flags, and the canary's last 14 days. */exportasyncfunctionhealthRoute(env: Env, now = newDate()): Promise<Response> {const today = now.toISOString().slice(0, 10)
The admin page's read Site request
WhatThe site's admin routes call GET /internal/admin/health through the DEMO service binding, and the router (app.ts) dispatches it before any access key is checked. The route is off the question path and only reads what the scheduled job wrote.
WhyThe site's proxy never forwards /internal paths, so only the site's server code can reach this route, and the route needs no visitor key.
// The last 30 days of numbers and flags, and 14 days of canary runs, in one round trip.const [days, flags, canary] = await env.DB.batch([ env.DB.prepare('SELECT * FROM pipeline_days WHERE day >= ? ORDER BY day DESC, via').bind(daysBefore(today, 30)), env.DB.prepare('SELECT * FROM pipeline_flags WHERE day >= ? ORDER BY day DESC, via, metric').bind(daysBefore(today, 30)), env.DB.prepare('SELECT day, name, passed, found, ms FROM canary_runs WHERE day >= ? ORDER BY day DESC, name').bind(daysBefore(today, 14)), ])
Three reads in one batch Site request
WhatOne D1 batch runs three SELECTs: pipeline_days and pipeline_flags from the last 30 days, newest first, and canary_runs from the last 14 days, without the answer column.
WhyA batch is one round trip from the Worker to D1, and D1 runs its statements in order as one transaction. The canary query returns day, name, passed, found and ms, and leaves out the stored answers (up to 300 characters each).
days, flags: day >= today − 30canary: day >= today − 14