ioc-scope-api 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ioc_scope_api-1.0.0.dist-info/METADATA +306 -0
- ioc_scope_api-1.0.0.dist-info/RECORD +106 -0
- ioc_scope_api-1.0.0.dist-info/WHEEL +4 -0
- ioc_scope_api-1.0.0.dist-info/entry_points.txt +2 -0
- scope/__init__.py +27 -0
- scope/api/__init__.py +119 -0
- scope/api/api_v1/__init__.py +2 -0
- scope/api/api_v1/api.py +71 -0
- scope/api/api_v1/endpoints/__init__.py +2 -0
- scope/api/api_v1/endpoints/agentic_protocols_metrics.py +39 -0
- scope/api/api_v1/endpoints/applications.py +440 -0
- scope/api/api_v1/endpoints/cache.py +50 -0
- scope/api/api_v1/endpoints/concepts.py +123 -0
- scope/api/api_v1/endpoints/features.py +19 -0
- scope/api/api_v1/endpoints/helpers.py +65 -0
- scope/api/api_v1/endpoints/kg.py +195 -0
- scope/api/api_v1/endpoints/labels.py +71 -0
- scope/api/api_v1/endpoints/live_topology.py +89 -0
- scope/api/api_v1/endpoints/metrics.py +1014 -0
- scope/api/api_v1/endpoints/reasoning.py +62 -0
- scope/api/api_v1/endpoints/semanticgroups.py +144 -0
- scope/api/api_v1/endpoints/sessions.py +339 -0
- scope/api/api_v1/endpoints/spans.py +41 -0
- scope/api/api_v1/endpoints/symbolic.py +186 -0
- scope/api/api_v1/endpoints/ui.py +145 -0
- scope/api/api_v1/endpoints/waste_estimation.py +182 -0
- scope/api/api_v2/__init__.py +3 -0
- scope/api/api_v2/api.py +23 -0
- scope/api/api_v2/endpoints/__init__.py +3 -0
- scope/api/api_v2/endpoints/metrics.py +193 -0
- scope/app.py +30 -0
- scope/cache.py +64 -0
- scope/client/__init__.py +27 -0
- scope/client/_concepts.py +137 -0
- scope/client/_kg.py +64 -0
- scope/client/_labels.py +86 -0
- scope/client/_live_topology.py +912 -0
- scope/client/_metrics.py +561 -0
- scope/client/_semanticgroups.py +166 -0
- scope/client/_sessions.py +168 -0
- scope/client/_symbolic.py +1354 -0
- scope/client/_ui.py +599 -0
- scope/client/agentic_protocols.py +289 -0
- scope/client/application_charts.py +1786 -0
- scope/client/applications.py +2246 -0
- scope/client/base.py +49 -0
- scope/client/cognition_protocols.py +302 -0
- scope/client/constants.py +81 -0
- scope/client/dal.py +2382 -0
- scope/client/failures.py +70 -0
- scope/client/local.py +161 -0
- scope/client/mock/__init__.py +7 -0
- scope/client/mock/client.py +1034 -0
- scope/client/sessions.py +1688 -0
- scope/client/spans.py +95 -0
- scope/client/utils.py +392 -0
- scope/connectors/__init__.py +13 -0
- scope/connectors/base.py +52 -0
- scope/connectors/clickhouse.py +105 -0
- scope/connectors/neo4j.py +220 -0
- scope/connectors/sqlalchemy.py +131 -0
- scope/core/config.py +530 -0
- scope/core/exceptions.py +64 -0
- scope/dependencies.py +164 -0
- scope/health.py +10 -0
- scope/interfaces/__init__.py +33 -0
- scope/interfaces/data_provider.py +61 -0
- scope/interfaces/integration_example.py +310 -0
- scope/interfaces/kg_provider.py +91 -0
- scope/interfaces/metrics_provider.py +92 -0
- scope/interfaces/models.py +185 -0
- scope/models/kg.py +48 -0
- scope/models/live_topology.py +78 -0
- scope/models/otel_traces.py +1595 -0
- scope/providers/__init__.py +277 -0
- scope/providers/_graph.py +59 -0
- scope/providers/cognition_protocols.py +178 -0
- scope/providers/kg.py +702 -0
- scope/providers/kg_query_runner.py +109 -0
- scope/providers/neo4j_mce.py +18 -0
- scope/providers/scope_metrics.py +7 -0
- scope/query_builders/__init__.py +14 -0
- scope/query_builders/cognition_protocol_graph.py +191 -0
- scope/query_builders/concepts.py +112 -0
- scope/query_builders/dal.py +931 -0
- scope/query_builders/failure_graph.py +102 -0
- scope/query_builders/features.py +5 -0
- scope/query_builders/kg.py +416 -0
- scope/query_builders/labels.py +53 -0
- scope/query_builders/live_topology.py +503 -0
- scope/query_builders/metric_graph.py +196 -0
- scope/query_builders/metrics.py +354 -0
- scope/query_builders/semanticgroups.py +46 -0
- scope/query_builders/sessions.py +208 -0
- scope/query_builders/symbolic.py +615 -0
- scope/query_builders/trajectory.py +76 -0
- scope/query_builders/types.py +20 -0
- scope/query_builders/ui.py +3278 -0
- scope/query_builders/waste_estimation.py +221 -0
- scope/repositories/__init__.py +28 -0
- scope/repositories/clickhouse_otel_repository.py +135 -0
- scope/repositories/otel_repository.py +97 -0
- scope/repositories/sqlite_repository.py +215 -0
- scope/scripts/__init__.py +2 -0
- scope/scripts/seed.py +35 -0
- scope/workarounds.py +38 -0
|
@@ -0,0 +1,931 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Cypher query builders for the DAL (Data Access Layer).
|
|
4
|
+
|
|
5
|
+
Each builder returns a ``(query_str, params_dict)`` tuple that can be
|
|
6
|
+
passed directly to :py:meth:`~scope.connectors.base.Connector.execute`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
|
12
|
+
|
|
13
|
+
_STATE_NODE_LABEL = "State"
|
|
14
|
+
|
|
15
|
+
_HIERARCHICAL_GROUPING_LOCK_QUERY = """
|
|
16
|
+
OPTIONAL MATCH (lock:SystemLock {id: "hierarchical_grouping"})
|
|
17
|
+
WITH lock, timestamp() AS now
|
|
18
|
+
RETURN lock IS NOT NULL
|
|
19
|
+
AND coalesce(lock.locked, false)
|
|
20
|
+
AND coalesce(lock.expiresAt, 0) >= now AS is_locked
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def build_state_content_query(
|
|
25
|
+
filters_eq: Dict[str, str],
|
|
26
|
+
filters_neq: Dict[str, str],
|
|
27
|
+
) -> tuple[str, Dict[str, object]]:
|
|
28
|
+
"""Build a Cypher query that matches ``State`` nodes with the given filters.
|
|
29
|
+
|
|
30
|
+
Mirrors the logic of ``Neo4jConnector.get_nodes`` in *scope-lib*.
|
|
31
|
+
|
|
32
|
+
Returns
|
|
33
|
+
-------
|
|
34
|
+
tuple[str, dict]
|
|
35
|
+
The parameterised Cypher query string and its parameter mapping.
|
|
36
|
+
"""
|
|
37
|
+
query = f"MATCH (n:{_STATE_NODE_LABEL})"
|
|
38
|
+
where_clauses: list[str] = []
|
|
39
|
+
params: Dict[str, object] = {}
|
|
40
|
+
|
|
41
|
+
for i, (key, value) in enumerate(filters_eq.items()):
|
|
42
|
+
param_key = f"eq_{i}"
|
|
43
|
+
where_clauses.append(f"n.{key} = ${param_key}")
|
|
44
|
+
params[param_key] = value
|
|
45
|
+
|
|
46
|
+
for i, (key, value) in enumerate(filters_neq.items()):
|
|
47
|
+
param_key = f"neq_{i}"
|
|
48
|
+
where_clauses.append(f"n.{key} <> ${param_key}")
|
|
49
|
+
params[param_key] = value
|
|
50
|
+
|
|
51
|
+
if where_clauses:
|
|
52
|
+
query += " WHERE " + " AND ".join(where_clauses)
|
|
53
|
+
|
|
54
|
+
query += " RETURN n"
|
|
55
|
+
return query, params
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def build_session_io_query(edge: str) -> tuple[str, Dict[str, object]]:
|
|
59
|
+
"""Build a Cypher query that traverses Session -[edge]-> State.
|
|
60
|
+
|
|
61
|
+
Mirrors the path traversal performed by ``Neo4jDBHandler.get_session_io``
|
|
62
|
+
in *scope-lib* via ``get_nodes_by_path``.
|
|
63
|
+
|
|
64
|
+
Returns
|
|
65
|
+
-------
|
|
66
|
+
tuple[str, dict]
|
|
67
|
+
The parameterised Cypher query string (with ``$session_id``) and an
|
|
68
|
+
empty params dict (caller fills in ``session_id``).
|
|
69
|
+
"""
|
|
70
|
+
query = (
|
|
71
|
+
f"MATCH (s:Session)-[:{edge}]->(n:State)"
|
|
72
|
+
" WHERE s.sessionId = $session_id"
|
|
73
|
+
" RETURN n"
|
|
74
|
+
)
|
|
75
|
+
return query, {"session_id": None}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def build_session_group_query(
|
|
79
|
+
session_id: str,
|
|
80
|
+
embedding_model: str,
|
|
81
|
+
max_distance: float,
|
|
82
|
+
) -> tuple[str, Dict[str, object]]:
|
|
83
|
+
"""Build a Cypher query that finds the closest semantic group for a session.
|
|
84
|
+
|
|
85
|
+
Mirrors the query used by ``Neo4jDBHandler.get_session_group`` in
|
|
86
|
+
*scope-lib*: performs a cosine-similarity search against medioid
|
|
87
|
+
embeddings of leaf ``SemanticGroup`` nodes and returns the nearest one
|
|
88
|
+
within *max_distance*.
|
|
89
|
+
|
|
90
|
+
Returns
|
|
91
|
+
-------
|
|
92
|
+
tuple[str, dict]
|
|
93
|
+
The parameterised Cypher query string and its parameter mapping.
|
|
94
|
+
"""
|
|
95
|
+
query = """
|
|
96
|
+
MATCH (mas:MAS)<-[:executesSession]-(:Session {sessionId: $session_id})-[:hasInitialState]->(:State)<-[:represents]-(te:Embedding {embeddingModel: $embedding_model})
|
|
97
|
+
WITH te.embeddingVector AS target_embedding
|
|
98
|
+
|
|
99
|
+
MATCH (sg:SemanticGroup)-[:hasMedioidSession]->(medioid_session:Session)-[:executesSession]->(mas)
|
|
100
|
+
WHERE NOT EXISTS { MATCH (sg)-[:containsSession]->(:SemanticGroup) }
|
|
101
|
+
MATCH (medioid_session)-[:hasInitialState]->(:State)<-[:represents]-(medioid_embedding:Embedding {embeddingModel: $embedding_model})
|
|
102
|
+
|
|
103
|
+
WITH sg, 1 - vector.similarity.cosine(medioid_embedding.embeddingVector, target_embedding) AS distance
|
|
104
|
+
|
|
105
|
+
WHERE distance <= $max_distance
|
|
106
|
+
ORDER BY distance ASC
|
|
107
|
+
LIMIT 1
|
|
108
|
+
|
|
109
|
+
RETURN sg.id AS group_id, sg.nodeHash AS node_hash
|
|
110
|
+
"""
|
|
111
|
+
params: Dict[str, object] = {
|
|
112
|
+
"session_id": session_id,
|
|
113
|
+
"embedding_model": embedding_model,
|
|
114
|
+
"max_distance": max_distance,
|
|
115
|
+
}
|
|
116
|
+
return query, params
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def build_hierarchical_grouping_lock_query() -> tuple[str, Dict[str, object]]:
|
|
120
|
+
"""Return the Cypher query that checks the hierarchical-grouping lock.
|
|
121
|
+
|
|
122
|
+
Mirrors the query used by ``Neo4jDBHandler.is_hierarchical_grouping_locked``
|
|
123
|
+
in *scope-lib*.
|
|
124
|
+
|
|
125
|
+
Returns
|
|
126
|
+
-------
|
|
127
|
+
tuple[str, dict]
|
|
128
|
+
The Cypher query string and an empty parameter mapping (no params
|
|
129
|
+
required).
|
|
130
|
+
"""
|
|
131
|
+
return _HIERARCHICAL_GROUPING_LOCK_QUERY, {}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def build_acquire_hierarchical_grouping_lock_query(
|
|
135
|
+
owner: str,
|
|
136
|
+
ttl_seconds: int,
|
|
137
|
+
) -> tuple[str, Dict[str, object]]:
|
|
138
|
+
"""Build a Cypher query that atomically acquires the hierarchical-grouping lock.
|
|
139
|
+
|
|
140
|
+
Mirrors the query used by ``Neo4jDBHandler.acquire_hierarchical_grouping_lock``
|
|
141
|
+
in *scope-lib*: uses ``MERGE`` to create the lock node if absent, then
|
|
142
|
+
conditionally claims it when it is either unlocked or expired.
|
|
143
|
+
|
|
144
|
+
Returns
|
|
145
|
+
-------
|
|
146
|
+
tuple[str, dict]
|
|
147
|
+
The parameterised Cypher query string and its parameter mapping.
|
|
148
|
+
"""
|
|
149
|
+
query = """
|
|
150
|
+
MERGE (lock:SystemLock {id: "hierarchical_grouping"})
|
|
151
|
+
ON CREATE SET lock.locked = false, lock.owner = "", lock.expiresAt = 0
|
|
152
|
+
WITH lock, timestamp() AS now
|
|
153
|
+
WHERE coalesce(lock.locked, false) = false
|
|
154
|
+
OR coalesce(lock.expiresAt, 0) < now
|
|
155
|
+
OR lock.owner = $owner
|
|
156
|
+
SET lock.locked = true,
|
|
157
|
+
lock.owner = $owner,
|
|
158
|
+
lock.expiresAt = now + $ttl_ms
|
|
159
|
+
RETURN true AS acquired
|
|
160
|
+
"""
|
|
161
|
+
params: Dict[str, object] = {
|
|
162
|
+
"owner": owner,
|
|
163
|
+
"ttl_ms": int(ttl_seconds * 1000),
|
|
164
|
+
}
|
|
165
|
+
return query, params
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def build_attach_session_fetch_query(
|
|
169
|
+
group_id: str,
|
|
170
|
+
node_hash: str,
|
|
171
|
+
) -> tuple[str, Dict[str, object]]:
|
|
172
|
+
"""Build the first query used by ``attach_session_to_group``.
|
|
173
|
+
|
|
174
|
+
Retrieves the current direct and transitive session IDs of a
|
|
175
|
+
``SemanticGroup`` so the caller can compute the new hash before writing.
|
|
176
|
+
|
|
177
|
+
Returns
|
|
178
|
+
-------
|
|
179
|
+
tuple[str, dict]
|
|
180
|
+
The parameterised Cypher query string and its parameter mapping.
|
|
181
|
+
"""
|
|
182
|
+
query = """
|
|
183
|
+
MATCH (sg:SemanticGroup {id: $group_id})
|
|
184
|
+
WHERE $node_hash = "" OR sg.nodeHash = $node_hash
|
|
185
|
+
WITH sg, coalesce(sg.sessionIds, []) AS direct_session_ids
|
|
186
|
+
|
|
187
|
+
OPTIONAL MATCH (sg)-[:containsSession*0..]->(child:Session)
|
|
188
|
+
WITH direct_session_ids, child.sessionId AS sid
|
|
189
|
+
ORDER BY sid
|
|
190
|
+
WITH direct_session_ids, collect(DISTINCT sid) AS raw_all_session_ids
|
|
191
|
+
|
|
192
|
+
RETURN
|
|
193
|
+
[x IN raw_all_session_ids WHERE x IS NOT NULL] AS all_session_ids,
|
|
194
|
+
direct_session_ids
|
|
195
|
+
"""
|
|
196
|
+
params: Dict[str, object] = {"group_id": group_id, "node_hash": node_hash}
|
|
197
|
+
return query, params
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def build_attach_session_update_query(
|
|
201
|
+
session_id: str,
|
|
202
|
+
group_id: str,
|
|
203
|
+
node_hash: str,
|
|
204
|
+
new_session_ids: list,
|
|
205
|
+
new_group_hash: str,
|
|
206
|
+
) -> tuple[str, Dict[str, object]]:
|
|
207
|
+
"""Build the second (write) query used by ``attach_session_to_group``.
|
|
208
|
+
|
|
209
|
+
Conditionally creates the ``containsSession`` relationship and
|
|
210
|
+
updates the group's session list and hash, guarded by *node_hash* to
|
|
211
|
+
detect concurrent modifications.
|
|
212
|
+
|
|
213
|
+
Returns
|
|
214
|
+
-------
|
|
215
|
+
tuple[str, dict]
|
|
216
|
+
The parameterised Cypher query string and its parameter mapping.
|
|
217
|
+
"""
|
|
218
|
+
query = """
|
|
219
|
+
MATCH (sg:SemanticGroup {id: $group_id})
|
|
220
|
+
WHERE $node_hash = "" OR sg.nodeHash = $node_hash
|
|
221
|
+
MATCH (s:Session {sessionId: $session_id})
|
|
222
|
+
MERGE (sg)-[:containsSession]->(s)
|
|
223
|
+
SET sg.sessionIds = $new_session_ids,
|
|
224
|
+
sg.nodeHash = $new_group_hash
|
|
225
|
+
RETURN sg.id AS group_id
|
|
226
|
+
"""
|
|
227
|
+
params: Dict[str, object] = {
|
|
228
|
+
"session_id": session_id,
|
|
229
|
+
"group_id": group_id,
|
|
230
|
+
"node_hash": node_hash,
|
|
231
|
+
"new_session_ids": new_session_ids,
|
|
232
|
+
"new_group_hash": new_group_hash,
|
|
233
|
+
}
|
|
234
|
+
return query, params
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def build_release_hierarchical_grouping_lock_query(
|
|
238
|
+
owner: str,
|
|
239
|
+
) -> tuple[str, Dict[str, object]]:
|
|
240
|
+
"""Build the Cypher query that releases the hierarchical-grouping lock.
|
|
241
|
+
|
|
242
|
+
Mirrors ``Neo4jDBHandler.release_hierarchical_grouping_lock`` in *scope-lib*.
|
|
243
|
+
"""
|
|
244
|
+
query = """
|
|
245
|
+
MATCH (lock:SystemLock {id: "hierarchical_grouping"})
|
|
246
|
+
WHERE lock.owner = $owner
|
|
247
|
+
SET lock.locked = false,
|
|
248
|
+
lock.owner = "",
|
|
249
|
+
lock.expiresAt = 0
|
|
250
|
+
RETURN true AS released
|
|
251
|
+
"""
|
|
252
|
+
return query, {"owner": owner}
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def build_all_session_input_embeddings_query(
|
|
256
|
+
application_id: str,
|
|
257
|
+
embedding_model: str,
|
|
258
|
+
) -> tuple[str, Dict[str, object]]:
|
|
259
|
+
"""Build the Cypher query that retrieves all input embeddings for an application.
|
|
260
|
+
|
|
261
|
+
Mirrors ``Neo4jDBHandler.get_all_session_input_embeddings`` in *scope-lib*.
|
|
262
|
+
"""
|
|
263
|
+
query = """
|
|
264
|
+
MATCH (in_emb {embeddingModel: $embedding_model})-[:represents]->(in_state:State)<-[:hasInitialState]-(s:Session)-[:executesSession]->(m:MAS {id: $application_id})
|
|
265
|
+
RETURN
|
|
266
|
+
s.sessionId as session_id,
|
|
267
|
+
in_state.content as input_query,
|
|
268
|
+
in_emb.embeddingVector as input_embedding
|
|
269
|
+
"""
|
|
270
|
+
return query, {"application_id": application_id, "embedding_model": embedding_model}
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def build_semantic_group_hierarchy_query(
|
|
274
|
+
embedding_model: str,
|
|
275
|
+
application_id: str,
|
|
276
|
+
) -> tuple[str, Dict[str, object]]:
|
|
277
|
+
"""Build the Cypher query that returns the semantic group hierarchy for an application.
|
|
278
|
+
|
|
279
|
+
Mirrors ``Neo4jDBHandler.get_semantic_group_hierarchy`` in *scope-lib*.
|
|
280
|
+
"""
|
|
281
|
+
query = """
|
|
282
|
+
MATCH (:MAS {id: $application_id})-[:containsSemanticGroup]->(sg:SemanticGroup {embeddingModel: $embedding_model})
|
|
283
|
+
RETURN sg
|
|
284
|
+
ORDER BY sg.nSessions DESC
|
|
285
|
+
"""
|
|
286
|
+
return query, {"embedding_model": embedding_model, "application_id": application_id}
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def build_update_semantic_group_names_query(
|
|
290
|
+
groups: list,
|
|
291
|
+
) -> tuple[str, Dict[str, object]]:
|
|
292
|
+
"""Build the Cypher UNWIND query that updates SemanticGroup name/summary fields.
|
|
293
|
+
|
|
294
|
+
Each entry in *groups* must have ``"id"``, ``"groupName"``, and ``"groupSummary"``.
|
|
295
|
+
|
|
296
|
+
Mirrors ``Neo4jDBHandler.update_semantic_group_names_and_summaries`` in *scope-lib*.
|
|
297
|
+
"""
|
|
298
|
+
query = """
|
|
299
|
+
UNWIND $groups AS group
|
|
300
|
+
MATCH (n:SemanticGroup {id: group.id})
|
|
301
|
+
SET n.groupName = group.groupName,
|
|
302
|
+
n.groupSummary = group.groupSummary
|
|
303
|
+
"""
|
|
304
|
+
return query, {"groups": groups}
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def build_semantic_groups_needing_analysis_query(
|
|
308
|
+
embedding_model: str,
|
|
309
|
+
) -> tuple[str, Dict[str, object]]:
|
|
310
|
+
"""Build the Cypher query for leaf groups missing at least one analysis report.
|
|
311
|
+
|
|
312
|
+
Mirrors ``Neo4jDBHandler.get_semantic_groups_needing_analysis`` in *scope-lib*.
|
|
313
|
+
"""
|
|
314
|
+
query = """
|
|
315
|
+
MATCH (sg:SemanticGroup {embeddingModel: $embedding_model})
|
|
316
|
+
WHERE sg.nodeHash IS NOT NULL
|
|
317
|
+
AND NOT EXISTS { MATCH (sg)-[:containsSession]->(:SemanticGroup) }
|
|
318
|
+
OPTIONAL MATCH (sg)-[:hasAnomalyReport]->(ar:AnomalyReport)
|
|
319
|
+
OPTIONAL MATCH (sg)-[:hasConsistencyReport]->(cr:ConsistencyReport)
|
|
320
|
+
OPTIONAL MATCH (sg)-[:hasNormalBehaviourReport]->(nr:NormalBehaviourReport)
|
|
321
|
+
WITH sg,
|
|
322
|
+
count(DISTINCT ar) > 0 AS has_anomaly,
|
|
323
|
+
count(DISTINCT cr) > 0 AS has_consistency,
|
|
324
|
+
count(DISTINCT nr) > 0 AS has_normal_behaviour
|
|
325
|
+
WHERE NOT (has_anomaly AND has_consistency AND has_normal_behaviour)
|
|
326
|
+
RETURN sg.id AS group_id, sg.nodeHash AS group_hash
|
|
327
|
+
"""
|
|
328
|
+
return query, {"embedding_model": embedding_model}
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
# Valid report types and their corresponding edge names (mirrors Nodes/Edges enums).
|
|
332
|
+
_REPORT_TYPE_TO_EDGE: Dict[str, str] = {
|
|
333
|
+
"ConsistencyReport": "hasConsistencyReport",
|
|
334
|
+
"AnomalyReport": "hasAnomalyReport",
|
|
335
|
+
"NormalBehaviourReport": "hasNormalBehaviourReport",
|
|
336
|
+
}
|
|
337
|
+
_VALID_REPORT_TYPES = frozenset(_REPORT_TYPE_TO_EDGE)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def build_analysis_pre_check_query(
|
|
341
|
+
report_type: str,
|
|
342
|
+
with_session_id: bool,
|
|
343
|
+
) -> tuple[str, Dict[str, object]]:
|
|
344
|
+
"""Build the dynamic Cypher query used by ``analysis_pre_check``.
|
|
345
|
+
|
|
346
|
+
*report_type* must be one of ``ConsistencyReport``, ``AnomalyReport``, or
|
|
347
|
+
``NormalBehaviourReport``. *with_session_id* controls whether an extra
|
|
348
|
+
``Session`` membership check is appended.
|
|
349
|
+
|
|
350
|
+
Mirrors ``Neo4jDBHandler.analysis_pre_check`` in *scope-lib*.
|
|
351
|
+
"""
|
|
352
|
+
if report_type not in _VALID_REPORT_TYPES:
|
|
353
|
+
raise ValueError(
|
|
354
|
+
f"Unknown report type: {report_type!r}. "
|
|
355
|
+
f"Must be one of {', '.join(sorted(_VALID_REPORT_TYPES))}."
|
|
356
|
+
)
|
|
357
|
+
report_edge = _REPORT_TYPE_TO_EDGE[report_type]
|
|
358
|
+
query = f"""
|
|
359
|
+
OPTIONAL MATCH (sg:SemanticGroup {{id: $group_id}})
|
|
360
|
+
WITH sg, sg IS NOT NULL AND ($group_hash = "" OR sg.nodeHash = $group_hash) AS hash_matches
|
|
361
|
+
OPTIONAL MATCH (sg)-[:{report_edge}]->(report:{report_type})
|
|
362
|
+
WHERE $group_hash = "" OR report.nodeHash = $group_hash
|
|
363
|
+
WITH sg, hash_matches, count(report) > 0 AS report_exists
|
|
364
|
+
"""
|
|
365
|
+
if with_session_id:
|
|
366
|
+
query += """
|
|
367
|
+
OPTIONAL MATCH (sg)-[:containsSession]->(s:Session {sessionId: $session_id})
|
|
368
|
+
WITH hash_matches, report_exists, count(s) AS session_count
|
|
369
|
+
RETURN hash_matches AND NOT report_exists AND session_count > 0 AS can_analyze
|
|
370
|
+
"""
|
|
371
|
+
else:
|
|
372
|
+
query += "RETURN hash_matches AND NOT report_exists AS can_analyze"
|
|
373
|
+
return query, {}
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def build_all_metrics_for_session_query() -> tuple[str, Dict[str, object]]:
|
|
377
|
+
"""Build the Cypher query that fetches all metric name/result pairs for a session.
|
|
378
|
+
|
|
379
|
+
The caller supplies ``session_id`` in the params dict.
|
|
380
|
+
|
|
381
|
+
Mirrors ``Neo4jConnector.get_all_metrics_for_a_session`` in *scope-lib*.
|
|
382
|
+
"""
|
|
383
|
+
query = """
|
|
384
|
+
MATCH (r:MetricResult)-[:measures]->(s:Session {sessionId: $session_id})
|
|
385
|
+
MATCH (r)-[:ofMetricType]->(d:Metric)
|
|
386
|
+
RETURN d.name AS metricName, r.result AS metricResult
|
|
387
|
+
"""
|
|
388
|
+
return query, {"session_id": None}
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def build_mas_name_query() -> tuple[str, Dict[str, object]]:
|
|
392
|
+
"""Build the Cypher query that looks up the MAS name for a session.
|
|
393
|
+
|
|
394
|
+
The caller supplies ``session_id`` in the params dict.
|
|
395
|
+
|
|
396
|
+
Mirrors ``Neo4jConnector.get_mas_name`` in *scope-lib*.
|
|
397
|
+
"""
|
|
398
|
+
query = """
|
|
399
|
+
MATCH (s:Session {sessionId: $session_id})-[:executesSession]->(mas:MAS)
|
|
400
|
+
RETURN mas.name AS masName
|
|
401
|
+
"""
|
|
402
|
+
return query, {"session_id": None}
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def build_impact_assessment_training_data_query(
|
|
406
|
+
session_ids: list[str], embedding_model_name: str
|
|
407
|
+
) -> tuple[str, Dict[str, object]]:
|
|
408
|
+
"""Build the Cypher query that retrieves raw impact-assessment training data.
|
|
409
|
+
|
|
410
|
+
Mirrors ``Neo4jConnector.retrieve_raw_impact_assessment_data`` in *scope-lib*.
|
|
411
|
+
"""
|
|
412
|
+
query = """
|
|
413
|
+
MATCH (s:Session)
|
|
414
|
+
WHERE s.sessionId IN $included_ids
|
|
415
|
+
|
|
416
|
+
MATCH (s)-[:hasInitialState]->(start:State)
|
|
417
|
+
|
|
418
|
+
MATCH (t:Transition {sessionId: s.sessionId})-[:representsExecution]->(ac:AgentCall)
|
|
419
|
+
OPTIONAL MATCH (ac)-[:executesAgent]->(agentNode:Agent)
|
|
420
|
+
MATCH (input_embedding:Embedding {embeddingModel: $emb_model})-[:represents]->(input:State)-[:inputTo]->(t)
|
|
421
|
+
MATCH (t)-[:leadsTo]->(output:State)<-[:represents]-(output_embedding:Embedding {embeddingModel: $emb_model})
|
|
422
|
+
|
|
423
|
+
WITH s, start, t, ac, agentNode, input, output, input_embedding, output_embedding
|
|
424
|
+
ORDER BY ac.startTime ASC
|
|
425
|
+
|
|
426
|
+
WITH s, start, collect({
|
|
427
|
+
agent: agentNode.name,
|
|
428
|
+
input: input.content,
|
|
429
|
+
input_embedding: input_embedding.embeddingVector,
|
|
430
|
+
output: output.content,
|
|
431
|
+
output_embedding: output_embedding.embeddingVector
|
|
432
|
+
}) as Triples
|
|
433
|
+
|
|
434
|
+
RETURN DISTINCT
|
|
435
|
+
s.sessionId AS SessionID,
|
|
436
|
+
Triples
|
|
437
|
+
"""
|
|
438
|
+
return query, {"included_ids": session_ids, "emb_model": embedding_model_name}
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def build_all_mas_metric_pairs_query() -> tuple[str, Dict[str, object]]:
|
|
442
|
+
"""Build the Cypher query that returns all distinct MAS/metric-name pairs.
|
|
443
|
+
|
|
444
|
+
Mirrors ``Neo4jConnector.get_all_mas_metric_pairs`` in *scope-lib*.
|
|
445
|
+
"""
|
|
446
|
+
query = """
|
|
447
|
+
MATCH (mas:MAS)<-[:executesSession]-(s:Session)
|
|
448
|
+
MATCH (r:MetricResult)-[:measures]->(s)
|
|
449
|
+
MATCH (r)-[:ofMetricType]->(d:Metric)
|
|
450
|
+
RETURN DISTINCT mas.id AS masId, d.name AS metricName
|
|
451
|
+
"""
|
|
452
|
+
return query, {}
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def build_all_application_ids_query() -> tuple[str, Dict[str, object]]:
|
|
456
|
+
"""Build the Cypher query that returns all distinct non-null MAS names."""
|
|
457
|
+
query = """
|
|
458
|
+
MATCH (mas:MAS)
|
|
459
|
+
WHERE mas.id IS NOT NULL
|
|
460
|
+
RETURN DISTINCT mas.id AS masId
|
|
461
|
+
"""
|
|
462
|
+
return query, {}
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def build_all_mas_ids_query() -> tuple[str, Dict[str, object]]:
|
|
466
|
+
"""Build the Cypher query that returns all distinct non-null MAS ids."""
|
|
467
|
+
query = """
|
|
468
|
+
MATCH (mas:MAS)
|
|
469
|
+
WHERE mas.id IS NOT NULL
|
|
470
|
+
RETURN DISTINCT mas.id AS masId
|
|
471
|
+
"""
|
|
472
|
+
return query, {}
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def build_remove_semantic_groups_query(ids: List[str]) -> tuple[str, Dict[str, object]]:
|
|
476
|
+
"""Build the query that removes semantic groups and attached analysis nodes."""
|
|
477
|
+
query = """
|
|
478
|
+
MATCH (n:SemanticGroup) WHERE n.id IN $ids
|
|
479
|
+
OPTIONAL MATCH (n)-[]-(r)
|
|
480
|
+
WHERE r:NormalBehaviourReport OR r:ConsistencyReport
|
|
481
|
+
OR r:AnomalyReport
|
|
482
|
+
DETACH DELETE r, n
|
|
483
|
+
"""
|
|
484
|
+
return query, {"ids": ids}
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def build_cleanup_semantic_groups_query(
|
|
488
|
+
ids: List[str],
|
|
489
|
+
) -> tuple[str, Dict[str, object]]:
|
|
490
|
+
"""Build the query that clears rels/reports for upserted semantic groups."""
|
|
491
|
+
query = """
|
|
492
|
+
MATCH (n:SemanticGroup) WHERE n.id IN $ids
|
|
493
|
+
OPTIONAL MATCH (n)-[rel:containsSession]->()
|
|
494
|
+
OPTIONAL MATCH (n)-[medioid_rel:hasMedioidSession]->()
|
|
495
|
+
OPTIONAL MATCH (n)-[]-(r)
|
|
496
|
+
WHERE r:NormalBehaviourReport OR r:ConsistencyReport
|
|
497
|
+
OR r:AnomalyReport
|
|
498
|
+
DELETE rel, medioid_rel
|
|
499
|
+
DETACH DELETE r
|
|
500
|
+
"""
|
|
501
|
+
return query, {"ids": ids}
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def build_delete_stale_child_edges_query(
|
|
505
|
+
child_ids: List[str],
|
|
506
|
+
) -> tuple[str, Dict[str, object]]:
|
|
507
|
+
"""Build the query that deletes stale parent->child semantic-group edges."""
|
|
508
|
+
query = """
|
|
509
|
+
UNWIND $child_ids AS child_id
|
|
510
|
+
MATCH (:SemanticGroup)-[rel:containsSession]->(child:SemanticGroup {id: child_id})
|
|
511
|
+
DELETE rel
|
|
512
|
+
"""
|
|
513
|
+
return query, {"child_ids": child_ids}
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def build_ingest_node_query(
|
|
517
|
+
label: str,
|
|
518
|
+
properties: Dict[str, Any],
|
|
519
|
+
) -> tuple[str, Dict[str, object]]:
|
|
520
|
+
"""Build the query that upserts/creates a node for DAL ingest operations."""
|
|
521
|
+
if "id" in properties:
|
|
522
|
+
query = f"MERGE (n:{label} {{id: $id}}) SET n += $properties"
|
|
523
|
+
params: Dict[str, object] = {"id": properties["id"], "properties": properties}
|
|
524
|
+
else:
|
|
525
|
+
query = f"CREATE (n:{label}) SET n = $properties"
|
|
526
|
+
params = {"properties": properties}
|
|
527
|
+
return query, params
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def build_create_rel_query(
|
|
531
|
+
from_label: str,
|
|
532
|
+
from_id_labels: List[str],
|
|
533
|
+
from_id_values: List[Any],
|
|
534
|
+
to_label: str,
|
|
535
|
+
to_id_labels: List[str],
|
|
536
|
+
to_id_values: List[Any],
|
|
537
|
+
relationship: str,
|
|
538
|
+
) -> tuple[str, Dict[str, object]]:
|
|
539
|
+
"""Build the query that creates a directed relationship between two nodes."""
|
|
540
|
+
query = ""
|
|
541
|
+
params: Dict[str, object] = {}
|
|
542
|
+
for i, (lbl, val) in enumerate(zip(from_id_labels, from_id_values)):
|
|
543
|
+
query += f"MATCH (a:{from_label} {{{lbl}: $from_id_{i}}})\n"
|
|
544
|
+
params[f"from_id_{i}"] = val
|
|
545
|
+
for i, (lbl, val) in enumerate(zip(to_id_labels, to_id_values)):
|
|
546
|
+
query += f"MATCH (b:{to_label} {{{lbl}: $to_id_{i}}})\n"
|
|
547
|
+
params[f"to_id_{i}"] = val
|
|
548
|
+
query += f"MERGE (a)-[:{relationship}]->(b)"
|
|
549
|
+
return query, params
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def build_cleanup_outdated_insights_query(
|
|
553
|
+
target_label: str,
|
|
554
|
+
target_id_field: str,
|
|
555
|
+
target_node_id: str,
|
|
556
|
+
template_id: str,
|
|
557
|
+
current_ids: List[str],
|
|
558
|
+
) -> tuple[str, Dict[str, object]]:
|
|
559
|
+
"""Build the query that detaches and prunes outdated insights."""
|
|
560
|
+
query = (
|
|
561
|
+
f"MATCH (target:{target_label} {{{target_id_field}: $target_node_id}})"
|
|
562
|
+
f"-[rel:hasInsight]->(old:Insight {{templateId: $template_id}})\n"
|
|
563
|
+
"WHERE NOT old.id IN $current_ids\n"
|
|
564
|
+
"DELETE rel\n"
|
|
565
|
+
"WITH old\n"
|
|
566
|
+
"WHERE NOT ()-[:hasInsight]->(old)\n"
|
|
567
|
+
"DETACH DELETE old"
|
|
568
|
+
)
|
|
569
|
+
params: Dict[str, object] = {
|
|
570
|
+
"target_node_id": target_node_id,
|
|
571
|
+
"template_id": template_id,
|
|
572
|
+
"current_ids": current_ids,
|
|
573
|
+
}
|
|
574
|
+
return query, params
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def build_analysis_data_for_semantic_group_query(
|
|
578
|
+
group_id: str,
|
|
579
|
+
group_hash: str,
|
|
580
|
+
embedding_model: str,
|
|
581
|
+
skip: int = 0,
|
|
582
|
+
limit: int = 0,
|
|
583
|
+
) -> tuple[str, Dict[str, object]]:
|
|
584
|
+
"""Build the Cypher query that retrieves all session data for a semantic group.
|
|
585
|
+
|
|
586
|
+
Mirrors ``Neo4jDBHandler.get_analysis_data_for_semantic_group`` in *scope-lib*.
|
|
587
|
+
"""
|
|
588
|
+
query = """
|
|
589
|
+
MATCH (sg:SemanticGroup {id: $group_id})
|
|
590
|
+
WHERE ($group_hash = "" OR sg.nodeHash = $group_hash)
|
|
591
|
+
AND NOT EXISTS { MATCH (sg)-[:containsSession]->(:SemanticGroup) }
|
|
592
|
+
WITH coalesce(sg.sessionIds, []) AS session_ids
|
|
593
|
+
WITH CASE
|
|
594
|
+
WHEN $limit > 0 THEN session_ids[$skip..($skip + $limit)]
|
|
595
|
+
ELSE session_ids
|
|
596
|
+
END AS paged_session_ids
|
|
597
|
+
UNWIND paged_session_ids AS session_id
|
|
598
|
+
MATCH (session:Session {sessionId: session_id})
|
|
599
|
+
|
|
600
|
+
CALL (session) {
|
|
601
|
+
OPTIONAL MATCH (mr:MetricResult)-[:measures]->(session)
|
|
602
|
+
OPTIONAL MATCH (mr)-[:ofMetricType]->(md:Metric)
|
|
603
|
+
RETURN [item IN collect(DISTINCT CASE
|
|
604
|
+
WHEN mr IS NULL THEN NULL
|
|
605
|
+
ELSE {metricName: md.name, metricResult: mr.result, provider: md.metricProvider, reasoning: mr.reasoning}
|
|
606
|
+
END) WHERE item IS NOT NULL] AS metrics
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
CALL (session) {
|
|
610
|
+
OPTIONAL MATCH (session)-[:hasInitialState]->(input_state:State)
|
|
611
|
+
OPTIONAL MATCH (input_embedding:Embedding {embeddingModel: $embedding_model})-[:represents]->(input_state)
|
|
612
|
+
RETURN
|
|
613
|
+
head(collect(DISTINCT input_state.content)) AS input_content,
|
|
614
|
+
coalesce(head(collect(DISTINCT input_embedding.embeddingVector)), []) AS input_embedding
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
CALL (session) {
|
|
618
|
+
OPTIONAL MATCH (session)-[:hasFinalState]->(output_state:State)
|
|
619
|
+
OPTIONAL MATCH (output_embedding:Embedding {embeddingModel: $embedding_model})-[:represents]->(output_state)
|
|
620
|
+
RETURN
|
|
621
|
+
head(collect(DISTINCT output_state.content)) AS output_content,
|
|
622
|
+
coalesce(head(collect(DISTINCT output_embedding.embeddingVector)), []) AS output_embedding
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
CALL (session) {
|
|
626
|
+
OPTIONAL MATCH (ac:AgentCall)
|
|
627
|
+
WHERE ac.sessionId = session.sessionId
|
|
628
|
+
OPTIONAL MATCH (ac)-[:executesAgent]->(agentNode:Agent)
|
|
629
|
+
OPTIONAL MATCH (t1:Transition)-[:representsExecution]->(ac)
|
|
630
|
+
WHERE t1.sessionId = session.sessionId
|
|
631
|
+
OPTIONAL MATCH (t1)-[:leadsTo]->(:State)-[:inputTo]->(t2:Transition)-[:representsExecution]->(ac_next:AgentCall)
|
|
632
|
+
WHERE t2.sessionId = session.sessionId
|
|
633
|
+
RETURN
|
|
634
|
+
[node IN collect(DISTINCT CASE
|
|
635
|
+
WHEN ac IS NULL THEN NULL
|
|
636
|
+
ELSE { node_id: ac.id, agent_id: agentNode.name }
|
|
637
|
+
END) WHERE node IS NOT NULL] AS graph_nodes,
|
|
638
|
+
[edge IN collect(DISTINCT CASE
|
|
639
|
+
WHEN ac_next IS NULL THEN NULL
|
|
640
|
+
ELSE { source: ac.id, target: ac_next.id }
|
|
641
|
+
END) WHERE edge IS NOT NULL] AS graph_edges
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
RETURN
|
|
645
|
+
session.sessionId AS session_id,
|
|
646
|
+
input_content,
|
|
647
|
+
input_embedding,
|
|
648
|
+
output_content,
|
|
649
|
+
output_embedding,
|
|
650
|
+
metrics,
|
|
651
|
+
graph_nodes,
|
|
652
|
+
graph_edges
|
|
653
|
+
"""
|
|
654
|
+
params: Dict[str, object] = {
|
|
655
|
+
"group_id": group_id,
|
|
656
|
+
"group_hash": group_hash,
|
|
657
|
+
"embedding_model": embedding_model,
|
|
658
|
+
"skip": max(0, skip),
|
|
659
|
+
"limit": max(0, limit),
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
return query, params
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def build_session_data_for_ia_inference_query(
|
|
666
|
+
session_id: str,
|
|
667
|
+
metric_name: str,
|
|
668
|
+
embedding_model_name: str,
|
|
669
|
+
) -> tuple[str, Dict[str, object]]:
|
|
670
|
+
"""Build the Cypher query for session data used in IA inference.
|
|
671
|
+
|
|
672
|
+
Mirrors ``Neo4jDBHandler.get_session_data_for_ia_inference`` in *scope-lib*.
|
|
673
|
+
"""
|
|
674
|
+
query = """
|
|
675
|
+
MATCH (s:Session {sessionId: $session_id})
|
|
676
|
+
MATCH (m:MetricResult)-[:measures]->(s)
|
|
677
|
+
MATCH (m)-[:ofMetricType]->(md:Metric {name: $metric_name})
|
|
678
|
+
MATCH (t:Transition {sessionId: s.sessionId})-[:representsExecution]->(ac:AgentCall)
|
|
679
|
+
OPTIONAL MATCH (ac)-[:executesAgent]->(agentNode:Agent)
|
|
680
|
+
MATCH (input_embedding:Embedding {embeddingModel: $emb_model})-[:represents]->(input:State)-[:inputTo]->(t)
|
|
681
|
+
MATCH (t)-[:leadsTo]->(output:State)<-[:represents]-(output_embedding:Embedding {embeddingModel: $emb_model})
|
|
682
|
+
|
|
683
|
+
WITH s, m, t, ac, agentNode, input, output, input_embedding, output_embedding
|
|
684
|
+
ORDER BY ac.startTime ASC
|
|
685
|
+
|
|
686
|
+
WITH s, m, collect({
|
|
687
|
+
agent: agentNode.name,
|
|
688
|
+
input: input.content,
|
|
689
|
+
input_embedding: input_embedding.embeddingVector,
|
|
690
|
+
output: output.content,
|
|
691
|
+
output_embedding: output_embedding.embeddingVector
|
|
692
|
+
}) AS triples
|
|
693
|
+
|
|
694
|
+
RETURN
|
|
695
|
+
s.sessionId AS SessionID,
|
|
696
|
+
triples AS Triples,
|
|
697
|
+
m.result AS RawMetric
|
|
698
|
+
"""
|
|
699
|
+
return query, {
|
|
700
|
+
"session_id": session_id,
|
|
701
|
+
"metric_name": metric_name,
|
|
702
|
+
"emb_model": embedding_model_name,
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def build_all_metrics_for_a_group_of_sessions_query(
|
|
707
|
+
session_ids: List[str], subset: Iterable[str] | None
|
|
708
|
+
) -> Tuple[str, Dict[str, object]]:
|
|
709
|
+
params = {"session_ids": session_ids}
|
|
710
|
+
match_clause: str = "MATCH (m:MetricResult)-[:measures]->(s:Session), (m)-[:ofMetricType]->(d:Metric)"
|
|
711
|
+
condition: str = "(s.sessionId IN $session_ids)"
|
|
712
|
+
if subset is not None:
|
|
713
|
+
params["metric_names"] = list(subset)
|
|
714
|
+
condition = f"({condition} AND (d.name in $metric_names))"
|
|
715
|
+
query: str = f"""{match_clause}
|
|
716
|
+
WHERE {condition}
|
|
717
|
+
RETURN Distinct
|
|
718
|
+
s.sessionId as sessionId,
|
|
719
|
+
d.name as metricName,
|
|
720
|
+
m.result as metricResult
|
|
721
|
+
"""
|
|
722
|
+
return query, params
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def build_waste_estimation_data_query(
|
|
726
|
+
session_ids: list[str], embedding_model_name: str
|
|
727
|
+
) -> tuple[str, dict[str, Any]]:
|
|
728
|
+
query = """
|
|
729
|
+
MATCH (s:Session)
|
|
730
|
+
WHERE s.sessionId IN $included_ids
|
|
731
|
+
|
|
732
|
+
MATCH (s)-[:hasInitialState]->(start:State)
|
|
733
|
+
|
|
734
|
+
MATCH (t:Transition {sessionId: s.sessionId})-[:representsExecution]->(ac:AgentCall)
|
|
735
|
+
MATCH (input_embedding:Embedding {embeddingModel: $emb_model})-[:represents]->(input:State)-[:inputTo]->(t)
|
|
736
|
+
|
|
737
|
+
WITH s, t, ac, input, input_embedding
|
|
738
|
+
ORDER BY ac.startTime ASC
|
|
739
|
+
|
|
740
|
+
WITH s, head(collect({
|
|
741
|
+
question: input.content,
|
|
742
|
+
question_embedding: input_embedding.embeddingVector
|
|
743
|
+
})) AS first_block
|
|
744
|
+
|
|
745
|
+
RETURN DISTINCT
|
|
746
|
+
s.sessionId AS SessionID,
|
|
747
|
+
first_block.question AS question,
|
|
748
|
+
first_block.question_embedding AS question_embedding
|
|
749
|
+
"""
|
|
750
|
+
|
|
751
|
+
params = {"included_ids": session_ids, "emb_model": embedding_model_name}
|
|
752
|
+
return query, params
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
def _build_wr_all_sessions_query(
|
|
756
|
+
excluded_session_ids: Optional[List[str]] = None,
|
|
757
|
+
) -> tuple[str, Dict[str, object]]:
|
|
758
|
+
query = """
|
|
759
|
+
MATCH (s:Session)
|
|
760
|
+
WHERE s.sessionId IS NOT NULL
|
|
761
|
+
AND trim(s.sessionId) <> ""
|
|
762
|
+
AND (
|
|
763
|
+
size(coalesce($excluded_session_ids, [])) = 0
|
|
764
|
+
OR NOT s.sessionId IN $excluded_session_ids
|
|
765
|
+
)
|
|
766
|
+
RETURN DISTINCT s.sessionId AS session_id
|
|
767
|
+
"""
|
|
768
|
+
return query, {"excluded_session_ids": excluded_session_ids or []}
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
def _build_wr_sessions_by_setting_with_metrics_query(
|
|
772
|
+
mas_id: Optional[str],
|
|
773
|
+
excluded_session_ids: Optional[list[str]] = None,
|
|
774
|
+
) -> tuple[str, Dict[str, object]]:
|
|
775
|
+
query = """
|
|
776
|
+
MATCH (s:Session)-[:executesSession]->(mas:MAS)
|
|
777
|
+
WHERE s.sessionId IS NOT NULL
|
|
778
|
+
AND trim(s.sessionId) <> ""
|
|
779
|
+
AND ($mas_id IS NULL OR coalesce(mas.id, "") = $mas_id)
|
|
780
|
+
AND (
|
|
781
|
+
size(coalesce($excluded_session_ids, [])) = 0
|
|
782
|
+
OR NOT s.sessionId IN $excluded_session_ids
|
|
783
|
+
)
|
|
784
|
+
AND EXISTS { MATCH (:MetricResult)-[:measures]->(s) }
|
|
785
|
+
RETURN DISTINCT s.sessionId AS session_id
|
|
786
|
+
"""
|
|
787
|
+
return query, {
|
|
788
|
+
"mas_id": mas_id,
|
|
789
|
+
"excluded_session_ids": excluded_session_ids or [],
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
def build_wr_session_ids(
|
|
794
|
+
mas_id: Optional[str] = None, excluded_session_ids: Optional[List[str]] = None
|
|
795
|
+
):
|
|
796
|
+
if mas_id is None:
|
|
797
|
+
query, params = _build_wr_all_sessions_query(
|
|
798
|
+
excluded_session_ids=excluded_session_ids,
|
|
799
|
+
)
|
|
800
|
+
else:
|
|
801
|
+
query, params = _build_wr_sessions_by_setting_with_metrics_query(
|
|
802
|
+
mas_id=mas_id,
|
|
803
|
+
excluded_session_ids=excluded_session_ids,
|
|
804
|
+
)
|
|
805
|
+
return query, params
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
def build_wr_agent_tool_baseline_by_session_ids_query(
|
|
809
|
+
session_ids: list[str],
|
|
810
|
+
) -> tuple[str, Dict[str, object]]:
|
|
811
|
+
query = """
|
|
812
|
+
UNWIND $session_ids AS sid
|
|
813
|
+
MATCH (t:Transition {sessionId: sid})-[:representsExecution]->(ac:AgentCall)
|
|
814
|
+
OPTIONAL MATCH (ac)-[:executesAgent]->(agentNode:Agent)
|
|
815
|
+
OPTIONAL MATCH (ac)-[:hasToolCall]->(tc:ToolCall)
|
|
816
|
+
OPTIONAL MATCH (tc)-[:executesTool]->(toolNode:Tool)
|
|
817
|
+
RETURN
|
|
818
|
+
coalesce(agentNode.name, "") AS agent_name,
|
|
819
|
+
coalesce(toolNode.name, "") AS tool_name
|
|
820
|
+
"""
|
|
821
|
+
return query, {"session_ids": session_ids}
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
def build_wr_tool_calls_by_session_query(sid: str) -> tuple[str, Dict[str, object]]:
|
|
825
|
+
query = """
|
|
826
|
+
MATCH (t:Transition {sessionId: $sid})-[:representsExecution]->(ac:AgentCall)-[:hasToolCall]->(tc:ToolCall)
|
|
827
|
+
OPTIONAL MATCH (tc)-[:executesTool]->(toolNode:Tool)
|
|
828
|
+
OPTIONAL MATCH (ac)-[:executesAgent]->(agentNode:Agent)
|
|
829
|
+
OPTIONAL MATCH (tc)-[:hasInitialState]->(input_state:State)
|
|
830
|
+
OPTIONAL MATCH (tc)-[:hasFinalState]->(output_state:State)
|
|
831
|
+
RETURN
|
|
832
|
+
coalesce(toolNode.name, "") AS tool_name,
|
|
833
|
+
coalesce(input_state.content, "") AS input_params,
|
|
834
|
+
coalesce(output_state.content, "") AS tool_output,
|
|
835
|
+
coalesce(output_state.content, "") AS output_content,
|
|
836
|
+
coalesce(tc.startTime, 0.0) AS timestamp,
|
|
837
|
+
coalesce(agentNode.name, "") AS agent_name
|
|
838
|
+
ORDER BY timestamp ASC
|
|
839
|
+
"""
|
|
840
|
+
return query, {"sid": sid}
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
def build_wr_agent_calls_by_session_query(sid: str) -> tuple[str, Dict[str, object]]:
|
|
844
|
+
query = """
|
|
845
|
+
MATCH (t:Transition {sessionId: $sid})-[:representsExecution]->(ac:AgentCall)
|
|
846
|
+
OPTIONAL MATCH (ac)-[:executesAgent]->(agentNode:Agent)
|
|
847
|
+
OPTIONAL MATCH (ac)-[:hasToolCall]->(tc:ToolCall)
|
|
848
|
+
OPTIONAL MATCH (tc)-[:executesTool]->(toolNode:Tool)
|
|
849
|
+
WITH
|
|
850
|
+
ac,
|
|
851
|
+
agentNode,
|
|
852
|
+
count(tc) AS tool_call_count,
|
|
853
|
+
collect(DISTINCT coalesce(toolNode.name, "")) AS tool_names
|
|
854
|
+
RETURN
|
|
855
|
+
elementId(ac) AS agentcall_id,
|
|
856
|
+
coalesce(agentNode.name, "") AS agent_name,
|
|
857
|
+
coalesce(ac.startTime, 0.0) AS timestamp,
|
|
858
|
+
tool_call_count,
|
|
859
|
+
[name IN tool_names WHERE name <> ""] AS tool_names
|
|
860
|
+
ORDER BY timestamp ASC, agentcall_id ASC
|
|
861
|
+
"""
|
|
862
|
+
return query, {"sid": sid}
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
def build_wr_agent_tool_counts_by_session_query(
|
|
866
|
+
sid: str,
|
|
867
|
+
) -> tuple[str, Dict[str, object]]:
|
|
868
|
+
query = """
|
|
869
|
+
MATCH (t:Transition {sessionId: $sid})-[:representsExecution]->(ac:AgentCall)-[:hasToolCall]->(tc:ToolCall)
|
|
870
|
+
OPTIONAL MATCH (ac)-[:executesAgent]->(agentNode:Agent)
|
|
871
|
+
OPTIONAL MATCH (tc)-[:executesTool]->(toolNode:Tool)
|
|
872
|
+
WITH
|
|
873
|
+
coalesce(agentNode.name, "") AS agent_name,
|
|
874
|
+
coalesce(toolNode.name, "") AS tool_name
|
|
875
|
+
WHERE agent_name <> "" AND tool_name <> ""
|
|
876
|
+
RETURN agent_name, tool_name, count(*) AS call_count
|
|
877
|
+
ORDER BY agent_name, tool_name
|
|
878
|
+
"""
|
|
879
|
+
return query, {"sid": sid}
|
|
880
|
+
|
|
881
|
+
|
|
882
|
+
def build_wr_llm_calls_via_edges_query(sid: str) -> tuple[str, Dict[str, object]]:
|
|
883
|
+
query = """
|
|
884
|
+
MATCH (t:Transition {sessionId: $sid})-[:representsExecution]->(ac:AgentCall)
|
|
885
|
+
OPTIONAL MATCH (ac)-[:hasLLMCall]->(lc:LLMCall)
|
|
886
|
+
WITH DISTINCT lc
|
|
887
|
+
WHERE lc IS NOT NULL
|
|
888
|
+
OPTIONAL MATCH (lc)-[:executesLLM]->(llmNode:LLM)
|
|
889
|
+
RETURN
|
|
890
|
+
elementId(lc) AS node_eid,
|
|
891
|
+
coalesce(lc.id, "") AS execution_id,
|
|
892
|
+
coalesce(llmNode.name, "") AS model_name,
|
|
893
|
+
coalesce(lc.promptTokenCount, 0) AS prompt_tokens,
|
|
894
|
+
coalesce(lc.cacheReadTokenCount, 0) AS cached_tokens,
|
|
895
|
+
coalesce(lc.completionTokenCount, 0) AS completion_tokens,
|
|
896
|
+
coalesce(lc.totalTokenCount, 0) AS total_tokens,
|
|
897
|
+
coalesce(lc.startTime, 0.0) AS timestamp
|
|
898
|
+
ORDER BY timestamp ASC
|
|
899
|
+
"""
|
|
900
|
+
return query, {"sid": sid}
|
|
901
|
+
|
|
902
|
+
|
|
903
|
+
def build_wr_llm_calls_by_session_property_query(
|
|
904
|
+
sid: str,
|
|
905
|
+
) -> tuple[str, Dict[str, object]]:
|
|
906
|
+
query = """
|
|
907
|
+
MATCH (lc:LLMCall {sessionId: $sid})
|
|
908
|
+
OPTIONAL MATCH (lc)-[:executesLLM]->(llmNode:LLM)
|
|
909
|
+
RETURN
|
|
910
|
+
elementId(lc) AS node_eid,
|
|
911
|
+
coalesce(lc.id, "") AS execution_id,
|
|
912
|
+
coalesce(llmNode.name, "") AS model_name,
|
|
913
|
+
coalesce(lc.promptTokenCount, 0) AS prompt_tokens,
|
|
914
|
+
coalesce(lc.cacheReadTokenCount, 0) AS cached_tokens,
|
|
915
|
+
coalesce(lc.completionTokenCount, 0) AS completion_tokens,
|
|
916
|
+
coalesce(lc.totalTokenCount, 0) AS total_tokens,
|
|
917
|
+
coalesce(lc.startTime, 0.0) AS timestamp
|
|
918
|
+
ORDER BY timestamp ASC
|
|
919
|
+
"""
|
|
920
|
+
return query, {"sid": sid}
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
def build_wr_session_metrics_query(sid: str) -> tuple[str, Dict[str, object]]:
|
|
924
|
+
query = """
|
|
925
|
+
MATCH (m:MetricResult)-[:measures]->(s:Session {sessionId: $sid})
|
|
926
|
+
MATCH (m)-[:ofMetricType]->(d:Metric)
|
|
927
|
+
RETURN
|
|
928
|
+
coalesce(d.name, "") AS metric_name,
|
|
929
|
+
coalesce(m.result, "") AS metric_result
|
|
930
|
+
"""
|
|
931
|
+
return query, {"sid": sid}
|