pngine 2.2.0 → 3.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.
@@ -100,6 +100,9 @@ export function createWorkerHandlers(env, opts = {}) {
100
100
  let canvas, device, context, gpu, wasm, memory;
101
101
  let initialized = false;
102
102
  let moduleLoaded = false;
103
+ // True once the current dispatcher has executed a command stream — the
104
+ // reset key for loadBytecode (a FAILED init leaves it dirty too).
105
+ let gpuDirty = false;
103
106
  let frameCount = 0;
104
107
  let debugMode = false;
105
108
  // Executor↔host ABI version (docs/abi.md); binaries without the export are v1.
@@ -206,13 +209,14 @@ export function createWorkerHandlers(env, opts = {}) {
206
209
 
207
210
  context = canvas.getContext("webgpu");
208
211
  const format = env.gpu.getPreferredCanvasFormat();
209
- // Header flag bit 3 → "opaque"; default stays the historical "premultiplied".
210
- const alphaMode = bytecode ? canvasAlphaMode(toU8(bytecode)) : "premultiplied";
212
+ // Header flag bit 3 → "premultiplied"; no payload → the spec default.
213
+ const alphaMode = bytecode ? canvasAlphaMode(toU8(bytecode)) : "opaque";
211
214
  context.configure({ device, format, alphaMode, usage: env.gpuTextureUsage.RENDER_ATTACHMENT | env.gpuTextureUsage.COPY_SRC });
212
215
 
213
216
  prefetch?.configure(device, format, alphaMode);
214
217
 
215
218
  wireDispatcher();
219
+ gpuDirty = false;
216
220
  }
217
221
 
218
222
  // Attach a one-shot lost handler. `reason === 'destroyed'` is our own
@@ -231,9 +235,11 @@ export function createWorkerHandlers(env, opts = {}) {
231
235
  const nowMs = env.now();
232
236
  if (nowMs - lastRecoverAt > RECOVER_COOLDOWN_MS) {
233
237
  lastRecoverAt = nowMs;
234
- recoverDevice().catch((err) => {
235
- post({ type: MSG.ERROR, message: `GPU recovery failed: ${err.message}` });
236
- });
238
+ // Through the FIFO, like every other state change: a direct call
239
+ // ran recovery beside the dispatch chain, and a LOAD landing while
240
+ // it awaited its device saw `deviceLost` still true and began a
241
+ // second one — two devices for one loss, one never destroyed.
242
+ dispatch({ type: MSG.RESTART });
237
243
  }
238
244
  }
239
245
  })
@@ -241,8 +247,16 @@ export function createWorkerHandlers(env, opts = {}) {
241
247
  }
242
248
 
243
249
  // Rebuild the GPU stack on a fresh device and reload a shader — the new one if
