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

opened this

Merged 12h 18m ago, live in production

ledger-off-thread → main 0 commits

  • Merged. ledger-off-thread was merged into main as 7ce8163.

Review

Sign in to review this change.
4 files changed +67 −20
src/core/ledger.ts +17 −8
@@ -13,6 +13,7 @@ import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync
1313 import { join } from "node:path";
1414 import { type Compute, type Meter, takeCompute } from "./run_compute.ts";
1515 import type { Run } from "./runs.ts";
16 import type { LedgerJob } from "./ledger_worker.ts";
1617
1718 export const GENESIS = "0".repeat(64);
1819
@@ -338,15 +339,18 @@ function walk(
338339 let kept: Verdict | undefined;
339340
340341 /**
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.
344344 */
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> {
346350 const t0 = performance.now();
347351 let verdict: Verdict;
348352 try {
349 verdict = verifyDir(d);
353 verdict = await walkOff(d);
350354 } catch (error) {
351355 verdict = { ok: false, at: d, why: `could not be read: ${(error as Error).message}` };
352356 }
@@ -356,9 +360,14 @@ export function checkLedger(d: string, log: (line: string) => void = console.log
356360 return verdict;
357361 }
358362
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());
362371 }
363372
364373 /** 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(
10461046 }, undefined, app),
10471047 METER_EVERY_MS,
10481048 );
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));
10531052 const ledgerTimer = readOnly
10541053 ? undefined
10551054 : setInterval(() => during("ledger", walkLedger, undefined, app), 86_400_000);
test/ledger-health.test.ts +17 −8
@@ -18,7 +18,7 @@ beforeEach(() => {
1818 dir = join(mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "ledger-health-")), "ledger");
1919 mkdirSync(dir);
2020 });
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
2222
2323 function fixture(): string {
2424 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
4040 test("a clean chain adds no need", async () => {
4141 fixture();
4242 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 });
4444 expect(mentions(forgeNeeds(app, a))).toEqual([]);
4545 });
4646
@@ -49,7 +49,7 @@ test("a broken field at boot names the line and why, to the admin only, with no
4949 writeFileSync(file, readFileSync(file, "utf8").replace('"kind":"check"', '"kind":"merge"'));
5050 expect(verifyDir(dir).ok).toBe(false);
5151 const logged: string[] = [];
52 checkLedger(dir, (l) => logged.push(l));
52 await checkLedger(dir, (l) => logged.push(l));
5353 expect(logged[0]).toMatch(/verified in \d+ ms/);
5454 const { app, admin: a } = await admin();
5555 // 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
6161 expect(forgeNeeds(app, undefined)).toBeUndefined();
6262 });
6363
64 function broken(): void {
64 async function broken(): Promise<void> {
6565 const file = fixture();
6666 writeFileSync(file, readFileSync(file, "utf8").replace('"kind":"check"', '"kind":"merge"'));
67 checkLedger(dir, () => {});
67 await checkLedger(dir, () => {});
6868 rmSync(dir, { recursive: true }); // the answers below come from memory
6969 }
7070
7171 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();
7373 const { app } = await admin();
7474 const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
7575 if (!bob.ok) throw new Error(bob.error);
@@ -100,7 +100,7 @@ async function screenOf(app: Awaited<ReturnType<typeof admin>>["app"], user: Use
100100 }
101101
102102 test("the terminal's forge strip shows the need to an admin and not to a guest", async () => {
103 broken();
103 await broken();
104104 const { app, admin: a } = await admin();
105105 const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
106106 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",
113113 });
114114
115115 test("a broken chain is a broken need, not a todo: health is not ok (#12167)", async () => {
116 broken();
116 await broken();
117117 const { app, admin: a } = await admin();
118118 const { readHealth } = await import("../src/actions/health.ts");
119119 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
121121 expect(mentions(h.broken).length).toBe(1);
122122 expect(mentions(h.todo)).toEqual([]);
123123 });
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 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs