ioc-scope-norm 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_norm-1.0.0.dist-info/METADATA +27 -0
- ioc_scope_norm-1.0.0.dist-info/RECORD +24 -0
- ioc_scope_norm-1.0.0.dist-info/WHEEL +4 -0
- norm/__init__.py +39 -0
- norm/compare.py +372 -0
- norm/ioa_observe/__init__.py +6 -0
- norm/ioa_observe/build.py +88 -0
- norm/ioa_observe/fields.py +109 -0
- norm/ioa_observe/handlers/__init__.py +18 -0
- norm/ioa_observe/handlers/agent.py +141 -0
- norm/ioa_observe/handlers/chat.py +135 -0
- norm/ioa_observe/handlers/graph.py +89 -0
- norm/ioa_observe/handlers/session.py +89 -0
- norm/ioa_observe/handlers/tool.py +103 -0
- norm/ioa_observe/heuristics/__init__.py +16 -0
- norm/ioa_observe/heuristics/capability_chain.py +90 -0
- norm/ioa_observe/heuristics/container_boundary_states.py +57 -0
- norm/ioa_observe/heuristics/handoff.py +145 -0
- norm/ioa_observe/otel_io.py +36 -0
- norm/ioa_observe/registry.py +109 -0
- norm/ioa_observe/trajectory.py +199 -0
- norm/normalizer.py +79 -0
- norm/ontology.py +112 -0
- norm/verifier.py +806 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ioc-scope-norm
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: OTel(ioa_observe) span -> Knowledge Graph normalization.
|
|
5
|
+
Author-email: Outshift Open <oss-github@cisco.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: ioc-scope-ontology>=1.1.0
|
|
9
|
+
Requires-Dist: neo4j>=6.3.1
|
|
10
|
+
Requires-Dist: pydantic>=2.0.0
|
|
11
|
+
Provides-Extra: all
|
|
12
|
+
Requires-Dist: pyshacl>=0.25.0; extra == 'all'
|
|
13
|
+
Requires-Dist: pytest-asyncio>=0.21; extra == 'all'
|
|
14
|
+
Requires-Dist: pytest-cov>=4.0; extra == 'all'
|
|
15
|
+
Requires-Dist: pytest>=7.0; extra == 'all'
|
|
16
|
+
Requires-Dist: rdflib>=6.0.0; extra == 'all'
|
|
17
|
+
Requires-Dist: ruff>=0.12.10; extra == 'all'
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pyshacl>=0.25.0; extra == 'dev'
|
|
20
|
+
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
|
|
21
|
+
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
|
|
22
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
23
|
+
Requires-Dist: rdflib>=6.0.0; extra == 'dev'
|
|
24
|
+
Requires-Dist: ruff>=0.12.10; extra == 'dev'
|
|
25
|
+
Provides-Extra: graph
|
|
26
|
+
Requires-Dist: pyshacl>=0.25.0; extra == 'graph'
|
|
27
|
+
Requires-Dist: rdflib>=6.0.0; extra == 'graph'
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
norm/__init__.py,sha256=N77h5_08XLrTop_Wr4PDC9qwoFCpLWkJC9ifBkujZy0,1014
|
|
2
|
+
norm/compare.py,sha256=rB3bLmM7zf2n0gbHsEWlLV9ehCsD-ItR-RQ49HyCP4M,12307
|
|
3
|
+
norm/normalizer.py,sha256=kVVHh52VyLcx6BtNt9roYQBgiL-V9qZmUNWaL2BCXgE,2910
|
|
4
|
+
norm/ontology.py,sha256=ghWFwIPZIq8JdDZtKdvi_x-hFXg0BIJti6MiqxkBF5k,4225
|
|
5
|
+
norm/verifier.py,sha256=x7HqJgG6lX7u_-vSXZy_-vCbkp9s0KHlIK8EwGvVaR8,32263
|
|
6
|
+
norm/ioa_observe/__init__.py,sha256=K1vSSHrPZxX-8adF6yFuCVjIzK3f3sUG1GBcvkFVvtE,153
|
|
7
|
+
norm/ioa_observe/build.py,sha256=Fv38j6MX5k730p9_D9Ksru3-lUx4DKmEQ88TjPB3ffQ,3108
|
|
8
|
+
norm/ioa_observe/fields.py,sha256=hrTtWN9JK7wngSg12k5kUjYpuhdt-a8DGEwFhR1l6NE,3908
|
|
9
|
+
norm/ioa_observe/otel_io.py,sha256=XJJgQva3Zol0nWP4p1o1dNh383qYJA3KAaGM7bmraRQ,1248
|
|
10
|
+
norm/ioa_observe/registry.py,sha256=ob3BlInBcE_I4o8kr0gxBHI-lP-7O7F0lXPWR6HNugs,4518
|
|
11
|
+
norm/ioa_observe/trajectory.py,sha256=_t54X3b4axnQJdbhQYusSrbCP5NV7DXj51rlh60S_YI,8257
|
|
12
|
+
norm/ioa_observe/handlers/__init__.py,sha256=xw-2BZ53zKW8TwbZVGBoh9BPbgehsaUO_x31O0GMlHs,512
|
|
13
|
+
norm/ioa_observe/handlers/agent.py,sha256=xAm7jHfVuZMtySg3v0httL2MjAQJIeHvtUe8YgQ5bXs,4494
|
|
14
|
+
norm/ioa_observe/handlers/chat.py,sha256=6_ZQKsankxYt8j2QJcbVso2aAbhzENErEVFS4g01JSM,4775
|
|
15
|
+
norm/ioa_observe/handlers/graph.py,sha256=fQPISbNr_uk6CMJCBRK01KhA0JIfOcrPbFBffILNQUc,3052
|
|
16
|
+
norm/ioa_observe/handlers/session.py,sha256=rrmjiNvlkZKWB0-9g7sOAHkFekj1TXgxXMUU3edIpFs,2818
|
|
17
|
+
norm/ioa_observe/handlers/tool.py,sha256=sojhbKMhhMajbcF4onGsCUqMaKS9ijLq3XM1BAXhnPg,3173
|
|
18
|
+
norm/ioa_observe/heuristics/__init__.py,sha256=RyGUwM8ubmAw9HKbJ_UkPZqrON-UNQ6pbqdk6aqIuPk,576
|
|
19
|
+
norm/ioa_observe/heuristics/capability_chain.py,sha256=a07Hb6JUDRk8n6kEcjJHToAxKD11DoN8Ubl0lZKySTU,4053
|
|
20
|
+
norm/ioa_observe/heuristics/container_boundary_states.py,sha256=GZGJ7EFkhYiYSChB1vPakZNEGvH2YurIFqO3tibN6FY,2278
|
|
21
|
+
norm/ioa_observe/heuristics/handoff.py,sha256=uxygBn5-Bgjb52G2nF8jr3XJO_9iR2uRZ1wnsdeJSf4,6491
|
|
22
|
+
ioc_scope_norm-1.0.0.dist-info/METADATA,sha256=bwnYTuvnUIz5rjT2-SIKOg_1gRMozKBcMpK7DU-ChNk,1046
|
|
23
|
+
ioc_scope_norm-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
24
|
+
ioc_scope_norm-1.0.0.dist-info/RECORD,,
|
norm/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
from .compare import KGCompareResult, compare_kg, read_kg_json, write_kg_json
|
|
4
|
+
from .ioa_observe import build_kg
|
|
5
|
+
from .ioa_observe.otel_io import infer_run_id, load_otel_export
|
|
6
|
+
from .normalizer import Normalizer, dump_jsonld, normalize
|
|
7
|
+
from .verifier import (
|
|
8
|
+
KGCheckSkipped,
|
|
9
|
+
check_edge_domain_range,
|
|
10
|
+
check_orphaned_edges,
|
|
11
|
+
check_unknown_edge_types,
|
|
12
|
+
check_unknown_node_types,
|
|
13
|
+
nodes_edges_to_jsonld,
|
|
14
|
+
read_jsonld,
|
|
15
|
+
verify_kg,
|
|
16
|
+
write_jsonld,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"KGCheckSkipped",
|
|
21
|
+
"KGCompareResult",
|
|
22
|
+
"Normalizer",
|
|
23
|
+
"build_kg",
|
|
24
|
+
"check_edge_domain_range",
|
|
25
|
+
"check_orphaned_edges",
|
|
26
|
+
"check_unknown_edge_types",
|
|
27
|
+
"check_unknown_node_types",
|
|
28
|
+
"compare_kg",
|
|
29
|
+
"dump_jsonld",
|
|
30
|
+
"infer_run_id",
|
|
31
|
+
"load_otel_export",
|
|
32
|
+
"nodes_edges_to_jsonld",
|
|
33
|
+
"normalize",
|
|
34
|
+
"read_jsonld",
|
|
35
|
+
"read_kg_json",
|
|
36
|
+
"verify_kg",
|
|
37
|
+
"write_jsonld",
|
|
38
|
+
"write_kg_json",
|
|
39
|
+
]
|
norm/compare.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Structural comparison and JSON I/O for KG documents.
|
|
4
|
+
|
|
5
|
+
This module provides the same lightweight comparison surface used by the broader
|
|
6
|
+
library-kg implementation, but keeps the logic self-contained in norm so the
|
|
7
|
+
standalone package can validate and compare generated graphs without importing
|
|
8
|
+
repo-specific orchestration code.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
from collections import Counter
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, Dict, Iterable, List, Set, Tuple
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"KGCompareResult",
|
|
24
|
+
"compare_kg",
|
|
25
|
+
"check_agent_coverage",
|
|
26
|
+
"check_node_distribution",
|
|
27
|
+
"check_edge_distribution",
|
|
28
|
+
"check_call_depth",
|
|
29
|
+
"check_tool_coverage",
|
|
30
|
+
"check_delegation_topology",
|
|
31
|
+
"check_element_diff",
|
|
32
|
+
"read_kg_json",
|
|
33
|
+
"write_kg_json",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class KGCompareResult:
|
|
39
|
+
"""Result of a KG structural comparison."""
|
|
40
|
+
|
|
41
|
+
passed: bool
|
|
42
|
+
checks: List[Dict[str, Any]] = field(default_factory=list)
|
|
43
|
+
summary: Dict[str, Any] = field(default_factory=dict)
|
|
44
|
+
reference_stats: Dict[str, Any] = field(default_factory=dict)
|
|
45
|
+
candidate_stats: Dict[str, Any] = field(default_factory=dict)
|
|
46
|
+
|
|
47
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
48
|
+
return {
|
|
49
|
+
"passed": self.passed,
|
|
50
|
+
"checks": self.checks,
|
|
51
|
+
"summary": self.summary,
|
|
52
|
+
"reference_stats": self.reference_stats,
|
|
53
|
+
"candidate_stats": self.candidate_stats,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _node_type(node: Dict[str, Any]) -> str:
|
|
58
|
+
for key in ("node_type", "nodeType", "type"):
|
|
59
|
+
val = node.get(key)
|
|
60
|
+
if val:
|
|
61
|
+
return str(val)
|
|
62
|
+
return "unknown"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _edge_type(edge: Dict[str, Any]) -> str:
|
|
66
|
+
for key in ("edge_type", "edgeType", "type"):
|
|
67
|
+
val = edge.get(key)
|
|
68
|
+
if val:
|
|
69
|
+
return str(val)
|
|
70
|
+
return "unknown"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _edge_source(edge: Dict[str, Any]) -> str:
|
|
74
|
+
return str(edge.get("from_id") or edge.get("source") or edge.get("from") or "")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _edge_target(edge: Dict[str, Any]) -> str:
|
|
78
|
+
return str(edge.get("to_id") or edge.get("target") or edge.get("to") or "")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
_CONTAINMENT_EDGE_TYPES = (
|
|
82
|
+
"hasMASCall",
|
|
83
|
+
"hasAgentCall",
|
|
84
|
+
"hasToolCall",
|
|
85
|
+
"hasLLMCall",
|
|
86
|
+
"hasProcessingCall",
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _agent_ids(nodes: Iterable[Dict[str, Any]]) -> Set[str]:
|
|
91
|
+
"""Return the identity (``id``) of every structural ``Agent`` node.
|
|
92
|
+
|
|
93
|
+
The ontology has no separate ``agentId`` field — ``Agent.id`` is an
|
|
94
|
+
agent's sole identity now (see norm.ioa_observe's ``agent:<name>``
|
|
95
|
+
scoping).
|
|
96
|
+
"""
|
|
97
|
+
return {str(n["id"]) for n in nodes if _node_type(n) == "Agent" and n.get("id")}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _tool_names(nodes: Iterable[Dict[str, Any]]) -> Set[str]:
|
|
101
|
+
"""Return the ``name`` of every structural ``Tool`` node.
|
|
102
|
+
|
|
103
|
+
``ToolCall`` carries no ``toolName`` of its own — the tool identity lives
|
|
104
|
+
on the ``Tool`` node it ``executesTool``.
|
|
105
|
+
"""
|
|
106
|
+
return {str(n["name"]) for n in nodes if _node_type(n) == "Tool" and n.get("name")}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _delegation_pairs(
|
|
110
|
+
edges: Iterable[Dict[str, Any]], nodes: Iterable[Dict[str, Any]]
|
|
111
|
+
) -> Set[Tuple[str, str]]:
|
|
112
|
+
"""Return (calling agent id, called agent id) pairs from ``executesAgent`` edges.
|
|
113
|
+
|
|
114
|
+
Under the flat hierarchy (AgentCall only nests under MASCall via
|
|
115
|
+
``hasAgentCall`` — an AgentCall cannot directly contain another
|
|
116
|
+
AgentCall), true cross-agent delegation isn't representable, so this
|
|
117
|
+
naturally returns an empty set; kept for schema completeness rather than
|
|
118
|
+
removed.
|
|
119
|
+
"""
|
|
120
|
+
del nodes
|
|
121
|
+
pairs: Set[Tuple[str, str]] = set()
|
|
122
|
+
for e in edges:
|
|
123
|
+
if _edge_type(e) == "executesAgent":
|
|
124
|
+
src, tgt = _edge_source(e), _edge_target(e)
|
|
125
|
+
if src and tgt and src != tgt:
|
|
126
|
+
pairs.add((src, tgt))
|
|
127
|
+
return pairs
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _max_nesting_depth(nodes: Iterable[Dict[str, Any]], edges: Iterable[Dict[str, Any]]) -> int:
|
|
131
|
+
children: Dict[str, List[str]] = {}
|
|
132
|
+
node_ids: Set[str] = {n.get("id", "") for n in nodes}
|
|
133
|
+
for e in edges:
|
|
134
|
+
if _edge_type(e) in _CONTAINMENT_EDGE_TYPES:
|
|
135
|
+
src, tgt = _edge_source(e), _edge_target(e)
|
|
136
|
+
if src in node_ids and tgt in node_ids:
|
|
137
|
+
children.setdefault(src, []).append(tgt)
|
|
138
|
+
|
|
139
|
+
roots = node_ids - {t for kids in children.values() for t in kids}
|
|
140
|
+
if not roots:
|
|
141
|
+
return 0
|
|
142
|
+
|
|
143
|
+
max_d = 0
|
|
144
|
+
stack = [(r, 0) for r in roots]
|
|
145
|
+
while stack:
|
|
146
|
+
nid, depth = stack.pop()
|
|
147
|
+
max_d = max(max_d, depth)
|
|
148
|
+
for child in children.get(nid, []):
|
|
149
|
+
stack.append((child, depth + 1))
|
|
150
|
+
return max_d
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _stable_node_key(node: Dict[str, Any]) -> str:
|
|
154
|
+
return f"{_node_type(node)}|{node.get('id', '')}"
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def check_agent_coverage(
|
|
158
|
+
candidate_nodes: List[Dict[str, Any]],
|
|
159
|
+
reference_nodes: List[Dict[str, Any]],
|
|
160
|
+
) -> Dict[str, Any]:
|
|
161
|
+
ref_agents = _agent_ids(reference_nodes)
|
|
162
|
+
cand_agents = _agent_ids(candidate_nodes)
|
|
163
|
+
missing = ref_agents - cand_agents
|
|
164
|
+
extra = cand_agents - ref_agents
|
|
165
|
+
return {
|
|
166
|
+
"name": "agent_coverage",
|
|
167
|
+
"passed": len(missing) == 0,
|
|
168
|
+
"reference_agents": sorted(ref_agents),
|
|
169
|
+
"candidate_agents": sorted(cand_agents),
|
|
170
|
+
"missing": sorted(missing),
|
|
171
|
+
"extra": sorted(extra),
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def check_node_distribution(
|
|
176
|
+
candidate_nodes: List[Dict[str, Any]],
|
|
177
|
+
reference_nodes: List[Dict[str, Any]],
|
|
178
|
+
) -> Dict[str, Any]:
|
|
179
|
+
ref_dist = Counter(_node_type(n) for n in reference_nodes)
|
|
180
|
+
cand_dist = Counter(_node_type(n) for n in candidate_nodes)
|
|
181
|
+
deficits = {
|
|
182
|
+
ntype: (ref_dist[ntype] - cand_dist.get(ntype, 0))
|
|
183
|
+
for ntype in ref_dist
|
|
184
|
+
if cand_dist.get(ntype, 0) < ref_dist[ntype]
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
"name": "node_distribution",
|
|
188
|
+
"passed": len(deficits) == 0,
|
|
189
|
+
"reference": dict(ref_dist),
|
|
190
|
+
"candidate": dict(cand_dist),
|
|
191
|
+
"deficits": deficits,
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def check_edge_distribution(
|
|
196
|
+
candidate_edges: List[Dict[str, Any]],
|
|
197
|
+
reference_edges: List[Dict[str, Any]],
|
|
198
|
+
) -> Dict[str, Any]:
|
|
199
|
+
ref_dist = Counter(_edge_type(e) for e in reference_edges)
|
|
200
|
+
cand_dist = Counter(_edge_type(e) for e in candidate_edges)
|
|
201
|
+
deficits = {
|
|
202
|
+
etype: (ref_dist[etype] - cand_dist.get(etype, 0))
|
|
203
|
+
for etype in ref_dist
|
|
204
|
+
if cand_dist.get(etype, 0) < ref_dist[etype]
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
"name": "edge_distribution",
|
|
208
|
+
"passed": len(deficits) == 0,
|
|
209
|
+
"reference": dict(ref_dist),
|
|
210
|
+
"candidate": dict(cand_dist),
|
|
211
|
+
"deficits": deficits,
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def check_call_depth(
|
|
216
|
+
candidate_nodes: List[Dict[str, Any]],
|
|
217
|
+
candidate_edges: List[Dict[str, Any]],
|
|
218
|
+
reference_nodes: List[Dict[str, Any]],
|
|
219
|
+
reference_edges: List[Dict[str, Any]],
|
|
220
|
+
) -> Dict[str, Any]:
|
|
221
|
+
ref_depth = _max_nesting_depth(reference_nodes, reference_edges)
|
|
222
|
+
cand_depth = _max_nesting_depth(candidate_nodes, candidate_edges)
|
|
223
|
+
return {
|
|
224
|
+
"name": "call_depth",
|
|
225
|
+
"passed": cand_depth >= ref_depth,
|
|
226
|
+
"reference_depth": ref_depth,
|
|
227
|
+
"candidate_depth": cand_depth,
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def check_tool_coverage(
|
|
232
|
+
candidate_nodes: List[Dict[str, Any]],
|
|
233
|
+
reference_nodes: List[Dict[str, Any]],
|
|
234
|
+
) -> Dict[str, Any]:
|
|
235
|
+
ref_tools = _tool_names(reference_nodes)
|
|
236
|
+
cand_tools = _tool_names(candidate_nodes)
|
|
237
|
+
missing = ref_tools - cand_tools
|
|
238
|
+
return {
|
|
239
|
+
"name": "tool_coverage",
|
|
240
|
+
"passed": len(missing) == 0,
|
|
241
|
+
"reference_tools": sorted(ref_tools),
|
|
242
|
+
"candidate_tools": sorted(cand_tools),
|
|
243
|
+
"missing": sorted(missing),
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def check_delegation_topology(
|
|
248
|
+
candidate_nodes: List[Dict[str, Any]],
|
|
249
|
+
candidate_edges: List[Dict[str, Any]],
|
|
250
|
+
reference_nodes: List[Dict[str, Any]],
|
|
251
|
+
reference_edges: List[Dict[str, Any]],
|
|
252
|
+
) -> Dict[str, Any]:
|
|
253
|
+
ref_pairs = _delegation_pairs(reference_edges, reference_nodes)
|
|
254
|
+
cand_pairs = _delegation_pairs(candidate_edges, candidate_nodes)
|
|
255
|
+
missing = ref_pairs - cand_pairs
|
|
256
|
+
return {
|
|
257
|
+
"name": "delegation_topology",
|
|
258
|
+
"passed": len(missing) == 0,
|
|
259
|
+
"reference": sorted(f"{s}->{t}" for s, t in ref_pairs),
|
|
260
|
+
"candidate": sorted(f"{s}->{t}" for s, t in cand_pairs),
|
|
261
|
+
"missing": sorted(f"{s}->{t}" for s, t in missing),
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _element_level_diff(
|
|
266
|
+
candidate_nodes: List[Dict[str, Any]],
|
|
267
|
+
candidate_edges: List[Dict[str, Any]],
|
|
268
|
+
reference_nodes: List[Dict[str, Any]],
|
|
269
|
+
reference_edges: List[Dict[str, Any]],
|
|
270
|
+
) -> Dict[str, Any]:
|
|
271
|
+
ref_node_keys = Counter(_stable_node_key(n) for n in reference_nodes)
|
|
272
|
+
cand_node_keys = Counter(_stable_node_key(n) for n in candidate_nodes)
|
|
273
|
+
missing_nodes = sorted((ref_node_keys - cand_node_keys).keys())
|
|
274
|
+
spurious_nodes = sorted((cand_node_keys - ref_node_keys).keys())
|
|
275
|
+
|
|
276
|
+
def _edge_key(edge: Dict[str, Any]) -> str:
|
|
277
|
+
return f"{_edge_type(edge)}|{_edge_source(edge)}|{_edge_target(edge)}"
|
|
278
|
+
|
|
279
|
+
ref_edge_keys = Counter(_edge_key(e) for e in reference_edges)
|
|
280
|
+
cand_edge_keys = Counter(_edge_key(e) for e in candidate_edges)
|
|
281
|
+
missing_edges = sorted((ref_edge_keys - cand_edge_keys).keys())
|
|
282
|
+
spurious_edges = sorted((cand_edge_keys - ref_edge_keys).keys())
|
|
283
|
+
identical = (
|
|
284
|
+
not missing_nodes and not spurious_nodes and not missing_edges and not spurious_edges
|
|
285
|
+
)
|
|
286
|
+
return {
|
|
287
|
+
"name": "element_level_diff",
|
|
288
|
+
"passed": identical,
|
|
289
|
+
"missing_nodes": missing_nodes,
|
|
290
|
+
"spurious_nodes": spurious_nodes,
|
|
291
|
+
"missing_edges": missing_edges,
|
|
292
|
+
"spurious_edges": spurious_edges,
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def check_element_diff(
|
|
297
|
+
candidate_nodes: List[Dict[str, Any]],
|
|
298
|
+
candidate_edges: List[Dict[str, Any]],
|
|
299
|
+
reference_nodes: List[Dict[str, Any]],
|
|
300
|
+
reference_edges: List[Dict[str, Any]],
|
|
301
|
+
) -> Dict[str, Any]:
|
|
302
|
+
return _element_level_diff(candidate_nodes, candidate_edges, reference_nodes, reference_edges)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def compare_kg(
|
|
306
|
+
candidate: Dict[str, Any], reference: Dict[str, Any], *, strict: bool = False
|
|
307
|
+
) -> KGCompareResult:
|
|
308
|
+
cand_nodes = candidate.get("nodes") or []
|
|
309
|
+
cand_edges = candidate.get("edges") or []
|
|
310
|
+
ref_nodes = reference.get("nodes") or []
|
|
311
|
+
ref_edges = reference.get("edges") or []
|
|
312
|
+
|
|
313
|
+
checks: List[Dict[str, Any]] = [
|
|
314
|
+
check_agent_coverage(cand_nodes, ref_nodes),
|
|
315
|
+
check_node_distribution(cand_nodes, ref_nodes),
|
|
316
|
+
check_edge_distribution(cand_edges, ref_edges),
|
|
317
|
+
check_call_depth(cand_nodes, cand_edges, ref_nodes, ref_edges),
|
|
318
|
+
check_tool_coverage(cand_nodes, ref_nodes),
|
|
319
|
+
check_delegation_topology(cand_nodes, cand_edges, ref_nodes, ref_edges),
|
|
320
|
+
check_element_diff(cand_nodes, cand_edges, ref_nodes, ref_edges),
|
|
321
|
+
]
|
|
322
|
+
|
|
323
|
+
structural_checks = [c for c in checks if c["name"] != "element_level_diff"]
|
|
324
|
+
all_passed = all(c["passed"] for c in (checks if strict else structural_checks))
|
|
325
|
+
|
|
326
|
+
summary = {
|
|
327
|
+
"total_checks": len(checks),
|
|
328
|
+
"passed": sum(1 for c in checks if c["passed"]),
|
|
329
|
+
"failed": sum(1 for c in checks if not c["passed"]),
|
|
330
|
+
}
|
|
331
|
+
ref_agents = _agent_ids(ref_nodes)
|
|
332
|
+
cand_agents = _agent_ids(cand_nodes)
|
|
333
|
+
|
|
334
|
+
return KGCompareResult(
|
|
335
|
+
passed=all_passed,
|
|
336
|
+
checks=checks,
|
|
337
|
+
summary=summary,
|
|
338
|
+
reference_stats={
|
|
339
|
+
"nodes": len(ref_nodes),
|
|
340
|
+
"edges": len(ref_edges),
|
|
341
|
+
"agents": sorted(ref_agents),
|
|
342
|
+
},
|
|
343
|
+
candidate_stats={
|
|
344
|
+
"nodes": len(cand_nodes),
|
|
345
|
+
"edges": len(cand_edges),
|
|
346
|
+
"agents": sorted(cand_agents),
|
|
347
|
+
},
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def read_kg_json(path: str | Path) -> Dict[str, Any]:
|
|
352
|
+
with Path(path).open("r", encoding="utf-8") as fh:
|
|
353
|
+
data = json.load(fh)
|
|
354
|
+
if not isinstance(data, dict):
|
|
355
|
+
raise TypeError("KG JSON document must deserialize to a dict")
|
|
356
|
+
return {
|
|
357
|
+
"nodes": list(data.get("nodes") or []),
|
|
358
|
+
"edges": list(data.get("edges") or []),
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def write_kg_json(doc: Dict[str, Any], path: str | Path) -> Path:
|
|
363
|
+
out = Path(path)
|
|
364
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
365
|
+
payload = {
|
|
366
|
+
"nodes": list(doc.get("nodes") or []),
|
|
367
|
+
"edges": list(doc.get("edges") or []),
|
|
368
|
+
}
|
|
369
|
+
with out.open("w", encoding="utf-8") as fh:
|
|
370
|
+
json.dump(payload, fh, indent=2, sort_keys=True)
|
|
371
|
+
fh.write("\n")
|
|
372
|
+
return out
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Dispatch: one handler per ``SpanName`` shape, accumulated into a Registry.
|
|
4
|
+
|
|
5
|
+
"session.start" -> Session, MAS (placeholder)
|
|
6
|
+
"session.end" -> update Session end time/duration
|
|
7
|
+
"*.graph" -> MAS (declared), Agent/Tool (declared, from graph data)
|
|
8
|
+
"*.agent" -> Agent (undeclared), AgentCall, initial/final State
|
|
9
|
+
"*.chat" -> LLM, LLMCall, initial/final State, Transition
|
|
10
|
+
"*.tool" -> Tool, ToolCall, initial/final State, Transition
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from .fields import attrs
|
|
18
|
+
from .handlers import (
|
|
19
|
+
handle_agent,
|
|
20
|
+
handle_chat,
|
|
21
|
+
handle_graph,
|
|
22
|
+
handle_session_end,
|
|
23
|
+
handle_session_start,
|
|
24
|
+
handle_tool,
|
|
25
|
+
)
|
|
26
|
+
from .heuristics import (
|
|
27
|
+
assign_container_boundary_states,
|
|
28
|
+
chain_agent_handoffs_fallback,
|
|
29
|
+
chain_capability_calls,
|
|
30
|
+
link_agent_handoffs,
|
|
31
|
+
)
|
|
32
|
+
from .registry import Registry
|
|
33
|
+
|
|
34
|
+
_HANDLERS: dict[str, Any] = {
|
|
35
|
+
"session.start": handle_session_start,
|
|
36
|
+
"session.end": handle_session_end,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_kg(
|
|
41
|
+
spans: list[dict[str, Any]],
|
|
42
|
+
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
|
43
|
+
"""Build (nodes, edges) JSON dicts from raw ClickHouse-shaped OTel spans."""
|
|
44
|
+
registry = Registry()
|
|
45
|
+
|
|
46
|
+
for span in spans:
|
|
47
|
+
span_name = str(span.get("SpanName") or "")
|
|
48
|
+
span_attrs = attrs(span)
|
|
49
|
+
|
|
50
|
+
handler = _HANDLERS.get(span_name)
|
|
51
|
+
if handler is not None:
|
|
52
|
+
handler(span, span_attrs, registry)
|
|
53
|
+
elif span_name.endswith(".graph"):
|
|
54
|
+
handle_graph(span, span_attrs, registry)
|
|
55
|
+
elif span_name.endswith(".agent"):
|
|
56
|
+
handle_agent(span, span_attrs, registry)
|
|
57
|
+
elif span_name.endswith(".chat"):
|
|
58
|
+
handle_chat(span, span_attrs, registry)
|
|
59
|
+
elif span_name.endswith(".tool"):
|
|
60
|
+
handle_tool(span, span_attrs, registry)
|
|
61
|
+
|
|
62
|
+
# Clean up trajectory once all spans are processed
|
|
63
|
+
# Agent handoffs
|
|
64
|
+
explicit_handoff_targets = link_agent_handoffs(spans, registry)
|
|
65
|
+
# Fallback: timestamp-order sibling AgentCalls the above left unlinked
|
|
66
|
+
chain_agent_handoffs_fallback(registry, explicit_handoff_targets)
|
|
67
|
+
# Capability calls within agent call
|
|
68
|
+
chain_capability_calls(registry)
|
|
69
|
+
# Session and MAS call i/o
|
|
70
|
+
assign_container_boundary_states(registry)
|
|
71
|
+
|
|
72
|
+
nodes: list[dict[str, Any]] = []
|
|
73
|
+
edges: list[dict[str, Any]] = []
|
|
74
|
+
for item in registry.all_items():
|
|
75
|
+
payload = item.to_json()
|
|
76
|
+
if "node_type" not in payload:
|
|
77
|
+
edges.append(payload)
|
|
78
|
+
continue
|
|
79
|
+
# hierarchyLevel/layer are ClassVar on the ontology models (a fixed
|
|
80
|
+
# constant per concrete class, not per-instance data), so pydantic
|
|
81
|
+
# never serializes them -- read them straight off the class and
|
|
82
|
+
# denormalize them into the output JSON instead.
|
|
83
|
+
for attr in ("hierarchyLevel", "layer"):
|
|
84
|
+
value = getattr(item, attr, None)
|
|
85
|
+
if value is not None:
|
|
86
|
+
payload[attr] = value
|
|
87
|
+
nodes.append(payload)
|
|
88
|
+
return nodes, edges
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Span field derivation: read straight off each raw span's own SpanAttributes."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def attrs(span: dict[str, Any]) -> dict[str, Any]:
|
|
13
|
+
"""Return a span's SpanAttributes map, or {} if absent."""
|
|
14
|
+
return span.get("SpanAttributes") or {}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def get_application_id(span: dict[str, Any], span_attrs: dict[str, Any]) -> str:
|
|
18
|
+
return str(span_attrs.get("application_id") or span.get("ServiceName") or "")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_session_id(span: dict[str, Any], span_attrs: dict[str, Any]) -> str:
|
|
22
|
+
"""Strip the ``<application_id>_`` prefix ioa-observe puts on session.id.
|
|
23
|
+
|
|
24
|
+
Strips the exact application_id prefix rather than splitting on the first
|
|
25
|
+
"_", since application_id itself may contain one.
|
|
26
|
+
"""
|
|
27
|
+
raw = str(span.get("SessionId") or span_attrs.get("session.id") or "")
|
|
28
|
+
application_id = get_application_id(span, span_attrs)
|
|
29
|
+
prefix = f"{application_id}_"
|
|
30
|
+
if application_id and raw.startswith(prefix):
|
|
31
|
+
return raw[len(prefix) :]
|
|
32
|
+
return raw.split("_")[-1] if "_" in raw else raw
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_agent_id(span: dict[str, Any], span_attrs: dict[str, Any]) -> str:
|
|
36
|
+
return str(span.get("AgentId") or span_attrs.get("agent_id") or "")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def get_success(span: dict[str, Any], span_attrs: dict[str, Any]) -> bool:
|
|
40
|
+
"""Read the span's own ``execution.success`` attribute (string-valued,
|
|
41
|
+
e.g. "true"/"false"), falling back to the OTel ``StatusCode`` column
|
|
42
|
+
when that attribute is absent: only an explicit "Error" status counts
|
|
43
|
+
as a failure -- "Ok"/"Unset"/anything else defaults to success."""
|
|
44
|
+
raw = span_attrs.get("execution.success")
|
|
45
|
+
if raw:
|
|
46
|
+
return str(raw).strip().lower() == "true"
|
|
47
|
+
return str(span.get("StatusCode") or "").strip().lower() != "error"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _parse_timestamp_ns(value: str) -> int:
|
|
51
|
+
date_part, _, fractional = value.partition(".")
|
|
52
|
+
dt = datetime.strptime(date_part, "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
|
|
53
|
+
fractional = (fractional + "000000000")[:9]
|
|
54
|
+
return int(dt.timestamp()) * 1_000_000_000 + int(fractional or 0)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def get_start_time(span: dict[str, Any], span_attrs: dict[str, Any]) -> float:
|
|
58
|
+
"""Prefer the SDK's own ``ioa_start_time`` capture; fall back to the
|
|
59
|
+
collector-recorded ``Timestamp`` column if it's absent."""
|
|
60
|
+
raw = span_attrs.get("ioa_start_time")
|
|
61
|
+
if raw not in (None, ""):
|
|
62
|
+
try:
|
|
63
|
+
return float(raw)
|
|
64
|
+
except (TypeError, ValueError):
|
|
65
|
+
pass
|
|
66
|
+
timestamp = str(span.get("Timestamp") or "")
|
|
67
|
+
if not timestamp:
|
|
68
|
+
return 0.0
|
|
69
|
+
return _parse_timestamp_ns(timestamp) / 1e9
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def get_duration_seconds(span: dict[str, Any]) -> float:
|
|
73
|
+
return float(span.get("Duration") or 0) / 1e9
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get_duration_ms(span: dict[str, Any]) -> float:
|
|
77
|
+
return float(span.get("Duration") or 0) / 1e6
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def get_end_time(start_time: float, span: dict[str, Any]) -> float:
|
|
81
|
+
return start_time + get_duration_seconds(span)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _to_float(value: Any) -> float:
|
|
85
|
+
try:
|
|
86
|
+
return float(value)
|
|
87
|
+
except (TypeError, ValueError):
|
|
88
|
+
return 0.0
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _to_int(value: Any) -> int:
|
|
92
|
+
try:
|
|
93
|
+
return int(float(value))
|
|
94
|
+
except (TypeError, ValueError):
|
|
95
|
+
return 0
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _first_str(value: Any) -> str:
|
|
99
|
+
"""gen_ai.response.finish_reasons etc. are array attributes; take element 0."""
|
|
100
|
+
if isinstance(value, (list, tuple)) and value:
|
|
101
|
+
return str(value[0])
|
|
102
|
+
return str(value or "")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _hash_id(prefix: str, *parts: str) -> str:
|
|
106
|
+
"""Deterministic id from natural identity -- same inputs always produce the
|
|
107
|
+
same id, so edges can reference a node before or after it's built."""
|
|
108
|
+
digest = hashlib.sha1("\x1f".join(str(p) for p in parts).encode("utf-8")).hexdigest()[:12]
|
|
109
|
+
return f"{prefix}:{digest}"
|