"""Site-owned SQLite business schema for the LeetCode offline clone. The vendored ``websitebench.site_backend`` runtime owns the shared library tables (site binding, mail jobs, payment ledger) and ``websitebench.local_clone_auth`` owns accounts, sessions and verification flows. Everything below is this site's own business state, held in the same site-bound database file: * ``leetcode_questions`` — the seeded local question catalogue * ``leetcode_profiles`` — username/account binding created during signup * ``leetcode_drafts`` — the editor buffer per (member, question, language) * ``leetcode_submissions`` — every graded submission, server-side * ``leetcode_progress`` — solved / attempted status per member Migrations are forward-only, recorded in ``leetcode_schema_migrations`` and safe to re-run. Seeding is deterministic: the catalogue is rewritten from :mod:`leetcode_app.content` on every boot, and every generated timestamp comes from a fixed base clock plus a row counter, never from the wall clock. """ from __future__ import annotations import json import sqlite3 import threading from contextlib import closing from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any from backend.site_backend_integration import open_site_services from websitebench.local_clone_auth import LocalAuthStore from websitebench.site_backend import SiteBackend from . import content from .content import Question SITE_ID = "leetcode" # One fixed base clock for the whole clone, so an identical operation sequence # always produces identical stored state. BASE_CLOCK = datetime(2026, 8, 20, 9, 0, 0, tzinfo=UTC) STEP_SECONDS = 61 SOLVED = "solved" ATTEMPTED = "attempted" _MIGRATIONS: dict[str, str] = { "0001_catalogue": """ CREATE TABLE IF NOT EXISTS leetcode_questions ( slug TEXT PRIMARY KEY, number INTEGER NOT NULL UNIQUE, title TEXT NOT NULL, difficulty TEXT NOT NULL CHECK (difficulty IN ('Easy', 'Medium', 'Hard')), category TEXT NOT NULL, topics_json TEXT NOT NULL, companies_json TEXT NOT NULL, languages_json TEXT NOT NULL, acceptance REAL NOT NULL CHECK (acceptance >= 0), frequency INTEGER NOT NULL CHECK (frequency BETWEEN 0 AND 100), contest_point INTEGER NOT NULL CHECK (contest_point >= 0), detail_json TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_leetcode_questions_category ON leetcode_questions (category, number); """, "0002_members": """ CREATE TABLE IF NOT EXISTS leetcode_profiles ( subject_id TEXT PRIMARY KEY, account_id TEXT NOT NULL UNIQUE, username TEXT NOT NULL, username_normalized TEXT NOT NULL UNIQUE, email_normalized TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL ); """, "0003_work": """ CREATE TABLE IF NOT EXISTS leetcode_drafts ( subject_id TEXT NOT NULL, question_slug TEXT NOT NULL, language TEXT NOT NULL, source TEXT NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY (subject_id, question_slug, language) ); CREATE TABLE IF NOT EXISTS leetcode_submissions ( id INTEGER PRIMARY KEY, subject_id TEXT NOT NULL, question_slug TEXT NOT NULL, language TEXT NOT NULL, status TEXT NOT NULL, message TEXT NOT NULL DEFAULT '', passed INTEGER NOT NULL CHECK (passed >= 0), total INTEGER NOT NULL CHECK (total >= 0), runtime_ms INTEGER, memory_mb REAL, runtime_percentile REAL, memory_percentile REAL, failing_input TEXT, failing_output TEXT, failing_expected TEXT, source TEXT NOT NULL, created_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_leetcode_submissions_member ON leetcode_submissions (subject_id, id DESC); CREATE INDEX IF NOT EXISTS idx_leetcode_submissions_question ON leetcode_submissions (subject_id, question_slug, id DESC); CREATE TABLE IF NOT EXISTS leetcode_progress ( subject_id TEXT NOT NULL, question_slug TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('solved', 'attempted')), first_solved_at TEXT, last_submitted_at TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0), PRIMARY KEY (subject_id, question_slug) ); """, } _BUSINESS_TABLES = ( "leetcode_progress", "leetcode_submissions", "leetcode_drafts", "leetcode_profiles", ) _SERVICES_LOCK = threading.Lock() _SERVICES: tuple[SiteBackend, LocalAuthStore] | None = None # --------------------------------------------------------------------------- # lifecycle # --------------------------------------------------------------------------- def services() -> tuple[SiteBackend, LocalAuthStore]: """Process-wide bound backend + auth pair with the business schema ready.""" global _SERVICES with _SERVICES_LOCK: if _SERVICES is None: backend, auth = open_site_services() migrate(backend.lifecycle.database_path) seed_catalogue(backend.lifecycle.database_path) _SERVICES = (backend, auth) return _SERVICES def close_services() -> None: global _SERVICES with _SERVICES_LOCK: _SERVICES = None def database_path() -> Path: return services()[0].lifecycle.database_path def _connect(path: Path) -> sqlite3.Connection: connection = sqlite3.connect(str(path), timeout=15) connection.row_factory = sqlite3.Row connection.execute("PRAGMA foreign_keys = ON") connection.execute("PRAGMA busy_timeout = 5000") return connection def connect() -> sqlite3.Connection: return _connect(database_path()) def migrate(path: Path) -> list[str]: """Apply every pending forward migration. Safe to run repeatedly.""" applied_now: list[str] = [] with closing(_connect(path)) as connection, connection: connection.execute( """ CREATE TABLE IF NOT EXISTS leetcode_schema_migrations ( migration_id TEXT PRIMARY KEY, applied_at TEXT NOT NULL ) """ ) applied = { str(row["migration_id"]) for row in connection.execute( "SELECT migration_id FROM leetcode_schema_migrations" ) } for migration_id, ddl in _MIGRATIONS.items(): if migration_id in applied: continue connection.executescript(ddl) connection.execute( "INSERT INTO leetcode_schema_migrations (migration_id, applied_at)" " VALUES (?, ?)", (migration_id, BASE_CLOCK.isoformat().replace("+00:00", "Z")), ) applied_now.append(migration_id) return applied_now def applied_migrations(path: Path | None = None) -> list[str]: target = path or database_path() with closing(_connect(target)) as connection: return [ str(row["migration_id"]) for row in connection.execute( "SELECT migration_id FROM leetcode_schema_migrations" " ORDER BY migration_id" ) ] def seed_catalogue(path: Path) -> int: """Write the deterministic question catalogue. Idempotent by slug.""" rows = [ ( item.slug, item.number, item.title, item.difficulty, item.category, json.dumps(list(item.topics), separators=(",", ":")), json.dumps(list(item.companies), separators=(",", ":")), json.dumps(list(item.languages), separators=(",", ":")), item.acceptance, item.frequency, item.contest_point, json.dumps( content.detail_payload(item), separators=(",", ":"), sort_keys=True ), ) for item in content.iter_questions() ] with closing(_connect(path)) as connection, connection: connection.executemany( """ INSERT INTO leetcode_questions ( slug, number, title, difficulty, category, topics_json, companies_json, languages_json, acceptance, frequency, contest_point, detail_json ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(slug) DO UPDATE SET number = excluded.number, title = excluded.title, difficulty = excluded.difficulty, category = excluded.category, topics_json = excluded.topics_json, companies_json = excluded.companies_json, languages_json = excluded.languages_json, acceptance = excluded.acceptance, frequency = excluded.frequency, contest_point = excluded.contest_point, detail_json = excluded.detail_json """, rows, ) return len(rows) def reset() -> None: """Clear member state and re-seed. Used by tests and the reset endpoint.""" backend, auth = services() def _site_reset(connection: sqlite3.Connection) -> None: for table in _BUSINESS_TABLES: connection.execute(f"DELETE FROM {table}") backend.lifecycle.reset_embedded(connection, confirm_site_id=SITE_ID) auth.reset_site_state(site_reset=_site_reset, seed_accounts=[]) seed_catalogue(backend.lifecycle.database_path) # --------------------------------------------------------------------------- # deterministic clock # --------------------------------------------------------------------------- def _stamp(connection: sqlite3.Connection) -> str: row = connection.execute("SELECT COUNT(*) FROM leetcode_submissions").fetchone() sequence = int(row[0]) if row is not None else 0 moment = BASE_CLOCK + timedelta(seconds=STEP_SECONDS * sequence) return moment.isoformat().replace("+00:00", "Z") def profile_stamp(connection: sqlite3.Connection) -> str: row = connection.execute("SELECT COUNT(*) FROM leetcode_profiles").fetchone() sequence = int(row[0]) if row is not None else 0 moment = BASE_CLOCK + timedelta(seconds=STEP_SECONDS * sequence) return moment.isoformat().replace("+00:00", "Z") # --------------------------------------------------------------------------- # catalogue reads # --------------------------------------------------------------------------- def _question_row(row: sqlite3.Row) -> dict[str, Any]: return { "slug": row["slug"], "number": int(row["number"]), "title": row["title"], "difficulty": row["difficulty"], "category": row["category"], "topics": json.loads(row["topics_json"]), "companies": json.loads(row["companies_json"]), "languages": json.loads(row["languages_json"]), "acceptance": float(row["acceptance"]), "frequency": int(row["frequency"]), "contest_point": int(row["contest_point"]), "detail": json.loads(row["detail_json"]), } def question_count() -> int: with closing(connect()) as connection: row = connection.execute("SELECT COUNT(*) FROM leetcode_questions").fetchone() return int(row[0]) if row is not None else 0 def load_question(slug: str) -> dict[str, Any] | None: with closing(connect()) as connection: row = connection.execute( "SELECT * FROM leetcode_questions WHERE slug = ?", (slug,) ).fetchone() return _question_row(row) if row is not None else None def catalogue_question(slug: str) -> Question | None: """The in-process question object used by the verdict model.""" return content.question(slug) # --------------------------------------------------------------------------- # member profiles # --------------------------------------------------------------------------- def normalize_username(username: str) -> str: return " ".join(username.split()).casefold() def username_taken(username: str) -> bool: with closing(connect()) as connection: return ( connection.execute( "SELECT 1 FROM leetcode_profiles WHERE username_normalized = ?", (normalize_username(username),), ).fetchone() is not None ) def create_profile( connection: sqlite3.Connection, *, account_id: str, username: str, email: str, ) -> str: """Create the business member row inside the auth store's transaction.""" subject_id = f"member_{normalize_username(username)}" connection.execute( """ INSERT INTO leetcode_profiles ( subject_id, account_id, username, username_normalized, email_normalized, created_at ) VALUES (?, ?, ?, ?, ?, ?) """, ( subject_id, account_id, username, normalize_username(username), email, profile_stamp(connection), ), ) return subject_id def profile_for_email(email: str) -> dict[str, Any] | None: with closing(connect()) as connection: row = connection.execute( "SELECT * FROM leetcode_profiles WHERE email_normalized = ?", (email.strip().casefold(),), ).fetchone() return dict(row) if row is not None else None def profile_for_username(username: str) -> dict[str, Any] | None: with closing(connect()) as connection: row = connection.execute( "SELECT * FROM leetcode_profiles WHERE username_normalized = ?", (normalize_username(username),), ).fetchone() return dict(row) if row is not None else None def profile_for_subject(subject_id: str) -> dict[str, Any] | None: with closing(connect()) as connection: row = connection.execute( "SELECT * FROM leetcode_profiles WHERE subject_id = ?", (subject_id,) ).fetchone() return dict(row) if row is not None else None def resolve_login_email(identifier: str) -> str: """Map a username-or-email login identifier onto the account email.""" candidate = identifier.strip() if "@" in candidate: return candidate.casefold() profile = profile_for_username(candidate) if profile is None: # Keep the failure path indistinguishable: hand the auth store a # syntactically valid address that owns no account. return "unknown-member@leetcode.invalid" return str(profile["email_normalized"]) # --------------------------------------------------------------------------- # drafts # --------------------------------------------------------------------------- def save_draft(subject_id: str, slug: str, language: str, source: str) -> str: with closing(connect()) as connection, connection: updated_at = profile_stamp(connection) connection.execute( """ INSERT INTO leetcode_drafts ( subject_id, question_slug, language, source, updated_at ) VALUES (?, ?, ?, ?, ?) ON CONFLICT(subject_id, question_slug, language) DO UPDATE SET source = excluded.source, updated_at = excluded.updated_at """, (subject_id, slug, language, source, updated_at), ) return updated_at def load_draft(subject_id: str, slug: str, language: str) -> dict[str, Any] | None: with closing(connect()) as connection: row = connection.execute( "SELECT source, updated_at FROM leetcode_drafts" " WHERE subject_id = ? AND question_slug = ? AND language = ?", (subject_id, slug, language), ).fetchone() return dict(row) if row is not None else None # --------------------------------------------------------------------------- # submissions and progress # --------------------------------------------------------------------------- def record_submission( subject_id: str, slug: str, language: str, source: str, verdict: Any, ) -> dict[str, Any]: """Persist one graded submission and update the member's progress.""" failing = verdict.failing with closing(connect()) as connection, connection: connection.execute("BEGIN IMMEDIATE") created_at = _stamp(connection) cursor = connection.execute( """ INSERT INTO leetcode_submissions ( subject_id, question_slug, language, status, message, passed, total, runtime_ms, memory_mb, runtime_percentile, memory_percentile, failing_input, failing_output, failing_expected, source, created_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( subject_id, slug, language, verdict.status, verdict.message, verdict.passed, verdict.total, verdict.runtime_ms, verdict.memory_mb, verdict.runtime_percentile, verdict.memory_percentile, failing.input if failing is not None else None, failing.output if failing is not None else None, failing.expected if failing is not None else None, source, created_at, ), ) submission_id = int(cursor.lastrowid or 0) solved = verdict.status == "Accepted" existing = connection.execute( "SELECT status, first_solved_at, attempts FROM leetcode_progress" " WHERE subject_id = ? AND question_slug = ?", (subject_id, slug), ).fetchone() attempts = (int(existing["attempts"]) if existing is not None else 0) + 1 first_solved_at = existing["first_solved_at"] if existing is not None else None if solved and first_solved_at is None: first_solved_at = created_at status = SOLVED if (solved or first_solved_at is not None) else ATTEMPTED connection.execute( """ INSERT INTO leetcode_progress ( subject_id, question_slug, status, first_solved_at, last_submitted_at, attempts ) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(subject_id, question_slug) DO UPDATE SET status = excluded.status, first_solved_at = excluded.first_solved_at, last_submitted_at = excluded.last_submitted_at, attempts = excluded.attempts """, (subject_id, slug, status, first_solved_at, created_at, attempts), ) return {"submission_id": submission_id, "created_at": created_at} def submission(subject_id: str, submission_id: int) -> dict[str, Any] | None: with closing(connect()) as connection: row = connection.execute( "SELECT * FROM leetcode_submissions WHERE id = ? AND subject_id = ?", (submission_id, subject_id), ).fetchone() return dict(row) if row is not None else None def submissions( subject_id: str, *, slug: str | None = None, limit: int = 20, offset: int = 0, ) -> list[dict[str, Any]]: query = ( "SELECT s.*, q.title, q.number FROM leetcode_submissions s" " JOIN leetcode_questions q ON q.slug = s.question_slug" " WHERE s.subject_id = ?" ) parameters: list[Any] = [subject_id] if slug is not None: query += " AND s.question_slug = ?" parameters.append(slug) query += " ORDER BY s.id DESC LIMIT ? OFFSET ?" parameters.extend([limit, offset]) with closing(connect()) as connection: return [dict(row) for row in connection.execute(query, parameters)] def submission_count(subject_id: str, *, slug: str | None = None) -> int: query = "SELECT COUNT(*) FROM leetcode_submissions WHERE subject_id = ?" parameters: list[Any] = [subject_id] if slug is not None: query += " AND question_slug = ?" parameters.append(slug) with closing(connect()) as connection: row = connection.execute(query, parameters).fetchone() return int(row[0]) if row is not None else 0 def progress_map(subject_id: str | None) -> dict[str, str]: if not subject_id: return {} with closing(connect()) as connection: return { str(row["question_slug"]): str(row["status"]) for row in connection.execute( "SELECT question_slug, status FROM leetcode_progress" " WHERE subject_id = ?", (subject_id,), ) } def progress_summary(subject_id: str | None) -> dict[str, Any]: """Solved/attempted counts by difficulty, plus the totals shown on /progress/.""" totals = {"Easy": 0, "Medium": 0, "Hard": 0} solved = {"Easy": 0, "Medium": 0, "Hard": 0} attempted = {"Easy": 0, "Medium": 0, "Hard": 0} with closing(connect()) as connection: for row in connection.execute( "SELECT difficulty, COUNT(*) AS total FROM leetcode_questions" " GROUP BY difficulty" ): totals[str(row["difficulty"])] = int(row["total"]) if subject_id: for row in connection.execute( """ SELECT q.difficulty AS difficulty, p.status AS status, COUNT(*) AS total FROM leetcode_progress p JOIN leetcode_questions q ON q.slug = p.question_slug WHERE p.subject_id = ? GROUP BY q.difficulty, p.status """, (subject_id,), ): bucket = solved if str(row["status"]) == SOLVED else attempted bucket[str(row["difficulty"])] = int(row["total"]) submissions_total = ( submission_count(subject_id) if subject_id else 0 ) accepted_total = 0 if subject_id: row = connection.execute( "SELECT COUNT(*) FROM leetcode_submissions" " WHERE subject_id = ? AND status = 'Accepted'", (subject_id,), ).fetchone() accepted_total = int(row[0]) if row is not None else 0 return { "totals": totals, "solved": solved, "attempted": attempted, "total_questions": sum(totals.values()), "total_solved": sum(solved.values()), "total_attempted": sum(attempted.values()), "submissions": submissions_total, "accepted": accepted_total, "acceptance_rate": ( round(accepted_total * 100 / submissions_total, 1) if submissions_total else 0.0 ), } def last_submitted_map(subject_id: str | None) -> dict[str, str]: if not subject_id: return {} with closing(connect()) as connection: return { str(row["question_slug"]): str(row["last_submitted_at"]) for row in connection.execute( "SELECT question_slug, last_submitted_at FROM leetcode_progress" " WHERE subject_id = ?", (subject_id,), ) }