-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathobservability.py
More file actions
408 lines (322 loc) · 12 KB
/
Copy pathobservability.py
File metadata and controls
408 lines (322 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
"""
SENTINEL Observability Module — Production-Grade Telemetry
Provides OpenTelemetry integration for:
- Distributed tracing of engine calls
- Prometheus metrics export
- Performance profiling
- Error tracking
Usage:
from observability import tracer, metrics
with tracer.start_as_current_span("analyze_prompt") as span:
result = engine.analyze(prompt)
span.set_attribute("risk_score", result.risk_score)
metrics.engine_latency.record(latency_ms, {"engine": "injection"})
Author: SENTINEL Team
Date: 2025-12-13
"""
import logging
import time
import functools
from typing import Optional, Dict, Any, Callable
from contextlib import contextmanager
# OpenTelemetry imports
try:
from opentelemetry import trace, metrics as otel_metrics
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource
OTEL_AVAILABLE = True
except ImportError:
OTEL_AVAILABLE = False
trace = None
otel_metrics = None
logger = logging.getLogger("SentinelObservability")
# ============================================================================
# Resource Configuration
# ============================================================================
def create_resource() -> "Resource":
"""Create OpenTelemetry resource with SENTINEL metadata."""
if not OTEL_AVAILABLE:
return None
return Resource.create({
"service.name": "sentinel-brain",
"service.version": "2.0.0",
"deployment.environment": "production",
"sentinel.engines": "56",
})
# ============================================================================
# Tracer Setup
# ============================================================================
class SentinelTracer:
"""
Distributed tracing for SENTINEL engine calls.
Provides span context for:
- Individual engine analysis
- Meta-Judge orchestration
- Full request lifecycle
"""
def __init__(self, service_name: str = "sentinel-brain"):
self.service_name = service_name
self._tracer = None
self._provider = None
if OTEL_AVAILABLE:
self._setup_tracer()
else:
logger.warning("OpenTelemetry not available, tracing disabled")
def _setup_tracer(self):
"""Initialize OpenTelemetry tracer."""
resource = create_resource()
self._provider = TracerProvider(resource=resource)
# Console exporter for development
console_exporter = ConsoleSpanExporter()
self._provider.add_span_processor(
BatchSpanProcessor(console_exporter)
)
trace.set_tracer_provider(self._provider)
self._tracer = trace.get_tracer(__name__)
logger.info("OpenTelemetry tracer initialized")
@contextmanager
def span(self, name: str, attributes: Optional[Dict[str, Any]] = None):
"""
Create a trace span.
Usage:
with tracer.span("analyze", {"engine": "injection"}) as span:
result = engine.analyze(text)
span.set_attribute("risk", result.risk_score)
"""
if not self._tracer:
# No-op context manager when tracing disabled
yield None
return
with self._tracer.start_as_current_span(name) as span:
if attributes:
for key, value in attributes.items():
span.set_attribute(key, value)
yield span
def trace_engine(self, engine_name: str):
"""
Decorator to trace engine methods.
Usage:
@tracer.trace_engine("injection")
def analyze(self, text):
...
"""
def decorator(func: Callable):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with self.span(f"engine.{engine_name}", {"engine.name": engine_name}):
start = time.perf_counter()
try:
result = func(*args, **kwargs)
return result
finally:
elapsed = (time.perf_counter() - start) * 1000
# Record latency even if we can't trace
logger.debug(f"{engine_name}: {elapsed:.2f}ms")
return wrapper
return decorator
# ============================================================================
# Metrics Setup
# ============================================================================
class SentinelMetrics:
"""
Prometheus-compatible metrics for SENTINEL.
Metrics:
- sentinel_engine_latency_ms: Histogram of engine latencies
- sentinel_engine_calls_total: Counter of engine invocations
- sentinel_risk_score: Gauge of current risk levels
- sentinel_threats_detected_total: Counter of detected threats
"""
def __init__(self):
self._meter = None
self._engine_latency = None
self._engine_calls = None
self._risk_score = None
self._threats_detected = None
if OTEL_AVAILABLE:
self._setup_metrics()
else:
logger.warning("OpenTelemetry not available, metrics disabled")
def _setup_metrics(self):
"""Initialize OpenTelemetry metrics."""
resource = create_resource()
# Create meter provider
provider = MeterProvider(resource=resource)
otel_metrics.set_meter_provider(provider)
self._meter = otel_metrics.get_meter(__name__)
# Engine latency histogram
self._engine_latency = self._meter.create_histogram(
name="sentinel_engine_latency_ms",
description="Engine analysis latency in milliseconds",
unit="ms",
)
# Engine call counter
self._engine_calls = self._meter.create_counter(
name="sentinel_engine_calls_total",
description="Total number of engine calls",
unit="1",
)
# Risk score gauge (using observable gauge)
self._current_risk = 0.0
self._risk_score = self._meter.create_observable_gauge(
name="sentinel_risk_score",
callbacks=[lambda options: [(self._current_risk, {})]],
description="Current risk score",
unit="1",
)
# Threats counter
self._threats_detected = self._meter.create_counter(
name="sentinel_threats_detected_total",
description="Total threats detected",
unit="1",
)
logger.info("OpenTelemetry metrics initialized")
def record_latency(self, engine: str, latency_ms: float):
"""Record engine latency."""
if self._engine_latency:
self._engine_latency.record(latency_ms, {"engine": engine})
def record_call(self, engine: str, verdict: str = "allow"):
"""Record engine call."""
if self._engine_calls:
self._engine_calls.add(1, {"engine": engine, "verdict": verdict})
def record_threat(self, threat_type: str, severity: str = "medium"):
"""Record detected threat."""
if self._threats_detected:
self._threats_detected.add(1, {
"threat_type": threat_type,
"severity": severity,
})
def set_risk_score(self, score: float):
"""Update current risk score."""
self._current_risk = score
# ============================================================================
# Performance Profiler
# ============================================================================
class PerformanceProfiler:
"""
Lightweight profiler for engine performance analysis.
Collects:
- Call counts
- Total time
- Min/Max/Avg latency
"""
def __init__(self):
self._stats: Dict[str, Dict[str, Any]] = {}
def profile(self, name: str):
"""
Decorator to profile function execution.
Usage:
@profiler.profile("injection_analyze")
def analyze(self, text):
...
"""
def decorator(func: Callable):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
elapsed = (time.perf_counter() - start) * 1000
self._record(name, elapsed)
return wrapper
return decorator
def _record(self, name: str, latency_ms: float):
"""Record profiling data."""
if name not in self._stats:
self._stats[name] = {
"count": 0,
"total_ms": 0.0,
"min_ms": float('inf'),
"max_ms": 0.0,
}
stats = self._stats[name]
stats["count"] += 1
stats["total_ms"] += latency_ms
stats["min_ms"] = min(stats["min_ms"], latency_ms)
stats["max_ms"] = max(stats["max_ms"], latency_ms)
def get_stats(self, name: Optional[str] = None) -> Dict[str, Any]:
"""Get profiling statistics."""
if name:
stats = self._stats.get(name, {})
if stats and stats["count"] > 0:
stats["avg_ms"] = stats["total_ms"] / stats["count"]
return stats
# Return all stats with computed averages
result = {}
for n, s in self._stats.items():
result[n] = s.copy()
if s["count"] > 0:
result[n]["avg_ms"] = s["total_ms"] / s["count"]
return result
def reset(self):
"""Reset all statistics."""
self._stats.clear()
# ============================================================================
# Global Instances
# ============================================================================
# Singleton instances
_tracer: Optional[SentinelTracer] = None
_metrics: Optional[SentinelMetrics] = None
_profiler: Optional[PerformanceProfiler] = None
def get_tracer() -> SentinelTracer:
"""Get global tracer instance."""
global _tracer
if _tracer is None:
_tracer = SentinelTracer()
return _tracer
def get_metrics() -> SentinelMetrics:
"""Get global metrics instance."""
global _metrics
if _metrics is None:
_metrics = SentinelMetrics()
return _metrics
def get_profiler() -> PerformanceProfiler:
"""Get global profiler instance."""
global _profiler
if _profiler is None:
_profiler = PerformanceProfiler()
return _profiler
# Convenience exports
tracer = get_tracer()
metrics = get_metrics()
profiler = get_profiler()
# ============================================================================
# Instrumentation Helpers
# ============================================================================
def instrument_engine(engine_class):
"""
Class decorator to instrument all public methods.
Usage:
@instrument_engine
class InjectionEngine:
...
"""
for name in dir(engine_class):
if not name.startswith('_'):
method = getattr(engine_class, name)
if callable(method):
instrumented = tracer.trace_engine(
engine_class.__name__)(method)
setattr(engine_class, name, instrumented)
return engine_class
if __name__ == "__main__":
# Quick test
print(f"OpenTelemetry available: {OTEL_AVAILABLE}")
# Test tracing
with tracer.span("test_span", {"test": True}) as span:
print("Inside traced span")
# Test metrics
metrics.record_latency("injection", 15.5)
metrics.record_call("injection", "block")
metrics.record_threat("prompt_injection", "high")
# Test profiler
@profiler.profile("test_func")
def test_func():
time.sleep(0.01)
return "done"
for _ in range(5):
test_func()
print(f"Profiler stats: {profiler.get_stats()}")