Spaces:
Running

File size: 24,273 Bytes
f7185ba
a97a0bc
0a7b128
 
f7185ba
0a7b128
 
a97a0bc
0a7b128
 
 
 
 
 
 
 
5655786
a97a0bc
 
5655786
 
 
 
 
f7185ba
 
5655786
 
 
 
0a7b128
5655786
 
 
4d76b14
a2f135a
0a7b128
 
 
 
 
409fe68
f7185ba
0a7b128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7185ba
4d76b14
 
0a7b128
 
f7185ba
 
5655786
 
 
 
 
 
 
 
a97a0bc
 
 
 
 
 
 
 
 
 
 
4d76b14
0a7b128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d76b14
 
 
c40a1a9
4d76b14
 
 
 
c40a1a9
f7185ba
 
 
 
a97a0bc
 
4d76b14
 
 
 
 
 
 
 
 
f7185ba
a97a0bc
 
 
 
 
 
 
 
 
4d76b14
 
 
 
 
 
0a7b128
4d76b14
 
 
0a7b128
 
 
 
 
4d76b14
0a7b128
 
 
 
 
 
 
4d76b14
 
 
 
0a7b128
 
 
 
 
4d76b14
0a7b128
4d76b14
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
 
 
 
a2f135a
 
5655786
0a7b128
 
 
 
 
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
5655786
 
0a7b128
5655786
 
 
 
 
 
0a7b128
5655786
0a7b128
5655786
 
0a7b128
5655786
 
 
0a7b128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5655786
 
 
0a7b128
5655786
0a7b128
5655786
 
0a7b128
5655786
 
 
0a7b128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5655786
0a7b128
5655786
0a7b128
 
 
 
 
 
 
5655786
0a7b128
5655786
0a7b128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5655786
 
 
 
a97a0bc
 
 
 
 
0a7b128
 
 
a97a0bc
 
 
0a7b128
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
a97a0bc
0a7b128
a97a0bc
 
 
 
 
 
0a7b128
 
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
a97a0bc
0a7b128
 
 
 
 
 
a97a0bc
0a7b128
 
a97a0bc
 
 
 
 
 
 
 
 
 
 
0a7b128
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
0a7b128
a97a0bc
 
 
 
 
0a7b128
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
a97a0bc
 
 
a2f135a
 
 
 
5655786
0a7b128
5655786
0a7b128
5655786
 
 
0a7b128
5655786
 
 
 
0a7b128
5655786
 
 
 
 
0a7b128
 
 
 
 
 
 
5655786
 
 
0a7b128
5655786
 
 
 
 
 
 
0a7b128
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2f135a
 
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
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
"""
FastAPI application for Libratio Fleet OpenEnv.
Includes per-session fleet isolation, rate limiting, optional API auth,
and MongoDB Atlas analytics/search endpoints.
"""
from collections import OrderedDict, deque
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Dict, List, Optional
import os
import sys
import threading
import time

from dotenv import load_dotenv
from fastapi import Depends, FastAPI, Header, HTTPException, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from pymongo import MongoClient
import certifi

load_dotenv()

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

try:
    from agent.adk_agent import run_fleet_task_with_adk, ADK_AVAILABLE
except ImportError:
    ADK_AVAILABLE = False

    async def run_fleet_task_with_adk(task_id: str = "fleet_precision"):
        return {"error": "google-adk not installed", "adk_available": False}

from environment.fleet_env import FleetEnvironment
from server.models import (
    ResetResponse,
    RewardPayload,
    StateResponse,
    StepResponse,
    TaskDefinition,
)

MONGO_URI = os.getenv("MONGO_URI")
DB_NAME = "libratio"
MAX_SESSIONS = 256
SESSION_TTL_SECONDS = 3600
RATE_LIMIT_WINDOW_SECONDS = 60

_mongo_client: Optional[MongoClient] = None
_mongo_lock = threading.Lock()


def _get_mongo_client() -> Optional[MongoClient]:
    """Return a shared, pooled MongoClient with short selection timeout."""
    global _mongo_client
    if not MONGO_URI:
        return None
    with _mongo_lock:
        if _mongo_client is None:
            _mongo_client = MongoClient(
                MONGO_URI,
                tlsCAFile=certifi.where(),
                serverSelectionTimeoutMS=5000,
            )
        return _mongo_client


