Repository navigation
v0.4.0b2
Pre-releaseBreaking changes
observability.enable()now adds python_wrap events as span events on the current
span instead of opening a zero-lengthpw.<event>span per event. Pass
spans="notifications"for the old behaviour. The breaker-state metric is now an
observable gauge read at collection time for every breaker in the process.- Re-registering a named policy no longer resets its breaker: an open in-process breaker
stays open acrossregister()/load_from_mapping()(also with new thresholds), and an
unchanged mapping keeps its generation. Call the breaker'sreset()to close it. - Retry events carry a new
attempt_secondsfield; listeners that compare the whole
fieldsdict must allow it.
Security
Review of the 0.4.0b2 additions (threat model: request-derived input reaching new
in-memory tables, SQL built from configuration, names resolved from configuration,
shared stores written by other processes). Fixed:
guard_openai(limiter_key=...)kept one limiter per key without a bound, so keys taken
from request data could grow memory without limit. At most 256 keys get their own
window; later keys share the base limiter.invalidate_tagskept a token for every tag name ever invalidated. The table is now
bounded; when it is cleared a global epoch makes every older entry read as stale, so a
cleared token can never revive a stale cache entry.SqlResultStoreonly accepts a plain identifier as table name, binds every value,
hashes call keys, and stores JSON by default (no pickle).- Policy mappings never import a dotted path: exception, predicate and backend names
resolve only through explicit registries. Write access to aRedisSourcekey is
control over every replica's resilience settings; protect it like configuration. - The breaker script hash is marked
usedforsecurity=False(it is Redis's script id).
Deprecated
- LLM, agent and MCP names (
Budget,guard_openai,RunGuard,AuditTape,
fake_llmand 86 more) leave the top-levelpython_wrapnamespace: import them from
python_wrap.llm,python_wrap.agents,python_wrap.genai,python_wrap.adapters....
The old names still work with aDeprecationWarningand go in 0.6.0.mcp_guard
stays, since it shares its name with its module.import python_wrapnow loads 45
modules instead of 57.
Changed
concurrencyis split intotimeouts,ratelimit,debounce(throttle and
debounce) andsingleflight;python_wrap.concurrencyre-exports every name, so
imports keep working. Code that patched a module global (concurrency._HAS_SETITIMER)
must patch the new module.docs/project/stability.mdpublishes graduation criteria and target releases for the
provisional modules and a support window;tests/test_stability.pypins the storage
formats of the shared backends.benchmarks/run.py --redis-urlmeasures shared layers
on a real Redis, andbenchmarks/soak.py --processes N --redis-urlsoaks several
processes sharing one breaker and limiter.
Fixed
- Shared cache keys (
RedisStore,AsyncRedisStore) andidempotent/single_instancecall
keys no longer depend on the per-process hash seed or dict insertion order: dict and set
arguments are encoded canonically. Values with no stable form raiseTypeErrornaming the
argument (passkey=). Redis cache keys gain ak2:marker, so existing entries expire
instead of being misread; idempotency records written by 0.4.0b1 for the same call are not
recognised once, during the upgrade. New doctor check PW022.
Added
-
Policies can change at runtime:
policies.watch(source, interval=30)with
EnvSource,FileSourceorRedisSourcevalidates and applies changed mappings,
emitsconfig.changed/config.rejected, and keeps an open breaker open across a
reload. Mappings refer to exceptions, predicates and backends by name
("builtins.ConnectionError","db_transient","@default") through explicit
register_exception/register_predicate/register_backendregistries; nothing
is imported by dotted path. Health reports include policy generations. -
guard_openaiguardsembeddings.create(charging input tokens) and takes
limiter_key=for one token window per deployment. Contract tests cover
AzureOpenAI/AsyncAzureOpenAI, including a content-filter 400 that is not retried. -
LangChain adapter:
guard_chat_model()rebuilds a chat model withmax_retries=0
and runsinvoke/ainvokethrough the budget, retry loop, policy and token limiter;
stream/astreamare resume-safe.PythonWrapCallbackobserves calls and emits
genai.llm_call.read_usageunderstands LangChainusage_metadata. New
langchainextra. -
OpenTelemetry export reaches parity with the Prometheus exporter from one shared
table (observability.COUNTERS): gave-up, budget-exhausted, rate-limit rejected,
backend-error and store-error counters, plus a component health gauge. Opt-in
attempt_spans=(one span per retry attempt, with its real duration) and
wait_spans=;naming="otel"uses OpenTelemetry-style names with units. Retry events
carryattempt_seconds. Shared breakers report their state in every process. -
memoizeandamemoizegainlock=(withlock_ttl,lock_wait): on a miss one
process computes under a shared lease while the others wait and read the store again;
stale refreshes take the same lease.tags=withinvalidate_tags()/
ainvalidate_tags()drops every entry written with a tag through one version write per
tag, with no scan.ttl_jitter=spreads expiry of entries written together. -
SqlResultStore(engine)keeps idempotency results in the application's own database
(PostgreSQL, SQL Server, SQLite through SQLAlchemy), withddl()for migrations and
purge_expired()for a scheduled sweep.idempotent(..., connection=...)writes the
key row on the caller's connection, so the key and the function's own writes commit
or roll back together. CI now also runs the SQL Server backends through pyodbc. -
Circuit breakers can open on a rate:
failure_ratewithminimum_callsoverwindow,
andslow_call_durationwithslow_call_rate(a slow half-open trial re-opens).
A non-defaultfailure_thresholdwithfailure_rateraisesValueError. Calls are
counted in ten time slots per window, locally and in the Redis and SQLite backends.
CircuitStatsand thecircuit.state_changedevent addfailure_rateandslow_rate. -
RedisBreakerStateandAsyncRedisBreakerStatecache a closed state forstate_ttl
seconds (default 1.0): calls are admitted with no store round trip and successes are
sent in batches (flush_interval,flush_every); failures, trials and admin calls
still go to the store at once. A process may admit calls for up tostate_ttlafter
another process opened the breaker;state_ttl=0restores one round trip per call.
The script runs withEVALSHAand reloads onNOSCRIPT. -
Async-native shared backends:
AsyncRedisBreakerState,AsyncRedisLockand
AsyncRedisSemaphorereuse the sync Lua scripts and keys, so sync and async processes
share state, and are awaited on the event loop instead of a worker thread. Breakers,
leases and shared bulkheads detect an async backend and raiseTypeErrorwhen used
from sync code;CircuitBreaker.areset()andaforce_open()cover the admin calls.
SharedBackends(andshared=) builds the async classes for aredis.asyncio
client.idempotent(store=...)accepts anAsyncCacheStore(anAsyncRedisStore
gets a matchingAsyncRedisLock).amemoizegainsstale_ttl,cache_exceptions,
exception_ttlandlogger, matchingmemoize. The benchmark adds shared rows for
the sync, async-native and async-through-a-thread paths. -
Shared Redis caches accept
signed_pickle_codec(secret), a projectcache_codec
default and aversion=namespace. Bad signatures producecache.rejectedmisses;
implicit pickle now warns before a later default change to JSON. -
Retry, HTTP retry and Celery countdowns accept
jitter="full"or"equal";
doctor PW024 flags retries without backoff or jitter across worker processes. -
Web adapters can trust a remaining-deadline header with
trust_deadline_header=True;
Celery publishes and restores request ids and optionally inherits the caller's
deadline withinstall(inherit_deadline=True). Header names can be set through
python_wrap.propagation.set_headers. -
Celery:
resilient_task(re-queue on open breaker, used-up limit or full bulkhead, with the
error'sretry_after; blocking limiters raise instead of sleeping),idempotent_task(one
run per task name and arguments across redeliveries, re-queue while running),
check_visibility(doctor code PW023) andinstall(hard_margin=5.0): a task with only a
hard time limit now gets a cooperative deadline of hard limit minus the margin. -
HttpPolicywithPolicyTransport,AsyncPolicyTransportandmount_policy: retries plus
a circuit breaker, rate limiter and bulkhead (optionally one set per host), default
connect/read timeouts shortened to the surrounding deadline, 429Retry-Afterpauses and
propagate=Truerequest-id /X-Request-Deadlineheaders.RetryTransport,
AsyncRetryTransportandmount_retriesare now thin wrappers over them. -
python_wrap.propagation: the header pair and helpers used to carry the request id and the
remaining deadline across processes. -
on_backend_error="raise" | "local" | "allow"on shared breakers, windows, quotas,
bulkheads andRedisSource, plusconfigure(backend_errors=...),retry_backend_after,
the eventsbackend.error/backend.recovered, and adegradedhealth status while a
fallback is active.RedisStore/AsyncRedisStorereport through the same events. -
shared=on every preset (http_client,db_call,third_party_api,llm_client) and
configure(shared=...), also read byPolicyRegistry: breaker state, rate window, bulkhead
lease and retry budget move to Redis, keyed by the preset name.SharedBackendsoverrides
one layer.RetryBudget(backend=...)andRedisRetryBudgetcap retries across a fleet.
Added
on_backend_error="raise" | "local" | "allow"on shared breakers, windows, quotas,
bulkheads andRedisSource, plusconfigure(backend_errors=...),retry_backend_after,
the eventsbackend.error/backend.recovered, and adegradedhealth status while a
fallback is active.RedisStore/AsyncRedisStorereport through the same events.