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

mobile-metrics.ts

821 lines31.9 KB

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