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
scope/providers/kg.py ADDED
@@ -0,0 +1,702 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """SCOPEKGProvider — Neo4j-backed KGProvider + DataProvider.
4
+
5
+ Handles all knowledge-graph read operations: generic node queries,
6
+ session / agent / LLM-call listings, and execution-span fetching for
7
+ the MCE computation engine.
8
+
9
+ All Cypher is centralised in ``scope.query_builders.kg``. No raw
10
+ query strings live in this file.
11
+
12
+ Query execution uses an ontology-first / workaround-fallback strategy
13
+ governed by :class:`~scope.workarounds.KGWorkaroundsConfig`. See
14
+ ``scope/workarounds.py`` for the full workaround catalogue.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import logging
20
+ import os
21
+ import re
22
+ from dataclasses import replace
23
+ from typing import Any
24
+
25
+ from scope.connectors.base import Connector
26
+ from scope.interfaces import DataProvider, KGProvider
27
+ from scope.interfaces.models import QueryOptions, RetrievalRequest, RetrievalScope
28
+ from scope.query_builders import kg as kg_qb
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ # Valid Neo4j node label: starts with letter or underscore, alphanumeric + underscore only.
33
+ _LABEL_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
34
+
35
+
36
+ def _resolve_connector(
37
+ db: Connector | None,
38
+ connector: Connector | None,
39
+ *,
40
+ host: str | None = None,
41
+ username: str | None = None,
42
+ password: str | None = None,
43
+ database: str | None = None,
44
+ ) -> Connector:
45
+ """Return the supplied connector, or build one from environment variables."""
46
+ resolved = db or connector
47
+ if resolved is None:
48
+ from scope.connectors.neo4j import Neo4JConnector
49
+ from scope.core.config import resolve_neo4j_auth
50
+
51
+ resolved_host = (
52
+ host or os.getenv("NEO4J_HOST") or os.getenv("KG_DB_HOST") or "localhost"
53
+ )
54
+ if ":" in resolved_host and not resolved_host.startswith("bolt://"):
55
+ hostname, _, port_str = resolved_host.rpartition(":")
56
+ try:
57
+ port = int(port_str)
58
+ except ValueError:
59
+ hostname, port = resolved_host, 7687
60
+ else:
61
+ hostname, port = resolved_host, 7687
62
+ default_username, default_password = resolve_neo4j_auth()
63
+ resolved = Neo4JConnector(
64
+ host=hostname,
65
+ port=port,
66
+ username=(username or os.getenv("KG_DB_USER") or default_username),
67
+ password=(password or os.getenv("KG_DB_PASSWORD") or default_password),
68
+ database=database
69
+ or os.getenv("NEO4J_DATABASE")
70
+ or os.getenv("KG_DB_NAME")
71
+ or "neo4j",
72
+ )
73
+ resolved.ensure_connected()
74
+ return resolved
75
+
76
+
77
+ class SCOPEKGProvider(KGProvider, DataProvider):
78
+ """Neo4j-backed KGProvider + DataProvider.
79
+
80
+ *KGProvider* — generic node queries, session / agent / LLM-call listings.
81
+ *DataProvider* — execution-span fetching (``fetch``, ``resolve_session_id``)
82
+ used by the MCE computation engine.
83
+ """
84
+
85
+ def __init__(
86
+ self,
87
+ db: Connector | None = None,
88
+ *,
89
+ connector: Connector | None = None,
90
+ host: str | None = None,
91
+ username: str | None = None,
92
+ password: str | None = None,
93
+ database: str | None = None,
94
+ ) -> None:
95
+ """Accept ``db=`` (canonical) or ``connector=`` (compat alias)."""
96
+ self._db = _resolve_connector(
97
+ db,
98
+ connector,
99
+ host=host,
100
+ username=username,
101
+ password=password,
102
+ database=database,
103
+ )
104
+
105
+ # ── KGProvider ────────────────────────────────────────────────────────
106
+
107
+ def query_nodes(
108
+ self,
109
+ entity_type: str,
110
+ options: QueryOptions | None = None,
111
+ ) -> list[dict[str, Any]]:
112
+ """Query KG nodes by label with SQL-like filters, projection, and ordering.
113
+
114
+ ``entity_type`` must be a valid Neo4j label (alphanumeric / underscore)
115
+ or ``"*"`` to match all nodes. Invalid labels raise ``ValueError``
116
+ rather than silently injecting Cypher.
117
+ """
118
+ if entity_type and entity_type != "*" and not _LABEL_RE.match(entity_type):
119
+ raise ValueError(f"Invalid entity_type label: {entity_type!r}")
120
+
121
+ options = options or QueryOptions()
122
+ label_part = f":{entity_type}" if entity_type and entity_type != "*" else ""
123
+ clauses = [f"MATCH (n{label_part})"]
124
+ params: dict[str, Any] = {}
125
+ where_parts: list[str] = []
126
+
127
+ if options.filters:
128
+ for k, v in options.filters.items():
129
+ pk = f"filter_{k}"
130
+ where_parts.append(
131
+ f"n.{k} IN ${pk}" if isinstance(v, list) else f"n.{k} = ${pk}"
132
+ )
133
+ params[pk] = v
134
+
135
+ if options.where_clause:
136
+ # NOTE: where_clause is an internal escape-hatch for trusted callers only.
137
+ # It is not exposed over HTTP and must never receive user-supplied strings.
138
+ wc = options.where_clause.strip()
139
+ if wc.lower().startswith("where"):
140
+ wc = wc[5:].strip()
141
+ where_parts.append(f"({wc})")
142
+
143
+ if where_parts:
144
+ clauses.append("WHERE " + " AND ".join(where_parts))
145
+
146
+ if options.columns and options.columns != ["*"]:
147
+ ret_parts = [
148
+ col
149
+ if ("(" in col or " AS " in col.upper() or "." in col)
150
+ else f"n.{col} AS {col}"
151
+ for col in options.columns
152
+ ]
153
+ clauses.append("RETURN " + ", ".join(ret_parts))
154
+ else:
155
+ clauses.append("RETURN n")
156
+
157
+ if options.order_by:
158
+ sort_parts = []
159
+ for field in options.order_by:
160
+ desc = field.startswith("-")
161
+ f_clean = field.lstrip("-")
162
+ if "." not in f_clean:
163
+ f_clean = f"n.{f_clean}"
164
+ sort_parts.append(f"{f_clean} {'DESC' if desc else 'ASC'}")
165
+ clauses.append("ORDER BY " + ", ".join(sort_parts))
166
+
167
+ if options.limit:
168
+ clauses.append(f"LIMIT {int(options.limit)}")
169
+
170
+ try:
171
+ return self._db.execute("\n".join(clauses), params) or []
172
+ except Exception as exc:
173
+ logger.error("query_nodes(%s) failed: %s", entity_type, exc)
174
+ return []
175
+
176
+ def list_sessions(self, limit: int = 100) -> list[dict[str, Any]]:
177
+ """List sessions ordered by most recent first."""
178
+ query, params = kg_qb.list_sessions_query(limit)
179
+ try:
180
+ return self._db.execute(query, params) or []
181
+ except Exception as exc:
182
+ logger.error("list_sessions failed: %s", exc)
183
+ return []
184
+
185
+ def list_agents(self, session_id: str) -> list[dict[str, Any]]:
186
+ """List AgentCall nodes for a session, with their Agent's real name."""
187
+ try:
188
+ return self._db.execute(*kg_qb.list_agents_query(session_id)) or []
189
+ except Exception as exc:
190
+ logger.error("list_agents failed: %s", exc)
191
+ return []
192
+
193
+ def list_llm_calls(self, session_id: str) -> list[dict[str, Any]]:
194
+ """List LLMCall nodes for a session, with their LLM's real name."""
195
+ try:
196
+ return self._db.execute(*kg_qb.list_llm_calls_query(session_id)) or []
197
+ except Exception as exc:
198
+ logger.error("list_llm_calls failed: %s", exc)
199
+ return []
200
+
201
+ # ── DataProvider ──────────────────────────────────────────────────────
202
+
203
+ def resolve_session_id(self, resource_id: str) -> str | None:
204
+ """Resolve any resource ID to its parent Session ID."""
205
+ for query, params in kg_qb.resolve_session_id_queries(resource_id):
206
+ try:
207
+ rows = self._db.execute(query, params)
208
+ if rows and rows[0].get("sid"):
209
+ return rows[0]["sid"]
210
+ except Exception as exc:
211
+ logger.debug("resolve_session_id query failed: %s", exc)
212
+ return None
213
+
214
+ def retrieve(self, request: RetrievalRequest) -> dict[str, Any]:
215
+ """Execute a faceted retrieval request.
216
+
217
+ This V1 implementation supports declarative session scoping, ordered
218
+ AgentCall sequence retrieval, basic client-side filtering/ordering, and
219
+ simple aggregates such as counts.
220
+ """
221
+ session_ids = self._resolve_scope_session_ids(request)
222
+ contexts: dict[str, dict[str, Any]] = {}
223
+
224
+ for session_id in session_ids:
225
+ context: dict[str, Any] = {"session_id": session_id}
226
+
227
+ for node in request.nodes:
228
+ alias = node.alias or self._context_key_for_entity(node.entity_type)
229
+ records = self._retrieve_node_records(session_id, node, request)
230
+ if node.limit is not None:
231
+ records = records[: node.limit]
232
+
233
+ if self._context_key_for_entity(node.entity_type) == "session":
234
+ context[alias] = records[0] if records else {}
235
+ else:
236
+ context[alias] = records
237
+
238
+ self._apply_aggregates(context, request)
239
+ contexts[session_id] = context
240
+
241
+ return {
242
+ "session_ids": session_ids,
243
+ "contexts": contexts,
244
+ }
245
+
246
+ def fetch(self, resource_id: str, requirements: Any) -> dict[str, Any]:
247
+ """Fetch execution spans from Neo4j for metric computation.
248
+
249
+ Returns a dict with keys: session_id, session, agent_spans, llm_spans,
250
+ tool_spans, conversation, conversation_data, input_text, output_text.
251
+ """
252
+ try:
253
+ retrieval_request = requirements.retrieval
254
+ except AttributeError:
255
+ retrieval_request = None
256
+ if retrieval_request is not None:
257
+ request = self._anchor_request(retrieval_request, resource_id)
258
+ retrieved = self.retrieve(request)
259
+ contexts = retrieved.get("contexts", {})
260
+ session_ids = retrieved.get("session_ids", [])
261
+ session_id = (
262
+ resource_id
263
+ if resource_id in contexts
264
+ else (session_ids[0] if session_ids else None)
265
+ )
266
+ return contexts.get(session_id, {}) if session_id is not None else {}
267
+
268
+ # 1. Main record (session + its AgentCall/LLMCall/ToolCall/ProcessingCall descendants)
269
+ try:
270
+ rows = self._db.execute(*kg_qb.fetch_session_query(resource_id))
271
+ except Exception as exc:
272
+ logger.warning("fetch_session failed for %s: %s", resource_id, exc)
273
+ rows = None
274
+ record = rows[0] if rows else None
275
+
276
+ if record is None:
277
+ logger.warning("Session %s not found in Neo4j", resource_id)
278
+ return {}
279
+
280
+ session_node = record.get("s") or {}
281
+ session_props = (
282
+ dict(session_node.items())
283
+ if hasattr(session_node, "items")
284
+ else dict(session_node)
285
+ )
286
+
287
+ # 2. Session timing (Session is always populated with startTime/duration
288
+ # directly, but keep this as a defensive top-up).
289
+ try:
290
+ timing_rows = self._db.execute(
291
+ *kg_qb.fetch_session_timing_query(resource_id)
292
+ )
293
+ except Exception as exc:
294
+ logger.debug("fetch_session_timing failed for %s: %s", resource_id, exc)
295
+ timing_rows = None
296
+ if timing_rows:
297
+ t = timing_rows[0]
298
+ if t.get("startTime") is not None:
299
+ session_props.setdefault("startTime", t["startTime"])
300
+ if t.get("duration") is not None:
301
+ session_props.setdefault("duration", t["duration"])
302
+
303
+ def _as_dict(n: Any) -> dict[str, Any]:
304
+ return dict(n.items()) if hasattr(n, "items") else dict(n)
305
+
306
+ agent_call_nodes = [_as_dict(n) for n in (record.get("agent_calls") or []) if n]
307
+ llm_call_nodes = [_as_dict(n) for n in (record.get("llm_calls") or []) if n]
308
+ tool_call_nodes = [_as_dict(n) for n in (record.get("tool_calls") or []) if n]
309
+
310
+ all_ids = [
311
+ n["id"]
312
+ for n in (*agent_call_nodes, *llm_call_nodes, *tool_call_nodes)
313
+ if n.get("id")
314
+ ]
315
+ enrichment = self._fetch_enrichment(all_ids)
316
+
317
+ agent_spans = [
318
+ self._normalize_agent_call(n, enrichment=enrichment.get(n.get("id")))
319
+ for n in agent_call_nodes
320
+ ]
321
+ llm_spans = [
322
+ self._normalize_llm_call(n, enrichment=enrichment.get(n.get("id")))
323
+ for n in llm_call_nodes
324
+ ]
325
+ tool_spans = [
326
+ self._normalize_tool_call(n, enrichment=enrichment.get(n.get("id")))
327
+ for n in tool_call_nodes
328
+ ]
329
+
330
+ # 3. Conversation data: the session's own turn, falling back to the
331
+ # first/last AgentCall's own turn, then the first/last LLMCall's.
332
+ try:
333
+ conv_rows = self._db.execute(*kg_qb.fetch_conversation_query(resource_id))
334
+ except Exception as exc:
335
+ logger.debug("fetch_conversation failed for %s: %s", resource_id, exc)
336
+ conv_rows = None
337
+ conv_row = conv_rows[0] if conv_rows else {}
338
+ input_text = conv_row.get("input") or ""
339
+ output_text = conv_row.get("output") or ""
340
+
341
+ if not input_text or not output_text:
342
+ fallback_input, fallback_output = self._derive_session_query_response(
343
+ agent_spans, llm_spans
344
+ )
345
+ input_text = input_text or fallback_input
346
+ output_text = output_text or fallback_output
347
+
348
+ conversation_data = {"query": input_text, "response": output_text}
349
+ conversation = (
350
+ f"User: {input_text}\nAssistant: {output_text}".strip()
351
+ if input_text or output_text
352
+ else ""
353
+ )
354
+
355
+ return {
356
+ "session_id": resource_id,
357
+ "session": session_props,
358
+ "agent_spans": agent_spans,
359
+ "llm_spans": llm_spans,
360
+ "tool_spans": tool_spans,
361
+ "conversation": conversation,
362
+ "conversation_data": conversation_data,
363
+ "input_text": input_text,
364
+ "output_text": output_text,
365
+ }
366
+
367
+ def _fetch_enrichment(self, call_ids: list[str]) -> dict[str, dict[str, Any]]:
368
+ """Batch-fetch structural name/provider + own initial/final State
369
+ content for every call id, keyed by id."""
370
+ if not call_ids:
371
+ return {}
372
+ try:
373
+ rows = self._db.execute(*kg_qb.fetch_call_content_and_names_query(call_ids))
374
+ except Exception as exc:
375
+ logger.debug("fetch_call_content_and_names failed: %s", exc)
376
+ return {}
377
+ return {row["id"]: dict(row) for row in (rows or []) if row.get("id")}
378
+
379
+ def _resolve_scope_session_ids(self, request: RetrievalRequest) -> list[str]:
380
+ session_ids: list[str] = []
381
+
382
+ for session_id in request.scope.session_ids:
383
+ if session_id not in session_ids:
384
+ session_ids.append(session_id)
385
+
386
+ for resource_id in request.scope.resource_ids:
387
+ session_id = self.resolve_session_id(resource_id)
388
+ if session_id and session_id not in session_ids:
389
+ session_ids.append(session_id)
390
+
391
+ if request.scope.start_time is not None or request.scope.end_time is not None:
392
+ query, params = kg_qb.list_sessions_in_interval_query(
393
+ request.scope.start_time,
394
+ request.scope.end_time,
395
+ request.limit,
396
+ )
397
+ rows = self._db.execute(query, params) or []
398
+ for row in rows:
399
+ session_id = row.get("session_id")
400
+ if session_id and session_id not in session_ids:
401
+ session_ids.append(session_id)
402
+
403
+ return session_ids
404
+
405
+ def _anchor_request(
406
+ self, request: RetrievalRequest, resource_id: str
407
+ ) -> RetrievalRequest:
408
+ if request.scope.session_ids or request.scope.resource_ids:
409
+ return request
410
+
411
+ session_id = self.resolve_session_id(resource_id) or resource_id
412
+ return replace(
413
+ request,
414
+ scope=RetrievalScope(session_ids=[session_id]),
415
+ )
416
+
417
+ @staticmethod
418
+ def _context_key_for_entity(entity_type: str) -> str:
419
+ mapping = {
420
+ "mas:AgentCall": "agent_calls",
421
+ "AgentCall": "agent_calls",
422
+ "mas:LLMCall": "llm_calls",
423
+ "LLMCall": "llm_calls",
424
+ "mas:ToolCall": "tool_calls",
425
+ "ToolCall": "tool_calls",
426
+ "mas:MASCall": "mas_calls",
427
+ "MASCall": "mas_calls",
428
+ "mas:Session": "session",
429
+ "Session": "session",
430
+ }
431
+ return mapping.get(entity_type, entity_type.split(":")[-1].lower())
432
+
433
+ def _retrieve_node_records(
434
+ self, session_id: str, node: Any, request: RetrievalRequest
435
+ ) -> list[dict[str, Any]]:
436
+ try:
437
+ rows = (
438
+ self._db.execute(
439
+ *kg_qb.fetch_traversed_nodes_query(
440
+ session_id,
441
+ node.entity_type,
442
+ request.edges,
443
+ order_by=node.order_by or request.order_by,
444
+ )
445
+ )
446
+ or []
447
+ )
448
+ except Exception as exc:
449
+ logger.debug(
450
+ "retrieve_%s failed for %s: %s",
451
+ self._context_key_for_entity(node.entity_type),
452
+ session_id,
453
+ exc,
454
+ )
455
+ rows = []
456
+
457
+ node_dicts = [self._as_dict(row["node"]) for row in rows if row.get("node")]
458
+ enrichment = self._fetch_enrichment(
459
+ [n["id"] for n in node_dicts if n.get("id")]
460
+ )
461
+
462
+ records = [
463
+ self._normalize_entity(
464
+ node.entity_type, n, enrichment=enrichment.get(n.get("id"))
465
+ )
466
+ for n in node_dicts
467
+ ]
468
+ records = self._apply_filters(records, node.filters)
469
+ records = self._sort_records(
470
+ records,
471
+ node.order_by
472
+ or request.order_by
473
+ or self._default_order_for_entity(node.entity_type),
474
+ )
475
+ if node.fields:
476
+ records = [self._project_fields(record, node.fields) for record in records]
477
+ return records
478
+
479
+ @staticmethod
480
+ def _project_fields(record: dict[str, Any], fields: list[str]) -> dict[str, Any]:
481
+ return {field: record.get(field) for field in fields}
482
+
483
+ @staticmethod
484
+ def _default_order_for_entity(entity_type: str) -> list[str]:
485
+ key = entity_type.split(":")[-1]
486
+ if key in {"AgentCall", "LLMCall", "ToolCall", "MASCall"}:
487
+ return ["startTime"]
488
+ return []
489
+
490
+ def _normalize_entity(
491
+ self,
492
+ entity_type: str,
493
+ node: dict[str, Any],
494
+ *,
495
+ enrichment: dict[str, Any] | None = None,
496
+ ) -> dict[str, Any]:
497
+ key = entity_type.split(":")[-1]
498
+ if key == "ToolCall":
499
+ return self._normalize_tool_call(node, enrichment=enrichment)
500
+ if key == "LLMCall":
501
+ return self._normalize_llm_call(node, enrichment=enrichment)
502
+ if key == "AgentCall":
503
+ return self._normalize_agent_call(node, enrichment=enrichment)
504
+ return node
505
+
506
+ @staticmethod
507
+ def _apply_filters(
508
+ records: list[dict[str, Any]], filters: dict[str, Any]
509
+ ) -> list[dict[str, Any]]:
510
+ if not filters:
511
+ return records
512
+
513
+ filtered: list[dict[str, Any]] = []
514
+ for record in records:
515
+ keep = True
516
+ for key, expected in filters.items():
517
+ value = record.get(key)
518
+ if isinstance(expected, list):
519
+ if value not in expected:
520
+ keep = False
521
+ break
522
+ elif value != expected:
523
+ keep = False
524
+ break
525
+ if keep:
526
+ filtered.append(record)
527
+ return filtered
528
+
529
+ @staticmethod
530
+ def _sort_records(
531
+ records: list[dict[str, Any]], order_by: list[str]
532
+ ) -> list[dict[str, Any]]:
533
+ if not order_by:
534
+ return records
535
+
536
+ sorted_records = list(records)
537
+ for field in reversed(order_by):
538
+ descending = field.startswith("-")
539
+ field_name = field.lstrip("-")
540
+ sorted_records.sort(
541
+ key=lambda record: (
542
+ record.get(field_name) is None,
543
+ record.get(field_name),
544
+ ),
545
+ reverse=descending,
546
+ )
547
+ return sorted_records
548
+
549
+ def _apply_aggregates(
550
+ self, context: dict[str, Any], request: RetrievalRequest
551
+ ) -> None:
552
+ for aggregate in request.aggregates:
553
+ alias = aggregate.alias or aggregate.function
554
+ if aggregate.function != "count" or not aggregate.entity_type:
555
+ raise NotImplementedError(
556
+ f"Unsupported aggregate facet: {aggregate.function!r}"
557
+ )
558
+
559
+ key = self._context_key_for_entity(aggregate.entity_type)
560
+ records = context.get(key, [])
561
+ if aggregate.group_by:
562
+ grouped: dict[Any, int] = {}
563
+ for record in records:
564
+ group_key = tuple(record.get(field) for field in aggregate.group_by)
565
+ normalized_key = group_key[0] if len(group_key) == 1 else group_key
566
+ grouped[normalized_key] = grouped.get(normalized_key, 0) + 1
567
+ context[alias] = grouped
568
+ else:
569
+ context[alias] = len(records)
570
+
571
+ @staticmethod
572
+ def _as_dict(node: Any) -> dict[str, Any]:
573
+ return dict(node.items()) if hasattr(node, "items") else dict(node)
574
+
575
+ @staticmethod
576
+ def _derive_session_query_response(
577
+ agent_spans: list[dict[str, Any]],
578
+ llm_spans: list[dict[str, Any]],
579
+ ) -> tuple[str, str]:
580
+ """Fall back to the first/last AgentCall's own turn, then the
581
+ first/last LLMCall's, when the session has no conversation State of
582
+ its own."""
583
+
584
+ def _pick_first(mapping: dict[str, Any], keys: tuple[str, ...]) -> str:
585
+ for key in keys:
586
+ value = mapping.get(key)
587
+ if value not in (None, ""):
588
+ return str(value)
589
+ return ""
590
+
591
+ query = ""
592
+ for agent_call in agent_spans:
593
+ query = _pick_first(agent_call, ("inputContent",))
594
+ if query:
595
+ break
596
+ if not query:
597
+ for llm_call in llm_spans:
598
+ query = _pick_first(llm_call, ("prompt", "inputContent"))
599
+ if query:
600
+ break
601
+
602
+ response = ""
603
+ for agent_call in reversed(agent_spans):
604
+ response = _pick_first(agent_call, ("outputContent",))
605
+ if response:
606
+ break
607
+ if not response:
608
+ for llm_call in reversed(llm_spans):
609
+ response = _pick_first(llm_call, ("completion", "outputContent"))
610
+ if response:
611
+ break
612
+
613
+ return query, response
614
+
615
+ # ── normalizers ───────────────────────────────────────────────────────
616
+ #
617
+ # Each takes the raw call node plus the batched enrichment row for its id
618
+ # (structural name/provider + own initial/final State content -- see
619
+ # kg_qb.fetch_call_content_and_names_query) and produces the field names
620
+ # downstream MCE metrics already expect (toolName/inputContent/
621
+ # outputContent/prompt/completion/contains_error/...).
622
+
623
+ @staticmethod
624
+ def _normalize_tool_call(
625
+ node: dict[str, Any],
626
+ *,
627
+ enrichment: dict[str, Any] | None = None,
628
+ ) -> dict[str, Any]:
629
+ normalized = dict(node)
630
+ enrichment = enrichment or {}
631
+
632
+ tool_name = enrichment.get("name")
633
+ if tool_name:
634
+ normalized["toolName"] = tool_name
635
+
636
+ input_content = enrichment.get("inputContent")
637
+ if input_content is not None:
638
+ normalized["inputContent"] = input_content
639
+ normalized["toolArguments"] = input_content
640
+ normalized["inputParams"] = input_content
641
+
642
+ output_content = enrichment.get("outputContent")
643
+ if output_content is not None:
644
+ normalized["outputContent"] = output_content
645
+ normalized["toolOutput"] = output_content
646
+
647
+ normalized["contains_error"] = normalized.get("success") is False
648
+ return normalized
649
+
650
+ @staticmethod
651
+ def _normalize_llm_call(
652
+ node: dict[str, Any],
653
+ *,
654
+ enrichment: dict[str, Any] | None = None,
655
+ ) -> dict[str, Any]:
656
+ normalized = dict(node)
657
+ enrichment = enrichment or {}
658
+
659
+ model_name = enrichment.get("name")
660
+ if model_name:
661
+ normalized["modelName"] = model_name
662
+ normalized["llmName"] = model_name
663
+ provider = enrichment.get("provider")
664
+ if provider:
665
+ normalized["provider"] = provider
666
+
667
+ input_content = enrichment.get("inputContent")
668
+ if input_content is not None:
669
+ normalized["inputContent"] = input_content
670
+ normalized["prompt"] = input_content
671
+
672
+ output_content = enrichment.get("outputContent")
673
+ if output_content is not None:
674
+ normalized["outputContent"] = output_content
675
+ normalized["completion"] = output_content
676
+
677
+ normalized["contains_error"] = normalized.get("success") is False
678
+ return normalized
679
+
680
+ @staticmethod
681
+ def _normalize_agent_call(
682
+ node: dict[str, Any],
683
+ *,
684
+ enrichment: dict[str, Any] | None = None,
685
+ ) -> dict[str, Any]:
686
+ normalized = dict(node)
687
+ enrichment = enrichment or {}
688
+
689
+ agent_name = enrichment.get("name")
690
+ if agent_name:
691
+ normalized["agentName"] = agent_name
692
+
693
+ input_content = enrichment.get("inputContent")
694
+ if input_content is not None:
695
+ normalized["inputContent"] = input_content
696
+
697
+ output_content = enrichment.get("outputContent")
698
+ if output_content is not None:
699
+ normalized["outputContent"] = output_content
700
+
701
+ normalized["contains_error"] = normalized.get("success") is False
702
+ return normalized