taipanstack 0.4.4__tar.gz → 0.4.6__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.4.4 → taipanstack-0.4.6}/PKG-INFO +11 -8
  2. {taipanstack-0.4.4 → taipanstack-0.4.6}/README.md +9 -7
  3. {taipanstack-0.4.4 → taipanstack-0.4.6}/pyproject.toml +4 -12
  4. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/__init__.py +1 -1
  5. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/bridges/_imports.py +1 -1
  6. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/bridges/db_bridge.py +6 -6
  7. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/bridges/http_bridge.py +11 -5
  8. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/config/generators.py +0 -1
  9. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/core/compat.py +2 -2
  10. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/core/result.py +19 -10
  11. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +0 -1
  12. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/adaptive/adaptive_retry.py +0 -1
  13. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/circuit_breaker.py +81 -39
  14. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/resilience.py +10 -10
  15. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/retry.py +35 -16
  16. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/watchdogs/_base.py +1 -1
  17. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/watchdogs/config_watcher.py +1 -1
  18. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/security/decorators.py +2 -2
  19. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/security/guards.py +80 -41
  20. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/security/jwt.py +7 -18
  21. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/security/models.py +6 -8
  22. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/security/sanitizers.py +42 -26
  23. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/utils/cache.py +23 -4
  24. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/utils/concurrency.py +26 -20
  25. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/utils/logging.py +1 -1
  26. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/utils/rate_limit.py +44 -8
  27. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/utils/subprocess.py +26 -15
  28. {taipanstack-0.4.4 → taipanstack-0.4.6}/LICENSE +0 -0
  29. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/bridges/__init__.py +0 -0
  30. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/bridges/web_bridge.py +0 -0
  31. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/config/__init__.py +0 -0
  32. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/config/models.py +0 -0
  33. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/config/version_config.py +0 -0
  34. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/core/__init__.py +0 -0
  35. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/core/optimizations.py +0 -0
  36. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/__init__.py +0 -0
  37. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
  38. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/adaptive/bulkhead.py +0 -0
  39. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/adaptive/orchestrator.py +0 -0
  40. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
  41. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/watchdogs/health_pinger.py +0 -0
  42. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/resilience/watchdogs/resource_watcher.py +0 -0
  43. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/security/__init__.py +0 -0
  44. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/security/password.py +0 -0
  45. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/security/types.py +0 -0
  46. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/security/validators.py +0 -0
  47. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/utils/__init__.py +0 -0
  48. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/utils/circuit_breaker.py +0 -0
  49. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/utils/context.py +0 -0
  50. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/utils/filesystem.py +0 -0
  51. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/utils/resilience.py +0 -0
  52. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/utils/retry.py +0 -0
  53. {taipanstack-0.4.4 → taipanstack-0.4.6}/src/taipanstack/utils/serialization.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.4.4
3
+ Version: 0.4.6
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -33,6 +33,7 @@ Requires-Dist: httpx (>=0.24.0) ; extra == "bridges-http"
33
33
  Requires-Dist: litestar (>=2.0.0) ; extra == "all"
34
34
  Requires-Dist: litestar (>=2.0.0) ; extra == "bridges-web"
35
35
  Requires-Dist: orjson (>=3.9.0)
36
+ Requires-Dist: pip (>=26.1,<27.0)
36
37
  Requires-Dist: psutil (>=5.9.0) ; extra == "all"
37
38
  Requires-Dist: psutil (>=5.9.0) ; extra == "resilience"
38
39
  Requires-Dist: pydantic (>=2.0)
@@ -86,10 +87,12 @@ Description-Content-Type: text/markdown
86
87
 
87
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.
88
89
 
