failsafe-py 0.1.0__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 (86) hide show
  1. failsafe_py-0.1.0/.github/workflows/ci.yml +39 -0
  2. failsafe_py-0.1.0/.github/workflows/release.yml +57 -0
  3. failsafe_py-0.1.0/.gitignore +12 -0
  4. failsafe_py-0.1.0/.readthedocs.yaml +24 -0
  5. failsafe_py-0.1.0/AGENTS.md +43 -0
  6. failsafe_py-0.1.0/CONTRIBUTING.md +51 -0
  7. failsafe_py-0.1.0/LICENSE +21 -0
  8. failsafe_py-0.1.0/PKG-INFO +64 -0
  9. failsafe_py-0.1.0/PORT.md +99 -0
  10. failsafe_py-0.1.0/README.md +41 -0
  11. failsafe_py-0.1.0/RELEASING.md +61 -0
  12. failsafe_py-0.1.0/docs/assets/brand.css +21 -0
  13. failsafe_py-0.1.0/docs/assets/favicon.png +0 -0
  14. failsafe_py-0.1.0/docs/assets/logo.svg +12 -0
  15. failsafe_py-0.1.0/docs/index.md +30 -0
  16. failsafe_py-0.1.0/docs/reference/adaptive-limiter.md +13 -0
  17. failsafe_py-0.1.0/docs/reference/adaptive-throttler.md +11 -0
  18. failsafe_py-0.1.0/docs/reference/budget.md +11 -0
  19. failsafe_py-0.1.0/docs/reference/bulkhead.md +9 -0
  20. failsafe_py-0.1.0/docs/reference/cache.md +13 -0
  21. failsafe_py-0.1.0/docs/reference/circuit-breaker.md +15 -0
  22. failsafe_py-0.1.0/docs/reference/conditions.md +8 -0
  23. failsafe_py-0.1.0/docs/reference/delays.md +15 -0
  24. failsafe_py-0.1.0/docs/reference/entry-points.md +14 -0
  25. failsafe_py-0.1.0/docs/reference/events.md +25 -0
  26. failsafe_py-0.1.0/docs/reference/exceptions.md +19 -0
  27. failsafe_py-0.1.0/docs/reference/fallback.md +7 -0
  28. failsafe_py-0.1.0/docs/reference/hedge.md +7 -0
  29. failsafe_py-0.1.0/docs/reference/priority.md +27 -0
  30. failsafe_py-0.1.0/docs/reference/rate-limiter.md +9 -0
  31. failsafe_py-0.1.0/docs/reference/retry.md +9 -0
  32. failsafe_py-0.1.0/docs/reference/timeout.md +9 -0
  33. failsafe_py-0.1.0/examples/async_hedge.py +50 -0
  34. failsafe_py-0.1.0/examples/basics.py +43 -0
  35. failsafe_py-0.1.0/examples/httpx_retry.py +65 -0
  36. failsafe_py-0.1.0/mkdocs.yml +86 -0
  37. failsafe_py-0.1.0/pyproject.toml +56 -0
  38. failsafe_py-0.1.0/src/failsafe/__init__.py +103 -0
  39. failsafe_py-0.1.0/src/failsafe/_async.py +285 -0
  40. failsafe_py-0.1.0/src/failsafe/_conditions.py +166 -0
  41. failsafe_py-0.1.0/src/failsafe/_core.py +448 -0
  42. failsafe_py-0.1.0/src/failsafe/_delays.py +223 -0
  43. failsafe_py-0.1.0/src/failsafe/_events.py +139 -0
  44. failsafe_py-0.1.0/src/failsafe/_exceptions.py +147 -0
  45. failsafe_py-0.1.0/src/failsafe/_prioritizer.py +257 -0
  46. failsafe_py-0.1.0/src/failsafe/_semaphore.py +245 -0
  47. failsafe_py-0.1.0/src/failsafe/_stats.py +155 -0
  48. failsafe_py-0.1.0/src/failsafe/_sync.py +196 -0
  49. failsafe_py-0.1.0/src/failsafe/_windows.py +395 -0
  50. failsafe_py-0.1.0/src/failsafe/adaptive_limiter.py +624 -0
  51. failsafe_py-0.1.0/src/failsafe/adaptive_throttler.py +374 -0
  52. failsafe_py-0.1.0/src/failsafe/budget.py +145 -0
  53. failsafe_py-0.1.0/src/failsafe/bulkhead.py +166 -0
  54. failsafe_py-0.1.0/src/failsafe/cache.py +166 -0
  55. failsafe_py-0.1.0/src/failsafe/circuit_breaker.py +454 -0
  56. failsafe_py-0.1.0/src/failsafe/fallback.py +101 -0
  57. failsafe_py-0.1.0/src/failsafe/hedge.py +214 -0
  58. failsafe_py-0.1.0/src/failsafe/httpx.py +300 -0
  59. failsafe_py-0.1.0/src/failsafe/priority.py +358 -0
  60. failsafe_py-0.1.0/src/failsafe/py.typed +0 -0
  61. failsafe_py-0.1.0/src/failsafe/rate_limiter.py +366 -0
  62. failsafe_py-0.1.0/src/failsafe/retry.py +237 -0
  63. failsafe_py-0.1.0/src/failsafe/timeout.py +78 -0
  64. failsafe_py-0.1.0/tests/conftest.py +65 -0
  65. failsafe_py-0.1.0/tests/test_adaptive_limiter.py +349 -0
  66. failsafe_py-0.1.0/tests/test_adaptive_throttler.py +287 -0
  67. failsafe_py-0.1.0/tests/test_budget.py +187 -0
  68. failsafe_py-0.1.0/tests/test_bulkhead.py +216 -0
  69. failsafe_py-0.1.0/tests/test_cache.py +306 -0
  70. failsafe_py-0.1.0/tests/test_circuit_breaker.py +452 -0
  71. failsafe_py-0.1.0/tests/test_core.py +198 -0
  72. failsafe_py-0.1.0/tests/test_drivers.py +256 -0
  73. failsafe_py-0.1.0/tests/test_fallback.py +127 -0
  74. failsafe_py-0.1.0/tests/test_hedge.py +371 -0
  75. failsafe_py-0.1.0/tests/test_httpx.py +402 -0
  76. failsafe_py-0.1.0/tests/test_import.py +5 -0
  77. failsafe_py-0.1.0/tests/test_issues.py +135 -0
  78. failsafe_py-0.1.0/tests/test_prioritizer.py +339 -0
  79. failsafe_py-0.1.0/tests/test_priority.py +217 -0
  80. failsafe_py-0.1.0/tests/test_rate_limiter.py +380 -0
  81. failsafe_py-0.1.0/tests/test_retry.py +491 -0
  82. failsafe_py-0.1.0/tests/test_semaphore.py +233 -0
  83. failsafe_py-0.1.0/tests/test_timeout.py +265 -0
  84. failsafe_py-0.1.0/tests/test_typing.py +97 -0
  85. failsafe_py-0.1.0/tests/test_windows.py +228 -0
  86. failsafe_py-0.1.0/uv.lock +1183 -0
