taipanstack 0.5.0__tar.gz → 0.5.1__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.1}/PKG-INFO +10 -10
  2. {taipanstack-0.5.0 → taipanstack-0.5.1}/README.md +9 -9
  3. {taipanstack-0.5.0 → taipanstack-0.5.1}/pyproject.toml +2 -2
  4. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/__init__.py +1 -1
  5. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/config/version_config.py +0 -4
  6. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/core/compat.py +0 -2
  7. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +53 -18
  8. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/adaptive/adaptive_retry.py +12 -9
  9. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/adaptive/orchestrator.py +19 -10
  10. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/resilience.py +10 -2
  11. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/watchdogs/config_watcher.py +14 -0
  12. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/security/guards.py +47 -27
  13. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/security/sanitizers.py +10 -0
  14. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/utils/concurrency.py +3 -2
  15. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/utils/rate_limit.py +56 -40
  16. {taipanstack-0.5.0 → taipanstack-0.5.1}/LICENSE +0 -0
  17. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/bridges/__init__.py +0 -0
  18. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/bridges/_imports.py +0 -0
  19. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/bridges/db_bridge.py +0 -0
  20. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/bridges/http_bridge.py +0 -0
  21. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/bridges/web_bridge.py +0 -0
  22. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/config/__init__.py +0 -0
  23. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/config/generators.py +0 -0
  24. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/config/models.py +0 -0
  25. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/core/__init__.py +0 -0
  26. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/core/optimizations.py +0 -0
  27. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/core/result.py +0 -0
  28. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/__init__.py +0 -0
  29. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
  30. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/adaptive/bulkhead.py +0 -0
  31. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/circuit_breaker.py +0 -0
  32. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/retry.py +0 -0
  33. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
  34. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/watchdogs/_base.py +0 -0
  35. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/watchdogs/health_pinger.py +0 -0
  36. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/resilience/watchdogs/resource_watcher.py +0 -0
  37. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/security/__init__.py +0 -0
  38. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/security/decorators.py +0 -0
  39. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/security/jwt.py +0 -0
  40. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/security/models.py +0 -0
  41. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/security/password.py +0 -0
  42. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/security/types.py +0 -0
  43. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/security/validators.py +0 -0
  44. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/utils/__init__.py +0 -0
  45. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/utils/cache.py +0 -0
  46. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/utils/circuit_breaker.py +0 -0
  47. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/utils/context.py +0 -0
  48. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/utils/filesystem.py +0 -0
  49. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/utils/logging.py +0 -0
  50. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/utils/resilience.py +0 -0
  51. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/utils/retry.py +0 -0
  52. {taipanstack-0.5.0 → taipanstack-0.5.1}/src/taipanstack/utils/serialization.py +0 -0
  53. {taipanstack-0.5.0 → taipanstack-0.5.1}/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.1
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -87,11 +87,11 @@ 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.1
91
+ - **Security & DoS Hardening**: Enforced configuration file size limits in config watcher (PR #807) and input length bounds on sanitizers (PR #801) to prevent Denial of Service; updated Starlette to `1.0.1` to resolve PYSEC-2026-161 (PR #804).
92
+ - **Resilience Enhancements**: Checked circuit breaker status inside the orchestrator's retry execution loop (PR #783) and hardened resilience decorators against type mutations under chaos (PR #795, #800, #802, #803).
93
+ - **Complexity & Refactoring**: Reduced complexity in rate limiter, circuit breakers, and security guards (PR #786, #798, #805); removed PyApp configuration (PR #784) and dead compatibility logic (PR #788).
94
+ - **QA Suite Standardization**: Standardized test naming convention (`test_*.py`) and removed code/test suite bypasses, expanding to **1,250 passing tests** with 100% genuine code and branch coverage (PR #797, #808).
95
95
 
96
96
  <table>
97
97
  <tr>
@@ -128,7 +128,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
128
128
 
129
129
  ### 🔧 Developer Experience
130
130
  - Pre-configured quality tools
131
- - **100% code coverage** (1,225 tests)
131
+ - **100% code coverage** (1,250 tests)
132
132
  - Architecture enforcement
133
133
  - Hardened Docker template
134
134
 
@@ -170,7 +170,7 @@ make all
170
170
  ### Verify Installation
171
171
 
172
172
  ```bash
173
- # Run tests with 100% coverage (1,225 tests)
173
+ # Run tests with 100% coverage (1,250 tests)
174
174
  make test
175
175
 
176
176
  # Check architecture contracts
@@ -223,7 +223,7 @@ TaipanStack/
223
223
  │ ├── config/ # ⚙️ Configuration models & generators
224
224
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
225
225
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
226
- ├── tests/ # ✅ 1,225 tests, 100% coverage
226
+ ├── tests/ # ✅ 1,250 tests, 100% coverage
227
227
  ├── .semgrep/ # 🔍 Custom SAST rules
228
228
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
229
229
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -239,7 +239,7 @@ Taipan Stack integrates security and quality at every level:
239
239
  | Category | Tools | Purpose |
240
240
  |----------|-------|---------|
241
241
  | **SAST** | Bandit, Semgrep + custom rules | Static Application Security Testing |
242
- | **SCA** | Safety, pip-audit | Dependency vulnerability scanning |
242
+ | **SCA** | pip-audit | Dependency vulnerability scanning |
243
243
  | **SBOM** | Syft (CycloneDX) | Software Bill of Materials |
244
244
  | **SLSA** | Cosign (Sigstore) | Artifact signing & attestation |
245
245
  | **Types** | Mypy (strict) | Compile-time type checking |
@@ -30,11 +30,11 @@
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.1
34
+ - **Security & DoS Hardening**: Enforced configuration file size limits in config watcher (PR #807) and input length bounds on sanitizers (PR #801) to prevent Denial of Service; updated Starlette to `1.0.1` to resolve PYSEC-2026-161 (PR #804).
35
+ - **Resilience Enhancements**: Checked circuit breaker status inside the orchestrator's retry execution loop (PR #783) and hardened resilience decorators against type mutations under chaos (PR #795, #800, #802, #803).
36
+ - **Complexity & Refactoring**: Reduced complexity in rate limiter, circuit breakers, and security guards (PR #786, #798, #805); removed PyApp configuration (PR #784) and dead compatibility logic (PR #788).
37
+ - **QA Suite Standardization**: Standardized test naming convention (`test_*.py`) and removed code/test suite bypasses, expanding to **1,250 passing tests** with 100% genuine code and branch coverage (PR #797, #808).
38
38
 
39
39
  <table>
40
40
  <tr>
@@ -71,7 +71,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
71
71
 
72
72
  ### 🔧 Developer Experience
73
73
  - Pre-configured quality tools
74
- - **100% code coverage** (1,225 tests)
74
+ - **100% code coverage** (1,250 tests)
75
75
  - Architecture enforcement
76
76
  - Hardened Docker template
77
77
 
@@ -113,7 +113,7 @@ make all
113
113
  ### Verify Installation
114
114
 
115
115
  ```bash
116
- # Run tests with 100% coverage (1,225 tests)
116
+ # Run tests with 100% coverage (1,250 tests)
117
117
  make test
118
118
 
119
119
  # Check architecture contracts
@@ -166,7 +166,7 @@ TaipanStack/
166
166
  │ ├── config/ # ⚙️ Configuration models & generators
167
167
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
168
168
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
169
- ├── tests/ # ✅ 1,225 tests, 100% coverage
169
+ ├── tests/ # ✅ 1,250 tests, 100% coverage
170
170
  ├── .semgrep/ # 🔍 Custom SAST rules
171
171
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
172
172
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -182,7 +182,7 @@ Taipan Stack integrates security and quality at every level:
182
182
  | Category | Tools | Purpose |
183
183
  |----------|-------|---------|
184
184
  | **SAST** | Bandit, Semgrep + custom rules | Static Application Security Testing |
185
- | **SCA** | Safety, pip-audit | Dependency vulnerability scanning |
185
+ | **SCA** | pip-audit | Dependency vulnerability scanning |
186
186
  | **SBOM** | Syft (CycloneDX) | Software Bill of Materials |
187
187
  | **SLSA** | Cosign (Sigstore) | Artifact signing & attestation |
188
188
  | **Types** | Mypy (strict) | Compile-time type checking |
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.5.0"
3
+ version = "0.5.1"
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"}
@@ -108,7 +108,7 @@ dev = [
108
108
 
109
109
  docs = [
110
110
  "mkdocs-material (>=9.7.3,<10.0.0)",
111
- "mkdocstrings[python] (>=1.0.3,<2.0.0)"
111
+ "mkdocstrings[python] (>=1.0.3,<2.0.0)",
112
112
  ]
113
113
 
114
114
 
@@ -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.1"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -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,
@@ -224,7 +224,7 @@ class ResilienceOrchestrator(Generic[T]):
224
224
 
225
225
  return await self._execute_inner(fn, *args, **kwargs)
226
226
 
227
- def _evaluate_circuit_breaker(self) -> Result[T, Exception] | None:
227
+ def _evaluate_circuit_breaker(self) -> Err[Exception] | None:
228
228
  """Check if execution is allowed by the circuit breaker."""
229
229
  if self._adaptive_breaker is not None:
230
230
  if not self._adaptive_breaker.should_allow():
@@ -278,10 +278,6 @@ class ResilienceOrchestrator(Generic[T]):
278
278
  **kwargs: P.kwargs,
279
279
  ) -> Result[T, Exception]:
280
280
  """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
281
  max_attempts = (
286
282
  self._retry_config.max_attempts if self._retry_config is not None else 1
287
283
  )
@@ -300,6 +296,14 @@ class ResilienceOrchestrator(Generic[T]):
300
296
  return True
301
297
  return False
302
298
 
299
+ def _handle_circuit_breaker_open(
300
+ self, cb_err: Err[Exception], attempt: int
301
+ ) -> Result[T, Exception] | Exception:
302
+ """Handle circuit breaker evaluation logic."""
303
+ if attempt == 1:
304
+ return self._apply_fallback(cb_err)
305
+ return cb_err.err_value
306
+
303
307
  async def _execute_with_retries(
304
308
  self,
305
309
  max_attempts: int,
@@ -307,8 +311,16 @@ class ResilienceOrchestrator(Generic[T]):
307
311
  *args: P.args,
308
312
  **kwargs: P.kwargs,
309
313
  ) -> Result[T, Exception]:
310
- last_error: Exception | None = None
314
+ last_error: Exception = RuntimeError("Execution failed")
311
315
  for attempt in range(1, max_attempts + 1):
316
+ cb_err = self._evaluate_circuit_breaker()
317
+ if cb_err is not None:
318
+ cb_res = self._handle_circuit_breaker_open(cb_err, attempt)
319
+ if isinstance(cb_res, Exception):
320
+ last_error = cb_res
321
+ break
322
+ return cb_res
323
+
312
324
  result = await self._execute_with_timeout(fn, *args, **kwargs)
313
325
  if isinstance(result, Ok):
314
326
  self._record_success_outcome(attempt)
@@ -319,10 +331,7 @@ class ResilienceOrchestrator(Generic[T]):
319
331
  continue
320
332
  break
321
333
 
322
- final_result: Result[T, Exception] = Err(
323
- last_error or RuntimeError("Execution failed")
324
- )
325
- return self._apply_fallback(final_result)
334
+ return self._apply_fallback(Err(last_error))
326
335
 
327
336
  async def _execute_with_timeout(
328
337
  self,
@@ -129,7 +129,11 @@ def timeout(seconds: float) -> TimeoutDecorator:
129
129
  async def async_wrapper(
130
130
  *args: P.args, **kwargs: P.kwargs
131
131
  ) -> Result[T, TimeoutError | E]:
132
- if not math.isfinite(seconds) or seconds < 0:
132
+ if (
133
+ not isinstance(seconds, (int, float))
134
+ or not math.isfinite(seconds)
135
+ or seconds < 0
136
+ ):
133
137
  return Err(
134
138
  cast(
135
139
  E,
@@ -157,7 +161,11 @@ def timeout(seconds: float) -> TimeoutDecorator:
157
161
  def sync_wrapper(
158
162
  *args: P.args, **kwargs: P.kwargs
159
163
  ) -> Result[T, TimeoutError | E]:
160
- if not math.isfinite(seconds) or seconds < 0:
164
+ if (
165
+ not isinstance(seconds, (int, float))
166
+ or not math.isfinite(seconds)
167
+ or seconds < 0
168
+ ):
161
169
  return Err(
162
170
  cast(
163
171
  E,
@@ -18,6 +18,8 @@ from taipanstack.resilience.watchdogs._base import BaseWatcher
18
18
 
19
19
  logger = logging.getLogger("taipanstack.resilience.watchdogs.config")
20
20
 
21
+ MAX_CONFIG_FILE_SIZE = 1048576
22
+
21
23
 
22
24
  def _hash_file(path: Path) -> Result[str, Exception]:
23
25
  """Compute the SHA-256 hex digest of a file.
@@ -30,6 +32,12 @@ def _hash_file(path: Path) -> Result[str, Exception]:
30
32
 
31
33
  """
32
34
  try:
35
+ if path.stat().st_size > MAX_CONFIG_FILE_SIZE:
36
+ return Err(
37
+ ValueError(
38
+ f"File {path} exceeds max size ({MAX_CONFIG_FILE_SIZE} bytes)"
39
+ )
40
+ )
33
41
  data = path.read_bytes()
34
42
  return Ok(hashlib.sha256(data).hexdigest())
35
43
  except OSError as exc:
@@ -94,6 +102,12 @@ def _load_file_data(path: Path) -> Result[dict[str, object], Exception]:
94
102
 
95
103
  """
96
104
  try:
105
+ if path.stat().st_size > MAX_CONFIG_FILE_SIZE:
106
+ return Err(
107
+ ValueError(
108
+ f"File {path} exceeds max size ({MAX_CONFIG_FILE_SIZE} bytes)"
109
+ )
110
+ )
97
111
  text = path.read_text(encoding="utf-8")
98
112
  except OSError as exc:
99
113
  return Err(exc)
@@ -188,6 +188,28 @@ def _check_symlink_safety(full_path: Path, base_dir: Path) -> None:
188
188
  current = current.parent
189
189
 
190
190
 
191
+ def _validate_path_types(path: object, base_dir: object) -> None:
192
+ """Validate types of path and base_dir."""
193
+ if not isinstance(path, (str, Path)):
194
+ raise TypeError(f"path must be str or Path, got {type(path).__name__}")
195
+ if base_dir is not None and not isinstance(base_dir, (str, Path)):
196
+ raise TypeError(f"base_dir must be str or Path, got {type(base_dir).__name__}")
197
+
198
+
199
+ def _check_path_null_bytes(path: Path | str, base_dir: Path | str | None) -> None:
200
+ """Check for null bytes in path and base_dir."""
201
+ if "\x00" in str(path) or (base_dir is not None and "\x00" in str(base_dir)):
202
+ raise SecurityError(
203
+ "Path contains null bytes",
204
+ guard_name="path_traversal",
205
+ )
206
+
207
+
208
+ def _resolve_base_dir(base_dir: Path | str | None) -> Path:
209
+ """Resolve the base directory."""
210
+ return Path(base_dir).resolve() if base_dir else Path.cwd().resolve()
211
+
212
+
191
213
  def guard_path_traversal(
192
214
  path: Path | str,
193
215
  base_dir: Path | str | None = None,
@@ -215,19 +237,11 @@ def guard_path_traversal(
215
237
  SecurityError: [path_traversal] Path escapes base directory
216
238
 
217
239
  """
218
- if not isinstance(path, (str, Path)):
219
- raise TypeError(f"path must be str or Path, got {type(path).__name__}")
220
- if base_dir is not None and not isinstance(base_dir, (str, Path)):
221
- raise TypeError(f"base_dir must be str or Path, got {type(base_dir).__name__}")
222
-
223
- if "\x00" in str(path) or (base_dir is not None and "\x00" in str(base_dir)):
224
- raise SecurityError(
225
- "Path contains null bytes",
226
- guard_name="path_traversal",
227
- )
240
+ _validate_path_types(path, base_dir)
241
+ _check_path_null_bytes(path, base_dir)
228
242
 
229
243
  path_obj = Path(path) if isinstance(path, str) else path
230
- base = Path(base_dir).resolve() if base_dir else Path.cwd().resolve()
244
+ base = _resolve_base_dir(base_dir)
231
245
 
232
246
  _check_traversal_patterns(str(path_obj))
233
247
  full_path, resolved = _resolve_and_check_bounds(path_obj, base)
@@ -467,6 +481,26 @@ def _check_env_sensitive(
467
481
  )
468
482
 
469
483
 
484
+ def _validate_env_var_name(name: object) -> str:
485
+ """Validate environment variable name."""
486
+ if not isinstance(name, str):
487
+ raise TypeError(f"Variable name must be str, got {type(name).__name__}")
488
+
489
+ if not name or not name.strip():
490
+ raise SecurityError(
491
+ "Environment variable name cannot be empty or whitespace",
492
+ guard_name="env_variable",
493
+ )
494
+
495
+ if "\x00" in name:
496
+ raise SecurityError(
497
+ "Environment variable name cannot contain null bytes",
498
+ guard_name="env_variable",
499
+ )
500
+
501
+ return name
502
+
503
+
470
504
  def guard_env_variable(
471
505
  name: str,
472
506
  *,
@@ -487,22 +521,8 @@ def guard_env_variable(
487
521
  SecurityError: If variable access is not allowed.
488
522
 
489
523
  """
490
- # Validate input type
491
- if not isinstance(name, str):
492
- raise TypeError(f"Variable name must be str, got {type(name).__name__}")
493
-
494
- # Reject empty/whitespace-only variable names
495
- if not name or not name.strip():
496
- raise SecurityError(
497
- "Environment variable name cannot be empty or whitespace",
498
- guard_name="env_variable",
499
- )
500
-
501
- if "\x00" in name:
502
- raise SecurityError(
503
- "Environment variable name cannot contain null bytes",
504
- guard_name="env_variable",
505
- )
524
+ # Validate input type and format
525
+ name = _validate_env_var_name(name)
506
526
 
507
527
  name_upper = name.upper()
508
528
 
@@ -11,6 +11,7 @@ from pathlib import Path
11
11
  # Constants to avoid magic values (PLR2004)
12
12
  MAX_SQL_IDENTIFIER_LENGTH = 128 # pragma: no mutate
13
13
  MAX_PATH_LENGTH = 4096 # pragma: no mutate
14
+ MAX_ENV_VALUE_LENGTH = 65535 # pragma: no mutate
14
15
 
15
16
  # Pre-compiled regex and sets for Performance Benchmarks
16
17
  _INVALID_FILENAME_CHARS_RE = re.compile(r'[<>:"/\\|?*\x00-\x1f]') # pragma: no mutate
@@ -241,6 +242,9 @@ def sanitize_filename(
241
242
  if not isinstance(filename, str):
242
243
  raise TypeError(f"filename must be str, got {type(filename).__name__}")
243
244
 
245
+ if len(filename) > MAX_PATH_LENGTH:
246
+ raise ValueError("Filename length exceeds maximum allowed limit")
247
+
244
248
  if not filename:
245
249
  filename = "unnamed"
246
250
 
@@ -438,6 +442,9 @@ def sanitize_env_value(
438
442
  if not isinstance(value, str):
439
443
  raise TypeError(f"value must be str, got {type(value).__name__}")
440
444
 
445
+ if len(value) > MAX_ENV_VALUE_LENGTH:
446
+ raise ValueError("Environment value length exceeds maximum allowed limit")
447
+
441
448
  if not value:
442
449
  return ""
443
450
 
@@ -498,6 +505,9 @@ def sanitize_sql_identifier(identifier: str) -> str:
498
505
  msg = "SQL identifier cannot be empty"
499
506
  raise ValueError(msg)
500
507
 
508
+ if len(identifier) > MAX_PATH_LENGTH:
509
+ raise ValueError("SQL identifier length exceeds maximum allowed limit")
510
+
501
511
  return _sanitize_sql_identifier_slow_path(identifier)
502
512
 
503
513
  raise TypeError(f"identifier must be str, got {type(identifier).__name__}")
@@ -9,6 +9,7 @@ returns a `Result` type.
9
9
  import asyncio
10
10
  import functools
11
11
  import inspect
12
+ import math
12
13
  import threading
13
14
  from collections.abc import Awaitable, Callable
14
15
  from typing import ParamSpec, Protocol, TypeVar, cast, overload
@@ -141,8 +142,8 @@ def limit_concurrency(
141
142
  """
142
143
  if max_tasks <= 0:
143
144
  raise ValueError("max_tasks must be > 0")
144
- if timeout < 0.0:
145
- raise ValueError("timeout must be >= 0.0")
145
+ if not math.isfinite(timeout) or timeout < 0.0:
146
+ raise ValueError("timeout must be a finite non-negative number")
146
147
 
147
148
  def decorator(
148
149
  func: Callable[P, T] | Callable[P, Awaitable[T]],
@@ -57,14 +57,21 @@ class RateLimiter:
57
57
  self.last_update: float = time.monotonic()
58
58
  self._lock = threading.Lock()
59
59
 
60
+ def _is_valid_time_window(self) -> bool:
61
+ """Check if time window is valid."""
62
+ if not isinstance(self.time_window, (int, float)):
63
+ return False
64
+ return math.isfinite(self.time_window) and self.time_window > 0.0
65
+
66
+ def _is_valid_capacity(self) -> bool:
67
+ """Check if capacity is valid."""
68
+ if not isinstance(self.capacity, (int, float)):
69
+ return False
70
+ return math.isfinite(self.capacity) and self.capacity > 0.0
71
+
60
72
  def _is_valid_bucket_state(self) -> bool:
61
73
  """Check if the bucket's time window and capacity are in a valid state."""
62
- try:
63
- if not math.isfinite(self.time_window) or self.time_window <= 0.0:
64
- return False
65
- return math.isfinite(self.capacity) and self.capacity > 0.0
66
- except TypeError:
67
- return False
74
+ return self._is_valid_time_window() and self._is_valid_capacity()
68
75
 
69
76
  def _calculate_new_tokens(self, elapsed: float) -> float | None:
70
77
  """Calculate new tokens based on elapsed time."""
@@ -73,6 +80,11 @@ class RateLimiter:
73
80
 
74
81
  def _apply_new_tokens(self, new_tokens: float) -> bool:
75
82
  """Apply new tokens to the bucket."""
83
+ if not isinstance(self.tokens, (int, float)):
84
+ self.tokens = self.capacity
85
+ return False
86
+ if not isinstance(new_tokens, (int, float)):
87
+ return False
76
88
  self.tokens += new_tokens
77
89
  if not math.isfinite(self.tokens):
78
90
  # Reset to previous state or capacity if corrupted
@@ -91,32 +103,49 @@ class RateLimiter:
91
103
  True if token update succeeds, False if state corruption is detected.
92
104
 
93
105
  """
94
- try:
95
- raw_elapsed = now - self.last_update
96
- if not math.isfinite(raw_elapsed):
97
- return False
98
- elapsed = max(0.0, raw_elapsed)
99
- self.last_update = now
100
-
101
- # Prevent state corruption or infinite elapsed time
102
- if not self._is_valid_bucket_state():
103
- return False
104
-
105
- new_tokens = self._calculate_new_tokens(elapsed)
106
- if new_tokens is None:
107
- return False
108
-
109
- return self._apply_new_tokens(new_tokens)
110
- except TypeError:
106
+ if not isinstance(self.last_update, (int, float)):
107
+ return False
108
+ raw_elapsed = now - self.last_update
109
+ if not math.isfinite(raw_elapsed):
111
110
  return False
111
+ elapsed = max(0.0, raw_elapsed)
112
+ self.last_update = now
113
+
114
+ # Prevent state corruption or infinite elapsed time
115
+ if not self._is_valid_bucket_state():
116
+ return False
117
+
118
+ new_tokens = self._calculate_new_tokens(elapsed)
119
+ if new_tokens is None:
120
+ return False
121
+
122
+ return self._apply_new_tokens(new_tokens)
112
123
 
113
124
  def _try_consume(self, tokens: float) -> bool:
114
125
  """Attempt to consume the tokens from the bucket if available."""
126
+ if not isinstance(self.tokens, (int, float)):
127
+ return False
115
128
  if self.tokens >= tokens:
116
129
  self.tokens -= tokens
117
130
  return True
118
131
  return False
119
132
 
133
+ def _process_consumption(self, tokens: float) -> bool:
134
+ """Process token consumption inside the lock."""
135
+ try:
136
+ now = time.monotonic()
137
+ except Exception:
138
+ return False
139
+
140
+ # Prevent time corruption from poisoning the bucket state.
141
+ # Only try to add tokens if time is finite.
142
+ if not isinstance(now, (int, float)) or (
143
+ math.isfinite(now) and not self._add_tokens(now)
144
+ ):
145
+ return False
146
+
147
+ return self._try_consume(tokens)
148
+
120
149
  def consume(self, tokens: float = 1.0) -> bool:
121
150
  """Try to consume tokens.
122
151
 
@@ -127,26 +156,13 @@ class RateLimiter:
127
156
  True if tokens were consumed (allow), False otherwise (limit exceeded).
128
157
 
129
158
  """
130
- try:
131
- if not math.isfinite(tokens):
132
- return False
133
- if tokens <= 0:
134
- return True
135
- except TypeError:
159
+ if not isinstance(tokens, (int, float)) or not math.isfinite(tokens):
136
160
  return False
161
+ if tokens <= 0:
162
+ return True
137
163
 
138
164
  with self._lock:
139
- try:
140
- now = time.monotonic()
141
-
142
- # Prevent time corruption from poisoning the bucket state.
143
- # Only try to add tokens if time is finite.
144
- if math.isfinite(now) and not self._add_tokens(now):
145
- return False
146
-
147
- return self._try_consume(tokens)
148
- except TypeError:
149
- return False
165
+ return self._process_consumption(tokens)
150
166
 
151
167
 
152
168
  class RateLimitDecorator(Protocol):
File without changes