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,3278 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Query builders for the **UI** feature domain.
4
+
5
+ All queries use SQLAlchemy Core expressions. A ``Dialect`` parameter
6
+ selects the correct column names / functions for each backend.
7
+
8
+ Column-name differences between ClickHouse (PascalCase) and SQLite
9
+ (snake_case) are handled centrally by :func:`_refs`, which returns a
10
+ :class:`_Refs` NamedTuple with the right column expressions for each
11
+ backend.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+ from typing import Any, NamedTuple, Optional
18
+
19
+ from sqlalchemy import (
20
+ column,
21
+ func,
22
+ literal_column,
23
+ or_,
24
+ select,
25
+ table,
26
+ text,
27
+ )
28
+
29
+ from scope.query_builders.types import Dialect
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ # ── per-backend table definitions ────────────────────────────────────────────
34
+
35
+ _ch_otel = table(
36
+ "otel_traces",
37
+ column("Timestamp"),
38
+ column("SpanId"),
39
+ column("SpanName"),
40
+ column("SpanAttributes"),
41
+ column("StatusCode"),
42
+ column("Duration"),
43
+ column("ParentSpanId"),
44
+ column("ScopeName"),
45
+ column("session_id"),
46
+ column("application_id"),
47
+ column("agent_id"),
48
+ )
49
+
50
+ _sqlite_otel = table(
51
+ "otel_traces",
52
+ column("timestamp"),
53
+ column("span_id"),
54
+ column("span_name"),
55
+ column("span_attributes"),
56
+ column("status_code"),
57
+ column("duration"),
58
+ column("parent_span_id"),
59
+ column("events_attributes"),
60
+ column("scope_name"),
61
+ column("session_id"),
62
+ column("application_id"),
63
+ column("agent_id"),
64
+ )
65
+
66
+ # ── derived_metrics table definitions ────────────────────────────────────────
67
+
68
+ _ch_derived = table(
69
+ "derived_metrics",
70
+ column("SessionId"),
71
+ column("Metrics"),
72
+ )
73
+
74
+ _sqlite_derived = table(
75
+ "derived_metrics",
76
+ column("session_id"),
77
+ column("metrics"),
78
+ )
79
+
80
+ # ── otel_metrics table definitions (ClickHouse only) ─────────────────────────
81
+
82
+ _ch_metrics_sum = table(
83
+ "otel_metrics_sum",
84
+ column("MetricName"),
85
+ column("TimeUnix"),
86
+ column("Value"),
87
+ )
88
+
89
+ _ch_metrics_histogram = table(
90
+ "otel_metrics_histogram",
91
+ column("MetricName"),
92
+ column("TimeUnix"),
93
+ column("Count"),
94
+ column("Sum"),
95
+ )
96
+
97
+
98
+ # ── unified column references ────────────────────────────────────────────────
99
+
100
+
101
+ class _Refs(NamedTuple):
102
+ """Unified column references for both dialects."""
103
+
104
+ tbl: object
105
+ ts: object
106
+ span_name: object
107
+ span_id: object
108
+ span_attributes: object
109
+ status_code: object
110
+ events_attributes: object
111
+ scope_name: object
112
+ session_id: object
113
+ application_id: object
114
+ agent_id: object
115
+ duration: object
116
+ parent_span_id: object
117
+ wrap: object # func.toString for CH, identity for SQLite
118
+
119
+
120
+ def _identity(expr):
121
+ """No-op wrapper (SQLite doesn't need ``toString`` around aggregates)."""
122
+ return expr
123
+
124
+
125
+ def _refs(dialect: Dialect) -> _Refs:
126
+ """Return a :class:`_Refs` with the correct column expressions for *dialect*."""
127
+ if dialect is Dialect.SQLITE:
128
+ t = _sqlite_otel
129
+ return _Refs(
130
+ tbl=t,
131
+ ts=t.c.timestamp,
132
+ span_name=t.c.span_name,
133
+ span_id=t.c.span_id,
134
+ span_attributes=t.c.span_attributes,
135
+ status_code=t.c.status_code,
136
+ events_attributes=t.c.events_attributes,
137
+ scope_name=t.c.scope_name,
138
+ session_id=t.c.session_id,
139
+ application_id=t.c.application_id,
140
+ agent_id=t.c.agent_id,
141
+ duration=t.c.duration,
142
+ parent_span_id=t.c.parent_span_id,
143
+ wrap=_identity,
144
+ )
145
+ # CLICKHOUSE / SQLALCHEMY
146
+ t = _ch_otel
147
+ return _Refs(
148
+ tbl=t,
149
+ ts=t.c.Timestamp,
150
+ span_name=t.c.SpanName,
151
+ span_id=t.c.SpanId,
152
+ span_attributes=t.c.SpanAttributes,
153
+ status_code=t.c.StatusCode,
154
+ events_attributes=literal_column("Events.Attributes").label(
155
+ "events_attributes"
156
+ ),
157
+ scope_name=t.c.ScopeName,
158
+ session_id=t.c.session_id,
159
+ application_id=t.c.application_id,
160
+ agent_id=t.c.agent_id,
161
+ duration=t.c.Duration,
162
+ parent_span_id=t.c.ParentSpanId,
163
+ wrap=func.toString,
164
+ )
165
+
166
+
167
+ # ── public query builders ────────────────────────────────────────────────────
168
+
169
+
170
+ def sessions_query(
171
+ dialect: Dialect = Dialect.CLICKHOUSE,
172
+ *,
173
+ start_time: Optional[str] = None,
174
+ end_time: Optional[str] = None,
175
+ app_name: Optional[str] = None,
176
+ limit: int = 50,
177
+ offset: int = 0,
178
+ ):
179
+ """Build a query for listing session (trace) summaries.
180
+
181
+ Returns columns: ``session_id, application_id, start_time, end_time,
182
+ span_count``.
183
+ """
184
+ r = _refs(dialect)
185
+ r = _refs(dialect)
186
+
187
+ stmt = (
188
+ select(
189
+ r.session_id.label("session_id"),
190
+ r.application_id.label("application_id"),
191
+ r.wrap(func.min(r.ts)).label("start_time"),
192
+ r.wrap(func.max(r.ts)).label("end_time"),
193
+ func.count().label("span_count"),
194
+ )
195
+ .select_from(r.tbl)
196
+ .where(r.session_id != "")
197
+ )
198
+
199
+ if start_time:
200
+ stmt = stmt.where(r.ts >= start_time)
201
+ if end_time:
202
+ stmt = stmt.where(r.ts <= end_time)
203
+ if app_name:
204
+ stmt = stmt.where(r.application_id == app_name)
205
+
206
+ stmt = (
207
+ stmt.group_by(r.session_id, r.application_id)
208
+ .order_by(func.min(r.ts).desc())
209
+ .limit(limit)
210
+ .offset(offset)
211
+ )
212
+
213
+ return stmt
214
+
215
+
216
+ def session_agents_query(
217
+ dialect: Dialect = Dialect.CLICKHOUSE,
218
+ *,
219
+ session_id: str,
220
+ start_time: Optional[str] = None,
221
+ end_time: Optional[str] = None,
222
+ limit: int = 50,
223
+ offset: int = 0,
224
+ ):
225
+ """Build a query for listing agent IDs seen in a session.
226
+
227
+ Returns columns: ``agent_id`` (the span name), ``session_id``.
228
+ """
229
+ r = _refs(dialect)
230
+
231
+ stmt = (
232
+ select(r.span_name.label("agent_id"), r.sid.label("session_id"))
233
+ .select_from(r.tbl)
234
+ .where(r.sid != "")
235
+ .where(r.span_name.like("%.agent"))
236
+ .where(r.sid == session_id)
237
+ )
238
+
239
+ if start_time:
240
+ stmt = stmt.where(r.ts >= start_time)
241
+ if end_time:
242
+ stmt = stmt.where(r.ts <= end_time)
243
+
244
+ stmt = stmt.limit(limit).offset(offset)
245
+
246
+ return stmt
247
+
248
+
249
+ def session_ids_query(
250
+ dialect: Dialect = Dialect.CLICKHOUSE,
251
+ *,
252
+ start_time: Optional[str] = None,
253
+ end_time: Optional[str] = None,
254
+ limit: int = 50,
255
+ offset: int = 0,
256
+ ):
257
+ """Build a query for listing distinct session IDs.
258
+
259
+ Returns columns: ``id``, ``start_timestamp``.
260
+ """
261
+ r = _refs(dialect)
262
+
263
+ stmt = (
264
+ select(
265
+ r.session_id.label("id"),
266
+ r.wrap(func.min(r.ts)).label("start_timestamp"),
267
+ )
268
+ .select_from(r.tbl)
269
+ .where(r.session_id != "")
270
+ )
271
+
272
+ if start_time:
273
+ stmt = stmt.where(r.ts >= start_time)
274
+ if end_time:
275
+ stmt = stmt.where(r.ts <= end_time)
276
+
277
+ stmt = (
278
+ stmt.group_by(r.session_id)
279
+ .order_by(func.min(r.ts).desc())
280
+ .limit(limit)
281
+ .offset(offset)
282
+ )
283
+
284
+ return stmt
285
+
286
+
287
+ def applications_query(
288
+ dialect: Dialect = Dialect.CLICKHOUSE,
289
+ *,
290
+ start_time: Optional[str] = None,
291
+ end_time: Optional[str] = None,
292
+ limit: int = 50,
293
+ offset: int = 0,
294
+ ):
295
+ """Build a query for listing applications
296
+
297
+ Returns columns: ``application_id, start_time, end_time``.
298
+ """
299
+ r = _refs(dialect)
300
+
301
+ stmt = (
302
+ select(
303
+ r.application_id.label("application_id"),
304
+ r.wrap(func.min(r.ts)).label("start_time"),
305
+ r.wrap(func.max(r.ts)).label("end_time"),
306
+ )
307
+ .select_from(r.tbl)
308
+ .where(r.application_id != "")
309
+ )
310
+
311
+ if start_time:
312
+ stmt = stmt.where(r.ts >= start_time)
313
+ if end_time:
314
+ stmt = stmt.where(r.ts <= end_time)
315
+
316
+ stmt = (
317
+ stmt.group_by(r.application_id)
318
+ .order_by(func.min(r.ts).desc())
319
+ .limit(limit)
320
+ .offset(offset)
321
+ )
322
+
323
+ return stmt
324
+
325
+
326
+ def applications_with_sessions_query(
327
+ dialect: Dialect = Dialect.CLICKHOUSE,
328
+ *,
329
+ start_time: Optional[str] = None,
330
+ end_time: Optional[str] = None,
331
+ ):
332
+ """Build a query for listing applications grouped by (application_id, session_id).
333
+
334
+ Returns columns: ``application_id, session_id, max_timestamp``.
335
+ Ordered by max_timestamp descending.
336
+ """
337
+ r = _refs(dialect)
338
+
339
+ stmt = (
340
+ select(
341
+ r.application_id.label("application_id"),
342
+ r.session_id.label("session_id"),
343
+ r.wrap(func.max(r.ts)).label("max_timestamp"),
344
+ )
345
+ .select_from(r.tbl)
346
+ .where(r.application_id != "")
347
+ )
348
+
349
+ if start_time:
350
+ stmt = stmt.where(r.ts >= start_time)
351
+ if end_time:
352
+ stmt = stmt.where(r.ts <= end_time)
353
+
354
+ stmt = stmt.group_by(r.application_id, r.session_id).order_by(func.max(r.ts).desc())
355
+
356
+ return stmt
357
+
358
+
359
+ def applications_with_sessions_and_tokens_query(
360
+ dialect: Dialect = Dialect.CLICKHOUSE,
361
+ *,
362
+ start_time: Optional[str] = None,
363
+ end_time: Optional[str] = None,
364
+ ):
365
+ """Merged query: sessions, token costs, agents and LLMs in one round-trip.
366
+
367
+ ClickHouse only. Returns one row per ``(application_id, session_id)``
368
+ with columns:
369
+
370
+ * ``application_id``
371
+ * ``session_id``
372
+ * ``max_timestamp``
373
+ * ``total_tokens`` — sum of prompt + completion tokens from ``.chat`` spans
374
+ for that session.
375
+ * ``agents`` — array of distinct agent base-names (part before the first
376
+ dot) across **all** sessions of the application.
377
+ * ``llms`` — array of distinct LLM model names across **all** sessions of
378
+ the application.
379
+
380
+ ``agents`` and ``llms`` are application-level aggregates repeated on every
381
+ session row for the same application; the caller may read them from any
382
+ row.
383
+ """
384
+ r = _refs(dialect)
385
+
386
+ prompt_tokens = literal_column(
387
+ "toFloat64OrZero(SpanAttributes['gen_ai.usage.input_tokens'])"
388
+ )
389
+ completion_tokens = literal_column(
390
+ "toFloat64OrZero(SpanAttributes['gen_ai.usage.output_tokens'])"
391
+ )
392
+ agent_base = literal_column("splitByChar('.', agent_id)[1]")
393
+ llm_expr = literal_column("SpanAttributes['gen_ai.request.model']")
394
+
395
+ # CTE 1: per-session timestamps ───────────────────────────────────
396
+ sessions_q = (
397
+ select(
398
+ r.application_id.label("application_id"),
399
+ r.session_id.label("session_id"),
400
+ r.wrap(func.max(r.ts)).label("max_timestamp"),
401
+ )
402
+ .select_from(r.tbl)
403
+ .where(r.application_id != "")
404
+ .where(r.session_id != "")
405
+ )
406
+ if start_time:
407
+ sessions_q = sessions_q.where(r.ts >= start_time)
408
+ if end_time:
409
+ sessions_q = sessions_q.where(r.ts <= end_time)
410
+ sessions_cte = (sessions_q.group_by(r.application_id, r.session_id)).cte(
411
+ "sessions_ts"
412
+ )
413
+
414
+ # CTE 2: per-session token sums (only .chat spans, no time range filter,
415
+ # no application_id filter — mirrors token_sum_by_sessions_query exactly:
416
+ # sum ALL .chat spans for a session_id, regardless of application_id or
417
+ # timestamp, so that spans with empty/different application_id are counted) ─
418
+ tokens_q = (
419
+ select(
420
+ r.session_id.label("session_id"),
421
+ func.sum(prompt_tokens + completion_tokens).label("total_tokens"),
422
+ )
423
+ .select_from(r.tbl)
424
+ .where(r.session_id != "")
425
+ .where(r.span_name.like("%.chat"))
426
+ )
427
+ tokens_cte = (tokens_q.group_by(r.session_id)).cte("sessions_tokens")
428
+
429
+ # CTE 2: per-application distinct agent base-names ────────────────
430
+ agents_q = (
431
+ select(
432
+ r.application_id.label("application_id"),
433
+ func.groupUniqArray(agent_base).label("agents"),
434
+ )
435
+ .select_from(r.tbl)
436
+ .where(r.application_id != "")
437
+ .where(agent_base != "")
438
+ )
439
+ if start_time:
440
+ agents_q = agents_q.where(r.ts >= start_time)
441
+ if end_time:
442
+ agents_q = agents_q.where(r.ts <= end_time)
443
+ agents_cte = agents_q.group_by(r.application_id).cte("app_agents")
444
+
445
+ # CTE 3: per-application distinct LLM model names ─────────────────
446
+ llms_q = (
447
+ select(
448
+ r.application_id.label("application_id"),
449
+ func.groupUniqArray(llm_expr).label("llms"),
450
+ )
451
+ .select_from(r.tbl)
452
+ .where(r.application_id != "")
453
+ .where(llm_expr != "")
454
+ .where(r.span_name.like("%.chat"))
455
+ )
456
+ if start_time:
457
+ llms_q = llms_q.where(r.ts >= start_time)
458
+ if end_time:
459
+ llms_q = llms_q.where(r.ts <= end_time)
460
+ llms_cte = llms_q.group_by(r.application_id).cte("app_llms")
461
+
462
+ # Final: join session rows with tokens, agents, and LLMs ─────────
463
+ return (
464
+ select(
465
+ sessions_cte.c.application_id,
466
+ sessions_cte.c.session_id,
467
+ sessions_cte.c.max_timestamp,
468
+ tokens_cte.c.total_tokens,
469
+ agents_cte.c.agents,
470
+ llms_cte.c.llms,
471
+ )
472
+ .select_from(sessions_cte)
473
+ .outerjoin(
474
+ tokens_cte,
475
+ tokens_cte.c.session_id == sessions_cte.c.session_id,
476
+ )
477
+ .outerjoin(
478
+ agents_cte,
479
+ agents_cte.c.application_id == sessions_cte.c.application_id,
480
+ )
481
+ .outerjoin(
482
+ llms_cte,
483
+ llms_cte.c.application_id == sessions_cte.c.application_id,
484
+ )
485
+ .order_by(sessions_cte.c.max_timestamp.desc())
486
+ )
487
+
488
+
489
+ def neo4j_applications_with_sessions_query(
490
+ dialect: Dialect = Dialect.NEO4J,
491
+ *,
492
+ start_epoch: Optional[float] = None,
493
+ end_epoch: Optional[float] = None,
494
+ offset: int = 0,
495
+ limit: int = 50,
496
+ ):
497
+ """Build a Neo4j Cypher query listing applications with their session IDs.
498
+
499
+ Matches ``Session`` nodes connected to ``MAS`` nodes and groups by
500
+ ``name``. Applies optional epoch-based time filters.
501
+
502
+ Returns a ``(cypher_string, params_dict)`` tuple with columns:
503
+ ``application_id, session_ids, min_start``.
504
+ """
505
+ stmt = """
506
+ MATCH (s:Session)-[]-(ma:MAS)
507
+ WHERE ma.id IS NOT NULL
508
+ AND ma.id <> ''
509
+ AND ($start_epoch IS NULL OR toFloat(s.startTime) >= $start_epoch)
510
+ AND ($end_epoch IS NULL OR toFloat(s.startTime) <= $end_epoch)
511
+ WITH
512
+ ma.id AS application_id,
513
+ collect(DISTINCT s.sessionId) AS session_ids,
514
+ min(toFloat(s.startTime)) AS min_start
515
+ WITH
516
+ application_id,
517
+ [sid IN session_ids WHERE sid IS NOT NULL AND sid <> ''] AS session_ids,
518
+ min_start
519
+ WHERE size(session_ids) > 0
520
+ ORDER BY min_start DESC
521
+ SKIP $offset
522
+ LIMIT $limit
523
+ RETURN application_id, session_ids, min_start
524
+ """
525
+ return stmt, {
526
+ "start_epoch": start_epoch,
527
+ "end_epoch": end_epoch,
528
+ "offset": int(offset),
529
+ "limit": int(limit),
530
+ }
531
+
532
+
533
+ def neo4j_applications_with_metrics_optimized_query(
534
+ dialect: Dialect = Dialect.NEO4J,
535
+ *,
536
+ start_epoch: Optional[float] = None,
537
+ end_epoch: Optional[float] = None,
538
+ offset: int = 0,
539
+ limit: int = 50,
540
+ metric_names: Optional[list[str]] = None,
541
+ ):
542
+ """Build a single Neo4j query for applications + sessions + enrichments.
543
+
544
+ Returns one row per application with these columns:
545
+ ``application_id, session_ids, min_start, total_tokens, agents, llms,
546
+ metric_rows``.
547
+
548
+ ``metric_rows`` is a list of maps with keys ``sid``, ``metric_name`` and
549
+ ``metric_result`` used by the caller to compute the final performance score.
550
+ """
551
+ if dialect is not Dialect.NEO4J:
552
+ raise NotImplementedError(
553
+ "neo4j_applications_with_metrics_optimized_query supports Neo4j only"
554
+ )
555
+
556
+ stmt = """
557
+ MATCH (s:Session)-[]-(ma:MAS)
558
+ WHERE ma.id IS NOT NULL
559
+ AND ma.id <> ''
560
+ AND ($start_epoch IS NULL OR toFloat(s.startTime) >= $start_epoch)
561
+ AND ($end_epoch IS NULL OR toFloat(s.startTime) <= $end_epoch)
562
+ WITH
563
+ ma.id AS application_id,
564
+ collect(DISTINCT s.sessionId) AS raw_session_ids,
565
+ min(toFloat(s.startTime)) AS min_start
566
+ WITH
567
+ application_id,
568
+ [sid IN raw_session_ids WHERE sid IS NOT NULL AND sid <> ''] AS session_ids,
569
+ min_start
570
+ WHERE size(session_ids) > 0
571
+ ORDER BY min_start DESC
572
+ SKIP $offset
573
+ LIMIT $limit
574
+ CALL {
575
+ WITH session_ids
576
+ MATCH (lc:LLMCall)
577
+ WHERE lc.sessionId IN session_ids
578
+ OPTIONAL MATCH (lc)-[:executesLLM]->(llmNode:LLM)
579
+ RETURN coalesce(
580
+ sum(coalesce(toFloat(lc.promptTokenCount), 0.0)
581
+ + coalesce(toFloat(lc.completionTokenCount), 0.0)),
582
+ 0.0
583
+ ) AS total_tokens,
584
+ [
585
+ llm IN collect(DISTINCT llmNode.name)
586
+ WHERE llm IS NOT NULL AND toString(llm) <> ''
587
+ | toString(llm)
588
+ ] AS llms
589
+ }
590
+ CALL {
591
+ WITH session_ids
592
+ MATCH (ac:AgentCall)
593
+ WHERE ac.sessionId IN session_ids
594
+ OPTIONAL MATCH (ac)-[:executesAgent]->(agentNode:Agent)
595
+ RETURN [
596
+ agent IN collect(DISTINCT agentNode.name)
597
+ WHERE agent IS NOT NULL AND toString(agent) <> ''
598
+ | toString(agent)
599
+ ] AS agents
600
+ }
601
+ CALL {
602
+ WITH session_ids
603
+ MATCH (mr:MetricResult)-[:measures]->(sm:Session),
604
+ (mr)-[:ofMetricType]->(m:Metric)
605
+ WHERE sm.sessionId IN session_ids
606
+ AND m.name IN $metric_names
607
+ RETURN collect({
608
+ sid: sm.sessionId,
609
+ metric_name: m.name,
610
+ metric_result: mr.result
611
+ }) AS metric_rows
612
+ }
613
+ RETURN
614
+ application_id,
615
+ session_ids,
616
+ min_start,
617
+ total_tokens,
618
+ agents,
619
+ llms,
620
+ metric_rows
621
+ """
622
+ return stmt, {
623
+ "start_epoch": start_epoch,
624
+ "end_epoch": end_epoch,
625
+ "offset": int(offset),
626
+ "limit": int(limit),
627
+ "metric_names": metric_names or [],
628
+ }
629
+
630
+
631
+ def agent_tools_by_application_query(
632
+ *,
633
+ application_id: str,
634
+ ) -> tuple[str, dict[str, Any]]:
635
+ """Build the Cypher query for each agent's tools in an application (Neo4j only).
636
+
637
+ Reads what each agent actually invoked within *this application's own*
638
+ sessions (``Session -[:hasMASCall]-> MASCall -[:hasAgentCall]->
639
+ AgentCall -[:hasToolCall]-> ToolCall -[:executesTool]-> Tool``),
640
+ scoped via ``Session -[:executesSession]-> MAS``.
641
+
642
+ This is deliberately *not* the structural ``Agent -[:usesTool]->
643
+ Tool`` edge: ``Agent``/``Tool`` nodes are declared once per name (not
644
+ per application) and get merged across every MAS that happens to
645
+ have an agent/tool with the same id -- e.g. an agent named
646
+ "moderator" is one shared node across multiple unrelated
647
+ applications. Matching on that structural edge alone would return
648
+ the union of every application's tool usage for any agent name this
649
+ application happens to share with another one. Walking the
650
+ execution layer instead -- where ``AgentCall``/``ToolCall`` are
651
+ per-session instances, not shared -- ties each tool back to actual
652
+ executions within this application's own sessions.
653
+
654
+ Nor does the agent framework's self-reported ``gen_ai.ioa.graph``
655
+ span attribute work as a source: it's produced by the instrumented
656
+ application itself and isn't guaranteed to include tool nodes at all
657
+ (e.g. when tools are bound directly to the LLM rather than
658
+ represented as separate graph nodes).
659
+ """
660
+ query = """
661
+ MATCH (mas:MAS {id: $applicationId})<-[:executesSession]-(s:Session)
662
+ MATCH (s)-[:hasMASCall]->(:MASCall)-[:hasAgentCall]->(ac:AgentCall)
663
+ -[:executesAgent]->(a:Agent)
664
+ OPTIONAL MATCH (ac)-[:hasToolCall]->(:ToolCall)-[:executesTool]->(t:Tool)
665
+ WITH a, collect(DISTINCT CASE WHEN t IS NULL THEN null ELSE {
666
+ name: t.name,
667
+ description: t.description
668
+ } END) as rawTools
669
+ RETURN a.id as agentId,
670
+ a.name as agentName,
671
+ a.description as agentDescription,
672
+ [x IN rawTools WHERE x IS NOT NULL] as tools
673
+ ORDER BY a.name
674
+ """
675
+ return query, {"applicationId": application_id}
676
+
677
+
678
+ def structural_agents_by_application_query(
679
+ *,
680
+ application_id: str,
681
+ ) -> tuple[str, dict[str, Any]]:
682
+ """Build the Cypher query for the structural agents of an application (Neo4j only).
683
+
684
+ These are the ``Agent`` nodes of the application's ``MAS`` (the structural
685
+ layer, linked by ``belongsToMAS``): what the topology of an application is
686
+ made of when its instrumented framework did not declare a graph. Unlike the
687
+ ``usesTool`` edge, ``belongsToMAS`` is per MAS, so an agent that several
688
+ applications share by name is only returned for the ones it belongs to.
689
+ """
690
+ query = """
691
+ MATCH (mas:MAS {id: $applicationId})<-[:belongsToMAS]-(a:Agent)
692
+ RETURN a.id AS agentId,
693
+ a.name AS agentName,
694
+ a.description AS agentDescription
695
+ ORDER BY agentName
696
+ """
697
+ return query, {"applicationId": application_id}
698
+
699
+
700
+ def agent_handoffs_by_application_query(
701
+ *,
702
+ application_id: str,
703
+ ) -> tuple[str, dict[str, Any]]:
704
+ """Build the Cypher query for the agent hand-offs of an application (Neo4j only).
705
+
706
+ The structural layer has no agent-to-agent edge, so a hand-off is read from
707
+ the execution layer: within each session of the application, an
708
+ ``AgentCall`` that directly follows another one (by start time) is a
709
+ hand-off from the first call's agent to the second's. Calls of the same
710
+ agent in a row are not hand-offs. Returns distinct ``(source, target)``
711
+ agent id pairs.
712
+ """
713
+ query = """
714
+ MATCH (:MAS {id: $applicationId})<-[:executesSession]-(s:Session)
715
+ -[:hasMASCall]->(:MASCall)-[:hasAgentCall]->(ac:AgentCall)
716
+ -[:executesAgent]->(a:Agent)
717
+ WITH s, ac, a ORDER BY s.id, ac.startTime
718
+ WITH s, collect(a.id) AS sequence
719
+ UNWIND range(0, size(sequence) - 2) AS i
720
+ WITH sequence[i] AS source, sequence[i + 1] AS target
721
+ WHERE source <> target
722
+ RETURN DISTINCT source, target
723
+ ORDER BY source, target
724
+ """
725
+ return query, {"applicationId": application_id}
726
+
727
+
728
+ def agents_by_application_and_sessions_query(
729
+ dialect: Dialect = Dialect.CLICKHOUSE,
730
+ *,
731
+ application_id: str,
732
+ session_ids: list[str],
733
+ ):
734
+ """Build a query for distinct agent base-names for an application.
735
+
736
+ The agent base name is the part of ``agent_id`` before the first dot.
737
+
738
+ For **Neo4j** returns a ``(cypher_string, params_dict)`` tuple; the
739
+ result row has column ``agents`` (a list).
740
+
741
+ Returns column: ``agent_name``.
742
+ """
743
+ if dialect is Dialect.NEO4J:
744
+ stmt = """
745
+ MATCH (ac:AgentCall)-[:executesAgent]->(agentNode:Agent)
746
+ WHERE ac.sessionId IN $session_ids
747
+ WITH DISTINCT agentNode.name AS agent
748
+ WHERE agent IS NOT NULL AND agent <> ''
749
+ RETURN collect(agent) AS agents
750
+ """
751
+ return stmt, {"session_ids": session_ids}
752
+
753
+ r = _refs(dialect)
754
+
755
+ if dialect is Dialect.SQLITE:
756
+ agent_base = func.substr(
757
+ r.agent_id,
758
+ 1,
759
+ func.instr(r.agent_id, ".") - 1,
760
+ )
761
+ return (
762
+ select(func.distinct(agent_base).label("agent_name"))
763
+ .select_from(r.tbl)
764
+ .where(r.session_id.in_(session_ids))
765
+ .where(func.lower(r.application_id) == func.lower(application_id))
766
+ .where(r.agent_id != "")
767
+ .where(r.agent_id.like("%.%"))
768
+ )
769
+
770
+ agent_base = literal_column("splitByChar('.', agent_id)[1]")
771
+ return (
772
+ select(func.distinct(agent_base).label("agent_name"))
773
+ .select_from(r.tbl)
774
+ .where(r.session_id.in_(session_ids))
775
+ .where(func.lower(r.application_id) == func.lower(application_id))
776
+ .where(agent_base != "")
777
+ )
778
+
779
+
780
+ def llms_by_application_and_sessions_query(
781
+ dialect: Dialect = Dialect.CLICKHOUSE,
782
+ *,
783
+ application_id: str,
784
+ session_ids: list[str],
785
+ ):
786
+ """Build a query for distinct LLM model names for an application.
787
+
788
+ Looks at the ``gen_ai.request.model`` key inside ``span_attributes``
789
+ for ``.chat`` spans.
790
+
791
+ For **Neo4j** returns a ``(cypher_string, params_dict)`` tuple; the
792
+ result row has column ``llms`` (a list).
793
+
794
+ For **SQLite** the column stores a Python-dict literal, so
795
+ ``json_extract`` cannot be used. Instead the query returns raw
796
+ ``span_attributes`` rows and the caller must extract model names
797
+ in Python (column: ``span_attributes``).
798
+
799
+ For **ClickHouse** the query returns ``llm_name`` directly.
800
+ """
801
+ if dialect is Dialect.NEO4J:
802
+ stmt = """
803
+ MATCH (lc:LLMCall)-[:executesLLM]->(llmNode:LLM)
804
+ WHERE lc.sessionId IN $session_ids
805
+ WITH DISTINCT llmNode.name AS llm
806
+ WHERE llm IS NOT NULL AND llm <> ''
807
+ RETURN collect(llm) AS llms
808
+ """
809
+ return stmt, {"session_ids": session_ids}
810
+
811
+ r = _refs(dialect)
812
+
813
+ if dialect is Dialect.SQLITE:
814
+ # span_attributes is a Python-dict string; return raw values for
815
+ # the caller to parse with ``parse_span_attributes``.
816
+ return (
817
+ select(r.span_attributes.label("span_attributes"))
818
+ .select_from(r.tbl)
819
+ .where(r.session_id.in_(session_ids))
820
+ .where(func.lower(r.application_id) == func.lower(application_id))
821
+ .where(r.span_name.like("%.chat"))
822
+ )
823
+
824
+ # ClickHouse: SpanAttributes is a Map — use bracket notation.
825
+ llm_expr = literal_column("SpanAttributes['gen_ai.request.model']")
826
+ return (
827
+ select(func.distinct(llm_expr).label("llm_name"))
828
+ .select_from(r.tbl)
829
+ .where(r.session_id.in_(session_ids))
830
+ .where(func.lower(r.application_id) == func.lower(application_id))
831
+ .where(llm_expr != "")
832
+ .where(r.span_name.like("%.chat"))
833
+ )
834
+
835
+
836
+ def span_details_query(
837
+ dialect: Dialect = Dialect.CLICKHOUSE,
838
+ *,
839
+ span_id: str,
840
+ ):
841
+ """Build a query for fetching a single span's details.
842
+
843
+ Returns columns: ``span_id, span_name, span_attributes, status_code,
844
+ events_attributes, scope_name``.
845
+ """
846
+ r = _refs(dialect)
847
+
848
+ return (
849
+ select(
850
+ r.span_id,
851
+ r.span_name,
852
+ r.span_attributes,
853
+ r.status_code,
854
+ r.events_attributes,
855
+ r.scope_name,
856
+ )
857
+ .select_from(r.tbl)
858
+ .where(r.span_id == span_id)
859
+ .limit(1)
860
+ )
861
+
862
+
863
+ def agent_description_query(
864
+ dialect: Dialect = Dialect.CLICKHOUSE,
865
+ *,
866
+ session_id: str,
867
+ agent_id: str,
868
+ ):
869
+ """Build a query to find the agent description from ``agent_start_event`` rows.
870
+
871
+ Searches ``events_attributes`` for a matching ``agent_id`` that starts
872
+ with *agent_id* and a non-empty ``description``.
873
+
874
+ Returns columns: ``events_attributes, span_name``.
875
+ """
876
+ r = _refs(dialect)
877
+
878
+ return (
879
+ select(r.events_attributes, r.span_name)
880
+ .select_from(r.tbl)
881
+ .where(r.session_id == session_id)
882
+ .where(r.span_name == "agent_start_event")
883
+ )
884
+
885
+
886
+ def agent_spans_query(
887
+ dialect: Dialect = Dialect.CLICKHOUSE,
888
+ *,
889
+ session_id: str,
890
+ agent_id: str,
891
+ ):
892
+ """Build a query for agent spans in a session (by ``agent_id`` column).
893
+
894
+ Returns columns: ``span_name, span_attributes``.
895
+ Excludes spans whose name contains ``__init_run``.
896
+ """
897
+ r = _refs(dialect)
898
+
899
+ return (
900
+ select(r.span_name, r.span_attributes)
901
+ .select_from(r.tbl)
902
+ .where(r.session_id == session_id)
903
+ .where(r.agent_id == agent_id)
904
+ .where(r.span_name.notlike("%__init_run%"))
905
+ )
906
+
907
+
908
+ def agent_token_aggregates_query(
909
+ dialect: Dialect = Dialect.CLICKHOUSE,
910
+ *,
911
+ session_id: str,
912
+ agent_id: str,
913
+ ):
914
+ """Build a query that returns chat span attributes for an agent.
915
+
916
+ Returns columns: ``span_attributes`` for each chat span, so the caller
917
+ can sum tokens and collect LLM names.
918
+ """
919
+ r = _refs(dialect)
920
+
921
+ return (
922
+ select(r.span_attributes)
923
+ .select_from(r.tbl)
924
+ .where(r.session_id == session_id)
925
+ .where(r.agent_id == agent_id)
926
+ .where(r.span_name.like("%.chat"))
927
+ )
928
+
929
+
930
+ def session_impact_assessment_query(
931
+ dialect: Dialect = Dialect.NEO4J,
932
+ *,
933
+ session_id: str,
934
+ ):
935
+ return f"""
936
+ MATCH (s:Session {{sessionId: "{session_id}"}})-[r]-(n:ImpactAssessment)
937
+ RETURN n.metricName AS metricName, n.contributions AS contributions
938
+ """
939
+
940
+
941
+ # ── Monitor Application Level query builders ─────────────────────────────────
942
+
943
+
944
+ def timestamps_for_sessions_query(
945
+ dialect: Dialect = Dialect.CLICKHOUSE,
946
+ *,
947
+ session_ids: list[str],
948
+ ):
949
+ """MIN / MAX timestamps for a set of session IDs (root spans only)."""
950
+ r = _refs(dialect)
951
+
952
+ return (
953
+ select(
954
+ r.wrap(func.min(r.ts)).label("min_ts"),
955
+ r.wrap(func.max(r.ts)).label("max_ts"),
956
+ )
957
+ .select_from(r.tbl)
958
+ .where(r.session_id.in_(session_ids))
959
+ .where(r.parent_span_id == "")
960
+ )
961
+
962
+
963
+ def session_ids_with_avgs_graph_query(
964
+ dialect: Dialect = Dialect.CLICKHOUSE,
965
+ *,
966
+ start_time: Optional[str] = None,
967
+ end_time: Optional[str] = None,
968
+ application_id: str,
969
+ given_session_ids: list[str],
970
+ ):
971
+ """Distinct session IDs from graph spans, with optional app + time filters."""
972
+ r = _refs(dialect)
973
+
974
+ stmt = (
975
+ select(
976
+ r.session_id.label("session_id"),
977
+ r.wrap(func.min(r.ts)).label("start_timestamp"),
978
+ r.wrap(func.max(r.ts)).label("end_timestamp"),
979
+ )
980
+ .select_from(r.tbl)
981
+ # Adding the dot, as we have content like: query_graph_database.tool
982
+ .where(r.span_name.like("%.graph%"))
983
+ .where(r.session_id != "")
984
+ )
985
+
986
+ if start_time:
987
+ stmt = stmt.where(r.ts >= start_time)
988
+ if end_time:
989
+ stmt = stmt.where(r.ts <= end_time)
990
+ if application_id:
991
+ stmt = stmt.where(func.lower(r.application_id) == func.lower(application_id))
992
+ if given_session_ids:
993
+ stmt = stmt.where(r.session_id.in_(given_session_ids))
994
+
995
+ return stmt.group_by(r.session_id).order_by(func.min(r.ts).desc())
996
+
997
+
998
+ def topology_query(
999
+ dialect: Dialect = Dialect.CLICKHOUSE,
1000
+ *,
1001
+ application_id: str,
1002
+ ):
1003
+ """Return the graph JSON for a single graph span of *application_id*."""
1004
+ r = _refs(dialect)
1005
+
1006
+ if dialect is Dialect.SQLITE:
1007
+ graph_col = r.span_attributes.label("graph_json")
1008
+ else:
1009
+ graph_col = literal_column("SpanAttributes['gen_ai.ioa.graph']").label(
1010
+ "graph_json"
1011
+ )
1012
+
1013
+ stmt = (
1014
+ select(graph_col)
1015
+ .select_from(r.tbl)
1016
+ .where(r.span_name.like("%.graph%"))
1017
+ .where(r.session_id != "")
1018
+ .where(func.lower(r.application_id) == func.lower(application_id))
1019
+ .order_by(r.ts.desc())
1020
+ .limit(1)
1021
+ )
1022
+
1023
+ return stmt
1024
+
1025
+
1026
+ def topology_query_by_session(
1027
+ dialect: Dialect = Dialect.CLICKHOUSE,
1028
+ *,
1029
+ session_id: str,
1030
+ ):
1031
+ """Return the graph JSON for a single graph span of *session_id*."""
1032
+ r = _refs(dialect)
1033
+
1034
+ if dialect is Dialect.SQLITE:
1035
+ graph_col = r.span_attributes.label("graph_json")
1036
+ else:
1037
+ graph_col = literal_column("SpanAttributes['gen_ai.ioa.graph']").label(
1038
+ "graph_json"
1039
+ )
1040
+
1041
+ stmt = (
1042
+ select(graph_col, r.session_id.label("session_id"))
1043
+ .select_from(r.tbl)
1044
+ .where(r.span_name.like("%.graph%"))
1045
+ .where(r.session_id == session_id)
1046
+ .order_by(r.ts.desc())
1047
+ .limit(1)
1048
+ )
1049
+
1050
+ return stmt
1051
+
1052
+
1053
+ def agent_descriptions_by_application_query(
1054
+ dialect: Dialect = Dialect.CLICKHOUSE,
1055
+ *,
1056
+ application_id: str,
1057
+ session_id: Optional[str] = None,
1058
+ ):
1059
+ """Return ``agent_start_event`` rows for an application.
1060
+
1061
+ Returns columns: ``events_attributes, span_name``.
1062
+ """
1063
+ r = _refs(dialect)
1064
+
1065
+ stmt = (
1066
+ select(r.events_attributes, r.span_name)
1067
+ .select_from(r.tbl)
1068
+ .where(r.span_name == "agent_start_event")
1069
+ )
1070
+
1071
+ if session_id:
1072
+ stmt = stmt.where(r.session_id == session_id)
1073
+ else:
1074
+ stmt = stmt.where(func.lower(r.application_id) == func.lower(application_id))
1075
+
1076
+ return stmt
1077
+
1078
+
1079
+ def semantic_groups_table_query(
1080
+ dialect: Dialect = Dialect.CLICKHOUSE,
1081
+ *,
1082
+ application_id: str,
1083
+ ):
1084
+ """Return the semantic-groups table query.
1085
+
1086
+ Semantic groups are currently sourced from Neo4j semantic nodes.
1087
+ """
1088
+ query = """
1089
+ MATCH (:MAS {id: $application_id})-[:containsSemanticGroup]->(sg:SemanticGroup {childrenNodes: []})
1090
+ // First, gather all consistency reports from the semantic groups
1091
+ OPTIONAL MATCH (sg)-[r]-(cr:ConsistencyReport)
1092
+ WITH sg, cr.dataType AS rawType, AVG(cr.mean) AS Value
1093
+ WITH sg,
1094
+ (CASE rawType
1095
+ WHEN 'metric' THEN 'MetricConsistency'
1096
+ WHEN 'graph' THEN 'GraphConsistency'
1097
+ WHEN 'text' THEN 'TextConsistency'
1098
+ ELSE rawType END) AS DataType, Value
1099
+ // Save consistency per type per semantic group as a JSON (will be reused later)
1100
+ WITH sg,
1101
+ collect({col1: DataType, col2: Value}) AS consistency
1102
+ // Collect sessions attached to the semantic groups
1103
+ OPTIONAL MATCH (sg)-[:containsSession]->(s:Session)
1104
+ // Collect Metrics associated to the sessions
1105
+ OPTIONAL MATCH (r:MetricResult)-[:measures]->(s), (r)-[:ofMetricType]->(m:Metric)
1106
+ WHERE m.name IN ["LLMErrorRate",
1107
+ "ToolErrorRate",
1108
+ "IntentRecognitionAccuracy",
1109
+ "Groundedness",
1110
+ "ToolUtilizationAccuracy",
1111
+ "AnswerRelevancy",
1112
+ "ResponseCompleteness",
1113
+ "WorkflowEfficiency",
1114
+ "CyclesCount"
1115
+ ]
1116
+ // Metrics manipulation, to compute the 3 overall scores
1117
+ WITH sg,
1118
+ avg(CASE WHEN m.name IN ["IntentRecognitionAccuracy", "Groundedness", "ToolUtilizationAccuracy", "AnswerRelevancy", "ResponseCompleteness"] THEN r.result END) AS overallQuality,
1119
+ 1 - avg(CASE WHEN m.name IN ["LLMErrorRate", "ToolErrorRate"] THEN r.result END) AS completionRate,
1120
+ (1 / (1 + avg(CASE WHEN m.name = "CyclesCount" THEN r.result END))) AS cycles,
1121
+ 1 - avg(CASE WHEN m.name = "LLMErrorRate" THEN r.result END) AS successLLM,
1122
+ 1 - avg(CASE WHEN m.name = "ToolErrorRate" THEN r.result END) AS successTool,
1123
+ avg(CASE WHEN m.name = "WorkflowEfficiency" THEN r.result END) AS avgWflwEff, consistency
1124
+ // Opening the consistency json
1125
+ UNWIND consistency as c
1126
+ WITH sg, overallQuality,
1127
+ [x IN [cycles, avgWflwEff, successLLM, successTool] WHERE x IS NOT NULL] AS perfValues,
1128
+ collect(c.col2) as consistencyValues, completionRate
1129
+ WITH sg, overallQuality,
1130
+ CASE WHEN size(perfValues) = 0 THEN null
1131
+ ELSE reduce(s = 0.0, x IN perfValues | s + x) / size(perfValues)
1132
+ END AS overallPerformance,
1133
+ consistencyValues, completionRate
1134
+ WITH sg, overallQuality, overallPerformance, reduce(s = 0.0, x IN consistencyValues | s + x) as consistencySum, reduce(s = 0, x IN consistencyValues | s + 1) as consistencyEntries, completionRate
1135
+ WITH sg, overallQuality, overallPerformance, (consistencySum + completionRate) / (consistencyEntries + 1) AS overallReliability
1136
+ RETURN sg, overallQuality, overallPerformance, overallReliability
1137
+ """
1138
+ return query, {"application_id": application_id}
1139
+
1140
+
1141
+ def semantic_groups_query(
1142
+ dialect: Dialect = Dialect.CLICKHOUSE,
1143
+ *,
1144
+ application_id: str,
1145
+ ):
1146
+ """Return all semantic-group nodes for an application.
1147
+
1148
+ The current Neo4j model stores semantic groups as ``SemanticGroup`` nodes.
1149
+ """
1150
+ query = """
1151
+ MATCH (:MAS {id: $application_id})-[:containsSemanticGroup]->(sg:SemanticGroup)
1152
+ // First, gather all consistency reports from the semantic groups
1153
+ OPTIONAL MATCH (sg)-[r]-(cr:ConsistencyReport)
1154
+ WITH sg, cr.dataType AS rawType, AVG(cr.mean) AS Value
1155
+ WITH sg,
1156
+ (CASE rawType
1157
+ WHEN 'metric' THEN 'MetricConsistency'
1158
+ WHEN 'graph' THEN 'GraphConsistency'
1159
+ WHEN 'text' THEN 'TextConsistency'
1160
+ ELSE rawType END) AS DataType, Value
1161
+ // Save consistency per type per semantic group as a JSON (will be reused later)
1162
+ WITH sg,
1163
+ collect({col1: DataType, col2: Value}) AS consistency
1164
+ // Collect sessions attached to the semantic groups
1165
+ OPTIONAL MATCH (sg)-[:containsSession*1..]->(s:Session)
1166
+ // Collect Metrics associated to the sessions
1167
+ OPTIONAL MATCH (r:MetricResult)-[:measures]->(s), (r)-[:ofMetricType]->(m:Metric)
1168
+ WHERE m.name IN ["LLMErrorRate",
1169
+ "ToolErrorRate",
1170
+ "IntentRecognitionAccuracy",
1171
+ "Groundedness",
1172
+ "ToolUtilizationAccuracy",
1173
+ "AnswerRelevancy",
1174
+ "ResponseCompleteness",
1175
+ "WorkflowEfficiency",
1176
+ "CyclesCount"
1177
+ ]
1178
+ // Metrics manipulation, to compute the 3 overall scores
1179
+ WITH sg,
1180
+ avg(CASE WHEN m.name IN ["IntentRecognitionAccuracy", "Groundedness", "ToolUtilizationAccuracy", "AnswerRelevancy", "ResponseCompleteness"] THEN r.result END) AS overallQuality,
1181
+ 1 - avg(CASE WHEN m.name IN ["LLMErrorRate", "ToolErrorRate"] THEN r.result END) AS completionRate,
1182
+ (1 / (1 + avg(CASE WHEN m.name = "CyclesCount" THEN r.result END))) AS cycles,
1183
+ 1 - avg(CASE WHEN m.name = "LLMErrorRate" THEN r.result END) AS successLLM,
1184
+ 1 - avg(CASE WHEN m.name = "ToolErrorRate" THEN r.result END) AS successTool,
1185
+ avg(CASE WHEN m.name = "WorkflowEfficiency" THEN r.result END) AS avgWflwEff, consistency
1186
+ // Opening the consistency json
1187
+ UNWIND consistency as c
1188
+ WITH sg, overallQuality,
1189
+ [x IN [cycles, avgWflwEff, successLLM, successTool] WHERE x IS NOT NULL] AS perfValues,
1190
+ collect(c.col2) as consistencyValues, completionRate
1191
+ WITH sg, overallQuality,
1192
+ CASE WHEN size(perfValues) = 0 THEN null
1193
+ ELSE reduce(s = 0.0, x IN perfValues | s + x) / size(perfValues)
1194
+ END AS overallPerformance,
1195
+ consistencyValues, completionRate
1196
+ WITH sg, overallQuality, overallPerformance, reduce(s = 0.0, x IN consistencyValues | s + x) as consistencySum, reduce(s = 0, x IN consistencyValues | s + 1) as consistencyEntries, completionRate
1197
+ WITH sg, overallQuality, overallPerformance, (consistencySum + completionRate) / (consistencyEntries + 1) AS overallReliability
1198
+ RETURN sg, overallQuality, overallPerformance, overallReliability
1199
+ """
1200
+ return query, {"application_id": application_id}
1201
+
1202
+
1203
+ def semantic_group_impact_assessment_query(
1204
+ dialect: Dialect = Dialect.CLICKHOUSE,
1205
+ *,
1206
+ application_id: str,
1207
+ semanticgroup_id: str,
1208
+ ):
1209
+ # TODO: need to find a better way to handle this
1210
+ # Currently this is parsing manually a string into a json object and extracting the different fields and values.
1211
+ # It works, but it's ugly
1212
+ query = """
1213
+ MATCH (sg:SemanticGroup {id: $semanticgroup_id})-[:containsSession*1..]->(s:Session)-[:hasImpactAssessment]->(ia:ImpactAssessment)
1214
+ WITH ia.metricName AS metricName, ia.contributions AS contributionsStr
1215
+ // Remove braces and quotes, then split by comma to get agent-value pairs
1216
+ WITH metricName, split(replace(replace(contributionsStr, '{', ''), '}', ''), ',') AS agentValuePairs
1217
+ UNWIND agentValuePairs AS pair
1218
+ //Split each pair by colon to separate agent and value
1219
+ WITH metricName, split(pair, ':') AS parts
1220
+ WITH metricName, trim(parts[0]) AS agentRaw, trim(parts[1]) AS valueRaw
1221
+ //Remove quotes from agent name
1222
+ WITH metricName, replace(agentRaw, '"', '') AS agent, toFloat(valueRaw) AS value
1223
+ WITH metricName, agent, avg(value) as avgValue
1224
+ WITH metricName, collect({agent: agent, value: avgValue}) AS contributions
1225
+ RETURN metricName, contributions
1226
+ """
1227
+ return query, {"semanticgroup_id": semanticgroup_id}
1228
+
1229
+
1230
+ def session_ids_graph_query(
1231
+ dialect: Dialect = Dialect.CLICKHOUSE,
1232
+ *,
1233
+ start_time: Optional[str] = None,
1234
+ end_time: Optional[str] = None,
1235
+ application_id: Optional[str] = None,
1236
+ given_session_ids: Optional[list[str]] = None,
1237
+ ):
1238
+ """Distinct session IDs from graph spans, with optional app + time filters."""
1239
+ r = _refs(dialect)
1240
+
1241
+ stmt = (
1242
+ select(
1243
+ r.session_id.label("session_id"),
1244
+ r.wrap(func.min(r.ts)).label("start_timestamp"),
1245
+ r.wrap(func.max(r.ts)).label("end_timestamp"),
1246
+ )
1247
+ .select_from(r.tbl)
1248
+ # Adding the dot, as we have content like: query_graph_database.tool
1249
+ .where(r.span_name.like("%.graph%"))
1250
+ .where(r.session_id != "")
1251
+ )
1252
+
1253
+ if start_time:
1254
+ stmt = stmt.where(r.ts >= start_time)
1255
+ if end_time:
1256
+ stmt = stmt.where(r.ts <= end_time)
1257
+ if application_id:
1258
+ stmt = stmt.where(func.lower(r.application_id) == func.lower(application_id))
1259
+ if given_session_ids:
1260
+ stmt = stmt.where(r.session_id.in_(given_session_ids))
1261
+
1262
+ return stmt.group_by(r.session_id).order_by(func.min(r.ts).desc())
1263
+
1264
+
1265
+ def traces_count_query(
1266
+ dialect: Dialect = Dialect.CLICKHOUSE,
1267
+ *,
1268
+ start_time: Optional[str] = None,
1269
+ end_time: Optional[str] = None,
1270
+ application_id: Optional[str] = None,
1271
+ ):
1272
+ """Count total rows for an application in a time range."""
1273
+ r = _refs(dialect)
1274
+
1275
+ stmt = select(func.count().label("cnt")).select_from(r.tbl)
1276
+
1277
+ if start_time:
1278
+ stmt = stmt.where(r.ts >= start_time)
1279
+ if end_time:
1280
+ stmt = stmt.where(r.ts <= end_time)
1281
+ if application_id:
1282
+ stmt = stmt.where(func.lower(r.application_id) == func.lower(application_id))
1283
+
1284
+ return stmt
1285
+
1286
+
1287
+ def conversation_count_query(
1288
+ dialect: Dialect = Dialect.CLICKHOUSE,
1289
+ *,
1290
+ start_time: Optional[str] = None,
1291
+ end_time: Optional[str] = None,
1292
+ application_id: Optional[str] = None,
1293
+ ):
1294
+ """Count distinct (agent_id, session_id) pairs for .chat spans."""
1295
+ r = _refs(dialect)
1296
+
1297
+ # COUNT(DISTINCT agent_id || '|' || session_id) works for both dialects.
1298
+ distinct_expr = func.count(
1299
+ func.distinct(r.agent_id + literal_column("'|'") + r.session_id)
1300
+ ).label("cnt")
1301
+ distinct_expr = func.count(
1302
+ func.distinct(func.concat(r.agent_id, literal_column("'|'"), r.session_id))
1303
+ ).label("cnt")
1304
+
1305
+ stmt = (
1306
+ select(distinct_expr)
1307
+ .select_from(r.tbl)
1308
+ .where(r.session_id != "")
1309
+ .where(r.span_name.like("%.chat"))
1310
+ )
1311
+
1312
+ if start_time:
1313
+ stmt = stmt.where(r.ts >= start_time)
1314
+ if end_time:
1315
+ stmt = stmt.where(r.ts <= end_time)
1316
+ if application_id:
1317
+ stmt = stmt.where(func.lower(r.application_id) == func.lower(application_id))
1318
+
1319
+ return stmt
1320
+
1321
+
1322
+ def distinct_agents_for_sessions_query(
1323
+ dialect: Dialect = Dialect.CLICKHOUSE,
1324
+ *,
1325
+ session_ids: list[str],
1326
+ ):
1327
+ """Return distinct base agent names (part before the first dot) for sessions."""
1328
+ r = _refs(dialect)
1329
+
1330
+ # String-splitting differs between SQLite and ClickHouse.
1331
+ if dialect is Dialect.SQLITE:
1332
+ agent_base = func.substr(
1333
+ r.agent_id,
1334
+ 1,
1335
+ func.instr(r.agent_id, ".") - 1,
1336
+ ).label("agent_id")
1337
+ return (
1338
+ select(func.distinct(agent_base).label("agent_id"))
1339
+ .select_from(r.tbl)
1340
+ .where(r.session_id.in_(session_ids))
1341
+ .where(r.agent_id != "")
1342
+ .where(r.agent_id.like("%.%"))
1343
+ )
1344
+
1345
+ agent_base = literal_column("splitByChar('.', agent_id)[1]")
1346
+ return (
1347
+ select(func.distinct(agent_base).label("agent_id"))
1348
+ .select_from(r.tbl)
1349
+ .where(r.session_id.in_(session_ids))
1350
+ .where(agent_base != "")
1351
+ )
1352
+
1353
+
1354
+ def agent_span_count_query(
1355
+ dialect: Dialect = Dialect.CLICKHOUSE,
1356
+ *,
1357
+ session_ids: list[str],
1358
+ agent_id: str,
1359
+ ):
1360
+ """Count spans for a specific agent (base name) within given sessions."""
1361
+ r = _refs(dialect)
1362
+
1363
+ return (
1364
+ select(func.count().label("cnt"))
1365
+ .select_from(r.tbl)
1366
+ .where(r.session_id.in_(session_ids))
1367
+ .where(r.agent_id == agent_id)
1368
+ )
1369
+
1370
+
1371
+ def top_agent_span_count_for_sessions_query(
1372
+ dialect: Dialect = Dialect.CLICKHOUSE,
1373
+ *,
1374
+ session_ids: list[str],
1375
+ ):
1376
+ """Return top-most (agent_id, cnt) computed in a single query.
1377
+
1378
+ Agent identity is normalized to the base name (part before the first dot),
1379
+ then ranked by count descending and agent_id ascending for deterministic ties.
1380
+ """
1381
+ r = _refs(dialect)
1382
+
1383
+ if dialect is Dialect.SQLITE:
1384
+ agent_base = func.substr(
1385
+ r.agent_id,
1386
+ 1,
1387
+ func.instr(r.agent_id, ".") - 1,
1388
+ )
1389
+ cnt_expr = func.count().label("cnt")
1390
+ return (
1391
+ select(
1392
+ agent_base.label("agent_base"),
1393
+ cnt_expr,
1394
+ )
1395
+ .select_from(r.tbl)
1396
+ .where(r.session_id.in_(session_ids))
1397
+ .where(r.agent_id != "")
1398
+ .where(r.agent_id.like("%.%"))
1399
+ .group_by(agent_base)
1400
+ .order_by(cnt_expr.desc(), literal_column("agent_base").asc())
1401
+ .limit(1)
1402
+ )
1403
+
1404
+ agent_base = literal_column("splitByChar('.', agent_id)[1]")
1405
+ cnt_expr = func.count().label("cnt")
1406
+ return (
1407
+ select(
1408
+ agent_base.label("agent_base"),
1409
+ cnt_expr,
1410
+ )
1411
+ .select_from(r.tbl)
1412
+ .where(r.session_id.in_(session_ids))
1413
+ .where(agent_base != "")
1414
+ .group_by(agent_base)
1415
+ .order_by(cnt_expr.desc(), literal_column("agent_base").asc())
1416
+ .limit(1)
1417
+ )
1418
+
1419
+
1420
+ # ── Monitor By Application query builders ─────────────────────────────────
1421
+
1422
+
1423
+ def agent_failure_count_for_sessions_query(
1424
+ dialect: Dialect = Dialect.CLICKHOUSE,
1425
+ *,
1426
+ session_ids: list[str],
1427
+ agent_id: str,
1428
+ ):
1429
+ """Count error-status spans for a specific agent across sessions.
1430
+
1431
+ Returns columns: ``cnt`` (number of error spans).
1432
+ """
1433
+ r = _refs(dialect)
1434
+
1435
+ return (
1436
+ select(func.count().label("cnt"))
1437
+ .select_from(r.tbl)
1438
+ .where(r.session_id.in_(session_ids))
1439
+ .where(r.agent_id == agent_id)
1440
+ .where(r.status_code == "Error")
1441
+ )
1442
+
1443
+
1444
+ def agent_token_costs_for_sessions_query(
1445
+ dialect: Dialect = Dialect.CLICKHOUSE,
1446
+ *,
1447
+ session_ids: list[str],
1448
+ agent_id: str,
1449
+ ):
1450
+ """Return chat span attributes for an agent across multiple sessions.
1451
+
1452
+ Returns columns: ``span_attributes, session_id`` for ``.chat`` spans
1453
+ so the caller can aggregate token counts and compute costs.
1454
+ """
1455
+ r = _refs(dialect)
1456
+
1457
+ return (
1458
+ select(r.span_attributes, r.session_id.label("session_id"))
1459
+ .select_from(r.tbl)
1460
+ .where(r.session_id.in_(session_ids))
1461
+ .where(r.agent_id == agent_id)
1462
+ .where(r.span_name.like("%.chat"))
1463
+ )
1464
+
1465
+
1466
+ def agent_active_sessions_query(
1467
+ dialect: Dialect = Dialect.CLICKHOUSE,
1468
+ *,
1469
+ session_ids: list[str],
1470
+ agent_id: str,
1471
+ ):
1472
+ """Return distinct session IDs where a specific agent is present.
1473
+
1474
+ Returns columns: ``session_id``.
1475
+ """
1476
+ r = _refs(dialect)
1477
+
1478
+ return (
1479
+ select(func.distinct(r.session_id).label("session_id"))
1480
+ .select_from(r.tbl)
1481
+ .where(r.session_id.in_(session_ids))
1482
+ .where(r.agent_id == agent_id)
1483
+ )
1484
+
1485
+
1486
+ def agent_avg_duration_for_sessions_query(
1487
+ dialect: Dialect = Dialect.CLICKHOUSE,
1488
+ *,
1489
+ session_ids: list[str],
1490
+ agent_id: str,
1491
+ ):
1492
+ """Average duration (in nanoseconds) of ``.agent`` spans for a specific
1493
+ agent across sessions.
1494
+
1495
+ Returns columns: ``avg_duration``.
1496
+ """
1497
+ r = _refs(dialect)
1498
+
1499
+ return (
1500
+ select(func.avg(r.duration).label("avg_duration"))
1501
+ .select_from(r.tbl)
1502
+ .where(r.session_id.in_(session_ids))
1503
+ .where(r.agent_id == agent_id)
1504
+ .where(r.span_name.like("%.agent"))
1505
+ )
1506
+
1507
+
1508
+ def session_avg_duration_for_sessions_query(
1509
+ dialect: Dialect = Dialect.CLICKHOUSE,
1510
+ *,
1511
+ session_ids: list[str],
1512
+ ):
1513
+ """Average session duration across the given sessions.
1514
+
1515
+ Computes ``MAX(timestamp) - MIN(timestamp)`` per session (in seconds),
1516
+ then averages across sessions.
1517
+
1518
+ Returns columns: ``avg_duration``.
1519
+ """
1520
+ r = _refs(dialect)
1521
+
1522
+ if dialect is Dialect.SQLITE:
1523
+ dur_expr = (
1524
+ func.julianday(func.max(r.ts)) - func.julianday(func.min(r.ts))
1525
+ ) * 86400
1526
+ else:
1527
+ dur_expr = (
1528
+ func.toUnixTimestamp64Nano(func.max(r.ts))
1529
+ - func.toUnixTimestamp64Nano(func.min(r.ts))
1530
+ ) / literal_column("1000000000")
1531
+
1532
+ sub = (
1533
+ select(dur_expr.label("sess_dur"))
1534
+ .select_from(r.tbl)
1535
+ .where(r.session_id.in_(session_ids))
1536
+ .where(r.session_id != "")
1537
+ .group_by(r.session_id)
1538
+ ).subquery()
1539
+
1540
+ return select(func.avg(column("sess_dur")).label("avg_duration")).select_from(sub)
1541
+
1542
+
1543
+ def llm_calls_count_by_sessions_query(
1544
+ dialect: Dialect = Dialect.CLICKHOUSE,
1545
+ *,
1546
+ session_ids: list[str],
1547
+ ):
1548
+ """Count total ``.chat`` spans (LLM calls) across sessions.
1549
+
1550
+ Returns columns: ``cnt``.
1551
+ """
1552
+ r = _refs(dialect)
1553
+ return (
1554
+ select(func.count().label("cnt"))
1555
+ .select_from(r.tbl)
1556
+ .where(r.session_id.in_(session_ids))
1557
+ .where(r.span_name.like("%.chat"))
1558
+ )
1559
+
1560
+
1561
+ def tool_calls_count_by_sessions_query(
1562
+ dialect: Dialect = Dialect.CLICKHOUSE,
1563
+ *,
1564
+ session_ids: list[str],
1565
+ ):
1566
+ """Count total ``.tool`` spans (tool calls) across sessions.
1567
+
1568
+ Returns columns: ``cnt``.
1569
+ """
1570
+ r = _refs(dialect)
1571
+ return (
1572
+ select(func.count().label("cnt"))
1573
+ .select_from(r.tbl)
1574
+ .where(r.session_id.in_(session_ids))
1575
+ .where(r.span_name.like("%.tool"))
1576
+ )
1577
+
1578
+
1579
+ def error_count_by_sessions_query(
1580
+ dialect: Dialect = Dialect.CLICKHOUSE,
1581
+ *,
1582
+ session_ids: list[str],
1583
+ ):
1584
+ """Count spans with status ``Error`` across sessions.
1585
+
1586
+ Returns columns: ``cnt``.
1587
+ """
1588
+ r = _refs(dialect)
1589
+ return (
1590
+ select(func.count().label("cnt"))
1591
+ .select_from(r.tbl)
1592
+ .where(r.session_id.in_(session_ids))
1593
+ .where(r.status_code == "Error")
1594
+ )
1595
+
1596
+
1597
+ def token_sum_by_sessions_query(
1598
+ *,
1599
+ session_ids: list[str],
1600
+ ):
1601
+ """Sum total tokens (prompt + completion) for a set of sessions via Neo4j.
1602
+
1603
+ Sums ``promptTokenCount`` + ``completionTokenCount`` on ``LLMCall`` nodes
1604
+ and returns a ``(cypher_string, params_dict)`` tuple with a single-row
1605
+ result column ``total_tokens``.
1606
+ """
1607
+ stmt = """
1608
+ MATCH (lc:LLMCall)
1609
+ WHERE lc.sessionId IN $session_ids
1610
+ RETURN coalesce(
1611
+ sum(coalesce(toFloat(lc.promptTokenCount), 0.0)
1612
+ + coalesce(toFloat(lc.completionTokenCount), 0.0)),
1613
+ 0.0
1614
+ ) AS total_tokens
1615
+ """
1616
+ return stmt, {"session_ids": session_ids}
1617
+
1618
+
1619
+ def token_sum_by_sessions_clickhouse_query(
1620
+ dialect: Dialect = Dialect.CLICKHOUSE,
1621
+ *,
1622
+ session_ids: list[str],
1623
+ ):
1624
+ """Sum total tokens (prompt + completion) for ClickHouse/SQLite backends.
1625
+
1626
+ For **SQLite** returns raw ``span_attributes`` rows for Python-side
1627
+ parsing. For **ClickHouse** returns a single ``total_tokens`` value.
1628
+ """
1629
+ r = _refs(dialect)
1630
+
1631
+ if dialect is Dialect.SQLITE:
1632
+ return (
1633
+ select(r.span_attributes.label("span_attributes"))
1634
+ .select_from(r.tbl)
1635
+ .where(r.session_id.in_(session_ids))
1636
+ .where(r.span_name.like("%.chat"))
1637
+ )
1638
+
1639
+ prompt_tokens = literal_column(
1640
+ "toFloat64OrZero(SpanAttributes['gen_ai.usage.input_tokens'])"
1641
+ )
1642
+ completion_tokens = literal_column(
1643
+ "toFloat64OrZero(SpanAttributes['gen_ai.usage.output_tokens'])"
1644
+ )
1645
+ return (
1646
+ select(func.sum(prompt_tokens + completion_tokens).label("total_tokens"))
1647
+ .select_from(r.tbl)
1648
+ .where(r.session_id.in_(session_ids))
1649
+ .where(r.span_name.like("%.chat"))
1650
+ )
1651
+
1652
+
1653
+ # ── Collect By Application query builders ─────────────────────────────────
1654
+
1655
+
1656
+ def collect_page_sessions_query(
1657
+ dialect: Dialect = Dialect.CLICKHOUSE,
1658
+ *,
1659
+ start_time: Optional[str] = None,
1660
+ end_time: Optional[str] = None,
1661
+ application_id: Optional[str] = None,
1662
+ ):
1663
+ """Build a query for collect page sessions grouped by session_id.
1664
+
1665
+ Returns columns: ``session_id, start_timestamp, end_timestamp``.
1666
+ """
1667
+ _refs(dialect)
1668
+
1669
+ # TODO: add support for time range here
1670
+ if dialect is Dialect.NEO4J:
1671
+ stmt = """
1672
+ MATCH (s:Session)-[:executesSession]->(ma:MAS) WHERE ma.id = $application_id
1673
+ OPTIONAL MATCH (mr:MetricResult)-[:measures]->(s), (mr)-[:ofMetricType]->(m:Metric)
1674
+ WHERE m.name = 'Cost'
1675
+ OPTIONAL MATCH (s)-[:hasMASCall]->(:MASCall)-[:hasAgentCall]->(ac:AgentCall)
1676
+ OPTIONAL MATCH (ac)-[:executesAgent]->(agentNode:Agent)
1677
+ OPTIONAL MATCH (ac)-[:hasLLMCall]->(l:LLMCall)
1678
+ RETURN
1679
+ s.sessionId AS sessionId,
1680
+ s.startTime as startTime,
1681
+ s.duration as duration,
1682
+ mr.result as cost,
1683
+ collect(DISTINCT agentNode.name) As agents,
1684
+ sum(l.completionTokenCount + l.promptTokenCount) as tokens
1685
+ """
1686
+ return stmt, {"application_id": application_id}
1687
+
1688
+
1689
+ def collect_page_sessions_with_stateful_eval_query_multi_query(
1690
+ dialect: Dialect = Dialect.CLICKHOUSE,
1691
+ *,
1692
+ start_time: Optional[str] = None,
1693
+ end_time: Optional[str] = None,
1694
+ application_id: Optional[str] = None,
1695
+ ):
1696
+ """Build a query for collect page sessions including stateful eval metrics.
1697
+
1698
+ Returns a Cypher string for Neo4j that also collects any session-attached
1699
+ metrics named `TrajectoryScore` or `statefulEval` as `statefulEvals`.
1700
+ """
1701
+ # Only Neo4j currently supports attached Metric nodes for stateful eval
1702
+ if dialect is Dialect.NEO4J:
1703
+ stmt = """
1704
+ MATCH (s:Session)-[:executesSession]->(ma:MAS) WHERE ma.id = $application_id
1705
+ OPTIONAL MATCH (mr:MetricResult)-[:measures]->(s), (mr)-[:ofMetricType]->(m:Metric)
1706
+ WHERE m.name = 'Cost'
1707
+ OPTIONAL MATCH (s)-[:hasMASCall]->(:MASCall)-[:hasAgentCall]->(ac:AgentCall)
1708
+ OPTIONAL MATCH (ac)-[:executesAgent]->(agentNode:Agent)
1709
+ OPTIONAL MATCH (ac)-[:hasLLMCall]->(l:LLMCall)
1710
+ OPTIONAL MATCH (rse:MetricResult)-[:measures]->(s), (rse)-[:ofMetricType]->(se:Metric)
1711
+ WHERE se.name IN ['TrajectoryScore','statefulEval']
1712
+ RETURN
1713
+ s.sessionId AS sessionId,
1714
+ s.startTime as startTime,
1715
+ s.duration as duration,
1716
+ mr.result as cost,
1717
+ collect(DISTINCT agentNode.name) As agents,
1718
+ sum(l.completionTokenCount + l.promptTokenCount) as tokens,
1719
+ collect(DISTINCT {
1720
+ name: se.name,
1721
+ result: rse.result,
1722
+ value: rse.result,
1723
+ provider: se.metricProvider,
1724
+ metric_id: se.name,
1725
+ source: se.metricProvider,
1726
+ reasoning: rse.reasoning
1727
+ }) AS statefulEvals
1728
+ """
1729
+ return stmt, {"application_id": application_id}
1730
+
1731
+ # Fallback to existing collect_page_sessions_query behaviour for SQL
1732
+ return collect_page_sessions_query(
1733
+ dialect=dialect,
1734
+ start_time=start_time,
1735
+ end_time=end_time,
1736
+ application_id=application_id,
1737
+ )
1738
+
1739
+
1740
+ def collect_page_sessions_with_stateful_eval_query(
1741
+ dialect: Dialect = Dialect.CLICKHOUSE,
1742
+ *,
1743
+ start_time: Optional[str] = None,
1744
+ end_time: Optional[str] = None,
1745
+ application_id: Optional[str] = None,
1746
+ semantic_group_id: Optional[str] = None,
1747
+ ):
1748
+ """Build a single Neo4j query returning sessions, stateful eval, and metrics.
1749
+
1750
+ Returns one row per session with:
1751
+ ``sessionId, startTime, duration, cost, agents, tokens, statefulEvals, sessionMetrics``.
1752
+
1753
+ When ``semantic_group_id`` is provided, only sessions that belong to the
1754
+ given ``SemanticGroup`` (keyed by its ``id`` property) are returned.
1755
+ """
1756
+ # For debugging, add:
1757
+ # MATCH (s:Session) - [] -(ma:MAS) WHERE ma.id = $application_id
1758
+ # WITH DISTINCT s
1759
+ # LIMIT 5
1760
+
1761
+ # WHERE clause filters on s.startTime using NULL-guards ($start_time IS NULL OR s.startTime >= $start_time
1762
+ # the same for end_time, so when a bound isn't supplied no filtering is applied.
1763
+ # The same NULL-guard pattern is used for $semantic_group_id: when it is
1764
+ # supplied, only sessions linked to that SemanticGroup are kept.
1765
+ # Only Neo4j currently supports attached Metric nodes in this shape.
1766
+ if dialect is Dialect.NEO4J:
1767
+ # logger.warning(
1768
+ # "\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
1769
+ # "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
1770
+ # "ERROR\n"
1771
+ # "WARNING: DEBUG is enabled: returning only 5 sessions in "
1772
+ # "collect_page_sessions_with_stateful_eval_query.\n"
1773
+ # "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
1774
+ # "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n"
1775
+ # )
1776
+ stmt = """
1777
+ MATCH (s:Session)-[:executesSession]->(ma:MAS) WHERE ma.id = $application_id
1778
+ WITH DISTINCT s
1779
+ WHERE ($start_time IS NULL OR s.startTime >= $start_time)
1780
+ AND ($end_time IS NULL OR s.startTime <= $end_time)
1781
+ AND ($semantic_group_id IS NULL OR EXISTS {
1782
+ MATCH (sg:SemanticGroup {id: $semantic_group_id})-[:containsSession*1..]->(s)
1783
+ })
1784
+ OPTIONAL MATCH (rCost:MetricResult)-[:measures]->(s), (rCost)-[:ofMetricType]->(mCost:Metric)
1785
+ WHERE mCost.name = 'Cost'
1786
+ WITH s, head(collect(DISTINCT rCost.result)) AS cost
1787
+ OPTIONAL MATCH (rDuration:MetricResult)-[:measures]->(s), (rDuration)-[:ofMetricType]->(mDuration:Metric)
1788
+ WHERE mDuration.name = 'Duration'
1789
+ WITH s, cost, head(collect(DISTINCT rDuration.result)) AS duration
1790
+ OPTIONAL MATCH (s)-[:hasMASCall]->(:MASCall)-[:hasAgentCall]->(ac:AgentCall)
1791
+ OPTIONAL MATCH (ac)-[:executesAgent]->(agentNode:Agent)
1792
+ OPTIONAL MATCH (ac)-[:hasLLMCall]->(l:LLMCall)
1793
+ WITH
1794
+ s,
1795
+ cost,
1796
+ duration,
1797
+ [a IN collect(DISTINCT agentNode.name) WHERE a IS NOT NULL] AS agents,
1798
+ coalesce(sum(coalesce(l.completionTokenCount, 0) + coalesce(l.promptTokenCount, 0)), 0) AS tokens
1799
+ OPTIONAL MATCH (rse:MetricResult)-[:measures]->(s), (rse)-[:ofMetricType]->(se:Metric)
1800
+ WHERE se.name IN ['TrajectoryScore','statefulEval']
1801
+ WITH
1802
+ s,
1803
+ cost,
1804
+ duration,
1805
+ agents,
1806
+ tokens,
1807
+ [x IN collect(DISTINCT {
1808
+ name: se.name,
1809
+ result: rse.result,
1810
+ value: rse.result,
1811
+ provider: se.metricProvider,
1812
+ metric_id: se.name,
1813
+ source: se.metricProvider,
1814
+ reasoning: rse.reasoning
1815
+ }) WHERE x.name IS NOT NULL] AS statefulEvals
1816
+ OPTIONAL MATCH (rsm:MetricResult)-[:measures]->(s), (rsm)-[:ofMetricType]->(sm:Metric)
1817
+ WITH
1818
+ s,
1819
+ cost,
1820
+ duration,
1821
+ agents,
1822
+ tokens,
1823
+ statefulEvals,
1824
+ [x IN collect(DISTINCT {
1825
+ name: sm.name,
1826
+ result: rsm.result,
1827
+ value: rsm.result,
1828
+ provider: sm.metricProvider,
1829
+ metric_id: sm.name,
1830
+ source: sm.metricProvider,
1831
+ reasoning: rsm.reasoning
1832
+ }) WHERE x.name IS NOT NULL] AS sessionMetrics
1833
+ RETURN
1834
+ s.sessionId AS sessionId,
1835
+ s.startTime AS startTime,
1836
+ duration,
1837
+ cost,
1838
+ agents,
1839
+ tokens,
1840
+ statefulEvals,
1841
+ sessionMetrics
1842
+ """
1843
+ return stmt, {
1844
+ "application_id": application_id,
1845
+ "start_time": start_time,
1846
+ "end_time": end_time,
1847
+ "semantic_group_id": semantic_group_id,
1848
+ }
1849
+
1850
+ return collect_page_sessions_with_stateful_eval_query_multi_query(
1851
+ dialect=dialect,
1852
+ start_time=start_time,
1853
+ end_time=end_time,
1854
+ application_id=application_id,
1855
+ )
1856
+
1857
+
1858
+ def collect_agents_per_session_query(
1859
+ dialect: Dialect = Dialect.CLICKHOUSE,
1860
+ *,
1861
+ session_ids: list[str],
1862
+ ):
1863
+ """Return distinct (session_id, agent_base_name) pairs for given sessions.
1864
+
1865
+ The agent base name is the part of ``agent_id`` before the first dot.
1866
+
1867
+ Returns columns: ``session_id, agent_id``.
1868
+ """
1869
+ r = _refs(dialect)
1870
+
1871
+ if dialect is Dialect.SQLITE:
1872
+ agent_base = func.substr(
1873
+ r.agent_id,
1874
+ 1,
1875
+ func.instr(r.agent_id, ".") - 1,
1876
+ ).label("agent_id")
1877
+ return (
1878
+ select(
1879
+ r.session_id.label("session_id"),
1880
+ agent_base,
1881
+ )
1882
+ .select_from(r.tbl)
1883
+ .where(r.session_id.in_(session_ids))
1884
+ .where(r.agent_id != "")
1885
+ .where(r.agent_id.like("%.%"))
1886
+ .group_by(r.session_id, agent_base)
1887
+ )
1888
+
1889
+ agent_base = literal_column("splitByChar('.', agent_id)[1]")
1890
+ return (
1891
+ select(
1892
+ r.session_id.label("session_id"),
1893
+ agent_base.label("agent_id"),
1894
+ )
1895
+ .select_from(r.tbl)
1896
+ .where(r.session_id.in_(session_ids))
1897
+ .where(agent_base != "")
1898
+ .group_by(r.session_id, r.agent_id)
1899
+ )
1900
+
1901
+
1902
+ def collect_chat_spans_for_sessions_query(
1903
+ dialect: Dialect = Dialect.CLICKHOUSE,
1904
+ *,
1905
+ session_ids: list[str],
1906
+ ):
1907
+ """Return chat span data for given sessions.
1908
+
1909
+ Returns columns: ``session_id, span_attributes`` for spans that
1910
+ represent LLM calls. Matches ``.chat`` span names *and* any span
1911
+ that carries token-usage attributes (covers non-LangChain
1912
+ instrumentations).
1913
+ """
1914
+ r = _refs(dialect)
1915
+
1916
+ if dialect is Dialect.SQLITE:
1917
+ llm_filter = or_(
1918
+ r.span_name.like("%.chat"),
1919
+ r.span_attributes.like("%llm.usage.total_tokens%"),
1920
+ r.span_attributes.like("%gen_ai.usage.input_tokens%"),
1921
+ r.span_attributes.like("%gen_ai.usage.prompt_tokens%"),
1922
+ )
1923
+ else:
1924
+ llm_filter = or_(
1925
+ r.span_name.like("%.chat"),
1926
+ literal_column("SpanAttributes['gen_ai.usage.prompt_tokens']") != "",
1927
+ literal_column("SpanAttributes['gen_ai.usage.input_tokens']") != "",
1928
+ literal_column("SpanAttributes['llm.usage.total_tokens']") != "",
1929
+ )
1930
+
1931
+ exact = ", ".join(f"'{s}'" for s in session_ids)
1932
+
1933
+ if dialect is Dialect.SQLITE:
1934
+ sess_filter = text(f"(session_id IN ({exact}))")
1935
+ else:
1936
+ # Chat spans may store the session id only in the SpanAttributes
1937
+ # map (often prefixed with the app name, e.g. "app_<uuid>").
1938
+ # Check both the session_id column AND SpanAttributes['session.id'].
1939
+ attr_col = "SpanAttributes['session.id']"
1940
+ like_col = " OR ".join(f"session_id LIKE '%\\_{s}'" for s in session_ids)
1941
+ like_attr = " OR ".join(f"{attr_col} LIKE '%\\_{s}'" for s in session_ids)
1942
+ sess_filter = text(
1943
+ f"(session_id IN ({exact}) OR {attr_col} IN ({exact})"
1944
+ f" OR {like_col} OR {like_attr})"
1945
+ )
1946
+
1947
+ return (
1948
+ select(
1949
+ r.session_id.label("session_id"),
1950
+ r.span_attributes,
1951
+ )
1952
+ .select_from(r.tbl)
1953
+ .where(sess_filter)
1954
+ .where(llm_filter)
1955
+ )
1956
+
1957
+
1958
+ # ── Application General Charts query builders ─────────────────────────────────
1959
+
1960
+
1961
+ def session_ids_by_app_and_agent_query(
1962
+ dialect: Dialect = Dialect.CLICKHOUSE,
1963
+ *,
1964
+ start_time: Optional[str] = None,
1965
+ end_time: Optional[str] = None,
1966
+ application_id: Optional[str] = None,
1967
+ agent_id: Optional[str] = None,
1968
+ given_session_ids: Optional[list[str]] = None,
1969
+ ):
1970
+ """Return distinct session IDs filtered by agent base name.
1971
+
1972
+ The agent base name is the part of ``agent_id`` before the first dot
1973
+ (e.g. ``noa-moderator`` from ``noa-moderator.invoke``).
1974
+
1975
+ Returns columns: ``session_id``.
1976
+ """
1977
+ r = _refs(dialect)
1978
+
1979
+ stmt = (
1980
+ select(func.distinct(r.session_id).label("session_id"))
1981
+ .select_from(r.tbl)
1982
+ .where(r.session_id != "")
1983
+ )
1984
+
1985
+ if start_time:
1986
+ stmt = stmt.where(r.ts >= start_time)
1987
+ if end_time:
1988
+ stmt = stmt.where(r.ts <= end_time)
1989
+ if application_id:
1990
+ stmt = stmt.where(func.lower(r.application_id) == func.lower(application_id))
1991
+ if agent_id:
1992
+ stmt = stmt.where(r.agent_id == agent_id)
1993
+ if given_session_ids:
1994
+ stmt = stmt.where(r.session_id.in_(given_session_ids))
1995
+
1996
+ return stmt.order_by(r.session_id.desc())
1997
+
1998
+
1999
+ # ── Application Tools Charts query builders ───────────────────────────────────
2000
+
2001
+
2002
+ def tool_details_by_sessions_and_agent_query(
2003
+ dialect: Dialect = Dialect.CLICKHOUSE,
2004
+ *,
2005
+ session_ids: list[str],
2006
+ agent_id: str,
2007
+ ):
2008
+ """Return per-tool aggregates for tool spans in the given sessions.
2009
+
2010
+ For each distinct tool name (prefix of ``SpanName`` before the first
2011
+ dot in ``.tool`` spans), computes:
2012
+ * ``Success`` – average success rate (1 for OK, 0 for Error)
2013
+ * ``SessionCount`` – number of distinct sessions using the tool
2014
+ * ``Duration`` – average duration in milliseconds
2015
+
2016
+ Returns columns: ``tool_name, success, session_count, duration``.
2017
+ """
2018
+
2019
+ r = _refs(dialect)
2020
+
2021
+ if dialect is Dialect.SQLITE:
2022
+ tool_name_expr = func.substr(
2023
+ r.span_name,
2024
+ 1,
2025
+ func.instr(r.span_name, ".") - 1,
2026
+ )
2027
+ success_expr = func.avg(func.iif(r.status_code == "Error", 0, 1))
2028
+ else:
2029
+ tool_name_expr = literal_column("splitByChar('.', SpanName)[1]")
2030
+ success_expr = func.avg(func.if_(r.status_code == "Error", 0, 1))
2031
+
2032
+ return (
2033
+ select(
2034
+ tool_name_expr.label("tool_name"),
2035
+ success_expr.label("success"),
2036
+ func.count(func.distinct(r.session_id)).label("session_count"),
2037
+ func.avg(r.duration / literal_column("1000000")).label("duration"),
2038
+ )
2039
+ .select_from(r.tbl)
2040
+ .where(r.session_id.in_(session_ids))
2041
+ .where(r.span_name.like("%.tool"))
2042
+ .group_by(tool_name_expr)
2043
+ )
2044
+
2045
+
2046
+ def tool_detail_for_tool_name_query(
2047
+ dialect: Dialect = Dialect.CLICKHOUSE,
2048
+ *,
2049
+ session_ids: list[str],
2050
+ agent_id: str,
2051
+ tool_name: str,
2052
+ ):
2053
+ """Return the average duration (ms) for a specific tool in given sessions.
2054
+
2055
+ Returns columns: ``tool_name, duration``.
2056
+ """
2057
+ r = _refs(dialect)
2058
+
2059
+ if dialect is Dialect.SQLITE:
2060
+ tool_name_expr = func.substr(
2061
+ r.span_name,
2062
+ 1,
2063
+ func.instr(r.span_name, ".") - 1,
2064
+ )
2065
+ else:
2066
+ tool_name_expr = literal_column("splitByChar('.', SpanName)[1]")
2067
+
2068
+ return (
2069
+ select(
2070
+ tool_name_expr.label("tool_name"),
2071
+ func.avg(r.duration / literal_column("1000000")).label("duration"),
2072
+ )
2073
+ .select_from(r.tbl)
2074
+ .where(r.session_id.in_(session_ids))
2075
+ .where(r.span_name.like("%.tool"))
2076
+ .where(tool_name_expr == tool_name)
2077
+ .group_by(tool_name_expr)
2078
+ )
2079
+
2080
+
2081
+ # ── Timeline (Waterfall) query builders ───────────────────────────────────────
2082
+
2083
+
2084
+ def traces_by_session_id_query(
2085
+ dialect: Dialect = Dialect.CLICKHOUSE,
2086
+ *,
2087
+ session_id: str,
2088
+ ):
2089
+ """Return all trace spans for a given session, ordered by timestamp.
2090
+
2091
+ Returns columns: ``timestamp, span_id, span_name,
2092
+ parent_span_id, agent_id, application_id, duration, status_code``.
2093
+ """
2094
+ r = _refs(dialect)
2095
+
2096
+ if dialect is Dialect.SQLITE:
2097
+ agent_base = func.substr(
2098
+ r.agent_id,
2099
+ 1,
2100
+ func.instr(r.agent_id, ".") - 1,
2101
+ )
2102
+ else:
2103
+ agent_base = literal_column("splitByChar('.', agent_id)[1]")
2104
+
2105
+ return (
2106
+ select(
2107
+ r.wrap(r.ts).label("timestamp"),
2108
+ r.span_id.label("span_id"),
2109
+ r.span_name.label("span_name"),
2110
+ r.parent_span_id.label("parent_span_id"),
2111
+ agent_base.label("agent_id"),
2112
+ r.application_id.label("application_id"),
2113
+ r.duration.label("duration"),
2114
+ r.status_code.label("status_code"),
2115
+ )
2116
+ .select_from(r.tbl)
2117
+ .where(r.session_id == session_id)
2118
+ .order_by(r.ts)
2119
+ )
2120
+
2121
+
2122
+ _LEVEL_TO_LABELS = {
2123
+ "session": ["Session"],
2124
+ "mas": ["MASCall"],
2125
+ "agent": ["AgentCall"],
2126
+ "tool": ["ToolCall"],
2127
+ "llm": ["LLMCall"],
2128
+ "processing": ["ProcessingCall"],
2129
+ # The UI groups all three capability call types into a single "Calls" row
2130
+ # (see ExecutionTimeline.tsx's HIERARCHY_LEVELS / sessions.py's level_order,
2131
+ # both of which use "call", never "llm"/"tool"/"processing" individually).
2132
+ "call": ["ToolCall", "LLMCall", "ProcessingCall"],
2133
+ }
2134
+
2135
+
2136
+ def state_machine_graph_query(
2137
+ *,
2138
+ session_id: str,
2139
+ level: str | None = None,
2140
+ ) -> tuple[str, dict[str, Any]]:
2141
+ """Build the Cypher query for the session execution graph.
2142
+
2143
+ ``hierarchyLevel`` is a per-class constant in the ontology (not a
2144
+ queryable Neo4j property with per-instance values), so "which level"
2145
+ a Transition belongs to is determined by the label of the node its
2146
+ ``representsExecution`` edge points to, not a ``t.hierarchyLevel``
2147
+ property.
2148
+
2149
+ Likewise, a State's initial/final role is not a property on
2150
+ ``State`` itself (which only carries ``content``) -- the ontology
2151
+ models it relationally via ``Session -[:hasInitialState]-> State``
2152
+ and ``Session -[:hasFinalState]-> State``, so those boundary states
2153
+ must be matched explicitly to tag ``fromType``/``toType``.
2154
+
2155
+ The trajectory is *not* a single flat chain hanging off ``Session``:
2156
+ every ``ExecutionElement`` (``AgentCall``, ``LLMCall``, ``ToolCall``,
2157
+ ``ProcessingCall``, ``MASCall``) has its own nested ``hasState``
2158
+ sub-trajectory, so walking only ``Session -[:hasState]-> State``
2159
+ reaches just the session's two boundary states and misses the rest
2160
+ of the execution tree entirely. ``Transition``/``State`` are
2161
+ ``TrajectoryElement``s and carry ``sessionId`` directly, so the walk
2162
+ is scoped by that property instead of by containment under Session.
2163
+
2164
+ ``level`` filtering must act as a genuine row filter, applied after
2165
+ ``e`` (and ``structural``) are fully resolved via a ``WITH`` boundary.
2166
+ A bare ``WHERE`` placed directly after an ``OPTIONAL MATCH`` only
2167
+ qualifies *that* optional pattern -- rows outside the requested
2168
+ levels would still be returned, just with ``e`` (and therefore
2169
+ ``duration``/``entityName``/``hierarchyLevel``/``spanId``/
2170
+ ``executionId``) silently nulled out instead of the row being
2171
+ excluded.
2172
+ """
2173
+ labels: list[str] = []
2174
+ for item in level.split(",") if level else []:
2175
+ labels.extend(_LEVEL_TO_LABELS.get(item.strip(), []))
2176
+ labels = list(dict.fromkeys(labels))
2177
+ level_filter = (
2178
+ "WHERE any(lbl IN $levelLabels WHERE lbl IN labels(e))" if labels else ""
2179
+ )
2180
+
2181
+ query = f"""
2182
+ MATCH (s:Session {{sessionId: $sessionId}})
2183
+ OPTIONAL MATCH (s)-[:hasInitialState]->(initialState:State)
2184
+ OPTIONAL MATCH (s)-[:hasFinalState]->(finalState:State)
2185
+ MATCH (from:State)-[:inputTo]->(t:Transition {{sessionId: $sessionId}})-[:leadsTo]->(to:State)
2186
+ OPTIONAL MATCH (t)-[:representsExecution]->(e)
2187
+ OPTIONAL MATCH (e)-[:executesAgent|executesTool|executesLLM|executesProcessing|executesMAS|executesSession]->(structural)
2188
+ WITH from, to, t, e, structural, initialState, finalState
2189
+ {level_filter}
2190
+ RETURN DISTINCT
2191
+ from.id as fromStateId,
2192
+ from.content as fromContent,
2193
+ CASE
2194
+ WHEN from.id = initialState.id THEN 'initial'
2195
+ WHEN from.id = finalState.id THEN 'final'
2196
+ ELSE 'intermediate'
2197
+ END as fromType,
2198
+ to.id as toStateId,
2199
+ to.content as toContent,
2200
+ CASE
2201
+ WHEN to.id = initialState.id THEN 'initial'
2202
+ WHEN to.id = finalState.id THEN 'final'
2203
+ ELSE 'intermediate'
2204
+ END as toType,
2205
+ t.id as transitionId,
2206
+ e.duration as duration,
2207
+ structural.name as entityName,
2208
+ CASE
2209
+ WHEN 'AgentCall' IN labels(e) THEN 'agent'
2210
+ WHEN 'LLMCall' IN labels(e) THEN 'call'
2211
+ WHEN 'ToolCall' IN labels(e) THEN 'call'
2212
+ WHEN 'ProcessingCall' IN labels(e) THEN 'call'
2213
+ WHEN 'MASCall' IN labels(e) THEN 'mas'
2214
+ WHEN 'Session' IN labels(e) THEN 'session'
2215
+ ELSE null
2216
+ END as hierarchyLevel,
2217
+ CASE
2218
+ WHEN 'ToolCall' IN labels(e) THEN 'tool'
2219
+ WHEN 'LLMCall' IN labels(e) THEN 'llm'
2220
+ WHEN 'ProcessingCall' IN labels(e) THEN 'processing'
2221
+ ELSE null
2222
+ END as callType,
2223
+ e.spanId as spanId,
2224
+ e.id as executionId
2225
+ ORDER BY from.id
2226
+ """
2227
+
2228
+ params: dict[str, Any] = {"sessionId": session_id}
2229
+ if labels:
2230
+ params["levelLabels"] = labels
2231
+ return query, params
2232
+
2233
+
2234
+ def latent_space_query(
2235
+ *,
2236
+ session_id: str,
2237
+ ) -> tuple[str, dict[str, Any]]:
2238
+ """Build the Cypher query for state embeddings at the agent hierarchy level.
2239
+
2240
+ Returns state nodes with their embeddings and transitions between them,
2241
+ matching the agent-level portion of the state machine graph.
2242
+ """
2243
+ query = """
2244
+ MATCH (state:State)-[:inputTo]->(t:Transition {sessionId: $sessionId})
2245
+ -[:leadsTo]->(toState:State)
2246
+ MATCH (t)-[:representsExecution]->(e)
2247
+ WHERE e:AgentCall
2248
+ OR (e:ProcessingCall AND EXISTS { MATCH (:MASCall)-[:hasProcessingCall]->(e) })
2249
+ OPTIONAL MATCH (emb:Embedding)-[:represents]->(state)
2250
+ OPTIONAL MATCH (toEmb:Embedding)-[:represents]->(toState)
2251
+ OPTIONAL MATCH (e)-[:executesAgent]->(agent:Agent)
2252
+ OPTIONAL MATCH (e)-[:executesProcessing]->(proc:Processing)
2253
+ RETURN DISTINCT
2254
+ state.id AS stateId,
2255
+ state.content AS content,
2256
+ emb.embeddingVector AS embedding,
2257
+ toState.id AS toStateId,
2258
+ toState.content AS toContent,
2259
+ toEmb.embeddingVector AS toEmbedding,
2260
+ t.id AS transitionId,
2261
+ e.duration AS duration,
2262
+ coalesce(agent.name, proc.name) AS entityName,
2263
+ CASE WHEN e:AgentCall THEN 'agent' ELSE 'processing' END AS entityType
2264
+ ORDER BY state.id
2265
+ """
2266
+ return query, {"sessionId": session_id}
2267
+
2268
+
2269
+ def execution_hierarchy_session_state_query(
2270
+ *,
2271
+ session_id: str,
2272
+ ) -> tuple[str, dict[str, Any]]:
2273
+ """Build the Cypher query for session-level input/output state content."""
2274
+ query = """
2275
+ MATCH (s:Session {sessionId: $sessionId})
2276
+ OPTIONAL MATCH (s)-[:hasInitialState]->(initial:State)
2277
+ OPTIONAL MATCH (s)-[:hasFinalState]->(final:State)
2278
+ RETURN initial.content as inputContent, final.content as outputContent
2279
+ """
2280
+ return query, {"sessionId": session_id}
2281
+
2282
+
2283
+ def execution_hierarchy_mas_query(
2284
+ *,
2285
+ session_id: str,
2286
+ ) -> tuple[str, dict[str, Any]]:
2287
+ """Build the Cypher query for MAS-level transitions.
2288
+
2289
+ Scoped by ``Transition.sessionId`` rather than by ``Session
2290
+ -[:hasState]->`` (see ``state_machine_graph_query``'s docstring):
2291
+ the latter only reaches the session's two boundary states, missing
2292
+ every MAS/agent/call nested further down the trajectory tree.
2293
+ """
2294
+ query = """
2295
+ MATCH (inputState:State)-[:inputTo]->(t:Transition {sessionId: $sessionId})
2296
+ -[:representsExecution]->(mc:MASCall)
2297
+ OPTIONAL MATCH (t)-[:leadsTo]->(outputState:State)
2298
+ RETURN t.id as transitionId,
2299
+ mc.startTime as timestamp,
2300
+ mc.duration as duration,
2301
+ inputState.content as inputContent,
2302
+ outputState.content as outputContent
2303
+ ORDER BY mc.startTime
2304
+ """
2305
+ return query, {"sessionId": session_id}
2306
+
2307
+
2308
+ def execution_hierarchy_agent_query(
2309
+ *,
2310
+ session_id: str,
2311
+ ) -> tuple[str, dict[str, Any]]:
2312
+ """Build the Cypher query for agent-level transitions.
2313
+
2314
+ Scoped by ``Transition.sessionId`` rather than by ``Session
2315
+ -[:hasState]->`` -- see ``execution_hierarchy_mas_query``.
2316
+ """
2317
+ query = """
2318
+ MATCH (inputState:State)-[:inputTo]->(t:Transition {sessionId: $sessionId})
2319
+ -[:representsExecution]->(ac:AgentCall)
2320
+ OPTIONAL MATCH (ac)-[:executesAgent]->(agent:Agent)
2321
+ OPTIONAL MATCH (t)-[:leadsTo]->(outputState:State)
2322
+ RETURN t.id as transitionId,
2323
+ ac.startTime as timestamp,
2324
+ ac.duration as duration,
2325
+ agent.name as agentName,
2326
+ ac.id as executionId,
2327
+ inputState.content as inputContent,
2328
+ outputState.content as outputContent
2329
+ ORDER BY ac.startTime
2330
+ """
2331
+ return query, {"sessionId": session_id}
2332
+
2333
+
2334
+ def execution_hierarchy_tool_call_query(
2335
+ *,
2336
+ session_id: str,
2337
+ ) -> tuple[str, dict[str, Any]]:
2338
+ """Build the Cypher query for tool call-level transitions.
2339
+
2340
+ Scoped by ``Transition.sessionId`` rather than by ``Session
2341
+ -[:hasState]->`` -- see ``execution_hierarchy_mas_query``.
2342
+ """
2343
+ query = """
2344
+ MATCH (inputState:State)-[:inputTo]->(t:Transition {sessionId: $sessionId})
2345
+ -[:representsExecution]->(tc:ToolCall)
2346
+ OPTIONAL MATCH (tc)-[:executesTool]->(tool:Tool)
2347
+ OPTIONAL MATCH (ac:AgentCall)-[:hasToolCall]->(tc)
2348
+ OPTIONAL MATCH (t)-[:leadsTo]->(outputState:State)
2349
+ RETURN t.id as transitionId,
2350
+ tc.startTime as timestamp,
2351
+ tc.duration as duration,
2352
+ tool.name as toolName,
2353
+ tc.id as executionId,
2354
+ tc.spanId as spanId,
2355
+ ac.id as parentAgentExecId,
2356
+ inputState.content as inputContent,
2357
+ outputState.content as outputContent
2358
+ ORDER BY tc.startTime
2359
+ """
2360
+ return query, {"sessionId": session_id}
2361
+
2362
+
2363
+ def execution_hierarchy_llm_call_query(
2364
+ *,
2365
+ session_id: str,
2366
+ ) -> tuple[str, dict[str, Any]]:
2367
+ """Build the Cypher query for LLM call-level transitions.
2368
+
2369
+ Scoped by ``Transition.sessionId`` rather than by ``Session
2370
+ -[:hasState]->`` -- see ``execution_hierarchy_mas_query``.
2371
+ """
2372
+ query = """
2373
+ MATCH (inputState:State)-[:inputTo]->(t:Transition {sessionId: $sessionId})
2374
+ -[:representsExecution]->(lc:LLMCall)
2375
+ OPTIONAL MATCH (lc)-[:executesLLM]->(llm:LLM)
2376
+ OPTIONAL MATCH (ac:AgentCall)-[:hasLLMCall]->(lc)
2377
+ OPTIONAL MATCH (ac)-[:executesAgent]->(agent:Agent)
2378
+ OPTIONAL MATCH (t)-[:leadsTo]->(outputState:State)
2379
+ RETURN t.id as transitionId,
2380
+ lc.startTime as timestamp,
2381
+ lc.duration as duration,
2382
+ llm.name as modelName,
2383
+ llm.provider as provider,
2384
+ lc.promptTokenCount as promptTokens,
2385
+ lc.completionTokenCount as completionTokens,
2386
+ lc.totalTokenCount as totalTokens,
2387
+ lc.cacheReadTokenCount as cacheReadTokens,
2388
+ lc.temperature as temperature,
2389
+ lc.finishReason as finishReason,
2390
+ lc.id as executionId,
2391
+ agent.name as agentName,
2392
+ ac.id as parentAgentExecId,
2393
+ inputState.content as inputContent,
2394
+ outputState.content as outputContent
2395
+ ORDER BY lc.startTime
2396
+ """
2397
+ return query, {"sessionId": session_id}
2398
+
2399
+
2400
+ # ── Derived-metrics query builders ───────────────────────────────────────────
2401
+
2402
+
2403
+ def _derived_session_filter(session_ids: list[str], dialect: Dialect) -> str:
2404
+ """Return a SQL WHERE fragment that matches ``derived_metrics`` rows for the
2405
+ given *session_ids*.
2406
+
2407
+ ``derived_metrics.SessionId`` may be stored either as the bare UUID
2408
+ (e.g. ``d58b4e48-…``) **or** with an application-name prefix
2409
+ (e.g. ``noa-trip-planner-mas_d58b4e48-…``). Both forms are matched by
2410
+ combining an exact ``IN (…)`` clause with a ``LIKE '%_<uuid>'``
2411
+ suffix-match per ID.
2412
+
2413
+ The column name differs by dialect:
2414
+ * ClickHouse → ``SessionId``
2415
+ * SQLite → ``session_id``
2416
+ """
2417
+ col = "SessionId" if dialect is Dialect.CLICKHOUSE else "session_id"
2418
+ exact = ", ".join(f"'{s}'" for s in session_ids)
2419
+ like_clauses = " OR ".join(f"{col} LIKE '%_{s}'" for s in session_ids)
2420
+ return f"({col} IN ({exact}) OR {like_clauses})"
2421
+
2422
+
2423
+ def passive_eval_app_avg_by_sessions_query(
2424
+ dialect: Dialect = Dialect.CLICKHOUSE,
2425
+ *,
2426
+ session_ids: list[str],
2427
+ ):
2428
+ """Average ``PassiveEvalApp`` metric fields across sessions.
2429
+
2430
+ The ``Metrics`` column for these rows has the shape::
2431
+
2432
+ {
2433
+ "metric_name": "PassiveEvalApp",
2434
+ "value": {
2435
+ "eval.app.tool_calls": <int>,
2436
+ "eval.app.tool_fails": <int>,
2437
+ "eval.app.llm_calls": <int>,
2438
+ "eval.app.llm_fails": <int>,
2439
+ "eval.app.llm_cost": <float>,
2440
+ "eval.app.duration": <float>,
2441
+ "eval.app.graph_determinism": <float>,
2442
+ "eval.app.graph_dynamism": <float>,
2443
+ ...
2444
+ },
2445
+ "category": "application",
2446
+ ...
2447
+ }
2448
+
2449
+ Returns a single row with columns:
2450
+ ``tool_calls, tool_fails, llm_calls, llm_fails, llm_cost,
2451
+ duration, graph_determinism, graph_dynamism``.
2452
+ """
2453
+ sess_filter = _derived_session_filter(session_ids, dialect)
2454
+
2455
+ if dialect is Dialect.SQLITE:
2456
+ raw = (
2457
+ f"SELECT "
2458
+ f" AVG(CAST(json_extract(metrics, '$.value.\"eval.app.tool_calls\"') AS REAL)) AS tool_calls, "
2459
+ f" AVG(CAST(json_extract(metrics, '$.value.\"eval.app.tool_fails\"') AS REAL)) AS tool_fails, "
2460
+ f" AVG(CAST(json_extract(metrics, '$.value.\"eval.app.llm_calls\"') AS REAL)) AS llm_calls, "
2461
+ f" AVG(CAST(json_extract(metrics, '$.value.\"eval.app.llm_fails\"') AS REAL)) AS llm_fails, "
2462
+ f" AVG(CAST(json_extract(metrics, '$.value.\"eval.app.llm_cost\"') AS REAL)) AS llm_cost, "
2463
+ f" AVG(CAST(json_extract(metrics, '$.value.\"eval.app.duration\"') AS REAL)) AS duration, "
2464
+ f" AVG(CAST(json_extract(metrics, '$.value.\"eval.app.graph_determinism\"') AS REAL)) AS graph_determinism, "
2465
+ f" AVG(CAST(json_extract(metrics, '$.value.\"eval.app.graph_dynamism\"') AS REAL)) AS graph_dynamism "
2466
+ f"FROM derived_metrics "
2467
+ f"WHERE {sess_filter} "
2468
+ f" AND json_extract(metrics, '$.metric_name') = 'PassiveEvalApp'"
2469
+ )
2470
+ return text(raw)
2471
+
2472
+ # ClickHouse — value is a nested JSON object
2473
+ raw = (
2474
+ f"SELECT "
2475
+ f" AVG(JSONExtractFloat(Metrics, 'value', 'eval.app.tool_calls')) AS tool_calls, "
2476
+ f" AVG(JSONExtractFloat(Metrics, 'value', 'eval.app.tool_fails')) AS tool_fails, "
2477
+ f" AVG(JSONExtractFloat(Metrics, 'value', 'eval.app.llm_calls')) AS llm_calls, "
2478
+ f" AVG(JSONExtractFloat(Metrics, 'value', 'eval.app.llm_fails')) AS llm_fails, "
2479
+ f" AVG(JSONExtractFloat(Metrics, 'value', 'eval.app.llm_cost')) AS llm_cost, "
2480
+ f" AVG(JSONExtractFloat(Metrics, 'value', 'eval.app.duration')) AS duration, "
2481
+ f" AVG(JSONExtractFloat(Metrics, 'value', 'eval.app.graph_determinism')) AS graph_determinism, "
2482
+ f" AVG(JSONExtractFloat(Metrics, 'value', 'eval.app.graph_dynamism')) AS graph_dynamism "
2483
+ f"FROM derived_metrics "
2484
+ f"WHERE {sess_filter} "
2485
+ f" AND JSONExtract(Metrics, 'metric_name', 'String') = 'PassiveEvalApp'"
2486
+ )
2487
+ return text(raw)
2488
+
2489
+
2490
+ def passive_eval_agents_metrics_by_sessions_query(
2491
+ dialect: Dialect = Dialect.CLICKHOUSE,
2492
+ *,
2493
+ session_ids: list[str],
2494
+ ):
2495
+ """Return raw ``PassiveEvalAgents`` rows from ``derived_metrics``.
2496
+
2497
+ Returns columns ``session_id`` and ``metrics`` (or ClickHouse variants)
2498
+ so callers can parse the nested ``value.agents`` payload in Python.
2499
+ """
2500
+ sess_filter = _derived_session_filter(session_ids, dialect)
2501
+
2502
+ if dialect is Dialect.SQLITE:
2503
+ raw = (
2504
+ f"SELECT session_id, metrics "
2505
+ f"FROM derived_metrics "
2506
+ f"WHERE {sess_filter} "
2507
+ f" AND json_extract(metrics, '$.metric_name') = 'PassiveEvalAgents'"
2508
+ )
2509
+ return text(raw)
2510
+
2511
+ raw = (
2512
+ f"SELECT SessionId, Metrics "
2513
+ f"FROM derived_metrics "
2514
+ f"WHERE {sess_filter} "
2515
+ f" AND JSONExtract(Metrics, 'metric_name', 'String') = 'PassiveEvalAgents'"
2516
+ )
2517
+ return text(raw)
2518
+
2519
+
2520
+ def derived_metric_mce_avg_by_sessions_query(
2521
+ dialect: Dialect = Dialect.CLICKHOUSE,
2522
+ *,
2523
+ metric_name: str,
2524
+ session_ids: list[str],
2525
+ with_category: bool = True,
2526
+ ):
2527
+ """Average an MCE metric across sessions from ``derived_metrics``.
2528
+
2529
+ Mirrors the Go helpers
2530
+ ``GetDerivedMetricMCEAggregatedAvgBySessionIDs`` (when
2531
+ *with_category* is True) and
2532
+ ``GetDerivedMetricMCEAggregatedAvgBySessionIDsNoCategory`` (when
2533
+ *with_category* is False).
2534
+
2535
+ The query first averages per session, then averages across sessions.
2536
+
2537
+ ``derived_metrics.SessionId`` may carry an application-name prefix;
2538
+ :func:`_derived_session_filter` handles both bare UUIDs and prefixed forms.
2539
+
2540
+ Returns a single row with column ``metric_avg``.
2541
+ """
2542
+ sess_filter = _derived_session_filter(session_ids, dialect)
2543
+
2544
+ if dialect is Dialect.SQLITE:
2545
+ cat_filter = (
2546
+ "AND json_extract(metrics, '$.category') = 'agent'" if with_category else ""
2547
+ )
2548
+ raw = (
2549
+ f"SELECT CASE WHEN count(*) > 0 THEN AVG(MetricValuesAggregated) ELSE 0 END AS metric_avg "
2550
+ f"FROM ( "
2551
+ f" SELECT session_id, "
2552
+ f" CASE WHEN count(*) > 0 "
2553
+ f" THEN AVG(CAST(json_extract(metrics, '$.value') AS REAL)) "
2554
+ f" ELSE 0 END AS MetricValuesAggregated "
2555
+ f" FROM derived_metrics "
2556
+ f" WHERE {sess_filter} "
2557
+ f" {cat_filter} "
2558
+ f" AND json_extract(metrics, '$.metric_name') = '{metric_name}' "
2559
+ f" GROUP BY session_id "
2560
+ f")"
2561
+ )
2562
+ return text(raw)
2563
+
2564
+ # ClickHouse
2565
+ cat_filter = (
2566
+ "AND JSONExtract(Metrics, 'category', 'String') = 'agent'"
2567
+ if with_category
2568
+ else ""
2569
+ )
2570
+ raw = (
2571
+ f"SELECT if(count() > 0, AVG(MetricValuesAggregated), 0) AS metric_avg "
2572
+ f"FROM ( "
2573
+ f" SELECT SessionId, "
2574
+ f" if(count() > 0, AVG(JSONExtract(Metrics, 'value', 'Float64')), 0) AS MetricValuesAggregated "
2575
+ f" FROM derived_metrics "
2576
+ f" WHERE {sess_filter} "
2577
+ f" {cat_filter} "
2578
+ f" AND JSONExtract(Metrics, 'metric_name', 'String') = '{metric_name}' "
2579
+ f" GROUP BY SessionId "
2580
+ f")"
2581
+ )
2582
+ return text(raw)
2583
+
2584
+
2585
+ def session_metrics_by_name_query(
2586
+ dialect: Dialect = Dialect.NEO4J,
2587
+ *,
2588
+ session_ids: list[str],
2589
+ metric_names: list[str],
2590
+ ):
2591
+ """Build a Neo4j Cypher query for per-session ``MetricResult`` nodes by name.
2592
+
2593
+ Matches ``MetricResult`` nodes that ``measures`` a ``Session`` and are
2594
+ ``ofMetricType`` a ``Metric`` definition whose ``name`` is in *metric_names*.
2595
+
2596
+ Returns a ``(cypher_string, params_dict)`` tuple. Each result row
2597
+ has columns: ``sid, metric_name, metric_results``.
2598
+ """
2599
+ if dialect is not Dialect.NEO4J:
2600
+ raise NotImplementedError(
2601
+ f"session_metrics_by_name_query: dialect {dialect!r} not supported"
2602
+ )
2603
+ stmt = """
2604
+ MATCH (r:MetricResult)-[:measures]->(s:Session), (r)-[:ofMetricType]->(m:Metric)
2605
+ WHERE s.sessionId IN $session_ids
2606
+ AND m.name IN $metric_names
2607
+ WITH s.sessionId AS sid, m.name AS metric_name,
2608
+ collect(r.result) AS metric_results
2609
+ RETURN sid, metric_name, metric_results
2610
+ """
2611
+ return stmt, {"session_ids": session_ids, "metric_names": metric_names}
2612
+
2613
+
2614
+ def all_mce_metrics_by_sessions_query(
2615
+ dialect: Dialect = Dialect.CLICKHOUSE,
2616
+ *,
2617
+ session_ids: list[str],
2618
+ ):
2619
+ """Fetch all five MCE performance metrics for a set of sessions in one query.
2620
+
2621
+ ClickHouse only. Returns one row per ``SessionId`` with columns:
2622
+ ``session_id, workflow_efficiency, app_groundedness, answer_relevancy,
2623
+ response_completeness, tool_utilization_accuracy``.
2624
+
2625
+ Each column holds the per-session average value for that metric (0 when the
2626
+ session has no rows for that metric). The caller is responsible for
2627
+ aggregating across sessions to produce a per-application average.
2628
+
2629
+ The five metrics and their ``with_category`` semantics:
2630
+ * ``WorkflowEfficiency`` — category = 'agent'
2631
+ * ``GroundednessMetric`` — category = 'agent'
2632
+ * ``AnswerRelevancyMetric`` — no category filter
2633
+ * ``ResponseCompleteness`` — category = 'agent'
2634
+ * ``ToolUtilizationAccuracy``— no category filter
2635
+ """
2636
+ sess_filter = _derived_session_filter(session_ids, dialect)
2637
+
2638
+ def _cond_avg(metric: str, with_cat: bool) -> str:
2639
+ """Build a ``if(countIf(…) > 0, avgIf(…), NULL)`` fragment.
2640
+
2641
+ Returns NULL (not 0) when the session has no rows for this metric so
2642
+ that sessions lacking a particular metric are excluded from the
2643
+ per-metric average in the caller — matching the behaviour of the
2644
+ non-optimised ``derived_metric_mce_avg_by_sessions_query``.
2645
+ """
2646
+ name_cond = f"JSONExtract(Metrics, 'metric_name', 'String') = '{metric}'"
2647
+ cat_cond = (
2648
+ " AND JSONExtract(Metrics, 'category', 'String') = 'agent'"
2649
+ if with_cat
2650
+ else ""
2651
+ )
2652
+ val = "JSONExtract(Metrics, 'value', 'Float64')"
2653
+ full_cond = f"{name_cond}{cat_cond}"
2654
+ return f"if(countIf({full_cond}) > 0, avgIf({val}, {full_cond}), NULL)"
2655
+
2656
+ raw = (
2657
+ f"SELECT "
2658
+ f" SessionId AS session_id, "
2659
+ f" {_cond_avg('WorkflowEfficiency', True)} AS workflow_efficiency, "
2660
+ f" {_cond_avg('GroundednessMetric', True)} AS app_groundedness, "
2661
+ f" {_cond_avg('AnswerRelevancyMetric', False)} AS answer_relevancy, "
2662
+ f" {_cond_avg('ResponseCompleteness', True)} AS response_completeness, "
2663
+ f" {_cond_avg('ToolUtilizationAccuracy', False)} AS tool_utilization_accuracy "
2664
+ f"FROM derived_metrics "
2665
+ f"WHERE {sess_filter} "
2666
+ f" AND JSONExtract(Metrics, 'metric_name', 'String') IN ("
2667
+ f" 'WorkflowEfficiency', 'GroundednessMetric', 'AnswerRelevancyMetric', "
2668
+ f" 'ResponseCompleteness', 'ToolUtilizationAccuracy'"
2669
+ f" ) "
2670
+ f"GROUP BY SessionId"
2671
+ )
2672
+ return text(raw)
2673
+
2674
+
2675
+ def derived_metric_sdk_avg_by_sessions_query(
2676
+ dialect: Dialect = Dialect.CLICKHOUSE,
2677
+ *,
2678
+ metric_name: str,
2679
+ session_ids: list[str],
2680
+ ):
2681
+ """Average an SDK metric across sessions from ``derived_metrics``.
2682
+
2683
+ Mirrors the Go helper ``GetDerivedMetricSDKAggregatedAvgBySessionIDs``.
2684
+
2685
+ SDK metrics have ``metric_name = 'PassiveEvalApp'`` and the
2686
+ ``value`` field is a JSON **string** containing nested keys such as
2687
+ ``eval.app.llm_cost``, ``eval.app.llm_calls``, etc.
2688
+
2689
+ Returns a single row with column ``metric_avg``.
2690
+ """
2691
+ ids_literal = ", ".join(f"'{s}'" for s in session_ids)
2692
+
2693
+ if dialect is Dialect.SQLITE:
2694
+ raw = (
2695
+ f"SELECT CASE WHEN count(*) > 0 "
2696
+ f" THEN AVG(CAST(json_extract(json_extract(metrics, '$.value'), '$.{metric_name}') AS REAL)) "
2697
+ f" ELSE 0 END AS metric_avg "
2698
+ f"FROM derived_metrics "
2699
+ f"WHERE session_id IN ({ids_literal}) "
2700
+ f" AND json_extract(metrics, '$.metric_name') = 'PassiveEvalApp' "
2701
+ f" AND json_extract(json_extract(metrics, '$.value'), '$.{metric_name}') IS NOT NULL"
2702
+ )
2703
+ return text(raw)
2704
+
2705
+ # ClickHouse
2706
+ raw = (
2707
+ f"SELECT if(count() > 0, "
2708
+ f" AVG(JSONExtract(JSONExtract(Metrics, 'value', 'String'), '{metric_name}', 'Float64')), 0) "
2709
+ f" AS metric_avg "
2710
+ f"FROM derived_metrics "
2711
+ f"WHERE SessionId IN ({ids_literal}) "
2712
+ f" AND JSONExtract(Metrics, 'metric_name', 'String') = 'PassiveEvalApp' "
2713
+ f" AND JSONExtract(JSONExtract(Metrics, 'value', 'String'), '{metric_name}', 'Float64') IS NOT NULL"
2714
+ )
2715
+ return text(raw)
2716
+
2717
+
2718
+ def derived_metric_sdk_sum_fails_by_sessions_query(
2719
+ dialect: Dialect = Dialect.CLICKHOUSE,
2720
+ *,
2721
+ session_ids: list[str],
2722
+ llm_fails_key: str = "eval.app.llm_fails",
2723
+ tool_fails_key: str = "eval.app.tool_fails",
2724
+ ):
2725
+ """Sum LLM and tool failure counts from SDK metrics.
2726
+
2727
+ Mirrors the Go helper ``GetDerivedMetricSDKAggregatedSumOfFailsBySessionIDs``.
2728
+
2729
+ Returns a single row with columns ``llm_fails`` and ``tool_fails``.
2730
+ """
2731
+ ids_literal = ", ".join(f"'{s}'" for s in session_ids)
2732
+
2733
+ if dialect is Dialect.SQLITE:
2734
+ raw = (
2735
+ f"SELECT "
2736
+ f" CASE WHEN count(*) > 0 "
2737
+ f" THEN COALESCE(SUM(CAST(json_extract(json_extract(metrics, '$.value'), '$.{llm_fails_key}') AS REAL)), 0) "
2738
+ f" ELSE 0 END AS llm_fails, "
2739
+ f" CASE WHEN count(*) > 0 "
2740
+ f" THEN COALESCE(SUM(CAST(json_extract(json_extract(metrics, '$.value'), '$.{tool_fails_key}') AS REAL)), 0) "
2741
+ f" ELSE 0 END AS tool_fails "
2742
+ f"FROM derived_metrics "
2743
+ f"WHERE session_id IN ({ids_literal}) "
2744
+ f" AND json_extract(metrics, '$.metric_name') = 'PassiveEvalApp'"
2745
+ )
2746
+ return text(raw)
2747
+
2748
+ # ClickHouse
2749
+ raw = (
2750
+ f"SELECT "
2751
+ f" if(count() > 0, SUM(JSONExtract(JSONExtract(Metrics, 'value', 'String'), '{llm_fails_key}', 'Float64')), 0) AS llm_fails, "
2752
+ f" if(count() > 0, SUM(JSONExtract(JSONExtract(Metrics, 'value', 'String'), '{tool_fails_key}', 'Float64')), 0) AS tool_fails "
2753
+ f"FROM derived_metrics "
2754
+ f"WHERE SessionId IN ({ids_literal}) "
2755
+ f" AND JSONExtract(Metrics, 'metric_name', 'String') = 'PassiveEvalApp'"
2756
+ )
2757
+ return text(raw)
2758
+
2759
+
2760
+ def most_frequent_errors_query(
2761
+ dialect: Dialect = Dialect.CLICKHOUSE,
2762
+ *,
2763
+ session_ids: list[str],
2764
+ top_n: int = 3,
2765
+ ):
2766
+ """Return the *top_n* most frequent error span names for the given sessions.
2767
+
2768
+ Mirrors the Go helper ``GetMostFrequentErrorsBySessionIDs``.
2769
+
2770
+ Returns rows with columns ``error_name`` and ``cnt``.
2771
+ """
2772
+ r = _refs(dialect)
2773
+
2774
+ status_col = r.status_code
2775
+ # Use status_message for error name when available, fall back to span_name
2776
+ if dialect is Dialect.SQLITE:
2777
+ error_name_expr = func.coalesce(
2778
+ column("status_message"),
2779
+ r.span_name,
2780
+ )
2781
+ else:
2782
+ error_name_expr = func.coalesce(
2783
+ column("StatusMessage"),
2784
+ r.span_name,
2785
+ )
2786
+
2787
+ return (
2788
+ select(
2789
+ error_name_expr.label("error_name"),
2790
+ func.count().label("cnt"),
2791
+ )
2792
+ .select_from(r.tbl)
2793
+ .where(r.session_id.in_(session_ids))
2794
+ .where(status_col == "Error")
2795
+ .where(error_name_expr != "")
2796
+ .group_by(error_name_expr)
2797
+ .order_by(func.count().desc())
2798
+ .limit(top_n)
2799
+ )
2800
+
2801
+
2802
+ def derived_metric_sdk_avg_by_sessions_and_agent_query(
2803
+ dialect: Dialect = Dialect.CLICKHOUSE,
2804
+ *,
2805
+ metric_name: str,
2806
+ session_ids: list[str],
2807
+ agent_id: str,
2808
+ ):
2809
+ """Average an SDK metric across sessions filtered by agent.
2810
+
2811
+ Like :func:`derived_metric_sdk_avg_by_sessions_query` but additionally
2812
+ filters rows where the ``agent_id`` column matches *agent_id*.
2813
+
2814
+ Returns a single row with column ``metric_avg``.
2815
+ """
2816
+ ids_literal = ", ".join(f"'{s}'" for s in session_ids)
2817
+
2818
+ if dialect is Dialect.SQLITE:
2819
+ raw = (
2820
+ f"SELECT CASE WHEN count(*) > 0 "
2821
+ f" THEN AVG(CAST(json_extract(json_extract(metrics, '$.value'), '$.{metric_name}') AS REAL)) "
2822
+ f" ELSE 0 END AS metric_avg "
2823
+ f"FROM derived_metrics "
2824
+ f"WHERE session_id IN ({ids_literal}) "
2825
+ f" AND json_extract(metrics, '$.metric_name') = 'PassiveEvalApp' "
2826
+ f" AND json_extract(json_extract(metrics, '$.value'), '$.{metric_name}') IS NOT NULL "
2827
+ f" AND agent_id = '{agent_id}'"
2828
+ )
2829
+ return text(raw)
2830
+
2831
+ # ClickHouse
2832
+ raw = (
2833
+ f"SELECT if(count() > 0, "
2834
+ f" AVG(JSONExtract(JSONExtract(Metrics, 'value', 'String'), '{metric_name}', 'Float64')), 0) "
2835
+ f" AS metric_avg "
2836
+ f"FROM derived_metrics "
2837
+ f"WHERE SessionId IN ({ids_literal}) "
2838
+ f" AND JSONExtract(Metrics, 'metric_name', 'String') = 'PassiveEvalApp' "
2839
+ f" AND JSONExtract(JSONExtract(Metrics, 'value', 'String'), '{metric_name}', 'Float64') IS NOT NULL "
2840
+ f" AND agent_id = '{agent_id}'"
2841
+ )
2842
+ return text(raw)
2843
+
2844
+
2845
+ def derived_metric_sdk_sum_by_sessions_and_agent_query(
2846
+ dialect: Dialect = Dialect.CLICKHOUSE,
2847
+ *,
2848
+ metric_name: str,
2849
+ session_ids: list[str],
2850
+ agent_id: str,
2851
+ ):
2852
+ """Sum an SDK metric across sessions filtered by agent.
2853
+
2854
+ Like the avg variant but uses ``SUM`` instead of ``AVG``.
2855
+
2856
+ Returns a single row with column ``metric_sum``.
2857
+ """
2858
+ ids_literal = ", ".join(f"'{s}'" for s in session_ids)
2859
+
2860
+ if dialect is Dialect.SQLITE:
2861
+ raw = (
2862
+ f"SELECT CASE WHEN count(*) > 0 "
2863
+ f" THEN COALESCE(SUM(CAST(json_extract(json_extract(metrics, '$.value'), '$.{metric_name}') AS REAL)), 0) "
2864
+ f" ELSE 0 END AS metric_sum "
2865
+ f"FROM derived_metrics "
2866
+ f"WHERE session_id IN ({ids_literal}) "
2867
+ f" AND json_extract(metrics, '$.metric_name') = 'PassiveEvalApp' "
2868
+ f" AND json_extract(json_extract(metrics, '$.value'), '$.{metric_name}') IS NOT NULL "
2869
+ f" AND agent_id = '{agent_id}'"
2870
+ )
2871
+ return text(raw)
2872
+
2873
+ # ClickHouse
2874
+ raw = (
2875
+ f"SELECT if(count() > 0, "
2876
+ f" COALESCE(SUM(JSONExtract(JSONExtract(Metrics, 'value', 'String'), '{metric_name}', 'Float64')), 0), 0) "
2877
+ f" AS metric_sum "
2878
+ f"FROM derived_metrics "
2879
+ f"WHERE SessionId IN ({ids_literal}) "
2880
+ f" AND JSONExtract(Metrics, 'metric_name', 'String') = 'PassiveEvalApp' "
2881
+ f" AND JSONExtract(JSONExtract(Metrics, 'value', 'String'), '{metric_name}', 'Float64') IS NOT NULL "
2882
+ f" AND agent_id = '{agent_id}'"
2883
+ )
2884
+ return text(raw)
2885
+
2886
+
2887
+ def derived_metric_sdk_sum_fails_by_sessions_and_agent_query(
2888
+ dialect: Dialect = Dialect.CLICKHOUSE,
2889
+ *,
2890
+ session_ids: list[str],
2891
+ agent_id: str,
2892
+ llm_fails_key: str = "eval.app.llm_fails",
2893
+ tool_fails_key: str = "eval.app.tool_fails",
2894
+ ):
2895
+ """Sum LLM and tool failure counts from SDK metrics, filtered by agent.
2896
+
2897
+ Returns a single row with columns ``llm_fails`` and ``tool_fails``.
2898
+ """
2899
+ ids_literal = ", ".join(f"'{s}'" for s in session_ids)
2900
+
2901
+ if dialect is Dialect.SQLITE:
2902
+ raw = (
2903
+ f"SELECT "
2904
+ f" CASE WHEN count(*) > 0 "
2905
+ f" THEN COALESCE(SUM(CAST(json_extract(json_extract(metrics, '$.value'), '$.{llm_fails_key}') AS REAL)), 0) "
2906
+ f" ELSE 0 END AS llm_fails, "
2907
+ f" CASE WHEN count(*) > 0 "
2908
+ f" THEN COALESCE(SUM(CAST(json_extract(json_extract(metrics, '$.value'), '$.{tool_fails_key}') AS REAL)), 0) "
2909
+ f" ELSE 0 END AS tool_fails "
2910
+ f"FROM derived_metrics "
2911
+ f"WHERE session_id IN ({ids_literal}) "
2912
+ f" AND json_extract(metrics, '$.metric_name') = 'PassiveEvalApp' "
2913
+ f" AND agent_id = '{agent_id}'"
2914
+ )
2915
+ return text(raw)
2916
+
2917
+ # ClickHouse
2918
+ raw = (
2919
+ f"SELECT "
2920
+ f" if(count() > 0, SUM(JSONExtract(JSONExtract(Metrics, 'value', 'String'), '{llm_fails_key}', 'Float64')), 0) AS llm_fails, "
2921
+ f" if(count() > 0, SUM(JSONExtract(JSONExtract(Metrics, 'value', 'String'), '{tool_fails_key}', 'Float64')), 0) AS tool_fails "
2922
+ f"FROM derived_metrics "
2923
+ f"WHERE SessionId IN ({ids_literal}) "
2924
+ f" AND JSONExtract(Metrics, 'metric_name', 'String') = 'PassiveEvalApp' "
2925
+ f" AND agent_id = '{agent_id}'"
2926
+ )
2927
+ return text(raw)
2928
+
2929
+
2930
+ def derived_metric_mce_avg_by_sessions_and_agent_query(
2931
+ dialect: Dialect = Dialect.CLICKHOUSE,
2932
+ *,
2933
+ metric_name: str,
2934
+ session_ids: list[str],
2935
+ agent_id: str,
2936
+ with_category: bool = True,
2937
+ ):
2938
+ """Average an MCE metric across sessions filtered by agent.
2939
+
2940
+ Like :func:`derived_metric_mce_avg_by_sessions_query` but additionally
2941
+ filters rows where the ``agent_id`` column matches *agent_id*.
2942
+
2943
+ Returns a single row with column ``metric_avg``.
2944
+ """
2945
+ sess_filter = _derived_session_filter(session_ids, dialect)
2946
+
2947
+ if dialect is Dialect.SQLITE:
2948
+ cat_filter = (
2949
+ "AND json_extract(metrics, '$.category') = 'agent'" if with_category else ""
2950
+ )
2951
+ raw = (
2952
+ f"SELECT CASE WHEN count(*) > 0 THEN AVG(MetricValuesAggregated) ELSE 0 END AS metric_avg "
2953
+ f"FROM ( "
2954
+ f" SELECT session_id, "
2955
+ f" CASE WHEN count(*) > 0 "
2956
+ f" THEN AVG(CAST(json_extract(metrics, '$.value') AS REAL)) "
2957
+ f" ELSE 0 END AS MetricValuesAggregated "
2958
+ f" FROM derived_metrics "
2959
+ f" WHERE {sess_filter} "
2960
+ f" {cat_filter} "
2961
+ f" AND json_extract(metrics, '$.metric_name') = '{metric_name}' "
2962
+ f" AND agent_id = '{agent_id}' "
2963
+ f" GROUP BY session_id "
2964
+ f")"
2965
+ )
2966
+ return text(raw)
2967
+
2968
+ # ClickHouse
2969
+ cat_filter = (
2970
+ "AND JSONExtract(Metrics, 'category', 'String') = 'agent'"
2971
+ if with_category
2972
+ else ""
2973
+ )
2974
+ raw = (
2975
+ f"SELECT if(count() > 0, AVG(MetricValuesAggregated), 0) AS metric_avg "
2976
+ f"FROM ( "
2977
+ f" SELECT SessionId, "
2978
+ f" if(count() > 0, AVG(JSONExtract(Metrics, 'value', 'Float64')), 0) AS MetricValuesAggregated "
2979
+ f" FROM derived_metrics "
2980
+ f" WHERE {sess_filter} "
2981
+ f" {cat_filter} "
2982
+ f" AND JSONExtract(Metrics, 'metric_name', 'String') = '{metric_name}' "
2983
+ f" AND agent_id = '{agent_id}' "
2984
+ f" GROUP BY SessionId "
2985
+ f")"
2986
+ )
2987
+ return text(raw)
2988
+
2989
+
2990
+ def agent_durations_sorted_query(
2991
+ dialect: Dialect = Dialect.CLICKHOUSE,
2992
+ *,
2993
+ session_ids: list[str],
2994
+ agent_id: str,
2995
+ ):
2996
+ """Return sorted durations (ms) for ``.agent`` spans, for percentile computation.
2997
+
2998
+ Returns rows with column ``duration_ms``, ordered ascending.
2999
+ """
3000
+ r = _refs(dialect)
3001
+
3002
+ return (
3003
+ select(
3004
+ (r.duration / literal_column("1000000")).label("duration_ms"),
3005
+ )
3006
+ .select_from(r.tbl)
3007
+ .where(r.session_id.in_(session_ids))
3008
+ .where(r.agent_id == agent_id)
3009
+ .where(r.span_name.like("%.agent"))
3010
+ .order_by(r.duration.asc())
3011
+ )
3012
+
3013
+
3014
+ def most_frequent_errors_by_agent_query(
3015
+ dialect: Dialect = Dialect.CLICKHOUSE,
3016
+ *,
3017
+ session_ids: list[str],
3018
+ agent_id: str,
3019
+ top_n: int = -1,
3020
+ ):
3021
+ """Return the most frequent error span names for a specific agent.
3022
+
3023
+ When *top_n* is ``-1`` (default), all errors are returned (no limit).
3024
+
3025
+ Returns rows with columns ``error_name`` and ``cnt``.
3026
+ """
3027
+ r = _refs(dialect)
3028
+
3029
+ if dialect is Dialect.SQLITE:
3030
+ error_name_expr = func.coalesce(
3031
+ column("status_message"),
3032
+ r.span_name,
3033
+ )
3034
+ else:
3035
+ error_name_expr = func.coalesce(
3036
+ column("StatusMessage"),
3037
+ r.span_name,
3038
+ )
3039
+
3040
+ stmt = (
3041
+ select(
3042
+ error_name_expr.label("error_name"),
3043
+ func.count().label("cnt"),
3044
+ )
3045
+ .select_from(r.tbl)
3046
+ .where(r.session_id.in_(session_ids))
3047
+ .where(r.agent_id == agent_id)
3048
+ .where(r.status_code == "Error")
3049
+ .where(error_name_expr != "")
3050
+ .group_by(error_name_expr)
3051
+ .order_by(func.count().desc())
3052
+ )
3053
+
3054
+ if top_n > 0:
3055
+ stmt = stmt.limit(top_n)
3056
+
3057
+ return stmt
3058
+
3059
+
3060
+ # ── SLIM / agentic-protocols metrics (ClickHouse only) ───────────────────────
3061
+
3062
+ _SLIM_AGENT_ATTR = literal_column("Attributes['agent']")
3063
+
3064
+
3065
+ def slim_agent_names_sum_query(
3066
+ *,
3067
+ app_prefix: str,
3068
+ metric_name: str,
3069
+ start_time: str,
3070
+ end_time: str,
3071
+ ):
3072
+ """Return distinct agent names from ``otel_metrics_sum`` for *app_prefix*.
3073
+
3074
+ Columns: ``agent``.
3075
+ """
3076
+ return (
3077
+ select(func.distinct(_SLIM_AGENT_ATTR).label("agent"))
3078
+ .select_from(_ch_metrics_sum)
3079
+ .where(_SLIM_AGENT_ATTR.like(app_prefix + "%"))
3080
+ .where(_ch_metrics_sum.c.MetricName == metric_name)
3081
+ .where(_ch_metrics_sum.c.TimeUnix >= start_time)
3082
+ .where(_ch_metrics_sum.c.TimeUnix <= end_time)
3083
+ )
3084
+
3085
+
3086
+ def slim_sum_values_by_agent_query(
3087
+ *,
3088
+ agent_name: str,
3089
+ metric_name: str,
3090
+ start_time: str,
3091
+ end_time: str,
3092
+ ):
3093
+ """Return ordered distinct ``Value`` rows from ``otel_metrics_sum`` for one agent.
3094
+
3095
+ Columns: ``value``.
3096
+ """
3097
+ return (
3098
+ select(func.distinct(_ch_metrics_sum.c.Value).label("value"))
3099
+ .select_from(_ch_metrics_sum)
3100
+ .where(_SLIM_AGENT_ATTR == agent_name)
3101
+ .where(_ch_metrics_sum.c.MetricName == metric_name)
3102
+ .where(_ch_metrics_sum.c.TimeUnix >= start_time)
3103
+ .where(_ch_metrics_sum.c.TimeUnix <= end_time)
3104
+ .order_by(_ch_metrics_sum.c.TimeUnix.asc())
3105
+ )
3106
+
3107
+
3108
+ def slim_agent_names_histogram_query(
3109
+ *,
3110
+ app_prefix: str,
3111
+ metric_name: str,
3112
+ start_time: str,
3113
+ end_time: str,
3114
+ ):
3115
+ """Return distinct agent names from ``otel_metrics_histogram`` for *app_prefix*.
3116
+
3117
+ Columns: ``agent``.
3118
+ """
3119
+ return (
3120
+ select(func.distinct(_SLIM_AGENT_ATTR).label("agent"))
3121
+ .select_from(_ch_metrics_histogram)
3122
+ .where(_SLIM_AGENT_ATTR.like(app_prefix + "%"))
3123
+ .where(_ch_metrics_histogram.c.MetricName == metric_name)
3124
+ .where(_ch_metrics_histogram.c.TimeUnix >= start_time)
3125
+ .where(_ch_metrics_histogram.c.TimeUnix <= end_time)
3126
+ )
3127
+
3128
+
3129
+ def slim_histogram_values_by_agent_query(
3130
+ *,
3131
+ agent_name: str,
3132
+ metric_name: str,
3133
+ start_time: str,
3134
+ end_time: str,
3135
+ ):
3136
+ """Return ordered distinct ``(Count, Sum)`` rows from ``otel_metrics_histogram`` for one agent.
3137
+
3138
+ Columns: ``count``, ``sum``.
3139
+ """
3140
+ return (
3141
+ select(
3142
+ func.distinct(_ch_metrics_histogram.c.Count).label("count"),
3143
+ _ch_metrics_histogram.c.Sum.label("sum"),
3144
+ )
3145
+ .select_from(_ch_metrics_histogram)
3146
+ .where(_SLIM_AGENT_ATTR == agent_name)
3147
+ .where(_ch_metrics_histogram.c.MetricName == metric_name)
3148
+ .where(_ch_metrics_histogram.c.TimeUnix >= start_time)
3149
+ .where(_ch_metrics_histogram.c.TimeUnix <= end_time)
3150
+ .order_by(_ch_metrics_histogram.c.TimeUnix.asc())
3151
+ )
3152
+
3153
+
3154
+ def neo4j_sessions_with_cognitive_observability_query(
3155
+ *,
3156
+ application_id: str,
3157
+ start_epoch: Optional[float] = None,
3158
+ end_epoch: Optional[float] = None,
3159
+ session_id: Optional[str] = None,
3160
+ ):
3161
+ """Build a Neo4j query returning sessions with cognitive observability data.
3162
+
3163
+ One row per session: ``sessionId, startTime, duration, cost, agents, tokens,
3164
+ sessionMetrics, failures``. ``failures`` holds the raw properties of the
3165
+ session's ``CognitiveFailureReport`` nodes (one per failure), which the cognitive failure worker
3166
+ attaches to the session by ``reportsOn``.
3167
+ """
3168
+ stmt = """
3169
+ MATCH (s:Session)-[:executesSession]->(ma:MAS) WHERE ma.id = $application_id
3170
+ WITH DISTINCT s
3171
+ WHERE ($start_epoch IS NULL OR toFloat(s.startTime) >= $start_epoch)
3172
+ AND ($end_epoch IS NULL OR toFloat(s.startTime) <= $end_epoch)
3173
+ AND ($session_id IS NULL OR s.sessionId = $session_id)
3174
+ OPTIONAL MATCH (s)-[]-(mCost:Metric) WHERE mCost.metricName = 'Cost'
3175
+ WITH s, head(collect(DISTINCT mCost.metricResult)) AS cost
3176
+ OPTIONAL MATCH (s)-[]-(mDuration:Metric) WHERE mDuration.metricName = 'Duration'
3177
+ WITH s, cost, head(collect(DISTINCT mDuration.metricResult)) AS duration
3178
+ OPTIONAL MATCH (s)-[:hasMASCall]->(:MASCall)-[:hasAgentCall]->(ac:AgentCall)
3179
+ OPTIONAL MATCH (ac)-[:executesAgent]->(agentNode:Agent)
3180
+ OPTIONAL MATCH (ac)-[:hasLLMCall]->(l:LLMCall)
3181
+ WITH
3182
+ s,
3183
+ cost,
3184
+ duration,
3185
+ [a IN collect(DISTINCT agentNode.name) WHERE a IS NOT NULL] AS agents,
3186
+ coalesce(sum(coalesce(l.completionTokenCount, 0)
3187
+ + coalesce(l.promptTokenCount, 0)), 0) AS tokens
3188
+ OPTIONAL MATCH (s)-[:hasMetric]->(sm:Metric)
3189
+ WITH
3190
+ s,
3191
+ cost,
3192
+ duration,
3193
+ agents,
3194
+ tokens,
3195
+ [x IN collect(DISTINCT {
3196
+ name: sm.metricName,
3197
+ result: sm.metricResult,
3198
+ value: sm.value,
3199
+ provider: sm.provider,
3200
+ metric_id: coalesce(sm.metricId, sm.metricName),
3201
+ source: sm.source,
3202
+ reasoning: sm.reasoning
3203
+ }) WHERE x.name IS NOT NULL] AS sessionMetrics
3204
+ OPTIONAL MATCH (f:CognitiveFailureReport)-[:reportsOn]->(s)
3205
+ WITH
3206
+ s,
3207
+ cost,
3208
+ duration,
3209
+ agents,
3210
+ tokens,
3211
+ sessionMetrics,
3212
+ [x IN collect(DISTINCT properties(f)) WHERE x IS NOT NULL] AS failures
3213
+ OPTIONAL MATCH (s)-[]-(cpr:CognitionProtocolReport)
3214
+ WITH
3215
+ s,
3216
+ cost,
3217
+ duration,
3218
+ agents,
3219
+ tokens,
3220
+ sessionMetrics,
3221
+ failures,
3222
+ [x IN collect(DISTINCT properties(cpr)) WHERE x IS NOT NULL] AS cognitionProtocolReports
3223
+ RETURN
3224
+ s.sessionId AS sessionId,
3225
+ s.startTime AS startTime,
3226
+ duration,
3227
+ cost,
3228
+ agents,
3229
+ tokens,
3230
+ sessionMetrics,
3231
+ failures,
3232
+ cognitionProtocolReports
3233
+ ORDER BY s.startTime DESC
3234
+ """
3235
+ return stmt, {
3236
+ "application_id": application_id,
3237
+ "start_epoch": start_epoch,
3238
+ "end_epoch": end_epoch,
3239
+ "session_id": session_id,
3240
+ }
3241
+
3242
+
3243
+ def neo4j_session_cognition_protocol_reports_query(*, session_id: str):
3244
+ """Build a Neo4j query returning the Cognition protocol reports of a session.
3245
+
3246
+ One row with ``found`` (whether the session exists), ``cognitionProtocolReports`` (the properties of the
3247
+ session's ``CognitionProtocolReport``: protocols enabled and activated) and ``executionReports`` (one entry
3248
+ per ``CognitionProtocolExecutionReport``: its ``report`` properties and its ``metrics``, the
3249
+ ``MetricResult`` nodes that measure it, with their ``Metric`` definition).
3250
+ """
3251
+ stmt = """
3252
+ OPTIONAL MATCH (s:Session {sessionId: $session_id})
3253
+ CALL (s) {
3254
+ OPTIONAL MATCH (r:CognitionProtocolReport)-[:reportsOn]->(s)
3255
+ RETURN [x IN collect(DISTINCT properties(r)) WHERE x IS NOT NULL] AS cognitionProtocolReports
3256
+ }
3257
+ CALL (s) {
3258
+ OPTIONAL MATCH (p:CognitionProtocolExecutionReport)-[:reportsOn]->(s)
3259
+ CALL (p) {
3260
+ OPTIONAL MATCH (m:MetricResult)-[:measures]->(p)
3261
+ OPTIONAL MATCH (m)-[:ofMetricType]->(d:Metric)
3262
+ RETURN [x IN collect(DISTINCT CASE WHEN m IS NULL THEN NULL ELSE {
3263
+ name: coalesce(d.name, m.name),
3264
+ result: m.result,
3265
+ reasoning: m.reasoning,
3266
+ timestamp: m.timestamp,
3267
+ provider: d.metricProvider,
3268
+ unit: d.unit
3269
+ } END) WHERE x IS NOT NULL] AS metrics
3270
+ }
3271
+ RETURN [x IN collect(CASE WHEN p IS NULL THEN NULL ELSE {
3272
+ report: properties(p),
3273
+ metrics: metrics
3274
+ } END) WHERE x IS NOT NULL] AS executionReports
3275
+ }
3276
+ RETURN s IS NOT NULL AS found, cognitionProtocolReports, executionReports
3277
+ """
3278
+ return stmt, {"session_id": session_id}