taipanstack 0.5.0__tar.gz → 0.5.2__tar.gz

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.
Files changed (53) hide show
  1. {taipanstack-0.5.0 → taipanstack-0.5.2}/PKG-INFO +13 -12
  2. {taipanstack-0.5.0 → taipanstack-0.5.2}/README.md +12 -11
  3. {taipanstack-0.5.0 → taipanstack-0.5.2}/pyproject.toml +4 -2
  4. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/__init__.py +1 -1
  5. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/bridges/http_bridge.py +2 -2
  6. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/config/version_config.py +0 -4
  7. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/core/compat.py +0 -2
  8. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +53 -18
  9. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/adaptive/adaptive_retry.py +12 -9
  10. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/adaptive/orchestrator.py +52 -18
  11. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/circuit_breaker.py +146 -71
  12. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/resilience.py +10 -2
  13. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/retry.py +14 -7
  14. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/watchdogs/config_watcher.py +39 -11
  15. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/security/guards.py +53 -28
  16. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/security/jwt.py +6 -0
  17. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/security/models.py +23 -10
  18. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/security/sanitizers.py +3 -109
  19. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/utils/concurrency.py +3 -2
  20. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/utils/logging.py +49 -15
  21. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/utils/rate_limit.py +56 -40
  22. {taipanstack-0.5.0 → taipanstack-0.5.2}/LICENSE +0 -0
  23. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/bridges/__init__.py +0 -0
  24. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/bridges/_imports.py +0 -0
  25. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/bridges/db_bridge.py +4 -4
  26. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/bridges/web_bridge.py +0 -0
  27. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/config/__init__.py +0 -0
  28. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/config/generators.py +0 -0
  29. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/config/models.py +0 -0
  30. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/core/__init__.py +0 -0
  31. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/core/optimizations.py +0 -0
  32. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/core/result.py +0 -0
  33. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/__init__.py +0 -0
  34. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
  35. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/adaptive/bulkhead.py +0 -0
  36. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
  37. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/watchdogs/_base.py +0 -0
  38. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/watchdogs/health_pinger.py +0 -0
  39. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/resilience/watchdogs/resource_watcher.py +0 -0
  40. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/security/__init__.py +0 -0
  41. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/security/decorators.py +0 -0
  42. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/security/password.py +0 -0
  43. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/security/types.py +0 -0
  44. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/security/validators.py +0 -0
  45. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/utils/__init__.py +0 -0
  46. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/utils/cache.py +0 -0
  47. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/utils/circuit_breaker.py +0 -0
  48. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/utils/context.py +0 -0
  49. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/utils/filesystem.py +0 -0
  50. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/utils/resilience.py +0 -0
  51. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/utils/retry.py +0 -0
  52. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/utils/serialization.py +0 -0
  53. {taipanstack-0.5.0 → taipanstack-0.5.2}/src/taipanstack/utils/subprocess.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.5.0
3
+ Version: 0.5.2
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -75,7 +75,7 @@ Description-Content-Type: text/markdown
75
75
 
76
76
  ---
77
77
 