89
- ### ✨ What's New in v0.4.3
90
- - **Strict Static Typing**: Project-wide refactoring to eliminate all `Any` types, ensuring 100% type safety with `Mypy` strict mode.
91
- - **SSRF & DoS Hardening**: Mitigates `urlparse` SSRF risks and algorithmic complexity DoS via bounded length and value validation.
92
- - **Total Core Coverage**: Achieved true 100% branch and statement coverage in the core result module with 1,207 passing tests.
90
+ ### ✨ What's New in v0.4.6
91
+ - **Security Hardening**: Patched TOCTOU, DoS in file extensions, and unbounded cache growth vulnerabilities (PR #651, #658, #646, #640).
92
+ - **100% Real Coverage**: Eliminated all `pragma: no cover` bypasses for true 100% genuine code coverage (PR #644, #654).
93
+ - **CI/CD Zero-Bypass**: Audited and hardened all pipelines to enforce strict zero-bypass execution (PR #643, #653, #639).
94
+ - **Resilience Chaos**: Reinforced `RateLimiter` and `@timeout` against massive time jumps and thread exhaustion (PR #642, #638).
95
+ - **Total Stack Coverage**: Reached **1,290 passing tests** with 100% verified genuine coverage across all modules.
93
96
 
94
97
  <table>
95
98
  <tr>
@@ -127,7 +130,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
127
130
 
128
131
  ### 🔧 Developer Experience
129
132
  - Pre-configured quality tools
130
- - **100% code coverage** (1207 tests)
133
+ - **100% code coverage** (1290 tests)
131
134
  - Architecture enforcement
132
135
  - Hardened Docker template
133
136
 
@@ -169,7 +172,7 @@ make all
169
172
  ### Verify Installation
170
173
 
171
174
  ```bash
172
- # Run tests with 100% coverage (1207 tests)
175
+ # Run tests with 100% coverage (1290 tests)
173
176
  make test
174
177
 
175
178
  # Check architecture contracts
@@ -224,7 +227,7 @@ TaipanStack/
224
227
  │ ├── config/ # ⚙️ Configuration models & generators
225
228
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
226
229
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
227
- ├── tests/ # ✅ 1207 tests, 100% coverage
230
+ ├── tests/ # ✅ 1290 tests, 100% coverage
228
231
  ├── .semgrep/ # 🔍 Custom SAST rules
229
232
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
230
233
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -30,10 +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.4.3
34
- - **Strict Static Typing**: Project-wide refactoring to eliminate all `Any` types, ensuring 100% type safety with `Mypy` strict mode.
35
- - **SSRF & DoS Hardening**: Mitigates `urlparse` SSRF risks and algorithmic complexity DoS via bounded length and value validation.
36
- - **Total Core Coverage**: Achieved true 100% branch and statement coverage in the core result module with 1,207 passing tests.
33
+ ### ✨ What's New in v0.4.6
34
+ - **Security Hardening**: Patched TOCTOU, DoS in file extensions, and unbounded cache growth vulnerabilities (PR #651, #658, #646, #640).
35
+ - **100% Real Coverage**: Eliminated all `pragma: no cover` bypasses for true 100% genuine code coverage (PR #644, #654).
36
+ - **CI/CD Zero-Bypass**: Audited and hardened all pipelines to enforce strict zero-bypass execution (PR #643, #653, #639).
37
+ - **Resilience Chaos**: Reinforced `RateLimiter` and `@timeout` against massive time jumps and thread exhaustion (PR #642, #638).
38
+ - **Total Stack Coverage**: Reached **1,290 passing tests** with 100% verified genuine coverage across all modules.
37
39
 
38
40
  <table>
39
41
  <tr>
@@ -71,7 +73,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
71
73
 
72
74
  ### 🔧 Developer Experience
73
75
  - Pre-configured quality tools
74
- - **100% code coverage** (1207 tests)
76
+ - **100% code coverage** (1290 tests)
75
77
  - Architecture enforcement
76
78
  - Hardened Docker template
77
79
 
@@ -113,7 +115,7 @@ make all
113
115
  ### Verify Installation
114
116
 
115
117
  ```bash
116
- # Run tests with 100% coverage (1207 tests)
118
+ # Run tests with 100% coverage (1290 tests)
117
119
  make test
118
120
 
119
121
  # Check architecture contracts
@@ -168,7 +170,7 @@ TaipanStack/
168
170
  │ ├── config/ # ⚙️ Configuration models & generators
169
171
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
170
172
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
171
- ├── tests/ # ✅ 1207 tests, 100% coverage
173
+ ├── tests/ # ✅ 1290 tests, 100% coverage
172
174
  ├── .semgrep/ # 🔍 Custom SAST rules
173
175
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
174
176
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.4.4"
3
+ version = "0.4.6"
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"}
@@ -29,6 +29,7 @@ dependencies = [
29
29
  "result (>=0.17.0)",
30
30
  "pyjwt (>=2.11.0,<3.0.0)",
31
31
  "argon2-cffi (>=25.1.0,<26.0.0)",
32
+ "pip (>=26.1,<27.0)",
32
33
  ]
33
34
 
34
35
  [project.urls]
@@ -104,21 +105,12 @@ dev = [
104
105
  # CVSS 1.9/10 Low - local attack vector only, no upstream patch available yet
105
106
  # Pinned to latest available; monitor for upstream fix in pygments >2.19.2
106
107
  "pygments (>=2.19.2)",
107
- # Security note: CVE-2026-3219 affects pip 26.0.1 (confused install via concatenated tar+ZIP).
108
- # CVSS Moderate - no pip fix published yet (expected in pip>=26.1).
109
- # pip-audit ignores this CVE explicitly via --ignore-vuln in CI and Makefile.
110
- # Monitor: https://github.com/pypa/pip/issues — Remove ignore once pip>=26.1 is available.
111
- #
112
- # Security note: PYSEC-2022-42969 affects py 1.11.0 (ReDoS via svn blame parsing).
113
- # py is a transitive dependency of pytest with no upstream fix version published.
114
- # Attack vector is local (requires attacker-controlled SVN output). Low real-world risk.
115
- # pip-audit ignores this via --ignore-vuln in CI and Makefile.
116
- # Monitor: https://github.com/pytest-dev/py/issues — Remove ignore if fix is published.
117
108
  "hypothesis (>=6.151.12,<7.0.0)",
118
109
  "authlib (>=1.6.11,<2.0.0)",
119
- "cryptography (>=46.0.7,<47.0.0)",
110
+ "cryptography (>=46.0.7,<48.0.0)",
120
111
  "nltk (>=3.9.4,<4.0.0)",
121
112
  "mutmut (>=3.0.0,<4.0.0)",
113
+ "pip (>=26.1,<27.0)",
122
114
  ]
123
115
 
124
116
 
@@ -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.4.4"
8
+ __version__ = "0.4.6"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -31,7 +31,7 @@ def require_dependency(
31
31
 
32
32
  """
33
33
  try:
34
- mod = importlib.import_module(module_name)
34
+ mod = importlib.import_module(module_name) # nosem
35
35
  return Ok(mod)
36
36
  except ImportError:
37
37
  install_hint = (
@@ -25,18 +25,18 @@ logger = logging.getLogger("taipanstack.bridges.db")
25
25
 
26
26
  try:
27
27
  import sqlalchemy # noqa: F401
28
- from sqlalchemy import text as sa_text # pragma: no cover
29
- from sqlalchemy.ext.asyncio import AsyncSession # pragma: no cover
28
+ from sqlalchemy import text as sa_text
29
+ from sqlalchemy.ext.asyncio import AsyncSession
30
30
 
31
- _HAS_SQLALCHEMY = True # pragma: no cover
32
- except ImportError: # pragma: no cover
31
+ _HAS_SQLALCHEMY = True
32
+ except ImportError:
33
33
  _HAS_SQLALCHEMY = False
34
34
 
35
35
  try:
36
36
  import redis.asyncio as aioredis
37
37
 
38
- _HAS_REDIS = True # pragma: no cover
39
- except ImportError: # pragma: no cover
38
+ _HAS_REDIS = True
39
+ except ImportError:
40
40
  _HAS_REDIS = False
41
41
 
42
42
  if TYPE_CHECKING:
@@ -11,7 +11,7 @@ from __future__ import annotations
11
11
  import asyncio
12
12
  import logging
13
13
  from collections.abc import Awaitable, Callable, Mapping, Sequence
14
- from typing import TYPE_CHECKING, Any, cast
14
+ from typing import TYPE_CHECKING, cast
15
15
 
16
16
  from typing_extensions import TypedDict, Unpack
17
17
 
@@ -80,8 +80,8 @@ class HttpClientKwargs(TypedDict, total=False):
80
80
  try:
81
81
  import httpx
82
82
 
83
- _HAS_HTTPX = True # pragma: no cover
84
- except ImportError: # pragma: no cover
83
+ _HAS_HTTPX = True
84
+ except ImportError:
85
85
  _HAS_HTTPX = False
86
86
 
87
87
  if TYPE_CHECKING:
@@ -261,7 +261,10 @@ async def safe_request(
261
261
 
262
262
  async def _do_request() -> httpx.Response:
263
263
  async with httpx.AsyncClient(timeout=timeout) as client: # nosemgrep
264
- response = await client.request(method, url, **cast(dict[str, Any], kwargs))
264
+ request_func = cast(
265
+ Callable[..., Awaitable[httpx.Response]], client.request
266
+ )
267
+ response = await request_func(method, url, **kwargs)
265
268
  return response
266
269
 
267
270
  return await _execute_with_retries(
@@ -379,7 +382,10 @@ class SafeHttpClient:
379
382
  async def _do_request() -> httpx.Response:
380
383
  # We explicitly verified client is not None above
381
384
  client: httpx.AsyncClient = cast(httpx.AsyncClient, self._client)
382
- response = await client.request(method, url, **cast(dict[str, Any], kwargs))
385
+ request_func = cast(
386
+ Callable[..., Awaitable[httpx.Response]], client.request
387
+ )
388
+ response = await request_func(method, url, **kwargs)
383
389
  return response
384
390
 
385
391
  return await _execute_with_retries(
@@ -121,7 +121,6 @@ omit = ["*/tests/*", "*/__pycache__/*"]
121
121
 
122
122
  [tool.coverage.report]
123
123
  exclude_lines = [
124
- "pragma: no cover",
125
124
  "def __repr__",
126
125
  "raise NotImplementedError",
127
126
  "if TYPE_CHECKING:",
@@ -80,7 +80,7 @@ def _check_jit_available() -> bool:
80
80
 
81
81
  JIT is available in Python 3.13+ when built with --enable-experimental-jit.
82
82
  """
83
- if not PY313: # pragma: no cover
83
+ if not PY313:
84
84
  return False
85
85
 
86
86
  try:
@@ -96,7 +96,7 @@ def _check_free_threading_available() -> bool:
96
96
 
97
97
  Free-threading is available in Python 3.13+ experimental builds.
98
98
  """
99
- if not PY313: # pragma: no cover
99
+ if not PY313:
100
100
  return False
101
101
 
102
102
  try:
@@ -85,7 +85,13 @@ def safe(
85
85
  Err(ValueError("invalid literal for int()..."))
86
86
 
87
87
  """
88
+ # Pre-cache constructors for minor speedup in tight loops
89
+ # (LOAD_DEREF is faster than LOAD_GLOBAL)
90
+ ok_cls = Ok
91
+ err_cls = Err
92
+
88
93
  if inspect.iscoroutinefunction(func):
94
+ # Cast once here to satisfy mypy inside the closure
89
95
  func_coro = cast(Callable[P, Awaitable[T]], func)
90
96
 
91
97
  @functools.wraps(func)
@@ -94,20 +100,21 @@ def safe(
94
100
  **kwargs: P.kwargs,
95
101
  ) -> Result[T, Exception]:
96
102
  try:
97
- return Ok(await func_coro(*args, **kwargs))
103
+ return ok_cls(await func_coro(*args, **kwargs))
98
104
  except Exception as e:
99
- return Err(e)
105
+ return err_cls(e)
100
106
 
101
107
  return cast(Callable[P, Awaitable[Result[T, Exception]]], async_wrapper)
102
108
 
109
+ # Cast once here to satisfy mypy inside the closure
103
110
  func_sync = cast(Callable[P, T], func)
104
111
 
105
112
  @functools.wraps(func)
106
113
  def wrapper(*args: P.args, **kwargs: P.kwargs) -> Result[T, Exception]:
107
114
  try:
108
- return Ok(func_sync(*args, **kwargs))
115
+ return ok_cls(func_sync(*args, **kwargs))
109
116
  except Exception as e:
110
- return Err(e)
117
+ return err_cls(e)
111
118
 
112
119
  return cast(Callable[P, Result[T, Exception]], wrapper)
113
120
 
@@ -202,19 +209,21 @@ def collect_results(
202
209
  except AttributeError:
203
210
  pass
204
211
 
212
+ ok_cls = Ok
213
+ err_cls = Err
205
214
  values: list[T] = []
206
215
  append = values.append
207
216
  for result in results:
208
- # We explicitly avoid structural pattern matching here to eliminate
209
- # Python overhead in tight loop iteration for Result arrays, but we
210
- # use isinstance rather than explicit type check to maintain subclass support.
211
- if isinstance(result, Ok):
217
+ # We use explicit type checks (isinstance) but pre-cache the constructors.
218
+ # type(result) is ok_cls would be even faster but breaks subclassing.
219
+ if isinstance(result, ok_cls):
212
220
  append(result.ok_value)
213
- elif isinstance(result, Err):
221
+ elif isinstance(result, err_cls):
214
222
  return result
215
223
  else:
224
+ # Fallback for structural compatibility
216
225
  return result
217
- return Ok(values)
226
+ return ok_cls(values)
218
227
 
219
228
 
220
229
  @overload
@@ -76,7 +76,6 @@ class AdaptiveCircuitBreaker:
76
76
  ) -> None:
77
77
  """Initialize the adaptive circuit breaker."""
78
78
  self.name = name
79
- self._window_size = window_size
80
79
  self._min_throughput = min_throughput
81
80
  self._target_error_rate = target_error_rate
82
81
  if not math.isfinite(recovery_timeout) or recovery_timeout < 0:
@@ -85,7 +85,6 @@ class AdaptiveRetry:
85
85
  """
86
86
  self._min_delay = min_delay
87
87
  self._max_delay = max_delay
88
- self._window_size = window_size
89
88
  self._max_attempts = max_attempts
90
89
  self._lock = threading.Lock()
91
90
 
@@ -27,12 +27,12 @@ class CircuitBreakerDecorator(Protocol):
27
27
  """Protocol for the circuit breaker decorator."""
28
28
 
29
29
  @overload
30
- def __call__(self, func: Callable[P, R]) -> Callable[P, R]: ... # pragma: no cover
30
+ def __call__(self, func: Callable[P, R]) -> Callable[P, R]: ...
31
31
 
32
32
  @overload
33
33
  def __call__(
34
34
  self, func: Callable[P, Awaitable[R]]
35
- ) -> Callable[P, Awaitable[R]]: ... # pragma: no cover
35
+ ) -> Callable[P, Awaitable[R]]: ...
36
36
 
37
37
 
38
38
  logger = logging.getLogger("taipanstack.resilience.circuit_breaker")
@@ -42,7 +42,7 @@ try:
42
42
 
43
43
  _structlog_logger = _structlog.get_logger("taipanstack.resilience.circuit_breaker")
44
44
  _HAS_STRUCTLOG = True
45
- except ImportError: # pragma: no cover — structlog is optional
45
+ except ImportError:
46
46
  _structlog_logger = None
47
47
  _HAS_STRUCTLOG = False
48
48
 
@@ -89,6 +89,15 @@ class CircuitBreakerConfig:
89
89
  excluded_exceptions: tuple[type[Exception], ...] = ()
90
90
  failure_exceptions: tuple[type[Exception], ...] = (Exception,)
91
91
 
92
+ def __post_init__(self) -> None:
93
+ """Validate configuration values."""
94
+ if not math.isfinite(self.failure_threshold):
95
+ raise ValueError("failure_threshold must be finite")
96
+ if not math.isfinite(self.success_threshold):
97
+ raise ValueError("success_threshold must be finite")
98
+ if not math.isfinite(self.timeout):
99
+ raise ValueError("timeout must be finite")
100
+
92
101
 
93
102
  @dataclass
94
103
  class CircuitBreakerState:
@@ -250,20 +259,28 @@ class CircuitBreaker:
250
259
  return self._handle_open_state()
251
260
 
252
261
  case CircuitState.HALF_OPEN:
262
+ # Protect against NaN/Inf state corruption
263
+ if not math.isfinite(self._state.half_open_attempts):
264
+ # Block attempt to prevent thundering herd when corrupted
265
+ return False
266
+
253
267
  # Allow limited attempts to prevent thundering herd
254
268
  if self._state.half_open_attempts < self.config.success_threshold:
255
269
  self._state.half_open_attempts += 1
256
270
  return True
257
271
  return False
258
272
 
259
- return False # pragma: no cover — unreachable, satisfies type checker
273
+ return False
260
274
 
261
275
  def _record_success(self) -> None:
262
276
  """Record a successful call."""
263
277
  with self._state.lock:
264
278
  match self._state.state:
265
279
  case CircuitState.HALF_OPEN:
280
+ if not math.isfinite(self._state.success_count):
281
+ self._state.success_count = 0
266
282
  self._state.success_count += 1
283
+
267
284
  if self._state.success_count >= self.config.success_threshold:
268
285
  self._state.state = CircuitState.CLOSED
269
286
  self._state.failure_count = 0
@@ -291,9 +308,8 @@ class CircuitBreaker:
291
308
  self._state.state = CircuitState.OPEN
292
309
  self._state.half_open_attempts = 0
293
310
  logger.warning(
294
- "Circuit %s reopened after failure in half-open (total failures=%d)",
311
+ "Circuit %s reopened after failure in half-open",
295
312
  self.name,
296
- self._state.failure_count,
297
313
  )
298
314
  self._notify_state_change(
299
315
  CircuitState.HALF_OPEN,
@@ -302,6 +318,19 @@ class CircuitBreaker:
302
318
 
303
319
  def _handle_failure_closed(self) -> None:
304
320
  """Handle failure when in CLOSED state."""
321
+ # Check against corrupted NaN/Inf failure_count
322
+ if not math.isfinite(self._state.failure_count):
323
+ self._state.state = CircuitState.OPEN
324
+ logger.warning(
325
+ "Circuit %s opened due to state corruption (NaN/Inf failures)",
326
+ self.name,
327
+ )
328
+ self._notify_state_change(
329
+ CircuitState.CLOSED,
330
+ CircuitState.OPEN,
331
+ )
332
+ return
333
+
305
334
  if self._state.failure_count >= self.config.failure_threshold:
306
335
  self._state.state = CircuitState.OPEN
307
336
  logger.warning(
@@ -322,7 +351,13 @@ class CircuitBreaker:
322
351
  return
323
352
 
324
353
  with self._state.lock:
325
- self._state.failure_count += 1
354
+ # First handle corruption
355
+ if not math.isfinite(self._state.failure_count):
356
+ # `_handle_failure_closed` will open it
357
+ pass
358
+ else:
359
+ self._state.failure_count += 1
360
+
326
361
  now = time.monotonic()
327
362
  if math.isfinite(now):
328
363
  self._state.last_failure_time = now
@@ -346,6 +381,41 @@ class CircuitBreaker:
346
381
  self._state.half_open_attempts = 0
347
382
  logger.info("Circuit %s manually reset", self.name)
348
383
 
384
+ def _process_result(self, result: R) -> R:
385
+ """Process Result outcome and record success/failure.
386
+
387
+ Args:
388
+ result: The result to process.
389
+
390
+ Returns:
391
+ The original result.
392
+
393
+ """
394
+ if isinstance(result, Err):
395
+ err_val = result.unwrap_err()
396
+ if isinstance(err_val, self.config.failure_exceptions):
397
+ self._record_failure(err_val)
398
+ return result
399
+ # Ignored exception in Result monad
400
+ return result
401
+ self._record_success()
402
+ return result
403
+
404
+ def _decrement_half_open(self, is_half_open: bool) -> None:
405
+ """Decrement half-open attempt count if applicable.
406
+
407
+ Args:
408
+ is_half_open: Whether the circuit was half-open before attempt.
409
+
410
+ """
411
+ if is_half_open:
412
+ with self._state.lock:
413
+ if (
414
+ self._state.state == CircuitState.HALF_OPEN
415
+ and self._state.half_open_attempts > 0
416
+ ):
417
+ self._state.half_open_attempts -= 1
418
+
349
419
  def __call__(
350
420
  self, func: Callable[P, R] | Callable[P, Awaitable[R]]
351
421
  ) -> Callable[P, R] | Callable[P, Awaitable[R]]:
@@ -365,26 +435,12 @@ class CircuitBreaker:
365
435
 
366
436
  try:
367
437
  result = await func_coro(*args, **kwargs)
368
- if isinstance(result, Err):
369
- err_val = result.unwrap_err()
370
- if isinstance(err_val, self.config.failure_exceptions):
371
- self._record_failure(err_val)
372
- return result
373
- # Ignored exception in Result monad
374
- return result
375
- self._record_success()
376
- return result
438
+ return self._process_result(result)
377
439
  except self.config.failure_exceptions as e:
378
440
  self._record_failure(e)
379
441
  raise
380
442
  finally:
381
- if is_half_open:
382
- with self._state.lock:
383
- if (
384
- self._state.state == CircuitState.HALF_OPEN
385
- and self._state.half_open_attempts > 0
386
- ):
387
- self._state.half_open_attempts -= 1
443
+ self._decrement_half_open(is_half_open)
388
444
 
389
445
  return async_wrapper
390
446
 
@@ -402,26 +458,12 @@ class CircuitBreaker:
402
458
 
403
459
  try:
404
460
  result = func_sync(*args, **kwargs)
405
- if isinstance(result, Err):
406
- err_val = result.unwrap_err()
407
- if isinstance(err_val, self.config.failure_exceptions):
408
- self._record_failure(err_val)
409
- return result
410
- # Ignored exception in Result monad
411
- return result
412
- self._record_success()
413
- return result
461
+ return self._process_result(result)
414
462
  except self.config.failure_exceptions as e:
415
463
  self._record_failure(e)
416
464
  raise
417
465
  finally:
418
- if is_half_open:
419
- with self._state.lock:
420
- if (
421
- self._state.state == CircuitState.HALF_OPEN
422
- and self._state.half_open_attempts > 0
423
- ):
424
- self._state.half_open_attempts -= 1
466
+ self._decrement_half_open(is_half_open)
425
467
 
426
468
  return wrapper
427
469
 
@@ -26,14 +26,10 @@ class FallbackDecorator(Protocol):
26
26
  """Protocol for the fallback decorator."""
27
27
 
28
28
  @overload
29
- def __call__(
30
- self, func: ResultFunc[P, T, E]
31
- ) -> ResultFunc[P, T, E]: ... # pragma: no cover
29
+ def __call__(self, func: ResultFunc[P, T, E]) -> ResultFunc[P, T, E]: ...
32
30
 
33
31
  @overload
34
- def __call__(
35
- self, func: AsyncResultFunc[P, T, E]
36
- ) -> AsyncResultFunc[P, T, E]: ... # pragma: no cover
32
+ def __call__(self, func: AsyncResultFunc[P, T, E]) -> AsyncResultFunc[P, T, E]: ...
37
33
 
38
34
 
39
35
  def fallback(
@@ -72,7 +68,7 @@ def fallback(
72
68
  return result
73
69
  except exceptions:
74
70
  return Ok(fallback_value)
75
- return Err(cast(E, RuntimeError("Unreachable"))) # pragma: no cover
71
+ return Err(cast(E, RuntimeError("Unreachable")))
76
72
 
77
73
  return async_wrapper
78
74
 
@@ -89,7 +85,7 @@ def fallback(
89
85
  return result
90
86
  except exceptions:
91
87
  return Ok(fallback_value)
92
- return Err(cast(E, RuntimeError("Unreachable"))) # pragma: no cover
88
+ return Err(cast(E, RuntimeError("Unreachable")))
93
89
 
94
90
  return sync_wrapper
95
91
 
@@ -102,12 +98,12 @@ class TimeoutDecorator(Protocol):
102
98
  @overload
103
99
  def __call__(
104
100
  self, func: ResultFunc[P, T, E]
105
- ) -> Callable[P, Result[T, TimeoutError | E]]: ... # pragma: no cover
101
+ ) -> Callable[P, Result[T, TimeoutError | E]]: ...
106
102
 
107
103
  @overload
108
104
  def __call__(
109
105
  self, func: AsyncResultFunc[P, T, E]
110
- ) -> Callable[P, Awaitable[Result[T, TimeoutError | E]]]: ... # pragma: no cover
106
+ ) -> Callable[P, Awaitable[Result[T, TimeoutError | E]]]: ...
111
107
 
112
108
 
113
109
  def timeout(seconds: float) -> TimeoutDecorator:
@@ -187,6 +183,10 @@ def timeout(seconds: float) -> TimeoutDecorator:
187
183
  thread.join(timeout=seconds)
188
184
  except RuntimeError as e:
189
185
  return Err(cast(E, RuntimeError(f"Thread exhaustion: {e!s}")))
186
+ except OSError as e:
187
+ return Err(cast(E, RuntimeError(f"Resource exhaustion: {e!s}")))
188
+ except MemoryError as e:
189
+ return Err(cast(E, RuntimeError(f"Memory exhaustion: {e!s}")))
190
190
 
191
191
  if thread.is_alive():
192
192
  return Err(