Spaces:
Running

File size: 5,726 Bytes
0a7b128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
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
"""
Verification script for Libratio Fleet AWS Database Adapter.
Validates table creation, telemetry writing, embedding generation, pgvector-simulated fallback RAG searches, and analytics retrieval.
"""
import sys
import os

# Ensure the root directory is in the path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from environment.aws_database import (
    create_aws_tables,
    setup_aurora_pgvector_table,
    log_step_metrics,
    log_run_telemetry,
    generate_embedding,
    retrieve_historical_context_aws,
    search_trajectories_aws,
    get_runs_analytics_aws,
    BOTO3_AVAILABLE,
    PSYCOPG2_AVAILABLE,
    GEMINI_AVAILABLE,
    EMBEDDING_DIM
)

def run_tests():
    print("=" * 60)
    print("STARTING AWS DATABASE ADAPTER VERIFICATION")
    print("=" * 60)

    # 1. Module & SDK Availability Check
    print("\n[TEST 1] SDK & Environment Check")
    print(f"  boto3 (DynamoDB): {'AVAILABLE' if BOTO3_AVAILABLE else 'UNAVAILABLE'}")
    print(f"  psycopg2 (Aurora PostgreSQL): {'AVAILABLE' if PSYCOPG2_AVAILABLE else 'UNAVAILABLE'}")
    print(f"  google-genai (Gemini Embeddings): {'AVAILABLE' if GEMINI_AVAILABLE else 'UNAVAILABLE'}")
    print(f"  AWS access key: {'SET' if os.getenv('AWS_ACCESS_KEY_ID') else 'NOT SET'}")
    print(f"  Aurora Host: {'SET' if os.getenv('AURORA_PG_HOST') else 'NOT SET'}")
    print(f"  Gemini API Key: {'SET' if os.getenv('GEMINI_API_KEY') else 'NOT SET'}")

    # 2. Table Creation Smoke Test
    print("\n[TEST 2] DynamoDB / Aurora PG Table Initialization Check")
    db_tables_ok = create_aws_tables()
    print(f"  create_aws_tables status: {db_tables_ok}")
    
    pg_tables_ok = setup_aurora_pgvector_table()
    print(f"  setup_aurora_pgvector_table status: {pg_tables_ok}")

    # 3. Embedding Generation Check
    print("\n[TEST 3] Vector Embedding Generation")
    test_text = "Standard LLaMA-3 model training crashed due to FP8 attention overflow."
    vector = generate_embedding(test_text)
    assert isinstance(vector, list), "Embedding must be a list"
    assert len(vector) == EMBEDDING_DIM, f"Embedding dimension must be {EMBEDDING_DIM}, got {len(vector)}"
    assert all(isinstance(v, float) for v in vector), "Embedding values must be floats"
    print(f"  Successfully generated {EMBEDDING_DIM}-dim embedding vector.")
    print(f"  Vector sample (first 3 elements): {vector[:3]}")

    # 4. Telemetry Metrics Logging Check
    print("\n[TEST 4] Telemetry & Metrics Writing")
    step_ok = log_step_metrics(
        task_id="test_verification",
        model_id="llama-test-model",
        step=5,
        reward=0.885,
        memory_used_gb=45.2,
        thermal_risk="LOW",
        power_util=68.5
    )
    assert step_ok is True, "log_step_metrics must return True (even on offline fallback)"
    print("  Step metrics log command executed successfully.")

    run_ok = log_run_telemetry(
        task_id="test_verification",
        model_name="llama-test-model",
        score=0.852,
        steps=10,
        success=True,
        rewards=[0.75, 0.82, 0.85, 0.88, 0.89, 0.90, 0.91, 0.92, 0.80, 0.85]
    )
    assert run_ok is True, "log_run_telemetry must return True (even on offline fallback)"
    print("  Run telemetry log command executed successfully.")

    # 5. RAG Retrieval Search Check
    print("\n[TEST 5] SRE RAG Query Retrieval")
    live_state = {
        "model_name": "llama-3.1-8b-instant",
        "total_params_b": 8.0,
        "memory_used_gb": 120.0,
        "cluster_capacity_gb": 160.0,
        "thermal_risk": "MEDIUM",
        "power_util": 75.0,
        "hardware_profile": "nvidia_h100",
        "vendor": "NVIDIA",
        "available_precisions": ["FP32", "BF16", "FP16", "FP8"]
    }
    context = retrieve_historical_context_aws(live_state, top_k=3)
    assert isinstance(context, str), "RAG context must return a string"
    assert "HISTORICAL CRASH DATA" in context, "RAG context must contain historical section header"
    print("  RAG retrieval context returned successfully.")
    print("-" * 50)
    print(context[:400] + "...")
    print("-" * 50)

    # 6. Hybrid Trajectory Search Check
    print("\n[TEST 6] Search Trajectories Query API Check")
    results = search_trajectories_aws(query="FP8 ffn overflow crash on NVIDIA H100", limit=3)
    assert isinstance(results, list), "Search results must be a list"
    assert len(results) > 0, "Should return at least one trajectory match"
    print(f"  Search returned {len(results)} matches.")
    first_res = results[0]
    required_keys = ["model_name", "outcome", "precision_strategy", "rrf_score"]
    for key in required_keys:
        assert key in first_res, f"Search result item must contain key: {key}"
    print(f"  Top match: {first_res['model_name']} with similarity/RRF score {first_res['rrf_score']:.3f}")

    # 7. Analytics Calculation Check
    print("\n[TEST 7] Runs Analytics Check")
    analytics = get_runs_analytics_aws()
    assert isinstance(analytics, dict), "Analytics must return a dictionary"
    assert "database_status" in analytics, "Analytics must report database status"
    assert "task_analytics" in analytics, "Analytics must report task analytics"
    assert "model_analytics" in analytics, "Analytics must report model analytics"
    print(f"  Analytics DB Status: {analytics['database_status']}")
    print(f"  Total Runs Logged: {analytics.get('total_runs_logged', 0)}")
    print(f"  Task Analytics: {analytics['task_analytics']}")
    print(f"  Model Analytics: {analytics['model_analytics']}")

    print("\n" + "=" * 60)
    print("=== ALL AWS DATABASE ADAPTER TESTS PASSED ===")
    print("=" * 60)


def test_aws_database_adapter():
    run_tests()


if __name__ == "__main__":
    run_tests()