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,193 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""FastAPI router for the v2 /metrics endpoint.
|
|
4
|
+
|
|
5
|
+
This module starts as a clone of the v1 metrics endpoint. Endpoints will be
|
|
6
|
+
reimplemented here incrementally without touching v1.
|
|
7
|
+
|
|
8
|
+
Endpoints
|
|
9
|
+
---------
|
|
10
|
+
GET /metrics/applications/{application_id}/metrics
|
|
11
|
+
Return metric values for an application given an explicit list of metric names.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import functools
|
|
17
|
+
import logging
|
|
18
|
+
from typing import Any, Optional
|
|
19
|
+
|
|
20
|
+
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
21
|
+
|
|
22
|
+
from scope.api.api_v1.endpoints.helpers import get_client
|
|
23
|
+
|
|
24
|
+
# Reuse v1 provider wiring and helpers until v2 introduces its own.
|
|
25
|
+
from scope.api.api_v1.endpoints.metrics import (
|
|
26
|
+
_mce_discovery_providers_available,
|
|
27
|
+
_require_provider,
|
|
28
|
+
)
|
|
29
|
+
from scope.connectors.base import Connector
|
|
30
|
+
from scope.core.config import settings
|
|
31
|
+
from scope.dependencies import get_neo4j_db
|
|
32
|
+
from scope.models.otel_traces import (
|
|
33
|
+
MetricCatalogItem,
|
|
34
|
+
MetricCatalogResponse,
|
|
35
|
+
MetricInfoItemResponse,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
router = APIRouter()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _client(db: Connector = Depends(get_neo4j_db)): # noqa: B008
|
|
44
|
+
"""Resolve a Neo4j-backed client with the active metrics provider."""
|
|
45
|
+
return get_client(api_client=db, metrics_provider=_require_provider())
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# ── Metrics catalog ───────────────────────────────────────────────────────────
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@functools.lru_cache(maxsize=1)
|
|
52
|
+
def _build_catalog() -> list[MetricCatalogItem]:
|
|
53
|
+
"""Discover all registered metrics using the mce-core registry.
|
|
54
|
+
|
|
55
|
+
Result is cached for the lifetime of the process — metrics are
|
|
56
|
+
registered at import time and do not change at runtime.
|
|
57
|
+
"""
|
|
58
|
+
try:
|
|
59
|
+
if _mce_discovery_providers_available():
|
|
60
|
+
from mce.core.registry.discovery import (
|
|
61
|
+
discover_all_metrics,
|
|
62
|
+
ensure_target_types,
|
|
63
|
+
get_provider_name,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
items = []
|
|
67
|
+
for metric_cls in discover_all_metrics():
|
|
68
|
+
ensure_target_types(metric_cls)
|
|
69
|
+
meta = getattr(metric_cls, "metadata", None)
|
|
70
|
+
scope = getattr(meta, "scope", None) if meta else None
|
|
71
|
+
scope_val = (
|
|
72
|
+
scope.value
|
|
73
|
+
if hasattr(scope, "value")
|
|
74
|
+
else str(scope)
|
|
75
|
+
if scope
|
|
76
|
+
else "session"
|
|
77
|
+
)
|
|
78
|
+
target_types = getattr(meta, "target_types", None) or set()
|
|
79
|
+
description = getattr(meta, "description", None)
|
|
80
|
+
display_name = (
|
|
81
|
+
meta.get_display_name()
|
|
82
|
+
if meta and hasattr(meta, "get_display_name")
|
|
83
|
+
else metric_cls.metric_id
|
|
84
|
+
)
|
|
85
|
+
items.append(
|
|
86
|
+
MetricCatalogItem(
|
|
87
|
+
metric_id=metric_cls.metric_id,
|
|
88
|
+
id=metric_cls.metric_id,
|
|
89
|
+
name=display_name,
|
|
90
|
+
provider=get_provider_name(metric_cls),
|
|
91
|
+
scope=scope_val,
|
|
92
|
+
target_types=sorted(target_types),
|
|
93
|
+
description=description,
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
return items
|
|
97
|
+
|
|
98
|
+
logger.info(
|
|
99
|
+
"MCE provider modules not installed; serving fallback metric catalog from METRIC_CATEGORIES"
|
|
100
|
+
)
|
|
101
|
+
except Exception as exc:
|
|
102
|
+
logger.warning(
|
|
103
|
+
"Metric discovery failed; falling back to configured catalog: %s", exc
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
return _build_fallback_catalog_from_settings()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _build_fallback_catalog_from_settings() -> list[MetricCatalogItem]:
|
|
110
|
+
"""Build a static metric catalog from application settings.
|
|
111
|
+
|
|
112
|
+
This keeps /metrics/catalog useful in minimal environments where optional
|
|
113
|
+
MCE provider wheels are intentionally not installed.
|
|
114
|
+
"""
|
|
115
|
+
items: list[MetricCatalogItem] = []
|
|
116
|
+
seen: set[str] = set()
|
|
117
|
+
|
|
118
|
+
for category in settings.METRIC_CATEGORIES.values():
|
|
119
|
+
for metric_id, cfg in category.items():
|
|
120
|
+
if metric_id in seen:
|
|
121
|
+
continue
|
|
122
|
+
seen.add(metric_id)
|
|
123
|
+
|
|
124
|
+
items.append(
|
|
125
|
+
MetricCatalogItem(
|
|
126
|
+
metric_id=metric_id,
|
|
127
|
+
id=metric_id,
|
|
128
|
+
name=cfg.get("name") or metric_id,
|
|
129
|
+
provider="SCOPE",
|
|
130
|
+
scope="session",
|
|
131
|
+
target_types=["mas:Session"],
|
|
132
|
+
description=cfg.get("description"),
|
|
133
|
+
)
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
return sorted(items, key=lambda item: item.metric_id.lower())
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# ── get_metrics ───────────────────────────────────────────────────────────────
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# @router.get("/applications/{application_id}/metrics")
|
|
143
|
+
# def get_metrics(
|
|
144
|
+
# application_id: str,
|
|
145
|
+
# metric_names: list[str] = Query(..., description="List of metric names to retrieve"),
|
|
146
|
+
# start_time: str | None = Query(None, description="ISO-8601 or epoch start time filter"),
|
|
147
|
+
# end_time: str | None = Query(None, description="ISO-8601 or epoch end time filter"),
|
|
148
|
+
# agent_id: str | None = Query(None, description="Optional agent ID filter"),
|
|
149
|
+
# metrics_client=Depends(_client), # noqa: B008
|
|
150
|
+
# ) -> Any:
|
|
151
|
+
# """Return metric values for an application given an explicit list of metric names."""
|
|
152
|
+
# return metrics_client.get_metrics(
|
|
153
|
+
# application_id,
|
|
154
|
+
# metric_names,
|
|
155
|
+
# agent_id=agent_id,
|
|
156
|
+
# start_time=start_time,
|
|
157
|
+
# end_time=end_time,
|
|
158
|
+
# )
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@router.get("/info")
|
|
162
|
+
def metrics_info(
|
|
163
|
+
metric_id: Optional[str] = Query(
|
|
164
|
+
None,
|
|
165
|
+
description="Metric ID to look up (returns single-metric detail when provided)",
|
|
166
|
+
),
|
|
167
|
+
) -> Any:
|
|
168
|
+
"""Return descriptive information about the metrics subsystem.
|
|
169
|
+
|
|
170
|
+
* Without ``?metric_id=``: returns the full MCE metric catalog (same shape as ``/catalog``).
|
|
171
|
+
* With ``?metric_id=<id>``: returns detailed info for that specific metric.
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
logger.debug(">>> scope-api v2 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
|
|
175
|
+
catalog = _build_catalog()
|
|
176
|
+
if metric_id is not None:
|
|
177
|
+
match = next(
|
|
178
|
+
(m for m in catalog if m.metric_id == metric_id or m.id == metric_id),
|
|
179
|
+
None,
|
|
180
|
+
)
|
|
181
|
+
if match is None:
|
|
182
|
+
raise HTTPException(
|
|
183
|
+
status_code=404, detail=f"Metric '{metric_id}' not found"
|
|
184
|
+
)
|
|
185
|
+
return MetricInfoItemResponse(
|
|
186
|
+
id=match.id,
|
|
187
|
+
name=match.name,
|
|
188
|
+
description=match.description,
|
|
189
|
+
unit=match.unit,
|
|
190
|
+
type=match.type,
|
|
191
|
+
dimensions=match.target_types,
|
|
192
|
+
)
|
|
193
|
+
return MetricCatalogResponse(total=len(catalog), metrics=catalog)
|
scope/app.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Entry point for the SCOPE API service.
|
|
4
|
+
|
|
5
|
+
Run with:
|
|
6
|
+
uvicorn scope.app:app --reload
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
|
|
12
|
+
import uvicorn
|
|
13
|
+
from dotenv import load_dotenv
|
|
14
|
+
|
|
15
|
+
logging.basicConfig(
|
|
16
|
+
format="%(asctime)s %(levelname)s [%(name)s:%(funcName)s] %(message)s",
|
|
17
|
+
level=logging.INFO,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
# Load environment variables from .env file
|
|
21
|
+
load_dotenv()
|
|
22
|
+
|
|
23
|
+
port = int(os.getenv("SCOPE_API_PORT", 8000))
|
|
24
|
+
reload = os.getenv("SCOPE_API_RELOAD", "true").lower() == "true"
|
|
25
|
+
print(f"Starting SCOPE API on port {port}...")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def main():
|
|
29
|
+
"""Run the SCOPE API server."""
|
|
30
|
+
uvicorn.run("scope.api:app", host="0.0.0.0", port=port, reload=reload)
|
scope/cache.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Redis-backed caching utilities."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
from typing import Any, Callable
|
|
11
|
+
|
|
12
|
+
import redis
|
|
13
|
+
from pydantic import BaseModel
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def make_cache_key(prefix: str, params: dict) -> str:
|
|
19
|
+
"""Return a deterministic Redis key for *prefix* + *params*."""
|
|
20
|
+
payload = json.dumps(params, sort_keys=True)
|
|
21
|
+
digest = hashlib.sha256(payload.encode()).hexdigest()[:16]
|
|
22
|
+
return f"cache:{prefix}:{digest}"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _serialize(value: Any) -> str:
|
|
26
|
+
if isinstance(value, BaseModel):
|
|
27
|
+
return value.model_dump_json()
|
|
28
|
+
return json.dumps(value)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def cached(
|
|
32
|
+
redis_client: redis.Redis,
|
|
33
|
+
key: str,
|
|
34
|
+
fetch: Callable[[], Any],
|
|
35
|
+
ttl: int = 30,
|
|
36
|
+
enabled: bool = True,
|
|
37
|
+
) -> Any:
|
|
38
|
+
"""Return the cached value for *key*, or call *fetch()*, cache and return it.
|
|
39
|
+
|
|
40
|
+
When *enabled* is False, *fetch()* is called directly and Redis is not
|
|
41
|
+
consulted. Redis errors are caught and logged so that unavailability
|
|
42
|
+
never breaks the API.
|
|
43
|
+
"""
|
|
44
|
+
if not enabled:
|
|
45
|
+
logger.debug("cache DISABLED — bypassing for %s", key)
|
|
46
|
+
return fetch()
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
raw = redis_client.get(key)
|
|
50
|
+
if raw is not None:
|
|
51
|
+
logger.debug("cache HIT %s", key)
|
|
52
|
+
return json.loads(raw)
|
|
53
|
+
except Exception as exc:
|
|
54
|
+
logger.warning("Redis GET failed (%s) — bypassing cache", exc)
|
|
55
|
+
|
|
56
|
+
result = fetch()
|
|
57
|
+
|
|
58
|
+
try:
|
|
59
|
+
redis_client.set(key, _serialize(result), ex=ttl)
|
|
60
|
+
logger.debug("cache MISS %s (stored, ttl=%ds)", key, ttl)
|
|
61
|
+
except Exception as exc:
|
|
62
|
+
logger.warning("Redis SET failed (%s) — result not cached", exc)
|
|
63
|
+
|
|
64
|
+
return result
|
scope/client/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""SCOPE client public exports.
|
|
4
|
+
|
|
5
|
+
Exports are loaded lazily so utility modules like ``scope.client.dal`` can be
|
|
6
|
+
imported without importing LocalClient and its optional dependencies.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
__all__ = ["SCOPEAPIClient", "GoldenClient", "LocalClient"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def __getattr__(name: str) -> Any:
|
|
15
|
+
if name == "SCOPEAPIClient":
|
|
16
|
+
from scope.client.base import SCOPEAPIClient
|
|
17
|
+
|
|
18
|
+
return SCOPEAPIClient
|
|
19
|
+
if name == "GoldenClient":
|
|
20
|
+
from scope.client.mock import GoldenClient
|
|
21
|
+
|
|
22
|
+
return GoldenClient
|
|
23
|
+
if name == "LocalClient":
|
|
24
|
+
from scope.client.local import LocalClient
|
|
25
|
+
|
|
26
|
+
return LocalClient
|
|
27
|
+
raise AttributeError(f"module 'scope.client' has no attribute {name!r}")
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Concepts-domain methods for :class:`LocalClient`.
|
|
4
|
+
|
|
5
|
+
These methods query the Neo4j knowledge graph for neurosymbolic
|
|
6
|
+
concepts / symbols, scoped by application and optionally by span.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
|
|
13
|
+
from scope.connectors.base import Connector
|
|
14
|
+
from scope.core.exceptions import DatabaseError
|
|
15
|
+
from scope.models.otel_traces import (
|
|
16
|
+
ConceptItem,
|
|
17
|
+
ConceptsResponse,
|
|
18
|
+
SpanConceptsResponse,
|
|
19
|
+
)
|
|
20
|
+
from scope.query_builders import concepts as concepts_queries
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ConceptsClient:
|
|
26
|
+
"""Concepts operations mixed into :class:`LocalClient`."""
|
|
27
|
+
|
|
28
|
+
db: Connector
|
|
29
|
+
|
|
30
|
+
# ── app-level concepts ────────────────────────────────────────────────
|
|
31
|
+
|
|
32
|
+
def get_app_concepts(self, app_id: str) -> ConceptsResponse:
|
|
33
|
+
"""Return all concepts for *app_id*."""
|
|
34
|
+
query, params = concepts_queries.app_concepts_query(app_id)
|
|
35
|
+
try:
|
|
36
|
+
rows = self.db.execute(query, params)
|
|
37
|
+
except Exception as exc:
|
|
38
|
+
raise DatabaseError(
|
|
39
|
+
f"Failed to get concepts for app '{app_id}': {exc}"
|
|
40
|
+
) from exc
|
|
41
|
+
|
|
42
|
+
return ConceptsResponse(
|
|
43
|
+
app_id=app_id,
|
|
44
|
+
concepts=[
|
|
45
|
+
ConceptItem(
|
|
46
|
+
name=r.get("name", ""),
|
|
47
|
+
type=r.get("type", ""),
|
|
48
|
+
properties=r.get("properties") or {},
|
|
49
|
+
)
|
|
50
|
+
for r in rows
|
|
51
|
+
],
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
# ── span-level concepts ───────────────────────────────────────────────
|
|
55
|
+
|
|
56
|
+
def get_span_concepts(
|
|
57
|
+
self,
|
|
58
|
+
app_id: str,
|
|
59
|
+
session_id: str,
|
|
60
|
+
span_id: str,
|
|
61
|
+
) -> SpanConceptsResponse:
|
|
62
|
+
"""Return concepts for a specific span."""
|
|
63
|
+
query, params = concepts_queries.span_concepts_query(
|
|
64
|
+
app_id,
|
|
65
|
+
session_id,
|
|
66
|
+
span_id,
|
|
67
|
+
)
|
|
68
|
+
try:
|
|
69
|
+
rows = self.db.execute(query, params)
|
|
70
|
+
except Exception as exc:
|
|
71
|
+
raise DatabaseError(
|
|
72
|
+
f"Failed to get concepts for span '{span_id}': {exc}"
|
|
73
|
+
) from exc
|
|
74
|
+
|
|
75
|
+
return SpanConceptsResponse(
|
|
76
|
+
app_id=app_id,
|
|
77
|
+
session_id=session_id,
|
|
78
|
+
span_id=span_id,
|
|
79
|
+
concepts=[
|
|
80
|
+
ConceptItem(
|
|
81
|
+
name=r.get("name", ""),
|
|
82
|
+
type=r.get("type", ""),
|
|
83
|
+
properties=r.get("properties") or {},
|
|
84
|
+
)
|
|
85
|
+
for r in rows
|
|
86
|
+
],
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# ── write concepts ────────────────────────────────────────────────────
|
|
90
|
+
|
|
91
|
+
def write_app_concepts(
|
|
92
|
+
self,
|
|
93
|
+
app_id: str,
|
|
94
|
+
concepts: list[dict],
|
|
95
|
+
) -> dict:
|
|
96
|
+
"""Write concepts to an application node in the KG."""
|
|
97
|
+
written = 0
|
|
98
|
+
errors: list[str] = []
|
|
99
|
+
for c in concepts:
|
|
100
|
+
query, params = concepts_queries.write_app_concept_query(
|
|
101
|
+
app_id=app_id,
|
|
102
|
+
name=c["name"],
|
|
103
|
+
concept_type=c.get("type", ""),
|
|
104
|
+
properties=c.get("properties"),
|
|
105
|
+
)
|
|
106
|
+
try:
|
|
107
|
+
self.db.execute_command(query, params)
|
|
108
|
+
written += 1
|
|
109
|
+
except Exception as exc:
|
|
110
|
+
errors.append(f"{c['name']}: {exc}")
|
|
111
|
+
return {"written": written, "errors": errors}
|
|
112
|
+
|
|
113
|
+
def write_span_concepts(
|
|
114
|
+
self,
|
|
115
|
+
app_id: str,
|
|
116
|
+
session_id: str,
|
|
117
|
+
span_id: str,
|
|
118
|
+
concepts: list[dict],
|
|
119
|
+
) -> dict:
|
|
120
|
+
"""Write concepts to a span node in the KG."""
|
|
121
|
+
written = 0
|
|
122
|
+
errors: list[str] = []
|
|
123
|
+
for c in concepts:
|
|
124
|
+
query, params = concepts_queries.write_span_concept_query(
|
|
125
|
+
app_id=app_id,
|
|
126
|
+
session_id=session_id,
|
|
127
|
+
span_id=span_id,
|
|
128
|
+
name=c["name"],
|
|
129
|
+
concept_type=c.get("type", ""),
|
|
130
|
+
properties=c.get("properties"),
|
|
131
|
+
)
|
|
132
|
+
try:
|
|
133
|
+
self.db.execute_command(query, params)
|
|
134
|
+
written += 1
|
|
135
|
+
except Exception as exc:
|
|
136
|
+
errors.append(f"{c['name']}: {exc}")
|
|
137
|
+
return {"written": written, "errors": errors}
|
scope/client/_kg.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""KG-domain methods for :class:`LocalClient`."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
|
|
9
|
+
from scope.connectors.base import Connector
|
|
10
|
+
from scope.core.exceptions import DatabaseError
|
|
11
|
+
from scope.query_builders import kg as kg_queries
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class KGClient:
|
|
17
|
+
"""KG (knowledge-graph) operations mixed into :class:`LocalClient`."""
|
|
18
|
+
|
|
19
|
+
db: Connector
|
|
20
|
+
|
|
21
|
+
def get_state_by_session_id(self, session_id: str) -> dict:
|
|
22
|
+
stmt = kg_queries.get_state_from_sessionId(session_id)
|
|
23
|
+
try:
|
|
24
|
+
rows = self.db.execute(stmt)
|
|
25
|
+
return rows[0]["s"] if rows else {}
|
|
26
|
+
except Exception as exc:
|
|
27
|
+
raise DatabaseError(
|
|
28
|
+
f"Failed to get state for session '{session_id}': {exc}"
|
|
29
|
+
) from exc
|
|
30
|
+
|
|
31
|
+
def get_embedding_by_session_id(self, session_id: str) -> list[float] | None:
|
|
32
|
+
"""Fetch the embedding vector for *session_id*, or *None* if absent."""
|
|
33
|
+
query, params = kg_queries.get_embedding_by_session_id(session_id)
|
|
34
|
+
try:
|
|
35
|
+
rows = self.db.execute(query, params)
|
|
36
|
+
if rows and rows[0].get("embedding"):
|
|
37
|
+
return rows[0]["embedding"]
|
|
38
|
+
return None
|
|
39
|
+
except Exception as exc:
|
|
40
|
+
raise DatabaseError(
|
|
41
|
+
f"Failed to get embedding for session '{session_id}': {exc}"
|
|
42
|
+
) from exc
|
|
43
|
+
|
|
44
|
+
def get_neighbors(
|
|
45
|
+
self,
|
|
46
|
+
*,
|
|
47
|
+
embedding: list[float],
|
|
48
|
+
max_distance: float = 1.0,
|
|
49
|
+
max_neighbors: int = 10,
|
|
50
|
+
metric_names: list[str] | None = None,
|
|
51
|
+
distance_metric: str = "cosine",
|
|
52
|
+
) -> list[dict]:
|
|
53
|
+
"""Return nearby sessions ranked by embedding distance."""
|
|
54
|
+
query, params = kg_queries.neighbors_query(
|
|
55
|
+
embedding=embedding,
|
|
56
|
+
max_distance=max_distance,
|
|
57
|
+
max_neighbors=max_neighbors,
|
|
58
|
+
metric_names=metric_names,
|
|
59
|
+
distance_metric=distance_metric,
|
|
60
|
+
)
|
|
61
|
+
try:
|
|
62
|
+
return self.db.execute(query, params)
|
|
63
|
+
except Exception as exc:
|
|
64
|
+
raise DatabaseError(f"Failed to get neighbors: {exc}") from exc
|
scope/client/_labels.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Labels-domain methods for :class:`LocalClient`.
|
|
4
|
+
|
|
5
|
+
These methods manage trace labels stored in the ``trace_labels``
|
|
6
|
+
ClickHouse table (ReplacingMergeTree).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
|
|
13
|
+
from scope.connectors.base import Connector
|
|
14
|
+
from scope.core.exceptions import DatabaseError
|
|
15
|
+
from scope.models.otel_traces import (
|
|
16
|
+
LabelDeleteResponse,
|
|
17
|
+
LabelItem,
|
|
18
|
+
LabelPutRequest,
|
|
19
|
+
LabelResponse,
|
|
20
|
+
)
|
|
21
|
+
from scope.query_builders import labels as label_queries
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class LabelsClient:
|
|
27
|
+
"""Labels operations mixed into :class:`LocalClient`."""
|
|
28
|
+
|
|
29
|
+
db: Connector
|
|
30
|
+
|
|
31
|
+
# ── GET ───────────────────────────────────────────────────────────────
|
|
32
|
+
|
|
33
|
+
def get_label(self, session_id: str) -> LabelResponse:
|
|
34
|
+
"""Return the label for *session_id*, or ``None`` if not set."""
|
|
35
|
+
query = label_queries.get_label_query(session_id)
|
|
36
|
+
try:
|
|
37
|
+
rows = self.db.execute(query)
|
|
38
|
+
except Exception as exc:
|
|
39
|
+
raise DatabaseError(
|
|
40
|
+
f"Failed to get label for session '{session_id}': {exc}"
|
|
41
|
+
) from exc
|
|
42
|
+
|
|
43
|
+
if not rows:
|
|
44
|
+
return LabelResponse(session_id=session_id, label=None)
|
|
45
|
+
|
|
46
|
+
r = rows[0]
|
|
47
|
+
return LabelResponse(
|
|
48
|
+
session_id=session_id,
|
|
49
|
+
label=LabelItem(
|
|
50
|
+
session_id=r[0],
|
|
51
|
+
label=bool(r[1]),
|
|
52
|
+
labeler=r[2],
|
|
53
|
+
reason=r[3],
|
|
54
|
+
updated_at=str(r[4]) if r[4] else None,
|
|
55
|
+
),
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
# ── PUT (upsert) ─────────────────────────────────────────────────────
|
|
59
|
+
|
|
60
|
+
def put_label(
|
|
61
|
+
self,
|
|
62
|
+
session_id: str,
|
|
63
|
+
body: LabelPutRequest,
|
|
64
|
+
) -> LabelResponse:
|
|
65
|
+
"""Create or update the label for *session_id*."""
|
|
66
|
+
cmd = label_queries.upsert_label_query(
|
|
67
|
+
session_id=session_id,
|
|
68
|
+
label=body.label,
|
|
69
|
+
labeler=body.labeler,
|
|
70
|
+
reason=body.reason,
|
|
71
|
+
)
|
|
72
|
+
self.db.execute_command(cmd)
|
|
73
|
+
return self.get_label(session_id)
|
|
74
|
+
|
|
75
|
+
# ── DELETE ────────────────────────────────────────────────────────────
|
|
76
|
+
|
|
77
|
+
def delete_label(self, session_id: str) -> LabelDeleteResponse:
|
|
78
|
+
"""Delete the label for *session_id*."""
|
|
79
|
+
cmd = label_queries.delete_label_query(session_id)
|
|
80
|
+
try:
|
|
81
|
+
self.db.execute_command(cmd)
|
|
82
|
+
return LabelDeleteResponse(session_id=session_id, deleted=True)
|
|
83
|
+
except Exception as exc:
|
|
84
|
+
raise DatabaseError(
|
|
85
|
+
f"Failed to delete label for session '{session_id}': {exc}"
|
|
86
|
+
) from exc
|