@@ -0,0 +1,39 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ concurrency:
9
+ group: ${{ github.workflow }}-${{ github.ref }}
10
+ cancel-in-progress: true
11
+
12
+ jobs:
13
+ test:
14
+ runs-on: ubuntu-latest
15
+ strategy:
16
+ fail-fast: false
17
+ matrix:
18
+ python-version: ["3.11", "3.12", "3.13", "3.14", "3.15"]
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+ - uses: astral-sh/setup-uv@v5
22
+ with:
23
+ enable-cache: true
24
+ - run: uv sync --locked --python ${{ matrix.python-version }}
25
+ - run: uv run --python ${{ matrix.python-version }} ruff check .
26
+ - run: uv run --python ${{ matrix.python-version }} ruff format --check .
27
+ - run: uv run --python ${{ matrix.python-version }} mypy
28
+ - run: uv run --python ${{ matrix.python-version }} pytest
29
+
30
+ docs:
31
+ runs-on: ubuntu-latest
32
+ steps:
33
+ - uses: actions/checkout@v4
34
+ - uses: astral-sh/setup-uv@v5
35
+ with:
36
+ enable-cache: true
37
+ - run: uv sync --locked --group docs
38
+ # --strict, so a stale docstring fails here rather than on Read the Docs.
39
+ - run: uv run mkdocs build --strict
@@ -0,0 +1,57 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ tags: ["v*"]
6
+
7
+ # A tag push is not a place to discover the tests are red.
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: astral-sh/setup-uv@v5
14
+ with:
15
+ enable-cache: true
16
+
17
+ - name: Check the tag matches the packaged version
18
+ run: |
19
+ tagged="${GITHUB_REF_NAME#v}"
20
+ packaged="$(uv run --no-project python -c '
21
+ import pathlib, tomllib
22
+ print(tomllib.loads(pathlib.Path("pyproject.toml").read_text())["project"]["version"])
23
+ ')"
24
+ if [ "$tagged" != "$packaged" ]; then
25
+ echo "::error::tag $GITHUB_REF_NAME does not match version $packaged in pyproject.toml"
26
+ exit 1
27
+ fi
28
+
29
+ - run: uv sync --locked
30
+ - run: uv run ruff check .
31
+ - run: uv run ruff format --check .
32
+ - run: uv run mypy
33
+ - run: uv run pytest
34
+
35
+ - run: uv build
36
+ - name: Check the artifacts render on PyPI
37
+ run: uv run --with twine twine check --strict dist/*
38
+
39
+ - uses: actions/upload-artifact@v4
40
+ with:
41
+ name: dist
42
+ path: dist/
43
+
44
+ publish:
45
+ needs: build
46
+ runs-on: ubuntu-latest
47
+ environment: pypi
48
+ permissions:
49
+ id-token: write # the OIDC token; no API token stored anywhere
50
+ steps:
51
+ - uses: actions/download-artifact@v4
52
+ with:
53
+ name: dist
54
+ path: dist/
55
+ - uses: pypa/gh-action-pypi-publish@release/v1
56
+ # Afterwards: activate the new version on Read the Docs — tags arrive inactive.
57
+ # See RELEASING.md.
@@ -0,0 +1,12 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .mypy_cache/
8
+ .ruff_cache/
9
+ .pytest_cache/
10
+ .coverage
11
+ htmlcov/
12
+ site/
@@ -0,0 +1,24 @@
1
+ version: 2
2
+
3
+ build:
4
+ os: ubuntu-24.04
5
+ tools:
6
+ python: "3.13"
7
+ jobs:
8
+ # Overriding the build step, so mkdocs.fail_on_warning does not apply: --strict
9
+ # is the equivalent, and it is the point of the setup. A renamed parameter or a
10
+ # dead cross-reference fails the build rather than rotting the published
11
+ # reference. Never relax it to make a build pass.
12
+ build:
13
+ html:
14
+ - uv run --group docs mkdocs build --strict --site-dir $READTHEDOCS_OUTPUT/html
15
+
16
+ python:
17
+ install:
18
+ - method: uv
19
+ command: sync
20
+ groups:
21
+ - docs
22
+
23
+ mkdocs:
24
+ configuration: mkdocs.yml
@@ -0,0 +1,43 @@
1
+ # AGENTS.md
2
+
3
+ ## Commits
4
+
5
+ Conventional commits. Terse descriptions — a subject line, nothing more unless the
6
+ *why* is genuinely non-obvious.
7
+
8
+ ```
9
+ <type>(<optional scope>): <description>
10
+ ```
11
+
12
+ - `<description>`: imperative, lower case, no trailing period, ≤ 50 chars.
13
+ - Types: `feat`, `fix`, `docs`, `test`, `refactor`, `perf`, `chore`, `build`, `ci`.
14
+ - Scope is the module or artifact (`retry`, `core`, `httpx`), omitted when it adds nothing.
15
+ - Breaking changes take a `!` after the type or scope: `feat!:`, `refactor(retry)!:`.
16
+ - Body only for surprising decisions or a `BREAKING CHANGE:` footer. No restating the diff.
17
+
18
+ Good:
19
+
20
+ ```
21
+ feat(retry): add backoff jitter
22
+ fix(core): release bulkhead permit on abandon
23
+ docs: add PLAN.md
24
+ chore: add pyproject
25
+ ```
26
+
27
+ Bad: `Updated some files`, `feat: this commit adds a new retry policy which
28
+ allows users to configure the maximum number of attempts`.
29
+
30
+ ## Tooling
31
+
32
+ - No user-wide installs. Ephemeral `uv` environments or containers only — never
33
+ `pip install` / `gem install` into the system or home directory.
34
+ - `uv run` for anything that needs a dependency.
35
+ - `uv.lock` is committed — it pins dev tooling only, not what consumers install. Use `uv sync`
36
+ to honour it.
37
+
38
+ ## Code
39
+
40
+ - Python 3.11+, stdlib only in the core. Optional extras at integration boundaries.
41
+ - `ruff` + `mypy --strict` clean; `py.typed` ships.
42
+ - Docstrings on every public symbol — they are the input to the API reference.
43
+ - Never swallow `BaseException`. `CancelledError` is not a retryable failure.
@@ -0,0 +1,51 @@
1
+ # Reporting Bugs
2
+
3
+ Bug reports are welcome and appreciated. When filing an issue, please include a small code snippet that demonstrates the bug if you can, else include a good description of how to reproduce the bug.
4
+
5
+ ## Contributing Bug Fixes
6
+
7
+ Pull requests for bugs related to existing features are always welcome.
8
+
9
+ # Features
10
+
11
+ ## New failsafe features: probably not
12
+
13
+ Overall the goal of this project is to follow `failsafe` (Java) and
14
+ `failsafe-go` (Go) implementations and be a strict subset of those projects. I
15
+ do not wish to deviate too much, and am not really planning to add features
16
+ which are not in one of those projects, please make your case in what I
17
+ consider the "upstream" projects first (CC'ing Python maintainers is welcome!).
18
+
19
+ If there's an agreement to support this new feature in Java or Go, I'm happy to
20
+ look into implementations here, or review Pull Requests.
21
+
22
+ ## Python integration
23
+
24
+ That being said I expect that my Python integration of those projects may not
25
+ be perfect so I will happily consider feature requests for "The Python API of
26
+ this feature should do X / Y / Z" as long as this matches the behavior of
27
+ failsafe.
28
+
29
+ # Contributing docstrings, Documentation or Website Fixes
30
+
31
+ Fixes to the failsafe-py docstrings, documentation or website are welcome. Just
32
+ clone the [website repo](https://github.com/failsafe-py/failsafe-py.github.io)
33
+ and feel free to submit a pull request.
34
+
35
+ # Working on the Code
36
+
37
+ [uv](https://docs.astral.sh/uv/) manages the environment:
38
+
39
+ ```bash
40
+ uv sync
41
+ uv run pytest
42
+ uv run ruff check .
43
+ uv run ruff format .
44
+ uv run mypy
45
+ ```
46
+
47
+ All four must pass. CI runs them on every
48
+ [supported Python version](https://devguide.python.org/versions/).
49
+
50
+ Breaking changes mark their commit with `!` — `feat!: …` — so they reach the release
51
+ notes. See [RELEASING.md](RELEASING.md).
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026-present Nicolas Dumazet and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.5
2
+ Name: failsafe-py
3
+ Version: 0.1.0
4
+ Summary: Fault tolerance and resilience policies for Python
5
+ Project-URL: Source, https://github.com/failsafe-py/failsafe-py
6
+ Project-URL: Documentation, https://failsafe-py.github.io
7
+ Author-email: Nicolas Dumazet <ndumazet@aire.ai>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: circuit-breaker,fault-tolerance,resilience,retry,timeout
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Programming Language :: Python :: 3.15
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.11
20
+ Provides-Extra: httpx
21
+ Requires-Dist: httpx>=0.27; extra == 'httpx'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # failsafe-py
25
+
26
+ [![License](http://img.shields.io/:license-mit-brightgreen.svg)](https://opensource.org/licenses/MIT)
27
+
28
+ failsafe-py is a library for building resilient, fault tolerant Python applications. It works by
29
+ wrapping functions with one or more resilience policies, which can be combined and composed as
30
+ needed. Policies include:
31
+
32
+ - Failure handling: Retry, Fallback
33
+ - Load limiting: Circuit Breaker, Adaptive Limiter, Adaptive Throttler, Bulkhead, Rate Limiter, Cache
34
+ - Time limiting: Timeout, Hedge
35
+
36
+ A Python port of [failsafe-go](https://github.com/failsafe-go/failsafe-go). See
37
+ [PORT.md](PORT.md) for divergences.
38
+
39
+ ## Project status
40
+
41
+ This is mostly agentic port of failsafe-go alongside its website, because I
42
+ needed a similar library at work in Python (Google-external equivalent of
43
+ "extensible stubs / canonical stubs"). It was fast to do, "only" costing me
44
+ about a weekend trying to improve the agent's writing / API choices.
45
+
46
+ Some disclaimers:
47
+
48
+ * Agents are ... agents. Their prose is annoying. Their tests are not that
49
+ good. They sometimes make mistakes [...].
50
+ * I'm not that attached to the particular implementation.
51
+ * This is a v0.1.0. I would want, welcome, and encourage specific API design
52
+ feedback (via Github bugs). I am happy to consider breaking API changes in
53
+ future, in particular to have more "Python friendly" APIs if I missed
54
+ something whilst guiding my agent.
55
+
56
+ I would aim for a v1.0 release before end of 2026, hopefully after feedback
57
+ from the community.
58
+
59
+ See [CONTRIBUTING.md](CONTRIBUTING.md) to file feedback or work on the code.
60
+
61
+ ## License
62
+
63
+ &copy; 2026-present Nicolas Dumazet and contributors. Released under the
64
+ [MIT license](LICENSE).
@@ -0,0 +1,99 @@
1
+ # Differences from failsafe-go
2
+
3
+ What this port does **differently from Go**, and why. For maintainers deciding whether
4
+ a Go behaviour applies here, and for anyone diffing the two libraries.
5
+
6
+ Not in scope: API spelling (builders became keyword arguments, `Get`/`Run` became
7
+ `call`), and anything a reader can see from a signature. Only decisions that change
8
+ what the library *does*.
9
+
10
+ ## Capability gaps
11
+
12
+ Things Go can do that this port cannot, or does not.
13
+
14
+ 1. **gRPC and server-side HTTP are not ported.** Go has interceptors and
15
+ `NewHandler`; the ASGI equivalent is a different shape and is deferred (never?).
16
+
17
+ 1. **Hedging is async only.** `HedgePolicy` under `Failsafe` raises
18
+ `NotImplementedError`. Cancelling a synchronous call is impossible in Python, so a
19
+ thread-pool version would leave losing attempts running against the very dependency
20
+ the policy protects — weaker semantics than Go under the same name. `AsyncFailsafe`
21
+ cancels losers for real.
22
+
23
+ 1. **No externally-triggered cancellation in sync mode.** Go exposes
24
+ `exec.IsCanceled()` and a `Context` that any caller can cancel
25
+ mid-execution. Sync Python has no obvious way to do this. Async mode gets
26
+ the full behaviour through task cancellation.
27
+
28
+ 1. **No `failsafehttp.Request` equivalent.** Go offers both a `RoundTripper` and a
29
+ request wrapper. httpx has a single composition point so Python is simpler here.
30
+
31
+ ## Semantic divergences
32
+
33
+ Same feature, slightly different behaviours.
34
+
35
+ Note: this is mostly an agent being a bit too specific about differences, read
36
+ at your own risk.
37
+
38
+ 1. **A hedge counts as an attempt but never as a retry.** Go's `CopyForHedge`
39
+ increments `attempts` and `hedges`, leaving `retries` alone, so concurrent attempts
40
+ never consume an outer retry's budget. Hedged attempts share their execution's
41
+ counters but carry their own last result.
42
+
43
+ 1. **An acceptable result always beats an expired hedge delay.** Go `select`s between
44
+ the delay timer and the result channel, so when both are ready it picks arbitrarily
45
+ and may start a hedge it no longer needs. This driver checks completed attempts
46
+ first: deterministic, and strictly fewer duplicate requests.
47
+
48
+ 1. **A budget-refused retry raises `BudgetExceeded`; a budget-refused hedge just stops
49
+ hedging.** The attempts already in flight still produce a result. This mirrors Go,
50
+ and is worth stating because one budget produces two different outcomes depending
51
+ on which policy consulted it.
52
+
53
+ 1. **`CancelledError` is never a failure.** Neither it nor any other `BaseException` is
54
+ caught, handled or retried. Go has no equivalent concept, so nothing in its test
55
+ corpus covers this.
56
+
57
+ 1. **Listener exceptions are logged, not propagated.** Go lets a panic in a listener
58
+ abort the execution. A metrics bug must not break a production request.
59
+
60
+ 1. **One listener per event, fixed at construction.** Go's `OnRetry(fn)` overwrites
61
+ any previously registered listener; this takes a single callable keyword and
62
+ offers no post-construction registration. Combine observers into one function.
63
+
64
+ 1. **Cache keys come from call arguments, and backends are mappings.** Go reads a
65
+ string key from the `Context` and defines `Get`/`Set` methods with an explicit
66
+ found flag. Here `CachePolicy(cache, key=lambda user_id: ...)` derives any
67
+ hashable key from the call arguments, while the backend follows Python's mapping
68
+ protocol: `cache[key]`, `cache[key] = value`, and `KeyError` for a miss. A
69
+ `cache_key(...)` block can still override `key=`. With neither key source, the
70
+ execution runs uncached.
71
+
72
+ 1. **Priority and user are contextvars, not context values.** Ambient and
73
+ request-scoped, as in Go, but propagated by `contextvars` rather than threaded
74
+ through a parameter. Absence is `None`, not Go's `-1`.
75
+
76
+ 1. **A bare value is a result condition.** `handle="bad"` and `handle=None` match a
77
+ returned value; Go needs its separate `HandleResult` builder. Values that would
78
+ read as something else — a tuple, a list, anything callable — need a predicate, as
79
+ does any member of a collection. Ambiguous and empty collections raise `TypeError`
80
+ rather than being guessed at.
81
+
82
+ 1. **The adaptive limiter computes exact quantiles, not a t-digest sketch.** Go feeds
83
+ recent durations to `influxdata/tdigest` and resets it on every limit update,
84
+ making it a batch quantile over ~50 samples. Measured against Go's own t-digest:
85
+ 2.66% error at n=50, 0.36% at n=500, where an exact sorted window is free of error
86
+ at every size and simpler. The hedge policy's `MovingQuantile` *is* ported — it is
87
+ windowless and serves a different purpose.
88
+
89
+ 1. **The hedge quantile times each attempt, not the execution.** Matching Go, and
90
+ worth recording because the obvious implementation is wrong: a hedged execution
91
+ spans the stalled attempt *plus* the winner, so feeding that back inflates the
92
+ estimate and suppresses future hedging — exactly when the tail is worst.
93
+
94
+ 1. **A policy rejection surfaces as `httpx.TransportError`.** Go returns its own error
95
+ type from the `RoundTripper`. httpx callers catch `httpx.HTTPError`, and a bare
96
+ `FailsafeError` escaping a transport would bypass every such handler. The original
97
+ is chained as `__cause__`.
98
+
99
+
@@ -0,0 +1,41 @@
1
+ # failsafe-py
2
+
3
+ [![License](http://img.shields.io/:license-mit-brightgreen.svg)](https://opensource.org/licenses/MIT)
4
+
5
+ failsafe-py is a library for building resilient, fault tolerant Python applications. It works by
6
+ wrapping functions with one or more resilience policies, which can be combined and composed as
7
+ needed. Policies include:
8
+
9
+ - Failure handling: Retry, Fallback
10
+ - Load limiting: Circuit Breaker, Adaptive Limiter, Adaptive Throttler, Bulkhead, Rate Limiter, Cache
11
+ - Time limiting: Timeout, Hedge
12
+
13
+ A Python port of [failsafe-go](https://github.com/failsafe-go/failsafe-go). See
14
+ [PORT.md](PORT.md) for divergences.
15
+
16
+ ## Project status
17
+
18
+ This is mostly agentic port of failsafe-go alongside its website, because I
19
+ needed a similar library at work in Python (Google-external equivalent of
20
+ "extensible stubs / canonical stubs"). It was fast to do, "only" costing me
21
+ about a weekend trying to improve the agent's writing / API choices.
22
+
23
+ Some disclaimers:
24
+
25
+ * Agents are ... agents. Their prose is annoying. Their tests are not that
26
+ good. They sometimes make mistakes [...].
27
+ * I'm not that attached to the particular implementation.
28
+ * This is a v0.1.0. I would want, welcome, and encourage specific API design
29
+ feedback (via Github bugs). I am happy to consider breaking API changes in
30
+ future, in particular to have more "Python friendly" APIs if I missed
31
+ something whilst guiding my agent.
32
+
33
+ I would aim for a v1.0 release before end of 2026, hopefully after feedback
34
+ from the community.
35
+
36
+ See [CONTRIBUTING.md](CONTRIBUTING.md) to file feedback or work on the code.
37
+
38
+ ## License
39
+
40
+ &copy; 2026-present Nicolas Dumazet and contributors. Released under the
41
+ [MIT license](LICENSE).
@@ -0,0 +1,61 @@
1
+ # Releasing
2
+
3
+ ## Versioning
4
+
5
+ [Semantic versioning](https://semver.org/), with the pre-1.0 caveat that breaking
6
+ changes are expected and only need a minor bump.
7
+
8
+ | Change | Before 1.0 | After 1.0 |
9
+ |---|---|---|
10
+ | Breaking API change | minor — `0.1.0` → `0.2.0` | major |
11
+ | New feature, backwards compatible | minor | minor |
12
+ | Bug fix, no API change | patch | patch |
13
+
14
+ A breaking change is anything that can turn working code into broken code: a removed
15
+ or renamed public name, a parameter that changes meaning or position, a narrowed
16
+ accepted type, a different exception, or a behavioural change a caller could be
17
+ relying on. Reordering keyword-only parameters is not breaking; renaming one is.
18
+
19
+ Until 1.0 these are acceptable when they improve the API — see
20
+ [CONTRIBUTING.md](CONTRIBUTING.md) — but they must be called out.
21
+
22
+ ## Release notes
23
+
24
+ Every release lists breaking changes **first**, under their own heading, each with
25
+ what to write instead. A reader skimming the notes should learn in one screen whether
26
+ the upgrade will cost them anything.
27
+
28
+ ```markdown
29
+ ### Breaking
30
+
31
+ - `CachePolicy(key=)` is no longer required. Policies relying on positional
32
+ construction must pass it by keyword.
33
+
34
+ ### Added
35
+ ### Fixed
36
+ ```
37
+
38
+ A breaking commit marks itself with `!` after the type: `feat!: …`,
39
+ `refactor(retry)!: …`. Add a `BREAKING CHANGE:` footer as well when the migration
40
+ needs more than a subject line. Either way `git log` is the source for that first
41
+ section, and a release containing a `!` commit with no breaking section in its notes
42
+ means one of the two is wrong.
43
+
44
+ ## Cutting a release
45
+
46
+ 1. Update `version` in `pyproject.toml`.
47
+ 2. Commit it: `chore: release 0.2.0`.
48
+ 3. Tag it: `git tag v0.2.0 && git push --tags`.
49
+
50
+ The tag triggers `.github/workflows/release.yml`, which runs the full gates, verifies
51
+ the tag matches the packaged version, builds, and publishes to PyPI through trusted
52
+ publishing. No token is stored anywhere.
53
+
54
+ A mismatched tag fails the build before anything is published, so a wrong tag costs a
55
+ deletion rather than a yanked release.
56
+
57
+ ## After publishing
58
+
59
+ Read the Docs builds the tag automatically, but **new versions arrive inactive** —
60
+ activate `v0.2.0` in the project's Versions tab for it to be served. `stable` then
61
+ follows the highest semver tag on its own, and `latest` always tracks `main`.
@@ -0,0 +1,21 @@
1
+ /* Brand palette: the python.org logo gradient stops the mark is drawn from. */
2
+ :root {
3
+ --md-primary-fg-color: #2d3837;
4
+ --md-primary-fg-color--light: #5A9FD4;
5
+ --md-primary-fg-color--dark: #1f2726;
6
+ --md-accent-fg-color: #306998;
7
+ }
8
+
9
+ [data-md-color-scheme="slate"] {
10
+ --md-primary-fg-color: #1f2726;
11
+ --md-accent-fg-color: #5A9FD4;
12
+ }
13
+
14
+ /* Links in body copy, so they are not the same near-black as the header. */
15
+ :root > * {
16
+ --md-typeset-a-color: #306998;
17
+ }
18
+
19
+ [data-md-color-scheme="slate"] {
20
+ --md-typeset-a-color: #5A9FD4;
21
+ }
@@ -0,0 +1,12 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 650 650" width="650" height="650">
2
+ <!-- The failsafe mark: three stacked bars, rounded outside, square inside.
3
+ failsafe and failsafe-go share this shape and differ only in palette.
4
+ Colours are the four official python.org logo gradient stops:
5
+ #306998 / #5A9FD4 (blue) and #FFD43B / #FFE873 (yellow). -->
6
+ <path fill="#306998" fill-rule="evenodd"
7
+ d="M83 30h485a24 24 0 0 1 24 24v107a24 24 0 0 1-24 24H83a24 24 0 0 1-24-24V54a24 24 0 0 1 24-24zm23 47v61h439V77H106z"/>
8
+ <path fill="#5A9FD4" fill-rule="evenodd"
9
+ d="M83 250h337a24 24 0 0 1 24 24v107a24 24 0 0 1-24 24H83a24 24 0 0 1-24-24V274a24 24 0 0 1 24-24zm23 47v61h291v-61H106z"/>
10
+ <path fill="#FFD43B" fill-rule="evenodd"
11
+ d="M83 464h168a24 24 0 0 1 24 24v107a24 24 0 0 1-24 24H83a24 24 0 0 1-24-24V488a24 24 0 0 1 24-24zm23 47v61h122v-61H106z"/>
12
+ </svg>
@@ -0,0 +1,30 @@
1
+ # failsafe-py API reference
2
+
3
+ This is the docstring-generated API reference. The prose guide — concepts, usage,
4
+ comparisons — lives at [failsafe-py.github.io](https://failsafe-py.github.io).
5
+
6
+ ## Shape of the library
7
+
8
+ A composition wraps a call with policies, outermost first:
9
+
10
+ ```python
11
+ from failsafe import CircuitBreaker, Failsafe, RetryPolicy, Timeout
12
+
13
+ api = Failsafe(RetryPolicy(max_retries=3), CircuitBreaker(), Timeout(2.0))
14
+ response = api.call(send_request, url)
15
+ ```
16
+
17
+ The result type comes from the function, and its arguments are checked against that
18
+ function's signature, so one composition can guard calls returning different types.
19
+
20
+ Stateful policies — `CircuitBreaker`, `Bulkhead`, `RateLimiter`, `AdaptiveThrottler`,
21
+ `AdaptiveLimiter`, `Budget` — accumulate state across executions, so they may be
22
+ shared. What a shared instance then measures is whatever its callers have in common:
23
+ one per backend tracks that backend's health, one per connection or per operation
24
+ tracks something narrower. Pick the scope you want to reason about.
25
+
26
+ | | |
27
+ |---|---|
28
+ | [Entry points](reference/entry-points.md) | `Failsafe`, `AsyncFailsafe`, and the execution in progress |
29
+ | [Policies](reference/retry.md) | retry, circuit breaker, timeout, fallback, bulkhead, rate limiter, hedge, cache, budget, adaptive throttler and limiter |
30
+ | [Vocabulary](reference/conditions.md) | conditions, delays, priority, events, exceptions |
@@ -0,0 +1,13 @@
1
+ # Adaptive limiter
2
+
3
+ Discovers a dependency's real concurrency limit.
4
+
5
+ Guide: [Adaptive limiter](https://failsafe-py.github.io/adaptive-limiter)
6
+
7
+ ::: failsafe.AdaptiveLimiter
8
+
9
+ ::: failsafe.queue_prioritizer
10
+
11
+ ::: failsafe.LimitChangedEvent
12
+
13
+ ::: failsafe.LimitExceeded
@@ -0,0 +1,11 @@
1
+ # Adaptive throttler
2
+
3
+ Sheds load when a dependency's failure rate climbs.
4
+
5
+ Guide: [Adaptive throttler](https://failsafe-py.github.io/adaptive-throttler)
6
+
7
+ ::: failsafe.AdaptiveThrottler
8
+
9
+ ::: failsafe.throttle_prioritizer
10
+
11
+ ::: failsafe.ThrottleExceeded
@@ -0,0 +1,11 @@
1
+ # Budget
2
+
3
+ Caps the share of in-flight work that retries and hedges may consume.
4
+
5
+ Guide: [Execution budgets](https://failsafe-py.github.io/execution-budgets)
6
+
7
+ ::: failsafe.Budget
8
+
9
+ ::: failsafe.BudgetExceeded
10
+
11
+ ::: failsafe.BudgetExceededEvent
@@ -0,0 +1,9 @@
1
+ # Bulkhead
2
+
3
+ Limits how many executions run at once.
4
+
5
+ Guide: [Bulkhead](https://failsafe-py.github.io/bulkhead)
6
+
7
+ ::: failsafe.Bulkhead
8
+
9
+ ::: failsafe.BulkheadFull
@@ -0,0 +1,13 @@
1
+ # Cache
2
+
3
+ Serves results from a cache, skipping the execution.
4
+
5
+ Guide: [Cache](https://failsafe-py.github.io/cache)
6
+
7
+ ::: failsafe.CachePolicy
8
+
9
+ ::: failsafe.Cache
10
+
11
+ ::: failsafe.cache_key
12
+
13
+ ::: failsafe.current_cache_key
@@ -0,0 +1,15 @@
1
+ # Circuit breaker
2
+
3
+ Stops calling a failing dependency so it can recover.
4
+
5
+ Guide: [Circuit breaker](https://failsafe-py.github.io/circuit-breaker)
6
+
7
+ ::: failsafe.CircuitBreaker
8
+
9
+ ::: failsafe.Rate
10
+
11
+ ::: failsafe.Ratio
12
+
13
+ ::: failsafe.StateChangedEvent
14
+
15
+ ::: failsafe.CircuitBreakerOpen