Files
reims-vgpu/scripts/browser-probe/gpu-probe.html
T
Anees IqbalandClaude 1acac3d31d 🐛 The device advertised 120 Hz and delivered VBL at 125
`crates/reims-vgpu` display VBL limiter (`runtime/drain/mod.rs`,
`model/regs.rs`, `observe/sink.rs`, `lib.rs`) plus an instrument caveat in
`scripts/browser-probe/gpu-probe.html`. Affects every pathway; measured on
x86 macOS / Linux Vulkan.

Two constants reach the guest by two routes: `DISPLAY_REFRESH_HZ = 120` goes
into the mode timing table it reads, and the VBL limiter paces the interrupt it
is actually woken by. The limiter was a hardcoded `DISPLAY_VBL_MIN_INTERVAL_MS
= 8`, which is 125 Hz. The guest paces to the interrupt, not the table, so it
latched 125 — a driven Safari measured its own frame rate at exactly 125 Hz
while our timing table claimed 120. Two comments in the same file disagreed
about which was intended, one calling 8 ms "approximately 120 Hz" and the other
"a healthy 125 Hz".

120 Hz is 8333 us and is **not expressible on an integer-millisecond grid**, so
the units were part of the defect rather than incidental to it: an 8 ms period
also carries +/-12.5% quantisation by construction. The limiter now works in
microseconds via a new `observe::elapsed_us()` on the same process-monotonic
clock, and `DISPLAY_VBL_MIN_INTERVAL_US` is **derived** from
`DISPLAY_REFRESH_HZ` rather than restated, so the two cannot drift apart again.
`t=` stamps stay in milliseconds so line-class censuses keep working.

Live verification, boot before and after: `display_vbl` read `window_hz=125.0
grid_hz=125.0` and now reads `window_hz=120.0 grid_hz=120.0` against 8192
delivered VBLs.

Tests: one added, 1212 -> 1213 passing, 0 failed (vulkan arm,
`--test-threads=1`). It asserts the *identity* — delivered cadence equals
advertised refresh — rather than either value, so it stays true if the
advertised rate changes and cannot itself go stale; a second assertion pins
that a whole-millisecond interval could not express the answer. Mutation
verified: restoring the 8 ms grid fails it with "advertising 120 Hz but
delivering 125.0 Hz (interval 8000 us)". Clippy clean with `-D warnings` on the
vulkan arm; `cargo check --target aarch64-apple-darwin --features backend-metal`
unchanged at 19 warnings, 0 errors.

Also documents a limit of our own probe that this exposed: browsers clamp
`performance.now()` (Safari to ~1 ms), so a true 8.333 ms interval arrives as
8/8/9 and the median-derived `refresh_hz` reports 125 for a display genuinely
at 120. The probe cannot tell those two apart and now says so; the host-side
`display_vbl` census is the instrument for that question.

Not verified: **no performance claim.** Guest-side long-frame counts across
runs were 15/24/28/8/10/42 with fps 118-119 and one run at 59.5, so run-to-run
variance dominates any effect this could have and the post-change run's higher
count is not evidence either way. The basis for this change is contract
consistency — advertise what we deliver — not measured frame pacing.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-02 00:14:34 +03:00

218 lines
9.5 KiB
HTML

