updated 2026-11-26·8 min read
Engine Architecture & Anti-Cheat
Isolated browser execution domains, lock-free SPSC ring buffers, Kalman clock sync, WebGL2 instancing, .itobin/.irep ABIs, and Wing-Kristofferson anti-cheat.
Itô runs under COOP: same-origin and COEP: credentialless (enabling SharedArrayBuffer) with a fixed 64 MB Rust WASM arena where memory.grow is banned, ergo TypedArray views never detach mid-song. Keeping memory static only helps if alignment actually holds across the boundary though, which took one fairly humbling clippy pass to learn the hard way.
Workspace Crates and Current Boundaries
Rust Crates & Live Browser Client
crates/ito-core:#![no_std]physics, ScoreV2 fixed-point math, Wife3 rational Chebyshev accuracy,.irepserialization, and dual-timelineheadless_sim.crates/ito-parser: Zero-allocation byte scanners (memchr,serde_yml), timing sweep-line normalization, 4-stage encoding fallback, and.itobinv2 compiler.crates/ito-audio:#![no_std]WASM SIMDv12832-voice mixer (f32x4) with 32-sample anti-pop linear gain ramp-downs.crates/ito-wasm: Zero-copyTypedArrayviews into the static 64 MB SoA arena (unit-tested in Rust; onlyito_pulse.wasmviaPulseAnalyzer.tsruns in the live web client today while gameplay, parsing, judgement, andItoAudioProcessor.tsuse TypeScript fallbacks and gameplay hitsounds were removed during the HUD pass).
Server Contracts & Unwired Edge Specs
web/input,web/audio,web/render,web/storage: 1000 Hzevent.timeStampcapture,SharedArrayBufferSPSC queue, 2-State Kalman Filter, single-draw-call WebGL2 instancer, and 4-tierStorageDriver.server/src/: Implements the D1 relational schema (schema.ts), stateless HMAC-SHA256 play tickets (tickets.ts), and 4 statistical anti-cheat checks (statistical.ts), paired in contract tests withcrates/ito-core(--no-default-features --features headless).- Still Spec-Only: Hono HTTP routes (
/api/play/init,/api/play/submit), Better-Auth (Discord PKCE + WebAuthn + Ed25519 JWTs), 4-tier rate limiting, R2 replay Deflate blobs,wrangler.toml, and the 80 ms SV teleport reaction gate remain design specs rather than deployed endpoints.
Alignment Traps, 8-Key Replay Limits, and Clock Sync
What started as cleaning up four clippy warnings in the Rust workspace turned up real undefined behavior. crates/ito-audio/src/mixer.rs was casting unaligned pointers for 4-wide v128 SIMD reads because AudioBridge passed 4-byte-aligned [f32; 128] buffers, SampleArena stored unpadded odd-length samples, and read_cursor could land on an odd offset mid-quantum. Worse, crates/ito-wasm/src/engine_bridge.rs cast raw 1-byte-aligned JS &[u8] slices straight to a 64-byte-aligned &ItoBinHeader. Padding SampleArena, enforcing 16-byte alignment on AlignedQuantumBuffer, gating (voice.read_cursor & 3) == 0, and routing header mounts through ItoBinView::validate_and_mount fixed the UB. In the same sweep, VoicePool::select_steal_victim turned out to be stealing live notes instead of dying 32-sample fadeout tails, and expanding HeadlessSimState from 8 to 10 lanes for Pop’n charts hit a hard format wall: .irep v1 packs column indices into 3 bits (0x07), so replays above 8 keys now fail cleanly with UnsupportedKeyCount rather than corrupting bits.
On the browser timing side, AudioContext.currentTime only steps once every 2.667 ms (128 samples at 48 kHz), postMessage into the AudioWorklet triggers GC stutters, and Bluetooth audio handoffs jump output latency by 100 to 200 ms. To bridge that, SPSCCommandQueue.ts puts producer and consumer indices on separate 64-byte cache lines inside a 16,512-byte SharedArrayBuffer, and ClockSynchronizer.ts runs a 2-state Kalman filter with Joseph-form covariance stabilization plus a Page-Hinkley CUSUM detector that hard-resets the filter to the raw timestamp the frame a hardware jump trips the threshold.
SPSC Ring Buffer & Kalman Clock Parameters
- SPSC Cache-Line Isolation (
SPSCCommandQueue.ts):16,512bytes total (0x0064Bwrite_ptr,0x4064Bread_ptr,0x80256 slots x 64B each) usingAtomics.load/store(SeqCst). Slot index usesw & 255and occupancy uses(w - r) >>> 0so 32-bit unsigned wrap-around holds cleanly across . - Kalman Constants (
ClockSynchronizer.ts): State vector (song time and crystal drift ratio near1.0) with ((1.2 ms)^2), , , initial diagonal covariance and , and Joseph-form covariance update . - CUSUM Step Reset & Monotonic Clamp: Page-Hinkley allowance (
0.0015 s) and alarm threshold (0.010 s); tripping the threshold resets , , , and on that same update, whilegetSongTime()clampsmax(lastSongTime, extrapolated). - Anti-Pop Voice Stealing (
crates/ito-audio): Stolen voices apply a 32-sample linear ramp (, at 48 kHz), keeping step discontinuity at0.03125(< 0.05).
WebGL2 Instanced Playfield and the 3D Carousel Fight

