Open History to see the last commit
1#!/usr/bin/env node
2// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalJsonInEffect:off - leases go through mobile-behavior's Promise-based pool helpers.
3/**
4 * Measures the mobile app like client-metrics measures the web one: thread switches, tabs, a pull
5 * request, typing and scrolling on a Simlock iOS simulator, through mobile:behavior's server,
6 * Metro and probe. See docs/internals/16_performance-regressions.md#mobile-switch-metrics.
7 */
8import * as NodeFSP from "node:fs/promises";
9import * as NodePath from "node:path";
10import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
11import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
12import * as NodeServices from "@effect/platform-node/NodeServices";
13import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
14import * as Console from "effect/Console";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as FileSystem from "effect/FileSystem";
18import * as Option from "effect/Option";
19import * as Schema from "effect/Schema";
20import { Argument, Command, Flag } from "effect/cli";
21import { ChildProcessSpawner } from "effect/process";
22
23import {
24 leaseAndInstall,
25 openPool,
26 releaseOnCrash,
27 renewWhileRunning,
28 type PoolAccess,
29} from "../../mobile-behavior/pool.ts";
30import { reachableHost, startSession, type Build } from "../../mobile-behavior/session.ts";
31import type { Device as PoolDevice } from "../../mobile-e2e/device.ts";
32import { CASE_NAMES, CASES, type CaseContext, type CaseName, type Fixtures } from "./cases.ts";
33import {
34 flatten,
35 MobileMetrics,
36 PROBE_KEYS,
37 summaryTable,
38 WORKLOAD_KEYS,
39 workloadDifferences,
40 type Memory,
41 type Run,
42 type SoakSample,
43 type Step,
44} from "./report.ts";
45import { run } from "../../scenarios/shell.ts";
46import { DIFF_FILES, pullRequestDetail, sourceFile } from "../core/fixture.ts";
47import { serveFakeGitHub, type FakeGitHub } from "../core/forge.ts";
48import { compareSeries, Floors, noiseOfSeries } from "../core/report.ts";
49import { machineLoad, MetricsError, output, runAbRounds } from "../core/run.ts";
50
51const REPO_ROOT = NodePath.resolve(import.meta.dirname, "../../..");
52const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
53const decodeMetrics = Schema.decodeUnknownEffect(Schema.fromJsonString(MobileMetrics));
54const encodeMetrics = Schema.encodeEffect(fromJsonStringPretty(MobileMetrics));
55const decodeFloors = Schema.decodeUnknownEffect(Schema.fromJsonString(Floors));
56const encodeFloors = Schema.encodeEffect(fromJsonStringPretty(Floors));
57
58const log = (message: string) => Console.error(`[mobile-metrics] ${message}`);
59
60/** The scratch repository on a branch changing many files, with an open PR on the fake GitHub. */
61const prepareBenchProject = (forge: FakeGitHub) =>
62 Effect.fn("mobileMetrics.prepareProject")(function* (workspace: string) {
63 const fs = yield* FileSystem.FileSystem;
64 const git = (args: ReadonlyArray<string>) => run("git", args, { cwd: workspace });
65 const author = ["-c", "user.email=bench@t3.codes", "-c", "user.name=bench"];
66 yield* git(["branch", "-M", "main"]);
67 yield* fs.makeDirectory(NodePath.join(workspace, "src"), { recursive: true });
68 for (let index = 0; index < DIFF_FILES; index++)
69 yield* fs.writeFileString(
70 NodePath.join(workspace, `src/module${index}.ts`),
71 sourceFile(index, "before"),
72 );
73 yield* git(["add", "."]);
74 yield* git([...author, "commit", "-qm", "modules"]);
75 // The feature branch commits these, so its diff against main is the pull request's weight.
76 for (let index = 0; index < DIFF_FILES; index++)
77 yield* fs.writeFileString(
78 NodePath.join(workspace, `src/module${index}.ts`),
79 sourceFile(index, "after"),
80 );
81 yield* forge.setupProject(workspace);
82 });
83
84/** The app process's memory from agent-device, in MB; its field differs by platform. */
85const processMemory = Effect.fn("mobileMetrics.processMemory")(function* (
86 device: CaseContext["device"],
87 raw: string,
88) {
89 const out = yield* device.run(["perf", "memory", "sample", "--json"]).pipe(Effect.option);
90 if (Option.isNone(out)) return null;
91 yield* Effect.promise(() => NodeFSP.writeFile(raw, out.value));
92 const memory = (
93 JSON.parse(out.value) as { data?: { metrics?: { memory?: Record<string, unknown> } } }
94 ).data?.metrics?.memory;
95 if (!memory || memory.available === false) return null;
96 const field =
97 ["physFootprintKb", "footprintKb", "totalPssKb", "residentMemoryKb", "totalRssKb"].find(
98 (key) => typeof memory[key] === "number",
99 ) ?? Object.keys(memory).find((key) => /Kb$/.test(key) && typeof memory[key] === "number");
100 return field ? Math.round(((memory[field] as number) / 1024) * 10) / 10 : null;
101});
102
103const memorySample = Effect.fn("mobileMetrics.memory")(function* (
104 device: CaseContext["device"],
105 label: string,
106 out: string,
107) {
108 const heap = yield* device.evaluate("__t3Behavior.heap()").pipe(
109 Effect.map((value) => {
110 // Older probes return the byte count itself.
111 if (typeof value === "number") return value;
112 const parsed = JSON.parse(String(value)) as { bytes: number | null };
113 return parsed.bytes;
114 }),
115 Effect.orElseSucceed(() => null),
116 );
117 const sample: Memory = {
118 label,
119 heapMB: typeof heap === "number" ? Math.round((heap / 1_048_576) * 10) / 10 : null,
120 processMB: yield* processMemory(device, NodePath.join(out, `memory-${label}.json`)),
121 };
122 return sample;
123});
124
125interface MeasureOptions {
126 readonly checkout: string;
127 readonly out: string;
128 readonly access: PoolAccess;
129 readonly deviceSession: string;
130 readonly cases: ReadonlyArray<CaseName>;
131 readonly rounds: number;
132 readonly longTurns: number;
133 readonly renders: boolean;
134 readonly host: string;
135 readonly soak: number;
136 readonly build: Build;
137}
138
139/** The cases `--soak` repeats: thread switches, the flow whose memory matters most. */
140const SOAK_CASES = ["switch-short", "switch-long"] as const satisfies ReadonlyArray<CaseName>;
141
142/** One app launch on a checkout's Metro: seed, pair, run every case `rounds` times. */
143const measureOnce = Effect.fn("mobileMetrics.measureOnce")(function* (options: MeasureOptions) {
144 yield* Effect.promise(() => NodeFSP.mkdir(options.out, { recursive: true }));
145 const forge = yield* serveFakeGitHub({ detail: pullRequestDetail() });
146 const fs = yield* FileSystem.FileSystem;
147 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
148 const session = yield* startSession({
149 out: options.out,
150 host: options.host,
151 agentDevice: options.access.pool.agentDevice,
152 deviceConfig: options.access.config,
153 deviceSession: options.deviceSession,
154 device: "",
155 deviceName: "",
156 // A leased simulator is wiped on release; anything saved on it is a previous run's.
157 forgetOtherEnvironments: true,
158 longTurns: options.longTurns,
159 checkout: options.checkout,
160 metroEnv: options.renders ? { EXPO_PUBLIC_T3_RENDER_COUNTER: "1" } : {},
161 build: options.build,
162 environment: {
163 serverEnv: forge.env,
164 prepareWorkspace: (workspace) =>
165 prepareBenchProject(forge)(workspace).pipe(
166 Effect.provideService(FileSystem.FileSystem, fs),
167 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
168 ),
169 },
170 });
171 const { env, device } = session;
172 const short = yield* env.launch("Bench short", "Hi. [[eval:reply]]");
173 yield* env.settled(short);
174 // A side chat people open holds a message; an empty one shows a placeholder, not a timeline.
175 const sideChat = yield* env.forkSideChat(short, "Bench side chat");
176 yield* env.send(sideChat, "Hi from the side. [[eval:reply]]");
177 yield* env.settled(sideChat);
178 const fixtures: Fixtures = {
179 sideChat: { id: sideChat, title: "Bench side chat" },
180 short: { id: short, title: "Bench short" },
181 long: { id: session.longThread, title: session.longTitle },
182 };
183 const supported = yield* device
184 .evaluate("typeof __t3Behavior.perfStart")
185 .pipe(Effect.orElseSucceed(() => "undefined"));
186 if (supported !== "function") {
187 const reason = "this checkout's behavior probe has no perf window";
188 return {
189 steps: [],
190 memory: [],
191 skipped: options.cases.map((name) => ({ case: name, reason })),
192 } satisfies Run;
193 }
194 yield* Effect.sleep("3 seconds");
195 const memory: Memory[] = [yield* memorySample(device, "launch", options.out)];
196 const steps: Step[] = [];
197 const skipped: Array<{ case: string; reason: string }> = [];
198 const visited = new Set<string>();
199 for (let round = 1; round <= options.rounds; round++) {
200 for (const name of options.cases) {
201 const ctx: CaseContext = { session, device, fixtures, round, visited };
202 const result = yield* CASES[name](ctx).pipe(
203 Effect.map((measured) => ({ measured })),
204 Effect.catch((error) => Effect.succeed({ error: error.message })),
205 );
206 if ("error" in result) {
207 yield* log(`${name} round ${round}: ${result.error}`);
208 // What was on screen, so a selector that missed can be fixed from the labels.
209 const labels = yield* device.nodes.pipe(
210 Effect.map((nodes) =>
211 nodes.flatMap((node) =>
212 node.label ? [`${node.kind ?? node.type}: ${node.label}`] : [],
213 ),
214 ),
215 Effect.orElseSucceed(() => []),
216 );
217 yield* Effect.promise(() =>
218 NodeFSP.writeFile(
219 NodePath.join(options.out, `${name}-r${round}-screen.txt`),
220 labels.join("\n"),
221 ),
222 );
223 skipped.push({ case: name, reason: result.error.slice(0, 300) });
224 // A case that failed midway can leave a menu or another tab up; start the next from Home.
225 yield* device.reload(session.seeded).pipe(Effect.ignore);
226 } else {
227 steps.push(...result.measured);
228 for (const step of result.measured)
229 yield* log(
230 `${name} ${step.step} r${round}: content ${step.contentMs ?? "–"} settled ${step.settledMs ?? "–"} commits ${step.commits}`,
231 );
232 }
233 }
234 }
235 memory.push(yield* memorySample(device, "after-cases", options.out));
236 const soak: SoakSample[] = [];
237 const sample = Effect.fn("mobileMetrics.soakSample")(function* (iteration: number, name: string) {
238 const at = yield* memorySample(device, `soak-${iteration}-${name}`, options.out);
239 soak.push({ iteration, case: name, heapMB: at.heapMB, processMB: at.processMB });
240 // What the app retains, so heap growth can be traced to atoms or mounted components.
241 const retention = yield* device
242 .evaluate("__t3Behavior.retention()")
243 .pipe(Effect.orElseSucceed(() => null));
244 if (typeof retention === "string")
245 yield* Effect.promise(() =>
246 NodeFSP.appendFile(
247 NodePath.join(options.out, "soak-retention.ndjson"),
248 `${JSON.stringify({ iteration, case: name, heapMB: at.heapMB, ...JSON.parse(retention) })}\n`,
249 ),
250 );
251 yield* log(`soak ${iteration} ${name}: heap ${at.heapMB} MB, process ${at.processMB} MB`);
252 });
253 if (options.soak > 0) yield* sample(0, "start");
254 for (let iteration = 1; iteration <= options.soak; iteration++) {
255 for (const name of SOAK_CASES) {
256 const ctx: CaseContext = {
257 session,
258 device,
259 fixtures,
260 round: options.rounds + iteration,
261 visited,
262 };
263 const ran = yield* CASES[name](ctx).pipe(
264 Effect.as(true),
265 Effect.catch((error) =>
266 log(`soak ${iteration} ${name}: ${error.message}`).pipe(Effect.as(false)),
267 ),
268 );
269 if (!ran) yield* device.reload(session.seeded).pipe(Effect.ignore);
270 yield* sample(iteration, name);
271 }
272 }
273 return {
274 steps,
275 memory,
276 ...(soak.length ? { soak } : {}),
277 ...(skipped.length ? { skipped } : {}),
278 } satisfies Run;
279}, Effect.scoped);
280
281/** Leases the device for a command, keeps the lease alive, and releases it at the end. */
282const withLease = Effect.fn("mobileMetrics.withLease")(function* <A, E, R>(
283 out: string,
284 deviceName: string,
285 use: (access: PoolAccess, device: PoolDevice) => Effect.Effect<A, E, R>,
286) {
287 const runId = DateTime.formatIso(yield* DateTime.now).replaceAll(/[:.]/g, "-");
288 return yield* Effect.acquireUseRelease(
289 Effect.promise(async () => {
290 await NodeFSP.mkdir(out, { recursive: true });
291 const access = await openPool(REPO_ROOT, out);
292 let device: PoolDevice | null = null;
293 try {
294 device = await leaseAndInstall(
295 {
296 id: "metrics",
297 platform: "ios",
298 device: deviceName,
299 form: "phone",
300 appearance: "light",
301 },
302 access.pool,
303 `metrics-${runId}`,
304 (message) => process.stderr.write(`[mobile-metrics] ${message}\n`),
305 );
306 const renewing = renewWhileRunning(access, device.session);
307 const crashing = releaseOnCrash(device, access);
308 return {
309 access,
310 device,
311 stop: () => {
312 renewing();
313 crashing();
314 },
315 };
316 } catch (error) {
317 await device?.release();
318 await access.close();
319 throw error;
320 }
321 }),
322 ({ access, device }) => use(access, device),
323 ({ access, device, stop }) =>
324 Effect.promise(async () => {
325 stop();
326 await device.release();
327 await access.close();
328 }),
329 );
330});
331
332const metaFor = Effect.fn("mobileMetrics.metaFor")(function* (
333 checkout: string,
334 workload: {
335 readonly cases: ReadonlyArray<CaseName>;
336 readonly rounds: number;
337 readonly longTurns: number;
338 readonly renders: boolean;
339 readonly device: string;
340 readonly build: Build;
341 },
342) {
343 return {
344 commit: Option.getOrNull(yield* output("git", ["rev-parse", "--short=12", "HEAD"], checkout)),
345 device: workload.device,
346 platform: "ios-simulator",
347 build: workload.build === "release" ? "release" : "development",
348 cases: workload.cases.join(","),
349 rounds: workload.rounds,
350 longTurns: workload.longTurns,
351 renders: workload.renders,
352 loadBefore: yield* machineLoad,
353 measuredAt: DateTime.formatIso(yield* DateTime.now),
354 };
355});
356
357const writeMetrics = Effect.fn("mobileMetrics.write")(function* (
358 file: string,
359 metrics: MobileMetrics,
360) {
361 const fs = yield* FileSystem.FileSystem;
362 yield* fs.writeFileString(`${file}.tmp`, `${yield* encodeMetrics(metrics)}\n`);
363 yield* fs.rename(`${file}.tmp`, file);
364});
365
366const readMetrics = Effect.fn("mobileMetrics.read")(function* (file: string) {
367 const fs = yield* FileSystem.FileSystem;
368 return yield* fs.readFileString(file).pipe(Effect.flatMap(decodeMetrics));
369});
370
371const readFloors = Effect.fn("mobileMetrics.readFloors")(function* (file: Option.Option<string>) {
372 const fs = yield* FileSystem.FileSystem;
373 if (Option.isNone(file)) return undefined;
374 return yield* fs.readFileString(file.value).pipe(Effect.flatMap(decodeFloors));
375});
376
377/** Prints the comparison and sets exit code 1 when a metric got worse. */
378const report = Effect.fn("mobileMetrics.report")(function* (
379 before: MobileMetrics,
380 after: MobileMetrics,
381 threshold: number,
382 floors: Floors | undefined,
383) {
384 const workload = workloadDifferences(before, after);
385 if (workload.differ.length > 0)
386 return yield* new MetricsError({
387 message: `the files ran different workloads (${workload.differ.join("; ")}); rerun one side with the other's settings`,
388 });
389 const { table, regressed, improved, noisy, compared } = compareSeries(
390 flatten(before),
391 flatten(after),
392 [
393 "### Mobile metrics (lower is better)",
394 "",
395 `before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs), ${before.meta.device}, ${before.meta.build} build${floors ? `, floors calibrated on ${floors.platform}` : ""}`,
396 ],
397 threshold,
398 floors,
399 );
400 yield* Console.log(table);
401 if (before.meta.renders !== after.meta.renders)
402 yield* Console.error(
403 "Warning: one side counted renders, which slows commits; compare like with like",
404 );
405 if (compared === 0) return yield* new MetricsError({ message: "the two files share no metric" });
406 if (noisy.length)
407 yield* Console.error(
408 `Moved, but not gated (too noisy, or one run a side): ${noisy.join(", ")}`,
409 );
410 if (improved.length) yield* Console.error(`Better: ${improved.join(", ")}`);
411 if (regressed.length === 0) return;
412 yield* Console.error(`Worse: ${regressed.join(", ")}`);
413 yield* Effect.sync(() => {
414 process.exitCode = 1;
415 });
416});
417
418/** The render counter reads React's development-only fiber fields. */
419const checkBuild = (input: { readonly renders: boolean; readonly build: Build }) =>
420 input.renders && input.build === "release"
421 ? Effect.fail(new MetricsError({ message: "--renders needs --build dev" }))
422 : Effect.void;
423
424const casesOf = (list: string) => {
425 const named = list
426 .split(",")
427 .map((entry) => entry.trim())
428 .filter(Boolean);
429 if (named.length === 0) return Effect.succeed(CASE_NAMES);
430 if (named.includes("switches"))
431 named.splice(named.indexOf("switches"), 1, "switch-short", "switch-long", "switch-working");
432 const unknown = named.filter((entry) => !(CASE_NAMES as ReadonlyArray<string>).includes(entry));
433 return unknown.length
434 ? Effect.fail(
435 new MetricsError({
436 message: `unknown cases: ${unknown.join(", ")}; choose from switches, ${CASE_NAMES.join(", ")}`,
437 }),
438 )
439 : Effect.succeed(CASE_NAMES.filter((name) => named.includes(name)));
440};
441
442const measureFlags = {
443 device: Flag.String("device").pipe(
444 Flag.withDescription("Simlock iOS model to lease; compare only runs on one model."),
445 Flag.withDefault("iPhone 18 Pro"),
446 ),
447 rounds: Flag.Int("rounds").pipe(
448 Flag.withSchema(PositiveInt),
449 Flag.withDescription(
450 "Rounds over every case per app launch; a switch's first round is its first visit.",
451 ),
452 Flag.withDefault(3),
453 ),
454 longTurns: Flag.Int("long-turns").pipe(
455 Flag.withSchema(PositiveInt),
456 Flag.withDescription("Turns in the long settled thread."),
457 Flag.withDefault(40),
458 ),
459 cases: Flag.String("cases").pipe(
460 Flag.withDescription(
461 `Cases, comma separated: switches, ${CASE_NAMES.join(", ")}. Default: all.`,
462 ),
463 Flag.withDefault(""),
464 ),
465 renders: Flag.Boolean("renders").pipe(
466 Flag.withDescription(
467 "Count component renders and their causes per step with the render counter. It slows commits; compare like with like.",
468 ),
469 Flag.withDefault(false),
470 ),
471 build: Flag.Literals("build", ["dev", "release"]).pipe(
472 Flag.withDescription(
473 "dev runs the development bundle; release runs the production bundle as Hermes bytecode on the same dev client (compiling takes a few minutes per launch). Soak in release: dev-build heap grows with dev machinery.",
474 ),
475 Flag.withDefault("dev"),
476 ),
477 soak: Flag.Int("soak").pipe(
478 Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
479 Flag.withDescription(
480 "After the rounds, repeat the switch cases this many times, sampling the Hermes heap and process memory after each, with growth per iteration.",
481 ),
482 Flag.withDefault(0),
483 ),
484 host: Flag.String("host").pipe(
485 Flag.withDescription(
486 "Address the simulator reaches this machine on; defaults to the tailnet IP.",
487 ),
488 Flag.optional,
489 ),
490};
491const thresholdFlag = Flag.Int("threshold").pipe(
492 Flag.withDescription("Percent a metric must move, past its floor, to count."),
493 Flag.withDefault(10),
494);
495const floorsFlag = Flag.String("floors").pipe(
496 Flag.withDescription("Floors file from `noise --out`."),
497 Flag.optional,
498);
499
500const runCommand = Command.make(
501 "run",
502 {
503 ...measureFlags,
504 out: Flag.String("out").pipe(
505 Flag.withDescription("JSON file to write."),
506 Flag.withDefault("mobile-metrics.json"),
507 ),
508 checkout: Flag.String("checkout").pipe(
509 Flag.withDescription("Checkout whose app Metro serves, with dependencies installed."),
510 Flag.withDefault(REPO_ROOT),
511 ),
512 },
513 Effect.fn("mobileMetrics.run")(function* (input) {
514 const checkout = NodePath.resolve(input.checkout);
515 const out = NodePath.resolve(input.out);
516 const cases = yield* casesOf(input.cases);
517 yield* checkBuild(input);
518 const meta = yield* metaFor(checkout, { ...input, cases });
519 const artifacts = `${out.replace(/\.json$/, "")}-artifacts`;
520 const measured = yield* withLease(artifacts, input.device, (access, device) =>
521 Effect.gen(function* () {
522 if (checkout !== REPO_ROOT) yield* Effect.promise(() => device.install(checkout));
523 return yield* measureOnce({
524 checkout,
525 out: NodePath.join(artifacts, "run-1"),
526 access,
527 deviceSession: device.session,
528 cases,
529 rounds: input.rounds,
530 longTurns: input.longTurns,
531 renders: input.renders,
532 soak: input.soak,
533 build: input.build,
534 host: Option.getOrElse(input.host, reachableHost),
535 });
536 }),
537 );
538 const metrics: MobileMetrics = {
539 meta: { ...meta, loadAfter: yield* machineLoad },
540 runs: [measured],
541 };
542 yield* writeMetrics(out, metrics);
543 yield* Console.log(summaryTable(metrics));
544 }),
545).pipe(
546 Command.withDescription(
547 "Lease a Simlock iOS simulator, seed a server (replayed threads, a 40-file branch with a PR on a fake GitHub), open a checkout's dev client and measure each case.",
548 ),
549);
550
551const abCommand = Command.make(
552 "ab",
553 {
554 ...measureFlags,
555 checkoutA: Argument.String("checkout-a").pipe(Argument.withDescription("Baseline checkout.")),
556 checkoutB: Argument.String("checkout-b").pipe(Argument.withDescription("Candidate checkout.")),
557 abRounds: Flag.Int("ab-rounds").pipe(
558 Flag.withSchema(PositiveInt),
559 Flag.withDescription(
560 "App launches a side; each round runs A and B once, alternating which goes first.",
561 ),
562 Flag.withDefault(2),
563 ),
564 outDir: Flag.String("out-dir").pipe(Flag.withDefault("mobile-metrics-ab")),
565 threshold: thresholdFlag,
566 floors: floorsFlag,
567 },
568 Effect.fn("mobileMetrics.ab")(function* (input) {
569 const outDir = NodePath.resolve(input.outDir);
570 const cases = yield* casesOf(input.cases);
571 yield* checkBuild(input);
572 const floors = yield* readFloors(input.floors);
573 const checkouts = [
574 NodePath.resolve(input.checkoutA),
575 NodePath.resolve(input.checkoutB),
576 ] as const;
577 const metas = [
578 yield* metaFor(checkouts[0], { ...input, cases }),
579 yield* metaFor(checkouts[1], { ...input, cases }),
580 ] as const;
581 const host = Option.getOrElse(input.host, reachableHost);
582 let launches = 0;
583 const saved = yield* withLease(outDir, input.device, (access, device) =>
584 runAbRounds({
585 rounds: input.abRounds,
586 outDir,
587 runSide: Effect.fn("mobileMetrics.abSide")(function* (side: 0 | 1) {
588 // Each side's dev client, from the cache when both share a native fingerprint.
589 yield* Effect.promise(() => device.install(checkouts[side]));
590 return yield* measureOnce({
591 checkout: checkouts[side],
592 out: NodePath.join(outDir, `${side === 0 ? "a" : "b"}-${++launches}`),
593 access,
594 deviceSession: device.session,
595 cases,
596 rounds: input.rounds,
597 longTurns: input.longTurns,
598 renders: input.renders,
599 soak: input.soak,
600 build: input.build,
601 host,
602 });
603 }),
604 save: Effect.fn("mobileMetrics.abSave")(function* (side: 0 | 1, runs: ReadonlyArray<Run>) {
605 const file: MobileMetrics = {
606 meta: { ...metas[side], loadAfter: yield* machineLoad },
607 runs: [...runs],
608 };
609 yield* writeMetrics(NodePath.join(outDir, side === 0 ? "a.json" : "b.json"), file);
610 return file;
611 }),
612 }),
613 );
614 yield* report(saved[0], saved[1], input.threshold, floors);
615 }),
616).pipe(
617 Command.withDescription(
618 "Run two checkouts alternately (A B, then B A) on one leased simulator and compare them. The harness, server and seed come from this script; each side's Metro serves its own app.",
619 ),
620);
621
622const compareCommand = Command.make(
623 "compare",
624 {
625 before: Argument.String("before").pipe(Argument.withDescription("Baseline JSON.")),
626 after: Argument.String("after").pipe(Argument.withDescription("Candidate JSON.")),
627 threshold: thresholdFlag,
628 floors: floorsFlag,
629 },
630 Effect.fn("mobileMetrics.compare")(function* (input) {
631 yield* report(
632 yield* readMetrics(input.before),
633 yield* readMetrics(input.after),
634 input.threshold,
635 yield* readFloors(input.floors),
636 );
637 }),
638).pipe(
639 Command.withDescription(
640 "Markdown table of two result files, gated like client-metrics: each app launch's median is one sample, and a metric counts only with 2+ launches a side when its bootstrap interval clears the threshold and floor. Exits 1 on a regression.",
641 ),
642);
643
644const noiseCommand = Command.make(
645 "noise",
646 {
647 dirs: Argument.String("dir").pipe(
648 Argument.withDescription("An `ab` out dir of one checkout against itself."),
649 Argument.atLeast(1),
650 ),
651 out: Flag.String("out").pipe(Flag.withDescription("Floors file to write."), Flag.optional),
652 },
653 Effect.fn("mobileMetrics.noise")(function* (input) {
654 const fs = yield* FileSystem.FileSystem;
655 const pairs = yield* Effect.forEach(input.dirs, (dir) =>
656 Effect.gen(function* () {
657 const a = yield* readMetrics(NodePath.join(dir, "a.json"));
658 const b = yield* readMetrics(NodePath.join(dir, "b.json"));
659 const settings = workloadDifferences(a, b, [...WORKLOAD_KEYS, ...PROBE_KEYS]).differ;
660 if (a.meta.commit !== b.meta.commit || settings.length > 0)
661 return yield* new MetricsError({
662 message: `${dir}: floors need one commit against itself with one set of settings`,
663 });
664 return [flatten(a), flatten(b)] as const;
665 }),
666 );
667 const { floors, table } = noiseOfSeries(pairs, "ios-simulator");
668 yield* Console.log(table);
669 if (Option.isSome(input.out))
670 yield* fs.writeFileString(input.out.value, `${yield* encodeFloors(floors)}\n`);
671 }),
672).pipe(Command.withDescription("Each metric's A/A spread and a floor for `compare --floors`."));
673
674const summaryCommand = Command.make(
675 "summary",
676 { file: Argument.String("file").pipe(Argument.withDescription("A result JSON.")) },
677 Effect.fn("mobileMetrics.summary")(function* (input) {
678 yield* Console.log(summaryTable(yield* readMetrics(input.file)));
679 }),
680).pipe(Command.withDescription("Print a result file's tables."));
681
682const command = Command.make("mobile-metrics").pipe(
683 Command.withDescription(
684 `Measure the iOS app on a Simlock simulator with mobile:behavior's server, Metro and behavior probe. Needs SIMLOCK_AGENT_DEVICE_URL and AGENT_DEVICE_DAEMON_AUTH_TOKEN.
685
686Cases (real taps, swipes and typing through agent-device):
687 switch-short, switch-long Tap a Home row: tap to the frame showing the thread's rows.
688 switch-working A thread streaming a reply, opened twice; each round starts and stops its own.
689 tabs PRs, Usage, then Chats in the tab bar.
690 pull-request The PR list, then the branch PR (40 files, long body, comments; fake GitHub).
691 issues The issues list, which shares the PR tab's slot.
692 diff A thread's git menu, then Review changes on the 40-file branch.
693 side-chat A thread's side chat chip.
694 type Keys typed into a composer, each to its next JS frame.
695 scroll-long Drag up through the long timeline: JS and UI frame drops.
696
697\`--build dev\` (the default) runs the development bundle: render and commit counts and A/B
698differences are representative, absolute times and heap growth are not. \`--build release\` runs
699the production bundle as Hermes bytecode: real times and a flat heap, but no commit ms, no
700\`--renders\`, and minified component names in soak retention. Soak in release. Trust a change
701only from \`ab\` on one simulator model and build.`,
702 ),
703 Command.withSubcommands([runCommand, abCommand, compareCommand, noiseCommand, summaryCommand]),
704);
705
706if (import.meta.main) {
707 Command.run(command, { version: "0.0.0" }).pipe(
708 Effect.provide([NodeServices.layer, NodeCrypto.layer]),
709 Effect.catchTags({
710 MetricsError: (error) =>
711 Console.error(`mobile-metrics: ${error.message}`).pipe(
712 Effect.andThen(
713 Effect.sync(() => {
714 process.exitCode = 1;
715 }),
716 ),
717 ),
718 }),
719 NodeRuntime.runMain,
720 );
721}