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.
- ioc_scope_api-1.0.0.dist-info/METADATA +306 -0
- ioc_scope_api-1.0.0.dist-info/RECORD +106 -0
- ioc_scope_api-1.0.0.dist-info/WHEEL +4 -0
- ioc_scope_api-1.0.0.dist-info/entry_points.txt +2 -0
- scope/__init__.py +27 -0
- scope/api/__init__.py +119 -0
- scope/api/api_v1/__init__.py +2 -0
- scope/api/api_v1/api.py +71 -0
- scope/api/api_v1/endpoints/__init__.py +2 -0
- scope/api/api_v1/endpoints/agentic_protocols_metrics.py +39 -0
- scope/api/api_v1/endpoints/applications.py +440 -0
- scope/api/api_v1/endpoints/cache.py +50 -0
- scope/api/api_v1/endpoints/concepts.py +123 -0
- scope/api/api_v1/endpoints/features.py +19 -0
- scope/api/api_v1/endpoints/helpers.py +65 -0
- scope/api/api_v1/endpoints/kg.py +195 -0
- scope/api/api_v1/endpoints/labels.py +71 -0
- scope/api/api_v1/endpoints/live_topology.py +89 -0
- scope/api/api_v1/endpoints/metrics.py +1014 -0
- scope/api/api_v1/endpoints/reasoning.py +62 -0
- scope/api/api_v1/endpoints/semanticgroups.py +144 -0
- scope/api/api_v1/endpoints/sessions.py +339 -0
- scope/api/api_v1/endpoints/spans.py +41 -0
- scope/api/api_v1/endpoints/symbolic.py +186 -0
- scope/api/api_v1/endpoints/ui.py +145 -0
- scope/api/api_v1/endpoints/waste_estimation.py +182 -0
- scope/api/api_v2/__init__.py +3 -0
- scope/api/api_v2/api.py +23 -0
- scope/api/api_v2/endpoints/__init__.py +3 -0
- scope/api/api_v2/endpoints/metrics.py +193 -0
- scope/app.py +30 -0
- scope/cache.py +64 -0
- scope/client/__init__.py +27 -0
- scope/client/_concepts.py +137 -0
- scope/client/_kg.py +64 -0
- scope/client/_labels.py +86 -0
- scope/client/_live_topology.py +912 -0
- scope/client/_metrics.py +561 -0
- scope/client/_semanticgroups.py +166 -0
- scope/client/_sessions.py +168 -0
- scope/client/_symbolic.py +1354 -0
- scope/client/_ui.py +599 -0
- scope/client/agentic_protocols.py +289 -0
- scope/client/application_charts.py +1786 -0
- scope/client/applications.py +2246 -0
- scope/client/base.py +49 -0
- scope/client/cognition_protocols.py +302 -0
- scope/client/constants.py +81 -0
- scope/client/dal.py +2382 -0
- scope/client/failures.py +70 -0
- scope/client/local.py +161 -0
- scope/client/mock/__init__.py +7 -0
- scope/client/mock/client.py +1034 -0
- scope/client/sessions.py +1688 -0
- scope/client/spans.py +95 -0
- scope/client/utils.py +392 -0
- scope/connectors/__init__.py +13 -0
- scope/connectors/base.py +52 -0
- scope/connectors/clickhouse.py +105 -0
- scope/connectors/neo4j.py +220 -0
- scope/connectors/sqlalchemy.py +131 -0
- scope/core/config.py +530 -0
- scope/core/exceptions.py +64 -0
- scope/dependencies.py +164 -0
- scope/health.py +10 -0
- scope/interfaces/__init__.py +33 -0
- scope/interfaces/data_provider.py +61 -0
- scope/interfaces/integration_example.py +310 -0
- scope/interfaces/kg_provider.py +91 -0
- scope/interfaces/metrics_provider.py +92 -0
- scope/interfaces/models.py +185 -0
- scope/models/kg.py +48 -0
- scope/models/live_topology.py +78 -0
- scope/models/otel_traces.py +1595 -0
- scope/providers/__init__.py +277 -0
- scope/providers/_graph.py +59 -0
- scope/providers/cognition_protocols.py +178 -0
- scope/providers/kg.py +702 -0
- scope/providers/kg_query_runner.py +109 -0
- scope/providers/neo4j_mce.py +18 -0
- scope/providers/scope_metrics.py +7 -0
- scope/query_builders/__init__.py +14 -0
- scope/query_builders/cognition_protocol_graph.py +191 -0
- scope/query_builders/concepts.py +112 -0
- scope/query_builders/dal.py +931 -0
- scope/query_builders/failure_graph.py +102 -0
- scope/query_builders/features.py +5 -0
- scope/query_builders/kg.py +416 -0
- scope/query_builders/labels.py +53 -0
- scope/query_builders/live_topology.py +503 -0
- scope/query_builders/metric_graph.py +196 -0
- scope/query_builders/metrics.py +354 -0
- scope/query_builders/semanticgroups.py +46 -0
- scope/query_builders/sessions.py +208 -0
- scope/query_builders/symbolic.py +615 -0
- scope/query_builders/trajectory.py +76 -0
- scope/query_builders/types.py +20 -0
- scope/query_builders/ui.py +3278 -0
- scope/query_builders/waste_estimation.py +221 -0
- scope/repositories/__init__.py +28 -0
- scope/repositories/clickhouse_otel_repository.py +135 -0
- scope/repositories/otel_repository.py +97 -0
- scope/repositories/sqlite_repository.py +215 -0
- scope/scripts/__init__.py +2 -0
- scope/scripts/seed.py +35 -0
- scope/workarounds.py +38 -0
scope/client/_metrics.py
ADDED
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Metrics-domain methods for :class:`LocalClient`.
|
|
4
|
+
|
|
5
|
+
These methods query the Neo4j knowledge graph for session-level and
|
|
6
|
+
span-level metrics, with optional sub-graph expansion (``hops``).
|
|
7
|
+
|
|
8
|
+
All operations delegate to the :class:`MetricsProvider` instance on
|
|
9
|
+
``self.metrics_provider``. The provider is always set — ``LocalClient``
|
|
10
|
+
auto-defaults to :class:`SCOPEMetricsProvider` when none is supplied.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import logging
|
|
17
|
+
from collections import defaultdict
|
|
18
|
+
from datetime import date, datetime, time, timezone
|
|
19
|
+
from numbers import Real
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from scope.client.constants import PERIODS_COUNT
|
|
23
|
+
from scope.core.config import settings
|
|
24
|
+
from scope.core.exceptions import DatabaseError
|
|
25
|
+
from scope.interfaces.metrics_provider import MetricsProvider
|
|
26
|
+
from scope.interfaces.models import MetricResult
|
|
27
|
+
from scope.models.otel_traces import (
|
|
28
|
+
ApplicationMetricsSummary,
|
|
29
|
+
ApplicationMetricsTimeline,
|
|
30
|
+
MetricItem,
|
|
31
|
+
SessionMetricsResponse,
|
|
32
|
+
SingleValueData,
|
|
33
|
+
SpanMetricsResponse,
|
|
34
|
+
TimelineData,
|
|
35
|
+
)
|
|
36
|
+
from scope.query_builders import metrics as metrics_queries
|
|
37
|
+
from scope.query_builders.metric_graph import EVALUATION_KEYS
|
|
38
|
+
|
|
39
|
+
# ── helpers ───────────────────────────────────────────────────────────────────
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _decode_json_like(value: Any) -> Any:
|
|
43
|
+
"""Decode JSON objects/lists stored in scalar KG properties when present."""
|
|
44
|
+
if not isinstance(value, str):
|
|
45
|
+
return value
|
|
46
|
+
stripped = value.strip()
|
|
47
|
+
if not stripped or stripped[0] not in "[{":
|
|
48
|
+
return value
|
|
49
|
+
try:
|
|
50
|
+
return json.loads(stripped)
|
|
51
|
+
except (json.JSONDecodeError, TypeError):
|
|
52
|
+
return value
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _decode_reasoning_payload(value: Any) -> Any:
|
|
56
|
+
"""Decode stored reasoning and unwrap legacy combined reasoning payloads."""
|
|
57
|
+
decoded = _decode_json_like(value)
|
|
58
|
+
if isinstance(decoded, dict) and "reasoning" in decoded:
|
|
59
|
+
return decoded.get("reasoning")
|
|
60
|
+
return decoded
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _metric_results_to_items(
|
|
64
|
+
results: list[MetricResult],
|
|
65
|
+
metric_names: list[str] | None = None,
|
|
66
|
+
) -> list[MetricItem]:
|
|
67
|
+
"""Convert a list of :class:`MetricResult` to Pydantic :class:`MetricItem`."""
|
|
68
|
+
items = []
|
|
69
|
+
for r in results:
|
|
70
|
+
items.append(
|
|
71
|
+
MetricItem(
|
|
72
|
+
name=r.metric_id,
|
|
73
|
+
value=r.value if isinstance(r.value, (int, float)) else None,
|
|
74
|
+
metric_id=r.metric_id,
|
|
75
|
+
source=r.provider,
|
|
76
|
+
reasoning=_decode_reasoning_payload(r.reasoning),
|
|
77
|
+
error=r.error,
|
|
78
|
+
)
|
|
79
|
+
)
|
|
80
|
+
if metric_names:
|
|
81
|
+
allowed = set(metric_names)
|
|
82
|
+
items = [m for m in items if m.name in allowed]
|
|
83
|
+
order = {name: index for index, name in enumerate(metric_names)}
|
|
84
|
+
items.sort(key=lambda item: order.get(item.name, len(order)))
|
|
85
|
+
return items
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
logger = logging.getLogger(__name__)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _json_safe(value):
|
|
92
|
+
if isinstance(value, datetime):
|
|
93
|
+
return value.isoformat()
|
|
94
|
+
if isinstance(value, date):
|
|
95
|
+
return value.isoformat()
|
|
96
|
+
if isinstance(value, time):
|
|
97
|
+
return value.isoformat()
|
|
98
|
+
if isinstance(value, dict):
|
|
99
|
+
return {k: _json_safe(v) for k, v in value.items()}
|
|
100
|
+
if isinstance(value, list):
|
|
101
|
+
return [_json_safe(v) for v in value]
|
|
102
|
+
return value
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _path_value(payload: Any, path: list[str] | None) -> Any:
|
|
106
|
+
"""Read a nested value from a decoded metric payload."""
|
|
107
|
+
if not path:
|
|
108
|
+
return payload
|
|
109
|
+
|
|
110
|
+
current = payload
|
|
111
|
+
for part in path:
|
|
112
|
+
if isinstance(current, dict) and part in current:
|
|
113
|
+
current = current[part]
|
|
114
|
+
continue
|
|
115
|
+
return None
|
|
116
|
+
return current
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _numeric_value(value: Any) -> float | None:
|
|
120
|
+
if isinstance(value, Real) and not isinstance(value, bool):
|
|
121
|
+
return float(value)
|
|
122
|
+
return None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _apply_value_scale(value: float, metric_def: dict[str, Any]) -> float:
|
|
126
|
+
scale = metric_def.get("value_scale")
|
|
127
|
+
if isinstance(scale, Real) and not isinstance(scale, bool):
|
|
128
|
+
return value * float(scale)
|
|
129
|
+
return value
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _apply_value_bounds(value: float, metric_def: dict[str, Any]) -> float | None:
|
|
133
|
+
min_value = metric_def.get("min_value")
|
|
134
|
+
max_value = metric_def.get("max_value")
|
|
135
|
+
|
|
136
|
+
if isinstance(min_value, Real) and not isinstance(min_value, bool):
|
|
137
|
+
if value < float(min_value):
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
if isinstance(max_value, Real) and not isinstance(max_value, bool):
|
|
141
|
+
if value > float(max_value):
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
return value
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _entry_value(payload: Any, metric_def: dict[str, Any]) -> float | None:
|
|
148
|
+
"""Extract or derive the numeric value for one metric entry."""
|
|
149
|
+
formula = metric_def.get("formula")
|
|
150
|
+
value_path = metric_def.get("value_path")
|
|
151
|
+
|
|
152
|
+
if formula == "ratio":
|
|
153
|
+
numerator = _numeric_value(
|
|
154
|
+
_path_value(payload, metric_def.get("numerator_path"))
|
|
155
|
+
)
|
|
156
|
+
denominator = _numeric_value(
|
|
157
|
+
_path_value(payload, metric_def.get("denominator_path"))
|
|
158
|
+
)
|
|
159
|
+
if numerator is None or denominator in (None, 0):
|
|
160
|
+
return None
|
|
161
|
+
return numerator / denominator
|
|
162
|
+
|
|
163
|
+
raw_value = _path_value(payload, value_path)
|
|
164
|
+
if value_path is None and isinstance(payload, dict):
|
|
165
|
+
raw_value = payload.get("value")
|
|
166
|
+
|
|
167
|
+
numeric = _numeric_value(raw_value)
|
|
168
|
+
if numeric is None:
|
|
169
|
+
return None
|
|
170
|
+
|
|
171
|
+
if formula == "inverse_one_plus":
|
|
172
|
+
return _apply_value_bounds(
|
|
173
|
+
_apply_value_scale(1.0 / (1.0 + numeric), metric_def),
|
|
174
|
+
metric_def,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
return _apply_value_bounds(_apply_value_scale(numeric, metric_def), metric_def)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class MetricsClient:
|
|
181
|
+
"""Metrics operations mixed into :class:`LocalClient`.
|
|
182
|
+
|
|
183
|
+
All operations delegate to ``self.metrics_provider``.
|
|
184
|
+
"""
|
|
185
|
+
|
|
186
|
+
metrics_provider: MetricsProvider
|
|
187
|
+
|
|
188
|
+
# ── session-level metrics ─────────────────────────────────────────────
|
|
189
|
+
|
|
190
|
+
def get_session_metrics(
|
|
191
|
+
self,
|
|
192
|
+
session_id: str,
|
|
193
|
+
*,
|
|
194
|
+
hops: int = 1,
|
|
195
|
+
metric_names: list[str] | None = None,
|
|
196
|
+
) -> SessionMetricsResponse:
|
|
197
|
+
"""Return metrics attached to *session_id* in the KG."""
|
|
198
|
+
results = self.metrics_provider.get_metrics(session_id, hops=hops)
|
|
199
|
+
return SessionMetricsResponse(
|
|
200
|
+
session_id=session_id,
|
|
201
|
+
metrics=_metric_results_to_items(results, metric_names),
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
# ── span-level metrics ────────────────────────────────────────────────
|
|
205
|
+
|
|
206
|
+
def get_span_metrics(
|
|
207
|
+
self,
|
|
208
|
+
span_id: str,
|
|
209
|
+
*,
|
|
210
|
+
session_id: str | None = None,
|
|
211
|
+
hops: int = 1,
|
|
212
|
+
metric_names: list[str] | None = None,
|
|
213
|
+
) -> SpanMetricsResponse:
|
|
214
|
+
"""Return metrics attached to a span in the KG."""
|
|
215
|
+
results = self.metrics_provider.get_metrics(
|
|
216
|
+
span_id,
|
|
217
|
+
session_id=session_id,
|
|
218
|
+
hops=hops,
|
|
219
|
+
)
|
|
220
|
+
return SpanMetricsResponse(
|
|
221
|
+
session_id=session_id or "",
|
|
222
|
+
span_id=span_id,
|
|
223
|
+
metrics=_metric_results_to_items(results, metric_names),
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
# ── write metrics ─────────────────────────────────────────────────────
|
|
227
|
+
|
|
228
|
+
def write_session_metrics(
|
|
229
|
+
self,
|
|
230
|
+
session_id: str,
|
|
231
|
+
metrics: list[dict],
|
|
232
|
+
) -> dict:
|
|
233
|
+
"""Write metrics to a session node in the KG."""
|
|
234
|
+
results = [
|
|
235
|
+
MetricResult(
|
|
236
|
+
metric_id=m["name"],
|
|
237
|
+
resource_id=session_id,
|
|
238
|
+
provider=m.get("provider", "API"),
|
|
239
|
+
value=m.get("value"),
|
|
240
|
+
reasoning=m.get("reasoning"),
|
|
241
|
+
metadata={
|
|
242
|
+
"metric_id": m.get("metric_id"),
|
|
243
|
+
"source": m.get("source"),
|
|
244
|
+
**{k: m[k] for k in EVALUATION_KEYS if m.get(k) is not None},
|
|
245
|
+
},
|
|
246
|
+
)
|
|
247
|
+
for m in metrics
|
|
248
|
+
]
|
|
249
|
+
ok = self.metrics_provider.save_metrics(results)
|
|
250
|
+
if ok:
|
|
251
|
+
return {"written": len(results), "errors": []}
|
|
252
|
+
return {"written": 0, "errors": ["provider save_metrics returned False"]}
|
|
253
|
+
|
|
254
|
+
# ── category-level metrics ────────────────────────────────────────────
|
|
255
|
+
|
|
256
|
+
def get_metrics_per_category(
|
|
257
|
+
self,
|
|
258
|
+
application_id: str,
|
|
259
|
+
cat_key: str,
|
|
260
|
+
*,
|
|
261
|
+
agent_id: str | None = None,
|
|
262
|
+
start_time: str | None = None,
|
|
263
|
+
end_time: str | None = None,
|
|
264
|
+
) -> dict[str, Any]:
|
|
265
|
+
"""Return metrics for a named category by delegating to ``get_metrics``.
|
|
266
|
+
|
|
267
|
+
Looks up the configured metric definitions for ``cat_key`` in
|
|
268
|
+
:data:`settings.METRIC_CATEGORIES` and calls ``get_metrics`` with the
|
|
269
|
+
list of metric names.
|
|
270
|
+
"""
|
|
271
|
+
categories = getattr(settings, "METRIC_CATEGORIES", {}) or {}
|
|
272
|
+
cat_defs = categories.get(cat_key)
|
|
273
|
+
if not cat_defs:
|
|
274
|
+
raise DatabaseError(f"Unknown metric category '{cat_key}'")
|
|
275
|
+
|
|
276
|
+
metric_names = list(cat_defs.keys())
|
|
277
|
+
return self.get_metrics(
|
|
278
|
+
application_id,
|
|
279
|
+
metric_names,
|
|
280
|
+
agent_id=agent_id,
|
|
281
|
+
start_time=start_time,
|
|
282
|
+
end_time=end_time,
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
def get_metrics(
|
|
286
|
+
self,
|
|
287
|
+
application_id: str,
|
|
288
|
+
metric_names: list[str],
|
|
289
|
+
*,
|
|
290
|
+
agent_id: str | None = None,
|
|
291
|
+
start_time: str | None = None,
|
|
292
|
+
end_time: str | None = None,
|
|
293
|
+
) -> dict[str, Any]:
|
|
294
|
+
"""Return metric values in the same timeline structure as ``/charts``.
|
|
295
|
+
|
|
296
|
+
Accepts an explicit list of metric names. Timeline metrics (those with
|
|
297
|
+
an ``operation`` when a full metric definition is available) are
|
|
298
|
+
time-bucketed into ``PERIODS_COUNT`` intervals and returned as
|
|
299
|
+
``list[TimelineData]``. Card-only metrics (``is_card=True`` or
|
|
300
|
+
``operation=None``) are returned as a single ``SingleValueData``.
|
|
301
|
+
"""
|
|
302
|
+
metric_names = sorted({name for name in metric_names})
|
|
303
|
+
query, params = metrics_queries.metrics_query(
|
|
304
|
+
application_id,
|
|
305
|
+
metric_names,
|
|
306
|
+
agent_id=agent_id,
|
|
307
|
+
start_time=start_time,
|
|
308
|
+
end_time=end_time,
|
|
309
|
+
)
|
|
310
|
+
logger.debug("query:\n%s", query)
|
|
311
|
+
logger.debug("params: %s", params)
|
|
312
|
+
try:
|
|
313
|
+
rows = self.db.execute(query, params)
|
|
314
|
+
logger.debug("rows returned: %d", len(rows) if rows else 0)
|
|
315
|
+
if rows:
|
|
316
|
+
logger.debug("first row: %s", rows[0])
|
|
317
|
+
except Exception as exc:
|
|
318
|
+
raise DatabaseError(
|
|
319
|
+
f"Failed to get metrics by category for '{application_id}': {exc}"
|
|
320
|
+
) from exc
|
|
321
|
+
|
|
322
|
+
# Parse raw entries and collect epochs for bucketing
|
|
323
|
+
entries_by_name: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
|
324
|
+
all_epochs: list[float] = []
|
|
325
|
+
|
|
326
|
+
for row in rows:
|
|
327
|
+
name = row.get("metricName", "")
|
|
328
|
+
if not name:
|
|
329
|
+
continue
|
|
330
|
+
raw_value = row.get("metricResult")
|
|
331
|
+
payload = (
|
|
332
|
+
float(raw_value)
|
|
333
|
+
if isinstance(raw_value, Real) and not isinstance(raw_value, bool)
|
|
334
|
+
else None
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
ts = row.get("timestamp")
|
|
338
|
+
epoch = 0.0
|
|
339
|
+
if hasattr(ts, "timestamp"):
|
|
340
|
+
epoch = ts.timestamp()
|
|
341
|
+
elif isinstance(ts, str):
|
|
342
|
+
from scope.client.utils import timestamp_to_epoch
|
|
343
|
+
|
|
344
|
+
epoch = timestamp_to_epoch(ts)
|
|
345
|
+
|
|
346
|
+
session_id = row.get("sessionId", "")
|
|
347
|
+
entries_by_name[name].append(
|
|
348
|
+
{
|
|
349
|
+
"payload": payload,
|
|
350
|
+
"epoch": epoch,
|
|
351
|
+
"session_id": session_id,
|
|
352
|
+
}
|
|
353
|
+
)
|
|
354
|
+
if epoch > 0:
|
|
355
|
+
all_epochs.append(epoch)
|
|
356
|
+
|
|
357
|
+
# Determine time range for bucketing
|
|
358
|
+
if all_epochs:
|
|
359
|
+
data_start = min(all_epochs)
|
|
360
|
+
data_end = max(all_epochs)
|
|
361
|
+
if data_end - data_start < 10:
|
|
362
|
+
data_end = data_start + 10
|
|
363
|
+
period_size = (data_end - data_start) / (PERIODS_COUNT - 2)
|
|
364
|
+
start_epoch = max(data_start - period_size, 0)
|
|
365
|
+
end_epoch = data_end + period_size
|
|
366
|
+
else:
|
|
367
|
+
from scope.client.utils import parse_epoch_range
|
|
368
|
+
|
|
369
|
+
start_epoch, end_epoch = parse_epoch_range(start_time or "", end_time or "")
|
|
370
|
+
|
|
371
|
+
period_size = (end_epoch - start_epoch) / PERIODS_COUNT
|
|
372
|
+
|
|
373
|
+
result: dict[str, Any] = {}
|
|
374
|
+
for metric_name in metric_names:
|
|
375
|
+
mdef: dict[str, Any] = {}
|
|
376
|
+
is_card = mdef.get("is_card", False)
|
|
377
|
+
operation = mdef.get("operation")
|
|
378
|
+
response_key = mdef.get("response_key", metric_name)
|
|
379
|
+
unit = mdef.get("unit", "SCALAR")
|
|
380
|
+
source_names = mdef.get("source_metrics", [metric_name])
|
|
381
|
+
entries = [
|
|
382
|
+
entry
|
|
383
|
+
for source_name in source_names
|
|
384
|
+
for entry in entries_by_name.get(source_name, [])
|
|
385
|
+
]
|
|
386
|
+
values = [
|
|
387
|
+
value
|
|
388
|
+
for entry in entries
|
|
389
|
+
if (value := _entry_value(entry.get("payload"), mdef)) is not None
|
|
390
|
+
]
|
|
391
|
+
|
|
392
|
+
if is_card or operation is None:
|
|
393
|
+
# Single value card
|
|
394
|
+
agg_value = 0.0
|
|
395
|
+
if values:
|
|
396
|
+
agg_value = sum(values) / len(values)
|
|
397
|
+
result[response_key] = SingleValueData(value=agg_value, unit=unit)
|
|
398
|
+
else:
|
|
399
|
+
# Timeline with time buckets
|
|
400
|
+
timeline: list[TimelineData] = []
|
|
401
|
+
current = start_epoch
|
|
402
|
+
while current < end_epoch:
|
|
403
|
+
bucket_end = current + period_size
|
|
404
|
+
bucket_entries = [
|
|
405
|
+
e for e in entries if current <= e["epoch"] < bucket_end
|
|
406
|
+
]
|
|
407
|
+
bucket_values = [
|
|
408
|
+
value
|
|
409
|
+
for entry in bucket_entries
|
|
410
|
+
if (value := _entry_value(entry.get("payload"), mdef))
|
|
411
|
+
is not None
|
|
412
|
+
]
|
|
413
|
+
bucket_sessions = list(
|
|
414
|
+
{e["session_id"] for e in bucket_entries if e["session_id"]}
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
agg_val = 0.0
|
|
418
|
+
if bucket_values:
|
|
419
|
+
if operation == "sum":
|
|
420
|
+
agg_val = sum(bucket_values)
|
|
421
|
+
elif operation == "average":
|
|
422
|
+
agg_val = sum(bucket_values) / len(bucket_values)
|
|
423
|
+
|
|
424
|
+
timestamp_iso = datetime.fromtimestamp(
|
|
425
|
+
current,
|
|
426
|
+
tz=timezone.utc,
|
|
427
|
+
).isoformat()
|
|
428
|
+
|
|
429
|
+
timeline.append(
|
|
430
|
+
TimelineData(
|
|
431
|
+
timestamp=timestamp_iso,
|
|
432
|
+
sessionIDs=bucket_sessions,
|
|
433
|
+
value=SingleValueData(value=agg_val, unit=unit),
|
|
434
|
+
)
|
|
435
|
+
)
|
|
436
|
+
current = bucket_end
|
|
437
|
+
|
|
438
|
+
result[response_key] = timeline
|
|
439
|
+
|
|
440
|
+
return result
|
|
441
|
+
|
|
442
|
+
def write_span_metrics(
|
|
443
|
+
self,
|
|
444
|
+
session_id: str,
|
|
445
|
+
span_id: str,
|
|
446
|
+
metrics: list[dict],
|
|
447
|
+
) -> dict:
|
|
448
|
+
"""Write metrics to a span node in the KG."""
|
|
449
|
+
from scope.providers import SCOPEMetricsProvider
|
|
450
|
+
|
|
451
|
+
results = [
|
|
452
|
+
MetricResult(
|
|
453
|
+
metric_id=m["name"],
|
|
454
|
+
resource_id=span_id,
|
|
455
|
+
provider=m.get("provider", "API"),
|
|
456
|
+
value=m.get("value"),
|
|
457
|
+
reasoning=m.get("reasoning"),
|
|
458
|
+
metadata={
|
|
459
|
+
"metric_id": m.get("metric_id"),
|
|
460
|
+
"source": m.get("source"),
|
|
461
|
+
**{k: m[k] for k in EVALUATION_KEYS if m.get(k) is not None},
|
|
462
|
+
},
|
|
463
|
+
)
|
|
464
|
+
for m in metrics
|
|
465
|
+
]
|
|
466
|
+
# Use span-specific save if the provider supports it
|
|
467
|
+
if isinstance(self.metrics_provider, SCOPEMetricsProvider):
|
|
468
|
+
ok = self.metrics_provider.save_span_metrics(
|
|
469
|
+
session_id,
|
|
470
|
+
span_id,
|
|
471
|
+
results,
|
|
472
|
+
)
|
|
473
|
+
else:
|
|
474
|
+
ok = self.metrics_provider.save_metrics(results)
|
|
475
|
+
if ok:
|
|
476
|
+
return {"written": len(results), "errors": []}
|
|
477
|
+
return {"written": 0, "errors": ["provider save_metrics returned False"]}
|
|
478
|
+
|
|
479
|
+
def get_application_metrics_summary(
|
|
480
|
+
self,
|
|
481
|
+
application_id: str,
|
|
482
|
+
) -> ApplicationMetricsSummary:
|
|
483
|
+
"""Return summary metrics grouped into reliability, quality, and performance."""
|
|
484
|
+
|
|
485
|
+
reliability = []
|
|
486
|
+
query, params = metrics_queries.reliability_metrics(
|
|
487
|
+
application_id=application_id,
|
|
488
|
+
)
|
|
489
|
+
try:
|
|
490
|
+
rows = self.db.execute(query, params)
|
|
491
|
+
except Exception as exc:
|
|
492
|
+
raise DatabaseError(
|
|
493
|
+
f"Failed to get application reliability metrics for '{application_id}': {exc}"
|
|
494
|
+
) from exc
|
|
495
|
+
|
|
496
|
+
for row in rows:
|
|
497
|
+
metric_name = row["metricName"]
|
|
498
|
+
if metric_name is None:
|
|
499
|
+
# The reliability aggregation can emit rows with a null
|
|
500
|
+
# metricName (e.g. a ConsistencyReport with no dataType, or the
|
|
501
|
+
# completion-rate branch aggregating over zero matched metrics).
|
|
502
|
+
# These are not meaningful metrics, so skip them instead of
|
|
503
|
+
# letting MetricItem raise a ValidationError (which surfaces as
|
|
504
|
+
# an unhandled 500 / misleading CORS error in the browser).
|
|
505
|
+
continue
|
|
506
|
+
reliability.append(MetricItem(name=metric_name, value=row["metricResult"]))
|
|
507
|
+
|
|
508
|
+
quality = []
|
|
509
|
+
query, params = metrics_queries.get_application_metrics_timeline(
|
|
510
|
+
application_id=application_id,
|
|
511
|
+
metrics=[
|
|
512
|
+
"IntentRecognitionAccuracy",
|
|
513
|
+
"Groundedness",
|
|
514
|
+
"ToolUtilizationAccuracy",
|
|
515
|
+
"AnswerRelevancy",
|
|
516
|
+
"ResponseCompleteness",
|
|
517
|
+
],
|
|
518
|
+
)
|
|
519
|
+
try:
|
|
520
|
+
rows = self.db.execute(query, params)
|
|
521
|
+
except Exception as exc:
|
|
522
|
+
raise DatabaseError(
|
|
523
|
+
f"Failed to get application quality metrics for '{application_id}': {exc}"
|
|
524
|
+
) from exc
|
|
525
|
+
|
|
526
|
+
for row in rows:
|
|
527
|
+
quality.append(
|
|
528
|
+
ApplicationMetricsTimeline(
|
|
529
|
+
metric_name=row["metricName"], values=row["dataPoints"]
|
|
530
|
+
)
|
|
531
|
+
)
|
|
532
|
+
|
|
533
|
+
performance = []
|
|
534
|
+
query, params = metrics_queries.get_application_metrics_timeline(
|
|
535
|
+
application_id=application_id,
|
|
536
|
+
metrics=[
|
|
537
|
+
"WorkflowEfficiency",
|
|
538
|
+
"CyclesCount",
|
|
539
|
+
"LLMErrorRate",
|
|
540
|
+
"ToolErrorRate",
|
|
541
|
+
],
|
|
542
|
+
)
|
|
543
|
+
try:
|
|
544
|
+
rows = self.db.execute(query, params)
|
|
545
|
+
except Exception as exc:
|
|
546
|
+
raise DatabaseError(
|
|
547
|
+
f"Failed to get application performance metrics for '{application_id}': {exc}"
|
|
548
|
+
) from exc
|
|
549
|
+
|
|
550
|
+
for row in rows:
|
|
551
|
+
performance.append(
|
|
552
|
+
ApplicationMetricsTimeline(
|
|
553
|
+
metric_name=row["metricName"], values=row["dataPoints"]
|
|
554
|
+
)
|
|
555
|
+
)
|
|
556
|
+
|
|
557
|
+
return ApplicationMetricsSummary(
|
|
558
|
+
quality=quality,
|
|
559
|
+
reliability=reliability,
|
|
560
|
+
performance=performance,
|
|
561
|
+
)
|