Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
496bc66
fix: keep results after bookkeeping errors, keep key errors out of st…
Pythondeveloper6 Nov 26, 2026
01e3f60
docs: document 0.4.1 behaviour changes and update the changelog
Pythondeveloper6 Nov 26, 2026
aac8f47
feat: warn about the 0.5.0 retry default change; doctor PW024 and PW025
Pythondeveloper6 Nov 26, 2026
6863add
feat: cache codec shortcuts, visible implicit-pickle warning, doctor …
Pythondeveloper6 Nov 26, 2026
322a317
feat: hint_jitter and min_delay options for hinted waits
Pythondeveloper6 Nov 26, 2026
10bd0bc
fix: read Celery request id and deadline from attributes or headers
Pythondeveloper6 Nov 26, 2026
6cedccc
fix: every lock in the package is fork-safe; real prefork check in CI
Pythondeveloper6 Nov 26, 2026
9df5897
test: cover mount_policy, live quota script and CI live job
Pythondeveloper6 Nov 27, 2026
8b2ef0b
fix: keyed rate windows and LLM scopes use the stable key encoding
Pythondeveloper6 Nov 27, 2026
397c888
perf: shared breaker answers from the process cache without tasks
Pythondeveloper6 Nov 27, 2026
dd8ec09
perf: Redis scripts run via EVALSHA; retry budget batches deposits
Pythondeveloper6 Nov 27, 2026
487b1a0
feat: one on_backend_error rule for caches, token windows, leases and…
Pythondeveloper6 Nov 27, 2026
3616bf1
perf: shared leases renew from one thread per process; poll back-off
Pythondeveloper6 Nov 27, 2026
24a4bf9
feat: idempotent task scope; re-queues no longer consume task retries
Pythondeveloper6 Nov 27, 2026
0f4c396
Complete cache coordination and resilience fixes
Pythondeveloper6 Nov 30, 2026
dd32e37
Share HTTP pauses and guard configuration through Redis
Pythondeveloper6 Nov 30, 2026
afe16af
Share keyed LLM token windows across processes
Pythondeveloper6 Nov 30, 2026
98d8eac
Allow retry defaults to update running applications
Pythondeveloper6 Nov 30, 2026
75ad1e8
Keep fork-aware synchronization and SDK detection typed
Pythondeveloper6 Nov 30, 2026
b3c7efa
Support async Redis retry budgets
Pythondeveloper6 Nov 30, 2026
c7ce00e
Extend SQL idempotency and LangChain integration
Pythondeveloper6 Dec 2, 2026
613a59b
Reuse shared bulkhead slots during an opt-in idle window
Pythondeveloper6 Dec 3, 2026
c95d3f9
Preserve Celery retry allowance while waiting for a lease
Pythondeveloper6 Dec 3, 2026
a455535
Keep retry documentation examples executable
Pythondeveloper6 Dec 3, 2026
a4d9bc3
Verify Celery broker redelivery after worker loss
Pythondeveloper6 Dec 3, 2026
2d67d4b
Exercise shared retry budgets and bulkheads in Redis soak
Pythondeveloper6 Dec 3, 2026
29aaab7
Close 0.4.2 release verification gaps
Pythondeveloper6 Dec 3, 2026
03573a9
Honor shared HTTP pauses and repair release checks
Pythondeveloper6 Dec 4, 2026
1b250ee
Close cache outage and platform verification gaps
Pythondeveloper6 Dec 4, 2026
33d0224
Enforce shared bulkhead capacity during local fallback
Pythondeveloper6 Dec 4, 2026
2cce0e3
Give streaming timeout tests room for CI scheduling
Pythondeveloper6 Dec 4, 2026
bbb6c24
Record the one-hour Redis soak results
Pythondeveloper6 Dec 4, 2026
56a09ad
Apply the planned 0.5.0 resilience defaults
Pythondeveloper6 Dec 4, 2026
b5df61c
Account for guarded structured replies and verify beta release notes
Pythondeveloper6 Dec 4, 2026
085f0b0
Keep inherited SQL sessions out of child finalizers
Pythondeveloper6 Dec 4, 2026
7d1b04b
Remove deprecated compatibility APIs for 0.6.0
Pythondeveloper6 Dec 4, 2026
50dc07a
Consolidate pending features on the 0.6 release branch
Pythondeveloper6 Dec 4, 2026
69fa2a3
Keep migrated and documented retry schedules under the new defaults
Pythondeveloper6 Dec 4, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ name: CI

on:
push:
branches: [main, 'fix/**']
branches: [main, 'fix/**', 'release/**']
pull_request:
workflow_dispatch:

