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,221 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Query builders for waste-estimation and insights endpoints."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def waste_estimations_query(limit: int) -> tuple[str, dict[str, Any]]:
|
|
11
|
+
query = """
|
|
12
|
+
MATCH (n:WasteEstimation)
|
|
13
|
+
RETURN properties(n) AS waste_estimation
|
|
14
|
+
LIMIT $limit
|
|
15
|
+
"""
|
|
16
|
+
return query, {"limit": limit}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def top_wasteful_sessions_query(
|
|
20
|
+
threshold: float,
|
|
21
|
+
limit: int,
|
|
22
|
+
start_time: int | None,
|
|
23
|
+
end_time: int | None,
|
|
24
|
+
application_name: str,
|
|
25
|
+
) -> tuple[str, dict[str, Any]]:
|
|
26
|
+
query = """
|
|
27
|
+
MATCH (n:WasteEstimation)
|
|
28
|
+
WHERE n.estimatedWaste > $threshold
|
|
29
|
+
MATCH (s:Session {sessionId: n.sessionId})
|
|
30
|
+
WHERE ($start_time IS NULL OR s.startTime >= $start_time)
|
|
31
|
+
AND ($end_time IS NULL OR s.startTime <= $end_time)
|
|
32
|
+
AND EXISTS {
|
|
33
|
+
MATCH (s)-[:executesSession]->(:MAS {id: $application_name})
|
|
34
|
+
}
|
|
35
|
+
OPTIONAL MATCH (g:SemanticGroup)-[:containsSession]->(s)
|
|
36
|
+
WITH n, s, head(collect(g.groupName)) AS semanticGroup,
|
|
37
|
+
head(collect(g.id)) AS semanticGroupId
|
|
38
|
+
RETURN properties(n) AS waste_estimation,
|
|
39
|
+
semanticGroup,
|
|
40
|
+
semanticGroupId
|
|
41
|
+
ORDER BY n.estimatedWaste DESC
|
|
42
|
+
LIMIT $limit
|
|
43
|
+
"""
|
|
44
|
+
return query, {
|
|
45
|
+
"threshold": threshold,
|
|
46
|
+
"limit": limit,
|
|
47
|
+
"start_time": start_time,
|
|
48
|
+
"end_time": end_time,
|
|
49
|
+
"application_name": application_name,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def waste_estimations_semantic_groups_query() -> tuple[str, dict[str, Any]]:
|
|
54
|
+
query = """
|
|
55
|
+
MATCH (sg:SemanticGroup {childrenNodes: []})
|
|
56
|
+
OPTIONAL MATCH (sg)-[:containsSession]->(s:Session)
|
|
57
|
+
WITH sg, collect(DISTINCT s.sessionId) AS sessionIds
|
|
58
|
+
UNWIND sessionIds AS sid
|
|
59
|
+
OPTIONAL MATCH (w:WasteEstimation {sessionId: sid})
|
|
60
|
+
WITH sg, sum(COALESCE(w.actualCost, 0)) AS totalCost
|
|
61
|
+
RETURN sg.id AS groupId, sg.groupName AS groupName, totalCost
|
|
62
|
+
ORDER BY totalCost DESC
|
|
63
|
+
"""
|
|
64
|
+
return query, {}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def cost_efficiency_grouped_sessions_query(
|
|
68
|
+
application_name: str,
|
|
69
|
+
) -> tuple[str, dict[str, Any]]:
|
|
70
|
+
query = """
|
|
71
|
+
MATCH (sg:SemanticGroup {childrenNodes: []})-[:containsSession]->(s:Session)
|
|
72
|
+
MATCH (w:WasteEstimation {sessionId: s.sessionId})
|
|
73
|
+
WHERE w.actualCost <> 0
|
|
74
|
+
AND EXISTS {
|
|
75
|
+
MATCH (s)-[:executesSession]->(:MAS {id: $application_name})
|
|
76
|
+
}
|
|
77
|
+
RETURN s.sessionId AS sessionId,
|
|
78
|
+
s.startTime AS startTime,
|
|
79
|
+
sg.groupName AS groupName,
|
|
80
|
+
sg.id AS groupId,
|
|
81
|
+
w.costEfficiency AS costEfficiency,
|
|
82
|
+
w.actualCost AS actualCost,
|
|
83
|
+
w.estimatedWaste AS estimatedWaste
|
|
84
|
+
ORDER BY sg.groupName, s.sessionId
|
|
85
|
+
"""
|
|
86
|
+
return query, {"application_name": application_name}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def wasted_resources_features_score_query(
|
|
90
|
+
session_id: str,
|
|
91
|
+
) -> tuple[str, dict[str, Any]]:
|
|
92
|
+
query = """
|
|
93
|
+
MATCH (s:WastedResourcesFeatureScore)
|
|
94
|
+
WHERE s.sessionId = $session_id
|
|
95
|
+
WITH s.qualityTarget AS qt, s
|
|
96
|
+
ORDER BY qt, s.rank ASC
|
|
97
|
+
WITH qt, collect({
|
|
98
|
+
qualityTarget: qt,
|
|
99
|
+
rank: s.rank,
|
|
100
|
+
feature: s.featureName,
|
|
101
|
+
score: s.score
|
|
102
|
+
}) AS items
|
|
103
|
+
WITH qt, items, size(items) AS total
|
|
104
|
+
WITH qt,
|
|
105
|
+
CASE WHEN total <= 10 THEN items
|
|
106
|
+
ELSE items[..5] + items[total-5..]
|
|
107
|
+
END AS selected
|
|
108
|
+
UNWIND selected AS row
|
|
109
|
+
RETURN row AS item
|
|
110
|
+
ORDER BY item.qualityTarget, item.rank ASC
|
|
111
|
+
"""
|
|
112
|
+
return query, {"session_id": session_id}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def semantic_groups_insights_query(
|
|
116
|
+
start_time: int | None,
|
|
117
|
+
end_time: int | None,
|
|
118
|
+
application_name: str | None = None,
|
|
119
|
+
) -> tuple[str, dict[str, Any]]:
|
|
120
|
+
query = """
|
|
121
|
+
MATCH (s:SemanticGroup)-[:hasInsight]->(i:Insight)
|
|
122
|
+
WHERE ($start_time IS NULL OR datetime(i.createdAt) >= datetime({epochSeconds: $start_time}))
|
|
123
|
+
AND ($end_time IS NULL OR datetime(i.createdAt) <= datetime({epochSeconds: $end_time}))
|
|
124
|
+
AND ($application_name IS NULL OR EXISTS {
|
|
125
|
+
MATCH (:MAS {id: $application_name})-[:containsSemanticGroup]->(s)
|
|
126
|
+
})
|
|
127
|
+
RETURN s.groupName AS groupName,
|
|
128
|
+
s.groupSummary AS groupSummary,
|
|
129
|
+
s.id AS groupId,
|
|
130
|
+
s.sessionIds AS sessionIds,
|
|
131
|
+
toString(i.createdAt) AS createdAt,
|
|
132
|
+
i.description AS description,
|
|
133
|
+
i.id AS insightId,
|
|
134
|
+
i.name AS name,
|
|
135
|
+
i.labels AS labels,
|
|
136
|
+
i.priority AS priority,
|
|
137
|
+
i.targetNodeId AS targetNodeId
|
|
138
|
+
ORDER BY i.priority DESC
|
|
139
|
+
"""
|
|
140
|
+
return query, {
|
|
141
|
+
"start_time": start_time,
|
|
142
|
+
"end_time": end_time,
|
|
143
|
+
"application_name": application_name,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def sessions_insights_query(
|
|
148
|
+
start_time: int | None,
|
|
149
|
+
end_time: int | None,
|
|
150
|
+
semantic_group_id: str | None,
|
|
151
|
+
limit: int,
|
|
152
|
+
offset: int,
|
|
153
|
+
application_name: str | None = None,
|
|
154
|
+
) -> tuple[str, dict[str, Any]]:
|
|
155
|
+
query = """
|
|
156
|
+
MATCH (s:Session)-[:hasInsight]->(i:Insight)
|
|
157
|
+
WHERE ($start_time IS NULL OR datetime(i.createdAt) >= datetime({epochSeconds: $start_time}))
|
|
158
|
+
AND ($end_time IS NULL OR datetime(i.createdAt) <= datetime({epochSeconds: $end_time}))
|
|
159
|
+
AND ($application_name IS NULL OR EXISTS {
|
|
160
|
+
MATCH (s)-[:executesSession]->(:MAS {id: $application_name})
|
|
161
|
+
})
|
|
162
|
+
AND ($semantic_group_id IS NULL OR EXISTS {
|
|
163
|
+
MATCH (:SemanticGroup {id: $semantic_group_id})-[:containsSession*1..]->(s)
|
|
164
|
+
})
|
|
165
|
+
RETURN s.duration AS duration,
|
|
166
|
+
s.endTime AS endTime,
|
|
167
|
+
s.sessionId AS sessionId,
|
|
168
|
+
s.startTime AS startTime,
|
|
169
|
+
toString(i.createdAt) AS createdAt,
|
|
170
|
+
i.description AS description,
|
|
171
|
+
i.id AS insightId,
|
|
172
|
+
i.name AS name,
|
|
173
|
+
i.labels AS labels,
|
|
174
|
+
i.priority AS priority,
|
|
175
|
+
i.targetNodeId AS targetNodeId
|
|
176
|
+
ORDER BY i.priority ASC
|
|
177
|
+
SKIP $offset LIMIT $limit
|
|
178
|
+
"""
|
|
179
|
+
return query, {
|
|
180
|
+
"start_time": start_time,
|
|
181
|
+
"end_time": end_time,
|
|
182
|
+
"semantic_group_id": semantic_group_id,
|
|
183
|
+
"application_name": application_name,
|
|
184
|
+
"offset": offset,
|
|
185
|
+
"limit": limit,
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def session_insights_query(
|
|
190
|
+
session_id: str,
|
|
191
|
+
start_time: int | None,
|
|
192
|
+
end_time: int | None,
|
|
193
|
+
limit: int,
|
|
194
|
+
offset: int,
|
|
195
|
+
) -> tuple[str, dict[str, Any]]:
|
|
196
|
+
query = """
|
|
197
|
+
MATCH (s:Session)-[:hasInsight]->(i:Insight)
|
|
198
|
+
WHERE s.sessionId = $session_id
|
|
199
|
+
AND ($start_time IS NULL OR datetime(i.createdAt) >= datetime({epochSeconds: $start_time}))
|
|
200
|
+
AND ($end_time IS NULL OR datetime(i.createdAt) <= datetime({epochSeconds: $end_time}))
|
|
201
|
+
RETURN s.duration AS duration,
|
|
202
|
+
s.endTime AS endTime,
|
|
203
|
+
s.sessionId AS sessionId,
|
|
204
|
+
s.startTime AS startTime,
|
|
205
|
+
toString(i.createdAt) AS createdAt,
|
|
206
|
+
i.description AS description,
|
|
207
|
+
i.id AS insightId,
|
|
208
|
+
i.name AS name,
|
|
209
|
+
i.labels AS labels,
|
|
210
|
+
i.priority AS priority,
|
|
211
|
+
i.targetNodeId AS targetNodeId
|
|
212
|
+
ORDER BY i.priority ASC
|
|
213
|
+
SKIP $offset LIMIT $limit
|
|
214
|
+
"""
|
|
215
|
+
return query, {
|
|
216
|
+
"session_id": session_id,
|
|
217
|
+
"start_time": start_time,
|
|
218
|
+
"end_time": end_time,
|
|
219
|
+
"offset": offset,
|
|
220
|
+
"limit": limit,
|
|
221
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Repository factory — returns the right :class:`OtelRepository` for the
|
|
4
|
+
current backend (``SCOPE_LOCAL`` env var)."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
from scope.repositories.otel_repository import OtelRepository
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def get_otel_repository() -> OtelRepository:
|
|
14
|
+
"""Return an :class:`OtelRepository` backed by the active database.
|
|
15
|
+
|
|
16
|
+
When the ``SCOPE_LOCAL`` env var is truthy (default), a SQLite-backed
|
|
17
|
+
repository is returned; otherwise a ClickHouse-backed one.
|
|
18
|
+
"""
|
|
19
|
+
if os.getenv("SCOPE_LOCAL", "true").lower() in ("true", "1", "yes"):
|
|
20
|
+
from scope.repositories.sqlite_repository import SqliteOtelRepository
|
|
21
|
+
|
|
22
|
+
return SqliteOtelRepository()
|
|
23
|
+
else:
|
|
24
|
+
from scope.repositories.clickhouse_otel_repository import (
|
|
25
|
+
ClickHouseOtelRepository,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
return ClickHouseOtelRepository()
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""ClickHouse implementation of :class:`OtelRepository`."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from typing import Any, Dict, Optional
|
|
8
|
+
|
|
9
|
+
import scope.db.database as _db
|
|
10
|
+
from scope.query_builders.types import Dialect
|
|
11
|
+
from scope.repositories.otel_repository import OtelRepository
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ClickHouseOtelRepository(OtelRepository):
|
|
15
|
+
"""Queries OTEL traces via clickhouse-connect against a ClickHouse server."""
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
def dialect(self) -> Dialect:
|
|
19
|
+
return Dialect.CLICKHOUSE
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def _client(self):
|
|
23
|
+
return _db.clickhouse_client
|
|
24
|
+
|
|
25
|
+
# ── connection ───────────────────────────────────────────────────────
|
|
26
|
+
|
|
27
|
+
def check_connection(self) -> None:
|
|
28
|
+
if self._client is None:
|
|
29
|
+
raise RuntimeError("ClickHouse client is not initialised")
|
|
30
|
+
self._client.query("SELECT 1")
|
|
31
|
+
|
|
32
|
+
# ── queries ──────────────────────────────────────────────────────────
|
|
33
|
+
|
|
34
|
+
def _grouped_ids(
|
|
35
|
+
self,
|
|
36
|
+
column: str,
|
|
37
|
+
start_dt: Optional[str],
|
|
38
|
+
end_dt: Optional[str],
|
|
39
|
+
) -> list[dict]:
|
|
40
|
+
conditions = [f"{column} != ''"]
|
|
41
|
+
params: dict[str, str] = {}
|
|
42
|
+
|
|
43
|
+
if start_dt is not None:
|
|
44
|
+
conditions.append("Timestamp >= {start_dt:String}")
|
|
45
|
+
params["start_dt"] = start_dt
|
|
46
|
+
if end_dt is not None:
|
|
47
|
+
conditions.append("Timestamp <= {end_dt:String}")
|
|
48
|
+
params["end_dt"] = end_dt
|
|
49
|
+
|
|
50
|
+
where = " AND ".join(conditions)
|
|
51
|
+
sql = (
|
|
52
|
+
f"SELECT {column} AS id, MIN(Timestamp) AS start_timestamp "
|
|
53
|
+
f"FROM otel_traces "
|
|
54
|
+
f"WHERE {where} "
|
|
55
|
+
f"GROUP BY {column} "
|
|
56
|
+
f"ORDER BY MIN(Timestamp) DESC"
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
result = self._client.query(sql, parameters=params)
|
|
60
|
+
return [
|
|
61
|
+
{"id": row[0], "start_timestamp": str(row[1])} for row in result.result_rows
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
def session_ids(
|
|
65
|
+
self,
|
|
66
|
+
start_dt: Optional[str] = None,
|
|
67
|
+
end_dt: Optional[str] = None,
|
|
68
|
+
) -> list[dict]:
|
|
69
|
+
return self._grouped_ids("session_id", start_dt, end_dt)
|
|
70
|
+
|
|
71
|
+
def traces(
|
|
72
|
+
self,
|
|
73
|
+
start_dt: Optional[str] = None,
|
|
74
|
+
end_dt: Optional[str] = None,
|
|
75
|
+
app_name: Optional[str] = None,
|
|
76
|
+
limit: int = 50,
|
|
77
|
+
offset: int = 0,
|
|
78
|
+
) -> list[dict]:
|
|
79
|
+
conditions = ["session_id != ''"]
|
|
80
|
+
params: dict[str, Any] = {}
|
|
81
|
+
|
|
82
|
+
if start_dt is not None:
|
|
83
|
+
conditions.append("Timestamp >= {start_dt:String}")
|
|
84
|
+
params["start_dt"] = start_dt
|
|
85
|
+
if end_dt is not None:
|
|
86
|
+
conditions.append("Timestamp <= {end_dt:String}")
|
|
87
|
+
params["end_dt"] = end_dt
|
|
88
|
+
if app_name is not None:
|
|
89
|
+
conditions.append("application_id = {app_name:String}")
|
|
90
|
+
params["app_name"] = app_name
|
|
91
|
+
|
|
92
|
+
where = " AND ".join(conditions)
|
|
93
|
+
sql = (
|
|
94
|
+
f"SELECT trace_id, application_id, "
|
|
95
|
+
f"MIN(Timestamp) AS start_time, MAX(Timestamp) AS end_time "
|
|
96
|
+
f"FROM otel_traces "
|
|
97
|
+
f"WHERE {where} "
|
|
98
|
+
f"GROUP BY trace_id "
|
|
99
|
+
f"ORDER BY MIN(Timestamp) DESC "
|
|
100
|
+
f"LIMIT {{limit:UInt32}} OFFSET {{offset:UInt32}}"
|
|
101
|
+
)
|
|
102
|
+
params["limit"] = limit
|
|
103
|
+
params["offset"] = offset
|
|
104
|
+
|
|
105
|
+
result = self._client.query(sql, parameters=params)
|
|
106
|
+
return [
|
|
107
|
+
{
|
|
108
|
+
"trace_id": row[0],
|
|
109
|
+
"application_id": row[1],
|
|
110
|
+
"start_time": str(row[2]),
|
|
111
|
+
"end_time": str(row[3]),
|
|
112
|
+
}
|
|
113
|
+
for row in result.result_rows
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
def application_ids(
|
|
117
|
+
self,
|
|
118
|
+
start_dt: Optional[str] = None,
|
|
119
|
+
end_dt: Optional[str] = None,
|
|
120
|
+
limit: int = 50,
|
|
121
|
+
offset: int = 0,
|
|
122
|
+
) -> list[dict]:
|
|
123
|
+
return self._grouped_ids("application_id", start_dt, end_dt)
|
|
124
|
+
|
|
125
|
+
# ── seeding ──────────────────────────────────────────────────────────
|
|
126
|
+
|
|
127
|
+
def seed(self, csv_path: str) -> None:
|
|
128
|
+
"""No-op — ClickHouse is seeded via its init SQL script."""
|
|
129
|
+
|
|
130
|
+
def execute(self, query: str, params: Optional[Dict[str, Any]] = None) -> list:
|
|
131
|
+
"""Execute an arbitrary SQL query and return result rows."""
|
|
132
|
+
if self._client is None:
|
|
133
|
+
raise RuntimeError("ClickHouse client is not initialised")
|
|
134
|
+
result = self._client.query(query, parameters=params or {})
|
|
135
|
+
return result.result_rows
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Abstract interface for OTEL trace data access."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from abc import ABC, abstractmethod
|
|
8
|
+
from typing import Any, Dict, Optional
|
|
9
|
+
|
|
10
|
+
from scope.query_builders.types import Dialect
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class OtelRepository(ABC):
|
|
14
|
+
"""Defines the data-retrieval contract for OTEL traces.
|
|
15
|
+
|
|
16
|
+
Each concrete implementation (SQLite, ClickHouse, …) must provide
|
|
17
|
+
these methods so the rest of the application stays backend-agnostic.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
@abstractmethod
|
|
22
|
+
def dialect(self) -> Dialect:
|
|
23
|
+
"""Return the SQL dialect used by this repository."""
|
|
24
|
+
|
|
25
|
+
@abstractmethod
|
|
26
|
+
def check_connection(self) -> None:
|
|
27
|
+
"""Verify that the underlying database is reachable.
|
|
28
|
+
|
|
29
|
+
Raises
|
|
30
|
+
------
|
|
31
|
+
RuntimeError
|
|
32
|
+
If the connection cannot be established.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
@abstractmethod
|
|
36
|
+
def session_ids(
|
|
37
|
+
self,
|
|
38
|
+
start_dt: Optional[str] = None,
|
|
39
|
+
end_dt: Optional[str] = None,
|
|
40
|
+
) -> list[dict]:
|
|
41
|
+
"""Return distinct non-empty session IDs with their earliest timestamp.
|
|
42
|
+
|
|
43
|
+
Parameters
|
|
44
|
+
----------
|
|
45
|
+
start_dt, end_dt:
|
|
46
|
+
Optional ``'YYYY-MM-DD HH:MM:SS'`` boundaries.
|
|
47
|
+
|
|
48
|
+
Returns
|
|
49
|
+
-------
|
|
50
|
+
list[dict]
|
|
51
|
+
Each dict has ``{"id": str, "start_timestamp": str}``,
|
|
52
|
+
ordered by earliest timestamp descending.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
@abstractmethod
|
|
56
|
+
def traces(
|
|
57
|
+
self,
|
|
58
|
+
start_dt: Optional[str] = None,
|
|
59
|
+
end_dt: Optional[str] = None,
|
|
60
|
+
app_name: Optional[str] = None,
|
|
61
|
+
limit: int = 50,
|
|
62
|
+
offset: int = 0,
|
|
63
|
+
) -> list[dict]:
|
|
64
|
+
"""Return trace summaries grouped by trace_id.
|
|
65
|
+
|
|
66
|
+
Returns
|
|
67
|
+
-------
|
|
68
|
+
list[dict]
|
|
69
|
+
Each dict has ``{"trace_id": str, "application_id": str,
|
|
70
|
+
"start_time": str, "end_time": str}``,
|
|
71
|
+
ordered by earliest timestamp descending.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
@abstractmethod
|
|
75
|
+
def application_ids(
|
|
76
|
+
self,
|
|
77
|
+
start_dt: Optional[str] = None,
|
|
78
|
+
end_dt: Optional[str] = None,
|
|
79
|
+
limit: int = 50,
|
|
80
|
+
offset: int = 0,
|
|
81
|
+
) -> list[dict]:
|
|
82
|
+
"""Return distinct non-empty application IDs with their earliest timestamp.
|
|
83
|
+
|
|
84
|
+
Same contract as :meth:`session_ids` but for the ``application_id`` column.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
@abstractmethod
|
|
88
|
+
def seed(self, csv_path: str) -> None:
|
|
89
|
+
"""Seed the otel_traces table from a CSV file (if not already seeded).
|
|
90
|
+
|
|
91
|
+
The CSV is expected to have a ClickHouse type-hint row as row 2
|
|
92
|
+
(immediately after the header), which must be skipped.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
@abstractmethod
|
|
96
|
+
def execute(self, query: str, params: Optional[Dict[str, Any]] = None) -> list:
|
|
97
|
+
"""Execute an arbitrary SQL query and return the result rows."""
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""SQLite (SQLAlchemy) implementation of :class:`OtelRepository`."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import csv
|
|
8
|
+
from typing import Any, Dict, Optional
|
|
9
|
+
|
|
10
|
+
from sqlalchemy import func, text
|
|
11
|
+
|
|
12
|
+
from scope.connectors.sqlalchemy import SQLAlchemyConnector
|
|
13
|
+
from scope.models.otel_traces import SCOPEBaseModel, OtelTrace
|
|
14
|
+
from scope.query_builders.types import Dialect
|
|
15
|
+
from scope.repositories.otel_repository import OtelRepository
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _get_engine(connector: SQLAlchemyConnector | None = None):
|
|
19
|
+
"""Return the SQLAlchemy engine from *connector* or the global default."""
|
|
20
|
+
if connector is not None:
|
|
21
|
+
return connector.engine
|
|
22
|
+
from scope.db.database import get_engine
|
|
23
|
+
|
|
24
|
+
return get_engine()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _get_session(connector: SQLAlchemyConnector | None = None):
|
|
28
|
+
"""Return a new SQLAlchemy session from *connector* or the global default."""
|
|
29
|
+
if connector is not None:
|
|
30
|
+
return connector.get_session()
|
|
31
|
+
from scope.db.database import get_session
|
|
32
|
+
|
|
33
|
+
return get_session()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ── Column name mapping: CSV header → OtelTrace model field ──────────────────
|
|
37
|
+
|
|
38
|
+
_CSV_FIELD_MAP = {
|
|
39
|
+
"Timestamp": "timestamp",
|
|
40
|
+
"TraceId": "trace_id",
|
|
41
|
+
"SpanId": "span_id",
|
|
42
|
+
"ParentSpanId": "parent_span_id",
|
|
43
|
+
"TraceState": "trace_state",
|
|
44
|
+
"SpanName": "span_name",
|
|
45
|
+
"SpanKind": "span_kind",
|
|
46
|
+
"ServiceName": "service_name",
|
|
47
|
+
"ResourceAttributes": "resource_attributes",
|
|
48
|
+
"ScopeName": "scope_name",
|
|
49
|
+
"ScopeVersion": "scope_version",
|
|
50
|
+
"SpanAttributes": "span_attributes",
|
|
51
|
+
"Duration": "duration",
|
|
52
|
+
"StatusCode": "status_code",
|
|
53
|
+
"StatusMessage": "status_message",
|
|
54
|
+
"Events.Timestamp": "events_timestamp",
|
|
55
|
+
"Events.Name": "events_name",
|
|
56
|
+
"Events.Attributes": "events_attributes",
|
|
57
|
+
"Links.TraceId": "links_trace_id",
|
|
58
|
+
"Links.SpanId": "links_span_id",
|
|
59
|
+
"Links.TraceState": "links_trace_state",
|
|
60
|
+
"Links.Attributes": "links_attributes",
|
|
61
|
+
"session_id": "session_id",
|
|
62
|
+
"agent_id": "agent_id",
|
|
63
|
+
"application_id": "application_id",
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class SqliteOtelRepository(OtelRepository):
|
|
68
|
+
"""Queries OTEL traces via SQLAlchemy against a local SQLite database."""
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def dialect(self) -> Dialect:
|
|
72
|
+
return Dialect.SQLITE
|
|
73
|
+
|
|
74
|
+
# ── connection ───────────────────────────────────────────────────────
|
|
75
|
+
|
|
76
|
+
def check_connection(self) -> None:
|
|
77
|
+
session = _get_session()
|
|
78
|
+
try:
|
|
79
|
+
session.execute(text("SELECT 1"))
|
|
80
|
+
finally:
|
|
81
|
+
session.close()
|
|
82
|
+
|
|
83
|
+
# ── queries ──────────────────────────────────────────────────────────
|
|
84
|
+
|
|
85
|
+
def _grouped_ids(
|
|
86
|
+
self,
|
|
87
|
+
column: str,
|
|
88
|
+
start_dt: Optional[str],
|
|
89
|
+
end_dt: Optional[str],
|
|
90
|
+
) -> list[dict]:
|
|
91
|
+
col_attr = getattr(OtelTrace, column)
|
|
92
|
+
session = _get_session()
|
|
93
|
+
try:
|
|
94
|
+
query = session.query(
|
|
95
|
+
col_attr.label("id"),
|
|
96
|
+
func.min(OtelTrace.timestamp).label("start_timestamp"),
|
|
97
|
+
).filter(col_attr != "")
|
|
98
|
+
if start_dt is not None:
|
|
99
|
+
query = query.filter(OtelTrace.timestamp >= start_dt)
|
|
100
|
+
if end_dt is not None:
|
|
101
|
+
query = query.filter(OtelTrace.timestamp <= end_dt)
|
|
102
|
+
|
|
103
|
+
query = query.group_by(col_attr).order_by(
|
|
104
|
+
func.min(OtelTrace.timestamp).desc()
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
return [
|
|
108
|
+
{"id": row.id, "start_timestamp": row.start_timestamp}
|
|
109
|
+
for row in query.all()
|
|
110
|
+
]
|
|
111
|
+
finally:
|
|
112
|
+
session.close()
|
|
113
|
+
|
|
114
|
+
def session_ids(
|
|
115
|
+
self,
|
|
116
|
+
start_dt: Optional[str] = None,
|
|
117
|
+
end_dt: Optional[str] = None,
|
|
118
|
+
) -> list[dict]:
|
|
119
|
+
return self._grouped_ids("session_id", start_dt, end_dt)
|
|
120
|
+
|
|
121
|
+
def traces(
|
|
122
|
+
self,
|
|
123
|
+
start_dt: Optional[str] = None,
|
|
124
|
+
end_dt: Optional[str] = None,
|
|
125
|
+
app_name: Optional[str] = None,
|
|
126
|
+
limit: int = 50,
|
|
127
|
+
offset: int = 0,
|
|
128
|
+
) -> list[dict]:
|
|
129
|
+
session = _get_session()
|
|
130
|
+
try:
|
|
131
|
+
query = session.query(
|
|
132
|
+
OtelTrace.trace_id.label("trace_id"),
|
|
133
|
+
OtelTrace.application_id.label("application_id"),
|
|
134
|
+
func.min(OtelTrace.timestamp).label("start_time"),
|
|
135
|
+
func.max(OtelTrace.timestamp).label("end_time"),
|
|
136
|
+
).filter(OtelTrace.session_id != "")
|
|
137
|
+
if start_dt is not None:
|
|
138
|
+
query = query.filter(OtelTrace.timestamp >= start_dt)
|
|
139
|
+
if end_dt is not None:
|
|
140
|
+
query = query.filter(OtelTrace.timestamp <= end_dt)
|
|
141
|
+
if app_name is not None:
|
|
142
|
+
query = query.filter(OtelTrace.application_id == app_name)
|
|
143
|
+
|
|
144
|
+
query = (
|
|
145
|
+
query.group_by(OtelTrace.trace_id)
|
|
146
|
+
.order_by(func.min(OtelTrace.timestamp).desc())
|
|
147
|
+
.limit(limit)
|
|
148
|
+
.offset(offset)
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
return [
|
|
152
|
+
{
|
|
153
|
+
"trace_id": row.trace_id,
|
|
154
|
+
"application_id": row.application_id,
|
|
155
|
+
"start_time": str(row.start_time),
|
|
156
|
+
"end_time": str(row.end_time),
|
|
157
|
+
}
|
|
158
|
+
for row in query.all()
|
|
159
|
+
]
|
|
160
|
+
finally:
|
|
161
|
+
session.close()
|
|
162
|
+
|
|
163
|
+
def application_ids(
|
|
164
|
+
self,
|
|
165
|
+
start_dt: Optional[str] = None,
|
|
166
|
+
end_dt: Optional[str] = None,
|
|
167
|
+
limit: int = 50,
|
|
168
|
+
offset: int = 0,
|
|
169
|
+
) -> list[dict]:
|
|
170
|
+
return self._grouped_ids("application_id", start_dt, end_dt)
|
|
171
|
+
|
|
172
|
+
# ── seeding ──────────────────────────────────────────────────────────
|
|
173
|
+
|
|
174
|
+
def seed(
|
|
175
|
+
self, csv_path: str, *, connector: SQLAlchemyConnector | None = None
|
|
176
|
+
) -> None:
|
|
177
|
+
engine = _get_engine(connector)
|
|
178
|
+
SCOPEBaseModel.metadata.create_all(engine)
|
|
179
|
+
|
|
180
|
+
session = _get_session(connector)
|
|
181
|
+
try:
|
|
182
|
+
if session.query(OtelTrace).count() > 0:
|
|
183
|
+
return
|
|
184
|
+
|
|
185
|
+
with open(csv_path, newline="", encoding="utf-8") as fh:
|
|
186
|
+
reader = csv.DictReader(fh)
|
|
187
|
+
rows: list[dict] = []
|
|
188
|
+
for i, raw_row in enumerate(reader):
|
|
189
|
+
# Row 0 after header is the ClickHouse type-hint row — skip it
|
|
190
|
+
if i == 0:
|
|
191
|
+
continue
|
|
192
|
+
row = {}
|
|
193
|
+
for csv_col, model_field in _CSV_FIELD_MAP.items():
|
|
194
|
+
value = raw_row.get(csv_col, "")
|
|
195
|
+
if model_field == "duration":
|
|
196
|
+
value = int(value) if value else 0
|
|
197
|
+
row[model_field] = value
|
|
198
|
+
rows.append(row)
|
|
199
|
+
|
|
200
|
+
session.bulk_insert_mappings(OtelTrace, rows)
|
|
201
|
+
session.commit()
|
|
202
|
+
except Exception:
|
|
203
|
+
session.rollback()
|
|
204
|
+
raise
|
|
205
|
+
finally:
|
|
206
|
+
session.close()
|
|
207
|
+
|
|
208
|
+
def execute(self, query: str, params: Optional[Dict[str, Any]] = None) -> list:
|
|
209
|
+
"""Execute an arbitrary SQL query and return result rows."""
|
|
210
|
+
session = _get_session()
|
|
211
|
+
try:
|
|
212
|
+
result = session.execute(text(query), params or {})
|
|
213
|
+
return result.fetchall()
|
|
214
|
+
finally:
|
|
215
|
+
session.close()
|