taipanstack 0.4.8__tar.gz → 0.4.9__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.8 → taipanstack-0.4.9}/PKG-INFO +10 -15
  2. {taipanstack-0.4.8 → taipanstack-0.4.9}/README.md +9 -14
  3. {taipanstack-0.4.8 → taipanstack-0.4.9}/pyproject.toml +3 -5
  4. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/__init__.py +1 -1
  5. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/bridges/http_bridge.py +2 -2
  6. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/bridges/web_bridge.py +2 -2
  7. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/core/optimizations.py +3 -3
  8. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/circuit_breaker.py +53 -54
  9. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/retry.py +42 -25
  10. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/watchdogs/_base.py +6 -2
  11. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/watchdogs/health_pinger.py +17 -10
  12. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/security/decorators.py +6 -6
  13. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/security/guards.py +1 -1
  14. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/security/sanitizers.py +24 -21
  15. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/security/types.py +0 -42
  16. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/security/validators.py +3 -4
  17. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/utils/logging.py +51 -2
  18. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/utils/rate_limit.py +31 -19
  19. {taipanstack-0.4.8 → taipanstack-0.4.9}/LICENSE +0 -0
  20. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/bridges/__init__.py +0 -0
  21. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/bridges/_imports.py +0 -0
  22. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/bridges/db_bridge.py +0 -0
  23. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/config/__init__.py +0 -0
  24. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/config/generators.py +0 -0
  25. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/config/models.py +0 -0
  26. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/config/version_config.py +0 -0
  27. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/core/__init__.py +0 -0
  28. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/core/compat.py +0 -0
  29. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/core/result.py +0 -0
  30. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/__init__.py +0 -0
  31. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
  32. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +0 -0
  33. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/adaptive/adaptive_retry.py +0 -0
  34. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/adaptive/bulkhead.py +0 -0
  35. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/adaptive/orchestrator.py +0 -0
  36. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/resilience.py +0 -0
  37. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
  38. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/watchdogs/config_watcher.py +0 -0
  39. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/resilience/watchdogs/resource_watcher.py +0 -0
  40. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/security/__init__.py +0 -0
  41. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/security/jwt.py +0 -0
  42. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/security/models.py +0 -0
  43. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/security/password.py +0 -0
  44. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/utils/__init__.py +0 -0
  45. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/utils/cache.py +0 -0
  46. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/utils/circuit_breaker.py +0 -0
  47. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/utils/concurrency.py +0 -0
  48. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/utils/context.py +0 -0
  49. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/utils/filesystem.py +0 -0
  50. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/utils/resilience.py +0 -0
  51. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/utils/retry.py +0 -0
  52. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/utils/serialization.py +0 -0
  53. {taipanstack-0.4.8 → taipanstack-0.4.9}/src/taipanstack/utils/subprocess.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.4.8
