ckb-cycle-tools 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,100 @@
1
+ import { type Folded } from "./flame.js";
2
+ import type { MockTransaction } from "./mock.js";
3
+ import { type DebuggerOutput } from "./replay.js";
4
+ /** A spawned script's own profile (`--vm-id`), as `flameTransaction` and `profileSpawns` record it. */
5
+ export interface FlameChild {
6
+ /** Its VM id (`--vm-id`), and the VM that spawned it (0: the group's script). */
7
+ vm: number;
8
+ parent: number;
9
+ /** Where its binary came from, as ckb-debugger prints it: `cell_dep[1][0..11552]`. */
10
+ locator: string;
11
+ /** The data hash of the binary it ran, when the locator names a cell of the transaction. */
12
+ codeHash?: string;
13
+ /** A name for it: `scriptNames` by its data hash (or its cell's type hash). */
14
+ name?: string;
15
+ /** The unstripped build its frames were named with (`--vm-symbols`): `bins` or `vmSymbols` by its data or type hash. */
16
+ symbols?: string;
17
+ /** Why no symbols build was used although one was given (it is not the same code). */
18
+ symbolsWarning?: string;
19
+ /** The replay's exit code (-1 with `error` when the VM stopped it), and its own cycle count, which counts loading the binary. */
20
+ result: number;
21
+ error?: string;
22
+ cycles: bigint;
23
+ /** Its folded stacks: its own instructions only. */
24
+ folded: Folded;
25
+ /** Set when the replay could not be run or read: no result, no profile. */
26
+ failed?: string;
27
+ }
28
+ /** The most spawned scripts profiled one by one per group; each is three runs of the whole group. */
29
+ export declare const MAX_CHILD_PROFILES = 16;
30
+ /**
31
+ * Shown when a spawned script's own replay ends non-zero but its group
32
+ * verified: typically a ckb-script-ipc server (`run_server`) that waits for
33
+ * another request after the spawning script has finished, and fails on the
34
+ * closed pipe. Its cycles up to there are the ones the group paid for.
35
+ */
36
+ export declare const SERVER_EXIT_NOTE = "the group verified: a spawned script whose own replay ends non-zero is usually a server (ckb-script-ipc run_server) still waiting after the spawning script finished; its profile up to there is complete";
37
+ /** Whether a child gets SERVER_EXIT_NOTE: its own replay ended non-zero (or the VM stopped it) while its group verified. */
38
+ export declare const serverExit: (c: Pick<FlameChild, "result" | "error" | "failed">, groupOk: boolean) => boolean;
39
+ /** Why a debugger (its `--version` line) older than CHILD_PROFILE_DEBUGGER profiles no spawned script on its own. */
40
+ export declare const olderDebuggerNote: (version: string) => string;
41
+ /** What profileChildren needs to replay a group's spawned VMs. */
42
+ export interface ChildContext {
43
+ /** The debugger's `--version` line: below 1.1.2 nothing is replayed. */
44
+ version: string;
45
+ /** The group's arguments (`debuggerArgs`, plus `--bin` if the root ran a build): each replay adds `--vm-id N`. */
46
+ base: string[];
47
+ /** Where the replay of VM `vm` writes its folded stacks (`--flamegraph-output`); `readFile` reads them there. */
48
+ out: (vm: number) => string;
49
+ exec: (args: string[]) => Promise<DebuggerOutput>;
50
+ readFile: (path: string) => Promise<string>;
51
+ /** The mock transaction the group runs in, and the group's cells: to find the binary each VM ran. */
52
+ mock: MockTransaction;
53
+ group: {
54
+ inputs: number[];
55
+ outputs: number[];
56
+ };
57
+ /** Names by `codeHash:hashType` (lowercase): a child is named by its data hash, or its cell's type hash. */
58
+ names?: Record<string, string>;
59
+ /** An unstripped build for a data or type hash, to name a child's frames (`--vm-symbols`), with how to read it. */
60
+ symbolsOf?: (hash: string) => string | undefined;
61
+ readBinary?: (path: string) => Promise<Uint8Array>;
62
+ namesOf?: (bin: string) => Promise<Map<bigint, string>>;
63
+ }
64
+ /**
65
+ * One `--vm-id` flamegraph replay per spawned VM of a group (generation 0, at
66
+ * most MAX_CHILD_PROFILES), from the spawn tree in the root's flamegraph run.
67
+ * Nothing is thrown: a replay that fails is a child with `failed`, and a
68
+ * debugger that cannot replay a child at all is a note.
69
+ */
70
+ export declare function profileChildren(rootOutput: string, ctx: ChildContext): Promise<{
71
+ children?: FlameChild[];
72
+ childrenNote?: string;
73
+ }>;
74
+ /** A group split by script: what profileSpawns returns for a group whose script spawned others. */
75
+ export interface SpawnSplit {
76
+ /** How many scripts the group's script spawned (`spawnedScripts`). */
77
+ spawned: number;
78
+ /** The spawning script's own profiled frames (VM 0 alone): loading it and the spawned scripts are in none of them. */
79
+ own: Folded;
80
+ /** Each spawned script's own profile (profileChildren), and why some have none. */
81
+ children?: FlameChild[];
82
+ childrenNote?: string;
83
+ }
84
+ /**
85
+ * Splits one group by script, with any ckb-debugger 1.1.2 or later: a
86
+ * flamegraph run of the group (the spawning script's own frames, and the
87
+ * spawn tree), then, if its script spawned others, one `--vm-id` replay per
88
+ * spawned VM (profileChildren). Undefined when it spawned nothing. The
89
+ * group's cycles are not read here: they come from its plain run
90
+ * (replayGroups), the total these frames sit inside. Throws (so the caller
91
+ * can say the spawn check failed, rather than that nothing was spawned) when
92
+ * the flamegraph run cannot be run or did not finish: no result lines, a
93
+ * crash (the WebAssembly build trapped, exit -1), a kill, cut-off output, or,
94
+ * for a script that spawned, no "Actual run" of its own. Also throws, before
95
+ * running anything, for a debugger older than 1.1.2 (olderDebuggerNote):
96
+ * 0.200.1, for one, has no flamegraph mode at all, so a spawn could not even
97
+ * be seen. A script that rejects is not a failed check: its run still shows
98
+ * what it spawned.
99
+ */
100
+ export declare function profileSpawns(ctx: ChildContext): Promise<SpawnSplit | undefined>;
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Per-child profiles of a script that spawns others (CKB2023 `spawn`): one
3
+ * `--vm-id` flamegraph replay per spawned VM, with ckb-debugger 1.1.2 or
4
+ * later. Plain TypeScript with no Node built-ins, like replay.ts and flame.ts,
5
+ * so the CLI (native debugger, profile.ts) and the web page (WebAssembly
6
+ * build, wasm.ts) split a group the same way and say the same thing about it.
7
+ */
8
+ import { sameCode } from "./elf.js";
9
+ import { nameAddresses, parseFolded, profilesChildren, spawnedScripts, spawnTree, CHILD_PROFILE_DEBUGGER } from "./flame.js";
10
+ import { parseDebuggerRun } from "./replay.js";
11
+ import { spawnedBinary } from "./spawn.js";
12
+ /** The most spawned scripts profiled one by one per group; each is three runs of the whole group. */
13
+ export const MAX_CHILD_PROFILES = 16;
14
+ /**
15
+ * Shown when a spawned script's own replay ends non-zero but its group
16
+ * verified: typically a ckb-script-ipc server (`run_server`) that waits for
17
+ * another request after the spawning script has finished, and fails on the
18
+ * closed pipe. Its cycles up to there are the ones the group paid for.
19
+ */
20
+ export const SERVER_EXIT_NOTE = "the group verified: a spawned script whose own replay ends non-zero is usually a server (ckb-script-ipc run_server) still waiting after the spawning script finished; its profile up to there is complete";
21
+ /** Whether a child gets SERVER_EXIT_NOTE: its own replay ended non-zero (or the VM stopped it) while its group verified. */
22
+ export const serverExit = (c, groupOk) => groupOk && !c.failed && (c.error !== undefined || c.result !== 0);
23
+ /** Why a debugger (its `--version` line) older than CHILD_PROFILE_DEBUGGER profiles no spawned script on its own. */
24
+ export const olderDebuggerNote = (version) => `${version} cannot profile a spawned script on its own (ckb-debugger ${CHILD_PROFILE_DEBUGGER} or later can)`;
25
+ /**
26
+ * One `--vm-id` flamegraph replay per spawned VM of a group (generation 0, at
27
+ * most MAX_CHILD_PROFILES), from the spawn tree in the root's flamegraph run.
28
+ * Nothing is thrown: a replay that fails is a child with `failed`, and a
29
+ * debugger that cannot replay a child at all is a note.
30
+ */
31
+ export async function profileChildren(rootOutput, ctx) {
32
+ if (!profilesChildren(ctx.version))
33
+ return { childrenNote: `${olderDebuggerNote(ctx.version)}: only the spawning script is profiled` };
34
+ const tree = spawnTree(rootOutput);
35
+ const spawned = tree.filter((v) => v.vm !== 0 && v.generation === 0);
36
+ const notes = [];
37
+ const execd = new Set(tree.filter((v) => v.generation > 0).map((v) => v.vm)).size;
38
+ if (execd)
39
+ notes.push(`${execd} VM${execd === 1 ? "" : "s"} ran exec: ckb-debugger replays only a VM's first program, so code reached by exec is not profiled`);
40
+ if (spawned.length > MAX_CHILD_PROFILES)
41
+ notes.push(`${spawned.length} spawned scripts: the first ${MAX_CHILD_PROFILES} are profiled`);
42
+ if (!spawned.length && !notes.length)
43
+ notes.push("the spawn tree could not be read: spawned scripts not profiled");
44
+ const names = ctx.names ?? {};
45
+ const children = [];
46
+ for (const v of spawned.slice(0, MAX_CHILD_PROFILES)) {
47
+ const binary = spawnedBinary(ctx.mock, v, ctx.group);
48
+ const hashes = binary ? [binary.dataHash, ...(binary.typeHash ? [binary.typeHash] : [])] : [];
49
+ const name = binary &&
50
+ (["data2", "data1", "data"].map((t) => names[`${binary.dataHash}:${t}`]).find(Boolean) ??
51
+ (binary.typeHash ? names[`${binary.typeHash}:type`] : undefined));
52
+ let symbols = ctx.symbolsOf ? hashes.map(ctx.symbolsOf).find(Boolean) : undefined;
53
+ let symbolsWarning;
54
+ if (symbols && binary) {
55
+ const same = ctx.readBinary
56
+ ? await ctx.readBinary(symbols).then((b) => sameCode(b, binary.data), () => undefined)
57
+ : undefined;
58
+ if (same !== true) {
59
+ symbolsWarning =
60
+ same === false
61
+ ? `${symbols} is not the same code as the binary VM ${v.vm} ran: its frames are left unnamed`
62
+ : `${symbols} could not be read as an ELF: VM ${v.vm}'s frames are left unnamed`;
63
+ symbols = undefined;
64
+ }
65
+ }
66
+ const child = {
67
+ vm: v.vm,
68
+ parent: v.parent,
69
+ locator: v.locator,
70
+ ...(binary && { codeHash: binary.dataHash }),
71
+ ...(name && { name }),
72
+ ...(symbols && { symbols }),
73
+ ...(symbolsWarning && { symbolsWarning }),
74
+ result: -1,
75
+ cycles: 0n,
76
+ folded: new Map(),
77
+ };
78
+ try {
79
+ const out = ctx.out(v.vm);
80
+ const run = await ctx.exec([
81
+ ...ctx.base,
82
+ "--vm-id",
83
+ String(v.vm),
84
+ ...(symbols ? ["--vm-symbols", symbols] : []),
85
+ "--enable-flamegraph",
86
+ "--flamegraph-output",
87
+ out,
88
+ ]);
89
+ if (!/^Actual run: start\s*$/m.test(run.stdout))
90
+ throw new Error(`no replay of VM ${v.vm} in ckb-debugger's output`);
91
+ const parsed = parseDebuggerRun(run);
92
+ child.result = parsed.result;
93
+ if (parsed.error)
94
+ child.error = parsed.error;
95
+ child.cycles = parsed.cycles;
96
+ const fnNames = symbols && ctx.namesOf ? await ctx.namesOf(symbols) : new Map();
97
+ child.folded = nameAddresses(parseFolded(await ctx.readFile(out).catch(() => "")), fnNames);
98
+ }
99
+ catch (e) {
100
+ child.failed = `the replay of VM ${v.vm} failed: ${e instanceof Error ? e.message : String(e)}`;
101
+ }
102
+ children.push(child);
103
+ }
104
+ return { ...(children.length && { children }), ...(notes.length && { childrenNote: notes.join("; ") }) };
105
+ }
106
+ /**
107
+ * Splits one group by script, with any ckb-debugger 1.1.2 or later: a
108
+ * flamegraph run of the group (the spawning script's own frames, and the
109
+ * spawn tree), then, if its script spawned others, one `--vm-id` replay per
110
+ * spawned VM (profileChildren). Undefined when it spawned nothing. The
111
+ * group's cycles are not read here: they come from its plain run
112
+ * (replayGroups), the total these frames sit inside. Throws (so the caller
113
+ * can say the spawn check failed, rather than that nothing was spawned) when
114
+ * the flamegraph run cannot be run or did not finish: no result lines, a
115
+ * crash (the WebAssembly build trapped, exit -1), a kill, cut-off output, or,
116
+ * for a script that spawned, no "Actual run" of its own. Also throws, before
117
+ * running anything, for a debugger older than 1.1.2 (olderDebuggerNote):
118
+ * 0.200.1, for one, has no flamegraph mode at all, so a spawn could not even
119
+ * be seen. A script that rejects is not a failed check: its run still shows
120
+ * what it spawned.
121
+ */
122
+ export async function profileSpawns(ctx) {
123
+ if (!profilesChildren(ctx.version))
124
+ throw new Error(olderDebuggerNote(ctx.version));
125
+ const rootOut = ctx.out(0);
126
+ const run = await ctx.exec([...ctx.base, "--enable-flamegraph", "--flamegraph-output", rootOut]);
127
+ const failed = (why) => new Error(`the spawn check (a profiled run of the group) failed: ${why}`);
128
+ // parseDebuggerRun turns a crash, a kill or cut-off output into an error (and throws on no result lines).
129
+ let parsed;
130
+ try {
131
+ parsed = parseDebuggerRun(run);
132
+ }
133
+ catch (e) {
134
+ throw failed(e instanceof Error ? e.message : String(e));
135
+ }
136
+ if (run.failure || run.exitCode === null || run.exitCode === -1)
137
+ throw failed(parsed.error ?? "the run did not finish");
138
+ const spawned = spawnedScripts(run.stdout);
139
+ if (!spawned)
140
+ return undefined;
141
+ if (!/^Actual run: start\s*$/m.test(run.stdout))
142
+ throw failed("no profiled run of the spawning script in ckb-debugger's output");
143
+ const own = parseFolded(await ctx.readFile(rootOut).catch(() => ""));
144
+ const { children, childrenNote } = await profileChildren(run.stdout, ctx);
145
+ return { spawned, own, ...(children && { children }), ...(childrenNote && { childrenNote }) };
146
+ }
package/dist/cli.js CHANGED
@@ -7,6 +7,7 @@ import { buildMockTransaction, httpRpc, mockFromTransaction } from "./mock.js";
7
7
  import { flameTree, foldedTotal, formatFolded, functionCosts, renderFlameSvg } from "./flame.js";
