import datetime import json import logging import os import shutil import sqlite3 from sqlalchemy import create_engine, event from sqlalchemy.engine.url import make_url from sqlalchemy.orm import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import NullPool logger = logging.getLogger(__name__) _data_dir = os.path.join(os.path.dirname(__file__), "data") os.makedirs(_data_dir, exist_ok=True) SQLALCHEMY_DATABASE_URL = os.environ.get("DATABASE_URL", f"sqlite:///{_data_dir}/inventory.db") # Accept managed-Postgres connection strings exactly as the provider console # hands them out (Neon/Supabase emit `postgresql://`, Heroku-style tooling # `postgres://`); SQLAlchemy needs the driver spelled out to pick psycopg3. if SQLALCHEMY_DATABASE_URL.startswith("postgres://"): SQLALCHEMY_DATABASE_URL = "postgresql+psycopg://" + SQLALCHEMY_DATABASE_URL[len("postgres://"):] elif SQLALCHEMY_DATABASE_URL.startswith("postgresql://"): SQLALCHEMY_DATABASE_URL = "postgresql+psycopg://" + SQLALCHEMY_DATABASE_URL[len("postgresql://"):] # Tables that hold only derived/analytics data. If corruption is confined to # one of these, it is safe to drop the table and let create_all rebuild it # empty; business data lives elsewhere. _EXPENDABLE_TABLES = {"page_views", "access_logs"} def _quick_check(db_path: str) -> list[str]: con = sqlite3.connect(db_path) try: try: return [row[0] for row in con.execute("PRAGMA quick_check")] except sqlite3.DatabaseError as exc: return [str(exc)] finally: con.close() def _drop_expendable_tables(db_path: str, broken: set) -> None: """Surgical fix: delete the broken tables' schema entries and VACUUM.""" con = sqlite3.connect(db_path) try: con.executescript( "PRAGMA writable_schema=ON;\n" + "".join(f"DELETE FROM sqlite_master WHERE tbl_name='{t}';\n" for t in broken) + "PRAGMA writable_schema=OFF;" ) finally: con.close() con = sqlite3.connect(db_path) try: con.execute("VACUUM") finally: con.close() def _salvage_rebuild(db_path: str) -> None: """Last resort: copy every readable table into a fresh file and swap it in. Tables (or row ranges) whose pages are gone are logged as lost; the original file stays behind as .corrupt.bak for offline forensics, and nightly backup-YYYY-MM-DD.db snapshots on the same volume are the fallback if a business table turns out to have lost rows. """ rebuilt = db_path + ".rebuilt" if os.path.exists(rebuilt): os.remove(rebuilt) src = sqlite3.connect(db_path) dst = sqlite3.connect(rebuilt) lost: list[str] = [] try: # Disables schema validation so sqlite_master and healthy tables stay # readable even when another table's schema entry is broken. src.execute("PRAGMA writable_schema=ON") entries = src.execute( "SELECT type, name, sql FROM sqlite_master " "WHERE sql IS NOT NULL ORDER BY CASE type WHEN 'table' THEN 0 ELSE 1 END" ).fetchall() for type_, name, sql in entries: if name.startswith("sqlite_"): continue if type_ != "table": # Indexes/triggers/views are derivable; ignore failures. try: dst.execute(sql) except sqlite3.Error: pass continue try: dst.execute(sql) cur = src.execute(f'SELECT * FROM "{name}"') except sqlite3.Error as exc: lost.append(f"{name}: table unreadable ({exc})") continue placeholders = ",".join("?" * len(cur.description)) insert = f'INSERT INTO "{name}" VALUES ({placeholders})' copied = 0 while True: try: rows = cur.fetchmany(1000) except sqlite3.DatabaseError as exc: lost.append(f"{name}: truncated at {copied} rows ({exc})") break if not rows: break dst.executemany(insert, rows) copied += len(rows) dst.commit() check = [row[0] for row in dst.execute("PRAGMA quick_check")] if check != ["ok"]: raise RuntimeError(f"salvage rebuild is itself corrupt: {check}") finally: dst.close() src.close() for suffix in ("-wal", "-shm"): if os.path.exists(db_path + suffix): os.remove(db_path + suffix) os.replace(rebuilt, db_path) if lost: logger.error( "Salvage rebuild of %s finished with data loss: %s. " "Original file kept at .corrupt.bak; nightly backup-*.db snapshots " "on the same volume hold pre-crash copies of business data.", db_path, "; ".join(lost), ) # Served data is now known-partial: persist the incident so the System # Health card shows it until recovery, instead of pretending normality. record_integrity_incident("salvage-loss", [f"salvage of {os.path.basename(db_path)}"] + lost) else: logger.warning("Salvage rebuild of %s completed with no data loss.", db_path) def _repair_malformed_sqlite(db_path: str) -> None: """Self-heal a corrupt SQLite file so the app can boot. A container swap that kills the process before the WAL is checkpointed can corrupt the db (seen in prod as 'malformed database schema (page_views) - invalid rootpage'). Strategy: if the damage is confined to expendable analytics tables, drop them surgically; otherwise — or if the surgical fix fails — rebuild the file from every readable table. """ if not os.path.exists(db_path): return problems = _quick_check(db_path) if problems == ["ok"]: return # Preserve every corrupt copy for forensics, timestamped so a second # incident never silently discards its pre-salvage original (learned the # hard way: incident 2's original was lost because a .corrupt.bak from # incident 1 already occupied the fixed name). stamp = datetime.datetime.utcnow().strftime("%Y%m%d-%H%M%S") backup_path = f"{db_path}.corrupt-{stamp}.bak" shutil.copy2(db_path, backup_path) logger.warning("Corrupt SQLite file %s (%s); backup at %s.", db_path, problems, backup_path) broken = {t for t in _EXPENDABLE_TABLES if any(t in p for p in problems)} if broken and all(any(t in p for t in broken) for p in problems): try: _drop_expendable_tables(db_path, broken) if _quick_check(db_path) == ["ok"]: logger.warning("Repair OK: dropped %s; create_all rebuilds them empty.", sorted(broken)) return logger.warning("Surgical drop left the file corrupt; falling back to salvage rebuild.") except sqlite3.Error: logger.exception("Surgical drop failed; falling back to salvage rebuild.") _salvage_rebuild(db_path) check = _quick_check(db_path) if check != ["ok"]: raise RuntimeError(f"{db_path} still corrupt after salvage rebuild: {check}") # --- Local-mirror mode ------------------------------------------------------- # HF Spaces persistent storage (/data) is a FUSE-mounted bucket without the # POSIX locking/mmap semantics SQLite needs: running the live db there # corrupted it twice (2026-08-17/18), the second time in mid-operation under # concurrent BI reads + audit writes with no restart involved. So the live db # runs on container-local disk, and the bucket only holds durable copies: # newest copy pulled at boot, consistent snapshots pushed back via the online # backup API (periodic job in main.py + shutdown hook). # # SQLITE_LOCAL_MIRROR: "1" force on, "0" force off, unset/auto = on when the # db path lives under /data (the HF bucket mount; local dev and the compose # volume use other paths and keep running in place). PERSISTENT_DB_PATH: str | None = None # set when mirroring; backup.py targets its folder _LOCAL_MIRROR_DIR = "/tmp/gateway-db" def _should_mirror(db_path: str) -> bool: flag = os.environ.get("SQLITE_LOCAL_MIRROR", "auto").lower() if flag in ("1", "true"): return True if flag in ("0", "false"): return False return db_path.startswith("/data/") def _activate_local_mirror(persist_path: str) -> str: """Copy the bucket's db to local disk and return the local live path. If a local file already exists (backend restarted inside the same container, e.g. the runtime self-heal restart in main.py), it is at least as fresh as the bucket copy — keep it when healthy/repairable instead of overwriting it with a snapshot up to 5 minutes older. """ os.makedirs(_LOCAL_MIRROR_DIR, exist_ok=True) local_path = os.path.join(_LOCAL_MIRROR_DIR, os.path.basename(persist_path)) if os.path.exists(local_path): try: _repair_malformed_sqlite(local_path) if _quick_check(local_path) == ["ok"]: logger.warning( "SQLite local-mirror active: keeping existing local db %s " "(fresher than bucket copy %s).", local_path, persist_path) return local_path except Exception: logger.exception("Existing local db unrecoverable; pulling bucket copy.") for suffix in ("", "-wal", "-shm"): if os.path.exists(local_path + suffix): os.remove(local_path + suffix) # Fallback chain over the bucket copies: main if healthy, else the .prev # copy from the sync before (losing ≤10 min beats salvage-losing tables), # and a salvage rebuild of main only as last resort. main, prev = persist_path, persist_path + ".prev" src = None if os.path.exists(main) and _quick_check(main) == ["ok"]: src = main elif os.path.exists(prev) and _quick_check(prev) == ["ok"]: if os.path.exists(main): stamp = datetime.datetime.utcnow().strftime("%Y%m%d-%H%M%S") shutil.copy2(main, f"{main}.corrupt-{stamp}.bak") logger.error( "Bucket main copy is corrupt; restoring from .prev (the sync " "before last). Corrupt main preserved as .corrupt-*.bak.") record_integrity_incident( "restored-prev", ["durable main copy corrupt at boot; promoted the .prev copy — " "up to ~10 minutes of writes before the crash may be missing"], severity="warning", ) src = prev elif os.path.exists(main): _repair_malformed_sqlite(main) src = main if src: shutil.copy2(src, local_path) if src == main: for suffix in ("-wal", "-shm"): if os.path.exists(main + suffix): shutil.copy2(main + suffix, local_path + suffix) _log_persistent_inventory(os.path.dirname(persist_path), local_path) logger.warning("SQLite local-mirror active: live db %s, durable copy %s.", local_path, persist_path) return local_path def _log_persistent_inventory(persist_dir: str, local_path: str) -> None: """Log what restore material exists and what the live db holds, so an incident can be assessed straight from the container logs.""" try: lines = [] for entry in sorted(os.scandir(persist_dir), key=lambda e: e.name): if not entry.is_file(): continue st = entry.stat() mtime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime("%Y-%m-%d %H:%M") check = "" if entry.name.endswith((".db", ".bak", ".prev")): result = _quick_check(entry.path) check = " integrity=ok" if result == ["ok"] else f" integrity=CORRUPT({result[0][:60]})" lines.append(f"{entry.name} size={st.st_size} mtime={mtime}{check}") logger.warning("Persistent volume inventory:\n %s", "\n ".join(lines) or "(empty)") if os.path.exists(local_path): con = sqlite3.connect(local_path) try: tables = [r[0] for r in con.execute( "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")] counts = {} for t in tables: try: counts[t] = con.execute(f'SELECT COUNT(*) FROM "{t}"').fetchone()[0] except sqlite3.Error: counts[t] = "unreadable" logger.warning("Live db row counts: %s", counts) finally: con.close() except Exception: logger.exception("Failed to log persistent inventory.") # --- Integrity telemetry ------------------------------------------------------ # Incident 2026-08-19: a salvage/restore promoted a partial database that then # served traffic for hours with no alarm (articles re-"created", only-2024 # invoices), and its processed_files ledger kept claiming the lost files were # already imported, so syncs skipped them and the holes persisted. Detection # now happens at the two points where a stale/partial state can enter service: # # * event hooks — a salvage that loses rows, or a boot that falls back to # the .prev durable copy — persist an incident record the System Health # card surfaces until an admin recovers (purge + full re-import) or # acknowledges it; # * a boot row-count check — business-table counts are compared against the # last counts pushed to the durable copy (sidecar JSON, updated on every # mirror sync). A restored old copy is internally consistent, so only an # external baseline can expose it. The baseline itself is refreshed from # the degraded state within minutes of it serving, which is why a # detection is persisted as an incident instead of being re-derived. # # Salvage's own `lost` list only sees pages that error while reading; a table # that lost rows but still reads cleanly is exactly what the row-count check # exists to catch. Neither layer alone covers both failure shapes. _INTEGRITY_TABLES = ( "items", "customers", "bom_components", "invoice_headers", "invoice_lines", "gl_accounts", "gl_entries", "processed_files", "users", ) # A table must shrink by BOTH this share and this many rows to flag — except a # drop to zero, which always flags. Growth never flags (imports only add). INTEGRITY_DROP_PCT = float(os.environ.get("DB_INTEGRITY_DROP_PCT", "10")) INTEGRITY_DROP_MIN_ROWS = int(os.environ.get("DB_INTEGRITY_DROP_MIN_ROWS", "20")) _INCIDENTS_KEPT = 20 BOOT_INTEGRITY: dict = { "status": "unknown", # ok | degraded | no-baseline | unknown "issues": [], "checked_at": None, "baseline_at": None, } def _live_db_path() -> str | None: if not SQLALCHEMY_DATABASE_URL.startswith("sqlite"): return None path = make_url(SQLALCHEMY_DATABASE_URL).database return path if path and path != ":memory:" else None def _integrity_sidecar(suffix: str) -> str | None: """Sidecar files live next to the durable copy (never inside the db — a restored old db would carry an old, self-consistent copy of them).""" anchor = PERSISTENT_DB_PATH or _live_db_path() if not anchor: return None return anchor + suffix def _business_row_counts(db_path: str) -> dict[str, int | None]: """Row counts for the monitored tables; None = table missing/unreadable.""" counts: dict[str, int | None] = {t: None for t in _INTEGRITY_TABLES} if not os.path.exists(db_path): return counts try: con = sqlite3.connect(db_path) except sqlite3.Error: return counts try: for t in _INTEGRITY_TABLES: try: counts[t] = con.execute(f'SELECT COUNT(*) FROM "{t}"').fetchone()[0] except sqlite3.Error: counts[t] = None finally: con.close() return counts def read_rowcount_baseline() -> dict | None: path = _integrity_sidecar(".rowcounts.json") if not path or not os.path.exists(path): return None try: with open(path, encoding="utf-8") as fh: data = json.load(fh) return data if isinstance(data.get("counts"), dict) else None except (OSError, ValueError): logger.exception("Row-count baseline %s unreadable; skipping comparison.", path) return None def write_rowcount_baseline(counts: dict, source: str) -> None: """Persist the last-known-good counts. Best-effort: never raises.""" path = _integrity_sidecar(".rowcounts.json") if not path: return payload = { "counts": {k: v for k, v in counts.items() if v is not None}, "updated_at": datetime.datetime.utcnow().isoformat(), "source": source, } try: tmp = path + ".tmp" with open(tmp, "w", encoding="utf-8") as fh: json.dump(payload, fh) os.replace(tmp, path) except OSError: logger.exception("Failed to write row-count baseline %s.", path) def refresh_rowcount_baseline(source: str) -> None: """Recount the live db and overwrite the baseline — for intentional mass deletions (purge) that would otherwise flag as corruption on next boot.""" live = _live_db_path() if live: write_rowcount_baseline(_business_row_counts(live), source) def read_integrity_incidents() -> list[dict]: path = _integrity_sidecar(".integrity-incidents.json") if not path or not os.path.exists(path): return [] try: with open(path, encoding="utf-8") as fh: data = json.load(fh) incidents = data.get("incidents") return incidents if isinstance(incidents, list) else [] except (OSError, ValueError): logger.exception("Integrity incident file %s unreadable.", path) return [] def record_integrity_incident(kind: str, details: list[str], severity: str = "critical") -> None: """Persist an incident so it survives restarts and baseline poisoning. Best-effort (never raises), but always screams into the log.""" log = logger.critical if severity == "critical" else logger.error log("DB INTEGRITY INCIDENT [%s/%s]: %s", kind, severity, "; ".join(details)) path = _integrity_sidecar(".integrity-incidents.json") if not path: return try: incidents = read_integrity_incidents() incidents.append({ "at": datetime.datetime.utcnow().isoformat(), "kind": kind, "severity": severity, "details": details, }) tmp = path + ".tmp" with open(tmp, "w", encoding="utf-8") as fh: json.dump({"incidents": incidents[-_INCIDENTS_KEPT:]}, fh) os.replace(tmp, path) except OSError: logger.exception("Failed to persist integrity incident to %s.", path) def clear_integrity_incidents(reason: str) -> None: """Called after deliberate recovery (purge + re-import) or an explicit admin acknowledgement — the incident had its effect and was handled.""" path = _integrity_sidecar(".integrity-incidents.json") if path and os.path.exists(path): try: os.remove(path) except OSError: logger.exception("Failed to clear integrity incidents at %s.", path) return BOOT_INTEGRITY["status"] = "ok" if BOOT_INTEGRITY["status"] == "degraded" else BOOT_INTEGRITY["status"] BOOT_INTEGRITY["issues"] = [] logger.warning("Integrity incidents cleared (%s).", reason) def compare_row_counts(baseline_counts: dict, current_counts: dict) -> list[str]: """Pure comparison: which monitored tables shrank beyond the thresholds.""" issues: list[str] = [] for table in _INTEGRITY_TABLES: base = baseline_counts.get(table) if not isinstance(base, int) or base <= 0: continue cur = current_counts.get(table) if cur is None: issues.append(f"{table}: table missing/unreadable (baseline {base} rows)") continue dropped = base - cur if cur == 0 or (dropped >= INTEGRITY_DROP_MIN_ROWS and dropped * 100.0 >= base * INTEGRITY_DROP_PCT): issues.append(f"{table}: {cur} rows vs baseline {base} (-{dropped})") return issues def run_boot_integrity_check(db_path: str) -> None: """Compare the db that is about to serve traffic against the last counts known to have been pushed durably. Populates BOOT_INTEGRITY and persists an incident on divergence. Never raises — the check must not block boot.""" checked_at = datetime.datetime.utcnow().isoformat() try: baseline = read_rowcount_baseline() if baseline is None: BOOT_INTEGRITY.update(status="no-baseline", issues=[], checked_at=checked_at, baseline_at=None) logger.info("Boot integrity check: no row-count baseline yet (first " "boot on this volume, or sidecar lost) — nothing to compare.") return issues = compare_row_counts(baseline["counts"], _business_row_counts(db_path)) BOOT_INTEGRITY.update(status="degraded" if issues else "ok", issues=issues, checked_at=checked_at, baseline_at=baseline.get("updated_at")) if issues: record_integrity_incident( "boot-rowcount-drop", issues + [f"baseline from {baseline.get('updated_at')} " f"({baseline.get('source', 'unknown')})"], ) else: logger.warning("Boot integrity check OK: business row counts >= baseline " "of %s.", baseline.get("updated_at")) except Exception: BOOT_INTEGRITY.update(status="unknown", issues=[], checked_at=checked_at) logger.exception("Boot integrity check failed; continuing boot.") def get_integrity_report() -> dict: """Feed for /api/admin/system-health — boot verdict + persisted incidents.""" incidents = read_integrity_incidents() return { "status": BOOT_INTEGRITY["status"], "issues": BOOT_INTEGRITY["issues"], "checked_at": BOOT_INTEGRITY["checked_at"], "baseline_at": BOOT_INTEGRITY["baseline_at"], "incidents": incidents, "alert": BOOT_INTEGRITY["status"] == "degraded" or any(i.get("severity") == "critical" for i in incidents), } def sync_mirror_to_persistent() -> None: """Push a consistent snapshot of the local live db to the bucket. Uses the online backup API (safe alongside active readers/writers) into a local temp file, then copies that to the bucket and renames into place so the durable copy is never half-written. """ if PERSISTENT_DB_PATH is None: return local_path = make_url(SQLALCHEMY_DATABASE_URL).database snap = local_path + ".sync" if os.path.exists(snap): os.remove(snap) src = sqlite3.connect(local_path, timeout=15) try: dst = sqlite3.connect(snap, timeout=15) try: src.backup(dst) finally: dst.close() finally: src.close() # Never replicate corruption into the durable copy: if the snapshot fails # the integrity check, keep the last good bucket copy and raise so the # failure is visible in the logs. snap_check = _quick_check(snap) if snap_check != ["ok"]: os.remove(snap) raise RuntimeError(f"mirror snapshot failed integrity check, not pushed: {snap_check}") # Counted on the local snapshot (fast) — exactly the data being pushed; # becomes the boot-time baseline once the rotation below succeeds. snap_counts = _business_row_counts(snap) # Rotation with read-back verification. Rename on the FUSE bucket is not # atomic (a container kill mid-push corrupted the durable copy on # 2026-08-18 and cost business rows), so: write .new, re-verify it by # reading it back THROUGH the bucket, keep the previous good copy as # .prev, and only then promote .new. Any interruption leaves at least one # healthy file among {main, .prev, .new} for the boot fallback chain. new_path = PERSISTENT_DB_PATH + ".new" shutil.copy2(snap, new_path) os.remove(snap) new_check = _quick_check(new_path) if new_check != ["ok"]: os.remove(new_path) raise RuntimeError(f"pushed copy failed read-back integrity check, rotation aborted: {new_check}") if os.path.exists(PERSISTENT_DB_PATH): os.replace(PERSISTENT_DB_PATH, PERSISTENT_DB_PATH + ".prev") os.replace(new_path, PERSISTENT_DB_PATH) write_rowcount_baseline(snap_counts, source="mirror-sync") logger.info("Mirror sync: verified snapshot promoted to %s (previous kept as .prev).", PERSISTENT_DB_PATH) if SQLALCHEMY_DATABASE_URL.startswith("sqlite"): _db_file = make_url(SQLALCHEMY_DATABASE_URL).database if _db_file and _db_file != ":memory:": if _should_mirror(_db_file): # The mirror activation owns repair: it prefers a healthy .prev # copy over salvage-rebuilding a corrupt main (less data loss). PERSISTENT_DB_PATH = _db_file _local_file = _activate_local_mirror(_db_file) SQLALCHEMY_DATABASE_URL = f"sqlite:///{_local_file}" run_boot_integrity_check(_local_file) else: _repair_malformed_sqlite(_db_file) run_boot_integrity_check(_db_file) if SQLALCHEMY_DATABASE_URL.startswith("sqlite"): engine = create_engine( SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}, poolclass=NullPool ) else: # Managed Postgres (Neon): small persistent pool. pre_ping transparently # revives connections dropped by the provider's idle timeout / scale-to- # zero autosuspend; recycle keeps them younger than typical LB cutoffs. engine = create_engine( SQLALCHEMY_DATABASE_URL, pool_pre_ping=True, # 2026-08-21: the first MVP 2 force sync exhausted 5+10 connections — # sync endpoints run in a threadpool, so every poll (UI, agent, uploader) # held a connection while Neon was busy with bulk inserts, and even the # token lookup of the next bundle's POST timed out (500s). Neon's # smallest compute allows ~100 connections; 10+20 leaves room. pool_size=10, max_overflow=20, pool_recycle=300, # Imports hold a connection for whole batches; UI/agent polling must # queue behind them instead of failing fast (30s default starved and # 500'd every endpoint during the first Postgres force sync). pool_timeout=120, ) # How long a connection waits for the write lock before giving up. A long # import transaction can hold it for several seconds; stress testing showed # audit writes exceeding the 5s driver default and surfacing as 500s. BUSY_TIMEOUT_MS = int(os.environ.get("SQLITE_BUSY_TIMEOUT_MS", "15000")) @event.listens_for(engine, "connect") def _sqlite_pragma_on_connect(dbapi_connection, connection_record): # WAL improves read concurrency while a long-running writer (e.g. SSE import) holds the DB. if SQLALCHEMY_DATABASE_URL.startswith("sqlite"): cur = dbapi_connection.cursor() try: cur.execute("PRAGMA journal_mode=WAL") cur.execute("PRAGMA synchronous=NORMAL") cur.execute(f"PRAGMA busy_timeout={BUSY_TIMEOUT_MS}") finally: cur.close() LOW_PRIORITY_BUSY_TIMEOUT_MS = int(os.environ.get("SQLITE_LOW_PRIORITY_BUSY_TIMEOUT_MS", "200")) def set_low_priority(db_session) -> None: """Mark a session as expendable-telemetry priority. Telemetry writes (access log, page views) must fail fast and be dropped when a long writer holds the lock — queueing for the full BUSY_TIMEOUT_MS parks an anyio threadpool slot per blocked write, and enough of those stall the whole app. Callers own swallowing the resulting error. """ if SQLALCHEMY_DATABASE_URL.startswith("sqlite"): db_session.connection().exec_driver_sql( f"PRAGMA busy_timeout={LOW_PRIORITY_BUSY_TIMEOUT_MS}") SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() def get_db(): db = SessionLocal() try: yield db finally: db.close()