Public: anyone can read this; the crew can change it.

Health says whether the forge is serving; what it would like done is a separa… #12117

Parked opened this in answer to
Closed without merging

mason/forge:mason/12071-health-says-whether-the-forge-is-serving → main 6 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
23 files changed +249 −211
src/crew/notify.ts −29
@@ -38,9 +38,6 @@ import { err, ok, type Result } from "../kernel/result.ts";
3838 import { lastMirror, mirrorNeed } from "../snapshot/mirror.ts";
3939 import { markRollbackPaged, rollbackNeed, rolledBack } from "../release/launch.ts";
4040 import { drillNeed, firstSeen, lastVerdict } from "../snapshot/verdict.ts";
41 import { domainDrillNeeds } from "../kernel/domain_drill.ts";
42 import { DOMAINS } from "../kernel/domains.ts";
43 import { newestDrills } from "../core/domain_drills.ts";
4441 import { health } from "../http/health.ts";
4542 import { forgeVitals } from "../actions/health.ts";
4643 import { RECOVERED, drainIncident, nextPage, observe, recoveredLine, type Watch } from "./incidents.ts";
@@ -228,31 +225,6 @@ export function drillLines(
228225 return [{ id, line: need.sentence, items: [id] }];
229226 }
230227
231 /**
232 * The forge's admin hears of a domain drill that is red, stale or never run,
233 * with the command that runs it. The needs are the vitals' own
234 * (`domainDrillNeeds`); the id is the cause and its `since`, so a repeat tick
235 * is not news and a later red is.
236 */
237 export function domainDrillLines(
238 app: App,
239 user: User,
240 now = Date.now(),
241 forgeUrl = "http://localhost",
242 ): { id: string; line: string; items: readonly string[] }[] {
243 if (!user.isAdmin || user.kind !== "user") return [];
244 return domainDrillNeeds(
245 newestDrills(app.db),
246 now,
247 firstSeen(app.config.dataDir),
248 forgeUrl,
249 DOMAINS,
250 ).map((need) => {
251 const id = `${need.cause}@${need.since}`;
252 return { id, line: need.sentence, items: [id] };
253 });
254 }
255
256228 /** The admin hears of a snapshot that did not land off the box, or a stale mirror, once per cause. */
257229 export function mirrorLines(
258230 app: App,
@@ -508,7 +480,6 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
508480 ...landedLines(app.db, user, now()),
509481 ...mailCeilingLines(app, user, now()),
510482 ...drillLines(app, user, now()),
511 ...domainDrillLines(app, user, now(), options.forgeUrl),
512483 ...mirrorLines(app, user, now()),
513484 ...redLines(app, user, now()),
514485 ...alarmLines(app, user, now(), options.alarms?.()),
src/crew/routine_report.ts +1 −1
@@ -103,7 +103,7 @@ export async function facts(app: App, user: User, now: number, sinceMs = now - 3
103103 const story = await storyFacts(app, sinceMs);
104104 return {
105105 ...story,
106 health: vitals.ok ? [] : vitals.needs.slice(0, 3),
106 health: vitals.broken.slice(0, 3),
107107 redMain: redLines(app, user, now).map((l) => l.line),
108108 asks: askLinesFor(db, user).length,
109109 holds,
src/http/mcp/tools/health.ts +2 −2
@@ -3,9 +3,9 @@ import { good, type Tool } from "../shared.ts";
33
44 export const tool: Tool = {
55 name: "health",
6 doc: "how this forge is: the version and commit it runs, draining or not, the rollout and its incidents",
6 doc: "how this forge is: the version and commit it runs, draining or not, the rollout and its incidents; ok is false only for what is broken (broken), never for what is merely wanted (todo)",
77 description:
8 "How this forge is: version, commit, draining or not, rollout, incidents.",
8 "Whether the forge is serving: ok is false only when something is broken now (act now); todo is what it would like done.",
99 inputSchema: { type: "object", properties: {} },
1010 writes: false,
1111 run: (ctx, user) => good(readHealth(ctx.app, user)),
src/kernel/vitals.ts +38 −31
@@ -38,11 +38,8 @@ import { proofNeed, proofNotice } from "../release/prove.ts";
3838 import { running as runningVersion } from "./version.ts";
3939 import { rollbackNeed } from "../release/launch.ts";
4040 import { behindStanding } from "../release/behind.ts";
41 import { newestDrills } from "../core/domain_drills.ts";
4241 import { capacityValue } from "../core/capacity.ts";
4342 import { unwrittenFor, SILENT_AFTER_S } from "../http/access_log.ts";
44 import { DOMAINS } from "./domains.ts";
45 import { domainDrillNeeds } from "./domain_drill.ts";
4643 import { freeChecks, heldChecks, redHref, redSentence } from "../checks/red_main.ts";
4744 import { diskRedSentence, diskReds } from "../checks/disk_red.ts";
4845 import { flakeList, type FlakeRow } from "../checks/flake.ts";
@@ -83,6 +80,8 @@ export interface EnvCount {
8380 */
8481 export interface Degraded {
8582 readonly cause: string;
83 /** `broken`: act now, the forge is not well; `todo`: would like done, it serves meanwhile. */
84 readonly tier: "broken" | "todo";
8685 readonly sentence: string;
8786 readonly since: string;
8887 readonly href: string;
@@ -100,8 +99,12 @@ export interface Lane {
10099 }
101100
102101 export interface Vitals {
102 /** The forge is serving and nothing is broken now: only `broken` makes it false. */
103103 readonly ok: boolean;
104 readonly needs: string[];
104 /** Act now: the disk is full or under its floor, a red main holds the checks. */
105 readonly broken: string[];
106 /** Would like done: it serves meanwhile (a big database, a release unproven, a slow lane). */
107 readonly todo: string[];
105108 readonly degraded: Degraded[];
106109 readonly disk: { freeBytes: number; totalBytes: number };
107110 readonly memory: {
@@ -322,11 +325,13 @@ export function laneSentence(
322325 export function vitals(input: VitalsInput): Vitals {
323326 const now = input.now ?? Date.now();
outdated

Cause-prefix matching decides what is 'broken'. A new cause silently becomes todo. Pass the tier explicitly in need() at each call site, and test that each tier choice is intended.

324327 const at = new Date(now).toISOString();
325 const needs: string[] = [];
328 const broken: string[] = [];
329 const todo: string[] = [];
326330 const degraded: Degraded[] = [];
327331 let firstSeen = firstSeenByForge.get(input.signals.errors);
328332 if (!firstSeen) firstSeenByForge.set(input.signals.errors, (firstSeen = new Map()));
329333 const need = (
334 tier: Degraded["tier"],
330335 cause: string,
331336 sentence: string,
332337 evidence: string | undefined,
@@ -337,8 +342,8 @@ export function vitals(input: VitalsInput): Vitals {
337342 since = evidence ?? new Date().toISOString();
338343 firstSeen.set(cause, since);
339344 }
340 needs.push(sentence);
341 degraded.push({ cause, sentence, since, href });
345 (tier === "broken" ? broken : todo).push(sentence);
346 degraded.push({ cause, tier, sentence, since, href });
342347 };
343348
344349 const disk = (input.disk ?? readDisk)(input.dataDir);
@@ -347,6 +352,7 @@ export function vitals(input: VitalsInput): Vitals {
347352 const room = roomy(disk);
348353 if (disk.totalBytes > 0 && disk.freeBytes / disk.totalBytes < (input.diskFreeMin ?? DISK_FREE_MIN))
349354 need(
355 "broken",
350356 "disk",
351357 `Disk is nearly full: ${Math.round((disk.freeBytes / disk.totalBytes) * 100)}% free.`,
352358 undefined,
@@ -354,6 +360,7 @@ export function vitals(input: VitalsInput): Vitals {
354360 );
355361 else if (disk.totalBytes > 0 && !room && disk.freeBytes / disk.totalBytes < DISK_FLOOR)
356362 need(
363 "broken",
357364 "disk-floor",
358365 `Disk is under the ${DISK_FLOOR * 100}% the forge keeps for itself: ${Math.round((disk.freeBytes / disk.totalBytes) * 100)}% free. Child forges sleep, and no child forge, app or check starts, until room is made.`,
359366 undefined,
@@ -365,6 +372,7 @@ export function vitals(input: VitalsInput): Vitals {
365372 const mark = DISK_USED_MARKS.find((m) => used >= m);
366373 if (mark !== undefined)
367374 need(
375 "todo",
368376 `disk-${Math.round(mark * 100)}`,
369377 `Disk under the forge's data is ${Math.floor(used * 100)}% used, past the ${Math.round(mark * 100)}% mark.`,
370378 undefined,
@@ -373,7 +381,7 @@ export function vitals(input: VitalsInput): Vitals {
373381 }
374382
375383 for (const file of openDbFiles(input.dataDir))
376 need(`file:${file.name}`, file.sentence, undefined, "/settings/capacity");
384 need("todo", `file:${file.name}`, file.sentence, undefined, "/settings/capacity");
377385
378386 // A database past the 2 GiB Bun maps, or growing faster than 64 MiB a day, is said (#12010),
379387 // with what fills it from the last walk once there is one (#12051): the sentence is the
@@ -382,7 +390,7 @@ export function vitals(input: VitalsInput): Vitals {
382390 const dbGrows = dbGrowth(input.db, dbBytes, now);
383391 let dbBig = dbSizeNeed(dbBytes, dbGrows);
384392 if (dbBig !== undefined) dbBig = dbSizeNeed(dbBytes, dbGrows, (input.dbWalk ?? dbSize.last)(input.db, input.dataDir));
385 if (dbBig !== undefined) need(dbBig.cause, dbBig.sentence, undefined, "/system");
393 if (dbBig !== undefined) need("todo", dbBig.cause, dbBig.sentence, undefined, "/system");
386394
387395 // Snapshots on the volume they copy, and no mirror, share its one point of failure.
388396 const snaps = input.snapshots;
@@ -391,7 +399,7 @@ export function vitals(input: VitalsInput): Vitals {
391399 !snaps.mirrored &&
392400 sharesVolume(input.dataDir, snaps.dir)
393401 )
394 need("snapshots", SNAPSHOTS_ON_STATE_VOLUME, undefined, "/settings/backups");
402 need("todo", "snapshots", SNAPSHOTS_ON_STATE_VOLUME, undefined, "/settings/backups");
395403
396404 const running = listRunning(input.db);
397405 const lane = readLane(input.db, running, now);
@@ -409,6 +417,7 @@ export function vitals(input: VitalsInput): Vitals {
409417 // Age and "since" come from the free checks alone.
410418 if (free.oldest !== null && now - new Date(free.oldest).getTime() > BUDGETS.laneWait)
411419 need(
420 "todo",
412421 "queue:check",
413422 laneSentence(
414423 free.n,
@@ -443,6 +452,7 @@ export function vitals(input: VitalsInput): Vitals {
443452 const waited = now - new Date(oldest).getTime();
444453 if (waited > QUEUE_WAIT_MAX_MS)
445454 need(
455 "todo",
446456 `queue:${row.kind}`,
447457 queueSentence(
448458 row.kind,
@@ -472,6 +482,7 @@ export function vitals(input: VitalsInput): Vitals {
472482 }
473483 for (const s of stuck)
474484 need(
485 "todo",
475486 `stuck:${s.runId}`,
476487 now - new Date(s.since).getTime() > BUDGETS.heartbeat &&
477488 now - new Date(s.since).getTime() < 24 * 3_600_000
@@ -487,6 +498,7 @@ export function vitals(input: VitalsInput): Vitals {
487498 new Date(now - 24 * 3_600_000).toISOString(),
488499 ))
489500 need(
501 "todo",
490502 `budget:${run.id}`,
491503 `A run was killed twice: ${run.summary}.`,
492504 run.finishedAt ?? undefined,
@@ -496,6 +508,7 @@ export function vitals(input: VitalsInput): Vitals {
496508 // A red main holding its pulls' checks is one card, naming the test.
497509 for (const { red, held } of reds)
498510 need(
511 "broken",
499512 `red:${red.repoId}`,
500513 redSentence(red, held) + foreignNote(red.repo),
501514 red.since,
@@ -504,7 +517,7 @@ export function vitals(input: VitalsInput): Vitals {
504517
505518 // A test failing on many pulls in the hour is one card, not a park per pull.
506519 for (const shared of sharedTests(input.db, now))
507 need(sharedCause(shared), sharedSentence(shared) + foreignNote(shared.repo), shared.since, flakeHref(input.db, shared));
520 need("todo", sharedCause(shared), sharedSentence(shared) + foreignNote(shared.repo), shared.since, flakeHref(input.db, shared));
508521
509522 // Checks that failed on a full disk are one card, not a park per pull, and
510523 // only while the disk is still under the floor: once it is back the machine
@@ -512,56 +525,47 @@ export function vitals(input: VitalsInput): Vitals {
512525 const diskStillFull =
513526 disk.totalBytes > 0 && disk.freeBytes / disk.totalBytes < (input.diskFreeMin ?? DISK_FREE_MIN);
514527 const full = diskStillFull ? diskReds(input.db, now) : undefined;
515 if (full !== undefined) need("disk-red", diskRedSentence(full), full.since, "/settings/capacity");
528 if (full !== undefined) need("broken", "disk-red", diskRedSentence(full), full.since, "/settings/capacity");
516529
517530 // A red restore drill, or none in eight days, is a card until a drill passes.
518531 const drill = lastVerdict(input.dataDir);
519532 const owed = drillNeed(drill, now, () => drillFirstSeen(input.dataDir));
520533 if (owed !== undefined)
521 need("drill", owed.sentence, owed.since, "/settings/backups");
522
523 // A domain whose drill is red or eight days old is a card with the command that runs it.
524 for (const owed of domainDrillNeeds(
525 newestDrills(input.db),
526 now,
527 drillFirstSeen(input.dataDir),
528 input.forgeUrl ?? "http://localhost",
529 DOMAINS,
530 ))
531 need(owed.cause, owed.sentence, owed.since, "/");
534 need("todo", "drill", owed.sentence, owed.since, "/settings/backups");
532535
533536 // A snapshot that failed is a card from that morning until one lands.
534537 const failing = snapshotNeed(lastSnapshotOutcome(input.dataDir));
535 if (failing !== undefined) need("snapshot-failed", failing.sentence, failing.since, "/settings/backups");
538 if (failing !== undefined) need("todo", "snapshot-failed", failing.sentence, failing.since, "/settings/backups");
outdated

A comment that explains a deletion is dead weight. notify.ts still raises this need (src/crew/notify.ts:244), so health and the pager now disagree. Remove both or keep both.

536539
537540 // The bucket itself, read by this process: late, unreadable, a failed drill, or a check that stopped is one card.
538541 if (isWatched(input.dataDir)) {
539542 const backup = backupVerdict(input.dataDir, lastDrill(input.db), now);
540 if (backup.state === "red") need("backup", [...backup.reasons, ...(backup.reasons.some((r) => r.includes("last ran")) ? [] : [backup.checkLine])].join(" "), backup.checkedAt ?? undefined, "/settings/backups");
543 if (backup.state === "red") need("todo", "backup", [...backup.reasons, ...(backup.reasons.some((r) => r.includes("last ran")) ? [] : [backup.checkLine])].join(" "), backup.checkedAt ?? undefined, "/settings/backups");
541544 }
542545
543546 // A snapshot that did not land off the box, or a mirror a day behind, is a card until it does.
544547 const behind = mirrorNeed(lastMirror(input.dataDir), now);
545 if (behind !== undefined) need("mirror", behind.sentence, behind.since, "/settings/backups");
548 if (behind !== undefined) need("todo", "mirror", behind.sentence, behind.since, "/settings/backups");
546549
547550 // A release the forge could not prove against its own public URL is a card until a release does.
548551 // Only a release that is not serving as it should is a card; a proof that could not finish for its own reasons (the sign-up limit, a slow answer) is a notice on /releases and on the home.
549552 const unproven = proofNeed(input.dataDir, runningVersion().version);
550 if (unproven !== undefined && proofNotice(input.dataDir, runningVersion().version, now)?.tone === "alarm") need("release", unproven.sentence, unproven.since, "/releases#proof");
553 if (unproven !== undefined && proofNotice(input.dataDir, runningVersion().version, now)?.tone === "alarm") need("todo", "release", unproven.sentence, unproven.since, "/releases#proof");
551554
552555 // A roll the image's launcher undid is a card until a later version reads ready. Its sentence
553556 // carries the release's own last words (stderr), so anything credential-shaped is masked.
554557 const undone = rollbackNeed(input.dataDir);
555 if (undone !== undefined) need("release:rolled-back", redactSecrets(undone.sentence), undone.since, "/board");
558 if (undone !== undefined) need("todo", "release:rolled-back", redactSecrets(undone.sentence), undone.since, "/board");
556559
557560 // Production serving a version older than a release main has had over an hour is a card until they match.
558561 const lagging = behindStanding(now);
559 if (lagging !== undefined) need("release:behind", `${lagging.sentence}.`, lagging.since, "/board");
562 if (lagging !== undefined) need("todo", "release:behind", `${lagging.sentence}.`, lagging.since, "/board");
560563
561564 // Lines recorded and not landed for five minutes: the writer is failing, however quiet the site.
562565 const quiet = unwrittenFor(now);
563566 if (quiet !== undefined && quiet > SILENT_AFTER_S)
564567 need(
568 "todo",
565569 "access-log",
566570 `The access log is not writing: a recorded line has waited ${quiet} s to reach disk (limit ${SILENT_AFTER_S / 60} min).`,
567571 new Date(now - quiet * 1000).toISOString(),
@@ -578,6 +582,7 @@ export function vitals(input: VitalsInput): Vitals {
578582 const seen = recentErrors(5, now, input.signals.errors);
579583 if (seen.lastHour >= ERROR_BURST)
580584 need(
585 "todo",
581586 "errors",
582587 `${seen.lastHour} errors in the last hour (${ERROR_BURST} or more is a burst).`,
583588 seen.oldest,
@@ -587,6 +592,7 @@ export function vitals(input: VitalsInput): Vitals {
587592 const refused = refusedInternal(now, input.signals.refused);
588593 if (refused.lastHour > 0)
589594 need(
595 "todo",
590596 "internal",
591597 `${refused.lastHour} internal call${refused.lastHour === 1 ? "" : "s"} without the boot secret refused in the last hour${refused.latest ? ` (latest ${refused.latest.method} ${refused.latest.path})` : ""}.`,
592598 refused.oldest,
@@ -597,8 +603,9 @@ export function vitals(input: VitalsInput): Vitals {
597603 if (!degraded.some((d) => d.cause === cause)) firstSeen.delete(cause);
598604
599605 return {
600 ok: needs.length === 0,
601 needs,
606 ok: broken.length === 0,
607 broken,
608 todo,
602609 degraded,
603610 disk,
604611 memory: {
src/release/journey.ts +16 −1
@@ -29,6 +29,11 @@ export interface JourneyOptions {
2929 readonly base: string;
3030 /** How to reach it; `fetch` when left out. A test hands in one that knows where the new forge's host is. */
3131 readonly fetch?: typeof fetch;
32 /**
33 * Headers sent on every request to the forge itself, never to the throwaway forge it makes:
34 * the forge's own probe, so the walk is not counted as a stranger.
35 */
36 readonly headers?: Readonly<Record<string, string>>;
3237 /** The tiny thing to ask the crew to build. */
3338 readonly ask?: string;
3439 /** Milliseconds, monotonic enough to subtract; `Date.now` when left out. */
@@ -116,8 +121,18 @@ export async function walkJourney(options: JourneyOptions): Promise<JourneyResul
116121 return { ok: false, screens, readyMs, firstActivityMs, failure: "the forge's address is not http or https", forge, removed };
117122 const hostUrl = host;
118123
124 /** The forge's probe headers go to the forge itself, never to the throwaway forge it makes. */
125 const headersFor = (url: URL, own: ConstructorParameters<typeof Headers>[0]): Record<string, string> => ({
outdated

One 200+ column line that nests a ternary and a cast. Split it into a small headersFor(url) helper; this also keeps header-width happy.

126 ...(url.origin === hostUrl.origin ? options.headers : undefined),
127 ...Object.fromEntries(new Headers(own)),
128 });
119129 const call = (url: URL, init: RequestInit = {}): Promise<Response> =>
120 doFetch(url.href, { redirect: "manual", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), ...init });
130 doFetch(url.href, {
131 redirect: "manual",
132 signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
133 ...init,
134 headers: headersFor(url, init.headers),
135 });
121136 const form = (url: URL, fields: Record<string, string>, extra: Record<string, string> = {}): Promise<Response> =>
122137 call(url, {
123138 method: "POST",
src/release/prove.ts +1 −1
@@ -307,7 +307,7 @@ export async function proveRelease(o: ProveOptions): Promise<Proof | undefined>
307307 if (failures[0] !== undefined || o.journey === undefined)
308308 return finish(failures[0] === undefined ? undefined : checkLine(failures[0]), failures[0]?.slow === true || failures[0]?.empty === true || failures[0]?.hung === true);
309309 // The stranger's journey, the last check: a failed walk is a failed proof, retried on `retryAfter` like any other (one card, paged once).
310 const walked = await o.journey({ base: o.url, fetch: doFetch, ...(o.token ? { adminToken: o.token } : {}) });
310 const walked = await o.journey({ base: o.url, fetch: doFetch, headers: ownProbeHeaders(o.dataDir), ...(o.token ? { adminToken: o.token } : {}) });
311311 return finish(walked.ok ? undefined : `a stranger's journey failed: ${walked.failure ?? "it did not finish"}`, false, false, walked);
312312 } catch (error) {
313313 return finish(`the smoke checks could not run: ${String(error)}`);
src/spawn/door.ts +7 −3
@@ -23,6 +23,7 @@ import { repoDir } from "../git/repos.ts";
2323 import { crossOrigin, type Ctx } from "../http/context.ts";
2424 import { changeLink } from "./manage.ts";
2525 import { takeDoor } from "../http/strangers.ts";
26 import { isProbe } from "../kernel/probe.ts";
2627 import {
2728 childPublicUrl,
2829 fallbackPlacement,
@@ -192,13 +193,16 @@ export async function spawnDoor(
192193 opts: { readonly paid?: boolean; readonly page?: boolean } = {},
193194 ): Promise<Door> {
194195 const paid = opts.paid === true;
196 // The forge's own journey prober (a release's proof) is not a stranger: neither limited
197 // nor counted against the day's allowance.
198 const probing = isProbe(ctx.request, ctx.app.config.dataDir);
195199 const anon = user === undefined;
196200 if (!anon && user.kind !== "user") return spawnWords({ kind: "forbidden" });
197201 // A forge asked for in order to contribute is never made: the fork path costs the host no cell.
198202 if (wantsToContribute(raw)) return { status: 200, body: contributeAnswer() };
199203 // A plan is free of children but not of work — it reads every catalog
200204 // app it names — so a stranger's are counted per address and per forge.
201 if (anon && !paid) {
205 if (anon && !paid && !probing) {
202206 const verdict = takeDoor(ctx.app, "plan", ctx.request);
203207 if (!verdict.allowed)
204208 return {
@@ -346,7 +350,7 @@ export async function spawnDoor(
346350 };
347351 }
348352 // A stranger may start only a few children a day; the plan above is free.
349 if (anon && !paid) {
353 if (anon && !paid && !probing) {
350354 const limit = checkAnonSpawn(ctx.app.db, ctx.request);
351355 if (!limit.allowed)
352356 return {
@@ -385,7 +389,7 @@ export async function spawnDoor(
385389 if (gift !== undefined && !settled) unclaimGift(ctx.app, gift);
386390 }
387391 if (!made.ok) return spawnWords(made.error);
388 if (anon && !paid && !made.value.existed) noteAnonSpawn(ctx.app.db, ctx.request);
392 if (anon && !paid && !probing && !made.value.existed) noteAnonSpawn(ctx.app.db, ctx.request);
389393 // The visitor who started (or was given) this forge becomes someone, on the host's side (#11265).
390394 if (!made.value.existed && !paid) linkRequestVisitor(ctx.app, ctx.request, made.value.name, gift === undefined ? "started" : "paid");
391395 // Its apps come up now, so the first visit after a claim finds them awake.
src/web/pages/board.ts +3 −1
@@ -431,7 +431,9 @@ function forgeNotes(ctx: Ctx): { notes: Note[]; ok: boolean; placement: Html | n
431431 const said = (line: string) => coveredByVerdict(line, verdict, fh);
432432 const rollout = rolloutLine(fh);
433433 const others = fh.incidents.filter((i) => !said(`${i.key}: ${i.message}`));
434 const ok = v.ok && fh.ok && verdict === undefined;
434 // Quiet only when nothing is asked of the owner, wanted things too:
435 // `v.ok` alone means only "nothing broken" (#12071).
436 const ok = v.degraded.length === 0 && fh.ok && verdict === undefined;
435437 const lane = laneLine(v.lane);
436438 const flaky = flakeLine(v.flakes);
437439 const sentinel = sentinelNotice(ctx.app.db);
test/asks-forge-alert.test.ts +1 −1
@@ -3,7 +3,7 @@ import { forgeCard } from "../src/web/studio/asks_page.ts";
33
44 // Principle 7 took the card away; the line must still read as an alert.
55 test("a degraded forge on /asks is an alert line in the danger tone, with Health on its own row", () => {
6 const out = String(forgeCard({ cause: "errors", sentence: "Errors <now>.", since: "2020-01-01T00:00:00.000Z", href: "/x" }));
6 const out = String(forgeCard({ cause: "errors", tier: "todo", sentence: "Errors <now>.", since: "2020-01-01T00:00:00.000Z", href: "/x" }));
77 const line = /<p role="alert">([\s\S]*?)<\/p>/.exec(out);
88 expect(line).not.toBeNull();
99 expect(line![1]).toContain('class="dot" data-tone="danger"');
test/backup-truth.test.ts +1 −1
@@ -290,7 +290,7 @@ test("the check records each run; stopped past its interval, the verdict, tile,
290290 const card = vitals({ db: own.db, signals: own.signals, dataDir: dir, now: later }).degraded.find((d) => d.cause === "backup");
291291 expect(card?.sentence).toContain(`last ran ${ranAt}`);
292292 const health = readHealth(own, { isAdmin: true } as User) as { ok: boolean; degraded: { cause: string; sentence: string }[] };
293 expect(health.ok).toBe(false);
293 expect(health.ok).toBe(true);
294294 expect(health.degraded.find((d) => d.cause === "backup")?.sentence).toContain(`last ran ${ranAt}`);
295295 expect(verdictLines({ app: own } as never).join("\n")).toContain("runs on record");
296296 } finally {
test/capacity.test.ts +4 −2
@@ -417,8 +417,10 @@ describe("report mode is loud to admins, and to nobody else", () => {
417417 const cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
418418 return (await fetch(`${servers.url}/settings/capacity`, { headers: { cookie } })).text();
419419 };
420 const needs = (who: User | undefined): string[] =>
421 "needs" in readHealth(app, who) ? (readHealth(app, who) as { needs: string[] }).needs : [];
420 const needs = (who: User | undefined): string[] => {
421 const h = readHealth(app, who);
outdated

Unreadable cast chain with a stray ';;'. Use allNeeds from ./vitals-needs.ts, or read .broken and .todo directly.

422 return "broken" in h ? [...h.broken, ...h.todo] : [];
423 };
422424
423425 const signedIn = async (): Promise<string> => {
424426 const res = await fetch(`${servers.url}/signin`, {
test/check-budget.test.ts +3 −2
@@ -3,6 +3,7 @@
33 * overrun failed and carried by the vitals as a card (#1271).
44 */
55
6 import { allNeeds } from "./vitals-needs.ts";
67 import { afterAll, beforeAll, expect, test } from "bun:test";
78 import { mkdtemp, rm } from "node:fs/promises";
89 import { tmpdir } from "node:os";
@@ -90,6 +91,6 @@ test("a check past its budget is re-queued once; the second overrun fails it and
9091 expect(second.summary).toMatch(/^budget: a full gate took \d+ min, limit \d+$/);
9192
9293 const seen = vitals({ db: app.db, signals: app.signals, dataDir });
93 expect(seen.ok).toBe(false);
94 expect(seen.needs.some((n) => n.includes("budget: a full gate"))).toBe(true);
94 expect(seen.ok).toBe(true);
95 expect(allNeeds(seen).some((n) => n.includes("budget: a full gate"))).toBe(true);
9596 }, 60_000);
test/disk-floor.test.ts +2 −1
@@ -7,6 +7,7 @@
77 * hands in.
88 */
99
10 import { allNeeds } from "./vitals-needs.ts";
1011 import { afterAll, afterEach, describe, expect, test } from "bun:test";
1112 import { mkdtempSync, rmSync } from "node:fs";
1213 import { tmpdir } from "node:os";
@@ -94,7 +95,7 @@ describe("below the floor", () => {
9495 try {
9596 const v = vitals({ db: app.db, signals: app.signals, dataDir: app.config.dataDir, disk: () => ({ freeBytes: 12, totalBytes: 100 }) });
9697 expect(v.degraded.map((d) => d.cause)).toEqual(["disk-floor"]);
97 expect(v.needs).toEqual(["Disk is under the 15% the forge keeps for itself: 12% free. Child forges sleep, and no child forge, app or check starts, until room is made."]);
98 expect(allNeeds(v)).toEqual(["Disk is under the 15% the forge keeps for itself: 12% free. Child forges sleep, and no child forge, app or check starts, until room is made."]);
9899 const at15 = vitals({ db: app.db, signals: app.signals, dataDir: app.config.dataDir, disk: () => ({ freeBytes: 15, totalBytes: 100 }) });
99100 // At the floor is not under it; 85% used is past the 80% mark (#11800), which says only that.
100101 expect(at15.degraded.map((d) => d.cause)).toEqual(["disk-80"]);
test/disk-marks.test.ts +2 −1
@@ -3,6 +3,7 @@
33 * forge's data used, once per crossing and Recovered once, and /system
44 * names the five largest directories under it.
55 */
6 import { allNeeds } from "./vitals-needs.ts";
67 import { afterAll, describe, expect, test } from "bun:test";
78 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
89 import { tmpdir } from "node:os";
@@ -38,7 +39,7 @@ describe("vitals names the highest mark passed", () => {
3839 test("69% says nothing, 70% and 80% say their mark, the floor says only the floor", () => {
3940 expect(at(69).degraded.map((d) => d.cause)).toEqual([]);
4041 expect(at(70).degraded.map((d) => d.cause)).toEqual(["disk-70"]);
41 expect(at(70).needs).toEqual(["Disk under the forge's data is 70% used, past the 70% mark."]);
42 expect(allNeeds(at(70))).toEqual(["Disk under the forge's data is 70% used, past the 70% mark."]);
4243 expect(at(79).degraded.map((d) => d.cause)).toEqual(["disk-70"]);
4344 expect(at(80).degraded.map((d) => d.cause)).toEqual(["disk-80"]);
4445 expect(at(88).degraded.map((d) => d.cause)).toEqual(["disk-floor"]);
test/domains.test.ts +3 −2
@@ -1,5 +1,6 @@
11 /** The failure-domain map: the doc and the data agree, and the forge really says what the data quotes. */
22
3 import { allNeeds } from "./vitals-needs.ts";
34 import { afterAll, beforeAll, expect, test } from "bun:test";
45 import { readFileSync } from "node:fs";
56 import { mkdtemp, rm } from "node:fs/promises";
@@ -39,7 +40,7 @@ const said = (key: string): string[] => {
3940 return [...d.says];
4041 };
4142 const read = (now = Date.now()) =>
42 vitals({ db: app.db, signals: app.signals, dataDir, now, disk: roomy }).needs.join("\n");
43 allNeeds(vitals({ db: app.db, signals: app.signals, dataDir, now, disk: roomy })).join("\n");
4344
4445 test("seven domains, each complete", () => {
4546 expect(DOMAINS.map((d) => d.key)).toEqual([
@@ -60,7 +61,7 @@ test("the doc's table is the data", () => {
6061
6162 test("a nearly full disk says the state's words", () => {
6263 const v = vitals({ db: app.db, signals: app.signals, dataDir, disk: roomy, diskFreeMin: 1.1 });
63 for (const s of said("state")) expect(v.needs.join("\n")).toContain(s);
64 for (const s of said("state")) expect(allNeeds(v).join("\n")).toContain(s);
6465 });
6566
6667 test("a red restore drill says the snapshot store's words", () => {
test/health-broken.test.ts added +98
@@ -0,0 +1,98 @@
1 /**
2 * #12071: `ok` says the forge is serving and nothing is broken now. What is
3 * broken (act now) and what is only wanted (todo) are two lists; only broken
4 * makes ok false.
5 */
6 import { afterEach, expect, test } from "bun:test";
7 import { mkdtempSync, truncateSync, writeFileSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp } from "../src/app.ts";
11 import { readHealth } from "../src/actions/health.ts";
12 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { health } from "../src/http/health.ts";
15 import { vitals } from "../src/kernel/vitals.ts";
16 import { dbFile } from "../src/system/db_size.ts";
17
18 const GiB = 1024 ** 3;
19 const roomy = () => ({ freeBytes: 900 * GiB, totalBytes: 1000 * GiB });
20
21 afterEach(() => {
22 health.draining = false;
23 });
24
25 const fresh = () => {
26 const dataDir = mkdtempSync(join(tmpdir(), "hb-"));
27 return { dataDir, app: createApp({ dataDir, port: 0 }) };
28 };
29 const read = (app: ReturnType<typeof createApp>, dataDir: string, disk = roomy) =>
30 vitals({ db: app.db, signals: app.signals, dataDir, disk });
31
32 test("a quiet forge is ok with nothing broken", () => {
33 const { app, dataDir } = fresh();
34 const v = read(app, dataDir);
35 expect(v.ok).toBe(true);
36 expect(v.broken).toEqual([]);
37 });
38
39 test("a full disk is broken, and ok is false", () => {
40 const { app, dataDir } = fresh();
41 const v = read(app, dataDir, () => ({ freeBytes: 2 * GiB, totalBytes: 100 * GiB }));
42 expect(v.ok).toBe(false);
43 expect(v.broken.join(" ")).toContain("Disk is nearly full");
44 expect(v.degraded.find((d) => d.cause === "disk")?.tier).toBe("broken");
45 });
46
47 test("a red main holding pulls is broken, and ok is false", async () => {
48 const { app, dataDir } = fresh();
49 app.db.run("INSERT INTO user (id, username, email, password_hash) VALUES ('u1', 'trevato', 't@x', '')");
50 app.db.run("INSERT INTO repo (id, owner_id, name) VALUES ('r1', 'u1', 'forge')");
51 app.db.run("INSERT INTO issue (id, repo_id, number, kind, title, author_id) VALUES ('i1', 'r1', 7, 'pull', 'p', 'u1')");
52 const run = createRun(app.db, { repoId: "r1", kind: "check", env: "main", commitOid: "b".repeat(40), reason: "push" });
53 claimRun(app.db, run.id);
54 finishRun(app.db, run.id, { state: "failed", summary: "check failed: 1 test failed", checkDetail: { passed: 1, failed: 1, names: ["a test"] } });
55 createRun(app.db, { repoId: "r1", kind: "check", env: "pull-7", issueId: "i1", commitOid: "a".repeat(40), reason: "push" });
56 const v = read(app, dataDir);
57 expect(v.ok).toBe(false);
58 expect(v.broken.join(" ")).toContain("a test");
59 expect(v.degraded.find((d) => d.cause === "red:r1")?.tier).toBe("broken");
60 expect(v.todo).toEqual([]);
61 });
62
63 test("a draining forge answers ok:false", async () => {
64 const { app } = fresh();
65 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "mira", email: "r@x", password: "a-good-passphrase", adminIfFirst: true });
66 if (!made.ok) throw new Error(made.error);
67 const admin = made.value;
68 expect(readHealth(app, admin)).toMatchObject({ ok: true });
69 health.draining = true;
70 expect(readHealth(app, admin)).toMatchObject({ ok: false, draining: true });
71 });
72
73 test("a database over 2 GiB is a todo: the forge still serves", () => {
74 const { app } = fresh();
75 const big = mkdtempSync(join(tmpdir(), "hb-big-"));
76 writeFileSync(dbFile(big), "");
77 truncateSync(dbFile(big), 3 * GiB);
78 const v = read(app, big);
79 expect(v.todo.join(" ")).toContain("past the 2 GiB");
80 expect(v.degraded.find((d) => d.cause === "db-size")?.tier).toBe("todo");
81 expect(v.broken).toEqual([]);
82 expect(v.ok).toBe(true);
83 });
84
85 test("no drill is owed: none runs by itself", () => {
86 const { app, dataDir } = fresh();
87 const v = read(app, dataDir);
88 expect([...v.broken, ...v.todo].join(" ")).not.toContain("drill");
89 });
90
91 test("each disk cause has the tier it was meant to have", () => {
92 const { app, dataDir } = fresh();
93 const tiers = (freeBytes: number, totalBytes: number) =>
94 Object.fromEntries(read(app, dataDir, () => ({ freeBytes, totalBytes })).degraded.map((d) => [d.cause, d.tier]));
95 expect(tiers(2 * GiB, 100 * GiB)).toMatchObject({ disk: "broken" });
96 expect(tiers(12, 100)).toMatchObject({ "disk-floor": "broken" });
97 expect(tiers(25 * GiB, 100 * GiB)).toMatchObject({ "disk-70": "todo" });
98 });
test/notify-causes.test.ts +1 −103
@@ -8,13 +8,9 @@ import { mkdtemp, rm } from "node:fs/promises";
88 import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
11 import { seedFirstSeen } from "../src/snapshot/verdict.ts";
12 import { DOMAINS } from "../src/kernel/domains.ts";
13 import { drillCommand } from "../src/kernel/domain_drill.ts";
14 import { recordDrill } from "../src/core/domain_drills.ts";
1511 import { createUser } from "../src/core/users.ts";
1612 import { owned } from "../src/crew/incidents.ts";
17 import { domainDrillLines, setNotifyUrl, startNotifier, type Notifier } from "../src/crew/notify.ts";
13 import { setNotifyUrl, startNotifier, type Notifier } from "../src/crew/notify.ts";
1814
1915 const MIN = 60_000;
2016
@@ -119,101 +115,3 @@ describe("the cause pager", () => {
119115 expect(posts).toHaveLength(0);
120116 });
121117 });
122
123 describe("domain drill lines", () => {
124 const URL_ = "https://forge.example.test";
125 const DAY = 86_400_000;
126 const t0 = Date.parse("2026-01-01T00:00:00Z");
127 let dataDir: string;
128 let app: App;
129 beforeEach(async () => {
130 dataDir = await mkdtemp(join(tmpdir(), "forge-domain-drill-"));
131 app = createApp({ dataDir, port: 0 });
132 seedFirstSeen(dataDir, t0);
133 });
134 afterEach(async () => {
135 await rm(dataDir, { recursive: true, force: true });
136 });
137 const person = async (name: string, adminIfFirst: boolean) => {
138 const made = await createUser(app.db, {
139 origin: "seed",
140 trusted: true,
141 username: name,
142 email: `${name}@forge.local`,
143 password: "a-good-passphrase",
144 adminIfFirst,
145 });
146 if (!made.ok) throw new Error(made.error);
147 return made.value;
148 };
149
150 test("an admin hears drill:never naming every command, once per need", async () => {
151 const admin = await person("alice", true);
152 const now = t0 + 9 * DAY;
153 const lines = domainDrillLines(app, admin, now, URL_);
154 expect(lines).toHaveLength(1);
155 expect(lines[0]!.id.startsWith("drill:never")).toBe(true);
156 for (const d of DOMAINS)
157 if (d.drill.name !== null) expect(lines[0]!.line).toContain(drillCommand(d.key, URL_));
158 // A repeat tick carries the same id: nothing new to send.
159 expect(domainDrillLines(app, admin, now + 60_000, URL_)[0]!.id).toBe(lines[0]!.id);
160 });
161
162 test("a later red is a new id", async () => {
163 const admin = await person("alice", true);
164 recordDrill(app.db, admin.id, "compute", { health: "", board: "" }, 1, { green: false, why: 'the forge never said "x"' });
165 const first = domainDrillLines(app, admin, t0 + DAY, URL_).find((l) => l.id.startsWith("drill:compute"));
166 expect(first).toBeDefined();
167 app.db.query("UPDATE domain_drill SET at = '2099-01-01T00:00:00.000Z'").run();
168 const next = domainDrillLines(app, admin, t0 + DAY, URL_).find((l) => l.id.startsWith("drill:compute"));
169 expect(next!.id).not.toBe(first!.id);
170 });
171
172 test("through the notifier: one post, none on a repeat tick, one on a later red", async () => {
173 const admin = await person("alice", true);
174 setNotifyUrl(app.db, admin.id, "https://ntfy.example.test/root-topic");
175 let clock = t0 + 7 * DAY;
176 const posts: string[] = [];
177 const notifier = startNotifier(app, {
178 forgeUrl: URL_,
179 now: () => clock,
180 drainingSince: () => null,
181 causes: () => [],
182 send: async (_u, body) => {
183 posts.push(body);
184 return true;
185 },
186 });
187 try {
188 await notifier.settled();
189 clock = t0 + 9 * DAY;
190 app.bus.append({ kind: "drill.finished", payload: {} });
191 await new Promise((r) => setTimeout(r, 20));
192 await notifier.settled();
193 const drills = () => posts.filter((p) => p.includes("scripts/drills/run.ts"));
194 expect(drills()).toHaveLength(1);
195 for (const d of DOMAINS)
196 if (d.drill.name !== null) expect(drills()[0]).toContain(drillCommand(d.key, URL_));
197 clock += MIN;
198 app.bus.append({ kind: "drill.finished", payload: {} });
199 await new Promise((r) => setTimeout(r, 20));
200 await notifier.settled();
201 expect(drills()).toHaveLength(1);
202 recordDrill(app.db, admin.id, "compute", { health: "", board: "" }, 1, { green: false, why: 'the forge never said "x"' });
203 clock += MIN;
204 app.bus.append({ kind: "drill.finished", payload: {} });
205 await new Promise((r) => setTimeout(r, 20));
206 await notifier.settled();
207 expect(drills()).toHaveLength(2);
208 expect(drills()[1]).toContain(drillCommand("compute", URL_));
209 } finally {
210 await notifier.close();
211 }
212 });
213
214 test("a non-admin hears nothing", async () => {
215 await person("alice", true);
216 const bob = await person("bob", false);
217 expect(domainDrillLines(app, bob, t0 + 9 * DAY, URL_)).toEqual([]);
218 });
219 });
test/release-journey.test.ts +11
@@ -166,6 +166,17 @@ test("an address that is not http(s) is refused before anything is sent", async
166166 expect(result).toMatchObject({ ok: false, forge: null, removed: true, failure: "the forge's address is not http or https" });
167167 });
168168
169 test("the walk sends the headers it was given to the forge itself, so the forge can tell its own prober from a stranger (#12071)", async () => {
170 const seen: Array<string | null> = [];
171 const fake = (async (_url: string, init?: RequestInit) => {
172 seen.push(new Headers(init?.headers).get("x-forge-probe"));
173 return new Response("no", { status: 500 });
174 }) as unknown as typeof fetch;
175 const result = await walkJourney({ base: "https://forge.test", fetch: fake, headers: { "x-forge-probe": "p" }, sleep: async () => {}, pollMs: 0 });
176 expect(result.ok).toBe(false);
177 expect(seen).toEqual(["p"]);
178 });
179
169180 test("a walk that blows up half-way (outside any step) still removes its forge", async () => {
170181 let calls = 0;
171182 const log: string[] = [];
test/spawn-anon.test.ts +21 −2
@@ -19,6 +19,7 @@ import { serve, type Servers } from "../src/http/server.ts";
1919 import { childDirOf } from "../src/actions/spawn.ts";
2020 import { bootHostedChild } from "../src/spawn/host.ts";
2121 import { ok } from "../src/kernel/result.ts";
22 import { probeHeaders } from "../src/kernel/probe.ts";
2223
2324 describe("anonymous spawn", () => {
2425 let dataDir: string;
@@ -93,7 +94,7 @@ describe("anonymous spawn", () => {
9394 afterAll(async () => {
9495 // Before the servers stop: stopping empties the child cache, and a
9596 // boot started after that would open a child nothing closes.
96 await settle("kid", "kid2", "kid3", "grown");
97 await settle("kid", "kid2", "kid3", "grown", "probe-b");
9798 servers.stop();
9899 app.close();
99100 await rm(dataDir, { recursive: true, force: true });
@@ -190,6 +191,24 @@ describe("anonymous spawn", () => {
190191 resetAnonSpawns(app.db);
191192 });
192193
194 test("the forge's own journey prober is neither limited nor counted (#12071)", async () => {
195 // Every stranger together has spent the day: the global cap is full.
196 for (let i = 0; i < ANON_SPAWNS_GLOBAL_PER_DAY; i++)
197 noteAnonSpawn(app.db, new Request(`http://x/${i}`, { headers: { "x-forwarded-for": `198.51.100.${i}` } }));
198 const refused = await post({ name: "probe-a", dryRun: false });
199 expect(refused.status).toBe(429);
200 const probing = await fetch(`${base}/api/v1/forges`, {
201 method: "POST",
202 headers: { "content-type": "application/json", ...probeHeaders(dataDir) },
203 body: JSON.stringify({ name: "probe-b", dryRun: false }),
204 });
205 expect(probing.status).toBe(201);
206 const counted = (app.db.query("SELECT COUNT(*) AS n FROM anon_spawn").get() as { n: number }).n;
207 expect(counted).toBe(ANON_SPAWNS_GLOBAL_PER_DAY);
208 resetAnonSpawns(app.db);
209 await settle("probe-b");
210 });
211
193212 test("the counts survive a restart and a global cap holds", async () => {
194213 const req = new Request("http://x/", { headers: { "x-forwarded-for": "203.0.113.9" } });
195214 for (let i = 0; i < ANON_SPAWNS_PER_DAY; i++) noteAnonSpawn(app.db, req);
@@ -224,6 +243,6 @@ describe("anonymous spawn", () => {
224243 } finally {
225244 child.close();
226245 }
227 expect(await readdir(join(dataDir, "children")).catch(() => [])).toHaveLength(4);
246 expect(await readdir(join(dataDir, "children")).catch(() => [])).toHaveLength(5);
228247 });
229248 });
test/vitals-domain-drill.test.ts +7 −6
@@ -68,7 +68,7 @@ test("a verdict that is not a quoted phrase is quoted whole, and bounded", () =>
6868 expect(n[0]!.sentence.length).toBeLessThan(400);
6969 });
7070
71 test("vitals raises them from the newest drill of each domain, in one query", async () => {
71 test("vitals raises none: no drill runs by itself, so a red drill is not a standing need (#12071)", async () => {
7272 const { vitals } = await import("../src/kernel/vitals.ts");
7373 const { newestDrills, recordDrill } = await import("../src/core/domain_drills.ts");
7474 const { createApp } = await import("../src/app.ts");
@@ -76,11 +76,12 @@ test("vitals raises them from the newest drill of each domain, in one query", as
7676 const app = createApp({ dataDir: dir, port: 0 });
7777 const seen = { health: "", board: "" };
7878 recordDrill(app.db, "u", "compute", seen, 1, { green: false, why: 'the forge never said "x"' });
79 const sentence = () =>
80 vitals({ db: app.db, signals: app.signals, dataDir: dir, forgeUrl: URL_ }).needs.find((s) => s.includes("compute drill"));
81 expect(sentence()).toContain(`bun scripts/drills/run.ts compute --forge ${URL_}`);
79 const said = () => {
80 const v = vitals({ db: app.db, signals: app.signals, dataDir: dir, forgeUrl: URL_ });
81 return [...v.broken, ...v.todo].find((s) => s.includes("drill"));
82 };
83 expect(said()).toBeUndefined();
8284 app.db.query("UPDATE domain_drill SET at = '2020-01-01T00:00:00.000Z'").run();
83 recordDrill(app.db, "u", "compute", seen, 1, { green: true, why: "ok" });
84 expect(sentence()).toBeUndefined();
85 expect(said()).toBeUndefined();
8586 expect(newestDrills(app.db).length).toBe(1);
8687 });
test/vitals-needs.ts added +4
@@ -0,0 +1,4 @@
1 import type { Vitals } from "../src/kernel/vitals.ts";
2
3 /** Every sentence a vitals reading holds, the broken ones first. */
4 export const allNeeds = (v: Vitals): string[] => [...v.broken, ...v.todo];
test/vitals-snapshots.test.ts +2 −1
@@ -4,6 +4,7 @@
44 * elsewhere or a mirror copies them off (#1148).
55 */
66
7 import { allNeeds } from "./vitals-needs.ts";
78 import { afterAll, beforeAll, expect, test } from "bun:test";
89 import { existsSync } from "node:fs";
910 import { mkdtemp, rm } from "node:fs/promises";
@@ -34,7 +35,7 @@ const flagged = (v: ReturnType<typeof read>) =>
3435
3536 test("a snapshot directory on the data volume, mirrored nowhere, is a need pointing at Backups", () => {
3637 const v = read({ dir: join(dataDir, "snapshots"), mirrored: false });
37 expect(v.needs).toContain(SNAPSHOTS_ON_STATE_VOLUME);
38 expect(allNeeds(v)).toContain(SNAPSHOTS_ON_STATE_VOLUME);
3839 expect(flagged(v)?.href).toBe("/settings/backups");
3940 });
4041
test/vitals.test.ts +21 −20
@@ -1,5 +1,6 @@
11 /** The forge's standing: its shape, the admin gate, and what it flags. */
22
3 import { allNeeds } from "./vitals-needs.ts";
34 import { laneSentence } from "../src/kernel/vitals.ts";
45 import { afterAll, beforeAll, expect, test } from "bun:test";
56 import { writeFileSync } from "node:fs";
@@ -94,9 +95,9 @@ test("a site admin with a read-only token gets the shape; others get the short o
9495 expect(Object.keys(v).sort()).toEqual(
9596 [
9697 "accessLog",
97 "apps", "at", "checkedAt", "commit", "degraded", "disk", "draining", "errors", "flakes",
98 "incidents", "lane", "memory", "needs", "ok", "queue", "rollout", "stale", "stuck",
99 "version",
98 "apps", "at", "broken", "checkedAt", "commit", "degraded", "disk", "draining", "errors", "flakes",
99 "incidents", "lane", "memory", "ok", "queue", "rollout", "stale", "stuck",
100 "todo", "version",
100101 ].sort(),
101102 );
102103 expect(v.disk.totalBytes).toBeGreaterThan(0);
@@ -127,10 +128,10 @@ test("a full queue shows in queue, and an old one in needs", async () => {
127128 const v = vitals({ db: app.db, signals: app.signals, dataDir, disk: roomy });
128129 expect(v.queue).toEqual({ agent: 3 });
129130 // Process-wide signals (errors, refused calls) from other suites may speak too.
130 expect(v.needs.join(" ")).not.toContain("queue");
131 expect(allNeeds(v).join(" ")).not.toContain("queue");
131132 const later = vitals({ db: app.db, signals: app.signals, dataDir, disk: roomy, now: old + 2 * 3_600_000 + 3_600_000 });
132 expect(later.ok).toBe(false);
133 expect(later.needs.join(" ")).toContain("agent queue");
133 expect(later.ok).toBe(true);
134 expect(allNeeds(later).join(" ")).toContain("agent queue");
134135 });
135136
136137 test("a running run with a lapsed lease is stuck, and needs says so", async () => {
@@ -143,8 +144,8 @@ test("a running run with a lapsed lease is stuck, and needs says so", async () =
143144 const v = (await (await health(admin)).json()) as ReturnType<typeof vitals>;
144145 expect(v.stuck.map((s) => s.runId)).toEqual([run.id]);
145146 expect(v.stuck[0]!.repo).toBe("alice/r");
146 expect(v.ok).toBe(false);
147 expect(v.needs.some((n) => n.includes("stuck"))).toBe(true);
147 expect(v.ok).toBe(true);
148 expect(allNeeds(v).some((n) => n.includes("stuck"))).toBe(true);
148149 // A fresh heartbeat clears it.
149150 app.db
150151 .query("UPDATE run SET heartbeat_at=?2 WHERE id=?1")
@@ -176,7 +177,7 @@ test("the number of queries does not grow with runs", () => {
176177 // red on a full disk only while the disk is full), and the newest drill of every domain, the
177178 // checks no red main holds, the week's flake list, and the database's daily size readings
178179 // (#12010, at most 60 rows).
179 expect(before).toBe(11);
180 expect(before).toBe(10);
180181 });
181182
182183 test("errors are counted, bounded, redacted, and a burst is said", async () => {
@@ -196,14 +197,14 @@ test("errors are counted, bounded, redacted, and a burst is said", async () => {
196197 const text = JSON.stringify(v);
197198 expect(text).toContain("[redacted]");
198199 expect(text).not.toContain("ghp_abcdefghijklmnop1234567890");
199 expect(v.needs.some((n) => n.includes("errors in the last hour"))).toBe(false);
200 expect(allNeeds(v).some((n) => n.includes("errors in the last hour"))).toBe(false);
200201
201202 for (let i = 0; i < ERROR_RING + 50; i++) log.error(`boom ${i}`);
202203 const seen = recentErrors(1000);
203204 expect(seen.latest.length).toBe(ERROR_RING);
204205 expect(seen.lastHour).toBe(ERROR_RING + 51);
205206 expect(seen.lastHour).toBeGreaterThanOrEqual(ERROR_BURST);
206 expect(vitals({ db: app.db, signals: app.signals, dataDir, disk: roomy }).needs.some((n) => n.includes("errors in the last hour"))).toBe(true);
207 expect(allNeeds(vitals({ db: app.db, signals: app.signals, dataDir, disk: roomy })).some((n) => n.includes("errors in the last hour"))).toBe(true);
207208 expect(vitals({ db: app.db, signals: app.signals, dataDir, disk: roomy, now: Date.now() + 2 * 3_600_000 }).errors.lastHour).toBe(0);
208209 } finally {
209210 console.error = orig;
@@ -247,7 +248,7 @@ test("the lane: depth, the running check and its age, the median of the last fin
247248 expect(body.lane.medianMinutes).toBe(20);
248249 // Waiting past thirty minutes names the cause, not only the symptom.
249250 const later = vitals({ db: app.db, signals: app.signals, dataDir, disk: roomy, now: now + 3_600_000 });
250 const cause = later.needs.find((n) => n.includes("one lane"));
251 const cause = allNeeds(later).find((n) => n.includes("one lane"));
251252 expect(cause).toMatch(/^6 checks wait behind one lane; the oldest since \d\d:\d\d; the lane runs nothing\.$/);
252253 expect(cause).not.toContain("Lane:");
253254 });
@@ -255,7 +256,7 @@ test("the lane: depth, the running check and its age, the median of the last fin
255256 test("an unauthenticated internal call is refused, logged and flagged; the probe is not", async () => {
256257 app.signals.refused.clear();
257258 const flagged = () =>
258 vitals({ db: app.db, signals: app.signals, dataDir: app.config.dataDir, disk: roomy }).needs.filter((n) =>
259 allNeeds(vitals({ db: app.db, signals: app.signals, dataDir: app.config.dataDir, disk: roomy })).filter((n) =>
259260 n.includes("internal call"),
260261 );
261262 const call = (path: string) =>
@@ -282,7 +283,7 @@ test("two forges in one process keep their own error and refusal signals", async
282283 const other = createApp({ dataDir: dirB, port: 0, disk: roomy });
283284 try {
284285 const needs = (a: App) =>
285 vitals({ db: a.db, dataDir: a.config.dataDir, signals: a.signals, disk: roomy }).needs;
286 allNeeds(vitals({ db: a.db, dataDir: a.config.dataDir, signals: a.signals, disk: roomy }));
286287 expect(needs(app)).toEqual([]);
287288 expect(needs(other)).toEqual([]);
288289 for (let i = 0; i < ERROR_BURST; i++) other.log.error("boom");
@@ -351,7 +352,7 @@ test("degraded names each cause, stable, with when it began", async () => {
351352 const entry = s.degraded.find((d) => d.cause === `stuck:${run.id}`);
352353 expect(entry?.since).toBe(moved);
353354 expect(entry?.href).toBe(`/alice/r/runs/${run.id}`);
354 expect(s.needs).toContain(entry!.sentence);
355 expect(allNeeds(s)).toContain(entry!.sentence);
355356 app.db.query("UPDATE run SET state='ok' WHERE id=?1").run(run.id);
356357
357358 // errors: no recorded start, so since is at; the cause is stable across calls.
@@ -388,7 +389,7 @@ test("degraded names each cause, stable, with when it began", async () => {
388389
389390 // every need has one matching sentence in degraded.
390391 const all = vitals({ db: app.db, signals: app.signals, dataDir, disk: roomy });
391 expect(new Set(all.degraded.map((d) => d.sentence))).toEqual(new Set(all.needs));
392 expect(new Set(all.degraded.map((d) => d.sentence))).toEqual(new Set(allNeeds(all)));
392393
393394 // the health API carries the same list.
394395 const h = (await (await health(admin)).json()) as { degraded: { cause: string }[] };
@@ -421,7 +422,7 @@ test("since is said as a person would", async () => {
421422 expect(sinceWords("2026-10-15T08:00:00Z", now)).toBe("4 h ago");
422423 expect(sinceWords("2026-10-15T11:59:50Z", now)).toBe("just now");
423424 expect(sinceWords("2020-01-01T00:00:00.000Z", now)).toBe("2020-01-01");
424 const line = needLine({ cause: "errors", sentence: "S.", since: "2020-01-01T00:00:00.000Z", href: "/x" }, now);
425 const line = needLine({ cause: "errors", tier: "todo", sentence: "S.", since: "2020-01-01T00:00:00.000Z", href: "/x" }, now);
425426 expect(line).toBe("S. Since 2020-01-01.");
426427 expect(line).not.toContain("T00:00");
427428 });
@@ -466,7 +467,7 @@ test("a lane older than its budget is degraded with its cause; a silent run is s
466467 expect(lane?.sentence).toMatch(
467468 /^3 checks wait behind one lane; the oldest since \d\d:\d\d; the lane runs a check for 31 min \(limit 60\)\.$/,
468469 );
469 expect(v.ok).toBe(false);
470 expect(v.ok).toBe(true);
470471 // Five minutes in, the oldest is under its budget: nothing to say.
471472 app.db.query("UPDATE run SET created_at=?1 WHERE state='queued'").run(iso(now - 5 * 60_000));
472473 expect(vitals({ db: app.db, signals: app.signals, dataDir, disk: roomy, now }).degraded.map((d) => d.cause)).toEqual([]);
@@ -481,8 +482,8 @@ test("only the disk need sees the disk: a 5% reading raises it, and nothing else
481482 const low = () => ({ freeBytes: 5, totalBytes: 100 });
482483 const v = vitals({ db: app.db, signals: app.signals, dataDir, disk: low });
483484 expect(v.degraded.map((d) => d.cause)).toEqual(["disk"]);
484 expect(v.needs).toEqual(["Disk is nearly full: 5% free."]);
485 expect(vitals({ db: app.db, signals: app.signals, dataDir, disk: roomy }).needs).toEqual([]);
485 expect(allNeeds(v)).toEqual(["Disk is nearly full: 5% free."]);
486 expect(allNeeds(vitals({ db: app.db, signals: app.signals, dataDir, disk: roomy }))).toEqual([]);
486487 });
487488
488489 test("laneSentence says one lane for one slot and names the slots in force for several", () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs