Public: anyone can read this; the crew can change it.
Cost ledger: measure compute for deploys and agent runs, not only checks #16841
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/1388-cost-ledger-measure-compute-for-deploys → main 0 commits fork
10 files
changed +265
−7
docs/features/cost-ledger.md +2 −1
| @@ -8,9 +8,10 @@ Every run that ends (`finishRun`, and `cancelRun`: agent, check, deploy) appends | ||
| 8 | 8 | |
| 9 | 9 | ## An entry |
| 10 | 10 | |
| 11 | `{run, kind, repo, issue, pull, startedAt, endedAt, wall_s, tokens_in, tokens_out, usd_tokens, prev, hash}` | |
| 11 | `{run, kind, repo, issue, pull, startedAt, endedAt, wall_s, tokens_in, tokens_out, usd_tokens, cpu_s, mem_gib_s, prev, hash}` | |
| 12 | 12 | |
| 13 | 13 | - `issue`, `pull`, `startedAt`, `wall_s`, `tokens_in`, `tokens_out`, `usd_tokens` appear only when the run knows them: absent, never zero. Today `tokens_*` are always absent (runs record dollars, not tokens); `usd_tokens` is the run's `costUsd` when above zero. |
| 14 | - `cpu_s` and `mem_gib_s` (#1388) are the compute of an agent run, a deploy and a check: CPU seconds (user plus system) of the run's cell, and resident GiB held times seconds, read from the cell watch every 5 s (`src/core/run_compute.ts`, one meter per forge database). A run is measured under its cell's label (`crew:<agent>`, `app:<slug>/<env>`, `check:<run>`). A label names a cell, not a run, so the figures are absent when a cell was already under the label as the run began (a deploy of an app that is serving) or another measured run shared the label at any moment (two runs of one agent): an entry cannot be corrected, and a sum known to be double is not written. Absent too when no cell was read (a run cancelled while queued, a host without the watch), never zero. A run that never finished is dropped from the meter after 24 hours; a restart empties it. | |
| 14 | 15 | - `hash` is sha256 (hex) of the entry's canonical JSON (keys sorted) without `hash`. |
| 15 | 16 | - `prev` is the previous entry's hash, across months; the first entry's is 64 zeros. |
| 16 | 17 |
src/apps/runtime_deploy.ts +2
| @@ -20,6 +20,7 @@ import { announceRun } from "../actions/runs.ts"; | ||
| 20 | 20 | import { getPull } from "../core/pulls.ts"; |
| 21 | 21 | import { getRepoById, type Repo } from "../core/repos.ts"; |
| 22 | 22 | import { runningLimitSentence } from "../settings/quotas.ts"; |
| 23 | import { meterOf, trackCompute } from "../core/run_compute.ts"; | |
| 23 | 24 | import { cancelRun, claimRun, finishRun, markServing, STOPPED_SUMMARY, type Run } from "../core/runs.ts"; |
| 24 | 25 | import { resolveOid } from "../git/merge.ts"; |
| 25 | 26 | import { repoDir } from "../git/repos.ts"; |
| @@ -188,6 +189,7 @@ export async function execute( | ||
| 188 | 189 | const claimed = claimRun(rt.app.db, run.id); |
| 189 | 190 | if (!claimed) return; // cancelled meanwhile |
| 190 | 191 | const lease = holdLease(rt.app.db, run.id); |
| 192 | trackCompute(meterOf(rt.app.db), run.id, `app:${state.app.slug}/${state.env}`); | |
| 191 | 193 | const abort = new AbortController(); |
| 192 | 194 | state.deploying = { run: claimed, abort }; |
| 193 | 195 | state.lastRunId = run.id; |
src/checks/execute.ts +2
| @@ -4,6 +4,7 @@ import { announceRun } from "../actions/runs.ts"; | ||
| 4 | 4 | import { announceShard } from "./shard_event.ts"; |
| 5 | 5 | import { issueMayRun } from "../core/pull_trust.ts"; |
| 6 | 6 | import type { Repo } from "../core/repos.ts"; |
| 7 | import { meterOf, trackCompute } from "../core/run_compute.ts"; | |
| 7 | 8 | import { cancelRun, getRun, claimRun, finishRun, overranBefore, vanishedBefore, VANISHED_SUMMARY, infraBefore, INFRA_SUMMARY, stalledBefore, STALLED_SUMMARY, CPU_STOP_SUMMARY, DISK_USED_SUMMARY, requeueCheck, chainCutOffs, CHECK_RELEASE_LIMIT, RELEASE_SUMMARY, type Run } from "../core/runs.ts"; |
| 8 | 9 | import { withDisk } from "./disk_red.ts"; |
| 9 | 10 | import { proposeRevert } from "./revert_red.ts"; |
| @@ -50,6 +51,7 @@ export async function execute( | ||
| 50 | 51 | const claimed = claimRun(app.db, run.id); |
| 51 | 52 | if (!claimed) return; |
| 52 | 53 | const lease = holdLease(app.db, run.id); |
| 54 | trackCompute(meterOf(app.db), run.id, `check:${run.id}`); | |
| 53 | 55 | announceRun(app, claimed); |
| 54 | 56 | let wrote = false; |
| 55 | 57 | const write = (line: string): void => { |
src/core/ledger.ts +10 −3
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | import { createHash } from "node:crypto"; |
| 12 | 12 | import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs"; |
| 13 | 13 | import { join } from "node:path"; |
| 14 | import { type Compute, type Meter, takeCompute } from "./run_compute.ts"; | |
| 14 | 15 | import type { Run } from "./runs.ts"; |
| 15 | 16 | |
| 16 | 17 | export const GENESIS = "0".repeat(64); |
| @@ -30,6 +31,10 @@ export interface LedgerEntry { | ||
| 30 | 31 | readonly tokens_in?: number; |
| 31 | 32 | readonly tokens_out?: number; |
| 32 | 33 | readonly usd_tokens?: number; |
| 34 | /** CPU seconds the run's processes used; absent when not measured. */ | |
| 35 | readonly cpu_s?: number; | |
| 36 | /** GiB of resident memory held, times seconds; absent when not measured. */ | |
| 37 | readonly mem_gib_s?: number; | |
| 33 | 38 | readonly prev: string; |
| 34 | 39 | readonly hash: string; |
| 35 | 40 | } |
| @@ -55,7 +60,7 @@ export function hashOf(body: EntryBody): string { | ||
| 55 | 60 | } |
| 56 | 61 | |
| 57 | 62 | /** The entry a finished run makes: only what the run knows. */ |
| 58 | export function entryOf(run: Run, prev: string): LedgerEntry { | |
| 63 | export function entryOf(run: Run, prev: string, compute?: Compute): LedgerEntry { | |
| 59 | 64 | const endedAt = run.finishedAt ?? new Date().toISOString(); |
| 60 | 65 | const pull = /^pull-(\d+)$/.exec(run.env)?.[1]; |
| 61 | 66 | const wall = |
| @@ -72,6 +77,7 @@ export function entryOf(run: Run, prev: string): LedgerEntry { | ||
| 72 | 77 | ...(run.tokensIn != null ? { tokens_in: run.tokensIn } : {}), |
| 73 | 78 | ...(run.tokensOut != null ? { tokens_out: run.tokensOut } : {}), |
| 74 | 79 | ...(run.costUsd > 0 ? { usd_tokens: run.costUsd } : {}), |
| 80 | ...(compute !== undefined ? { cpu_s: compute.cpu_s, mem_gib_s: compute.mem_gib_s } : {}), | |
| 75 | 81 | prev, |
| 76 | 82 | }; |
| 77 | 83 | return { ...body, hash: hashOf(body) }; |
| @@ -185,8 +191,9 @@ function appendBody(make: (prev: string) => LedgerEntry, what: string): void { | ||
| 185 | 191 | } |
| 186 | 192 | |
| 187 | 193 | /** Append the entry for a finished run. Never throws. */ |
| 188 | export function appendRun(run: Run): void { | |
| 189 | appendBody((prev) => entryOf(run, prev), `run ${run.id}`); | |
| 194 | export function appendRun(run: Run, meter?: Meter): void { | |
| 195 | const compute = meter === undefined ? undefined : takeCompute(meter, run.id); | |
| 196 | appendBody((prev) => entryOf(run, prev, compute), `run ${run.id}`); | |
| 190 | 197 | } |
| 191 | 198 | |
| 192 | 199 | /** A snapshot that ended: when it began and ended, and whether it failed. */ |
src/core/run_compute.ts added +121
| @@ -0,0 +1,121 @@ | ||
| 1 | /** | |
| 2 | * What a run's processes used: CPU seconds and memory seconds (GiB·s), kept in memory while the | |
| 3 | * run is under way and written once, on its ledger entry (`core/ledger.ts`). Plain data in: the | |
| 4 | * watch's readings (`CellCounter`), so this file knows nothing of cells. | |
| 5 | * | |
| 6 | * A run is tracked under the label its cell is watched as (`crew:<agent>`, `app:<slug>/<env>`, | |
| 7 | * `check:<run>`). A label names a cell, not a run, so a figure is written only when the label was | |
| 8 | * the run's alone: a cell already under the label when tracking starts (an app's serving cell), | |
| 9 | * or another tracked run on the same label at any moment, makes the figures ambiguous and the | |
| 10 | * run has none. An entry in a hash chain cannot be corrected, so absent beats a sum known to be | |
| 11 | * double. Memory is the resident bytes held over each interval between readings. A run never | |
| 12 | * tracked, never read or ambiguous has no figures: absent, never zero. | |
| 13 | * | |
| 14 | * The meter belongs to a forge: `meterOf(app.db)`. A run that never finishes (a crash between | |
| 15 | * track and finish) is dropped by `sampleCompute` once it is `STALE_MS` old; a restarted process | |
| 16 | * starts with an empty meter. | |
| 17 | */ | |
| 18 | ||
| 19 | import type { Database } from "bun:sqlite"; | |
| 20 | ||
| 21 | ||
| 22 | /** One reading of a labelled cell, the shape of the watch's `CellCounter`. */ | |
| 23 | export interface Reading { | |
| 24 | readonly key: number; | |
| 25 | readonly label: string; | |
| 26 | readonly cpuUsec: number; | |
| 27 | readonly memoryBytes: number; | |
| 28 | } | |
| 29 | ||
| 30 | export interface Compute { | |
| 31 | /** CPU seconds, user plus system, rounded to milliseconds. */ | |
| 32 | readonly cpu_s: number; | |
| 33 | /** Resident GiB held, times seconds, rounded to thousandths. */ | |
| 34 | readonly mem_gib_s: number; | |
| 35 | } | |
| 36 | ||
| 37 | interface Track { | |
| 38 | readonly label: string; | |
| 39 | readonly startedAt: number; | |
| 40 | /** Last CPU µs seen per watched tree. */ | |
| 41 | readonly last: Map<number, number>; | |
| 42 | cpuUsec: number; | |
| 43 | byteMs: number; | |
| 44 | at: number; | |
| 45 | seen: boolean; | |
| 46 | /** The label was not the run's alone: no figures. */ | |
| 47 | shared: boolean; | |
| 48 | } | |
| 49 | ||
| 50 | /** A track older than this belongs to a run that never finished. */ | |
| 51 | export const STALE_MS = 24 * 3_600_000; | |
| 52 | ||
| 53 | /** One forge's meter: the runs being measured and where readings come from. */ | |
| 54 | export class Meter { | |
| 55 | readonly tracks = new Map<string, Track>(); | |
| 56 | read: (() => readonly Reading[]) | undefined; | |
| 57 | } | |
| 58 | ||
| 59 | const meters = new WeakMap<Database, Meter>(); | |
| 60 | ||
| 61 | /** The meter of the forge whose database this is. */ | |
| 62 | export function meterOf(db: Database): Meter { | |
| 63 | let m = meters.get(db); | |
| 64 | if (m === undefined) meters.set(db, (m = new Meter())); | |
| 65 | return m; | |
| 66 | } | |
| 67 | ||
| 68 | /** Begin measuring `runId` under `label`. A second call for the same run changes nothing. */ | |
| 69 | export function trackCompute(meter: Meter, runId: string, label: string, now = Date.now(), readings = meter.read?.() ?? []): void { | |
| 70 | if (meter.tracks.has(runId)) return; | |
| 71 | const last = new Map<number, number>(); | |
| 72 | for (const r of readings) if (r.label === label) last.set(r.key, r.cpuUsec); | |
| 73 | const track: Track = { label, startedAt: now, last, cpuUsec: 0, byteMs: 0, at: now, seen: false, shared: last.size > 0 }; | |
| 74 | for (const other of meter.tracks.values()) { | |
| 75 | if (other.label !== label) continue; | |
| 76 | other.shared = true; | |
| 77 | track.shared = true; | |
| 78 | } | |
| 79 | meter.tracks.set(runId, track); | |
| 80 | } | |
| 81 | ||
| 82 | /** Fold one set of readings into every tracked run. */ | |
| 83 | export function sampleCompute(meter: Meter, readings: readonly Reading[] = meter.read?.() ?? [], now = Date.now()): void { | |
| 84 | for (const [id, t] of meter.tracks) { | |
| 85 | if (now - t.startedAt > STALE_MS) { | |
| 86 | meter.tracks.delete(id); | |
| 87 | continue; | |
| 88 | } | |
| 89 | let bytes = 0; | |
| 90 | let any = false; | |
| 91 | for (const r of readings) { | |
| 92 | if (r.label !== t.label) continue; | |
| 93 | any = true; | |
| 94 | bytes += r.memoryBytes; | |
| 95 | const before = t.last.get(r.key) ?? 0; | |
| 96 | t.cpuUsec += Math.max(0, r.cpuUsec - before); | |
| 97 | t.last.set(r.key, Math.max(before, r.cpuUsec)); | |
| 98 | } | |
| 99 | if (any) { | |
| 100 | t.seen = true; | |
| 101 | t.byteMs += bytes * Math.max(0, now - t.at); | |
| 102 | } | |
| 103 | t.at = now; | |
| 104 | } | |
| 105 | } | |
| 106 | ||
| 107 | /** | |
| 108 | * Stop measuring `runId` and answer what it used; undefined when nothing was read or the label was | |
| 109 | * shared. | |
| 110 | */ | |
| 111 | export function takeCompute(meter: Meter, runId: string, now = Date.now()): Compute | undefined { | |
| 112 | const t = meter.tracks.get(runId); | |
| 113 | if (t === undefined) return undefined; | |
| 114 | if (meter.read !== undefined) sampleCompute(meter, meter.read(), now); | |
| 115 | meter.tracks.delete(runId); | |
| 116 | if (!t.seen || t.shared) return undefined; | |
| 117 | return { | |
| 118 | cpu_s: Math.round(t.cpuUsec / 1000) / 1000, | |
| 119 | mem_gib_s: Math.round((t.byteMs / 1000 / 2 ** 30) * 1000) / 1000, | |
| 120 | }; | |
| 121 | } |
src/core/runs.ts +3 −2
| @@ -13,6 +13,7 @@ import { hostname } from "node:os"; | ||
| 13 | 13 | import { BUDGET_PREFIX } from "../kernel/budgets.ts"; |
| 14 | 14 | import { id } from "../kernel/id.ts"; |
| 15 | 15 | import { appendRun } from "./ledger.ts"; |
| 16 | import { meterOf } from "./run_compute.ts"; | |
| 16 | 17 | |
| 17 | 18 | export type RunKind = "deploy" | "agent" | "check"; |
| 18 | 19 | |
| @@ -402,7 +403,7 @@ export function finishRun( | ||
| 402 | 403 | knownTokens(outcome.tokensOut), |
| 403 | 404 | ).changes; |
| 404 | 405 | const done = changes > 0 ? getRun(db, runId) : undefined; |
| 405 | if (done !== undefined) appendRun(done); | |
| 406 | if (done !== undefined) appendRun(done, meterOf(db)); | |
| 406 | 407 | return done; |
| 407 | 408 | } |
| 408 | 409 | |
| @@ -455,7 +456,7 @@ export function cancelRun( | ||
| 455 | 456 | ) |
| 456 | 457 | .run(runId, summary).changes; |
| 457 | 458 | const done = changes > 0 ? getRun(db, runId) : undefined; |
| 458 | if (done !== undefined) appendRun(done); | |
| 459 | if (done !== undefined) appendRun(done, meterOf(db)); | |
| 459 | 460 | return done; |
| 460 | 461 | } |
| 461 | 462 |
src/crew/run_prepare.ts +3
| @@ -10,6 +10,7 @@ import { capacityEnv } from "../core/capacity.ts"; | ||
| 10 | 10 | import type { Issue } from "../core/issues.ts"; |
| 11 | 11 | import { forgetMeasure, noteMeasure } from "../core/measure.ts"; |
| 12 | 12 | import type { Repo } from "../core/repos.ts"; |
| 13 | import { meterOf, trackCompute } from "../core/run_compute.ts"; | |
| 13 | 14 | import { noteRunProgress, type Run } from "../core/runs.ts"; |
| 14 | 15 | import { PLATFORM, type Pick } from "../core/subscriptions.ts"; |
| 15 | 16 | import { redactValues } from "../kernel/log.ts"; |
| @@ -228,6 +229,8 @@ export async function prepareAgent(s: PrepareState): Promise<Prepared> { | ||
| 228 | 229 | budgetUsd: number, |
| 229 | 230 | resume: string | undefined, |
| 230 | 231 | ): Promise<AgentOutcome> => { |
| 232 | // Idempotent: the first invocation starts the run's compute meter (#1388). | |
| 233 | trackCompute(meterOf(app.db), run.id, `crew:${agent.user.username}`); | |
| 231 | 234 | const spent = redactResult( |
| 232 | 235 | await runAgent({ |
| 233 | 236 | binary: options.binary, |
src/main.ts +6 −1
| @@ -14,6 +14,7 @@ import { statusTick } from "./core/status_days.ts"; | ||
| 14 | 14 | import { scanNightly } from "./checks/scan.ts"; |
| 15 | 15 | import { nightlyDue } from "./checks/scan_store.ts"; |
| 16 | 16 | import { checkLedger, setLedgerDir } from "./core/ledger.ts"; |
| 17 | import { meterOf, sampleCompute } from "./core/run_compute.ts"; | |
| 17 | 18 | import { BATCH_EVERY_MS, ledgerGitTick } from "./core/ledger_git.ts"; |
| 18 | 19 | import { getRepoById } from "./core/repos.ts"; |
| 19 | 20 | import { BOOT_ACTOR, setSignup, signupFromEnv } from "./settings/signup.ts"; |
| @@ -143,7 +144,7 @@ import { limitValue } from "./settings/limits.ts"; | ||
| 143 | 144 | import { migrateSsh, sshOn } from "./settings/ssh.ts"; |
| 144 | 145 | import { followSsh } from "./ssh/switch.ts"; |
| 145 | 146 | import { capacityDefault, egressEnvIgnored } from "./core/capacity.ts"; |
| 146 | import { keepServingCoresFrom } from "./apps/contain.ts"; | |
| 147 | import { cellCounters, keepServingCoresFrom } from "./apps/contain.ts"; | |
| 147 | 148 | import { bootCounts, recordBoot, recordCleanExit } from "./kernel/boots.ts"; |
| 148 | 149 | import { census, censusWords, processRows } from "./kernel/census.ts"; |
| 149 | 150 | import { reapLeftoverBridges } from "./crew/leftovers.ts"; |
| @@ -983,6 +984,9 @@ void during("entitlements", () => sweepEntitlements(app), undefined, app); | ||
| 983 | 984 | // While the crew waits on a full window, the provider's meter is read every 15 minutes, so an early |
| 984 | 985 | // reset resumes it with nobody touching it (#14254). |
| 985 | 986 | const watchMeter = newMeterWatch(); |
| 987 | // What each run's cell used, read every few seconds and written on its ledger entry (#1388). | |
| 988 | meterOf(app.db).read = cellCounters; | |
| 989 | const computeTimer = setInterval(() => during("run-compute", () => sampleCompute(meterOf(app.db)), undefined, app), 5_000); | |
| 986 | 990 | const meterTimer = setInterval( |
| 987 | 991 | () => void during("meter-watch", async () => { |
| 988 | 992 | for (const line of await watchMeter(app.db, app.config.dataDir)) app.log.info(line); |
| @@ -1241,6 +1245,7 @@ function drain(signal: NodeJS.Signals): Promise<unknown> { | ||
| 1241 | 1245 | clearInterval(entitlementTimer); |
| 1242 | 1246 | if (allocationTimer !== undefined) clearInterval(allocationTimer); |
| 1243 | 1247 | clearInterval(meterTimer); |
| 1248 | clearInterval(computeTimer); | |
| 1244 | 1249 | if (ledgerTimer !== undefined) clearInterval(ledgerTimer); |
| 1245 | 1250 | clearInterval(followTimer); |
| 1246 | 1251 | landingsWatch(); |
test/job-slices.test.ts +1
| @@ -275,6 +275,7 @@ const UNTIMED: Record<string, string> = { | ||
| 275 | 275 | "git-pace": "a one-shot timer in git/pace.ts that only resolves the promise a paced pack write waits on: no work of its own, armed per pack chunk while a page response is in flight; git-pace.test.ts drives the pacer with a fake clock", |
| 276 | 276 | "dataset-export": "every 10 minutes reads the last export's time and returns unless a night has passed; the publish itself runs once a night in actions/dataset.ts publishDataset and is off without a dataset repository; dataset tests drive publishDataset directly", |
| 277 | 277 | "drill-watch": "a /proc read of the drill child's memory and a state write every WATCH_MS, only while a restore drill runs in its own process; drill-job tests drive runDrillInChild directly", |
| 278 | "run-compute": "reads the watch's counters every 5 s and adds them to the few runs in flight (core/run_compute.ts sampleCompute): memory only, no query or write; run-compute.test.ts drives sampleCompute", | |
| 278 | 279 | "meter-watch": "one indexed read of held-full windows every 15 minutes, and a status fetch only while one is held full; meter-watch.test.ts drives it with a fake fetcher; the fixture holds no window", |
| 279 | 280 | "talk-live": "a one-shot timer in talkStream (web/pages/talk.ts), armed only while a person has /talk open and a reply is being written: it sends that one stream its latest live frame, at most one per 125 ms, drawing a block of at most 20,000 characters; talk-live.test.ts drives the stream and counts its frames", |
| 280 | 281 | "boards-stream": "a one-shot timer in boards/live_hub.ts, armed only while a person has /boards/<slug> open: one read per board for every tab, sent as the points newer than the last, at most one per MIN_GAP_MS; boards-stream.test.ts drives the stream and counts its frames", |
test/run-compute.test.ts added +115
| @@ -0,0 +1,115 @@ | ||
| 1 | import { afterEach, expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { createRepo } from "../src/actions/repos.ts"; | |
| 6 | import { createApp } from "../src/app.ts"; | |
| 7 | import { entryOf, setLedgerDir } from "../src/core/ledger.ts"; | |
| 8 | import { meterOf, Meter, sampleCompute, STALE_MS, takeCompute, trackCompute } from "../src/core/run_compute.ts"; | |
| 9 | import { createUser } from "../src/core/users.ts"; | |
| 10 | import { claimRun, createRun, finishRun, type Run } from "../src/core/runs.ts"; | |
| 11 | ||
| 12 | const GIB = 2 ** 30; | |
| 13 | const cell = (key: number, label: string, cpuUsec: number, memoryBytes: number) => ({ key, label, cpuUsec, memoryBytes }); | |
| 14 | const src = (file: string) => readFileSync(new URL(`../${file}`, import.meta.url), "utf8"); | |
| 15 | ||
| 16 | afterEach(() => setLedgerDir(undefined)); | |
| 17 | ||
| 18 | test("cpu and memory seconds are summed over the run's own cell", () => { | |
| 19 | const m = new Meter(); | |
| 20 | trackCompute(m, "r1", "crew:a", 0, []); | |
| 21 | sampleCompute(m, [cell(1, "crew:a", 2_000_000, GIB), cell(2, "crew:b", 9e9, 9 * GIB)], 10_000); | |
| 22 | sampleCompute(m, [cell(1, "crew:a", 5_000_000, 2 * GIB)], 20_000); | |
| 23 | expect(takeCompute(m, "r1", 20_000)).toEqual({ cpu_s: 5, mem_gib_s: 30 }); | |
| 24 | expect(takeCompute(m, "r1", 20_000)).toBeUndefined(); | |
| 25 | }); | |
| 26 | ||
| 27 | test("a cell already under the label when a run began makes its figures absent", () => { | |
| 28 | const m = new Meter(); | |
| 29 | trackCompute(m, "r2", "app:x/production", 0, [cell(7, "app:x/production", 100_000_000, GIB)]); | |
| 30 | sampleCompute(m, [cell(7, "app:x/production", 101_000_000, GIB)], 1000); | |
| 31 | expect(takeCompute(m, "r2", 1000)).toBeUndefined(); | |
| 32 | }); | |
| 33 | ||
| 34 | test("two runs on one label at once have no figures, and a later lone run does", () => { | |
| 35 | const m = new Meter(); | |
| 36 | trackCompute(m, "a", "crew:x", 0, []); | |
| 37 | trackCompute(m, "b", "crew:x", 0, []); | |
| 38 | sampleCompute(m, [cell(1, "crew:x", 4_000_000, GIB)], 1000); | |
| 39 | expect(takeCompute(m, "a", 1000)).toBeUndefined(); | |
| 40 | expect(takeCompute(m, "b", 1000)).toBeUndefined(); | |
| 41 | trackCompute(m, "c", "crew:x", 2000, []); | |
| 42 | sampleCompute(m, [cell(2, "crew:x", 1_000_000, GIB)], 3000); | |
| 43 | expect(takeCompute(m, "c", 3000)?.cpu_s).toBe(1); | |
| 44 | }); | |
| 45 | ||
| 46 | test("a run never read, or never tracked, has no figures", () => { | |
| 47 | const m = new Meter(); | |
| 48 | trackCompute(m, "r3", "crew:none", 0, []); | |
| 49 | sampleCompute(m, [], 1000); | |
| 50 | expect(takeCompute(m, "r3", 1000)).toBeUndefined(); | |
| 51 | expect(takeCompute(m, "never")).toBeUndefined(); | |
| 52 | }); | |
| 53 | ||
| 54 | test("a run that never finished is dropped once stale", () => { | |
| 55 | const m = new Meter(); | |
| 56 | trackCompute(m, "lost", "crew:z", 0, []); | |
| 57 | sampleCompute(m, [], STALE_MS + 1); | |
| 58 | expect(m.tracks.size).toBe(0); | |
| 59 | }); | |
| 60 | ||
| 61 | test("the entry carries the figures only when measured", () => { | |
| 62 | const run = { id: "r", repoId: "p", kind: "deploy", issueId: null, env: "production", startedAt: null, finishedAt: "2026-11-30T00:00:00.000Z", costUsd: 0, tokensIn: null, tokensOut: null } as unknown as Run; | |
| 63 | const bare = entryOf(run, "0".repeat(64)); | |
| 64 | expect("cpu_s" in bare || "mem_gib_s" in bare).toBe(false); | |
| 65 | const e = entryOf(run, "0".repeat(64), { cpu_s: 1.5, mem_gib_s: 2 }); | |
| 66 | expect(e.cpu_s).toBe(1.5); | |
| 67 | expect(e.mem_gib_s).toBe(2); | |
| 68 | }); | |
| 69 | ||
| 70 | test("a run started, read and finished through finishRun leaves cpu_s on its ledger line", async () => { | |
| 71 | const root = mkdtempSync(join(tmpdir(), "forge-compute-")); | |
| 72 | try { | |
| 73 | const app = createApp({ dataDir: root, port: 0 }); | |
| 74 | setLedgerDir(join(root, "ledger")); | |
| 75 | const alice = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 76 | if (!alice.ok) throw new Error(alice.error); | |
| 77 | const made = await createRepo(app, alice.value, { name: "shop", visibility: "private" }); | |
| 78 | if (!made.ok) throw new Error(String(made.error)); | |
| 79 | const run = createRun(app.db, { repoId: made.value.id, kind: "check", env: "main", reason: "push" }); | |
| 80 | claimRun(app.db, run.id); | |
| 81 | const meter = meterOf(app.db); | |
| 82 | trackCompute(meter, run.id, `check:${run.id}`, Date.now(), []); | |
| 83 | meter.read = () => [cell(1, `check:${run.id}`, 2_500_000, GIB)]; | |
| 84 | finishRun(app.db, run.id, { state: "ok", summary: "ok" }); | |
| 85 | const dir = join(root, "ledger"); | |
| 86 | const lines = readdirSync(dir).flatMap((f) => readFileSync(join(dir, f), "utf8").trim().split("\n")); | |
| 87 | const entry = JSON.parse(lines.find((l) => l.includes(run.id))!); | |
| 88 | expect(entry.cpu_s).toBe(2.5); | |
| 89 | expect(typeof entry.mem_gib_s).toBe("number"); | |
| 90 | expect(meter.tracks.size).toBe(0); | |
| 91 | } finally { | |
| 92 | rmSync(root, { recursive: true, force: true }); | |
| 93 | } | |
| 94 | }); | |
| 95 | ||
| 96 | test("the start sites and boot are wired, under the labels the watch uses", () => { | |
| 97 | const sites: [string, string][] = [ | |
| 98 | ["src/crew/run_prepare.ts", "`crew:${agent.user.username}`"], | |
| 99 | ["src/apps/runtime_deploy.ts", "`app:${state.app.slug}/${state.env}`"], | |
| 100 | ["src/checks/execute.ts", "`check:${run.id}`"], | |
| 101 | ]; | |
| 102 | for (const [file, label] of sites) { | |
| 103 | expect(src(file)).toContain(`trackCompute(meterOf(`); | |
| 104 | expect(src(file)).toContain(label); | |
| 105 | } | |
| 106 | // The watch labels its cells the same way (`label: …` in the watcher's source). | |
| 107 | expect(src("src/checks/run_tier.ts")).toContain("label: `check:${run.id}`"); | |
| 108 | expect(src("src/apps/runtime_status.ts")).toContain("label: `app:${record.slug}/${env}`"); | |
| 109 | expect(src("src/crew/run_prepare.ts")).toContain("label: `crew:${agent.user.username}`"); | |
| 110 | // Boot hands the meter the watch's readings and samples it. | |
| 111 | expect(src("src/main.ts")).toContain("meterOf(app.db).read = cellCounters"); | |
| 112 | expect(src("src/main.ts")).toContain("sampleCompute(meterOf(app.db))"); | |
| 113 | // The ledger takes the figures at the finish. | |
| 114 | expect(src("src/core/runs.ts")).toContain("appendRun(done, meterOf(db))"); | |
| 115 | }); |
new above
offline