""" database.py — HUINH V20.9.8.2 Wrapper SQLite async thread-safe avec toutes les tables. """ import asyncio import logging import os import sqlite3 import threading from typing import Any, Dict, List, Optional logger = logging.getLogger("huinh.db") class Database: def __init__(self, path: str = "data/huinh.db"): self.path = path self._lock = threading.Lock() self._conn: Optional[sqlite3.Connection] = None d = os.path.dirname(path) if d: os.makedirs(d, exist_ok=True) # ---------- Init ---------- def init_sync(self): self._conn = sqlite3.connect(self.path, check_same_thread=False) self._conn.row_factory = sqlite3.Row try: self._conn.execute("PRAGMA journal_mode=WAL") self._conn.execute("PRAGMA synchronous=NORMAL") except Exception: pass self._create_tables() logger.info(f"[DB] {self.path} prêt") def _ensure(self): if self._conn is None: self.init_sync() def _create_tables(self): cur = self._conn.cursor() # --- Conversations / messages --- cur.execute("""CREATE TABLE IF NOT EXISTS conversations ( id TEXT PRIMARY KEY, title TEXT, created_at REAL, updated_at REAL )""") cur.execute("""CREATE TABLE IF NOT EXISTS messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, conversation_id TEXT, role TEXT, content TEXT, strategy TEXT, ts REAL )""") cur.execute("CREATE INDEX IF NOT EXISTS idx_msg_cid ON messages(conversation_id, id)") # --- Mémoire --- cur.execute("""CREATE TABLE IF NOT EXISTS episodic ( id INTEGER PRIMARY KEY AUTOINCREMENT, conversation_id TEXT, content TEXT, ts REAL )""") cur.execute("""CREATE TABLE IF NOT EXISTS semantic ( id INTEGER PRIMARY KEY AUTOINCREMENT, topic TEXT, key TEXT, value TEXT, confidence REAL DEFAULT 0.7, source TEXT, ts REAL )""") cur.execute("""CREATE TABLE IF NOT EXISTS procedural ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, code TEXT, ts REAL )""") cur.execute("""CREATE TABLE IF NOT EXISTS hebbian_edges ( id INTEGER PRIMARY KEY AUTOINCREMENT, src TEXT, dst TEXT, weight REAL DEFAULT 1.0, ts REAL )""") # --- Graphe --- cur.execute("""CREATE TABLE IF NOT EXISTS entities ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, type TEXT, ts REAL )""") cur.execute("""CREATE TABLE IF NOT EXISTS relations ( id INTEGER PRIMARY KEY AUTOINCREMENT, subject TEXT, predicate TEXT, object TEXT, confidence REAL DEFAULT 0.6, source_conv TEXT, ts REAL )""") cur.execute("CREATE INDEX IF NOT EXISTS idx_rel_subj ON relations(subject)") cur.execute("CREATE INDEX IF NOT EXISTS idx_rel_obj ON relations(object)") # --- Stats / Feedback / Training --- cur.execute("""CREATE TABLE IF NOT EXISTS strategy_stats ( id INTEGER PRIMARY KEY AUTOINCREMENT, strategy TEXT, success INTEGER, latency_ms REAL, ts REAL )""") cur.execute("""CREATE TABLE IF NOT EXISTS feedback_events ( id INTEGER PRIMARY KEY AUTOINCREMENT, conversation_id TEXT, question TEXT, answer_preview TEXT, strategy TEXT, latency_ms REAL, feedback INTEGER, ts REAL, signature TEXT, status TEXT, created_at REAL )""") cur.execute("""CREATE TABLE IF NOT EXISTS training_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, conversation_id TEXT, user_msg TEXT, assistant_msg TEXT, strategy TEXT, latency_ms REAL, feedback INTEGER, ts REAL )""") cur.execute("""CREATE TABLE IF NOT EXISTS style_examples ( id INTEGER PRIMARY KEY AUTOINCREMENT, example_query TEXT, example_response TEXT, weight REAL DEFAULT 1.0 )""") # --- Mémoire 7 couches --- cur.execute("""CREATE TABLE IF NOT EXISTS memory_layers ( id INTEGER PRIMARY KEY AUTOINCREMENT, layer TEXT NOT NULL, content TEXT NOT NULL, scope TEXT NOT NULL DEFAULT 'session', scope_id TEXT NOT NULL DEFAULT '', confidence REAL DEFAULT 0.7, retention REAL DEFAULT 1.0, embedding BLOB, metadata TEXT DEFAULT '{}', created_at REAL DEFAULT 0, last_accessed REAL DEFAULT 0, user_id TEXT DEFAULT 'default_user' )""") cur.execute("CREATE INDEX IF NOT EXISTS idx_ml_layer ON memory_layers(layer)") cur.execute("CREATE INDEX IF NOT EXISTS idx_ml_scope ON memory_layers(scope, scope_id)") # --- RAG vectoriel (manquait) --- cur.execute("""CREATE TABLE IF NOT EXISTS encyclopedia_chunks ( id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT NOT NULL, metadata TEXT DEFAULT '{}', embedding BLOB, source_url TEXT DEFAULT '', ts REAL )""") cur.execute("CREATE INDEX IF NOT EXISTS idx_chunks_source ON encyclopedia_chunks(source_url)") # --- Benchmark --- cur.execute("""CREATE TABLE IF NOT EXISTS bench_runs_v2 ( run_id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT NOT NULL, suite TEXT, version TEXT NOT NULL, questions_count INTEGER, modes TEXT, duration_ms INTEGER, baseline_acc REAL, huinh_no_sch_acc REAL, huinh_acc REAL, report_json TEXT )""") cur.execute("""CREATE TABLE IF NOT EXISTS bench_results_v2 ( id INTEGER PRIMARY KEY AUTOINCREMENT, run_id TEXT, question_id TEXT, category TEXT, mode TEXT, strategy TEXT, passed INTEGER, latency_ms INTEGER, answer TEXT, expected TEXT, error TEXT, reasoning TEXT, rag_context TEXT, memory_context TEXT, sch_branches TEXT, system_prompt TEXT )""") cur.execute("CREATE INDEX IF NOT EXISTS idx_br_run ON bench_results_v2(run_id)") self._conn.commit() # ---------- API sync ---------- def _execute_sync(self, sql: str, params: tuple = ()): self._ensure() with self._lock: cur = self._conn.cursor() cur.execute(sql, params) self._conn.commit() return cur.lastrowid def _fetch_sync(self, sql: str, params: tuple = ()) -> List[Dict[str, Any]]: self._ensure() with self._lock: cur = self._conn.cursor() cur.execute(sql, params) rows = cur.fetchall() return [dict(r) for r in rows] # ---------- API async ---------- async def execute(self, sql: str, params: tuple = ()): return await asyncio.to_thread(self._execute_sync, sql, params) async def fetch(self, sql: str, params: tuple = ()) -> List[Dict[str, Any]]: return await asyncio.to_thread(self._fetch_sync, sql, params) async def fetchone(self, sql: str, params: tuple = ()) -> Optional[Dict[str, Any]]: rows = await self.fetch(sql, params) return rows[0] if rows else None def close(self): with self._lock: if self._conn: try: self._conn.close() except Exception: pass self._conn = None