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
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Query builders for the **live topology** feature domain."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from scope.query_builders.types import Dialect
|
|
8
|
+
from typing import Optional
|
|
9
|
+
|
|
10
|
+
from sqlalchemy import (
|
|
11
|
+
case,
|
|
12
|
+
column,
|
|
13
|
+
func,
|
|
14
|
+
literal,
|
|
15
|
+
literal_column,
|
|
16
|
+
or_,
|
|
17
|
+
select,
|
|
18
|
+
table,
|
|
19
|
+
distinct,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
_SESSION_EVENT_NAMES = (
|
|
24
|
+
"topology.session.started",
|
|
25
|
+
"topology.session.completed",
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
_AGENT_EVENT_NAMES = (
|
|
29
|
+
"topology.node.started",
|
|
30
|
+
"topology.node.completed",
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
_TOOL_EVENT_NAMES = (
|
|
34
|
+
"tool.started",
|
|
35
|
+
"tool.completed",
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
_ch_otel = table(
|
|
39
|
+
"otel_logs",
|
|
40
|
+
column("Timestamp"),
|
|
41
|
+
column("SpanId"),
|
|
42
|
+
column("Body"),
|
|
43
|
+
column("LogAttributes"),
|
|
44
|
+
column("ServiceName"),
|
|
45
|
+
column("Duration"),
|
|
46
|
+
column("ResourceAttributes"),
|
|
47
|
+
column("ScopeName"),
|
|
48
|
+
column("EventName"),
|
|
49
|
+
column("application_id"),
|
|
50
|
+
column("agent_id"),
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
_sqlite_otel = table(
|
|
54
|
+
"otel_logs",
|
|
55
|
+
column("timestamp"),
|
|
56
|
+
column("span_id"),
|
|
57
|
+
column("body"),
|
|
58
|
+
column("log_attributes"),
|
|
59
|
+
column("service_name"),
|
|
60
|
+
column("duration"),
|
|
61
|
+
column("resource_attributes"),
|
|
62
|
+
column("scope_name"),
|
|
63
|
+
column("event_name"),
|
|
64
|
+
column("application_id"),
|
|
65
|
+
column("agent_id"),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
_ch_traces = table(
|
|
69
|
+
"otel_traces",
|
|
70
|
+
column("session_id"),
|
|
71
|
+
column("application_id"),
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
_sqlite_traces = table(
|
|
75
|
+
"otel_traces",
|
|
76
|
+
column("session_id"),
|
|
77
|
+
column("application_id"),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _identity(expr):
|
|
82
|
+
return expr
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _cols(dialect: str):
|
|
86
|
+
"""Return (table, column-mapping) appropriate for *dialect*."""
|
|
87
|
+
if dialect == "sqlite":
|
|
88
|
+
t = _sqlite_otel
|
|
89
|
+
return dict(
|
|
90
|
+
tbl=t,
|
|
91
|
+
ts=t.c.timestamp,
|
|
92
|
+
span_id=t.c.span_id,
|
|
93
|
+
body=t.c.body,
|
|
94
|
+
log_attributes=t.c.log_attributes,
|
|
95
|
+
service_name=t.c.service_name,
|
|
96
|
+
duration=t.c.duration,
|
|
97
|
+
resource_attributes=t.c.resource_attributes,
|
|
98
|
+
scope_name=t.c.scope_name,
|
|
99
|
+
event_name=t.c.event_name,
|
|
100
|
+
session_id=func.json_extract(t.c.log_attributes, literal('$."session.id"')),
|
|
101
|
+
agent_name=func.json_extract(t.c.log_attributes, literal('$."agent.name"')),
|
|
102
|
+
tool_name=func.json_extract(t.c.log_attributes, literal('$."tool.name"')),
|
|
103
|
+
agent_id=t.c.agent_id,
|
|
104
|
+
wrap=_identity,
|
|
105
|
+
)
|
|
106
|
+
else:
|
|
107
|
+
t = _ch_otel
|
|
108
|
+
return dict(
|
|
109
|
+
tbl=t,
|
|
110
|
+
ts=t.c.Timestamp,
|
|
111
|
+
span_id=t.c.SpanId,
|
|
112
|
+
body=t.c.Body,
|
|
113
|
+
log_attributes=t.c.LogAttributes,
|
|
114
|
+
service_name=t.c.ServiceName,
|
|
115
|
+
duration=t.c.Duration,
|
|
116
|
+
resource_attributes=t.c.ResourceAttributes,
|
|
117
|
+
scope_name=t.c.ScopeName,
|
|
118
|
+
event_name=t.c.EventName,
|
|
119
|
+
session_id=literal_column("LogAttributes['session.id']"),
|
|
120
|
+
agent_name=literal_column("LogAttributes['agent.name']"),
|
|
121
|
+
tool_name=literal_column("LogAttributes['tool.name']"),
|
|
122
|
+
agent_id=t.c.agent_id,
|
|
123
|
+
wrap=_identity,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
_ALL_TOPOLOGY_EVENT_NAMES = (
|
|
128
|
+
*_SESSION_EVENT_NAMES,
|
|
129
|
+
*_AGENT_EVENT_NAMES,
|
|
130
|
+
*_TOOL_EVENT_NAMES,
|
|
131
|
+
"topology.edge.updated",
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def get_topology_events_by_session(
|
|
136
|
+
dialect: Dialect = Dialect.CLICKHOUSE,
|
|
137
|
+
*,
|
|
138
|
+
session_id: str,
|
|
139
|
+
):
|
|
140
|
+
"""Return all topology events for *session_id* ordered by timestamp ascending.
|
|
141
|
+
|
|
142
|
+
Returns columns:
|
|
143
|
+
``(event_name, agent_name, tool_name, source_agent, target_agent,
|
|
144
|
+
edge_id, edge_kind, snapshot_version, timestamp, agent_input, tool_input,
|
|
145
|
+
tool_output)``
|
|
146
|
+
|
|
147
|
+
Covers all event types needed to reconstruct the full runtime topology graph:
|
|
148
|
+
- ``topology.session.started/completed`` — session lifecycle
|
|
149
|
+
- ``topology.node.started/completed`` — agent execution
|
|
150
|
+
- ``topology.edge.updated`` — agent handoffs (edges)
|
|
151
|
+
- ``tool.started/completed`` — tool invocations
|
|
152
|
+
"""
|
|
153
|
+
c = _cols(dialect)
|
|
154
|
+
|
|
155
|
+
if dialect is Dialect.SQLITE:
|
|
156
|
+
t = c["tbl"]
|
|
157
|
+
source_agent = func.json_extract(
|
|
158
|
+
t.c.log_attributes, literal('$."source.agent"')
|
|
159
|
+
)
|
|
160
|
+
target_agent = func.json_extract(
|
|
161
|
+
t.c.log_attributes, literal('$."target.agent"')
|
|
162
|
+
)
|
|
163
|
+
edge_id = func.json_extract(t.c.log_attributes, literal('$."topology.edge.id"'))
|
|
164
|
+
edge_kind = func.json_extract(
|
|
165
|
+
t.c.log_attributes, literal('$."topology.edge.kind"')
|
|
166
|
+
)
|
|
167
|
+
snapshot_version = func.json_extract(
|
|
168
|
+
t.c.log_attributes, literal('$."snapshot.version"')
|
|
169
|
+
)
|
|
170
|
+
agent_input = func.json_extract(t.c.log_attributes, literal('$."agent.input"'))
|
|
171
|
+
tool_input = func.json_extract(t.c.log_attributes, literal('$."tool.input"'))
|
|
172
|
+
tool_output = func.json_extract(t.c.log_attributes, literal('$."tool.output"'))
|
|
173
|
+
else:
|
|
174
|
+
source_agent = literal_column("LogAttributes['source.agent']")
|
|
175
|
+
target_agent = literal_column("LogAttributes['target.agent']")
|
|
176
|
+
edge_id = literal_column("LogAttributes['topology.edge.id']")
|
|
177
|
+
edge_kind = literal_column("LogAttributes['topology.edge.kind']")
|
|
178
|
+
snapshot_version = literal_column("LogAttributes['snapshot.version']")
|
|
179
|
+
agent_input = literal_column("LogAttributes['agent.input']")
|
|
180
|
+
tool_input = literal_column("LogAttributes['tool.input']")
|
|
181
|
+
tool_output = literal_column("LogAttributes['tool.output']")
|
|
182
|
+
|
|
183
|
+
stmt = (
|
|
184
|
+
select(
|
|
185
|
+
c["event_name"].label("event_name"), # 0
|
|
186
|
+
c["agent_name"].label("agent_name"), # 1
|
|
187
|
+
c["tool_name"].label("tool_name"), # 2
|
|
188
|
+
source_agent.label("source_agent"), # 3
|
|
189
|
+
target_agent.label("target_agent"), # 4
|
|
190
|
+
edge_id.label("edge_id"), # 5
|
|
191
|
+
edge_kind.label("edge_kind"), # 6
|
|
192
|
+
snapshot_version.label("snapshot_version"), # 7
|
|
193
|
+
c["ts"].label("timestamp"), # 8
|
|
194
|
+
agent_input.label("agent_input"), # 9
|
|
195
|
+
tool_input.label("tool_input"), # 10
|
|
196
|
+
tool_output.label("tool_output"), # 11
|
|
197
|
+
)
|
|
198
|
+
.select_from(c["tbl"])
|
|
199
|
+
.where(c["event_name"].in_(_ALL_TOPOLOGY_EVENT_NAMES))
|
|
200
|
+
.where(c["session_id"] == session_id)
|
|
201
|
+
.order_by(c["ts"].asc())
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
return stmt
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def get_live_topology_sessions(
|
|
208
|
+
dialect: Dialect = Dialect.CLICKHOUSE,
|
|
209
|
+
*,
|
|
210
|
+
start_time: Optional[str] = None,
|
|
211
|
+
end_time: Optional[str] = None,
|
|
212
|
+
application_name: Optional[str] = None,
|
|
213
|
+
limit: int = 50,
|
|
214
|
+
offset: int = 0,
|
|
215
|
+
):
|
|
216
|
+
"""Return ``(session_id, application_id, timestamp)`` for each session.
|
|
217
|
+
|
|
218
|
+
Only rows with a session event name are considered.
|
|
219
|
+
Sorted by most-recent session start first.
|
|
220
|
+
"""
|
|
221
|
+
c = _cols(dialect)
|
|
222
|
+
|
|
223
|
+
stmt = (
|
|
224
|
+
select(
|
|
225
|
+
c["session_id"].label("session_id"),
|
|
226
|
+
c["wrap"](func.min(c["ts"])).label("timestamp"),
|
|
227
|
+
func.sum(
|
|
228
|
+
case(
|
|
229
|
+
(c["event_name"] == "topology.session.completed", 1),
|
|
230
|
+
else_=0,
|
|
231
|
+
)
|
|
232
|
+
).label("has_completed"),
|
|
233
|
+
c["wrap"](
|
|
234
|
+
func.min(
|
|
235
|
+
case(
|
|
236
|
+
(c["event_name"] == "topology.session.completed", c["ts"]),
|
|
237
|
+
else_=None,
|
|
238
|
+
)
|
|
239
|
+
)
|
|
240
|
+
).label("end_time"),
|
|
241
|
+
)
|
|
242
|
+
.select_from(c["tbl"])
|
|
243
|
+
.where(c["session_id"] != "")
|
|
244
|
+
.where(c["event_name"].in_(_SESSION_EVENT_NAMES))
|
|
245
|
+
.group_by(c["session_id"])
|
|
246
|
+
.order_by(func.min(c["ts"]).desc())
|
|
247
|
+
.limit(limit)
|
|
248
|
+
.offset(offset)
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
if start_time:
|
|
252
|
+
stmt = stmt.where(c["ts"] >= start_time)
|
|
253
|
+
if end_time:
|
|
254
|
+
stmt = stmt.where(c["ts"] <= end_time)
|
|
255
|
+
if application_name:
|
|
256
|
+
if dialect == Dialect.SQLITE:
|
|
257
|
+
stmt = stmt.where(_sqlite_otel.c.application_id == application_name)
|
|
258
|
+
else:
|
|
259
|
+
app_sessions = select(distinct(_ch_traces.c.session_id)).where(
|
|
260
|
+
_ch_traces.c.application_id == application_name
|
|
261
|
+
)
|
|
262
|
+
# The SDK prefixes the session id of the events with the application
|
|
263
|
+
# ("<application>_<uuid>"), while ``otel_traces.session_id`` is stored
|
|
264
|
+
# without it (the column's default strips up to the first "_"). Compare
|
|
265
|
+
# the id as it is and without the prefix.
|
|
266
|
+
raw = "LogAttributes['session.id']"
|
|
267
|
+
unprefixed = literal_column(
|
|
268
|
+
f"multiIf(position({raw}, '_') > 0, "
|
|
269
|
+
f"substring({raw}, position({raw}, '_') + 1), {raw})"
|
|
270
|
+
)
|
|
271
|
+
stmt = stmt.where(
|
|
272
|
+
or_(
|
|
273
|
+
c["session_id"].in_(app_sessions),
|
|
274
|
+
unprefixed.in_(app_sessions),
|
|
275
|
+
)
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
return stmt
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def get_orphan_live_topology_sessions(
|
|
282
|
+
dialect: Dialect = Dialect.CLICKHOUSE,
|
|
283
|
+
*,
|
|
284
|
+
limit: int = 200,
|
|
285
|
+
):
|
|
286
|
+
"""Return candidate orphan sessions and their latest activity timestamp.
|
|
287
|
+
|
|
288
|
+
Returns columns:
|
|
289
|
+
``(session_id, last_activity, started_count, completed_count)``
|
|
290
|
+
|
|
291
|
+
A session is considered an orphan candidate when it has at least one
|
|
292
|
+
``topology.session.started`` event and no ``topology.session.completed`` event.
|
|
293
|
+
|
|
294
|
+
``last_activity`` is computed only from topology-domain events so unrelated
|
|
295
|
+
session-scoped telemetry cannot keep a dead session artificially "recent".
|
|
296
|
+
"""
|
|
297
|
+
c = _cols(dialect)
|
|
298
|
+
|
|
299
|
+
started_count = func.sum(
|
|
300
|
+
case(
|
|
301
|
+
(c["event_name"] == "topology.session.started", 1),
|
|
302
|
+
else_=0,
|
|
303
|
+
)
|
|
304
|
+
)
|
|
305
|
+
completed_count = func.sum(
|
|
306
|
+
case(
|
|
307
|
+
(c["event_name"] == "topology.session.completed", 1),
|
|
308
|
+
else_=0,
|
|
309
|
+
)
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
return (
|
|
313
|
+
select(
|
|
314
|
+
c["session_id"].label("session_id"),
|
|
315
|
+
c["wrap"](func.max(c["ts"])).label("last_activity"),
|
|
316
|
+
started_count.label("started_count"),
|
|
317
|
+
completed_count.label("completed_count"),
|
|
318
|
+
)
|
|
319
|
+
.select_from(c["tbl"])
|
|
320
|
+
.where(c["session_id"] != "")
|
|
321
|
+
.where(c["event_name"].in_(_ALL_TOPOLOGY_EVENT_NAMES))
|
|
322
|
+
.group_by(c["session_id"])
|
|
323
|
+
.having(started_count > 0)
|
|
324
|
+
.having(completed_count == 0)
|
|
325
|
+
.order_by(func.max(c["ts"]).desc())
|
|
326
|
+
.limit(limit)
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def get_live_topology_agents(
|
|
331
|
+
dialect: Dialect = Dialect.CLICKHOUSE,
|
|
332
|
+
*,
|
|
333
|
+
start_time: Optional[str] = None,
|
|
334
|
+
end_time: Optional[str] = None,
|
|
335
|
+
limit: int = 50,
|
|
336
|
+
offset: int = 0,
|
|
337
|
+
):
|
|
338
|
+
"""Return per-agent live execution aggregates.
|
|
339
|
+
|
|
340
|
+
Returns columns:
|
|
341
|
+
``(agent_name, latest_start_time, started_count, completed_count, latest_end_time)``
|
|
342
|
+
|
|
343
|
+
An agent is currently active when ``started_count > completed_count``.
|
|
344
|
+
"""
|
|
345
|
+
c = _cols(dialect)
|
|
346
|
+
|
|
347
|
+
stmt = (
|
|
348
|
+
select(
|
|
349
|
+
c["agent_name"].label("agent_name"),
|
|
350
|
+
c["wrap"](
|
|
351
|
+
func.max(
|
|
352
|
+
case(
|
|
353
|
+
(c["event_name"] == "topology.node.started", c["ts"]),
|
|
354
|
+
else_=None,
|
|
355
|
+
)
|
|
356
|
+
)
|
|
357
|
+
).label("start_time"),
|
|
358
|
+
func.sum(
|
|
359
|
+
case(
|
|
360
|
+
(c["event_name"] == "topology.node.started", 1),
|
|
361
|
+
else_=0,
|
|
362
|
+
)
|
|
363
|
+
).label("started_count"),
|
|
364
|
+
func.sum(
|
|
365
|
+
case(
|
|
366
|
+
(c["event_name"] == "topology.node.completed", 1),
|
|
367
|
+
else_=0,
|
|
368
|
+
)
|
|
369
|
+
).label("completed_count"),
|
|
370
|
+
c["wrap"](
|
|
371
|
+
func.max(
|
|
372
|
+
case(
|
|
373
|
+
(c["event_name"] == "topology.node.completed", c["ts"]),
|
|
374
|
+
else_=None,
|
|
375
|
+
)
|
|
376
|
+
)
|
|
377
|
+
).label("end_time"),
|
|
378
|
+
)
|
|
379
|
+
.select_from(c["tbl"])
|
|
380
|
+
.where(c["agent_name"] != "")
|
|
381
|
+
.where(c["event_name"].in_(_AGENT_EVENT_NAMES))
|
|
382
|
+
.group_by(c["agent_name"])
|
|
383
|
+
.order_by(func.max(c["ts"]).desc())
|
|
384
|
+
.limit(limit)
|
|
385
|
+
.offset(offset)
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
if start_time:
|
|
389
|
+
stmt = stmt.where(c["ts"] >= start_time)
|
|
390
|
+
if end_time:
|
|
391
|
+
stmt = stmt.where(c["ts"] <= end_time)
|
|
392
|
+
|
|
393
|
+
return stmt
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def get_live_topology_tools(
|
|
397
|
+
dialect: Dialect = Dialect.CLICKHOUSE,
|
|
398
|
+
*,
|
|
399
|
+
start_time: Optional[str] = None,
|
|
400
|
+
end_time: Optional[str] = None,
|
|
401
|
+
limit: int = 50,
|
|
402
|
+
offset: int = 0,
|
|
403
|
+
):
|
|
404
|
+
"""Return per-tool live execution aggregates.
|
|
405
|
+
|
|
406
|
+
Returns columns:
|
|
407
|
+
``(tool_name, latest_start_time, started_count, completed_count, latest_end_time)``
|
|
408
|
+
|
|
409
|
+
A tool is currently active when ``started_count > completed_count``.
|
|
410
|
+
"""
|
|
411
|
+
c = _cols(dialect)
|
|
412
|
+
|
|
413
|
+
stmt = (
|
|
414
|
+
select(
|
|
415
|
+
c["tool_name"].label("tool_name"),
|
|
416
|
+
c["wrap"](
|
|
417
|
+
func.max(
|
|
418
|
+
case(
|
|
419
|
+
(c["event_name"] == "tool.started", c["ts"]),
|
|
420
|
+
else_=None,
|
|
421
|
+
)
|
|
422
|
+
)
|
|
423
|
+
).label("start_time"),
|
|
424
|
+
func.sum(
|
|
425
|
+
case(
|
|
426
|
+
(c["event_name"] == "tool.started", 1),
|
|
427
|
+
else_=0,
|
|
428
|
+
)
|
|
429
|
+
).label("started_count"),
|
|
430
|
+
func.sum(
|
|
431
|
+
case(
|
|
432
|
+
(c["event_name"] == "tool.completed", 1),
|
|
433
|
+
else_=0,
|
|
434
|
+
)
|
|
435
|
+
).label("completed_count"),
|
|
436
|
+
c["wrap"](
|
|
437
|
+
func.max(
|
|
438
|
+
case(
|
|
439
|
+
(c["event_name"] == "tool.completed", c["ts"]),
|
|
440
|
+
else_=None,
|
|
441
|
+
)
|
|
442
|
+
)
|
|
443
|
+
).label("end_time"),
|
|
444
|
+
)
|
|
445
|
+
.select_from(c["tbl"])
|
|
446
|
+
.where(c["tool_name"] != "")
|
|
447
|
+
.where(c["event_name"].in_(_TOOL_EVENT_NAMES))
|
|
448
|
+
.group_by(c["tool_name"])
|
|
449
|
+
.order_by(func.max(c["ts"]).desc())
|
|
450
|
+
.limit(limit)
|
|
451
|
+
.offset(offset)
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
if start_time:
|
|
455
|
+
stmt = stmt.where(c["ts"] >= start_time)
|
|
456
|
+
if end_time:
|
|
457
|
+
stmt = stmt.where(c["ts"] <= end_time)
|
|
458
|
+
|
|
459
|
+
return stmt
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def get_live_topology_tool_inference_events(
|
|
463
|
+
dialect: Dialect = Dialect.CLICKHOUSE,
|
|
464
|
+
*,
|
|
465
|
+
start_time: Optional[str] = None,
|
|
466
|
+
end_time: Optional[str] = None,
|
|
467
|
+
limit: int = 200,
|
|
468
|
+
offset: int = 0,
|
|
469
|
+
):
|
|
470
|
+
"""Return recent agent events with payloads for tool inference fallback.
|
|
471
|
+
|
|
472
|
+
Returns columns:
|
|
473
|
+
``(agent_name, timestamp, agent_input)``
|
|
474
|
+
"""
|
|
475
|
+
c = _cols(dialect)
|
|
476
|
+
|
|
477
|
+
if dialect is Dialect.SQLITE:
|
|
478
|
+
agent_input = func.json_extract(
|
|
479
|
+
c["tbl"].c.log_attributes, literal('$."agent.input"')
|
|
480
|
+
)
|
|
481
|
+
else:
|
|
482
|
+
agent_input = literal_column("LogAttributes['agent.input']")
|
|
483
|
+
|
|
484
|
+
stmt = (
|
|
485
|
+
select(
|
|
486
|
+
c["agent_name"].label("agent_name"),
|
|
487
|
+
c["ts"].label("timestamp"),
|
|
488
|
+
agent_input.label("agent_input"),
|
|
489
|
+
)
|
|
490
|
+
.select_from(c["tbl"])
|
|
491
|
+
.where(c["agent_name"] != "")
|
|
492
|
+
.where(c["event_name"].in_(_AGENT_EVENT_NAMES))
|
|
493
|
+
.order_by(c["ts"].desc())
|
|
494
|
+
.limit(limit)
|
|
495
|
+
.offset(offset)
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
if start_time:
|
|
499
|
+
stmt = stmt.where(c["ts"] >= start_time)
|
|
500
|
+
if end_time:
|
|
501
|
+
stmt = stmt.where(c["ts"] <= end_time)
|
|
502
|
+
|
|
503
|
+
return stmt
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""How metrics are stored in the knowledge graph: the ontology's Metric + MetricResult.
|
|
4
|
+
|
|
5
|
+
::
|
|
6
|
+
|
|
7
|
+
(r:MetricResult {id, name, result, reasoning, timestamp, evaluation*})
|
|
8
|
+
-[:ofMetricType]-> (d:Metric {id, name, metricProvider, unit, valueRange})
|
|
9
|
+
(r:MetricResult) -[:measures]-> (t)
|
|
10
|
+
|
|
11
|
+
``Metric`` is the *definition*: one node per metric name and provider (so
|
|
12
|
+
``Groundedness`` computed by ``Native`` and by ``DeepEval`` are two definitions).
|
|
13
|
+
``MetricResult`` is one *observation* of it. ``t`` is what was measured: a
|
|
14
|
+
``Session`` (found by ``sessionId``) or an execution element, an
|
|
15
|
+
``LLMCall``/``ToolCall``/``AgentCall``... (found by ``spanId``). There is no
|
|
16
|
+
``hasMetric`` edge and no ``Span`` node.
|
|
17
|
+
|
|
18
|
+
A result is keyed by its definition and the measured resource, so computing a
|
|
19
|
+
metric again overwrites the previous observation instead of adding one.
|
|
20
|
+
|
|
21
|
+
The node properties are exactly the fields of the models generated from the
|
|
22
|
+
ontology (``scope_ontology.models.nodes.Metric`` / ``MetricResult``); every write
|
|
23
|
+
is validated against them.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import hashlib
|
|
29
|
+
from datetime import datetime, timezone
|
|
30
|
+
from typing import Any, Literal
|
|
31
|
+
|
|
32
|
+
from scope_ontology.models.nodes import Metric as MetricModel
|
|
33
|
+
from scope_ontology.models.nodes import MetricResult as MetricResultModel
|
|
34
|
+
|
|
35
|
+
# MetricResult.metadata key (set by the MCE and the stateful-eval worker) ->
|
|
36
|
+
# field of MetricResult for the LLM cost of computing a metric.
|
|
37
|
+
_EVALUATION_FIELDS: dict[str, str] = {
|
|
38
|
+
"evaluation_model": "evaluationModel",
|
|
39
|
+
"evaluation_prompt_tokens": "evaluationPromptTokenCount",
|
|
40
|
+
"evaluation_completion_tokens": "evaluationCompletionTokenCount",
|
|
41
|
+
"evaluation_total_tokens": "evaluationTotalTokenCount",
|
|
42
|
+
"evaluation_cost_usd": "evaluationCost",
|
|
43
|
+
}
|
|
44
|
+
EVALUATION_KEYS = tuple(_EVALUATION_FIELDS)
|
|
45
|
+
|
|
46
|
+
# API metric catalog unit -> (ontology unit, value range)
|
|
47
|
+
_UNITS: dict[str, tuple[str, str]] = {
|
|
48
|
+
"PERCENTAGE": ("dimensionless", "0.0-1.0"),
|
|
49
|
+
"DOLLAR": ("USD", "non-negative"),
|
|
50
|
+
"MILLISECONDS": ("ms", "non-negative"),
|
|
51
|
+
"TOKENS": ("tokens", "non-negative integer"),
|
|
52
|
+
"SCALAR": ("dimensionless", ""),
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
Target = Literal["session", "execution", "call", "any", "protocol_execution_report"]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _digest(*parts: str) -> str:
|
|
59
|
+
return hashlib.sha1("\x1f".join(parts).encode("utf-8")).hexdigest()[:12]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def metric_definition_id(metric_name: str, provider: str) -> str:
|
|
63
|
+
"""Id of the ``Metric`` definition of ``metric_name`` computed by ``provider``."""
|
|
64
|
+
return f"metric:{_digest(provider, metric_name)}"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _catalog_unit(metric_name: str) -> tuple[str, str]:
|
|
68
|
+
"""Ontology unit and value range of a metric, from the API metric catalog."""
|
|
69
|
+
from scope.core.config import settings
|
|
70
|
+
|
|
71
|
+
for category in (getattr(settings, "METRIC_CATEGORIES", None) or {}).values():
|
|
72
|
+
for key, definition in category.items():
|
|
73
|
+
if metric_name in (key, key.rsplit(".", 1)[-1]) and isinstance(
|
|
74
|
+
definition, dict
|
|
75
|
+
):
|
|
76
|
+
return _UNITS.get(str(definition.get("unit") or ""), ("", ""))
|
|
77
|
+
return "", ""
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def metric_definition_properties(metric_name: str, provider: str) -> dict[str, Any]:
|
|
81
|
+
"""Properties of the ontology ``Metric`` definition (validated against the model)."""
|
|
82
|
+
unit, value_range = _catalog_unit(metric_name)
|
|
83
|
+
return MetricModel(
|
|
84
|
+
id=metric_definition_id(metric_name, provider),
|
|
85
|
+
name=metric_name,
|
|
86
|
+
metricProvider=provider,
|
|
87
|
+
unit=unit,
|
|
88
|
+
valueRange=value_range,
|
|
89
|
+
).model_dump()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def metric_result_properties(
|
|
93
|
+
metric_name: str,
|
|
94
|
+
provider: str,
|
|
95
|
+
resource_id: str,
|
|
96
|
+
value: Any,
|
|
97
|
+
reasoning: str = "",
|
|
98
|
+
metadata: dict[str, Any] | None = None,
|
|
99
|
+
timestamp: datetime | None = None,
|
|
100
|
+
) -> dict[str, Any]:
|
|
101
|
+
"""Properties of the ontology ``MetricResult`` for one observation.
|
|
102
|
+
|
|
103
|
+
Validated against the model generated from the ontology, so every stored
|
|
104
|
+
result has the same fields: ``id``, ``name``, ``result``, ``reasoning``,
|
|
105
|
+
``timestamp`` and the ``evaluation*`` cost fields. A metric that made no LLM
|
|
106
|
+
call carries the model defaults (empty model, zero tokens, zero cost).
|
|
107
|
+
Raises ``pydantic.ValidationError`` if the observation does not fit the
|
|
108
|
+
model, for example a non-numeric ``value`` or cost.
|
|
109
|
+
"""
|
|
110
|
+
metadata = metadata or {}
|
|
111
|
+
evaluation = {
|
|
112
|
+
field: metadata[key]
|
|
113
|
+
for key, field in _EVALUATION_FIELDS.items()
|
|
114
|
+
if metadata.get(key) is not None
|
|
115
|
+
}
|
|
116
|
+
return MetricResultModel(
|
|
117
|
+
id=f"metricresult:{_digest(metric_definition_id(metric_name, provider), resource_id)}",
|
|
118
|
+
name=metric_name,
|
|
119
|
+
result=value,
|
|
120
|
+
reasoning=reasoning or "",
|
|
121
|
+
timestamp=timestamp or datetime.now(timezone.utc),
|
|
122
|
+
**evaluation,
|
|
123
|
+
).model_dump()
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# Execution elements (ExecutionElement subclasses, but the Session) carry the span id.
|
|
127
|
+
_EXECUTION_LABELS = "LLMCall|ToolCall|AgentCall|CapabilityCall|MASCall|ProcessingCall"
|
|
128
|
+
|
|
129
|
+
_TARGET_MATCH: dict[str, str] = {
|
|
130
|
+
"session": "MATCH (t:Session {sessionId: $resource_id})",
|
|
131
|
+
"execution": (
|
|
132
|
+
f"MATCH (t:{_EXECUTION_LABELS} {{spanId: $resource_id}})\n"
|
|
133
|
+
" WHERE $session_id IS NULL OR t.sessionId = $session_id"
|
|
134
|
+
),
|
|
135
|
+
# A call node by its own id (the trajectory's call id, not the OTel span id).
|
|
136
|
+
"call": (
|
|
137
|
+
f"MATCH (t:{_EXECUTION_LABELS} {{id: $resource_id}})\n"
|
|
138
|
+
" WHERE $session_id IS NULL OR t.sessionId = $session_id"
|
|
139
|
+
),
|
|
140
|
+
# A Cognition protocol execution report by its own id: the protocol's evaluation metrics measure it.
|
|
141
|
+
"protocol_execution_report": "MATCH (t:CognitionProtocolExecutionReport {id: $resource_id})",
|
|
142
|
+
"any": (
|
|
143
|
+
"OPTIONAL MATCH (s:Session {sessionId: $resource_id})\n"
|
|
144
|
+
f" OPTIONAL MATCH (e:{_EXECUTION_LABELS} {{spanId: $resource_id}})\n"
|
|
145
|
+
" WITH coalesce(s, e) AS t\n"
|
|
146
|
+
" WHERE t IS NOT NULL"
|
|
147
|
+
),
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def write_metric_result_query(
|
|
152
|
+
target: Target,
|
|
153
|
+
resource_id: str,
|
|
154
|
+
definition: dict[str, Any],
|
|
155
|
+
result: dict[str, Any],
|
|
156
|
+
session_id: str | None = None,
|
|
157
|
+
) -> tuple[str, dict[str, Any]]:
|
|
158
|
+
"""MERGE a ``MetricResult`` and its ``Metric`` definition onto what it measures.
|
|
159
|
+
|
|
160
|
+
``target`` says what ``resource_id`` is: a ``session`` id, an ``execution``
|
|
161
|
+
element's span id or a ``call`` node's id (both optionally within
|
|
162
|
+
``session_id``), ``any`` session or span id, or a ``protocol_execution_report``
|
|
163
|
+
by its id.
|
|
164
|
+
Nothing is written if the measured node does not exist.
|
|
165
|
+
"""
|
|
166
|
+
query = f"""
|
|
167
|
+
{_TARGET_MATCH[target]}
|
|
168
|
+
MERGE (d:Metric {{id: $definition.id}})
|
|
169
|
+
SET d += $definition
|
|
170
|
+
MERGE (r:MetricResult {{id: $result.id}})
|
|
171
|
+
SET r += $result
|
|
172
|
+
MERGE (r)-[:ofMetricType]->(d)
|
|
173
|
+
MERGE (r)-[:measures]->(t)
|
|
174
|
+
RETURN r.id AS id
|
|
175
|
+
"""
|
|
176
|
+
return query, {
|
|
177
|
+
"resource_id": resource_id,
|
|
178
|
+
"session_id": session_id,
|
|
179
|
+
"definition": definition,
|
|
180
|
+
"result": result,
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def clean_metrics_query(session_id: str | None) -> tuple[str, dict[str, Any]]:
|
|
185
|
+
"""Delete the metric results of a session (or of everything); definitions stay."""
|
|
186
|
+
if session_id:
|
|
187
|
+
return (
|
|
188
|
+
"""
|
|
189
|
+
MATCH (r:MetricResult)-[:measures]->(t)
|
|
190
|
+
WHERE t.sessionId = $session_id
|
|
191
|
+
DETACH DELETE r
|
|
192
|
+
RETURN count(r) AS deleted
|
|
193
|
+
""",
|
|
194
|
+
{"session_id": session_id},
|
|
195
|
+
)
|
|
196
|
+
return "MATCH (r:MetricResult) DETACH DELETE r RETURN count(r) AS deleted", {}
|