Expand Down Expand Up @@ -230,13 +230,24 @@ jobs:
run: sudo apt-get update && sudo apt-get install -y redis-server
- run: uv sync --group dev --frozen
- name: Validate atomic backend scripts against Redis
run: uv run --no-sync pytest tests/test_redis_backends.py tests/test_fork_safety.py
run: >-
uv run --no-sync --with 'requests>=2.32' pytest tests/test_redis_backends.py
tests/test_fork_safety.py tests/test_redis_scripts_live.py tests/test_backend_recovered.py
tests/test_http_requests.py

framework-integration:
# Oldest supported and newest releases of each framework, so an adapter that only
# works on one end of the range shows up here.
name: Frameworks (${{ matrix.versions.name }})
runs-on: ubuntu-latest
env:
PW_CELERY_REDIS_URL: redis://127.0.0.1:6379/0
services:
redis:
image: redis:7-alpine
ports:
- 6379:6379
options: --health-cmd "redis-cli ping" --health-interval 2s --health-timeout 2s --health-retries 15
strategy:
fail-fast: false
matrix:
Expand All @@ -261,9 +272,26 @@ jobs:
- run: uv sync --group dev --frozen
- name: Exercise real framework request/task lifecycles and HTTP clients
run: >-
uv run --frozen ${{ matrix.versions.pins }}
uv run --frozen --with redis ${{ matrix.versions.pins }}
pytest tests/test_integrations.py tests/test_http.py tests/test_web.py
tests/test_celery_helpers.py
tests/test_celery_helpers.py tests/test_celery_real_worker.py

- name: Prefork workers keep a policy watch alive after os.fork
run: uv run --frozen python scripts/prefork_check.py

- name: LangChain provider contracts
if: matrix.versions.name == 'latest'
run: >-
uv run --frozen --with langchain --with langchain-openai --with langchain-anthropic
pytest tests/test_langchain_adapter.py tests/test_langchain_providers.py

- name: LangChain minimum core contracts
if: matrix.versions.name == 'oldest'
env:
PYTEST_DISABLE_PLUGIN_AUTOLOAD: "1"
run: >-
uv run --frozen --no-default-groups --group core-test --with 'langchain-core==0.3.0'
pytest tests/test_langchain_adapter.py

sql-backends:
# PgAdvisoryLock, SqlAppLock and the transient-error predicates against real servers.
Expand Down Expand Up @@ -307,7 +335,7 @@ jobs:
exit 1
- name: Live SQL backend tests
run: >-
uv run --frozen --with 'sqlalchemy>=2' --with 'psycopg[binary]>=3.1'
uv run --frozen --with 'sqlalchemy[asyncio]>=2' --with aiosqlite --with 'psycopg[binary]>=3.1'
--with 'pymssql>=2.3' pytest tests/test_sql_backends_live.py tests/test_transient_predicates.py
tests/test_sql_result_store.py
- name: Install the Microsoft ODBC driver for SQL Server
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ jobs:
fi
fi

- name: Check changelog and stability metadata
if: github.ref_type == 'tag'
run: uv run --frozen --no-sync python scripts/check_release.py --tag

- name: Install Redis for the release integration gate
run: sudo apt-get update && sudo apt-get install -y redis-server

Expand Down
92 changes: 84 additions & 8 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,23 @@ Breaking changes are listed under **Breaking changes**, each with its migration.

## [Unreleased]

## [0.6.0b1] - 2026-12-04

This beta consolidates the feature work, fixes, default changes and API removals
since the last published `0.4.0` release. See the [0.6 migration guide] for the
replacement APIs and metrics.

### Breaking changes

- Redis cache stores and shared token windows no longer accept `fail_open=`. Use
`on_backend_error="raise"` for `False` or `on_backend_error="allow"` for `True`.
- The token-window event `rate_limit.store_error` and its dedicated counters are retired.
Use `backend.error` and filter events on `backend="tokens"` for token-window failures.
- The private `_runtime.digest` alias is removed. `name_digest` preserves the existing
digests for internal names, while `stable_digest` is for caller-supplied keys.
- The deprecated LLM, agent and MCP imports leave the `python_wrap` package root.
Use the documented submodule imports. The `mcp_guard` top-level entry point stays available.

### Security

- Shared SQLite token windows now sample time after taking the writer lock and keep stored
Expand All @@ -19,11 +36,75 @@ Breaking changes are listed under **Breaking changes**, each with its migration.
stay alive and disrupt later invalidations. A synchronous shutdown callback that times out
exhausts the remaining finite drain budget before another callback can start.

