Mist-ic commited on
Commit
a46811c
Β·
1 Parent(s): 64d38cb

Add propagation engine, log templates, and updated models

Browse files

- server/propagation.py: queueing theory cascade engine with circuit breakers,
Little's Law utilization, retry amplification, and multi-hop propagation
- server/logs.py: framework-specific log templates for all 8 failure types
(Spring Boot, Node.js, FastAPI, K8s, HikariCP, Redis, gRPC patterns)
- models.py: cleaned up Pydantic models for API contract
- pyproject.toml: updated dependencies
- uv.lock: locked dependency versions
- README.md: initial project readme

Files changed (6) hide show
  1. README.md +7 -0
  2. models.py +1 -17
  3. pyproject.toml +2 -2
  4. server/logs.py +268 -0
  5. server/propagation.py +323 -0
  6. uv.lock +0 -0
README.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # SevZero β€” SRE Incident Response Environment
2
+
3
+ An autonomous on-call SRE managing a microservice cluster undergoing cascading failures.
4
+
5
+ Built with [OpenEnv](https://github.com/meta-pytorch/OpenEnv) for the OpenEnv AI Hackathon 2026.
6
+
7
+ > Full documentation coming soon.
models.py CHANGED
@@ -10,7 +10,7 @@ from __future__ import annotations
10
 
11
  from typing import Any, Dict, List, Optional, Union
12
 
13
- from pydantic import Field
14
 
15
  from openenv.core.env_server import Action, Observation, State
16
 
@@ -20,22 +20,6 @@ from openenv.core.env_server import Action, Observation, State
20
  # ---------------------------------------------------------------------------
21
 
22
 
23
- class CircuitBreakerInfo(dict):
24
- """Maps dependency name -> breaker state ('CLOSED' | 'OPEN' | 'HALF_OPEN')."""
25
-
26
-
27
- class ServiceInfo(object):
28
- """Per-service observable state β€” declared as plain dict in observation for
29
- JSON-serialisability; structured via ServiceInfoModel for validation."""
30
-
31
-
32
- class ServiceInfoModel:
33
- """Pydantic model for a single service's metrics (used internally)."""
34
-
35
-
36
- from pydantic import BaseModel
37
-
38
-
39
  class ServiceInfoModel(BaseModel):
40
  """
41
  All observable per-service metrics, ordered by SRE triage priority:
 
10
 
11
  from typing import Any, Dict, List, Optional, Union
12
 
13
+ from pydantic import BaseModel, Field
14
 
15
  from openenv.core.env_server import Action, Observation, State
16
 
 
20
  # ---------------------------------------------------------------------------
21
 
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  class ServiceInfoModel(BaseModel):
24
  """
25
  All observable per-service metrics, ordered by SRE triage priority:
pyproject.toml CHANGED
@@ -25,8 +25,8 @@ build-backend = "hatchling.build"
25
  [tool.hatch.build.targets.wheel]
26
  packages = ["server"]
27
 
28
- [tool.uv]
29
- dev-dependencies = [
30
  "pytest>=7.0.0",
31
  "httpx>=0.24.0",
32
  ]
 
25
  [tool.hatch.build.targets.wheel]
26
  packages = ["server"]
27
 
28
+ [dependency-groups]
29
+ dev = [
30
  "pytest>=7.0.0",
31
  "httpx>=0.24.0",
32
  ]
server/logs.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ server/logs.py β€” Framework-specific log message templates per failure type.
3
+
4
+ Each failure type has 5-10 realistic log templates drawn from real frameworks:
5
+ Spring Boot, Node.js, FastAPI, Kubernetes, HikariCP, Redis, gRPC.
6
+
7
+ Templates use placeholders {service}, {dependency}, {value} etc. that are
8
+ filled at runtime with actual service/metric values.
9
+
10
+ Sources: Docs/DataResearch.md Answer 4 + Answer 11.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import random
16
+ from typing import Dict, List, Optional
17
+
18
+ from server.failures import FailureType
19
+
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Log templates per failure type
23
+ # ---------------------------------------------------------------------------
24
+
25
+ _TEMPLATES: Dict[FailureType, List[str]] = {
26
+ FailureType.CRASH: [
27
+ "ERROR {service} OOMKilled: container exceeded memory limit ({memory_limit}Mi). Exit code 137. Pod restarting (backoff: {backoff}s)",
28
+ "FATAL {service} Process exited with signal 9 (SIGKILL). Out of memory. Restart count: {restart_count}",
29
+ "ERROR {service} CrashLoopBackOff: back-off restarting failed container. Last exit: OOMKilled",
30
+ "CRIT {service} JVM heap exhausted: java.lang.OutOfMemoryError: Java heap space. Heap: {heap_used}Mi/{heap_max}Mi",
31
+ "ERROR {service} Panic: runtime error: out of memory. goroutine stack overflow at allocateHeap()",
32
+ "FATAL {service} Node process crashed: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory",
33
+ ],
34
+
35
+ FailureType.BAD_DEPLOY: [
36
+ "ERROR {service} {version} NullPointerException: Cannot invoke \"{method}\" on null reference at {class}.process({class}.java:{line})",
37
+ "ERROR {service} {version} TypeError: Cannot read properties of undefined (reading '{property}'). Stack: at {handler} ({file}:{line})",
38
+ "ERROR {service} {version} Traceback (most recent call last):\\n File \"{file}\", line {line}\\n {code_line}\\nAttributeError: '{class}' object has no attribute '{attribute}'",
39
+ "ERROR {service} {version} panic: interface conversion: interface {} is nil, not *{type}. goroutine {goroutine_id} [running]",
40
+ "ERROR {service} {version} Unhandled rejection: ValidationError: \"{field}\" is required. Schema version mismatch between {version} and data format.",
41
+ "WARN {service} {version} Health check failing: /health returned 500. Error rate climbing: {error_rate}%",
42
+ ],
43
+
44
+ FailureType.CONFIG_STARTUP: [
45
+ "FATAL {service} password authentication failed for user \"{db_user}\" on {dependency}:{port}. Connection refused.",
46
+ "ERROR {service} Could not resolve placeholder '{config_key}' in value \"${{{config_key}}}\"",
47
+ "FATAL {service} Configuration error: required key [{config_key}] not found in application.yml",
48
+ "ERROR {service} Failed to bind to port {port}: EADDRINUSE. Another process is using this port.",
49
+ "FATAL {service} SSL/TLS certificate error: certificate has expired. CN={dependency}. Valid until: {expiry}",
50
+ "ERROR {service} Cannot connect to {dependency}: Connection refused. Retried {retry_count} times, giving up.",
51
+ ],
52
+
53
+ FailureType.CONFIG_RUNTIME: [
54
+ "ERROR {service} Request to https://{config_value}/charge failed: ECONNREFUSED. Feature \"{feature_flag}\" enabled but endpoint misconfigured.",
55
+ "WARN {service} Fallback triggered for {dependency}: timeout after {timeout_ms}ms. Config key '{config_key}' may be incorrect.",
56
+ "ERROR {service} Invalid JSON response from {dependency}: Unexpected token '<' at position 0. Endpoint returning HTML instead of API response.",
57
+ "ERROR {service} Feature flag '{feature_flag}' enabled new code path but dependency '{dependency}' not configured. Returning 500 for {error_rate}% of /api/v2 requests.",
58
+ "WARN {service} Rate limit config mismatch: max_rps={config_value} but actual traffic is {throughput}rps. Dropping {error_rate}% of requests.",
59
+ ],
60
+
61
+ FailureType.CASCADING_LATENCY: [
62
+ "WARN {service} Downstream {dependency} timeout after {timeout_ms}ms. Circuit breaker OPEN for {cooldown}s. {queued} requests queued.",
63
+ "WARN {service} Thread pool exhaustion: {active}/{pool_size} threads active. Queue depth: {queue_depth}. Avg wait: {wait_ms}ms.",
64
+ "ERROR {service} gRPC deadline exceeded: remaining_ms={remaining_ms}. Upstream deadline propagated through {hop_count} hops.",
65
+ "WARN {service} Connection pool to {dependency}: active={active}/{pool_size}, pending={pending}. Avg checkout time: {checkout_ms}ms (threshold: {threshold_ms}ms).",
66
+ "ERROR {service} Request timeout: {dependency} did not respond within {timeout_ms}ms. Retry {retry_count}/{retry_max}.",
67
+ "WARN {service} p99 latency spike: {p99_ms}ms (baseline: {baseline_ms}ms). {dependency} response time degrading.",
68
+ ],
69
+
70
+ FailureType.RESOURCE_LEAK: [
71
+ "WARN {service} Memory usage {memory_pct}% ({memory_used}Mi/{memory_limit}Mi). GC overhead {gc_pct}%. Last full GC: {gc_pause}s pause. Allocation failure imminent.",
72
+ "WARN {service} File descriptor leak detected: open_fds={open_fds} (limit: {fd_limit}). Growing at {fd_rate}/min.",
73
+ "WARN {service} Goroutine leak: count={goroutine_count} (baseline: {baseline}). Growing linearly. Stack trace: {leak_source}",
74
+ "ERROR {service} GC overhead limit exceeded: spending {gc_pct}% of time in GC. Heap: {memory_used}Mi/{memory_limit}Mi.",
75
+ "WARN {service} Connection leak to {dependency}: {active} connections checked out but not returned. Pool: {active}/{pool_size}.",
76
+ ],
77
+
78
+ FailureType.DB_DEGRADATION: [
79
+ "ERROR {service} HikariPool-1 connection not available, request timed out after {timeout_ms}ms. Active: {active}/{pool_size}, Waiting: {waiting}.",
80
+ "WARN {service} Slow query detected: SELECT * FROM {table} WHERE ... took {query_ms}ms (threshold: {threshold_ms}ms). Lock contention on {table}.",
81
+ "ERROR {service} Connection pool exhausted for {dependency}. Active: {active}/{pool_size}. Oldest connection age: {age_ms}ms.",
82
+ "WARN {service} Database replication lag: {lag_ms}ms on {dependency}. Read-after-write consistency violated.",
83
+ "ERROR {service} Deadlock detected on {dependency}: Transaction {tx_id} waiting for lock held by {blocking_tx}. Auto-rolling back.",
84
+ "WARN {service} {dependency} CPU={db_cpu}% but app CPU={app_cpu}% (paradoxically low). Threads blocked on I/O wait.",
85
+ ],
86
+
87
+ FailureType.CACHE_FAILURE: [
88
+ "WARN {service} CLUSTERDOWN: {dependency} cluster is down. Hit rate dropped from {baseline_hit_rate}% to 0%. Backend QPS spiked {spike_factor}x.",
89
+ "ERROR {service} Redis connection lost: {dependency} ECONNRESET. Failover in progress. Cache miss rate: 100%.",
90
+ "WARN {service} Cache stampede detected: {concurrent_misses} concurrent cache misses for key pattern '{key_pattern}'. Backend overloaded.",
91
+ "ERROR {service} {dependency} READONLY: Redis replica cannot accept writes. Cluster rebalancing.",
92
+ "WARN {service} Cache eviction storm: {evicted} keys evicted in last {interval}s. Memory pressure on {dependency}.",
93
+ ],
94
+
95
+ FailureType.NETWORK_ERROR: [
96
+ "ERROR {service} DNS resolution failed for {dependency}.{region}.internal: NXDOMAIN. 0/{endpoint_count} endpoints reachable.",
97
+ "ERROR {service} TCP connection to {dependency}:{port} failed: ETIMEDOUT after {timeout_ms}ms. Network partition suspected.",
98
+ "ERROR {service} TLS handshake failed with {dependency}: certificate verify failed (depth 0). CN mismatch or expired cert.",
99
+ "CRIT {service} All endpoints for {dependency} unreachable in region {region}. Last successful connection: {last_success} ago.",
100
+ "ERROR {service} gRPC transport error: UNAVAILABLE: {dependency} DNS resolution failed for \"{dependency}.svc.cluster.local\"",
101
+ ],
102
+ }
103
+
104
+
105
+ # ---------------------------------------------------------------------------
106
+ # Placeholder value generators
107
+ # ---------------------------------------------------------------------------
108
+
109
+
110
+ def _random_class_name(rng: random.Random) -> str:
111
+ prefixes = ["Payment", "Order", "Auth", "Inventory", "Cart", "Billing", "Shipping"]
112
+ suffixes = ["Service", "Handler", "Controller", "Processor", "Manager"]
113
+ return rng.choice(prefixes) + rng.choice(suffixes)
114
+
115
+
116
+ def _random_method(rng: random.Random) -> str:
117
+ return rng.choice(["process", "handle", "execute", "validate", "transform", "serialize", "getId", "getStatus"])
118
+
119
+
120
+ def _random_property(rng: random.Random) -> str:
121
+ return rng.choice(["id", "status", "amount", "userId", "orderId", "timestamp", "payload", "response"])
122
+
123
+
124
+ def _fill_placeholders(
125
+ template: str,
126
+ service_id: str,
127
+ rng: random.Random,
128
+ dependency: str = "unknown",
129
+ error_rate: float = 0.0,
130
+ memory_pct: float = 50.0,
131
+ p99_ms: float = 100.0,
132
+ pool_pct: float = 10.0,
133
+ version: str = "v1.0.0",
134
+ config_key: str = "db_host",
135
+ config_value: str = "wrong-endpoint.internal",
136
+ region: str = "us-east-1",
137
+ throughput: float = 100.0,
138
+ ) -> str:
139
+ """Fill placeholders in a log template with realistic values."""
140
+ replacements = {
141
+ "service": service_id,
142
+ "dependency": dependency,
143
+ "version": version,
144
+ "error_rate": f"{error_rate * 100:.0f}",
145
+ "memory_pct": f"{memory_pct:.0f}",
146
+ "memory_used": f"{int(memory_pct * 20.48):.0f}",
147
+ "memory_limit": "2048",
148
+ "heap_used": f"{int(memory_pct * 10.24):.0f}",
149
+ "heap_max": "1024",
150
+ "p99_ms": f"{p99_ms:.0f}",
151
+ "baseline_ms": f"{rng.randint(20, 80)}",
152
+ "timeout_ms": f"{rng.choice([3000, 5000, 10000, 30000])}",
153
+ "cooldown": f"{rng.randint(15, 60)}",
154
+ "queued": f"{rng.randint(50, 500)}",
155
+ "queue_depth": f"{rng.randint(100, 1000)}",
156
+ "wait_ms": f"{rng.randint(500, 5000)}",
157
+ "active": f"{rng.randint(15, 25)}",
158
+ "pool_size": "20",
159
+ "pending": f"{rng.randint(50, 200)}",
160
+ "checkout_ms": f"{rng.randint(1000, 10000)}",
161
+ "threshold_ms": "1000",
162
+ "retry_count": f"{rng.randint(1, 5)}",
163
+ "retry_max": "3",
164
+ "backoff": f"{rng.choice([10, 15, 30, 60])}",
165
+ "restart_count": f"{rng.randint(3, 15)}",
166
+ "port": f"{rng.choice([5432, 6379, 8080, 9090, 3000])}",
167
+ "db_user": rng.choice(["app_user", "service_account", "auth_user", "readonly"]),
168
+ "config_key": config_key,
169
+ "config_value": config_value,
170
+ "feature_flag": rng.choice(["new_checkout_flow", "v2_api", "experimental_search", "dynamic_pricing"]),
171
+ "region": region,
172
+ "endpoint_count": f"{rng.randint(2, 5)}",
173
+ "class": _random_class_name(rng),
174
+ "method": _random_method(rng),
175
+ "property": _random_property(rng),
176
+ "attribute": _random_property(rng),
177
+ "type": _random_class_name(rng),
178
+ "handler": rng.choice(["processRequest", "handleEvent", "onMessage"]),
179
+ "file": rng.choice(["app.py", "handler.js", "service.go", "controller.java"]),
180
+ "line": f"{rng.randint(42, 350)}",
181
+ "code_line": rng.choice(["result = response.data['items']", "return self.client.process(payload)"]),
182
+ "field": rng.choice(["amount", "currency", "userId", "orderId"]),
183
+ "goroutine_id": f"{rng.randint(100, 999)}",
184
+ "table": rng.choice(["orders", "payments", "users", "inventory", "sessions"]),
185
+ "query_ms": f"{rng.randint(5000, 30000)}",
186
+ "tx_id": f"tx-{rng.randint(1000, 9999)}",
187
+ "blocking_tx": f"tx-{rng.randint(1000, 9999)}",
188
+ "lag_ms": f"{rng.randint(1000, 10000)}",
189
+ "age_ms": f"{rng.randint(30000, 120000)}",
190
+ "db_cpu": f"{rng.randint(5, 25)}",
191
+ "app_cpu": f"{rng.randint(2, 15)}",
192
+ "waiting": f"{rng.randint(50, 300)}",
193
+ "baseline_hit_rate": f"{rng.uniform(95.0, 99.5):.1f}",
194
+ "spike_factor": f"{rng.randint(10, 50)}",
195
+ "concurrent_misses": f"{rng.randint(100, 1000)}",
196
+ "key_pattern": rng.choice(["user:*", "product:*:price", "session:*", "inventory:*"]),
197
+ "evicted": f"{rng.randint(10000, 100000)}",
198
+ "interval": f"{rng.randint(10, 60)}",
199
+ "gc_pct": f"{rng.randint(30, 70)}",
200
+ "gc_pause": f"{rng.uniform(0.5, 3.0):.1f}",
201
+ "open_fds": f"{rng.randint(800, 1024)}",
202
+ "fd_limit": "1024",
203
+ "fd_rate": f"{rng.randint(5, 20)}",
204
+ "goroutine_count": f"{rng.randint(5000, 50000)}",
205
+ "baseline": f"{rng.randint(50, 200)}",
206
+ "leak_source": rng.choice(["http.ListenAndServe", "grpc.NewServer", "sql.Open"]),
207
+ "hop_count": f"{rng.randint(2, 5)}",
208
+ "remaining_ms": f"{rng.randint(-500, 10)}",
209
+ "last_success": rng.choice(["45s", "2m30s", "5m12s"]),
210
+ "throughput": f"{throughput:.0f}",
211
+ }
212
+
213
+ result = template
214
+ for key, value in replacements.items():
215
+ result = result.replace("{" + key + "}", str(value))
216
+ return result
217
+
218
+
219
+ # ---------------------------------------------------------------------------
220
+ # Public API
221
+ # ---------------------------------------------------------------------------
222
+
223
+
224
+ def generate_log_message(
225
+ failure_type: FailureType,
226
+ service_id: str,
227
+ rng: random.Random,
228
+ dependency: str = "unknown",
229
+ error_rate: float = 0.0,
230
+ memory_pct: float = 50.0,
231
+ p99_ms: float = 100.0,
232
+ pool_pct: float = 10.0,
233
+ version: str = "v1.0.0",
234
+ config_key: str = "db_host",
235
+ config_value: str = "wrong-endpoint.internal",
236
+ region: str = "us-east-1",
237
+ throughput: float = 100.0,
238
+ ) -> str:
239
+ """Generate a realistic log message for the given failure type and service."""
240
+ templates = _TEMPLATES.get(failure_type, [])
241
+ if not templates:
242
+ return f"ERROR {service_id} Unknown failure condition detected."
243
+
244
+ template = rng.choice(templates)
245
+ return _fill_placeholders(
246
+ template, service_id, rng,
247
+ dependency=dependency,
248
+ error_rate=error_rate,
249
+ memory_pct=memory_pct,
250
+ p99_ms=p99_ms,
251
+ pool_pct=pool_pct,
252
+ version=version,
253
+ config_key=config_key,
254
+ config_value=config_value,
255
+ region=region,
256
+ throughput=throughput,
257
+ )
258
+
259
+
260
+ def generate_healthy_log(service_id: str, rng: random.Random) -> str:
261
+ """Generate a log message for a healthy service being inspected."""
262
+ templates = [
263
+ f"INFO {service_id} Health check passed. Status: UP. Response time: {rng.randint(2, 15)}ms.",
264
+ f"INFO {service_id} All endpoints healthy. Error rate: 0.0%. p99: {rng.randint(10, 50)}ms.",
265
+ f"DEBUG {service_id} Metrics nominal. CPU: {rng.randint(5, 25)}%, Memory: {rng.randint(20, 45)}%, Connections: {rng.randint(2, 10)}/20.",
266
+ f"INFO {service_id} No anomalies detected in last 60s. request_count={rng.randint(500, 2000)}, error_count=0.",
267
+ ]
268
+ return rng.choice(templates)
server/propagation.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ server/propagation.py β€” Queueing-theory cascade engine.
3
+
4
+ Computes how failures propagate through the service dependency graph using:
5
+ - Little's Law: L = Ξ» Γ— S for thread pool saturation (ρ = L/T)
6
+ - Retry amplification: E[attempts] = (1 - p^(R+1)) / (1 - p)
7
+ - Per-hop dampening (~0.7 with circuit breakers) vs amplification (~1.2-1.8Γ—)
8
+ - 1-2 tick propagation delay (not instant)
9
+ - Circuit breaker state machine: CLOSED β†’ OPEN β†’ HALF_OPEN β†’ CLOSED
10
+
11
+ Sources: Google SRE Book, Netflix Hystrix, Docs/DataResearch.md Answer 3.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import random
17
+ from dataclasses import dataclass, field
18
+ from enum import Enum
19
+ from typing import Dict, List, Optional, Tuple
20
+
21
+
22
+ # ---------------------------------------------------------------------------
23
+ # Circuit breaker state machine
24
+ # ---------------------------------------------------------------------------
25
+
26
+
27
+ class BreakerState(str, Enum):
28
+ CLOSED = "CLOSED"
29
+ OPEN = "OPEN"
30
+ HALF_OPEN = "HALF_OPEN"
31
+
32
+
33
+ @dataclass
34
+ class CircuitBreaker:
35
+ """Per-edge circuit breaker with rolling error window."""
36
+
37
+ state: BreakerState = BreakerState.CLOSED
38
+
39
+ # Config (tunable by agent via tune_config)
40
+ error_threshold: float = 0.5 # Error rate to trip OPEN
41
+ cooldown_ticks: int = 5 # Ticks to stay OPEN before half-open
42
+ half_open_success_threshold: int = 3 # Successes needed to close
43
+
44
+ # Runtime state
45
+ ticks_in_current_state: int = 0
46
+ error_window: List[float] = field(default_factory=list)
47
+ window_size: int = 5
48
+ half_open_successes: int = 0
49
+
50
+ def record_error_rate(self, error_rate: float) -> None:
51
+ """Record an error rate observation and potentially transition state."""
52
+ self.error_window.append(error_rate)
53
+ if len(self.error_window) > self.window_size:
54
+ self.error_window = self.error_window[-self.window_size:]
55
+ self.ticks_in_current_state += 1
56
+
57
+ def tick(self, current_error_rate: float, rng: random.Random) -> BreakerState:
58
+ """Advance the circuit breaker state machine by one tick."""
59
+ self.record_error_rate(current_error_rate)
60
+ avg_error = sum(self.error_window) / len(self.error_window) if self.error_window else 0.0
61
+
62
+ if self.state == BreakerState.CLOSED:
63
+ if avg_error >= self.error_threshold:
64
+ self.state = BreakerState.OPEN
65
+ self.ticks_in_current_state = 0
66
+ self.half_open_successes = 0
67
+
68
+ elif self.state == BreakerState.OPEN:
69
+ if self.ticks_in_current_state >= self.cooldown_ticks:
70
+ self.state = BreakerState.HALF_OPEN
71
+ self.ticks_in_current_state = 0
72
+ self.half_open_successes = 0
73
+
74
+ elif self.state == BreakerState.HALF_OPEN:
75
+ if current_error_rate < self.error_threshold * 0.5:
76
+ self.half_open_successes += 1
77
+ if self.half_open_successes >= self.half_open_success_threshold:
78
+ self.state = BreakerState.CLOSED
79
+ self.ticks_in_current_state = 0
80
+ self.error_window.clear()
81
+ else:
82
+ # Probe failed β€” go back to OPEN
83
+ self.state = BreakerState.OPEN
84
+ self.ticks_in_current_state = 0
85
+ self.half_open_successes = 0
86
+
87
+ return self.state
88
+
89
+ @property
90
+ def dampening_factor(self) -> float:
91
+ """How much this breaker dampens downstream error propagation."""
92
+ if self.state == BreakerState.OPEN:
93
+ return 0.05 # Nearly all errors blocked (fail-fast)
94
+ elif self.state == BreakerState.HALF_OPEN:
95
+ return 0.3 # Some probe traffic gets through
96
+ else:
97
+ return 1.0 # No dampening
98
+
99
+
100
+ # ---------------------------------------------------------------------------
101
+ # Queueing theory functions
102
+ # ---------------------------------------------------------------------------
103
+
104
+
105
+ def compute_utilisation(
106
+ arrival_rate: float,
107
+ service_time: float,
108
+ thread_pool_size: int,
109
+ ) -> float:
110
+ """
111
+ Little's Law: L = Ξ» Γ— S (average items in system).
112
+ Utilisation ρ = L / T where T is thread pool size.
113
+ When ρ β†’ 1.0, latency blows up nonlinearly (M/M/c queueing).
114
+ """
115
+ L = arrival_rate * service_time
116
+ T = max(1, thread_pool_size)
117
+ rho = L / T
118
+ return min(rho, 1.0) # Cap at 1.0 (saturated)
119
+
120
+
121
+ def compute_queueing_latency_multiplier(rho: float) -> float:
122
+ """
123
+ Approximate M/M/1 queueing delay multiplier.
124
+ As ρ β†’ 1, response time β†’ ∞.
125
+ Uses 1/(1-ρ) approximation with a cap to avoid infinity.
126
+ """
127
+ if rho >= 0.99:
128
+ return 50.0 # ~50x baseline latency (effectively down)
129
+ if rho >= 0.95:
130
+ return 20.0 # ~20x
131
+ if rho >= 0.90:
132
+ return 10.0 # ~10x
133
+ if rho >= 0.80:
134
+ return 5.0 # ~5x
135
+ if rho < 0.01:
136
+ return 1.0 # No queueing
137
+ return 1.0 / (1.0 - rho)
138
+
139
+
140
+ def compute_retry_amplification(
141
+ failure_probability: float,
142
+ max_retries: int,
143
+ ) -> float:
144
+ """
145
+ Expected number of attempts with retries.
146
+ E[attempts] = (1 - p^(R+1)) / (1 - p)
147
+ where p = failure probability, R = max retries.
148
+ """
149
+ p = max(0.0, min(1.0, failure_probability))
150
+ if p < 0.001:
151
+ return 1.0 # No failures, no retries
152
+ if p > 0.999:
153
+ return float(max_retries + 1) # Every attempt fails
154
+
155
+ R = max(0, max_retries)
156
+ return (1.0 - p ** (R + 1)) / (1.0 - p)
157
+
158
+
159
+ # ---------------------------------------------------------------------------
160
+ # Propagation engine
161
+ # ---------------------------------------------------------------------------
162
+
163
+
164
+ @dataclass
165
+ class ServiceRuntimeState:
166
+ """Mutable runtime state for one service during simulation."""
167
+
168
+ service_id: str
169
+
170
+ # --- Current metrics (updated each tick) ---
171
+ error_rate: float = 0.0
172
+ latency_p50_ms: float = 20.0
173
+ latency_p95_ms: float = 50.0
174
+ latency_p99_ms: float = 100.0
175
+ throughput_rps: float = 100.0
176
+ cpu_pct: float = 15.0
177
+ memory_pct: float = 30.0
178
+ connection_pool_usage_pct: float = 10.0
179
+
180
+ # --- Queueing model state ---
181
+ arrival_rate: float = 100.0 # Ξ» β€” requests/tick
182
+ service_time_local: float = 0.05 # S_local β€” seconds per request
183
+ thread_pool_size: int = 50 # T β€” max concurrent
184
+ utilisation: float = 0.0 # ρ = L/T
185
+
186
+ # --- Deployment ---
187
+ replicas: int = 2
188
+ version: str = "v1.0.0"
189
+ previous_version: Optional[str] = None
190
+ status: str = "healthy" # healthy | degraded | critical | down
191
+
192
+ # --- Config (tunable by agent) ---
193
+ timeout_ms: int = 5000
194
+ retry_max: int = 3
195
+ retry_backoff: bool = False
196
+ pool_size: int = 20
197
+
198
+ # --- Circuit breakers (per-dependency) ---
199
+ circuit_breakers: Dict[str, CircuitBreaker] = field(default_factory=dict)
200
+
201
+ # --- Failure state ---
202
+ has_active_failure: bool = False
203
+ failure_ticks: int = 0
204
+ propagation_error_rate: float = 0.0 # Error rate from upstream propagation
205
+
206
+ def compute_status(self) -> str:
207
+ """Derive health status from metrics."""
208
+ if self.error_rate >= 0.90:
209
+ return "down"
210
+ elif self.error_rate >= 0.30 or self.latency_p99_ms >= 5000:
211
+ return "critical"
212
+ elif self.error_rate >= 0.05 or self.latency_p99_ms >= 1000:
213
+ return "degraded"
214
+ else:
215
+ return "healthy"
216
+
217
+ def update_latency_percentiles(self, base_p99: float, multiplier: float, rng: random.Random) -> None:
218
+ """Update p50/p95/p99 from a base p99 and multiplier, with natural noise."""
219
+ noise = rng.uniform(0.95, 1.05)
220
+ self.latency_p99_ms = max(1.0, base_p99 * multiplier * noise)
221
+ self.latency_p95_ms = self.latency_p99_ms * rng.uniform(0.60, 0.85)
222
+ self.latency_p50_ms = self.latency_p95_ms * rng.uniform(0.30, 0.50)
223
+
224
+
225
+ def propagate_failures(
226
+ services: Dict[str, ServiceRuntimeState],
227
+ adjacency: Dict[str, List[str]],
228
+ reverse_adjacency: Dict[str, List[str]],
229
+ edge_activation: Dict[Tuple[str, str], float],
230
+ rng: random.Random,
231
+ propagation_delay: int = 1,
232
+ current_tick: int = 0,
233
+ ) -> None:
234
+ """
235
+ Propagate failure effects through the dependency graph for one tick.
236
+
237
+ Each service that has errors causes downstream impact on its callers:
238
+ 1. Caller's arrival rate may spike (retries, cache miss stampede)
239
+ 2. Caller's service time increases (waiting on slow downstream)
240
+ 3. Caller's thread pool fills up (blocked threads)
241
+ 4. Circuit breakers may trip (dampening propagation)
242
+
243
+ This modifies ServiceRuntimeState in-place.
244
+ """
245
+ # Process in reverse topological order: infra β†’ business β†’ edge
246
+ # So downstream failures propagate to upstream callers
247
+ for service_id, state in services.items():
248
+ if state.error_rate < 0.01:
249
+ continue # Healthy β€” no propagation from this service
250
+
251
+ # Who calls this service? (reverse edges = callers)
252
+ callers = reverse_adjacency.get(service_id, [])
253
+
254
+ for caller_id in callers:
255
+ caller = services.get(caller_id)
256
+ if caller is None:
257
+ continue
258
+
259
+ edge_key = (caller_id, service_id)
260
+ activation_prob = edge_activation.get(edge_key, 1.0)
261
+
262
+ # Is this edge active this tick?
263
+ if rng.random() > activation_prob:
264
+ continue # Edge not active β€” this dependency not called
265
+
266
+ # Get circuit breaker for this edge
267
+ if service_id not in caller.circuit_breakers:
268
+ caller.circuit_breakers[service_id] = CircuitBreaker()
269
+ breaker = caller.circuit_breakers[service_id]
270
+
271
+ # Update circuit breaker state
272
+ breaker.tick(state.error_rate, rng)
273
+ dampening = breaker.dampening_factor
274
+
275
+ # --- Compute propagated impact ---
276
+
277
+ # 1. Error propagation (dampened by circuit breaker)
278
+ propagated_error = state.error_rate * dampening * rng.uniform(0.5, 0.9)
279
+ caller.propagation_error_rate = max(
280
+ caller.propagation_error_rate,
281
+ propagated_error,
282
+ )
283
+
284
+ # 2. Retry amplification (increases arrival rate)
285
+ if dampening > 0.1: # Only retries if breaker isn't fully open
286
+ retry_mult = compute_retry_amplification(
287
+ state.error_rate * dampening,
288
+ caller.retry_max,
289
+ )
290
+ caller.arrival_rate *= min(retry_mult, 3.0) # Cap at 3x
291
+
292
+ # 3. Latency propagation (waiting on slow downstream)
293
+ if state.latency_p99_ms > 500 and dampening > 0.1:
294
+ downstream_wait = state.latency_p99_ms * dampening * 0.001 # ms β†’ seconds
295
+ caller.service_time_local += downstream_wait * 0.5 # Partial impact
296
+
297
+ # --- After propagation: update utilisation and derived metrics ---
298
+ for service_id, state in services.items():
299
+ # Recompute utilisation
300
+ state.utilisation = compute_utilisation(
301
+ state.arrival_rate / max(1, state.replicas), # Per-replica arrival rate
302
+ state.service_time_local,
303
+ state.thread_pool_size,
304
+ )
305
+
306
+ # Apply queueing delay to latency
307
+ q_mult = compute_queueing_latency_multiplier(state.utilisation)
308
+ if q_mult > 1.1:
309
+ base_p99 = 100.0 # Baseline p99 in ms
310
+ state.update_latency_percentiles(base_p99, q_mult, rng)
311
+
312
+ # Combine direct failure error rate with propagation error rate
313
+ combined_error = max(state.error_rate, state.propagation_error_rate)
314
+ state.error_rate = min(1.0, combined_error)
315
+
316
+ # Compute throughput (inverse of error rate, scaled by arrival)
317
+ state.throughput_rps = state.arrival_rate * (1.0 - state.error_rate) / max(1, state.replicas)
318
+
319
+ # Update status
320
+ state.status = state.compute_status()
321
+
322
+ # Reset per-tick propagation accumulator
323
+ state.propagation_error_rate = 0.0
uv.lock ADDED
The diff for this file is too large to render. See raw diff