diff --git a/README.md b/README.md index 5760948..8e1e9ee 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # WebGPU Groundtruth -A browser map that renders global airports and sea ports over a dark vector basemap and uses WebGPU compute shaders for an airport density heatmap and a live GPU throughput readout. A stress-test slider adds up to 5,000,000 random points so you can watch frame time under load. +A browser map that renders global airports and sea ports over a dark vector basemap and uses WebGPU compute shaders for an airport density heatmap and an on-demand GPU throughput benchmark. A stress-test slider adds up to 5,000,000 random points so you can watch frame time under load. Built with React 19, Vite, MapLibre GL (through `react-map-gl`), deck.gl (`@deck.gl/mapbox` overlay with `ScatterplotLayer` and `BitmapLayer`), and zustand for UI state. @@ -11,7 +11,7 @@ Built with React 19, Vite, MapLibre GL (through `react-map-gl`), deck.gl (`@deck - **Sea ports layer:** the bundled ports GeoJSON, drawn as green points. Click a point to see its properties. - **Heatmap layer (WebGPU only):** a two-pass compute shader bins airport positions into a 1024 x 512 grid and colorizes it into a bitmap overlay. It runs once, after the airports load. The layer toggle appears only after that compute succeeds, so it is hidden while airports load, when WebGPU is unavailable, and when the airports fetch or the compute fails. - **Stress test:** a slider from 0 to 5,000,000 points in steps of 100,000. Points are generated on the main thread 150 ms after the slider stops moving, then drawn as a deck.gl binary attribute layer. -- **GPU info panel:** adapter name, render tier (`WebGPU`, `WebGL Fallback`, or `Detecting...`), active point count, frame time with a 60-frame sparkline, compute throughput (a 64 MB storage buffer read and written once per second, reported in GB/s), and heatmap compute time. At 1024px wide or less it shows only the render tier, active point count, and frame time. On small screens (see below) it is hidden while a feature popup is open. +- **GPU info panel:** adapter name, render tier (`WebGPU`, `WebGL Fallback`, or `Detecting...`), active point count, frame time with a 60-frame sparkline, an on-demand compute benchmark (press `RUN` next to COMPUTE: 5 sequential dispatches over a 64 MB storage buffer, reported as the median in GB/s, labelled `est.` because it is CPU timed, or `Too fast` when the timer is too coarse to measure it; out-of-memory, validation errors, and device loss show `Failed`; the buffer and device are freed when the run ends, and the run stops if the tab is hidden), and heatmap compute time. At 1024px wide or less it shows only the render tier, active point count, and frame time. On small screens (see below) it is hidden while a feature popup is open. - **Small screens** (640px wide or less, or up to 1024px wide and 500px tall or less): the layer panel starts collapsed behind a "Sensor layers" button, the header drops the coordinates and status, and the feature popup opens as a bottom sheet. ## Requirements @@ -75,5 +75,5 @@ public/data/ports.geojson bundled ports data - The basemap needs CARTO to be reachable; offline, only the overlays draw. - The heatmap runs once per page load from the first non-empty airports list and does not update afterwards. - Stress points are generated on the main thread. Large counts (millions of points) briefly block the UI once the slider settles. -- The COMPUTE throughput benchmark keeps a 64 MB GPU buffer allocated and dispatches every second for as long as the map is mounted. +- The COMPUTE benchmark is CPU timed (submit to `onSubmittedWorkDone`), so it includes driver and callback latency and reads lower than the real memory bandwidth. The `RUN` control is hidden at 1024px wide or less along with the rest of COMPUTE. - Unit tests run in jsdom, which has no WebGL or WebGPU. GPU code paths are covered by mocks and pure helpers only; check rendering in a real browser. diff --git a/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md b/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md new file mode 100644 index 0000000..b3a8272 --- /dev/null +++ b/docs/plans/2026-11-07-issue-11-on-demand-gpu-benchmark.md @@ -0,0 +1,72 @@ +# Plan: GPU compute benchmark runs a 64 MB dispatch every second indefinitely (issue #11) + +Risk tier: High. Not a forced-High area, but it raises three tiers: stateful UI with a new interactive control (not fully provable in jsdom), it alters existing behavior (continuous readout becomes on-demand), and it is async GPU lifecycle code (run, cancel, unmount, visibility). About six files change. + +Domain skills: +- superpowers:test-driven-development: invoke. +- vercel-react-best-practices: invoke (hook state, effect cleanup, stable callbacks, no work in render). +- chrome-devtools-mcp:a11y-debugging: invoke for the live drive (button name, focus ring, target size, live region). If the chrome-devtools MCP fails (locked profile), use Playwright via `npx playwright` with the cached Chromium instead. +- frontend-design: not applicable because the control must follow the existing HUD styling of the GPU panel; no new visual direction. +- dataviz, django, fastapi, expo, payments, email: not applicable because none of that is touched. + +## Acceptance criteria + +1. No benchmark GPU work on mount: `useGPUCompute` calls neither `navigator.gpu.requestAdapter`, `requestDevice`, `createBuffer`, nor `queue.submit`. Nothing is allocated for the benchmark until the user activates the "Run benchmark" control. (The map's existing `useGPUCapabilities` adapter probe and the one-shot `useGPUHeatmap` run are unchanged and out of scope.) +2. The GPU info panel's COMPUTE item contains a native `` that ignores clicks while running. +- `src/components/GPUInfoPanel.test.jsx`: add tests (button present/absent, name, click and keyboard activation via user-event, aria-disabled while running and no call, live region). Existing tests unchanged; they render without the new prop, so the prop must be optional. +- `src/components/MapView.jsx`: pass `benchmark={{ supported, running, onRun: run }}` from `useGPUCompute()`; memoize it. +- `src/index.css`: `.gpu-bench-btn` (pointer-events: auto; min-width and min-height 24px; background none; 1px `--border-active` border; `color: var(--accent)`; font inherit; cursor pointer), `.gpu-bench-btn:hover`, `.gpu-bench-btn:focus-visible` (2px solid `--accent`, offset 2px), `.gpu-bench-btn[aria-disabled='true']` (`color: var(--text-dim)`, cursor default). Only add `color:` rules you also add to `TEXT_PAIRS`. +- `src/styles.test.js`: add the new `color:` selectors to `TEXT_PAIRS` (bg `overMap`) and a 24x24 target-size assertion for `.gpu-bench-btn`. +- `README.md`: GPU info panel bullet and the Known limitations line about the benchmark. + +## Order of work + +1. Pure helpers (`median`, `formatThroughput`) with tests. +2. Hook tests red, then the hook: no work on mount; sequential dispatches; destroy after; hidden before and mid-run; overlap guard; unmount mid-run; no adapter; failure path. +3. Panel tests red, then the panel and MapView wiring. +4. CSS and the styles test table. +5. README. +6. Gate, then the live drive. + +## Risks + +- A stuck `running` state (a promise that never settles) would leave the button permanently disabled. Mitigation: never destroy the device on hide while awaiting; `finally` always clears. +- Layout: the 24px button grows the wide panel's height. It is bottom-right at `bottom: 40px`; check it still clears the layer panel and attribution at 1440x900. +- `.gpu-info-panel` has `pointer-events: none`; forgetting `pointer-events: auto` on the button makes it unclickable with a mouse while still passing keyboard tests. +- Existing `GPUInfoPanel` tests render without `benchmark`; the prop must default safely. + +## Proof + +- AC1, 3, 5, 6, 7, 8, 10: `src/hooks/useGPUCompute.test.js` with mocked `navigator.gpu`: no calls on mount; 5 submits, each only after the previous `onSubmittedWorkDone` resolves (submit count checked while a deferred is pending); `buffer.destroy` and `device.destroy` called after completion, after stop, and after a throw; hidden before run means `requestAdapter` not called; hidden mid-run stops at the next dispatch and shows `Stopped`; `src/hooks/useGPUCompute.hiddenLast.test.js`: hidden while the 5th dispatch is pending still shows the result; second `run()` during a run does not request a second adapter; unmount mid-run destroys and further deferred resolution submits nothing (React 19 does not warn on a state update after unmount, so the mounted-ref guard is reviewed, not asserted); `src/hooks/useGPUCompute.setupStop.test.js`: hidden during pending `requestAdapter` or `requestDevice`, and unmount during pending `requestDevice`, never call `createBuffer` and destroy a late device, and `run()` after unmount requests no adapter; null adapter gives `supported: false` and `--`. +- AC10 async errors: `src/hooks/useGPUCompute.asyncErrors.test.js`: both scopes pushed and popped; `popErrorScope` resolving an error shows `Failed` and destroys; `device.lost` resolving with reason `unknown` while `onSubmittedWorkDone` never settles shows `Failed`, `running: false`, destroyed. `src/hooks/useGPUCompute.lostWithWork.test.js`: `device.lost` (reason `unknown`) and the 5th work-done resolving in the same tick shows `Failed`, not a GB/s value, with resources destroyed; after the loop and after the error scope pops, any recorded loss other than `destroyed` fails the run. `src/hooks/useGPUCompute.lostAfterLoop.test.js`: `device.lost` (reason `unknown`) resolving while the scope pops are pending, after all 5 work-dones, shows `Failed`; a hide during dispatch 2 followed by `device.lost` (reason `unknown`) shows `Failed`, not `Stopped`. +- AC4: helper tests (`median`, `formatThroughput`) and a full-run test asserting the `~X.X GB/s est.` value; `src/hooks/useGPUCompute.tooFast.test.js`: `formatThroughput` of 0, negative, NaN, or Infinity is `Too fast`, and a run with a frozen `performance.now` shows `Too fast`. +- AC2, 7, 9, 10: `src/components/GPUInfoPanel.test.jsx`; the tier gate in AC10 (found in the live drive) in `src/components/GPUInfoPanel.benchmarkTier.test.jsx`. +- AC11: `src/styles.test.js` table and target size; existing suite unchanged. +- Live drive (build + `npm run preview`, Playwright or chrome-devtools): headless Chromium has no WebGPU, so (a) confirm the no-WebGPU state: no button, COMPUTE `--`; (b) inject a mock `navigator.gpu` with an init script and drive a run by Tab plus Enter and by mouse click: `Running...`, then `~X GB/s est.`, aria-disabled while running, focus ring visible, button box at least 24x24; (c) edge paths with the mock: hide the tab mid-run (override `visibilityState` and dispatch `visibilitychange`) shows `Stopped`; double activation runs once; (d) measure layout at 375x812, 768x1024, 1440x900 per AC11, including the button's box at 1440 and its absence at 768 and 375. If the user's real Chrome (claude-in-chrome) has WebGPU, try a real run and record the number. + +## Frozen test changes + +- `src/hooks/useGPUCompute.tooFast.test.js`: the unused `setVisibility()` and `hide()` helpers were deleted. Approved by the orchestrator under the user's delegation. Reason: dead code copied from the shared mock helper block broke `npm run lint` (`no-unused-vars`); no assertion changed. diff --git a/src/components/GPUInfoPanel.benchmarkTier.test.jsx b/src/components/GPUInfoPanel.benchmarkTier.test.jsx new file mode 100644 index 0000000..0fb7111 --- /dev/null +++ b/src/components/GPUInfoPanel.benchmarkTier.test.jsx @@ -0,0 +1,28 @@ +import { describe, it, expect, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import { GPUInfoPanel } from './GPUInfoPanel.jsx' + +// Browsers can expose navigator.gpu while requestAdapter() returns null +// (headless Chromium does). useGPUCapabilities reports that as 'no-webgpu', +// and the RUN control must stay hidden then (issue #11, AC10). +const base = { + adapterInfo: {}, + activePointCount: 0, + frameTime: 16, + frameHistory: [], + gpuThroughput: '--', +} +const benchmark = { supported: true, running: false, onRun: vi.fn() } + +describe('GPUInfoPanel RUN control and the detected tier', () => { + it.each(['no-webgpu', 'unknown'])('hides the RUN button when the tier is %s', (tier) => { + render() + expect(screen.queryByRole('button', { name: 'Run compute benchmark' })).not.toBeInTheDocument() + expect(screen.getByText('COMPUTE').closest('.gpu-info-item')).toHaveTextContent('--') + }) + + it('shows the RUN button when the tier is webgpu', () => { + render() + expect(screen.getByRole('button', { name: 'Run compute benchmark' })).toBeInTheDocument() + }) +}) diff --git a/src/components/GPUInfoPanel.jsx b/src/components/GPUInfoPanel.jsx index 1da9b43..733b33d 100644 --- a/src/components/GPUInfoPanel.jsx +++ b/src/components/GPUInfoPanel.jsx @@ -30,7 +30,23 @@ function Sparkline({ history }) { ) } -export function GPUInfoPanel({ capabilities }) { +const NO_BENCHMARK = { supported: false, running: false, onRun: undefined } + +function BenchmarkButton({ running, onRun }) { + return ( + + ) +} + +export function GPUInfoPanel({ capabilities, benchmark = NO_BENCHMARK }) { const { tier, adapterInfo, activePointCount, frameTime, frameHistory, gpuThroughput, heatmapComputeMs } = capabilities const deviceLabel = @@ -67,7 +83,11 @@ export function GPUInfoPanel({ capabilities }) { | COMPUTE - {gpuThroughput} + {gpuThroughput} + {/* navigator.gpu can exist with no adapter, so also require the detected tier. */} + {benchmark.supported && isWebGPU ? ( + + ) : null} | diff --git a/src/components/GPUInfoPanel.test.jsx b/src/components/GPUInfoPanel.test.jsx index e057758..0d69668 100644 --- a/src/components/GPUInfoPanel.test.jsx +++ b/src/components/GPUInfoPanel.test.jsx @@ -1,6 +1,7 @@ -import { describe, it, expect } from 'vitest' +import { describe, it, expect, vi } from 'vitest' import { render, screen } from '@testing-library/react' import { GPUInfoPanel } from './GPUInfoPanel.jsx' +import userEvent from '@testing-library/user-event' const base = { tier: 'webgpu', @@ -90,3 +91,73 @@ describe('GPUInfoPanel secondary stats', () => { expect(visible).toEqual(['RENDER', '|', 'PTS', '|', 'FRAME']) }) }) + +describe('GPUInfoPanel benchmark control', () => { + const bench = (over = {}) => ({ supported: true, running: false, onRun: vi.fn(), ...over }) + + it('has no RUN button when the benchmark prop is omitted', () => { + render() + expect(screen.queryByRole('button', { name: 'Run compute benchmark' })).not.toBeInTheDocument() + }) + + it('has no RUN button when the benchmark is unsupported', () => { + render() + expect(screen.queryByRole('button', { name: 'Run compute benchmark' })).not.toBeInTheDocument() + expect(screen.getByText('COMPUTE').closest('.gpu-info-item')).toHaveTextContent('--') + }) + + it('renders a native RUN button inside the COMPUTE item when supported', () => { + render() + const button = screen.getByRole('button', { name: 'Run compute benchmark' }) + expect(button.tagName).toBe('BUTTON') + expect(button).toHaveAttribute('type', 'button') + expect(button).toHaveTextContent('RUN') + expect(button).toHaveClass('gpu-bench-btn') + expect(button.closest('.gpu-info-item')).toBe(screen.getByText('COMPUTE').closest('.gpu-info-item')) + }) + + it('runs on click', async () => { + const b = bench() + render() + await userEvent.click(screen.getByRole('button', { name: 'Run compute benchmark' })) + expect(b.onRun).toHaveBeenCalledTimes(1) + }) + + it('is reachable with Tab and runs on Enter and on Space', async () => { + const user = userEvent.setup() + const b = bench() + render() + await user.tab() + expect(screen.getByRole('button', { name: 'Run compute benchmark' })).toHaveFocus() + await user.keyboard('{Enter}') + expect(b.onRun).toHaveBeenCalledTimes(1) + await user.keyboard(' ') + expect(b.onRun).toHaveBeenCalledTimes(2) + }) + + it('is aria-disabled, still focusable, and ignores activation while running', async () => { + const user = userEvent.setup() + const b = bench({ running: true }) + render() + const button = screen.getByRole('button', { name: 'Run compute benchmark' }) + expect(button).toHaveAttribute('aria-disabled', 'true') + expect(button).not.toBeDisabled() + await user.tab() + expect(button).toHaveFocus() + await user.keyboard('{Enter}') + await user.click(button) + expect(b.onRun).not.toHaveBeenCalled() + }) + + it('has no aria-disabled when idle', () => { + render() + expect(screen.getByRole('button', { name: 'Run compute benchmark' })).not.toHaveAttribute('aria-disabled') + }) + + it('announces the COMPUTE value through a polite live region', () => { + render() + const value = screen.getByText('~1.3 GB/s est.') + expect(value).toHaveAttribute('aria-live', 'polite') + expect(value).not.toContainElement(screen.getByRole('button', { name: 'Run compute benchmark' })) + }) +}) diff --git a/src/components/MapView.jsx b/src/components/MapView.jsx index b653d80..97c9581 100644 --- a/src/components/MapView.jsx +++ b/src/components/MapView.jsx @@ -46,7 +46,8 @@ export function MapView({ layerData, heatmapComputeMs }) { const { viewport, setViewport, layerVisibility, setSelectedFeature } = useMapStore() const gpuBase = useGPUCapabilities() const { frameTime, frameHistory } = useFrameTime() - const { throughput: gpuThroughput } = useGPUCompute() + const { throughput: gpuThroughput, supported: benchSupported, running: benchRunning, run: runBenchmark } = + useGPUCompute() const activePointCount = (layerVisibility.airports ? (layerData.airports?.length ?? 0) : 0) + @@ -58,6 +59,11 @@ export function MapView({ layerData, heatmapComputeMs }) { [gpuBase, activePointCount, frameTime, frameHistory, gpuThroughput, heatmapComputeMs] ) + const benchmark = useMemo( + () => ({ supported: benchSupported, running: benchRunning, onRun: runBenchmark }), + [benchSupported, benchRunning, runBenchmark] + ) + const onFeatureClick = useCallback( (feature) => setSelectedFeature(feature), [setSelectedFeature] @@ -79,7 +85,7 @@ export function MapView({ layerData, heatmapComputeMs }) {
- +
) } \ No newline at end of file diff --git a/src/hooks/useGPUCompute.asyncErrors.test.js b/src/hooks/useGPUCompute.asyncErrors.test.js new file mode 100644 index 0000000..1a3d941 --- /dev/null +++ b/src/hooks/useGPUCompute.asyncErrors.test.js @@ -0,0 +1,113 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { renderHook, act, waitFor } from '@testing-library/react' +import { useGPUCompute } from './useGPUCompute.js' + +// Issue #11: WebGPU reports out-of-memory and validation errors asynchronously +// through error scopes, and device loss through device.lost. Either must show +// Failed, not a bogus GB/s. + +function deferred() { + let resolve + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +// Self-contained WebGPU mock. Each async step can be held open with a deferred. +function installGPU({ holdAdapter = false, holdDevice = false, holdWork = false, popError = null, lost = null } = {}) { + const adapterGate = deferred() + const deviceGate = deferred() + const pending = [] + const buffer = { getMappedRange: vi.fn(() => new ArrayBuffer(16)), unmap: vi.fn(), destroy: vi.fn() } + const pass = { setPipeline: vi.fn(), setBindGroup: vi.fn(), dispatchWorkgroups: vi.fn(), end: vi.fn() } + const queue = { + submit: vi.fn(), + onSubmittedWorkDone: vi.fn(() => { + const d = deferred() + pending.push(d) + if (!holdWork) d.resolve() + return d.promise + }), + } + const device = { + queue, + createBuffer: vi.fn(() => buffer), + createShaderModule: vi.fn(() => ({})), + createComputePipeline: vi.fn(() => ({ getBindGroupLayout: () => ({}) })), + createBindGroup: vi.fn(() => ({})), + createCommandEncoder: vi.fn(() => ({ beginComputePass: () => pass, finish: () => ({}) })), + pushErrorScope: vi.fn(), + popErrorScope: vi.fn(async () => popError), + lost: lost ? lost.promise : new Promise(() => {}), + destroy: vi.fn(), + } + const gpuAdapter = { + requestDevice: vi.fn(async () => { + if (holdDevice) await deviceGate.promise + return device + }), + } + const gpu = { + requestAdapter: vi.fn(async () => { + if (holdAdapter) await adapterGate.promise + return gpuAdapter + }), + } + Object.defineProperty(navigator, 'gpu', { configurable: true, value: gpu }) + vi.stubGlobal('GPUBufferUsage', { STORAGE: 128 }) + return { gpu, gpuAdapter, device, buffer, queue, pending, adapterGate, deviceGate } +} + +afterEach(() => { + delete navigator.gpu + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +describe('useGPUCompute async GPU errors', () => { + it('shows Failed and destroys resources when an error scope reports an error', async () => { + const mock = installGPU({ popError: { message: 'Out of memory' } }) + const { result } = renderHook(() => useGPUCompute()) + await act(async () => { + await result.current.run() + }) + expect(mock.device.pushErrorScope).toHaveBeenCalledWith('out-of-memory') + expect(mock.device.pushErrorScope).toHaveBeenCalledWith('validation') + expect(mock.device.popErrorScope).toHaveBeenCalledTimes(2) + expect(mock.buffer.destroy).toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('Failed') + }) + + it('shows a result when both error scopes are clean', async () => { + const mock = installGPU() + const { result } = renderHook(() => useGPUCompute()) + await act(async () => { + await result.current.run() + }) + expect(mock.device.popErrorScope).toHaveBeenCalledTimes(2) + expect(result.current.throughput).not.toBe('Failed') + }) + + it('shows Failed when the device is lost mid-run while the work never completes', async () => { + const lost = deferred() + const mock = installGPU({ holdWork: true, lost }) + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await waitFor(() => expect(mock.queue.submit).toHaveBeenCalledTimes(1)) + await act(async () => { + lost.resolve({ reason: 'unknown', message: 'GPU reset' }) + await done + }) + expect(mock.queue.submit).toHaveBeenCalledTimes(1) + expect(mock.buffer.destroy).toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('Failed') + }) +}) diff --git a/src/hooks/useGPUCompute.hiddenLast.test.js b/src/hooks/useGPUCompute.hiddenLast.test.js new file mode 100644 index 0000000..ad55001 --- /dev/null +++ b/src/hooks/useGPUCompute.hiddenLast.test.js @@ -0,0 +1,100 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { renderHook, act, waitFor } from '@testing-library/react' +import { useGPUCompute, BENCHMARK_DISPATCHES } from './useGPUCompute.js' + +// Issue #11: a hide that arrives while the last dispatch is in flight lets that +// dispatch finish, so all timings are in and the result must be shown. + +function deferred() { + let resolve + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +// Self-contained WebGPU mock. Each async step can be held open with a deferred. +function installGPU({ holdAdapter = false, holdDevice = false, holdWork = false, popError = null, lost = null } = {}) { + const adapterGate = deferred() + const deviceGate = deferred() + const pending = [] + const buffer = { getMappedRange: vi.fn(() => new ArrayBuffer(16)), unmap: vi.fn(), destroy: vi.fn() } + const pass = { setPipeline: vi.fn(), setBindGroup: vi.fn(), dispatchWorkgroups: vi.fn(), end: vi.fn() } + const queue = { + submit: vi.fn(), + onSubmittedWorkDone: vi.fn(() => { + const d = deferred() + pending.push(d) + if (!holdWork) d.resolve() + return d.promise + }), + } + const device = { + queue, + createBuffer: vi.fn(() => buffer), + createShaderModule: vi.fn(() => ({})), + createComputePipeline: vi.fn(() => ({ getBindGroupLayout: () => ({}) })), + createBindGroup: vi.fn(() => ({})), + createCommandEncoder: vi.fn(() => ({ beginComputePass: () => pass, finish: () => ({}) })), + pushErrorScope: vi.fn(), + popErrorScope: vi.fn(async () => popError), + lost: lost ? lost.promise : new Promise(() => {}), + destroy: vi.fn(), + } + const gpuAdapter = { + requestDevice: vi.fn(async () => { + if (holdDevice) await deviceGate.promise + return device + }), + } + const gpu = { + requestAdapter: vi.fn(async () => { + if (holdAdapter) await adapterGate.promise + return gpuAdapter + }), + } + Object.defineProperty(navigator, 'gpu', { configurable: true, value: gpu }) + vi.stubGlobal('GPUBufferUsage', { STORAGE: 128 }) + return { gpu, gpuAdapter, device, buffer, queue, pending, adapterGate, deviceGate } +} + +function setVisibility(state) { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state }) +} + +function hide() { + setVisibility('hidden') + document.dispatchEvent(new Event('visibilitychange')) +} + +afterEach(() => { + delete navigator.gpu + delete document.visibilityState + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +describe('useGPUCompute hidden during the last dispatch', () => { + it('shows the result, not Stopped, when every dispatch completed', async () => { + const mock = installGPU({ holdWork: true }) + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + for (let k = 0; k < BENCHMARK_DISPATCHES; k++) { + await waitFor(() => expect(mock.pending.length).toBe(k + 1)) + if (k === BENCHMARK_DISPATCHES - 1) act(() => hide()) + await act(async () => { + mock.pending[k].resolve() + }) + } + await act(async () => { + await done + }) + expect(mock.queue.submit).toHaveBeenCalledTimes(BENCHMARK_DISPATCHES) + expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toMatch(/^~\d+\.\d GB\/s est\.$|^Too fast$/) + }) +}) diff --git a/src/hooks/useGPUCompute.js b/src/hooks/useGPUCompute.js index 821dbae..8e8f1dc 100644 --- a/src/hooks/useGPUCompute.js +++ b/src/hooks/useGPUCompute.js @@ -1,8 +1,13 @@ -import { useState, useEffect } from 'react' +import { useState, useEffect, useRef, useCallback } from 'react' const COUNT = 65535 * 256 // 16,776,960 floats ~64MB, exactly 65535 workgroups const WORKGROUP_SIZE = 256 const WORKGROUPS = COUNT / WORKGROUP_SIZE // 65535 +// 128MB traffic per dispatch: 64MB read + 64MB write +const BYTES_PER_DISPATCH_GB = 0.128 +const LOST = Symbol('lost') + +export const BENCHMARK_DISPATCHES = 5 const SHADER = ` @group(0) @binding(0) var data: array; @@ -16,75 +21,162 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } ` +export function median(values) { + const sorted = [...values].sort((a, b) => a - b) + const mid = Math.floor(sorted.length / 2) + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2 +} + +// CPU-timed, so it includes submit and callback latency: an estimate. +// A coarse timer can report 0, so anything but a positive finite time is +// shown as Too fast rather than Infinity. +export function formatThroughput(seconds) { + if (!(Number.isFinite(seconds) && seconds > 0)) return 'Too fast' + return `~${(BYTES_PER_DISPATCH_GB / seconds).toFixed(1)} GB/s est.` +} + +function isHidden() { + return document.visibilityState === 'hidden' +} + export function useGPUCompute() { - const [state, setState] = useState({ throughput: '--', supported: false }) + const [state, setState] = useState(() => ({ + throughput: '--', + supported: Boolean(navigator.gpu), + running: false, + })) + + const activeRef = useRef(false) + const stopRef = useRef(false) + const mountedRef = useRef(false) + const resourcesRef = useRef({ buffer: null, device: null }) + + const release = useCallback(() => { + const res = resourcesRef.current + res.buffer?.destroy() + res.device?.destroy() + res.buffer = null + res.device = null + }, []) useEffect(() => { - if (!navigator.gpu) return - - let intervalId = null - let device = null - let buf = null - - async function init() { - try { - const adapter = await navigator.gpu.requestAdapter() - if (!adapter) return - - device = await adapter.requestDevice() - - buf = device.createBuffer({ - size: COUNT * 4, - usage: GPUBufferUsage.STORAGE, - mappedAtCreation: true, - }) - new Float32Array(buf.getMappedRange()).fill(1.0) - buf.unmap() - - const module = device.createShaderModule({ code: SHADER }) - const pipeline = device.createComputePipeline({ - layout: 'auto', - compute: { module, entryPoint: 'main' }, - }) - const bindGroup = device.createBindGroup({ - layout: pipeline.getBindGroupLayout(0), - entries: [{ binding: 0, resource: { buffer: buf } }], - }) - - setState({ throughput: '...', supported: true }) - - intervalId = setInterval(async () => { - try { - const t0 = performance.now() - const encoder = device.createCommandEncoder() - const pass = encoder.beginComputePass() - pass.setPipeline(pipeline) - pass.setBindGroup(0, bindGroup) - pass.dispatchWorkgroups(WORKGROUPS) - pass.end() - device.queue.submit([encoder.finish()]) - await device.queue.onSubmittedWorkDone() - const elapsed = (performance.now() - t0) / 1000 - // 128MB traffic per dispatch: 64MB read + 64MB write - const gbps = (0.128 / elapsed).toFixed(1) - setState({ throughput: `${gbps} GB/s`, supported: true }) - } catch { - setState({ throughput: '--', supported: false }) - } - }, 1000) - } catch { - setState({ throughput: '--', supported: false }) - } + mountedRef.current = true + return () => { + mountedRef.current = false + stopRef.current = true + release() } + }, [release]) - init() + const run = useCallback(async () => { + if (activeRef.current || !mountedRef.current || !navigator.gpu || isHidden()) return + activeRef.current = true + stopRef.current = false + const stopped = () => stopRef.current || !mountedRef.current - return () => { - if (intervalId) clearInterval(intervalId) - buf?.destroy() - device?.destroy() + const update = (next) => { + if (mountedRef.current) setState((s) => ({ ...s, ...next })) } - }, []) + const onVisibility = () => { + if (isHidden()) stopRef.current = true + } + document.addEventListener('visibilitychange', onVisibility) + update({ running: true, throughput: 'Running...' }) + + const res = resourcesRef.current + try { + const adapter = await navigator.gpu.requestAdapter() + if (stopped()) { + update({ throughput: 'Stopped' }) + return + } + if (!adapter) { + update({ supported: false, throughput: '--' }) + return + } + + // Assigned before the stop check so a device that arrives after a stop + // is still destroyed in finally. + res.device = await adapter.requestDevice() + if (stopped()) { + update({ throughput: 'Stopped' }) + return + } + const device = res.device + + // Out-of-memory and validation errors are reported asynchronously, and an + // invalid buffer or pipeline turns submits into no-ops, so collect them. + device.pushErrorScope('out-of-memory') + device.pushErrorScope('validation') + let lostReason = null + const lost = device.lost.then((info) => { + lostReason = info?.reason ?? 'unknown' + return LOST + }) + + res.buffer = device.createBuffer({ + size: COUNT * 4, + usage: GPUBufferUsage.STORAGE, + mappedAtCreation: true, + }) + new Float32Array(res.buffer.getMappedRange()).fill(1.0) + res.buffer.unmap() + + const module = device.createShaderModule({ code: SHADER }) + const pipeline = device.createComputePipeline({ + layout: 'auto', + compute: { module, entryPoint: 'main' }, + }) + const bindGroup = device.createBindGroup({ + layout: pipeline.getBindGroupLayout(0), + entries: [{ binding: 0, resource: { buffer: res.buffer } }], + }) + + const timings = [] + let failed = false + for (let k = 0; k < BENCHMARK_DISPATCHES; k++) { + if (stopped()) break + const t0 = performance.now() + const encoder = device.createCommandEncoder() + const pass = encoder.beginComputePass() + pass.setPipeline(pipeline) + pass.setBindGroup(0, bindGroup) + pass.dispatchWorkgroups(WORKGROUPS) + pass.end() + device.queue.submit([encoder.finish()]) + const outcome = await Promise.race([device.queue.onSubmittedWorkDone(), lost]) + // lostReason is set before the race sees LOST; it is judged after the loop. + if (outcome === LOST) break + timings.push((performance.now() - t0) / 1000) + } + + if (lostReason === null) { + const validationError = await device.popErrorScope() + const oomError = await device.popErrorScope() + if (validationError || oomError) failed = true + } + + // Checked last: the loss can settle together with or after a work-done + // promise, or while the scopes are popped (they resolve null on a lost + // device). Any loss but our own destroy on unmount fails the run. + if (lostReason !== null && lostReason !== 'destroyed') failed = true - return state -} \ No newline at end of file + if (failed) { + update({ throughput: 'Failed' }) + } else if (timings.length < BENCHMARK_DISPATCHES) { + update({ throughput: 'Stopped' }) + } else { + update({ throughput: formatThroughput(median(timings)) }) + } + } catch { + update({ throughput: 'Failed' }) + } finally { + document.removeEventListener('visibilitychange', onVisibility) + release() + activeRef.current = false + update({ running: false }) + } + }, [release]) + + return { ...state, run } +} diff --git a/src/hooks/useGPUCompute.lostAfterLoop.test.js b/src/hooks/useGPUCompute.lostAfterLoop.test.js new file mode 100644 index 0000000..ef68fe9 --- /dev/null +++ b/src/hooks/useGPUCompute.lostAfterLoop.test.js @@ -0,0 +1,136 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { renderHook, act, waitFor } from '@testing-library/react' +import { useGPUCompute, BENCHMARK_DISPATCHES } from './useGPUCompute.js' + +// Issue #11: a device loss that is only recorded after the loop (while the error +// scopes are being popped, or after a hide ended the loop) must still show Failed. + +function deferred() { + let resolve + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +// Self-contained WebGPU mock. Each async step can be held open with a deferred. +function installGPU({ holdAdapter = false, holdDevice = false, holdWork = false, holdPop = false, popError = null, lost = null } = {}) { + const adapterGate = deferred() + const deviceGate = deferred() + const popGate = deferred() + const pending = [] + const buffer = { getMappedRange: vi.fn(() => new ArrayBuffer(16)), unmap: vi.fn(), destroy: vi.fn() } + const pass = { setPipeline: vi.fn(), setBindGroup: vi.fn(), dispatchWorkgroups: vi.fn(), end: vi.fn() } + const queue = { + submit: vi.fn(), + onSubmittedWorkDone: vi.fn(() => { + const d = deferred() + pending.push(d) + if (!holdWork) d.resolve() + return d.promise + }), + } + const device = { + queue, + createBuffer: vi.fn(() => buffer), + createShaderModule: vi.fn(() => ({})), + createComputePipeline: vi.fn(() => ({ getBindGroupLayout: () => ({}) })), + createBindGroup: vi.fn(() => ({})), + createCommandEncoder: vi.fn(() => ({ beginComputePass: () => pass, finish: () => ({}) })), + pushErrorScope: vi.fn(), + popErrorScope: vi.fn(async () => { + if (holdPop) await popGate.promise + return popError + }), + lost: lost ? lost.promise : new Promise(() => {}), + destroy: vi.fn(), + } + const gpuAdapter = { + requestDevice: vi.fn(async () => { + if (holdDevice) await deviceGate.promise + return device + }), + } + const gpu = { + requestAdapter: vi.fn(async () => { + if (holdAdapter) await adapterGate.promise + return gpuAdapter + }), + } + Object.defineProperty(navigator, 'gpu', { configurable: true, value: gpu }) + vi.stubGlobal('GPUBufferUsage', { STORAGE: 128 }) + return { gpu, gpuAdapter, device, buffer, queue, pending, adapterGate, deviceGate, popGate } +} + +function setVisibility(state) { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state }) +} + +function hide() { + setVisibility('hidden') + document.dispatchEvent(new Event('visibilitychange')) +} + +afterEach(() => { + delete navigator.gpu + delete document.visibilityState + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +describe('useGPUCompute device loss recorded after the dispatch loop', () => { + it('shows Failed when device.lost resolves while the error scopes are being popped', async () => { + const lost = deferred() + const mock = installGPU({ holdWork: true, holdPop: true, lost }) + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + for (let k = 0; k < BENCHMARK_DISPATCHES; k++) { + await waitFor(() => expect(mock.pending.length).toBe(k + 1)) + await act(async () => { + mock.pending[k].resolve() + }) + } + await waitFor(() => expect(mock.device.popErrorScope).toHaveBeenCalled()) + await act(async () => { + lost.resolve({ reason: 'unknown', message: 'GPU reset' }) + }) + await act(async () => { + mock.popGate.resolve() + await done + }) + expect(mock.queue.submit).toHaveBeenCalledTimes(BENCHMARK_DISPATCHES) + expect(mock.buffer.destroy).toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('Failed') + }) + + it('shows Failed, not Stopped, when the tab is hidden and the device is lost mid-run', async () => { + const lost = deferred() + const mock = installGPU({ holdWork: true, lost }) + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await waitFor(() => expect(mock.pending.length).toBe(1)) + await act(async () => { + mock.pending[0].resolve() + }) + await waitFor(() => expect(mock.pending.length).toBe(2)) + act(() => hide()) + await act(async () => { + lost.resolve({ reason: 'unknown', message: 'GPU reset' }) + mock.pending[1].resolve() + await done + }) + expect(mock.queue.submit).toHaveBeenCalledTimes(2) + expect(mock.buffer.destroy).toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('Failed') + }) +}) diff --git a/src/hooks/useGPUCompute.lostWithWork.test.js b/src/hooks/useGPUCompute.lostWithWork.test.js new file mode 100644 index 0000000..490d59e --- /dev/null +++ b/src/hooks/useGPUCompute.lostWithWork.test.js @@ -0,0 +1,95 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { renderHook, act, waitFor } from '@testing-library/react' +import { useGPUCompute, BENCHMARK_DISPATCHES } from './useGPUCompute.js' + +// Issue #11: Chrome resolves pending work-done promises when the device is lost, +// so device.lost and onSubmittedWorkDone() can settle in the same tick. A loss +// that is not our own destroy must still show Failed. + +function deferred() { + let resolve + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +// Self-contained WebGPU mock. Each async step can be held open with a deferred. +function installGPU({ holdAdapter = false, holdDevice = false, holdWork = false, popError = null, lost = null } = {}) { + const adapterGate = deferred() + const deviceGate = deferred() + const pending = [] + const buffer = { getMappedRange: vi.fn(() => new ArrayBuffer(16)), unmap: vi.fn(), destroy: vi.fn() } + const pass = { setPipeline: vi.fn(), setBindGroup: vi.fn(), dispatchWorkgroups: vi.fn(), end: vi.fn() } + const queue = { + submit: vi.fn(), + onSubmittedWorkDone: vi.fn(() => { + const d = deferred() + pending.push(d) + if (!holdWork) d.resolve() + return d.promise + }), + } + const device = { + queue, + createBuffer: vi.fn(() => buffer), + createShaderModule: vi.fn(() => ({})), + createComputePipeline: vi.fn(() => ({ getBindGroupLayout: () => ({}) })), + createBindGroup: vi.fn(() => ({})), + createCommandEncoder: vi.fn(() => ({ beginComputePass: () => pass, finish: () => ({}) })), + pushErrorScope: vi.fn(), + popErrorScope: vi.fn(async () => popError), + lost: lost ? lost.promise : new Promise(() => {}), + destroy: vi.fn(), + } + const gpuAdapter = { + requestDevice: vi.fn(async () => { + if (holdDevice) await deviceGate.promise + return device + }), + } + const gpu = { + requestAdapter: vi.fn(async () => { + if (holdAdapter) await adapterGate.promise + return gpuAdapter + }), + } + Object.defineProperty(navigator, 'gpu', { configurable: true, value: gpu }) + vi.stubGlobal('GPUBufferUsage', { STORAGE: 128 }) + return { gpu, gpuAdapter, device, buffer, queue, pending, adapterGate, deviceGate } +} + +afterEach(() => { + delete navigator.gpu + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +describe('useGPUCompute device loss together with the last work-done', () => { + it('shows Failed when device.lost and the 5th work-done resolve in the same tick', async () => { + const lost = deferred() + const mock = installGPU({ holdWork: true, lost }) + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + for (let k = 0; k < BENCHMARK_DISPATCHES - 1; k++) { + await waitFor(() => expect(mock.pending.length).toBe(k + 1)) + await act(async () => { + mock.pending[k].resolve() + }) + } + await waitFor(() => expect(mock.pending.length).toBe(BENCHMARK_DISPATCHES)) + await act(async () => { + lost.resolve({ reason: 'unknown', message: 'GPU reset' }) + mock.pending[BENCHMARK_DISPATCHES - 1].resolve() + await done + }) + expect(mock.queue.submit).toHaveBeenCalledTimes(BENCHMARK_DISPATCHES) + expect(mock.buffer.destroy).toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('Failed') + }) +}) diff --git a/src/hooks/useGPUCompute.setupStop.test.js b/src/hooks/useGPUCompute.setupStop.test.js new file mode 100644 index 0000000..763b583 --- /dev/null +++ b/src/hooks/useGPUCompute.setupStop.test.js @@ -0,0 +1,147 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { renderHook, act, waitFor } from '@testing-library/react' +import { useGPUCompute } from './useGPUCompute.js' + +// Issue #11: a stop (hidden tab or unmount) during adapter or device setup must +// bail before the 64 MB buffer is allocated, and run() after unmount does nothing. + +function deferred() { + let resolve + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +// Self-contained WebGPU mock. Each async step can be held open with a deferred. +function installGPU({ holdAdapter = false, holdDevice = false, holdWork = false, popError = null, lost = null } = {}) { + const adapterGate = deferred() + const deviceGate = deferred() + const pending = [] + const buffer = { getMappedRange: vi.fn(() => new ArrayBuffer(16)), unmap: vi.fn(), destroy: vi.fn() } + const pass = { setPipeline: vi.fn(), setBindGroup: vi.fn(), dispatchWorkgroups: vi.fn(), end: vi.fn() } + const queue = { + submit: vi.fn(), + onSubmittedWorkDone: vi.fn(() => { + const d = deferred() + pending.push(d) + if (!holdWork) d.resolve() + return d.promise + }), + } + const device = { + queue, + createBuffer: vi.fn(() => buffer), + createShaderModule: vi.fn(() => ({})), + createComputePipeline: vi.fn(() => ({ getBindGroupLayout: () => ({}) })), + createBindGroup: vi.fn(() => ({})), + createCommandEncoder: vi.fn(() => ({ beginComputePass: () => pass, finish: () => ({}) })), + pushErrorScope: vi.fn(), + popErrorScope: vi.fn(async () => popError), + lost: lost ? lost.promise : new Promise(() => {}), + destroy: vi.fn(), + } + const gpuAdapter = { + requestDevice: vi.fn(async () => { + if (holdDevice) await deviceGate.promise + return device + }), + } + const gpu = { + requestAdapter: vi.fn(async () => { + if (holdAdapter) await adapterGate.promise + return gpuAdapter + }), + } + Object.defineProperty(navigator, 'gpu', { configurable: true, value: gpu }) + vi.stubGlobal('GPUBufferUsage', { STORAGE: 128 }) + return { gpu, gpuAdapter, device, buffer, queue, pending, adapterGate, deviceGate } +} + +function setVisibility(state) { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state }) +} + +function hide() { + setVisibility('hidden') + document.dispatchEvent(new Event('visibilitychange')) +} + +afterEach(() => { + delete navigator.gpu + delete document.visibilityState + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +describe('useGPUCompute stop during setup', () => { + it('stops before allocating when hidden while requestAdapter is pending', async () => { + const mock = installGPU({ holdAdapter: true }) + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await waitFor(() => expect(mock.gpu.requestAdapter).toHaveBeenCalled()) + act(() => hide()) + await act(async () => { + mock.adapterGate.resolve() + await done + }) + expect(mock.device.createBuffer).not.toHaveBeenCalled() + expect(mock.queue.submit).not.toHaveBeenCalled() + if (mock.gpuAdapter.requestDevice.mock.calls.length) expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('Stopped') + }) + + it('stops before allocating and destroys the device when hidden while requestDevice is pending', async () => { + const mock = installGPU({ holdDevice: true }) + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await waitFor(() => expect(mock.gpuAdapter.requestDevice).toHaveBeenCalled()) + act(() => hide()) + await act(async () => { + mock.deviceGate.resolve() + await done + }) + expect(mock.device.createBuffer).not.toHaveBeenCalled() + expect(mock.queue.submit).not.toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('Stopped') + }) + + it('does not allocate and destroys the device when unmounted while requestDevice is pending', async () => { + const mock = installGPU({ holdDevice: true }) + const { result, unmount } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await waitFor(() => expect(mock.gpuAdapter.requestDevice).toHaveBeenCalled()) + unmount() + await act(async () => { + mock.deviceGate.resolve() + await done + }) + expect(mock.device.createBuffer).not.toHaveBeenCalled() + expect(mock.queue.submit).not.toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + }) + + it('does nothing when run() is called after unmount', async () => { + const mock = installGPU() + const { result, unmount } = renderHook(() => useGPUCompute()) + const run = result.current.run + unmount() + await act(async () => { + await run() + }) + expect(mock.gpu.requestAdapter).not.toHaveBeenCalled() + expect(mock.device.createBuffer).not.toHaveBeenCalled() + }) +}) diff --git a/src/hooks/useGPUCompute.test.js b/src/hooks/useGPUCompute.test.js index dfba79c..46c0b1a 100644 --- a/src/hooks/useGPUCompute.test.js +++ b/src/hooks/useGPUCompute.test.js @@ -1,6 +1,6 @@ -import { describe, it, expect } from 'vitest' -import { renderHook } from '@testing-library/react' -import { useGPUCompute } from './useGPUCompute.js' +import { describe, it, expect, vi, afterEach } from 'vitest' +import { renderHook, act, waitFor } from '@testing-library/react' +import { useGPUCompute, median, formatThroughput, BENCHMARK_DISPATCHES } from './useGPUCompute.js' describe('useGPUCompute', () => { it('returns supported: false and throughput: "--" when navigator.gpu is undefined', () => { @@ -10,3 +10,270 @@ describe('useGPUCompute', () => { expect(result.current.throughput).toBe('--') }) }) + +describe('median', () => { + it('returns the middle value of an odd-length list', () => { + expect(median([5, 1, 3, 2, 4])).toBe(3) + }) + + it('returns the mean of the two middle values of an even-length list', () => { + expect(median([4, 1, 3, 2])).toBe(2.5) + }) + + it('does not reorder its input', () => { + const values = [3, 1, 2] + median(values) + expect(values).toEqual([3, 1, 2]) + }) +}) + +describe('formatThroughput', () => { + it('formats 128 MB over the elapsed seconds as an estimate in GB/s', () => { + expect(formatThroughput(0.1)).toBe('~1.3 GB/s est.') + expect(formatThroughput(0.001)).toBe('~128.0 GB/s est.') + }) +}) + +// ─── Mocked WebGPU ─── + +function deferred() { + let resolve + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +function installGPU({ adapter = true, failPipeline = false } = {}) { + const pending = [] + const buffer = { + getMappedRange: vi.fn(() => new ArrayBuffer(16)), + unmap: vi.fn(), + destroy: vi.fn(), + } + const queue = { + submit: vi.fn(), + onSubmittedWorkDone: vi.fn(() => { + const d = deferred() + pending.push(d) + return d.promise + }), + } + const pass = { + setPipeline: vi.fn(), + setBindGroup: vi.fn(), + dispatchWorkgroups: vi.fn(), + end: vi.fn(), + } + const device = { + queue, + createBuffer: vi.fn(() => buffer), + createShaderModule: vi.fn(() => ({})), + createComputePipeline: vi.fn(() => { + if (failPipeline) throw new Error('pipeline failed') + return { getBindGroupLayout: () => ({}) } + }), + createBindGroup: vi.fn(() => ({})), + createCommandEncoder: vi.fn(() => ({ + beginComputePass: () => pass, + finish: () => ({}), + })), + destroy: vi.fn(), + pushErrorScope: vi.fn(), + popErrorScope: vi.fn(async () => null), + lost: new Promise(() => {}), + } + const gpuAdapter = { requestDevice: vi.fn(async () => device) } + const gpu = { requestAdapter: vi.fn(async () => (adapter ? gpuAdapter : null)) } + Object.defineProperty(navigator, 'gpu', { configurable: true, value: gpu }) + vi.stubGlobal('GPUBufferUsage', { STORAGE: 128 }) + return { gpu, gpuAdapter, device, buffer, queue, pending } +} + +function setVisibility(state) { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state }) +} + +afterEach(() => { + delete navigator.gpu + delete document.visibilityState + vi.unstubAllGlobals() +}) + +async function resolveDispatch(mock, k) { + await waitFor(() => expect(mock.queue.submit).toHaveBeenCalledTimes(k + 1)) + await waitFor(() => expect(mock.pending.length).toBe(k + 1)) + await act(async () => { + mock.pending[k].resolve() + }) +} + +describe('useGPUCompute with WebGPU', () => { + it('does no GPU work on mount', () => { + const mock = installGPU() + const { result } = renderHook(() => useGPUCompute()) + expect(mock.gpu.requestAdapter).not.toHaveBeenCalled() + expect(mock.gpuAdapter.requestDevice).not.toHaveBeenCalled() + expect(mock.device.createBuffer).not.toHaveBeenCalled() + expect(mock.queue.submit).not.toHaveBeenCalled() + expect(result.current.supported).toBe(true) + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('--') + }) + + it('runs the dispatches strictly in sequence and reports the estimate', async () => { + const mock = installGPU() + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + expect(result.current.running).toBe(true) + expect(result.current.throughput).toBe('Running...') + + for (let k = 0; k < BENCHMARK_DISPATCHES; k++) { + await waitFor(() => expect(mock.queue.submit).toHaveBeenCalledTimes(k + 1)) + // The next dispatch must wait for this one to finish. + await act(async () => {}) + expect(mock.queue.submit).toHaveBeenCalledTimes(k + 1) + await act(async () => { + mock.pending[k].resolve() + }) + } + await act(async () => { + await done + }) + + expect(mock.gpu.requestAdapter).toHaveBeenCalledTimes(1) + expect(mock.gpuAdapter.requestDevice).toHaveBeenCalledTimes(1) + expect(mock.device.createBuffer).toHaveBeenCalledTimes(1) + expect(mock.queue.submit).toHaveBeenCalledTimes(BENCHMARK_DISPATCHES) + expect(mock.buffer.destroy).toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toMatch(/^~\d+\.\d GB\/s est\.$/) + }) + + it('schedules nothing after a run', async () => { + const mock = installGPU() + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + for (let k = 0; k < BENCHMARK_DISPATCHES; k++) await resolveDispatch(mock, k) + await act(async () => { + await done + }) + await act(async () => { + await new Promise((r) => setTimeout(r, 1100)) + }) + expect(mock.queue.submit).toHaveBeenCalledTimes(BENCHMARK_DISPATCHES) + }) + + it('does nothing when activated while the document is hidden', async () => { + const mock = installGPU() + setVisibility('hidden') + const { result } = renderHook(() => useGPUCompute()) + await act(async () => { + await result.current.run() + }) + expect(mock.gpu.requestAdapter).not.toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('--') + }) + + it('stops before the next dispatch when the tab is hidden mid-run', async () => { + const mock = installGPU() + setVisibility('visible') + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await waitFor(() => expect(mock.queue.submit).toHaveBeenCalledTimes(1)) + setVisibility('hidden') + act(() => { + document.dispatchEvent(new Event('visibilitychange')) + }) + await act(async () => { + mock.pending[0].resolve() + await done + }) + expect(mock.queue.submit).toHaveBeenCalledTimes(1) + expect(mock.buffer.destroy).toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('Stopped') + }) + + it('ignores activation while a run is in progress', async () => { + const mock = installGPU() + const { result } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await act(async () => { + await result.current.run() + }) + for (let k = 0; k < BENCHMARK_DISPATCHES; k++) await resolveDispatch(mock, k) + await act(async () => { + await done + }) + expect(mock.gpu.requestAdapter).toHaveBeenCalledTimes(1) + expect(mock.queue.submit).toHaveBeenCalledTimes(BENCHMARK_DISPATCHES) + }) + + it('keeps run stable across renders', async () => { + installGPU() + const { result, rerender } = renderHook(() => useGPUCompute()) + const first = result.current.run + rerender() + expect(result.current.run).toBe(first) + }) + + it('stops and destroys on unmount mid-run', async () => { + const mock = installGPU() + const { result, unmount } = renderHook(() => useGPUCompute()) + let done + act(() => { + done = result.current.run() + }) + await waitFor(() => expect(mock.queue.submit).toHaveBeenCalledTimes(1)) + unmount() + expect(mock.buffer.destroy).toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + await act(async () => { + mock.pending[0].resolve() + await done + }) + expect(mock.queue.submit).toHaveBeenCalledTimes(1) + }) + + it('reports unsupported when requestAdapter returns null', async () => { + const mock = installGPU({ adapter: false }) + const { result } = renderHook(() => useGPUCompute()) + await act(async () => { + await result.current.run() + }) + expect(mock.gpu.requestAdapter).toHaveBeenCalledTimes(1) + expect(result.current.supported).toBe(false) + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('--') + }) + + it('shows Failed and destroys what it allocated when a run throws', async () => { + const mock = installGPU({ failPipeline: true }) + const { result } = renderHook(() => useGPUCompute()) + await act(async () => { + await result.current.run() + }) + expect(mock.buffer.destroy).toHaveBeenCalled() + expect(mock.device.destroy).toHaveBeenCalled() + expect(mock.queue.submit).not.toHaveBeenCalled() + expect(result.current.supported).toBe(true) + expect(result.current.running).toBe(false) + expect(result.current.throughput).toBe('Failed') + }) +}) diff --git a/src/hooks/useGPUCompute.tooFast.test.js b/src/hooks/useGPUCompute.tooFast.test.js new file mode 100644 index 0000000..7385487 --- /dev/null +++ b/src/hooks/useGPUCompute.tooFast.test.js @@ -0,0 +1,85 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { renderHook, act } from '@testing-library/react' +import { useGPUCompute, formatThroughput } from './useGPUCompute.js' + +// Issue #11: a coarse performance.now() can make the median 0, which must not +// render as Infinity GB/s. + +function deferred() { + let resolve + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +// Self-contained WebGPU mock. Each async step can be held open with a deferred. +function installGPU({ holdAdapter = false, holdDevice = false, holdWork = false, popError = null, lost = null } = {}) { + const adapterGate = deferred() + const deviceGate = deferred() + const pending = [] + const buffer = { getMappedRange: vi.fn(() => new ArrayBuffer(16)), unmap: vi.fn(), destroy: vi.fn() } + const pass = { setPipeline: vi.fn(), setBindGroup: vi.fn(), dispatchWorkgroups: vi.fn(), end: vi.fn() } + const queue = { + submit: vi.fn(), + onSubmittedWorkDone: vi.fn(() => { + const d = deferred() + pending.push(d) + if (!holdWork) d.resolve() + return d.promise + }), + } + const device = { + queue, + createBuffer: vi.fn(() => buffer), + createShaderModule: vi.fn(() => ({})), + createComputePipeline: vi.fn(() => ({ getBindGroupLayout: () => ({}) })), + createBindGroup: vi.fn(() => ({})), + createCommandEncoder: vi.fn(() => ({ beginComputePass: () => pass, finish: () => ({}) })), + pushErrorScope: vi.fn(), + popErrorScope: vi.fn(async () => popError), + lost: lost ? lost.promise : new Promise(() => {}), + destroy: vi.fn(), + } + const gpuAdapter = { + requestDevice: vi.fn(async () => { + if (holdDevice) await deviceGate.promise + return device + }), + } + const gpu = { + requestAdapter: vi.fn(async () => { + if (holdAdapter) await adapterGate.promise + return gpuAdapter + }), + } + Object.defineProperty(navigator, 'gpu', { configurable: true, value: gpu }) + vi.stubGlobal('GPUBufferUsage', { STORAGE: 128 }) + return { gpu, gpuAdapter, device, buffer, queue, pending, adapterGate, deviceGate } +} + +afterEach(() => { + delete navigator.gpu + delete document.visibilityState + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +describe('formatThroughput with a non-positive or non-finite time', () => { + it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])('returns Too fast for %s seconds', (seconds) => { + expect(formatThroughput(seconds)).toBe('Too fast') + }) +}) + +describe('useGPUCompute with zero timings', () => { + it('shows Too fast when every dispatch times as 0', async () => { + const mock = installGPU() + vi.spyOn(performance, 'now').mockReturnValue(1000) + const { result } = renderHook(() => useGPUCompute()) + await act(async () => { + await result.current.run() + }) + expect(mock.queue.submit).toHaveBeenCalledTimes(5) + expect(result.current.throughput).toBe('Too fast') + }) +}) diff --git a/src/index.css b/src/index.css index dca8cff..b3801ea 100644 --- a/src/index.css +++ b/src/index.css @@ -641,6 +641,35 @@ body::before { color: var(--text-dim); } +/* The panel ignores pointer input so it never blocks the map; the button opts back in. */ +.gpu-bench-btn { + pointer-events: auto; + min-width: 24px; + min-height: 24px; + padding: 0 6px; + background: none; + border: 1px solid var(--border-active); + color: var(--accent); + font: inherit; + letter-spacing: inherit; + cursor: pointer; +} + +.gpu-bench-btn:hover { + border-color: var(--accent); +} + +.gpu-bench-btn:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.gpu-bench-btn[aria-disabled='true'] { + color: var(--text-dim); + border-color: var(--border); + cursor: default; +} + /* ─── RESPONSIVE ─── */ @media (max-width: 1024px) { diff --git a/src/styles.test.js b/src/styles.test.js index 106856a..d33be0c 100644 --- a/src/styles.test.js +++ b/src/styles.test.js @@ -161,6 +161,8 @@ const TEXT_PAIRS = [ { selector: '.gpu-info-val.warn', bg: 'overMap' }, { selector: '.gpu-info-val.err', bg: 'overMap' }, { selector: '.gpu-info-sep', bg: 'overMap' }, + { selector: '.gpu-bench-btn', bg: 'overMap' }, + { selector: ".gpu-bench-btn[aria-disabled='true']", bg: 'overMap' }, ] function textRatio({ selector, bg, fg }) { @@ -262,6 +264,12 @@ describe('target size (WCAG 2.5.8, 24x24)', () => { expect(px(d.height)).toBeGreaterThanOrEqual(24) }) + it('compute benchmark RUN button is at least 24x24', () => { + const d = rule('.gpu-bench-btn') + expect(px(d['min-width'])).toBeGreaterThanOrEqual(24) + expect(px(d['min-height'])).toBeGreaterThanOrEqual(24) + }) + it('stress slider input is at least 24px tall', () => { expect(px(rule('.stress-slider').height)).toBeGreaterThanOrEqual(24) })