Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

run.ts

253 lines10.1 KB

1// The effectful half the benchmarks share: alternating A/B rounds, the machine watcher that
2// records what competed with each run, and the process helpers they build on.
3// @effect-diagnostics nodeBuiltinImport:off - NodeHttpServer takes a node:http server.
4import * as NodeHttp from "node:http";
5​
6import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import * as Clock from "effect/Clock";
9import * as Console from "effect/Console";
10import * as Context from "effect/Context";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Schema from "effect/Schema";
17import * as Semaphore from "effect/Semaphore";
18import { HttpServer } from "effect/http";
19​
20import { run } from "../../scenarios/shell.ts";
21import { competingBetween, round, type MachineState } from "./report.ts";
22​
23export class MetricsError extends Schema.TaggedError<MetricsError>()("MetricsError", {
24 message: Schema.String,
25 cause: Schema.optional(Schema.Defect()),
26}) {}
27​
28/** What a command printed, or none when it is missing or failed. */
29export const output = (program: string, args: ReadonlyArray<string>, cwd?: string) =>
30 run(program, args, cwd === undefined ? {} : { cwd }).pipe(
31 Effect.map(({ stdout }) => stdout.trim()),
32 Effect.option,
33 );
34export const powershell = (script: string) =>
35 output("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
36​
37/** Milliseconds on a monotonic clock, for intervals only. */
38export const nowMs = Effect.map(Clock.monotonicTimeNanos, (nanos) => Number(nanos) / 1e6);
39​
40export const httpServerOn = (port: number) =>
41 NodeHttpServer.layer(() => NodeHttp.createServer(), { port, host: "127.0.0.1" });
42​
43/** Every process below `pid`. Windows needs none: taskkill /T stops the tree. */
44export const descendantsOf = Effect.fn("serverMetrics.descendantsOf")(function* (pid: number) {
45 const platform = yield* HostProcess.Platform;
46 const children = new Map<number, number[]>();
47 const add = (child: number, parent: number) =>
48 children.set(parent, [...(children.get(parent) ?? []), child]);
49 if (platform === "linux") {
50 const fs = yield* FileSystem.FileSystem;
51 for (const entry of yield* fs.readDirectory("/proc")) {
52 if (!/^\d+$/.test(entry)) continue;
53 const stat = yield* fs
54 .readFileString(`/proc/${entry}/stat`)
55 .pipe(Effect.orElseSucceed(() => ""));
56 const parent = Number(stat.split(") ")[1]?.split(" ")[1]);
57 if (parent) add(Number(entry), parent);
58 }
59 } else if (platform === "darwin") {
60 const table = yield* output("ps", ["-A", "-o", "pid=,ppid="]);
61 if (Option.isNone(table)) return yield* new MetricsError({ message: "ps listed no processes" });
62 for (const line of table.value.split("\n")) {
63 const [child, parent] = line.trim().split(/\s+/).map(Number);
64 if (child && parent) add(child, parent);
65 }
66 } else return [];
67 const found: number[] = [];
68 const pending = [pid];
69 for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
70 for (const child of children.get(next) ?? []) {
71 found.push(child);
72 pending.push(child);
73 }
74 }
75 return found;
76});
77​
78/** A free loopback port: bind 0, read it, let it go. */
79export const freePort = Effect.scoped(
80 Effect.gen(function* () {
81 const context = yield* Layer.build(httpServerOn(0));
82 const { address } = Context.get(context, HttpServer.HttpServer);
83 return address._tag === "UnixPathAddress" ? 0 : address.port;
84 }),
85);
86​
87export const machineLoad = Effect.gen(function* () {
88 const platform = yield* HostProcess.Platform;
89 if (platform === "win32") {
90 return yield* powershell(
91 "(Get-CimInstance Win32_Processor | Measure-Object LoadPercentage -Average).Average",
92 );
93 }
94 if (platform === "linux") {
95 const fs = yield* FileSystem.FileSystem;
96 const load = yield* fs.readFileString("/proc/loadavg").pipe(Effect.option);
97 return Option.map(load, (text) => text.split(" ").slice(0, 3).join(" "));
98 }
99 return yield* output("sysctl", ["-n", "vm.loadavg"]);
100}).pipe(
101 Effect.map((load) =>
102 Option.getOrNull(Option.map(load, (text) => text.replace(/[{}]/g, "").trim())),
103 ),
104);
105​
106/** Comm names of the processes that compete with a measured server on a developer's machine. */
107const COMPETING = /^(node|node-MainThread|t3|claude|codex|vite|pnpm)/;
108​
109/**
110 * CPU seconds of every node, T3, claude or codex process outside this script's own tree, keyed by
111 * pid and start time so a reused pid is a new process. Linux only; elsewhere none, and the run
112 * records only the load average.
113 */
114const competingCpuSeconds = Effect.gen(function* () {
115 const platform = yield* HostProcess.Platform;
116 if (platform !== "linux") return Option.none<ReadonlyMap<string, number>>();
117 const fs = yield* FileSystem.FileSystem;
118 const self = Number(yield* fs.readLink("/proc/self"));
119 const parents = new Map<number, number>();
120 const cpu = new Map<number, { key: string; seconds: number }>();
121 for (const entry of yield* fs.readDirectory("/proc")) {
122 if (!/^\d+$/.test(entry)) continue;
123 const stat = yield* fs
124 .readFileString(`/proc/${entry}/stat`)
125 .pipe(Effect.orElseSucceed(() => ""));
126 const open = stat.indexOf(" (");
127 const close = stat.lastIndexOf(") ");
128 if (open < 0 || close < 0) continue;
129 const fields = stat.slice(close + 2).split(" ");
130 const pid = Number(entry);
131 parents.set(pid, Number(fields[1]));
132 if (COMPETING.test(stat.slice(open + 2, close))) {
133 // Fields after the name start at the state, field 3: utime 14, stime 15, starttime 22.
134 cpu.set(pid, {
135 key: `${pid}:${fields[19]}`,
136 seconds: (Number(fields[11]) + Number(fields[12])) / 100,
137 });
138 }
139 }
140 const ours = (pid: number) => {
141 for (let at: number | undefined = pid; at !== undefined && at > 1; at = parents.get(at)) {
142 if (at === self) return true;
143 }
144 return false;
145 };
146 return Option.some(
147 new Map([...cpu].filter(([pid]) => !ours(pid)).map(([, { key, seconds }]) => [key, seconds])),
148 );
149}).pipe(Effect.orElseSucceed(() => Option.none<ReadonlyMap<string, number>>()));
150​
151/** How often the machine watcher reads competing CPU; a process that exits loses at most this. */
152const MACHINE_SAMPLE_SECONDS = 10;
153​
154const load1 = Effect.gen(function* () {
155 const platform = yield* HostProcess.Platform;
156 if (platform === "win32") return Option.none<number>();
157 if (platform === "linux") {
158 const fs = yield* FileSystem.FileSystem;
159 const text = yield* fs.readFileString("/proc/loadavg").pipe(Effect.option);
160 return Option.map(text, (value) => Number(value.split(" ")[0]));
161 }
162 const text = yield* output("sysctl", ["-n", "vm.loadavg"]);
163 return Option.map(text, (value) => Number(value.replace(/[{}]/g, "").trim().split(/\s+/)[0]));
164}).pipe(Effect.map(Option.filter(Number.isFinite)));
165​
166/**
167 * Starts watching the machine for one run; the returned effect reads what competed with it: the
168 * highest 1-minute load seen and the cores other T3, node and agent processes kept busy.
169 */
170export const watchMachine = Effect.gen(function* () {
171 const startedAt = yield* nowMs;
172 const loads: number[] = [];
173 // Unknown (none) once any read fails, so a partial sum never passes for the whole run.
174 let competing: Option.Option<number> = Option.some(0);
175 let previous = yield* competingCpuSeconds;
176 if (Option.isNone(previous)) competing = Option.none();
177 // The periodic and final reads would otherwise interleave across the await below.
178 const reading = yield* Semaphore.make(1);
179 const read = Effect.gen(function* () {
180 loads.push(...Option.toArray(yield* load1));
181 if (Option.isNone(previous) || Option.isNone(competing)) return;
182 const next = yield* competingCpuSeconds;
183 if (Option.isNone(next)) {
184 competing = Option.none();
185 return;
186 }
187 competing = Option.some(competing.value + competingBetween(previous.value, next.value));
188 previous = next;
189 }).pipe(reading.withPermits(1));
190 yield* read;
191 // Reading through the run, not only at its ends, keeps a busy process that exits mid-run.
192 yield* read.pipe(
193 Effect.delay(Duration.seconds(MACHINE_SAMPLE_SECONDS)),
194 Effect.forever,
195 Effect.forkScoped,
196 );
197 return Effect.gen(function* () {
198 yield* read;
199 const elapsed = ((yield* nowMs) - startedAt) / 1_000;
200 const machine: MachineState = {
201 load1: loads.length ? round(Math.max(...loads), 2) : null,
202 otherCpuCores:
203 Option.isSome(competing) && elapsed > 0 ? round(competing.value / elapsed, 2) : null,
204 minutes: round(elapsed / 60, 1),
205 };
206 return machine;
207 });
208});
209​
210/**
211 * Runs A and B alternately, saving a side after each of its runs so a failure keeps the finished
212 * runs. On a failure it reports how many runs of each side reached disk.
213 */
214export const runAbRounds = Effect.fn("serverMetrics.abRounds")(function* <
215 A,
216 S,
217 E,
218 R,
219 ES,
220 RS,
221>(options: {
222 readonly rounds: number;
223 readonly outDir: string;
224 readonly runSide: (side: 0 | 1) => Effect.Effect<A, E, R>;
225 readonly save: (side: 0 | 1, runs: ReadonlyArray<A>) => Effect.Effect<S, ES, RS>;
226}) {
227 const runs: [A[], A[]] = [[], []];
228 const persisted = [0, 0];
229 const saveSide = Effect.fn("serverMetrics.abSave")(function* (side: 0 | 1) {
230 const count = runs[side].length;
231 const saved = yield* options.save(side, runs[side]);
232 persisted[side] = count;
233 return saved;
234 });
235 const saved: [S, S] = [yield* saveSide(0), yield* saveSide(1)];
236 yield* Effect.gen(function* () {
237 for (let round = 0; round < options.rounds; round++) {
238 // A B, then B A, so a drift in machine load lands on both sides.
239 for (const side of round % 2 === 0 ? ([0, 1] as const) : ([1, 0] as const)) {
240 yield* Console.error(`round ${round + 1}/${options.rounds}: ${side === 0 ? "A" : "B"}`);
241 runs[side].push(yield* options.runSide(side));
242 saved[side] = yield* saveSide(side);
243 }
244 }
245 }).pipe(
246 Effect.onError(() =>
247 Console.error(
248 `ab stopped early; ${options.outDir} keeps ${persisted[0]} A and ${persisted[1]} B runs`,
249 ),
250 ),
251 );
252 return saved;
253});