<!doctype html>
<html>
<head><meta charset="utf-8"><title>probe: starting</title></head>
<body style="margin:0;background:#111;color:#eee;font:13px monospace">
<pre id="out">running…</pre>
<canvas id="c" width="512" height="512" style="width:256px;height:256px"></canvas>
<script>
// Reports which of WebGL1 / WebGL2 / WebGPU actually come up, what renderer is
// behind each, and how evenly a trivial animated draw is paced.
//
// Pacing is reported as a distribution, not a mean: the question these probes
// exist to answer is whether frames are dropped *occasionally*, and a mean frame
// rate is blind to that by construction. `?seconds=N` widens the window.
//
// The result is written to document.title as well as to the page, because Safari
// exposes no debugging protocol here: AppleScript can read a document's name
// without the "Allow JavaScript from Apple Events" setting, so the title is the
// only channel that works in all three browsers.
//
// The draw loop is deliberately trivial (one clear + one triangle). It is
// measuring the presentation path, not shader throughput; anything heavier
// would confound "the compositor drops frames" with "the GPU is busy".
const lines = [];
const say = (s) => { lines.push(s); document.getElementById('out').textContent = lines.join('\n'); };
function rendererOf(gl) {
if (!gl) return null;
const dbg = gl.getExtension('WEBGL_debug_renderer_info');
return {
vendor: dbg ? gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL) : gl.getParameter(gl.VENDOR),
renderer: dbg ? gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER),
version: gl.getParameter(gl.VERSION),
maxTexture: gl.getParameter(gl.MAX_TEXTURE_SIZE),
};
}
const canvas = document.getElementById('c');
const results = { webgl1: null, webgl2: null, webgpu: null, fps: null };
// WebGL contexts are probed on throwaway canvases so the visible canvas stays
// free for whichever API is used to measure frame rate.
for (const [key, name] of [['webgl1', 'webgl'], ['webgl2', 'webgl2']]) {
try {
const t = document.createElement('canvas');
const gl = t.getContext(name, { failIfMajorPerformanceCaveat: false });
results[key] = gl ? rendererOf(gl) : 'NOT_AVAILABLE';
} catch (e) { results[key] = 'THREW: ' + e.message; }
}
say('webgl1: ' + JSON.stringify(results.webgl1));
say('webgl2: ' + JSON.stringify(results.webgl2));
// `failIfMajorPerformanceCaveat: true` is the direct question "is this a
// software renderer?" — a browser that fell back to software refuses the
// context outright rather than reporting it in a string.
try {
const t = document.createElement('canvas');
results.noCaveat = !!t.getContext('webgl', { failIfMajorPerformanceCaveat: true });
} catch (e) { results.noCaveat = false; }
say('hardware(no perf caveat): ' + results.noCaveat);
async function probeWebGPU() {
if (!navigator.gpu) return 'NO_navigator.gpu';
try {
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) return 'NO_ADAPTER';
const info = adapter.info || (adapter.requestAdapterInfo ? await adapter.requestAdapterInfo() : {});
const dev = await adapter.requestDevice();
return {
vendor: info.vendor, architecture: info.architecture,
device: info.device, description: info.description,
hasDevice: !!dev,
features: dev ? [...dev.features].slice(0, 12) : [],
};
} catch (e) { return 'THREW: ' + e.message; }
}
// A mean frame rate cannot answer the question we actually have. "120 fps with
// occasional hitches" and "120 fps, perfectly even" produce the same mean, and
// a single worst-frame number cannot tell one 40 ms stall apart from forty of
// them. So keep every frame delta and report the distribution.
//
// The refresh interval is taken as the MEDIAN observed delta rather than a
// hardcoded 1/120: this rig's guest display has run at 60 and at 120, and a
// fixed budget would misreport every frame on the other one. The median is
// used instead of the mean because it is the one estimator a burst of long
// frames cannot drag with it.
//
// KNOWN LIMIT: browsers clamp `performance.now()` for fingerprinting reasons —
// Safari to about 1 ms. A true 120 Hz interval is 8.333 ms and arrives as
// 8/8/9/8/8/9, whose median is 8, so `refresh_hz` reports 125 on a display
// genuinely running at 120. Anything at a non-integer millisecond period is
// therefore reported as the nearest integer-millisecond rate, and this probe
// CANNOT be used to tell 120 Hz from 125 Hz. Use the host-side
// `display_vbl ... window_hz=` census for that question; it is measured on a
// clock nothing clamps. `fps` over the whole run is unaffected by the clamp and
// remains the honest rate.
//
// A "long" frame is one that consumed at least two refresh intervals, i.e. at
// least one frame was not shown. The 1.5x threshold is the midpoint between one
// interval and two, which is where a delta stops being jitter around the budget
// and starts being a skipped vblank.
const LONG_FRAME_INTERVALS = 1.5;
function quantile(sorted, q) {
if (!sorted.length) return 0;
const pos = (sorted.length - 1) * q;
const lo = Math.floor(pos);
const hi = Math.ceil(pos);
return sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo);
}
// Pure: no DOM, no timers. Kept separate from the rAF loop so the statistics
// can be exercised against synthetic frame streams with a known answer — a
// summariser that miscounts hitches would otherwise be indistinguishable from a
// guest that has none.
function summarizeDeltas(deltas, elapsedSeconds, frames) {
const sorted = deltas.slice().sort((a, b) => a - b);
const median = quantile(sorted, 0.5);
const budget = median * LONG_FRAME_INTERVALS;
let longFrames = 0, worstRun = 0, run = 0, dropped = 0;
for (const d of deltas) {
if (d > budget) {
longFrames++;
// How many refreshes went unshown. A delta of exactly two intervals
// skipped one.
dropped += Math.max(1, Math.round(d / median) - 1);
run++;
if (run > worstRun) worstRun = run;
} else {
run = 0;
}
}
// Histogram in units of refresh intervals, so it reads the same at 60 and at
// 120 Hz. Bucket i counts frames that took i+1 intervals; the last bucket is
// everything at or beyond 6.
const hist = [0, 0, 0, 0, 0, 0];
for (const d of deltas) {
hist[Math.min(hist.length - 1, Math.max(0, Math.round(d / median) - 1))]++;
}
return {
fps: +(frames / elapsedSeconds).toFixed(1),
// Retained under its original name: existing callers and the page title
// read this key.
worst_frame_ms: +(sorted.length ? sorted[sorted.length - 1] : 0).toFixed(1),
frames,
seconds: +elapsedSeconds.toFixed(1),
refresh_hz: +(1000 / median).toFixed(1),
median_ms: +median.toFixed(2),
p95_ms: +quantile(sorted, 0.95).toFixed(2),
p99_ms: +quantile(sorted, 0.99).toFixed(2),
long_frames: longFrames,
long_frame_pct: +(100 * longFrames / (deltas.length || 1)).toFixed(2),
dropped_refreshes: dropped,
worst_hitch_frames: worstRun,
hist_intervals: hist,
};
}
function measureFps(seconds) {
return new Promise((resolve) => {
const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
// Frame deltas, in order. Order matters: a hitch is a RUN of long frames,
// and a sorted summary alone would report ten scattered stalls and one
// ten-frame freeze identically, though only the second is visible as a jerk.
const deltas = [];
let frames = 0, last = performance.now();
const t0 = last;
const step = () => {
const now = performance.now();
const dt = now - last; last = now;
// The first frames carry context setup and first-draw compilation, which
// is real cost but not a pacing defect; excluding them keeps the tail
// statistics about steady-state pacing.
if (frames > 2) deltas.push(dt);
frames++;
if (gl) {
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor((frames % 60) / 60, 0.2, 0.6, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
}
if (now - t0 < seconds * 1000) { requestAnimationFrame(step); return; }
resolve(summarizeDeltas(deltas, (now - t0) / 1000, frames));
};
requestAnimationFrame(step);
});
}
(async () => {
results.webgpu = await probeWebGPU();
say('webgpu: ' + JSON.stringify(results.webgpu));
// Five seconds is enough to establish a mean but not to see an *occasional*
// hitch; `?seconds=N` buys a longer window when the tail is the question.
const want = +new URLSearchParams(location.search).get('seconds');
results.fps = await measureFps(want > 0 ? want : 5);
say('fps: ' + JSON.stringify(results.fps));
const r1 = results.webgl1 && results.webgl1.renderer ? results.webgl1.renderer : String(results.webgl1);
const wg = typeof results.webgpu === 'string' ? results.webgpu : 'OK';
document.title = 'probe: gl=' + r1 + ' | hw=' + results.noCaveat +
' | webgpu=' + wg + ' | fps=' + results.fps.fps +
' | worst=' + results.fps.worst_frame_ms + 'ms' +
' | long=' + results.fps.long_frames +
' | hitch=' + results.fps.worst_hitch_frames;
window.__probe = results;
// Safari exposes no debugging protocol and AppleScript automation needs a
// consent click, so the page posts its own result back to the server that
// served it. Same-origin, so no permission is involved.
try {
await fetch('/report', {
method: 'POST',
body: JSON.stringify({ ua: navigator.userAgent, results }),
});
} catch (e) { say('report failed: ' + e.message); }
say('DONE');
})();
</script>
</body>
</html>