taipanstack 0.5.2__tar.gz → 0.5.3__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.2 → taipanstack-0.5.3}/PKG-INFO +10 -10
  2. {taipanstack-0.5.2 → taipanstack-0.5.3}/README.md +9 -9
  3. {taipanstack-0.5.2 → taipanstack-0.5.3}/pyproject.toml +1 -1
  4. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/__init__.py +1 -1
  5. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/bridges/_imports.py +2 -2
  6. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/bridges/db_bridge.py +4 -4
  7. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/bridges/http_bridge.py +26 -10
  8. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/bridges/web_bridge.py +2 -2
  9. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/config/models.py +3 -2
  10. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/core/optimizations.py +2 -2
  11. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/core/result.py +2 -1
  12. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/adaptive/adaptive_retry.py +1 -1
  13. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/adaptive/bulkhead.py +4 -4
  14. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/adaptive/orchestrator.py +97 -57
  15. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/circuit_breaker.py +74 -58
  16. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/resilience.py +26 -12
  17. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/retry.py +60 -11
  18. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/watchdogs/config_watcher.py +16 -8
  19. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/watchdogs/resource_watcher.py +5 -5
  20. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/security/decorators.py +1 -1
  21. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/security/guards.py +23 -17
  22. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/security/models.py +4 -4
  23. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/security/sanitizers.py +9 -5
  24. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/security/validators.py +7 -3
  25. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/utils/cache.py +8 -4
  26. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/utils/concurrency.py +4 -2
  27. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/utils/filesystem.py +2 -2
  28. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/utils/logging.py +24 -15
  29. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/utils/rate_limit.py +4 -2
  30. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/utils/subprocess.py +1 -1
  31. {taipanstack-0.5.2 → taipanstack-0.5.3}/LICENSE +0 -0
  32. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/bridges/__init__.py +0 -0
  33. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/config/__init__.py +0 -0
  34. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/config/generators.py +0 -0
  35. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/config/version_config.py +0 -0
  36. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/core/__init__.py +0 -0
  37. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/core/compat.py +0 -0
  38. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/__init__.py +0 -0
  39. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
  40. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +0 -0
  41. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
  42. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/watchdogs/_base.py +0 -0
  43. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/resilience/watchdogs/health_pinger.py +0 -0
  44. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/security/__init__.py +0 -0
  45. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/security/jwt.py +0 -0
  46. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/security/password.py +0 -0
  47. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/security/types.py +0 -0
  48. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/utils/__init__.py +0 -0
  49. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/utils/circuit_breaker.py +0 -0
  50. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/utils/context.py +0 -0
  51. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/utils/resilience.py +0 -0
  52. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/utils/retry.py +0 -0
  53. {taipanstack-0.5.2 → taipanstack-0.5.3}/src/taipanstack/utils/serialization.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.5.2
3
+ Version: 0.5.3
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -58,6 +58,7 @@ Description-Content-Type: text/markdown
58
58
  <div align="center">
59
59
 
60
60
  # 🐍 Taipan Stack
