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 viajose(createRemoteJWKSetin_authGuard.ts), while telemetry writes (POST /api/v1/sessions/telemetry) validatesessionIdagainsttest_sessionsand append rows toitem_telemetry. - Three parent batteries:
ist-battery,ist-battery-unpad-1973, andutbk-snbthold subtests under parent battery modules, queried throughidx_module_items_mod_sub_idx(module_id, subtest_id, item_index). - Unencrypted JWKS & candidate bridging: Signing keys in
jwksstay unencrypted (disablePrivateKeyEncryption: true) so edge isolates don’t desync on key decryption, andensureCandidateRecordmirrorsuser(id)intocandidates(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
| Table | Primary Key | Purpose & Key Columns |
|---|---|---|
modules | id | Canonical parent batteries (track_id, delivery_engine, scoring_type, item_count, pacing_target_seconds, subtests_json, target_benchmark, administered_language). |
module_localizations | module_id, locale | Indonesian and English metadata overlays (title, subtitle, description, heuristic_exploit, overview_md, sources_md). |
module_items | id | Calibrated item bank (module_id, subtest_id, item_index, prompt, response_type, options_json, correct_option_id, prompt_svg, a_param, b_param, c_param). |
candidates | id | Canonical examinee record bridging OAuth/guest identities (auth_provider, provider_uid, handle, email_hash, is_anonymous). |
test_sessions | id | Exam 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_telemetry | id | Append-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_stats | candidate_id | Aggregated streaks, ELO ratings, duel totals, latest_deviation_iq, highest_deviation_iq, latest_utbk_score, highest_utbk_score, and mean_solve_latency_ms. |
candidate_preferences | candidate_id | Pacing mode ('standard'), preferred_locale ('en'), and show_stats_ribbon flag. |
candidate_daily_activity | candidate_id, activity_date | Daily calendar rollup of items_completed and sessions_completed. |
viewed_modules | id (unique candidate_id, module_id) | Recently accessed module history (module_id, title, viewed_at). |
migration_tombstones | id (unique client_uuid) | Deduplication record for historical localStorage session imports (imported_sessions_count, migrated_epoch_ms). |
Authentication Tables (Better Auth) & Migrations
| Table | Category | Primary Key | Role |
|---|---|---|---|
user | auth | id | Authenticated profile records (name, email, emailVerified, isAnonymous, handle). |
account | auth | id | OAuth/credential linkage (providerId, accountId, accessToken, refreshToken, idToken). |
session | auth | id | Active session records (token, expiresAt, ipAddress, userAgent, userId). |
verification | auth | id | Email verification tokens and OTP challenges (identifier, value, expiresAt). |
jwks | auth | id | JSON Web Key Set holding active public and private signing keys (alg, crv). |
_schema_migrations | system | version | Applied 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:
- 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.
- 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.
- 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 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:
- Single-subtest quarantine: Practicing a single subtest returns
deviationIq = null(for IST) andcompositeScore = null(for UTBK-SNBT), so a 20-item practice run can’t masquerade as a full IQ or UTBK composite (irtScoring.ts,finish.ts). - IST curve fix: Earlier synthetic curves mapped the Unpad senior mean (
84/192) all the way up to (, a bump) and clamped factors to[80, 120].normsEvaluator.tsreplaces those with linear z-score tables (generateSmoothedTable(84.0, 16.5, 192), clamped to[70, 140]) so84/192lands cleanly at and (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 directly underflows double precision (). The 41-node quadrature ([-4.0, +4.0]) clamps probabilities to with , clamps to , and subtracts before exponentiation:
Closed Algebraic Templates (src/data/utbk/aig/)
- Closed Quadratic Class: Parity-matched roots () guarantee integer vertices , , and positive square discriminants .
- Closed Linear System Class: systems with apply a unit perturbation (), yielding , then project backward from integer coordinates .
- Kinematics & Rate Closures: Coprime factors produce strictly positive integer durations , , .
Runner Ergonomics & Focus Guards
- Workspace layout:
ModuleRunPage.tsxuses a single main column (1fr) stacked vertically (passage above prompt stem and choices) next to a260pxQuestion Navigator sidebar on#181818dark surfaces (#e5e5e5passage text,#a3a3a3metadata,#fbbf24flagged state). - Preventing accidental submits: Unbinds
Spacefrom advancing questions (EnterorArrowRightadvances 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.tsflagsdwellTimeMs < 200(andtrajectoryStraightness > 0.985oractuationJitterMs < 5.0on mouse clicks), whilefinish.tsmarks non-practice sessionsis_verified = 0when mean dwell time drops below150msor over50%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.