### Added

- `python_wrap._runtime.cache_key_of(value)` exposes stable key encoding for application checks.
- The key encoder accepts subclasses of builtin types, named tuples and `__cache_key__()`.
- Shared bulkheads can opt into brief lease reuse with `slot_idle=`.

- LangChain guards compose as runnables, preserve guards on bindings, and cover embeddings.

- SQL idempotency supports async connections, database-clock expiration, and sequential DDL.

- Async retries and HTTP transports can use Redis-backed retry budgets without blocking the loop.

- `configure(live=True)` refreshes omitted retry arguments on already-decorated functions.

- OpenAI and Anthropic adapters support per-key token windows backed by shared Redis or SQLite.

- Tagged cache invalidation returns the number of shared writes and supports
`require_shared=True`. Both cache decorators support `lock_wait=None` to wait
for the shared lease.
- Policy watches support strict startup validation and optional polling jitter.
- HTTP policies cap cached host state with `max_hosts` (default 1000), accept
limiter and bulkhead mappings, and share 429 pauses through Redis.

### Changed

- Retry defaults use exponential backoff, equal jitter, and a 30-second scheduled delay cap.
Pass `backoff=1, jitter=0, max_delay=None` to restore 0.4.x timing. Explicit delay schedules
keep their values. HTTP and Celery backoff use equal jitter by default.
- Shared Redis caches default to JSON. Existing pickle entries are read as misses.
Choose an explicit codec if you need to cache exceptions or other Python objects.
- Shared backends fall back to local state during an outage. Set
`configure(backend_errors="raise")` for 0.4.x behavior. Strict leases and idempotency
retain their existing error behavior.
- Policy watches reject an invalid initial load by default. Pass `strict=False` to keep polling.
- Celery idempotency defaults to the delivery ID. Pass `scope="arguments"` to retain the
0.4.x cache key and behavior.

### Fixed

- `python_wrap migrate` writes `jitter=0` and `max_delay=None` for source schedules that set
neither, so migrated waits are no longer jittered or capped by the new retry defaults.

- Forked PostgreSQL and SQL Server lock backends preserve the parent's active SQL sessions
while opening a separate pool in the child.
- Celery deliveries waiting on an idempotency lease preserve the task retry counter.

- Shared caches batch tag reads and recreate missing version tokens so deleting
a tag key cannot revive an old entry.
- HTTP policies honor a host's 429 pause without requiring a configured limiter.
- Policies read a shared 429 pause before each attempt. Overlapping responses can extend
the pause but cannot shorten it.
- Cache decorators back off lease requests during a store outage and emit a recovery event
when the lease backend responds again.
- Signed-pickle codec configuration reads its signing secret on Windows as well as POSIX.
- The local fallback for a shared bulkhead enforces capacity under concurrent admission.
- Failed transactional idempotent calls remove their own unfinished claim.
- Rebuilding LangChain provider models drops the original SDK clients so their retries
are disabled while preserving the API settings and HTTP transports.
- LangChain structured output with `include_raw=True` counts token usage from the
provider message. Guarded models block direct generation methods that bypass the guard.

- LLM retry ownership is now limited to the task or thread that established it. A copied
context in a new execution owner no longer suppresses that owner's retries, and stored
retry scopes do not retain finished tasks.
- A store error after a successful call no longer replaces the result: circuit breaker bookkeeping (sync and async) and shared bulkhead release are logged and the result is returned. `backend.error` is emitted with operation "success" or "release".
- Redis and async Redis cache stores: key building and codec work now run outside the backend monitor. A key that cannot be encoded raises `TypeError` and does not count as a store outage. An entry that cannot be decoded is a miss with `cache.rejected(reason="decode")`.
- `-0.0` and `0.0` now produce the same cache key. This changes the key of `-0.0` arguments only.
- Half-open circuit rejections carry a positive `retry_after` (local: `min(max(recovery_timeout, 0.05), 1.0)`; shared: time to the trial deadline, at least 50 ms).
- Every hinted wait (`Retry-After`, breaker hints, retry countdowns) gets up to 10% jitter on top and a 50 ms floor when the hint is 0. Exact hinted waits in tests change accordingly.

## [0.4.0] - 2026-11-26

Expand Down Expand Up @@ -174,13 +255,6 @@ shared stores written by other processes). Fixed:
lease and retry budget move to Redis, keyed by the preset name. `SharedBackends` overrides
one layer. `RetryBudget(backend=...)` and `RedisRetryBudget` cap retries across a fleet.

