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

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

fix/timing-flakes → main 0 commits 2 threads · 2 unresolved

  • Merged. fix/timing-flakes was merged into main as fee6f7a.

Review

Sign in to review this change.
5 files changed +96 −11
src/crew/runner.ts +15 −3
@@ -98,6 +98,12 @@ export interface CrewOptions {
9898 readonly networkRetryScale?: number | undefined;
9999 /** How long a review run may take. @default BUDGETS.review */
100100 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;
101107 /**
102108 * How long past its budget a review run is waited for before it is left behind (tests shorten
103109 * it).
@@ -249,9 +255,15 @@ async function runClaimed(
249255 giveUp = r;
250256 });
251257 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 =
253265 claimed.reason === "review"
254 ? setTimeout(() => {
266 ? budgetClock(() => {
255267 overran = true;
256268 controller.abort();
257269 grace = setTimeout(
@@ -291,7 +303,7 @@ async function runClaimed(
291303 summary: `${RUN_THREW_PREFIX} ${String(error).slice(0, 200)}`,
292304 };
293305 } finally {
294 clearTimeout(clock);
306 stopClock?.();
295307 clearTimeout(grace);
296308 untrackAgentRun(run.id);
297309 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", () => {
3434 agentRunSettled(app, repo, where, timeoutMs);
3535
3636 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.
3741 standIn = await startStandInCrew({
3842 reviewBudgetMs: 300,
43 reviewSpentWhenStarted: true,
3944 tickMs: 50,
4045 });
4146 ({ app, alice, repo } = standIn);
@@ -78,7 +83,9 @@ describe("the crew, with a stand-in Claude Code: review budget", () => {
7883 expect(reviews.find((r) => r.state === "cancelled")?.summary).toMatch(
7984 /^budget: a review run/,
8085 );
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);
8289
8390 test("a review run for a head whose check is queued stands down: no attempt, not queued again", async () => {
8491 const made = await createAgent(app, alice, { username: "waitrev" });
test/helpers/crew-standin.ts +37 −2
@@ -10,7 +10,7 @@
1010 */
1111
1212 import { expect } from "bun:test";
13 import { chmodSync, writeFileSync } from "node:fs";
13 import { chmodSync, existsSync, readFileSync, watch, writeFileSync } from "node:fs";
1414 import { mkdtemp, rm } from "node:fs/promises";
1515 import { tmpdir } from "node:os";
1616 import { join } from "node:path";
@@ -51,10 +51,44 @@ export interface StandInCrew {
5151 */
5252 export const STAND_IN_TICK_MS = 50;
5353
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();

fs.watch can drop events. Add a slow interval re-check of check() here and clear it in stop, so a missed event costs a poll and not the 60 s guard.

72 };
73 const check = (): void => {
74 if (done || lines() <= seen) return;
75 stop();
76 overrun();
77 };
78 check();
79 return stop;
80 };
81 }
82
5483 /** A forge with checks and a crew whose Claude Code is the stand-in. */
5584 export async function startStandInCrew(
5685 options: {
5786 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;
5892 /** How long past its budget a review run is waited for. */
5993 readonly reviewGraceMs?: number;
6094 readonly tickMs?: number;
@@ -87,6 +121,7 @@ export async function startStandInCrew(
87121 runTimeoutMs: 60_000,
88122 networkRetryScale: 0,
89123 reviewBudgetMs: options.reviewBudgetMs ?? 4_000,
124 ...(options.reviewSpentWhenStarted === true ? { reviewClock: spentWhenStarted(dataDir) } : {}),
90125 ...(options.reviewGraceMs === undefined ? {} : { reviewGraceMs: options.reviewGraceMs }),
91126 tickMs: options.tickMs ?? STAND_IN_TICK_MS,
92127 ...(options.autonomyEveryMs === undefined ? {} : { autonomyEveryMs: options.autonomyEveryMs }),
@@ -314,7 +349,7 @@ printf '{"type":"result","subtype":"success","is_error":false,"result":"DECLINED
314349 exit 0
315350 fi
316351 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
318353 git for-each-ref --format='%(objectname) %(refname)' > "${dataDir}/review.refs"
319354 path=$(grep -o 'api/v1/repos/[^"\\]*/review-states' "${promptFile}" | head -1)
320355 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 @@
77 * The count is the hard assertion and is judged first: it does not move with
88 * the machine's load, and it is the fewest of five warm requests. The clock is the process's CPU
99 * 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.
1216 */
1317 import { afterAll, beforeAll, expect, test } from "bun:test";
1418 import { mkdtempSync, rmSync } from "node:fs";
@@ -39,6 +43,30 @@ const COUNTED = 5;
3943 const ROUNDS = 3;
4044 /** Generous but real: ten times the budget, so only a page that really waits fails it. */
4145 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);
4270
4371 let root = "";
4472 let app: App;
@@ -158,13 +186,15 @@ async function time(
158186 // a sample, never hide a page's own cost; the median of 20 and the retry rounds
159187 // absorb a stray tick. CPU alone would let a page that blocks on I/O look free, so
160188 // 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();
161191 const w = performance.now();
162192 const t = process.cpuUsage();
163193 const res = await fetch(url(b), init(b));
164194 await res.arrayBuffer();
165195 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));
168198 header = res.headers.get("server-timing") ?? "";
169199 }
170200 return { samples, walls, phases: parsePhases(header) };
test/timers-named.test.ts +2 −1
@@ -173,7 +173,8 @@ const ALLOWED: readonly Allowed[] = [
173173 ["src/crew/first_look.ts", "() => resolve(undefined)"],
174174 ["src/crew/plan.ts", "() => resolve(undefined)"],
175175 ["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"],

The match string "overrun" is too loose. Use the whole setTimeout(overrun, ms) expression so it allows only this one timer.

177178 ["src/crew/runner.ts", "() => giveUp({ state: \"failed\""],
178179 ["src/crew/claude.ts", "() => { input.log("],
179180 ["src/crew/claude.ts", "() => { why = \"timeout\"; stopChild(); }"],

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

Keyboard shortcuts

Docs