ioc-scope-api 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. ioc_scope_api-1.0.0.dist-info/METADATA +306 -0
  2. ioc_scope_api-1.0.0.dist-info/RECORD +106 -0
  3. ioc_scope_api-1.0.0.dist-info/WHEEL +4 -0
  4. ioc_scope_api-1.0.0.dist-info/entry_points.txt +2 -0
  5. scope/__init__.py +27 -0
  6. scope/api/__init__.py +119 -0
  7. scope/api/api_v1/__init__.py +2 -0
  8. scope/api/api_v1/api.py +71 -0
  9. scope/api/api_v1/endpoints/__init__.py +2 -0
  10. scope/api/api_v1/endpoints/agentic_protocols_metrics.py +39 -0
  11. scope/api/api_v1/endpoints/applications.py +440 -0
  12. scope/api/api_v1/endpoints/cache.py +50 -0
  13. scope/api/api_v1/endpoints/concepts.py +123 -0
  14. scope/api/api_v1/endpoints/features.py +19 -0
  15. scope/api/api_v1/endpoints/helpers.py +65 -0
  16. scope/api/api_v1/endpoints/kg.py +195 -0
  17. scope/api/api_v1/endpoints/labels.py +71 -0
  18. scope/api/api_v1/endpoints/live_topology.py +89 -0
  19. scope/api/api_v1/endpoints/metrics.py +1014 -0
  20. scope/api/api_v1/endpoints/reasoning.py +62 -0
  21. scope/api/api_v1/endpoints/semanticgroups.py +144 -0
  22. scope/api/api_v1/endpoints/sessions.py +339 -0
  23. scope/api/api_v1/endpoints/spans.py +41 -0
  24. scope/api/api_v1/endpoints/symbolic.py +186 -0
  25. scope/api/api_v1/endpoints/ui.py +145 -0
  26. scope/api/api_v1/endpoints/waste_estimation.py +182 -0
  27. scope/api/api_v2/__init__.py +3 -0
  28. scope/api/api_v2/api.py +23 -0
  29. scope/api/api_v2/endpoints/__init__.py +3 -0
  30. scope/api/api_v2/endpoints/metrics.py +193 -0
  31. scope/app.py +30 -0
  32. scope/cache.py +64 -0
  33. scope/client/__init__.py +27 -0
  34. scope/client/_concepts.py +137 -0
  35. scope/client/_kg.py +64 -0
  36. scope/client/_labels.py +86 -0
  37. scope/client/_live_topology.py +912 -0
  38. scope/client/_metrics.py +561 -0
  39. scope/client/_semanticgroups.py +166 -0
  40. scope/client/_sessions.py +168 -0
  41. scope/client/_symbolic.py +1354 -0
  42. scope/client/_ui.py +599 -0
  43. scope/client/agentic_protocols.py +289 -0
  44. scope/client/application_charts.py +1786 -0
  45. scope/client/applications.py +2246 -0
  46. scope/client/base.py +49 -0
  47. scope/client/cognition_protocols.py +302 -0
  48. scope/client/constants.py +81 -0
  49. scope/client/dal.py +2382 -0
  50. scope/client/failures.py +70 -0
  51. scope/client/local.py +161 -0
  52. scope/client/mock/__init__.py +7 -0
  53. scope/client/mock/client.py +1034 -0
  54. scope/client/sessions.py +1688 -0
  55. scope/client/spans.py +95 -0
  56. scope/client/utils.py +392 -0
  57. scope/connectors/__init__.py +13 -0
  58. scope/connectors/base.py +52 -0
  59. scope/connectors/clickhouse.py +105 -0
  60. scope/connectors/neo4j.py +220 -0
  61. scope/connectors/sqlalchemy.py +131 -0
  62. scope/core/config.py +530 -0
  63. scope/core/exceptions.py +64 -0
  64. scope/dependencies.py +164 -0
  65. scope/health.py +10 -0
  66. scope/interfaces/__init__.py +33 -0
  67. scope/interfaces/data_provider.py +61 -0
  68. scope/interfaces/integration_example.py +310 -0
  69. scope/interfaces/kg_provider.py +91 -0
  70. scope/interfaces/metrics_provider.py +92 -0
  71. scope/interfaces/models.py +185 -0
  72. scope/models/kg.py +48 -0
  73. scope/models/live_topology.py +78 -0
  74. scope/models/otel_traces.py +1595 -0
  75. scope/providers/__init__.py +277 -0
  76. scope/providers/_graph.py +59 -0
  77. scope/providers/cognition_protocols.py +178 -0
  78. scope/providers/kg.py +702 -0
  79. scope/providers/kg_query_runner.py +109 -0
  80. scope/providers/neo4j_mce.py +18 -0
  81. scope/providers/scope_metrics.py +7 -0
  82. scope/query_builders/__init__.py +14 -0
  83. scope/query_builders/cognition_protocol_graph.py +191 -0
  84. scope/query_builders/concepts.py +112 -0
  85. scope/query_builders/dal.py +931 -0
  86. scope/query_builders/failure_graph.py +102 -0
  87. scope/query_builders/features.py +5 -0
  88. scope/query_builders/kg.py +416 -0
  89. scope/query_builders/labels.py +53 -0
  90. scope/query_builders/live_topology.py +503 -0
  91. scope/query_builders/metric_graph.py +196 -0
  92. scope/query_builders/metrics.py +354 -0
  93. scope/query_builders/semanticgroups.py +46 -0
  94. scope/query_builders/sessions.py +208 -0
  95. scope/query_builders/symbolic.py +615 -0
  96. scope/query_builders/trajectory.py +76 -0
  97. scope/query_builders/types.py +20 -0
  98. scope/query_builders/ui.py +3278 -0
  99. scope/query_builders/waste_estimation.py +221 -0
  100. scope/repositories/__init__.py +28 -0
  101. scope/repositories/clickhouse_otel_repository.py +135 -0
  102. scope/repositories/otel_repository.py +97 -0
  103. scope/repositories/sqlite_repository.py +215 -0
  104. scope/scripts/__init__.py +2 -0
  105. scope/scripts/seed.py +35 -0
  106. scope/workarounds.py +38 -0
