Repository Public
1# =============================================================================2# SP BOUCHER | INFRASTRUCTURE & AUTOMATION3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : MacLustr LLM API7# File : src/maclustr_llm/db.py8# Description : SQLite (WAL) derrière un fil dédié + migrations9# numérotées.10# Module : maclustr_llm11# Repository : https://git.spboucher.ai/maclustr-llm12# Created : 2026-11-1913# Last Modified : 2026-11-1914#15# Author : Simon-Pierre Boucher16# Position : Professor of Finance17# Institution : Université du Québec en Outaouais (UQO)18# Organization : SP Boucher19# Website : https://spboucher.ai20# Git : https://git.spboucher.ai21#22# Preferred Contact: admin@spboucher.ai23# Technical Contact: dev@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""SQLite (WAL) derrière un fil dédié + migrations numérotées.4243Une seule connexion d'écriture, sérialisée par un exécuteur à un fil : pas de verrou applicatif à gérer,44et aucune requête SQL ne bloque la boucle asyncio.45"""4647from __future__ import annotations4849import asyncio50import sqlite351from collections.abc import Callable52from concurrent.futures import ThreadPoolExecutor53from pathlib import Path54from typing import TypeVar5556T = TypeVar("T")5758MIGRATIONS: list[tuple[int, str]] = [59 (60 1,61 """62 CREATE TABLE admin_users (63 id TEXT PRIMARY KEY, handle TEXT NOT NULL UNIQUE, created_at INTEGER NOT NULL,64 singleton INTEGER NOT NULL DEFAULT 1 UNIQUE CHECK (singleton = 1)65 );66 CREATE TABLE passkeys (67 id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES admin_users(id),68 credential_id BLOB NOT NULL UNIQUE, public_key BLOB NOT NULL, sign_count INTEGER NOT NULL,69 transports TEXT, aaguid TEXT, device_type TEXT, backed_up INTEGER NOT NULL DEFAULT 0,70 name TEXT NOT NULL, created_at INTEGER NOT NULL, last_used_at INTEGER71 );72 CREATE TABLE setup_tokens (73 id TEXT PRIMARY KEY, token_hash TEXT NOT NULL UNIQUE, purpose TEXT NOT NULL,74 created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, used_at INTEGER75 );76 CREATE TABLE challenges (77 id TEXT PRIMARY KEY, challenge BLOB NOT NULL, purpose TEXT NOT NULL, user_id TEXT,78 setup_token_id TEXT, session_hash TEXT, created_at INTEGER NOT NULL,79 expires_at INTEGER NOT NULL, used_at INTEGER80 );81 CREATE TABLE sessions (82 id_hash TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES admin_users(id),83 csrf_hash TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL,84 last_seen_at INTEGER NOT NULL, reauth_at INTEGER NOT NULL, ip TEXT, user_agent TEXT,85 revoked_at INTEGER86 );87 CREATE TABLE api_keys (88 id TEXT PRIMARY KEY, name TEXT NOT NULL, app TEXT NOT NULL DEFAULT '',89 prefix TEXT NOT NULL, key_hash TEXT NOT NULL UNIQUE, priority TEXT NOT NULL DEFAULT 'client',90 models TEXT NOT NULL DEFAULT '["*"]', endpoints TEXT NOT NULL DEFAULT '["*"]',91 rpm INTEGER NOT NULL DEFAULT 60, tpm INTEGER NOT NULL DEFAULT 200000,92 daily_tokens INTEGER NOT NULL DEFAULT 0, monthly_tokens INTEGER NOT NULL DEFAULT 0,93 max_concurrency INTEGER NOT NULL DEFAULT 4,94 expires_at INTEGER, disabled INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL,95 revoked_at INTEGER, last_used_at INTEGER, rotated_from TEXT96 );97 CREATE TABLE usage_minute (98 bucket INTEGER NOT NULL, key_id TEXT NOT NULL, model TEXT NOT NULL, endpoint TEXT NOT NULL,99 requests INTEGER NOT NULL DEFAULT 0, errors INTEGER NOT NULL DEFAULT 0,100 prompt_tokens INTEGER NOT NULL DEFAULT 0, completion_tokens INTEGER NOT NULL DEFAULT 0,101 cached_tokens INTEGER NOT NULL DEFAULT 0, sum_ttft_ms INTEGER NOT NULL DEFAULT 0,102 n_ttft INTEGER NOT NULL DEFAULT 0, sum_latency_ms INTEGER NOT NULL DEFAULT 0,103 sum_gen_ms INTEGER NOT NULL DEFAULT 0, sum_queue_ms INTEGER NOT NULL DEFAULT 0,104 PRIMARY KEY (bucket, key_id, model, endpoint)105 ) WITHOUT ROWID;106 CREATE TABLE request_log (107 id TEXT PRIMARY KEY, ts INTEGER NOT NULL, key_id TEXT NOT NULL, model TEXT NOT NULL,108 endpoint TEXT NOT NULL, status INTEGER NOT NULL, error_code TEXT, stream INTEGER NOT NULL,109 prompt_tokens INTEGER NOT NULL DEFAULT 0, completion_tokens INTEGER NOT NULL DEFAULT 0,110 cached_tokens INTEGER NOT NULL DEFAULT 0, queue_ms INTEGER NOT NULL DEFAULT 0,111 ttft_ms INTEGER, latency_ms INTEGER NOT NULL DEFAULT 0, tps REAL, engine TEXT112 );113 CREATE INDEX request_log_ts ON request_log (ts);114 CREATE TABLE audit_log (115 id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER NOT NULL, actor TEXT NOT NULL,116 event TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '{}', ip TEXT117 );118 CREATE INDEX audit_log_ts ON audit_log (ts);119 CREATE TABLE sys_samples (ts INTEGER PRIMARY KEY, sample TEXT NOT NULL) WITHOUT ROWID;120 CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;121 """,122 ),123]124125126class Database:127 def __init__(self, path: Path) -> None:128 self.path = path129 self._pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="mllm-db")130 self._conn: sqlite3.Connection | None = None131132 def _connect(self) -> sqlite3.Connection:133 if self._conn is None:134 self.path.parent.mkdir(parents=True, exist_ok=True)135 conn = sqlite3.connect(self.path, isolation_level=None, check_same_thread=False)136 conn.row_factory = sqlite3.Row137 conn.execute("PRAGMA journal_mode=WAL")138 conn.execute("PRAGMA synchronous=NORMAL")139 conn.execute("PRAGMA foreign_keys=ON")140 conn.execute("PRAGMA busy_timeout=5000")141 self._conn = conn142 return self._conn143144 def migrate_sync(self) -> int:145 conn = self._connect()146 conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at INTEGER)")147 done = {r[0] for r in conn.execute("SELECT version FROM schema_migrations")}148 applied = 0149 for version, sql in MIGRATIONS:150 if version in done:151 continue152 conn.executescript(153 "BEGIN;\n" + sql + f"\nINSERT INTO schema_migrations VALUES ({version}, strftime('%s','now'));\nCOMMIT;"154 )155 applied += 1156 try:157 self.path.chmod(0o600)158 except OSError:159 pass160 return applied161162 def run_sync(self, fn: Callable[[sqlite3.Connection], T]) -> T:163 return self._pool.submit(lambda: fn(self._connect())).result()164165 async def run(self, fn: Callable[[sqlite3.Connection], T]) -> T:166 loop = asyncio.get_running_loop()167 return await loop.run_in_executor(self._pool, lambda: fn(self._connect()))168169 async def tx(self, fn: Callable[[sqlite3.Connection], T]) -> T:170 """Exécute fn dans une transaction IMMEDIATE (atomique vis-à-vis des autres écritures)."""171172 def wrapped(conn: sqlite3.Connection) -> T:173 conn.execute("BEGIN IMMEDIATE")174 try:175 out = fn(conn)176 except BaseException:177 conn.execute("ROLLBACK")178 raise179 conn.execute("COMMIT")180 return out181182 return await self.run(wrapped)183184 async def migrate(self) -> int:185 loop = asyncio.get_running_loop()186 return await loop.run_in_executor(self._pool, self.migrate_sync)187188 def close(self) -> None:189 def _close() -> None:190 if self._conn is not None:191 self._conn.close()192 self._conn = None193194 self._pool.submit(_close).result()195 self._pool.shutdown(wait=True)196