### Added

- `on_backend_error="raise" | "local" | "allow"` on shared breakers, windows, quotas,
bulkheads and `RedisSource`, plus `configure(backend_errors=...)`, `retry_backend_after`,
the events `backend.error` / `backend.recovered`, and a `degraded` health status while a
fallback is active. `RedisStore`/`AsyncRedisStore` report through the same events.

## [0.4.0b1] - 2026-11-11

First beta. The public API is feature-complete for 0.4: the remaining work before the
Expand Down Expand Up @@ -926,7 +1000,9 @@ Core:

Initial release.

[Unreleased]: https://github.com/LitePy/PythonWrap/compare/v0.4.0...HEAD
[Unreleased]: https://github.com/LitePy/PythonWrap/compare/v0.6.0b1...HEAD
[0.6.0b1]: https://github.com/LitePy/PythonWrap/compare/v0.4.0...v0.6.0b1
[0.6 migration guide]: https://pythonwrap.readthedocs.io/en/latest/project/migration/#upgrading-to-06
[0.4.0]: https://github.com/LitePy/PythonWrap/compare/v0.4.0b2...v0.4.0
[0.4.0b1]: https://github.com/LitePy/PythonWrap/compare/v0.3.0...v0.4.0b1
[0.3.0]: https://github.com/LitePy/PythonWrap/compare/v0.2.1...v0.3.0
Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,23 @@ Unreleased on `main`; see the [CHANGELOG](https://github.com/LitePy/PythonWrap/b
The [stable core](https://pythonwrap.readthedocs.io/en/latest/project/stability/) (retry,
circuit breaker, timeout, policies, presets) is now frozen ahead of 1.0.

## What is stable in 0.4

The stable core is frozen: retry, circuit breaker, timeout and deadline, policies, presets,
errors and events. It does not change incompatibly before 1.0.

For shared HTTP policies, `HttpPolicy(shared=redis, per_host=True)` shares
429 pauses across processes. Pass `limiter={"calls": 50, "period": 1}` and
`bulkhead={"max_concurrent": 8}` to share those per-host guards as well.
See [HTTP clients](https://pythonwrap.readthedocs.io/en/latest/features/resilience/http-clients/).

Provisional modules may change in a minor release. They are `shared`, `coordination`,
`quotas`, `stores`, `http` and `celery` (target 0.5.0), and `async_cache`, `web`,
`exporters` and `observability` (target 0.6.0). The newer integrations (dashboard, chaos,
migrate and distributed backends) are provisional too. The full policy, graduation
criteria and status table are in
[`docs/project/stability.md`](https://github.com/LitePy/PythonWrap/blob/main/docs/project/stability.md).

## New in 0.4 (beta)

| Need | API |
Expand Down
24 changes: 17 additions & 7 deletions RELEASING.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,24 @@ was removed; revoke the token it used at <https://pypi.org/manage/account/token/
`pypi` and `testpypi`. Add yourself as a required reviewer on `pypi` so every real
upload waits for one click.

## Active release branch

Use `release/0.6.0` for the combined release. It carries the fixes and features
from the earlier 0.4.2 and 0.5.0 preparation branches, along with the 0.6.0 API
removals. Its changelog compares the beta with the published `v0.4.0` tag.

Before publishing a build that includes the removals, verify the compatibility
window in the [deprecation policy](docs/project/stability.md#deprecation-policy).
That window is measured from the release that actually shipped the deprecation.

## Every release

1. **Version.** Set `__version__` in `src/python_wrap/__init__.py`. It is the only place
the version lives. Use PEP 440 spelling: `0.3.0rc1`, `0.3.0`.
2. **Changelog.** Move the `Unreleased` entries under `## [<version>] - <date>`. The
GitHub release notes are taken from this section.
GitHub release notes are taken from this section. Two checks before tagging:
- No `Unreleased` entry may describe code that is in the tag. Cut the section first.
- A final release differs from its last beta only by fixes. New features need a new beta.
3. **Check locally.**

```bash
Expand All @@ -43,17 +55,15 @@ was removed; revoke the token it used at <https://pypi.org/manage/account/token/
uv run mkdocs build --strict
uv build && uvx twine check --strict dist/* && rm -rf dist
python scripts/smoke_wheel.py # wheel in a fresh venv: version, no deps, py.typed, CLIs
python scripts/check_release.py --tag # duplicate changelog entries, empty Unreleased, classifier vs stability page
```

The default `pytest` run includes the `tests/e2e/` happy-path scenarios.

4. **Merge to `main`**, after the local checks pass. CI and docs run only on pushes
to `main`, so PR updates do not start Actions runs. Wait for both workflows on the
merged commit to pass before creating a release tag. The Redis integration job is
4. **Merge to `main`**, after local checks and release-branch CI pass. Wait for CI and
the docs workflow on the merged commit before creating a release tag. The Redis integration job is
required for 0.3.0; the release workflow repeats its real-server gate before any
upload, so a skipped local Redis run cannot approve a publication. If the repository requires
PR status checks, a maintainer must align that rule with this post-merge policy;
new PR commits will not receive CI/docs checks.
upload, so a skipped local Redis run cannot approve a publication.
5. **Rehearse (recommended for a big release).** Tag a pre-release such as `v0.3.0rc1`
(after setting `__version__ = "0.3.0rc1"`). Every tagged version is published to
TestPyPI and installed back from that index
Expand Down
25 changes: 16 additions & 9 deletions benchmarks/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,10 @@
from python_wrap.coordination import AsyncRedisSemaphore, RedisSemaphore
from python_wrap.devtools import deprecate, mock_data
from python_wrap.logs import audit, log_args
from python_wrap.presets import http_client
from python_wrap.quotas import AsyncRedisWindow, RedisWindow, shared_rate_limit
from python_wrap.retry import retry
from python_wrap.shared import AsyncRedisBreakerState, RedisBreakerState
from python_wrap.retry import RetryBudget, retry
from python_wrap.shared import AsyncRedisBreakerState, RedisBreakerState, RedisRetryBudget
from python_wrap.timing import timing
from python_wrap.validation import check_type, enforce_types, validate_args

Expand Down Expand Up @@ -167,10 +168,14 @@ def _redis_cases(url: str) -> list[Case]:
rows = [
("circuit_breaker", _shared_breaker),
("Bulkhead(8)", _shared_bulkhead),
("Bulkhead(8, slot_idle=1)", functools.partial(_shared_bulkhead, slot_idle=1)),
("rate_limit", _shared_window),
("retry_budget", _shared_budget),
]
preset = http_client("bench", shared=client)
return [
*(Case(f"{name} (redis)", lambda fn, b=build: b(client)(fn), None) for name, build in rows),
Case("http_client (shared)", lambda fn: preset(fn), None),
Case("memoize (redis hit)", lambda fn: memoize(store=store, ttl=60)(fn), None),
]

Expand All @@ -180,16 +185,21 @@ def _shared_breaker(client: Any) -> Callable[[Any], Any]:
return CircuitBreaker(name="bench", backend=kind(client), logger=LOG)


def _shared_bulkhead(client: Any) -> Callable[[Any], Any]:
def _shared_bulkhead(client: Any, *, slot_idle: float = 0) -> Callable[[Any], Any]:
kind = AsyncRedisSemaphore if _is_async(client) else RedisSemaphore
return Bulkhead(8, name="bench", backend=kind(client))
return Bulkhead(8, name="bench", backend=kind(client), slot_idle=slot_idle)


def _shared_window(client: Any) -> Callable[[Any], Any]:
kind = AsyncRedisWindow if _is_async(client) else RedisWindow
return shared_rate_limit(kind(client, "bench", calls=10**9, period=1))


def _shared_budget(client: Any) -> Callable[[Any], Any]:
budget = RetryBudget(ratio=0.2, min_per_second=5, backend=RedisRetryBudget(client, "bench"))
return retry(max_attempts=3, delay=0, budget=budget, logger=LOG)


def cases() -> list[Case]:
out = [
_case("timing (logging off)", lambda: timing(logger=LOG)),
Expand Down Expand Up @@ -221,6 +231,7 @@ def cases() -> list[Case]:
Case("retry+timeout+circuit_breaker", _stack, _stack_async),
*_shared("circuit_breaker", _shared_breaker, _CLOSED),
*_shared("Bulkhead(8)", _shared_bulkhead, 1),
*_shared("Bulkhead(8, slot_idle=1)", functools.partial(_shared_bulkhead, slot_idle=1), 1),
]
# An async window refuses sync functions, so it has no "via thread" row.
out.append(
Expand Down Expand Up @@ -251,11 +262,7 @@ async def _arun(f: Callable[..., Awaitable[Any]], n: int) -> float:


def _time_async(f: Fn, n: int) -> float:
loop = asyncio.new_event_loop()
try:
return loop.run_until_complete(_arun(f, n))
finally:
loop.close()
return asyncio.run(_arun(f, n))


def _measure(
Expand Down
Loading
Loading