@margoengine/stats 0.1.0 → 1.0.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 CHANGED
@@ -1,414 +1,414 @@
1
- # @margoengine/stats
2
-
3
- Allocation-free frame samples, DOM performance overlay, optional WebGPU timestamp profiling, pipeline compile tracking, a CPU phase breakdown, leak alerts and field telemetry.
4
-
5
- Import `margoengine/stats` from the `margoengine` package, or `@margoengine/stats` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
6
-
7
- Depends on `@margoengine/math`, with `@margoengine/core` as a peer. Frame sampling uses a fixed Float64Array ring.
8
- `tick(milliseconds, drawCalls?, dispatches?)` performs numeric updates only;
9
- DOM strings and canvas drawing refresh separately every 150 ms. A timer refresh is skipped when nothing it draws
10
- has changed, so an idle page (no frames) does no DOM or canvas work; `refresh()` always redraws. Encoder/pass wrappers
11
- and asynchronous GPU readback allocate outside `tick`.
12
-
13
- `Stats`, `FramePhases`, `PipelineCompiles` and `FrameBeacon` detach from the scene
14
- that registered them when disposed directly. Another scene may use the same
15
- plugin name. Registration is scene-owned; frame listeners and device wrappers
16
- still observe the engine/device rather than providing independent scene timings.
17
-
18
- ```ts
19
- import {Engine} from 'margoengine/core';
20
- import {Stats} from 'margoengine/stats';
21
-
22
- const engine = await Engine.create(document.querySelector('canvas')!);
23
- const scene = engine.createScene('preview');
24
- const stats = new Stats();
25
- scene.use(stats);
26
- stats.dispose(); // detaches from preview and releases its overlay and listeners
27
- ```
28
-
29
- ```ts
30
- import {Stats} from 'margoengine/stats';
31
- import type {EngineKernel} from 'margoengine/core';
32
- function attach(engine: EngineKernel) {
33
- return Stats.attach(engine, {samples: 120, profiling: true});
34
- }
35
- ```
36
-
37
- GPU memory and a JSON report are in their own entry:
38
-
39
- ```ts
40
- import {Engine} from 'margoengine/core';
41
- import {Stats} from 'margoengine/stats';
42
- import {GPUMemory, statsReport} from 'margoengine/stats/report';
43
-
44
- const engine = await Engine.create(document.querySelector('canvas')!);
45
- const memory = GPUMemory.attach(engine.gpu!); // counts what is made from now on
46
- const stats = Stats.attach(engine);
47
- memory.view(stats); // a row in the panel
48
- engine.start();
49
- console.log(JSON.stringify(statsReport(stats, memory)));
50
- ```
51
-
52
- Sizes come from the descriptors, so driver padding is not in them, and objects made before `attach` are not seen. Several trackers on one device each count, and disposing one leaves the others counting (StatsPanels makes its own).
53
-
54
- Pipeline compile tracking is in its own entry. It shows which shader and pipeline compiles ran near a slow frame, and when. Read a hitch as evidence, not proof: times are CPU time around each call, and browsers compile in another process, so that is the most a page can see. It sees only what is compiled after it starts, so use `trackNext` below to include the engine's startup pipelines:
55
-
56
- ```ts
57
- import {Engine} from 'margoengine/core';
58
- import {Stats} from 'margoengine/stats';
59
- import {PipelineCompiles} from 'margoengine/stats/compile';
60
-
61
- const engine = await Engine.create(document.querySelector('canvas')!);
62
- const compiles = PipelineCompiles.attach(engine, {hitchMilliseconds: 33.4});
63
- compiles.view(Stats.attach(engine)); // totals and the newest hitch in the panel
64
- compiles.onHitch((hitch) => {
65
- console.warn(`${hitch.milliseconds.toFixed(1)} ms frame near`, hitch.compiles.map((record) => record.label));
66
- });
67
- engine.start();
68
- console.log(JSON.stringify(compiles)); // every record and hitch, when you want them
69
- ```
70
-
71
- Each record has `kind` (`'shader'`, `'render'` or `'compute'`), `label`, `blocking` (false for the `...Async` calls), `startedAt`, `frame`, `milliseconds` (null while an async call runs) and `failed`. A frame over `hitchMilliseconds` (default 33.4) with compiles in it or in the frame before is a hitch, with `frame`, `at`, `milliseconds` and `compiles`, blocking calls first and then the longest. `capacity` (default 256) is how many records and hitches stay; `count` goes on counting. Label your pipelines to read this easily, or pass `stacks: true` (default false) to keep where each call came from.
72
-
73
- To see the engine's own startup pipelines as well, start before the engine does:
74
-
75
- ```ts
76
- import {Engine} from 'margoengine/core';
77
- import {PipelineCompiles} from 'margoengine/stats/compile';
78
-
79
- const compiles = new PipelineCompiles().trackNext(); // catches the next device this page makes
80
- const engine = await Engine.create(document.querySelector('canvas')!);
81
- engine.use(compiles);
82
- console.log(compiles.toJSON().count, 'compiles so far');
83
- ```
84
-
85
- It follows the engine's device through a device restore and sees only what is compiled after `attach`, or after `trackNext`. Times are CPU time around each call. Browsers compile in another process, so a blocking call can return quickly and the stall arrives later, which is why the frame before counts too. A hitch is evidence that a compile was near a slow frame, not proof that it was the cause. With your own loop, call `compiles.track(device)` and `compiles.frame(milliseconds)` once per frame.
86
-
87
- The CPU phase breakdown times the kernel tick, culling, encoding and submit of each frame:
88
-
89
- ```ts
90
- import {Engine} from 'margoengine/core';
91
- import {Stats} from 'margoengine/stats';
92
- import {FramePhases} from 'margoengine/stats/phases';
93
-
94
- const engine = await Engine.create(document.querySelector('canvas')!);
95
- const phases = FramePhases.attach(engine, {samples: 120});
96
- phases.view(Stats.attach(engine)); // the averages in the panel
97
- engine.start();
98
- setInterval(() => console.log(phases.last.encode, phases.average().tick), 1000);
99
- ```
100
-
101
- All numbers are CPU milliseconds, and they add up to `total`:
102
-
103
- | Phase | What it covers |
104
- | --- | --- |
105
- | `update` | `onFrame` callbacks, plugin updates, resize and camera, up to the kernel tick |
106
- | `tick` | The kernel tick: world matrices and the frustum test, in one Wasm call |
107
- | `cull` | Collecting the visible instances into batches and preparing the frame, up to the command encoder. Core's frustum test runs inside the kernel's one Wasm call, so its time is in `tick`, not here |
108
- | `encode` | Every frame graph pass, then `encoder.finish()` |
109
- | `submit` | `queue.submit` |
110
- | `other` | The rest of the frame's task |
111
-
112
- `last` is the newest finished frame, one object updated in place; `average()` is the mean over the last `samples` frames (2 to 4096, default 120). `JSON.stringify(phases)` gives `frames`, `last` and `average`. A frame ends when its task does, so read `last` from a later task. Views in one frame add into that frame. Nothing is allocated per frame, and core is not changed: the entry wraps `store.tick`, `createCommandEncoder` and `queue.submit` and adds two frame graph passes until `dispose()`. On WebGL2 `encode` is the frame graph and `submit` is 0.
113
-
114
- The frustum test is part of the kernel call, so it counts as `tick`. Browsers round `performance.now()` to 5 to 100 microseconds, so trust the averages over a single short phase.
115
-
116
- Leak alerts warn when GPU memory or a resource count keeps growing:
117
-
118
- ```ts
119
- import {Engine} from 'margoengine/core';
120
- import {Stats} from 'margoengine/stats';
121
- import {GPUMemory} from 'margoengine/stats/report';
122
- import {LeakWatch} from 'margoengine/stats/leaks';
123
-
124
- const engine = await Engine.create(document.querySelector('canvas')!);
125
- const memory = GPUMemory.attach(engine.gpu!);
126
- const leaks = LeakWatch.attach(memory); // totals and every label, sampled each 5 s
127
- leaks.watch('meshes', () => engine.stats.visible, {min: 100}); // or any number of your own
128
- leaks.view(Stats.attach(engine)); // what is growing, in the panel
129
- leaks.onLeak((alert) => console.error(alert.name, alert.perMinute));
130
- engine.start();
131
- ```
132
-
133
- Each window of samples is cut into quarters and the lowest value of each is taken. A leak raises all four. A load, a level change or a pool that fills and empties does not, however high it peaks. An alert has `name`, `from`, `to` (the first and last low point), `perMinute` and `at`, and goes to `console.warn` unless you pass `warn` (null for none). It fires once, and can fire again after the growth stops. `leaks.leaking` names what is growing now, and `JSON.stringify(leaks)` gives every alert. Label your buffers and textures: the growing label is named, as `label <name> bytes` and `label <name> count`.
134
-
135
- | Option | Default | Meaning |
136
- | --- | --- | --- |
137
- | `intervalMilliseconds` | 5000 | Time between samples; 0 means you call `leaks.sample()` |
138
- | `window` | 48 | Samples judged together, 8 to 4096, a multiple of 4 |
139
- | `minBytes` | 1048576 | Bytes a low point must grow by to alert |
140
- | `minCount` | 16 | Objects a low point must grow by to alert |
141
- | `maxSeries` | 64 | Numbers followed at most; each label is two |
142
- | `warn` | `console.warn` | Called for each alert; null for none |
143
-
144
- It needs a full window before it can alert: four minutes by default. After a device loss the old objects stay counted, so make a new `GPUMemory` and `LeakWatch` for the new device.
145
-
146
- Field telemetry sends frame time percentiles from real sessions to an endpoint you choose:
147
-
148
- ```ts
149
- import {Engine} from 'margoengine/core';
150
- import {FrameBeacon} from 'margoengine/stats/beacon';
151
-
152
- const engine = await Engine.create(document.querySelector('canvas')!);
153
- const beacon = FrameBeacon.attach(engine, {
154
- endpoint: '/telemetry/frames',
155
- sampleRate: 0.1, // one session in ten
156
- context: {build: '1.2.3', scene: 'menu'}, // read at each send, so change it as you go
157
- });
158
- engine.start();
159
- ```
160
-
161
- Each report is a POST with this JSON body, sent as `text/plain` so that a cross-origin endpoint needs no preflight:
162
-
163
- ```json
164
- {"frames": 1794, "seconds": 30.01, "p50": 16.71, "p90": 17.48, "p95": 18.29, "p99": 33.12, "max": 41.2, "context": {"build": "1.2.3", "scene": "menu"}}
165
- ```
166
-
167
- That is all it holds: no identifier, no user agent, no address of its own. Whether to create a `FrameBeacon` at all, and whether to ask users first, is the app's choice.
168
-
169
- | Option | Default | Meaning |
170
- | --- | --- | --- |
171
- | `endpoint` | required | An http or https URL, relative to the page if relative |
172
- | `intervalMilliseconds` | 30000 | Time between reports; 0 means only on page hide and `flush()` |
173
- | `minFrames` | 60 | A report with fewer frames waits for more |
174
- | `sampleRate` | 1 | Share of sessions that report, decided once; `beacon.active` says which |
175
- | `context` | `{}` | Strings, numbers and booleans sent with every report |
176
- | `signal` | none | An `AbortSignal` that stops reporting, as `dispose()` does |
177
-
178
- It reports on the interval, when the page hides or closes, and on `dispose()`, through `navigator.sendBeacon`, or `fetch` with `keepalive` where that is missing or refuses. `sendBeacon` sends the page's cookies for the endpoint; the `fetch` route does not. Each report covers the frames since the last one. Paused time is left out. Percentiles use fixed bins, so memory stays at 2 KB however long the session is, and each reads at most 4.6% above the true value; `max` is exact. `sent` and `failed` count reports and `lastError` keeps the reason; nothing is retried. With your own loop, construct it and call `beacon.frame(milliseconds)`.
179
-
180
- The engine plugin samples actual frame intervals and counts direct/indirect draw
181
- and dispatch commands in its frame graph. Render bundle contents and commands
182
- recorded on other encoders are outside these counters. For a custom encoder,
183
- call `stats.track(encoder)` before recording and `stats.tick(deltaMs)` once per
184
- frame. Submit immediately after `encoder.finish()`; timestamp readback starts
185
- in the next microtask. The Stats plugin profiles one frame out of every 15;
186
- draw/dispatch counting and numeric ring sampling continue every frame.
187
-
188
- `{lowAllocationPasses: true}` is an explicit opt-in for applications that own their
189
- pass objects. It shares frozen prototypes for ordinary same-realm native WebGPU
190
- passes instead of attaching a separate owner and command methods to each pass.
191
- The default remains `false`, with the original own-property wrapper behavior.
192
- The opt-in falls back to that behavior for unknown factories, other realms,
193
- custom methods, existing own or inherited Stats owners, changed native
194
- methods/accessors, nonwritable inherited methods,
195
- and passes that cannot accept the derived prototype. Native command receivers,
196
- draw/dispatch counters and timestamp handling are preserved. Host allocations
197
- and profiling readbacks remain; this option does not promise zero allocation.
198
- Guards and inherited accessors can increase CPU cost, so measure your workload.
199
-
200
- This option changes reflective behavior: `Object.getPrototypeOf(pass)` is a
201
- shared frozen object that inherits from the native prototype; wrapper methods
202
- and the owner are inherited instead of own properties. Native `instanceof` and
203
- constructor identity are retained. Assigning an individual pass method creates
204
- an ordinary writable own property, and nested Stats instrumentation can replace
205
- the owner. Deleting an own method reveals the shared wrapper rather than the
206
- native method. If the application prevents extensions **after** wrapping, later
207
- method reassignment or nested Stats owner transfer cannot add an own property
208
- and throws; default Stats already has writable own methods and an owner slot
209
- and can update them in that situation. Keep the
210
- default when consumers depend on native prototype identity, own-property
211
- reflection, deletion, or these extensibility semantics. No shared prototype can
212
- be mutated through a returned pass.
213
-
214
- The hardware browser regression checks the actual built package's native pass
215
- layout, fallback behavior, counters, GPU output and timestamp readback. Build
216
- Stats with `node scripts/build-optional.js stats`, then run
217
- `node scripts/run-with-timeout.mjs -- node scripts/test-stats-native-passes.mjs`.
218
- It requires a hardware WebGPU adapter with timestamp-query support and writes
219
- its proof to `test-results/stats-native-passes.json`; it does not measure allocations.
220
-
221
- GPU timing is the sum of profiled pass durations, not presentation latency.
222
- Timing needs a device created with the `timestamp-query` feature: create the
223
- engine with `Engine.create(canvas, {features: ['timestamp-query']})` (requested only
224
- if the adapter offers it, and again after device restoration). Without it,
225
- `{profiling: true}` reports timing as unavailable and keeps CPU metrics and
226
- counters. Stats profiling is off by default and creates no queries, query buffers
227
- or readbacks. The overlay distinguishes off,
228
- supported warmup and unavailable timing; unsupported devices retain CPU metrics
229
- and counters. Custom devices can use
230
- `stats.enableGPUProfiling(device)` or the standalone `GPUProfiler` API:
231
- `beginFrame()`, `timestampWrites()` for each pass descriptor, `resolve(encoder)`,
232
- submit, then `await read()`. Frames while a readback is pending are skipped;
233
- samples above 128 passes are omitted. Existing timestampWrites are preserved
234
- and those passes are excluded from this profiler.
235
-
236
- The standalone profiler also exposes the latest complete sample through
237
- `passMilliseconds` (a reused 128-element Float64Array) and `passCount`, in the
238
- order that `timestampWrites()` was called. `milliseconds` remains the sum of
239
- those pass durations. `elapsedMilliseconds` spans the first profiled pass beginning
240
- to the last profiled pass end, including intervening copies, unprofiled passes
241
- and GPU gaps. Commands before the first pass or after the last pass, queue waiting
242
- before execution and presentation are outside that span. Timestamp precision
243
- depends on the browser. Unsupported, empty, overflowing or invalid samples clear
244
- all timing fields; busy readbacks retain the last complete sample. No additional
245
- GPU resources are allocated per sample.
246
-
247
- Stats exposes that same completed sample through read-only getters
248
- `gpuPassMilliseconds` (the existing reused array, or null when unsupported/off),
249
- `gpuPassCount` and `gpuElapsedMilliseconds`. Read only the first `gpuPassCount`
250
- entries. The array is replaced when a new device requires a new profiler; no copy
251
- or array allocation occurs when reading these getters. The overlay's GPU span
252
- includes the inter-pass work described above and is not a displayed-frame time.
253
-
254
- `gpuSampleId` increments after each valid completed GPU readback, even when its
255
- duration equals the previous sample. It stays monotonic through device replacement;
256
- unsampled frames, pending reads, and invalid samples do not increment it.
257
- `gpuSampleEncodedAt` records the CPU `performance.now()` at the sampled encoder's
258
- `finish()`, and `gpuSampleReadAt` records the CPU time when its readback completes.
259
- These timestamps describe host encoding/readback, not GPU execution on a host clock.
260
- They are null before a valid sample and when timing is cleared. They can correlate
261
- events with samples; temporal proximity alone does not establish a cause.
262
-
263
- `dispose()` removes the overlay, timer and plugin and destroys owned GPU resources.
264
-
265
- ## Submitted geometry counters
266
-
267
- Import `GeometryStats` from `@margoengine/stats/geometry` (or `margoengine/stats/geometry`).
268
- `GeometryStats.attach(engine, options)` counts draw arguments on WebGPU and native
269
- WebGL2 without reading geometry back. `toJSON()` copies the current frame's triangles,
270
- vertices, instances, drawCalls and unknownDraws. `view(stats)` adds a row to an existing
271
- Stats overlay, refreshed every 150 ms.
272
-
273
- Vertices means submitted vertex/index references multiplied by instance count. Indexed
274
- draws count repeated indices, rather than unique vertices. Triangle lists count
275
- floor(count/3) triangles per instance; triangle strips and WebGL triangle fans count
276
- max(0,count-2). Line and point primitives contribute vertices but no triangles. A draw
277
- with zero count or zero instances still contributes a draw call, with no geometry.
278
- Triangle counts are assembled candidates before primitive restart, degeneracy, clipping
279
- or culling; they are not a count of visible rasterized triangles.
280
-
281
- With a custom WebGPU loop, call `trackDevice(device)` before creating pipelines to
282
- capture their topology, or `pipeline(existingPipeline, topology)` for an earlier pipeline.
283
- Unregistered pipelines default to triangle-list. Call `track(encoder)` before recording
284
- its render passes, or `trackGL(context)` for native GL commands. `beginFrame()` resets
285
- the counters once per custom frame. The engine attachment resets once per task so
286
- multiple engine views in that task contribute to the same frame.
287
-
288
- Indirect GPU arguments are opaque. The optional `indirect(buffer, offset, indexed)`
289
- callback supplies CPU metadata `{count, instances}` at draw time; it is not cached.
290
- Without it, an indirect draw contributes to drawCalls and unknownDraws, without invented
291
- geometry counts. Each opaque executed render bundle contributes one unknownDraws entry;
292
- its internal draws are outside drawCalls and geometry totals. This counter is not a
293
- measurement of unique geometry, visibility or GPU vertex-cache work. Dispose it to
294
- restore its device/context wrappers, remove its overlay row and detach the plugin.
295
-
296
-
297
- ```ts
298
- import {Engine, box, PbrMaterial} from '@margoengine/core';
299
- import {Stats} from '@margoengine/stats';
300
- import {GeometryStats} from '@margoengine/stats/geometry';
301
- const canvas = document.body.appendChild(document.createElement('canvas'));
302
- canvas.width = 480; canvas.height = 320;
303
- const engine = await Engine.create(canvas);
304
- const stats = Stats.attach(engine);
305
- const geometry = GeometryStats.attach(engine);
306
- geometry.view(stats);
307
- engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial());
308
- engine.render();
309
- const report = geometry.toJSON();
310
- if (report.triangles !== 12) throw new Error('Expected one submitted box');
311
- console.log(report);
312
- geometry.dispose(); stats.dispose(); engine.dispose(); canvas.remove();
313
- ```
314
-
315
- ## Asynchronous native WebGL2 timing
316
-
317
- Import `GLStats` from `@margoengine/stats/gl` or `margoengine/stats/gl`. Attach it before
318
- other optional plugins register passes so their pass names are captured automatically.
319
- It wraps native draws and uses EXT_disjoint_timer_query_webgl2 when available. Its
320
- `drawCalls` includes arrays, elements, range-elements and instanced calls. Those counters
321
- remain useful when `supported` is false and GPU timing is unavailable.
322
-
323
- For a custom loop, construct a GLStats, call `track(gl)`, and pair `beginFrame()` with
324
- `endFrame()`. Passing gl directly to beginFrame also starts tracking it. A false return
325
- means timing did not start; still end the frame to close the scope. Pair non-nested
326
- `beginPass(name)` and `endPass()`, or use `pass(name, synchronousFunction)` to close the
327
- scope even when the function throws. Call `poll()` from a later task/frame to collect
328
- only queries whose results are available. No synchronous GPU wait is introduced.
329
-
330
- `frameMilliseconds` is the sum of measured frame segments; `passes` holds completed
331
- named intervals, in milliseconds. `sampleId` advances on a valid completed sample;
332
- the current draw count can therefore belong to a newer frame than the GPU timings.
333
- `toJSON()` returns a copy and `view(stats)` adds a 150 ms overlay row. Default
334
- `maxPasses` is 128 (allowed 1..128); maxPendingFrames is 4 (allowed 1..8). Excess pending
335
- frames or an existing external timer query increase droppedFrames instead of nesting
336
- queries. Exceeding the pass limit invalidates that sample.
337
-
338
- Disjoint or lost-context samples clear timing to null and discard their pass list.
339
- Null means unavailable, rather than zero GPU work. Pending queries retain the last
340
- completed timing. After context restoration, track the restored context again to
341
- reacquire its extension. Disposal restores owned wrappers, deletes owned queries,
342
- removes the optional overlay row and detaches the plugin.
343
-
344
-
345
- ```ts
346
- import {Engine, box, PbrMaterial} from '@margoengine/core';
347
- import {GLStats} from '@margoengine/stats/gl';
348
- import {webglRenderer} from '@margoengine/webgl2-compat/preview';
349
- const canvas = document.body.appendChild(document.createElement('canvas'));
350
- const engine = await Engine.create(canvas, {backend: 'webgl2', fallback: webglRenderer});
351
- const timing = GLStats.attach(engine); // Before optional pass plugins.
352
- engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial());
353
- engine.render();
354
- await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
355
- timing.poll(); // Read only results already available; pending samples stay null.
356
- console.log(timing.supported, timing.toJSON());
357
- timing.dispose(); engine.dispose(); canvas.remove();
358
- ```
359
-
360
- ## Four metric histories
361
-
362
- Import `StatsPanels` from `@margoengine/stats/panels` or `margoengine/stats/panels`.
363
- `StatsPanels.attach(engine, options)` combines FPS, CPU milliseconds, GPU milliseconds
364
- and memory into fixed-capacity histories. `samples` defaults to 120 (2..4096),
365
- `refreshMilliseconds` to 150 (16..60000), and an owned overlay's parent to document.body.
366
- Pass an existing `stats` to borrow its overlay; otherwise the panels create their own.
367
-
368
- FPS comes from Stats frame sampling; CPU time comes from FramePhases' completed task.
369
- WebGPU GPU time is the sum of profiled pass timestamps, with profiling attempted every
370
- 15 encoders and read back asynchronously. Request timestamp-query in Engine.create's
371
- features for supported adapters. WebGL2 uses GLStats and its asynchronous timer queries.
372
- Neither metric measures presentation latency. Named GPU passes and their times come
373
- from the same completed sample: WebGPU uses descriptor labels (or generated render/
374
- compute names), while WebGL2 uses the registered pass names. Passes that already own
375
- WebGPU timestampWrites are excluded from the panels' profiler. Pending reads reuse the
376
- last completed sample; do not interpret every graph point as a new GPU measurement.
377
-
378
- Memory defaults to descriptor-based GPU resource tracking on WebGPU, observing only
379
- resources created after attachment. On other backends it uses browser JS heap size
380
- when exposed, otherwise null. These are different scopes, neither is process memory
381
- or driver allocation. `memory: () => numberOrNull` supplies an application sampler in
382
- bytes. Graph labels show MiB; reports retain bytes. Labels include latest, average and
383
- peak over finite values retained in the history. Null values produce gaps and are
384
- excluded from averages, rather than being plotted as zero.
385
-
386
- For a custom loop, construct StatsPanels and call `sample` with fps, cpuMilliseconds,
387
- gpuMilliseconds and memoryBytes, plus optional named passes. Samples must be finite
388
- and nonnegative; only GPU and memory may be null. `sample` updates the rings separately
389
- from DOM/canvas work; `refresh()` redraws immediately, alongside the refresh timer.
390
- `toJSON()` returns oldest-first arrays with null gaps and a copy of the latest pass list.
391
-
392
- Disposal removes histories, timer, owned phase/timing/memory trackers and the panels
393
- plugin. A borrowed Stats remains alive and its original graph display is restored;
394
- an owned Stats is disposed with the panels. Engine disposal performs this cleanup too.
395
-
396
-
397
- ```ts
398
- import {Engine} from '@margoengine/core';
399
- import {Stats} from '@margoengine/stats';
400
- import {StatsPanels} from '@margoengine/stats/panels';
401
- const canvas = document.body.appendChild(document.createElement('canvas'));
402
- canvas.width = 480; canvas.height = 320;
403
- const engine = await Engine.create(canvas);
404
- const stats = Stats.attach(engine);
405
- const panels = StatsPanels.attach(engine, {stats, samples: 120});
406
- engine.render();
407
- console.log(panels.toJSON());
408
- panels.dispose(); // Borrowed stats remains attached.
409
- stats.dispose(); engine.dispose(); canvas.remove();
410
- ```
411
-
412
- ## Preview tier contract
413
-
414
- `GeometryStats`, `GLStats` and `StatsPanels` are reviewed preview routes in `scripts/check-preview-contract.mjs` (2026-11-10; 1, 2 and 1 `backend` tests). On the small WebGL2 preview `GeometryStats` counts WebGL2 draws, `GLStats` times named passes with WebGL2 timer queries, and `StatsPanels` uses `GLStats` for its GPU graph and pass list. Evidence: `test/preview.test.js` (new: a preview engine, one WebGL2 draw counted as 2 triangles and the `main` pass timed into the panel) and `test/gl.test.js`. No behaviour changed; the missing rows kept `npm run verify` red.
1
+ # @margoengine/stats
2
+
3
+ Allocation-free frame samples, DOM performance overlay, optional WebGPU timestamp profiling, pipeline compile tracking, a CPU phase breakdown, leak alerts and field telemetry.
4
+
5
+ Import `margoengine/stats` from the `margoengine` package, or `@margoengine/stats` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
6
+
7
+ Depends on `@margoengine/math`, with `@margoengine/core` as a peer. Frame sampling uses a fixed Float64Array ring.
8
+ `tick(milliseconds, drawCalls?, dispatches?)` performs numeric updates only;
9
+ DOM strings and canvas drawing refresh separately every 150 ms. A timer refresh is skipped when nothing it draws
10
+ has changed, so an idle page (no frames) does no DOM or canvas work; `refresh()` always redraws. Encoder/pass wrappers
11
+ and asynchronous GPU readback allocate outside `tick`.
12
+
13
+ `Stats`, `FramePhases`, `PipelineCompiles` and `FrameBeacon` detach from the scene
14
+ that registered them when disposed directly. Another scene may use the same
15
+ plugin name. Registration is scene-owned; frame listeners and device wrappers
16
+ still observe the engine/device rather than providing independent scene timings.
17
+
18
+ ```ts
19
+ import {Engine} from 'margoengine/core';
20
+ import {Stats} from 'margoengine/stats';
21
+
22
+ const engine = await Engine.create(document.querySelector('canvas')!);
23
+ const scene = engine.createScene('preview');
24
+ const stats = new Stats();
25
+ scene.use(stats);
26
+ stats.dispose(); // detaches from preview and releases its overlay and listeners
27
+ ```
28
+
29
+ ```ts
30
+ import {Stats} from 'margoengine/stats';
31
+ import type {EngineKernel} from 'margoengine/core';
32
+ function attach(engine: EngineKernel) {
33
+ return Stats.attach(engine, {samples: 120, profiling: true});
34
+ }
35
+ ```
36
+
37
+ GPU memory and a JSON report are in their own entry:
38
+
39
+ ```ts
40
+ import {Engine} from 'margoengine/core';
41
+ import {Stats} from 'margoengine/stats';
42
+ import {GPUMemory, statsReport} from 'margoengine/stats/report';
43
+
44
+ const engine = await Engine.create(document.querySelector('canvas')!);
45
+ const memory = GPUMemory.attach(engine.gpu!); // counts what is made from now on
46
+ const stats = Stats.attach(engine);
47
+ memory.view(stats); // a row in the panel
48
+ engine.start();
49
+ console.log(JSON.stringify(statsReport(stats, memory)));
50
+ ```
51
+
52
+ Sizes come from the descriptors, so driver padding is not in them, and objects made before `attach` are not seen. Several trackers on one device each count, and disposing one leaves the others counting (StatsPanels makes its own).
53
+
54
+ Pipeline compile tracking is in its own entry. It shows which shader and pipeline compiles ran near a slow frame, and when. Read a hitch as evidence, not proof: times are CPU time around each call, and browsers compile in another process, so that is the most a page can see. It sees only what is compiled after it starts, so use `trackNext` below to include the engine's startup pipelines:
55
+
56
+ ```ts
57
+ import {Engine} from 'margoengine/core';
58
+ import {Stats} from 'margoengine/stats';
59
+ import {PipelineCompiles} from 'margoengine/stats/compile';
60
+
61
+ const engine = await Engine.create(document.querySelector('canvas')!);
62
+ const compiles = PipelineCompiles.attach(engine, {hitchMilliseconds: 33.4});
63
+ compiles.view(Stats.attach(engine)); // totals and the newest hitch in the panel
64
+ compiles.onHitch((hitch) => {
65
+ console.warn(`${hitch.milliseconds.toFixed(1)} ms frame near`, hitch.compiles.map((record) => record.label));
66
+ });
67
+ engine.start();
68
+ console.log(JSON.stringify(compiles)); // every record and hitch, when you want them
69
+ ```
70
+
71
+ Each record has `kind` (`'shader'`, `'render'` or `'compute'`), `label`, `blocking` (false for the `...Async` calls), `startedAt`, `frame`, `milliseconds` (null while an async call runs) and `failed`. A frame over `hitchMilliseconds` (default 33.4) with compiles in it or in the frame before is a hitch, with `frame`, `at`, `milliseconds` and `compiles`, blocking calls first and then the longest. `capacity` (default 256) is how many records and hitches stay; `count` goes on counting. Label your pipelines to read this easily, or pass `stacks: true` (default false) to keep where each call came from.
72
+
73
+ To see the engine's own startup pipelines as well, start before the engine does:
74
+
75
+ ```ts
76
+ import {Engine} from 'margoengine/core';
77
+ import {PipelineCompiles} from 'margoengine/stats/compile';
78
+
79
+ const compiles = new PipelineCompiles().trackNext(); // catches the next device this page makes
80
+ const engine = await Engine.create(document.querySelector('canvas')!);
81
+ engine.use(compiles);
82
+ console.log(compiles.toJSON().count, 'compiles so far');
83
+ ```
84
+
85
+ It follows the engine's device through a device restore and sees only what is compiled after `attach`, or after `trackNext`. Times are CPU time around each call. Browsers compile in another process, so a blocking call can return quickly and the stall arrives later, which is why the frame before counts too. A hitch is evidence that a compile was near a slow frame, not proof that it was the cause. With your own loop, call `compiles.track(device)` and `compiles.frame(milliseconds)` once per frame.
86
+
87
+ The CPU phase breakdown times the kernel tick, culling, encoding and submit of each frame:
88
+
89
+ ```ts
90
+ import {Engine} from 'margoengine/core';
91
+ import {Stats} from 'margoengine/stats';
92
+ import {FramePhases} from 'margoengine/stats/phases';
93
+
94
+ const engine = await Engine.create(document.querySelector('canvas')!);
95
+ const phases = FramePhases.attach(engine, {samples: 120});
96
+ phases.view(Stats.attach(engine)); // the averages in the panel
97
+ engine.start();
98
+ setInterval(() => console.log(phases.last.encode, phases.average().tick), 1000);
99
+ ```
100
+
101
+ All numbers are CPU milliseconds, and they add up to `total`:
102
+
103
+ | Phase | What it covers |
104
+ | --- | --- |
105
+ | `update` | `onFrame` callbacks, plugin updates, resize and camera, up to the kernel tick |
106
+ | `tick` | The kernel tick: world matrices and the frustum test, in one Wasm call |
107
+ | `cull` | Collecting the visible instances into batches and preparing the frame, up to the command encoder. Core's frustum test runs inside the kernel's one Wasm call, so its time is in `tick`, not here |
108
+ | `encode` | Every frame graph pass, then `encoder.finish()` |
109
+ | `submit` | `queue.submit` |
110
+ | `other` | The rest of the frame's task |
111
+
112
+ `last` is the newest finished frame, one object updated in place; `average()` is the mean over the last `samples` frames (2 to 4096, default 120). `JSON.stringify(phases)` gives `frames`, `last` and `average`. A frame ends when its task does, so read `last` from a later task. Views in one frame add into that frame. Nothing is allocated per frame, and core is not changed: the entry wraps `store.tick`, `createCommandEncoder` and `queue.submit` and adds two frame graph passes until `dispose()`. On WebGL2 `encode` is the frame graph and `submit` is 0.
113
+
114
+ The frustum test is part of the kernel call, so it counts as `tick`. Browsers round `performance.now()` to 5 to 100 microseconds, so trust the averages over a single short phase.
115
+
116
+ Leak alerts warn when GPU memory or a resource count keeps growing:
117
+
118
+ ```ts
119
+ import {Engine} from 'margoengine/core';
120
+ import {Stats} from 'margoengine/stats';
121
+ import {GPUMemory} from 'margoengine/stats/report';
122
+ import {LeakWatch} from 'margoengine/stats/leaks';
123
+
124
+ const engine = await Engine.create(document.querySelector('canvas')!);
125
+ const memory = GPUMemory.attach(engine.gpu!);
126
+ const leaks = LeakWatch.attach(memory); // totals and every label, sampled each 5 s
127
+ leaks.watch('meshes', () => engine.stats.visible, {min: 100}); // or any number of your own
128
+ leaks.view(Stats.attach(engine)); // what is growing, in the panel
129
+ leaks.onLeak((alert) => console.error(alert.name, alert.perMinute));
130
+ engine.start();
131
+ ```
132
+
133
+ Each window of samples is cut into quarters and the lowest value of each is taken. A leak raises all four. A load, a level change or a pool that fills and empties does not, however high it peaks. An alert has `name`, `from`, `to` (the first and last low point), `perMinute` and `at`, and goes to `console.warn` unless you pass `warn` (null for none). It fires once, and can fire again after the growth stops. `leaks.leaking` names what is growing now, and `JSON.stringify(leaks)` gives every alert. Label your buffers and textures: the growing label is named, as `label <name> bytes` and `label <name> count`.
134
+
135
+ | Option | Default | Meaning |
136
+ | --- | --- | --- |
137
+ | `intervalMilliseconds` | 5000 | Time between samples; 0 means you call `leaks.sample()` |
138
+ | `window` | 48 | Samples judged together, 8 to 4096, a multiple of 4 |
139
+ | `minBytes` | 1048576 | Bytes a low point must grow by to alert |
140
+ | `minCount` | 16 | Objects a low point must grow by to alert |
141
+ | `maxSeries` | 64 | Numbers followed at most; each label is two |
142
+ | `warn` | `console.warn` | Called for each alert; null for none |
143
+
144
+ It needs a full window before it can alert: four minutes by default. After a device loss the old objects stay counted, so make a new `GPUMemory` and `LeakWatch` for the new device.
145
+
146
+ Field telemetry sends frame time percentiles from real sessions to an endpoint you choose:
147
+
148
+ ```ts
149
+ import {Engine} from 'margoengine/core';
150
+ import {FrameBeacon} from 'margoengine/stats/beacon';
151
+
152
+ const engine = await Engine.create(document.querySelector('canvas')!);
153
+ const beacon = FrameBeacon.attach(engine, {
154
+ endpoint: '/telemetry/frames',
155
+ sampleRate: 0.1, // one session in ten
156
+ context: {build: '1.2.3', scene: 'menu'}, // read at each send, so change it as you go
157
+ });
158
+ engine.start();
159
+ ```
160
+
161
+ Each report is a POST with this JSON body, sent as `text/plain` so that a cross-origin endpoint needs no preflight:
162
+
163
+ ```json
164
+ {"frames": 1794, "seconds": 30.01, "p50": 16.71, "p90": 17.48, "p95": 18.29, "p99": 33.12, "max": 41.2, "context": {"build": "1.2.3", "scene": "menu"}}
165
+ ```
166
+
167
+ That is all it holds: no identifier, no user agent, no address of its own. Whether to create a `FrameBeacon` at all, and whether to ask users first, is the app's choice.
168
+
169
+ | Option | Default | Meaning |
170
+ | --- | --- | --- |
171
+ | `endpoint` | required | An http or https URL, relative to the page if relative |
172
+ | `intervalMilliseconds` | 30000 | Time between reports; 0 means only on page hide and `flush()` |
173
+ | `minFrames` | 60 | A report with fewer frames waits for more |
174
+ | `sampleRate` | 1 | Share of sessions that report, decided once; `beacon.active` says which |
175
+ | `context` | `{}` | Strings, numbers and booleans sent with every report |
176
+ | `signal` | none | An `AbortSignal` that stops reporting, as `dispose()` does |
177
+
178
+ It reports on the interval, when the page hides or closes, and on `dispose()`, through `navigator.sendBeacon`, or `fetch` with `keepalive` where that is missing or refuses. `sendBeacon` sends the page's cookies for the endpoint; the `fetch` route does not. Each report covers the frames since the last one. Paused time is left out. Percentiles use fixed bins, so memory stays at 2 KB however long the session is, and each reads at most 4.6% above the true value; `max` is exact. `sent` and `failed` count reports and `lastError` keeps the reason; nothing is retried. With your own loop, construct it and call `beacon.frame(milliseconds)`.
179
+
180
+ The engine plugin samples actual frame intervals and counts direct/indirect draw
181
+ and dispatch commands in its frame graph. Render bundle contents and commands
182
+ recorded on other encoders are outside these counters. For a custom encoder,
183
+ call `stats.track(encoder)` before recording and `stats.tick(deltaMs)` once per
184
+ frame. Submit immediately after `encoder.finish()`; timestamp readback starts
185
+ in the next microtask. The Stats plugin profiles one frame out of every 15;
186
+ draw/dispatch counting and numeric ring sampling continue every frame.
187
+
188
+ `{lowAllocationPasses: true}` is an explicit opt-in for applications that own their
189
+ pass objects. It shares frozen prototypes for ordinary same-realm native WebGPU
190
+ passes instead of attaching a separate owner and command methods to each pass.
191
+ The default remains `false`, with the original own-property wrapper behavior.
192
+ The opt-in falls back to that behavior for unknown factories, other realms,
193
+ custom methods, existing own or inherited Stats owners, changed native
194
+ methods/accessors, nonwritable inherited methods,
195
+ and passes that cannot accept the derived prototype. Native command receivers,
196
+ draw/dispatch counters and timestamp handling are preserved. Host allocations
197
+ and profiling readbacks remain; this option does not promise zero allocation.
198
+ Guards and inherited accessors can increase CPU cost, so measure your workload.
199
+
200
+ This option changes reflective behavior: `Object.getPrototypeOf(pass)` is a
201
+ shared frozen object that inherits from the native prototype; wrapper methods
202
+ and the owner are inherited instead of own properties. Native `instanceof` and
203
+ constructor identity are retained. Assigning an individual pass method creates
204
+ an ordinary writable own property, and nested Stats instrumentation can replace
205
+ the owner. Deleting an own method reveals the shared wrapper rather than the
206
+ native method. If the application prevents extensions **after** wrapping, later
207
+ method reassignment or nested Stats owner transfer cannot add an own property
208
+ and throws; default Stats already has writable own methods and an owner slot
209
+ and can update them in that situation. Keep the
210
+ default when consumers depend on native prototype identity, own-property
211
+ reflection, deletion, or these extensibility semantics. No shared prototype can
212
+ be mutated through a returned pass.
213
+
214
+ The hardware browser regression checks the actual built package's native pass
215
+ layout, fallback behavior, counters, GPU output and timestamp readback. Build
216
+ Stats with `node scripts/build-optional.js stats`, then run
217
+ `node scripts/run-with-timeout.mjs -- node scripts/test-stats-native-passes.mjs`.
218
+ It requires a hardware WebGPU adapter with timestamp-query support and writes
219
+ its proof to `test-results/stats-native-passes.json`; it does not measure allocations.
220
+
221
+ GPU timing is the sum of profiled pass durations, not presentation latency.
222
+ Timing needs a device created with the `timestamp-query` feature: create the
223
+ engine with `Engine.create(canvas, {features: ['timestamp-query']})` (requested only
224
+ if the adapter offers it, and again after device restoration). Without it,
225
+ `{profiling: true}` reports timing as unavailable and keeps CPU metrics and
226
+ counters. Stats profiling is off by default and creates no queries, query buffers
227
+ or readbacks. The overlay distinguishes off,
228
+ supported warmup and unavailable timing; unsupported devices retain CPU metrics
229
+ and counters. Custom devices can use
230
+ `stats.enableGPUProfiling(device)` or the standalone `GPUProfiler` API:
231
+ `beginFrame()`, `timestampWrites()` for each pass descriptor, `resolve(encoder)`,
232
+ submit, then `await read()`. Frames while a readback is pending are skipped;
233
+ samples above 128 passes are omitted. Existing timestampWrites are preserved
234
+ and those passes are excluded from this profiler.
235
+
236
+ The standalone profiler also exposes the latest complete sample through
237
+ `passMilliseconds` (a reused 128-element Float64Array) and `passCount`, in the
238
+ order that `timestampWrites()` was called. `milliseconds` remains the sum of
239
+ those pass durations. `elapsedMilliseconds` spans the first profiled pass beginning
240
+ to the last profiled pass end, including intervening copies, unprofiled passes
241
+ and GPU gaps. Commands before the first pass or after the last pass, queue waiting
242
+ before execution and presentation are outside that span. Timestamp precision
243
+ depends on the browser. Unsupported, empty, overflowing or invalid samples clear
244
+ all timing fields; busy readbacks retain the last complete sample. No additional
245
+ GPU resources are allocated per sample.
246
+
247
+ Stats exposes that same completed sample through read-only getters
248
+ `gpuPassMilliseconds` (the existing reused array, or null when unsupported/off),
249
+ `gpuPassCount` and `gpuElapsedMilliseconds`. Read only the first `gpuPassCount`
250
+ entries. The array is replaced when a new device requires a new profiler; no copy
251
+ or array allocation occurs when reading these getters. The overlay's GPU span
252
+ includes the inter-pass work described above and is not a displayed-frame time.
253
+
254
+ `gpuSampleId` increments after each valid completed GPU readback, even when its
255
+ duration equals the previous sample. It stays monotonic through device replacement;
256
+ unsampled frames, pending reads, and invalid samples do not increment it.
257
+ `gpuSampleEncodedAt` records the CPU `performance.now()` at the sampled encoder's
258
+ `finish()`, and `gpuSampleReadAt` records the CPU time when its readback completes.
259
+ These timestamps describe host encoding/readback, not GPU execution on a host clock.
260
+ They are null before a valid sample and when timing is cleared. They can correlate
261
+ events with samples; temporal proximity alone does not establish a cause.
262
+
263
+ `dispose()` removes the overlay, timer and plugin and destroys owned GPU resources.
264
+
265
+ ## Submitted geometry counters
266
+
267
+ Import `GeometryStats` from `@margoengine/stats/geometry` (or `margoengine/stats/geometry`).
268
+ `GeometryStats.attach(engine, options)` counts draw arguments on WebGPU and native
269
+ WebGL2 without reading geometry back. `toJSON()` copies the current frame's triangles,
270
+ vertices, instances, drawCalls and unknownDraws. `view(stats)` adds a row to an existing
271
+ Stats overlay, refreshed every 150 ms.
272
+
273
+ Vertices means submitted vertex/index references multiplied by instance count. Indexed
274
+ draws count repeated indices, rather than unique vertices. Triangle lists count
275
+ floor(count/3) triangles per instance; triangle strips and WebGL triangle fans count
276
+ max(0,count-2). Line and point primitives contribute vertices but no triangles. A draw
277
+ with zero count or zero instances still contributes a draw call, with no geometry.
278
+ Triangle counts are assembled candidates before primitive restart, degeneracy, clipping
279
+ or culling; they are not a count of visible rasterized triangles.
280
+
281
+ With a custom WebGPU loop, call `trackDevice(device)` before creating pipelines to
282
+ capture their topology, or `pipeline(existingPipeline, topology)` for an earlier pipeline.
283
+ Unregistered pipelines default to triangle-list. Call `track(encoder)` before recording
284
+ its render passes, or `trackGL(context)` for native GL commands. `beginFrame()` resets
285
+ the counters once per custom frame. The engine attachment resets once per task so
286
+ multiple engine views in that task contribute to the same frame.
287
+
288
+ Indirect GPU arguments are opaque. The optional `indirect(buffer, offset, indexed)`
289
+ callback supplies CPU metadata `{count, instances}` at draw time; it is not cached.
290
+ Without it, an indirect draw contributes to drawCalls and unknownDraws, without invented
291
+ geometry counts. Each opaque executed render bundle contributes one unknownDraws entry;
292
+ its internal draws are outside drawCalls and geometry totals. This counter is not a
293
+ measurement of unique geometry, visibility or GPU vertex-cache work. Dispose it to
294
+ restore its device/context wrappers, remove its overlay row and detach the plugin.
295
+
296
+
297
+ ```ts
298
+ import {Engine, box, PbrMaterial} from '@margoengine/core';
299
+ import {Stats} from '@margoengine/stats';
300
+ import {GeometryStats} from '@margoengine/stats/geometry';
301
+ const canvas = document.body.appendChild(document.createElement('canvas'));
302
+ canvas.width = 480; canvas.height = 320;
303
+ const engine = await Engine.create(canvas);
304
+ const stats = Stats.attach(engine);
305
+ const geometry = GeometryStats.attach(engine);
306
+ geometry.view(stats);
307
+ engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial());
308
+ engine.render();
309
+ const report = geometry.toJSON();
310
+ if (report.triangles !== 12) throw new Error('Expected one submitted box');
311
+ console.log(report);
312
+ geometry.dispose(); stats.dispose(); engine.dispose(); canvas.remove();
313
+ ```
314
+
315
+ ## Asynchronous native WebGL2 timing
316
+
317
+ Import `GLStats` from `@margoengine/stats/gl` or `margoengine/stats/gl`. Attach it before
318
+ other optional plugins register passes so their pass names are captured automatically.
319
+ It wraps native draws and uses EXT_disjoint_timer_query_webgl2 when available. Its
320
+ `drawCalls` includes arrays, elements, range-elements and instanced calls. Those counters
321
+ remain useful when `supported` is false and GPU timing is unavailable.
322
+
323
+ For a custom loop, construct a GLStats, call `track(gl)`, and pair `beginFrame()` with
324
+ `endFrame()`. Passing gl directly to beginFrame also starts tracking it. A false return
325
+ means timing did not start; still end the frame to close the scope. Pair non-nested
326
+ `beginPass(name)` and `endPass()`, or use `pass(name, synchronousFunction)` to close the
327
+ scope even when the function throws. Call `poll()` from a later task/frame to collect
328
+ only queries whose results are available. No synchronous GPU wait is introduced.
329
+
330
+ `frameMilliseconds` is the sum of measured frame segments; `passes` holds completed
331
+ named intervals, in milliseconds. `sampleId` advances on a valid completed sample;
332
+ the current draw count can therefore belong to a newer frame than the GPU timings.
333
+ `toJSON()` returns a copy and `view(stats)` adds a 150 ms overlay row. Default
334
+ `maxPasses` is 128 (allowed 1..128); maxPendingFrames is 4 (allowed 1..8). Excess pending
335
+ frames or an existing external timer query increase droppedFrames instead of nesting
336
+ queries. Exceeding the pass limit invalidates that sample.
337
+
338
+ Disjoint or lost-context samples clear timing to null and discard their pass list.
339
+ Null means unavailable, rather than zero GPU work. Pending queries retain the last
340
+ completed timing. After context restoration, track the restored context again to
341
+ reacquire its extension. Disposal restores owned wrappers, deletes owned queries,
342
+ removes the optional overlay row and detaches the plugin.
343
+
344
+
345
+ ```ts
346
+ import {Engine, box, PbrMaterial} from '@margoengine/core';
347
+ import {GLStats} from '@margoengine/stats/gl';
348
+ import {webglRenderer} from '@margoengine/webgl2-compat/preview';
349
+ const canvas = document.body.appendChild(document.createElement('canvas'));
350
+ const engine = await Engine.create(canvas, {backend: 'webgl2', fallback: webglRenderer});
351
+ const timing = GLStats.attach(engine); // Before optional pass plugins.
352
+ engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial());
353
+ engine.render();
354
+ await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
355
+ timing.poll(); // Read only results already available; pending samples stay null.
356
+ console.log(timing.supported, timing.toJSON());
357
+ timing.dispose(); engine.dispose(); canvas.remove();
358
+ ```
359
+
360
+ ## Four metric histories
361
+
362
+ Import `StatsPanels` from `@margoengine/stats/panels` or `margoengine/stats/panels`.
363
+ `StatsPanels.attach(engine, options)` combines FPS, CPU milliseconds, GPU milliseconds
364
+ and memory into fixed-capacity histories. `samples` defaults to 120 (2..4096),
365
+ `refreshMilliseconds` to 150 (16..60000), and an owned overlay's parent to document.body.
366
+ Pass an existing `stats` to borrow its overlay; otherwise the panels create their own.
367
+
368
+ FPS comes from Stats frame sampling; CPU time comes from FramePhases' completed task.
369
+ WebGPU GPU time is the sum of profiled pass timestamps, with profiling attempted every
370
+ 15 encoders and read back asynchronously. Request timestamp-query in Engine.create's
371
+ features for supported adapters. WebGL2 uses GLStats and its asynchronous timer queries.
372
+ Neither metric measures presentation latency. Named GPU passes and their times come
373
+ from the same completed sample: WebGPU uses descriptor labels (or generated render/
374
+ compute names), while WebGL2 uses the registered pass names. Passes that already own
375
+ WebGPU timestampWrites are excluded from the panels' profiler. Pending reads reuse the
376
+ last completed sample; do not interpret every graph point as a new GPU measurement.
377
+
378
+ Memory defaults to descriptor-based GPU resource tracking on WebGPU, observing only
379
+ resources created after attachment. On other backends it uses browser JS heap size
380
+ when exposed, otherwise null. These are different scopes, neither is process memory
381
+ or driver allocation. `memory: () => numberOrNull` supplies an application sampler in
382
+ bytes. Graph labels show MiB; reports retain bytes. Labels include latest, average and
383
+ peak over finite values retained in the history. Null values produce gaps and are
384
+ excluded from averages, rather than being plotted as zero.
385
+
386
+ For a custom loop, construct StatsPanels and call `sample` with fps, cpuMilliseconds,
387
+ gpuMilliseconds and memoryBytes, plus optional named passes. Samples must be finite
388
+ and nonnegative; only GPU and memory may be null. `sample` updates the rings separately
389
+ from DOM/canvas work; `refresh()` redraws immediately, alongside the refresh timer.
390
+ `toJSON()` returns oldest-first arrays with null gaps and a copy of the latest pass list.
391
+
392
+ Disposal removes histories, timer, owned phase/timing/memory trackers and the panels
393
+ plugin. A borrowed Stats remains alive and its original graph display is restored;
394
+ an owned Stats is disposed with the panels. Engine disposal performs this cleanup too.
395
+
396
+
397
+ ```ts
398
+ import {Engine} from '@margoengine/core';
399
+ import {Stats} from '@margoengine/stats';
400
+ import {StatsPanels} from '@margoengine/stats/panels';
401
+ const canvas = document.body.appendChild(document.createElement('canvas'));
402
+ canvas.width = 480; canvas.height = 320;
403
+ const engine = await Engine.create(canvas);
404
+ const stats = Stats.attach(engine);
405
+ const panels = StatsPanels.attach(engine, {stats, samples: 120});
406
+ engine.render();
407
+ console.log(panels.toJSON());
408
+ panels.dispose(); // Borrowed stats remains attached.
409
+ stats.dispose(); engine.dispose(); canvas.remove();
410
+ ```
411
+
412
+ ## Preview tier contract
413
+
414
+ `GeometryStats`, `GLStats` and `StatsPanels` are reviewed preview routes in `scripts/check-preview-contract.mjs` (2026-11-10; 1, 2 and 1 `backend` tests). On the small WebGL2 preview `GeometryStats` counts WebGL2 draws, `GLStats` times named passes with WebGL2 timer queries, and `StatsPanels` uses `GLStats` for its GPU graph and pass list. Evidence: `test/preview.test.js` (new: a preview engine, one WebGL2 draw counted as 2 triangles and the `main` pass timed into the panel) and `test/gl.test.js`. No behaviour changed; the missing rows kept `npm run verify` red.