8
8
  import { flameTransaction, parseNames, profileTransaction, readTransactionJson } from "./profile.js";
9
9
  import { PUBLIC_RPC, sumLines } from "./replay.js";
10
+ import { serverExit, SERVER_EXIT_NOTE } from "./children.js";
10
11
  import { formatReport, runReport } from "./report.js";
11
12
  import { formatScan, scanTestMocks } from "./scan.js";
12
13
  const USAGE = `usage: ckb-cycles <tx-hash> [--mainnet] [--rpc <url>] [--timeout <s>] [--debugger <path>]
@@ -97,7 +98,10 @@ Exit codes: 0 every script accepts (and the sum matches the node's)
97
98
  one frame: --bin gives an unstripped build of the same code (its
98
99
  cycles are checked against the deployed binary's). The profile
99
100
  leaves out loading the binary, so it is a little under the group's
100
- cycles`;
101
+ cycles. A script that spawns others: with ckb-debugger 1.1.2 or
102
+ later, each spawned script is profiled on its own (--vm-id) into
103
+ <dir>/<selector>.vm<N>.svg and .folded; --bin with the spawned
104
+ binary's data hash names its functions (--vm-symbols)`;
101
105
  const fmt = (n) => n.toLocaleString("en-US");
102
106
  const short = (h, n = 6) => (h.length > 2 * n + 2 ? `${h.slice(0, n + 2)}…${h.slice(-n)}` : h);
