glitchless-playtest 0.1.1 → 0.3.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.
- package/README.md +100 -7
- package/bin/glitchless-playtest.js +15 -5
- package/package.json +8 -2
- package/src/compare.js +63 -4
- package/src/config.js +50 -2
- package/src/engine.js +411 -0
- package/src/index.js +25 -8
- package/src/report.js +45 -12
- package/src/roblox.js +319 -0
package/src/engine.js
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
// Engine builds: Unity, Godot, Unreal and GameMaker. A scenario starts the build from the command line with the
|
|
2
|
+
// game's own autoplay arguments plus --glitchless-measure=SECONDS. The Glitchless SDK in the build times every frame
|
|
3
|
+
// for that long, prints one line of JSON ({"glitchless_measure": {...}}) and quits. This turns those lines into the
|
|
4
|
+
// summary compareRuns reads, so engine runs need no browser and no Glitchless server.
|
|
5
|
+
// Builds run one at a time, as browser bots do: two games at once fight over the GPU.
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
11
|
+
import { gitInfo } from './run.js';
|
|
12
|
+
|
|
13
|
+
// How each engine takes flags, how long to wait before measuring, and how to give a game an autoplay mode.
|
|
14
|
+
// Unreal and GameMaker games read single-dash flags; the Glitchless SDKs in them take either.
|
|
15
|
+
// Unity's memory counters read nothing on the first frames, so it measures after a second; the others from the start,
|
|
16
|
+
// so errors and stutter while the game loads count too.
|
|
17
|
+
export const ENGINES = {
|
|
18
|
+
godot: {
|
|
19
|
+
label: 'Godot',
|
|
20
|
+
dash: '--',
|
|
21
|
+
warmup: 0,
|
|
22
|
+
autoplay:
|
|
23
|
+
'In Godot, read the flags from OS.get_cmdline_user_args() in the main scene\'s _ready(): with "--autoplay", let a bot play (pick inputs from a RandomNumberGenerator seeded with the --seed=N value, so the same seed plays the same way on both builds), call Glitchless.level_start() as it goes, and keep playing for as long as the scenario measures. The demo in the Glitchless repo, godot/demo/demo.gd, does this.',
|
|
24
|
+
},
|
|
25
|
+
unity: {
|
|
26
|
+
label: 'Unity',
|
|
27
|
+
dash: '--',
|
|
28
|
+
warmup: 1,
|
|
29
|
+
autoplay:
|
|
30
|
+
'In Unity, read the flags from System.Environment.GetCommandLineArgs() in a startup script: with "--autoplay", let a bot play (a System.Random seeded with the --seed=N value, so the same seed plays the same way on both builds), call Glitchless.LevelStart() as it goes, and keep playing for as long as the scenario measures. The SDK\'s Fetch! sample (Package Manager → Glitchless → Samples) has such a bot.',
|
|
31
|
+
},
|
|
32
|
+
unreal: {
|
|
33
|
+
label: 'Unreal',
|
|
34
|
+
dash: '-',
|
|
35
|
+
warmup: 0,
|
|
36
|
+
autoplay:
|
|
37
|
+
'In Unreal, check FParse::Param(FCommandLine::Get(), TEXT("autoplay")) in the game mode\'s BeginPlay: with -autoplay, let a bot drive the pawn (an FRandomStream seeded from -seed=N, read with FParse::Value, so the same seed plays the same way on both builds), call Level Start as it goes, and keep playing for as long as the scenario measures.',
|
|
38
|
+
},
|
|
39
|
+
gamemaker: {
|
|
40
|
+
label: 'GameMaker',
|
|
41
|
+
dash: '-',
|
|
42
|
+
warmup: 0,
|
|
43
|
+
autoplay:
|
|
44
|
+
'In GameMaker, check glitchless_has_flag("autoplay") in the first room: with -autoplay, let a bot play (random_set_seed(real(glitchless_flag_value("seed", "1"))), so the same seed plays the same way on both builds), call glitchless_level_start() as it goes, and keep playing for as long as the scenario measures.',
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const GENERIC_AUTOPLAY =
|
|
49
|
+
'Give the game an autoplay mode: a flag such as --autoplay that lets a bot play by itself, with --seed=N so the same seed plays the same way on both builds. Have it start levels as it goes (Glitchless level_start) and keep playing for as long as the scenario measures.';
|
|
50
|
+
|
|
51
|
+
// Unity, Godot, Unreal and GameMaker builds print this line when started with the measure flag.
|
|
52
|
+
const MEASURE_LINE = /\{\s*"glitchless_measure"\s*:/;
|
|
53
|
+
|
|
54
|
+
/** Finds the SDK's measure line in a build's output (Unreal prefixes it with its log category). */
|
|
55
|
+
export function parseMeasure(text) {
|
|
56
|
+
const lines = String(text || '').split(/\r?\n/).reverse();
|
|
57
|
+
for (const line of lines) {
|
|
58
|
+
const at = line.search(MEASURE_LINE);
|
|
59
|
+
if (at < 0) continue;
|
|
60
|
+
try {
|
|
61
|
+
const m = JSON.parse(line.slice(at).trim()).glitchless_measure;
|
|
62
|
+
if (m && typeof m === 'object') return m;
|
|
63
|
+
} catch {}
|
|
64
|
+
}
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Splits a command line written as one string ("godot --path ." or with quotes) into its arguments. */
|
|
69
|
+
export function splitCommand(command) {
|
|
70
|
+
if (Array.isArray(command)) return command.map(String);
|
|
71
|
+
const out = [];
|
|
72
|
+
let cur = '';
|
|
73
|
+
let quote = null;
|
|
74
|
+
let any = false;
|
|
75
|
+
for (const ch of String(command || '')) {
|
|
76
|
+
if (quote) {
|
|
77
|
+
if (ch === quote) quote = null;
|
|
78
|
+
else cur += ch;
|
|
79
|
+
} else if (ch === '"' || ch === "'") {
|
|
80
|
+
quote = ch;
|
|
81
|
+
any = true;
|
|
82
|
+
} else if (/\s/.test(ch)) {
|
|
83
|
+
if (cur || any) out.push(cur);
|
|
84
|
+
cur = '';
|
|
85
|
+
any = false;
|
|
86
|
+
} else {
|
|
87
|
+
cur += ch;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (cur || any) out.push(cur);
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const home = (p) => (p === '~' || p.startsWith('~/') ? path.join(os.homedir(), p.slice(1)) : p);
|
|
95
|
+
|
|
96
|
+
// A path in the command is relative to the project, and a macOS .app runs its own executable.
|
|
97
|
+
export function resolveCommand(command, cwd) {
|
|
98
|
+
const argv = splitCommand(command);
|
|
99
|
+
if (!argv.length) throw new Error('"command" in glitchless.playtest.json is empty. Set it to the exported build, or the engine\'s command line with the project path (for Godot: ["godot", "--path", "."]).');
|
|
100
|
+
let bin = home(argv[0]);
|
|
101
|
+
// A path, or a build sitting in the project folder ("Game.app", "Game.x86_64"), is relative to the project;
|
|
102
|
+
// a bare name ("godot") is looked up on the PATH, even beside a folder of that name.
|
|
103
|
+
const local = path.resolve(cwd, bin);
|
|
104
|
+
if (bin.includes('/') || bin.includes('\\') || /\.app\/?$/.test(bin) || (fs.existsSync(local) && fs.statSync(local).isFile())) bin = local;
|
|
105
|
+
if (/\.app\/?$/.test(bin) && fs.existsSync(path.join(bin, 'Contents/MacOS'))) {
|
|
106
|
+
const name = path.basename(bin).replace(/\.app\/?$/, '');
|
|
107
|
+
const inside = fs.readdirSync(path.join(bin, 'Contents/MacOS'));
|
|
108
|
+
bin = path.join(bin, 'Contents/MacOS', inside.includes(name) ? name : inside[0]);
|
|
109
|
+
}
|
|
110
|
+
return [bin, ...argv.slice(1)];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Which engine a command starts: from its name, then from the files an export leaves beside its executable. */
|
|
114
|
+
export function detectEngine(argv) {
|
|
115
|
+
const [bin, ...rest] = argv;
|
|
116
|
+
const name = path.basename(bin || '');
|
|
117
|
+
const all = argv.join(' ');
|
|
118
|
+
if (/godot/i.test(name) || rest.some((a) => /\.pck$/.test(a) || a === '--main-pack')) return 'godot';
|
|
119
|
+
if (/UnrealEditor|UE4Editor/i.test(name) || rest.some((a) => /\.uproject$/i.test(a))) return 'unreal';
|
|
120
|
+
if (/YoYo Runner|Runner\.exe$/i.test(all) || rest.some((a) => /(^|[/\\])(game\.ios|data\.win|game\.unx)$/.test(a))) return 'gamemaker';
|
|
121
|
+
if (/^Unity(\.exe)?$/i.test(name)) return 'unity';
|
|
122
|
+
const dir = path.dirname(bin || '');
|
|
123
|
+
const near = [dir, path.join(dir, '../Resources'), path.join(dir, '../Frameworks'), path.join(dir, '../UE')];
|
|
124
|
+
const has = (test) => near.some((d) => {
|
|
125
|
+
try {
|
|
126
|
+
return fs.readdirSync(d).some(test);
|
|
127
|
+
} catch {
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
if (has((f) => /^UnityPlayer\.(dylib|dll|so)$/.test(f) || /_Data$/.test(f))) return 'unity';
|
|
132
|
+
if (has((f) => /\.pck$/.test(f))) return 'godot';
|
|
133
|
+
if (has((f) => /^(game\.ios|data\.win|game\.unx)$/.test(f))) return 'gamemaker';
|
|
134
|
+
if (has((f) => f === 'Engine' || /\.uproject$/.test(f))) return 'unreal';
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// A scenario's params become the game's own flags: { autoplay: true, seed: 7 } → --autoplay --seed=7 (-autoplay in
|
|
139
|
+
// Unreal and GameMaker). true is a bare flag; false and null leave it out.
|
|
140
|
+
export function paramFlags(params = {}, dash = '--') {
|
|
141
|
+
const out = [];
|
|
142
|
+
for (const [k, v] of Object.entries(params || {})) {
|
|
143
|
+
if (v == null || v === false) continue;
|
|
144
|
+
out.push(v === true ? `${dash}${k}` : `${dash}${k}=${v}`);
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The arguments one scenario adds to the command: the game's own flags, then the measure flags. */
|
|
150
|
+
export function scenarioArgs(engine, base, sc, { out } = {}) {
|
|
151
|
+
const dash = ENGINES[engine]?.dash || '--';
|
|
152
|
+
const game = [...paramFlags(sc.params, dash), ...(sc.args || []).map(String)];
|
|
153
|
+
const measure = [`${dash}glitchless-measure=${sc.seconds}`, `${dash}glitchless-warmup=${sc.warmup}`, ...(out ? [`${dash}glitchless-out=${out}`] : [])];
|
|
154
|
+
// Godot hands a game only the arguments after "--" (OS.get_cmdline_user_args).
|
|
155
|
+
const separate = engine === 'godot' && ![...base, ...game].some((a) => a === '--' || a === '++');
|
|
156
|
+
return [...(separate ? ['--'] : []), ...game, ...measure];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// The scenario's measure settings with the engine's defaults filled in.
|
|
160
|
+
export function engineScenario(sc, engine, cfg) {
|
|
161
|
+
const warmup = sc.warmup ?? cfg.warmup ?? ENGINES[engine]?.warmup ?? 1;
|
|
162
|
+
const seconds = sc.seconds ?? cfg.seconds ?? 10;
|
|
163
|
+
return { ...sc, seconds, warmup, max_s: sc.max_s ?? warmup + seconds + 120 };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const label = (sc) => sc.name || [...paramFlags(sc.params), ...(sc.args || [])].join(' ') || 'run';
|
|
167
|
+
const tail = (text, n = 15) => String(text || '').trimEnd().split(/\r?\n/).slice(-n).join('\n');
|
|
168
|
+
|
|
169
|
+
// Runs one build to the end, or kills it at the time cap.
|
|
170
|
+
function runBuild(argv, { cwd, timeoutMs }) {
|
|
171
|
+
return new Promise((resolve, reject) => {
|
|
172
|
+
const t0 = Date.now();
|
|
173
|
+
let output = '';
|
|
174
|
+
let timedOut = false;
|
|
175
|
+
const child = spawn(argv[0], argv.slice(1), { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
176
|
+
const keep = (d) => {
|
|
177
|
+
output += d;
|
|
178
|
+
if (output.length > 4_000_000) output = output.slice(-2_000_000); // the measure line comes last
|
|
179
|
+
};
|
|
180
|
+
child.stdout.on('data', keep);
|
|
181
|
+
child.stderr.on('data', keep);
|
|
182
|
+
const timer = setTimeout(() => {
|
|
183
|
+
timedOut = true;
|
|
184
|
+
child.kill('SIGTERM');
|
|
185
|
+
setTimeout(() => child.kill('SIGKILL'), 5000).unref();
|
|
186
|
+
}, timeoutMs);
|
|
187
|
+
child.on('error', (err) => {
|
|
188
|
+
clearTimeout(timer);
|
|
189
|
+
reject(err.code === 'ENOENT' ? new Error(`Could not start ${argv[0]}: no such program. Set "command" in glitchless.playtest.json to the exported build, or to the engine's command line with the project path (for Godot: ["godot", "--path", "."]).`) : err);
|
|
190
|
+
});
|
|
191
|
+
child.on('close', (code, signal) => {
|
|
192
|
+
clearTimeout(timer);
|
|
193
|
+
resolve({ code, signal, output, timedOut, seconds: Math.round((Date.now() - t0) / 1000) });
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function readIfNew(file, since) {
|
|
199
|
+
try {
|
|
200
|
+
if (fs.statSync(file).mtimeMs < since - 1000) return null;
|
|
201
|
+
return parseMeasure(fs.readFileSync(file, 'utf8'));
|
|
202
|
+
} catch {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Plays every scenario with the build, one at a time. */
|
|
208
|
+
export async function runEngineScenarios(cfg, { command = cfg.command, scenarios = cfg.scenarios, log = () => {} } = {}) {
|
|
209
|
+
const root = cfg.root || process.cwd();
|
|
210
|
+
const base = resolveCommand(command, root);
|
|
211
|
+
const engine = cfg.engine || detectEngine(base);
|
|
212
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'glitchless-playtest-'));
|
|
213
|
+
for (const sc of scenarios) {
|
|
214
|
+
if (!paramFlags(sc.params).length && !(sc.args || []).length) throw new Error(`Scenario "${label(sc)}" passes nothing to the game, so nothing starts its autoplay bot. Give it "params" (such as { "autoplay": true, "seed": 7 }) or "args". ${ENGINES[engine]?.autoplay || GENERIC_AUTOPLAY}`);
|
|
215
|
+
}
|
|
216
|
+
const results = [];
|
|
217
|
+
try {
|
|
218
|
+
for (const [i, raw] of scenarios.entries()) {
|
|
219
|
+
const sc = engineScenario(raw, engine, cfg);
|
|
220
|
+
const out = path.join(tmp, `run-${i + 1}.json`);
|
|
221
|
+
const argv = [...base, ...scenarioArgs(engine, base, sc, { out })];
|
|
222
|
+
log(`run ${i + 1}/${scenarios.length}: ${label(sc)} …`);
|
|
223
|
+
const t0 = Date.now();
|
|
224
|
+
const r = await runBuild(argv, { cwd: root, timeoutMs: sc.max_s * 1000 });
|
|
225
|
+
const measure = parseMeasure(r.output) || readIfNew(out, t0) || (cfg.measure_file ? readIfNew(path.resolve(root, home(cfg.measure_file)), t0) : null);
|
|
226
|
+
const shown = argv.filter((a) => !a.includes('glitchless-out='));
|
|
227
|
+
const result = { scenario: sc.name || null, params: sc.params, args: sc.args, seconds: sc.seconds, warmup: sc.warmup, command: shown, session_id: measure?.session_id || null, elapsed_s: r.seconds, finished: !!measure && !measure.error, crashed: false, exit_code: r.code, measure: measure && !measure.error ? measure : null };
|
|
228
|
+
if (measure?.error) throw new Error(`${label(sc)}: the build measured nothing: ${measure.error}${/off/i.test(measure.error) ? ' A playtest needs it on: leave out --glitchless-off, and turn the in-game "share data" setting back on for this device.' : ` The game has to keep drawing frames for warmup + seconds (${sc.warmup} + ${sc.seconds} s): if its autoplay run is shorter, lower "seconds" or let the bot keep playing.`}`);
|
|
229
|
+
if (!measure) {
|
|
230
|
+
if (r.timedOut) {
|
|
231
|
+
Object.assign(result, { crashed: true, reason: `froze or never quit within ${sc.max_s} s`, output_tail: tail(r.output) });
|
|
232
|
+
} else if (r.code === 0 && !r.signal) {
|
|
233
|
+
throw new Error(
|
|
234
|
+
`${label(sc)}: the build quit after ${r.seconds} s without printing its measurement ({"glitchless_measure": …}). Either it quit before the measure ended, because its autoplay run is shorter than warmup + seconds (${sc.warmup} + ${sc.seconds} s): lower "seconds" or let the bot keep playing; or the build doesn't have the Glitchless SDK (Unity, Godot, Unreal and GameMaker builds with it print that line when started with --glitchless-measure=SECONDS)${engine === 'unity' || engine === 'gamemaker' ? '; or the game\'s file sandbox kept it from writing the measurement where this run could read it: set "measure_file" in glitchless.playtest.json to where it writes glitchless/measure.json' : ''}.\nLast lines it printed:\n${tail(r.output)}`,
|
|
235
|
+
);
|
|
236
|
+
} else {
|
|
237
|
+
Object.assign(result, { crashed: true, reason: r.signal ? `killed by ${r.signal}` : `exit code ${r.code}`, output_tail: tail(r.output) });
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
results.push(result);
|
|
241
|
+
const m = result.measure;
|
|
242
|
+
log(m ? ` → ${m.frames} frames · p95 ${m.frame_ms?.p95} ms · ${m.hitch_count} hitch(es)${m.new_errors ? ` · ${m.new_errors} error(s)` : ''} · ${r.seconds}s` : ` → crashed (${result.reason}) after ${r.seconds}s`);
|
|
243
|
+
}
|
|
244
|
+
} finally {
|
|
245
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
246
|
+
}
|
|
247
|
+
if (!results.some((r) => r.measure)) {
|
|
248
|
+
const first = results[0];
|
|
249
|
+
throw new Error(`The build crashed in every run before it finished measuring (${first.reason}). Last lines it printed:\n${first.output_tail}`);
|
|
250
|
+
}
|
|
251
|
+
return { engine, command: base, results };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const round = (n, d = 2) => (n == null || !Number.isFinite(n) ? null : Math.round(n * 10 ** d) / 10 ** d);
|
|
255
|
+
const p50 = (x) => (x && typeof x === 'object' ? (x.p50 ?? null) : (x ?? null));
|
|
256
|
+
const sum = (xs) => xs.reduce((a, b) => a + b, 0);
|
|
257
|
+
function mostFrames(pairs) {
|
|
258
|
+
const by = new Map();
|
|
259
|
+
for (const [v, n] of pairs) if (v != null) by.set(v, (by.get(v) || 0) + n);
|
|
260
|
+
return [...by.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// The same error in two builds: messages carry numbers that change every run (an ID, a row), and an edit above the
|
|
264
|
+
// line that raised it moves its line number. glitchless-deck matches errors the same way.
|
|
265
|
+
export const errorType = (e) => `${e.kind || ''}|${String(e.message || '').replace(/\d+/g, '#')}|${String(e.location || '').replace(/:\d+/g, '')}`;
|
|
266
|
+
|
|
267
|
+
// One run's numbers, from its measure JSON. Engines differ: update time is update_cpu_ms in Unity and Unreal and
|
|
268
|
+
// process_ms in Godot and GameMaker; GameMaker has no draw calls; only Unreal has an RHI thread.
|
|
269
|
+
function runMetrics(m) {
|
|
270
|
+
return {
|
|
271
|
+
frames: m.frames ?? null,
|
|
272
|
+
seconds: m.seconds ?? null,
|
|
273
|
+
frame_budget_ms: m.frame_budget_ms ?? null,
|
|
274
|
+
pct_frames_over_budget: m.pct_frames_over_budget ?? null,
|
|
275
|
+
frame_p50: m.frame_ms?.p50 ?? null,
|
|
276
|
+
frame_p95: m.frame_ms?.p95 ?? null,
|
|
277
|
+
frame_p99: m.frame_ms?.p99 ?? null,
|
|
278
|
+
frame_worst: m.frame_ms?.worst ?? null,
|
|
279
|
+
render_cpu_ms: p50(m.render_cpu_ms),
|
|
280
|
+
update_cpu_ms: p50(m.update_cpu_ms ?? m.process_ms),
|
|
281
|
+
gpu_ms: p50(m.gpu_ms),
|
|
282
|
+
rhi_cpu_ms: p50(m.rhi_cpu_ms),
|
|
283
|
+
physics_ms: p50(m.physics_ms),
|
|
284
|
+
draw_calls: m.draw_calls && typeof m.draw_calls === 'object' ? (m.draw_calls.avg ?? null) : (m.draw_calls ?? null),
|
|
285
|
+
hitches: m.hitch_count ?? null,
|
|
286
|
+
hitches_per_min: m.seconds ? round((m.hitch_count || 0) / (m.seconds / 60)) : null,
|
|
287
|
+
errors: m.new_errors ?? null,
|
|
288
|
+
gc_ms: m.gc_ms ?? null,
|
|
289
|
+
gc_collections: m.gc_collections ?? null,
|
|
290
|
+
level_start: m.level_start ?? null,
|
|
291
|
+
level_end: m.level_end ?? null,
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* The summary compareRuns reads, from the runs of one playtest. Across runs, per-frame numbers are averaged weighted
|
|
297
|
+
* by frames (exact for slow frames and draw calls, close for percentiles), hitches are counted per minute measured,
|
|
298
|
+
* and each run is kept in by_scenario for a run-by-run comparison.
|
|
299
|
+
*/
|
|
300
|
+
export function measureSummary(results) {
|
|
301
|
+
const measured = results.filter((r) => r.measure);
|
|
302
|
+
const runs = measured.map((r) => ({ r, x: runMetrics(r.measure) }));
|
|
303
|
+
const weighted = (key, d = 2) => {
|
|
304
|
+
let total = 0;
|
|
305
|
+
let weight = 0;
|
|
306
|
+
for (const { x } of runs) {
|
|
307
|
+
if (x[key] == null) continue;
|
|
308
|
+
const w = x.frames || x.seconds || 1;
|
|
309
|
+
total += x[key] * w;
|
|
310
|
+
weight += w;
|
|
311
|
+
}
|
|
312
|
+
return weight ? round(total / weight, d) : null;
|
|
313
|
+
};
|
|
314
|
+
const measuredSeconds = sum(runs.map(({ x }) => x.seconds || 0));
|
|
315
|
+
const errors = new Map();
|
|
316
|
+
for (const { r } of runs) {
|
|
317
|
+
for (const e of r.measure.errors || []) {
|
|
318
|
+
const fp = errorType(e);
|
|
319
|
+
const have = errors.get(fp) || { fingerprint: fp, kind: e.kind, message: e.message, location: e.location, count: 0, sessions: 0 };
|
|
320
|
+
have.count += e.count || 1;
|
|
321
|
+
have.sessions += 1;
|
|
322
|
+
errors.set(fp, have);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
// What grew over a run (objects, nodes, instances, MB): a leak shows as growth that a fixed-seed run repeats.
|
|
326
|
+
const growth = {};
|
|
327
|
+
const growthRuns = {};
|
|
328
|
+
for (const { r } of runs) {
|
|
329
|
+
for (const [k, v] of Object.entries(r.measure.memory_delta || {})) {
|
|
330
|
+
if (typeof v !== 'number') continue;
|
|
331
|
+
growth[k] = (growth[k] || 0) + v;
|
|
332
|
+
growthRuns[k] = (growthRuns[k] || 0) + 1;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
const byScenario = {};
|
|
336
|
+
for (const [i, r] of results.entries()) {
|
|
337
|
+
const key = r.scenario || `run ${i + 1}`;
|
|
338
|
+
byScenario[key] = r.measure ? runMetrics(r.measure) : { crashed: true, reason: r.reason };
|
|
339
|
+
}
|
|
340
|
+
const gc = runs.filter(({ x }) => x.gc_ms != null);
|
|
341
|
+
const gcCount = runs.filter(({ x }) => x.gc_collections != null);
|
|
342
|
+
return {
|
|
343
|
+
sessions: results.length,
|
|
344
|
+
frames: sum(runs.map(({ x }) => x.frames || 0)),
|
|
345
|
+
seconds_measured: measuredSeconds,
|
|
346
|
+
// The budget most frames ran against; a run that detected another one shows it in by_scenario.
|
|
347
|
+
frame_budget_ms: mostFrames(runs.map(({ x }) => [x.frame_budget_ms, x.frames || 1])),
|
|
348
|
+
pct_frames_over_budget: weighted('pct_frames_over_budget', 1),
|
|
349
|
+
frame_p50: weighted('frame_p50'),
|
|
350
|
+
frame_p95: weighted('frame_p95'),
|
|
351
|
+
frame_p99: weighted('frame_p99'),
|
|
352
|
+
frame_worst: runs.length ? Math.max(...runs.map(({ x }) => x.frame_worst ?? 0)) : null,
|
|
353
|
+
render_cpu_ms: weighted('render_cpu_ms'),
|
|
354
|
+
update_cpu_ms: weighted('update_cpu_ms'),
|
|
355
|
+
gpu_ms: weighted('gpu_ms'),
|
|
356
|
+
rhi_cpu_ms: weighted('rhi_cpu_ms'),
|
|
357
|
+
physics_ms: weighted('physics_ms'),
|
|
358
|
+
draw_calls: weighted('draw_calls', 0),
|
|
359
|
+
hitch_count: sum(runs.map(({ x }) => x.hitches || 0)),
|
|
360
|
+
hitches_per_min: measuredSeconds ? round(sum(runs.map(({ x }) => x.hitches || 0)) / (measuredSeconds / 60)) : null,
|
|
361
|
+
errors_per_session: runs.length ? round(sum(runs.map(({ x }) => x.errors || 0)) / runs.length) : null,
|
|
362
|
+
gc_ms: gc.length ? round(sum(gc.map(({ x }) => x.gc_ms)) / gc.length, 1) : null,
|
|
363
|
+
gc_collections: gcCount.length ? round(sum(gcCount.map(({ x }) => x.gc_collections)) / gcCount.length, 1) : null,
|
|
364
|
+
memory_growth: Object.fromEntries(Object.entries(growth).map(([k, v]) => [k, round(v / growthRuns[k], 1)])),
|
|
365
|
+
crashes: results.filter((r) => r.crashed).length,
|
|
366
|
+
errors: [...errors.values()],
|
|
367
|
+
levels: {},
|
|
368
|
+
by_scenario: byScenario,
|
|
369
|
+
headless: runs.some(({ r }) => r.measure.headless === true),
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** Plays every scenario with the build and returns a run record ready to save or compare. */
|
|
374
|
+
export async function engineRun(cfg, { command = cfg.command, scenarios = cfg.scenarios, log = () => {} } = {}) {
|
|
375
|
+
const { engine, command: argv, results } = await runEngineScenarios(cfg, { command, scenarios, log });
|
|
376
|
+
const summary = measureSummary(results);
|
|
377
|
+
const measured = results.filter((r) => r.measure);
|
|
378
|
+
const noLevel = measured.every((r) => r.measure.level_start == null && r.measure.level_end == null);
|
|
379
|
+
const howTo = ENGINES[engine]?.autoplay || GENERIC_AUTOPLAY;
|
|
380
|
+
// With the default scenarios, a game that never starts a level most likely ignored --autoplay and sat on its menu.
|
|
381
|
+
if (noLevel && cfg.default_scenarios) {
|
|
382
|
+
throw new Error(`The build ran with the default scenarios (${paramFlags(scenarios[0].params, ENGINES[engine]?.dash).join(' ')}) but no run started a level, so it probably has no autoplay mode and measured its menu. ${howTo} Then list the runs in glitchless.playtest.json under "scenarios" (each with the "params" or "args" that start the bot).`);
|
|
383
|
+
}
|
|
384
|
+
const notes = [];
|
|
385
|
+
if (noLevel) notes.push(`No run started a level (Glitchless level_start), so the bot may not have played. If the game has no autoplay mode yet: ${howTo}`);
|
|
386
|
+
if (summary.headless) notes.push('The build ran headless: nothing was drawn and frames ran uncapped, so frame times mean little and only warn in a comparison. Run it with a window to gate a change on them.');
|
|
387
|
+
const sdk = measured[0]?.measure.sdk || null;
|
|
388
|
+
return {
|
|
389
|
+
created: new Date().toISOString(),
|
|
390
|
+
kind: 'engine',
|
|
391
|
+
engine,
|
|
392
|
+
command: argv,
|
|
393
|
+
service: cfg.service || path.basename(cfg.root || process.cwd()),
|
|
394
|
+
git: gitInfo(cfg.root),
|
|
395
|
+
machine: { os: `${os.type()} ${os.release()}`, cpu: os.cpus()[0]?.model || null, gpu: null, browser: [ENGINES[engine]?.label, sdk].filter(Boolean).join(' · ') || 'engine build' },
|
|
396
|
+
scenarios: results,
|
|
397
|
+
summary,
|
|
398
|
+
notes,
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// A quick run plays fewer scenarios than a full baseline: compare it with the same runs of the baseline only.
|
|
403
|
+
export function matchingEngineRuns(baseline, candidate) {
|
|
404
|
+
if (baseline.kind !== 'engine') return baseline;
|
|
405
|
+
const key = (s) => JSON.stringify([s.scenario, s.params, s.args]);
|
|
406
|
+
const wanted = new Set((candidate.scenarios || []).map(key));
|
|
407
|
+
const have = baseline.scenarios || [];
|
|
408
|
+
const subset = have.filter((s) => wanted.has(key(s)));
|
|
409
|
+
if (subset.length === have.length || subset.length !== wanted.size) return baseline;
|
|
410
|
+
return { ...baseline, scenarios: subset, summary: measureSummary(subset), name: `${baseline.name} (matching runs)` };
|
|
411
|
+
}
|
package/src/index.js
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
// Glitchless playtest: autoplay bots play the game on the current code, and the result is compared with
|
|
2
|
-
// a saved baseline. Used by the glitchless-playtest CLI and the glitchless_playtest MCP tool.
|
|
2
|
+
// a saved baseline. Used by the glitchless-playtest CLI and the glitchless_playtest MCP tool. A web game
|
|
3
|
+
// plays in Chrome (run.js); an engine build (Unity, Godot, Unreal, GameMaker) runs from its command with
|
|
4
|
+
// the SDK's --glitchless-measure (engine.js); a Roblox game plays in the open Roblox Studio over Studio's MCP
|
|
5
|
+
// server (roblox.js).
|
|
3
6
|
//
|
|
4
7
|
// await playtest({ saveAs: 'baseline' }) // before a change
|
|
5
8
|
// await playtest({ compareTo: 'baseline' }) // after it → { verdict, report, ... }
|
|
6
9
|
|
|
7
10
|
import { loadConfig } from './config.js';
|
|
8
11
|
import { playtestRun, fetchSummary } from './run.js';
|
|
12
|
+
import { engineRun, matchingEngineRuns } from './engine.js';
|
|
13
|
+
import { robloxRun, matchingRobloxBaseline } from './roblox.js';
|
|
9
14
|
import { compareRuns } from './compare.js';
|
|
10
15
|
import { comparisonReport, runReport } from './report.js';
|
|
11
16
|
import { saveRun, loadRun, listRuns } from './runs.js';
|
|
@@ -15,26 +20,38 @@ export { compareRuns, judge } from './compare.js';
|
|
|
15
20
|
export { comparisonReport, runReport } from './report.js';
|
|
16
21
|
export { saveRun, loadRun, listRuns } from './runs.js';
|
|
17
22
|
export { playtestRun, loadPlaywright } from './run.js';
|
|
23
|
+
export { engineRun, measureSummary, parseMeasure, detectEngine, splitCommand, ENGINES } from './engine.js';
|
|
24
|
+
export { robloxRun } from './roblox.js';
|
|
18
25
|
|
|
19
26
|
/**
|
|
20
27
|
* @param {object} o
|
|
21
28
|
* @param {string} [o.saveAs] save this run under a name (e.g. "baseline")
|
|
22
29
|
* @param {string} [o.compareTo] compare with a saved run (default "baseline" when it exists and we're not saving over it)
|
|
23
30
|
* @param {string} [o.baselineUrl] play a baseline against another running build first, then compare
|
|
31
|
+
* @param {string|string[]} [o.baselineCommand] engine builds: run another build as the baseline first (for CI)
|
|
24
32
|
* @param {boolean} [o.quick] first scenario only
|
|
25
|
-
* @param {number} [o.maxSeconds] cap each run
|
|
26
|
-
* @param {object} [o.config] overrides for glitchless.playtest.json / defaults (game, server, service, channel, headed, api_key)
|
|
33
|
+
* @param {number} [o.maxSeconds] cap each run (an engine build: the seconds it measures)
|
|
34
|
+
* @param {object} [o.config] overrides for glitchless.playtest.json / defaults (game, command, engine, server, service, channel, headed, api_key)
|
|
27
35
|
* @param {(msg: string) => void} [o.log]
|
|
28
36
|
*/
|
|
29
|
-
export async function playtest({ saveAs, compareTo, baselineUrl, quick = false, maxSeconds, config = {}, cwd = process.cwd(), log = () => {} } = {}) {
|
|
37
|
+
export async function playtest({ saveAs, compareTo, baselineUrl, baselineCommand, quick = false, maxSeconds, config = {}, cwd = process.cwd(), log = () => {} } = {}) {
|
|
30
38
|
const cfg = loadConfig(cwd, config);
|
|
39
|
+
const roblox = cfg.engine === 'roblox';
|
|
40
|
+
const engine = !roblox && !!cfg.command;
|
|
41
|
+
if (roblox && (baselineUrl || baselineCommand)) throw new Error('A Roblox game plays in the open Roblox Studio: save a baseline with --save baseline before the change instead of playing another build.');
|
|
42
|
+
if (engine && baselineUrl) throw new Error('This project runs an engine build ("command"), not a web game: give the baseline build with --baseline-command instead of --baseline-url.');
|
|
43
|
+
if (!engine && baselineCommand) throw new Error('--baseline-command runs an engine build: set "command" in glitchless.playtest.json (or pass --command) to the build being tested too.');
|
|
44
|
+
const play = (opts) => (roblox ? robloxRun(cfg, opts) : engine ? engineRun(cfg, opts) : playtestRun(cfg, opts));
|
|
31
45
|
let scenarios = quick ? cfg.scenarios.slice(0, 1) : cfg.scenarios;
|
|
32
|
-
if (maxSeconds) scenarios = scenarios.map((s) => ({ ...s, max_s: maxSeconds }));
|
|
46
|
+
if (maxSeconds) scenarios = scenarios.map((s) => (engine ? { ...s, seconds: Math.min(s.seconds ?? cfg.seconds ?? maxSeconds, maxSeconds) } : { ...s, max_s: maxSeconds }));
|
|
33
47
|
|
|
34
48
|
let baseline = null;
|
|
35
49
|
if (baselineUrl) {
|
|
36
50
|
log(`Baseline: playing ${baselineUrl}`);
|
|
37
51
|
baseline = { ...(await playtestRun(cfg, { game: baselineUrl, scenarios, log })), name: 'baseline-url' };
|
|
52
|
+
} else if (baselineCommand) {
|
|
53
|
+
log(`Baseline: running ${[].concat(baselineCommand).join(' ')}`);
|
|
54
|
+
baseline = { ...(await engineRun(cfg, { command: baselineCommand, scenarios, log })), name: 'baseline-command' };
|
|
38
55
|
} else {
|
|
39
56
|
const target = compareTo ?? (saveAs === 'baseline' ? null : 'baseline');
|
|
40
57
|
if (target) {
|
|
@@ -46,8 +63,8 @@ export async function playtest({ saveAs, compareTo, baselineUrl, quick = false,
|
|
|
46
63
|
}
|
|
47
64
|
}
|
|
48
65
|
|
|
49
|
-
log(`Candidate: playing ${cfg.game}`);
|
|
50
|
-
const candidate = await
|
|
66
|
+
log(`Candidate: ${roblox ? 'playing in Roblox Studio' : engine ? `running ${[].concat(cfg.command).join(' ')}` : `playing ${cfg.game}`}`);
|
|
67
|
+
const candidate = await play({ scenarios, log });
|
|
51
68
|
const files = { latest: saveRun(cfg.runs_dir, 'latest', candidate) };
|
|
52
69
|
if (saveAs) files[saveAs] = saveRun(cfg.runs_dir, saveAs, candidate);
|
|
53
70
|
candidate.name = saveAs || 'latest';
|
|
@@ -56,7 +73,7 @@ export async function playtest({ saveAs, compareTo, baselineUrl, quick = false,
|
|
|
56
73
|
const report = `${runReport(candidate)}\n\n${saveAs ? `Saved as \`${saveAs}\`.` : 'No baseline to compare with. Save one before changing the code with `--save baseline`.'}`;
|
|
57
74
|
return { verdict: 'none', report, candidate, files };
|
|
58
75
|
}
|
|
59
|
-
baseline = await matchingBaseline(cfg, baseline, candidate, log);
|
|
76
|
+
baseline = candidate.kind === 'engine' ? matchingEngineRuns(baseline, candidate) : candidate.kind === 'roblox' ? await matchingRobloxBaseline(cfg, baseline, candidate, log) : await matchingBaseline(cfg, baseline, candidate, log);
|
|
60
77
|
const comparison = compareRuns(baseline, candidate, cfg.thresholds);
|
|
61
78
|
return { verdict: comparison.verdict, report: comparisonReport(baseline, candidate, comparison), comparison, baseline, candidate, files };
|
|
62
79
|
}
|
package/src/report.js
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
const fmt = (v) => (v == null ? '–' : typeof v === 'number' ? (Number.isInteger(v) ? v.toLocaleString('en-US') : v.toLocaleString('en-US', { maximumFractionDigits: 2 })) : String(v));
|
|
4
4
|
const change = (c) => (c.change_pct == null ? '' : `${c.change_pct > 0 ? '+' : ''}${c.change_pct}%`);
|
|
5
5
|
const runs = (n) => `${n} autoplay run${n === 1 ? '' : 's'}`;
|
|
6
|
+
// memory_growth keys as words: orphan_nodes → orphan nodes, static_mb → static MB.
|
|
7
|
+
export const growthKey = (k) => k.replace(/_mb$/, ' MB').replace(/_/g, ' ');
|
|
6
8
|
const where = (c) => (c.scope === 'all levels' ? c.label : `${c.label}, ${c.scope}`);
|
|
7
9
|
|
|
8
10
|
function describeRun(run) {
|
|
@@ -35,36 +37,67 @@ export function comparisonReport(baseline, candidate, cmp) {
|
|
|
35
37
|
out.push('', '### Errors that no longer happen', '');
|
|
36
38
|
for (const e of cmp.fixed_errors) out.push(`- \`${e.message}\` at ${e.location || 'unknown location'}`);
|
|
37
39
|
}
|
|
40
|
+
out.push(...crashedRuns(candidate));
|
|
38
41
|
const same = cmp.checks.filter((c) => c.status === 'same');
|
|
39
42
|
if (same.length) out.push('', '<details><summary>Unchanged metrics</summary>', '', table(same), '', '</details>');
|
|
40
43
|
return out.join('\n');
|
|
41
44
|
}
|
|
42
45
|
|
|
46
|
+
// An engine build's crashed or frozen runs, with the last lines each printed: what an agent needs to fix it.
|
|
47
|
+
function crashedRuns(run) {
|
|
48
|
+
const crashed = (run.scenarios || []).filter((r) => r.crashed);
|
|
49
|
+
if (!crashed.length) return [];
|
|
50
|
+
const out = ['', '### Crashed runs', ''];
|
|
51
|
+
for (const r of crashed) out.push(`- ${r.scenario || 'run'}: ${r.reason}, after ${r.elapsed_s} s. Last lines it printed:`, '', '```', r.output_tail || '(nothing)', '```', '');
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
43
55
|
export function runReport(run) {
|
|
44
56
|
const s = run.summary || {};
|
|
57
|
+
const engine = run.kind === 'engine';
|
|
45
58
|
const out = [`## Glitchless playtest run ${describeRun(run)}`, ''];
|
|
46
59
|
out.push(`${runs((run.scenarios || []).length)} · ${run.service} · ${[run.machine?.browser, run.machine?.gpu].filter(Boolean).join(' · ')}`, '');
|
|
47
60
|
out.push('| Metric | Value |', '| --- | ---: |');
|
|
61
|
+
// A web run always shows the browser's metrics; an engine build only what its engine reports.
|
|
48
62
|
const rows = [
|
|
49
|
-
['Slow frames (% over budget)', s.pct_frames_over_budget],
|
|
50
|
-
['Frame time p95 (ms)', s.frame_p95],
|
|
51
|
-
['
|
|
52
|
-
['
|
|
53
|
-
['
|
|
54
|
-
['
|
|
55
|
-
['
|
|
56
|
-
['
|
|
57
|
-
['
|
|
63
|
+
['Slow frames (% over budget)', s.pct_frames_over_budget, true],
|
|
64
|
+
['Frame time p95 (ms)', s.frame_p95, true],
|
|
65
|
+
['Frame time p99 (ms)', s.frame_p99],
|
|
66
|
+
['Render CPU per frame (ms)', s.render_cpu_ms, true],
|
|
67
|
+
['Update CPU per frame (ms)', s.update_cpu_ms],
|
|
68
|
+
['GPU per frame (ms)', s.gpu_ms],
|
|
69
|
+
['RHI thread per frame (ms)', s.rhi_cpu_ms],
|
|
70
|
+
['Physics per frame (ms)', s.physics_ms],
|
|
71
|
+
['Draw calls per frame', s.draw_calls, true],
|
|
72
|
+
['Hitches per minute', s.hitches_per_min, true],
|
|
73
|
+
['Errors per run', s.errors_per_session, true],
|
|
74
|
+
['Crashed runs', s.crashes, true],
|
|
75
|
+
['Deaths per run', s.deaths_per_session, !engine],
|
|
76
|
+
['Level completion (%)', s.level_completion_pct, !engine],
|
|
77
|
+
['Garbage collection per run (ms)', s.gc_ms],
|
|
78
|
+
['Garbage collections per run', s.gc_collections],
|
|
58
79
|
];
|
|
59
|
-
for (const [k, v] of rows) out.push(`| ${k} | ${fmt(v)} |`);
|
|
80
|
+
for (const [k, v, always] of rows) if (v != null || (always && !engine)) out.push(`| ${k} | ${fmt(v)} |`);
|
|
81
|
+
const growth = Object.entries(s.memory_growth || {}).filter(([, v]) => v);
|
|
82
|
+
if (growth.length) out.push('', `Growth over a run: ${growth.map(([k, v]) => `${growthKey(k)} ${v > 0 ? '+' : ''}${fmt(v)}`).join(', ')}.`);
|
|
83
|
+
if (engine && s.by_scenario) {
|
|
84
|
+
out.push('', '| Run | Frames | Slow frames (%) | Frame p95 (ms) | Frame p99 (ms) | Hitches | Errors | Levels |', '| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |');
|
|
85
|
+
for (const [name, r] of Object.entries(s.by_scenario)) {
|
|
86
|
+
if (r.crashed) out.push(`| ${name} | crashed (${r.reason}) | | | | | | |`);
|
|
87
|
+
else out.push(`| ${name} | ${fmt(r.frames)} | ${fmt(r.pct_frames_over_budget)} | ${fmt(r.frame_p95)} | ${fmt(r.frame_p99)} | ${fmt(r.hitches)} | ${fmt(r.errors)} | ${r.level_start == null && r.level_end == null ? '–' : r.level_start === r.level_end ? r.level_end : `${r.level_start ?? '–'} → ${r.level_end ?? '–'}`} |`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
60
90
|
const levels = Object.entries(s.levels || {});
|
|
61
91
|
if (levels.length) {
|
|
62
|
-
|
|
63
|
-
|
|
92
|
+
const update = levels.some(([, v]) => v.update_cpu_ms != null);
|
|
93
|
+
out.push('', `| Level | Slow frames (%) | Frame p95 (ms) | Draw calls | Render CPU (ms) |${update ? ' Update CPU (ms) |' : ''}`, `| --- | ---: | ---: | ---: | ---: |${update ? ' ---: |' : ''}`);
|
|
94
|
+
for (const [l, v] of levels) out.push(`| ${l} | ${fmt(v.pct_frames_over_budget)} | ${fmt(v.frame_p95)} | ${fmt(v.draw_calls)} | ${fmt(v.render_cpu_ms)} |${update ? ` ${fmt(v.update_cpu_ms)} |` : ''}`);
|
|
64
95
|
}
|
|
65
96
|
if (s.errors?.length) {
|
|
66
97
|
out.push('', 'Errors:');
|
|
67
98
|
for (const e of s.errors) out.push(`- \`${e.message}\` at ${e.location || 'unknown location'}: ${e.count}×`);
|
|
68
99
|
}
|
|
100
|
+
out.push(...crashedRuns(run));
|
|
101
|
+
for (const note of run.notes || []) out.push('', `> ${note}`);
|
|
69
102
|
return out.join('\n');
|
|
70
103
|
}
|