@asynccontextmanager
async def lifespan(_app: FastAPI):
    yield
    global _mongo_client
    with _mongo_lock:
        if _mongo_client is not None:
            _mongo_client.close()
            _mongo_client = None


app = FastAPI(
    title="Libratio Fleet β€” Multi-Agent GPU Fleet Management",
    description="OpenEnv for multi-agent GPU cluster precision optimization and fleet oversight",
    version="3.0.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)

ROOT_DIR = Path(__file__).resolve().parent.parent
FRONTEND_DIR = ROOT_DIR / "frontend"
COLAB_GRAPHS_DIR = ROOT_DIR / "colab_graphs"
HF_GRAPHS_DIR = ROOT_DIR / "hf_graphs"
if FRONTEND_DIR.exists():
    app.mount("/frontend", StaticFiles(directory=str(FRONTEND_DIR)), name="frontend")
if COLAB_GRAPHS_DIR.exists():
    app.mount("/colab_graphs", StaticFiles(directory=str(COLAB_GRAPHS_DIR)), name="colab_graphs")
if HF_GRAPHS_DIR.exists():
    app.mount("/hf_graphs", StaticFiles(directory=str(HF_GRAPHS_DIR)), name="hf_graphs")


class _SessionStore:
    """Thread-safe bounded LRU+TTL store isolating FleetEnvironment per caller."""

    def __init__(self, max_sessions: int = MAX_SESSIONS, ttl_seconds: int = SESSION_TTL_SECONDS):
        self.max_sessions = max_sessions
        self.ttl_seconds = ttl_seconds
        self._lock = threading.Lock()
        self._sessions: OrderedDict[str, tuple[float, FleetEnvironment]] = OrderedDict()

    def get_or_create(self, session_id: str) -> FleetEnvironment:
        now = time.monotonic()
        with self._lock:
            expired = [
                sid for sid, (ts, _) in self._sessions.items() if now - ts > self.ttl_seconds
            ]
            for sid in expired:
                del self._sessions[sid]

            if session_id in self._sessions:
                _, env = self._sessions.pop(session_id)
                self._sessions[session_id] = (now, env)
                return env

            while len(self._sessions) >= self.max_sessions:
                self._sessions.popitem(last=False)

            env = FleetEnvironment()
            self._sessions[session_id] = (now, env)
            return env


_session_store = _SessionStore()
fleet_env = _session_store.get_or_create("default")


def _resolve_session_id(request: Request, payload: Optional[dict] = None) -> str:
    """Extract session_id from body, header, or cookie; fall back to 'default'."""
    if isinstance(payload, dict) and payload.get("session_id"):
        return str(payload["session_id"])[:128]
    header_sid = request.headers.get("x-session-id")
    if header_sid:
        return header_sid[:128]
    cookie_sid = request.cookies.get("libratio_sid")
    if cookie_sid:
        return cookie_sid[:128]
    return "default"


_rate_lock = threading.Lock()
_rate_buckets: Dict[str, deque] = {}


def _enforce_rate_limit(request: Request, bucket: str, max_calls: int = 20) -> None:
    """Simple per-IP sliding-window rate limiter to protect heavy/paid endpoints."""
    client_ip = request.client.host if request.client else "unknown"
    key = f"{bucket}:{client_ip}"
    now = time.monotonic()
    with _rate_lock:
        dq = _rate_buckets.setdefault(key, deque())
        while dq and now - dq[0] > RATE_LIMIT_WINDOW_SECONDS:
            dq.popleft()
        if len(dq) >= max_calls:
            raise HTTPException(status_code=429, detail="Rate limit exceeded. Try again shortly.")
        dq.append(now)


def _require_api_auth(
    authorization: Optional[str] = Header(default=None),
    x_api_key: Optional[str] = Header(default=None),
    allow_unconfigured: bool = False,
) -> None:
    """Protect costly/mutating endpoints with LIBRATIO_API_KEY when configured."""
    expected_key = os.getenv("LIBRATIO_API_KEY", "").strip()
    if not expected_key:
        if allow_unconfigured:
            return
        if os.getenv("LIBRATIO_ALLOW_UNAUTH_ADK", "false").lower() == "true":
            return
        raise HTTPException(
            status_code=403,
            detail="Endpoint disabled until LIBRATIO_API_KEY (or LIBRATIO_ALLOW_UNAUTH_ADK=true) is set.",
        )

    bearer = ""
    if authorization and authorization.lower().startswith("bearer "):
        bearer = authorization[7:].strip()
    provided = x_api_key or bearer
    if provided != expected_key:
        raise HTTPException(status_code=401, detail="Invalid or missing API key.")


def _require_search_auth(
    authorization: Optional[str] = Header(default=None),
    x_api_key: Optional[str] = Header(default=None),
) -> None:
    _require_api_auth(authorization=authorization, x_api_key=x_api_key, allow_unconfigured=True)


def _clamp_score(raw_score) -> float:
    """Defense-in-depth: clamp score to strict (0.01, 0.99) interval."""
    try:
        val = float(raw_score)
    except (ValueError, TypeError):
        val = 0.01
    return float(max(0.01, min(0.99, val)))


@app.get("/")
def root():
    if FRONTEND_DIR.exists():
        return FileResponse(str(FRONTEND_DIR / "index.html"))
    return {
        "status": "ok",
        "environment": "Libratio Fleet β€” Multi-Agent GPU Fleet Management",
        "version": "3.0.0",
        "modes": {
            "fleet": "Multi-agent fleet environment (/fleet/reset, /fleet/step, /fleet/state, /fleet/tasks)",
        },
    }


@app.get("/health")
def health():
    return {
        "status": "ok",
        "environment": "Libratio Fleet β€” Multi-Agent GPU Fleet Management",
        "version": "3.0.0",
    }


# ═══════════════════════════════════════════════════════════
# FLEET MODE β€” Multi-agent fleet endpoints
# ═══════════════════════════════════════════════════════════

@app.get("/fleet/tasks", response_model=List[TaskDefinition])
def get_fleet_tasks() -> List[TaskDefinition]:
    return [TaskDefinition(**t) for t in FleetEnvironment.TASK_DEFS]


@app.post("/fleet/reset", response_model=ResetResponse)
def reset_fleet(request: Request, response: Response, payload: dict = {}):
    if not isinstance(payload, dict):
        raise HTTPException(status_code=400, detail="Request body must be a JSON object.")
    sid = _resolve_session_id(request, payload)
    env = _session_store.get_or_create(sid)
    task_id = payload.get("task_id", "fleet_precision")
    scenario_id = payload.get("scenario_id")
    try:
        obs = env.reset(task_id, scenario_id=scenario_id)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    if sid != "default" and not request.cookies.get("libratio_sid"):
        response.set_cookie("libratio_sid", sid, httponly=True, samesite="lax")
    return ResetResponse(observation=obs)


@app.post("/fleet/step", response_model=StepResponse)
def step_fleet(request: Request, payload: dict = {}):
    if not isinstance(payload, dict):
        raise HTTPException(status_code=400, detail="Request body must be a JSON object.")
    sid = _resolve_session_id(request, payload)
    env = _session_store.get_or_create(sid)
    action = payload.get("action", payload)
    result = env.step(action)
    clamped_score = _clamp_score(result["reward"]["score"])
    return StepResponse(
        observation=result["observation"],
        reward=RewardPayload(
            score=clamped_score,
            feedback=result["reward"]["feedback"],
        ),
        done=result["done"],
        info=result.get("info", {}),
    )


@app.post("/fleet/state", response_model=StateResponse)
def get_fleet_state(request: Request, payload: dict = {}):
    sid = _resolve_session_id(request, payload if isinstance(payload, dict) else None)
    env = _session_store.get_or_create(sid)
    return StateResponse(**env.state())


@app.get("/api/analytics")
def get_fleet_analytics(request: Request):
    """Expose fleet analytics aggregated via MongoDB pipelines."""
    _enforce_rate_limit(request, "analytics", max_calls=30)
    client_mongo = _get_mongo_client()
    if client_mongo is None:
        return {"database_status": "not_configured", "error": "MONGO_URI not set in env"}

    try:
        db_mongo = client_mongo[DB_NAME]
        runs_col = db_mongo["runs"]

        pipeline_tasks = [
            {
                "$group": {
                    "_id": "$task_id",
                    "avg_score": {"$avg": "$score"},
                    "max_score": {"$max": "$score"},
                    "min_score": {"$min": "$score"},
                    "success_rate": {
                        "$avg": {
                            "$cond": [{"$eq": ["$success", True]}, 1.0, 0.0]
                        }
                    },
                    "total_runs": {"$sum": 1},
                }
            },
            {"$sort": {"avg_score": -1}},
        ]
        task_stats = list(runs_col.aggregate(pipeline_tasks))

        pipeline_models = [
            {
                "$group": {
                    "_id": {"$ifNull": ["$model_name", "$model"]},
                    "avg_score": {"$avg": "$score"},
                    "total_runs": {"$sum": 1},
                }
            },
            {"$sort": {"avg_score": -1}},
        ]
        model_stats = list(runs_col.aggregate(pipeline_models))

        formatted_tasks = [
            {
                "task_id": t.get("_id") or "unknown",
                "avg_score": round(float(t.get("avg_score") or 0.0), 3),
                "max_score": round(float(t.get("max_score") or 0.0), 3),
                "min_score": round(float(t.get("min_score") or 0.0), 3),
                "success_rate_pct": round(float(t.get("success_rate") or 0.0) * 100.0, 1),
                "total_runs": int(t.get("total_runs") or 0),
            }
            for t in task_stats
        ]

        formatted_models = [
            {
                "model_name": m.get("_id") or "unknown",
                "avg_score": round(float(m.get("avg_score") or 0.0), 3),
                "total_runs": int(m.get("total_runs") or 0),
            }
            for m in model_stats
        ]

        return {
            "database_status": "connected",
            "total_runs_logged": sum(t["total_runs"] for t in formatted_tasks),
            "task_analytics": formatted_tasks,
            "model_analytics": formatted_models,
        }
    except Exception as e:
        return {"database_status": "failed_connection", "error": str(e)}


@app.get("/api/search")
def search_trajectories(
    request: Request,
    query: str,
    type: str = "hybrid",
    limit: int = 5,
    _auth: None = Depends(_require_search_auth),
):
    """Search historical trajectories using shared MongoDB Atlas Search helpers."""
    _enforce_rate_limit(request, "search", max_calls=20)
    if not query.strip():
        raise HTTPException(status_code=400, detail="Query parameter must not be empty.")
    safe_limit = max(1, min(int(limit), 50))

    client_mongo = _get_mongo_client()
    if client_mongo is None:
        return {"error": "MONGO_URI not set in env"}

    try:
        from mongodb_vector import (
            hybrid_search_similar_trajectories,
            text_search_similar_trajectories,
            vector_search_similar_trajectories,
        )

        collection = client_mongo[DB_NAME]["trajectories"]
        if type == "text":
            results = text_search_similar_trajectories(collection, query, top_k=safe_limit)
        elif type == "vector":
            results = vector_search_similar_trajectories(
                collection, {"query": query}, top_k=safe_limit
            )
        else:
            results = hybrid_search_similar_trajectories(
                collection, query, {"query": query}, top_k=safe_limit
            )

        return {
            "status": "success",
            "query": query,
            "type": type,
            "count": len(results),
            "results": results,
        }
    except Exception as e:
        return {"status": "error", "message": str(e)}


# ═══════════════════════════════════════════════════════════
# AGENTIC KERNEL β€” Live Performance Benchmarking
# ═══════════════════════════════════════════════════════════

@app.get("/kernel/benchmark")
def kernel_benchmark(request: Request):
    """Run a live benchmark of the Agentic Kernel physics engine."""
    _enforce_rate_limit(request, "benchmark", max_calls=15)
    import random as _rnd
    from environment.physics_model import (
        compute_hardware_safety,
        compute_training_cost,
        score_precision_layer,
    )

    NUM_TRAJECTORIES = 1000
    precisions = ["FP32", "BF16", "FP16", "FP8"]
    layers = ["embedding", "attention", "ffn", "layernorm", "output"]
    layer_dist = {
        "embedding": 0.05, "attention": 0.35, "ffn": 0.45,
        "layernorm": 0.05, "output": 0.10,
    }

    start = time.perf_counter_ns()
    for _ in range(NUM_TRAJECTORIES):
        strategy = {l: _rnd.choice(precisions) for l in layers}
        params = _rnd.choice([3_000_000_000, 7_000_000_000, 13_000_000_000, 70_000_000_000])
        compute_training_cost(
            total_params=params,
            precision_strategy=strategy,
            layer_distribution=layer_dist,
        )
    cost_ns = time.perf_counter_ns() - start

    start = time.perf_counter_ns()
    for _ in range(NUM_TRAJECTORIES):
        strategy = {l: _rnd.choice(precisions) for l in layers}
        params = _rnd.choice([3_000_000_000, 7_000_000_000, 13_000_000_000])
        compute_hardware_safety(
            total_params=params,
            precision_strategy=strategy,
            layer_distribution=layer_dist,
            num_gpus=_rnd.choice([1, 2, 4, 8]),
            gpu_memory_gb=80.0,
        )
    safety_ns = time.perf_counter_ns() - start

    start = time.perf_counter_ns()
    for _ in range(NUM_TRAJECTORIES):
        for l in layers:
            score_precision_layer(l, _rnd.choice(precisions))
    scoring_ns = time.perf_counter_ns() - start

    bench_env = FleetEnvironment()
    start = time.perf_counter_ns()
    cycle_count = 200
    for _ in range(cycle_count):
        bench_env.reset("fleet_precision")
        bench_env.step({
            "precision_strategy": {
                "embedding": "FP32", "attention": "BF16", "ffn": "FP8",
                "layernorm": "BF16", "output": "FP32",
            },
            "reasoning": "benchmark",
        })
    env_ns = time.perf_counter_ns() - start

    total_ns = cost_ns + safety_ns + scoring_ns
    per_trajectory_us = (total_ns / NUM_TRAJECTORIES) / 1000

    docker_cold_start_ms = 150
    microvm_cold_start_ms = 125

    return {
        "kernel_version": "1.0.0",
        "trajectories_evaluated": NUM_TRAJECTORIES,
        "timing": {
            "cost_model_total_us": round(cost_ns / 1000, 1),
            "cost_model_per_eval_us": round(cost_ns / NUM_TRAJECTORIES / 1000, 2),
            "safety_check_total_us": round(safety_ns / 1000, 1),
            "safety_check_per_eval_us": round(safety_ns / NUM_TRAJECTORIES / 1000, 2),
            "layer_scoring_total_us": round(scoring_ns / 1000, 1),
            "layer_scoring_per_eval_us": round(scoring_ns / NUM_TRAJECTORIES / 1000, 2),
            "full_env_cycle_per_eval_us": round(env_ns / cycle_count / 1000, 2),
            "total_per_trajectory_us": round(per_trajectory_us, 2),
        },
        "throughput": {
            "trajectories_per_second": round(1_000_000 / per_trajectory_us) if per_trajectory_us > 0 else 999999,
            "speedup_vs_docker": round(docker_cold_start_ms * 1000 / per_trajectory_us, 0) if per_trajectory_us > 0 else 999999,
            "speedup_vs_microvm": round(microvm_cold_start_ms * 1000 / per_trajectory_us, 0) if per_trajectory_us > 0 else 999999,
        },
        "comparison": {
            "agentic_kernel_us": round(per_trajectory_us, 2),
            "docker_container_ms": docker_cold_start_ms,
            "firecracker_microvm_ms": microvm_cold_start_ms,
            "sandbox_ratio_solved": per_trajectory_us < 1000,
        },
    }


@app.get("/kernel/profile")
def kernel_profile():
    """Profile each kernel module individually."""
    from environment.physics_model import (
        ACCURACY_PENALTY,
        BYTES_PER_PARAM,
        POWER_DRAW_MULTIPLIER,
        STABILITY_SCORE,
        THROUGHPUT_MULTIPLIER,
        compute_hardware_safety,
        compute_network_topology,
        compute_training_cost,
        score_precision_layer,
    )

    layers = ["embedding", "attention", "ffn", "layernorm", "output"]
    layer_dist = {
        "embedding": 0.05, "attention": 0.35, "ffn": 0.45,
        "layernorm": 0.05, "output": 0.10,
    }
    strategy = {
        "embedding": "FP32", "attention": "BF16", "ffn": "FP8",
        "layernorm": "BF16", "output": "FP32",
    }
    params = 7_000_000_000

    modules = {}

    start = time.perf_counter_ns()
    result = compute_training_cost(params, strategy, layer_dist)
    modules["precision_kernel"] = {
        "latency_us": round((time.perf_counter_ns() - start) / 1000, 2),
        "description": "VRAM, throughput, cost, stability evaluation",
        "outputs": {
            "memory_gb": result["memory_gb"],
            "speedup_vs_fp32": result["speedup_vs_fp32"],
            "cost_usd": result["cost_usd"],
            "estimated_stable": result["estimated_stable"],
            "accuracy_retention": result["accuracy_retention"],
        },
    }

    start = time.perf_counter_ns()
    hw = compute_hardware_safety(params, strategy, layer_dist, num_gpus=4, gpu_memory_gb=80.0)
    modules["safety_kernel"] = {
        "latency_us": round((time.perf_counter_ns() - start) / 1000, 2),
        "description": "Thermal, power, memory utilization checks",
        "outputs": {
            "memory_per_gpu_gb": hw["memory_per_gpu_gb"],
            "memory_utilization_pct": hw["memory_utilization_pct"],
            "thermal_risk": hw["thermal_risk"],
            "overall_safe": hw["overall_safe"],
        },
    }

    start = time.perf_counter_ns()
    layer_results = {}
    for l in layers:
        score, _ = score_precision_layer(l, strategy.get(l, "FP32"))
        layer_results[l] = {"score": score, "precision": strategy.get(l, "FP32")}
    modules["scoring_kernel"] = {
        "latency_us": round((time.perf_counter_ns() - start) / 1000, 2),
        "description": "Per-layer precision quality scoring",
        "outputs": layer_results,
    }

    start = time.perf_counter_ns()
    net = compute_network_topology("PCIe_Gen4", tensor_parallel_size=8, pipeline_parallel_size=1)
    modules["network_kernel"] = {
        "latency_us": round((time.perf_counter_ns() - start) / 1000, 2),
        "description": "Multi-GPU topology bottleneck analysis",
        "outputs": {
            "topology": net["topology"],
            "effective_throughput_pct": net["effective_throughput_pct"],
            "bottleneck_risk": net["bottleneck_risk"],
        },
    }

    total_latency = sum(m["latency_us"] for m in modules.values())

    return {
        "profile_model": "LLaMA-3-7B",
        "profile_strategy": strategy,
        "modules": modules,
        "total_kernel_latency_us": round(total_latency, 2),
        "physics_constants_loaded": {
            "precision_formats": len(BYTES_PER_PARAM),
            "layer_types": len(STABILITY_SCORE),
            "stability_rules": sum(len(v) for v in STABILITY_SCORE.values()),
            "throughput_rules": sum(len(v) for v in THROUGHPUT_MULTIPLIER.values()),
            "source": "NVIDIA Transformer Engine + Micikevicius et al. 2018/2022",
        },
    }


def main():
    import uvicorn
    uvicorn.run("server.app:app", host="0.0.0.0", port=7860)


# ═══════════════════════════════════════════════════════════
# GOOGLE ADK AGENT ENDPOINTS
# ═══════════════════════════════════════════════════════════

@app.get("/adk/status")
def adk_status():
    """Check whether the Google ADK agent and MongoDB MCP server are available."""
    return {
        "adk_available": ADK_AVAILABLE,
        "mongodb_mcp": "enabled" if ADK_AVAILABLE else "requires google-adk and mcp packages",
        "agent_model": os.getenv("ADK_MODEL", "gemini-2.0-flash"),
        "install_command": "pip install -r requirements-extras.txt" if not ADK_AVAILABLE else None,
        "description": "Google Cloud Agent Builder (ADK) + MongoDB MCP Server integration",
    }


@app.post("/adk/run")
async def run_adk_agent(
    request: Request,
    payload: dict = {},
    _auth: None = Depends(_require_api_auth),
):
    """Run the Libratio Fleet Agent using Google ADK + MongoDB MCP Server."""
    _enforce_rate_limit(request, "adk_run", max_calls=5)
    if not ADK_AVAILABLE:
        return {
            "error": "Google ADK not installed",
            "fix": "pip install -r requirements-extras.txt",
            "adk_available": False,
        }

    task_id = payload.get("task_id", "fleet_precision")
    valid_tasks = ["fleet_precision", "fleet_oversight", "fleet_resource", "fleet_recovery"]

    if task_id not in valid_tasks:
        raise HTTPException(status_code=400, detail=f"Invalid task_id. Choose from: {valid_tasks}")

    try:
        result = await run_fleet_task_with_adk(task_id)
        return {
            "status": "completed",
            "agent": "LibratioFleetCommander",
            "framework": "Google ADK (Agent Development Kit)",
            "partner_integration": "MongoDB MCP Server (@mongodb-js/mongodb-mcp-server)",
            **result,
        }
    except Exception as e:
        return {
            "status": "error",
            "error": str(e),
            "task_id": task_id,
        }


if __name__ == "__main__":
    main()