forked from microsoft/agent-governance-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlifecycle.py
More file actions
3113 lines (2565 loc) · 112 KB
/
lifecycle.py
File metadata and controls
3113 lines (2565 loc) · 112 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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""
Agent Lifecycle Management - v0.2.0
This module provides comprehensive lifecycle management for autonomous AI agents,
including health monitoring, auto-recovery, circuit breakers, scaling, distributed
coordination, dependency management, graceful shutdown, resource quotas, observability,
and hot reload capabilities.
Features:
- ACP-001: Agent Health Checks (liveness/readiness probes)
- ACP-002: Agent Auto-Recovery (automatic restart of crashed agents)
- ACP-003: Circuit Breaker (prevent cascading failures)
- ACP-004: Agent Scaling (horizontal scaling for high-throughput)
- ACP-005: Distributed Coordination (leader election, consensus)
- ACP-006: Agent Dependency Graph (enforced start order)
- ACP-007: Graceful Shutdown (preserve in-flight verifications)
- ACP-008: Resource Quotas (memory/CPU limits per agent)
- ACP-009: Agent Observability (metrics/logging integration)
- ACP-010: Hot Reload (code changes without full restart)
Research Foundations:
- Circuit Breaker pattern (Michael Nygard, "Release It!")
- Kubernetes probe patterns (liveness, readiness, startup)
- Raft consensus algorithm (Ongaro & Ousterhout, 2014)
- Actor model supervision (Erlang/OTP, Akka)
"""
from typing import (
Dict, List, Optional, Any, Union, Callable, Type, Set, Awaitable,
TypeVar, Generic, Protocol, runtime_checkable
)
from dataclasses import dataclass, field
from enum import Enum, auto
from datetime import datetime, timedelta
from collections import defaultdict, deque
from abc import ABC, abstractmethod
import asyncio
import time
import uuid
import logging
import threading
import weakref
import traceback
import hashlib
import importlib
import sys
# Configure module logger
logger = logging.getLogger(__name__)
# ============================================================================
# Enums and Constants
# ============================================================================
class HealthStatus(Enum):
"""Health status of an agent"""
UNKNOWN = "unknown"
HEALTHY = "healthy"
UNHEALTHY = "unhealthy"
DEGRADED = "degraded"
STARTING = "starting"
STOPPING = "stopping"
STOPPED = "stopped"
FAILED = "failed"
class AgentState(Enum):
"""State of an agent in the lifecycle"""
REGISTERED = "registered"
PENDING = "pending"
STARTING = "starting"
RUNNING = "running"
STOPPING = "stopping"
STOPPED = "stopped"
FAILED = "failed"
RECOVERING = "recovering"
class CircuitState(Enum):
"""State of a circuit breaker"""
CLOSED = "closed" # Normal operation
OPEN = "open" # Failing, reject requests
HALF_OPEN = "half_open" # Testing recovery
class CoordinationRole(Enum):
"""Role in distributed coordination"""
LEADER = "leader"
FOLLOWER = "follower"
CANDIDATE = "candidate"
class ShutdownPhase(Enum):
"""Phases of graceful shutdown"""
RUNNING = "running"
DRAINING = "draining"
STOPPING = "stopping"
TERMINATED = "terminated"
# ============================================================================
# ACP-001: Agent Health Checks
# ============================================================================
@dataclass
class HealthCheckResult:
"""Result of a health check probe"""
healthy: bool
status: HealthStatus
message: str = ""
latency_ms: float = 0.0
timestamp: datetime = field(default_factory=datetime.now)
details: Dict[str, Any] = field(default_factory=dict)
@dataclass
class HealthCheckConfig:
"""Configuration for health check probes"""
# Liveness probe settings
liveness_interval_seconds: float = 10.0
liveness_timeout_seconds: float = 5.0
liveness_failure_threshold: int = 3
# Readiness probe settings
readiness_interval_seconds: float = 5.0
readiness_timeout_seconds: float = 3.0
readiness_failure_threshold: int = 1
# Startup probe settings (for slow-starting agents)
startup_probe_enabled: bool = True
startup_timeout_seconds: float = 60.0
startup_period_seconds: float = 5.0
# Custom health check function
custom_health_check: Optional[Callable[[], Awaitable[bool]]] = None
@runtime_checkable
class HealthCheckable(Protocol):
"""Protocol for agents that support health checks"""
async def liveness_check(self) -> bool:
"""Check if the agent is alive (not deadlocked/crashed)"""
...
async def readiness_check(self) -> bool:
"""Check if the agent is ready to accept requests"""
...
class HealthMonitor:
"""
Monitors agent health via liveness and readiness probes.
Implements Kubernetes-style health checking patterns:
- Liveness: Is the agent alive? If not, restart it.
- Readiness: Is the agent ready to accept requests?
- Startup: Has the agent finished starting up?
Usage:
monitor = HealthMonitor(config=HealthCheckConfig())
# Register an agent
monitor.register_agent(agent_id, agent_instance)
# Start monitoring
await monitor.start()
# Check status
status = monitor.get_agent_health(agent_id)
"""
def __init__(self, config: Optional[HealthCheckConfig] = None):
self.config = config or HealthCheckConfig()
self._agents: Dict[str, Any] = {}
self._health_status: Dict[str, HealthStatus] = {}
self._liveness_failures: Dict[str, int] = defaultdict(int)
self._readiness_failures: Dict[str, int] = defaultdict(int)
self._last_check: Dict[str, datetime] = {}
self._check_history: Dict[str, deque] = defaultdict(lambda: deque(maxlen=100))
self._running = False
self._tasks: List[asyncio.Task] = []
self._callbacks: Dict[str, List[Callable]] = defaultdict(list)
self._lock = asyncio.Lock()
def register_agent(
self,
agent_id: str,
agent: Any,
custom_liveness: Optional[Callable[[], Awaitable[bool]]] = None,
custom_readiness: Optional[Callable[[], Awaitable[bool]]] = None
) -> None:
"""Register an agent for health monitoring"""
self._agents[agent_id] = {
"agent": agent,
"custom_liveness": custom_liveness,
"custom_readiness": custom_readiness,
"registered_at": datetime.now()
}
self._health_status[agent_id] = HealthStatus.UNKNOWN
logger.info(f"Registered agent {agent_id} for health monitoring")
def unregister_agent(self, agent_id: str) -> None:
"""Unregister an agent from health monitoring"""
if agent_id in self._agents:
del self._agents[agent_id]
self._health_status.pop(agent_id, None)
self._liveness_failures.pop(agent_id, None)
self._readiness_failures.pop(agent_id, None)
logger.info(f"Unregistered agent {agent_id} from health monitoring")
async def start(self) -> None:
"""Start the health monitoring loop"""
if self._running:
return
self._running = True
self._tasks.append(asyncio.create_task(self._liveness_loop()))
self._tasks.append(asyncio.create_task(self._readiness_loop()))
logger.info("Health monitor started")
async def stop(self) -> None:
"""Stop the health monitoring loop"""
self._running = False
for task in self._tasks:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
self._tasks.clear()
logger.info("Health monitor stopped")
async def _liveness_loop(self) -> None:
"""Main loop for liveness checks"""
while self._running:
for agent_id in list(self._agents.keys()):
try:
result = await self._check_liveness(agent_id)
self._check_history[agent_id].append(result)
if not result.healthy:
self._liveness_failures[agent_id] += 1
if self._liveness_failures[agent_id] >= self.config.liveness_failure_threshold:
self._health_status[agent_id] = HealthStatus.FAILED
await self._trigger_callbacks("liveness_failed", agent_id)
else:
self._liveness_failures[agent_id] = 0
if self._health_status[agent_id] == HealthStatus.FAILED:
self._health_status[agent_id] = HealthStatus.HEALTHY
await self._trigger_callbacks("liveness_restored", agent_id)
except Exception as e:
logger.error(f"Liveness check failed for {agent_id}: {e}")
self._liveness_failures[agent_id] += 1
await asyncio.sleep(self.config.liveness_interval_seconds)
async def _readiness_loop(self) -> None:
"""Main loop for readiness checks"""
while self._running:
for agent_id in list(self._agents.keys()):
try:
result = await self._check_readiness(agent_id)
if not result.healthy:
self._readiness_failures[agent_id] += 1
if self._readiness_failures[agent_id] >= self.config.readiness_failure_threshold:
if self._health_status[agent_id] == HealthStatus.HEALTHY:
self._health_status[agent_id] = HealthStatus.DEGRADED
await self._trigger_callbacks("readiness_failed", agent_id)
else:
self._readiness_failures[agent_id] = 0
if self._health_status[agent_id] == HealthStatus.DEGRADED:
self._health_status[agent_id] = HealthStatus.HEALTHY
await self._trigger_callbacks("readiness_restored", agent_id)
except Exception as e:
logger.error(f"Readiness check failed for {agent_id}: {e}")
self._readiness_failures[agent_id] += 1
await asyncio.sleep(self.config.readiness_interval_seconds)
async def _check_liveness(self, agent_id: str) -> HealthCheckResult:
"""Perform liveness check for an agent"""
start_time = time.time()
agent_info = self._agents.get(agent_id)
if not agent_info:
return HealthCheckResult(
healthy=False,
status=HealthStatus.UNKNOWN,
message="Agent not found"
)
agent = agent_info["agent"]
custom_check = agent_info.get("custom_liveness")
try:
# Try custom liveness check first
if custom_check:
healthy = await asyncio.wait_for(
custom_check(),
timeout=self.config.liveness_timeout_seconds
)
# Try protocol method
elif isinstance(agent, HealthCheckable):
healthy = await asyncio.wait_for(
agent.liveness_check(),
timeout=self.config.liveness_timeout_seconds
)
# Fallback: check if agent has is_alive method
elif hasattr(agent, 'is_alive'):
if asyncio.iscoroutinefunction(agent.is_alive):
healthy = await asyncio.wait_for(
agent.is_alive(),
timeout=self.config.liveness_timeout_seconds
)
else:
healthy = agent.is_alive()
else:
# Default: assume healthy if agent exists
healthy = True
latency_ms = (time.time() - start_time) * 1000
self._last_check[agent_id] = datetime.now()
return HealthCheckResult(
healthy=healthy,
status=HealthStatus.HEALTHY if healthy else HealthStatus.UNHEALTHY,
latency_ms=latency_ms
)
except asyncio.TimeoutError:
return HealthCheckResult(
healthy=False,
status=HealthStatus.UNHEALTHY,
message="Liveness check timed out",
latency_ms=self.config.liveness_timeout_seconds * 1000
)
except Exception as e:
return HealthCheckResult(
healthy=False,
status=HealthStatus.FAILED,
message=str(e),
latency_ms=(time.time() - start_time) * 1000
)
async def _check_readiness(self, agent_id: str) -> HealthCheckResult:
"""Perform readiness check for an agent"""
start_time = time.time()
agent_info = self._agents.get(agent_id)
if not agent_info:
return HealthCheckResult(
healthy=False,
status=HealthStatus.UNKNOWN,
message="Agent not found"
)
agent = agent_info["agent"]
custom_check = agent_info.get("custom_readiness")
try:
if custom_check:
ready = await asyncio.wait_for(
custom_check(),
timeout=self.config.readiness_timeout_seconds
)
elif isinstance(agent, HealthCheckable):
ready = await asyncio.wait_for(
agent.readiness_check(),
timeout=self.config.readiness_timeout_seconds
)
elif hasattr(agent, 'is_ready'):
if asyncio.iscoroutinefunction(agent.is_ready):
ready = await asyncio.wait_for(
agent.is_ready(),
timeout=self.config.readiness_timeout_seconds
)
else:
ready = agent.is_ready()
else:
ready = True
latency_ms = (time.time() - start_time) * 1000
return HealthCheckResult(
healthy=ready,
status=HealthStatus.HEALTHY if ready else HealthStatus.DEGRADED,
latency_ms=latency_ms
)
except asyncio.TimeoutError:
return HealthCheckResult(
healthy=False,
status=HealthStatus.DEGRADED,
message="Readiness check timed out",
latency_ms=self.config.readiness_timeout_seconds * 1000
)
except Exception as e:
return HealthCheckResult(
healthy=False,
status=HealthStatus.DEGRADED,
message=str(e),
latency_ms=(time.time() - start_time) * 1000
)
def on_event(self, event: str, callback: Callable[[str], Awaitable[None]]) -> None:
"""Register a callback for health events"""
self._callbacks[event].append(callback)
async def _trigger_callbacks(self, event: str, agent_id: str) -> None:
"""Trigger all callbacks for an event"""
for callback in self._callbacks.get(event, []):
try:
await callback(agent_id)
except Exception as e:
logger.error(f"Callback error for {event}: {e}")
def get_agent_health(self, agent_id: str) -> HealthStatus:
"""Get the current health status of an agent"""
return self._health_status.get(agent_id, HealthStatus.UNKNOWN)
def get_all_health_status(self) -> Dict[str, HealthStatus]:
"""Get health status for all agents"""
return dict(self._health_status)
def get_health_history(self, agent_id: str) -> List[HealthCheckResult]:
"""Get health check history for an agent"""
return list(self._check_history.get(agent_id, []))
# ============================================================================
# ACP-002: Agent Auto-Recovery
# ============================================================================
@dataclass
class RecoveryConfig:
"""Configuration for auto-recovery behavior"""
enabled: bool = True
max_restarts: int = 5
restart_delay_seconds: float = 1.0
restart_delay_max_seconds: float = 60.0
restart_delay_multiplier: float = 2.0
reset_restart_count_after_seconds: float = 300.0
on_max_restarts: str = "stop" # "stop", "alert", "continue"
@dataclass
class RecoveryEvent:
"""Record of a recovery event"""
agent_id: str
event_type: str # "restart", "failure", "recovery_success", "max_restarts"
timestamp: datetime = field(default_factory=datetime.now)
attempt: int = 0
error: Optional[str] = None
details: Dict[str, Any] = field(default_factory=dict)
class AutoRecoveryManager:
"""
Manages automatic recovery of failed agents.
Implements exponential backoff for restart attempts and tracks
recovery history for analysis.
Features:
- Automatic restart with exponential backoff
- Maximum restart limit with configurable behavior
- Recovery event logging
- Callbacks for recovery events
Usage:
recovery = AutoRecoveryManager(config=RecoveryConfig())
recovery.register_agent(agent_id, agent_factory)
# When agent fails
await recovery.handle_failure(agent_id, error)
"""
def __init__(self, config: Optional[RecoveryConfig] = None):
self.config = config or RecoveryConfig()
self._agent_factories: Dict[str, Callable[[], Any]] = {}
self._restart_counts: Dict[str, int] = defaultdict(int)
self._last_restart: Dict[str, datetime] = {}
self._current_delay: Dict[str, float] = {}
self._recovery_history: deque = deque(maxlen=1000)
self._callbacks: Dict[str, List[Callable]] = defaultdict(list)
self._agents: Dict[str, Any] = {}
self._lock = asyncio.Lock()
def register_agent(
self,
agent_id: str,
factory: Callable[[], Any],
initial_instance: Optional[Any] = None
) -> None:
"""Register an agent with its factory function for recovery"""
self._agent_factories[agent_id] = factory
if initial_instance:
self._agents[agent_id] = initial_instance
self._restart_counts[agent_id] = 0
self._current_delay[agent_id] = self.config.restart_delay_seconds
logger.info(f"Registered agent {agent_id} for auto-recovery")
def unregister_agent(self, agent_id: str) -> None:
"""Unregister an agent from auto-recovery"""
self._agent_factories.pop(agent_id, None)
self._agents.pop(agent_id, None)
self._restart_counts.pop(agent_id, None)
self._last_restart.pop(agent_id, None)
self._current_delay.pop(agent_id, None)
async def handle_failure(
self,
agent_id: str,
error: Optional[Exception] = None
) -> Optional[Any]:
"""
Handle an agent failure and attempt recovery.
Returns the new agent instance if recovery succeeds, None otherwise.
"""
if not self.config.enabled:
logger.info(f"Auto-recovery disabled, not recovering {agent_id}")
return None
async with self._lock:
# Check if we should reset restart count
if agent_id in self._last_restart:
time_since_last = (datetime.now() - self._last_restart[agent_id]).total_seconds()
if time_since_last > self.config.reset_restart_count_after_seconds:
self._restart_counts[agent_id] = 0
self._current_delay[agent_id] = self.config.restart_delay_seconds
# Check if max restarts reached
if self._restart_counts[agent_id] >= self.config.max_restarts:
event = RecoveryEvent(
agent_id=agent_id,
event_type="max_restarts",
attempt=self._restart_counts[agent_id],
error=str(error) if error else None
)
self._recovery_history.append(event)
await self._trigger_callbacks("max_restarts", agent_id, event)
if self.config.on_max_restarts == "stop":
logger.error(f"Max restarts reached for {agent_id}, stopping")
return None
elif self.config.on_max_restarts == "alert":
logger.warning(f"Max restarts reached for {agent_id}, alerting")
await self._trigger_callbacks("alert", agent_id, event)
# "continue" falls through to attempt restart anyway
# Calculate delay with exponential backoff
delay = self._current_delay.get(agent_id, self.config.restart_delay_seconds)
# Log failure event
failure_event = RecoveryEvent(
agent_id=agent_id,
event_type="failure",
attempt=self._restart_counts[agent_id],
error=str(error) if error else None
)
self._recovery_history.append(failure_event)
await self._trigger_callbacks("failure", agent_id, failure_event)
logger.info(f"Attempting recovery for {agent_id} after {delay:.1f}s delay")
await asyncio.sleep(delay)
# Attempt restart
try:
factory = self._agent_factories.get(agent_id)
if not factory:
logger.error(f"No factory registered for {agent_id}")
return None
new_agent = factory()
if asyncio.iscoroutine(new_agent):
new_agent = await new_agent
# Start the agent if it has a start method
if hasattr(new_agent, 'start'):
if asyncio.iscoroutinefunction(new_agent.start):
await new_agent.start()
else:
new_agent.start()
self._agents[agent_id] = new_agent
self._restart_counts[agent_id] += 1
self._last_restart[agent_id] = datetime.now()
# Increase delay for next potential failure (exponential backoff)
self._current_delay[agent_id] = min(
delay * self.config.restart_delay_multiplier,
self.config.restart_delay_max_seconds
)
success_event = RecoveryEvent(
agent_id=agent_id,
event_type="recovery_success",
attempt=self._restart_counts[agent_id]
)
self._recovery_history.append(success_event)
await self._trigger_callbacks("recovery_success", agent_id, success_event)
logger.info(f"Successfully recovered agent {agent_id}")
return new_agent
except Exception as e:
logger.error(f"Failed to recover agent {agent_id}: {e}")
self._restart_counts[agent_id] += 1
return await self.handle_failure(agent_id, e)
def on_event(
self,
event: str,
callback: Callable[[str, RecoveryEvent], Awaitable[None]]
) -> None:
"""Register a callback for recovery events"""
self._callbacks[event].append(callback)
async def _trigger_callbacks(
self,
event: str,
agent_id: str,
recovery_event: RecoveryEvent
) -> None:
"""Trigger all callbacks for an event"""
for callback in self._callbacks.get(event, []):
try:
await callback(agent_id, recovery_event)
except Exception as e:
logger.error(f"Callback error for {event}: {e}")
def get_agent(self, agent_id: str) -> Optional[Any]:
"""Get the current agent instance"""
return self._agents.get(agent_id)
def get_restart_count(self, agent_id: str) -> int:
"""Get the restart count for an agent"""
return self._restart_counts.get(agent_id, 0)
def get_recovery_history(
self,
agent_id: Optional[str] = None
) -> List[RecoveryEvent]:
"""Get recovery history, optionally filtered by agent"""
if agent_id:
return [e for e in self._recovery_history if e.agent_id == agent_id]
return list(self._recovery_history)
def reset_restart_count(self, agent_id: str) -> None:
"""Manually reset the restart count for an agent"""
self._restart_counts[agent_id] = 0
self._current_delay[agent_id] = self.config.restart_delay_seconds
# ============================================================================
# ACP-003: Circuit Breaker
# ============================================================================
@dataclass
class CircuitBreakerConfig:
"""Configuration for circuit breaker behavior"""
failure_threshold: int = 5
success_threshold: int = 3
recovery_timeout_seconds: float = 60.0
half_open_max_calls: int = 3
exclude_exceptions: List[Type[Exception]] = field(default_factory=list)
include_exceptions: Optional[List[Type[Exception]]] = None
@dataclass
class CircuitBreakerMetrics:
"""Metrics for a circuit breaker"""
state: CircuitState
failure_count: int
success_count: int
total_calls: int
total_failures: int
total_successes: int
last_failure_time: Optional[datetime]
last_success_time: Optional[datetime]
state_changed_at: datetime
class CircuitBreaker:
"""
Circuit breaker for preventing cascading failures.
Implements the circuit breaker pattern to protect against cascading
failures when an agent or service becomes unavailable.
States:
- CLOSED: Normal operation, requests pass through
- OPEN: Failing, requests are rejected immediately
- HALF_OPEN: Testing recovery, limited requests allowed
Features:
- Configurable failure/success thresholds
- Automatic recovery timeout
- Exception filtering
- Metrics collection
Usage:
breaker = CircuitBreaker(
config=CircuitBreakerConfig(
failure_threshold=5,
recovery_timeout=60
)
)
# Use as decorator
@breaker
async def call_agent():
...
# Or use context manager
async with breaker:
await call_agent()
"""
def __init__(
self,
name: str = "default",
config: Optional[CircuitBreakerConfig] = None,
failure_threshold: Optional[int] = None,
recovery_timeout: Optional[float] = None
):
self.name = name
self.config = config or CircuitBreakerConfig()
# Allow direct parameter override for convenience API
if failure_threshold is not None:
self.config.failure_threshold = failure_threshold
if recovery_timeout is not None:
self.config.recovery_timeout_seconds = recovery_timeout
self._state = CircuitState.CLOSED
self._failure_count = 0
self._success_count = 0
self._half_open_calls = 0
self._last_failure_time: Optional[datetime] = None
self._last_success_time: Optional[datetime] = None
self._state_changed_at = datetime.now()
self._total_calls = 0
self._total_failures = 0
self._total_successes = 0
self._lock = asyncio.Lock()
self._callbacks: Dict[str, List[Callable]] = defaultdict(list)
@property
def state(self) -> CircuitState:
"""Get the current circuit state"""
return self._state
@property
def is_closed(self) -> bool:
"""Check if circuit is closed (normal operation)"""
return self._state == CircuitState.CLOSED
@property
def is_open(self) -> bool:
"""Check if circuit is open (rejecting requests)"""
return self._state == CircuitState.OPEN
async def __aenter__(self):
"""Async context manager entry"""
await self._before_call()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Async context manager exit"""
if exc_type is None:
await self._on_success()
else:
if self._should_count_exception(exc_type):
await self._on_failure(exc_val)
return False
def __call__(self, func: Callable) -> Callable:
"""Decorator for wrapping functions with circuit breaker"""
async def wrapper(*args, **kwargs):
await self._before_call()
try:
if asyncio.iscoroutinefunction(func):
result = await func(*args, **kwargs)
else:
result = func(*args, **kwargs)
await self._on_success()
return result
except Exception as e:
if self._should_count_exception(type(e)):
await self._on_failure(e)
raise
return wrapper
async def _before_call(self) -> None:
"""Check circuit state before a call"""
async with self._lock:
self._total_calls += 1
if self._state == CircuitState.OPEN:
# Check if recovery timeout has elapsed
if self._last_failure_time:
elapsed = (datetime.now() - self._last_failure_time).total_seconds()
if elapsed >= self.config.recovery_timeout_seconds:
self._transition_to(CircuitState.HALF_OPEN)
self._half_open_calls = 0
else:
raise CircuitBreakerOpenError(
f"Circuit {self.name} is open, retry after "
f"{self.config.recovery_timeout_seconds - elapsed:.1f}s"
)
else:
raise CircuitBreakerOpenError(f"Circuit {self.name} is open")
elif self._state == CircuitState.HALF_OPEN:
if self._half_open_calls >= self.config.half_open_max_calls:
raise CircuitBreakerOpenError(
f"Circuit {self.name} is half-open, max test calls reached"
)
self._half_open_calls += 1
async def _on_success(self) -> None:
"""Handle a successful call"""
async with self._lock:
self._total_successes += 1
self._last_success_time = datetime.now()
if self._state == CircuitState.HALF_OPEN:
self._success_count += 1
if self._success_count >= self.config.success_threshold:
self._transition_to(CircuitState.CLOSED)
elif self._state == CircuitState.CLOSED:
self._failure_count = 0
async def _on_failure(self, error: Exception) -> None:
"""Handle a failed call"""
async with self._lock:
self._total_failures += 1
self._last_failure_time = datetime.now()
self._failure_count += 1
if self._state == CircuitState.HALF_OPEN:
# Any failure in half-open state opens the circuit
self._transition_to(CircuitState.OPEN)
elif self._state == CircuitState.CLOSED:
if self._failure_count >= self.config.failure_threshold:
self._transition_to(CircuitState.OPEN)
def _transition_to(self, new_state: CircuitState) -> None:
"""Transition to a new circuit state"""
old_state = self._state
self._state = new_state
self._state_changed_at = datetime.now()
if new_state == CircuitState.CLOSED:
self._failure_count = 0
self._success_count = 0
elif new_state == CircuitState.HALF_OPEN:
self._success_count = 0
self._half_open_calls = 0
logger.info(f"Circuit {self.name} transitioned from {old_state.value} to {new_state.value}")
# Trigger callbacks asynchronously
asyncio.create_task(self._trigger_state_change(old_state, new_state))
async def _trigger_state_change(
self,
old_state: CircuitState,
new_state: CircuitState
) -> None:
"""Trigger callbacks for state change"""
for callback in self._callbacks.get("state_change", []):
try:
await callback(self.name, old_state, new_state)
except Exception as e:
logger.error(f"Circuit breaker callback error: {e}")
def _should_count_exception(self, exc_type: Type[Exception]) -> bool:
"""Determine if an exception should be counted as a failure"""
# Check exclude list
for excluded in self.config.exclude_exceptions:
if issubclass(exc_type, excluded):
return False
# Check include list if specified
if self.config.include_exceptions is not None:
for included in self.config.include_exceptions:
if issubclass(exc_type, included):
return True
return False
return True
def on_state_change(
self,
callback: Callable[[str, CircuitState, CircuitState], Awaitable[None]]
) -> None:
"""Register a callback for state changes"""
self._callbacks["state_change"].append(callback)
def get_metrics(self) -> CircuitBreakerMetrics:
"""Get current circuit breaker metrics"""
return CircuitBreakerMetrics(
state=self._state,
failure_count=self._failure_count,
success_count=self._success_count,
total_calls=self._total_calls,
total_failures=self._total_failures,
total_successes=self._total_successes,
last_failure_time=self._last_failure_time,
last_success_time=self._last_success_time,
state_changed_at=self._state_changed_at
)
def reset(self) -> None:
"""Manually reset the circuit breaker to closed state"""
self._state = CircuitState.CLOSED
self._failure_count = 0
self._success_count = 0
self._half_open_calls = 0
self._state_changed_at = datetime.now()
logger.info(f"Circuit {self.name} manually reset to CLOSED")
class CircuitBreakerOpenError(Exception):
"""Raised when a circuit breaker is open"""
pass
class CircuitBreakerRegistry:
"""Registry for managing multiple circuit breakers"""
def __init__(self):
self._breakers: Dict[str, CircuitBreaker] = {}
def get_or_create(
self,
name: str,
config: Optional[CircuitBreakerConfig] = None
) -> CircuitBreaker:
"""Get or create a circuit breaker by name"""
if name not in self._breakers:
self._breakers[name] = CircuitBreaker(name=name, config=config)
return self._breakers[name]
def get(self, name: str) -> Optional[CircuitBreaker]:
"""Get a circuit breaker by name"""
return self._breakers.get(name)
def get_all_metrics(self) -> Dict[str, CircuitBreakerMetrics]:
"""Get metrics for all circuit breakers"""
return {name: cb.get_metrics() for name, cb in self._breakers.items()}
# ============================================================================
# ACP-004: Agent Scaling
# ============================================================================
@dataclass
class ScalingConfig:
"""Configuration for agent scaling"""
min_replicas: int = 1
max_replicas: int = 10
target_cpu_utilization: float = 0.7
target_memory_utilization: float = 0.8
scale_up_threshold: float = 0.8
scale_down_threshold: float = 0.3
scale_up_cooldown_seconds: float = 60.0
scale_down_cooldown_seconds: float = 300.0
scale_up_increment: int = 1
scale_down_increment: int = 1
@dataclass
class AgentReplica:
"""Represents a replica of an agent"""
replica_id: str
agent_id: str
instance: Any
created_at: datetime = field(default_factory=datetime.now)
status: AgentState = AgentState.PENDING
metrics: Dict[str, float] = field(default_factory=dict)
class AgentScaler:
"""
Horizontal scaling manager for agents.
Provides automatic scaling based on load metrics, supporting both
scale-up and scale-down with configurable thresholds and cooldowns.