61
+ [![CI](https://img.shields.io/github/actions/workflow/status/gabrielima7/TaipanStack/ci-push-validate.yml?branch=main)](https://github.com/gabrielima7/TaipanStack/actions/workflows/ci-push-validate.yml)
61
62
 
62
63
  ### **The Modern Python Foundation**
63
64
 
@@ -87,12 +88,11 @@ Description-Content-Type: text/markdown
87
88
 
88
89
  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
90
 
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).
91
+ ### ✨ What's New in v0.5.3
92
+ - **Security Fixes & Hardening**: Fixed file descriptor leaks in `safe_write` on `BaseException` (PR #838). Hardened retry, fallback, and circuit breaker decorators/classes against runtime type mutations, clock jumps, and NaN state poisoning under chaos injection (PR #852, #853, #842, #856, #839, #864).
93
+ - **Complexity Refactor**: Reduced cyclomatic and cognitive complexity in orchestrators, circuit breakers, and logging/retry utils (PR #862, #844, #866).
94
+ - **QA & Test Count**: Standardized test naming conventions (PR #847), expanded test coverage to 100% genuine code and branch coverage across core components, verifying **1,344 passing tests** (PR #843, #857, #850).
95
+ - **Documentation & CI/CD**: Cleaned up dead references and links (PR #854, #851), updated watchdogs code examples (PR #867), and synchronized CI badges (PR #863).
96
96
 
97
97
  <table>
98
98
  <tr>
@@ -129,7 +129,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
129
129
 
130
130
  ### 🔧 Developer Experience
131
131
  - Pre-configured quality tools
132
- - **100% code coverage** (1,226 tests)
132
+ - **100% code coverage** (1,344 tests)
133
133
  - Architecture enforcement
134
134
  - Hardened Docker template
135
135
 
@@ -171,7 +171,7 @@ make all
171
171
  ### Verify Installation
172
172
 
173
173
  ```bash
174
- # Run tests with 100% coverage (1,226 tests)
174
+ # Run tests with 100% coverage (1,344 tests)
175
175
  make test
176
176
 
177
177
  # Check architecture contracts
@@ -224,7 +224,7 @@ TaipanStack/
224
224
  │ ├── config/ # ⚙️ Configuration models & generators
225
225
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
226
226
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
227
- ├── tests/ # ✅ 1,226 tests, 100% coverage
227
+ ├── tests/ # ✅ 1,344 tests, 100% coverage
228
228
  ├── .semgrep/ # 🔍 Custom SAST rules
229
229
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
230
230
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -1,6 +1,7 @@
1
1
  <div align="center">
2
2
 
3
3
  # 🐍 Taipan Stack
4
+ [![CI](https://img.shields.io/github/actions/workflow/status/gabrielima7/TaipanStack/ci-push-validate.yml?branch=main)](https://github.com/gabrielima7/TaipanStack/actions/workflows/ci-push-validate.yml)
4
5
 
5
6
  ### **The Modern Python Foundation**
6
7
 
@@ -30,12 +31,11 @@
30
31
 
31
32
  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
33
 
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).
34
+ ### ✨ What's New in v0.5.3
35
+ - **Security Fixes & Hardening**: Fixed file descriptor leaks in `safe_write` on `BaseException` (PR #838). Hardened retry, fallback, and circuit breaker decorators/classes against runtime type mutations, clock jumps, and NaN state poisoning under chaos injection (PR #852, #853, #842, #856, #839, #864).
36
+ - **Complexity Refactor**: Reduced cyclomatic and cognitive complexity in orchestrators, circuit breakers, and logging/retry utils (PR #862, #844, #866).
37
+ - **QA & Test Count**: Standardized test naming conventions (PR #847), expanded test coverage to 100% genuine code and branch coverage across core components, verifying **1,344 passing tests** (PR #843, #857, #850).
38
+ - **Documentation & CI/CD**: Cleaned up dead references and links (PR #854, #851), updated watchdogs code examples (PR #867), and synchronized CI badges (PR #863).
39
39
 
40
40
  <table>
41
41
  <tr>
@@ -72,7 +72,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
72
72
 
73
73
  ### 🔧 Developer Experience
74
74
  - Pre-configured quality tools
75
- - **100% code coverage** (1,226 tests)
75
+ - **100% code coverage** (1,344 tests)
76
76
  - Architecture enforcement
77
77
  - Hardened Docker template
78
78
 
@@ -114,7 +114,7 @@ make all
114
114
  ### Verify Installation
115
115
 
116
116
  ```bash
117
- # Run tests with 100% coverage (1,226 tests)
117
+ # Run tests with 100% coverage (1,344 tests)
118
118
  make test
119
119
 
120
120
  # Check architecture contracts
@@ -167,7 +167,7 @@ TaipanStack/
167
167
  │ ├── config/ # ⚙️ Configuration models & generators
168
168
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
169
169
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
170
- ├── tests/ # ✅ 1,226 tests, 100% coverage
170
+ ├── tests/ # ✅ 1,344 tests, 100% coverage
171
171
  ├── .semgrep/ # 🔍 Custom SAST rules
172
172
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
173
173
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.5.2"
3
+ version = "0.5.3"
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"}
@@ -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.2"
8
+ __version__ = "0.5.3"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -42,8 +42,8 @@ def require_dependency(
42
42
  return Err(
43
43
  ImportError(
44
44
  f"'{module_name}' is required but not installed. "
45
- f"Install with: {install_hint}"
46
- )
45
+ f"Install with: {install_hint}",
46
+ ),
47
47
  )
48
48
 
49
49
 
@@ -166,8 +166,8 @@ class ResilientDatabase:
166
166
  return Err(
167
167
  ImportError(
168
168
  "sqlalchemy is required for ResilientDatabase. "
169
- "Install with: pip install taipanstack[bridges-db]"
170
- )
169
+ "Install with: pip install taipanstack[bridges-db]",
170
+ ),
171
171
  )
172
172
 
173
173
  # Circuit breaker gate
@@ -236,8 +236,8 @@ class ResilientRedis:
236
236
  return Err(
237
237
  ImportError(
238
238
  "redis is required for ResilientRedis. "
239
- "Install with: pip install taipanstack[bridges-db]"
240
- )
239
+ "Install with: pip install taipanstack[bridges-db]",
240
+ ),
241
241
  )
242
242
  return Ok(None)
243
243
 
@@ -192,7 +192,11 @@ async def _execute_single_attempt(
192
192
  return Ok(response)
193
193
  except Exception as exc:
194
194
  should_retry = await _handle_http_exception(
195
- exc, attempt, max_attempts, retry_config, circuit_breaker
195
+ exc,
196
+ attempt,
197
+ max_attempts,
198
+ retry_config,
199
+ circuit_breaker,
196
200
  )
197
201
  if should_retry:
198
202
  return exc
@@ -268,8 +272,8 @@ async def safe_request(
268
272
  return Err(
269
273
  ImportError(
270
274
  "httpx is required for HTTP bridge. "
271
- "Install with: pip install taipanstack[bridges-http]"
272
- )
275
+ "Install with: pip install taipanstack[bridges-http]",
276
+ ),
273
277
  )
274
278
 
275
279
  # SSRF check
@@ -286,7 +290,8 @@ async def safe_request(
286
290
  async def _do_request() -> httpx.Response:
287
291
  async with httpx.AsyncClient(timeout=timeout) as client: # nosemgrep
288
292
  request_func = cast(
289
- Callable[..., Awaitable[httpx.Response]], client.request
293
+ Callable[..., Awaitable[httpx.Response]],
294
+ client.request,
290
295
  )
291
296
  response = await request_func(method, url, **kwargs)
292
297
  return response
@@ -406,7 +411,8 @@ class SafeHttpClient:
406
411
  # We explicitly verified client is not None above
407
412
  client: httpx.AsyncClient = cast(httpx.AsyncClient, self._client)
408
413
  request_func = cast(
409
- Callable[..., Awaitable[httpx.Response]], client.request
414
+ Callable[..., Awaitable[httpx.Response]],
415
+ client.request,
410
416
  )
411
417
  response = await request_func(method, url, **kwargs)
412
418
  return response
@@ -419,31 +425,41 @@ class SafeHttpClient:
419
425
  )
420
426
 
421
427
  async def get(
422
- self, url: str, **kw: Unpack[HttpRequestKwargs]
428
+ self,
429
+ url: str,
430
+ **kw: Unpack[HttpRequestKwargs],
423
431
  ) -> Result[httpx.Response, Exception]:
424
432
  """Send a GET request."""
425
433
  return await self.request("GET", url, **kw)
426
434
 
427
435
  async def post(
428
- self, url: str, **kw: Unpack[HttpRequestKwargs]
436
+ self,
437
+ url: str,
438
+ **kw: Unpack[HttpRequestKwargs],
429
439
  ) -> Result[httpx.Response, Exception]:
430
440
  """Send a POST request."""
431
441
  return await self.request("POST", url, **kw)
432
442
 
433
443
  async def put(
434
- self, url: str, **kw: Unpack[HttpRequestKwargs]
444
+ self,
445
+ url: str,
446
+ **kw: Unpack[HttpRequestKwargs],
435
447
  ) -> Result[httpx.Response, Exception]:
436
448
  """Send a PUT request."""
437
449
  return await self.request("PUT", url, **kw)
438
450
 
439
451
  async def delete(
440
- self, url: str, **kw: Unpack[HttpRequestKwargs]
452
+ self,
453
+ url: str,
454
+ **kw: Unpack[HttpRequestKwargs],
441
455
  ) -> Result[httpx.Response, Exception]:
442
456
  """Send a DELETE request."""
443
457
  return await self.request("DELETE", url, **kw)
444
458
 
445
459
  async def patch(
446
- self, url: str, **kw: Unpack[HttpRequestKwargs]
460
+ self,
461
+ url: str,
462
+ **kw: Unpack[HttpRequestKwargs],
447
463
  ) -> Result[httpx.Response, Exception]:
448
464
  """Send a PATCH request."""
449
465
  return await self.request("PATCH", url, **kw)
@@ -124,13 +124,13 @@ async def _send_json_response(
124
124
  "type": "http.response.start",
125
125
  "status": status,
126
126
  "headers": headers,
127
- }
127
+ },
128
128
  )
129
129
  await send(
130
130
  {
131
131
  "type": "http.response.body",
132
132
  "body": payload,
133
- }
133
+ },
134
134
  )
135
135
 
136
136
 
@@ -44,7 +44,8 @@ class SecurityConfig(BaseModel):
44
44
  enable_pip_audit: bool = Field(default=True, description="Enable pip-audit SCA")
45
45
  enable_semgrep: bool = Field(default=True, description="Enable Semgrep")
46
46
  enable_detect_secrets: bool = Field(
47
- default=True, description="Enable secret detection"
47
+ default=True,
48
+ description="Enable secret detection",
48
49
  )
49
50
  bandit_severity: Literal["low", "medium", "high"] = Field(
50
51
  default="low",
@@ -299,7 +300,7 @@ class StackConfig(BaseModel):
299
300
  self.security.enable_pip_audit,
300
301
  self.security.enable_semgrep,
301
302
  self.security.enable_detect_secrets,
302
- ]
303
+ ],
303
304
  )
