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,354 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Query builders for the **Metrics** feature domain.
4
+
5
+ Provides Cypher query builders for session-level and span-level metric
6
+ retrieval from Neo4j, with optional sub-graph expansion controlled by
7
+ a ``hops`` parameter.
8
+
9
+ Metrics are read from the ontology model written by
10
+ :mod:`scope.query_builders.metric_graph`::
11
+
12
+ (r:MetricResult)-[:ofMetricType]->(d:Metric) # d is the definition
13
+ (r:MetricResult)-[:measures]->(t) # Session or execution element
14
+
15
+ The "span" of the API is the execution element (``LLMCall``, ``ToolCall``,
16
+ ``AgentCall``...) carrying that ``spanId``.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from datetime import datetime, timezone
22
+ from typing import Any
23
+
24
+
25
+ def _to_iso(value: str) -> str:
26
+ """Normalise a timestamp to ISO-8601 with timezone for Neo4j ``datetime()``.
27
+
28
+ Accepts epoch seconds/millis (plain numeric string) or ISO-8601 strings.
29
+ Always returns a timezone-aware ISO string ending with ``+00:00``.
30
+ """
31
+ try:
32
+ numeric = float(value)
33
+ # Heuristic: values > 1e12 are epoch millis, otherwise seconds
34
+ if numeric > 1e12:
35
+ numeric /= 1000.0
36
+ return datetime.fromtimestamp(numeric, tz=timezone.utc).isoformat()
37
+ except ValueError:
38
+ pass
39
+ # Already ISO-8601; ensure it has a timezone suffix for Neo4j
40
+ if value.endswith("Z"):
41
+ return value[:-1] + "+00:00"
42
+ return value
43
+
44
+
45
+ # Execution elements carry the span id (everything but the Session).
46
+ _EXECUTION_LABELS = "LLMCall|ToolCall|AgentCall|CapabilityCall|MASCall|ProcessingCall"
47
+
48
+ # Dict projected for each result in the ``metrics`` list of a session/span lookup.
49
+ _METRIC_MAP = """{
50
+ name: d.name,
51
+ result: r.result,
52
+ value: r.result,
53
+ provider: d.metricProvider,
54
+ metric_id: d.name,
55
+ source: d.metricProvider,
56
+ reasoning: r.reasoning
57
+ }"""
58
+
59
+ # Sub-graph expansion must not walk through a (shared) ``Metric`` definition:
60
+ # it links every result of that metric, so it would pull in unrelated sessions.
61
+ _NO_DEFINITION = "none(n IN nodes(path) WHERE n:Metric)"
62
+
63
+
64
+ def _metrics_with_subgraph(anchor: str, var: str, key: str, hops: int) -> str:
65
+ """Query returning the results measuring ``var`` plus, if ``hops`` > 0, its sub-graph."""
66
+ if hops <= 0:
67
+ return f"""
68
+ {anchor}
69
+ OPTIONAL MATCH (r:MetricResult)-[:measures]->({var}), (r)-[:ofMetricType]->(d:Metric)
70
+ RETURN
71
+ {var}.{key} AS {key},
72
+ collect(DISTINCT {_METRIC_MAP}) AS metrics,
73
+ null AS subgraph
74
+ """
75
+ return f"""
76
+ {anchor}
77
+ OPTIONAL MATCH (r:MetricResult)-[:measures]->({var}), (r)-[:ofMetricType]->(d:Metric)
78
+ WITH {var}, collect(DISTINCT {_METRIC_MAP}) AS metrics
79
+ OPTIONAL MATCH path = ({var})-[*1..{hops}]-(related)
80
+ WHERE {_NO_DEFINITION}
81
+ WITH {var}, metrics,
82
+ collect(DISTINCT {{
83
+ id: elementId(related),
84
+ labels: labels(related),
85
+ properties: properties(related)
86
+ }}) AS nodes,
87
+ collect(DISTINCT {{
88
+ type: type(relationships(path)[-1]),
89
+ startId: elementId(startNode(relationships(path)[-1])),
90
+ endId: elementId(endNode(relationships(path)[-1]))
91
+ }}) AS edges
92
+ RETURN
93
+ {var}.{key} AS {key},
94
+ metrics,
95
+ {{nodes: nodes, edges: edges}} AS subgraph
96
+ """
97
+
98
+
99
+ def session_metrics_query(
100
+ session_id: str,
101
+ *,
102
+ hops: int = 1,
103
+ ) -> tuple[str, dict[str, Any]]:
104
+ """Return metrics for a session, with optional sub-graph of *hops* depth.
105
+
106
+ When ``hops`` is 0, only the results measuring the session node are
107
+ returned. Each additional hop expands the traversal through related
108
+ nodes (states, calls, embeddings, results...) and returns them as a
109
+ sub-graph; ``Metric`` definitions are not traversed.
110
+ """
111
+ query = _metrics_with_subgraph(
112
+ "MATCH (session:Session {sessionId: $session_id})",
113
+ "session",
114
+ "sessionId",
115
+ hops,
116
+ )
117
+ return query, {"session_id": session_id}
118
+
119
+
120
+ def span_metrics_query(
121
+ span_id: str,
122
+ *,
123
+ session_id: str | None = None,
124
+ hops: int = 1,
125
+ ) -> tuple[str, dict[str, Any]]:
126
+ """Return metrics for a span, with optional sub-graph of *hops* depth.
127
+
128
+ The span is the execution element (call) with that ``spanId``. If
129
+ *session_id* is also given the match is stricter (the element must belong
130
+ to that session), but it is not required.
131
+ """
132
+ anchor = f"MATCH (span:{_EXECUTION_LABELS} {{spanId: $span_id}})"
133
+ params: dict[str, Any] = {"span_id": span_id}
134
+ if session_id:
135
+ anchor += "\n WHERE span.sessionId = $session_id"
136
+ params["session_id"] = session_id
137
+ return _metrics_with_subgraph(anchor, "span", "spanId", hops), params
138
+
139
+
140
+ # ── category / application-level read queries ────────────────────────────────
141
+
142
+ _ROW_PROJECTION = """
143
+ s.sessionId AS sessionId,
144
+ d.name AS metricName,
145
+ r.result AS metricResult,
146
+ r.result AS value,
147
+ d.metricProvider AS provider,
148
+ d.name AS metricId,
149
+ d.metricProvider AS source,
150
+ r.reasoning AS reasoning,
151
+ r.timestamp AS timestamp"""
152
+
153
+
154
+ def metrics_query(
155
+ application_id: str,
156
+ metric_names: list[str],
157
+ *,
158
+ agent_id: str | None = None,
159
+ start_time: str | None = None,
160
+ end_time: str | None = None,
161
+ ) -> tuple[str, dict[str, Any]]:
162
+ """Return metrics for an application filtered by a list of metric names.
163
+
164
+ Traversal (no agent filter):
165
+ ``MAS {id} <-[:executesSession]- Session <-[:measures]- MetricResult``
166
+ Traversal (with agent filter), additionally the results measuring the
167
+ calls of that agent in the session:
168
+ ``Session <- AgentCall {agentName} -[:hasLLMCall|hasToolCall*0..1]-> t
169
+ <-[:measures]- MetricResult``
170
+
171
+ The definition (name, provider) is reached through ``ofMetricType``.
172
+ """
173
+ time_clauses: list[str] = []
174
+ params: dict[str, Any] = {
175
+ "application_id": application_id,
176
+ "metric_names": metric_names,
177
+ }
178
+
179
+ if start_time:
180
+ params["start_time"] = _to_iso(start_time)
181
+ time_clauses.append("r.timestamp >= datetime($start_time)")
182
+ if end_time:
183
+ params["end_time"] = _to_iso(end_time)
184
+ time_clauses.append("r.timestamp <= datetime($end_time)")
185
+
186
+ where = ""
187
+ if time_clauses:
188
+ where = "AND " + " AND ".join(time_clauses)
189
+
190
+ if agent_id:
191
+ params["agent_id"] = agent_id
192
+ # Return both session-measuring results and results measuring the
193
+ # agent's calls (the agent call itself and its LLM/tool calls).
194
+ query = f"""
195
+ MATCH (s:Session)-[:executesSession]->(:MAS {{id: $application_id}})
196
+ WHERE EXISTS {{
197
+ MATCH (a:AgentCall {{sessionId: s.sessionId, agentName: $agent_id}})
198
+ }}
199
+ CALL (s) {{
200
+ MATCH (s)<-[:measures]-(r:MetricResult)-[:ofMetricType]->(d:Metric)
201
+ WHERE d.name IN $metric_names
202
+ {where}
203
+ RETURN {_ROW_PROJECTION}
204
+
205
+ UNION
206
+
207
+ MATCH (ac:AgentCall {{sessionId: s.sessionId, agentName: $agent_id}})
208
+ -[:hasLLMCall|hasToolCall*0..1]->(t)
209
+ MATCH (t)<-[:measures]-(r:MetricResult)-[:ofMetricType]->(d:Metric)
210
+ WHERE d.name IN $metric_names
211
+ {where}
212
+ RETURN {_ROW_PROJECTION}
213
+ }}
214
+ RETURN DISTINCT
215
+ sessionId,
216
+ metricName,
217
+ metricResult,
218
+ value,
219
+ provider,
220
+ metricId,
221
+ source,
222
+ reasoning,
223
+ timestamp
224
+ ORDER BY metricName, timestamp
225
+ """
226
+ else:
227
+ query = f"""
228
+ MATCH (s:Session)-[:executesSession]->(:MAS {{id: $application_id}})
229
+ MATCH (s)<-[:measures]-(r:MetricResult)-[:ofMetricType]->(d:Metric)
230
+ WHERE d.name IN $metric_names
231
+ {where}
232
+ RETURN {_ROW_PROJECTION}
233
+ ORDER BY metricName, timestamp
234
+ """
235
+ return query, params
236
+
237
+
238
+ # ── aggregation queries ──────────────────────────────────────────────────────
239
+
240
+
241
+ def metrics_over_time_query(
242
+ metric_id: str,
243
+ start: datetime,
244
+ end: datetime | None,
245
+ bucket: str,
246
+ app_name: str | None,
247
+ agent_id: str | None,
248
+ ) -> tuple[str, dict[str, Any]]:
249
+ """Build a time-bucketed aggregation query for a single metric.
250
+
251
+ Returns per-bucket avg/min/max/count over all sessions in the range.
252
+ ``bucket`` must be a valid ``datetime.truncate`` unit (minute / hour / day).
253
+ """
254
+ where_parts = [
255
+ "d.name = $metric_id",
256
+ "r.timestamp >= datetime($start)",
257
+ "r.result IS NOT NULL",
258
+ ]
259
+ params: dict[str, Any] = {
260
+ "metric_id": metric_id,
261
+ "start": start.isoformat(),
262
+ "bucket": bucket,
263
+ }
264
+ if end is not None:
265
+ where_parts.append("r.timestamp <= datetime($end)")
266
+ params["end"] = end.isoformat()
267
+ if app_name is not None:
268
+ where_parts.append("s.appName = $app_name")
269
+ params["app_name"] = app_name
270
+ if agent_id is not None:
271
+ where_parts.append(
272
+ "EXISTS { MATCH (:AgentCall {sessionId: s.sessionId, agentName: $agent_id}) }"
273
+ )
274
+ params["agent_id"] = agent_id
275
+
276
+ where_clause = "\n AND ".join(where_parts)
277
+ query = f"""
278
+ MATCH (r:MetricResult)-[:measures]->(s:Session), (r)-[:ofMetricType]->(d:Metric)
279
+ WHERE {where_clause}
280
+ WITH datetime.truncate($bucket, r.timestamp) AS bucket,
281
+ toFloat(r.result) AS v
282
+ RETURN toString(bucket) AS bucket,
283
+ avg(v) AS avg_value,
284
+ min(v) AS min_value,
285
+ max(v) AS max_value,
286
+ count(*) AS n_sessions
287
+ ORDER BY bucket
288
+ """
289
+ return query, params
290
+
291
+
292
+ def get_application_metrics_timeline(
293
+ application_id: str,
294
+ metrics: list[str],
295
+ start_time: str | None = None,
296
+ end_time: str | None = None,
297
+ ) -> tuple[str, dict[str, Any]]:
298
+ params = {"application_id": application_id, "metrics": metrics}
299
+ query = """
300
+ MATCH (s:Session)-[:executesSession]->(:MAS {id: $application_id})
301
+ MATCH (s)<-[:measures]-(r:MetricResult)-[:ofMetricType]->(d:Metric)
302
+ WHERE d.name IN $metrics
303
+ AND s.startTime IS NOT NULL
304
+ AND r.result IS NOT NULL
305
+ WITH d.name AS metricName, s.startTime AS startTime, r.result AS metricValue
306
+ ORDER BY s.startTime
307
+ RETURN
308
+ metricName,
309
+ collect([startTime, metricValue]) AS dataPoints
310
+ """
311
+
312
+ return query, params
313
+
314
+
315
+ def reliability_metrics(
316
+ application_id: str,
317
+ start_time: str | None = None,
318
+ end_time: str | None = None,
319
+ ) -> tuple[str, dict[str, Any]]:
320
+ """Reliability sub-scores for the application's health score.
321
+
322
+ ``ConsistencyReport`` isn't linked to ``MAS`` directly -- it's scoped
323
+ to the application via the ``SemanticGroup`` whose sessions it was
324
+ computed over (``ConsistencyReport -[:ofSemanticGroup]-> SemanticGroup
325
+ -[:containsSession]-> Session -[:executesSession]-> MAS``), so that
326
+ walk is used instead of matching ``ConsistencyReport`` globally across
327
+ every application.
328
+ """
329
+ params = {"application_id": application_id}
330
+ query = """
331
+ // Consistency (scoped to this application via its semantic groups' sessions)
332
+ MATCH (cr:ConsistencyReport)-[:ofSemanticGroup]->(:SemanticGroup)
333
+ -[:containsSession]->(:Session)-[:executesSession]->(:MAS {id: $application_id})
334
+ WITH DISTINCT cr
335
+ WITH cr.dataType AS rawType, AVG(cr.mean) AS Reliability
336
+ WITH (CASE rawType
337
+ WHEN 'metric' THEN 'MetricConsistency'
338
+ WHEN 'graph' THEN 'GraphConsistency'
339
+ WHEN 'text' THEN 'TextConsistency'
340
+ ELSE rawType END) AS DataType, Reliability
341
+ WITH collect({col1: DataType, col2: Reliability}) AS reliabilityStats
342
+
343
+ // Completion Rate
344
+ MATCH (:MAS {id: $application_id})<-[:executesSession]-(s:Session)
345
+ <-[:measures]-(r:MetricResult)-[:ofMetricType]->(d:Metric)
346
+ WHERE d.name IN ['ToolErrorRate', 'LLMErrorRate']
347
+ WITH reliabilityStats, 1 - AVG(r.result) AS CompletionRate
348
+
349
+ WITH reliabilityStats + [{col1: "CompletionRate", col2: CompletionRate}] AS finalResults
350
+ UNWIND finalResults AS row
351
+ RETURN row.col1 AS metricName, row.col2 AS metricResult
352
+ """
353
+
354
+ return query, params
@@ -0,0 +1,46 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Query builders for the **semantic groups** feature domain."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any
8
+
9
+
10
+ def get_normal_behaviour_report(semantic_group_id: str) -> tuple[str, dict[str, Any]]:
11
+ """Cypher query for normal behaviour reports (metric type) of a semantic group."""
12
+ query = """
13
+ MATCH (s:SemanticGroup {id: $semantic_group_id})-[:hasNormalBehaviourReport]->(r:NormalBehaviourReport {dataType: "metric"})
14
+ RETURN r.metadata AS metadata, r.centroid AS centroid
15
+ """
16
+ return query, {"semantic_group_id": semantic_group_id}
17
+
18
+
19
+ def get_consistency_report(semantic_group_id: str) -> tuple[str, dict[str, Any]]:
20
+ """Cypher query for consistency reports (metric type) of a semantic group."""
21
+ query = """
22
+ MATCH (s:SemanticGroup {id: $semantic_group_id})-[:hasConsistencyReport]->(r:ConsistencyReport {dataType: "metric"})
23
+ RETURN r.confidenceIndicator AS confidence_indicator, r.metadata AS metadata, r.mean AS mean
24
+ """
25
+ return query, {"semantic_group_id": semantic_group_id}
26
+
27
+
28
+ def get_anomaly_report(semantic_group_id: str) -> tuple[str, dict[str, Any]]:
29
+ """Cypher query for anomaly reports (metric type) with non-empty outliers."""
30
+ query = """
31
+ MATCH (s:SemanticGroup {id: $semantic_group_id})-[:hasAnomalyReport]->(r:AnomalyReport {dataType: "metric"})
32
+ WHERE r.outliersValues <> "[]"
33
+ AND r.outliersValues IS NOT NULL
34
+ AND r.outliersValues <> ""
35
+ RETURN r
36
+ """
37
+ return query, {"semantic_group_id": semantic_group_id}
38
+
39
+
40
+ def get_details(semantic_group_id: str) -> tuple[str, dict[str, Any]]:
41
+ """Cypher query for semantic group node details."""
42
+ query = """
43
+ MATCH (s:SemanticGroup {id: $semantic_group_id})
44
+ RETURN s
45
+ """
46
+ return query, {"semantic_group_id": semantic_group_id}
@@ -0,0 +1,208 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Query builders for the **Sessions** feature domain.
4
+
5
+ Provides SQL queries (via SQLAlchemy Core) for the session-level
6
+ endpoints: session listing and span retrieval by session / type.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Optional
12
+
13
+ from sqlalchemy import column, func, select, table
14
+
15
+ from scope.query_builders.types import Dialect
16
+
17
+ # ── per-backend table definitions ────────────────────────────────────────────
18
+
19
+ _ch_otel = table(
20
+ "otel_traces",
21
+ column("Timestamp"),
22
+ column("SpanId"),
23
+ column("SpanName"),
24
+ column("SpanAttributes"),
25
+ column("StatusCode"),
26
+ column("Duration"),
27
+ column("ParentSpanId"),
28
+ column("ScopeName"),
29
+ column("ServiceName"),
30
+ column("session_id"),
31
+ column("application_id"),
32
+ column("agent_id"),
33
+ column("Links.TraceId"),
34
+ column("Links.SpanId"),
35
+ column("Links.TraceState"),
36
+ column("Links.Attributes"),
37
+ )
38
+
39
+ _sqlite_otel = table(
40
+ "otel_traces",
41
+ column("timestamp"),
42
+ column("span_id"),
43
+ column("span_name"),
44
+ column("span_attributes"),
45
+ column("status_code"),
46
+ column("duration"),
47
+ column("parent_span_id"),
48
+ column("scope_name"),
49
+ column("service_name"),
50
+ column("session_id"),
51
+ column("application_id"),
52
+ column("agent_id"),
53
+ column("links_trace_id"),
54
+ column("links_span_id"),
55
+ column("links_trace_state"),
56
+ column("links_attributes"),
57
+ )
58
+
59
+
60
+ # ── helper ────────────────────────────────────────────────────────────────────
61
+
62
+
63
+ def _identity(expr):
64
+ return expr
65
+
66
+
67
+ def _cols(dialect: Dialect):
68
+ """Return (table, column-mapping) appropriate for *dialect*."""
69
+ if dialect is Dialect.SQLITE:
70
+ t = _sqlite_otel
71
+ return dict(
72
+ tbl=t,
73
+ ts=t.c.timestamp,
74
+ span_id=t.c.span_id,
75
+ span_name=t.c.span_name,
76
+ span_attributes=t.c.span_attributes,
77
+ status_code=t.c.status_code,
78
+ duration=t.c.duration,
79
+ parent_span_id=t.c.parent_span_id,
80
+ scope_name=t.c.scope_name,
81
+ service_name=t.c.service_name,
82
+ session_id=t.c.session_id,
83
+ application_id=t.c.application_id,
84
+ links_trace_id=t.c.links_trace_id,
85
+ links_span_id=t.c.links_span_id,
86
+ links_trace_state=t.c.links_trace_state,
87
+ links_attributes=t.c.links_attributes,
88
+ wrap=_identity,
89
+ )
90
+ t = _ch_otel
91
+ return dict(
92
+ tbl=t,
93
+ ts=t.c.Timestamp,
94
+ span_id=t.c.SpanId,
95
+ span_name=t.c.SpanName,
96
+ span_attributes=t.c.SpanAttributes,
97
+ status_code=t.c.StatusCode,
98
+ duration=t.c.Duration,
99
+ parent_span_id=t.c.ParentSpanId,
100
+ scope_name=t.c.ScopeName,
101
+ service_name=t.c.ServiceName,
102
+ session_id=t.c.session_id,
103
+ application_id=t.c.application_id,
104
+ links_trace_id=t.c["Links.TraceId"],
105
+ links_span_id=t.c["Links.SpanId"],
106
+ links_trace_state=t.c["Links.TraceState"],
107
+ links_attributes=t.c["Links.Attributes"],
108
+ wrap=func.toString,
109
+ )
110
+
111
+
112
+ # ── public query builders ────────────────────────────────────────────────────
113
+
114
+
115
+ def list_sessions_query(
116
+ dialect: Dialect = Dialect.CLICKHOUSE,
117
+ *,
118
+ start_time: Optional[str] = None,
119
+ end_time: Optional[str] = None,
120
+ limit: int = 50,
121
+ offset: int = 0,
122
+ ):
123
+ """Return ``(session_id, first_timestamp)`` for each session.
124
+
125
+ Sorted by most-recent first.
126
+ """
127
+ c = _cols(dialect)
128
+
129
+ stmt = (
130
+ select(
131
+ c["session_id"].label("session_id"),
132
+ c["wrap"](func.min(c["ts"])).label("timestamp"),
133
+ )
134
+ .select_from(c["tbl"])
135
+ .where(c["session_id"] != "")
136
+ .group_by(c["session_id"])
137
+ .order_by(func.min(c["ts"]).desc())
138
+ .limit(limit)
139
+ .offset(offset)
140
+ )
141
+
142
+ if start_time:
143
+ stmt = stmt.where(c["ts"] >= start_time)
144
+ if end_time:
145
+ stmt = stmt.where(c["ts"] <= end_time)
146
+
147
+ return stmt
148
+
149
+
150
+ def session_spans_query(
151
+ dialect: Dialect = Dialect.CLICKHOUSE,
152
+ *,
153
+ session_ids: list[str] | None = None,
154
+ span_types: list[str] | None = None,
155
+ limit: int = 500,
156
+ offset: int = 0,
157
+ order: str = "asc",
158
+ ):
159
+ """Return all span attributes + metadata for given session(s) and/or type(s).
160
+
161
+ *span_types* filters on the last segment of ``span_name`` (after the
162
+ last ``"."``) — e.g. ``"llm"``, ``"tool"``, ``"agent"``, ``"chat"``.
163
+ """
164
+ c = _cols(dialect)
165
+
166
+ wrap = c["wrap"]
167
+
168
+ stmt = (
169
+ select(
170
+ c["span_id"].label("span_id"),
171
+ c["session_id"].label("session_id"),
172
+ c["span_name"].label("span_name"),
173
+ wrap(c["ts"]).label("timestamp"),
174
+ c["duration"].label("duration"),
175
+ c["status_code"].label("status_code"),
176
+ c["parent_span_id"].label("parent_span_id"),
177
+ c["service_name"].label("service_name"),
178
+ c["span_attributes"].label("span_attributes"),
179
+ c["links_trace_id"].label("links_trace_id"),
180
+ c["links_span_id"].label("links_span_id"),
181
+ c["links_trace_state"].label("links_trace_state"),
182
+ c["links_attributes"].label("links_attributes"),
183
+ )
184
+ .select_from(c["tbl"])
185
+ .where(c["session_id"] != "")
186
+ )
187
+
188
+ if session_ids:
189
+ stmt = stmt.where(c["session_id"].in_(session_ids))
190
+
191
+ if span_types:
192
+ # Filter spans whose name ends with one of the requested types.
193
+ # e.g. span_name LIKE '%.llm' OR span_name LIKE '%.tool'
194
+ type_conditions = [c["span_name"].like(f"%.{t}") for t in span_types]
195
+ from sqlalchemy import or_
196
+
197
+ stmt = stmt.where(or_(*type_conditions))
198
+
199
+ col = c["ts"]
200
+ stmt = (
201
+ stmt.order_by(
202
+ col.desc() if order == "desc" else col.asc(),
203
+ c["span_id"].desc() if order == "desc" else c["span_id"].asc(),
204
+ )
205
+ .limit(limit)
206
+ .offset(offset)
207
+ )
208
+ return stmt