@@ -0,0 +1,1014 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """FastAPI router for the /metrics endpoint.
4
+
5
+ Endpoints
6
+ ---------
7
+ GET /metrics/info
8
+ Descriptive information about this endpoint.
9
+ GET /metrics/catalog
10
+ List all discoverable metrics (id, provider, scope, target_types).
11
+ GET /metrics/catalog/{scope}
12
+ List metrics filtered by attachment scope.
13
+ GET /metrics/timeseries
14
+ Single-query aggregated time-series for one metric (plot-ready).
15
+ GET /metrics/sessions/{session_id}
16
+ Read session-level metrics (with optional ``hops`` for sub-graph).
17
+ POST /metrics/sessions/{session_id}
18
+ Write metrics to a session.
19
+ POST /metrics/compute
20
+ Compute metrics for a batch of session IDs.
21
+
22
+ All operations delegate to an :class:`MetricsProvider` instance.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import functools
28
+ import importlib.util
29
+ import logging
30
+ import os
31
+ import re
32
+ from copy import deepcopy
33
+ from datetime import datetime, timedelta, timezone
34
+ from typing import Any, Literal, Optional
35
+
36
+ import redis as redis_lib
37
+ from fastapi import APIRouter, Depends, HTTPException, Query, Request
38
+ from pydantic import BaseModel
39
+
40
+ from scope.api.api_v1.endpoints.helpers import get_client
41
+ from scope.cache import cached, make_cache_key
42
+ from scope.client._metrics import _metric_results_to_items
43
+ from scope.client.utils import parse_epoch_range
44
+ from scope.connectors.base import Connector
45
+ from scope.core.config import settings
46
+ from scope.dependencies import get_neo4j_db, get_redis
47
+ from scope.interfaces.metrics_provider import MetricsProvider
48
+ from scope.interfaces.models import MetricResult
49
+ from scope.models.otel_traces import (
50
+ MetricCatalogItem,
51
+ MetricCatalogResponse,
52
+ MetricInfoItemResponse,
53
+ MetricsComputeRequest,
54
+ MetricsComputeResponse,
55
+ MetricsWriteResponse,
56
+ MetricTimePoint,
57
+ MetricTimeSeriesResponse,
58
+ SessionMetricsResponse,
59
+ SessionMetricsWriteRequest,
60
+ SpanMetricsResponse,
61
+ SpanMetricsWriteRequest,
62
+ )
63
+ from scope.providers import SCOPEMetricsProvider
64
+ from scope.providers.kg_query_runner import KGQueryExecutionError
65
+
66
+ logger = logging.getLogger(__name__)
67
+
68
+
69
+ class MetricsInfoResponse(BaseModel):
70
+ """Response model for ``GET /metrics/info``."""
71
+
72
+ subsystem: str
73
+ total_metrics: int
74
+ scopes: list[str]
75
+ providers: list[str]
76
+ metrics: list[dict[str, str]]
77
+
78
+
79
+ router = APIRouter()
80
+
81
+
82
+ def _client(db: Connector = Depends(get_neo4j_db)): # noqa: B008
83
+ """Lazily resolve the shared client from the Neo4j dependency."""
84
+ return get_client(api_client=db)
85
+
86
+
87
+ # ── provider wiring ──────────────────────────────────────────────────────────
88
+ # Providers are initialised eagerly so the connection is validated at startup.
89
+ # If Neo4j is unavailable, _provider is set to None and every endpoint returns
90
+ # 503 until the DB becomes reachable.
91
+
92
+ _logger = logging.getLogger(__name__)
93
+
94
+ _provider: Optional[MetricsProvider] = None
95
+ _neo4j_graph_provider: Any = None # singleton for /compute
96
+
97
+
98
+ def _init_metrics_provider() -> MetricsProvider:
99
+ """Create a metrics provider backed by the shared Neo4j connector."""
100
+ neo4j_db = next(get_neo4j_db())
101
+ return SCOPEMetricsProvider(db=neo4j_db)
102
+
103
+
104
+ try:
105
+ _provider = _init_metrics_provider()
106
+ except Exception as _exc:
107
+ _logger.warning(
108
+ "Neo4j unavailable at startup — metrics endpoints will return 503 "
109
+ "until the database is reachable. Reason: %s",
110
+ _exc,
111
+ )
112
+
113
+
114
+ def _require_provider() -> MetricsProvider:
115
+ """Return the active MetricsProvider or raise HTTP 503."""
116
+ global _provider
117
+ if _provider is None:
118
+ try:
119
+ _provider = _init_metrics_provider()
120
+ except Exception as exc:
121
+ raise HTTPException(
122
+ status_code=503,
123
+ detail="Neo4j is unavailable. Metrics endpoint is degraded.",
124
+ ) from exc
125
+ return _provider
126
+
127
+
128
+ def _client(db: Connector = Depends(get_neo4j_db)): # noqa: B008
129
+ """Resolve a Neo4j-backed client with the active metrics provider."""
130
+ return get_client(api_client=db, metrics_provider=_require_provider())
131
+
132
+
133
+ def _get_neo4j_graph_provider() -> Any:
134
+ """Return (and lazily create) the singleton Neo4jGraphProvider."""
135
+ global _neo4j_graph_provider
136
+ if _neo4j_graph_provider is None:
137
+ # Avoid import cycle if scope.providers -> metrics_endpoint
138
+ from scope.providers import Neo4jGraphProvider
139
+
140
+ _neo4j_graph_provider = Neo4jGraphProvider()
141
+ return _neo4j_graph_provider
142
+
143
+
144
+ def _get_configured_llm_model() -> str:
145
+ """Return the model name configured for MCE runtime evaluation."""
146
+ return os.getenv("MCE_LLM_MODEL") or os.getenv("LLM_MODEL_NAME") or "gpt-4o"
147
+
148
+
149
+ def _configure_llm_runtime() -> str:
150
+ """Configure the shared LLM runtime used by native and external metrics."""
151
+ from mce.engine.llm import LLMService
152
+
153
+ model_name = _get_configured_llm_model()
154
+ LLMService.configure(
155
+ mode=os.getenv("MCE_LLM_MODE", "live"),
156
+ cache_path=os.getenv("MCE_LLM_CACHE_PATH", "llm_cache.json"),
157
+ api_key=os.getenv("OPENAI_API_KEY") or None,
158
+ model=model_name,
159
+ base_url=(
160
+ os.getenv("OPENAI_BASE_URL")
161
+ or os.getenv("OPENAI_API_BASE")
162
+ or os.getenv("LITELLM_BASE_URL")
163
+ or None
164
+ ),
165
+ )
166
+ return model_name
167
+
168
+
169
+ def _get_configured_engine_max_workers() -> int:
170
+ """Return the MetricEngine worker count for API-side metric execution."""
171
+ env_value = os.getenv("MCE_ENGINE_MAX_WORKERS")
172
+ if env_value:
173
+ try:
174
+ parsed = int(env_value)
175
+ if parsed >= 1:
176
+ return parsed
177
+ except ValueError:
178
+ logger.warning(
179
+ "Invalid MCE_ENGINE_MAX_WORKERS=%r, using default",
180
+ env_value,
181
+ )
182
+
183
+ return 8
184
+
185
+
186
+ def _prepare_metric_for_runtime(metric: Any, model_name: str) -> Any:
187
+ """Clone mutable external wrappers before injecting runtime model state."""
188
+ init_with_model = getattr(metric, "init_with_model", None)
189
+ if not callable(init_with_model):
190
+ return metric
191
+
192
+ runtime_metric = deepcopy(metric)
193
+ runtime_metric.init_with_model(model_name)
194
+ return runtime_metric
195
+
196
+
197
+ def _build_metric_engine(metric_ids: list[str] | None = None) -> Any:
198
+ """Build a MetricEngine configured with the Neo4j graph provider."""
199
+ try:
200
+ from mce.core.registry import get_default_metrics
201
+ from mce.engine.engine import MetricEngine
202
+ except ImportError as exc:
203
+ raise HTTPException(
204
+ status_code=501, detail=f"mce-core not available: {exc}"
205
+ ) from exc
206
+
207
+ engine = MetricEngine(max_workers=_get_configured_engine_max_workers())
208
+ engine.set_data_provider(_get_neo4j_graph_provider())
209
+ llm_model = _configure_llm_runtime()
210
+
211
+ all_metrics = get_default_metrics()
212
+ selected = [m for m in all_metrics if not metric_ids or m.metric_id in metric_ids]
213
+ if metric_ids and not selected:
214
+ raise HTTPException(
215
+ status_code=400,
216
+ detail="No valid metrics found for the requested metric_names.",
217
+ )
218
+
219
+ for metric in selected:
220
+ engine.register_metric(_prepare_metric_for_runtime(metric, llm_model))
221
+ return engine
222
+
223
+
224
+ def _compute_session_metrics(
225
+ session_id: str,
226
+ metric_ids: list[str],
227
+ *,
228
+ recursive: bool,
229
+ ) -> list[MetricResult]:
230
+ """Compute session-level metrics for the requested metric IDs."""
231
+ engine = _build_metric_engine(metric_ids)
232
+ try:
233
+ computed = engine.compute_session(session_id, recursive=recursive)
234
+ except KGQueryExecutionError as exc:
235
+ raise HTTPException(
236
+ status_code=503,
237
+ detail=f"Knowledge graph unavailable while computing metrics: {exc}",
238
+ ) from exc
239
+
240
+ by_name: dict[str, MetricResult] = {}
241
+ for result in computed:
242
+ if result.resource_id != session_id:
243
+ continue
244
+ if result.metric_id not in metric_ids:
245
+ continue
246
+ by_name.setdefault(result.metric_id, result)
247
+
248
+ return [by_name[name] for name in metric_ids if name in by_name]
249
+
250
+
251
+ def _normalize_metric_names(
252
+ metric_names: list[str] | None,
253
+ raw_metric_names: list[str],
254
+ ) -> list[str] | None:
255
+ """Normalize metric names from parsed and raw query parameters."""
256
+ candidates = raw_metric_names or (metric_names or [])
257
+ normalized: list[str] = []
258
+ for candidate in candidates:
259
+ for part in candidate.split(","):
260
+ name = part.strip()
261
+ if name:
262
+ normalized.append(name)
263
+ if not normalized:
264
+ return None
265
+ return list(dict.fromkeys(normalized))
266
+
267
+
268
+ def set_metrics_provider(provider: MetricsProvider) -> None:
269
+ """Replace the active MetricsProvider at runtime (used by tests)."""
270
+ global _provider
271
+ _provider = provider
272
+
273
+
274
+ # ── Metrics catalog ───────────────────────────────────────────────────────────
275
+
276
+
277
+ @functools.lru_cache(maxsize=1)
278
+ def _build_catalog() -> list[MetricCatalogItem]:
279
+ """Discover all registered metrics using the mce-core registry.
280
+
281
+ Result is cached for the lifetime of the process — metrics are
282
+ registered at import time and do not change at runtime.
283
+ """
284
+ try:
285
+ if _mce_discovery_providers_available():
286
+ from mce.core.registry.discovery import (
287
+ discover_all_metrics,
288
+ ensure_target_types,
289
+ get_provider_name,
290
+ )
291
+
292
+ items = []
293
+ for metric_cls in discover_all_metrics():
294
+ ensure_target_types(metric_cls)
295
+ meta = getattr(metric_cls, "metadata", None)
296
+ scope = getattr(meta, "scope", None) if meta else None
297
+ scope_val = (
298
+ scope.value
299
+ if hasattr(scope, "value")
300
+ else str(scope)
301
+ if scope
302
+ else "session"
303
+ )
304
+ target_types = getattr(meta, "target_types", None) or set()
305
+ description = getattr(meta, "description", None)
306
+ display_name = (
307
+ meta.get_display_name()
308
+ if meta and hasattr(meta, "get_display_name")
309
+ else metric_cls.metric_id
310
+ )
311
+ items.append(
312
+ MetricCatalogItem(
313
+ metric_id=metric_cls.metric_id,
314
+ id=metric_cls.metric_id,
315
+ name=display_name,
316
+ provider=get_provider_name(metric_cls),
317
+ scope=scope_val,
318
+ target_types=sorted(target_types),
319
+ description=description,
320
+ )
321
+ )
322
+ return items
323
+
324
+ logger.info(
325
+ "MCE provider modules not installed; serving fallback metric catalog from METRIC_CATEGORIES"
326
+ )
327
+ except Exception as exc:
328
+ logger.warning(
329
+ "Metric discovery failed; falling back to configured catalog: %s", exc
330
+ )
331
+
332
+ return _build_fallback_catalog_from_settings()
333
+
334
+
335
+ def _mce_discovery_providers_available() -> bool:
336
+ """Return True when at least one MCE provider module is importable.
337
+
338
+ Avoid calling discover_all_metrics() when only mce-core is installed, because
339
+ mce-core probes optional provider modules and emits noisy import warnings.
340
+ """
341
+ provider_modules = (
342
+ "mce.providers.native.metrics",
343
+ "mce.providers.sdk",
344
+ "mce.providers.deepeval.wrapper",
345
+ "mce.providers.ragas.wrapper",
346
+ "mce.providers.opik.wrapper",
347
+ )
348
+ return any(
349
+ importlib.util.find_spec(module) is not None for module in provider_modules
350
+ )
351
+
352
+
353
+ def _build_fallback_catalog_from_settings() -> list[MetricCatalogItem]:
354
+ """Build a static metric catalog from application settings.
355
+
356
+ This keeps /metrics/catalog useful in minimal environments where optional
357
+ MCE provider wheels are intentionally not installed.
358
+ """
359
+ items: list[MetricCatalogItem] = []
360
+ seen: set[str] = set()
361
+
362
+ for category in settings.METRIC_CATEGORIES.values():
363
+ for metric_id, cfg in category.items():
364
+ if metric_id in seen:
365
+ continue
366
+ seen.add(metric_id)
367
+
368
+ items.append(
369
+ MetricCatalogItem(
370
+ metric_id=metric_id,
371
+ id=metric_id,
372
+ name=cfg.get("name") or metric_id,
373
+ provider="SCOPE",
374
+ scope="session",
375
+ target_types=["mas:Session"],
376
+ description=cfg.get("description"),
377
+ )
378
+ )
379
+
380
+ return sorted(items, key=lambda item: item.metric_id.lower())
381
+
382
+
383
+ @router.get("/catalog", response_model=MetricCatalogResponse)
384
+ def get_metrics_catalog() -> Any:
385
+ """List all discoverable metrics with their provider, scope, and target types."""
386
+ items = _build_catalog()
387
+ return MetricCatalogResponse(total=len(items), metrics=items)
388
+
389
+
390
+ @router.get("/catalog/{scope}", response_model=MetricCatalogResponse)
391
+ def get_metrics_catalog_by_scope(scope: str) -> Any:
392
+ """List metrics filtered by attachment scope (session, span, execution_element)."""
393
+ all_items = _build_catalog()
394
+ filtered = [m for m in all_items if m.scope == scope]
395
+ return MetricCatalogResponse(total=len(filtered), metrics=filtered)
396
+
397
+
398
+ @router.get("/catalog_with_categories")
399
+ def get_metrics_catalog_with_categories() -> Any:
400
+ """Return the metric catalog organized by configured categories."""
401
+
402
+ categories = settings.METRIC_CATEGORIES
403
+ return categories
404
+
405
+
406
+ @router.get("/catalog_with_categories_meta")
407
+ def get_metrics_catalog_with_categories_meta() -> Any:
408
+ """Return the metric catalog organized by configured categories."""
409
+
410
+ categories = settings.METRIC_CATEGORIES_META
411
+ # categories = settings.METRIC_CATEGORIES
412
+ # meta = getattr(settings, "METRIC_CATEGORIES_META", {}) or {}
413
+ # enriched: dict[str, Any] = {}
414
+ # for key, metrics in categories.items():
415
+ # md = meta.get(key, {})
416
+ # metric_names = list(metrics.keys()) if isinstance(metrics, dict) else []
417
+ # enriched[key] = {
418
+ # "name": md.get("name") or key,
419
+ # "description": md.get("description") or f"Metrics in the {key} category",
420
+ # "key": md.get("key") or key,
421
+ # "metrics_names_list": md.get("metrics_list") or metric_names,
422
+ # "metrics": metrics,
423
+ # }
424
+ # return enriched
425
+ return categories
426
+
427
+
428
+ @router.get("/info")
429
+ def metrics_info(
430
+ metric_id: Optional[str] = Query(
431
+ None,
432
+ description="Metric ID to look up (returns single-metric detail when provided)",
433
+ ),
434
+ ) -> Any:
435
+ """Return descriptive information about the metrics subsystem.
436
+
437
+ * Without ``?metric_id=``: returns the full MCE metric catalog (same shape as ``/catalog``).
438
+ * With ``?metric_id=<id>``: returns detailed info for that specific metric.
439
+ """
440
+ catalog = _build_catalog()
441
+ if metric_id is not None:
442
+ match = next(
443
+ (m for m in catalog if m.metric_id == metric_id or m.id == metric_id),
444
+ None,
445
+ )
446
+ if match is None:
447
+ raise HTTPException(
448
+ status_code=404, detail=f"Metric '{metric_id}' not found"
449
+ )
450
+ return MetricInfoItemResponse(
451
+ id=match.id,
452
+ name=match.name,
453
+ description=match.description,
454
+ unit=match.unit,
455
+ type=match.type,
456
+ dimensions=match.target_types,
457
+ )
458
+ return MetricCatalogResponse(total=len(catalog), metrics=catalog)
459
+
460
+
461
+ # ── helpers ───────────────────────────────────────────────────────────────────
462
+
463
+ _DURATION_RE = re.compile(
464
+ r"^(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?$", re.IGNORECASE
465
+ )
466
+
467
+
468
+ def _parse_duration(s: str) -> timedelta:
469
+ """Parse a human-readable duration string into a timedelta.
470
+
471
+ Supported units: w (weeks), d (days), h (hours), m (minutes).
472
+ Examples: ``7d``, ``2w3d``, ``24h``, ``1w2d6h``.
473
+ """
474
+ m = _DURATION_RE.match(s.strip())
475
+ if not m or not any(m.groups()):
476
+ raise ValueError(
477
+ f"Invalid duration '{s}'. Use combinations of w/d/h/m, e.g. '7d', '2w', '24h', '1w3d6h'."
478
+ )
479
+ weeks, days, hours, minutes = (int(v or 0) for v in m.groups())
480
+ return timedelta(weeks=weeks, days=days, hours=hours, minutes=minutes)
481
+
482
+
483
+ # ── Time-series metrics ─────────────────────────────────────────────────
484
+
485
+
486
+ @router.get("/timeseries", response_model=MetricTimeSeriesResponse)
487
+ def get_metric_timeseries(
488
+ metric_id: str = Query(..., description="Metric name, e.g. 'Groundedness'"),
489
+ # ── Unix epoch timestamps (harmonized with /applications/{id}/agent/{id}/charts) ──
490
+ start_time: Optional[str] = Query(
491
+ None,
492
+ description="Unix epoch timestamp (seconds) for the start of the range. "
493
+ "Takes precedence over 'start', 'duration', and 'window_hours' when provided.",
494
+ ),
495
+ end_time: Optional[str] = Query(
496
+ None,
497
+ description="Unix epoch timestamp (seconds) for the end of the range. "
498
+ "Defaults to now. Used together with 'start_time' or 'duration'.",
499
+ ),
500
+ # ── Human-readable duration ───────────────────────────────────────────────
501
+ duration: Optional[str] = Query(
502
+ None,
503
+ description="Human-readable duration ending at 'end_time'/'end' (or now). "
504
+ "Combinations of w/d/h/m: '7d', '2w', '24h', '1w3d6h'. "
505
+ "Mutually exclusive with 'start_time' and 'window_hours'.",
506
+ ),
507
+ window_hours: Optional[int] = Query(
508
+ None,
509
+ ge=1,
510
+ le=8760,
511
+ description="Rolling window in hours (legacy). Prefer 'duration'. "
512
+ "Mutually exclusive with 'start_time' and 'start'.",
513
+ ),
514
+ # ── ISO-8601 explicit range ───────────────────────────────────────────────
515
+ start: Optional[datetime] = Query(
516
+ None,
517
+ description="ISO-8601 start datetime (UTC). Used when neither start_time, duration nor window_hours is given.",
518
+ ),
519
+ end: Optional[datetime] = Query(
520
+ None,
521
+ description="ISO-8601 end datetime (UTC). Ignored when end_time is provided.",
522
+ ),
523
+ # ── Aggregation & filters ─────────────────────────────────────────────────
524
+ bucket: Literal["minute", "hour", "day"] = Query(
525
+ "hour", description="Time-bucket granularity for aggregation."
526
+ ),
527
+ app_name: Optional[str] = Query(
528
+ None, description="Filter by application name (alias: application_id)."
529
+ ),
530
+ application_id: Optional[str] = Query(
531
+ None, description="Filter by application ID (alias for app_name)."
532
+ ),
533
+ agent_id: Optional[str] = Query(None, description="Filter by agent ID."),
534
+ redis_client: redis_lib.Redis = Depends(get_redis), # noqa: B008
535
+ ) -> Any:
536
+ """Return aggregated time-series data for one metric.
537
+
538
+ **Parameter priority** (highest to lowest):
539
+
540
+ 1. ``start_time`` / ``end_time`` — Unix epoch seconds (harmonized with ``/applications/{id}/charts``)
541
+ 2. ``duration`` — human-readable window relative to ``end_time`` or now
542
+ 3. ``window_hours`` — legacy integer window in hours
543
+ 4. ``start`` / ``end`` — explicit ISO-8601 datetimes
544
+
545
+ When ``end_time`` / ``end`` are omitted the window extends up to now (open-ended).
546
+
547
+ **Examples**:
548
+
549
+ Unix epoch (same format as ``/applications/{id}/charts``)::
550
+
551
+ ?metric_id=Groundedness&start_time=1773187200&end_time=1773360000&bucket=day
552
+
553
+ Human-readable duration ending now::
554
+
555
+ ?metric_id=Groundedness&duration=7d&bucket=day
556
+
557
+ Human-readable duration ending at a specific epoch::
558
+
559
+ ?metric_id=Cost&duration=2w&end_time=1773360000&bucket=day
560
+
561
+ ISO-8601 explicit range::
562
+
563
+ ?metric_id=Duration&start=2026-03-01T00:00:00Z&end=2026-03-13T00:00:00Z&bucket=day
564
+ """
565
+ # Validate mutually exclusive params before cache lookup so invalid requests always 422.
566
+ if duration is not None and window_hours is not None:
567
+ raise HTTPException(
568
+ status_code=422,
569
+ detail="Provide either 'duration' or 'window_hours', not both.",
570
+ )
571
+ if duration is not None:
572
+ try:
573
+ _parse_duration(duration)
574
+ except ValueError as exc:
575
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
576
+
577
+ key = make_cache_key(
578
+ "metrics:timeseries",
579
+ {
580
+ "metric": metric_id,
581
+ "start_time": start_time,
582
+ "end_time": end_time,
583
+ "duration": duration,
584
+ "window_hours": window_hours,
585
+ "start": start.isoformat() if start else None,
586
+ "end": end.isoformat() if end else None,
587
+ "bucket": bucket,
588
+ "app": app_name or application_id,
589
+ "agent": agent_id,
590
+ },
591
+ )
592
+
593
+ def _fetch():
594
+ # Resolve end first (needed by duration logic)
595
+ if end_time is not None:
596
+ _start_e, end_e = parse_epoch_range("", end_time)
597
+ resolved_end = datetime.fromtimestamp(end_e, tz=timezone.utc)
598
+ elif end is not None:
599
+ resolved_end = end
600
+ else:
601
+ resolved_end = datetime.now(timezone.utc)
602
+
603
+ # Resolve start
604
+ if start_time is not None:
605
+ start_e, _ = parse_epoch_range(start_time, "")
606
+ resolved_start = datetime.fromtimestamp(start_e, tz=timezone.utc)
607
+ elif duration is not None:
608
+ resolved_start = resolved_end - _parse_duration(duration)
609
+ elif window_hours is not None:
610
+ resolved_start = resolved_end - timedelta(hours=window_hours)
611
+ else:
612
+ resolved_start = start or (resolved_end - timedelta(hours=24))
613
+
614
+ resolved_end_param = resolved_end if (end_time or end) else None
615
+
616
+ effective_app = app_name or application_id
617
+ rows = _require_provider().get_metrics_over_time(
618
+ metric_id,
619
+ start=resolved_start,
620
+ end=resolved_end_param,
621
+ bucket=bucket,
622
+ app_name=effective_app,
623
+ agent_id=agent_id,
624
+ )
625
+ return MetricTimeSeriesResponse(
626
+ metric_id=metric_id,
627
+ bucket_size=bucket,
628
+ start=resolved_start.isoformat(),
629
+ end=resolved_end_param.isoformat() if resolved_end_param else None,
630
+ points=[
631
+ MetricTimePoint(
632
+ bucket=r["bucket"],
633
+ avg_value=r["avg_value"],
634
+ min_value=r["min_value"],
635
+ max_value=r["max_value"],
636
+ n_sessions=r["n_sessions"],
637
+ )
638
+ for r in rows
639
+ ],
640
+ )
641
+
642
+ return cached(
643
+ redis_client=redis_client,
644
+ key=key,
645
+ fetch=_fetch,
646
+ ttl=settings.CACHE_TTL_SECONDS,
647
+ enabled=settings.CACHE_ENABLED,
648
+ )
649
+
650
+
651
+ # ── Session-level metrics ─────────────────────────────────────────────────────
652
+
653
+
654
+ @router.get("/sessions/{session_id}", response_model=SessionMetricsResponse)
655
+ def get_session_metrics(
656
+ request: Request,
657
+ session_id: str,
658
+ hops: int = Query(1, ge=0, le=5, description="Sub-graph traversal depth"),
659
+ metric_names: list[str] | None = Query(
660
+ None,
661
+ description="Optional list of metric names to return; repeated query parameter supported",
662
+ ),
663
+ compute: bool = Query(
664
+ True, description="Compute requested missing metrics on the fly"
665
+ ),
666
+ persist: bool = Query(
667
+ False, description="Persist successfully computed session-level metrics"
668
+ ),
669
+ recursive: bool = Query(
670
+ False, description="Enable recursive span fetching when compute=true"
671
+ ),
672
+ use_cache: bool = Query(
673
+ True,
674
+ description="Read persisted metrics before computing missing ones. Set to false to force live computation only.",
675
+ ),
676
+ ) -> Any:
677
+ """Return session-level metrics from the knowledge graph."""
678
+ metric_names = _normalize_metric_names(
679
+ metric_names,
680
+ request.query_params.getlist("metric_names"),
681
+ )
682
+
683
+ if persist and not compute:
684
+ raise HTTPException(
685
+ status_code=400, detail="persist=true requires compute=true."
686
+ )
687
+ if not use_cache and not compute:
688
+ raise HTTPException(
689
+ status_code=400, detail="use_cache=false requires compute=true."
690
+ )
691
+ if not use_cache and not metric_names:
692
+ raise HTTPException(
693
+ status_code=400,
694
+ detail="use_cache=false requires metric_names so the API knows what to compute.",
695
+ )
696
+
697
+ provider = _require_provider()
698
+ persisted_results = provider.get_metrics(session_id, hops=hops) if use_cache else []
699
+
700
+ if not metric_names:
701
+ results = persisted_results
702
+ else:
703
+ requested_names = list(dict.fromkeys(metric_names))
704
+ persisted_by_name = {
705
+ result.metric_id: result
706
+ for result in persisted_results
707
+ if result.metric_id in requested_names
708
+ }
709
+
710
+ computed_by_name: dict[str, MetricResult] = {}
711
+ missing_names = [
712
+ name for name in requested_names if name not in persisted_by_name
713
+ ]
714
+ if compute and missing_names:
715
+ computed_results = _compute_session_metrics(
716
+ session_id,
717
+ missing_names,
718
+ recursive=recursive,
719
+ )
720
+ computed_by_name = {result.metric_id: result for result in computed_results}
721
+
722
+ if persist:
723
+ to_persist = [
724
+ result
725
+ for result in computed_results
726
+ if result.error is None and result.value is not None
727
+ ]
728
+ if to_persist:
729
+ provider.save_metrics(to_persist)
730
+
731
+ results = []
732
+ for name in requested_names:
733
+ if name in persisted_by_name:
734
+ results.append(persisted_by_name[name])
735
+ elif name in computed_by_name:
736
+ results.append(computed_by_name[name])
737
+ else:
738
+ results.append(
739
+ MetricResult(
740
+ metric_id=name,
741
+ resource_id=session_id,
742
+ provider="scope",
743
+ error="missing data",
744
+ )
745
+ )
746
+
747
+ return SessionMetricsResponse(
748
+ session_id=session_id,
749
+ metrics=_metric_results_to_items(results, metric_names),
750
+ )
751
+
752
+
753
+ @router.post("/sessions/{session_id}", response_model=MetricsWriteResponse)
754
+ def post_session_metrics(
755
+ session_id: str,
756
+ body: SessionMetricsWriteRequest,
757
+ ) -> Any:
758
+ """Write metrics to a session in the knowledge graph."""
759
+ items = [
760
+ MetricResult(
761
+ metric_id=m.name,
762
+ resource_id=session_id,
763
+ provider=m.provider,
764
+ value=m.value,
765
+ metadata={
766
+ "metric_id": m.metric_id or m.name,
767
+ "source": m.source,
768
+ },
769
+ reasoning=m.reasoning,
770
+ )
771
+ for m in body.metrics
772
+ ]
773
+ ok = _require_provider().save_metrics(items)
774
+ if ok:
775
+ return MetricsWriteResponse(written=len(items))
776
+ return MetricsWriteResponse(
777
+ written=0, errors=["save_metrics returned False — check server logs"]
778
+ )
779
+
780
+
781
+ # ── Compute metrics ──────────────────────────────────────────────────────────
782
+
783
+
784
+ @router.post("/compute", response_model=MetricsComputeResponse)
785
+ def compute_metrics(body: MetricsComputeRequest) -> Any:
786
+ """Compute metrics for a batch of sessions using MetricEngine + SCOPEKGProvider."""
787
+ import uuid as _uuid
788
+
789
+ effective_ids = body.metric_ids or ([body.metric_id] if body.metric_id else None)
790
+ engine = _build_metric_engine(effective_ids)
791
+
792
+ computed = 0
793
+ failed = 0
794
+ errors: list[str] = []
795
+ all_results: list[dict] = []
796
+ for session_id in body.session_ids:
797
+ try:
798
+ session_results = engine.compute_session(
799
+ session_id, recursive=body.recursive
800
+ )
801
+ all_results.extend(
802
+ [
803
+ {
804
+ "session_id": session_id,
805
+ "metric_id": r.metric_id,
806
+ "value": r.value,
807
+ "resource_id": getattr(r, "resource_id", session_id),
808
+ "error": r.error,
809
+ "reasoning": getattr(r, "reasoning", None),
810
+ }
811
+ for r in session_results
812
+ ]
813
+ )
814
+ computed += 1
815
+ except KGQueryExecutionError as exc:
816
+ failed += 1
817
+ errors.append(f"{session_id}: knowledge graph unavailable ({exc})")
818
+ except Exception as exc:
819
+ import logging as _logging
820
+
821
+ _logging.getLogger(__name__).exception(
822
+ "compute_session failed for %s", session_id
823
+ )
824
+ failed += 1
825
+ errors.append(f"{session_id}: {exc}")
826
+
827
+ return MetricsComputeResponse(
828
+ job_id=f"job_{_uuid.uuid4().hex[:6]}",
829
+ status="completed" if not errors else "partial",
830
+ message=f"Metric computation completed for {len(body.session_ids)} session{'s' if len(body.session_ids) != 1 else ''}",
831
+ total_sessions=len(body.session_ids),
832
+ computed=computed,
833
+ failed=failed,
834
+ errors=errors,
835
+ results=all_results,
836
+ )
837
+
838
+
839
+ @router.get(
840
+ "/sessions/{session_id}/spans/{span_id}",
841
+ response_model=SpanMetricsResponse,
842
+ )
843
+ def get_span_metrics(
844
+ session_id: str,
845
+ span_id: str,
846
+ hops: int = Query(1, ge=0, le=5, description="Sub-graph traversal depth"),
847
+ metrics_client=Depends(_client), # noqa: B008
848
+ redis_client: redis_lib.Redis = Depends(get_redis), # noqa: B008
849
+ ) -> Any:
850
+ """Return span-level metrics from the knowledge graph."""
851
+ key = make_cache_key(
852
+ "metrics:span",
853
+ {"session": session_id, "span": span_id, "hops": hops},
854
+ )
855
+ return cached(
856
+ redis_client=redis_client,
857
+ key=key,
858
+ fetch=lambda: metrics_client.get_span_metrics(
859
+ span_id,
860
+ session_id=session_id,
861
+ hops=hops,
862
+ ),
863
+ ttl=settings.CACHE_TTL_SECONDS,
864
+ enabled=settings.CACHE_ENABLED,
865
+ )
866
+
867
+
868
+ @router.post(
869
+ "/sessions/{session_id}/spans/{span_id}",
870
+ response_model=MetricsWriteResponse,
871
+ )
872
+ def post_span_metrics(
873
+ session_id: str,
874
+ span_id: str,
875
+ body: SpanMetricsWriteRequest,
876
+ metrics_client=Depends(_client), # noqa: B008
877
+ ) -> Any:
878
+ """Write metrics to a span in the knowledge graph."""
879
+ result = metrics_client.write_span_metrics(
880
+ session_id,
881
+ span_id,
882
+ metrics=[m.model_dump() for m in body.metrics],
883
+ )
884
+ return MetricsWriteResponse(**result)
885
+
886
+
887
+ # ── Category-level metrics ───────────────────────────────────────────────────
888
+
889
+
890
+ @router.get(
891
+ "/applications/{application_id}/summary",
892
+ )
893
+ def get_metrics_summary(
894
+ application_id: str,
895
+ start_time: str | None = Query(None, description="ISO-8601 start time filter"),
896
+ end_time: str | None = Query(None, description="ISO-8601 end time filter"),
897
+ metrics_client=Depends(_client), # noqa: B008
898
+ redis_client: redis_lib.Redis = Depends(get_redis), # noqa: B008
899
+ ) -> Any:
900
+ key = make_cache_key(
901
+ "metrics:app_summary",
902
+ {"app": application_id, "start": start_time, "end": end_time},
903
+ )
904
+ return cached(
905
+ redis_client=redis_client,
906
+ key=key,
907
+ fetch=lambda: metrics_client.get_application_metrics_summary(
908
+ application_id=application_id
909
+ ),
910
+ ttl=settings.CACHE_TTL_SECONDS,
911
+ enabled=settings.CACHE_ENABLED,
912
+ )
913
+
914
+
915
+ @router.get("/applications/{application_id}/metrics")
916
+ def get_application_metrics(
917
+ application_id: str,
918
+ metric_names: list[str] = Query(
919
+ ..., description="List of metric names to retrieve"
920
+ ),
921
+ start_time: str | None = Query(
922
+ None, description="ISO-8601 or epoch start time filter"
923
+ ),
924
+ end_time: str | None = Query(None, description="ISO-8601 or epoch end time filter"),
925
+ agent_id: str | None = Query(None, description="Optional agent ID filter"),
926
+ metrics_client=Depends(_client), # noqa: B008
927
+ redis_client: redis_lib.Redis = Depends(get_redis), # noqa: B008
928
+ ) -> Any:
929
+ """Return metric values for an application given an explicit list of metric names."""
930
+ key = make_cache_key(
931
+ "metrics:app_metrics",
932
+ {
933
+ "app": application_id,
934
+ "metrics": sorted(metric_names),
935
+ "start": start_time,
936
+ "end": end_time,
937
+ "agent": agent_id,
938
+ },
939
+ )
940
+ return cached(
941
+ redis_client=redis_client,
942
+ key=key,
943
+ fetch=lambda: metrics_client.get_metrics(
944
+ application_id,
945
+ metric_names,
946
+ agent_id=agent_id,
947
+ start_time=start_time,
948
+ end_time=end_time,
949
+ ),
950
+ ttl=settings.CACHE_TTL_SECONDS,
951
+ enabled=settings.CACHE_ENABLED,
952
+ )
953
+
954
+
955
+ @router.get("/applications/{application_id}/category/{cat_key}")
956
+ def get_application_metrics_by_category(
957
+ application_id: str,
958
+ cat_key: str,
959
+ start_time: str | None = Query(
960
+ None, description="ISO-8601 or epoch start time filter"
961
+ ),
962
+ end_time: str | None = Query(None, description="ISO-8601 or epoch end time filter"),
963
+ agent_id: str | None = Query(None, description="Optional agent ID filter"),
964
+ metrics_client=Depends(_client), # noqa: B008
965
+ redis_client: redis_lib.Redis = Depends(get_redis), # noqa: B008
966
+ ) -> Any:
967
+ """Return metric values for an application filtered by a configured category key."""
968
+ key = make_cache_key(
969
+ "metrics:app_category",
970
+ {
971
+ "app": application_id,
972
+ "cat": cat_key,
973
+ "start": start_time,
974
+ "end": end_time,
975
+ "agent": agent_id,
976
+ },
977
+ )
978
+ return cached(
979
+ redis_client=redis_client,
980
+ key=key,
981
+ fetch=lambda: metrics_client.get_metrics_per_category(
982
+ application_id,
983
+ cat_key,
984
+ agent_id=agent_id,
985
+ start_time=start_time,
986
+ end_time=end_time,
987
+ ),
988
+ ttl=settings.CACHE_TTL_SECONDS,
989
+ enabled=settings.CACHE_ENABLED,
990
+ )
991
+
992
+
993
+ def get_metrics_by_category(
994
+ application_id: str,
995
+ metric_defs_or_names: Any,
996
+ category: str | None = None,
997
+ metrics_client: Any | None = None,
998
+ ) -> dict[str, Any]:
999
+ """Helper exported for tests: delegate to a LocalClient or provided client.
1000
+
1001
+ Kept as a plain function (not a route) so tests can import it directly.
1002
+ """
1003
+ # Accept either a dict of metric defs or a list of metric names.
1004
+ if isinstance(metric_defs_or_names, dict):
1005
+ metric_names = list(metric_defs_or_names.keys())
1006
+ else:
1007
+ metric_names = list(metric_defs_or_names or [])
1008
+
1009
+ if metrics_client is None:
1010
+ from scope.client import LocalClient
1011
+
1012
+ client = LocalClient()
1013
+ return client.get_metrics(application_id, metric_names)
1014
+ return metrics_client.get_metrics(application_id, metric_names)