304
305
  if self.security.level == "paranoid" and not all_tools_enabled:
305
306
  msg = "Paranoid security level requires all security tools enabled."
@@ -259,7 +259,7 @@ def _apply_gc_tuning(
259
259
  applied.append(
260
260
  f"gc_threshold: {current} -> "
261
261
  f"({profile.gc_threshold_0}, {profile.gc_threshold_1}, "
262
- f"{profile.gc_threshold_2})"
262
+ f"{profile.gc_threshold_2})",
263
263
  )
264
264
  except Exception as e:
265
265
  errors.append(f"gc_threshold: {e}")
@@ -301,7 +301,7 @@ def _apply_experimental(
301
301
  if features.has_free_threading:
302
302
  applied.append("free_threading: available")
303
303
  logger.warning(
304
- "EXPERIMENTAL FEATURES ENABLED: Stability and security may be affected."
304
+ "EXPERIMENTAL FEATURES ENABLED: Stability and security may be affected.",
305
305
  )
306
306
  else:
307
307
  skipped.append("experimental: requires STACK_ENABLE_EXPERIMENTAL=1")
@@ -126,7 +126,8 @@ class SafeFromDecorator(Protocol[E_co]):
126
126
 
127
127
  @overload
128
128
  def __call__(
129
- self, func: Callable[P, Awaitable[T]]
129
+ self,
130
+ func: Callable[P, Awaitable[T]],
130
131
  ) -> Callable[P, Awaitable[Result[T, E_co]]]: ...
131
132
 
132
133
 
@@ -92,7 +92,7 @@ class AdaptiveRetry:
92
92
  self._outcomes: deque[_Outcome] = deque(maxlen=window_size)
93
93
  # Per-attempt successful delays
94
94
  self._success_delays: dict[int, deque[float]] = defaultdict(
95
- lambda: deque(maxlen=window_size)
95
+ lambda: deque(maxlen=window_size),
96
96
  )
97
97
 
98
98
  def record_outcome(
@@ -38,7 +38,7 @@ class BulkheadFullError(Exception):
38
38
  self.max_queue = max_queue
39
39
  super().__init__(
40
40
  f"Bulkhead '{name}' is full "
41
- f"(max_concurrent={max_concurrent}, max_queue={max_queue})"
41
+ f"(max_concurrent={max_concurrent}, max_queue={max_queue})",
42
42
  )
43
43
 
44
44
 
@@ -127,7 +127,7 @@ class Bulkhead:
127
127
  self.name,
128
128
  self._max_concurrent,
129
129
  self._max_queue,
130
- )
130
+ ),
131
131
  )