103
107
  function table(p) {
@@ -352,7 +356,9 @@ async function flameCommand(args) {
352
356
  out.push(` profiled ${fmt(profiled)} cycles (loading the binary is not profiled)`);
353
357
  if (g.spawned) {
354
358
  const n = g.spawned;
355
- out.push(` spawned ${n} other script${n === 1 ? "" : "s"}: ${n === 1 ? "its" : "their"} cycles are in the ${fmt(g.cycles)}, not in this profile`, " (ckb-debugger profiles only the spawning script; --bin replaces only its binary)");
359
+ out.push(` spawned ${n} other script${n === 1 ? "" : "s"}: ${n === 1 ? "its" : "their"} cycles are in the ${fmt(g.cycles)}, not in this profile`, g.children?.length
360
+ ? " (this profile is the spawning script's own; each spawned script's follows, from a --vm-id replay)"
361
+ : " (ckb-debugger profiles only the spawning script; --bin replaces only its binary)");
356
362
  }
357
363
  out.push(" SELF TOTAL FUNCTION");
358
364
  for (const c of costs.slice(0, top))
@@ -361,11 +367,41 @@ async function flameCommand(args) {
361
367
  await writeFile(`${base}.folded`, formatFolded(g.folded) + "\n");
362
368
  await writeFile(`${base}.svg`, renderFlameSvg(flameTree(g.folded, g.selector), { title: `${g.selector} · ${label}` }));
363
369
  out.push(` → ${base}.svg, ${base}.folded`, "");
370
+ for (const c of g.children ?? [])
371
+ out.push(...(await childOutput(g.selector, c, dir, top, g.result === 0 && !g.error)));
372
+ if (g.childrenNote)
373
+ out.push(` spawned scripts: ${termLine(g.childrenNote)}`, "");
364
374
  }
365
375
  out.push(`${termLine(version)} · CKB-VM v${plan.scriptVersion} for type scripts · ${plan.network} · ${plan.rpcUrl}`);
366
376
  console.log(out.join("\n"));
367
377
  return bad || groups.some((g) => g.result !== 0) ? 1 : 0;
368
378
  }
379
+ /** One spawned script's profile under its group in `flame`, and its own .folded and .svg (`<selector>.vm<N>`). */
380
+ async function childOutput(selector, c, dir, top, groupOk) {
381
+ const label = termLine(c.name ?? (c.codeHash ? short(c.codeHash) : c.locator));
382
+ const head = ` spawned vm ${c.vm} ${label} (${termLine(c.locator)}${c.parent ? `, spawned by vm ${c.parent}` : ""})`;
383
+ if (c.failed)
384
+ return [`${head} not profiled`, ` ${termLine(c.failed)}`, ""];
385
+ const out = [`${head} ${c.error ? "error" : c.result === 0 ? "ok" : `exit ${c.result}`}`];
386
+ if (serverExit(c, groupOk))
387
+ out.push(` ${SERVER_EXIT_NOTE}`);
388
+ if (c.symbolsWarning)
389
+ out.push(` ${termLine(c.symbolsWarning)}`);
390
+ if (!c.folded.size)
391
+ return [...out, " no profile written", ""];
392
+ const costs = functionCosts(c.folded);
393
+ if (!c.symbols)
394
+ out.push(` no symbols build for it: pass --bin ${c.codeHash ?? "<data-hash>"}=<unstripped build> to name its functions`);
395
+ out.push(` profiled ${fmt(foldedTotal(c.folded))} cycles in its own frames (inside the group's total; loading it and the spawn are not profiled)`);
396
+ out.push(" SELF TOTAL FUNCTION");
397
+ for (const f of costs.slice(0, top))
398
+ out.push(` ${fmt(f.self).padStart(10)} ${fmt(f.total).padStart(10)} ${termLine(f.name)}`);
399
+ const base = join(dir, `${selector}.vm${c.vm}`);
400
+ await writeFile(`${base}.folded`, formatFolded(c.folded) + "\n");
401
+ await writeFile(`${base}.svg`, renderFlameSvg(flameTree(c.folded, `vm ${c.vm}`), { title: `${selector} · vm ${c.vm} · ${label}` }));
402
+ out.push(` → ${base}.svg, ${base}.folded`, "");
403
+ return out;
404
+ }
369
405
  async function main() {
370
406
  const [command, ...rest] = process.argv.slice(2);
371
407
  if (command === "report")
package/dist/diff.d.ts CHANGED
@@ -163,6 +163,36 @@ export interface GroupResult {
163
163
  spawned?: number;
164
164
  /** With `spawned`: the cycles the function profile covers (the root script's own run). */
165
165
  profiled?: number;
166
+ /**
167
+ * With `spawned` (added after 1.3.0, ckb-debugger 1.1.2 and later): each
168
+ * spawned script's own profile, from a `--vm-id` replay of it. Its numbers
169
+ * are profiled frames, not a split of `cycles`: they leave out loading the
170
+ * binary and what the spawn costs the parent. `cycles` stays the total.
171
+ */
172
+ children?: ChildResult[];
173
+ /** With `spawned`: why some or all spawned scripts have no profile of their own (an older ckb-debugger, a replay that failed). */
174
+ childrenNote?: string;
175
+ }
176
+ /** A spawned script's own profile, in a report (added after 1.3.0). */
177
+ export interface ChildResult {
178
+ /** Its VM id (ckb-debugger's `--vm-id`): what a child is matched by across reports. */
179
+ vm: number;
180
+ /** The VM that spawned it: 0 is the group's own script. */
181
+ parent: number;
182
+ /** A name for the binary it ran (the config's binary name), or its short data hash. */
183
+ script: string;
184
+ /** The data hash of the binary it ran. */
185
+ codeHash?: string;
186
+ /** The replay's exit code: -1 with `error` when the VM stopped it. Absent with `failed`. */
187
+ result?: number;
188
+ error?: string;
189
+ /** The cycles in its profiled frames. Absent with `failed`. */
190
+ profiled?: number;
191
+ /** Its costliest functions, heaviest self first (at most FUNCTION_LIMIT), when its binary has a symbols build. */
192
+ functions?: FunctionResult[];
193
+ functionsWarning?: string;
194
+ /** Why it has no profile: the replay could not be run or read. */
195
+ failed?: string;
166
196
  }
167
197
  export interface FunctionResult {
168
198
  name: string;
@@ -185,6 +215,29 @@ export interface FunctionDelta {
185
215
  /** Set when both sides are known. */
186
216
  delta?: number;
187
217
  }
218
+ /** A spawned script on both sides of a diff, matched by VM id. Its numbers are profiled frames. */
219
+ export interface ChildDelta {
220
+ vm: number;
221
+ /** The head's name for it (the base's when it is gone). */
222
+ script: string;
223
+ /** Each side's result (`ok`, `exit 9`, `not profiled`) and profiled cycles; a side is absent when it had no such VM. */
224
+ base?: {
225
+ result: string;
226
+ profiled?: number;
227
+ };
228
+ head?: {
229
+ result: string;
230
+ profiled?: number;
231
+ };
232
+ /** Set when both sides have profiled cycles. */
233
+ delta?: number;
234
+ /** Its profiled cycles or result differ, or it is on one side only. */
235
+ changed: boolean;
236
+ /** Its functions whose self cycles changed, when the head recorded them. */
237
+ functions?: FunctionDelta[];
238
+ /** Why the head has no functions or no profile for it. */
239
+ note?: string;
240
+ }
188
241
  /** `error`: the head could not run the scenario. `base-error`: the base could not, so nothing was compared. */
189
242
  export type RowKind = "same" | "changed" | "result" | "new" | "removed" | "error" | "base-error";
190
243
  export interface DiffRow {
@@ -216,6 +269,10 @@ export interface DiffRow {
216
269
  spawned?: number;
217
270
  /** With `spawned`: the cycles the head's function profile covers. */
218
271
  profiled?: number;
272
+ /** With `spawned`: each spawned script's profile on both sides, by VM id (head reports from 1.1.2 debuggers, added after 1.3.0). */
273
+ children?: ChildDelta[];
274
+ /** The head's reason some spawned scripts have no profile of their own. */
275
+ childrenNote?: string;
219
276
  /** Why the base side of this group was not compared (its binary was not in the base checkout, its inputs changed). */
220
277
  notCompared?: string;
221
278
  /** Not compared because the scenario's inputs differ between the two reports' manifests. */
@@ -320,6 +377,12 @@ export declare const unmatchedError: (name: string) => string;
320
377
  */
321
378
  export declare function resultLabel(g: Pick<GroupResult, "result" | "error">): string;
322
379
  export declare function diffReports(base: CycleReport, head: CycleReport, options?: DiffOptions): CycleDiff;
380
+ /**
381
+ * Each spawned script on both sides, by VM id, in VM order. Without base
382
+ * children (an older report, an older debugger) every head child has no base
383
+ * side: what it costs is shown, not a change.
384
+ */
385
+ export declare function childDeltas(base: ChildResult[] | undefined, head: ChildResult[]): ChildDelta[];
323
386
  /**
324
387
  * The functions whose self cycles differ between two lists, largest change
325
388
  * first. One whose other side is not known (see FunctionDelta) is kept, ranked
@@ -369,7 +432,10 @@ export declare function spawnNote(r: {
369
432
  head?: {
370
433
  cycles?: number;
371
434
  };
435
+ children?: unknown[];
372
436
  }): string;
437
+ /** What a spawned script's numbers are, under every list of them. */
438
+ export declare const CHILDREN_FOOTNOTE = "Profiled frames of each spawned script, from a ckb-debugger --vm-id replay of it: they leave out loading its binary and what the spawn costs the parent, so they do not add up to the group's cycles, which stay the total.";
373
439
  /** The hidden marker that identifies the sticky comment, so it is updated instead of duplicated. */
374
440
  export declare const COMMENT_MARKER = "<!-- ckb-cycles-report -->";
375
441
  export interface MarkdownOptions {
package/dist/diff.js CHANGED
@@ -4,6 +4,7 @@
4
4
  *
5
5
  * Pure: no network, no file system.
6
6
  */
7
+ import { asciiFrame } from "./flame.js";
7
8
  /**
8
9
  * A scenario's `overTxLimit`, read defensively (a report file is the PR's):
9
10
  * undefined unless both numbers are there and the sum is over the limit.
@@ -269,15 +270,77 @@ function groupRow(scenario, measured, h, threshold, inputsChanged) {
269
270
  row.spawned = h.spawned;
270
271
  if (h.profiled !== undefined)
271
272
  row.profiled = h.profiled;
273
+ const head = childrenOf(h);
274
+ if (head)
275
+ row.children = childDeltas(childrenOf(b), head);
276
+ if (typeof h.childrenNote === "string" && h.childrenNote)
277
+ row.childrenNote = h.childrenNote;
272
278
  }
273
279
  return row;
274
280
  }
281
+ /** A group's `children`, read defensively (a report file is the PR's): entries without a VM id or a name are dropped. */
282
+ function childrenOf(g) {
283
+ const list = g?.children;
284
+ if (!Array.isArray(list))
285
+ return undefined;
286
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
287
+ return list
288
+ .filter((c) => !!c && typeof c === "object" && Number.isInteger(c.vm) && typeof c.script === "string")
289
+ .map((c) => ({
290
+ vm: c.vm,
291
+ parent: num(c.parent) ?? 0,
292
+ script: c.script,
293
+ ...(num(c.result) !== undefined && { result: num(c.result) }),
294
+ ...(str(c.error) && { error: str(c.error) }),
295
+ ...(num(c.profiled) !== undefined && { profiled: num(c.profiled) }),
296
+ ...(Array.isArray(c.functions) && {
297
+ functions: c.functions.filter((f) => !!f && typeof f === "object" && typeof f.name === "string" && num(f.self) !== undefined),
298
+ }),
299
+ ...(str(c.functionsWarning) && { functionsWarning: str(c.functionsWarning) }),
300
+ ...(str(c.failed) && { failed: str(c.failed) }),
301
+ }));
302
+ }
303
+ const childLabel = (c) => c.failed || c.result === undefined ? "not profiled" : resultLabel({ result: c.result, ...(c.error && { error: c.error }) });
304
+ /**
305
+ * Each spawned script on both sides, by VM id, in VM order. Without base
306
+ * children (an older report, an older debugger) every head child has no base
307
+ * side: what it costs is shown, not a change.
308
+ */
309
+ export function childDeltas(base, head) {
310
+ const vms = [...new Set([...head.map((c) => c.vm), ...(base ?? []).map((c) => c.vm)])].sort((x, y) => x - y);
311
+ return vms.map((vm) => {
312
+ const b = base?.find((c) => c.vm === vm);
313
+ const h = head.find((c) => c.vm === vm);
314
+ const side = (c) => ({ result: childLabel(c), ...(c.profiled !== undefined && !c.failed && { profiled: c.profiled }) });
315
+ const d = {
316
+ vm,
317
+ script: (h ?? b).script,
318
+ ...(b && { base: side(b) }),
319
+ ...(h && { head: side(h) }),
320
+ changed: false,
321
+ };
322
+ if (d.base?.profiled !== undefined && d.head?.profiled !== undefined)
323
+ d.delta = d.head.profiled - d.base.profiled;
324
+ d.changed = base !== undefined && (!b || !h || d.base.result !== d.head.result || (d.delta ?? 0) !== 0);
325
+ if (h?.functions)
326
+ d.functions = functionDeltas(b?.functions, h.functions);
327
+ const note = h?.failed ?? h?.functionsWarning;
328
+ if (note)
329
+ d.note = note;
330
+ return d;
331
+ });
332
+ }
275
333
  /**
276
334
  * The functions whose self cycles differ between two lists, largest change
277
335
  * first. One whose other side is not known (see FunctionDelta) is kept, ranked
278
336
  * by the side that is.
279
337
  */
280
338
  export function functionDeltas(base, head) {
339
+ // A report written by an older ckb-cycle-tools with a newer ckb-debugger can
340
+ // name `[u8; 32]` with a U+037E for the `;`: the same function either way.
341
+ const ascii = (list) => list.map((f) => ({ ...f, name: asciiFrame(f.name) }));
342
+ base = base && ascii(base);
343
+ head = ascii(head);
281
344
  const side = (list, name) => {
282
345
  if (!list)
283
346
  return undefined;
@@ -468,13 +531,53 @@ function functionBlocks(rows) {
468
531
  if (spawn && r.functions && r.kind !== "same") {
469
532
  out.push(`<details><summary>Functions in ${where}: none of its own changed</summary>`, "", md(spawn), "", "</details>", "");
470
533
  }
534
+ out.push(...childBlock(r, where));
471
535
  continue;
472
536
  }
473
537
  const shown = r.functions.slice(0, FUNCTIONS_SHOWN);
474
538
  const more = r.functions.length - shown.length;
475
539
  const n = r.functions.length;
476
540
  out.push(`<details><summary>Functions in ${where}: ${n} function${n === 1 ? "" : "s"} changed</summary>`, "", "| Function | Base self | Head self | Δ |", "|---|---:|---:|---:|", ...shown.map((f) => `| ${md(clipName(f.name))} | ${fnCell(f.base)} | ${fnCell(f.head)} | ${f.delta === undefined ? "" : signed(f.delta)} |`), "", ...(more > 0 ? [`and ${more} more.`, ""] : []), ...(spawn ? [md(spawn), ""] : []), `<sub>Self cycles, from ckb-debugger's profiler with the symbols build; — means not among the ${FUNCTION_LIMIT} costliest (or not recorded).</sub>`, "", "</details>", "");
541
+ out.push(...childBlock(r, where));
542
+ }
543
+ return out;
544
+ }
545
+ /** A folded block per spawning group with child profiles: which spawned script changed, and its functions. */
546
+ function childBlock(r, where) {
547
+ if (r.kind === "same" || (!r.children?.length && !r.childrenNote))
548
+ return [];
549
+ const kids = r.children ?? [];
550
+ const compared = kids.some((c) => c.base);
551
+ const changed = kids.filter((c) => c.changed);
552
+ const summary = !kids.length
553
+ ? "not profiled"
554
+ : !compared
555
+ ? `${kids.length} profiled`
556
+ : changed.length
557
+ ? changed
558
+ .slice(0, 3)
559
+ .map((c) => `vm ${c.vm} ${html(c.script)} ${c.delta !== undefined && c.base && c.head ? signed(c.delta) : !c.base ? "new" : !c.head ? "gone" : html(c.head.result)}`)
560
+ .join(", ") + (changed.length > 3 ? `, and ${changed.length - 3} more` : "")
561
+ : "none changed";
562
+ const out = [`<details><summary>Spawned scripts in ${where}: ${summary}</summary>`, ""];
563
+ if (kids.length) {
564
+ out.push("| VM | Script | Base profiled | Head profiled | Δ |", "|---|---|---:|---:|---:|");
565
+ for (const c of kids) {
566
+ out.push(`| ${c.vm} | ${md(clipName(c.script))} | ${md(childSide(c.base))} | ${md(childSide(c.head))} | ${c.delta === undefined ? "" : signed(c.delta)} |`);
567
+ }
568
+ out.push("");
569
+ }
570
+ for (const c of kids) {
571
+ const fns = (c.functions ?? []).slice(0, FUNCTIONS_SHOWN);
572
+ if (fns.length && (c.changed || !compared)) {
573
+ out.push(`Functions of vm ${c.vm} (${md(clipName(c.script))}):`, "", "| Function | Base self | Head self | Δ |", "|---|---:|---:|---:|", ...fns.map((f) => `| ${md(clipName(f.name))} | ${fnCell(f.base)} | ${fnCell(f.head)} | ${f.delta === undefined ? "" : signed(f.delta)} |`), "");
574
+ }
575
+ if (c.note)
576
+ out.push(`vm ${c.vm}: ${md(c.note)}`, "");
477
577
  }
578
+ if (r.childrenNote)
579
+ out.push(md(r.childrenNote), "");
580
+ out.push(`<sub>${md(CHILDREN_FOOTNOTE)}</sub>`, "", "</details>", "");
478
581
  return out;
479
582
  }
480
583
  const fnCell = (n) => (n === undefined ? "—" : fmt(n));
@@ -482,9 +585,20 @@ const fnCell = (n) => (n === undefined ? "—" : fmt(n));
482
585
  export function spawnNote(r) {
483
586
  const n = r.spawned ?? 0;
484
587
  const covers = r.profiled !== undefined && r.head?.cycles !== undefined ? ` (the profile covers ${fmt(r.profiled)} of its ${fmt(r.head.cycles)} cycles)` : "";
588
+ const own = r.children?.length ? ` ${n === 1 ? "Its" : "Their"} own profile${n === 1 ? " is" : "s are"} listed separately.` : "";
485
589
  return (`This script spawned ${n} other script${n === 1 ? "" : "s"}: ${n === 1 ? "its" : "their"} cycles are in the group's total, ` +
486
- `but not in these functions, which are the spawning script's own${covers}.`);
590
+ `but not in these functions, which are the spawning script's own${covers}.${own}`);
591
+ }
592
+ /** What a spawned script's numbers are, under every list of them. */
593
+ export const CHILDREN_FOOTNOTE = "Profiled frames of each spawned script, from a ckb-debugger --vm-id replay of it: they leave out loading its binary and what the spawn costs the parent, so they do not add up to the group's cycles, which stay the total.";
594
+ const childSide = (s) => !s ? "—" : s.profiled === undefined ? s.result : s.result === "ok" ? fmt(s.profiled) : `${fmt(s.profiled)} (${s.result})`;
595
+ /** `vm 1 (spawn-child): profiled 19,093 → 635,605 (+616,512)`, plain text: the caller cleans it. */
596
+ function childLine(c) {
597
+ const what = !c.base ? `new, profiled ${childSide(c.head)}` : !c.head ? `gone (was ${childSide(c.base)})` : `profiled ${childSide(c.base)} → ${childSide(c.head)}${c.delta ? ` (${signed(c.delta)})` : ""}`;
598
+ return `vm ${c.vm} (${c.script}): ${what}`;
487
599
  }
600
+ /** A spawned script's profile on the head alone (no base children to compare with). */
601
+ const childHeadLine = (c) => `vm ${c.vm} (${c.script}): profiled ${childSide(c.head)}`;
488
602
  /** The hidden marker that identifies the sticky comment, so it is updated instead of duplicated. */
489
603
  export const COMMENT_MARKER = "<!-- ckb-cycles-report -->";
490
604
  /**
@@ -653,6 +767,23 @@ export function formatText(diff) {
653
767
  }
654
768
  else if (r.functions && r.spawned)
655
769
  functions.push(`functions in ${where}: none of its own changed. ${spawnNote(r)}`);
770
+ if (r.children?.length) {
771
+ const compared = r.children.some((c) => c.base);
772
+ const kids = compared ? r.children.filter((c) => c.changed) : r.children;
773
+ if (!kids.length)
774
+ functions.push(` spawned scripts: none changed (profiled frames)`);
775
+ for (const c of kids) {
776
+ const fns = (c.functions ?? [])
777
+ .filter((f) => f.delta !== undefined)
778
+ .slice(0, 3)
779
+ .map((f) => `${termLine(f.name)} ${signed(f.delta)}`);
780
+ functions.push(` spawned ${termLine(compared ? childLine(c) : childHeadLine(c))}${fns.length ? `; ${fns.join(", ")}` : ""}`);
781
+ if (c.note)
782
+ functions.push(` ${termLine(c.note)}`);
783
+ }
784
+ }
785
+ if (r.childrenNote)
786
+ functions.push(` spawned scripts: ${termLine(r.childrenNote)}`);
656
787
  }
657
788
  const errors = [
658
789
  ...(diff.overTxLimit?.length ? overTxLimitBlock(diff.overTxLimit, termLine, "") : []),
package/dist/elf.d.ts CHANGED
@@ -16,3 +16,16 @@ export declare function elfFunctionNames(elf: Uint8Array): Map<bigint, string>;
16
16
  * still a stable name, only a less readable one.
17
17
  */
18
18
  export declare function demangle(name: string): string;
19
+ /**
20
+ * The code a CKB-VM runs from an ELF: the entry point and each executable
21
+ * `PT_LOAD` segment (its address and the bytes the file gives it), in program
22
+ * header order. A build and its stripped copy have the same code; the
23
+ * stripped one only loses sections no segment loads (symbols, debug info).
24
+ * Undefined for anything that is not a 64-bit little-endian ELF with code.
25
+ */
26
+ export declare function elfCode(elf: Uint8Array): Uint8Array | undefined;
27
+ /**
28
+ * Whether two ELFs run the same code (elfCode): an unstripped build and the
29
+ * binary it stands for. Undefined when either is not an ELF this can read.
30
+ */
31
+ export declare function sameCode(a: Uint8Array, b: Uint8Array): boolean | undefined;