import os import sqlite3 import pickle import pandas as pd import numpy as np import datetime from pathlib import Path from database import get_db_connection from outcome_learning import ingest_real_outcome, get_repayment_loss_weights from feature_trust_engine import FeatureTrustEngine from open_banking_streams import StreamingBankingMonitor from adaptive_calibration import AdaptiveCalibrationEngine from macro_adaptation import MacroAdaptationEngine from human_feedback_learning import HumanFeedbackEngine from archetype_evolution import ArchetypeEvolutionEngine, ARCHETYPE_LABELS from learning_governance import LearningGovernanceGatekeeper class ContinuousLearningOrchestrator: """Consolidated orchestrator feeding on transaction streams, outcomes, overrides, and macro updates.""" def __init__(self, db_path, models_dir=None): self.db_path = db_path # Default models dir if models_dir is None: self.models_dir = Path(__file__).resolve().parent / "models" else: self.models_dir = models_dir self.trust_engine = FeatureTrustEngine(db_path) self.stream_monitor = StreamingBankingMonitor(db_path) self.calibration_engine = AdaptiveCalibrationEngine(db_path) self.macro_engine = MacroAdaptationEngine() self.feedback_engine = HumanFeedbackEngine(db_path) self.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: user_id (int): Target user df_transactions (DataFrame): Streaming transaction updates outcomes (list): Optional true outcome structures to ingest overrides (dict): Optional manual overrides to log macro_regime (dict): Optional macro regime indicators """ import uuid print(f"\n--- [CONTINUOUS UPDATE] Ingesting streams for User ID {user_id} ---") # 0. Check user existence and update profile fields conn = get_db_connection(self.db_path) cursor = conn.cursor() cursor.execute("SELECT 1 FROM users WHERE user_id = ?", (user_id,)) exists = cursor.fetchone() # Determine age and dob from overrides if possible age = 30 dob = "1996-01-01" if overrides: if "dob" in overrides: dob = overrides["dob"] try: dob_date = datetime.datetime.strptime(dob, "%Y-%m-%d") age = (datetime.datetime.now() - dob_date).days // 365 except Exception: pass elif "age" in overrides: age = int(overrides["age"]) dob = (datetime.datetime.now() - datetime.timedelta(days=age*365.25)).strftime("%Y-%m-%d") if not exists: # Create a default user profile using overrides if available impulse_spending = overrides.get("impulse_spending", 2) if overrides else 2 tracking_habits = overrides.get("tracking_habits", 2) if overrides else 2 income_stability_report = overrides.get("income_stability_report", 2) if overrides else 2 debt_self_report = float(overrides.get("debt_self_report", 0.0)) if overrides else 0.0 savings_habits = overrides.get("savings_habits", 2) if overrides else 2 credit_score = overrides.get("credit_score", 700) if overrides else 700 cursor.execute(""" INSERT INTO users ( user_id, age, dob, gross_income, net_income, employment_status, housing_type, dependents, financial_goals, impulse_spending, tracking_habits, income_stability_report, debt_self_report, savings_habits, credit_score ) VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'SAVING', ?, ?, ?, ?, ?, ?) """, ( user_id, age, dob, float(overrides.get("gross_income", 3000.0)) if overrides else 3000.0, float(overrides.get("gross_income", 3000.0)) * 0.8 if overrides else 2400.0, overrides.get("employment_status", "EMPLOYED") if overrides else "EMPLOYED", overrides.get("housing_type", "RENT") if overrides else "RENT", impulse_spending, tracking_habits, income_stability_report, debt_self_report, savings_habits, credit_score )) # Create a default CHECKING account if not exists cursor.execute("SELECT 1 FROM accounts WHERE user_id = ? AND account_type = 'CHECKING'", (user_id,)) if not cursor.fetchone(): cursor.execute(""" INSERT INTO accounts (account_id, user_id, account_type, balance, credit_limit, overdraft_limit, status, created_at) VALUES (?, ?, 'CHECKING', 0.0, 1000.0, 500.0, 'ACTIVE', ?) """, (f"cz_{user_id}", user_id, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) else: # Update user profile if overrides are passed if overrides: update_fields = [] update_params = [] profile_keys = [ "employment_status", "housing_type", "gross_income", "credit_score", "impulse_spending", "tracking_habits", "income_stability_report", "debt_self_report", "savings_habits" ] for key in profile_keys: if key in overrides: update_fields.append(f"{key} = ?") val = overrides[key] if key == "gross_income": update_fields.append("net_income = ?") update_params.append(float(val)) update_params.append(float(val) * 0.8) elif key == "debt_self_report": update_params.append(float(val)) else: update_params.append(val) if "dob" in overrides or "age" in overrides: update_fields.append("dob = ?") update_fields.append("age = ?") update_params.append(dob) update_params.append(age) if update_fields: query = f"UPDATE users SET {', '.join(update_fields)} WHERE user_id = ?" update_params.append(user_id) cursor.execute(query, update_params) conn.commit() conn.close() # Ingest or update linked accounts if passed if 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: continue cursor.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.0 status = 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 accounts SET 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 alerts if 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 DB conn = get_db_connection(self.db_path) cursor = conn.cursor() # Fetch fallback checking account ID for this user once cursor.execute("SELECT account_id FROM accounts WHERE user_id = ? AND account_type = 'CHECKING'", (user_id,)) row_acc = cursor.fetchone() checking_acc_id = row_acc[0] if row_acc else f"cz_{user_id}" # Prepare transaction records tx_records = [] for _, tx in df_transactions.iterrows(): tx_id = tx.get("transaction_id") or str(uuid.uuid4())[:18] acc_id = tx.get("account_id") or checking_acc_id tx_records.append({ "transaction_id": tx_id, "account_id": acc_id, "user_id": user_id, "transaction_date": tx.get("transaction_date"), "amount": float(tx.get("amount")), "category": tx.get("category"), "description": tx.get("description", ""), "is_failed": int(tx.get("is_failed", 0)) }) # Query existing transaction IDs in a single batch to avoid N+1 query overhead existing_ids = set() if tx_records: # Chunk list to prevent exceeding SQL parameter limit batch_size = 500 all_ids = [r["transaction_id"] for r in tx_records] for i in range(0, len(all_ids), batch_size): chunk = all_ids[i:i+batch_size] placeholders = ",".join(["?"] * len(chunk)) query = f"SELECT transaction_id FROM transactions WHERE transaction_id IN ({placeholders})" cursor.execute(query, chunk) existing_ids.update(row[0] for row in cursor.fetchall()) # Filter duplicates and perform batch operations new_records = [r for r in tx_records if r["transaction_id"] not in existing_ids] if new_records: # Batch insert new transactions insert_data = [ ( r["transaction_id"], r["account_id"], r["user_id"], r["transaction_date"], r["amount"], r["category"], r["description"], r["is_failed"] ) for r in new_records ] cursor.executemany(""" INSERT INTO transactions (transaction_id, account_id, user_id, transaction_date, amount, category, description, is_failed) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """, insert_data) # Aggregate and execute balance updates per unique account account_balance_deltas = {} for r in new_records: acc_id = r["account_id"] account_balance_deltas[acc_id] = account_balance_deltas.get(acc_id, 0.0) + r["amount"] for acc_id, delta in account_balance_deltas.items(): cursor.execute(""" UPDATE accounts SET balance = balance + ? WHERE account_id = ? """, (delta, acc_id)) conn.commit() conn.close() # 2. Ingest real outcomes if outcomes: for out in outcomes: ingest_real_outcome( self.db_path, user_id, out["outcome_type"], days_past_due=out.get("days_past_due", 0), amount=out.get("amount", 0.0) ) print(f" Logged {len(outcomes)} repayment outcomes.") # 3. Ingest human overrides if overrides: self.feedback_engine.log_override( user_id=user_id, analyst_id=overrides.get("analyst_id", "ANALYST_01"), action_taken=overrides.get("action_taken", "APPROVE_OVERRIDE"), original_decision=overrides.get("original_decision", "APPROVED"), new_decision=overrides.get("new_decision", "APPROVED"), original_limit=overrides.get("original_credit_limit", 1000.0), new_limit=overrides.get("new_credit_limit", 1000.0), reviewer_confidence=overrides.get("reviewer_confidence", 1.0) ) print(" Logged reviewer feedback overrides.") # 4. Ingest macro conditions if macro_regime: self.macro_engine.detect_and_update_regime( inflation_rate=macro_regime.get("inflation_rate", 0.02), gdp_growth_rate=macro_regime.get("gdp_growth_rate", 0.025), unemployment_rate=macro_regime.get("unemployment_rate", 0.04) ) # 5. Evaluate and update feature trust logs (fts) # Load metadata to get feature list meta_path = self.models_dir / "model_metadata.pkl" if os.path.exists(meta_path): with open(meta_path, "rb") as f: meta = pickle.load(f) feat_names = meta["feature_names"] # Mock importances importances = {f: 0.02 for f in feat_names} # Run FTS logs self.trust_engine.evaluate_and_log_all_features( model_version=f"xgb_{meta.get('timestamp', 'v1.0')}", df_test=pd.DataFrame(), feature_importances=importances, feature_names=feat_names ) # 6. Cluster updates (archetype evolution) from features import compute_user_features df_feat = compute_user_features(self.db_path, [user_id], datetime.datetime.now()) if not df_feat.empty and os.path.exists(meta_path): from models.train import NUMERICAL_FEATURES self.archetype_engine.fit_incremental(df_feat, NUMERICAL_FEATURES) # 7. Check calibration deterioration & run rolling checks # Query predictions to assess ECE # Calibration is measured against OBSERVED outcomes only. This previously # generated y_true with np.random.choice, so the resulting ECE, the # recalibration verdict and the calibration_memory row that # /shadow-learning-status reports were all derived from coin flips. if os.path.exists(meta_path): from adaptive_calibration import fetch_matured_calibration_pairs y_true, y_prob, cal_meta = fetch_matured_calibration_pairs( self.db_path, model_version=f"xgb_{meta.get('timestamp', 'v1.0')}", target="default") if not cal_meta["sufficient"]: print(f" [CALIBRATION] Skipped: {cal_meta['reason']}") else: cal_report = self.calibration_engine.track_calibration_deterioration( model_version=f"xgb_{meta.get('timestamp', 'v1.0')}", y_true=y_true, y_prob=y_prob ) print(f" [CALIBRATION] Assessed on {cal_meta['matched_pairs']} matured outcomes " f"(positive rate {cal_meta['positive_rate']:.3f})") if cal_report["recalibration_triggered"]: print(f" [CALIBRATION ALERT] {cal_report['reason']}") # 8. Multi-Account continuous adaptation: learn transfer patterns, adapt visibility priors print(" Analyzing multi-account transfer patterns and updating visibility priors...") try: from multi_account_intelligence import MultiAccountAggregator ma_aggregator = MultiAccountAggregator(self.db_path) ma_profile = ma_aggregator.aggregate_entity_profile(user_id, datetime.datetime.now()) reconciled_transfers = ma_profile.get("transfer_reconciliation_summary", {}) visibility_gov = ma_profile.get("visibility_governance", {}) priors_path = self.models_dir / "multi_account_priors.pkl" priors = {} if priors_path.exists(): try: with open(priors_path, "rb") as f: priors = pickle.load(f) except Exception: priors = {} user_priors = priors.setdefault(str(user_id), {}) user_priors["linkage_confidence"] = float(visibility_gov.get("visibility_score", 1.0)) user_priors["observed_unreconciled_transfers"] = reconciled_transfers.get("reconciled_transfer_count", 0) user_priors["hidden_debt_probability"] = float(visibility_gov.get("hidden_debt_probability", 0.10)) user_priors["last_updated"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open(priors_path, "wb") as f: pickle.dump(priors, f) print(f" [MULTI-ACCOUNT ADAPTATION] Updated visibility priors for User {user_id}: linkage confidence = {user_priors['linkage_confidence']:.2f}") except Exception as e_ma: print(f" [MULTI-ACCOUNT ADAPTATION WARNING] Failed to adapt multi-account priors: {e_ma}") print("Continuous learning streams processing completed successfully.")