132
132
 
133
133
  self._queued += 1
@@ -142,8 +142,8 @@ class Bulkhead:
142
142
  return Err(
143
143
  TimeoutError(
144
144
  f"Bulkhead '{self.name}' timed out "
145
- f"after {self._timeout}s waiting for permit"
146
- )
145
+ f"after {self._timeout}s waiting for permit",
146
+ ),
147
147
  )
148
148
  except (RuntimeError, OSError, MemoryError) as e:
149
149
  return Err(RuntimeError(f"Resource exhaustion: {e!s}"))
@@ -165,7 +165,54 @@ class ResilienceOrchestrator(Generic[T]):
165
165
  self._fallback_value = value
166
166
  return self
167
167
 
168
- async def execute( # noqa: PLR0911
168
+ async def _acquire_bulkhead(self, bh: Bulkhead) -> Result[None, Exception]:
169
+ """Attempt to acquire a bulkhead permit, handling timeouts and errors."""
170
+ try:
171
+ await asyncio.wait_for(
172
+ bh._semaphore.acquire(),
173
+ timeout=bh._timeout,
174
+ )
175
+ return Ok(None)
176
+ except TimeoutError:
177
+ return Err(
178
+ TimeoutError(f"Bulkhead '{bh.name}' timed out after {bh._timeout}s")
179
+ )
180
+ except (RuntimeError, OSError, MemoryError) as e:
181
+ return Err(RuntimeError(f"Resource exhaustion: {e!s}"))
182
+
183
+ async def _execute_with_bulkhead(
184
+ self,
185
+ bh: Bulkhead,
186
+ fn: Callable[P, Awaitable[T]],
187
+ *args: P.args,
188
+ **kwargs: P.kwargs,
189
+ ) -> Result[T, Exception]:
190
+ """Execute through the bulkhead layer."""
191
+ if bh.queued >= bh._max_queue:
192
+ result: Result[T, Exception] = Err(
193
+ BulkheadFullError(bh.name, bh._max_concurrent, bh._max_queue),
194
+ )
195
+ return self._apply_fallback(result)
196
+
197
+ bh._queued += 1
198
+ try:
199
+ acquire_result = await self._acquire_bulkhead(bh)
200
+ if isinstance(acquire_result, Err):
201
+ return self._apply_fallback(cast(Result[T, Exception], acquire_result))
202
+ finally:
203
+ bh._queued -= 1
204
+
205
+ bh._active += 1
206
+ try:
207
+ try:
208
+ return await self._execute_inner(fn, *args, **kwargs)
209
+ except Exception as exc:
210
+ return self._apply_fallback(Err(exc))
211
+ finally:
212
+ bh._active -= 1
213
+ bh._semaphore.release()
214
+
215
+ async def execute(
169
216
  self,
170
217
  fn: Callable[P, Awaitable[T]],
171
218
  *args: P.args,
@@ -186,44 +233,12 @@ class ResilienceOrchestrator(Generic[T]):
186
233
  """
187
234
  # Layer 1: Bulkhead — use semaphore directly to avoid double-wrapping
188
235
  if self._bulkhead is not None:
189
- bh = self._bulkhead
190
- if bh.queued >= bh._max_queue:
191
- result: Result[T, Exception] = Err(
192
- BulkheadFullError(bh.name, bh._max_concurrent, bh._max_queue)
193
- )
194
- return self._apply_fallback(result)
195
-
196
- bh._queued += 1
197
- try:
198
- try:
199
- await asyncio.wait_for(
200
- bh._semaphore.acquire(),
201
- timeout=bh._timeout,
202
- )
203
- except TimeoutError:
204
- return self._apply_fallback(
205
- Err(
206
- TimeoutError(
207
- f"Bulkhead '{bh.name}' timed out after {bh._timeout}s"
208
- )
209
- )
210
- )
211
- except (RuntimeError, OSError, MemoryError) as e:
212
- return self._apply_fallback(
213
- Err(RuntimeError(f"Resource exhaustion: {e!s}"))
214
- )
215
- finally:
216
- bh._queued -= 1
217
-
218
- bh._active += 1
219
- try:
220
- try:
221
- return await self._execute_inner(fn, *args, **kwargs)
222
- except Exception as exc:
223
- return self._apply_fallback(Err(exc))
224
- finally:
225
- bh._active -= 1
226
- bh._semaphore.release()
236
+ return await self._execute_with_bulkhead(
237
+ self._bulkhead,
238
+ fn,
239
+ *args,
240
+ **kwargs,
241
+ )
227
242
 
228
243
  try:
229
244
  return await self._execute_inner(fn, *args, **kwargs)
@@ -238,14 +253,14 @@ class ResilienceOrchestrator(Generic[T]):
238
253
  CircuitBreakerError(
239
254
  f"Circuit '{self._adaptive_breaker.name}' is open",
240
255
  state=self._adaptive_breaker.state,
241
- )
256
+ ),
242
257
  )
243
258
  elif self._breaker is not None and not self._breaker._should_attempt():
244
259
  return Err(
245
260
  CircuitBreakerError(
246
261
  f"Circuit '{self._breaker.name}' is open",
247
262
  state=self._breaker.state,
248
- )
263
+ ),
249
264
  )
250
265
  return None
251
266
 
@@ -303,7 +318,9 @@ class ResilienceOrchestrator(Generic[T]):
303
318
  return False
304
319
 
305
320
  def _handle_circuit_breaker_open(
306
- self, cb_err: Err[Exception], attempt: int
321
+ self,
322
+ cb_err: Err[Exception],
323
+ attempt: int,
307
324
  ) -> Result[T, Exception] | Exception:
308
325
  """Handle circuit breaker evaluation logic."""
309
326
  if attempt == 1:
@@ -324,7 +341,8 @@ class ResilienceOrchestrator(Generic[T]):
324
341
  return result
325
342
 
326
343
  def _check_circuit_breaker_for_attempt(
327
- self, attempt: int
344
+ self,
345
+ attempt: int,
328
346
  ) -> Result[T, Exception] | Exception | None:
329
347
  """Evaluate circuit breaker for the current attempt."""
330
348
  cb_err = self._evaluate_circuit_breaker()
@@ -332,6 +350,31 @@ class ResilienceOrchestrator(Generic[T]):
332
350
  return self._handle_circuit_breaker_open(cb_err, attempt)
333
351
  return None
334
352
 
353
+ async def _process_retry_attempt(
354
+ self,
355
+ attempt: int,
356
+ max_attempts: int,
357
+ fn: Callable[P, Awaitable[T]],
358
+ *args: P.args,
359
+ **kwargs: P.kwargs,
360
+ ) -> Result[T, Exception] | tuple[bool, Exception]:
361
+ """Process a single retry attempt including circuit breaker check."""
362
+ cb_res = self._check_circuit_breaker_for_attempt(attempt)
363
+ if cb_res is not None:
364
+ if isinstance(cb_res, Exception):
365
+ return False, cb_res
366
+ return cb_res
367
+
368
+ result = await self._execute_single_attempt(attempt, fn, *args, **kwargs)
369
+ if isinstance(result, Ok):
370
+ return result
371
+
372
+ last_error = result.err_value
373
+ should_continue = await self._handle_retry_failure(
374
+ last_error, attempt, max_attempts
375
+ )
376
+ return should_continue, last_error
377
+
335
378
  async def _execute_with_retries(
336
379
  self,
337
380
  max_attempts: int,
@@ -341,19 +384,14 @@ class ResilienceOrchestrator(Generic[T]):
341
384
  ) -> Result[T, Exception]:
342
385
  last_error: Exception = RuntimeError("Execution failed")
343
386
  for attempt in range(1, max_attempts + 1):
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)
352
- if isinstance(result, Ok):
353
- return result
354
-
355
- last_error = result.err_value
356
- if not await self._handle_retry_failure(last_error, attempt, max_attempts):
387
+ outcome = await self._process_retry_attempt(
388
+ attempt, max_attempts, fn, *args, **kwargs
389
+ )
390
+ if not isinstance(outcome, tuple):
391
+ return outcome
392
+
393
+ should_continue, last_error = outcome
394
+ if not should_continue:
357
395
  break
358
396
 
359
397
  return self._apply_fallback(Err(last_error))
@@ -389,7 +427,9 @@ class ResilienceOrchestrator(Generic[T]):
389
427
  return Ok(result)
390
428
  except TimeoutError:
391
429
  return Err(
392
- TimeoutError(f"Pipeline '{self.name}' timed out after {self._timeout}s")
430
+ TimeoutError(
431
+ f"Pipeline '{self.name}' timed out after {self._timeout}s"
432
+ ),
393
433
  )
394
434
  except Exception as exc:
395
435
  return Err(exc)