lietzsche;ito
Pages

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, .irep serialization, and dual-timeline headless_sim.
  • crates/ito-parser: Zero-allocation byte scanners (memchr, serde_yml), timing sweep-line normalization, 4-stage encoding fallback, and .itobin v2 compiler.
  • crates/ito-audio: #![no_std] WASM SIMD v128 32-voice mixer (f32x4) with 32-sample anti-pop linear gain ramp-downs.
  • crates/ito-wasm: Zero-copy TypedArray views into the static 64 MB SoA arena (unit-tested in Rust; only ito_pulse.wasm via PulseAnalyzer.ts runs in the live web client today while gameplay, parsing, judgement, and ItoAudioProcessor.ts use 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 Hz event.timeStamp capture, SharedArrayBuffer SPSC queue, 2-State Kalman Filter, single-draw-call WebGL2 instancer, and 4-tier StorageDriver.
  • 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 with crates/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,512 bytes total (0x00 64B write_ptr, 0x40 64B read_ptr, 0x80 256 slots x 64B each) using Atomics.load/store (SeqCst). Slot index uses w & 255 and occupancy uses (w - r) >>> 0 so 32-bit unsigned wrap-around holds cleanly across 2322^{32}.
  • Kalman Constants (ClockSynchronizer.ts): State vector x=[τ,s]Tx = [\tau, s]^T (song time and crystal drift ratio near 1.0) with R=1.44×10−6 s2R = 1.44 \times 10^{-6}\text{ s}^2 ((1.2 ms)^2), qτ=1.0×10−8 s2/sq_\tau = 1.0 \times 10^{-8}\text{ s}^2/\text{s}, qs=1.0×10−12 s−1q_s = 1.0 \times 10^{-12}\text{ s}^{-1}, initial diagonal covariance P00=1.44×10−6P_{00} = 1.44 \times 10^{-6} and P11=1.0×10−6P_{11} = 1.0 \times 10^{-6}, and Joseph-form covariance update P=(I−KH)Ppred(I−KH)T+KRKTP = (I - KH)P_{\text{pred}}(I - KH)^T + KRK^T.
  • CUSUM Step Reset & Monotonic Clamp: Page-Hinkley allowance ν=1.5 ms\nu = 1.5\text{ ms} (0.0015 s) and alarm threshold h=10.0 msh = 10.0\text{ ms} (0.010 s); tripping the threshold resets τ=zk\tau = z_k, s=1.0s = 1.0, P00=RP_{00} = R, and P11=1.0×10−6P_{11} = 1.0 \times 10^{-6} on that same update, while getSongTime() clamps max(lastSongTime, extrapolated).
  • Anti-Pop Voice Stealing (crates/ito-audio): Stolen voices apply a 32-sample linear ramp g(n)=1.0−n/32g(n) = 1.0 - n/32 (n∈[0,31]n \in [0, 31], ≈0.667 ms\approx 0.667\text{ ms} at 48 kHz), keeping step discontinuity at 0.03125 (< 0.05).
Active 4K WebGL2 playfield on Lagtrain rendered with single-draw-call instanced quads and hit-error meter
single-draw-call webgl2 instanced playfield rendering 64-byte instance structs and hit-error meter telemetry.

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 O(log⁡N+K)O(\log N + K) 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
  • .itobin v2: 128-byte dual-cache-line ItoBinHeader (magic = "ITOBIN\x02\x00", IEEE 802.3 CRC32), 16-byte SvSegmentRaw (4 per 64B cache line), 32-byte NoteRaw with camera-relative pos_y bounded in [−100,000,100,000][-100{,}000, 100{,}000] (ULP=0.0078125 units\text{ULP} = 0.0078125\text{ units}), and 8-byte KeysoundEntryRaw indexing a contiguous UTF-8 string heap, verified at load time in ItoBinView::validate_and_mount.
  • .irep v1: 64-byte IrepHeader (magic = "IREP", chart_sha256, rate_modifier) followed by 5-byte PackedInputEvent records (delta_us: u32, flags: u8), checked for payload size (≤256 KB\le 256\text{ KB}) and event density (M≤3NnotesM \le 3 N_{\text{notes}}). Because column indices use 3 bits (0x07), replays above 8 keys are rejected cleanly.
  • ModifiersUBO: 144 bytes (Float32Array(36)): mat4 u_ProjectionMatrix plus five vec4 uniform vectors (Timeline, Wave, Bob, Vortex, Receptor).
  • 4-Stage Encoding & Storage: Strict UTF-8 -> CP932 (Shift-JIS) -> CP949 (EUC-KR) -> Unicode NFKC; K = 4 audio decode semaphore with xxHash64 dedup into Int16Array PCM (329.6 MB, 4.21x heap reduction); 4-tier StorageDriver (OPFS Sync -> OPFS Async -> IndexedDB -> In-Memory LRU) guarded by navigator.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 (Z0=−2ln⁡U1cos⁡(2πU2)Z_0 = \sqrt{-2\ln U_1}\cos(2\pi U_2)) 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:

ρ(1)=∑i=1N−1(ei−eˉ)(ei+1−eˉ)∑i=1N(ei−eˉ)2=−σm22(σc2+σm2)∈[−0.50,−0.05]\rho(1) = \frac{\sum_{i=1}^{N-1} (e_i - \bar{e})(e_{i+1} - \bar{e})}{\sum_{i=1}^N (e_i - \bar{e})^2} = -\frac{\sigma_m^2}{2(\sigma_c^2 + \sigma_m^2)} \in [-0.50, -0.05]
  1. 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).

  2. 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).

  3. 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.

Search wiki and portfolio

type to search across all entries.