diff --git a/benchmark/framework/manifest.ts b/benchmark/framework/manifest.ts index b29f4ef..0d98dec 100644 --- a/benchmark/framework/manifest.ts +++ b/benchmark/framework/manifest.ts @@ -139,6 +139,26 @@ export const BENCHMARK_MANIFEST: BenchmarkManifest = Object.freeze({ }) ]), suites: Object.freeze([ + Object.freeze({ + id: 'p1-rendering-acceptance', + description: + 'CPU/Null opaque MSAA graph and owner-mediated residency pressure acceptance evidence.', + domainIds: Object.freeze(['rendering', 'assets']), + pathPrefixes: Object.freeze([ + 'benchmark/p1-rendering-acceptance/', + 'test/benchmark/p1-rendering-acceptance.test.ts', + 'test/rendering/baseline-msaa-graph.test.ts', + 'test/rendering/baseline-msaa-policy.test.ts', + 'src/rendering/baseline/baseline-renderer.ts', + 'src/rendering/baseline/baseline-options.ts', + 'src/rendering/world/residency-pressure.ts', + 'src/rendering/world/prepared-assets.ts' + ]), + command: Object.freeze({ + executable: 'node', + args: Object.freeze(['benchmark/p1-rendering-acceptance/runner.mjs', '{profile}']) + }) + }), Object.freeze({ id: 'dynamic-plugin-runtime', description: diff --git a/benchmark/p1-rendering-acceptance/msaa.ts b/benchmark/p1-rendering-acceptance/msaa.ts new file mode 100644 index 0000000..ceceba5 --- /dev/null +++ b/benchmark/p1-rendering-acceptance/msaa.ts @@ -0,0 +1,142 @@ +import assert from 'node:assert/strict'; +import { NullDevice } from '../../src/rhi/null/device'; +import { RenderGraphBuilder, RenderGraphExecutor } from '../../src/render-graph'; +import { createOpaqueRenderSystem } from '../../src/rendering/phase/opaque-render-system'; +import { resolveBaselineSampleCount } from '../../src/rendering/baseline/baseline-options'; +import { RenderSystemRegistry, compileRenderSystems } from '../../src/rendering/systems'; +import type { RenderEntityId } from '../../src/rendering/world'; +import type { RenderView } from '../../src/rendering/visibility/types'; +import type { AcceptanceObservation } from './types'; + +/** + * Executes empty-draw opaque passes; measures graph CPU work, not GPU raster cost. + * @throws When the positive view count or production attachment/resolve invariants are invalid. + */ +export async function observeMsaa( + viewCount: number, + sampleCount: 1 | 4 +): Promise { + assert.ok(Number.isSafeInteger(viewCount) && viewCount > 0); + const device = createMultisampleNullDevice(); + assert.deepEqual(resolveBaselineSampleCount(device, sampleCount), { sampleCount }); + const graph = new RenderGraphBuilder(); + const registry = new RenderSystemRegistry(); + const views: RenderView[] = []; + for (let index = 0; index < viewCount; index += 1) { + const id = `acceptance-${index}`; + views.push({ + id, + camera: index as RenderEntityId, + surface: id, + viewport: { x: 0, y: 0, width: 64, height: 64 }, + layerMask: 1, + featurePolicyKey: 'acceptance-v1', + historyKey: id + }); + const color = graph.createTexture(texture('rgba16float', sampleCount)); + const depth = graph.createTexture(texture('depth24plus', sampleCount)); + const resolved = sampleCount === 4 ? graph.createTexture(texture('rgba16float', 1)) : undefined; + const opaque = createOpaqueRenderSystem({ + id, + phase: { viewId: id, phase: 'opaque', packets: [] }, + surfaceFrame: { kind: 'surface-frame', id }, + color: texture('rgba16float', sampleCount), + depth: texture('depth24plus', sampleCount), + colorTarget: color, + depthTarget: depth, + ...(resolved === undefined ? {} : { resolveTarget: resolved }), + present: false + }); + const descriptor = opaque.descriptor; + assert.equal(descriptor.kind, 'raster'); + if (descriptor.kind !== 'raster') throw new Error('Opaque descriptor must be raster.'); + registry.add({ + ...descriptor, + setup(...[pass, context]: Parameters) { + const resources = descriptor.setup(pass, context); + // Empty draws still exercise attachment allocation/resolve; retain the pass explicitly. + pass.sideEffect(`acceptance-${index}`); + return resources; + } + }); + } + const compiled = compileRenderSystems(registry, { views, graph }); + const passes = compiled.plan.snapshot.passes; + const resources = compiled.plan.snapshot.resources; + assert.equal(passes.length, viewCount); + let resolves = 0; + for (const pass of passes) { + assert.ok(pass.rasterDetails); + resolves += pass.rasterDetails.resolveAttachments.length; + for (const resolve of pass.rasterDetails.resolveAttachments) { + const source = resources.find( + (resource) => resource.resourceId === resolve.source.resourceId + ); + const destination = resources.find( + (resource) => resource.resourceId === resolve.destination.resourceId + ); + assert.ok(source?.kind === 'texture' && destination?.kind === 'texture'); + assert.equal(source.descriptor.sampleCount, 4); + assert.equal(destination.descriptor.sampleCount, 1); + assert.equal(source.descriptor.format, destination.descriptor.format); + assert.notEqual(source.resourceId, destination.resourceId); + } + } + assert.equal(resolves, sampleCount === 4 ? viewCount : 0); + const counts = resources + .filter((resource) => resource.kind === 'texture') + .map((resource) => { + assert.equal(resource.descriptor.width, 64); + return resource.descriptor.sampleCount; + }); + assert.equal(counts.filter((count) => count === sampleCount).length, viewCount * 2); + assert.equal(resources.length, viewCount * (sampleCount === 4 ? 3 : 2)); + const execution = new RenderGraphExecutor().execute(compiled.plan, { device }); + assert.equal(execution.commandStats.renderPasses, viewCount); + assert.equal(device.queue.metrics().submitted, 1); + await execution.submission.done; + execution.commandBuffer.dispose(); + device.destroy(); + const counters = { + views: viewCount, + sampleCount, + resolves, + textures: resources.length, + renderPasses: execution.commandStats.renderPasses, + submissions: 1 + }; + return { checksum: JSON.stringify(counters), counters }; +} + +function createMultisampleNullDevice(): NullDevice { + const source = new NullDevice(); + const capabilities = source.capabilities; + const formats = new Map(capabilities.formats); + for (const format of ['rgba16float', 'depth24plus'] as const) { + formats.set(format, { + sample: true, + filter: false, + render: true, + blend: false, + storage: false, + copySrc: true, + copyDst: true, + sampleCounts: [1, 4] + }); + } + source.destroy(); + // This is declared Null capability coverage; it does not assert real-device 4x support. + return new NullDevice({ capabilities: { ...capabilities, formats } }); +} + +function texture(format: 'rgba16float' | 'depth24plus', sampleCount: 1 | 4) { + return { + width: 64, + height: 64, + depthOrArrayLayers: 1, + mipLevelCount: 1, + sampleCount, + format, + usage: [format === 'rgba16float' ? 'color-attachment' : 'depth-stencil-attachment'] + } as const; +} diff --git a/benchmark/p1-rendering-acceptance/residency.ts b/benchmark/p1-rendering-acceptance/residency.ts new file mode 100644 index 0000000..b997aeb --- /dev/null +++ b/benchmark/p1-rendering-acceptance/residency.ts @@ -0,0 +1,144 @@ +import assert from 'node:assert/strict'; +import { createAssetHandle, defineAssetType } from '../../src/assets'; +import { AssetPayloadRegistry } from '../../src/assets/runtime'; +import { PreparedAssetRegistry } from '../../src/rendering/world'; +import { + enforceCpuResidencyBudget, + enforceGpuResidencyBudget, + type ResidencyPressureSubject +} from '../../src/rendering/world/residency-pressure'; +import { NullDevice } from '../../src/rhi/null/device'; +import type { PreparedAssetLease, PreparedVariantKey } from '../../src/rendering/world'; +import type { AcceptanceObservation } from './types'; + +/** + * Runs real owner eviction with leases and a pending Null submission; sizes are bytes. + * @throws When the positive four-aligned scale or owner protection/cleanup invariants are invalid. + */ +export async function observeResidency( + count: number, + mode: 'planner' | 'owner-scan' +): Promise { + assert.ok(Number.isSafeInteger(count) && count > 0); + assert.equal(count % 4, 0); + const device = new NullDevice({ submissionMode: 'manual' }); + const prepared = new PreparedAssetRegistry(); + const payloads = new AssetPayloadRegistry(); + const type = defineAssetType<{ value: number }>('acceptance-payload-v1'); + const subjects: ResidencyPressureSubject[] = []; + const cpuLeases: Array<{ dispose(): void }> = []; + const gpuLeases: PreparedAssetLease[] = []; + const submission = device.queue.submit([device.createCommandEncoder().finish()]); + let destroyedBuffers = 0; + for (let index = 0; index <= count; index += 1) { + const handle = createAssetHandle(type, `asset:acceptance-${index}`); + const key: PreparedVariantKey = { + assetId: handle.assetId, + payloadVersion: 1, + deviceGeneration: device.generation, + featurePolicyKey: 'acceptance-v1', + abiVersion: 'v1' + }; + const buffer = device.createBuffer({ size: 64, usage: 1 << 3 }); + prepared.publish({ key, value: { byteLength: 64, buffer } }, (value) => { + value.buffer.dispose(); + assert.equal(value.buffer.state, 'disposed'); + destroyedBuffers += 1; + }); + const subject = { handle, gpuVariants: [key], priority: 0, lastUseTick: index, rebuildCost: 1 }; + subjects.push(subject); + if (index === count) continue; // Extra device bytes are absent from initial candidates. + payloads.register(handle); + payloads.publish( + handle, + { + version: 1, + contentHash: `v1-${index}`, + byteLength: 32, + value: { value: index }, + dependencies: [] + }, + (value) => ({ ...value }) + ); + if (index % 2 === 0) { + const lease = payloads.acquire(handle); + assert.ok(lease); + cpuLeases.push(lease); + } + if (index % 4 < 2) { + const lease = prepared.acquire(key); + assert.ok(lease); + if (index % 4 === 0) gpuLeases.push(lease); + else { + lease.retainUntil(submission); + lease.dispose(); + } + } + } + const candidates = subjects.slice(0, count); + const first = enforce(candidates); + assert.deepEqual(first, { + cpuReleased: count * 16, + cpuRemaining: count * 16, + gpuReleased: count * 32, + gpuRemaining: count * 32 + 64 + }); + assert.equal(prepared.snapshot().activeLeases, count / 4); + assert.equal(prepared.snapshot().activeSubmissions, count / 4); + assert.equal(destroyedBuffers, count / 2); + for (const lease of cpuLeases) lease.dispose(); + for (const lease of gpuLeases) lease.dispose(); + device.queue.completeNextForTesting(); + await submission.done; + await Promise.resolve(); + const second = enforce(subjects); + assert.deepEqual(second, { + cpuReleased: count * 16, + cpuRemaining: 0, + gpuReleased: count * 32 + 64, + gpuRemaining: 0 + }); + assert.equal(prepared.snapshot().knownBytes, 0); + assert.equal(payloads.residentBytes, 0); + assert.equal(destroyedBuffers, count + 1); + device.destroy(); + const counters = { + assets: count, + protectedCpu: count / 2, + protectedGpuLeases: count / 4, + protectedGpuSubmissions: count / 4, + unlistedGpuBytes: 64, + destroyedBuffers, + firstCpuReleased: first.cpuReleased, + firstGpuReleased: first.gpuReleased, + finalCpuBytes: 0, + finalGpuBytes: 0 + }; + return { checksum: JSON.stringify(counters), counters }; + + function enforce(inventory: readonly ResidencyPressureSubject[]) { + if (mode === 'planner') { + const cpu = enforceCpuResidencyBudget(payloads, 0, inventory); + const gpu = enforceGpuResidencyBudget(prepared, device.generation, 0, inventory); + return { + cpuReleased: cpu.releasedBytes, + cpuRemaining: cpu.remainingPressureBytes, + gpuReleased: gpu.releasedBytes, + gpuRemaining: gpu.remainingPressureBytes + }; + } + // Lower-bound comparator: owners still validate leases; it omits planner priority ordering. + const cpuBefore = payloads.residentBytes; + const gpuBefore = prepared.snapshot().knownBytes; + for (const subject of inventory) { + if (payloads.inspect(subject.handle).revisions.length > 0) payloads.evict(subject.handle); + for (const key of subject.gpuVariants) prepared.evictUnreferenced(key); + } + return { + cpuReleased: cpuBefore - payloads.residentBytes, + cpuRemaining: payloads.residentBytes, + gpuReleased: gpuBefore - prepared.snapshot().knownBytes, + gpuRemaining: prepared.snapshot().knownBytes + }; + } +} diff --git a/benchmark/p1-rendering-acceptance/run.ts b/benchmark/p1-rendering-acceptance/run.ts new file mode 100644 index 0000000..a2f3e5f --- /dev/null +++ b/benchmark/p1-rendering-acceptance/run.ts @@ -0,0 +1,91 @@ +import assert from 'node:assert/strict'; +import { mkdirSync, writeFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { captureEnvironment, captureRepositoryState } from '../harness/environment'; +import { summarize } from '../harness/statistics'; +import { resolveProfile } from '../profiles'; +import { observeMsaa } from './msaa'; +import { observeResidency } from './residency'; +import type { AcceptanceObservation } from './types'; + +const profile = resolveProfile(process.argv.at(-1) ?? 'smoke'); +const cases: Array<{ id: string; operation: () => Promise }> = []; +for (const views of profile.name === 'smoke' ? [1, 4] : [1, 8, 32]) { + for (const samples of [1, 4] as const) + cases.push({ + id: `opaque-views-${views}-samples-${samples}`, + operation: () => observeMsaa(views, samples) + }); +} +for (const assets of profile.name === 'smoke' ? [16] : [16, 128, 1024]) { + for (const mode of ['planner', 'owner-scan'] as const) + cases.push({ + id: `residency-assets-${assets}-${mode}`, + operation: () => observeResidency(assets, mode) + }); +} +const results: Array< + AcceptanceObservation & { + caseId: string; + version: number; + rawSamplesMs: number[]; + correctness: 'pass'; + } +> = []; +for (const scenario of cases) { + const oracle = await scenario.operation(); + for (let warmup = 0; warmup < profile.warmupCount; warmup += 1) await scenario.operation(); + results.push({ + caseId: scenario.id, + version: 1, + ...oracle, + rawSamplesMs: [] as number[], + correctness: 'pass' + }); +} +for (let sample = 0; sample < profile.sampleCount * profile.rounds; sample += 1) { + const order = sample % 2 === 0 ? cases : [...cases].reverse(); + for (const scenario of order) { + const result = results.find((entry) => entry.caseId === scenario.id); + assert.ok(result); + const started = performance.now(); + const observation = await scenario.operation(); + result.rawSamplesMs.push(performance.now() - started); + assert.equal(observation.checksum, result.checksum); + } +} +for (const assets of profile.name === 'smoke' ? [16] : [16, 128, 1024]) { + const planner = results.find((result) => result.caseId === `residency-assets-${assets}-planner`); + const reference = results.find( + (result) => result.caseId === `residency-assets-${assets}-owner-scan` + ); + assert.equal(planner?.checksum, reference?.checksum); +} +const report = { + schemaVersion: 1, + suite: 'p1-rendering-acceptance', + profile: profile.name, + createdAt: new Date().toISOString(), + environment: captureEnvironment(), + repository: captureRepositoryState(), + protocol: { + warmupCount: profile.warmupCount, + sampleCountPerRound: profile.sampleCount, + rounds: profile.rounds, + order: 'alternating forward/reverse', + backend: 'Null', + includes: 'fixture setup, production operations, oracle checks and cleanup', + timing: 'descriptive CPU wall clock; concurrent work may contend; no GPU timing', + comparisons: + '1x versus 4x quality baseline; planner versus lower-bound owner scan without ranking' + }, + results: results.map((result) => ({ ...result, summary: summarize(result.rawSamplesMs) })) +}; +const output = resolve('benchmark/artifacts/p1-rendering-acceptance'); +mkdirSync(output, { recursive: true }); +const path = resolve( + output, + `p1-rendering-acceptance-${profile.name}-${report.createdAt.replaceAll(':', '-')}.json` +); +writeFileSync(path, `${JSON.stringify(report, null, 2)}\n`); +console.log(`P1 rendering acceptance: ${results.length} cases passed; artifact: ${path}`); diff --git a/benchmark/p1-rendering-acceptance/runner.mjs b/benchmark/p1-rendering-acceptance/runner.mjs new file mode 100644 index 0000000..74518e8 --- /dev/null +++ b/benchmark/p1-rendering-acceptance/runner.mjs @@ -0,0 +1,10 @@ +import { spawnSync } from 'node:child_process'; +const profile = process.argv.at(-1); +if (!['smoke', 'standard', 'nightly'].includes(profile)) + throw new Error(`Unknown profile: ${profile}`); +const viteNode = new URL('../../node_modules/vite-node/vite-node.mjs', import.meta.url); +const runner = new URL('./run.ts', import.meta.url); +const result = spawnSync(process.execPath, [viteNode.pathname, runner.pathname, profile], { + stdio: 'inherit' +}); +process.exit(result.status ?? 1); diff --git a/benchmark/p1-rendering-acceptance/types.ts b/benchmark/p1-rendering-acceptance/types.ts new file mode 100644 index 0000000..d7b044b --- /dev/null +++ b/benchmark/p1-rendering-acceptance/types.ts @@ -0,0 +1,5 @@ +/** Deterministic semantics and structural counters accompanying CPU benchmark samples. */ +export interface AcceptanceObservation { + readonly checksum: string; + readonly counters: Readonly>; +} diff --git a/e2e/harness/interop/webgpu-borrowed-buffer.ts b/e2e/harness/interop/webgpu-borrowed-buffer.ts new file mode 100644 index 0000000..07454b6 --- /dev/null +++ b/e2e/harness/interop/webgpu-borrowed-buffer.ts @@ -0,0 +1,99 @@ +import { + WebGPUInteropExtension, + type BrowserGraphicsSession, + type WebGPUNativeBufferPort, + type WebGPUNativeResourcePort +} from '../../../src'; + +/** Exercises the reviewed interop trust boundary on a real browser-owned device and submission. */ +export async function runWebGpuBorrowedBufferGolden( + session: BrowserGraphicsSession +): Promise>> { + const interop = session.device.getExtension(WebGPUInteropExtension); + if (interop === undefined) throw new Error('WebGPU interop extension is missing.'); + const scope = interop.createScope('e2e-reviewed-native-copy', 'aether-owned-submission'); + const createBuffer = scope.device.createBuffer; + if (createBuffer === undefined) throw new Error('Native interop device cannot create a buffer.'); + const native = requireBuffer(createBuffer.call(scope.device, { size: 16, usage: 12 })); + const destroyNative = native.destroy; + if (destroyNative === undefined) + throw new Error('Native borrowed buffer cannot be destroyed by its owner.'); + const imported = scope.importBorrowed('buffer', native, { size: 16, usage: 12 }); + const intermediate = session.device.createBuffer({ size: 16, usage: 12 }); + const nativeTarget = session.device.createBuffer({ size: 16, usage: 12 }); + const readback = session.device.createBuffer({ size: 16, usage: 9 }); + const expected = new Uint32Array([0x12345678, 0x89abcdef, 0x13579bdf, 0x2468ace0]); + const second = interop.createScope('e2e-external-owner'); + try { + let independentSubmissionRejected = false; + try { + interop.createScope('e2e-unreviewed-library', 'independent-submission'); + } catch (error) { + independentSubmissionRejected = error instanceof Error && error.message.includes('isolated'); + } + if (!independentSubmissionRejected) throw new Error('Independent submission was accepted.'); + session.device.queue.writeBuffer(imported, 0, expected); + const encoder = session.device.createCommandEncoder({ label: 'e2e-native-borrowed-copy' }); + // Public copies establish leases for every native access. The first readback observes + // zeroed nativeTarget; only the native command supplies the words read by the final copy. + encoder.copyBufferToBuffer(imported, 0, intermediate, 0, 16); + encoder.copyBufferToBuffer(nativeTarget, 0, readback, 0, 16); + scope + .unwrapEncoder(encoder) + .copyBufferToBuffer( + scope.unwrapResource('buffer', intermediate), + 0, + scope.unwrapResource('buffer', nativeTarget), + 0, + 16 + ); + encoder.copyBufferToBuffer(nativeTarget, 0, readback, 0, 16); + const submission = session.device.queue.submit([encoder.finish()]); + scope.dispose(); + if (imported.state !== 'disposed') throw new Error('Scope cleanup did not dispose its import.'); + const result = await submission.done; + if (result.status !== 'completed') throw new Error(`Native copy ended with ${result.status}.`); + await readback.mapAsync(1); + const actual = new Uint32Array(readback.getMappedRange().slice(0)); + readback.unmap(); + if (!actual.every((value, index) => value === expected[index])) + throw new Error('Native copy changed buffer words.'); + + // Reimport and execute again to prove borrowed scope cleanup did not destroy native storage. + const borrowedAgain = second.importBorrowed('buffer', native, { size: 16, usage: 12 }); + const verify = session.device.createCommandEncoder(); + verify.copyBufferToBuffer(borrowedAgain, 0, readback, 0, 16); + const verified = await session.device.queue.submit([verify.finish()]).done; + if (verified.status !== 'completed') + throw new Error('Borrowed storage did not survive scope cleanup.'); + await readback.mapAsync(1); + const retained = new Uint32Array(readback.getMappedRange().slice(0)); + readback.unmap(); + if (!retained.every((value, index) => value === expected[index])) + throw new Error('Borrowed storage was not retained.'); + return Object.freeze({ + matchesSource: true, + borrowedSurvivesScopeCleanup: true, + independentSubmissionRejected + }); + } finally { + second.dispose(); + scope.dispose(); + readback.dispose(); + nativeTarget.dispose(); + intermediate.dispose(); + destroyNative.call(native); + } +} + +function requireBuffer(resource: WebGPUNativeResourcePort): WebGPUNativeBufferPort { + if ( + !('size' in resource) || + typeof resource.size !== 'number' || + !('usage' in resource) || + typeof resource.usage !== 'number' + ) { + throw new Error('Native interop buffer lacks size and usage facts.'); + } + return resource as WebGPUNativeBufferPort; +} diff --git a/e2e/harness/webgpu-bgra-copy.ts b/e2e/harness/webgpu-bgra-copy.ts new file mode 100644 index 0000000..85a4b43 --- /dev/null +++ b/e2e/harness/webgpu-bgra-copy.ts @@ -0,0 +1,41 @@ +import type { BrowserGraphicsSession } from '../../src'; + +/** Checks byte-preserving BGRA copies, including encoded sRGB bytes without color conversion. */ +export async function runWebGpuBgraCopyGolden( + session: BrowserGraphicsSession +): Promise<{ readonly bgraMatchesSource: boolean; readonly bgraSrgbMatchesSource: boolean }> { + for (const format of ['bgra8unorm', 'bgra8unorm-srgb'] as const) { + const source = session.device.createBuffer({ size: 256, usage: 12 }); + const readback = session.device.createBuffer({ size: 256, usage: 9 }); + const texture = session.device.createTexture({ size: [1, 1], format, usage: 3 }); + const destination = session.device.createTexture({ size: [1, 1], format, usage: 3 }); + // Distinct B/G/R bytes detect accidental RGBA channel interpretation. + const expected = new Uint8Array([193, 127, 61, 255]); + try { + session.device.queue.writeBuffer(source, 0, expected); + const encoder = session.device.createCommandEncoder({ label: `e2e-${format}-copy` }); + encoder.copyBufferToTexture({ buffer: source, bytesPerRow: 256 }, { texture }, [1, 1]); + encoder.copyTextureToTexture({ texture }, { texture: destination }, [1, 1]); + encoder.copyTextureToBuffer( + { texture: destination }, + { buffer: readback, bytesPerRow: 256 }, + [1, 1] + ); + const result = await session.device.queue.submit([encoder.finish()]).done; + if (result.status !== 'completed') + throw new Error(`${format} copy ended with ${result.status}.`); + await readback.mapAsync(1); + const actual = new Uint8Array(readback.getMappedRange().slice(0, 4)); + readback.unmap(); + if (!actual.every((value, index) => value === expected[index])) { + throw new Error(`${format} copy changed raw BGRA bytes: ${actual}.`); + } + } finally { + destination.dispose(); + texture.dispose(); + readback.dispose(); + source.dispose(); + } + } + return Object.freeze({ bgraMatchesSource: true, bgraSrgbMatchesSource: true }); +} diff --git a/e2e/harness/webgpu-scene.ts b/e2e/harness/webgpu-scene.ts index 41741fa..ded258f 100644 --- a/e2e/harness/webgpu-scene.ts +++ b/e2e/harness/webgpu-scene.ts @@ -1,3 +1,4 @@ +import { runWebGpuBorrowedBufferGolden } from './interop/webgpu-borrowed-buffer'; import { createBrowserGraphics, type BrowserGraphicsSession, @@ -8,6 +9,7 @@ import { createE2EDrawPacket, executeOpaqueScene } from './opaque-scene'; import { runWebGpuLightListGolden } from './webgpu-light-list'; import { runWebGpuClusterLightListGolden } from './webgpu-cluster-light-list'; import { runWebGpuTextureCopyGolden } from './webgpu-texture-copy'; +import { runWebGpuSurfaceLifetime } from './webgpu-surface-lifetime'; const WIDTH = 640; const HEIGHT = 360; @@ -25,6 +27,7 @@ export interface WebGPUSceneResult { } export async function runWebGPUScene(canvas: HTMLCanvasElement): Promise { + const surfaceLifetime = await runWebGpuSurfaceLifetime(); const session = await createBrowserGraphics({ canvas, preference: ['webgpu'], @@ -44,6 +47,7 @@ export async function runWebGPUScene(canvas: HTMLCanvasElement): Promise>> { + const canvas = document.createElement('canvas'); + canvas.width = 16; + canvas.height = 16; + document.body.append(canvas); + const session = await createBrowserGraphics({ + canvas, + preference: ['webgpu'], + device: { requiredFeatures: [], optionalFeatures: [] }, + surface: { width: 16, height: 16, alphaMode: 'opaque' } + }); + const interop = session.device.getExtension(WebGPUInteropExtension); + if (interop === undefined) throw new Error('Surface lifetime requires WebGPU interop.'); + const scope = interop.createScope('e2e-surface-lifetime'); + const native = scope.device; + if (native.pushErrorScope === undefined || native.popErrorScope === undefined) + throw new Error('Surface lifetime requires native validation error scopes.'); + const errors: Array = []; + const clear = (view: RHITextureView): void => { + const encoder = session.device.createCommandEncoder(); + const pass = encoder.beginRenderPass({ + colorAttachments: [{ view, loadOp: 'clear', storeOp: 'store', clearValue: [0, 1, 0, 1] }] + }); + pass.end(); + session.device.queue.submit([encoder.finish()]); + }; + const checkedClear = async (view: RHITextureView): Promise => { + native.pushErrorScope!('validation'); + clear(view); + const error = await native.popErrorScope!(); + const message = error === null ? null : error.message; + errors.push(message); + return message; + }; + try { + // Microtasks do not run the browser's canvas expiry algorithm. + const microtask = acquire(session); + const microtaskView = microtask.texture.createView(); + await Promise.resolve(); + const microtaskError = await checkedClear(microtaskView); + microtask.present(); + microtaskView.dispose(); + + const expired = acquire(session); + const expiredView = expired.texture.createView(); + // The second callback guarantees an intervening rendering update, rather than + // relying on timer delays or assuming that the first rAF already expired it. + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())) + ); + const expiryError = await checkedClear(expiredView); + expired.release(); + expiredView.dispose(); + + const reconfigured = acquire(session); + session.resize({ width: 17, height: 16 }); + let reconfigureError: string | null = null; + try { + reconfigured.texture.createView(); + } catch (error) { + if (!(error instanceof Error)) throw error; + reconfigureError = error.message; + } + const recovered = acquire(session); + const recoveredView = recovered.texture.createView(); + const recoveryError = await checkedClear(recoveredView); + recovered.present(); + recoveredView.dispose(); + await native.queue.onSubmittedWorkDone(); + return Object.freeze({ + adapter: session.adapter.info, + microtaskError, + expiryError, + expiredFrameState: expired.state, + expiredTextureState: expired.texture.state, + reconfigureError, + reconfiguredFrameState: reconfigured.state, + reconfiguredTextureState: reconfigured.texture.state, + recoveryError, + recoveredFrameState: recovered.state, + queue: session.device.queue.metrics(), + errors + }); + } finally { + scope.dispose(); + await session.destroy(); + canvas.remove(); + } +} + +function acquire(session: BrowserGraphicsSession): RHISurfaceFrame { + const result = session.surface.acquire(); + if (result.status !== 'success') throw new Error(`Surface acquire failed: ${result.status}.`); + return result.frame; +} diff --git a/e2e/harness/webgpu-texture-copy.ts b/e2e/harness/webgpu-texture-copy.ts index 1d5e699..d64d590 100644 --- a/e2e/harness/webgpu-texture-copy.ts +++ b/e2e/harness/webgpu-texture-copy.ts @@ -1,4 +1,5 @@ import type { BrowserGraphicsSession } from '../../src'; +import { runWebGpuBgraCopyGolden } from './webgpu-bgra-copy'; const COPY_SRC = 1 << 2; const COPY_DST = 1 << 3; @@ -25,6 +26,8 @@ export interface WebGpuTextureCopyGolden { readonly singleChannelMatchesSource: boolean; readonly twoChannelMatchesSource: boolean; readonly srgbMatchesSource: boolean; + readonly bgraMatchesSource: boolean; + readonly bgraSrgbMatchesSource: boolean; readonly bytes: readonly number[]; } @@ -85,6 +88,7 @@ export async function runWebGpuTextureCopyGolden( const singleChannelMatchesSource = await runSingleChannelTextureCopyGolden(session); const twoChannelMatchesSource = await runTwoChannelTextureCopyGolden(session); const srgbMatchesSource = await runSrgbTextureCopyGolden(session); + const bgra = await runWebGpuBgraCopyGolden(session); return Object.freeze({ matchesSource, integerMatchesSource, @@ -93,6 +97,7 @@ export async function runWebGpuTextureCopyGolden( singleChannelMatchesSource, twoChannelMatchesSource, srgbMatchesSource, + ...bgra, bytes: Object.freeze(bytes) }); } finally { diff --git a/e2e/specs/react-vite-device-loss.spec.ts b/e2e/specs/react-vite-device-loss.spec.ts new file mode 100644 index 0000000..bff5677 --- /dev/null +++ b/e2e/specs/react-vite-device-loss.spec.ts @@ -0,0 +1,304 @@ +import { expect, test } from '@playwright/test'; +import { writeFile } from 'node:fs/promises'; +import type { MountedAetherScene } from '../../examples/react-vite-ts/src/aether-scene'; + +interface CapturedDeviceSnapshot { + readonly id: number; + readonly label: string; + readonly adapter: Readonly>; + readonly loss: Readonly<{ reason: string; message: string }> | null; +} + +interface DeviceLossProbe { + snapshot(): readonly CapturedDeviceSnapshot[]; + requestCount(): number; + destroyActiveDevice(): Promise>; +} + +declare global { + interface Window { + __WEBGPU_DEVICE_LOSS_PROBE__?: DeviceLossProbe; + } +} + +test('WebGPU native device destruction terminates the scene generation without recreation', async ({ + page, + browser +}, info) => { + test.skip(!info.project.name.endsWith('webgpu'), 'Native GPUDevice loss applies only to WebGPU.'); + const pageErrors: string[] = []; + page.on('pageerror', (error) => pageErrors.push(error.message)); + await page.addInitScript(installNativeDeviceProbe); + await page.goto('/?backend=webgpu&samples=4'); + await expect(page.locator('.status-ready')).toBeVisible({ timeout: 25_000 }); + + const initial = await page.evaluate(() => { + const scene = window.__aetherScene as MountedAetherScene | undefined; + const probe = window.__WEBGPU_DEVICE_LOSS_PROBE__; + if (scene?.lost === undefined || probe === undefined) + throw new Error('Rendered WebGPU scene and native device capture are required.'); + return { + backend: scene.backend, + diagnostics: scene.diagnostics(), + validationErrors: scene.validationErrors(), + runtimeErrors: scene.runtimeErrors(), + deviceRequests: probe.requestCount(), + devices: probe.snapshot() + }; + }); + expect(initial.backend).toBe('webgpu'); + expect(initial.diagnostics).toMatchObject({ status: 'rendered', sampleCount: 4 }); + expect(initial.validationErrors).toEqual([]); + expect(initial.runtimeErrors).toEqual([]); + expect(initial.devices.filter((device) => device.loss === null)).toHaveLength(1); + expect(initial.deviceRequests).toBe(initial.devices.length); + + const terminated = await page.evaluate(async () => { + const scene = window.__aetherScene as MountedAetherScene | undefined; + const probe = window.__WEBGPU_DEVICE_LOSS_PROBE__; + if (scene?.lost === undefined || probe === undefined) + throw new Error('Mounted WebGPU scene and device capture are missing.'); + const nativeLoss = await probe.destroyActiveDevice(); + const sceneLoss = await scene.lost; + // Drain the host's loss continuation before starting the bounded observation. + await scene.recoveryReady; + const devicesAtLoss = probe.snapshot(); + let replaced = false; + for (let frame = 0; frame < 30; frame += 1) { + await new Promise((resolve) => requestAnimationFrame(() => resolve())); + if (window.__aetherScene !== scene) replaced = true; + } + return { + nativeLoss, + sceneLoss, + replaced, + devicesAtLoss, + devicesAfterObservation: probe.snapshot(), + deviceRequestsAfterObservation: probe.requestCount(), + diagnostics: scene.diagnostics(), + metrics: scene.nativeMetrics() + }; + }); + const evidencePath = info.outputPath('webgpu-native-device-destruction.json'); + await writeFile( + evidencePath, + JSON.stringify( + { + environment: { + platform: process.platform, + architecture: process.arch, + browserVersion: browser.version(), + project: info.project.name, + observationFrames: 30 + }, + initial, + terminated, + pageErrors + }, + null, + 2 + ) + ); + await info.attach('webgpu-native-device-destruction', { + path: evidencePath, + contentType: 'application/json' + }); + expect(terminated.nativeLoss.reason).toBe('destroyed'); + expect(terminated.sceneLoss).toMatchObject({ + backend: 'webgpu', + stage: 'device', + reason: 'destroyed', + recreationAllowed: false + }); + expect(terminated.sceneLoss.generation).toBeGreaterThan(0); + expect(terminated.replaced).toBe(false); + expect(terminated.devicesAfterObservation).toEqual(terminated.devicesAtLoss); + expect(terminated.devicesAfterObservation).toHaveLength(initial.devices.length); + expect(terminated.deviceRequestsAfterObservation).toBe(initial.deviceRequests); + expect(terminated.metrics).toMatchObject({ pending: 0, leasedResources: 0 }); + expect(pageErrors).toEqual([]); + + // Teardown stays explicit for a non-recoverable loss; the host must not remount it. + await page.evaluate(async () => { + const scene = window.__aetherScene as MountedAetherScene | undefined; + if (scene === undefined) throw new Error('Terminated scene is missing.'); + await scene.destroy(); + await scene.destroy(); + }); + expect(pageErrors).toEqual([]); +}); + +test('WebGPU recovers a real GPU process loss with a new validation-clean scene generation', async ({ + page, + browser +}, info) => { + test.skip(!info.project.name.endsWith('webgpu'), 'Native GPUDevice loss applies only to WebGPU.'); + const pageErrors: string[] = []; + page.on('pageerror', (error) => pageErrors.push(error.message)); + await page.addInitScript(installNativeDeviceProbe); + await page.goto('/?backend=webgpu&samples=4'); + await expect(page.locator('.status-ready')).toBeVisible({ timeout: 25_000 }); + const previous = await page.evaluateHandle(() => { + const scene = window.__aetherScene as MountedAetherScene | undefined; + if (scene?.lost === undefined) throw new Error('Mounted WebGPU scene is missing.'); + return scene; + }); + const initial = await previous.evaluate((scene) => ({ + backend: scene.backend, + diagnostics: scene.diagnostics(), + validationErrors: scene.validationErrors(), + runtimeErrors: scene.runtimeErrors(), + devices: window.__WEBGPU_DEVICE_LOSS_PROBE__!.snapshot() + })); + expect(initial.backend).toBe('webgpu'); + expect(initial.diagnostics).toMatchObject({ status: 'rendered', sampleCount: 4 }); + expect(initial.validationErrors).toEqual([]); + expect(initial.runtimeErrors).toEqual([]); + + // CDP targets this Playwright worker's browser, never an existing user browser. + const cdp = await browser.newBrowserCDPSession(); + await cdp.send('Browser.crashGpuProcess'); + await cdp.detach(); + const loss = await previous.evaluate((scene) => scene.lost); + expect(loss).toMatchObject({ backend: 'webgpu', stage: 'device', recreationAllowed: true }); + expect(loss?.reason).not.toBe('destroyed'); + expect(loss?.generation).toBe(initial.diagnostics?.deviceGeneration); + await expect + .poll( + () => + previous.evaluate((scene) => { + const current = window.__aetherScene as MountedAetherScene | undefined; + return ( + current !== undefined && + current !== scene && + current.diagnostics()?.status === 'rendered' + ); + }), + { timeout: 25_000 } + ) + .toBe(true); + const recovered = await page.evaluate(() => { + const scene = window.__aetherScene as MountedAetherScene | undefined; + const probe = window.__WEBGPU_DEVICE_LOSS_PROBE__; + if (scene === undefined || probe === undefined) throw new Error('Recovered scene is missing.'); + return { + backend: scene.backend, + diagnostics: scene.diagnostics(), + validationErrors: scene.validationErrors(), + runtimeErrors: scene.runtimeErrors(), + metrics: scene.nativeMetrics(), + devices: probe.snapshot(), + deviceRequests: probe.requestCount() + }; + }); + const retired = await previous.evaluate((scene) => ({ metrics: scene.nativeMetrics() })); + const evidencePath = info.outputPath('webgpu-device-loss-recovery.json'); + await writeFile( + evidencePath, + JSON.stringify( + { + environment: { + platform: process.platform, + architecture: process.arch, + browserVersion: browser.version() + }, + injection: 'Browser.crashGpuProcess', + initial, + loss, + retired, + recovered, + pageErrors + }, + null, + 2 + ) + ); + await info.attach('webgpu-device-loss-recovery', { + path: evidencePath, + contentType: 'application/json' + }); + expect(recovered.backend).toBe('webgpu'); + expect(recovered.diagnostics).toMatchObject({ status: 'rendered', sampleCount: 4 }); + expect(recovered.diagnostics?.deviceGeneration).toBeGreaterThan(loss!.generation); + expect(recovered.validationErrors).toEqual([]); + expect(recovered.runtimeErrors).toEqual([]); + expect(retired.metrics).toMatchObject({ pending: 0, leasedResources: 0 }); + expect(recovered.devices.filter((device) => device.loss === null)).toHaveLength(1); + expect(recovered.deviceRequests).toBe(initial.devices.length + 1); + expect(pageErrors).toEqual([]); + await previous.dispose(); +}); + +/** Installs page-local instrumentation without altering native device or loss identities. */ +function installNativeDeviceProbe(): void { + interface NativeDevice { + readonly label: string; + readonly lost: Promise<{ readonly reason: string; readonly message: string }>; + destroy(): void; + } + interface NativeAdapter { + readonly info: { + readonly vendor: string; + readonly architecture: string; + readonly device: string; + readonly description: string; + }; + requestDevice(descriptor?: object): Promise; + } + const adapterConstructor = Reflect.get(globalThis, 'GPUAdapter'); + if (typeof adapterConstructor !== 'function') throw new Error('GPUAdapter is unavailable.'); + const prototype = adapterConstructor.prototype as NativeAdapter; + const requestDevice = prototype.requestDevice; + let deviceRequests = 0; + const records: Array<{ + readonly device: NativeDevice; + readonly id: number; + readonly adapter: Readonly>; + loss: CapturedDeviceSnapshot['loss']; + }> = []; + prototype.requestDevice = async function (descriptor?: object): Promise { + deviceRequests += 1; + const device = await requestDevice.call(this, descriptor); + const info = this.info; + const record = { + device, + id: records.length + 1, + adapter: Object.freeze({ + vendor: info.vendor, + architecture: info.architecture, + device: info.device, + description: info.description + }), + loss: null as CapturedDeviceSnapshot['loss'] + }; + records.push(record); + void device.lost.then((loss) => { + record.loss = Object.freeze({ reason: loss.reason, message: loss.message }); + }); + return device; + }; + window.__WEBGPU_DEVICE_LOSS_PROBE__ = Object.freeze({ + requestCount: () => deviceRequests, + snapshot: () => + Object.freeze( + records.map((record) => + Object.freeze({ + id: record.id, + label: record.device.label, + adapter: record.adapter, + loss: record.loss + }) + ) + ), + async destroyActiveDevice() { + const live = records.filter((record) => record.loss === null); + if (live.length !== 1) + throw new Error(`Expected one live WebGPU device, found ${live.length}.`); + const record = live[0]; + if (record === undefined) throw new Error('Active WebGPU device is missing.'); + record.device.destroy(); + const loss = await record.device.lost; + return Object.freeze({ id: record.id, reason: loss.reason, message: loss.message }); + } + }); +} diff --git a/e2e/specs/react-vite-render.spec.ts b/e2e/specs/react-vite-render.spec.ts index 4a53ce6..3cb51f6 100644 --- a/e2e/specs/react-vite-render.spec.ts +++ b/e2e/specs/react-vite-render.spec.ts @@ -1,4 +1,6 @@ import { expect, test, type Page, type TestInfo } from '@playwright/test'; +import { writeFile } from 'node:fs/promises'; +import type { MountedAetherScene } from '../../examples/react-vite-ts/src/aether-scene'; declare global { interface Window { @@ -92,26 +94,50 @@ test('renders the point-shadow receiver demo without graph binding errors', asyn }); test('WebGL2 restores a real lost context by replacing the scene generation', async ({ - page + page, + browser }, info) => { test.skip(!info.project.name.endsWith('webgl2'), 'WEBGL_lose_context applies only to WebGL2.'); await page.goto('/?backend=webgl2&samples=4'); await expect(page.locator('.status-ready')).toBeVisible({ timeout: 25_000 }); - const didTrigger = await page.evaluate(async () => { + const injection = await page.evaluate(async () => { const canvas = document.querySelector('canvas'); if (!(canvas instanceof HTMLCanvasElement)) throw new Error('Demo canvas is missing.'); - const before = window.__aetherScene; + const before = window.__aetherScene as MountedAetherScene | undefined; if (before === undefined) throw new Error('Mounted scene is missing.'); const context = canvas.getContext('webgl2'); - const extension = context?.getExtension('WEBGL_lose_context'); - if (extension === null || extension === undefined) return false; + if (context === null) throw new Error('Mounted WebGL2 context is missing.'); + const initial = { + backend: before.backend, + diagnostics: before.diagnostics(), + renderer: context.getParameter(context.RENDERER) as string, + vendor: context.getParameter(context.VENDOR) as string + }; + const extension = context.getExtension('WEBGL_lose_context'); + if (extension === null) return { triggered: false, initial }; extension.loseContext(); await new Promise((resolve) => setTimeout(resolve, 20)); extension.restoreContext(); (window as unknown as { __aetherRecoveryBefore?: unknown }).__aetherRecoveryBefore = before; - return true; + return { triggered: true, initial }; }); - test.skip(!didTrigger, 'Current browser does not expose WEBGL_lose_context.'); + const evidencePath = info.outputPath('webgl2-context-loss-recovery.json'); + const environment = { + platform: process.platform, + architecture: process.arch, + browserVersion: browser.version(), + project: info.project.name + }; + await writeFile( + evidencePath, + JSON.stringify({ environment, injection, recovered: null }, null, 2) + ); + if (!injection.triggered) + await info.attach('webgl2-context-loss-recovery', { + path: evidencePath, + contentType: 'application/json' + }); + test.skip(!injection.triggered, 'Current browser does not expose WEBGL_lose_context.'); await expect .poll( () => @@ -128,6 +154,24 @@ test('WebGL2 restores a real lost context by replacing the scene generation', as { timeout: 25_000 } ) .toBe(true); + const recovered = await page.evaluate(() => { + const scene = window.__aetherScene as MountedAetherScene | undefined; + if (scene === undefined) throw new Error('Recovered WebGL2 scene is missing.'); + return { + backend: scene.backend, + diagnostics: scene.diagnostics(), + validationErrors: scene.validationErrors(), + runtimeErrors: scene.runtimeErrors() + }; + }); + await writeFile(evidencePath, JSON.stringify({ environment, injection, recovered }, null, 2)); + await info.attach('webgl2-context-loss-recovery', { + path: evidencePath, + contentType: 'application/json' + }); + expect(recovered.backend).toBe('webgl2'); + expect(recovered.validationErrors).toEqual([]); + expect(recovered.runtimeErrors).toEqual([]); }); test('navigates to DamagedHelmet demo and renders glTF PBR model', async ({ page }, info) => { diff --git a/e2e/specs/webgpu-render.spec.ts b/e2e/specs/webgpu-render.spec.ts index 6807f47..1c7497b 100644 --- a/e2e/specs/webgpu-render.spec.ts +++ b/e2e/specs/webgpu-render.spec.ts @@ -1,9 +1,19 @@ import { expect, test } from '../fixtures/harness'; +import { writeFile } from 'node:fs/promises'; test('WebGPU renders the clear, triangle, and indexed depth cube in one submission', async ({ - harness + harness, + browser }, testInfo) => { const state = await harness.state(); + await writeFile( + testInfo.outputPath('webgpu-surface-lifetime.json'), + JSON.stringify( + { platform: process.platform, architecture: process.arch, browser: browser.version(), state }, + null, + 2 + ) + ); await testInfo.attach('webgpu-state', { body: JSON.stringify(state, null, 2), contentType: 'application/json' @@ -23,7 +33,7 @@ test('WebGPU renders the clear, triangle, and indexed depth cube in one submissi renderPasses: 1, drawCalls: 0, indexedDrawCalls: 2, - nativeQueueSubmits: 12, + nativeQueueSubmits: 16, validationErrors: 0, lightListGolden: { matchesCpuOracle: true, @@ -49,7 +59,26 @@ test('WebGPU renders the clear, triangle, and indexed depth cube in one submissi singleChannelMatchesSource: true, twoChannelMatchesSource: true, srgbMatchesSource: true, + bgraMatchesSource: true, + bgraSrgbMatchesSource: true, bytes: [17, 61, 143, 255] + }, + interopGolden: { + matchesSource: true, + borrowedSurvivesScopeCleanup: true, + independentSubmissionRejected: true + }, + surfaceLifetime: { + microtaskError: null, + expiryError: expect.stringMatching(/expired|destroyed/i), + expiredFrameState: 'released', + expiredTextureState: 'disposed', + reconfigureError: expect.stringMatching(/disposed/), + reconfiguredFrameState: 'released', + reconfiguredTextureState: 'disposed', + recoveryError: null, + recoveredFrameState: 'presented', + queue: { pending: 0, leasedResources: 0 } } } }); @@ -71,7 +100,7 @@ test('WebGPU stays validation-clean across resize, zero extent, and surface gene physicalSize: [320, 180], surfaceGeneration: 2, rendered: true, - nativeQueueSubmits: 13, + nativeQueueSubmits: 17, validationErrors: 0 } }); @@ -84,7 +113,7 @@ test('WebGPU stays validation-clean across resize, zero extent, and surface gene physicalSize: [0, 0], surfaceGeneration: 3, rendered: false, - nativeQueueSubmits: 13, + nativeQueueSubmits: 17, validationErrors: 0 } }); @@ -98,7 +127,7 @@ test('WebGPU stays validation-clean across resize, zero extent, and surface gene physicalSize: [256, 144], surfaceGeneration: 4, rendered: true, - nativeQueueSubmits: 14, + nativeQueueSubmits: 18, validationErrors: 0 } }); diff --git a/playwright.config.ts b/playwright.config.ts index f162f39..df71ccf 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -48,7 +48,7 @@ export default defineConfig({ }, { name: 'react-vite-webgl2', - testMatch: 'react-vite-render.spec.ts', + testMatch: ['react-vite-render.spec.ts', 'react-vite-device-loss.spec.ts'], use: { ...devices['Desktop Chrome'], ...(process.platform === 'darwin' ? { channel: 'chrome' } : {}), @@ -61,7 +61,7 @@ export default defineConfig({ }, { name: 'react-vite-webgpu', - testMatch: 'react-vite-render.spec.ts', + testMatch: ['react-vite-render.spec.ts', 'react-vite-device-loss.spec.ts'], use: { ...devices['Desktop Chrome'], ...(process.platform === 'darwin' ? { channel: 'chrome' } : {}), diff --git a/src/assets/cook/dependency-graph.ts b/src/assets/cook/dependency-graph.ts index cf7815a..bd35806 100644 --- a/src/assets/cook/dependency-graph.ts +++ b/src/assets/cook/dependency-graph.ts @@ -99,36 +99,33 @@ export class CookDependencyGraph { const onStack = new Set(); const path: CookNodeId[] = []; - const visit = (current: CookNodeId): CookNodeId[] | undefined => { - if (current === node) { - return [...path, current, path[0]!]; + // Explicit enter/exit frames preserve recursive DFS order without tying asset depth + // to the host JavaScript call-stack limit. Storage is bounded by the traversed edges. + const stack: { current: CookNodeId; exit: boolean }[] = [...candidateDependencies] + .sort((a, b) => a.localeCompare(b)) + .reverse() + .map((current) => ({ current, exit: false })); + while (stack.length > 0) { + const { current, exit } = stack.pop()!; + if (exit) { + path.pop(); + onStack.delete(current); + visited.add(current); + continue; } - if (visited.has(current)) return undefined; + if (current === node) return [...path, current, path[0]!]; + if (visited.has(current)) continue; if (onStack.has(current)) { const startIndex = path.indexOf(current); return startIndex >= 0 ? [...path.slice(startIndex), current] : undefined; } onStack.add(current); path.push(current); - - const nextDependencies = - current === node - ? candidateDependencies - : (this.#dependencies.get(current) ?? EMPTY_NODE_SET); - for (const dependency of [...nextDependencies].sort((a, b) => a.localeCompare(b))) { - const cycle = visit(dependency); - if (cycle) return cycle; - } - - path.pop(); - onStack.delete(current); - visited.add(current); - return undefined; - }; - - for (const dependency of [...candidateDependencies].sort((a, b) => a.localeCompare(b))) { - const cycle = visit(dependency); - if (cycle) return cycle; + stack.push({ current, exit: true }); + const dependencies = [...(this.#dependencies.get(current) ?? EMPTY_NODE_SET)] + .sort((a, b) => a.localeCompare(b)) + .reverse(); + for (const dependency of dependencies) stack.push({ current: dependency, exit: false }); } return undefined; } diff --git a/src/rhi/webgl2/browser/capability-query.ts b/src/rhi/webgl2/browser/capability-query.ts index 4e79708..6164675 100644 --- a/src/rhi/webgl2/browser/capability-query.ts +++ b/src/rhi/webgl2/browser/capability-query.ts @@ -40,10 +40,25 @@ export function queryWebGL2Formats( formats.set('r8unorm', format(true, true, true, true, sampleCounts)); formats.set('rg8unorm', format(true, true, true, true, sampleCounts)); formats.set('rgba8unorm', format(true, true, true, true, sampleCounts)); - formats.set('rgba8unorm-srgb', format(true, true, true, true, sampleCounts)); + // Encoded uploads preserve bytes, but source reads/copies would apply color conversion. + formats.set( + 'rgba8unorm-srgb', + Object.freeze({ + ...format(true, true, true, true, sampleCounts), + copySrc: false + }) + ); // RGBA32UI color rendering and integer sampling are core WebGL2 capabilities. formats.set('rgba32uint', format(true, false, true, false, [1])); - formats.set('depth24plus', format(false, false, true, false, sampleCounts)); + // Depth attachments are renderable; the current native copy port supports color only. + formats.set( + 'depth24plus', + Object.freeze({ + ...format(false, false, true, false, sampleCounts), + copySrc: false, + copyDst: false + }) + ); if (extensions.has(COLOR_BUFFER_FLOAT_EXTENSION)) { // Half-float linear filtering is core in WebGL2; OES_texture_float_linear // controls 32-bit floating-point filtering, not RGBA16F. diff --git a/test/assets/cook-dependency-depth.test.ts b/test/assets/cook-dependency-depth.test.ts new file mode 100644 index 0000000..685eddb --- /dev/null +++ b/test/assets/cook-dependency-depth.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, test } from 'vitest'; +import { CookDependencyGraph } from '../../src/assets/cook'; + +const NODE_COUNT = 10_000; +const nodes = Array.from({ length: NODE_COUNT }, (_, index) => `asset://depth/${index}`); + +function createChain(): CookDependencyGraph { + const graph = new CookDependencyGraph(); + // Forward references keep construction independent of traversal depth. + for (let index = 0; index < NODE_COUNT - 1; index++) { + graph.replaceDependencies(nodes[index]!, [nodes[index + 1]!]); + } + return graph; +} + +describe('CookDependencyGraph deep dependency validation', () => { + test('retains insertion order when distinct node IDs compare equally', () => { + const graph = new CookDependencyGraph(); + const first = 'asset://é'; + const second = 'asset://e\u0301'; + expect(first.localeCompare(second)).toBe(0); + graph.replaceDependencies(first, ['asset://target']); + graph.replaceDependencies(second, ['asset://target']); + expect(() => graph.replaceDependencies('asset://target', [first, second])).toThrow( + `Cook dependency cycle: ${first} -> asset://target -> ${first}` + ); + }); + + test('keeps sorted depth-first cycle selection when candidates are supplied in reverse order', () => { + const graph = new CookDependencyGraph(); + graph.replaceDependencies('asset://z', ['asset://target']); + graph.replaceDependencies('asset://a', ['asset://target']); + expect(() => graph.replaceDependencies('asset://target', ['asset://z', 'asset://a'])).toThrow( + 'Cook dependency cycle: asset://a -> asset://target -> asset://a' + ); + }); + + test('accepts a 10,000-node dependency closure without using the call stack', () => { + const graph = createChain(); + expect(() => graph.replaceDependencies('asset://root', [nodes[0]!])).not.toThrow(); + expect(graph.dependenciesOf('asset://root')).toEqual([nodes[0]]); + expect(graph.invalidate(nodes.at(-1)!)).toEqual([...nodes].reverse().concat('asset://root')); + }); + + test('rejects a 10,000-node cycle with the same ordered diagnostic and last-good edges', () => { + const graph = createChain(); + const terminal = nodes.at(-1)!; + const expectedCycle = [...nodes, nodes[0]!]; + expect(() => graph.replaceDependencies(terminal, [nodes[0]!])).toThrow( + `Cook dependency cycle: ${expectedCycle.join(' -> ')}` + ); + expect(graph.dependenciesOf(terminal)).toEqual([]); + expect(graph.invalidate(terminal)).toEqual([...nodes].reverse()); + }); +}); diff --git a/test/benchmark/p1-rendering-acceptance.test.ts b/test/benchmark/p1-rendering-acceptance.test.ts new file mode 100644 index 0000000..1673d47 --- /dev/null +++ b/test/benchmark/p1-rendering-acceptance.test.ts @@ -0,0 +1,37 @@ +import { expect, test } from 'vitest'; +import { observeMsaa } from '../../benchmark/p1-rendering-acceptance/msaa'; +import { observeResidency } from '../../benchmark/p1-rendering-acceptance/residency'; + +test('records real opaque 1x/4x graphs and Null execution with exact resolve counts', async () => { + expect((await observeMsaa(2, 1)).counters).toEqual({ + views: 2, + sampleCount: 1, + resolves: 0, + textures: 4, + renderPasses: 2, + submissions: 1 + }); + expect((await observeMsaa(2, 4)).counters).toEqual({ + views: 2, + sampleCount: 4, + resolves: 2, + textures: 6, + renderPasses: 2, + submissions: 1 + }); +}); + +test('planner and owner scan agree while real leases and submissions protect residency', async () => { + const planner = await observeResidency(16, 'planner'); + const reference = await observeResidency(16, 'owner-scan'); + expect(planner).toEqual(reference); + expect(planner.counters).toMatchObject({ + protectedCpu: 8, + protectedGpuLeases: 4, + protectedGpuSubmissions: 4, + unlistedGpuBytes: 64, + destroyedBuffers: 17, + finalCpuBytes: 0, + finalGpuBytes: 0 + }); +}); diff --git a/test/examples/react-scene-host.test.ts b/test/examples/react-scene-host.test.ts index a69b7e1..3bb0488 100644 --- a/test/examples/react-scene-host.test.ts +++ b/test/examples/react-scene-host.test.ts @@ -282,4 +282,36 @@ describe('AetherSceneHost', () => { unsubscribe(); await host.unmount(); }); + + test('does not recreate a non-recoverable scene even when recovery readiness resolves', async () => { + let resolveLoss!: (value: { readonly recreationAllowed: boolean }) => void; + const lost = new Promise<{ readonly recreationAllowed: boolean }>((resolve) => { + resolveLoss = resolve; + }); + const scene = { + lost, + recoveryReady: Promise.resolve(), + destroy: vi.fn(async () => {}) + }; + const mount = vi.fn(async () => scene); + const host = new AetherSceneHost(mount); + const publish = vi.fn(); + host.subscribe(publish); + const canvas = {} as HTMLCanvasElement; + await host.mount(canvas); + + resolveLoss({ recreationAllowed: false }); + await lost; + // A task boundary drains the asynchronous recovery continuation and queued mount chain. + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(mount).toHaveBeenCalledTimes(1); + expect(publish).toHaveBeenCalledTimes(1); + expect(publish).toHaveBeenCalledWith(scene); + expect(host.activeScene).toBe(scene); + expect(scene.destroy).not.toHaveBeenCalled(); + + await host.unmount(); + expect(scene.destroy).toHaveBeenCalledTimes(1); + expect(host.activeScene).toBeNull(); + }); }); diff --git a/test/platform/platform-browser-graphics.test.ts b/test/platform/platform-browser-graphics.test.ts index 9d4b5b3..6ab18c5 100644 --- a/test/platform/platform-browser-graphics.test.ts +++ b/test/platform/platform-browser-graphics.test.ts @@ -87,6 +87,38 @@ describe('browser graphics bootstrap', () => { expect(fixture.context.unconfigures).toBe(1); }); + test('preserves native destroyed loss as non-recoverable until explicit session cleanup', async () => { + const fixture = createBrowserFixture(); + const session = await createBrowserGraphics({ + canvas: fixture.canvas, + environment: fixture.environment, + device: { requiredFeatures: [], optionalFeatures: [] }, + surface: { width: 640, height: 360 } + }); + const events: unknown[] = []; + session.subscribe((event) => events.push(event)); + + fixture.resolveLost({ reason: 'destroyed', message: 'Native device destroyed.' }); + const loss = await session.lost; + expect(loss).toEqual({ + backend: 'webgpu', + stage: 'device', + reason: 'destroyed', + generation: session.device.generation, + recreationAllowed: false + }); + expect(Object.isFrozen(loss)).toBe(true); + expect(events).toEqual([{ kind: 'lost', loss }]); + expect(session.device.state).toBe('lost'); + expect(session.surface.acquire()).toEqual({ status: 'device-lost' }); + + await session.destroy(); + await session.destroy(); + expect(fixture.context.unconfigures).toBe(1); + expect(events).toHaveLength(1); + await expect(session.lost).resolves.toBe(loss); + }); + test('rejects invalid size before probing and does not fallback after canvas binding', async () => { const fixture = createBrowserFixture(); await expect( diff --git a/test/rhi/contracts/rhi-copy-format-corpus.test.ts b/test/rhi/contracts/rhi-copy-format-corpus.test.ts new file mode 100644 index 0000000..cb7a095 --- /dev/null +++ b/test/rhi/contracts/rhi-copy-format-corpus.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, test } from 'vitest'; + +import { NullDevice } from '../../../src/rhi'; + +// Independent contract fixtures: do not derive expected byte counts from production layouts. +const FORMAT_CASES = [ + ['r8unorm', 1, 1], + ['r8snorm', 1, 1], + ['r8uint', 1, 1], + ['r8sint', 1, 1], + ['rg8unorm', 1, 2], + ['rg8snorm', 1, 2], + ['rgba8unorm', 1, 4], + ['rgba8unorm-srgb', 1, 4], + ['bgra8unorm', 1, 4], + ['bgra8unorm-srgb', 1, 4], + ['rgba16float', 1, 8], + ['rgba32float', 1, 16], + ['rgba32uint', 1, 16], + ['bc1-rgba-unorm', 4, 8], + ['bc1-rgba-unorm-srgb', 4, 8], + ['bc3-rgba-unorm', 4, 16], + ['bc3-rgba-unorm-srgb', 4, 16] +] as const; + +const DIRECTIONS = ['buffer-to-texture', 'texture-to-buffer'] as const; + +describe('registered portable copy format corpus', () => { + describe.each(FORMAT_CASES)('%s', (format, blockDimension, blockBytes) => { + test.each(DIRECTIONS)( + '%s includes padded images but only the final row payload', + (direction) => { + const device = new NullDevice(); + const texture = device.createTexture({ + size: [2 * blockDimension, 2 * blockDimension, 2], + format, + usage: 3 + }); + // Two block rows per layer, three padded rows between layers, and a nonzero offset. + const requiredBytes = 4 + 3 * 256 + 256 + 2 * blockBytes; + const bufferUsage = direction === 'buffer-to-texture' ? 4 : 8; + const exact = device.createBuffer({ + size: Math.ceil(requiredBytes / 4) * 4, + usage: bufferUsage + }); + const short = device.createBuffer({ + size: Math.floor((requiredBytes - 1) / 4) * 4, + usage: bufferUsage + }); + const encoder = device.createCommandEncoder(); + const extent = [2 * blockDimension, 2 * blockDimension, 2] as const; + const layout = { offset: 4, bytesPerRow: 256, rowsPerImage: 3 }; + if (direction === 'buffer-to-texture') { + encoder.copyBufferToTexture({ buffer: exact, ...layout }, { texture }, extent); + expect(() => + encoder.copyBufferToTexture({ buffer: short, ...layout }, { texture }, extent) + ).toThrow(`requires buffer range 4..${requiredBytes} outside buffer size ${short.size}`); + } else { + encoder.copyTextureToBuffer({ texture }, { buffer: exact, ...layout }, extent); + expect(() => + encoder.copyTextureToBuffer({ texture }, { buffer: short, ...layout }, extent) + ).toThrow(`requires buffer range 4..${requiredBytes} outside buffer size ${short.size}`); + } + const commands = encoder.finish(); + expect(commands.getCommandStream()).toHaveLength(1); + expect(commands.getStats().copy).toMatchObject( + direction === 'buffer-to-texture' + ? { copyBufferToTexture: 1 } + : { copyTextureToBuffer: 1 } + ); + } + ); + }); + + test('rejects unregistered byte layouts without recording a command', () => { + const device = new NullDevice(); + const buffer = device.createBuffer({ size: 256, usage: 12 }); + const texture = device.createTexture({ size: [1, 1], format: 'depth32float', usage: 3 }); + const encoder = device.createCommandEncoder(); + expect(() => + encoder.copyBufferToTexture({ buffer, bytesPerRow: 256 }, { texture }, [1, 1]) + ).toThrow('has no portable copy block layout'); + expect(() => + encoder.copyTextureToBuffer({ texture }, { buffer, bytesPerRow: 256 }, [1, 1]) + ).toThrow('has no portable copy block layout'); + expect(encoder.finish().getCommandStream()).toHaveLength(0); + }); +}); diff --git a/test/rhi/webgl2/webgl2-copy-capabilities.test.ts b/test/rhi/webgl2/webgl2-copy-capabilities.test.ts new file mode 100644 index 0000000..20b7e22 --- /dev/null +++ b/test/rhi/webgl2/webgl2-copy-capabilities.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, test } from 'vitest'; + +import { queryWebGL2Formats } from '../../../src/rhi/webgl2/browser/capability-query'; +import type { BrowserWebGL2Context } from '../../../src/rhi/webgl2/browser/types'; + +const context = { + MAX_SAMPLES: 0x8d57, + getParameter: () => 4, + getSupportedExtensions: () => [], + getShaderPrecisionFormat: () => null, + pixelStorei() {}, + disable() {}, + colorMask() {}, + depthMask() {}, + stencilMask() {}, + bindBuffer() {}, + bindFramebuffer() {}, + bindRenderbuffer() {}, + bindVertexArray() {}, + activeTexture() {} +} satisfies BrowserWebGL2Context & { readonly MAX_SAMPLES: number }; + +describe('WebGL2 copy capability publication', () => { + test('rejects sRGB source copies while retaining encoded upload destination support', () => { + const formats = queryWebGL2Formats(context, new Set()); + expect(formats.get('rgba8unorm-srgb')).toMatchObject({ + sample: true, + render: true, + copySrc: false, + copyDst: true + }); + }); + + test('does not advertise unsupported depth copies as a consequence of render support', () => { + const formats = queryWebGL2Formats(context, new Set()); + expect(formats.get('depth24plus')).toMatchObject({ + render: true, + copySrc: false, + copyDst: false + }); + expect(formats.get('rgba8unorm')).toMatchObject({ copySrc: true, copyDst: true }); + }); +}); diff --git a/test/rhi/webgpu/webgpu-interop.test.ts b/test/rhi/webgpu/webgpu-interop.test.ts index 3ac1f2f..95da132 100644 --- a/test/rhi/webgpu/webgpu-interop.test.ts +++ b/test/rhi/webgpu/webgpu-interop.test.ts @@ -247,6 +247,32 @@ describe('WebGPU controlled native interop', () => { ); }); + test('checks every native texture identity fact before claiming ownership', async () => { + const { interop } = await createDevice(); + const scope = interop.createScope('texture-facts'); + const native = new NativeTexture(8, 4, 1, 'rgba8unorm', 16); + const descriptor = { size: [8, 4] as const, format: 'rgba8unorm', usage: 16 }; + expect(() => scope.importBorrowed('texture', native, { ...descriptor, size: [4, 4] })).toThrow( + 'does not match descriptor extent' + ); + expect(() => + scope.importBorrowed('texture', native, { ...descriptor, format: 'rgba16float' }) + ).toThrow('does not match descriptor format'); + expect(() => scope.importBorrowed('texture', native, { ...descriptor, usage: 4 })).toThrow( + 'does not match descriptor usage' + ); + expect(() => + scope.importBorrowed('texture', native, { ...descriptor, dimension: '3d' }) + ).toThrow('does not match descriptor dimension'); + expect(() => + scope.importBorrowed('texture', native, { ...descriptor, mipLevelCount: 2 }) + ).toThrow('does not match descriptor mip level count'); + // Failed validation must not reserve the native identity or destroy caller-owned storage. + expect(() => scope.importBorrowed('texture', native, descriptor)).not.toThrow(); + scope.dispose(); + expect(native.destroyed).toBe(0); + }); + test('binds imported resources to their scope and cleans them up on dispose', async () => { const { device, interop } = await createDevice(); const first = interop.createScope('first-owner'); diff --git a/test/rhi/webgpu/webgpu-submission.test.ts b/test/rhi/webgpu/webgpu-submission.test.ts index 3e3d7c0..83337c1 100644 --- a/test/rhi/webgpu/webgpu-submission.test.ts +++ b/test/rhi/webgpu/webgpu-submission.test.ts @@ -248,6 +248,42 @@ describe('WebGPU submission epochs', () => { expect(device.queue.metrics()).toMatchObject({ completed: 0, deviceLost: 2 }); }); + test('native destroyed loss invalidates old handles and retires disposed submission resources', async () => { + const { device, native } = await createDevice(); + const { source, destination, commands } = recordCopy(device); + const submission = device.queue.submit([commands]); + const staleEncoder = device.createCommandEncoder(); + source.dispose(); + expect(native.buffers[0]?.destroyed).toBe(0); + + native.lose({ reason: 'destroyed', message: 'Native device was explicitly destroyed.' }); + await expect(device.lost).resolves.toMatchObject({ + reason: 'destroyed', + generation: device.generation + }); + expect(device.state).toBe('lost'); + expect(source.state).toBe('device-lost'); + expect(destination.state).toBe('device-lost'); + await expect(submission.done).resolves.toEqual({ status: 'device-lost' }); + expect(device.queue.metrics()).toMatchObject({ pending: 0, deviceLost: 1, leasedResources: 0 }); + expect(native.buffers[0]?.destroyed).toBe(1); + expect(() => device.createBuffer({ size: 16, usage: 1 })).toThrow('WebGPUDevice is lost.'); + expect(() => device.queue.submit([commands])).toThrow('lost device'); + expect(() => staleEncoder.copyBufferToBuffer(source, 0, destination, 0, 16)).toThrow( + 'lost device' + ); + + native.queue.complete(0); + await Promise.resolve(); + expect(device.queue.metrics()).toMatchObject({ completed: 0, deviceLost: 1 }); + expect(native.buffers[0]?.destroyed).toBe(1); + destination.dispose(); + commands.dispose(); + device.destroy(); + device.destroy(); + expect(native.buffers.map((buffer) => buffer.destroyed)).toEqual([1, 1]); + }); + test('defers native buffer and texture destruction until their submission is terminal', async () => { const { device, native } = await createDevice(); const { source, destination, commands } = recordCopy(device);