78
- [**Features**](#-features) • [**Quick Start**](#-quick-start) • [**Architecture**](#-architecture) • [**DevSecOps**](#-devsecops) • [**API**](#-api-highlights) • [**Contributing**](#-contributing)
78
+ [**Features**](#-why-taipan-stack) • [**Quick Start**](#-quick-start) • [**Architecture**](#-architecture) • [**DevSecOps**](#-devsecops) • [**API**](#-api-highlights) • [**Contributing**](#-contributing)
79
79
 
80
80
  </div>
81
81
 
@@ -87,11 +87,12 @@ Description-Content-Type: text/markdown
87
87
 
88
88
  Taipan Stack is a battle-tested foundation for production-grade Python projects that combines **security**, **performance**, and **developer experience** into a single, cohesive toolkit.
89
89
 
90
- ### ✨ What's New in v0.5.0
91
- - **Security Hardening**: Hardened path traversal protection (PR #741) and JWT encoding/decoding logic (PR #775) against malformed inputs; fixed IndexError on project validator (PR #768).
92
- - **Resilience Enhancements**: Frozen circuit breaker configuration to prevent runtime mutations under chaos (PR #778) and resolved double-wrapping of Result objects in ResilienceOrchestrator (PR #767).
93
- - **Clean Code & Type Guards**: Enforced strict isinstance type checks to replace match/case result matching (PR #746, #763, #777) and optimized modules to reduce complexity (PR #770).
94
- - **QA Suite Optimization**: Consolidated and refactored the entire test suite down to **1,225 passing tests** while maintaining absolute 100% genuine code and branch coverage (PR #773, #781, #782).
90
+ ### ✨ What's New in v0.5.2
91
+ - **Sentinel Hardening**: Enforced multicast and unspecified IP address bounds checking inside `guard_ssrf` (PR #826) and added negative domain bounds checks to resilience LBYL type guards (PR #823).
92
+ - **Resilience under Chaos**: Protected `CircuitBreaker` and `Retry` against runtime property type mutations and configuration exception changes under chaos, and fixed `NaN` `last_failure_time` lockout vulnerability (PR #811, #819, #830).
93
+ - **Complexity Refactor**: Reduced cyclomatic and cognitive complexity in watchdogs, orchestrators, bridges, and circuit breakers (PR #813, #817, #821, #835).
94
+ - **QA & Typing**: Standardized test naming convention (`test_*.py`) and refactored test suite to achieve 100% genuine coverage over **1,226 passing tests** (PR #816, #825, #831, #837).
95
+ - **Bridges API Reference**: Added new API documentation reference for the Bridges module (PR #822).
95
96
 
96
97
  <table>
97
98
  <tr>
@@ -128,7 +129,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
128
129
 
129
130
  ### 🔧 Developer Experience
130
131
  - Pre-configured quality tools
131
- - **100% code coverage** (1,225 tests)
132
+ - **100% code coverage** (1,226 tests)
132
133
  - Architecture enforcement
133
134
  - Hardened Docker template
134
135
 
@@ -170,7 +171,7 @@ make all
170
171
  ### Verify Installation
171
172
 
172
173
  ```bash
173
- # Run tests with 100% coverage (1,225 tests)
174
+ # Run tests with 100% coverage (1,226 tests)
174
175
  make test
175
176
 
176
177
  # Check architecture contracts
@@ -223,7 +224,7 @@ TaipanStack/
223
224
  │ ├── config/ # ⚙️ Configuration models & generators
224
225
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
225
226
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
226
- ├── tests/ # ✅ 1,225 tests, 100% coverage
227
+ ├── tests/ # ✅ 1,226 tests, 100% coverage
227
228
  ├── .semgrep/ # 🔍 Custom SAST rules
228
229
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
229
230
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -239,7 +240,7 @@ Taipan Stack integrates security and quality at every level:
239
240
  | Category | Tools | Purpose |
240
241
  |----------|-------|---------|
241
242
  | **SAST** | Bandit, Semgrep + custom rules | Static Application Security Testing |
242
- | **SCA** | Safety, pip-audit | Dependency vulnerability scanning |
243
+ | **SCA** | pip-audit | Dependency vulnerability scanning |
243
244
  | **SBOM** | Syft (CycloneDX) | Software Bill of Materials |
244
245
  | **SLSA** | Cosign (Sigstore) | Artifact signing & attestation |
245
246
  | **Types** | Mypy (strict) | Compile-time type checking |
@@ -484,7 +485,7 @@ This project is open-sourced under the [MIT License](LICENSE).
484
485
 
485
486
  **Made with ❤️ for the Python community**
486
487
 
487
- [⬆ Back to Top](#-taipanstack)
488
+ [⬆ Back to Top](#-taipan-stack)
488
489
 
489
490
  </div>
490
491
 
@@ -18,7 +18,7 @@
18
18
 
19
19
  ---
20
20
 
21
- [**Features**](#-features) • [**Quick Start**](#-quick-start) • [**Architecture**](#-architecture) • [**DevSecOps**](#-devsecops) • [**API**](#-api-highlights) • [**Contributing**](#-contributing)
21
+ [**Features**](#-why-taipan-stack) • [**Quick Start**](#-quick-start) • [**Architecture**](#-architecture) • [**DevSecOps**](#-devsecops) • [**API**](#-api-highlights) • [**Contributing**](#-contributing)
22
22
 
23
23
  </div>
24
24
 
@@ -30,11 +30,12 @@
30
30
 
31
31
  Taipan Stack is a battle-tested foundation for production-grade Python projects that combines **security**, **performance**, and **developer experience** into a single, cohesive toolkit.
32
32
 
33
- ### ✨ What's New in v0.5.0
34
- - **Security Hardening**: Hardened path traversal protection (PR #741) and JWT encoding/decoding logic (PR #775) against malformed inputs; fixed IndexError on project validator (PR #768).
35
- - **Resilience Enhancements**: Frozen circuit breaker configuration to prevent runtime mutations under chaos (PR #778) and resolved double-wrapping of Result objects in ResilienceOrchestrator (PR #767).
36
- - **Clean Code & Type Guards**: Enforced strict isinstance type checks to replace match/case result matching (PR #746, #763, #777) and optimized modules to reduce complexity (PR #770).
37
- - **QA Suite Optimization**: Consolidated and refactored the entire test suite down to **1,225 passing tests** while maintaining absolute 100% genuine code and branch coverage (PR #773, #781, #782).
33
+ ### ✨ What's New in v0.5.2
34
+ - **Sentinel Hardening**: Enforced multicast and unspecified IP address bounds checking inside `guard_ssrf` (PR #826) and added negative domain bounds checks to resilience LBYL type guards (PR #823).
35
+ - **Resilience under Chaos**: Protected `CircuitBreaker` and `Retry` against runtime property type mutations and configuration exception changes under chaos, and fixed `NaN` `last_failure_time` lockout vulnerability (PR #811, #819, #830).
36
+ - **Complexity Refactor**: Reduced cyclomatic and cognitive complexity in watchdogs, orchestrators, bridges, and circuit breakers (PR #813, #817, #821, #835).
37
+ - **QA & Typing**: Standardized test naming convention (`test_*.py`) and refactored test suite to achieve 100% genuine coverage over **1,226 passing tests** (PR #816, #825, #831, #837).
38
+ - **Bridges API Reference**: Added new API documentation reference for the Bridges module (PR #822).
38
39
 
39
40
  <table>
40
41
  <tr>
@@ -71,7 +72,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
71
72
 
72
73
  ### 🔧 Developer Experience
73
74
  - Pre-configured quality tools
74
- - **100% code coverage** (1,225 tests)
75
+ - **100% code coverage** (1,226 tests)
75
76
  - Architecture enforcement
76
77
  - Hardened Docker template
77
78
 
@@ -113,7 +114,7 @@ make all
113
114
  ### Verify Installation
114
115
 
115
116
  ```bash
116
- # Run tests with 100% coverage (1,225 tests)
117
+ # Run tests with 100% coverage (1,226 tests)
117
118
  make test
118
119
 
119
120
  # Check architecture contracts
@@ -166,7 +167,7 @@ TaipanStack/
166
167
  │ ├── config/ # ⚙️ Configuration models & generators
167
168
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
168
169
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
169
- ├── tests/ # ✅ 1,225 tests, 100% coverage
170
+ ├── tests/ # ✅ 1,226 tests, 100% coverage
170
171
  ├── .semgrep/ # 🔍 Custom SAST rules
171
172
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
172
173
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -182,7 +183,7 @@ Taipan Stack integrates security and quality at every level:
182
183
  | Category | Tools | Purpose |
183
184
  |----------|-------|---------|
184
185
  | **SAST** | Bandit, Semgrep + custom rules | Static Application Security Testing |
185
- | **SCA** | Safety, pip-audit | Dependency vulnerability scanning |
186
+ | **SCA** | pip-audit | Dependency vulnerability scanning |
186
187
  | **SBOM** | Syft (CycloneDX) | Software Bill of Materials |
187
188
  | **SLSA** | Cosign (Sigstore) | Artifact signing & attestation |
188
189
  | **Types** | Mypy (strict) | Compile-time type checking |
@@ -427,6 +428,6 @@ This project is open-sourced under the [MIT License](LICENSE).
427
428
 
428
429
  **Made with ❤️ for the Python community**
429
430
 
430
- [⬆ Back to Top](#-taipanstack)
431
+ [⬆ Back to Top](#-taipan-stack)
431
432
 
432
433
  </div>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.5.0"
3
+ version = "0.5.2"
4
4
  description = "TaipanStack - Modular, secure, and scalable Python stack for robust development"
5
5
  authors = [
6
6
  {name = "gabrielima7", email = "gabrielima.alu.lmb@gmail.com"}
@@ -104,11 +104,12 @@ dev = [
104
104
  "authlib (>=1.6.11,<2.0.0)",
105
105
  "cryptography (>=46.0.7,<49.0.0)",
106
106
  "mutmut (>=3.0.0,<4.0.0)",
107
+ "mkdocs-material (>=9.7.6,<10.0.0)",
107
108
  ]
108
109
 
109
110
  docs = [
110
111
  "mkdocs-material (>=9.7.3,<10.0.0)",
111
- "mkdocstrings[python] (>=1.0.3,<2.0.0)"
112
+ "mkdocstrings[python] (>=1.0.3,<2.0.0)",
112
113
  ]
113
114
 
114
115
 
@@ -197,6 +198,7 @@ plugins = ["pydantic.mypy"]
197
198
  [[tool.mypy.overrides]]
198
199
  module = [
199
200
  "mutmut.*",
201
+ "tests.*",
200
202
  ]
201
203
  ignore_missing_imports = true
202
204
  ignore_errors = true
@@ -5,7 +5,7 @@ A modular, secure, and scalable Python stack for robust development.
5
5
  Supports Python 3.11+ with version-aware optimizations for 3.13/3.14.
6
6
  """
7
7
 
8
- __version__ = "0.5.0"
8
+ __version__ = "0.5.2"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -218,7 +218,7 @@ async def _execute_with_retries(
218
218
 
219
219
  """
220
220
  max_attempts = retry_config.max_attempts if retry_config is not None else 1
221
- last_error: Exception | None = None
221
+ last_error: Exception = RuntimeError("Request failed")
222
222
 
223
223
  for attempt in range(1, max_attempts + 1):
224
224
  outcome = await _execute_single_attempt(
@@ -234,7 +234,7 @@ async def _execute_with_retries(
234
234
  if isinstance(outcome, Exception):
235
235
  last_error = outcome
236
236
 
237
- return Err(last_error or RuntimeError("Request failed"))
237
+ return Err(last_error)
238
238
 
239
239
 
240
240
  async def safe_request(
@@ -10,7 +10,6 @@ Following Stack pillars: Security, Stability, Simplicity, Scalability, Compatibi
10
10
 
11
11
  import logging
12
12
  from dataclasses import dataclass
13
- from typing import TYPE_CHECKING
14
13
 
15
14
  from taipanstack.core.compat import (
16
15
  PY312,
@@ -21,9 +20,6 @@ from taipanstack.core.compat import (
21
20
  )
22
21
  from taipanstack.core.optimizations import get_recommended_thread_pool_size
23
22
 
24
- if TYPE_CHECKING:
25
- pass
26
-
27
23
  __all__ = [
28
24
  "VersionRecommendations",
29
25
  "get_version_recommendations",
@@ -223,7 +223,6 @@ class PythonFeatures:
223
223
  has_exception_groups: bool = False # 3.11+
224
224
  has_self_type: bool = False # 3.11+
225
225
  has_type_params: bool = False # 3.12+
226
- has_fstring_improvements: bool = False # 3.12+
227
226
  has_override_decorator: bool = False # 3.12+
228
227
  has_deprecated_decorator: bool = False # 3.13+
229
228
  has_deferred_annotations: bool = False # 3.14+
@@ -283,7 +282,6 @@ def _get_language_features() -> dict[str, bool]:
283
282
  "has_exception_groups": PY311,
284
283
  "has_self_type": PY311,
285
284
  "has_type_params": PY312,
286
- "has_fstring_improvements": PY312,
287
285
  "has_override_decorator": PY312,
288
286
  "has_deprecated_decorator": PY313,
289
287
  "has_deferred_annotations": PY314,
@@ -76,6 +76,8 @@ class AdaptiveCircuitBreaker:
76
76
  ) -> None:
77
77
  """Initialize the adaptive circuit breaker."""
78
78
  self.name = name
79
+ if min_throughput < 1:
80
+ raise ValueError("min_throughput must be at least 1")
79
81
  self._min_throughput = min_throughput
80
82
  self._target_error_rate = target_error_rate
81
83
  if not math.isfinite(recovery_timeout) or recovery_timeout < 0:
@@ -88,19 +90,59 @@ class AdaptiveCircuitBreaker:
88
90
  self._last_opened_at: float = 0.0
89
91
  self._lock = threading.Lock()
90
92
 
93
+ def _calculate_elapsed_time(self, now: float) -> float:
94
+ """Calculate elapsed time since the circuit opened."""
95
+ last_opened = self._last_opened_at
96
+ if not isinstance(last_opened, (int, float)) or not math.isfinite(last_opened):
97
+ return self._recovery_timeout
98
+
99
+ elapsed = now - last_opened
100
+ return self._recovery_timeout if elapsed < 0 else elapsed
101
+
102
+ def _check_half_open_transition(self) -> None:
103
+ """Evaluate if an OPEN circuit should transition to HALF_OPEN."""
104
+ now = time.monotonic()
105
+ elapsed = self._calculate_elapsed_time(now)
106
+
107
+ if math.isfinite(now) and elapsed >= self._recovery_timeout:
108
+ self._state = CircuitState.HALF_OPEN
109
+ logger.info("Adaptive breaker '%s' entering HALF_OPEN state", self.name)
110
+
91
111
  @property
92
112
  def state(self) -> CircuitState:
93
113
  """Current circuit state. May evaluate timeouts and switch to HALF_OPEN."""
94
114
  with self._lock:
95
115
  if self._state == CircuitState.OPEN:
96
- now = time.monotonic()
97
- if now - self._last_opened_at >= self._recovery_timeout:
98
- self._state = CircuitState.HALF_OPEN
99
- logger.info(
100
- "Adaptive breaker '%s' entering HALF_OPEN state", self.name
101
- )
116
+ self._check_half_open_transition()
102
117
  return self._state
103
118
 
119
+ def _calculate_error_rate(self, total: int) -> float:
120
+ """Calculate the current error rate in the window."""
121
+ if total <= 0:
122
+ return 0.0
123
+ errors = sum(1 for ok in self._window if not ok)
124
+ return errors / total
125
+
126
+ def _get_safe_target_rate(self) -> float:
127
+ """Safely retrieve the target error rate."""
128
+ target_rate = self._target_error_rate
129
+ if not isinstance(target_rate, (int, float)) or not math.isfinite(target_rate):
130
+ return -1.0 # Fail closed
131
+ return float(target_rate)
132
+
133
+ def _transition_to_open(self, error_rate: float, target_rate: float) -> None:
134
+ """Transition the circuit to the OPEN state."""
135
+ self._state = CircuitState.OPEN
136
+ self._last_opened_at = time.monotonic()
137
+
138
+ log_target = target_rate if target_rate >= 0 else 0.0
139
+ logger.warning(
140
+ "Adaptive breaker '%s' OPENED. Error rate %.2f > %.2f",
141
+ self.name,
142
+ error_rate,
143
+ log_target,
144
+ )
145
+
104
146
  def _evaluate_trip(self) -> None:
105
147
  """Evaluate if the circuit should trip open.
106
148
 
@@ -113,18 +155,11 @@ class AdaptiveCircuitBreaker:
113
155
  if total < self._min_throughput:
114
156
  return
115
157
 
116
- errors = sum(1 for ok in self._window if not ok)
117
- error_rate = errors / total
118
-
119
- if error_rate > self._target_error_rate:
120
- self._state = CircuitState.OPEN
121
- self._last_opened_at = time.monotonic()
122
- logger.warning(
123
- "Adaptive breaker '%s' OPENED. Error rate %.2f > %.2f",
124
- self.name,
125
- error_rate,
126
- self._target_error_rate,
127
- )
158
+ error_rate = self._calculate_error_rate(total)
159
+ target_rate = self._get_safe_target_rate()
160
+
161
+ if error_rate > target_rate:
162
+ self._transition_to_open(error_rate, target_rate)
128
163
 
129
164
  def record_success(self) -> None:
130
165
  """Record a successful call."""
@@ -158,6 +158,17 @@ class AdaptiveRetry:
158
158
  jitter=False,
159
159
  )
160
160
 
161
+ def _calculate_delay_metrics(self, all_delays: list[float]) -> tuple[float, float]:
162
+ """Calculate average and p95 delays from a list of delays."""
163
+ if not all_delays:
164
+ return 0.0, 0.0
165
+
166
+ avg_delay = statistics.mean(all_delays)
167
+ sorted_delays = sorted(all_delays)
168
+ idx = int(len(sorted_delays) * 0.95)
169
+ p95_delay = sorted_delays[min(idx, len(sorted_delays) - 1)]
170
+ return avg_delay, p95_delay
171
+
161
172
  @property
162
173
  def metrics(self) -> RetryMetrics:
163
174
  """Snapshot of current adaptive retry metrics."""
@@ -167,15 +178,7 @@ class AdaptiveRetry:
167
178
  all_delays = [o.elapsed for o in self._outcomes]
168
179
 
169
180
  success_rate = successes / total if total > 0 else 1.0
170
-
171
- if all_delays:
172
- avg_delay = statistics.mean(all_delays)
173
- sorted_delays = sorted(all_delays)
174
- idx = int(len(sorted_delays) * 0.95)
175
- p95_delay = sorted_delays[min(idx, len(sorted_delays) - 1)]
176
- else:
177
- avg_delay = 0.0
178
- p95_delay = 0.0
181
+ avg_delay, p95_delay = self._calculate_delay_metrics(all_delays)
179
182
 
180
183
  return RetryMetrics(
181
184
  success_rate=success_rate,
@@ -165,7 +165,7 @@ class ResilienceOrchestrator(Generic[T]):
165
165
  self._fallback_value = value
166
166
  return self
167
167
 
168
- async def execute(
168
+ async def execute( # noqa: PLR0911
169
169
  self,
170
170
  fn: Callable[P, Awaitable[T]],
171
171
  *args: P.args,
@@ -217,14 +217,20 @@ class ResilienceOrchestrator(Generic[T]):
217
217
 
218
218
  bh._active += 1
219
219
  try:
220
- return await self._execute_inner(fn, *args, **kwargs)
220
+ try:
221
+ return await self._execute_inner(fn, *args, **kwargs)
222
+ except Exception as exc:
223
+ return self._apply_fallback(Err(exc))
221
224
  finally:
222
225
  bh._active -= 1
223
226
  bh._semaphore.release()
224
227
 
225
- return await self._execute_inner(fn, *args, **kwargs)
228
+ try:
229
+ return await self._execute_inner(fn, *args, **kwargs)
230
+ except Exception as exc:
231
+ return self._apply_fallback(Err(exc))
226
232
 
227
- def _evaluate_circuit_breaker(self) -> Result[T, Exception] | None:
233
+ def _evaluate_circuit_breaker(self) -> Err[Exception] | None:
228
234
  """Check if execution is allowed by the circuit breaker."""
229
235
  if self._adaptive_breaker is not None:
230
236
  if not self._adaptive_breaker.should_allow():
@@ -278,10 +284,6 @@ class ResilienceOrchestrator(Generic[T]):
278
284
  **kwargs: P.kwargs,
279
285
  ) -> Result[T, Exception]:
280
286
  """Execute through breaker → retry → timeout → fn layers."""
281
- cb_err = self._evaluate_circuit_breaker()
282
- if cb_err is not None:
283
- return self._apply_fallback(cb_err)
284
-
285
287
  max_attempts = (
286
288
  self._retry_config.max_attempts if self._retry_config is not None else 1
287
289
  )
@@ -300,6 +302,36 @@ class ResilienceOrchestrator(Generic[T]):
300
302
  return True
301
303
  return False
302
304
 
305
+ def _handle_circuit_breaker_open(
306
+ self, cb_err: Err[Exception], attempt: int
307
+ ) -> Result[T, Exception] | Exception:
308
+ """Handle circuit breaker evaluation logic."""
309
+ if attempt == 1:
310
+ return self._apply_fallback(cb_err)
311
+ return cb_err.err_value
312
+
313
+ async def _execute_single_attempt(
314
+ self,
315
+ attempt: int,
316
+ fn: Callable[P, Awaitable[T]],
317
+ *args: P.args,
318
+ **kwargs: P.kwargs,
319
+ ) -> Result[T, Exception]:
320
+ """Execute a single attempt including timeout."""
321
+ result = await self._execute_with_timeout(fn, *args, **kwargs)
322
+ if isinstance(result, Ok):
323
+ self._record_success_outcome(attempt)
324
+ return result
325
+
326
+ def _check_circuit_breaker_for_attempt(
327
+ self, attempt: int
328
+ ) -> Result[T, Exception] | Exception | None:
329
+ """Evaluate circuit breaker for the current attempt."""
330
+ cb_err = self._evaluate_circuit_breaker()
331
+ if cb_err is not None:
332
+ return self._handle_circuit_breaker_open(cb_err, attempt)
333
+ return None
334
+
303
335
  async def _execute_with_retries(
304
336
  self,
305
337
  max_attempts: int,
@@ -307,22 +339,24 @@ class ResilienceOrchestrator(Generic[T]):
307
339
  *args: P.args,
308
340
  **kwargs: P.kwargs,
309
341
  ) -> Result[T, Exception]:
310
- last_error: Exception | None = None
342
+ last_error: Exception = RuntimeError("Execution failed")
311
343
  for attempt in range(1, max_attempts + 1):
312
- result = await self._execute_with_timeout(fn, *args, **kwargs)
344
+ cb_res = self._check_circuit_breaker_for_attempt(attempt)
345
+ if cb_res is not None:
346
+ if isinstance(cb_res, Exception):
347
+ last_error = cb_res
348
+ break
349
+ return cb_res
350
+
351
+ result = await self._execute_single_attempt(attempt, fn, *args, **kwargs)
313
352
  if isinstance(result, Ok):
314
- self._record_success_outcome(attempt)
315
353
  return result
316
354
 
317
355
  last_error = result.err_value
318
- if await self._handle_retry_failure(last_error, attempt, max_attempts):
319
- continue
320
- break
356
+ if not await self._handle_retry_failure(last_error, attempt, max_attempts):
357
+ break
321
358
 
322
- final_result: Result[T, Exception] = Err(
323
- last_error or RuntimeError("Execution failed")
324
- )
325
- return self._apply_fallback(final_result)
359
+ return self._apply_fallback(Err(last_error))
326
360
 
327
361
  async def _execute_with_timeout(
328
362
  self,