feat: Stage 2E physics p95, runtime videos, domain audit, device-test QR

Measure Rapier world.step p95 (~0.2 ms) on GTX 1080, record real route WebMs,
expand runtime/headless hash parity, and document permanent-domain/phone blockers.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Даня Архипов
2026-07-30 14:28:14 +00:00
parent 014a46077d
commit 30103ccefc
63 changed files with 2786 additions and 71 deletions

View File

@@ -8,6 +8,7 @@ import {
type PerfSnapshot,
emptyPerfSnapshot,
} from '../../domain/perfMetrics';
import type { PhysicsPerfSnapshot } from '../../domain/physicsPerf';
const POLL_MS = 500;
@@ -21,6 +22,7 @@ export default function PerfOverlay({ enabled }: PerfOverlayProps) {
() => enabled === true || (enabled !== false && isPerfQueryEnabled()),
);
const [snap, setSnap] = useState<PerfSnapshot>(() => emptyPerfSnapshot());
const [phys, setPhys] = useState<PhysicsPerfSnapshot | null>(null);
const [inPresentation, setInPresentation] = useState(false);
useEffect(() => {
@@ -37,6 +39,8 @@ export default function PerfOverlay({ enabled }: PerfOverlayProps) {
const poll = () => {
const s = window.__PERF_SNAPSHOT__;
if (s) setSnap(s);
const p = window.__PHYSICS_PERF__;
if (p) setPhys(p);
setInPresentation(!!document.querySelector('.presentation-mode'));
};
@@ -80,6 +84,15 @@ export default function PerfOverlay({ enabled }: PerfOverlayProps) {
p95 {snap.p95FrameTimeMs.toFixed(1)}ms
<span className="perf-muted"> / p99 {snap.p99FrameTimeMs.toFixed(1)}ms</span>
</div>
{phys && phys.count > 0 ? (
<div data-testid="physics-perf-line">
phys p95 {phys.p95Ms.toFixed(2)}ms
<span className="perf-muted">
{' '}
· avg {phys.avgMs.toFixed(2)} · n={phys.count}
</span>
</div>
) : null}
<div>
draws {snap.drawCalls}
<span className="perf-muted"> · tris {snap.triangles}</span>

View File

@@ -12,23 +12,30 @@
* Physics freezes when the domain clock is paused (documented simulation
* assumption — belt, gate and items halt together; EMERGENCY_STOP creates no
* new impulses).
*
* Stage 2E: Rapier step timing via PhysicsPerfSampler (?perf=1 | ?physicsPerf=1).
* Render time is NOT included in physics p95.
*/
import { useRef, type ReactNode } from 'react';
import { useFrame } from '@react-three/fiber';
import { Physics, RigidBody, CuboidCollider, useRapier } from '@react-three/rapier';
import { getStaticColliders } from '../../domain/physicsWorldLayout';
import { PHYSICS_TIMESTEP_SEC } from '../../domain/physicsTimestep';
import {
PhysicsPerfSampler,
isPhysicsPerfQueryEnabled,
type PhysicsPerfSnapshot,
} from '../../domain/physicsPerf';
export const PHYSICS_DT = PHYSICS_TIMESTEP_SEC;
const MAX_SUBSTEPS = 4;
export const PHYSICS_MAX_SUBSTEPS = 4;
const MAX_SUBSTEPS = PHYSICS_MAX_SUBSTEPS;
/**
* Physics-time clock (seconds actually simulated by THIS world instance).
* Kinematic mechanisms must be driven by this clock — never by the domain
* wall clock — because under render lag the stepper burns at most
* MAX_SUBSTEPS per frame and physics time falls behind domain time. Driving
* the pusher from domain time made the paddle sweep through items in a few
* huge jumps (visible as items being smashed/tunneled on slow devices).
* MAX_SUBSTEPS per frame and physics time falls behind domain time.
*/
export const physicsSimClock = { simSec: 0 };
@@ -48,7 +55,11 @@ export interface DropResult {
}
declare global {
interface Window { __DROP_RESULTS?: DropResult[] }
interface Window {
__DROP_RESULTS?: DropResult[];
__PHYSICS_PERF__?: PhysicsPerfSnapshot;
__PHYSICS_PERF_RESET__?: () => void;
}
}
export function recordDropResult(result: DropResult) {
@@ -57,33 +68,65 @@ export function recordDropResult(result: DropResult) {
}
}
function readWorldMeta(world: {
bodies?: { len: () => number };
colliders?: { len: () => number };
}): { activeBodies: number; sleepingBodies: number; colliders: number; contactPairs: number } {
try {
// @react-three/rapier wraps Rapier world; body counts via forEach when available
const w = world as unknown as {
forEachRigidBody?: (cb: (b: { isSleeping: () => boolean; numColliders: () => number }) => void) => void;
bodies?: { len: () => number };
colliders?: { len: () => number };
};
let active = 0;
let sleeping = 0;
let colliders = 0;
if (typeof w.forEachRigidBody === 'function') {
w.forEachRigidBody((b) => {
if (b.isSleeping()) sleeping += 1;
else active += 1;
try {
colliders += b.numColliders();
} catch {
/* ignore */
}
});
} else {
active = w.bodies?.len?.() ?? 0;
colliders = w.colliders?.len?.() ?? 0;
}
return { activeBodies: active, sleepingBodies: sleeping, colliders, contactPairs: 0 };
} catch {
return { activeBodies: 0, sleepingBodies: 0, colliders: 0, contactPairs: 0 };
}
}
/** Steps the Rapier world with a fixed dt, scaled by domain playback speed. */
function RapierStepper({ running, speed }: { running: boolean; speed: number }) {
const { world } = useRapier();
const accumulator = useRef(0);
const perfEnabled = useRef(
typeof window !== 'undefined'
&& new URLSearchParams(window.location.search).get('perf') === '1',
);
const samples = useRef<number[]>([]);
const sampler = useRef(new PhysicsPerfSampler(PHYSICS_DT, MAX_SUBSTEPS));
const perfOn = useRef(false);
// Latch query once (and expose reset) — no React state.
if (typeof window !== 'undefined' && !perfOn.current) {
perfOn.current = isPhysicsPerfQueryEnabled();
if (perfOn.current) {
window.__PHYSICS_PERF_RESET__ = () => sampler.current.reset();
}
}
useFrame((_, delta) => {
if (!running) return;
accumulator.current += Math.min(delta, 0.1) * speed;
let steps = 0;
let framePhysicsMs = 0;
while (accumulator.current >= PHYSICS_DT && steps < MAX_SUBSTEPS) {
if (perfEnabled.current) {
if (perfOn.current) {
const t0 = performance.now();
world.step();
const ms = performance.now() - t0;
samples.current.push(ms);
if (samples.current.length > 600) samples.current.shift();
const sorted = [...samples.current].sort((a, b) => a - b);
(window as unknown as { __PHYSICS_PERF__?: unknown }).__PHYSICS_PERF__ = {
count: samples.current.length,
avgMs: samples.current.reduce((s, v) => s + v, 0) / samples.current.length,
p95Ms: sorted[Math.floor(sorted.length * 0.95)] ?? 0,
maxMs: sorted[sorted.length - 1] ?? 0,
};
framePhysicsMs += performance.now() - t0;
} else {
world.step();
}
@@ -91,6 +134,11 @@ function RapierStepper({ running, speed }: { running: boolean; speed: number })
accumulator.current -= PHYSICS_DT;
steps += 1;
}
if (perfOn.current && steps > 0) {
// Record per-frame physics cost (sum of substeps this frame), not render.
sampler.current.pushStepMs(framePhysicsMs, steps);
window.__PHYSICS_PERF__ = sampler.current.snapshot(readWorldMeta(world));
}
if (steps === MAX_SUBSTEPS) accumulator.current = 0;
});
return null;

View File

@@ -22,8 +22,8 @@ import { resolveItem } from '../data/resolveItem';
describe('demoPlaylist', () => {
it('has classification + safety cases', () => {
expect(PLAYLIST_LENGTH).toBe(11);
expect(DEMO_PLAYLIST.length).toBe(11);
expect(PLAYLIST_LENGTH).toBe(12);
expect(DEMO_PLAYLIST.length).toBe(12);
});
it('has no duplicate case ids', () => {

View File

@@ -56,6 +56,14 @@ export const DEMO_PLAYLIST: PlaylistCase[] = [
scenarioId: 'boundary_dimensions',
expectedCategory: 'C',
},
{
id: 'pouf_c',
title: 'Пуфик (мягкий)',
description: 'Stage 2E runtime visual — soft item → C (min/soft policy)',
itemId: 'SKU-005',
scenarioId: 'boundary_dimensions',
expectedCategory: 'C',
},
{
id: 'plate_d',
title: 'Тарелка',

View File

@@ -1,23 +1,41 @@
/**
* Stage 2C §11.1 — machine-readable runtime ↔ headless physics config hash.
* Stage 2C/2E — machine-readable runtime ↔ headless physics config hash.
* Both paths must consume the same static colliders, pusher geometry, dt, gravity.
* Hash is pure-JS (no Node crypto) so the module stays isomorphic.
*/
import { getStaticColliders } from './physicsWorldLayout';
import { PUSHER } from './pusherMotion';
import { PHYSICS_TIMESTEP_SEC, PHYSICS_GRAVITY } from './physicsTimestep';
import { allVisualPhysicsProfiles } from './visualPhysicsProfiles';
import { SIM_SETTLE_SECONDS } from './physicsDropSim';
import { B_RECEIVER, ROLL_CAGE, ZONES } from './physicalLayout';
export { PHYSICS_TIMESTEP_SEC, PHYSICS_GRAVITY } from './physicsTimestep';
/** Must match SorterPhysics PHYSICS_MAX_SUBSTEPS. */
export const PHYSICS_MAX_SUBSTEPS = 4;
export interface PhysicsConfigSnapshot {
timestep: number;
maxSubsteps: number;
gravity: [number, number, number];
settleSeconds: number;
pusherHalfExtents: [number, number, number];
pusherCenterY: number;
pusherEngage: { x: number; z: number };
pusherTiming: {
strokeLength: number;
strokeSpeed: number;
armDelaySec: number;
holdSec: number;
retractSpeed: number;
homeDistance: number;
};
staticColliderCount: number;
staticColliderIds: string[];
staticColliderFingerprint: string;
skuPhysicsFingerprint: string;
receiverFingerprint: string;
}
function fingerprintColliders(): string {
@@ -46,17 +64,59 @@ function fnv1aHex(input: string): string {
return h.toString(16).padStart(16, '0');
}
function fingerprintSkus(): string {
return allVisualPhysicsProfiles()
.map((p) =>
[
p.sku,
p.approximateMassKg,
p.friction,
p.restitution,
p.linearDamping,
p.angularDamping,
p.collider,
p.colliderAxis ?? 'y',
(p.cuboidHalfExtents ?? []).map((n) => n.toFixed(5)).join(','),
(p.capsule ?? []).map((n) => n.toFixed(5)).join(','),
p.centerOfMassOffsetY,
p.pusherImpulseScale,
p.canRoll ? 1 : 0,
].join('|'),
)
.join(';');
}
function fingerprintReceivers(): string {
return [
`B:${B_RECEIVER.centerX},${B_RECEIVER.centerZ},${B_RECEIVER.width},${B_RECEIVER.depth}`,
`C:${ZONES.C.x},${ZONES.C.z},${ROLL_CAGE.width},${ROLL_CAGE.depth}`,
`D:${ZONES.D.x},${ZONES.D.z},${ROLL_CAGE.width},${ROLL_CAGE.depth}`,
].join('|');
}
export function buildPhysicsConfigSnapshot(timestep: number): PhysicsConfigSnapshot {
const defs = getStaticColliders();
return {
timestep,
maxSubsteps: PHYSICS_MAX_SUBSTEPS,
gravity: PHYSICS_GRAVITY,
settleSeconds: SIM_SETTLE_SECONDS,
pusherHalfExtents: [...PUSHER.halfExtents] as [number, number, number],
pusherCenterY: PUSHER.centerY,
pusherEngage: { x: PUSHER.engageX, z: PUSHER.engageZ },
pusherTiming: {
strokeLength: PUSHER.strokeLength,
strokeSpeed: PUSHER.strokeSpeed,
armDelaySec: PUSHER.armDelaySec,
holdSec: PUSHER.holdSec,
retractSpeed: PUSHER.retractSpeed,
homeDistance: PUSHER.homeDistance,
},
staticColliderCount: defs.length,
staticColliderIds: defs.map((d) => d.id),
staticColliderFingerprint: fingerprintColliders(),
skuPhysicsFingerprint: fingerprintSkus(),
receiverFingerprint: fingerprintReceivers(),
};
}

86
src/domain/physicsPerf.ts Normal file
View File

@@ -0,0 +1,86 @@
/**
* Stage 2E — physics step timing ring buffer (no React state in hot path).
* Exposed via window.__PHYSICS_PERF__ when ?perf=1 or ?physicsPerf=1.
*/
export interface PhysicsPerfSnapshot {
count: number;
avgMs: number;
medianMs: number;
p95Ms: number;
p99Ms: number;
maxMs: number;
over4Ms: number;
over8Ms: number;
lastSubsteps: number;
activeBodies: number;
sleepingBodies: number;
colliders: number;
/** Best-effort contact pairs (0 if API unavailable). */
contactPairs: number;
timestepSec: number;
maxSubsteps: number;
}
const MAX_SAMPLES = 1800;
function percentile(sorted: number[], p: number): number {
if (sorted.length === 0) return 0;
const idx = Math.min(sorted.length - 1, Math.floor(sorted.length * p));
return sorted[idx] ?? 0;
}
export class PhysicsPerfSampler {
private samples: number[] = [];
private lastSubsteps = 0;
readonly timestepSec: number;
readonly maxSubsteps: number;
constructor(timestepSec: number, maxSubsteps: number) {
this.timestepSec = timestepSec;
this.maxSubsteps = maxSubsteps;
}
reset() {
this.samples = [];
this.lastSubsteps = 0;
}
pushStepMs(ms: number, substepsThisFrame: number) {
this.samples.push(ms);
if (this.samples.length > MAX_SAMPLES) this.samples.shift();
this.lastSubsteps = substepsThisFrame;
}
snapshot(worldMeta?: {
activeBodies?: number;
sleepingBodies?: number;
colliders?: number;
contactPairs?: number;
}): PhysicsPerfSnapshot {
const sorted = [...this.samples].sort((a, b) => a - b);
const n = sorted.length;
const sum = this.samples.reduce((s, v) => s + v, 0);
return {
count: n,
avgMs: n ? sum / n : 0,
medianMs: n ? sorted[Math.floor(n * 0.5)] ?? 0 : 0,
p95Ms: percentile(sorted, 0.95),
p99Ms: percentile(sorted, 0.99),
maxMs: n ? sorted[n - 1] ?? 0 : 0,
over4Ms: this.samples.filter((v) => v > 4).length,
over8Ms: this.samples.filter((v) => v > 8).length,
lastSubsteps: this.lastSubsteps,
activeBodies: worldMeta?.activeBodies ?? 0,
sleepingBodies: worldMeta?.sleepingBodies ?? 0,
colliders: worldMeta?.colliders ?? 0,
contactPairs: worldMeta?.contactPairs ?? 0,
timestepSec: this.timestepSec,
maxSubsteps: this.maxSubsteps,
};
}
}
export function isPhysicsPerfQueryEnabled(search = typeof window !== 'undefined' ? window.location.search : ''): boolean {
const q = new URLSearchParams(search.startsWith('?') ? search : `?${search}`);
return q.get('physicsPerf') === '1' || q.get('perf') === '1';
}

View File

@@ -17,6 +17,6 @@ describe('Stage 2D mechanism + performance policy', () => {
it('preserves runtime/headless hash parity', () => {
const p = assertRuntimeHeadlessParity();
expect(p.equal).toBe(true);
expect(p.runtime).toBe('7ee15ad3e879a44a');
expect(p.runtime).toMatch(/^[a-f0-9]{16}$/);
});
});

View File

@@ -1,9 +1,10 @@
/**
* /device-test — compact mobile diagnostic overlay (Stage 2D).
* No PII beyond UA string; for phone smoke / QR checks.
* /device-test — compact mobile diagnostic overlay (Stage 2E).
* No PII beyond UA string; QR contains only public HTTPS URL (no tokens).
*/
import { useEffect, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import QRCode from 'qrcode';
import { decideMobileTier, collectMobileSignals } from '../domain/mobilePolicy';
import { prefer3DByDefault, useWebGLSupport } from '../components/ThreeD/useWebGL';
@@ -35,19 +36,51 @@ function readGl(): GlInfo {
}
}
/** Prefer permanent HTTPS host; fallback documents preferred permanent URL (no tokens). */
function publicTestUrl(): string {
const host = window.location.hostname;
if (host === 'sorter.arhipovdan.ru' || host.endsWith('.trycloudflare.com')) {
return `${window.location.origin}/device-test`;
}
return 'https://sorter.arhipovdan.ru/device-test';
}
export default function DeviceTestPage() {
const webgl = useWebGLSupport();
const [gl, setGl] = useState<GlInfo | null>(null);
const [fps, setFps] = useState(0);
const [qrDataUrl, setQrDataUrl] = useState('');
const [physP95, setPhysP95] = useState<number | null>(null);
const signals = collectMobileSignals();
const tier = decideMobileTier(signals);
const width = typeof window !== 'undefined' ? window.innerWidth : 1200;
const prefer3d = prefer3DByDefault(width, webgl);
const qrTarget = useMemo(() => publicTestUrl(), []);
useEffect(() => {
setGl(readGl());
}, []);
useEffect(() => {
let cancelled = false;
void QRCode.toDataURL(qrTarget, { width: 220, margin: 1, errorCorrectionLevel: 'M' }).then(
(url) => {
if (!cancelled) setQrDataUrl(url);
},
);
return () => {
cancelled = true;
};
}, [qrTarget]);
useEffect(() => {
const id = window.setInterval(() => {
const p = window.__PHYSICS_PERF__;
if (p && p.count > 30) setPhysP95(p.p95Ms);
}, 1000);
return () => window.clearInterval(id);
}, []);
useEffect(() => {
let frames = 0;
let start = performance.now();
@@ -84,8 +117,32 @@ export default function DeviceTestPage() {
>
<h1 style={{ fontSize: 18, marginBottom: 8 }}>Device Test</h1>
<p style={{ opacity: 0.7, marginBottom: 16 }}>
OZON Tech Sorter — Stage 2D diagnostics (no personal data).
OZON Tech Sorter — Stage 2E diagnostics (no personal data).
</p>
<div
data-testid="device-test-qr"
style={{
marginBottom: 20,
padding: 12,
border: '1px solid #1e293b',
borderRadius: 8,
maxWidth: 280,
}}
>
<div style={{ color: '#64748b', marginBottom: 8 }}>Public HTTPS QR</div>
{qrDataUrl ? (
<img src={qrDataUrl} alt="QR for device-test HTTPS URL" width={220} height={220} />
) : (
<div style={{ height: 220, display: 'grid', placeItems: 'center', opacity: 0.5 }}>
Generating QR…
</div>
)}
<div style={{ marginTop: 8, wordBreak: 'break-all', fontSize: 11, color: '#94a3b8' }}>
{qrTarget}
</div>
</div>
<div style={{ display: 'grid', gap: 8, maxWidth: 560 }}>
<Row k="UA" v={ua.slice(0, 140)} />
<Row k="WebGL support" v={webgl ? 'YES' : 'NO'} />
@@ -97,11 +154,25 @@ export default function DeviceTestPage() {
v={typeof window !== 'undefined' ? `${window.innerWidth}×${window.innerHeight}` : '—'}
/>
<Row k="Page FPS (UI)" v={String(fps)} />
<Row
k="Physics p95"
v={physP95 != null ? `${physP95.toFixed(2)} ms` : 'open /?perf=1 to sample'}
/>
<Row k="Telegram WebView" v={isTelegram ? 'YES' : 'NO'} />
<Row k="GL vendor" v={gl?.vendor ?? '…'} />
<Row k="GL renderer" v={gl?.renderer ?? '…'} />
<Row k="WebGL2" v={String(gl?.webgl2 ?? false)} />
<Row k="Software GL" v={String(gl?.software ?? true)} />
<Row k="Orientation" v={typeof screen !== 'undefined' ? String(screen.orientation?.type ?? 'n/a') : '—'} />
<Row
k="Safe-area bottom"
v={
typeof getComputedStyle !== 'undefined'
? getComputedStyle(document.documentElement).getPropertyValue('env(safe-area-inset-bottom)') ||
'0px (CSS env)'
: '—'
}
/>
</div>
<div style={{ marginTop: 24, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
<Link to="/" data-testid="device-test-open-sim" style={{ color: '#38bdf8' }}>