Every frame binds one GL_ARRAY_BUFFER with 64-byte instance stride (a_InstancePosSize, a_InstanceTexRect, a_InstanceColor, a_InstanceParams at divisor 1) and draws all visible notes in one gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, activeInstanceCount) call. Non-linear NotITG modcharts (Wave, Drunk, Tipsy, Bumpy, Tornado, Roll, Invert) read from a 144-byte std140 ModifiersUBO, and hold note bodies tessellate into 16 px slices because single-quad holds shear up to 80 px under heavy curves; slicing drops that error below 0.5 px. Because negative scroll velocities break naive monotonic time cursors, charts with SV reversals query a pre-integrated spatial table render_indices_by_y in time.
The 240 Hz 3D fanned song carousel (MenuCarousel.ts) had its own silly race condition: adjacent cards overlap horizontally by 90 px (270 px width on a 180 px step), so CSS :hover and JS .hovered fought each other and popped two cards up simultaneously. Ripping :hover out of CSS and projecting pointers onto a 1D Voronoi runway axis with Schmitt-trigger hysteresis (+-0.08 slots / ~15 px), rAF coalescing for high-polling mice, an 80 ms trackpad quench, and a hover lock above 80 px/s fling velocity (stopping 35 audio previews/sec during fast scrolls) finally settled it.
Binary ABIs (.itobin v2, .irep v1) and ModifiersUBO Layout
.itobinv2: 128-byte dual-cache-lineItoBinHeader(magic = "ITOBIN\x02\x00", IEEE 802.3 CRC32), 16-byteSvSegmentRaw(4 per 64B cache line), 32-byteNoteRawwith camera-relativepos_ybounded in (), and 8-byteKeysoundEntryRawindexing a contiguous UTF-8 string heap, verified at load time inItoBinView::validate_and_mount..irepv1: 64-byteIrepHeader(magic = "IREP",chart_sha256,rate_modifier) followed by 5-bytePackedInputEventrecords (delta_us: u32,flags: u8), checked for payload size () and event density (). Because column indices use 3 bits (0x07), replays above 8 keys are rejected cleanly.ModifiersUBO: 144 bytes (Float32Array(36)):mat4 u_ProjectionMatrixplus fivevec4uniform vectors (Timeline,Wave,Bob,Vortex,Receptor).- 4-Stage Encoding & Storage: Strict UTF-8 -> CP932 (Shift-JIS) -> CP949 (EUC-KR) -> Unicode NFKC;
K = 4audio decode semaphore withxxHash64dedup intoInt16ArrayPCM (329.6 MB,4.21xheap reduction); 4-tierStorageDriver(OPFS Sync -> OPFS Async -> IndexedDB -> In-Memory LRU) guarded bynavigator.locks.
Headless Replay Simulation and Statistical Anti-Cheat
Client score claims aren’t trusted on the verification side. crates/ito-core/src/headless_sim.rs replays submitted .irep tapes using i64 microsecond math (-C target-feature=-relaxed-simd) and advance_to_time dual-timeline sweep-line miss expiration so every note maps to one judgement bucket (EXACT, PERF, GREAT, GOOD, OK, or MISS, with MARVELOUS/BAD aliases kept for telemetry). For replay deduplication, crates/ito-core/src/crypto.rs and server/src/anti_cheat/statistical.ts actually compute SHA-256 rather than the BLAKE3 hash originally drafted in the design docs.
Simple mean and variance checks don’t catch Box-Muller Gaussian cheat bots () because each hit looks independent and normal in 1D. Real human tapping isn’t independent across adjacent notes: under the Wing-Kristofferson (1973) timing model, motor-execution variance produces negative lag-1 serial autocorrelation between consecutive hit errors:
- Biological Variance & Kurtosis Gates (Implemented)
server/src/anti_cheat/statistical.ts requires std dev sigma >= 3.2 ms (rejecting relax hacks) and Pearson kurtosis 2.5 <= K <= 3.5 (rejecting uniform macros at K = 1.80).
- Lilliefors Normality & Wing-Kristofferson Lag-1 (Implemented)
Enforces D_N <= 1.150 / sqrt(N) (alpha = 0.001) and rho(1) <= -0.05 for N > 500 (human baseline near -0.21 vs Box-Muller bots near 0).
- SHA-256 Plagiarism Constraint & Teleport Gate (Partial)
D1 schema enforces UNIQUE(chart_id, judgement_fingerprint) over SHA-256 hit-error digests; the 80 ms SV teleport reaction gate remains spec-only.
Next: Phased Implementation Roadmap or return to Itô Overview.