3
+ Version: 0.4.9
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -87,12 +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.4.8
91
- - **Hardening Resilience**: Hardened `RateLimiter` and `CircuitBreaker` against state corruption and type mutations via chaos testing (PR #689, #684).
92
- - **Complexity Reduction**: Major reduction of cyclomatic complexity across core modules, subprocess utilities, and web bridges (PR #706, #692).
93
- - **Security Hardening**: Restored missing type guard for password verification and enhanced durability of atomic writes (Commit f83b6745, PR #688).
94
- - **Performance**: Implemented concurrent execution for async health checks in `HealthPinger` (PR #694).
95
- - **Total Stack Coverage**: Reached **1,315 passing tests** with 100% verified genuine coverage across all modules.
90
+ ### ✨ What's New in v0.4.9
91
+ - **100% REAL Coverage**: Achieved true **100% genuine branch coverage** across the entire core without artificial gaps (PR #738, #724).
92
+ - **Security Hardening**: Remedied error handling information leakage and fixed nested dictionary redaction in logging (PR #739, #730).
93
+ - **Resilience**: Eliminated circuit breaker lock deadlock vector and hardened retry type mutation handling (PR #726, #719).
94
+ - **Chaos Testing**: Introduced daily micro-chaos tests for resilience components to ensure state integrity (PR #714, #711, #710).
95
+ - **Total Stack Quality**: Expanded to **1,331 passing tests** with 100% verified genuine coverage across all modules.
96
96
 
97
97
  <table>
98
98
  <tr>
@@ -112,7 +112,6 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
112
112
  - `uvloop` async event loop
113
113
  - `orjson` fast JSON serialization
114
114
  - `Pydantic v2` validation
115
- - Performance benchmarks with regression detection
116
115
 
117
116
  </td>
118
117
  </tr>
@@ -130,7 +129,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
130
129
 
131
130
  ### 🔧 Developer Experience
132
131
  - Pre-configured quality tools
133
- - **100% code coverage** (1315 tests)
132
+ - **100% code coverage** (1,331 tests)
134
133
  - Architecture enforcement
135
134
  - Hardened Docker template
136
135
 
@@ -172,7 +171,7 @@ make all
172
171
  ### Verify Installation
173
172
 
174
173
  ```bash
175
- # Run tests with 100% coverage (1315 tests)
174
+ # Run tests with 100% coverage (1,331 tests)
176
175
  make test
177
176
 
178
177
  # Check architecture contracts
@@ -184,8 +183,6 @@ make security
184
183
  # Run property-based fuzzing
185
184
  make property-test
186
185
 
187
- # Run performance benchmarks
188
- make benchmark
189
186
  ```
190
187
 
191
188
  ---
@@ -227,7 +224,7 @@ TaipanStack/
227
224
  │ ├── config/ # ⚙️ Configuration models & generators
228
225
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
229
226
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
230
- ├── tests/ # ✅ 1315 tests, 100% coverage
227
+ ├── tests/ # ✅ 1,331 tests, 100% coverage
231
228
  ├── .semgrep/ # 🔍 Custom SAST rules
232
229
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
233
230
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -250,7 +247,6 @@ Taipan Stack integrates security and quality at every level:
250
247
  | **Lint** | Ruff | Lightning-fast linting & formatting |
251
248
  | **Arch** | Import Linter | Dependency rule enforcement |
252
249
  | **Test** | Pytest, Hypothesis, mutmut | Property-based & mutation testing |
253
- | **Perf** | pytest-benchmark | Performance regression detection |
254
250
  | **Containers** | Docker (Alpine, rootless) | Hardened-by-default images |
255
251
 
256
252
  ### CI Pipeline
@@ -451,7 +447,6 @@ Security features: multi-stage build, Alpine base (<50MB), non-root `appuser` (U
451
447
  - Bandit
452
448
  - Pytest + Hypothesis
453
449
  - mutmut
454
- - pytest-benchmark
455
450
 
456
451
  </td>
457
452
  <td>
@@ -30,12 +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.8
34
- - **Hardening Resilience**: Hardened `RateLimiter` and `CircuitBreaker` against state corruption and type mutations via chaos testing (PR #689, #684).
35
- - **Complexity Reduction**: Major reduction of cyclomatic complexity across core modules, subprocess utilities, and web bridges (PR #706, #692).
36
- - **Security Hardening**: Restored missing type guard for password verification and enhanced durability of atomic writes (Commit f83b6745, PR #688).
37
- - **Performance**: Implemented concurrent execution for async health checks in `HealthPinger` (PR #694).
38
- - **Total Stack Coverage**: Reached **1,315 passing tests** with 100% verified genuine coverage across all modules.
33
+ ### ✨ What's New in v0.4.9
34
+ - **100% REAL Coverage**: Achieved true **100% genuine branch coverage** across the entire core without artificial gaps (PR #738, #724).
35
+ - **Security Hardening**: Remedied error handling information leakage and fixed nested dictionary redaction in logging (PR #739, #730).
36
+ - **Resilience**: Eliminated circuit breaker lock deadlock vector and hardened retry type mutation handling (PR #726, #719).
37
+ - **Chaos Testing**: Introduced daily micro-chaos tests for resilience components to ensure state integrity (PR #714, #711, #710).
38
+ - **Total Stack Quality**: Expanded to **1,331 passing tests** with 100% verified genuine coverage across all modules.
39
39
 
40
40
  <table>
41
41
  <tr>
@@ -55,7 +55,6 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
55
55
  - `uvloop` async event loop
56
56
  - `orjson` fast JSON serialization
57
57
  - `Pydantic v2` validation
58
- - Performance benchmarks with regression detection
59
58
 
60
59
  </td>
61
60
  </tr>
@@ -73,7 +72,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
73
72
 
74
73
  ### 🔧 Developer Experience
75
74
  - Pre-configured quality tools
76
- - **100% code coverage** (1315 tests)
75
+ - **100% code coverage** (1,331 tests)
77
76
  - Architecture enforcement
78
77
  - Hardened Docker template
79
78
 
@@ -115,7 +114,7 @@ make all
115
114
  ### Verify Installation
116
115
 
117
116
  ```bash
118
- # Run tests with 100% coverage (1315 tests)
117
+ # Run tests with 100% coverage (1,331 tests)
119
118
  make test
120
119
 
121
120
  # Check architecture contracts
@@ -127,8 +126,6 @@ make security
127
126
  # Run property-based fuzzing
128
127
  make property-test
129
128
 
130
- # Run performance benchmarks
131
- make benchmark
132
129
  ```
133
130
 
134
131
  ---
@@ -170,7 +167,7 @@ TaipanStack/
170
167
  │ ├── config/ # ⚙️ Configuration models & generators
171
168
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
172
169
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
173
- ├── tests/ # ✅ 1315 tests, 100% coverage
170
+ ├── tests/ # ✅ 1,331 tests, 100% coverage
174
171
  ├── .semgrep/ # 🔍 Custom SAST rules
175
172
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
176
173
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -193,7 +190,6 @@ Taipan Stack integrates security and quality at every level:
193
190
  | **Lint** | Ruff | Lightning-fast linting & formatting |
194
191
  | **Arch** | Import Linter | Dependency rule enforcement |
195
192
  | **Test** | Pytest, Hypothesis, mutmut | Property-based & mutation testing |
196
- | **Perf** | pytest-benchmark | Performance regression detection |
197
193
  | **Containers** | Docker (Alpine, rootless) | Hardened-by-default images |
198
194
 
199
195
  ### CI Pipeline
@@ -394,7 +390,6 @@ Security features: multi-stage build, Alpine base (<50MB), non-root `appuser` (U
394
390
  - Bandit
395
391
  - Pytest + Hypothesis
396
392
  - mutmut
397
- - pytest-benchmark
398
393
 
399
394
  </td>
400
395
  <td>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.4.8"
3
+ version = "0.4.9"
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"}
@@ -94,7 +94,6 @@ dev = [
94
94
  "structlog (>=25.5.0,<26.0.0)",
95
95
  "import-linter (>=2.1)",
96
96
  "gitingest (>=0.1.0)",
97
- "pytest-benchmark (>=5.0.0)",
98
97
  "pytest-asyncio (>=0.23.0)",
99
98
  "radon (>=6.0.1,<7.0.0)",
100
99
  "pip-audit (>=2.10.0,<3.0.0)",
@@ -223,7 +222,6 @@ markers = [
223
222
  "slow: marks tests as slow (deselect with '-m \"not slow\"')",
224
223
  "security: marks tests as security-related",
225
224
  "integration: marks tests as integration tests",
226
- "benchmark: marks tests as performance benchmarks",
227
225
  ]
228
226
  filterwarnings = [
229
227
 
@@ -237,7 +235,7 @@ omit = ["*/tests/*", "*/__pycache__/*", "*/conftest.py"]
237
235
 
238
236
  [tool.coverage.report]
239
237
  exclude_lines = [
240
- "pragma: no cover",
238
+
241
239
  "def __repr__",
242
240
  "raise NotImplementedError",
243
241
  "if TYPE_CHECKING:",
@@ -247,7 +245,7 @@ exclude_lines = [
247
245
  "def __call__\\(.*\\) -> .*:\\s*(?:\"\"\".*?\"\"\"\\s*)?\\.\\.\\.",
248
246
  ]
249
247
  partial_branches = [
250
- "pragma: no branch",
248
+
251
249
  "case Err\\(",
252
250
  "case Ok\\(",
253
251
  ]
@@ -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.8"
8
+ __version__ = "0.4.9"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -129,7 +129,7 @@ def _check_ssrf(url: str, ssrf_protection: bool) -> Result[None, Exception]:
129
129
  match ssrf_result:
130
130
  case Err(security_err):
131
131
  return Err(security_err)
132
- case Ok(): # pragma: no branch
132
+ case Ok():
133
133
  return Ok(None)
134
134
 
135
135
 
@@ -156,7 +156,7 @@ async def _handle_http_exception(
156
156
  circuit_breaker: CircuitBreaker | None,
157
157
  ) -> bool:
158
158
  """Handle exception and return True if we should retry, False otherwise."""
159
- if circuit_breaker is not None: # pragma: no branch
159
+ if circuit_breaker is not None:
160
160
  circuit_breaker._record_failure(exc)
161
161
  if retry_config is not None and attempt < max_attempts:
162
162
  delay = calculate_delay(attempt, retry_config)
@@ -256,8 +256,8 @@ class TaipanMiddleware:
256
256
  # Call the actual application
257
257
  try:
258
258
  await self._app(scope, receive, send)
259
- except Exception:
260
- logger.exception("Unhandled exception in ASGI app")
259
+ except Exception as exc:
260
+ logger.exception("Unhandled exception in ASGI app", exc_info=exc)
261
261
  await _send_json_response(
262
262
  send,
263
263
  status=500,
@@ -292,9 +292,9 @@ def _apply_experimental(
292
292
  """Check and log experimental features."""
293
293
  if profile.enable_experimental:
294
294
  features = get_features()
295
- if features.has_jit: # pragma: no branch
295
+ if features.has_jit:
296
296
  applied.append("jit: available")
297
- if features.has_free_threading: # pragma: no branch
297
+ if features.has_free_threading:
298
298
  applied.append("free_threading: available")
299
299
  logger.warning(
300
300
  "EXPERIMENTAL FEATURES ENABLED: Stability and security may be affected."
@@ -354,7 +354,7 @@ def apply_optimizations(
354
354
  success = len(errors) == 0
355
355
  if applied:
356
356
  logger.debug("Applied optimizations: %s", ", ".join(applied))
357
- if skipped: # pragma: no branch
357
+ if skipped:
358
358
  logger.debug("Skipped optimizations: %s", ", ".join(skipped))
359
359
  if errors:
360
360
  logger.warning("Optimization errors: %s", ", ".join(errors))
@@ -230,7 +230,7 @@ class CircuitBreaker:
230
230
  self._on_state_change(old_state, new_state)
231
231
  except Exception as e:
232
232
  self._log_callback_failure(old_state, new_state, e)
233
- elif _HAS_STRUCTLOG and _structlog_logger is not None: # pragma: no branch
233
+ elif _HAS_STRUCTLOG and _structlog_logger is not None:
234
234
  _structlog_logger.warning(
235
235
  "circuit_state_changed",
236
236
  circuit=self.name,
@@ -239,14 +239,16 @@ class CircuitBreaker:
239
239
  failure_count=self._state.failure_count,
240
240
  )
241
241
 
242
- def _handle_open_state(self) -> bool:
242
+ def _handle_open_state(
243
+ self,
244
+ ) -> tuple[bool, tuple[CircuitState, CircuitState] | None]:
243
245
  """Handle logic for OPEN state in _should_attempt."""
244
246
  now = time.monotonic()
245
247
  try:
246
248
  elapsed = now - self._state.last_failure_time
247
249
  except TypeError:
248
250
  # Type corruption detected (e.g. last_failure_time is string)
249
- return False
251
+ return False, None
250
252
 
251
253
  # Safe check against NaN and Inf time corruption
252
254
  # If elapsed < 0, a backward clock jump occurred. We should
@@ -270,12 +272,8 @@ class CircuitBreaker:
270
272
  elapsed,
271
273
  self._state.failure_count,
272
274
  )
273
- self._notify_state_change(
274
- CircuitState.OPEN,
275
- CircuitState.HALF_OPEN,
276
- )
277
- return True
278
- return False
275
+ return True, (CircuitState.OPEN, CircuitState.HALF_OPEN)
276
+ return False, None
279
277
 
280
278
  def _handle_attempt_half_open(self) -> bool:
281
279
  try:
@@ -292,20 +290,24 @@ class CircuitBreaker:
292
290
 
293
291
  def _should_attempt(self) -> bool:
294
292
  """Check if a call should be attempted."""
293
+ state_change: tuple[CircuitState, CircuitState] | None = None
294
+ should_attempt = False
295
+
295
296
  with self._state.lock:
296
297
  match self._state.state:
297
298
  case CircuitState.CLOSED:
298
- return True
299
-
299
+ should_attempt = True
300
300
  case CircuitState.OPEN:
301
- return self._handle_open_state()
302
-
301
+ should_attempt, state_change = self._handle_open_state()
303
302
  case CircuitState.HALF_OPEN:
304
- return self._handle_attempt_half_open()
303
+ should_attempt = self._handle_attempt_half_open()
305
304
 
306
- return False
305
+ if state_change:
306
+ self._notify_state_change(*state_change)
307
307
 
308
- def _handle_success_half_open(self) -> None:
308
+ return should_attempt
309
+
310
+ def _handle_success_half_open(self) -> tuple[CircuitState, CircuitState] | None:
309
311
  try:
310
312
  if not math.isfinite(self._state.success_count):
311
313
  self._state.success_count = 0
@@ -323,26 +325,27 @@ class CircuitBreaker:
323
325
  self.name,
324
326
  self._state.success_count,
325
327
  )
326
- self._notify_state_change(
327
- CircuitState.HALF_OPEN,
328
- CircuitState.CLOSED,
329
- )
328
+ return (CircuitState.HALF_OPEN, CircuitState.CLOSED)
329
+ return None
330
330
 
331
331
  def _record_success(self) -> None:
332
332
  """Record a successful call."""
333
+ state_change: tuple[CircuitState, CircuitState] | None = None
334
+
333
335
  with self._state.lock:
334
336
  match self._state.state:
335
337
  case CircuitState.HALF_OPEN:
336
- self._handle_success_half_open()
337
-
338
+ state_change = self._handle_success_half_open()
338
339
  case CircuitState.CLOSED:
339
340
  # Reset failure count on success
340
341
  self._state.failure_count = 0
341
-
342
- case CircuitState.OPEN: # pragma: no branch
342
+ case CircuitState.OPEN:
343
343
  pass # Should not happen, but handle gracefully
344
344
 
345
- def _handle_failure_half_open(self) -> None:
345
+ if state_change:
346
+ self._notify_state_change(*state_change)
347
+
348
+ def _handle_failure_half_open(self) -> tuple[CircuitState, CircuitState] | None:
346
349
  """Handle failure when in HALF_OPEN state."""
347
350
  self._state.state = CircuitState.OPEN
348
351
  self._state.half_open_attempts = 0
@@ -350,12 +353,9 @@ class CircuitBreaker:
350
353
  "Circuit %s reopened after failure in half-open",
351
354
  self.name,
352
355
  )
353
- self._notify_state_change(
354
- CircuitState.HALF_OPEN,
355
- CircuitState.OPEN,
356
- )
356
+ return (CircuitState.HALF_OPEN, CircuitState.OPEN)
357
357
 
358
- def _handle_failure_closed(self) -> None:
358
+ def _handle_failure_closed(self) -> tuple[CircuitState, CircuitState] | None:
359
359
  """Handle failure when in CLOSED state."""
360
360
  # Check against corrupted NaN/Inf failure_count
361
361
  try:
@@ -365,22 +365,14 @@ class CircuitBreaker:
365
365
  "Circuit %s opened due to state corruption (NaN/Inf failures)",
366
366
  self.name,
367
367
  )
368
- self._notify_state_change(
369
- CircuitState.CLOSED,
370
- CircuitState.OPEN,
371
- )
372
- return
368
+ return (CircuitState.CLOSED, CircuitState.OPEN)
373
369
  except TypeError:
374
370
  self._state.state = CircuitState.OPEN
375
371
  logger.warning(
376
372
  "Circuit %s opened due to type corruption in failure_count",
377
373
  self.name,
378
374
  )
379
- self._notify_state_change(
380
- CircuitState.CLOSED,
381
- CircuitState.OPEN,
382
- )
383
- return
375
+ return (CircuitState.CLOSED, CircuitState.OPEN)
384
376
 
385
377
  if self._state.failure_count >= self.config.failure_threshold:
386
378
  self._state.state = CircuitState.OPEN
@@ -390,10 +382,9 @@ class CircuitBreaker:
390
382
  self._state.failure_count,
391
383
  self.config.failure_threshold,
392
384
  )
393
- self._notify_state_change(
394
- CircuitState.CLOSED,
395
- CircuitState.OPEN,
396
- )
385
+ return (CircuitState.CLOSED, CircuitState.OPEN)
386
+
387
+ return None
397
388
 
398
389
  def _update_failure_metrics(self) -> None:
399
390
  try:
@@ -414,19 +405,22 @@ class CircuitBreaker:
414
405
  if isinstance(exc, self.config.excluded_exceptions):
415
406
  return
416
407
 
408
+ state_change: tuple[CircuitState, CircuitState] | None = None
409
+
417
410
  with self._state.lock:
418
411
  self._update_failure_metrics()
419
412
 
420
413
  match self._state.state:
421
414
  case CircuitState.HALF_OPEN:
422
- self._handle_failure_half_open()
423
-
415
+ state_change = self._handle_failure_half_open()
424
416
  case CircuitState.CLOSED:
425
- self._handle_failure_closed()
426
-
427
- case CircuitState.OPEN: # pragma: no branch
417
+ state_change = self._handle_failure_closed()
418
+ case CircuitState.OPEN:
428
419
  pass # Already open, nothing to do
429
420
 
421
+ if state_change:
422
+ self._notify_state_change(*state_change)
423
+
430
424
  def reset(self) -> None:
431
425
  """Reset circuit breaker to closed state."""
432
426
  with self._state.lock:
@@ -465,11 +459,16 @@ class CircuitBreaker:
465
459
  """
466
460
  if is_half_open:
467
461
  with self._state.lock:
468
- if (
469
- self._state.state == CircuitState.HALF_OPEN
470
- and self._state.half_open_attempts > 0
471
- ):
472
- self._state.half_open_attempts -= 1
462
+ try:
463
+ if (
464
+ self._state.state == CircuitState.HALF_OPEN
465
+ and math.isfinite(self._state.half_open_attempts)
466
+ and self._state.half_open_attempts > 0
467
+ ):
468
+ self._state.half_open_attempts -= 1
469
+ except TypeError:
470
+ # Reset if state is corrupted to prevent crash
471
+ self._state.half_open_attempts = 0
473
472
 
474
473
  def __call__(
475
474
  self, func: Callable[P, R] | Callable[P, Awaitable[R]]
@@ -48,6 +48,18 @@ except ImportError:
48
48
  _HAS_STRUCTLOG = False
49
49
 
50
50
 
51
+ def _validate_finite_or_default(
52
+ obj: object, attr_name: str, default_val: float | int
53
+ ) -> None:
54
+ """Validate that an attribute is finite, falling back to a default."""
55
+ try:
56
+ val = cast(float | int, getattr(obj, attr_name))
57
+ if not math.isfinite(val):
58
+ raise ValueError(f"{attr_name} must be a finite number")
59
+ except TypeError:
60
+ object.__setattr__(obj, attr_name, default_val)
61
+
62
+
51
63
  @dataclass(frozen=True)
52
64
  class RetryConfig:
53
65
  """Configuration for retry behavior.
@@ -75,16 +87,11 @@ class RetryConfig:
75
87
 
76
88
  def __post_init__(self) -> None:
77
89
  """Validate configuration parameters."""
78
- if not math.isfinite(self.max_attempts):
79
- raise ValueError("max_attempts must be a finite number")
80
- if not math.isfinite(self.initial_delay):
81
- raise ValueError("initial_delay must be a finite number")
82
- if not math.isfinite(self.max_delay):
83
- raise ValueError("max_delay must be a finite number")
84
- if not math.isfinite(self.exponential_base):
85
- raise ValueError("exponential_base must be a finite number")
86
- if not math.isfinite(self.jitter_factor):
87
- raise ValueError("jitter_factor must be a finite number")
90
+ _validate_finite_or_default(self, "max_attempts", 3)
91
+ _validate_finite_or_default(self, "initial_delay", 1.0)
92
+ _validate_finite_or_default(self, "max_delay", 60.0)
93
+ _validate_finite_or_default(self, "exponential_base", 2.0)
94
+ _validate_finite_or_default(self, "jitter_factor", 0.1)
88
95
 
89
96
 
90
97
  class RetryError(Exception):
@@ -114,15 +121,17 @@ def _calculate_base_delay(attempt: int, config: RetryConfig) -> float:
114
121
  safe_attempt = max(1, attempt)
115
122
  try:
116
123
  delay = config.initial_delay * (config.exponential_base ** (safe_attempt - 1))
117
- except OverflowError:
124
+ if not math.isfinite(delay):
125
+ delay = config.max_delay
126
+ except (OverflowError, TypeError):
118
127
  delay = config.max_delay
119
128
 
120
- if not math.isfinite(delay):
121
- delay = config.max_delay
129
+ try:
122
130
  if not math.isfinite(delay):
123
131
  delay = 0.0
124
-
125
- return min(delay, config.max_delay)
132
+ return min(delay, config.max_delay)
133
+ except TypeError:
134
+ return 0.0
126
135
 
127
136
 
128
137
  def _apply_jitter(delay: float, config: RetryConfig) -> float:
@@ -130,12 +139,15 @@ def _apply_jitter(delay: float, config: RetryConfig) -> float:
130
139
  if not config.jitter or not math.isfinite(delay):
131
140
  return delay
132
141
 
133
- jitter_amount = delay * config.jitter_factor
134
- if math.isfinite(jitter_amount):
135
- try:
136
- delay += secrets.SystemRandom().uniform(-jitter_amount, jitter_amount)
137
- except Exception as e:
138
- logger.warning("Failed to add jitter to delay: %s", str(e))
142
+ try:
143
+ jitter_amount = delay * config.jitter_factor
144
+ if math.isfinite(jitter_amount):
145
+ try:
146
+ delay += secrets.SystemRandom().uniform(-jitter_amount, jitter_amount)
147
+ except Exception as e:
148
+ logger.warning("Failed to add jitter to delay: %s", str(e))
149
+ except (TypeError, OverflowError, ValueError, Exception) as e:
150
+ logger.warning("Failed to add jitter to delay due to mutation: %s", str(e))
139
151
 
140
152
  return delay
141
153
 
@@ -187,7 +199,7 @@ def _log_retry_attempt_fallback(
187
199
  config: RetryConfig,
188
200
  ) -> None:
189
201
  """Log the retry attempt if no callback is provided."""
190
- if _HAS_STRUCTLOG and _structlog_logger is not None: # pragma: no branch
202
+ if _HAS_STRUCTLOG and _structlog_logger is not None:
191
203
  _structlog_logger.warning(
192
204
  "retry_attempted",
193
205
  function=func_name,
@@ -373,7 +385,7 @@ def retry(
373
385
  last_exception: Exception | None = None
374
386
  last_result: R | None = None
375
387
 
376
- for attempt in range(1, max_attempts + 1): # pragma: no branch
388
+ for attempt in range(1, max_attempts + 1):
377
389
  last_result = None
378
390
  try:
379
391
  last_result = await func_coro(*args, **kwargs)
@@ -421,7 +433,7 @@ def retry(
421
433
  last_exception: Exception | None = None
422
434
  last_result: R | None = None
423
435
 
424
- for attempt in range(1, max_attempts + 1): # pragma: no branch
436
+ for attempt in range(1, max_attempts + 1):
425
437
  last_result = None
426
438
  try:
427
439
  last_result = func_sync(*args, **kwargs)
@@ -558,7 +570,12 @@ class Retrier:
558
570
 
559
571
  # Safe cast: issubclass guard above ensures exc_val is Exception
560
572
  self.last_exception = exc_val if isinstance(exc_val, Exception) else None
561
- self.attempt += 1
573
+ try:
574
+ if not math.isfinite(self.attempt):
575
+ return False
576
+ self.attempt += 1
577
+ except TypeError:
578
+ return False
562
579
 
563
580
  if self.attempt >= self.config.max_attempts:
564
581
  return False # Max attempts reached, propagate exception
@@ -79,8 +79,12 @@ class BaseWatcher(ABC):
79
79
  while not self._stop_event.is_set():
80
80
  try:
81
81
  await self._run()
82
- except Exception:
83
- logger.exception("%s encountered an error", type(self).__name__)
82
+ except Exception as exc:
83
+ logger.exception(
84
+ "%s encountered an error",
85
+ type(self).__name__,
86
+ exc_info=exc,
87
+ )
84
88
  try:
85
89
  await asyncio.wait_for(self._stop_event.wait(), timeout=self._interval)
86
90
  except TimeoutError:
@@ -143,11 +143,8 @@ class HealthPinger(BaseWatcher):
143
143
 
144
144
  self._update_target_status(target, is_healthy)
145
145
 
146
- def _update_target_status(self, target: HealthTarget, is_healthy: bool) -> None:
147
- """Update target status and handle side-effects."""
148
- previous = self._last_status.get(target.name)
149
-
150
- # Open circuit breaker preventively on failure (always checked)
146
+ def _check_and_open_breaker(self, target: HealthTarget, is_healthy: bool) -> None:
147
+ """Open circuit breaker preventively on failure (always checked)."""
151
148
  if (
152
149
  not is_healthy
153
150
  and target.circuit_breaker is not None
@@ -155,11 +152,8 @@ class HealthPinger(BaseWatcher):
155
152
  ):
156
153
  _force_open_breaker(target.circuit_breaker, target.name)
157
154
 
158
- if previous == is_healthy:
159
- return
160
-
161
- self._last_status[target.name] = is_healthy
162
-
155
+ def _notify_health_change(self, target: HealthTarget, is_healthy: bool) -> None:
156
+ """Notify on health status change and log it."""
163
157
  if self._on_health_change is not None:
164
158
  self._on_health_change(target.name, is_healthy)
165
159
 
@@ -168,6 +162,19 @@ class HealthPinger(BaseWatcher):
168
162
  else:
169
163
  logger.warning("Target '%s' is now unhealthy", target.name)
170
164
 
165
+ def _update_target_status(self, target: HealthTarget, is_healthy: bool) -> None:
166
+ """Update target status and handle side-effects."""
167
+ previous = self._last_status.get(target.name)
168
+
169
+ self._check_and_open_breaker(target, is_healthy)
170
+
171
+ if previous == is_healthy:
172
+ return
173
+
174
+ self._last_status[target.name] = is_healthy
175
+
176
+ self._notify_health_change(target, is_healthy)
177
+
171
178
  async def _run(self) -> None:
172
179
  """Execute a single health-check cycle concurrently."""
173
180
  await asyncio.gather(*(self._process_target(t) for t in self._targets))
@@ -105,14 +105,14 @@ def validate_inputs(
105
105
  bound.apply_defaults()
106
106
 
107
107
  # Validate each parameter that has a validator
108
- for param_name, validator in validators.items(): # pragma: no branch
109
- if param_name in bound.arguments: # pragma: no branch
108
+ for param_name, validator in validators.items():
109
+ if param_name in bound.arguments:
110
110
  value = bound.arguments[param_name]
111
111
  try:
112
112
  # Call validator - it should raise on invalid input
113
113
  validated = validator(value)
114
114
  # Update to validated value if returned
115
- if validated is not None: # pragma: no branch
115
+ if validated is not None:
116
116
  bound.arguments[param_name] = validated
117
117
  except (ValueError, TypeError) as e:
118
118
  raise ValidationError(
@@ -165,7 +165,7 @@ def guard_exceptions(
165
165
  try:
166
166
  return func(*args, **kwargs)
167
167
  except catch as e:
168
- if log_errors: # pragma: no branch
168
+ if log_errors:
169
169
  import logging
170
170
 
171
171
  logging.getLogger("taipanstack.security").warning(
@@ -378,8 +378,8 @@ def require_type(
378
378
  bound = sig.bind(*args, **kwargs)
379
379
  bound.apply_defaults()
380
380
 
381
- for param_name, expected_type in type_hints.items(): # pragma: no branch
382
- if param_name in bound.arguments: # pragma: no branch
381
+ for param_name, expected_type in type_hints.items():
382
+ if param_name in bound.arguments:
383
383
  value = bound.arguments[param_name]
384
384
  if not isinstance(value, expected_type):
385
385
  raise TypeError(
@@ -368,7 +368,7 @@ def _check_denied_extension(
368
368
  def _check_allowed_extension(
369
369
  ext: str, original_name: str, allowed_extensions: Sequence[str] | None
370
370
  ) -> None:
371
- if allowed_extensions is not None: # pragma: no branch
371
+ if allowed_extensions is not None:
372
372
  allowed = {_normalize_ext(e) for e in allowed_extensions}
373
373
  if ext not in allowed:
374
374
  raise SecurityError(
@@ -111,29 +111,32 @@ def sanitize_string(
111
111
  return result
112
112
 
113
113
 
114
+ def _get_filename_from_path(filename: str) -> str:
115
+ """Extract the base filename from a full path."""
116
+ slash_idx = max(filename.rfind("/"), filename.rfind("\\"))
117
+ if slash_idx >= 0:
118
+ return filename[slash_idx + 1 :]
119
+ return filename
120
+
121
+
122
+ def _has_valid_extension(name: str, idx: int) -> bool:
123
+ """Determine if a dot represents a valid extension."""
124
+ return idx > 0 and not all(c == "." for c in name) and name != ".."
125
+
126
+
114
127
  def _extract_stem_and_suffix(
115
128
  filename: str, preserve_extension: bool
116
129
  ) -> tuple[str, str]:
117
130
  """Extract stem and suffix from a filename."""
118
- # Get parts using native string manipulation instead of Path for performance
119
- # Emulate Path(filename).name
120
- name = filename
121
- slash_idx = max(name.rfind("/"), name.rfind("\\"))
122
- if slash_idx >= 0:
123
- name = name[slash_idx + 1 :]
124
-
125
- stem = name
126
- suffix = ""
127
-
131
+ name = _get_filename_from_path(filename)
128
132
  idx = name.rfind(".")
129
- # Pathlib considers pure dotfiles (like ".hidden") or "..." as stem no suffix
130
- if idx > 0 and not all(c == "." for c in name) and name != "..":
133
+
134
+ if _has_valid_extension(name, idx):
131
135
  stem = name[:idx]
132
136
  suffix = name[idx:] if preserve_extension else ""
133
- else:
134
- stem = name
137
+ return stem, suffix
135
138
 
136
- return stem, suffix
139
+ return name, ""
137
140
 
138
141
 
139
142
  def _remove_invalid_chars(stem: str, replacement: str) -> str:
@@ -281,7 +284,7 @@ def _handle_normal_part(part: str, parts: list[str]) -> None:
281
284
  parts.append(part)
282
285
  else:
283
286
  safe_part = sanitize_filename(part, preserve_extension=True)
284
- if safe_part and safe_part != "..": # pragma: no branch
287
+ if safe_part and safe_part != "..":
285
288
  parts.append(safe_part)
286
289
 
287
290
 
@@ -289,7 +292,7 @@ def _process_path_part(part: str, parts: list[str], anchor: str) -> None:
289
292
  """Process a single path component, updating the parts list inline."""
290
293
  if part == "..":
291
294
  _handle_dot_dot(parts, anchor)
292
- elif part != ".": # pragma: no branch
295
+ elif part != ".":
293
296
  _handle_normal_part(part, parts)
294
297
 
295
298
 
@@ -320,7 +323,7 @@ def _apply_base_dir_constraint(
320
323
  raise ValueError(msg) from e
321
324
 
322
325
  # Make absolute relative to base
323
- if not sanitized.is_absolute(): # pragma: no branch
326
+ if not sanitized.is_absolute():
324
327
  return base / sanitized
325
328
 
326
329
  return sanitized
@@ -332,7 +335,7 @@ def _normalize_path_input(path: str | Path) -> Path:
332
335
  if len(path) > MAX_PATH_LENGTH:
333
336
  msg = "Path length exceeds maximum allowed"
334
337
  raise ValueError(msg)
335
- if "\x00" in path: # pragma: no branch
338
+ if "\x00" in path:
336
339
  path = path.replace("\x00", "")
337
340
  return Path(path)
338
341
 
@@ -344,12 +347,12 @@ def _normalize_path_input(path: str | Path) -> Path:
344
347
 
345
348
  def _reconstruct_path(original_path: Path, parts: list[str]) -> Path:
346
349
  """Reconstruct a path from its sanitized parts."""
347
- if original_path.is_absolute(): # pragma: no branch
350
+ if original_path.is_absolute():
348
351
  # Use path.anchor to correctly preserve absolute roots on Windows (e.g. C:\)
349
352
  anchor = Path(original_path.anchor)
350
353
  return anchor.joinpath(*parts) if parts else anchor
351
354
 
352
- if parts: # pragma: no branch
355
+ if parts:
353
356
  return Path().joinpath(*parts)
354
357
 
355
358
  return Path()
@@ -7,7 +7,6 @@ declarative, type-safe input validation inside ``BaseModel``
7
7
  definitions.
8
8
  """
9
9
 
10
- import html
11
10
  import re
12
11
  from typing import Annotated
13
12
 
@@ -136,44 +135,3 @@ SafeProjectName = Annotated[str, AfterValidator(_validate_safe_project_name)]
136
135
 
137
136
 
138
137
  _SQL_IDENTIFIER_REGEX = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*\Z")
139
-
140
-
141
- def _sanitize_safe_html(text: str) -> str:
142
- """Sanitize a string to prevent XSS attacks.
143
-
144
- Args:
145
- text: The string to sanitize.
146
-
147
- Returns:
148
- The HTML-escaped string.
149
-
150
- """
151
- return html.escape(text)
152
-
153
-
154
- def _validate_safe_sql_identifier(identifier: str) -> str:
155
- """Validate a string is a safe SQL identifier.
156
-
157
- Args:
158
- identifier: The SQL identifier to validate.
159
-
160
- Returns:
161
- The validated SQL identifier.
162
-
163
- Raises:
164
- ValueError: If the identifier implies SQL injection risk.
165
-
166
- """
167
- if not _SQL_IDENTIFIER_REGEX.match(identifier):
168
- raise ValueError(
169
- f"Invalid SQL identifier: '{identifier}'. "
170
- "Must match ^[a-zA-Z_][a-zA-Z0-9_]*$"
171
- )
172
- return identifier
173
-
174
-
175
- SafeHtml = Annotated[str, AfterValidator(_sanitize_safe_html)]
176
- """A string sanitized for safe inclusion in HTML templates."""
177
-
178
- SafeSqlIdentifier = Annotated[str, AfterValidator(_validate_safe_sql_identifier)]
179
- """A string validated as a safe dynamic SQL identifier (e.g., table or column name)."""
@@ -6,8 +6,7 @@ project names, URLs, etc. All validators raise ValueError on invalid input.
6
6
  """
7
7
 
8
8
  import re
9
- import urllib.parse
10
- from urllib.parse import urlsplit
9
+ from urllib.parse import SplitResult, urlsplit
11
10
 
12
11
  # Constants to avoid magic values (PLR2004)
13
12
  PYTHON_MAJOR_VERSION = 3
@@ -317,7 +316,7 @@ def _check_url_basics(url: str) -> None:
317
316
 
318
317
 
319
318
  def _check_scheme(
320
- parsed: urllib.parse.SplitResult,
319
+ parsed: SplitResult,
321
320
  allowed_schemes: tuple[str, ...],
322
321
  ) -> None:
323
322
  """Validate the URL scheme."""
@@ -340,7 +339,7 @@ def _check_tld(domain: str) -> None:
340
339
 
341
340
 
342
341
  def _check_url_domain(
343
- parsed: urllib.parse.SplitResult,
342
+ parsed: SplitResult,
344
343
  allowed_schemes: tuple[str, ...],
345
344
  require_tld: bool,
346
345
  ) -> None:
@@ -68,8 +68,55 @@ def _is_sensitive(key: object, regex: re.Pattern[str] | None) -> bool:
68
68
  return bool(regex.search(key))
69
69
 
70
70
 
71
+ def _redact(obj: object, seen: set[int] | None = None) -> object:
72
+ """Redact sensitive data recursively with circular reference protection.
73
+
74
+ Args:
75
+ obj: The object to redact.
76
+ seen: Set of IDs of already processed containers.
77
+
78
+ Returns:
79
+ A new object with sensitive data redacted.
80
+
81
+ """
82
+ if _SENSITIVE_KEY_REGEX is None:
83
+ return obj
84
+
85
+ if seen is None:
86
+ seen = set()
87
+
88
+ # Detect circular references
89
+ if id(obj) in seen:
90
+ return REDACTED_VALUE
91
+
92
+ if isinstance(obj, MutableMapping):
93
+ seen.add(id(obj))
94
+ # Create a new dict to avoid in-place mutation of shared state
95
+ return {
96
+ k: (
97
+ REDACTED_VALUE
98
+ if _is_sensitive(k, _SENSITIVE_KEY_REGEX)
99
+ else _redact(v, seen)
100
+ )
101
+ for k, v in obj.items()
102
+ }
103
+
104
+ if isinstance(obj, list):
105
+ seen.add(id(obj))
106
+ return [_redact(item, seen) for item in obj]
107
+
108
+ if isinstance(obj, tuple):
109
+ seen.add(id(obj))
110
+ return tuple(_redact(item, seen) for item in obj)
111
+
112
+ return obj
113
+
114
+
71
115
  def _redact_dict(d: MutableMapping[str, object]) -> None:
72
- """Redact sensitive keys in a dictionary in-place.
116
+ """Redact sensitive keys in a dictionary in-place (top-level only).
117
+
118
+ Note: Nested structures are replaced with redacted copies to prevent
119
+ shared state mutation.
73
120
 
74
121
  Args:
75
122
  d: The dictionary to redact.
@@ -78,9 +125,11 @@ def _redact_dict(d: MutableMapping[str, object]) -> None:
78
125
  if _SENSITIVE_KEY_REGEX is None:
79
126
  return
80
127
 
81
- for key in d:
128
+ for key, value in list(d.items()):
82
129
  if _is_sensitive(key, _SENSITIVE_KEY_REGEX):
83
130
  d[key] = REDACTED_VALUE
131
+ else:
132
+ d[key] = _redact(value)
84
133
 
85
134
 
86
135
  def mask_sensitive_data_processor(
@@ -66,6 +66,21 @@ class RateLimiter:
66
66
  except TypeError:
67
67
  return False
68
68
 
69
+ def _calculate_new_tokens(self, elapsed: float) -> float | None:
70
+ """Calculate new tokens based on elapsed time."""
71
+ new_tokens = elapsed * (self.capacity / self.time_window)
72
+ return new_tokens if math.isfinite(new_tokens) else None
73
+
74
+ def _apply_new_tokens(self, new_tokens: float) -> bool:
75
+ """Apply new tokens to the bucket."""
76
+ self.tokens += new_tokens
77
+ if not math.isfinite(self.tokens):
78
+ # Reset to previous state or capacity if corrupted
79
+ self.tokens = self.capacity
80
+ return False
81
+ self.tokens = min(self.tokens, self.capacity)
82
+ return True
83
+
69
84
  def _add_tokens(self, now: float) -> bool:
70
85
  """Calculate and add new tokens to the bucket based on elapsed time.
71
86
 
@@ -77,31 +92,31 @@ class RateLimiter:
77
92
 
78
93
  """
79
94
  try:
80
- elapsed = max(0.0, now - self.last_update)
95
+ raw_elapsed = now - self.last_update
96
+ if not math.isfinite(raw_elapsed):
97
+ return False
98
+ elapsed = max(0.0, raw_elapsed)
81
99
  self.last_update = now
82
100
 
83
101
  # Prevent state corruption or infinite elapsed time
84
- if not (self._is_valid_bucket_state() and math.isfinite(elapsed)):
102
+ if not self._is_valid_bucket_state():
85
103
  return False
86
104
 
87
- # Add tokens for elapsed time based on fill rate
88
- new_tokens = elapsed * (self.capacity / self.time_window)
89
-
90
- if not math.isfinite(new_tokens):
105
+ new_tokens = self._calculate_new_tokens(elapsed)
106
+ if new_tokens is None:
91
107
  return False
92
108
 
93
- self.tokens += new_tokens
94
-
95
- if not math.isfinite(self.tokens):
96
- # Reset to previous state or capacity if corrupted
97
- self.tokens = self.capacity
98
- return False
99
-
100
- self.tokens = min(self.tokens, self.capacity)
101
- return True
109
+ return self._apply_new_tokens(new_tokens)
102
110
  except TypeError:
103
111
  return False
104
112
 
113
+ def _try_consume(self, tokens: float) -> bool:
114
+ """Attempt to consume the tokens from the bucket if available."""
115
+ if self.tokens >= tokens:
116
+ self.tokens -= tokens
117
+ return True
118
+ return False
119
+
105
120
  def consume(self, tokens: float = 1.0) -> bool:
106
121
  """Try to consume tokens.
107
122
 
@@ -124,10 +139,7 @@ class RateLimiter:
124
139
  if math.isfinite(now) and not self._add_tokens(now):
125
140
  return False
126
141
 
127
- if self.tokens >= tokens:
128
- self.tokens -= tokens
129
- return True
130
- return False
142
+ return self._try_consume(tokens)
131
143
  except TypeError:
132
144
  return False
133
145
 
File without changes