lietzsche;flynn

updated 2026-11-26·10 min read

Database & Empirical Evaluation

Turso libSQL schema, auth and session split, sealed-key grading, log-domain IRT fixes, and random-seed item generators.

Running an exam site on Turso libSQL sounds straightforward until half your random algebra seeds emit placeholder distractors, an early norm curve pushes an average score to IQ 127, and a duplicate migration filename leaves orphaned tables sitting in production. Most of Flynn’s backend work went into keeping user login separate from live exam writes, sealing correct_option_id until submit, and cleaning up those scoring and generator bugs.

How the Backend Splits

Flynn keeps user identity, live exam telemetry, and schema changes out of each other’s way:

  • Auth vs. session grading: Better Auth stays on /api/auth/*. Session creation (POST /api/v1/sessions/start) verifies Better Auth JWTs via jose (createRemoteJWKSet in _authGuard.ts), while telemetry writes (POST /api/v1/sessions/telemetry) validate sessionId against test_sessions and append rows to item_telemetry.
  • Three parent batteries: ist-battery, ist-battery-unpad-1973, and utbk-snbt hold subtests under parent battery modules, queried through idx_module_items_mod_sub_idx(module_id, subtest_id, item_index).
  • Unencrypted JWKS & candidate bridging: Signing keys in jwks stay unencrypted (disablePrivateKeyEncryption: true) so edge isolates don’t desync on key decryption, and ensureCandidateRecord mirrors user(id) into candidates(id) before session writes.

Early on, shipping loose standalone subtest modules (ist-wu, ist-fa) alongside a duplicate 0021 migration prefix collision left orphaned plural auth tables (accounts, sessions, verifications, jwks_keys) and broken module counts sitting in Turso. Numbered migrations tracked in _schema_migrations (scripts/migrate.cjs) eventually consolidated everything under the 3 parent batteries (0024) and dropped the dead plural tables (0027, 0028).

Edge Database Schema (Turso libSQL)

The schema separates Better Auth identity tables (user, account, session, verification, jwks) from psychometric tables (candidates, modules, module_localizations, module_items, test_sessions, item_telemetry, candidate_stats, candidate_preferences, candidate_daily_activity, viewed_modules, migration_tombstones) and _schema_migrations.

user ──< account
 │
 └──< session

candidates ──< test_sessions ──< item_telemetry
    ├──< candidate_daily_activity
    ├─── candidate_preferences
    ├─── candidate_stats
    ├──< viewed_modules
    └──< migration_tombstones

modules ──< module_items
   └──< module_localizations
Reference: Application, Auth & System Table Catalog (17 tables)

Application Tables

TablePrimary KeyPurpose & Key Columns
modulesidCanonical parent batteries (track_id, delivery_engine, scoring_type, item_count, pacing_target_seconds, subtests_json, target_benchmark, administered_language).
module_localizationsmodule_id, localeIndonesian and English metadata overlays (title, subtitle, description, heuristic_exploit, overview_md, sources_md).
module_itemsidCalibrated item bank (module_id, subtest_id, item_index, prompt, response_type, options_json, correct_option_id, prompt_svg, a_param, b_param, c_param).
candidatesidCanonical examinee record bridging OAuth/guest identities (auth_provider, provider_uid, handle, email_hash, is_anonymous).
test_sessionsidExam attempt state machine (candidate_id, client_session_uuid, session_type, battery_id, master_seed, attempt_index, status, total_raw_score, composite_standardwert, deviation_iq, start_epoch_ms, end_epoch_ms).
item_telemetryidAppend-only interaction telemetry (session_id, subtest_id, item_id, item_index, submitted_answer, is_correct, points_awarded, dwell_time_ms, bot_flag, trajectory_straightness, actuation_jitter_ms, window_blur_count).
candidate_statscandidate_idAggregated streaks, ELO ratings, duel totals, latest_deviation_iq, highest_deviation_iq, latest_utbk_score, highest_utbk_score, and mean_solve_latency_ms.
candidate_preferencescandidate_idPacing mode ('standard'), preferred_locale ('en'), and show_stats_ribbon flag.
candidate_daily_activitycandidate_id, activity_dateDaily calendar rollup of items_completed and sessions_completed.
viewed_modulesid (unique candidate_id, module_id)Recently accessed module history (module_id, title, viewed_at).
migration_tombstonesid (unique client_uuid)Deduplication record for historical localStorage session imports (imported_sessions_count, migrated_epoch_ms).

Authentication Tables (Better Auth) & Migrations

TableCategoryPrimary KeyRole
userauthidAuthenticated profile records (name, email, emailVerified, isAnonymous, handle).
accountauthidOAuth/credential linkage (providerId, accountId, accessToken, refreshToken, idToken).
sessionauthidActive session records (token, expiresAt, ipAddress, userAgent, userId).
verificationauthidEmail verification tokens and OTP challenges (identifier, value, expiresAt).
jwksauthidJSON Web Key Set holding active public and private signing keys (alg, crv).
_schema_migrationssystemversionApplied migrations table (name, checksum, applied_at_epoch_ms, execution_time_ms).
Core SQL Queries: Telemetry, Subtests & Localized Overlays
-- 1. Telemetry Insertion (append-only)
INSERT INTO item_telemetry (
  id, session_id, subtest_id, item_id, item_index,
  submitted_answer, is_correct, points_awarded, dwell_time_ms,
  render_epoch_ms, submit_epoch_ms, bot_flag,
  trajectory_straightness, actuation_jitter_ms, window_blur_count
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);

-- 2. Battery Subtest Item Traversal
SELECT id, module_id, subtest_id, item_index, prompt, response_type,
       options_json, correct_option_id, prompt_svg, irt_difficulty,
       irt_discrimination, prompt_image_uri, a_param, b_param, c_param
FROM module_items
WHERE module_id = ? AND subtest_id = ?
ORDER BY item_index ASC;

-- 3. Localized Module Retrieval with Overlay Fallback
SELECT
  m.id, m.track_id, m.category,
  COALESCE(ml.title, m.title) AS title,
  COALESCE(ml.subtitle, m.subtitle) AS subtitle,
  COALESCE(ml.description, m.description) AS description,
  COALESCE(ml.heuristic_exploit, m.heuristic_exploit) AS heuristic_exploit,
  m.delivery_engine, m.scoring_type, m.item_count,
  m.pacing_target_seconds, m.is_featured, m.status,
  m.banner_image, m.subtests_json, m.tags_json, m.target_benchmark,
  COALESCE(ml.overview_md, m.overview_md) AS overview_md,
  COALESCE(ml.sources_md, m.sources_md) AS sources_md,
  m.administered_language, m.supported_locales_json
FROM modules m
LEFT JOIN module_localizations ml
  ON m.id = ml.module_id AND ml.locale = ?
WHERE m.status = 'active'
ORDER BY m.is_featured DESC, m.id ASC;

Keeping Answer Keys Sealed Until Submit

To stop anyone from scraping correct_option_id out of the network tab mid-test, grading runs strictly on the edge:

  1. Phase 1: Live exam (keys stay on the server)

    start.ts queries prompts, options, and stimulus SVGs without correct_option_id, applies Attempt 2+ procedural overlays, and shuffles eligible options.

  2. Phase 2: Deterministic replay and scoring

    finish.ts re-runs applyProceduralSessionOverlay and resolveSelectedCanonicalId from master_seed, scores IST or UTBK responses, checks bot flags in item_telemetry, and persists test_sessions.

  3. Phase 3: Subtest breakdown and A4 PDF report

    The client receives aggregate raw scores, Standardwert / Deviation IQ (or EAP theta and 200-1000 UTBK scaled scores), and subtest breakdowns to render scorecards and printable PDFs.

Scoring & Generator Fixes

Stopping Float Underflow and the +1.8σ+1.8\sigma Norm Bump

Multiplying 160 probabilities directly during a full UTBK simulation underflows IEEE 754 floats fast, so irtScoring.ts sums log-likelihoods instead and subtracts the peak log-likelihood before exponentiating back out (see UTBK-SNBT Item Response Theory).

Two other calibration bugs needed fixing so reported scores stayed honest:

  1. Single-subtest quarantine: Practicing a single subtest returns deviationIq = null (for IST) and compositeScore = null (for UTBK-SNBT), so a 20-item practice run can’t masquerade as a full IQ or UTBK composite (irtScoring.ts, finish.ts).
  2. IST +1.8σ+1.8\sigma curve fix: Earlier synthetic curves mapped the Unpad senior mean (84/192) all the way up to SW=118SW = 118 (IQ=127\text{IQ} = 127, a +1.8σ+1.8\sigma bump) and clamped factors to [80, 120]. normsEvaluator.ts replaces those with linear z-score tables (generateSmoothedTable(84.0, 16.5, 192), clamped to [70, 140]) so 84/192 lands cleanly at SW=100SW = 100 and Deviation IQ=100\text{Deviation IQ} = 100 (see Amthauer IST-70).

Fixing Broken Distractors on Random Seeds

My first distractor generator matched bare numbers with a regex (normCorrect.match(/^-?\d+(?:\.\d+)?$/)), which broke completely the moment an answer was wrapped in LaTeX ("$18$") or carried a unit ("4 jam"). Nearly half of random PK linear-system seeds (48.83%, or 4,883/10,000), 17.24% of quadratic Vieta seeds, and 26.36% of PM kinematics seeds (21,090/80,000) fell back to placeholder strings.

Swapping that out in src/data/utbk/aig/algebraicEquivalence.ts (buildMultipleChoiceOptions) meant two things: writing closed integer templates for quadratics, linear systems, and rate problems so random SplitMix32 seeds always stay solvable in clean integers, and adding dedicated distractor branches for plain numbers, $...$ LaTeX strings, $(x, y)$ coordinates, unit-suffixed values, and Rp currency strings.

Math: Log-Domain Stabilization & Closed AIG Templates

Log-Domain IRT Stabilization

Across a 160-item UTBK battery, multiplying L(u∣θk)L(\mathbf{u} \mid \theta_k) directly underflows double precision (≈2.22×10−16\approx 2.22 \times 10^{-16}). The 41-node quadrature ([-4.0, +4.0]) clamps probabilities to [ϵ,1−ϵ][\epsilon, 1-\epsilon] with ϵ=10−12\epsilon = 10^{-12}, clamps zi(θ)=−1.702ai(θ−bi)z_i(\theta) = -1.702 a_i (\theta - b_i) to [−50.0,+50.0][-50.0, +50.0], and subtracts M=max⁡0≤j≤40ln⁡L(θj)\mathcal{M} = \max_{0 \le j \le 40} \ln L(\theta_j) before exponentiation:

L~(θk)=exp⁡(ln⁡L(θk)−M)∈(0.0,1.0]\tilde{L}(\theta_k) = \exp\left(\ln L(\theta_k) - \mathcal{M}\right) \in (0.0, 1.0]

Closed Algebraic Templates (src/data/utbk/aig/)

  • Closed Quadratic Class: Parity-matched roots r1=2k1+p,  r2=2k2+pr_1 = 2k_1 + p, \; r_2 = 2k_2 + p (p∈{0,1},k1≠k2p \in \{0, 1\}, k_1 \neq k_2) guarantee integer vertices xv=k1+k2+p∈Zx_v = k_1 + k_2 + p \in \mathbb{Z}, yv=−a(k1−k2)2∈Zy_v = -a(k_1 - k_2)^2 \in \mathbb{Z}, and positive square discriminants Δ=[2a(k1−k2)]2≥4\Delta = [2a(k_1 - k_2)]^2 \ge 4.
  • Closed Linear System Class: 2×22 \times 2 systems with det⁡(A)=0\det(A) = 0 apply a unit perturbation b2′=b2+δb_2' = b_2 + \delta (δ∈{−1,+1}\delta \in \{-1, +1\}), yielding det⁡(A)new=±a1≠0\det(A)_{\text{new}} = \pm a_1 \neq 0, then project (c1,c2)(c_1, c_2) backward from integer coordinates (x0,y0)∈Z2(x_0, y_0) \in \mathbb{Z}^2.
  • Kinematics & Rate Closures: Coprime factors (m,n)(m, n) produce strictly positive integer durations ttogether=Hmnt_{\text{together}} = Hmn, tA=Hn(m+n)t_A = Hn(m+n), tB=Hm(m+n)t_B = Hm(m+n).

Runner Ergonomics & Focus Guards

  • Workspace layout: ModuleRunPage.tsx uses a single main column (1fr) stacked vertically (passage above prompt stem and choices) next to a 260px Question Navigator sidebar on #181818 dark surfaces (#e5e5e5 passage text, #a3a3a3 metadata, #fbbf24 flagged state).
  • Preventing accidental submits: Unbinds Space from advancing questions (Enter or ArrowRight advances instead) and opens a pre-submission review modal (showing answered, unanswered, and flagged counts with jump links) before final submit.
  • Focus checks and bot flags: In Take Mode, exiting fullscreen or blurring the window triggers an "Exam Window Defocused" overlay with a 15-second grace timer and strike counter (Strike X of 3). On the edge, telemetry.ts flags dwellTimeMs < 200 (and trajectoryStraightness > 0.985 or actuationJitterMs < 5.0 on mouse clicks), while finish.ts marks non-practice sessions is_verified = 0 when mean dwell time drops below 150ms or over 50% of responses are flagged.
Primary Sources: Psychometric & Ergonomic References
  • Amthauer, R. (1953, 1970). I-S-T: Intelligenz-Struktur-Test & Handanweisung IST-70 (4th ed.). Hogrefe.
  • Bejar, I. I. (1993). A generative approach to psychological and educational measurement. Test Analysis for Computer-Based Measurement, 323-357.
  • Birnbaum, A. (1968). Some latent trait models and their use in inferring an examinee’s ability. Statistical Theories of Mental Test Scores, 395-479.
  • Bock, R. D., & Mislevy, R. J. (1982). Adaptive EAP estimation of ability in a microcomputer environment. Applied Psychological Measurement, 6(4), 431-444.
  • Hambleton, R. K., & Swaminathan, H. (1985). Item Response Theory: Principles and Applications. Kluwer-Nijhoff.
  • Irvine, S. H., & Kyllonen, P. C. (Eds.). (2002). Generating Items for Cognitive Tests: Theory and Practice. Lawrence Erlbaum Associates.
  • Liepmann, D., Beauducel, A., Brocke, B., & Amthauer, R. (2007). Intelligenz-Struktur-Test 2000 R (I-S-T 2000 R): Manual (2nd ed.). Hogrefe.
  • Lord, F. M. (1980). Applications of Item Response Theory to Practical Testing Problems. Lawrence Erlbaum Associates.

See Platform Architecture for the client-side SplitMix32 PRNG and sendBeacon telemetry, and Privacy & Telemetry for data fields and statutory rights.

Search wiki and portfolio

type to search across all entries.