@plasius/gpu-debug 0.2.4

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/dist/index.js ADDED
@@ -0,0 +1,961 @@
1
+ // src/validation.ts
2
+ var IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u;
3
+ var gpuDebugQueueClasses = Object.freeze([
4
+ "render",
5
+ "simulation",
6
+ "lighting",
7
+ "post-processing",
8
+ "voxel",
9
+ "transfer",
10
+ "custom"
11
+ ]);
12
+ var gpuResourceCategories = Object.freeze([
13
+ "buffer",
14
+ "texture",
15
+ "bind-group",
16
+ "pipeline",
17
+ "custom"
18
+ ]);
19
+ var gpuPipelinePhases = Object.freeze([
20
+ "simulation",
21
+ "secondary-simulation",
22
+ "scene-preparation",
23
+ "render"
24
+ ]);
25
+ function isRecord(value) {
26
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27
+ }
28
+ function assertIdentifier(name, value) {
29
+ if (typeof value !== "string" || !IDENTIFIER_PATTERN.test(value)) {
30
+ throw new Error(
31
+ `${name} must match ${IDENTIFIER_PATTERN.toString()} and be at most 64 characters long.`
32
+ );
33
+ }
34
+ return value;
35
+ }
36
+ function assertEnumValue(name, value, allowedValues) {
37
+ if (typeof value !== "string" || !allowedValues.includes(value)) {
38
+ throw new Error(`${name} must be one of: ${allowedValues.join(", ")}.`);
39
+ }
40
+ return value;
41
+ }
42
+ function readPositiveNumber(name, value) {
43
+ if (value === void 0) {
44
+ return void 0;
45
+ }
46
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
47
+ throw new Error(`${name} must be a finite number greater than zero.`);
48
+ }
49
+ return value;
50
+ }
51
+ function readNonNegativeNumber(name, value) {
52
+ if (value === void 0) {
53
+ return void 0;
54
+ }
55
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
56
+ throw new Error(`${name} must be a finite number greater than or equal to zero.`);
57
+ }
58
+ return value;
59
+ }
60
+ function readPositiveInteger(name, value) {
61
+ const parsed = readPositiveNumber(name, value);
62
+ if (parsed === void 0) {
63
+ return void 0;
64
+ }
65
+ if (!Number.isInteger(parsed)) {
66
+ throw new Error(`${name} must be an integer greater than zero.`);
67
+ }
68
+ return parsed;
69
+ }
70
+ function normalizePlainObject(name, value) {
71
+ if (value === void 0) {
72
+ return Object.freeze({});
73
+ }
74
+ if (!isRecord(value)) {
75
+ throw new Error(`${name} must be a plain object when provided.`);
76
+ }
77
+ return Object.freeze({ ...value });
78
+ }
79
+ function normalizeVector(name, value) {
80
+ const x = readPositiveInteger(`${name}.x`, value.x) ?? 1;
81
+ const y = readPositiveInteger(`${name}.y`, value.y) ?? 1;
82
+ const z = readPositiveInteger(`${name}.z`, value.z) ?? 1;
83
+ return { x, y, z };
84
+ }
85
+ function isAbortSignalLike(value) {
86
+ return typeof value === "object" && value !== null && "aborted" in value && typeof value.aborted === "boolean";
87
+ }
88
+ function normalizeAdapterInfo(value) {
89
+ if (value === void 0) {
90
+ return Object.freeze({});
91
+ }
92
+ const adapter = {};
93
+ if (value.label !== void 0) {
94
+ adapter.label = String(value.label).trim().slice(0, 120);
95
+ }
96
+ if (value.vendor !== void 0) {
97
+ adapter.vendor = String(value.vendor).trim().slice(0, 120);
98
+ }
99
+ if (value.architecture !== void 0) {
100
+ adapter.architecture = String(value.architecture).trim().slice(0, 120);
101
+ }
102
+ if (value.driver !== void 0) {
103
+ adapter.driver = String(value.driver).trim().slice(0, 120);
104
+ }
105
+ adapter.maxBufferSizeBytes = readPositiveInteger(
106
+ "adapter.maxBufferSizeBytes",
107
+ value.maxBufferSizeBytes
108
+ );
109
+ adapter.maxStorageBufferBindingSizeBytes = readPositiveInteger(
110
+ "adapter.maxStorageBufferBindingSizeBytes",
111
+ value.maxStorageBufferBindingSizeBytes
112
+ );
113
+ adapter.maxComputeInvocationsPerWorkgroup = readPositiveInteger(
114
+ "adapter.maxComputeInvocationsPerWorkgroup",
115
+ value.maxComputeInvocationsPerWorkgroup
116
+ );
117
+ adapter.maxComputeWorkgroupsPerDimension = readPositiveInteger(
118
+ "adapter.maxComputeWorkgroupsPerDimension",
119
+ value.maxComputeWorkgroupsPerDimension
120
+ );
121
+ adapter.memoryCapacityHintBytes = readPositiveInteger(
122
+ "adapter.memoryCapacityHintBytes",
123
+ value.memoryCapacityHintBytes
124
+ );
125
+ adapter.coreCountHint = readPositiveInteger(
126
+ "adapter.coreCountHint",
127
+ value.coreCountHint
128
+ );
129
+ adapter.metadata = normalizePlainObject("adapter.metadata", value.metadata);
130
+ return Object.freeze(adapter);
131
+ }
132
+
133
+ // src/session.ts
134
+ var DEFAULT_OPTIONS = Object.freeze({
135
+ enabled: false,
136
+ maxRetainedDispatches: 240,
137
+ maxRetainedQueueSamples: 240,
138
+ maxRetainedReadyLaneSamples: 240,
139
+ maxRetainedDependencyUnlockSamples: 240,
140
+ maxRetainedPipelinePhaseSamples: 240,
141
+ maxRetainedWavefrontSamples: 240,
142
+ maxRetainedFrameSamples: 240,
143
+ maxTrackedAllocations: 512
144
+ });
145
+ var LIMITATIONS = Object.freeze([
146
+ "Tracked memory reflects only allocations reported to this debug session.",
147
+ "Portable WebGPU does not expose authoritative live GPU core-count or total-memory counters.",
148
+ "Hardware hints are optional caller-supplied metadata and may be platform-specific.",
149
+ "Ready-lane and dependency-unlock diagnostics are caller-reported integration samples, not automatic WebGPU counters.",
150
+ "Pipeline phase and snapshot-lag diagnostics are caller-reported integration samples, not automatic WebGPU counters.",
151
+ "Wavefront queue, hit-buffer, and termination diagnostics are caller-reported summaries rather than full GPU buffer dumps."
152
+ ]);
153
+ function clampCount(value, fallback) {
154
+ if (!value || !Number.isFinite(value) || value <= 0) {
155
+ return fallback;
156
+ }
157
+ return Math.min(Math.round(value), 4096);
158
+ }
159
+ function trimHistory(items, maxEntries) {
160
+ while (items.length > maxEntries) {
161
+ items.shift();
162
+ }
163
+ }
164
+ function average(values) {
165
+ if (values.length === 0) {
166
+ return void 0;
167
+ }
168
+ return values.reduce((total, value) => total + value, 0) / values.length;
169
+ }
170
+ function pushAggregate(map, key, value) {
171
+ map.set(key, (map.get(key) ?? 0) + value);
172
+ }
173
+ function normalizeAllocation(allocation) {
174
+ if (allocation.signal !== void 0 && !isAbortSignalLike(allocation.signal)) {
175
+ throw new Error("allocation.signal must be an AbortSignal when provided.");
176
+ }
177
+ return {
178
+ id: assertIdentifier("allocation.id", allocation.id),
179
+ owner: assertIdentifier("allocation.owner", allocation.owner),
180
+ category: assertEnumValue(
181
+ "allocation.category",
182
+ allocation.category,
183
+ gpuResourceCategories
184
+ ),
185
+ sizeBytes: readPositiveInteger("allocation.sizeBytes", allocation.sizeBytes) ?? 1,
186
+ label: allocation.label === void 0 ? void 0 : String(allocation.label).trim().slice(0, 120)
187
+ };
188
+ }
189
+ function normalizeQueueSample(sample) {
190
+ if (sample.signal !== void 0 && !isAbortSignalLike(sample.signal)) {
191
+ throw new Error("queue.signal must be an AbortSignal when provided.");
192
+ }
193
+ const capacity = readPositiveInteger("queue.capacity", sample.capacity);
194
+ const depth = readNonNegativeNumber("queue.depth", sample.depth) ?? 0;
195
+ if (capacity !== void 0 && depth > capacity) {
196
+ throw new Error("queue.depth cannot exceed queue.capacity.");
197
+ }
198
+ return {
199
+ owner: assertIdentifier("queue.owner", sample.owner),
200
+ queueClass: assertEnumValue(
201
+ "queue.queueClass",
202
+ sample.queueClass,
203
+ gpuDebugQueueClasses
204
+ ),
205
+ depth,
206
+ capacity,
207
+ frameId: sample.frameId === void 0 ? void 0 : assertIdentifier("queue.frameId", sample.frameId)
208
+ };
209
+ }
210
+ function normalizeReadyLaneSample(sample) {
211
+ if (sample.signal !== void 0 && !isAbortSignalLike(sample.signal)) {
212
+ throw new Error("readyLane.signal must be an AbortSignal when provided.");
213
+ }
214
+ const capacity = readPositiveInteger("readyLane.capacity", sample.capacity);
215
+ const depth = readNonNegativeNumber("readyLane.depth", sample.depth) ?? 0;
216
+ if (capacity !== void 0 && depth > capacity) {
217
+ throw new Error("readyLane.depth cannot exceed readyLane.capacity.");
218
+ }
219
+ const priority = readNonNegativeNumber("readyLane.priority", sample.priority);
220
+ if (priority !== void 0 && !Number.isInteger(priority)) {
221
+ throw new Error("readyLane.priority must be an integer greater than or equal to zero.");
222
+ }
223
+ return {
224
+ owner: assertIdentifier("readyLane.owner", sample.owner),
225
+ queueClass: assertEnumValue(
226
+ "readyLane.queueClass",
227
+ sample.queueClass,
228
+ gpuDebugQueueClasses
229
+ ),
230
+ laneId: assertIdentifier("readyLane.laneId", sample.laneId),
231
+ priority,
232
+ depth,
233
+ capacity,
234
+ frameId: sample.frameId === void 0 ? void 0 : assertIdentifier("readyLane.frameId", sample.frameId)
235
+ };
236
+ }
237
+ function normalizeDispatchSample(sample) {
238
+ if (sample.signal !== void 0 && !isAbortSignalLike(sample.signal)) {
239
+ throw new Error("dispatch.signal must be an AbortSignal when provided.");
240
+ }
241
+ return {
242
+ id: sample.id === void 0 ? void 0 : assertIdentifier("dispatch.id", sample.id),
243
+ owner: assertIdentifier("dispatch.owner", sample.owner),
244
+ queueClass: assertEnumValue(
245
+ "dispatch.queueClass",
246
+ sample.queueClass,
247
+ gpuDebugQueueClasses
248
+ ),
249
+ jobType: assertIdentifier("dispatch.jobType", sample.jobType),
250
+ frameId: sample.frameId === void 0 ? void 0 : assertIdentifier("dispatch.frameId", sample.frameId),
251
+ durationMs: readNonNegativeNumber("dispatch.durationMs", sample.durationMs),
252
+ workgroups: normalizeVector("dispatch.workgroups", sample.workgroups),
253
+ workgroupSize: normalizeVector(
254
+ "dispatch.workgroupSize",
255
+ sample.workgroupSize ?? { x: 1, y: 1, z: 1 }
256
+ ),
257
+ bytesRead: readNonNegativeNumber("dispatch.bytesRead", sample.bytesRead),
258
+ bytesWritten: readNonNegativeNumber("dispatch.bytesWritten", sample.bytesWritten)
259
+ };
260
+ }
261
+ function normalizeFrameSample(sample) {
262
+ if (sample.signal !== void 0 && !isAbortSignalLike(sample.signal)) {
263
+ throw new Error("frame.signal must be an AbortSignal when provided.");
264
+ }
265
+ if (sample.dropped !== void 0 && typeof sample.dropped !== "boolean") {
266
+ throw new Error("frame.dropped must be a boolean when provided.");
267
+ }
268
+ return {
269
+ frameId: sample.frameId === void 0 ? void 0 : assertIdentifier("frame.frameId", sample.frameId),
270
+ frameTimeMs: readPositiveNumber("frame.frameTimeMs", sample.frameTimeMs) ?? 0,
271
+ targetFrameTimeMs: readPositiveNumber(
272
+ "frame.targetFrameTimeMs",
273
+ sample.targetFrameTimeMs
274
+ ),
275
+ gpuBusyMs: readNonNegativeNumber("frame.gpuBusyMs", sample.gpuBusyMs),
276
+ dropped: sample.dropped
277
+ };
278
+ }
279
+ function normalizeDependencyUnlockSample(sample) {
280
+ if (sample.signal !== void 0 && !isAbortSignalLike(sample.signal)) {
281
+ throw new Error("dependencyUnlock.signal must be an AbortSignal when provided.");
282
+ }
283
+ const priority = readNonNegativeNumber(
284
+ "dependencyUnlock.priority",
285
+ sample.priority
286
+ );
287
+ if (priority !== void 0 && !Number.isInteger(priority)) {
288
+ throw new Error(
289
+ "dependencyUnlock.priority must be an integer greater than or equal to zero."
290
+ );
291
+ }
292
+ return {
293
+ owner: assertIdentifier("dependencyUnlock.owner", sample.owner),
294
+ queueClass: assertEnumValue(
295
+ "dependencyUnlock.queueClass",
296
+ sample.queueClass,
297
+ gpuDebugQueueClasses
298
+ ),
299
+ sourceJobType: assertIdentifier(
300
+ "dependencyUnlock.sourceJobType",
301
+ sample.sourceJobType
302
+ ),
303
+ unlockedJobType: assertIdentifier(
304
+ "dependencyUnlock.unlockedJobType",
305
+ sample.unlockedJobType
306
+ ),
307
+ priority,
308
+ unlockCount: readPositiveInteger("dependencyUnlock.unlockCount", sample.unlockCount) ?? 1,
309
+ frameId: sample.frameId === void 0 ? void 0 : assertIdentifier("dependencyUnlock.frameId", sample.frameId)
310
+ };
311
+ }
312
+ function normalizePipelinePhaseSample(sample) {
313
+ if (sample.signal !== void 0 && !isAbortSignalLike(sample.signal)) {
314
+ throw new Error("pipelinePhase.signal must be an AbortSignal when provided.");
315
+ }
316
+ const snapshotAgeFrames = readNonNegativeNumber(
317
+ "pipelinePhase.snapshotAgeFrames",
318
+ sample.snapshotAgeFrames
319
+ );
320
+ if (snapshotAgeFrames !== void 0 && !Number.isInteger(snapshotAgeFrames)) {
321
+ throw new Error(
322
+ "pipelinePhase.snapshotAgeFrames must be an integer greater than or equal to zero."
323
+ );
324
+ }
325
+ return {
326
+ owner: assertIdentifier("pipelinePhase.owner", sample.owner),
327
+ pipeline: assertEnumValue(
328
+ "pipelinePhase.pipeline",
329
+ sample.pipeline,
330
+ gpuPipelinePhases
331
+ ),
332
+ stage: assertIdentifier("pipelinePhase.stage", sample.stage),
333
+ frameId: sample.frameId === void 0 ? void 0 : assertIdentifier("pipelinePhase.frameId", sample.frameId),
334
+ durationMs: readNonNegativeNumber(
335
+ "pipelinePhase.durationMs",
336
+ sample.durationMs
337
+ ),
338
+ snapshotFrameId: sample.snapshotFrameId === void 0 ? void 0 : assertIdentifier("pipelinePhase.snapshotFrameId", sample.snapshotFrameId),
339
+ snapshotAgeFrames,
340
+ snapshotAgeMs: readNonNegativeNumber(
341
+ "pipelinePhase.snapshotAgeMs",
342
+ sample.snapshotAgeMs
343
+ )
344
+ };
345
+ }
346
+ function normalizeWavefrontHitKinds(entries) {
347
+ if (entries === void 0) {
348
+ return Object.freeze([]);
349
+ }
350
+ if (!Array.isArray(entries)) {
351
+ throw new Error("wavefront.hitKinds must be an array when provided.");
352
+ }
353
+ return Object.freeze(
354
+ entries.map((entry, index) => {
355
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
356
+ throw new Error(`wavefront.hitKinds[${index}] must be an object.`);
357
+ }
358
+ return Object.freeze({
359
+ kind: assertIdentifier(`wavefront.hitKinds[${index}].kind`, entry.kind),
360
+ count: readPositiveInteger(`wavefront.hitKinds[${index}].count`, entry.count) ?? 1
361
+ });
362
+ })
363
+ );
364
+ }
365
+ function normalizeWavefrontTerminationReasons(entries) {
366
+ if (entries === void 0) {
367
+ return Object.freeze([]);
368
+ }
369
+ if (!Array.isArray(entries)) {
370
+ throw new Error(
371
+ "wavefront.terminationReasons must be an array when provided."
372
+ );
373
+ }
374
+ return Object.freeze(
375
+ entries.map((entry, index) => {
376
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
377
+ throw new Error(
378
+ `wavefront.terminationReasons[${index}] must be an object.`
379
+ );
380
+ }
381
+ return Object.freeze({
382
+ reason: assertIdentifier(
383
+ `wavefront.terminationReasons[${index}].reason`,
384
+ entry.reason
385
+ ),
386
+ count: readPositiveInteger(
387
+ `wavefront.terminationReasons[${index}].count`,
388
+ entry.count
389
+ ) ?? 1
390
+ });
391
+ })
392
+ );
393
+ }
394
+ function normalizeWavefrontTelemetrySample(sample) {
395
+ if (sample.signal !== void 0 && !isAbortSignalLike(sample.signal)) {
396
+ throw new Error("wavefront.signal must be an AbortSignal when provided.");
397
+ }
398
+ const queueCapacity = readPositiveInteger(
399
+ "wavefront.queueCapacity",
400
+ sample.queueCapacity
401
+ );
402
+ const activeRayCount = readNonNegativeNumber("wavefront.activeRayCount", sample.activeRayCount) ?? 0;
403
+ if (!Number.isInteger(activeRayCount)) {
404
+ throw new Error("wavefront.activeRayCount must be an integer greater than or equal to zero.");
405
+ }
406
+ if (queueCapacity !== void 0 && activeRayCount > queueCapacity) {
407
+ throw new Error(
408
+ "wavefront.activeRayCount cannot exceed wavefront.queueCapacity."
409
+ );
410
+ }
411
+ const bounceDepth = readNonNegativeNumber("wavefront.bounceDepth", sample.bounceDepth) ?? 0;
412
+ if (!Number.isInteger(bounceDepth)) {
413
+ throw new Error("wavefront.bounceDepth must be an integer greater than or equal to zero.");
414
+ }
415
+ const overflowCount = readNonNegativeNumber("wavefront.overflowCount", sample.overflowCount) ?? 0;
416
+ if (!Number.isInteger(overflowCount)) {
417
+ throw new Error("wavefront.overflowCount must be an integer greater than or equal to zero.");
418
+ }
419
+ const hitBufferCount = readNonNegativeNumber(
420
+ "wavefront.hitBufferCount",
421
+ sample.hitBufferCount
422
+ );
423
+ if (hitBufferCount !== void 0 && !Number.isInteger(hitBufferCount)) {
424
+ throw new Error(
425
+ "wavefront.hitBufferCount must be an integer greater than or equal to zero."
426
+ );
427
+ }
428
+ return {
429
+ owner: assertIdentifier("wavefront.owner", sample.owner),
430
+ queueClass: assertEnumValue(
431
+ "wavefront.queueClass",
432
+ sample.queueClass,
433
+ gpuDebugQueueClasses
434
+ ),
435
+ frameId: sample.frameId === void 0 ? void 0 : assertIdentifier("wavefront.frameId", sample.frameId),
436
+ bounceDepth,
437
+ activeRayCount,
438
+ queueCapacity,
439
+ overflowCount,
440
+ hitBufferCount,
441
+ hitKinds: normalizeWavefrontHitKinds(sample.hitKinds),
442
+ terminationReasons: normalizeWavefrontTerminationReasons(
443
+ sample.terminationReasons
444
+ )
445
+ };
446
+ }
447
+ function estimateDispatchInvocations(sample) {
448
+ const normalized = normalizeDispatchSample(sample);
449
+ return normalized.workgroups.x * normalized.workgroups.y * normalized.workgroups.z * normalized.workgroupSize.x * normalized.workgroupSize.y * normalized.workgroupSize.z;
450
+ }
451
+ function createGpuDebugSession(options = {}) {
452
+ const settings = {
453
+ enabled: options.enabled ?? DEFAULT_OPTIONS.enabled,
454
+ maxRetainedDispatches: clampCount(
455
+ options.maxRetainedDispatches,
456
+ DEFAULT_OPTIONS.maxRetainedDispatches
457
+ ),
458
+ maxRetainedQueueSamples: clampCount(
459
+ options.maxRetainedQueueSamples,
460
+ DEFAULT_OPTIONS.maxRetainedQueueSamples
461
+ ),
462
+ maxRetainedReadyLaneSamples: clampCount(
463
+ options.maxRetainedReadyLaneSamples,
464
+ DEFAULT_OPTIONS.maxRetainedReadyLaneSamples
465
+ ),
466
+ maxRetainedDependencyUnlockSamples: clampCount(
467
+ options.maxRetainedDependencyUnlockSamples,
468
+ DEFAULT_OPTIONS.maxRetainedDependencyUnlockSamples
469
+ ),
470
+ maxRetainedPipelinePhaseSamples: clampCount(
471
+ options.maxRetainedPipelinePhaseSamples,
472
+ DEFAULT_OPTIONS.maxRetainedPipelinePhaseSamples
473
+ ),
474
+ maxRetainedWavefrontSamples: clampCount(
475
+ options.maxRetainedWavefrontSamples,
476
+ DEFAULT_OPTIONS.maxRetainedWavefrontSamples
477
+ ),
478
+ maxRetainedFrameSamples: clampCount(
479
+ options.maxRetainedFrameSamples,
480
+ DEFAULT_OPTIONS.maxRetainedFrameSamples
481
+ ),
482
+ maxTrackedAllocations: clampCount(
483
+ options.maxTrackedAllocations,
484
+ DEFAULT_OPTIONS.maxTrackedAllocations
485
+ )
486
+ };
487
+ const adapter = normalizeAdapterInfo(options.adapter);
488
+ let enabled = settings.enabled;
489
+ const allocations = /* @__PURE__ */ new Map();
490
+ const allocationOrder = [];
491
+ const queueSamples = [];
492
+ const readyLaneSamples = [];
493
+ const dispatchSamples = [];
494
+ const dependencyUnlockSamples = [];
495
+ const pipelinePhaseSamples = [];
496
+ const wavefrontSamples = [];
497
+ const frameSamples = [];
498
+ let peakTrackedBytes = 0;
499
+ const totalTrackedBytes = () => [...allocations.values()].reduce((total, allocation) => total + allocation.sizeBytes, 0);
500
+ const updatePeakTrackedBytes = () => {
501
+ peakTrackedBytes = Math.max(peakTrackedBytes, totalTrackedBytes());
502
+ };
503
+ const ensureAllocationCapacity = () => {
504
+ while (allocationOrder.length > settings.maxTrackedAllocations) {
505
+ const oldestId = allocationOrder.shift();
506
+ if (oldestId !== void 0) {
507
+ allocations.delete(oldestId);
508
+ }
509
+ }
510
+ };
511
+ const buildDispatchSnapshot = () => {
512
+ const durations = dispatchSamples.map((sample) => sample.durationMs).filter((value) => value !== void 0);
513
+ const bytesRead = dispatchSamples.map((sample) => sample.bytesRead).filter((value) => value !== void 0);
514
+ const bytesWritten = dispatchSamples.map((sample) => sample.bytesWritten).filter((value) => value !== void 0);
515
+ const byQueueClass = /* @__PURE__ */ new Map();
516
+ let estimatedWorkgroups = 0;
517
+ let estimatedInvocations = 0;
518
+ for (const sample of dispatchSamples) {
519
+ const workgroupCount = sample.workgroups.x * sample.workgroups.y * sample.workgroups.z;
520
+ const invocationCount = workgroupCount * sample.workgroupSize.x * sample.workgroupSize.y * sample.workgroupSize.z;
521
+ estimatedWorkgroups += workgroupCount;
522
+ estimatedInvocations += invocationCount;
523
+ const bucket = byQueueClass.get(sample.queueClass) ?? {
524
+ queueClass: sample.queueClass,
525
+ dispatches: 0,
526
+ totalDurationMs: 0,
527
+ estimatedInvocations: 0
528
+ };
529
+ bucket.dispatches += 1;
530
+ bucket.totalDurationMs += sample.durationMs ?? 0;
531
+ bucket.estimatedInvocations += invocationCount;
532
+ byQueueClass.set(sample.queueClass, bucket);
533
+ }
534
+ const frameTimes = frameSamples.map((sample) => sample.frameTimeMs);
535
+ const totalFrameTimeMs = frameTimes.reduce((total, value) => total + value, 0);
536
+ const totalDurationMs = durations.reduce((total, value) => total + value, 0);
537
+ return {
538
+ sampleCount: dispatchSamples.length,
539
+ totalDurationMs,
540
+ averageDurationMs: average(durations),
541
+ estimatedWorkgroups,
542
+ estimatedInvocations,
543
+ averageBytesRead: average(bytesRead),
544
+ averageBytesWritten: average(bytesWritten),
545
+ busyRatio: totalFrameTimeMs > 0 ? Math.min(totalDurationMs / totalFrameTimeMs, 1) : void 0,
546
+ byQueueClass: [...byQueueClass.values()].sort(
547
+ (left, right) => right.totalDurationMs - left.totalDurationMs
548
+ )
549
+ };
550
+ };
551
+ const buildQueueSnapshot = () => {
552
+ const depths = queueSamples.map((sample) => sample.depth);
553
+ const hottestQueues = queueSamples.map((sample) => ({
554
+ owner: sample.owner,
555
+ queueClass: sample.queueClass,
556
+ depth: sample.depth,
557
+ capacity: sample.capacity,
558
+ utilizationRatio: sample.capacity !== void 0 ? sample.depth / sample.capacity : void 0
559
+ })).sort((left, right) => {
560
+ const leftScore = left.utilizationRatio ?? left.depth;
561
+ const rightScore = right.utilizationRatio ?? right.depth;
562
+ return rightScore - leftScore;
563
+ }).slice(0, 5);
564
+ const peakUtilizationRatio = queueSamples.reduce(
565
+ (peak, sample) => {
566
+ if (sample.capacity === void 0) {
567
+ return peak;
568
+ }
569
+ const nextRatio = sample.depth / sample.capacity;
570
+ return peak === void 0 ? nextRatio : Math.max(peak, nextRatio);
571
+ },
572
+ void 0
573
+ );
574
+ return {
575
+ sampleCount: queueSamples.length,
576
+ averageDepth: average(depths) ?? 0,
577
+ peakDepth: depths.length === 0 ? 0 : Math.max(...depths),
578
+ peakUtilizationRatio,
579
+ hottestQueues
580
+ };
581
+ };
582
+ const buildDagSnapshot = () => {
583
+ const laneDepths = readyLaneSamples.map((sample) => sample.depth);
584
+ const hottestReadyLanes = readyLaneSamples.map((sample) => ({
585
+ owner: sample.owner,
586
+ queueClass: sample.queueClass,
587
+ laneId: sample.laneId,
588
+ priority: sample.priority,
589
+ depth: sample.depth,
590
+ capacity: sample.capacity,
591
+ utilizationRatio: sample.capacity !== void 0 ? sample.depth / sample.capacity : void 0
592
+ })).sort((left, right) => {
593
+ const leftScore = left.utilizationRatio ?? left.depth;
594
+ const rightScore = right.utilizationRatio ?? right.depth;
595
+ return rightScore - leftScore;
596
+ }).slice(0, 5);
597
+ const peakReadyLaneUtilizationRatio = readyLaneSamples.reduce(
598
+ (peak, sample) => {
599
+ if (sample.capacity === void 0) {
600
+ return peak;
601
+ }
602
+ const nextRatio = sample.depth / sample.capacity;
603
+ return peak === void 0 ? nextRatio : Math.max(peak, nextRatio);
604
+ },
605
+ void 0
606
+ );
607
+ const bySourceJobType = /* @__PURE__ */ new Map();
608
+ const byUnlockedJobType = /* @__PURE__ */ new Map();
609
+ let totalUnlockCount = 0;
610
+ for (const sample of dependencyUnlockSamples) {
611
+ totalUnlockCount += sample.unlockCount;
612
+ const sourceKey = `${sample.owner}:${sample.queueClass}:${sample.sourceJobType}`;
613
+ const unlockedKey = `${sample.owner}:${sample.queueClass}:${sample.unlockedJobType}:${sample.priority ?? "none"}`;
614
+ const sourceBucket = bySourceJobType.get(sourceKey) ?? {
615
+ owner: sample.owner,
616
+ queueClass: sample.queueClass,
617
+ sourceJobType: sample.sourceJobType,
618
+ unlockCount: 0
619
+ };
620
+ sourceBucket.unlockCount += sample.unlockCount;
621
+ bySourceJobType.set(sourceKey, sourceBucket);
622
+ const unlockedBucket = byUnlockedJobType.get(unlockedKey) ?? {
623
+ owner: sample.owner,
624
+ queueClass: sample.queueClass,
625
+ unlockedJobType: sample.unlockedJobType,
626
+ priority: sample.priority,
627
+ unlockCount: 0
628
+ };
629
+ unlockedBucket.unlockCount += sample.unlockCount;
630
+ byUnlockedJobType.set(unlockedKey, unlockedBucket);
631
+ }
632
+ return {
633
+ readyLaneSampleCount: readyLaneSamples.length,
634
+ averageReadyLaneDepth: average(laneDepths) ?? 0,
635
+ peakReadyLaneDepth: laneDepths.length === 0 ? 0 : Math.max(...laneDepths),
636
+ peakReadyLaneUtilizationRatio,
637
+ hottestReadyLanes,
638
+ dependencyUnlockSampleCount: dependencyUnlockSamples.length,
639
+ totalUnlockCount,
640
+ bySourceJobType: [...bySourceJobType.values()].sort(
641
+ (left, right) => right.unlockCount - left.unlockCount
642
+ ),
643
+ byUnlockedJobType: [...byUnlockedJobType.values()].sort(
644
+ (left, right) => right.unlockCount - left.unlockCount
645
+ )
646
+ };
647
+ };
648
+ const buildPipelineSnapshot = () => {
649
+ const durations = pipelinePhaseSamples.map((sample) => sample.durationMs).filter((value) => value !== void 0);
650
+ const snapshotAgeMsValues = pipelinePhaseSamples.map((sample) => sample.snapshotAgeMs).filter((value) => value !== void 0);
651
+ const snapshotAgeFrameValues = pipelinePhaseSamples.map((sample) => sample.snapshotAgeFrames).filter((value) => value !== void 0);
652
+ const byPipeline = /* @__PURE__ */ new Map();
653
+ for (const sample of pipelinePhaseSamples) {
654
+ const bucket = byPipeline.get(sample.pipeline) ?? {
655
+ pipeline: sample.pipeline,
656
+ sampleCount: 0,
657
+ totalDurationMs: 0,
658
+ durationValues: [],
659
+ snapshotAgeMsValues: [],
660
+ snapshotAgeFramesValues: []
661
+ };
662
+ bucket.sampleCount += 1;
663
+ bucket.totalDurationMs += sample.durationMs ?? 0;
664
+ if (sample.durationMs !== void 0) {
665
+ bucket.durationValues.push(sample.durationMs);
666
+ }
667
+ if (sample.snapshotAgeMs !== void 0) {
668
+ bucket.snapshotAgeMsValues.push(sample.snapshotAgeMs);
669
+ }
670
+ if (sample.snapshotAgeFrames !== void 0) {
671
+ bucket.snapshotAgeFramesValues.push(sample.snapshotAgeFrames);
672
+ }
673
+ byPipeline.set(sample.pipeline, bucket);
674
+ }
675
+ const hottestStages = pipelinePhaseSamples.map((sample) => ({
676
+ owner: sample.owner,
677
+ pipeline: sample.pipeline,
678
+ stage: sample.stage,
679
+ frameId: sample.frameId,
680
+ durationMs: sample.durationMs,
681
+ snapshotFrameId: sample.snapshotFrameId,
682
+ snapshotAgeFrames: sample.snapshotAgeFrames,
683
+ snapshotAgeMs: sample.snapshotAgeMs
684
+ })).sort((left, right) => {
685
+ const leftScore = left.durationMs ?? left.snapshotAgeMs ?? left.snapshotAgeFrames ?? 0;
686
+ const rightScore = right.durationMs ?? right.snapshotAgeMs ?? right.snapshotAgeFrames ?? 0;
687
+ return rightScore - leftScore;
688
+ }).slice(0, 5);
689
+ return {
690
+ sampleCount: pipelinePhaseSamples.length,
691
+ totalDurationMs: durations.reduce((total, value) => total + value, 0),
692
+ averageDurationMs: average(durations),
693
+ averageSnapshotAgeMs: average(snapshotAgeMsValues),
694
+ maxSnapshotAgeMs: snapshotAgeMsValues.length > 0 ? Math.max(...snapshotAgeMsValues) : void 0,
695
+ maxSnapshotAgeFrames: snapshotAgeFrameValues.length > 0 ? Math.max(...snapshotAgeFrameValues) : void 0,
696
+ byPipeline: [...byPipeline.values()].map((bucket) => ({
697
+ pipeline: bucket.pipeline,
698
+ sampleCount: bucket.sampleCount,
699
+ totalDurationMs: bucket.totalDurationMs,
700
+ averageDurationMs: average(bucket.durationValues),
701
+ averageSnapshotAgeMs: average(bucket.snapshotAgeMsValues),
702
+ maxSnapshotAgeMs: bucket.snapshotAgeMsValues.length > 0 ? Math.max(...bucket.snapshotAgeMsValues) : void 0,
703
+ maxSnapshotAgeFrames: bucket.snapshotAgeFramesValues.length > 0 ? Math.max(...bucket.snapshotAgeFramesValues) : void 0
704
+ })).sort((left, right) => right.totalDurationMs - left.totalDurationMs),
705
+ hottestStages
706
+ };
707
+ };
708
+ const buildWavefrontSnapshot = () => {
709
+ const activeRayCounts = wavefrontSamples.map((sample) => sample.activeRayCount);
710
+ const hitBufferCounts = wavefrontSamples.map((sample) => sample.hitBufferCount).filter((value) => value !== void 0);
711
+ const byBounceDepth = /* @__PURE__ */ new Map();
712
+ const byTerminationReason = /* @__PURE__ */ new Map();
713
+ const byHitKind = /* @__PURE__ */ new Map();
714
+ const peakQueueUtilizationRatio = wavefrontSamples.reduce(
715
+ (peak, sample) => {
716
+ if (sample.queueCapacity === void 0) {
717
+ return peak;
718
+ }
719
+ const ratio = sample.activeRayCount / sample.queueCapacity;
720
+ return peak === void 0 ? ratio : Math.max(peak, ratio);
721
+ },
722
+ void 0
723
+ );
724
+ let totalOverflowCount = 0;
725
+ let peakOverflowCount = 0;
726
+ let maxBounceDepth;
727
+ for (const sample of wavefrontSamples) {
728
+ totalOverflowCount += sample.overflowCount;
729
+ peakOverflowCount = Math.max(peakOverflowCount, sample.overflowCount);
730
+ maxBounceDepth = maxBounceDepth === void 0 ? sample.bounceDepth : Math.max(maxBounceDepth, sample.bounceDepth);
731
+ const bucket = byBounceDepth.get(sample.bounceDepth) ?? {
732
+ bounceDepth: sample.bounceDepth,
733
+ sampleCount: 0,
734
+ activeRayCounts: [],
735
+ hitBufferCounts: [],
736
+ totalOverflowCount: 0
737
+ };
738
+ bucket.sampleCount += 1;
739
+ bucket.activeRayCounts.push(sample.activeRayCount);
740
+ if (sample.hitBufferCount !== void 0) {
741
+ bucket.hitBufferCounts.push(sample.hitBufferCount);
742
+ }
743
+ bucket.totalOverflowCount += sample.overflowCount;
744
+ byBounceDepth.set(sample.bounceDepth, bucket);
745
+ for (const reason of sample.terminationReasons) {
746
+ pushAggregate(byTerminationReason, reason.reason, reason.count);
747
+ }
748
+ for (const kind of sample.hitKinds) {
749
+ pushAggregate(byHitKind, kind.kind, kind.count);
750
+ }
751
+ }
752
+ return {
753
+ sampleCount: wavefrontSamples.length,
754
+ averageActiveRayCount: average(activeRayCounts) ?? 0,
755
+ peakActiveRayCount: activeRayCounts.length > 0 ? Math.max(...activeRayCounts) : 0,
756
+ peakQueueUtilizationRatio,
757
+ maxBounceDepth,
758
+ totalOverflowCount,
759
+ peakOverflowCount,
760
+ averageHitBufferCount: average(hitBufferCounts),
761
+ peakHitBufferCount: hitBufferCounts.length > 0 ? Math.max(...hitBufferCounts) : void 0,
762
+ byBounceDepth: [...byBounceDepth.values()].map((bucket) => ({
763
+ bounceDepth: bucket.bounceDepth,
764
+ sampleCount: bucket.sampleCount,
765
+ averageActiveRayCount: average(bucket.activeRayCounts) ?? 0,
766
+ peakActiveRayCount: Math.max(...bucket.activeRayCounts),
767
+ averageHitBufferCount: average(bucket.hitBufferCounts),
768
+ peakHitBufferCount: bucket.hitBufferCounts.length > 0 ? Math.max(...bucket.hitBufferCounts) : void 0,
769
+ totalOverflowCount: bucket.totalOverflowCount
770
+ })).sort((left, right) => left.bounceDepth - right.bounceDepth),
771
+ byTerminationReason: [...byTerminationReason.entries()].map(([reason, count]) => ({ reason, count })).sort((left, right) => right.count - left.count),
772
+ byHitKind: [...byHitKind.entries()].map(([kind, count]) => ({ kind, count })).sort((left, right) => right.count - left.count)
773
+ };
774
+ };
775
+ return {
776
+ isEnabled() {
777
+ return enabled;
778
+ },
779
+ setEnabled(nextEnabled) {
780
+ enabled = Boolean(nextEnabled);
781
+ },
782
+ trackAllocation(allocation) {
783
+ if (!enabled || allocation.signal?.aborted === true) {
784
+ return () => {
785
+ };
786
+ }
787
+ const normalized = normalizeAllocation(allocation);
788
+ if (!allocations.has(normalized.id)) {
789
+ allocationOrder.push(normalized.id);
790
+ }
791
+ allocations.set(normalized.id, normalized);
792
+ ensureAllocationCapacity();
793
+ updatePeakTrackedBytes();
794
+ return () => {
795
+ this.releaseAllocation(normalized.id);
796
+ };
797
+ },
798
+ releaseAllocation(id) {
799
+ const normalizedId = assertIdentifier("allocation.id", id);
800
+ const deleted = allocations.delete(normalizedId);
801
+ if (!deleted) {
802
+ return false;
803
+ }
804
+ const index = allocationOrder.indexOf(normalizedId);
805
+ if (index >= 0) {
806
+ allocationOrder.splice(index, 1);
807
+ }
808
+ return true;
809
+ },
810
+ recordQueue(sample) {
811
+ if (!enabled || sample.signal?.aborted === true) {
812
+ return false;
813
+ }
814
+ queueSamples.push(normalizeQueueSample(sample));
815
+ trimHistory(queueSamples, settings.maxRetainedQueueSamples);
816
+ return true;
817
+ },
818
+ recordReadyLane(sample) {
819
+ if (!enabled || sample.signal?.aborted === true) {
820
+ return false;
821
+ }
822
+ readyLaneSamples.push(normalizeReadyLaneSample(sample));
823
+ trimHistory(readyLaneSamples, settings.maxRetainedReadyLaneSamples);
824
+ return true;
825
+ },
826
+ recordDispatch(sample) {
827
+ if (!enabled || sample.signal?.aborted === true) {
828
+ return false;
829
+ }
830
+ dispatchSamples.push(normalizeDispatchSample(sample));
831
+ trimHistory(dispatchSamples, settings.maxRetainedDispatches);
832
+ return true;
833
+ },
834
+ recordDependencyUnlock(sample) {
835
+ if (!enabled || sample.signal?.aborted === true) {
836
+ return false;
837
+ }
838
+ dependencyUnlockSamples.push(normalizeDependencyUnlockSample(sample));
839
+ trimHistory(
840
+ dependencyUnlockSamples,
841
+ settings.maxRetainedDependencyUnlockSamples
842
+ );
843
+ return true;
844
+ },
845
+ recordPipelinePhase(sample) {
846
+ if (!enabled || sample.signal?.aborted === true) {
847
+ return false;
848
+ }
849
+ pipelinePhaseSamples.push(normalizePipelinePhaseSample(sample));
850
+ trimHistory(
851
+ pipelinePhaseSamples,
852
+ settings.maxRetainedPipelinePhaseSamples
853
+ );
854
+ return true;
855
+ },
856
+ recordWavefrontTelemetry(sample) {
857
+ if (!enabled || sample.signal?.aborted === true) {
858
+ return false;
859
+ }
860
+ wavefrontSamples.push(normalizeWavefrontTelemetrySample(sample));
861
+ trimHistory(wavefrontSamples, settings.maxRetainedWavefrontSamples);
862
+ return true;
863
+ },
864
+ recordFrame(sample) {
865
+ if (!enabled || sample.signal?.aborted === true) {
866
+ return false;
867
+ }
868
+ frameSamples.push(normalizeFrameSample(sample));
869
+ trimHistory(frameSamples, settings.maxRetainedFrameSamples);
870
+ return true;
871
+ },
872
+ getSnapshot() {
873
+ const memoryByOwner = /* @__PURE__ */ new Map();
874
+ const memoryByCategory = /* @__PURE__ */ new Map();
875
+ for (const allocation of allocations.values()) {
876
+ pushAggregate(memoryByOwner, allocation.owner, allocation.sizeBytes);
877
+ pushAggregate(memoryByCategory, allocation.category, allocation.sizeBytes);
878
+ }
879
+ const totalBytes = totalTrackedBytes();
880
+ const frameTimes = frameSamples.map((sample) => sample.frameTimeMs);
881
+ const targetFrameTimes = frameSamples.map((sample) => sample.targetFrameTimeMs).filter((value) => value !== void 0);
882
+ const gpuBusyTimes = frameSamples.map((sample) => sample.gpuBusyMs).filter((value) => value !== void 0);
883
+ const snapshot = {
884
+ enabled,
885
+ adapter,
886
+ memory: {
887
+ totalTrackedBytes: totalBytes,
888
+ peakTrackedBytes,
889
+ allocationCount: allocations.size,
890
+ trackedUsageRatio: adapter.memoryCapacityHintBytes !== void 0 ? totalBytes / adapter.memoryCapacityHintBytes : void 0,
891
+ byOwner: [...memoryByOwner.entries()].map(([owner, bytes]) => ({ owner, bytes })).sort((left, right) => right.bytes - left.bytes),
892
+ byCategory: [...memoryByCategory.entries()].map(([category, bytes]) => ({ category, bytes })).sort((left, right) => right.bytes - left.bytes)
893
+ },
894
+ dispatch: buildDispatchSnapshot(),
895
+ queues: buildQueueSnapshot(),
896
+ frames: {
897
+ sampleCount: frameSamples.length,
898
+ latestFrameTimeMs: frameSamples[frameSamples.length - 1]?.frameTimeMs,
899
+ averageFrameTimeMs: average(frameTimes),
900
+ averageTargetFrameTimeMs: average(targetFrameTimes),
901
+ droppedFrameRatio: frameSamples.length > 0 ? frameSamples.filter((sample) => sample.dropped === true).length / frameSamples.length : void 0,
902
+ averageGpuBusyMs: average(gpuBusyTimes)
903
+ },
904
+ dag: buildDagSnapshot(),
905
+ pipeline: buildPipelineSnapshot(),
906
+ wavefront: buildWavefrontSnapshot(),
907
+ limitations: LIMITATIONS
908
+ };
909
+ return snapshot;
910
+ },
911
+ reset() {
912
+ allocations.clear();
913
+ allocationOrder.splice(0, allocationOrder.length);
914
+ queueSamples.splice(0, queueSamples.length);
915
+ readyLaneSamples.splice(0, readyLaneSamples.length);
916
+ dispatchSamples.splice(0, dispatchSamples.length);
917
+ dependencyUnlockSamples.splice(0, dependencyUnlockSamples.length);
918
+ pipelinePhaseSamples.splice(0, pipelinePhaseSamples.length);
919
+ wavefrontSamples.splice(0, wavefrontSamples.length);
920
+ frameSamples.splice(0, frameSamples.length);
921
+ peakTrackedBytes = 0;
922
+ }
923
+ };
924
+ }
925
+ function summarizeWavefrontTelemetry(snapshot) {
926
+ if (!snapshot || snapshot.sampleCount === 0) {
927
+ return Object.freeze(["Wavefront telemetry: no samples recorded."]);
928
+ }
929
+ const lines = [
930
+ `Wavefront telemetry: ${snapshot.sampleCount} samples, peak ${snapshot.peakActiveRayCount} active rays, overflow ${snapshot.totalOverflowCount}, max bounce ${snapshot.maxBounceDepth ?? 0}.`
931
+ ];
932
+ if (snapshot.byTerminationReason.length > 0) {
933
+ lines.push(
934
+ `Termination reasons: ${snapshot.byTerminationReason.slice(0, 3).map((entry) => `${entry.reason}=${entry.count}`).join(", ")}.`
935
+ );
936
+ } else {
937
+ lines.push("Termination reasons: none recorded.");
938
+ }
939
+ if (snapshot.byHitKind.length > 0) {
940
+ lines.push(
941
+ `Hit kinds: ${snapshot.byHitKind.slice(0, 3).map((entry) => `${entry.kind}=${entry.count}`).join(", ")}.`
942
+ );
943
+ } else {
944
+ lines.push("Hit kinds: none recorded.");
945
+ }
946
+ lines.push(
947
+ `Bounce depth: ${snapshot.byBounceDepth.map(
948
+ (entry) => `b${entry.bounceDepth} avg=${entry.averageActiveRayCount.toFixed(1)} peak=${entry.peakActiveRayCount}`
949
+ ).join("; ")}.`
950
+ );
951
+ return Object.freeze(lines);
952
+ }
953
+ export {
954
+ createGpuDebugSession,
955
+ estimateDispatchInvocations,
956
+ gpuDebugQueueClasses,
957
+ gpuPipelinePhases,
958
+ gpuResourceCategories,
959
+ summarizeWavefrontTelemetry
960
+ };
961
+ //# sourceMappingURL=index.js.map