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9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
"""
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,
    }