Public: anyone can read this; the crew can change it.
A spark profile decodes to a summary: call tree, slowest ticks, per-mod time, GC and memory #18144
Merged 8h 31m ago, live in production
mason/forge:mason/18139-a-spark-profile-decodes-to-a-summary-cal → main 0 commits fork 1 thread · 1 unresolved
4 files
changed +495
−1
scripts/unreached-allow.json +2 −1
scripts/unused-exports-allow.json +1
src/games/spark_profile.ts added +332
| @@ -0,0 +1,332 @@ | ||
| 1 | /** | |
| 2 | * A spark profile decoded to a summary (#18139, step of #18058): the call tree, the slowest ticks, | |
| 3 | * time per mod, GC and memory, the platform and its mod list. Pure: bytes in, plain data out, no | |
| 4 | * dependency (a small protobuf wire reader, below, and node:zlib). A body that is not a profile | |
| 5 | * is a named error (`SparkError`), never a throw: too large, not gzip, truncated, malformed. | |
| 6 | * | |
| 7 | * The field numbers are spark's and sit in `F`, the one table to fix if spark moves one. A field | |
| 8 | * absent from the bytes reads as empty, so a profile from an older spark still decodes to what it | |
| 9 | * holds. | |
| 10 | */ | |
| 11 | import { gunzipSync } from "node:zlib"; | |
| 12 | ||
| 13 | /** | |
| 14 | * The largest body taken (gzipped) and the largest it may expand to: a bomb is refused, not | |
| 15 | * inflated. | |
| 16 | */ | |
| 17 | export const MAX_PACKED = 32 * 1024 * 1024; | |
| 18 | /** | |
| 19 | * Real profiles are a few MB unpacked (a long run on a big modpack is tens); 64 MB leaves room | |
| 20 | * and bounds what one request parses on the single thread: `fields` holds one object per field. | |
| 21 | */ | |
| 22 | export const MAX_UNPACKED = 64 * 1024 * 1024; | |
| 23 | const MAX_DEPTH = 256; | |
| 24 | const MAX_NODES = 2_000_000; | |
| 25 | /** The summary's own bounds: the tree shows this much of itself. */ | |
| 26 | export const TREE_DEPTH = 12; | |
| 27 | export const TREE_WIDTH = 8; | |
| 28 | export const SLOWEST = 10; | |
| 29 | /** | |
| 30 | * Nodes one thread's summary tree may hold: shared nodes are copied when shown, so count the | |
| 31 | * copies. | |
| 32 | */ | |
| 33 | const TREE_NODES = 2_000; | |
| 34 | ||
| 35 | export type SparkErrorName = "too-large" | "not-gzip" | "truncated" | "malformed"; | |
| 36 | export interface SparkError { readonly name: SparkErrorName; readonly message: string } | |
| 37 | ||
| 38 | export interface TreeNode { readonly name: string; readonly ms: number; readonly children: TreeNode[] } | |
| 39 | export interface SlowTick { readonly window: number; readonly msptMax: number; readonly msptMedian: number; readonly tps: number; readonly ticks: number; readonly players: number } | |
| 40 | export interface ModTime { readonly source: string; readonly ms: number; readonly share: number } | |
| 41 | export interface GcRow { readonly name: string; readonly collections: number; readonly avgTimeMs: number; readonly avgFrequencyMs: number } | |
| 42 | export interface Pool { readonly used: number; readonly total: number } | |
| 43 | export interface SparkSummary { | |
| 44 | readonly platform: { readonly type: string; readonly name: string; readonly version: string; readonly minecraft: string }; | |
| 45 | readonly mods: { readonly id: string; readonly name: string; readonly version: string }[]; | |
| 46 | readonly startTime: number; | |
| 47 | readonly endTime: number; | |
| 48 | readonly intervalMicros: number; | |
| 49 | readonly threads: { readonly name: string; readonly ms: number; readonly tree: TreeNode[] }[]; | |
| 50 | readonly slowestTicks: SlowTick[]; | |
| 51 | readonly perMod: ModTime[]; | |
| 52 | readonly gc: GcRow[]; | |
| 53 | readonly memory: { readonly heap: Pool; readonly nonHeap: Pool; readonly physical: Pool }; | |
| 54 | } | |
| 55 | export type SparkResult = { readonly ok: true; readonly summary: SparkSummary } | { readonly ok: false; readonly error: SparkError }; | |
| 56 | ||
| 57 | /** | |
| 58 | * Spark's field numbers, by message, checked one by one against lucko/spark at commit | |
| 59 | * 3e8745a76eaabe9a4f70aad6283876fb518d2ae8, spark-common/src/main/proto/spark/spark.proto and | |
| 60 | * spark_sampler.proto (data version 2), as vendored by the npm packages dsh-spark-insights | |
| 61 | * (pinned to that commit) and spark-profiler-mcp 0.1.1, which agree on every number here. | |
| 62 | * ThreadNode is name 1, children 3, times 4, children_refs 5 (2 is the reserved `time`); | |
| 63 | * SamplerData 6 is `time_windows`, the bare window ids, and 7 the per-window statistics this | |
| 64 | * reads. The test's `spark-v2` fixture is encoded from those | |
| 65 | * files, not from this table, so a wrong number here fails it. `legacy` are the data version 1 | |
| 66 | * fields those files now mark `reserved`: a node's nested children and the single `time`. | |
| 67 | */ | |
| 68 | const F = { | |
| 69 | data: { metadata: 1, threads: 2, classSources: 3, methodSources: 4, windowStats: 7 }, | |
| 70 | meta: { start: 2, interval: 3, platform: 7, platformStats: 8, systemStats: 9, end: 11, sources: 13 }, | |
| 71 | source: { name: 1, version: 2 }, | |
| 72 | platform: { type: 1, name: 2, version: 3, minecraft: 4 }, | |
| 73 | platformStats: { memory: 1, gc: 2 }, | |
| 74 | platformMemory: { heap: 1, nonHeap: 2 }, | |
| 75 | systemStats: { memory: 2 }, | |
| 76 | systemMemory: { physical: 1 }, | |
| 77 | pool: { used: 1, total: 2 }, | |
| 78 | gc: { total: 1, avgTime: 2, avgFrequency: 3 }, | |
| 79 | thread: { name: 1, children: 3, times: 4, refs: 5 }, | |
| 80 | node: { className: 3, methodName: 4, times: 8, refs: 9 }, | |
| 81 | legacy: { threadTime: 2, nodeTime: 1, nodeChildren: 2 }, | |
| 82 | window: { ticks: 1, tps: 4, msptMedian: 5, msptMax: 6, players: 7 }, | |
| 83 | } as const; | |
| 84 | const PLATFORM_TYPES = ["server", "client", "proxy", "application"]; | |
| 85 | ||
| 86 | class Bad extends Error { | |
| 87 | constructor(readonly kind: SparkErrorName, message: string) { super(message); } | |
| 88 | } | |
| 89 | ||
| 90 | interface Field { readonly n: number; readonly t: number; readonly v: number; readonly b: Uint8Array } | |
| 91 | const NONE = new Uint8Array(0); | |
| 92 | const utf8 = new TextDecoder("utf-8", { fatal: true }); | |
| 93 | ||
| 94 | /** | |
| 95 | * Every field of one message. Running off the end is "truncated"; a wire type that does not exist | |
| 96 | * is "malformed". | |
| 97 | */ | |
| 98 | function fields(buf: Uint8Array): Field[] { | |
| 99 | const out: Field[] = []; | |
| 100 | let i = 0; | |
| 101 | const varint = (): number => { | |
| 102 | let r = 0; | |
| 103 | for (let shift = 0; shift < 70; shift += 7) { | |
| 104 | if (i >= buf.length) throw new Bad("truncated", "the profile ends inside a number"); | |
| 105 | const byte = buf[i++]!; | |
| 106 | r += (byte & 0x7f) * 2 ** shift; | |
| 107 | if (!(byte & 0x80)) return r; | |
| 108 | } | |
| 109 | throw new Bad("malformed", "a number is longer than the format allows"); | |
| 110 | }; | |
| 111 | const take = (len: number): Uint8Array => { | |
| 112 | if (len > buf.length - i) throw new Bad("truncated", "the profile ends inside a field"); | |
| 113 | const s = buf.subarray(i, i + len); | |
| 114 | i += len; | |
| 115 | return s; | |
| 116 | }; | |
| 117 | while (i < buf.length) { | |
| 118 | const key = varint(); | |
| 119 | const n = Math.floor(key / 8), t = key % 8; | |
| 120 | if (n < 1) throw new Bad("malformed", "a field has number 0"); | |
| 121 | if (t === 0) out.push({ n, t, v: varint(), b: NONE }); | |
| 122 | else if (t === 1) out.push({ n, t, v: 0, b: take(8) }); | |
| 123 | else if (t === 2) out.push({ n, t, v: 0, b: take(varint()) }); | |
| 124 | else if (t === 5) out.push({ n, t, v: 0, b: take(4) }); | |
| 125 | else throw new Bad("malformed", `a field has wire type ${t}`); | |
| 126 | } | |
| 127 | return out; | |
| 128 | } | |
| 129 | ||
| 130 | const all = (fs: Field[], n: number) => fs.filter((f) => f.n === n); | |
| 131 | const sub = (fs: Field[], n: number): Field[] => { const f = fs.findLast((x) => x.n === n && x.t === 2); return f ? fields(f.b) : []; }; | |
| 132 | const subs = (fs: Field[], n: number): Field[][] => all(fs, n).filter((f) => f.t === 2).map((f) => fields(f.b)); | |
| 133 | const num = (fs: Field[], n: number): number => { const f = fs.findLast((x) => x.n === n); return !f ? 0 : f.t === 0 ? f.v : f.t === 1 ? f64(f.b) : f.t === 5 ? new DataView(f.b.buffer, f.b.byteOffset, 4).getFloat32(0, true) : 0; }; | |
| 134 | const str = (fs: Field[], n: number): string => { | |
| 135 | const f = fs.findLast((x) => x.n === n && x.t === 2); | |
| 136 | if (!f) return ""; | |
| 137 | try { return utf8.decode(f.b); } catch { throw new Bad("malformed", "a text field is not UTF-8"); } | |
| 138 | }; | |
| 139 | function f64(b: Uint8Array): number { return new DataView(b.buffer, b.byteOffset, 8).getFloat64(0, true); } | |
| 140 | /** A repeated double, packed (one length-delimited field) or not. */ | |
| 141 | function doubles(fs: Field[], n: number): number[] { | |
| 142 | const out: number[] = []; | |
| 143 | for (const f of all(fs, n)) { | |
| 144 | if (f.t === 1) out.push(f64(f.b)); | |
| 145 | else if (f.t === 2) { | |
| 146 | if (f.b.length % 8) throw new Bad("malformed", "a list of times is not whole numbers"); | |
| 147 | for (let o = 0; o < f.b.length; o += 8) out.push(f64(f.b.subarray(o, o + 8))); | |
| 148 | } | |
| 149 | } | |
| 150 | return out; | |
| 151 | } | |
| 152 | /** A repeated int32, packed or not. */ | |
| 153 | function ints(fs: Field[], n: number): number[] { | |
| 154 | const out: number[] = []; | |
| 155 | for (const f of all(fs, n)) { | |
| 156 | if (f.t === 0) out.push(f.v); | |
| 157 | else if (f.t === 2) for (const g of fields(packedAsFields(f.b))) out.push(g.v); | |
| 158 | } | |
| 159 | return out; | |
| 160 | } | |
| 161 | /** A packed varint list read as fields of wire type 0, so it shares the one varint reader. */ | |
| 162 | function packedAsFields(b: Uint8Array): Uint8Array { | |
| 163 | const out: number[] = []; | |
| 164 | let at = 0; | |
| 165 | while (at < b.length) { | |
| 166 | out.push(8); // field 1, varint | |
| 167 | let k = at; | |
| 168 | while (k < b.length && b[k]! & 0x80) k++; | |
| 169 | if (k >= b.length) throw new Bad("truncated", "the profile ends inside a list"); | |
| 170 | for (; at <= k; at++) out.push(b[at]!); | |
| 171 | } | |
| 172 | return Uint8Array.from(out); | |
| 173 | } | |
| 174 | /** A `map<string, X>`: each entry is a message with the key in field 1 and the value in 2. */ | |
| 175 | function mapOf(fs: Field[], n: number): [string, Field[]][] { | |
| 176 | return subs(fs, n).map((e) => [str(e, 1), e] as [string, Field[]]); | |
| 177 | } | |
| 178 | ||
| 179 | const sum = (xs: number[]) => xs.reduce((a, b) => a + b, 0); | |
| 180 | const round = (x: number) => Math.round(x * 100) / 100; | |
| 181 | ||
| 182 | interface Raw { readonly name: string; readonly ms: number; readonly source: string; readonly kids: Raw[] } | |
| 183 | ||
| 184 | /** | |
| 185 | * One thread's nodes as a tree: a node's children are its nested ones and those it refers to by | |
| 186 | * index. | |
| 187 | */ | |
| 188 | function threadTree(thread: Field[], classSources: Map<string, string>, methodSources: Map<string, string>, budget: { left: number }): Raw[] { | |
| 189 | const flat = subs(thread, F.thread.children); | |
| 190 | const memo = new Map<number, Raw>(); | |
| 191 | const build = (nodeFields: Field[], depth: number): Raw => { | |
| 192 | if (depth > MAX_DEPTH) throw new Bad("malformed", "the call tree is nested deeper than any real one"); | |
| 193 | if (--budget.left < 0) throw new Bad("too-large", "the call tree has more nodes than a profile of this size can"); | |
| 194 | const cls = str(nodeFields, F.node.className), method = str(nodeFields, F.node.methodName); | |
| 195 | const kids = subs(nodeFields, F.legacy.nodeChildren).map((c) => build(c, depth + 1)); | |
| 196 | for (const r of ints(nodeFields, F.node.refs)) kids.push(ref(r, depth + 1)); | |
| 197 | const source = classSources.get(cls) ?? methodSources.get(`${cls}.${method}`) ?? ""; | |
| 198 | return { name: cls ? `${cls}.${method}` : method, ms: sum(doubles(nodeFields, F.node.times)) || num(nodeFields, F.legacy.nodeTime), source, kids }; | |
| 199 | }; | |
| 200 | const ref = (i: number, depth: number): Raw => { | |
| 201 | const hit = memo.get(i); | |
| 202 | if (hit) return hit; | |
| 203 | const f = flat[i]; | |
| 204 | if (!f) throw new Bad("malformed", "a node refers to one that is not there"); | |
| 205 | const r = build(f, depth); | |
| 206 | memo.set(i, r); | |
| 207 | return r; | |
| 208 | }; | |
| 209 | const rootRefs = ints(thread, F.thread.refs); | |
| 210 | if (rootRefs.length) return rootRefs.map((r) => ref(r, 1)); | |
| 211 | // No root list: the flat table is every node, so the roots are the ones nothing refers to. | |
| 212 | const referred = new Set<number>(); | |
| 213 | const collect = (nodeFields: Field[], depth: number): void => { | |
| 214 | if (depth > MAX_DEPTH) throw new Bad("malformed", "the call tree is nested deeper than any real one"); | |
| 215 | for (const r of ints(nodeFields, F.node.refs)) referred.add(r); | |
| 216 | for (const c of subs(nodeFields, F.legacy.nodeChildren)) collect(c, depth + 1); | |
| 217 | }; | |
| 218 | for (const f of flat) collect(f, 1); | |
| 219 | return flat.flatMap((f, i) => (referred.has(i) ? [] : [ref(i, 1)])); | |
| 220 | } | |
| 221 | ||
| 222 | /** | |
| 223 | * A node shown with its heaviest children; `budget` bounds the copies emitted, shared nodes | |
| 224 | * included. | |
| 225 | */ | |
| 226 | function prune(n: Raw, depth: number, budget: { left: number }): TreeNode { | |
| 227 | budget.left--; | |
| 228 | const kids: TreeNode[] = []; | |
| 229 | if (depth < TREE_DEPTH) { | |
| 230 | for (const k of [...n.kids].sort((a, b) => b.ms - a.ms).slice(0, TREE_WIDTH)) { | |
| 231 | if (budget.left <= 0) break; | |
| 232 | kids.push(prune(k, depth + 1, budget)); | |
| 233 | } | |
| 234 | } | |
| 235 | return { name: n.name, ms: round(n.ms), children: kids }; | |
| 236 | } | |
| 237 | ||
| 238 | /** | |
| 239 | * Self time of each node (its time less its children's), added to its source: the mod or plugin it | |
| 240 | * ran for. | |
| 241 | */ | |
| 242 | function addSelf(n: Raw, into: Map<string, number>, seen: Set<Raw>, depth = 0): void { | |
| 243 | if (depth > MAX_DEPTH || seen.has(n)) return; | |
| 244 | seen.add(n); // a shared node is one node: its time counts once | |
| 245 | const self = Math.max(0, n.ms - sum(n.kids.map((k) => k.ms))); | |
| 246 | if (n.source) into.set(n.source, (into.get(n.source) ?? 0) + self); | |
| 247 | for (const k of n.kids) addSelf(k, into, seen, depth + 1); | |
| 248 | } | |
| 249 | ||
| 250 | const pool = (fs: Field[]): Pool => ({ used: num(fs, F.pool.used), total: num(fs, F.pool.total) }); | |
| 251 | ||
| 252 | function shown(roots: Raw[]): TreeNode[] { | |
| 253 | const budget = { left: TREE_NODES }; | |
| 254 | const out: TreeNode[] = []; | |
| 255 | for (const r of [...roots].sort((a, b) => b.ms - a.ms).slice(0, TREE_WIDTH)) { | |
| 256 | if (budget.left <= 0) break; | |
| 257 | out.push(prune(r, 1, budget)); | |
| 258 | } | |
| 259 | return out; | |
| 260 | } | |
| 261 | ||
| 262 | function summarize(root: Field[]): SparkSummary { | |
| 263 | const meta = sub(root, F.data.metadata); | |
| 264 | const plat = sub(meta, F.meta.platform); | |
| 265 | const pstats = sub(meta, F.meta.platformStats); | |
| 266 | const pmem = sub(pstats, F.platformStats.memory); | |
| 267 | const classSources = new Map(mapOf(root, F.data.classSources).map(([k, e]) => [k, str(e, 2)] as [string, string])); | |
| 268 | const methodSources = new Map(mapOf(root, F.data.methodSources).map(([k, e]) => [k, str(e, 2)] as [string, string])); | |
| 269 | const budget = { left: MAX_NODES }; | |
| 270 | ||
| 271 | const threads = subs(root, F.data.threads).map((t) => { | |
| 272 | const roots = threadTree(t, classSources, methodSources, budget); | |
| 273 | return { name: str(t, F.thread.name), roots, ms: sum(doubles(t, F.thread.times)) || num(t, F.legacy.threadTime) || sum(roots.map((r) => r.ms)) }; | |
| 274 | }); | |
| 275 | const bySource = new Map<string, number>(); | |
| 276 | const seen = new Set<Raw>(); | |
| 277 | for (const t of threads) for (const r of t.roots) addSelf(r, bySource, seen); | |
| 278 | const attributed = sum([...bySource.values()]); | |
| 279 | ||
| 280 | const slowest = mapOf(root, F.data.windowStats) | |
| 281 | .map(([, e]) => { | |
| 282 | const w = sub(e, 2); | |
| 283 | return { window: Number(e.find((f) => f.n === 1)?.v ?? 0), msptMax: round(num(w, F.window.msptMax)), msptMedian: round(num(w, F.window.msptMedian)), tps: round(num(w, F.window.tps)), ticks: num(w, F.window.ticks), players: num(w, F.window.players) }; | |
| 284 | }) | |
| 285 | .sort((a, b) => b.msptMax - a.msptMax) | |
| 286 | .slice(0, SLOWEST); | |
| 287 | ||
| 288 | return { | |
| 289 | platform: { type: PLATFORM_TYPES[num(plat, F.platform.type)] ?? "unknown", name: str(plat, F.platform.name), version: str(plat, F.platform.version), minecraft: str(plat, F.platform.minecraft) }, | |
| 290 | mods: mapOf(meta, F.meta.sources).map(([id, e]) => ({ id, name: str(sub(e, 2), F.source.name), version: str(sub(e, 2), F.source.version) })).sort((a, b) => a.id.localeCompare(b.id)), | |
| 291 | startTime: num(meta, F.meta.start), | |
| 292 | endTime: num(meta, F.meta.end), | |
| 293 | intervalMicros: num(meta, F.meta.interval), | |
| 294 | threads: threads.map((t) => ({ name: t.name, ms: round(t.ms), tree: shown(t.roots) })).sort((a, b) => b.ms - a.ms), | |
| 295 | slowestTicks: slowest, | |
| 296 | perMod: [...bySource].map(([source, ms]) => ({ source, ms: round(ms), share: attributed ? round(ms / attributed) : 0 })).sort((a, b) => b.ms - a.ms), | |
| 297 | gc: mapOf(pstats, F.platformStats.gc).map(([name, e]) => { | |
| 298 | const g = sub(e, 2); | |
| 299 | return { name, collections: num(g, F.gc.total), avgTimeMs: round(num(g, F.gc.avgTime)), avgFrequencyMs: round(num(g, F.gc.avgFrequency)) }; | |
| 300 | }).sort((a, b) => a.name.localeCompare(b.name)), | |
| 301 | memory: { | |
| 302 | heap: pool(sub(pmem, F.platformMemory.heap)), | |
| 303 | nonHeap: pool(sub(pmem, F.platformMemory.nonHeap)), | |
| 304 | physical: pool(sub(sub(sub(meta, F.meta.systemStats), F.systemStats.memory), F.systemMemory.physical)), | |
| 305 | }, | |
| 306 | }; | |
| 307 | } | |
| 308 | ||
| 309 | /** | |
| 310 | * A spark profile (gzipped protobuf, as `/spark profiler` uploads it) as a summary, or the error | |
| 311 | * that names why not. | |
| 312 | */ | |
| 313 | export function decodeSparkProfile(body: Uint8Array): SparkResult { | |
| 314 | const fail = (name: SparkErrorName, message: string): SparkResult => ({ ok: false, error: { name, message } }); | |
| 315 | if (body.length > MAX_PACKED) return fail("too-large", `the body is over ${MAX_PACKED} bytes`); | |
| 316 | if (body.length < 2 || body[0] !== 0x1f || body[1] !== 0x8b) return fail("not-gzip", "the body is not gzip"); | |
| 317 | let raw: Uint8Array; | |
| 318 | try { | |
| 319 | raw = gunzipSync(body, { maxOutputLength: MAX_UNPACKED }); | |
| 320 | } catch (e) { | |
| 321 | const code = (e as { code?: string }).code; | |
| 322 | if (code === "ERR_BUFFER_TOO_LARGE") return fail("too-large", `the profile expands past ${MAX_UNPACKED} bytes`); | |
| 323 | if (code === "Z_BUF_ERROR" || /unexpected end/i.test(String((e as Error).message))) return fail("truncated", "the gzip stream ends early"); | |
| 324 | return fail("malformed", "the gzip stream is damaged"); | |
| 325 | } | |
| 326 | try { | |
| 327 | return { ok: true, summary: summarize(fields(raw)) }; | |
| 328 | } catch (e) { | |
| 329 | if (e instanceof Bad) return fail(e.kind, e.message); | |
| 330 | return fail("malformed", "the profile could not be read"); | |
| 331 | } | |
| 332 | } |
test/games-spark-profile.test.ts added +160
| @@ -0,0 +1,160 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { gzipSync } from "node:zlib"; | |
| 3 | import { decodeSparkProfile, MAX_PACKED, SLOWEST } from "../src/games/spark_profile.ts"; | |
| 4 | ||
| 5 | // A tiny protobuf writer: the fixture is built here so the test says what it holds. | |
| 6 | const varint = (n: number): number[] => { const o: number[] = []; while (n > 127) { o.push((n % 128) | 128); n = Math.floor(n / 128); } o.push(n); return o; }; | |
| 7 | const key = (n: number, t: number) => varint(n * 8 + t); | |
| 8 | const vint = (n: number, v: number) => [...key(n, 0), ...varint(v)]; | |
| 9 | const bytes = (n: number, b: number[] | Uint8Array) => [...key(n, 2), ...varint(b.length), ...b]; | |
| 10 | const text = (n: number, s: string) => bytes(n, new TextEncoder().encode(s)); | |
| 11 | const dbl = (v: number) => [...new Uint8Array(new Float64Array([v]).buffer)]; | |
| 12 | const packedDoubles = (n: number, vs: number[]) => bytes(n, vs.flatMap(dbl)); | |
| 13 | const entry = (n: number, k: number[], v: number[]) => bytes(n, [...k, ...v]); | |
| 14 | const strEntry = (n: number, k: string, v: number[]) => entry(n, text(1, k), bytes(2, v)); | |
| 15 | /** | |
| 16 | * A data version 1 node: one `time` (field 1) and its children nested (field 2), both now reserved. | |
| 17 | */ | |
| 18 | const node = (cls: string, method: string, ms: number, kids: number[][] = []) => [...text(3, cls), ...text(4, method), ...key(1, 1), ...dbl(ms), ...kids.flatMap((k) => bytes(2, k))]; | |
| 19 | const pool = (used: number, total: number) => [...vint(1, used), ...vint(2, total)]; | |
| 20 | ||
| 21 | function fixture(): Uint8Array { | |
| 22 | const tree = node("net.minecraft.server.MinecraftServer", "tick", 100, [ | |
| 23 | node("net.minecraft.world.level.Level", "tickEntities", 60, [node("com.example.lithium.Algo", "run", 40)]), | |
| 24 | node("com.example.chunky.Task", "step", 25), | |
| 25 | ]); | |
| 26 | const thread = [...text(1, "Server thread"), ...key(2, 1), ...dbl(100), ...bytes(3, tree)]; | |
| 27 | const win = (ticks: number, max: number) => [...vint(1, ticks), ...[...key(6, 1), ...dbl(max)], ...[...key(5, 1), ...dbl(max / 2)], ...[...key(4, 1), ...dbl(20)]]; | |
| 28 | const meta = [ | |
| 29 | ...vint(2, 1_700_000_000_000), ...vint(11, 1_700_000_060_000), | |
| 30 | ...bytes(7, [...vint(1, 0), ...text(2, "Fabric"), ...text(3, "0.15"), ...text(4, "1.21")]), | |
| 31 | ...bytes(8, [...bytes(1, [...bytes(1, pool(512, 1024)), ...bytes(2, pool(64, 128))]), ...strEntry(2, "G1 Young", [...vint(1, 12), ...[...key(2, 1), ...dbl(7.5)], ...[...key(3, 1), ...dbl(900)]])]), | |
| 32 | ...bytes(9, bytes(2, bytes(1, pool(4000, 8000)))), | |
| 33 | ...strEntry(13, "lithium", [...text(1, "Lithium"), ...text(2, "0.12")]), | |
| 34 | ...strEntry(13, "chunky", [...text(1, "Chunky"), ...text(2, "1.4")]), | |
| 35 | ]; | |
| 36 | const raw = [ | |
| 37 | ...bytes(1, meta), ...bytes(2, thread), | |
| 38 | ...entry(3, text(1, "com.example.lithium.Algo"), text(2, "lithium")), | |
| 39 | ...entry(3, text(1, "com.example.chunky.Task"), text(2, "chunky")), | |
| 40 | ...entry(7, vint(1, 1), bytes(2, win(1200, 80))), | |
| 41 | ...entry(7, vint(1, 2), bytes(2, win(1200, 300))), | |
| 42 | ]; | |
| 43 | return gzipSync(Uint8Array.from(raw)); | |
| 44 | } | |
| 45 | ||
| 46 | test("a data version 1 profile (nested nodes, one time each) decodes to its summary", () => { | |
| 47 | const r = decodeSparkProfile(fixture()); | |
| 48 | if (!r.ok) throw new Error(r.error.message); | |
| 49 | const s = r.summary; | |
| 50 | expect(s.platform).toEqual({ type: "server", name: "Fabric", version: "0.15", minecraft: "1.21" }); | |
| 51 | expect(s.mods).toEqual([{ id: "chunky", name: "Chunky", version: "1.4" }, { id: "lithium", name: "Lithium", version: "0.12" }]); | |
| 52 | expect(s.endTime - s.startTime).toBe(60_000); | |
| 53 | expect(s.threads[0]!.name).toBe("Server thread"); | |
| 54 | const root = s.threads[0]!.tree[0]!; | |
| 55 | expect(root.name).toBe("net.minecraft.server.MinecraftServer.tick"); | |
| 56 | expect(root.children.map((c) => c.name)).toEqual(["net.minecraft.world.level.Level.tickEntities", "com.example.chunky.Task.step"]); | |
| 57 | expect(root.children[0]!.children[0]!.ms).toBe(40); | |
| 58 | expect(s.slowestTicks.map((t) => t.msptMax)).toEqual([300, 80]); | |
| 59 | expect(s.slowestTicks.length).toBeLessThanOrEqual(SLOWEST); | |
| 60 | expect(s.perMod).toEqual([{ source: "lithium", ms: 40, share: 0.62 }, { source: "chunky", ms: 25, share: 0.38 }]); | |
| 61 | expect(s.gc).toEqual([{ name: "G1 Young", collections: 12, avgTimeMs: 7.5, avgFrequencyMs: 900 }]); | |
| 62 | expect(s.memory).toEqual({ heap: { used: 512, total: 1024 }, nonHeap: { used: 64, total: 128 }, physical: { used: 4000, total: 8000 } }); | |
| 63 | }); | |
| 64 | ||
| 65 | /** | |
| 66 | * A data version 2 profile encoded by protobufjs from spark's own spark.proto and | |
| 67 | * spark_sampler.proto (lucko/spark 3e8745a76eaabe9a4f70aad6283876fb518d2ae8), not from the | |
| 68 | * decoder's table or the writer above: a wrong field number in `F` fails this test. It holds a | |
| 69 | * flat node table with `children_refs`, per-window `times`, two windows, two mods. | |
| 70 | */ | |
| 71 | const SPARK_V2 = "H4sIAAAAAAACA3WRQU7CQBSGaakwTiDUiQk4C8HKRhcTC5gACzMgakLQjSx0WcoIhVJIKai7HsClLtxh4gE8gAuO4BG8iRY6TTCGWcx7mfm/9897A98E2f16+flUU7N0OQVCKHKutWxDx9IRUY8VSSU5tShW8zABI8CVZBegDUBlV0AZCC7UzO1wYnXQNohthZZrl+4sY+aJ1iECHjRLy/OTm+/3V8+kh2HUNJyuMRmgBIw2eLrwyvWSMKJ3J1b/EcVh5NTPwiopoGcRxq+ZPWV2xunaTGvjKs5azCEDw2K6rd05ZLy8JpfBgS9XJMfQ+1XZf9oV9WON1kUhjGs4/bfG/dA228RkU2aSxmJXYgv8zHIMx2BjXsat8DIlWhdErOKUPhwQ9qANRiYjvDlSMTtDJWxPrMC8xClCPSS5ivg9k6Y27ivS2GGjACEcyVLlXweHQgjvw7XWKJgy3oPrzBCfdk4UxHIWeB8KPjb3fIMCPQicVD9p0mLYU4krKjfPVfMWV81tWpR+AbMxh65TAgAA"; | |
| 72 | ||
| 73 | test("a profile encoded from spark's own protos decodes to its summary", () => { | |
| 74 | const r = decodeSparkProfile(Buffer.from(SPARK_V2, "base64")); | |
| 75 | if (!r.ok) throw new Error(r.error.message); | |
| 76 | const s = r.summary; | |
| 77 | expect(s.platform).toEqual({ type: "server", name: "Fabric", version: "0.15", minecraft: "1.21" }); | |
| 78 | expect(s.mods).toEqual([{ id: "chunky", name: "Chunky", version: "1.4" }, { id: "lithium", name: "Lithium", version: "0.12" }]); | |
| 79 | expect([s.startTime, s.endTime, s.intervalMicros]).toEqual([1_700_000_000_000, 1_700_000_060_000, 4000]); | |
| 80 | expect(s.threads.map((t) => [t.name, t.ms])).toEqual([["Server thread", 100]]); | |
| 81 | const root = s.threads[0]!.tree; | |
| 82 | expect(root.map((n) => [n.name, n.ms])).toEqual([["net.minecraft.server.MinecraftServer.tick", 100]]); | |
| 83 | expect(root[0]!.children.map((n) => [n.name, n.ms])).toEqual([["net.minecraft.world.level.Level.tickEntities", 60], ["com.example.chunky.Task.step", 25]]); | |
| 84 | expect(root[0]!.children[0]!.children.map((n) => [n.name, n.ms])).toEqual([["com.example.lithium.Algo.run", 40]]); | |
| 85 | expect(s.slowestTicks).toEqual([ | |
| 86 | { window: 2, msptMax: 300, msptMedian: 150, tps: 19.5, ticks: 1200, players: 4 }, | |
| 87 | { window: 1, msptMax: 80, msptMedian: 40, tps: 20, ticks: 1200, players: 3 }, | |
| 88 | ]); | |
| 89 | expect(s.perMod).toEqual([{ source: "lithium", ms: 40, share: 0.62 }, { source: "chunky", ms: 25, share: 0.38 }]); | |
| 90 | expect(s.gc).toEqual([{ name: "G1 Young", collections: 12, avgTimeMs: 7.5, avgFrequencyMs: 900 }]); | |
| 91 | expect(s.memory).toEqual({ heap: { used: 512, total: 1024 }, nonHeap: { used: 64, total: 128 }, physical: { used: 4000, total: 8000 } }); | |
| 92 | }); | |
| 93 | ||
| 94 | test("a truncated profile is refused by name, never thrown", () => { | |
| 95 | const whole = fixture(); | |
| 96 | const r = decodeSparkProfile(whole.slice(0, whole.length - 12)); | |
| 97 | expect(r.ok).toBe(false); | |
| 98 | if (!r.ok) expect(r.error.name).toBe("truncated"); | |
| 99 | }); | |
| 100 | ||
| 101 | test("a protobuf cut mid-field is truncated, and a bad wire type is malformed", () => { | |
| 102 | const cut = decodeSparkProfile(gzipSync(Uint8Array.from([...text(1, "hello")].slice(0, 4)))); | |
| 103 | expect(cut.ok === false && cut.error.name).toBe("truncated"); | |
| 104 | const bad = decodeSparkProfile(gzipSync(Uint8Array.from([...key(1, 3)]))); | |
| 105 | expect(bad.ok === false && bad.error.name).toBe("malformed"); | |
| 106 | }); | |
| 107 | ||
| 108 | test("not gzip, empty and oversized bodies are named errors", () => { | |
| 109 | const name = (b: Uint8Array) => { const r = decodeSparkProfile(b); return r.ok ? "ok" : r.error.name; }; | |
| 110 | expect(name(new TextEncoder().encode("hello"))).toBe("not-gzip"); | |
| 111 | expect(name(new Uint8Array(0))).toBe("not-gzip"); | |
| 112 | expect(name(new Uint8Array(MAX_PACKED + 1))).toBe("too-large"); | |
| 113 | expect(name(Uint8Array.from([0x1f, 0x8b, 1, 2, 3]))).not.toBe("ok"); | |
| 114 | }); | |
| 115 | ||
| 116 | test("a body that expands past the cap is refused, not inflated", () => { | |
| 117 | const bomb = gzipSync(new Uint8Array(300 * 1024 * 1024)); | |
| 118 | expect(bomb.length).toBeLessThan(MAX_PACKED); | |
| 119 | const r = decodeSparkProfile(bomb); | |
| 120 | expect(r.ok === false && r.error.name).toBe("too-large"); | |
| 121 | }); | |
| 122 | ||
| 123 | test("an empty profile decodes to an empty summary", () => { | |
| 124 | const r = decodeSparkProfile(gzipSync(new Uint8Array(0))); | |
| 125 | expect(r.ok && r.summary.threads).toEqual([]); | |
| 126 | }); | |
| 127 | ||
| 128 | const packedInts = (n: number, vs: number[]) => bytes(n, vs.flatMap(varint)); | |
| 129 | const refNode = (cls: string, ms: number, refs: number[]) => [...text(3, cls), ...text(4, "m"), ...packedDoubles(8, [ms]), ...(refs.length ? packedInts(9, refs) : [])]; | |
| 130 | const withSources = (thread: number[]) => gzipSync(Uint8Array.from([ | |
| 131 | ...bytes(2, thread), ...entry(3, text(1, "mod.Leaf"), text(2, "m")), | |
| 132 | ])); | |
| 133 | ||
| 134 | test("a chain of shared-ref diamonds finishes fast and counts each node's time once", () => { | |
| 135 | const levels = 24; | |
| 136 | const nodes: number[][] = []; | |
| 137 | for (let l = 0; l < levels; l++) { | |
| 138 | const next = l === levels - 1 ? [] : [(l + 1) * 2, (l + 1) * 2 + 1, (l + 1) * 2, (l + 1) * 2 + 1, (l + 1) * 2, (l + 1) * 2 + 1, (l + 1) * 2, (l + 1) * 2 + 1]; | |
| 139 | for (let k = 0; k < 2; k++) nodes.push(refNode(l === levels - 1 ? "mod.Leaf" : "x.Mid", l === levels - 1 ? 5 : 1000, next)); | |
| 140 | } | |
| 141 | const thread = [...text(1, "t"), ...packedInts(5, [0, 1]), ...nodes.flatMap((n) => bytes(3, n))]; | |
| 142 | const t0 = performance.now(); | |
| 143 | const r = decodeSparkProfile(withSources(thread)); | |
| 144 | expect(performance.now() - t0).toBeLessThan(1000); | |
| 145 | if (!r.ok) throw new Error(r.error.message); | |
| 146 | expect(r.summary.perMod).toEqual([{ source: "m", ms: 10, share: 1 }]); | |
| 147 | const count = (n: { children: unknown[] }): number => 1 + (n.children as { children: unknown[] }[]).reduce((a, c) => a + count(c), 0); | |
| 148 | expect(r.summary.threads[0]!.tree.reduce((a, n) => a + count(n), 0)).toBeLessThanOrEqual(2_100); | |
| 149 | }); | |
| 150 | ||
| 151 | test("without a root list the roots are the flat nodes nothing refers to", () => { | |
| 152 | const flat = [refNode("x.Root", 30, [1]), refNode("mod.Leaf", 10, [])]; | |
| 153 | const thread = [...text(1, "t"), ...flat.flatMap((n) => bytes(3, n))]; | |
| 154 | const r = decodeSparkProfile(withSources(thread)); | |
| 155 | if (!r.ok) throw new Error(r.error.message); | |
| 156 | const tree = r.summary.threads[0]!.tree; | |
| 157 | expect(tree.map((n) => n.name)).toEqual(["x.Root.m"]); | |
| 158 | expect(tree[0]!.children.map((n) => n.name)).toEqual(["mod.Leaf.m"]); | |
| 159 | expect(r.summary.perMod).toEqual([{ source: "m", ms: 10, share: 1 }]); | |
| 160 | }); |
new above
offline
Check this table against spark's protos first. As I remember them, thread is { name:1, times:2, children:3, children_refs:4 }, and SamplerData time_windows is 6, not 7. If any number is wrong the decoder returns empty or garbage for every real profile while all tests stay green. Cite the proto file and commit in a comment here, and add a test fixture captured from real spark output.