""" Libratio Fleet AWS Database Adapter. Supports Amazon DynamoDB (for step metrics and run telemetry) and Amazon Aurora PostgreSQL with pgvector (for semantic RAG over historical trajectories), with an offline JSON and in-memory fallback when AWS credentials or Aurora hosts are not configured. """ from __future__ import annotations import json import math import os import re import time from datetime import datetime, timezone from decimal import Decimal from pathlib import Path from typing import Any, Dict, List, Optional from dotenv import load_dotenv from mongodb_vector import ( EMBEDDING_DIM, _GEMINI_AVAILABLE as GEMINI_AVAILABLE, generate_embedding, live_state_to_query_text, trajectory_to_text, ) load_dotenv() try: import boto3 from botocore.config import Config as BotoConfig from botocore.exceptions import BotoCoreError, ClientError BOTO3_AVAILABLE = True except ImportError: boto3 = None BotoConfig = None BotoCoreError = Exception ClientError = Exception BOTO3_AVAILABLE = False try: import psycopg2 PSYCOPG2_AVAILABLE = True except ImportError: psycopg2 = None PSYCOPG2_AVAILABLE = False AWS_REGION = os.getenv("AWS_REGION", os.getenv("AWS_DEFAULT_REGION", "us-east-1")) DYNAMODB_STEPS_TABLE = os.getenv("DYNAMODB_STEPS_TABLE", "libratio_step_metrics") DYNAMODB_RUNS_TABLE = os.getenv("DYNAMODB_RUNS_TABLE", "libratio_runs") AURORA_PG_HOST = os.getenv("AURORA_PG_HOST", "") AURORA_PG_PORT = int(os.getenv("AURORA_PG_PORT", "5432")) AURORA_PG_DB = os.getenv("AURORA_PG_DB", "libratio") AURORA_PG_USER = os.getenv("AURORA_PG_USER", "") AURORA_PG_PASSWORD = os.getenv("AURORA_PG_PASSWORD", "") _ROOT_DIR = Path(__file__).resolve().parent.parent _TRAJECTORIES_PATH = _ROOT_DIR / "synthetic_trajectories.json" _dynamodb_resource = None _cached_trajectories: Optional[List[Dict[str, Any]]] = None _local_step_logs: List[Dict[str, Any]] = [] _local_run_logs: List[Dict[str, Any]] = [] def _get_dynamodb_resource(): """Return a cached boto3 DynamoDB resource configured with short timeouts.""" global _dynamodb_resource if not BOTO3_AVAILABLE: return None if not (os.getenv("AWS_ACCESS_KEY_ID") or os.getenv("AWS_PROFILE")): return None if _dynamodb_resource is None: cfg = BotoConfig( retries={"total_max_attempts": 2, "mode": "adaptive"}, connect_timeout=5, read_timeout=10, max_pool_connections=20, ) _dynamodb_resource = boto3.resource("dynamodb", region_name=AWS_REGION, config=cfg) return _dynamodb_resource def _to_decimal_safe(value: Any) -> Any: """Convert Python floats recursively to Decimal for DynamoDB resource writes.""" if isinstance(value, float): return Decimal(str(round(value, 6))) if isinstance(value, list): return [_to_decimal_safe(v) for v in value] if isinstance(value, dict): return {k: _to_decimal_safe(v) for k, v in value.items()} return value def _get_aurora_connection(): """Open an Aurora PostgreSQL connection if configured, else return None.""" if not PSYCOPG2_AVAILABLE or not AURORA_PG_HOST: return None return psycopg2.connect( host=AURORA_PG_HOST, port=AURORA_PG_PORT, dbname=AURORA_PG_DB, user=AURORA_PG_USER, password=AURORA_PG_PASSWORD, connect_timeout=5, ) def create_aws_tables() -> bool: """Create DynamoDB tables if AWS is configured; otherwise confirm offline store.""" ddb = _get_dynamodb_resource() if ddb is None: return True specs = [ ( DYNAMODB_STEPS_TABLE, [{"AttributeName": "run_key", "KeyType": "HASH"}, {"AttributeName": "step", "KeyType": "RANGE"}], [{"AttributeName": "run_key", "AttributeType": "S"}, {"AttributeName": "step", "AttributeType": "N"}], ), ( DYNAMODB_RUNS_TABLE, [{"AttributeName": "run_id", "KeyType": "HASH"}], [{"AttributeName": "run_id", "AttributeType": "S"}], ), ] client = ddb.meta.client for table_name, key_schema, attr_defs in specs: try: client.describe_table(TableName=table_name) except client.exceptions.ResourceNotFoundException: try: ddb.create_table( TableName=table_name, KeySchema=key_schema, AttributeDefinitions=attr_defs, BillingMode="PAY_PER_REQUEST", ) except client.exceptions.ResourceInUseException: pass except (ClientError, BotoCoreError): return False except (ClientError, BotoCoreError): return False return True def setup_aurora_pgvector_table() -> bool: """Ensure the pgvector trajectories table exists in Aurora PostgreSQL.""" if not PSYCOPG2_AVAILABLE or not AURORA_PG_HOST: return True conn = None try: conn = _get_aurora_connection() with conn, conn.cursor() as cur: cur.execute("CREATE EXTENSION IF NOT EXISTS vector;") cur.execute( f""" CREATE TABLE IF NOT EXISTS trajectories ( id SERIAL PRIMARY KEY, model_name TEXT, total_params_b DOUBLE PRECISION, outcome TEXT, failure_reason TEXT, memory_used_gb DOUBLE PRECISION, thermal_risk TEXT, estimated_power_pct DOUBLE PRECISION, precision_strategy JSONB, source_text TEXT, embedding vector({EMBEDDING_DIM}) ); """ ) return True except Exception: return False finally: if conn is not None: conn.close() def log_step_metrics( task_id: str, model_id: str, step: int, reward: float, memory_used_gb: float, thermal_risk: str, power_util: float, ) -> bool: """Persist one step metric record to DynamoDB or local fallback list.""" item = { "run_key": f"{task_id}#{model_id}", "step": int(step), "task_id": str(task_id), "model_id": str(model_id), "reward": float(reward), "memory_used_gb": float(memory_used_gb), "thermal_risk": str(thermal_risk), "power_util": float(power_util), "timestamp": datetime.now(timezone.utc).isoformat(), } _local_step_logs.append(item) ddb = _get_dynamodb_resource() if ddb is None: return True try: table = ddb.Table(DYNAMODB_STEPS_TABLE) table.put_item(Item=_to_decimal_safe(item)) return True except (ClientError, BotoCoreError): return True def log_run_telemetry( task_id: str, model_name: str, score: float, steps: int, success: bool, rewards: List[float], ) -> bool: """Persist one completed episode summary to DynamoDB or local fallback list.""" item = { "run_id": f"{task_id}-{model_name}-{int(time.time() * 1000)}", "task_id": str(task_id), "model_name": str(model_name), "score": float(score), "steps": int(steps), "success": bool(success), "rewards": [float(r) for r in (rewards or [])], "timestamp": datetime.now(timezone.utc).isoformat(), } _local_run_logs.append(item) ddb = _get_dynamodb_resource() if ddb is None: return True try: table = ddb.Table(DYNAMODB_RUNS_TABLE) table.put_item(Item=_to_decimal_safe(item)) return True except (ClientError, BotoCoreError): return True def _load_local_trajectories() -> List[Dict[str, Any]]: """Load flattened trajectory records from synthetic_trajectories.json if present.""" global _cached_trajectories if _cached_trajectories is not None: return _cached_trajectories if _TRAJECTORIES_PATH.exists(): try: with open(_TRAJECTORIES_PATH, "r", encoding="utf-8") as fh: episodes = json.load(fh) flat: List[Dict[str, Any]] = [] for ep in episodes: cap = ep.get("cluster_capacity_gb", 0) ep_id = ep.get("episode_id", 0) for traj in ep.get("trajectories", []): flat.append({**traj, "episode_id": ep_id, "cluster_capacity_gb": cap}) if flat: _cached_trajectories = flat return _cached_trajectories except (OSError, json.JSONDecodeError): pass _cached_trajectories = [ { "model_name": "LLaMA-3-70B", "total_params_b": 70.0, "precision_strategy": { "embedding": "FP8", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32", }, "memory_used_gb": 112.0, "memory_utilization_pct": 87.5, "thermal_risk": "HIGH", "estimated_power_pct": 74.0, "speedup_vs_fp32": 2.1, "outcome": "CRASH_NUMERICAL_INSTABILITY", "failure_reason": "embedding at FP8 (stability=0.0) on NVIDIA H100", }, { "model_name": "LLaMA-3-13B", "total_params_b": 13.0, "precision_strategy": { "embedding": "FP32", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32", }, "memory_used_gb": 22.8, "memory_utilization_pct": 57.0, "thermal_risk": "LOW", "estimated_power_pct": 69.0, "speedup_vs_fp32": 2.15, "outcome": "SUCCESS", }, ] return _cached_trajectories def _cosine_similarity(vec_a: List[float], vec_b: List[float]) -> float: dot = sum(a * b for a, b in zip(vec_a, vec_b)) norm_a = math.sqrt(sum(a * a for a in vec_a)) norm_b = math.sqrt(sum(b * b for b in vec_b)) if norm_a == 0.0 or norm_b == 0.0: return 0.0 return dot / (norm_a * norm_b) def search_trajectories_aws( query: str, limit: int = 5, live_state: Optional[Dict[str, Any]] = None, ) -> List[Dict[str, Any]]: """Search historical trajectories via Aurora pgvector or local hybrid RRF simulation.""" top_k = max(1, int(limit)) query_vec = generate_embedding(query, task_type="RETRIEVAL_QUERY") conn = None try: conn = _get_aurora_connection() if conn is not None: vec_literal = "[" + ",".join(f"{v:.6f}" for v in query_vec) + "]" with conn.cursor() as cur: cur.execute( """ SELECT model_name, total_params_b, outcome, failure_reason, memory_used_gb, thermal_risk, estimated_power_pct, precision_strategy, 1 - (embedding <=> %s::vector) AS similarity FROM trajectories ORDER BY embedding <=> %s::vector LIMIT %s; """, (vec_literal, vec_literal, top_k), ) rows = cur.fetchall() return [ { "model_name": row[0], "total_params_b": row[1], "outcome": row[2], "failure_reason": row[3], "memory_used_gb": row[4], "thermal_risk": row[5], "estimated_power_pct": row[6], "precision_strategy": row[7] or {}, "rrf_score": float(row[8] or 0.0), } for row in rows ] except Exception: pass finally: if conn is not None: conn.close() # Local JSON pgvector + keyword RRF simulation (bounded sample for sub-10ms latency) records = _load_local_trajectories() sample = records[:250] tokens = {tok for tok in re.findall(r"[a-z0-9_]+", query.lower()) if len(tok) > 1} vec_ranked = [] text_ranked = [] for idx, traj in enumerate(sample): text = trajectory_to_text(traj) text_tokens = set(re.findall(r"[a-z0-9_]+", text.lower())) overlap = len(tokens & text_tokens) sim = _cosine_similarity(query_vec, generate_embedding(text, task_type="RETRIEVAL_DOCUMENT")) vec_ranked.append((sim, idx)) text_ranked.append((overlap, idx)) vec_ranked.sort(key=lambda item: item[0], reverse=True) text_ranked.sort(key=lambda item: item[0], reverse=True) k_rrf = 60.0 rrf_scores: Dict[int, float] = {} for rank, (_, idx) in enumerate(vec_ranked[: top_k * 4]): rrf_scores[idx] = rrf_scores.get(idx, 0.0) + 1.0 / (k_rrf + rank + 1) for rank, (overlap, idx) in enumerate(text_ranked[: top_k * 4]): if overlap > 0: rrf_scores[idx] = rrf_scores.get(idx, 0.0) + 1.0 / (k_rrf + rank + 1) if not rrf_scores: for rank, (_, idx) in enumerate(vec_ranked[:top_k]): rrf_scores[idx] = 1.0 / (k_rrf + rank + 1) ordered = sorted(rrf_scores.items(), key=lambda item: item[1], reverse=True)[:top_k] results = [] for idx, score in ordered: item = dict(sample[idx]) item["rrf_score"] = round(score, 4) results.append(item) return results def retrieve_historical_context_aws(live_state: Dict[str, Any], top_k: int = 5) -> str: """Retrieve and format top-k historical trajectories for the predictive SRE prompt.""" query_text = live_state_to_query_text(live_state) results = search_trajectories_aws(query=query_text, limit=top_k, live_state=live_state) if not results: return "HISTORICAL CRASH DATA (AWS Adapter): No matching historical trajectories found." lines = ["HISTORICAL CRASH DATA (Amazon Aurora pgvector / Local RAG Simulation):"] for idx, traj in enumerate(results, 1): strategy = traj.get("precision_strategy", {}) strat_str = ", ".join(f"{k}={v}" for k, v in strategy.items()) if strategy else "unknown" entry = ( f"\n[{idx}] Similarity/RRF: {traj.get('rrf_score', 0.0):.4f}\n" f" Model: {traj.get('model_name', 'unknown')} ({traj.get('total_params_b', '?')}B params)\n" f" Outcome: {traj.get('outcome', 'UNKNOWN')} | " f"VRAM: {traj.get('memory_used_gb', '?')}GB | " f"Thermal: {traj.get('thermal_risk', '?')} | " f"Power: {traj.get('estimated_power_pct', '?')}%\n" f" Strategy: {strat_str}" ) if traj.get("failure_reason"): entry += f"\n Failure: {traj['failure_reason']}" lines.append(entry) return "\n".join(lines) def get_runs_analytics_aws() -> Dict[str, Any]: """Aggregate run telemetry from DynamoDB if configured, else from local runs.""" runs = list(_local_run_logs) db_status = "offline_fallback" ddb = _get_dynamodb_resource() if ddb is not None: try: table = ddb.Table(DYNAMODB_RUNS_TABLE) resp = table.scan(Limit=500) items = resp.get("Items", []) if items: runs = items db_status = "dynamodb_connected" except (ClientError, BotoCoreError): db_status = "dynamodb_fallback" by_task: Dict[str, List[float]] = {} by_task_success: Dict[str, int] = {} by_model: Dict[str, List[float]] = {} for run in runs: tid = str(run.get("task_id", "unknown")) mname = str(run.get("model_name", "unknown")) score = float(run.get("score", 0.0)) by_task.setdefault(tid, []).append(score) if run.get("success"): by_task_success[tid] = by_task_success.get(tid, 0) + 1 by_model.setdefault(mname, []).append(score) task_analytics = [ { "task_id": tid, "avg_score": round(sum(scores) / len(scores), 3), "max_score": round(max(scores), 3), "min_score": round(min(scores), 3), "success_rate_pct": round(100.0 * by_task_success.get(tid, 0) / len(scores), 1), "total_runs": len(scores), } for tid, scores in by_task.items() ] model_analytics = [ { "model_name": mname, "avg_score": round(sum(scores) / len(scores), 3), "total_runs": len(scores), } for mname, scores in by_model.items() ] return { "database_status": db_status, "total_runs_logged": len(runs), "task_analytics": task_analytics, "model_analytics": model_analytics, }