244
- // supplied, else the last good bytecode — then report ready. The dead device's
245
- // resources are abandoned, so clear moduleLoaded first for a clean build.
250
+ // supplied, else the last good bytecode — then report ready.
251
+ //
252
+ // The stack being replaced is RELEASED first, not abandoned: the old
253
+ // dispatcher's destroy() closes its bitmaps, drops its tables and flips
254
+ // `alive` so a create still suspended in it lands nowhere; the old device's
255
+ // destroy() is a spec no-op on a lost device and frees a LIVE one — the
256
+ // limits-exceed reload replaces a device nothing lost, and every buffer and
257
+ // texture of the previous payload stayed allocated with it until GC.
258
+ // `watchDeviceLost` ignores the resulting `destroyed` reason. (Third leak
259
+ // pass, LEAK-06's edge)
246
260
  async function recoverDevice(bytecode) {
247
261
  if (!initialized) return;
248
262
  const bc = bytecode ?? lastBytecode;
@@ -251,6 +265,9 @@ export function createWorkerHandlers(env, opts = {}) {
251
265
  // rebuilds an empty stack unconditionally, matching the original workers.
252
266
  if (!bc && selfRecover) return;
253
267
  moduleLoaded = false;
268
+ gpu?.destroy();
269
+ gpuDirty = false;
270
+ device?.destroy();
254
271
  await setupGpuStack(bc); // fresh device clears deviceLost; re-applies authored limits
255
272
  if (bc) await loadBytecode(bc);
256
273
  post({ type: MSG.DEVICE_RESTORED });
@@ -373,13 +390,19 @@ export function createWorkerHandlers(env, opts = {}) {
373
390
  // for input, init() to emit resource-creation commands, frame() to render,
374
391
  // getCommandPtr/getCommandLen for the command-buffer output.
375
392
  async function loadBytecode(bytecode) {
376
- // Reset GPU state if reloading
377
- if (moduleLoaded) {
393
+ // Reset GPU state if the dispatcher has executed anything. Keyed on
394
+ // `gpuDirty`, not `moduleLoaded`: the latter is set only on SUCCESS, so a
395
+ // load whose init stream rejected midway (an undecodable image blob, a
396
+ // refused wasm module) left its half-filled dispatcher in place and the
397
+ // next load ran on it — every create guard then skipped the new payload's
398
+ // resources for ids the failed one had filled. (Third leak pass)
399
+ if (gpuDirty) {
378
400
  gpu.destroy();
379
401
  wireDispatcher();
380
- moduleLoaded = false;
381
- uniformMap = null;
402
+ gpuDirty = false;
382
403
  }
404
+ moduleLoaded = false;
405
+ uniformMap = null;
383
406
 
384
407
  // Split PNGB: bytecode (small) → bytecodePtr, data section (large) → dataPtr
385
408
  const bytecodeArray = bytecode instanceof Uint8Array ? bytecode : new Uint8Array(bytecode);
@@ -393,13 +416,16 @@ export function createWorkerHandlers(env, opts = {}) {
393
416
  new Uint8Array(memory.buffer, bytecodePtr, dataOffset).set(bytecodeArray.subarray(0, dataOffset));
394
417
  wasm.setBytecodeLen(dataOffset);
395
418
 
396
- // Data section → separate data buffer (avoids bytecode buffer overflow for large payloads)
419
+ // Data section → separate data buffer (avoids bytecode buffer overflow for large payloads).
420
+ // setDataLen is called EVERY load — with 0 for an empty section, which the
421
+ // ABI defines as single-buffer mode — so a reload never inherits the
422
+ // previous payload's data length.
397
423
  const dataLen = dataEnd - dataOffset;
398
424
  if (dataLen > 0) {
399
425
  const dataPtr = wasm.getDataPtr();
400
426
  new Uint8Array(memory.buffer, dataPtr, dataLen).set(bytecodeArray.subarray(dataOffset, dataEnd));
401
- wasm.setDataLen(dataLen);
402
427
  }
428
+ wasm.setDataLen(dataLen);
403
429
 
404
430
  // Parse uniform table from bytecode before init (for runtime reflection)
405
431
  const { uniforms } = parseUniformTable(bytecodeArray);
@@ -414,10 +440,12 @@ export function createWorkerHandlers(env, opts = {}) {
414
440
  throw new Error(`Init failed: ${initResult}`);
415
441
  }
416
442
 
417
- // Execute the init command buffer (creates GPU resources)
443
+ // Execute the init command buffer (creates GPU resources). The dispatcher
444
+ // is dirty from here on, whether or not the stream completes.
418
445
  const initPtr = wasm.getCommandPtr();
419
446
  const initLen = wasm.getCommandLen();
420
447
  if (initPtr && initLen > 0) {
448
+ gpuDirty = true;
421
449
  await gpu.execute(initPtr);
422
450
  }
423
451
 
@@ -621,7 +649,11 @@ export function createWorkerHandlers(env, opts = {}) {
621
649
  await handleLoad(data);
622
650
  break;
623
651
  case MSG.RESTART:
624
- await recoverDevice(data.bytecode);
652
+ try {
653
+ await recoverDevice(data.bytecode);
654
+ } catch (err) {
655
+ throw new Error(`GPU recovery failed: ${err instanceof Error ? err.message : String(err)}`);
656
+ }
625
657
  break;
626
658
  case MSG.DESTROY:
627
659
  handleDestroy();
@@ -60,7 +60,7 @@ export function createPrefetch(host) {
60
60
  // pipelines/buffers/bind groups stay valid across target swaps; the only
61
61
  // per-target variance is which context resolves the canvas-magic id. The
62
62
  // canvas survives a device loss, so reuse it across recoveries.
63
- function configure(device, format, alphaMode = "premultiplied") {
63
+ function configure(device, format, alphaMode = "opaque") {
64
64
  const canvas = host.getCanvas();
65
65
  if (!prefetchCanvas) prefetchCanvas = env.makeOffscreen(canvas.width, canvas.height);
66
66
  prefetchCtx = prefetchCanvas.getContext("webgpu");
@@ -142,9 +142,14 @@ export function createPrefetch(host) {
142
142
  if (!prefetchCtx || !prefetchCanvas) return;
143
143
  if (prefetchQueue.size === 0) return;
144
144
  prefetchDraining = true;
145
- const gpu = host.getGpu();
146
145
  try {
147
146
  while (prefetchQueue.size > 0 && host.loaded()) {
147
+ // Read the dispatcher INSIDE the loop: this drain yields between
148
+ // thumbnails, and a `load` landing in that yield replaces worker-core's
149
+ // dispatcher — a reference captured once would route the next
150
+ // thumbnail's render target onto a dispatcher the live draw no longer
151
+ // uses, or set the prefetch context on a destroyed one.
152
+ const gpu = host.getGpu();
148
153
  // The queue is a Map (index → uniforms): read its uniforms before delete.
149
154
  const idx = prefetchQueue.keys().next().value;
150
155
  const uniforms = prefetchQueue.get(idx);
Binary file
package/wasm/pngine.wasm CHANGED
Binary file