Spaces:
Running

File size: 3,565 Bytes
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
5655786
 
 
 
 
 
 
 
 
 
 
0a7b128
 
 
5655786
 
0a7b128
 
5655786
 
0a7b128
 
 
 
 
 
 
 
 
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
MongoDB Time Series Metrics Logging — Libratio Fleet
===================================================
Uses MongoDB's native Time Series collections to store step-by-step performance
telemetry (VRAM, thermal status, reward, power draw) from multi-agent training runs.

Why Time Series Collections?
- Highly optimized storage for sequential measurements over time.
- Automatic compression of metrics (reduces disk footprint by up to 95%).
- Efficient querying by time windows, intervals, and aggregations.
- Demonstrates advanced MongoDB capabilities to hackathon judges.
"""

import os
import threading
from datetime import datetime, timezone
from pymongo import MongoClient
import certifi
from dotenv import load_dotenv

load_dotenv()

MONGO_URI = os.getenv("MONGO_URI")
DB_NAME = "libratio"
METRICS_COLLECTION = "gpu_telemetry_metrics"

_metrics_client = None
_metrics_lock = threading.Lock()


def get_mongo_client():
    """Return a shared, pooled MongoClient with a 5s selection timeout."""
    global _metrics_client
    if not MONGO_URI:
        return None
    with _metrics_lock:
        if _metrics_client is None:
            try:
                _metrics_client = MongoClient(
                    MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=5000
                )
            except Exception:
                return None
        return _metrics_client


def create_metrics_timeseries_collection() -> bool:
    """
    Creates a native MongoDB Time Series collection if it doesn't already exist.
    """
    client = get_mongo_client()
    if not client:
        print("[WARN] MONGO_URI not configured. Skipping Time Series creation.")
        return False

    db = client[DB_NAME]

    # Check if the collection already exists
    if METRICS_COLLECTION in db.list_collection_names():
        print(f"  [INFO] Time Series collection '{METRICS_COLLECTION}' already exists.")
        return True

    try:
        db.create_collection(
            METRICS_COLLECTION,
            timeseries={
                "timeField": "timestamp",
                "metaField": "metadata",
                "granularity": "seconds",
            }
        )
        print(f"  [OK] Created native MongoDB Time Series collection '{METRICS_COLLECTION}'!")
        return True
    except Exception as e:
        print(f"  [WARN] Failed to create native Time Series collection: {e}")
        print("     (Usually means the database user does not have 'createCollection' permission)")
        return False


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:
    """
    Logs a single measurement point to the Time Series collection.
    """
    client = get_mongo_client()
    if not client:
        return False

    try:
        db = client[DB_NAME]
        col = db[METRICS_COLLECTION]

        metric_doc = {
            "timestamp": datetime.now(timezone.utc),
            "metadata": {
                "task_id": task_id,
                "model_id": model_id,
            },
            "step": step,
            "reward": float(reward),
            "memory_used_gb": float(memory_used_gb),
            "thermal_risk": str(thermal_risk),
            "power_util": float(power_util),
        }

        col.insert_one(metric_doc)
        return True
    except Exception:
        return False


if __name__ == "__main__":
    print("Initializing Time Series collection...")
    create_metrics_timeseries_collection()