@margoengine/stats 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Campbell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Margo Engine
2
+ Copyright 2026 Scott Campbell
3
+
4
+ This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
package/README.md CHANGED
@@ -1,3 +1,414 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.