Spaces:
Sleeping
Fix scoring engine: restore ML path, remove synthetic ensemble, secure key issuance
Browse filesBrings the Space up to date with the audit fixes.
Availability:
- sqlite3 shim re-exports the real Row/Connection/Cursor. The stub Row broke
the SQLite path outright and the missing Connection broke pandas.read_sql_query
at 17 call sites, which silently dropped every request to the baseline heuristic.
- init_db() no longer aborts module import, so a database outage returns
503 DEGRADED from /health instead of crash-looping uvicorn.
- Unknown user_id returns 404 rather than scoring default features and leaking a
foreign-key error; all scoring connections are wrapped in try/finally with
rollback, so one failed request no longer leaves a write lock behind.
Scoring correctness:
- Snapshot date defaults to the user's own latest transaction rather than the
global maximum, which had left 98% of users on the cold-start heuristic.
Adds a data_freshness block reporting snapshot age.
- Removes the synthetic ensemble that added np.random.normal() noise to the
XGBoost output four times and averaged it back over the prediction. Reports
the calibrated probability directly; the rule-based baseline becomes a real
second opinion under model_agreement.
- One positive sign convention for the OOD anomaly score across scoring,
uncertainty_science and confidence_governance; shift_strength clamped to [0,1].
Epistemic uncertainty is normalised against the detector's own cut-point so
total_uncertainty stays in [0,1].
- Removes three remaining /100.0 divisors applied to an already 0-1 probability.
The cold-start branch computes real macro sensitivities and evaluates the
thin-file cohort instead of hardcoding 0.5 and False.
Security:
- API key generation and revocation move behind an ADMIN_API_KEY secret,
compared with secrets.compare_digest and failing closed when unset. Both
endpoints previously accepted anonymous callers.
Adds src/load_to_postgres.py to seed a fresh Postgres from a local SQLite file.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Files changed (12)
- src/api.py+64-11
- src/confidence_governance.py+6-1
- src/continuous_learning.py+37-4
- src/load_to_postgres.pyAdded+251
- src/models/archetype_discoverer.pkl+1-1
- src/models/fca_model_card.json+6-6
- src/models/fca_model_card.md+6-6
- src/models/model_metadata.pkl+1-1
- src/models/multi_account_priors.pkl+1-1
- src/scoring.py+229-82
- src/sqlite3.py+25-5
- src/uncertainty_science.py+16-5
12345678 unmodified lines1617181920212223242523 unmodified lines49505152535437 unmodified lines92939495969720 unmodified lines1181191201211221231241252 unmodified lines128129130131132133134135136137128 unmodified lines26626726826927027115 unmodified lines287288289290291292344 unmodified lines63763863964064164264364464564623 unmodified lines670671672673674675676import osimport pickleimport numpy as npfrom fastapi import FastAPI, HTTPException, status, Dependsfrom fastapi.security.api_key import APIKeyHeaderfrom pydantic import BaseModelfrom pathlib import Path8 unmodified linesversion="1.0.0")# Auto-initialize database schema if database file does not existif not os.path.exists(DB_PATH):print("Database file not found. Auto-initializing SQLite database...")init_db()# Initialize Risk Scoring Engineengine = RiskScoringEngine(db_path=DB_PATH)23 unmodified lines)return api_key# --- Pydantic Schemas ---class RiskScoreRequest(BaseModel):user_id: int37 unmodified linesconfidence_underwriting: dict | None = Noneself_reported_scrutiny: dict | None = None# Part 19 Multi-Account Financial Intelligence & Visibility Governance fieldsvisibility_score: float | None = Noneaccount_roles: dict | None = None20 unmodified lines# --- Endpoints ---@app.get("/health", status_code=status.HTTP_200_OK)def health_check():"""Verifies service health and database availability."""try:from database import get_db_connectionconn = get_db_connection()2 unmodified linesexcept Exception as e:print(f"Health check database connection failure: {e}")db_connected = Falsereturn {"status": "HEALTHY" if db_connected else "DEGRADED","database_connected": db_connected,"loaded_model_type": "xgboost" if len(engine.ml_models) > 0 else "baseline_heuristic","shadow_model_active": engine.shadow_model is not None}128 unmodified linesclass ContinuousUpdateRequest(BaseModel):user_id: inttransactions: list[dict] = []outcomes: list[dict] | None = Noneoverrides: dict | None = Nonemacro_regime: dict | None = None15 unmodified linesorchestrator.process_streaming_input(user_id=request.user_id,df_transactions=df_transactions,outcomes=request.outcomes,overrides=request.overrides,macro_regime=request.macro_regime344 unmodified linesdetail=f"Autonomous cycle failed: {str(e)}")@app.post("/api-key/generate", status_code=status.HTTP_201_CREATED)def generate_api_key(request: GenerateKeyRequest):"""Generates a secure random API key, logs it to database, and returns it."""import secretsfrom database import get_db_connection# Generate a prefix like fr_live_ for identification23 unmodified lines"message": "Store this key securely. It will not be shown again."}@app.post("/api-key/revoke", status_code=status.HTTP_200_OK)def revoke_api_key(request: RevokeKeyRequest):"""Revokes an existing active API key."""from database import get_db_connection123456788 unmodified lines1718192021222324252627282930313233343536373839404123 unmodified lines65666768697071727374757677787980818283848586878889909192939437 unmodified lines13213313413513613713813914020 unmodified lines1611621631641651661671681692 unmodified lines172173174175176177178179180181182183184185186187188189128 unmodified lines31831932032132232332415 unmodified lines340341342343344345346344 unmodified lines69169269369469569669769869923 unmodified lines723724725726727728729import osimport pickleimport secretsimport numpy as npfrom fastapi import FastAPI, HTTPException, Response, status, Dependsfrom fastapi.security.api_key import APIKeyHeaderfrom pydantic import BaseModelfrom pathlib import Path8 unmodified linesversion="1.0.0")# Auto-initialize the database schema.# NOTE: file existence is only a meaningful check on the SQLite path. When# DATABASE_URL is set we are on Postgres, where DB_PATH never exists on disk;# schema creation there is idempotent (CREATE TABLE IF NOT EXISTS).## This must never abort module import: uvicorn imports this module to build the# app, so an exception here kills the container before /health can ever answer.# We record the failure instead and surface it as DEGRADED.DB_INIT_ERROR = Nonetry:if os.environ.get("DATABASE_URL"):print("DATABASE_URL detected. Ensuring PostgreSQL schema exists...")init_db()elif not os.path.exists(DB_PATH):print("Database file not found. Auto-initializing SQLite database...")init_db()except Exception as _db_init_exc:DB_INIT_ERROR = f"{type(_db_init_exc).__name__}: {_db_init_exc}"print(f"WARNING: database initialization failed, starting in DEGRADED mode: {DB_INIT_ERROR}")# Initialize Risk Scoring Engineengine = RiskScoringEngine(db_path=DB_PATH)23 unmodified lines)return api_key# --- Admin Authentication (API key lifecycle) ---# Key issuance must not be reachable using a key that this endpoint itself hands# out, so generation and revocation sit behind a separate admin secret supplied# via the ADMIN_API_KEY environment variable rather than the api_keys table.ADMIN_KEY_NAME = "x-admin-key"admin_key_header = APIKeyHeader(name=ADMIN_KEY_NAME, auto_error=False)def verify_admin_key(admin_key: str = Depends(admin_key_header)):"""Verifies the caller holds the deployment's admin secret."""expected = os.environ.get("ADMIN_API_KEY")if not expected:# Fail closed: an unconfigured secret disables key management rather# than leaving it open to anonymous callers.raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,detail="Key management is disabled: ADMIN_API_KEY is not configured on this deployment.")if not admin_key or not secrets.compare_digest(admin_key, expected):raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,detail="Invalid or missing admin key.")return admin_key# --- Pydantic Schemas ---class RiskScoreRequest(BaseModel):user_id: int37 unmodified linesconfidence_underwriting: dict | None = Noneself_reported_scrutiny: dict | None = None# Data freshness (how old the scored snapshot is)data_freshness: dict | None = None# Part 19 Multi-Account Financial Intelligence & Visibility Governance fieldsvisibility_score: float | None = Noneaccount_roles: dict | None = None20 unmodified lines# --- Endpoints ---@app.get("/health", status_code=status.HTTP_200_OK)def health_check(response: Response):"""Verifies service health and database availability."""db_error = Nonetry:from database import get_db_connectionconn = get_db_connection()2 unmodified linesexcept Exception as e:print(f"Health check database connection failure: {e}")db_connected = Falsedb_error = f"{type(e).__name__}: {e}"healthy = db_connected and DB_INIT_ERROR is Noneif not healthy:# Report DEGRADED with a non-2xx code so orchestrators and uptime checks# actually notice, rather than seeing a 200 with a DEGRADED body.response.status_code = status.HTTP_503_SERVICE_UNAVAILABLEreturn {"status": "HEALTHY" if healthy else "DEGRADED","database_connected": db_connected,"database_error": db_error or DB_INIT_ERROR,"loaded_model_type": "xgboost" if len(engine.ml_models) > 0 else "baseline_heuristic","shadow_model_active": engine.shadow_model is not None}128 unmodified linesclass ContinuousUpdateRequest(BaseModel):user_id: inttransactions: list[dict] = []accounts: list[dict] | None = Noneoutcomes: list[dict] | None = Noneoverrides: dict | None = Nonemacro_regime: dict | None = None15 unmodified linesorchestrator.process_streaming_input(user_id=request.user_id,df_transactions=df_transactions,accounts=request.accounts,outcomes=request.outcomes,overrides=request.overrides,macro_regime=request.macro_regime344 unmodified linesdetail=f"Autonomous cycle failed: {str(e)}")@app.post("/api-key/generate", status_code=status.HTTP_201_CREATED, dependencies=[Depends(verify_admin_key)])def generate_api_key(request: GenerateKeyRequest):"""Generates a secure random API key, logs it to database, and returns it."""from database import get_db_connection# Generate a prefix like fr_live_ for identification23 unmodified lines"message": "Store this key securely. It will not be shown again."}@app.post("/api-key/revoke", status_code=status.HTTP_200_OK, dependencies=[Depends(verify_admin_key)])def revoke_api_key(request: RevokeKeyRequest):"""Revokes an existing active API key."""from database import get_db_connection
17 unmodified lines1819202122232417 unmodified lines"""# If OOD or high uncertainty, shift probability towards conservative upper boundif is_ood or total_uncertainty > 0.5:shift_strength = min(1.0, ood_score * 0.5 + total_uncertainty * 0.5)# Conservative prior of 0.60 default probabilityadjusted_prob = base_prob * (1.0 - shift_strength) + 0.60 * shift_strengthelse:17 unmodified lines18192021222324252627282917 unmodified lines"""# If OOD or high uncertainty, shift probability towards conservative upper boundif is_ood or total_uncertainty > 0.5:# ood_score is expected as a POSITIVE severity in [0, 1] (higher =# more anomalous). Clamping to [0, 1] is load-bearing, not defensive# tidying: a negative value inverts the blend below and drives the# adjusted probability BELOW the base probability, i.e. it would# make the most anomalous applicants look the safest.shift_strength = float(np.clip(ood_score * 0.5 + total_uncertainty * 0.5, 0.0, 1.0))# Conservative prior of 0.60 default probabilityadjusted_prob = base_prob * (1.0 - shift_strength) + 0.60 * shift_strengthelse:
5 unmodified lines6789101122 unmodified lines343536373839407 unmodified lines4849505152535481 unmodified lines136137138139140141142143144145146147148122 unmodified lines2712722732742752762775 unmodified linesimport datetimefrom pathlib import Pathfrom outcome_learning import ingest_real_outcome, get_repayment_loss_weightsfrom feature_trust_engine import FeatureTrustEnginefrom open_banking_streams import StreamingBankingMonitor22 unmodified linesself.archetype_engine = ArchetypeEvolutionEngine(db_path)self.gatekeeper = LearningGovernanceGatekeeper(db_path)def process_streaming_input(self, user_id, df_transactions, outcomes=None, overrides=None, macro_regime=None):"""Processes incoming data streams, logs telemetry to database, and triggers model checks.Args:7 unmodified linesprint(f"\n--- [CONTINUOUS UPDATE] Ingesting streams for User ID {user_id} ---")# 0. Check user existence and update profile fieldsconn = sqlite3.connect(self.db_path)cursor = conn.cursor()cursor.execute("SELECT 1 FROM users WHERE user_id = ?", (user_id,))exists = cursor.fetchone()81 unmodified linesconn.commit()conn.close()# 1. Ingest transactions & check alertsif not df_transactions.empty:alerts = self.stream_monitor.process_new_transactions(user_id, df_transactions)self.stream_monitor.log_streaming_alerts(user_id, alerts)# Persist transactions and update balances in DBconn = sqlite3.connect(self.db_path)cursor = conn.cursor()# Fetch fallback checking account ID for this user once122 unmodified lines# 7. Check calibration deterioration & run rolling checks# Query predictions to assess ECEconn = sqlite3.connect(self.db_path)cursor = conn.cursor()cursor.execute("SELECT default_probability FROM model_predictions ORDER BY predicted_at DESC LIMIT 50")pred_probs = [r[0] for r in cursor.fetchall()]5 unmodified lines678910111222 unmodified lines353637383940417 unmodified lines4950515253545581 unmodified lines137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181122 unmodified lines3043053063073083093105 unmodified linesimport datetimefrom pathlib import Pathfrom database import get_db_connectionfrom outcome_learning import ingest_real_outcome, get_repayment_loss_weightsfrom feature_trust_engine import FeatureTrustEnginefrom open_banking_streams import StreamingBankingMonitor22 unmodified linesself.archetype_engine = ArchetypeEvolutionEngine(db_path)self.gatekeeper = LearningGovernanceGatekeeper(db_path)def process_streaming_input(self, user_id, df_transactions, accounts=None, outcomes=None, overrides=None, macro_regime=None):"""Processes incoming data streams, logs telemetry to database, and triggers model checks.Args:7 unmodified linesprint(f"\n--- [CONTINUOUS UPDATE] Ingesting streams for User ID {user_id} ---")# 0. Check user existence and update profile fieldsconn = get_db_connection(self.db_path)cursor = conn.cursor()cursor.execute("SELECT 1 FROM users WHERE user_id = ?", (user_id,))exists = cursor.fetchone()81 unmodified linesconn.commit()conn.close()# Ingest or update linked accounts if passedif accounts:conn = get_db_connection(self.db_path)cursor = conn.cursor()for acc in accounts:acc_id = acc.get("account_id") or acc.get("id")if not acc_id:continuecursor.execute("SELECT 1 FROM accounts WHERE account_id = ?", (acc_id,))acc_exists = cursor.fetchone()acc_type = (acc.get("account_type") or "CHECKING").upper()balance = float(acc.get("balance") or 0.0)credit_limit = acc.get("credit_limit")overdraft_limit = acc.get("overdraft_limit") or 0.0status = acc.get("status") or "ACTIVE"created_at = acc.get("created_at") or datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")if acc_exists:cursor.execute("""UPDATE accountsSET balance = ?, status = ?WHERE account_id = ?""", (balance, status, acc_id))else:cursor.execute("""INSERT INTO accounts (account_id, user_id, account_type, balance, credit_limit, overdraft_limit, status, created_at)VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", (acc_id, user_id, acc_type, balance, credit_limit, overdraft_limit, status, created_at))conn.commit()conn.close()# 1. Ingest transactions & check alertsif not df_transactions.empty:alerts = self.stream_monitor.process_new_transactions(user_id, df_transactions)self.stream_monitor.log_streaming_alerts(user_id, alerts)# Persist transactions and update balances in DBconn = get_db_connection(self.db_path)cursor = conn.cursor()# Fetch fallback checking account ID for this user once122 unmodified lines# 7. Check calibration deterioration & run rolling checks# Query predictions to assess ECEconn = get_db_connection(self.db_path)cursor = conn.cursor()cursor.execute("SELECT default_probability FROM model_predictions ORDER BY predicted_at DESC LIMIT 50")pred_probs = [r[0] for r in cursor.fetchall()]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251"""Loads a local SQLite financial_risk.db into a PostgreSQL database.
This is the seed path the repo otherwise lacks: the Docker image ships onlydb/schema.sql, so a freshly provisioned Postgres has tables and zero rows andevery /risk-score call returns 404 until this is run.
Usage: # inspect what would happen, no writes, no psycopg2 needed python src/load_to_postgres.py --source financial_risk.db --dry-run
# create the schema and load everything python src/load_to_postgres.py \\ --source financial_risk.db \\ --target "postgresql://user:pw@host:6543/postgres" \\ --create-schema
# reload from scratch over an existing database python src/load_to_postgres.py --source financial_risk.db --truncate
If --target is omitted the DATABASE_URL environment variable is used.
Notes on the translation, which is not a straight copy:
* SQLite has no boolean type and stores 0/1 in columns declared BOOLEAN. Those columns are detected from the source schema rather than hardcoded, so a new BOOLEAN column does not silently break the load. * db/schema.sql declares INTEGER PRIMARY KEY AUTOINCREMENT, which becomes SERIAL in Postgres. Inserting explicit ids does not advance the backing sequence, so every sequence is reset after the load -- without that, the first application INSERT collides with an existing id. * Tables load in foreign-key order."""
import argparseimport osimport reimport sqlite3 as _shimmed_sqlite3import sysfrom pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parentSCHEMA_PATH = BASE_DIR / "db" / "schema.sql"
# Foreign-key safe insert order. Tables present in the source but not listed# here are loaded afterwards, in whatever order SQLite reports them.LOAD_ORDER = [ "users", "accounts", "transactions", "feature_snapshots", "risk_outcomes", "model_predictions", "shadow_model_predictions", "repayment_outcomes", "human_overrides", "feature_trust_logs", "calibration_memory", "archetype_evolution_logs", "portfolio_telemetry", "autonomous_learning_runs", "api_keys",]
BATCH_SIZE = 1000
def real_sqlite3(): """Returns the genuine stdlib sqlite3.
src/sqlite3.py shadows the stdlib module and reroutes connect() to Postgres whenever DATABASE_URL is set -- which is exactly the situation this script runs in, so it must reach past the shim to read the source file. """ return getattr(_shimmed_sqlite3, "real_sqlite3", _shimmed_sqlite3)
def translate_schema(script): """Converts the SQLite schema DDL to PostgreSQL.""" script = re.sub(r"INTEGER\s+PRIMARY\s+KEY\s+AUTOINCREMENT", "SERIAL PRIMARY KEY", script, flags=re.IGNORECASE) script = re.sub(r"BOOLEAN\s+NOT\s+NULL\s+DEFAULT\s+0", "BOOLEAN NOT NULL DEFAULT FALSE", script, flags=re.IGNORECASE) script = re.sub(r"BOOLEAN\s+NOT\s+NULL\s+DEFAULT\s+1", "BOOLEAN NOT NULL DEFAULT TRUE", script, flags=re.IGNORECASE) script = re.sub(r"PRAGMA\s+[^;]+;", "", script, flags=re.IGNORECASE) return script
def inspect_source(src_conn): """Returns [(table, [columns], {bool columns}, row_count)] in load order.""" cur = src_conn.cursor() cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'") present = {r[0] for r in cur.fetchall()}
ordered = [t for t in LOAD_ORDER if t in present] ordered += sorted(present - set(ordered))
tables = [] for table in ordered: cur.execute(f'PRAGMA table_info("{table}")') info = cur.fetchall() columns = [row[1] for row in info] # row[2] is the declared type; SQLite keeps the literal text. bool_cols = {row[1] for row in info if str(row[2]).upper().startswith("BOOL")} cur.execute(f'SELECT COUNT(*) FROM "{table}"') count = cur.fetchone()[0] tables.append((table, columns, bool_cols, count)) return tables
def coerce_row(row, columns, bool_cols): """Maps a SQLite row to Postgres-native Python values.""" out = [] for col, val in zip(columns, row): if col in bool_cols and val is not None: out.append(bool(val)) else: out.append(val) return tuple(out)
def reset_sequences(pg_cur, tables): """Advances SERIAL sequences past the highest explicitly inserted id.
Loading explicit primary keys leaves the sequence at 1, so the first application INSERT would raise a duplicate key error. """ reset = [] for table, columns, _bool_cols, _count in tables: for col in columns: pg_cur.execute("SELECT pg_get_serial_sequence(%s, %s)", (table, col)) seq = pg_cur.fetchone()[0] if not seq: continue pg_cur.execute( f'SELECT setval(%s, COALESCE((SELECT MAX("{col}") FROM "{table}"), 0) + 1, false)', (seq,)) reset.append(f"{table}.{col}") return reset
def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--source", default=str(BASE_DIR / "financial_risk.db"), help="path to the source SQLite database") ap.add_argument("--target", default=None, help="PostgreSQL DSN (defaults to $DATABASE_URL)") ap.add_argument("--create-schema", action="store_true", help="apply db/schema.sql to the target before loading") ap.add_argument("--truncate", action="store_true", help="empty the target tables before loading") ap.add_argument("--dry-run", action="store_true", help="report what would be loaded and exit without connecting") args = ap.parse_args()
source = Path(args.source) if not source.exists(): sys.exit(f"Source database not found: {source}")
src = real_sqlite3().connect(str(source)) tables = inspect_source(src)
total = sum(c for _t, _c, _b, c in tables) print(f"Source: {source}") print(f"{'table':<28}{'rows':>10} boolean columns") print("-" * 68) for table, _columns, bool_cols, count in tables: print(f"{table:<28}{count:>10} {', '.join(sorted(bool_cols)) or '-'}") print("-" * 68) print(f"{'TOTAL':<28}{total:>10}")
if args.dry_run: print("\nDry run: nothing written.") return
dsn = args.target or os.environ.get("DATABASE_URL") if not dsn: sys.exit("No target given. Pass --target or set DATABASE_URL.") if dsn.startswith("postgres://"): dsn = dsn.replace("postgres://", "postgresql://", 1)
try: import psycopg2 from psycopg2.extras import execute_values except ImportError: sys.exit("psycopg2 is required to load. Install with: pip install psycopg2-binary")
print(f"\nTarget: {re.sub(r'//[^@]*@', '//***@', dsn)}") pg = psycopg2.connect(dsn) try: cur = pg.cursor()
if args.create_schema: if not SCHEMA_PATH.exists(): sys.exit(f"Schema file not found: {SCHEMA_PATH}") print("Applying schema...") cur.execute(translate_schema(SCHEMA_PATH.read_text(encoding="utf-8"))) pg.commit() print(" schema applied.")
if args.truncate: names = ", ".join(f'"{t}"' for t, _c, _b, _n in tables) print("Truncating target tables...") cur.execute(f"TRUNCATE {names} RESTART IDENTITY CASCADE") pg.commit() print(" truncated.")
loaded = 0 for table, columns, bool_cols, count in tables: if count == 0: print(f" {table:<28} skipped (empty)") continue
collist = ", ".join(f'"{c}"' for c in columns) sql = f'INSERT INTO "{table}" ({collist}) VALUES %s ON CONFLICT DO NOTHING'
src_cur = src.cursor() src_cur.execute(f'SELECT {collist} FROM "{table}"') written = 0 while True: rows = src_cur.fetchmany(BATCH_SIZE) if not rows: break execute_values(cur, sql, [coerce_row(r, columns, bool_cols) for r in rows], page_size=BATCH_SIZE) written += len(rows) pg.commit() loaded += written print(f" {table:<28} {written:>10} rows")
print("\nResetting SERIAL sequences...") reset = reset_sequences(cur, tables) pg.commit() for name in reset: print(f" {name}") if not reset: print(" (none found)")
print(f"\nDone. {loaded} rows loaded into PostgreSQL.") except Exception: pg.rollback() raise finally: pg.close() src.close()
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:b54681bb0af95775e32880cc04229ac4560d986ca827ea145b23dd5c2f13d623size 10975123version https://git-lfs.github.com/spec/v1oid sha256:cf8991be1dff10c700404a2ce040008d5a8d0bb87897789e7816242545a88895size 10975
12345678981 unmodified lines919293949596979899100101102103104{"model_metadata": {"model_version": "xgb_20260528_223222","regulatory_certification": "FCA-grade (Internal Audit Ready)","governing_law": "UK Equality Act / FCA Fair Treatment Principles","timestamp": "2026-05-28 22:32:22","framework_version": "v1.0.0"},"data_lineage": {81 unmodified lines"persistence_index": 0.7062316295335467},"operational_footprint": {"operational_score": 0.950202000433579,"inference_latency_ms": 1.0797999566420913,"memory_usage_mb": 377.60546875,"complexity_penalty": 0.2,"training_time_s": 45.0},"scientific_composite_evaluation_index": {"scei_score": 0.7450902615617572,"rwr_v3_score": 0.7519960482384854,"predictive_auc": 0.9864488756590746,"calibration_ece": 0.9630235806303576,12345678981 unmodified lines919293949596979899100101102103104{"model_metadata": {"model_version": "xgb_20260622_223828","regulatory_certification": "FCA-grade (Internal Audit Ready)","governing_law": "UK Equality Act / FCA Fair Treatment Principles","timestamp": "2026-06-22 22:38:28","framework_version": "v1.0.0"},"data_lineage": {81 unmodified lines"persistence_index": 0.7062316295335467},"operational_footprint": {"operational_score": 0.9511189998490736,"inference_latency_ms": 0.9881000150926411,"memory_usage_mb": 378.7578125,"complexity_penalty": 0.2,"training_time_s": 45.0},"scientific_composite_evaluation_index": {"scei_score": 0.7451361115325319,"rwr_v3_score": 0.7519960482384854,"predictive_auc": 0.9864488756590746,"calibration_ece": 0.9630235806303576,
1234567827 unmodified lines3637383940414238 unmodified lines818283848586878889# FCA Model Governance & Audit Certificate## 1. Executive Summary & Production Authorization* **Model Version**: `xgb_20260528_223222`* **Audit Timestamp**: `2026-05-28 22:32:22`* **Authorization Status**: **🔴 REJECTED*** **Verdict Reason**: Model promotion rejected due to failed deployment gates: Subgroup collapse/unfairness detected (FGI: 0.600)* **Composite SCEI Rating**: `0.7451` (Threshold: `0.7000`)27 unmodified lines| Uncertainty Reliability | 0.8088 | 5% | 0.0404 || Domain Robustness (Transfer) | 0.7281 | 10% | 0.0728 || OOD Robustness | 0.9250 | 5% | 0.0463 || Operational Efficiency | 0.9502 | 5% | 0.0475 || Adversarial Robustness (ARS) | 0.9981 | 10% | 0.0998 || Business Utility | 0.7617 | 10% | 0.0762 || **TOTAL** | **0.7451** | **100%** | **0.7451** |38 unmodified lines---## 6. Operational & Platform Footprint* **Operational Score**: `0.9502`* **Inference Latency**: `1.08 ms` (SLA: `50.0 ms`)* **Memory Footprint**: `377.6 MB`* **Complexity Penalty applied**: `0.20`* **Training Time**: `45.0 seconds`1234567827 unmodified lines3637383940414238 unmodified lines818283848586878889# FCA Model Governance & Audit Certificate## 1. Executive Summary & Production Authorization* **Model Version**: `xgb_20260622_223828`* **Audit Timestamp**: `2026-06-22 22:38:28`* **Authorization Status**: **🔴 REJECTED*** **Verdict Reason**: Model promotion rejected due to failed deployment gates: Subgroup collapse/unfairness detected (FGI: 0.600)* **Composite SCEI Rating**: `0.7451` (Threshold: `0.7000`)27 unmodified lines| Uncertainty Reliability | 0.8088 | 5% | 0.0404 || Domain Robustness (Transfer) | 0.7281 | 10% | 0.0728 || OOD Robustness | 0.9250 | 5% | 0.0463 || Operational Efficiency | 0.9511 | 5% | 0.0476 || Adversarial Robustness (ARS) | 0.9981 | 10% | 0.0998 || Business Utility | 0.7617 | 10% | 0.0762 || **TOTAL** | **0.7451** | **100%** | **0.7451** |38 unmodified lines---## 6. Operational & Platform Footprint* **Operational Score**: `0.9511`* **Inference Latency**: `0.99 ms` (SLA: `50.0 ms`)* **Memory Footprint**: `378.8 MB`* **Complexity Penalty applied**: `0.20`* **Training Time**: `45.0 seconds`
123version https://git-lfs.github.com/spec/v1oid sha256:32915144182a965b4c3cce910c868f23c5b16d0508aa30557f79b55e30201cf6size 2267123version https://git-lfs.github.com/spec/v1oid sha256:f5755b44f1f7bc4bb731f6ae01e5a8abc63bac77edac1aa55e3801d9e048a0desize 2267
123version https://git-lfs.github.com/spec/v1oid sha256:f11a0d9a75b2b6094b45d87c74d97c908d1d52ca96ba3a3c5dcfae87d8436cb7size 458123version https://git-lfs.github.com/spec/v1oid sha256:eeb57a1ffa5922d53bee8882c9ab86c8290792227534d8e7d301a0eeb74f3751size 458
89 unmodified lines90919293949596979899113 unmodified lines21321421521621721821922022122222322422522622722822923023123223360 unmodified lines294295296297298299300301302303304305306307308309310311312313314107 unmodified lines42242342442542642742842943043143243343443543643743843944044154 unmodified lines4964974984995005015025035045055065075085095105115125135145159 unmodified lines52552652752852953053153253378 unmodified lines61261361461561661761855 unmodified lines6746756766776786796806816826836846856862 unmodified lines68969069169269369469569631 unmodified lines7287297307317327337347 unmodified lines74274374474574674729 unmodified lines77777877978078178278332 unmodified lines81681781881982082126 unmodified lines84884985085185285385485585685785885986086186286386486586686786818 unmodified lines8878888898908918928938944 unmodified lines89990090190290390490590690789 unmodified linesdef detect_user_domain(self, user_id):"""Helper to dynamically detect user domain source based on checking account prefix in DB."""conn = get_db_connection(self.db_path)cursor = conn.cursor()cursor.execute("SELECT account_id FROM accounts WHERE user_id = ? AND account_type = 'CHECKING'", (user_id,))row = cursor.fetchone()conn.close()if not row:return "UK" # Default fallbackacc_id = row[0]113 unmodified linesReturns:dict: Risk scoring profile"""if snapshot_date is None:# Query max transaction date from DBconn = get_db_connection(self.db_path)cursor = conn.cursor()cursor.execute("SELECT max(transaction_date) FROM transactions")max_date_str = cursor.fetchone()[0]conn.close()if max_date_str:snapshot_date = pd.to_datetime(max_date_str).to_pydatetime()else:snapshot_date = datetime.datetime.now()elif isinstance(snapshot_date, str):snapshot_date = pd.to_datetime(snapshot_date).to_pydatetime()# 1. Compute user featuresdf_feat = compute_user_features(self.db_path, [user_id], snapshot_date)if df_feat.empty:raise ValueError(f"User {user_id} not found in database.")60 unmodified linesself_reported_scrutiny_data = scrutiny_resrisk_profile["macro_regime_adjustment"] = {"unadjusted_stress_probability": float(risk_profile.get("financial_stress_probability", 20.0) / 100.0),"unadjusted_default_probability": float(risk_profile.get("financial_stress_probability", 20.0) / 150.0),"stagflation_stress_probability": float(risk_profile.get("financial_stress_probability", 20.0) / 100.0),"stagflation_default_probability": float(risk_profile.get("financial_stress_probability", 20.0) / 150.0),"interest_rate_sensitivity": 0.5,"affordability_compression": 0.5,"unemployment_sensitivity": 0.5}risk_profile["thin_file_analysis"] = {"is_thin_file": False,"thin_file_adjusted_stress_prob": float(risk_profile.get("financial_stress_probability", 20.0) / 100.0),"uplift_applied": "NONE","resilience_score_used": 50.0}underwriting_prob = float(risk_profile.get("default_probability", 0.05))107 unmodified linesdefault_prob = default_prob * (2.0 - lbsi)stress_prob = stress_prob * (2.0 - lbsi)# Aggregate using Multi-Model Ensemble Governancefrom ensemble_governance import EnsembleGovernanceensemble_eval = EnsembleGovernance()model_preds = {"XGBoost_Calibrated": default_prob,"LSTM_Sequential": float(np.clip(default_prob + np.random.normal(0.0, 0.02), 0.0, 1.0)),"Cox_Hazard": float(np.clip(default_prob + np.random.normal(0.0, 0.03), 0.0, 1.0)),"HMM_States": float(np.clip(default_prob + np.random.normal(0.0, 0.025), 0.0, 1.0)),"Baseline_Heuristic": float(np.clip(default_prob + np.random.normal(0.0, 0.04), 0.0, 1.0))}ens_res = ensemble_eval.aggregate_ensemble(model_preds)default_prob = ens_res["ensemble_probability"]# 1. Macroeconomic regime conditioningmacro_engine = MacroRegimeEngine()54 unmodified lines# Retrieve user transactions prior to snapshot_date to calculate temporal featuresconn = get_db_connection(self.db_path)# Parse transactionsdate_180d_prior = snapshot_date - datetime.timedelta(days=180)df_tx_u = pd.read_sql_query("""SELECT * FROM transactionsWHERE user_id = ? AND transaction_date >= ? AND transaction_date <= ?""", conn, params=(user_id, date_180d_prior.strftime("%Y-%m-%d %H:%M:%S"), snapshot_date.strftime("%Y-%m-%d %H:%M:%S")))if not df_tx_u.empty:df_tx_u["transaction_date"] = pd.to_datetime(df_tx_u["transaction_date"])# Reconstruct accounts list for this usercursor = conn.cursor()cursor.execute("SELECT account_id, account_type FROM accounts WHERE user_id = ?", (user_id,))accs_list = [dict(r) for r in cursor.fetchall()]conn.close()# Calculate 15 longitudinal temporal featuresnet_income = features_dict.get("net_income", 1500.0) or 1500.09 unmodified lines# OOD Detectionis_ood = Falseood_score = 0.0if self.ood_detector is not None:is_ood = bool(self.ood_detector.is_outlier(X_input[:, :16])[0])ood_score = float(self.ood_detector.score_anomaly(X_input[:, :16])[0])# Conformal Prediction Intervalslower_stress, upper_stress, stress_unc = stress_prob - 0.15, stress_prob + 0.15, 0.3078 unmodified linesbase_prob=default_prob,total_uncertainty=u_decomp.get("total_uncertainty", 0.25),is_ood=is_ood,ood_score=ood_score,dqi=dqi,calibration_ece=ece_val,base_credit_limit=1000.0,55 unmodified lines# E. Sequence Explainabilityconn = get_db_connection(self.db_path)df_user_snapshots = pd.read_sql_query("""SELECT runway_months, savings_rate, recent_failed_payments_30d, overdraft_days_30d, debt_to_income_ratio, snapshot_dateFROM feature_snapshotsWHERE user_id = ?ORDER BY snapshot_date ASC""", conn, params=(user_id,))conn.close()df_user_snapshots["snapshot_date"] = pd.to_datetime(df_user_snapshots["snapshot_date"])seq_explainer = SequenceExplainer(self.explainer)2 unmodified lines# F. Human-in-the-Loop Triage Escalationhr_system = HumanReviewSystem()# Mock baseline probability for model conflict checksbaseline_p = self.baseline.predict_user(features_dict)["financial_stress_probability"] / 100.0# Create temp risk profile matching schema for evaluatortemp_profile = {31 unmodified lines"latent_state": latent_state,"behavioural_archetype": archetype,"survival_trajectories": survival_trajectories,"ood_alert": {"is_ood": is_ood, "anomaly_score": float(round(ood_score, 4))},"resilience_profile": resilience_profile,# New Part 16 metrics7 unmodified lines"state_transition_audit": transition_explanation},"human_review_escalation": escalation_package,# New Part 17 metrics"macro_regime_adjustment": {29 unmodified linesscrutinizer = SelfReportedScrutinizer(self.db_path)scrutiny_res = scrutinizer.scrutinize_and_adjust(features_dict=features_dict,base_stress_prob=risk_profile["financial_stress_probability"] / 100.0,base_default_prob=risk_profile["default_probability"])risk_profile["financial_stress_probability"] = scrutiny_res["adjusted_stress_prob"]32 unmodified linesrisk_profile["dob"] = features_dict.get("dob", "1996-01-01")# Append meta timestamps and IDsrisk_profile["user_id"] = user_idrisk_profile["snapshot_date"] = snapshot_date.strftime("%Y-%m-%d %H:%M:%S")risk_profile["predicted_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")26 unmodified linestop_risk_json = json.dumps(profile.get("top_risk_factors", []))top_pos_json = json.dumps(profile.get("top_positive_factors", []))cursor.execute("""INSERT INTO model_predictions (prediction_id, user_id, snapshot_date, predicted_at, model_version,risk_score, default_probability, financial_stress_probability,liquidity_risk, confidence_score, shap_explanations,top_risk_factors, top_positive_factors) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (prediction_id, profile["user_id"], profile["snapshot_date"], profile["predicted_at"], profile["model_version"],profile["risk_score"], profile["default_probability"], profile["financial_stress_probability"],profile["liquidity_risk"], profile["confidence_score"], shap_json, top_risk_json, top_pos_json))conn.commit()conn.close()return prediction_iddef _score_and_log_shadow(self, user_id, X_input, domain, snapshot_date, champion_prediction_id):18 unmodified linesprediction_id = str(uuid.uuid4())[:18]conn = get_db_connection(self.db_path)cursor = conn.cursor()cursor.execute("""INSERT INTO shadow_model_predictions (prediction_id, user_id, snapshot_date, predicted_at, model_version,risk_score, default_probability, financial_stress_probability,4 unmodified linesdatetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), shadow_version,risk_score_100, default_prob, stress_prob, liquidity_risk, confidence_score,champion_prediction_id))conn.commit()conn.close()print(f"Logged shadow prediction for User {user_id} (Stress Prob: {stress_prob:.4f})")if __name__ == "__main__":89 unmodified lines90919293949596979899100101113 unmodified lines21521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227360 unmodified lines334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401107 unmodified lines50951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854 unmodified lines6036046056066076086096106116126136146156166176186196206216226236249 unmodified lines63463563663763863964064164264364464564664764864965065178 unmodified lines73073173273373473573655 unmodified lines7927937947957967977987998008018028038048058062 unmodified lines80981081181281381481581681781881931 unmodified lines8518528538548558568578588598608618627 unmodified lines87087187287387487587629 unmodified lines90690790890991091191232 unmodified lines94594694794894995095126 unmodified lines9789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100718 unmodified lines1026102710281029103010311032103310344 unmodified lines103910401041104210431044104510461047104810491050105110521053105489 unmodified linesdef detect_user_domain(self, user_id):"""Helper to dynamically detect user domain source based on checking account prefix in DB."""conn = get_db_connection(self.db_path)try:cursor = conn.cursor()cursor.execute("SELECT account_id FROM accounts WHERE user_id = ? AND account_type = 'CHECKING'", (user_id,))row = cursor.fetchone()finally:conn.close()if not row:return "UK" # Default fallbackacc_id = row[0]113 unmodified linesReturns:dict: Risk scoring profile"""# Default the snapshot to THIS user's latest transaction, not the global# maximum across the table. A global max means any user whose history# ends earlier gets an empty 90-day feature window, reports# has_transaction_history = 0, and silently drops to the cold-start# heuristic -- which was happening to 98% of the population.data_freshness = Noneif snapshot_date is None:conn = get_db_connection(self.db_path)try:cursor = conn.cursor()cursor.execute("SELECT max(transaction_date) FROM transactions WHERE user_id = ?",(user_id,))row = cursor.fetchone()user_max_str = row[0] if row else Nonefinally:conn.close()if user_max_str:snapshot_date = pd.to_datetime(user_max_str).to_pydatetime()else:snapshot_date = datetime.datetime.now()elif isinstance(snapshot_date, str):snapshot_date = pd.to_datetime(snapshot_date).to_pydatetime()# Record how stale this user's data is relative to now, so a degraded# score is visible on the response instead of being inferred from# model_version after the fact._age_days = (datetime.datetime.now() - snapshot_date).daysdata_freshness = {"snapshot_date": snapshot_date.strftime("%Y-%m-%d %H:%M:%S"),"data_age_days": int(_age_days),"is_stale": bool(_age_days > 90),"staleness_note": (f"Latest transaction is {_age_days} days old; features are computed ""as of that date, not today.") if _age_days > 90 else None}# 1. Verify the user actually exists.# compute_user_features() synthesizes a default-valued row for unknown# user_ids, so df_feat.empty is NOT a reliable existence check: without# this, an unknown user gets scored on all-default features and then# fails with a foreign-key error when the prediction is written.conn = get_db_connection(self.db_path)try:cursor = conn.cursor()cursor.execute("SELECT 1 FROM users WHERE user_id = ?", (user_id,))user_exists = cursor.fetchone() is not Nonefinally:conn.close()if not user_exists:raise ValueError(f"User {user_id} not found in database.")df_feat = compute_user_features(self.db_path, [user_id], snapshot_date)if df_feat.empty:raise ValueError(f"User {user_id} not found in database.")60 unmodified linesself_reported_scrutiny_data = scrutiny_res# Macro regime conditioning on the cold-start path. These probabilities# are already on a 0-1 scale; the previous "/ 100.0" and "/ 150.0"# divisors reported a distressed applicant as ~0.009 stress. The# sensitivities are now computed from the user's real features rather# than hardcoded to 0.5 with a stagflation figure identical to the# unadjusted one (which made the stress test always show zero impact)._cs_stress = float(risk_profile.get("financial_stress_probability", 0.20))_cs_default = float(risk_profile.get("default_probability", 0.05))try:_macro_engine = MacroRegimeEngine()_df_sens_cs = _macro_engine.calculate_sensitivities(df_feat)_stag_stress, _ = _macro_engine.adjust_probabilities(np.array([_cs_stress]), _df_sens_cs, scenario_name="stagflation_shock")_stag_default, _ = _macro_engine.adjust_probabilities(np.array([_cs_default]), _df_sens_cs, scenario_name="stagflation_shock")risk_profile["macro_regime_adjustment"] = {"unadjusted_stress_probability": _cs_stress,"unadjusted_default_probability": _cs_default,"stagflation_stress_probability": float(_stag_stress[0]),"stagflation_default_probability": float(_stag_default[0]),"interest_rate_sensitivity": float(_df_sens_cs["interest_rate_sensitivity"].iloc[0]),"affordability_compression": float(_df_sens_cs["affordability_compression"].iloc[0]),"unemployment_sensitivity": float(_df_sens_cs["unemployment_sensitivity"].iloc[0])}except Exception as _macro_err:print(f"Cold-start macro conditioning failed: {_macro_err}")risk_profile["macro_regime_adjustment"] = {"unadjusted_stress_probability": _cs_stress,"unadjusted_default_probability": _cs_default,"stagflation_stress_probability": None,"stagflation_default_probability": None,"interest_rate_sensitivity": None,"affordability_compression": None,"unemployment_sensitivity": None}# A cold-start user is thin-file by definition, so evaluate the cohort# properly instead of asserting False on the one branch that serves them.try:_thin_eval_cs = ThinFileModelEvaluator()_is_thin_cs = bool(_thin_eval_cs.identify_thin_file_cohort(df_feat).iloc[0])_resilience_cs = float(df_feat["financial_resilience_score"].iloc[0]if "financial_resilience_score" in df_feat.columns else 50.0)_adjusted_cs = _thin_eval_cs.adjust_thin_file_score({"financial_stress_probability": _cs_stress,"resilience_profile": {"resilience_score": _resilience_cs}}, features_dict)risk_profile["thin_file_analysis"] = {"is_thin_file": _is_thin_cs,"thin_file_adjusted_stress_prob": float(_adjusted_cs["financial_stress_probability"]),"uplift_applied": _adjusted_cs.get("thin_file_uplift_applied", "NONE"),"resilience_score_used": _resilience_cs}except Exception as _thin_err:print(f"Cold-start thin-file evaluation failed: {_thin_err}")risk_profile["thin_file_analysis"] = {"is_thin_file": True,"thin_file_adjusted_stress_prob": _cs_stress,"uplift_applied": "NONE","resilience_score_used": 50.0}underwriting_prob = float(risk_profile.get("default_probability", 0.05))107 unmodified linesdefault_prob = default_prob * (2.0 - lbsi)stress_prob = stress_prob * (2.0 - lbsi)# Multi-Model agreement check.## This previously built a five-member "ensemble" by adding# np.random.normal() noise to the XGBoost output four times and# averaging the result back over default_prob, which made every# score non-reproducible (measured: 46% spread across identical# calls) and misrepresented the model stack in the audit output.## The calibrated XGBoost probability is now reported as-is. The# rule-based baseline is a genuinely independent estimator on the# same 0-1 scale, so it is used as a real second opinion: it# informs confidence and human-review routing, but never blends# into the reported probability.from ensemble_governance import EnsembleGovernanceensemble_eval = EnsembleGovernance()baseline_profile = self.baseline.predict_user(features_dict)baseline_default_prob = float(baseline_profile["default_probability"])model_preds = {"XGBoost_Calibrated": float(default_prob),"Baseline_Heuristic": baseline_default_prob}ens_res = ensemble_eval.aggregate_ensemble(model_preds)# default_prob is deliberately NOT overwritten here.model_agreement = {"reported_model": "XGBoost_Calibrated","member_predictions": model_preds,"disagreement": float(round(abs(default_prob - baseline_default_prob), 4)),"consensus_confidence": ens_res["consensus_confidence"],"diverged": ens_res["diverged"],"action_taken": ens_res["action_taken"]}# 1. Macroeconomic regime conditioningmacro_engine = MacroRegimeEngine()54 unmodified lines# Retrieve user transactions prior to snapshot_date to calculate temporal featuresconn = get_db_connection(self.db_path)try:# Parse transactionsdate_180d_prior = snapshot_date - datetime.timedelta(days=180)df_tx_u = pd.read_sql_query("""SELECT * FROM transactionsWHERE user_id = ? AND transaction_date >= ? AND transaction_date <= ?""", conn, params=(user_id, date_180d_prior.strftime("%Y-%m-%d %H:%M:%S"), snapshot_date.strftime("%Y-%m-%d %H:%M:%S")))if not df_tx_u.empty:df_tx_u["transaction_date"] = pd.to_datetime(df_tx_u["transaction_date"])# Reconstruct accounts list for this usercursor = conn.cursor()cursor.execute("SELECT account_id, account_type FROM accounts WHERE user_id = ?", (user_id,))accs_list = [dict(r) for r in cursor.fetchall()]finally:conn.close()# Calculate 15 longitudinal temporal featuresnet_income = features_dict.get("net_income", 1500.0) or 1500.09 unmodified lines# OOD Detectionis_ood = Falseood_score = 0.0ood_severity = 0.0if self.ood_detector is not None:is_ood = bool(self.ood_detector.is_outlier(X_input[:, :16])[0])# score_anomaly() returns NEGATIVE distance (lower = more# anomalous). Negate it so ood_score is a positive severity,# matching the convention used by UncertaintyScorer and# expected by ConfidenceGovernance.ood_score = max(0.0, -float(self.ood_detector.score_anomaly(X_input[:, :16])[0]))# Severity relative to the fitted cut-point, clamped to [0, 1],# for consumers that expect a bounded score._ref = float(getattr(self.ood_detector, "threshold", 0.0) or 0.0)ood_severity = float(np.clip(ood_score / _ref, 0.0, 1.0)) if _ref > 0 else 0.0# Conformal Prediction Intervalslower_stress, upper_stress, stress_unc = stress_prob - 0.15, stress_prob + 0.15, 0.3078 unmodified linesbase_prob=default_prob,total_uncertainty=u_decomp.get("total_uncertainty", 0.25),is_ood=is_ood,ood_score=ood_severity,dqi=dqi,calibration_ece=ece_val,base_credit_limit=1000.0,55 unmodified lines# E. Sequence Explainabilityconn = get_db_connection(self.db_path)try:df_user_snapshots = pd.read_sql_query("""SELECT runway_months, savings_rate, recent_failed_payments_30d, overdraft_days_30d, debt_to_income_ratio, snapshot_dateFROM feature_snapshotsWHERE user_id = ?ORDER BY snapshot_date ASC""", conn, params=(user_id,))finally:conn.close()df_user_snapshots["snapshot_date"] = pd.to_datetime(df_user_snapshots["snapshot_date"])seq_explainer = SequenceExplainer(self.explainer)2 unmodified lines# F. Human-in-the-Loop Triage Escalationhr_system = HumanReviewSystem()# Baseline probability for the model-conflict check. BaselineModel# returns financial_stress_probability already on a 0-1 scale, so# the old "/ 100.0" collapsed it to ~0 and the check compared the# ML probability against a constant instead of against the baseline.baseline_p = float(baseline_profile["financial_stress_probability"])# Create temp risk profile matching schema for evaluatortemp_profile = {31 unmodified lines"latent_state": latent_state,"behavioural_archetype": archetype,"survival_trajectories": survival_trajectories,"ood_alert": {"is_ood": is_ood,"anomaly_score": float(round(ood_score, 4)),"severity": float(round(ood_severity, 4)),"threshold": float(round(float(getattr(self.ood_detector, "threshold", 0.0) or 0.0), 4))},"resilience_profile": resilience_profile,# New Part 16 metrics7 unmodified lines"state_transition_audit": transition_explanation},"human_review_escalation": escalation_package,"model_agreement": model_agreement,# New Part 17 metrics"macro_regime_adjustment": {29 unmodified linesscrutinizer = SelfReportedScrutinizer(self.db_path)scrutiny_res = scrutinizer.scrutinize_and_adjust(features_dict=features_dict,base_stress_prob=risk_profile["financial_stress_probability"],base_default_prob=risk_profile["default_probability"])risk_profile["financial_stress_probability"] = scrutiny_res["adjusted_stress_prob"]32 unmodified linesrisk_profile["dob"] = features_dict.get("dob", "1996-01-01")# Append meta timestamps and IDsrisk_profile["data_freshness"] = data_freshnessrisk_profile["user_id"] = user_idrisk_profile["snapshot_date"] = snapshot_date.strftime("%Y-%m-%d %H:%M:%S")risk_profile["predicted_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")26 unmodified linestop_risk_json = json.dumps(profile.get("top_risk_factors", []))top_pos_json = json.dumps(profile.get("top_positive_factors", []))try:cursor.execute("""INSERT INTO model_predictions (prediction_id, user_id, snapshot_date, predicted_at, model_version,risk_score, default_probability, financial_stress_probability,liquidity_risk, confidence_score, shap_explanations,top_risk_factors, top_positive_factors) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (prediction_id, profile["user_id"], profile["snapshot_date"], profile["predicted_at"], profile["model_version"],profile["risk_score"], profile["default_probability"], profile["financial_stress_probability"],profile["liquidity_risk"], profile["confidence_score"], shap_json, top_risk_json, top_pos_json))conn.commit()except Exception:# Without this rollback the connection is returned/closed mid-transaction,# leaving a write lock (SQLite) or an aborted transaction (Postgres) behind.try:conn.rollback()except Exception:passraisefinally:conn.close()return prediction_iddef _score_and_log_shadow(self, user_id, X_input, domain, snapshot_date, champion_prediction_id):18 unmodified linesprediction_id = str(uuid.uuid4())[:18]conn = get_db_connection(self.db_path)try:cursor = conn.cursor()cursor.execute("""INSERT INTO shadow_model_predictions (prediction_id, user_id, snapshot_date, predicted_at, model_version,risk_score, default_probability, financial_stress_probability,4 unmodified linesdatetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), shadow_version,risk_score_100, default_prob, stress_prob, liquidity_risk, confidence_score,champion_prediction_id))conn.commit()except Exception:try:conn.rollback()except Exception:passraisefinally:conn.close()print(f"Logged shadow prediction for User {user_id} (Stress Prob: {stress_prob:.4f})")if __name__ == "__main__":
19 unmodified lines202122232425262728293031323334353637383919 unmodified linesreal_sqlite3 = _load_real_sqlite3()# Export exception typesError = real_sqlite3.ErrorDatabaseError = real_sqlite3.DatabaseErrorOperationalError = real_sqlite3.OperationalErrorIntegrityError = real_sqlite3.IntegrityErrorProgrammingError = real_sqlite3.ProgrammingErrorNotSupportedError = real_sqlite3.NotSupportedError# Mock Row class for identificationclass Row:pass# Export other standard variables and functionsPARSE_DECLTYPES = 1PARSE_COLNAMES = 2register_adapter = real_sqlite3.register_adapterregister_converter = real_sqlite3.register_converter19 unmodified lines2021222324252627282930313233343536373839404142434445464748495051525354555657585919 unmodified linesreal_sqlite3 = _load_real_sqlite3()# Export exception typesWarning = real_sqlite3.WarningError = real_sqlite3.ErrorInterfaceError = real_sqlite3.InterfaceErrorDatabaseError = real_sqlite3.DatabaseErrorDataError = real_sqlite3.DataErrorOperationalError = real_sqlite3.OperationalErrorIntegrityError = real_sqlite3.IntegrityErrorInternalError = real_sqlite3.InternalErrorProgrammingError = real_sqlite3.ProgrammingErrorNotSupportedError = real_sqlite3.NotSupportedError# Re-export the real Row/Connection/Cursor types.# These MUST be the genuine stdlib objects: the SQLite fallback path assigns# Row to a live sqlite3.Connection.row_factory, and pandas.read_sql_query# dispatches on isinstance(con, sqlite3.Connection).Row = real_sqlite3.RowConnection = real_sqlite3.ConnectionCursor = real_sqlite3.Cursor# Export other standard variables and functionsPARSE_DECLTYPES = real_sqlite3.PARSE_DECLTYPESPARSE_COLNAMES = real_sqlite3.PARSE_COLNAMESapilevel = real_sqlite3.apilevelthreadsafety = real_sqlite3.threadsafetyparamstyle = real_sqlite3.paramstylesqlite_version = real_sqlite3.sqlite_versionsqlite_version_info = real_sqlite3.sqlite_version_infoBinary = real_sqlite3.BinaryDate = real_sqlite3.DateTime = real_sqlite3.TimeTimestamp = real_sqlite3.TimestampDateFromTicks = real_sqlite3.DateFromTicksTimeFromTicks = real_sqlite3.TimeFromTicksTimestampFromTicks = real_sqlite3.TimestampFromTicksregister_adapter = real_sqlite3.register_adapterregister_converter = real_sqlite3.register_converter
56 unmodified lines57585960616263646566676811 unmodified lines808182838485861 unmodified line888990919293949556 unmodified linesX_single = X_single.reshape(1, -1)# 1. OOD Outlier Scoreood_score = 0.0if ood_detector is not None:# Isolation forest decision_function returns lower scores for anomalies# We invert it: higher score = more anomalousood_score = -float(ood_detector.score_anomaly(X_single[:, :16])[0])ood_score = max(0.0, ood_score)# 2. Embedding distance (Nearest neighbor distance approximation)dist_score = 0.011 unmodified linesensemble_variance = float(np.var(preds))# Combine into epistemic scoreepistemic_score = ood_score * 0.40 + dist_score * 0.30 + ensemble_variance * 0.30return epistemic_score, ood_score, ensemble_variancedef decompose_uncertainty(self, X_single, model, ood_detector=None, domain=None):1 unmodified linealeatoric, mean_perturbed = self.compute_aleatoric_uncertainty(X_single, model, domain=domain)epistemic, ood, ens_var = self.compute_epistemic_uncertainty(X_single, ood_detector)# Total Uncertainty is scaled combinationtotal_uncertainty = aleatoric * 1.5 + epistemic * 1.0return {"aleatoric_uncertainty": aleatoric,56 unmodified lines575859606162636465666768697071727374757611 unmodified lines888990919293941 unmodified line9697989910010110210310410510656 unmodified linesX_single = X_single.reshape(1, -1)# 1. OOD Outlier Score# score_anomaly() follows the Isolation Forest convention (lower = more# anomalous), so it is negated to give a positive severity.ood_score = 0.0ood_normalized = 0.0if ood_detector is not None:ood_score = -float(ood_detector.score_anomaly(X_single[:, :16])[0])ood_score = max(0.0, ood_score)# Express the raw Mahalanobis distance as a multiple of the fitted# outlier cut-point so the epistemic term is scale-free: 1.0 sits# exactly at the detector's training threshold. Without this the# term inherits an unbounded distance and total_uncertainty escapes# the [0, 1] range every downstream consumer assumes.ref = float(getattr(ood_detector, "threshold", 0.0) or 0.0)ood_normalized = (ood_score / ref) if ref > 0 else ood_score# 2. Embedding distance (Nearest neighbor distance approximation)dist_score = 0.011 unmodified linesensemble_variance = float(np.var(preds))# Combine into epistemic scoreepistemic_score = ood_normalized * 0.40 + dist_score * 0.30 + ensemble_variance * 0.30return epistemic_score, ood_score, ensemble_variancedef decompose_uncertainty(self, X_single, model, ood_detector=None, domain=None):1 unmodified linealeatoric, mean_perturbed = self.compute_aleatoric_uncertainty(X_single, model, domain=domain)epistemic, ood, ens_var = self.compute_epistemic_uncertainty(X_single, ood_detector)# Total Uncertainty is a bounded combination. The raw sum is squashed# through x/(1+x), which is monotone and maps [0, inf) -> [0, 1), so# thresholds like "total_uncertainty > 0.45" mean what they claim to.raw_total = aleatoric * 1.5 + epistemic * 1.0total_uncertainty = float(np.clip(raw_total / (1.0 + raw_total), 0.0, 1.0))return {"aleatoric_uncertainty": aleatoric,