lietzsche;flynn

updated 2026-11-26·5 min read

Platform Architecture

How Flynn runs exams locally without lag, authenticates sessions, keeps timers honest, and generates deterministic seeds.

When a number-series subtest gives you 25 seconds per item, waiting 120ms to 450ms for an API roundtrip every time you click “Next” ruins pacing fast. I kept clicks instant by running the entire exam runner locally in the browser while handing auth, telemetry beacons, and final grading to Cloudflare Pages Functions and Turso, so flaky school Wi-Fi doesn’t eat your timer. See Getting Started for user modes and Database & Empirical Evaluation for the Turso schema.

Stack Overview

LayerStackWhat It DoesFail-Safe
UIReact 19 + Tailwind CSS v4Single-shell views, 100dvh exam lockLocal client state
SimulationTypeScriptProcedural AIG, SO(3)SO(3) cubes, figure SVGsDeterministic math
Edge AuthCloudflare Pages Functions + Better AuthOAuth/guest sessions, 4h JWTs, JWKS cacheGuest UUID fallback
Telemetrynavigator.sendBeacon + fetch keepaliveAnswer choices, render-to-click dwell timesNon-blocking fallback
DatabaseTurso (libSQL)User profiles, item banks, session resultsLocalStorage fallback

Auth vs. Session Grading

Auth (/api/auth/*)

Handles Google and GitHub OAuth 2.0 PKCE login, anonymous guest linking, and 4-hour JWT minting via Better Auth.

Session Grading (/api/v1/sessions/*)

Handles session creation, telemetry logging, and deterministic server-side grading on Turso.

Short-lived 15-minute tokens don’t survive a 195-minute UTBK-SNBT simulation or an 86-minute I-S-T 2000R battery. Because of that, auth.ts configures Better Auth’s jwt() plugin with a 4-hour expiration (240 minutes), and _authGuard.ts caches the JWKS endpoint via jose (createRemoteJWKSet) in edge memory to verify bearer tokens when starting a session.

  1. Start session and derive master seed

    POST /api/v1/sessions/start creates a test_sessions row, generates a 32-bit master_seed, runs Attempt 2+ procedural overlays, and strips correct_option_id.

  2. Simulate locally at zero latency

    The client renders prompts, SVG geometry, and an isolated UTC-anchored countdown leaf without waiting on network roundtrips.

  3. Stream non-blocking telemetry beacons

    Answer selections send dwell_time_ms and pointer signals via navigator.sendBeacon (or keepalive fetch) to /api/v1/sessions/telemetry.

  4. Re-simulate and grade on completion

    POST /api/v1/sessions/finish replays the procedural overlay and option shuffle from master_seed on the server and stores final scores.

Focus Mode and Background-Safe Timers

When you enter Take Mode (/take), Flynn hides the sidebar and top header and locks the viewport shell to h-[100dvh] so you can’t misclick out of an exam.

Timers anchor to a fixed UTC deadline instead of trusting setInterval ticks, for browsers throttle setInterval as soon as you switch tabs. ExamTimer computes deadlineTimestamp - Date.now() on every tick inside a memo-isolated leaf component: if you minimize the window or switch tabs, the deadline stays put and the clock catches up immediately when focus returns, without re-rendering the question text or SVG canvas every second.

Telemetry and Bot Checks

Every option click fires asynchronously via navigator.sendBeacon('/api/v1/sessions/telemetry', payload), falling back to fetch with { keepalive: true } if sendBeacon isn’t available or returns false (TursoEdgeAdapter.ts). Question transitions never wait on network I/O (see Privacy & Telemetry for the exact fields stored).

To catch automated scripts, Flynn checks response timing and pointer geometry:

  • Dwell time (render to click): ModuleRunPage.tsx measures performance.now() from item render to selection and logs a warning under 25ms. On the server, telemetry.ts sets bot_flag = 1 when dwellTimeMs < 200, and finish.ts marks non-practice sessions is_verified = 0 if average dwell time falls below 150ms or more than half of items are flagged.
  • Mouse geometry and jitter: For non-touch, non-keyboard clicks, telemetry.ts also flags trajectoryStraightness > 0.985 or actuationJitterMs < 5.0.
Flynn infinite canvas workspace showing interactive frames and bottom floating toolbars for undo, redo, new box, text, and marker
the /canvas infinite grid workspace providing pan-and-zoom scratch boxes alongside quantitative and spatial drills.

Deterministic Seeds with SplitMix32

Sending answer keys down to the browser lets anyone inspect the network tab mid-test, so correct_option_id stays on the server. Instead, both the client and edge workers share a single 32-bit master_seed and run a SplitMix32 PRNG: when you submit, POST /api/v1/sessions/finish replays the exact procedural Attempt 2+ variants and option shuffles from that seed without trusting client-side keys.

Implementation & Math: SplitMix32 Deterministic PRNG (src/data/ist/aig/prng/splitmix32.ts)

Both client and edge generators derive itemSeed = hashSeed(masterSeed, subtestId, itemIndex) and step via the golden-ratio Weyl recurrence:

St+1=(St+γ)(mod232),γ=0x9E3779B9=⌊232⋅(5−1)/2⌋S_{t+1} = (S_t + \gamma) \pmod{2^{32}}, \quad \gamma = \text{0x9E3779B9} = \lfloor 2^{32} \cdot (\sqrt{5} - 1) / 2 \rfloor

export class SplitMix32 {
  private state: number

  constructor(seed: number) {
    this.state = seed | 0
  }

  public next(): number {
    this.state = (this.state + 0x9e3779b9) | 0
    let z = this.state
    z = Math.imul(z ^ (z >>> 16), 0x21f0aaad)
    z = Math.imul(z ^ (z >>> 15), 0x735a2d97)
    return (z ^ (z >>> 15)) >>> 0
  }

  public nextFloat(): number {
    return this.next() / 4294967296
  }

  public nextInt(min: number, max: number): number {
    return min + Math.floor(this.nextFloat() * (max - min + 1))
  }
}

Option shuffling skips items where order carries meaning (isOptionShuffleEligible in start.ts): IST FA, WU, and MA visual options, IELTS True/False/Not Given, UTBK PK Data Sufficiency and Quantity Comparison (P vs Q), options that reference other choice letters (A and B), and monotonic numeric choices on SAT-tagged modules. (SAT and IELTS never shipped as active modules, albeit the shuffle guard stayed in start.ts.)

Search wiki and portfolio

type to search across all entries.