-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathmacos-rss-retention-harness.ts
More file actions
1461 lines (1356 loc) · 43.8 KB
/
Copy pathmacos-rss-retention-harness.ts
File metadata and controls
1461 lines (1356 loc) · 43.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
existsSync,
lstatSync,
mkdirSync,
readFileSync,
realpathSync,
renameSync,
writeFileSync,
} from "node:fs";
import {
dirname,
isAbsolute,
join,
relative,
resolve,
sep,
} from "node:path";
import {
arch,
cpus,
freemem,
loadavg,
platform,
release,
totalmem,
uptime,
} from "node:os";
type Condition =
| "real-proxy-legacy-tee"
| "single-reader-inspection"
| "direct-http-baseline";
type Kind = "calibration" | "parent-pressure" | "workload";
type Row = Record<string, unknown> & { type: string; wallMs: number };
type Run = {
id: string;
condition: Condition;
kind: Kind;
sampler: boolean;
series: string;
};
const MiB = 1024 ** 2;
/**
* Smoke mode exists to prove the pipeline runs end to end without waiting out a
* ~7h session. It shortens durations ONLY, and every artifact it produces is
* stamped `smoke: true` and `valid: false` so a shortened run can never be
* mistaken for, or compared against, a real measurement. The pre-registered
* measurement constants below are untouched in a real run.
*/
const SMOKE = process.env.OCX_RSS_HARNESS_SMOKE === "1";
const WARM = SMOKE ? 2_000 : 60_000;
const OBSERVE = SMOKE ? 6_000 : 600_000;
const WAVES = SMOKE ? 2 : 10;
const EVENTS = SMOKE ? 20 : 400;
const EVENT_BYTES = 65_536;
const WAVE_MS = SMOKE ? 4_000 : 120_000;
const READ_MS = 25;
// Scheduler jitter is tolerated, but not enough drift to stretch the locked profile.
// Changing this after seeing a result invalidates and restarts the full calibration sequence.
const WAVE_TOLERANCE_MS = 5_000;
/**
* Total turns in a run: three clients, one turn each per wave. Derive it rather
* than writing 30 in the validators — a literal silently becomes a lie the moment
* the wave count changes, and the validator would then reject a correct run (or,
* worse, accept a truncated one).
*/
const CLIENTS = 3;
const TURNS = CLIENTS * WAVES;
const SETTLE = SMOKE ? ([0, 2, 4] as const) : ([0, 30, 60, 120, 300, 600] as const);
const CONDITIONS: readonly Condition[] = [
"real-proxy-legacy-tee",
"single-reader-inspection",
"direct-http-baseline",
];
const LATIN: readonly (readonly Condition[])[] = [
CONDITIONS,
["single-reader-inspection", "direct-http-baseline", "real-proxy-legacy-tee"],
["direct-http-baseline", "real-proxy-legacy-tee", "single-reader-inspection"],
];
const ORDER = [false, true, true, false, true, false] as const;
class Log {
private writer;
constructor(readonly path: string) {
this.writer = Bun.file(path).writer();
}
add(row: Record<string, unknown>): void {
this.writer.write(JSON.stringify({ wallMs: Date.now(), ...row }) + "\n");
}
async flush(): Promise<void> {
await this.writer.flush();
}
async close(): Promise<void> {
const errors: unknown[] = [];
try {
await this.writer.flush();
} catch (error) {
errors.push(error);
}
try {
this.writer.end();
} catch (error) {
errors.push(error);
}
if (errors.length > 0) throw new AggregateError(errors, "manifest cleanup failed");
}
}
type CleanupEntry = {
name: string;
cleanup: () => Promise<void>;
stopping?: Promise<void>;
};
type CleanupHandle = { stop: () => Promise<void> };
class CleanupRegistry {
private entries: CleanupEntry[] = [];
register(name: string, cleanup: () => Promise<void>): CleanupHandle {
const entry: CleanupEntry = { name, cleanup };
this.entries.push(entry);
return { stop: () => this.stop(entry) };
}
private stop(entry: CleanupEntry): Promise<void> {
if (!entry.stopping) {
entry.stopping = (async () => {
try {
await entry.cleanup();
} finally {
const index = this.entries.indexOf(entry);
if (index >= 0) this.entries.splice(index, 1);
}
})();
}
return entry.stopping;
}
async stopAll(): Promise<void> {
const errors: unknown[] = [];
for (const entry of [...this.entries].reverse()) {
try {
await this.stop(entry);
} catch (error) {
errors.push(new Error(`cleanup failed for ${entry.name}`, { cause: error }));
}
}
if (errors.length > 0) throw new AggregateError(errors, "registered cleanup failed");
}
}
const resources = new CleanupRegistry();
const sessionAbort = new AbortController();
let signalCleanup: Promise<void> | null = null;
let signalCleanupFailure: unknown;
function interruptedError(): Error {
const reason: unknown = sessionAbort.signal.reason;
return reason instanceof Error ? reason : new Error(String(reason ?? "session interrupted"));
}
function throwIfInterrupted(): void {
if (sessionAbort.signal.aborted) throw interruptedError();
}
function interruptible<T>(operation: PromiseLike<T>): Promise<T> {
throwIfInterrupted();
return new Promise<T>((resolvePromise, rejectPromise) => {
let settled = false;
const finish = (callback: () => void): void => {
if (settled) return;
settled = true;
sessionAbort.signal.removeEventListener("abort", onAbort);
callback();
};
const onAbort = (): void => finish(() => rejectPromise(interruptedError()));
sessionAbort.signal.addEventListener("abort", onAbort, { once: true });
Promise.resolve(operation).then(
value => finish(() => resolvePromise(value)),
error => finish(() => rejectPromise(error)),
);
});
}
function beginSignalCleanup(signal: "SIGINT" | "SIGTERM"): void {
if (sessionAbort.signal.aborted) return;
sessionAbort.abort(new Error(`parent received ${signal}`));
// Closing registered servers and children also unblocks reads that cannot observe AbortSignal.
signalCleanup = resources.stopAll().catch((error) => {
signalCleanupFailure = error;
});
}
function inside(base: string, target: string): boolean {
const pathFromBase = relative(base, target);
return pathFromBase === ""
|| (
pathFromBase !== ".."
&& !pathFromBase.startsWith(".." + sep)
&& !isAbsolute(pathFromBase)
);
}
function nearest(target: string): string {
let current = target;
while (!existsSync(current)) {
const next = dirname(current);
if (next === current) throw new Error("no ancestor");
current = next;
}
return current;
}
function validate(base: string, lexical: string): string {
if (!inside(base, lexical)) throw new Error("lexical escape");
let current = base;
for (const part of relative(base, lexical).split(sep).filter(Boolean)) {
current = join(current, part);
if (lstatSync(current).isSymbolicLink()) throw new Error("symlink: " + current);
}
const canonical = realpathSync.native(lexical);
if (!inside(base, canonical)) throw new Error("canonical escape");
return canonical;
}
function create(base: string, requested: string, fresh: boolean): string {
const target = resolve(requested);
if (!inside(base, target) || (fresh && existsSync(target))) {
throw new Error("unsafe leaf");
}
// Validate the nearest existing ancestor before creating even the first component.
const ancestor = nearest(target);
let parent = validate(base, ancestor);
for (const part of relative(ancestor, target).split(sep).filter(Boolean)) {
const next = join(parent, part);
if (!existsSync(next)) mkdirSync(next, { recursive: false, mode: 0o700 });
if (lstatSync(next).isSymbolicLink()) throw new Error("symlink: " + next);
parent = realpathSync.native(next);
if (!inside(base, parent)) throw new Error("created escape");
}
return validate(base, target);
}
function outputRoot(requested?: string): string {
const repo = realpathSync.native(resolve(import.meta.dir, ".."));
const allowedLexical = resolve(repo, ".tmp", "macos-rss-retention");
validate(repo, nearest(allowedLexical));
const allowed = create(repo, allowedLexical, false);
return create(
allowed,
requested ?? join(
allowed,
new Date().toISOString().replace(/[:.]/g, "-") + "-" + process.pid,
),
true,
);
}
function host() {
return {
platform: platform(),
release: release(),
arch: arch(),
bun: Bun.version,
cpus: cpus().length,
cpuModel: cpus()[0]?.model ?? null,
loadavg: loadavg(),
totalmem: totalmem(),
freemem: freemem(),
uptime: uptime(),
};
}
async function pause(ms: number): Promise<void> {
const deadline = performance.now() + Math.max(0, ms);
for (;;) {
const remaining = deadline - performance.now();
if (remaining <= 0) return;
// Bun.sleep may wake fractionally before the requested deadline. Re-sleep
// instead of weakening a pre-registered duration.
await interruptible(Bun.sleep(Math.ceil(remaining)));
}
}
function frame(type: string | null, payload: unknown): Uint8Array {
const data = typeof payload === "string" ? payload : JSON.stringify(payload);
return new TextEncoder().encode(
(type ? "event: " + type + "\n" : "") + "data: " + data + "\n\n",
);
}
type Fixture = { url: string; stop: () => Promise<void> };
function fixture(log: Log, run: string): Fixture {
throwIfInterrupted();
let serial = 0;
const server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
async fetch(request) {
if (request.method !== "POST" || new URL(request.url).pathname !== "/v1/responses") {
return new Response("not found", { status: 404 });
}
const body = await request.json().catch(() => ({})) as Record<string, unknown>;
const id = ++serial;
let eventNumber = 0;
log.add({
type: "upstream-request",
run,
id,
previous: typeof body.previous_response_id === "string"
? body.previous_response_id
: null,
inputItems: Array.isArray(body.input) ? body.input.length : null,
});
return new Response(new ReadableStream<Uint8Array>({
pull(controller) {
let kind: string;
let bytes: Uint8Array;
if (eventNumber === 0) {
kind = "created";
bytes = frame("response.created", {
type: "response.created",
response: {
id: "fixture-" + id,
status: "in_progress",
output: [],
},
});
} else if (eventNumber <= EVENTS) {
kind = "delta";
bytes = frame("response.output_text.delta", {
type: "response.output_text.delta",
output_index: 0,
content_index: 0,
item_id: "msg-" + id,
delta: "x".repeat(EVENT_BYTES),
});
} else {
const item = {
id: "msg-" + id,
type: "message",
status: "completed",
role: "assistant",
content: [],
};
if (eventNumber === EVENTS + 1) {
kind = "item";
bytes = frame("response.output_item.done", {
type: "response.output_item.done",
output_index: 0,
item,
});
} else if (eventNumber === EVENTS + 2) {
kind = "completed";
bytes = frame("response.completed", {
type: "response.completed",
response: {
id: "fixture-" + id,
status: "completed",
output: [],
},
});
} else {
kind = "done";
bytes = frame(null, "[DONE]");
}
}
log.add({
type: "upstream-pull",
run,
id,
n: eventNumber,
kind,
bytes: bytes.byteLength,
});
controller.enqueue(bytes);
eventNumber++;
if (kind === "done") controller.close();
},
}), {
headers: { "content-type": "text/event-stream" },
});
},
});
const cleanup = resources.register(`fixture ${run}`, async () => {
await server.stop(true);
});
return {
url: server.url.toString().replace(/\/$/, ""),
stop: cleanup.stop,
};
}
class IdParser {
private decoder = new TextDecoder();
private buffer = "";
private id?: string;
push(bytes: Uint8Array): void {
this.buffer += this.decoder.decode(bytes, { stream: true });
if (this.buffer.length > 128 * 1024 && !this.buffer.includes("\n\n")) {
throw new Error("SSE frame bound");
}
for (let cut; (cut = this.buffer.indexOf("\n\n")) >= 0;) {
const block = this.buffer.slice(0, cut);
this.buffer = this.buffer.slice(cut + 2);
const data = block
.split(/\r?\n/)
.filter(line => line.startsWith("data:"))
.map(line => line.slice(5).trimStart())
.join("\n");
if (data.includes("\"type\":\"response.completed\"")) {
const parsed = JSON.parse(data) as { response?: { id?: unknown } };
if (typeof parsed.response?.id === "string") this.id = parsed.response.id;
}
}
}
finish(): string {
this.push(new Uint8Array());
if (!this.id) throw new Error("completion id missing");
return this.id;
}
}
type State = { client: number; previous?: string };
async function oneTurn(
base: string,
run: string,
wave: number,
state: State,
log: Log,
): Promise<void> {
const turn = wave + 1;
const started = Date.now();
log.add({
type: "client-start",
run,
wave,
client: state.client,
turn,
previous: state.previous ?? null,
});
const response = await interruptible(fetch(base + "/v1/responses", {
method: "POST",
headers: {
"content-type": "application/json",
// Responses admission intentionally does not accept a caller Bearer token.
"x-opencodex-api-key": "fixture-admission",
},
body: JSON.stringify({
model: "fixture/fixture-model",
input: "fixture-" + state.client + "-" + turn,
stream: true,
...(state.previous ? { previous_response_id: state.previous } : {}),
}),
}));
log.add({
type: "client-http",
run,
wave,
client: state.client,
turn,
status: response.status,
body: response.body !== null,
});
// The status receipt is durable before this throws, so auth/routing failures remain auditable.
if (response.status !== 200 || !response.body) {
throw new Error("HTTP " + response.status);
}
// Chunk-wise backpressure is the measured mechanism; response.text() would erase it.
const reader = response.body.getReader();
const parser = new IdParser();
let chunk = 0;
let prior = Date.now();
for (;;) {
const part = await interruptible(reader.read());
if (part.done) break;
const now = Date.now();
parser.push(part.value);
log.add({
type: "client-chunk",
run,
wave,
client: state.client,
turn,
chunk: ++chunk,
bytes: part.value.byteLength,
gapMs: now - prior,
sinceTurnStartMs: now - started,
});
prior = now;
await pause(READ_MS);
}
const completed = parser.finish();
log.add({
type: "client-end",
run,
wave,
client: state.client,
turn,
previous: state.previous ?? null,
completed,
durationMs: Date.now() - started,
});
state.previous = completed;
}
async function workload(base: string, run: string, log: Log): Promise<void> {
// These three chain heads persist across all ten waves: one turn per client per wave.
const states: State[] = Array.from({ length: CLIENTS }, (_, index) => ({ client: index + 1 }));
const origin = performance.now();
log.add({
type: "workload-origin",
run,
wallMs: Date.now(),
monotonicMs: origin,
});
for (let wave = 0; wave < WAVES; wave++) {
await pause(Math.max(0, origin + wave * WAVE_MS - performance.now()));
await Promise.all(states.map(state => oneTurn(base, run, wave, state, log)));
}
}
type Child = {
process: Bun.Subprocess;
base: string;
drain: Promise<void>;
stop: () => Promise<void>;
};
function childStderr(path: string): string {
try {
if (!existsSync(path)) return "<no child stderr>";
const text = readFileSync(path, "utf8").trim();
return text ? text.slice(-4_000) : "<empty child stderr>";
} catch (error) {
return `<child stderr unreadable: ${String(error)}>`;
}
}
async function stopChildProcess(
processHandle: Bun.Subprocess,
drain: Promise<void>,
): Promise<void> {
const errors: unknown[] = [];
if (processHandle.exitCode === null) {
try {
processHandle.kill("SIGTERM");
} catch (error) {
errors.push(error);
}
}
try {
await Promise.race([processHandle.exited, Bun.sleep(5_000)]);
} catch (error) {
errors.push(error);
}
if (processHandle.exitCode === null) {
try {
processHandle.kill("SIGKILL");
await processHandle.exited;
} catch (error) {
errors.push(error);
}
}
try {
await drain;
} catch (error) {
errors.push(error);
}
if (processHandle.exitCode !== 0) {
errors.push(new Error(`child exit code ${String(processHandle.exitCode)}`));
}
if (errors.length > 0) throw new AggregateError(errors, "child cleanup failed");
}
async function startChild(
condition: Condition,
url: string,
dir: string,
sampler: boolean,
): Promise<Child> {
throwIfInterrupted();
const real = condition === "real-proxy-legacy-tee";
const args = real
? [
create(dir, join(dir, "opencodex"), true),
create(dir, join(dir, "codex"), true),
url,
join(dir, "child.jsonl"),
sampler ? "on" : "off",
]
: [
url,
join(dir, "child.jsonl"),
join(dir, "child-events.jsonl"),
condition,
sampler ? "on" : "off",
];
const stderrPath = join(dir, "child.stderr.log");
const processHandle = Bun.spawn([
globalThis.process.execPath,
join(
import.meta.dir,
real
? "macos-rss-retention-harness-child.ts"
: "macos-rss-retention-single-reader-child.ts",
),
...args,
], {
stdout: "pipe",
stderr: Bun.file(stderrPath),
});
const reader = processHandle.stdout.getReader();
let port: number | undefined;
let ready!: () => void;
const signal = new Promise<void>((resolveReady) => {
ready = resolveReady;
});
const drain = (async () => {
const decoder = new TextDecoder();
let buffer = "";
for (;;) {
const part = await reader.read();
if (part.done) break;
buffer += decoder.decode(part.value, { stream: true });
const lines = buffer.split(/\r?\n/);
buffer = lines.pop() ?? "";
for (const line of lines) {
try {
const value = JSON.parse(line) as { type?: string; port?: number };
if (value.type === "ready" && value.port) {
port = value.port;
ready();
}
} catch {
// The real server emits human-readable startup lines before its readiness receipt.
}
}
}
})();
// Registration happens before the first readiness await, closing the spawn-to-ready leak window.
const cleanup = resources.register(`child ${condition}`, async () => {
await stopChildProcess(processHandle, drain);
});
try {
await interruptible(Promise.race([
signal,
processHandle.exited.then(() => {
throw new Error("child exited before ready");
}),
drain.then(() => {
if (!port) throw new Error("child stdout closed before ready");
}),
Bun.sleep(15_000).then(() => {
throw new Error("readiness timeout");
}),
]));
if (!port) throw new Error("readiness missing");
} catch (error) {
const failures: unknown[] = [];
try {
await cleanup.stop();
} catch (cleanupError) {
failures.push(cleanupError);
}
// Read after termination so the redirected descriptor has flushed its final diagnostics.
failures.unshift(new Error(
`${error instanceof Error ? error.message : String(error)}; child stderr: ${childStderr(stderrPath)}`,
{ cause: error },
));
throw failures.length === 1
? failures[0]
: new AggregateError(failures, "child readiness and cleanup failed");
}
return {
process: processHandle,
base: "http://127.0.0.1:" + port,
drain,
stop: cleanup.stop,
};
}
async function stopChild(child: Child): Promise<void> {
await child.stop();
}
type Observers = { stop: () => Promise<void> };
function observers(
pid: number,
run: string,
log: Log,
phase: () => string,
): Observers {
throwIfInterrupted();
let stopped = false;
const origin = performance.now();
let sampleNumber = 0;
let previousCpu = process.cpuUsage();
const parent = setInterval(() => {
const actual = performance.now();
const memory = process.memoryUsage();
const cpu = process.cpuUsage(previousCpu);
previousCpu = process.cpuUsage();
const scheduled = origin + sampleNumber * 200;
log.add({
type: "parent-sample",
run,
phase: phase(),
rss: memory.rss,
cpuUser: cpu.user,
cpuSystem: cpu.system,
scheduled,
actual,
latenessMs: actual - scheduled,
});
sampleNumber++;
}, 200);
const ps = (async () => {
while (!stopped) {
const child = Bun.spawn(["ps", "-o", "rss=", "-p", String(pid)], {
stdout: "pipe",
});
const text = await new Response(child.stdout).text();
await child.exited;
log.add({
type: "ps-rss",
run,
phase: phase(),
rss: Number(text.trim()) * 1024,
});
// This local wait must remain cleanable even after the session AbortSignal fires.
await Bun.sleep(1_000);
}
})();
const cleanup = resources.register(`observers ${run}`, async () => {
stopped = true;
clearInterval(parent);
await ps;
});
return { stop: cleanup.stop };
}
function combinedFailure(message: string, errors: unknown[]): unknown | undefined {
if (errors.length === 0) return undefined;
if (errors.length === 1) return errors[0];
return new AggregateError(errors, message);
}
async function execute(root: string, log: Log, run: Run): Promise<void> {
const dir = create(root, join(root, "runs", run.id), true);
run.series = join(dir, "child.jsonl");
let phase = "startup";
let upstream: Fixture | undefined;
let measured: Child | undefined;
let watch: Observers | undefined;
const errors: unknown[] = [];
try {
upstream = fixture(log, run.id);
measured = await startChild(run.condition, upstream.url, dir, run.sampler);
watch = observers(measured.process.pid, run.id, log, () => phase);
log.add({
type: "run-start",
run: run.id,
condition: run.condition,
kind: run.kind,
sampler: run.sampler,
host: host(),
clients: 3,
turns: 10,
events: EVENTS,
eventBytes: EVENT_BYTES,
waveMs: WAVE_MS,
readMs: READ_MS,
});
phase = "warm";
const warmWall = Date.now();
const warm = performance.now();
log.add({ type: "warm-start", run: run.id });
await pause(WARM);
const warmActualMs = performance.now() - warm;
const warmWallActualMs = Date.now() - warmWall;
const warmExitCode = measured.process.exitCode;
log.add({
type: "warm-end",
run: run.id,
actualMs: warmActualMs,
wallActualMs: warmWallActualMs,
exitCodeAtGate: warmExitCode,
});
if (warmExitCode !== null) {
throw new Error(`child exited during warm: exit code ${warmExitCode}`);
}
if (warmActualMs < WARM) {
throw new Error(`warm duration invalid: ${warmActualMs}ms < ${WARM}ms`);
}
if (run.kind === "workload") {
phase = "workload";
await workload(measured.base, run.id, log);
phase = "settle";
const start = performance.now();
for (const seconds of SETTLE) {
await pause(Math.max(0, start + seconds * 1_000 - performance.now()));
log.add({ type: "settle", run: run.id, seconds });
}
} else {
phase = "observation";
const observationWall = Date.now();
const start = performance.now();
log.add({ type: "observation-start", run: run.id });
await pause(OBSERVE);
const observationActualMs = performance.now() - start;
log.add({
type: "observation-end",
run: run.id,
actualMs: observationActualMs,
wallActualMs: Date.now() - observationWall,
});
if (observationActualMs < OBSERVE) {
throw new Error(
`observation duration invalid: ${observationActualMs}ms < ${OBSERVE}ms`,
);
}
log.add({
type: "client-cadence",
run: run.id,
chunks: 0,
bytes: 0,
meanGapMs: null,
});
}
if (measured.process.exitCode !== null) throw new Error("child exited");
} catch (error) {
errors.push(error);
}
// Cleanup steps are independent: every later resource is attempted even if an earlier one fails.
if (watch) {
try {
await watch.stop();
} catch (error) {
errors.push(error);
}
}
if (measured) {
try {
await stopChild(measured);
} catch (error) {
errors.push(error);
}
}
if (upstream) {
try {
await upstream.stop();
} catch (error) {
errors.push(error);
}
}
try {
log.add({
type: "run-end",
run: run.id,
exitCode: measured?.process.exitCode ?? null,
});
} catch (error) {
errors.push(error);
}
const failure = combinedFailure(`run ${run.id} failed`, errors);
if (failure) throw failure;
}
function rows(path: string): Row[] {
return readFileSync(path, "utf8")
.split(/\r?\n/)
.filter(Boolean)
.map((line, index) => {
try {
return JSON.parse(line) as Row;
} catch (error) {
throw new Error(`malformed JSONL line ${index + 1}: ${String(error)}`);
}
});
}
const med = (values: number[]): number => {
const sorted = [...values].sort((left, right) => left - right);
const middle = Math.floor(sorted.length / 2);
if (!sorted.length) throw new Error("empty median");
return sorted.length % 2
? sorted[middle]!
: (sorted[middle - 1]! + sorted[middle]!) / 2;
};
// Ordinary least squares must centre on arithmetic means. Median centring would
// silently corrupt the sampler budget, no-load envelope, and retention verdict.
function slope(values: Array<{ x: number; y: number }>): number {
if (values.length < 2) return 0;
const meanX = values.reduce((sum, point) => sum + point.x, 0) / values.length;
const meanY = values.reduce((sum, point) => sum + point.y, 0) / values.length;
const numerator = values.reduce(
(sum, point) => sum + (point.x - meanX) * (point.y - meanY),
0,
);
const denominator = values.reduce(
(sum, point) => sum + (point.x - meanX) ** 2,
0,
);
return denominator ? numerator / denominator : 0;
}
/**
* Calibration and controls establish all later budgets and envelopes, so sampler
* degradation in any sampler-on run must invalidate the session immediately.
*/
function assertSamplerIntegrity(run: Run): void {
const self = rows(run.series);
if (self.length < 2) throw new Error(`sampler empty: ${run.id}`);
const late = self.map(row => Number(row.latenessMs)).sort((left, right) => left - right);
const p99 = late[Math.min(late.length - 1, Math.floor(late.length * 0.99))]!;
if (p99 > 200) {
throw new Error(`sampler p99 lateness ${Math.round(p99)}ms: ${run.id}`);
}
for (let index = 1; index < self.length; index++) {
if (Number(self[index]!.wallMs) - Number(self[index - 1]!.wallMs) > 1_000) {
throw new Error(`sampler gap >1s: ${run.id}`);
}
}
}
function calibrationVerdict(all: Row[], runs: Run[]) {
if (runs.some((run, index) => run.sampler !== ORDER[index])) {
throw new Error("calibration order");
}
runs.filter(run => run.sampler).forEach(assertSamplerIntegrity);
const stat = (run: Run) => {
const samples = all
.filter(row => (
row.run === run.id
&& row.type === "ps-rss"
&& row.phase === "observation"
))
.map(row => ({ x: row.wallMs, y: Number(row.rss) }));
// Derive the floor from OBSERVE rather than hard-coding 590: the `ps` observer
// ticks once per second, and allowing ~2% slack absorbs scheduler jitter without
// accepting a truncated run. A hard-coded count silently becomes wrong the moment
// the observation window changes.
const expected = Math.floor((OBSERVE / 1_000) * 0.98);
if (samples.length < expected) {
throw new Error(`calibration incomplete: ${samples.length} < ${expected} ps samples`);
}
return {
final: samples.at(-1)!.y,
peak: Math.max(...samples.map(sample => sample.y)),
slope: slope(samples) * 60_000 / MiB,
};
};
for (const run of runs.filter(candidate => candidate.sampler)) {
const self = rows(run.series);
const osSamples = all.filter(row => row.run === run.id && row.type === "ps-rss");
let cursor = 0;
let bad = 0;