Coverage for core / src / sensorkit / auto / failure.py: 100%
97 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
1# SPDX-License-Identifier: Apache-2.0
2"""Track controller failures and retry and recovery timing."""
4from __future__ import annotations
6import time
7from datetime import UTC, datetime, timedelta
9from pydantic import BaseModel, PrivateAttr, computed_field
12class FailureState(BaseModel):
13 """Track controller failures and schedule retries, recovery, and emergency shutdown.
15 Repeated failures trigger recovery unless the stable period passed without a failure or
16 recovery attempt between them. Exhausting recovery attempts, successful or failed, triggers an
17 emergency shutdown. Each procedure counts at most one failure, so one incident seen by several
18 observers counts once.
20 Lifecycle bookkeeping uses monotonic timestamps and exception objects. Published snapshots
21 use UTC datetimes and exception text.
22 """
24 recover_after_failures: int = 2
25 """Failures that trigger recovery."""
26 retry_delay: float = 5.0
27 """Seconds before retrying after a failure."""
28 recovery_attempts: int = 6
29 """Recovery attempts before an emergency shutdown."""
30 attempt_delay: float = 20.0
31 """Seconds between failed recovery attempts."""
32 cycle_delay: float = 120.0
33 """Seconds after a failed emergency shutdown before recovery resumes."""
34 stable_period: float = 900.0
35 """Seconds without a failure or recovery attempt before failure and recovery counts reset."""
36 failures: int = 0
37 """Failures counted toward recovery. Successful recovery resets this to one."""
38 attempts: int = 0
39 """Completed recovery attempts since the counts last reset or an emergency shutdown failed."""
41 # Event loop times and the live exception stay out of serialized state.
42 _retry_at: float | None = PrivateAttr(default=None)
43 _error: BaseException | None = PrivateAttr(default=None)
44 _stable_since: float | None = PrivateAttr(default=None)
46 @property
47 def error(self) -> BaseException | None:
48 """First controller failure counted for the current procedure, if any."""
49 return self._error
51 @computed_field
52 @property
53 def recovery_due(self) -> bool:
54 """Whether the next command is a recovery attempt."""
55 return self.failures >= self.recover_after_failures
57 @computed_field
58 @property
59 def emergency_due(self) -> bool:
60 """Whether the next command is an emergency shutdown."""
61 return self.recovery_due and self.attempts >= self.recovery_attempts
63 def waiting(self, now: float) -> float | None:
64 """Return the pending retry deadline in event loop time, or None if no delay remains."""
65 if self._retry_at is not None and now < self._retry_at:
66 return self._retry_at
68 return None
70 def snapshot(self, monotonic: float) -> FailureStateSnapshot:
71 """Return a detached copy with UTC datetimes, exception text, and expired counts reset.
73 Args:
74 monotonic: The shared monotonic reference for evaluating retry deadlines.
75 """
76 utc_now = datetime.now(UTC) - timedelta(seconds=time.monotonic() - monotonic)
78 def project(time: float | None):
79 return None if time is None else utc_now + timedelta(seconds=time - monotonic)
81 state = self.model_copy()
82 state.expire(monotonic)
83 error = state._error
84 stable_since = state._stable_since
86 return FailureStateSnapshot(
87 **state.model_dump(include=set(FailureState.model_fields)),
88 failure=None if error is None else f"{type(error).__name__}: {error}",
89 retry_at=project(state.waiting(monotonic)),
90 stable_at=project(None if stable_since is None else stable_since + self.stable_period),
91 )
93 def begin_procedure(self):
94 """Clear the current failure and retry delay without clearing accumulated counts."""
95 self._error = None
96 self._retry_at = None
98 def expire(self, now: float):
99 """Reset failure and recovery counts once the stable period passes without either."""
100 if self._stable_since is not None and now - self._stable_since >= self.stable_period:
101 self.failures = 0
102 self.attempts = 0
104 def record_initial_error(self, now: float):
105 """Count a controller error found at startup once, without delaying the first command."""
106 self.expire(now)
107 self._stable_since = now
109 if self.failures == 0:
110 self.failures = 1
112 def record_failure(self, now: float, error: BaseException):
113 """Record and count the first controller failure for the current procedure."""
114 if self._error is not None:
115 return
117 self.expire(now)
118 self._error = error
119 self._stable_since = now
120 self.failures += 1
122 # Only the first failure schedules a retry delay.
123 if not self.recovery_due:
124 self._retry_at = now + self.retry_delay
126 def delay_retry(self, now: float):
127 """Delay the next command without counting a controller failure."""
128 self._retry_at = now + self.retry_delay
130 def record_recovery(self, now: float):
131 """Record a successful recovery.
133 Another failure before the stable period ends triggers recovery again and counts toward
134 `recovery_attempts`.
135 """
136 self.failures = 1
137 self.attempts += 1
138 self._stable_since = now
139 self._retry_at = now + self.retry_delay
141 def record_failed_attempt(self, now: float):
142 """Count a failed recovery attempt."""
143 self.attempts += 1
144 self._stable_since = now
146 # Exhausted attempts fall back to emergency shutdown without waiting.
147 if not self.emergency_due:
148 self._retry_at = now + self.attempt_delay
150 def record_failed_emergency(self, now: float):
151 """Resume recovery attempts after a delay."""
152 self.attempts = 0
153 self._stable_since = now
154 self._retry_at = now + self.cycle_delay
156 def clear(self):
157 """Reset escalation counters and timing after emergency shutdown."""
158 self.failures = 0
159 self.attempts = 0
160 self._retry_at = None
161 self._stable_since = None
164class FailureStateSnapshot(FailureState):
165 """Detached failure state with UTC times and failure text."""
167 failure: str | None = None
168 """First controller failure counted for the current procedure, if any."""
169 retry_at: datetime | None = None
170 """Earliest retry or recovery time, or None if no delay remains."""
171 stable_at: datetime | None = None
172 """When counts reset or will reset without another failure, or None if none were counted."""