Public: anyone can read this; the crew can change it.
The cost ledger's chain is walked in a worker: a boot no longer holds the loop 0.5-1 s for it #17638
Merged 12h 18m ago, live in production
ledger-off-thread → main 0 commits
4 files
changed +67
−20
src/core/ledger.ts +17 −8
| @@ -13,6 +13,7 @@ import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync | ||
| 13 | 13 | import { join } from "node:path"; |
| 14 | 14 | import { type Compute, type Meter, takeCompute } from "./run_compute.ts"; |
| 15 | 15 | import type { Run } from "./runs.ts"; |
| 16 | import type { LedgerJob } from "./ledger_worker.ts"; | |
| 16 | 17 | |
| 17 | 18 | export const GENESIS = "0".repeat(64); |
| 18 | 19 | |
| @@ -338,15 +339,18 @@ function walk( | ||
| 338 | 339 | let kept: Verdict | undefined; |
| 339 | 340 | |
| 340 | 341 | /** |
| 341 | * Walk the chain and keep the verdict in memory, logging how long the walk | |
| 342 | * took (a big ledger makes it slow, so it is never run on a request). Boot | |
| 343 | * and a daily timer call this; health only reads `keptVerdict`. | |
| 342 | * Walk the chain in a worker (`ledger_worker.ts`) and keep the verdict on this thread, where health | |
| 343 | * reads it; log one line with what the walk found and how long it took. `walkOff` is the test seam. | |
| 344 | 344 | */ |
| 345 | export function checkLedger(d: string, log: (line: string) => void = console.log): Verdict { | |
| 345 | export async function checkLedger( | |
| 346 | d: string, | |
| 347 | log: (line: string) => void = console.log, | |
| 348 | walkOff: (d: string) => Promise<Verdict> = walkInWorker, | |
| 349 | ): Promise<Verdict> { | |
| 346 | 350 | const t0 = performance.now(); |
| 347 | 351 | let verdict: Verdict; |
| 348 | 352 | try { |
| 349 | verdict = verifyDir(d); | |
| 353 | verdict = await walkOff(d); | |
| 350 | 354 | } catch (error) { |
| 351 | 355 | verdict = { ok: false, at: d, why: `could not be read: ${(error as Error).message}` }; |
| 352 | 356 | } |
| @@ -356,9 +360,14 @@ export function checkLedger(d: string, log: (line: string) => void = console.log | ||
| 356 | 360 | return verdict; |
| 357 | 361 | } |
| 358 | 362 | |
| 359 | /** The last verdict `checkLedger` kept; undefined until the first walk. No file is read. */ | |
| 360 | export function keptVerdict(): Verdict | undefined { | |
| 361 | return kept; | |
| 363 | /** `verifyDir` in a worker of its own, ended when it answers. */ | |
| 364 | function walkInWorker(d: string): Promise<Verdict> { | |
| 365 | const worker = new Worker(new URL("./ledger_worker.ts", import.meta.url).href); | |
| 366 | return new Promise<Verdict>((resolve, reject) => { | |
| 367 | worker.onmessage = (e: MessageEvent<Verdict>) => resolve(e.data); | |
| 368 | worker.onerror = (e) => reject(new Error(e.message)); | |
| 369 | worker.postMessage({ dir: d } satisfies LedgerJob); | |
| 370 | }).finally(() => worker.terminate()); | |
| 362 | 371 | } |
| 363 | 372 | |
| 364 | 373 | /** The kept verdict as one plain sentence when the chain is broken; null otherwise. */ |
src/core/ledger_worker.ts added +30
| @@ -0,0 +1,30 @@ | ||
| 1 | /** | |
| 2 | * The cost ledger's chain walked off the serving thread (`checkLedger`). The walk reads every month | |
| 3 | * file and hashes every entry: on production, 58,000 entries and 22 MB, it held the loop 507-979 ms | |
| 4 | * at every boot, and boots come every half hour. | |
| 5 | */ | |
| 6 | ||
| 7 | import { verifyDir, type Verdict } from "./ledger.ts"; | |
| 8 | ||
| 9 | /** What the worker is asked: the ledger directory to walk. */ | |
| 10 | export interface LedgerJob { | |
| 11 | readonly dir: string; | |
| 12 | } | |
| 13 | ||
| 14 | declare const self: Worker; | |
| 15 | ||
| 16 | /** | |
| 17 | * The worker's side only: imported on the main thread, this module defines the job and does | |
| 18 | * nothing. | |
| 19 | */ | |
| 20 | if (!Bun.isMainThread) { | |
| 21 | self.onmessage = (e: MessageEvent<LedgerJob>) => { | |
| 22 | let verdict: Verdict; | |
| 23 | try { | |
| 24 | verdict = verifyDir(e.data.dir); | |
| 25 | } catch (error) { | |
| 26 | verdict = { ok: false, at: e.data.dir, why: `could not be read: ${(error as Error).message}` }; | |
| 27 | } | |
| 28 | postMessage(verdict); | |
| 29 | }; | |
| 30 | } |
src/main.ts +3 −4
| @@ -1046,10 +1046,9 @@ const meterTimer = setInterval( | ||
| 1046 | 1046 | }, undefined, app), |
| 1047 | 1047 | METER_EVERY_MS, |
| 1048 | 1048 | ); |
| 1049 | // The cost ledger's chain is walked at boot and once a day (#12273), on this thread: | |
| 1050 | // health reads the verdict from this thread's memory. | |
| 1051 | const walkLedger = (): void => | |
| 1052 | void checkLedger(join(dataDir, "ledger"), (line) => app.log.info(line)); | |
| 1049 | // The cost ledger's chain is walked at boot and once a day (#12273), in a worker: on this thread it | |
| 1050 | // held the loop up to a second at every boot (#17629). Health reads the verdict this thread keeps. | |
| 1051 | const walkLedger = (): Promise<unknown> => checkLedger(join(dataDir, "ledger"), (line) => app.log.info(line)); | |
| 1053 | 1052 | const ledgerTimer = readOnly |
| 1054 | 1053 | ? undefined |
| 1055 | 1054 | : setInterval(() => during("ledger", walkLedger, undefined, app), 86_400_000); |
test/ledger-health.test.ts +17 −8
| @@ -18,7 +18,7 @@ beforeEach(() => { | ||
| 18 | 18 | dir = join(mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "ledger-health-")), "ledger"); |
| 19 | 19 | mkdirSync(dir); |
| 20 | 20 | }); |
| 21 | afterEach(() => void checkLedger(dir, () => {})); // an empty chain is ok: the next test starts with no broken verdict | |
| 21 | afterEach(async () => void (await checkLedger(dir, () => {}))); // an empty chain is ok: the next test starts with no broken verdict | |
| 22 | 22 | |
| 23 | 23 | function fixture(): string { |
| 24 | 24 | const run = (id: string): Run => ({ id, kind: "check", repoId: "r", env: "pull-1", issueId: null, startedAt: null, finishedAt: "2026-11-01T00:00:00.000Z", costUsd: 1 }) as unknown as Run; |
| @@ -40,7 +40,7 @@ const mentions = (needs: string[] | undefined): string[] => (needs ?? []).filter | ||
| 40 | 40 | test("a clean chain adds no need", async () => { |
| 41 | 41 | fixture(); |
| 42 | 42 | const { app, admin: a } = await admin(); |
| 43 | expect(checkLedger(dir, () => {})).toEqual({ ok: true, entries: 2 }); | |
| 43 | expect(await checkLedger(dir, () => {})).toEqual({ ok: true, entries: 2 }); | |
| 44 | 44 | expect(mentions(forgeNeeds(app, a))).toEqual([]); |
| 45 | 45 | }); |
| 46 | 46 | |
| @@ -49,7 +49,7 @@ test("a broken field at boot names the line and why, to the admin only, with no | ||
| 49 | 49 | writeFileSync(file, readFileSync(file, "utf8").replace('"kind":"check"', '"kind":"merge"')); |
| 50 | 50 | expect(verifyDir(dir).ok).toBe(false); |
| 51 | 51 | const logged: string[] = []; |
| 52 | checkLedger(dir, (l) => logged.push(l)); | |
| 52 | await checkLedger(dir, (l) => logged.push(l)); | |
| 53 | 53 | expect(logged[0]).toMatch(/verified in \d+ ms/); |
| 54 | 54 | const { app, admin: a } = await admin(); |
| 55 | 55 | // The files are gone: health answers from the kept verdict, not the disk. |
| @@ -61,15 +61,15 @@ test("a broken field at boot names the line and why, to the admin only, with no | ||
| 61 | 61 | expect(forgeNeeds(app, undefined)).toBeUndefined(); |
| 62 | 62 | }); |
| 63 | 63 | |
| 64 | function broken(): void { | |
| 64 | async function broken(): Promise<void> { | |
| 65 | 65 | const file = fixture(); |
| 66 | 66 | writeFileSync(file, readFileSync(file, "utf8").replace('"kind":"check"', '"kind":"merge"')); |
| 67 | checkLedger(dir, () => {}); | |
| 67 | await checkLedger(dir, () => {}); | |
| 68 | 68 | rmSync(dir, { recursive: true }); // the answers below come from memory |
| 69 | 69 | } |
| 70 | 70 | |
| 71 | 71 | test("GET /api/v1/health carries the need for an admin, and not for a guest or a stranger", async () => { |
| 72 | broken(); | |
| 72 | await broken(); | |
| 73 | 73 | const { app } = await admin(); |
| 74 | 74 | const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); |
| 75 | 75 | if (!bob.ok) throw new Error(bob.error); |
| @@ -100,7 +100,7 @@ async function screenOf(app: Awaited<ReturnType<typeof admin>>["app"], user: Use | ||
| 100 | 100 | } |
| 101 | 101 | |
| 102 | 102 | test("the terminal's forge strip shows the need to an admin and not to a guest", async () => { |
| 103 | broken(); | |
| 103 | await broken(); | |
| 104 | 104 | const { app, admin: a } = await admin(); |
| 105 | 105 | const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); |
| 106 | 106 | if (!bob.ok) throw new Error(bob.error); |
| @@ -113,7 +113,7 @@ test("the terminal's forge strip shows the need to an admin and not to a guest", | ||
| 113 | 113 | }); |
| 114 | 114 | |
| 115 | 115 | test("a broken chain is a broken need, not a todo: health is not ok (#12167)", async () => { |
| 116 | broken(); | |
| 116 | await broken(); | |
| 117 | 117 | const { app, admin: a } = await admin(); |
| 118 | 118 | const { readHealth } = await import("../src/actions/health.ts"); |
| 119 | 119 | const h = readHealth(app, a) as { ok: boolean; broken: string[]; todo: string[] }; |
| @@ -121,3 +121,12 @@ test("a broken chain is a broken need, not a todo: health is not ok (#12167)", a | ||
| 121 | 121 | expect(mentions(h.broken).length).toBe(1); |
| 122 | 122 | expect(mentions(h.todo)).toEqual([]); |
| 123 | 123 | }); |
| 124 | ||
| 125 | test("the walk is a worker's, and its verdict is the chain's own, clean or broken (#17629)", async () => { | |
| 126 | const file = fixture(); | |
| 127 | expect(await checkLedger(dir, () => {})).toEqual(verifyDir(dir)); | |
| 128 | writeFileSync(file, readFileSync(file, "utf8").replace('"usd_tokens":1', '"usd_tokens":2')); | |
| 129 | const broken = await checkLedger(dir, () => {}); | |
| 130 | expect(broken.ok).toBe(false); | |
| 131 | expect(broken).toEqual(verifyDir(dir)); | |
| 132 | }); |
new above
offline