Public: anyone can read this; the crew can change it.
Two timing flakes measured against load: page budgets scale by a same-run calibration; review budget is event-driven #16879
Check · Review · Land · Live done — Landed and live in production.
fix/timing-flakes → main 0 commits 2 threads · 2 unresolved
5 files
changed +96
−11
src/crew/runner.ts +15 −3
| @@ -98,6 +98,12 @@ export interface CrewOptions { | ||
| 98 | 98 | readonly networkRetryScale?: number | undefined; |
| 99 | 99 | /** How long a review run may take. @default BUDGETS.review */ |
| 100 | 100 | readonly reviewBudgetMs?: number | undefined; |
| 101 | /** | |
| 102 | * What spends a review run's budget: `overrun` is called once it is spent, and the function | |
| 103 | * returned stops it. A test spends it on an event, not on the wall clock. @default a timer of | |
| 104 | * `reviewBudgetMs` | |
| 105 | */ | |
| 106 | readonly reviewClock?: ((overrun: () => void, budgetMs: number) => () => void) | undefined; | |
| 101 | 107 | /** |
| 102 | 108 | * How long past its budget a review run is waited for before it is left behind (tests shorten |
| 103 | 109 | * it). |
| @@ -249,9 +255,15 @@ async function runClaimed( | ||
| 249 | 255 | giveUp = r; |
| 250 | 256 | }); |
| 251 | 257 | let grace: ReturnType<typeof setTimeout> | undefined; |
| 252 | const clock = | |
| 258 | const budgetClock = | |
| 259 | options.reviewClock ?? | |
| 260 | ((overrun: () => void, ms: number) => { | |
| 261 | const t = setTimeout(overrun, ms); | |
| 262 | return () => clearTimeout(t); | |
| 263 | }); | |
| 264 | const stopClock = | |
| 253 | 265 | claimed.reason === "review" |
| 254 | ? setTimeout(() => { | |
| 266 | ? budgetClock(() => { | |
| 255 | 267 | overran = true; |
| 256 | 268 | controller.abort(); |
| 257 | 269 | grace = setTimeout( |
| @@ -291,7 +303,7 @@ async function runClaimed( | ||
| 291 | 303 | summary: `${RUN_THREW_PREFIX} ${String(error).slice(0, 200)}`, |
| 292 | 304 | }; |
| 293 | 305 | } finally { |
| 294 | clearTimeout(clock); | |
| 306 | stopClock?.(); | |
| 295 | 307 | clearTimeout(grace); |
| 296 | 308 | untrackAgentRun(run.id); |
| 297 | 309 | stopSteering(run.id); |
test/crew-review-budget.test.ts +8 −1
| @@ -34,8 +34,13 @@ describe("the crew, with a stand-in Claude Code: review budget", () => { | ||
| 34 | 34 | agentRunSettled(app, repo, where, timeoutMs); |
| 35 | 35 | |
| 36 | 36 | beforeAll(async () => { |
| 37 | // The budget is spent when the slow reviewer has started, not after 300 ms of a loaded | |
| 38 | // host's wall clock, which ran out before the reviewer started ("before its reviewer | |
| 39 | // started"). The second test's run stands down before any reviewer, so its budget is never | |
| 40 | // spent. | |
| 37 | 41 | standIn = await startStandInCrew({ |
| 38 | 42 | reviewBudgetMs: 300, |
| 43 | reviewSpentWhenStarted: true, | |
| 39 | 44 | tickMs: 50, |
| 40 | 45 | }); |
| 41 | 46 | ({ app, alice, repo } = standIn); |
| @@ -78,7 +83,9 @@ describe("the crew, with a stand-in Claude Code: review budget", () => { | ||
| 78 | 83 | expect(reviews.find((r) => r.state === "cancelled")?.summary).toMatch( |
| 79 | 84 | /^budget: a review run/, |
| 80 | 85 | ); |
| 81 | }, 10_000); | |
| 86 | // A hang guard over two runs that each reach their reviewer (each wait is `settled`'s own 30 s), | |
| 87 | // not a speed claim: under 96 busy processes the two took past 10 s. | |
| 88 | }, 60_000); | |
| 82 | 89 | |
| 83 | 90 | test("a review run for a head whose check is queued stands down: no attempt, not queued again", async () => { |
| 84 | 91 | const made = await createAgent(app, alice, { username: "waitrev" }); |
test/helpers/crew-standin.ts +37 −2
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | */ |
| 11 | 11 | |
| 12 | 12 | import { expect } from "bun:test"; |
| 13 | import { chmodSync, writeFileSync } from "node:fs"; | |
| 13 | import { chmodSync, existsSync, readFileSync, watch, writeFileSync } from "node:fs"; | |
| 14 | 14 | import { mkdtemp, rm } from "node:fs/promises"; |
| 15 | 15 | import { tmpdir } from "node:os"; |
| 16 | 16 | import { join } from "node:path"; |
| @@ -51,10 +51,44 @@ export interface StandInCrew { | ||
| 51 | 51 | */ |
| 52 | 52 | export const STAND_IN_TICK_MS = 50; |
| 53 | 53 | |
| 54 | /** The file the stand-in's SLOW-REVIEW reviewer adds a line to as it starts. */ | |
| 55 | const SLOW_REVIEW_STARTED = "slow-review.started"; | |
| 56 | ||
| 57 | /** | |
| 58 | * A review clock (`reviewClock`) that spends the budget when the stand-in's slow reviewer has | |
| 59 | * started since the run was claimed: a line added to `SLOW_REVIEW_STARTED`, seen by a watch on | |
| 60 | * the data directory. No wall time, so the run always reaches its reviewer before it overruns. | |
| 61 | */ | |
| 62 | function spentWhenStarted(dataDir: string): (overrun: () => void) => () => void { | |
| 63 | const file = join(dataDir, SLOW_REVIEW_STARTED); | |
| 64 | const lines = (): number => (existsSync(file) ? readFileSync(file, "utf8").split("\n").filter((l) => l !== "").length : 0); | |
| 65 | return (overrun) => { | |
| 66 | const seen = lines(); | |
| 67 | let done = false; | |
| 68 | const watcher = watch(dataDir, () => check()); | |
| 69 | const stop = (): void => { | |
| 70 | done = true; | |
| 71 | watcher.close(); | |
| 72 | }; | |
| 73 | const check = (): void => { | |
| 74 | if (done || lines() <= seen) return; | |
| 75 | stop(); | |
| 76 | overrun(); | |
| 77 | }; | |
| 78 | check(); | |
| 79 | return stop; | |
| 80 | }; | |
| 81 | } | |
| 82 | ||
| 54 | 83 | /** A forge with checks and a crew whose Claude Code is the stand-in. */ |
| 55 | 84 | export async function startStandInCrew( |
| 56 | 85 | options: { |
| 57 | 86 | readonly reviewBudgetMs?: number; |
| 87 | /** | |
| 88 | * Spend a review run's budget the moment the stand-in's SLOW-REVIEW reviewer has started, not | |
| 89 | * after wall time: on a loaded host a short budget ran out before the reviewer ever started. | |
| 90 | */ | |
| 91 | readonly reviewSpentWhenStarted?: boolean; | |
| 58 | 92 | /** How long past its budget a review run is waited for. */ |
| 59 | 93 | readonly reviewGraceMs?: number; |
| 60 | 94 | readonly tickMs?: number; |
| @@ -87,6 +121,7 @@ export async function startStandInCrew( | ||
| 87 | 121 | runTimeoutMs: 60_000, |
| 88 | 122 | networkRetryScale: 0, |
| 89 | 123 | reviewBudgetMs: options.reviewBudgetMs ?? 4_000, |
| 124 | ...(options.reviewSpentWhenStarted === true ? { reviewClock: spentWhenStarted(dataDir) } : {}), | |
| 90 | 125 | ...(options.reviewGraceMs === undefined ? {} : { reviewGraceMs: options.reviewGraceMs }), |
| 91 | 126 | tickMs: options.tickMs ?? STAND_IN_TICK_MS, |
| 92 | 127 | ...(options.autonomyEveryMs === undefined ? {} : { autonomyEveryMs: options.autonomyEveryMs }), |
| @@ -314,7 +349,7 @@ printf '{"type":"result","subtype":"success","is_error":false,"result":"DECLINED | ||
| 314 | 349 | exit 0 |
| 315 | 350 | fi |
| 316 | 351 | if grep -q "You are the reviewer on this crew" "${promptFile}"; then |
| 317 | if grep -q SLOW-REVIEW "${promptFile}"; then exec sleep 60; fi | |
| 352 | if grep -q SLOW-REVIEW "${promptFile}"; then echo started >> "${dataDir}/${SLOW_REVIEW_STARTED}"; exec sleep 60; fi | |
| 318 | 353 | git for-each-ref --format='%(objectname) %(refname)' > "${dataDir}/review.refs" |
| 319 | 354 | path=$(grep -o 'api/v1/repos/[^"\\]*/review-states' "${promptFile}" | head -1) |
| 320 | 355 | curl -sS -X POST -H "authorization: Bearer $FORGE_TOKEN" -H "content-type: application/json" "\${FORGE_URL%/}/$path" -d '{"state":"changes_requested","body":"Name the fence."}' > "${dataDir}/review.out" |
test/page-budget.test.ts +34 −4
| @@ -7,8 +7,12 @@ | ||
| 7 | 7 | * The count is the hard assertion and is judged first: it does not move with |
| 8 | 8 | * the machine's load, and it is the fewest of five warm requests. The clock is the process's CPU |
| 9 | 9 | * time over 20 warm requests per page after one to warm (CPU, not wall-clock, so shard load does |
| 10 | * not fail a fast page, #12609); a page whose median misses is measured again (up to three rounds) | |
| 11 | * before it is named, so a busy check host does not fail a fast page. | |
| 10 | * not fail a fast page, #12609). CPU time still stretches on a busy host (cache and core | |
| 11 | * contention: 2.5x under 64 busy processes on the Mac), so each request is paired with a fixed | |
| 12 | * piece of work timed just before it (`calibrate`), and the request's time is read in the units of | |
| 13 | * that work: on a host where the work takes longer than it does quiet, the request's time is | |
| 14 | * scaled down by the same factor, never up. A page whose median misses is measured again (up to | |
| 15 | * three rounds) before it is named. | |
| 12 | 16 | */ |
| 13 | 17 | import { afterAll, beforeAll, expect, test } from "bun:test"; |
| 14 | 18 | import { mkdtempSync, rmSync } from "node:fs"; |
| @@ -39,6 +43,30 @@ const COUNTED = 5; | ||
| 39 | 43 | const ROUNDS = 3; |
| 40 | 44 | /** Generous but real: ten times the budget, so only a page that really waits fails it. */ |
| 41 | 45 | const WALL_CEILING_MS = 500; |
| 46 | /** | |
| 47 | * The calibration's CPU time on a quiet machine, the owner's Mac (an M-series), where the budgets | |
| 48 | * are read: a median of 200 runs was 1.07 ms (2.07 ms under 64 busy processes). | |
| 49 | */ | |
| 50 | const CALIBRATION_QUIET_MS = 1.07; | |
| 51 | const CALIBRATION_DATA = Array.from({ length: 2_000 }, (_, i) => ({ id: i, name: `row ${i}`, tags: ["a", "b", String(i)] })); | |
| 52 | ||
| 53 | /** | |
| 54 | * A fixed piece of the work a page does (JSON written and read back, strings and objects made), | |
| 55 | * timed as a request is: its CPU time and its wall time. Under load it stretches as a request does. | |
| 56 | */ | |
| 57 | function calibrate(): { cpu: number; wall: number } { | |
| 58 | const w = performance.now(); | |
| 59 | const t = process.cpuUsage(); | |
| 60 | let rows = 0; | |
| 61 | for (let r = 0; r < 3; r++) rows += (JSON.parse(JSON.stringify(CALIBRATION_DATA)) as unknown[]).length; | |
| 62 | const used = process.cpuUsage(t); | |
| 63 | const wall = performance.now() - w; | |
| 64 | if (rows !== 6_000) throw new Error("the calibration did not run"); | |
| 65 | return { cpu: (used.user + used.system) / 1000, wall }; | |
| 66 | } | |
| 67 | ||
| 68 | /** How much slower this moment is than a quiet machine, by the calibration's time; 1 at most fast. */ | |
| 69 | const slowdown = (took: number): number => Math.max(1, took / CALIBRATION_QUIET_MS); | |
| 42 | 70 | |
| 43 | 71 | let root = ""; |
| 44 | 72 | let app: App; |
| @@ -158,13 +186,15 @@ async function time( | ||
| 158 | 186 | // a sample, never hide a page's own cost; the median of 20 and the retry rounds |
| 159 | 187 | // absorb a stray tick. CPU alone would let a page that blocks on I/O look free, so |
| 160 | 188 | // each request's wall time is kept too and judged against WALL_CEILING_MS. |
| 189 | // Timed just before the request, so both see the host as it is at that moment. | |
| 190 | const cal = calibrate(); | |
| 161 | 191 | const w = performance.now(); |
| 162 | 192 | const t = process.cpuUsage(); |
| 163 | 193 | const res = await fetch(url(b), init(b)); |
| 164 | 194 | await res.arrayBuffer(); |
| 165 | 195 | const used = process.cpuUsage(t); |
| 166 | walls.push(performance.now() - w); | |
| 167 | samples.push((used.user + used.system) / 1000); | |
| 196 | walls.push((performance.now() - w) / slowdown(cal.wall)); | |
| 197 | samples.push((used.user + used.system) / 1000 / slowdown(cal.cpu)); | |
| 168 | 198 | header = res.headers.get("server-timing") ?? ""; |
| 169 | 199 | } |
| 170 | 200 | return { samples, walls, phases: parsePhases(header) }; |
test/timers-named.test.ts +2 −1
| @@ -173,7 +173,8 @@ const ALLOWED: readonly Allowed[] = [ | ||
| 173 | 173 | ["src/crew/first_look.ts", "() => resolve(undefined)"], |
| 174 | 174 | ["src/crew/plan.ts", "() => resolve(undefined)"], |
| 175 | 175 | ["src/crew/decide.ts", "() => abort.abort()"], |
| 176 | ["src/crew/runner.ts", "() => { overran = true; controller.abort(); grace"], | |
| 176 | // The review budget's default clock (`reviewClock`): its callback aborts the run and arms the grace. | |
| 177 | ["src/crew/runner.ts", "overrun"], | |
| 177 | 178 | ["src/crew/runner.ts", "() => giveUp({ state: \"failed\""], |
| 178 | 179 | ["src/crew/claude.ts", "() => { input.log("], |
| 179 | 180 | ["src/crew/claude.ts", "() => { why = \"timeout\"; stopChild(); }"], |
new above
offline
fs.watch can drop events. Add a slow interval re-check of
check()here and clear it instop, so a missed event costs a poll and not the 60 s guard.