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,220 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Neo4j connector using *neo4j-driver*."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
import random
|
|
9
|
+
import re
|
|
10
|
+
import time as _time
|
|
11
|
+
from datetime import date, datetime, time, timedelta
|
|
12
|
+
from typing import Any, Callable, Dict, Optional, TypeVar
|
|
13
|
+
from urllib.parse import urlparse
|
|
14
|
+
|
|
15
|
+
import neo4j.time
|
|
16
|
+
from neo4j import GraphDatabase
|
|
17
|
+
from neo4j.exceptions import TransientError
|
|
18
|
+
|
|
19
|
+
from scope.connectors.base import Connector
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
T = TypeVar("T")
|
|
24
|
+
|
|
25
|
+
# Neo4j rolls a transaction back and says "retry me" (TransientError) when two writers
|
|
26
|
+
# collide, typically a deadlock on the nodes they share. Several workers write the same
|
|
27
|
+
# structural nodes at once, so a query is tried again a few times before it fails.
|
|
28
|
+
TRANSIENT_ATTEMPTS = 5
|
|
29
|
+
TRANSIENT_BACKOFF_SECONDS = 0.2
|
|
30
|
+
# The first retries are routine under concurrency (two sessions collide about once each), so they are
|
|
31
|
+
# logged at INFO; from this attempt on, something is wrong enough to be worth a WARNING.
|
|
32
|
+
TRANSIENT_WARN_FROM_ATTEMPT = 3
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
SEMANTICGROUP_NODE_CHILDREN_NODES = "childrenNodes"
|
|
36
|
+
SEMANTICGROUP_NODE_GROUP_NAME = "groupName"
|
|
37
|
+
SEMANTICGROUP_NODE_GROUP_SUMMARY = "groupSummary"
|
|
38
|
+
SEMANTICGROUP_NODE_ID = "id"
|
|
39
|
+
SEMANTICGROUP_NODE_N_SESSIONS = "nSessions"
|
|
40
|
+
SEMANTICGROUP_NODE_SESSION_IDS = "sessionIds"
|
|
41
|
+
SEMANTICGROUP_NODE_MEDIOID_SESSION_ID = "medioidSessionId"
|
|
42
|
+
SEMANTICGROUP_NODE_SPLIT_DISTANCE = "splitDistance"
|
|
43
|
+
SEMANTICGROUP_NODE_SEMANTICGROUP_ID = "semanticgroupId"
|
|
44
|
+
SEMANTICGROUP_NODE_OVERALL_QUALITY = "overallQuality"
|
|
45
|
+
SEMANTICGROUP_NODE_OVERALL_RELIABILITY = "overallReliability"
|
|
46
|
+
SEMANTICGROUP_NODE_OVERALL_PERFORMANCE = "overallPerformance"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _convert_neo4j_types(value: Any) -> Any:
|
|
50
|
+
"""Recursively convert Neo4j temporal types to Python standard types."""
|
|
51
|
+
if isinstance(value, neo4j.time.DateTime):
|
|
52
|
+
return value.to_native()
|
|
53
|
+
if isinstance(value, neo4j.time.Date):
|
|
54
|
+
return date(value.year, value.month, value.day)
|
|
55
|
+
if isinstance(value, neo4j.time.Time):
|
|
56
|
+
return value.to_native()
|
|
57
|
+
if isinstance(value, neo4j.time.Duration):
|
|
58
|
+
return timedelta(
|
|
59
|
+
days=value.months_days_seconds[1],
|
|
60
|
+
seconds=value.months_days_seconds[2],
|
|
61
|
+
)
|
|
62
|
+
if isinstance(value, dict):
|
|
63
|
+
return {k: _convert_neo4j_types(v) for k, v in value.items()}
|
|
64
|
+
if isinstance(value, list):
|
|
65
|
+
return [_convert_neo4j_types(v) for v in value]
|
|
66
|
+
return value
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _to_cypher_literal(value: Any) -> str:
|
|
70
|
+
"""Best-effort literal rendering for debug logs only."""
|
|
71
|
+
if value is None:
|
|
72
|
+
return "null"
|
|
73
|
+
if isinstance(value, bool):
|
|
74
|
+
return "true" if value else "false"
|
|
75
|
+
if isinstance(value, (int, float)):
|
|
76
|
+
return str(value)
|
|
77
|
+
if isinstance(value, (date, datetime, time)):
|
|
78
|
+
return repr(value.isoformat())
|
|
79
|
+
if isinstance(value, dict):
|
|
80
|
+
parts = ", ".join(f"{k}: {_to_cypher_literal(v)}" for k, v in value.items())
|
|
81
|
+
return "{" + parts + "}"
|
|
82
|
+
if isinstance(value, list):
|
|
83
|
+
return "[" + ", ".join(_to_cypher_literal(v) for v in value) + "]"
|
|
84
|
+
return repr(str(value))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _render_query_with_params(query: str, params: Optional[Dict[str, Any]]) -> str:
|
|
88
|
+
if not params:
|
|
89
|
+
return query
|
|
90
|
+
|
|
91
|
+
rendered_query = query
|
|
92
|
+
for key in sorted(params.keys(), key=len, reverse=True):
|
|
93
|
+
pattern = re.compile(rf"\${re.escape(key)}(?![A-Za-z0-9_])")
|
|
94
|
+
rendered_query = pattern.sub(_to_cypher_literal(params[key]), rendered_query)
|
|
95
|
+
return rendered_query
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Neo4JConnector(Connector):
|
|
99
|
+
"""Manages a Neo4J connection via neo4j-driver."""
|
|
100
|
+
|
|
101
|
+
def __init__(
|
|
102
|
+
self,
|
|
103
|
+
host: str = "localhost",
|
|
104
|
+
port: int = 7687,
|
|
105
|
+
username: str = "neo4j",
|
|
106
|
+
password: str = "password",
|
|
107
|
+
database: str = "neo4j",
|
|
108
|
+
):
|
|
109
|
+
self._host = host
|
|
110
|
+
self._port = port
|
|
111
|
+
self._username = username
|
|
112
|
+
self._password = password
|
|
113
|
+
self._database = database
|
|
114
|
+
self._client: Any = None # neo4j.Driver
|
|
115
|
+
|
|
116
|
+
# ── lifecycle ─────────────────────────────────────────────────────────
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def _uri(self) -> str:
|
|
120
|
+
"""Build the Neo4j bolt URI, handling hosts that already contain a scheme and/or port."""
|
|
121
|
+
host = self._host
|
|
122
|
+
# If host already looks like a full URI (e.g. bolt://host:7687), parse it.
|
|
123
|
+
if "://" in host:
|
|
124
|
+
parsed = urlparse(host)
|
|
125
|
+
scheme = parsed.scheme or "bolt"
|
|
126
|
+
hostname = parsed.hostname or "localhost"
|
|
127
|
+
port = parsed.port or self._port
|
|
128
|
+
return f"{scheme}://{hostname}:{port}"
|
|
129
|
+
return f"bolt://{host}:{self._port}"
|
|
130
|
+
|
|
131
|
+
def connect(self) -> None:
|
|
132
|
+
self._client = GraphDatabase.driver(
|
|
133
|
+
self._uri,
|
|
134
|
+
auth=(self._username, self._password),
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
def close(self) -> None:
|
|
138
|
+
if self._client is not None:
|
|
139
|
+
self._client.close()
|
|
140
|
+
self._client = None
|
|
141
|
+
|
|
142
|
+
def is_connected(self) -> bool:
|
|
143
|
+
if self._client is None:
|
|
144
|
+
return False
|
|
145
|
+
try:
|
|
146
|
+
self._client.verify_connectivity()
|
|
147
|
+
return True
|
|
148
|
+
except Exception as exc:
|
|
149
|
+
logger.warning("Neo4j connection check failed: %s", exc)
|
|
150
|
+
return False
|
|
151
|
+
|
|
152
|
+
# ── query execution ───────────────────────────────────────────────────
|
|
153
|
+
|
|
154
|
+
@staticmethod
|
|
155
|
+
def _retry_transient(run: Callable[[], T]) -> T:
|
|
156
|
+
"""Call ``run``, again after a short random wait when Neo4j reports a transient error.
|
|
157
|
+
|
|
158
|
+
A transient error means the transaction was rolled back, so running it again is safe.
|
|
159
|
+
"""
|
|
160
|
+
for attempt in range(1, TRANSIENT_ATTEMPTS + 1):
|
|
161
|
+
try:
|
|
162
|
+
return run()
|
|
163
|
+
except TransientError as exc:
|
|
164
|
+
if attempt == TRANSIENT_ATTEMPTS:
|
|
165
|
+
raise
|
|
166
|
+
delay = (
|
|
167
|
+
TRANSIENT_BACKOFF_SECONDS
|
|
168
|
+
* 2 ** (attempt - 1)
|
|
169
|
+
* (0.5 + random.random())
|
|
170
|
+
)
|
|
171
|
+
logger.log(
|
|
172
|
+
logging.WARNING
|
|
173
|
+
if attempt >= TRANSIENT_WARN_FROM_ATTEMPT
|
|
174
|
+
else logging.INFO,
|
|
175
|
+
"Neo4j transient error (%s), trying again in %.2fs (attempt %d of %d)",
|
|
176
|
+
getattr(exc, "code", "unknown"),
|
|
177
|
+
delay,
|
|
178
|
+
attempt,
|
|
179
|
+
TRANSIENT_ATTEMPTS,
|
|
180
|
+
)
|
|
181
|
+
_time.sleep(delay)
|
|
182
|
+
raise AssertionError("unreachable") # pragma: no cover
|
|
183
|
+
|
|
184
|
+
def execute(self, query: str, params: Optional[Dict[str, Any]] = None) -> Any:
|
|
185
|
+
self.ensure_connected()
|
|
186
|
+
if logger.isEnabledFor(logging.DEBUG):
|
|
187
|
+
logger.debug(
|
|
188
|
+
"Executing query:\n***********************\n%s",
|
|
189
|
+
_render_query_with_params(query, params),
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
def run() -> Any:
|
|
193
|
+
with self._client.session(database=self._database) as session:
|
|
194
|
+
result = session.run(query, parameters=params or {})
|
|
195
|
+
return [_convert_neo4j_types(record.data()) for record in result]
|
|
196
|
+
|
|
197
|
+
return self._retry_transient(run)
|
|
198
|
+
|
|
199
|
+
def execute_command(
|
|
200
|
+
self, command: str, params: Optional[Dict[str, Any]] = None
|
|
201
|
+
) -> None:
|
|
202
|
+
"""Execute a write command (CREATE, MERGE, DELETE, etc.)."""
|
|
203
|
+
self.ensure_connected()
|
|
204
|
+
if logger.isEnabledFor(logging.DEBUG):
|
|
205
|
+
logger.debug(
|
|
206
|
+
"Executing command:\n***********************\n%s",
|
|
207
|
+
_render_query_with_params(command, params),
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
def run() -> None:
|
|
211
|
+
with self._client.session(database=self._database) as session:
|
|
212
|
+
session.run(command, parameters=params or {}).consume()
|
|
213
|
+
|
|
214
|
+
self._retry_transient(run)
|
|
215
|
+
|
|
216
|
+
@property
|
|
217
|
+
def driver(self):
|
|
218
|
+
"""Return the raw neo4j Driver so providers can open sessions directly."""
|
|
219
|
+
self.ensure_connected()
|
|
220
|
+
return self._client
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""SQLAlchemy connector (works with SQLite, PostgreSQL, and other SA-supported engines)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
from typing import Any, Dict, List, Optional
|
|
9
|
+
|
|
10
|
+
from scope.connectors.base import Connector
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SQLAlchemyConnector(Connector):
|
|
16
|
+
"""Manages a database connection via SQLAlchemy."""
|
|
17
|
+
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
url: str = "sqlite:///scope.db",
|
|
21
|
+
echo: bool = False,
|
|
22
|
+
**engine_kwargs: Any,
|
|
23
|
+
):
|
|
24
|
+
self._url = url
|
|
25
|
+
self._echo = echo
|
|
26
|
+
self._engine_kwargs = engine_kwargs
|
|
27
|
+
self._engine: Any = None # sqlalchemy.engine.Engine
|
|
28
|
+
self._session_factory: Any = None # sqlalchemy.orm.sessionmaker
|
|
29
|
+
|
|
30
|
+
# ── lifecycle ─────────────────────────────────────────────────────────
|
|
31
|
+
|
|
32
|
+
def connect(self) -> None:
|
|
33
|
+
from sqlalchemy import create_engine
|
|
34
|
+
from sqlalchemy.orm import sessionmaker
|
|
35
|
+
|
|
36
|
+
self._engine = create_engine(self._url, echo=self._echo, **self._engine_kwargs)
|
|
37
|
+
self._session_factory = sessionmaker(bind=self._engine)
|
|
38
|
+
|
|
39
|
+
def close(self) -> None:
|
|
40
|
+
if self._engine is not None:
|
|
41
|
+
self._engine.dispose()
|
|
42
|
+
self._engine = None
|
|
43
|
+
self._session_factory = None
|
|
44
|
+
|
|
45
|
+
def is_connected(self) -> bool:
|
|
46
|
+
if self._engine is None:
|
|
47
|
+
return False
|
|
48
|
+
try:
|
|
49
|
+
with self._engine.connect() as conn:
|
|
50
|
+
conn.execute(self._text("SELECT 1"))
|
|
51
|
+
return True
|
|
52
|
+
except Exception as exc:
|
|
53
|
+
logger.warning("SQLAlchemy connection check failed: %s", exc)
|
|
54
|
+
return False
|
|
55
|
+
|
|
56
|
+
# ── query execution ───────────────────────────────────────────────────
|
|
57
|
+
|
|
58
|
+
def execute(self, query: Any, params: Optional[Dict[str, Any]] = None) -> List:
|
|
59
|
+
"""Execute a read query and return a list of row tuples.
|
|
60
|
+
|
|
61
|
+
*query* may be a raw SQL string **or** a SQLAlchemy Core
|
|
62
|
+
``Select`` / ``TextClause`` statement.
|
|
63
|
+
"""
|
|
64
|
+
self.ensure_connected()
|
|
65
|
+
if logger.isEnabledFor(logging.DEBUG):
|
|
66
|
+
if isinstance(query, str):
|
|
67
|
+
logger.debug("Executing query: %s", query)
|
|
68
|
+
else:
|
|
69
|
+
try:
|
|
70
|
+
compiled = query.compile(
|
|
71
|
+
self._engine,
|
|
72
|
+
compile_kwargs={"literal_binds": True},
|
|
73
|
+
)
|
|
74
|
+
logger.debug(
|
|
75
|
+
"Executing query: \n***********************\n%s",
|
|
76
|
+
compiled.string,
|
|
77
|
+
)
|
|
78
|
+
except Exception:
|
|
79
|
+
# Some types (e.g. expanding IN) can't render literal binds;
|
|
80
|
+
# fall back to showing query + params separately.
|
|
81
|
+
compiled = query.compile(
|
|
82
|
+
self._engine,
|
|
83
|
+
compile_kwargs={"literal_binds": False},
|
|
84
|
+
)
|
|
85
|
+
logger.debug(
|
|
86
|
+
"Executing query: %s | params: %s",
|
|
87
|
+
compiled.string,
|
|
88
|
+
compiled.params,
|
|
89
|
+
)
|
|
90
|
+
session = self._session_factory()
|
|
91
|
+
try:
|
|
92
|
+
stmt = self._text(query) if isinstance(query, str) else query
|
|
93
|
+
result = session.execute(stmt, params or {})
|
|
94
|
+
return result.fetchall()
|
|
95
|
+
finally:
|
|
96
|
+
session.close()
|
|
97
|
+
|
|
98
|
+
def execute_command(
|
|
99
|
+
self, command: str, params: Optional[Dict[str, Any]] = None
|
|
100
|
+
) -> None:
|
|
101
|
+
"""Execute a DDL/DML command (INSERT, DELETE, CREATE TABLE, …)."""
|
|
102
|
+
self.ensure_connected()
|
|
103
|
+
session = self._session_factory()
|
|
104
|
+
try:
|
|
105
|
+
session.execute(self._text(command), params or {})
|
|
106
|
+
session.commit()
|
|
107
|
+
except Exception:
|
|
108
|
+
session.rollback()
|
|
109
|
+
raise
|
|
110
|
+
finally:
|
|
111
|
+
session.close()
|
|
112
|
+
|
|
113
|
+
# ── helpers ───────────────────────────────────────────────────────────
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def engine(self):
|
|
117
|
+
"""Expose the underlying SQLAlchemy engine (e.g. for ``metadata.create_all``)."""
|
|
118
|
+
self.ensure_connected()
|
|
119
|
+
return self._engine
|
|
120
|
+
|
|
121
|
+
def get_session(self):
|
|
122
|
+
"""Return a new SQLAlchemy :class:`~sqlalchemy.orm.Session`."""
|
|
123
|
+
self.ensure_connected()
|
|
124
|
+
return self._session_factory()
|
|
125
|
+
|
|
126
|
+
@staticmethod
|
|
127
|
+
def _text(sql: str):
|
|
128
|
+
"""Wrap a raw SQL string with :func:`sqlalchemy.text`."""
|
|
129
|
+
from sqlalchemy import text
|
|
130
|
+
|
|
131
|
+
return text(sql)
|