All notable changes to this project are documented here.
The format follows Keep a Changelog, and this project adheres to Semantic Versioning.
While the version is below 1.0 the public API may change between minor versions.
Breaking changes are listed under Breaking changes, each with its migration.
- Shared SQLite token windows now sample time after taking the writer lock and keep stored timestamps from moving backward, preventing delayed transactions or clock rollback from granting extra refill. Tagged cache invalidation now weakly tracks Redis clients (or their cache stores when a client cannot be weakly referenced), so abandoned closed clients do not stay alive and disrupt later invalidations. A synchronous shutdown callback that times out exhausts the remaining finite drain budget before another callback can start.
- 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.
0.4.0 - 2026-11-26
observability.enable()now adds python_wrap events as span events on the current span instead of opening a zero-lengthpw.<event>span per event. Passspans="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 across
register()/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 wholefieldsdict must allow it.
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 a
RedisSourcekey 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).
- LLM, agent and MCP names (
Budget,guard_openai,RunGuard,AuditTape,fake_llmand 86 more) leave the top-levelpython_wrapnamespace: import them frompython_wrap.llm,python_wrap.agents,python_wrap.genai,python_wrap.adapters.... The old names still work with aDeprecationWarningand go in 0.6.0.mcp_guardstays, since it shares its name with its module.import python_wrapnow loads 45 modules instead of 57.
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.
- 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.
-
Policies can change at runtime:
policies.watch(source, interval=30)withEnvSource,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 explicitregister_exception/register_predicate/register_backendregistries; nothing is imported by dotted path. Health reports include policy generations. -
guard_openaiguardsembeddings.create(charging input tokens) and takeslimiter_key=for one token window per deployment. Contract tests coverAzureOpenAI/AsyncAzureOpenAI, including a content-filter 400 that is not retried. -
LangChain adapter:
guard_chat_model()rebuilds a chat model withmax_retries=0and runsinvoke/ainvokethrough the budget, retry loop, policy and token limiter;stream/astreamare resume-safe.PythonWrapCallbackobserves calls and emitsgenai.llm_call.read_usageunderstands LangChainusage_metadata. Newlangchainextra. -
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-inattempt_spans=(one span per retry attempt, with its real duration) andwait_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 andpurge_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_ttlseconds (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,AsyncRedisLockandAsyncRedisSemaphorereuse 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.asyncioclient.idempotent(store=...)accepts anAsyncCacheStore(anAsyncRedisStoregets 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_codecdefault 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 throughpython_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 andpropagate=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) andconfigure(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.
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.
0.4.0b1 - 2026-11-11
First beta. The public API is feature-complete for 0.4: the remaining work before the
stable release is feedback, bug fixes and documentation. Highlights: cooperative timeout
cancellation, per-instance state for throttle/debounce/rate_limit, single-flight
memoize, doctor checks PW009-PW012, AsyncRedisWindow, durable buffer journals and
enforce_types(strict=True). Python 3.10 to 3.14 are tested.
-
token_rate_limit(..., store=)accepts a shared window so every worker process draws from one tokens-per-minute bucket:SQLiteTokenWindow(one host, WAL,BEGIN IMMEDIATE; corrupt files are quarantined and rebuilt),RedisTokenWindow/AsyncRedisTokenWindow(one Lua script on the Redis clock). Storage errors fail open to a local bucket (eventrate_limit.store_error) unlessfail_open=False.SQLiteBudgetBackendshares aBudgetthe same way. -
observe_headers(headers)onTokenRateLimiterand the windows (plusparse_rate_limit_headers) turns provider headers (x-ratelimit-remaining-tokens,x-ratelimit-reset-tokens,anthropic-ratelimit-*,retry-after,retry-after-ms) into a lower level and a fleet-wide block, so a 429 storm backs off together; error headers on a failed call are fed back automatically. -
validated(parse, max_repairs=2, repair="error_only" | "full")validates structured model output (pydanticmodel_validate_jsonor any callable), re-asks with only the error text, caps calls at1 + max_repairs(plusmax_tokens=andbudget=), and raisesValidationRepairExhaustedwith every attempt and its token cost. Sync and async; eventsllm.validation_failedandllm.repair_exhausted. -
Cassetterecords and replays LLM HTTP traffic at the transport level (RecordingTransport/ReplayTransport, duck-typed against httpx): request-hash matching withignore_body_keys/ignore_query, secrets never stored (headers, JSON keys, query parameters, literalsecrets=and key shapes), chunked streaming bodies, strict replay (CassetteMiss) and loud failure on a damaged file (CassetteError). Opt-in pytest fixturesllm_cassetteandchaos_llm_httpviapytest_plugins = ["python_wrap.pytest_plugin"]. -
chaos.llm_http(LLMHTTPFaults,ChaosTransport) injects 429, 529, 5xx, timeouts, stalls (before or mid-stream) and truncated bodies at the HTTP level, reusing theLLMFaultsrules. -
python_wrap.adapters:guard_openai/guard_anthropicwrap the OpenAI and Anthropic Python SDK clients (sync and async) in a proxy with the same call surface (chat.completions.create,responses.create,messages.create,messages.stream,beta.messages.tool_runner). Each call runs through one retry loop, aBudget, aTokenRateLimiterlowered tox-ratelimit-remaining-tokens/anthropic-ratelimit-tokens-remaining(read viawith_raw_response; a 429'sretry-afterdrains it) and optionaltraced_llm. No SDK is imported; optionalopenai/anthropicextras pin tested versions. -
Retry coordination:
no_sdk_retries(client)(with_options(max_retries=0)),sdk_max_retries, andllm_retry(owns_retries=True, client=...): nestedllm_retrylayers make a single attempt, so attempts never multiply (4 x 3 = 12). -
resume_safe/ResumableStream: a stream that fails before any output is reopened invisibly; after text or a tool-call delta it raisesStreamInterruptedwith the partial text, completed and pending tool calls (never replayed). Understands OpenAI chat chunks, Responses events and Anthropic message events; stall limits viastream_timeout.stream_transientclassifies in-stream errors. -
CacheGuard: records prompt-cache reads/writes from usage, warns once (PromptCacheWarning,llm.prompt_cache_cold) when the hit rate stays near zero, and flags volatile prompt prefixes (timestamps, UUIDs, random ids;llm.prompt_cache_volatile). -
Doctor checks PW018 (SDK retries still on under a python-wrap retry) and PW019 (a retry around a streamed call without
resume_safe). Contract tests markedsdkrun against the real SDKs over a mock HTTP transport and skip when they are absent. -
agent_run(budget=...)/RunGuardaccept a realpython_wrap.llm.Budget: entering the run opens the budget's per-run scope, so decorated LLM calls draw on it, and the next step raisesRunBudgetExceededonce it is spent (direct calls still raiseBudgetExceeded). -
python -m python_wrap migrate(and the MCPmigrate_previewtool) detects hand-rolled retry loops around LLM client calls and rewrites the safefor ... in range(N)shape to an@llm_retryfunction; every other loop is reported with line numbers and a suggestion.Changegains akindfield. -
LLM and agent recipes in the packaged recipe index, cookbook pages (resilient LLM client, agent tool layer, building with AI coding agents) and two runnable examples. The doctor range is documented as PW001 to PW017 and the threat model covers prompt and audit-tape data handling.
-
LLM test doubles:
fake_llm/FakeProvider(scripted replies, sync/async/streaming withfake_clock-driven delays, call recording, Anthropic- and OpenAI-style usage, token and call assertions) andchaos.llmfault rules (rate_limit,overloaded,server_error,timeout,malformed_json,slow_first_token,stalled_stream,invalid_tool_call,refusal), also loadable fromPW_CHAOSvia an"llm"key. Look-alike errors live inpython_wrap.llm_testing. -
python_wrap.genai: AI observability and compliance.traced_llm/traced_toolpublishgenai.llm_call/genai.tool_callevents with run id, step, tool, model, token usage (SDK-free), cost from an optional price table, latency and inner retry attempts;instrument()sets defaults and emits OpenTelemetry GenAI-convention spans when OpenTelemetry is installed.Redactorscrubs secrets, emails, card numbers and custom patterns and truncates text; content capture is opt-in.AuditTaperecords calls to memory, JSONL or SQLite;replay()returns aReplayProviderserving recorded results withReplayMismatchdetection. Newobservability.enable_genaiandgenai_span_attributes. -
Cooperative cancellation for sync
timeout:CancelToken,cancel_requested(),checkpoint()andcurrent_token(). The token is cancelled when the limit is hit, so a function that cannot be stopped preemptively (worker-thread fallback, Windows) can stop itself by polling. -
SignalTimerConflictWarning:timeoutwarns when it takes over aSIGALRMthat already has a non-default handler or an armedITIMER_REALtimer (both are still restored). -
Doctor checks PW009 (sync
timeoutthat cannot be enforced preemptively: side effects may continue) and PW010 (existingSIGALRMhandler or timer thattimeoutwould take over). -
Policy.explain(),python_wrap.doctor.doctor(func)andpython -m python_wrap doctordescribe every layer of a resilience stack and flag risky combinations: unbounded retries, retries of non-idempotent operations, retries without a timeout or budget, timeouts longer than the retry budget, misordered or duplicated layers (codes PW001-PW008). -
python -m python_wrap migrate(andpython_wrap.migrate.migrate_source): a stdlib-only codemod rewriting tenacity and backoff retry decorators toretry, with dry-run,--diffand--writemodes, reporting anything it cannot translate. Full migration guides from tenacity, pybreaker and limits with API mapping tables. -
python_wrap.chaos:fault_point(name)and the process-widechaosinjector add latency, exceptions or canned results at named points (glob patterns, rate, times, seeded randomness),chaos.open_circuit(breaker), and rules loaded fromPW_CHAOSonly when that variable is set. New eventchaos.injected. -
python_wrap.presets:http_client(),db_call()andthird_party_api()policies with documented timeouts, attempts, backoff, retry budgets and breaker thresholds;idempotent=Falseleaves the retry layer out. -
attempt_history(exc): the exceptionretryre-raises carries anAttemptRecordper failed attempt (duration, exception type name, following wait).observability.annotate_spancopies it onto an OpenTelemetry span andobservability.sentry_breadcrumbs()records python-wrap events as Sentry breadcrumbs, with exceptions reduced to type names. -
HealthRegistry.summary(critical=...)rolls component health up intook/degraded/downwith a matching HTTP status, served as JSON byhealth.wsgi_app()andhealth.asgi_app()(checks run off the event loop). -
SQLiteBreakerState: share circuit breaker state between processes on one host (prefork Celery children, gunicorn/uvicorn workers) without Redis, with the same semantics asRedisBreakerState; guide for multi-process breaker deployments. -
WebhookAlerter: breaker-open (and recovery) alerts to Slack, Microsoft Teams (Adaptive Card) or JSON webhooks, delivered off the calling thread with a per-breaker cooldown and no exception text or URLs in payloads. -
python_wrap.compat:named_lock(name, suffix),acquire_lock,release_lock,RunLocksandconfigure_locks, a low-diff replacement for hand-rolledSET NX/DELlock helpers with owner-checked release and auto-renewal. -
AdaptiveLimiter: an AIMD adaptive concurrency limit (latency target, error-driven decrease, low-priority shedding) that sheds excess load withLoadShed;PerKeyLimiterandper_keygive each tenant its own limiter or bulkhead with LRU eviction. New eventsadaptive.limit_changedandadaptive.shed. -
Graceful shutdown:
shutdown(ShutdownManager) drains registered periodic tasks, buffered writers, batchers, debouncers, bulkheads and callables in priority order within a time budget, with SIGTERM/SIGINT handler andatexitinstallation and a per-itemShutdownReport. Newlifecycle.*events. -
benchmarks/soak.py(policy soak test against a simulated flaky dependency, checking retry amplification, breaker recovery and memory) andbenchmarks/compare.py(overhead next to tenacity, backoff, cachetools andfunctools.lru_cache, with a ratio gate). -
Project docs: API stability and deprecation policy with the declared stable core pinned by
tests/test_stability.py, a threat model and serialization/redaction review, an operations runbook with troubleshooting and the stored key formats, and a production pilot guide. -
Celery helpers:
retry_countdownandretry_taskschedule Celery task retries fromrequest.retrieswith explicit delays or capped backoff, honouring a dependency'sretry_after/Retry-After;shared_breakerbuilds a breaker whose state is shared by all prefork children. -
Ready-made transient database error predicates:
postgres_transient,mysql_transient,sqlserver_transient(pyodbc SQLSTATEs and native numbers such as deadlock 1205 and Azure SQL 40613), their uniondb_transient(also SQLAlchemyconnection_invalidated) anderror_code(...)for driver error numbers. No driver is imported. -
amemoize, an async-native cache forasync deffunctions whose store is awaited, so Redis I/O no longer blocks the event loop:AsyncCacheStoreprotocol,AsyncMemoryStore(LRU + TTL) andAsyncRedisStoreforredis.asyncioclients, with singleflight for concurrent misses andjson_codec()for caches that must not unpickle. -
python_wrap.http: method-safe HTTP retries.HttpRetryPolicyretries idempotent methods (or any request carrying anIdempotency-Key) on transport errors and 408/425/ 429/5xx, honouringRetry-After, deadlines andRetryBudget.RetryTransportandAsyncRetryTransportplug into httpx,mount_retriesinto arequests.Session, andhttp_retrywraps aiohttp-style or hand-written clients. No HTTP library is imported. -
python_wrap.exporters:PrometheusExporterturns the event stream into Prometheus text-format metrics (retries, give-ups, timeouts, rejections by kind, cache hits, breaker state gauges, health gauges) with WSGI/ASGI/metricsendpoints, aprometheus_clientbridge and a cap on label cardinality;StatsDExportersends non-blocking UDP counters, timings and gauges with optional DogStatsD tags. -
python_wrap.dashboard.Dashboard: a live, self-contained resilience page (breaker states, retry and rejection rates, bulkhead load, recent events) over WSGI/ASGI or a localserve(), plus a sample Grafana dashboard indocs/assets/grafana-dashboard.json. -
python_wrap.web:IdempotencyMiddleware(ASGI) andWsgiIdempotencyMiddlewarededupe requests carrying anIdempotency-Key, replaying stored responses, answering 409 for a concurrent duplicate and 422 for a reused key with a different body. -
ratelimit_headers,too_many_requestsandproblem_responsebuild IETFRateLimit-*headers and RFC 9457 problem+json responses for rate-limit, open-circuit and bulkhead rejections, with optional FastAPI, Flask and Django glue. -
throttle(..., key=, per_instance=)anddebounce(..., key=, per_instance=), andrate_limit(..., per_instance=): split the state of decorated methods that every instance used to share.key=mirrorsrate_limit/singleflight(a function of the call's arguments, one window or countdown per key; idle keys are dropped);per_instance=Truekeeps one window, pending call or limiter per instance, held through a weak reference so instances stay collectable and need not be hashable. With either optiondebounce's.cancel()and.flush()take a call's arguments to pick the slot;limiter_of(method, instance=obj)returns an instance's limiter. Defaults are unchanged. -
memoize(..., singleflight=True): concurrent misses on the same key in different threads run the function once; the other threads wait for that outcome (result or exception) and count as hits. A re-entrant call on the computing thread computes directly. Off by default (the previous behavior, where two threads may both compute, is unchanged);async deffunctions already shared one in-flight task per key and loop.cache_parameters()gainssingleflightandkey. -
Doctor code PW011: a
memoized method keyed onselfwith nomaxsize,ttlorstorepins every instance it sees. The fix is the existingmemoize(per_instance=True), which keeps instances collectable through weak references. No default changed. -
Doctor check PW012:
explain(..., multiprocess=True),doctor(..., multiprocess=True)andpython -m python_wrap doctor --multiprocesswarn about every breaker, bulkhead, rate limiter or adaptive limiter without a shared backend, since each worker process then enforces its own copy of the limit. Doctor layers now reportsharedfor bulkheads and rate limiters and recogniseAdaptiveLimiterlayers. -
Async-friendly Redis backends.
AsyncRedisWindowisRedisWindowforredis.asyncioclients (same Lua script and keys):shared_rate_limitandRateLimiter(backend=...)await it on the event loop instead of spending a worker thread per round trip, and reject it on synchronous functions withTypeError.ThreadedStore(store, executor=None)turns any synchronousCacheStore(such asRedisStorewith a plainredis.Redisclient) into anAsyncCacheStoreforamemoize, running each call in a worker thread so it never blocks the loop. -
Durable buffered writers:
buffered(journal=...),Buffered(journal=...)andAsyncBuffered(journal=...)persist each accepted record beforesubmitreturns and remove it only after its batch is written, giving at-least-once delivery. Records left over (crash, failed batch, disabled or closed writer) are replayed on the next firstsubmitor an explicitreplay(). Journals:SQLiteJournal(stdlib, local file),RedisStreamJournal(Redis stream), or anyBufferJournalimplementation. Opt-in; without a journal nothing changes. -
enforce_types(strict=True)raisesUnsupportedAnnotationError(aTypeError, inpython_wrap.validation) for annotations it cannot check (protocols that are notruntime_checkable, unresolvable forward references,ClassVar,Self...) instead of accepting them silently; vetted at decoration, or on the first call when a forward reference resolves later. -
python_wrap.agents, safe agent tool use:@tool(read_only=, idempotent_key=, requires_approval=, timeout=, retry=, dry_result=)deduplicates side-effect tools by an idempotency key from the tool name, canonical arguments and run id, so a retried or replayed call returns the stored result instead of running twice. -
RunGuard/agent_run(max_steps=, max_seconds=, max_repeats=, budget=): a contextvar-based, nesting, sync and async run guard raisingStepLimitExceeded,LoopDetected(identical repeated calls) andRunTimeout;current_run()exposes the run id, step count and history,run_id_varthe run id for tracing, and the run'sCancelTokenmakescheckpoint()stop long tools cooperatively.record_step()counts LLM calls. -
ToolPolicy(allow/deny globs,allow_write=False,dry_run=Truereturning a declareddry_resultor aDryRunmarker) raisingToolNotAllowed; sync/async human approvers with a timeout that deny by default (ApprovalDenied,ApprovalTimeout);ToolRegistrydispatches tool calls by name with JSON arguments. -
Events
agent.run.start,agent.run.step,agent.run.end,tool.call,tool.denied,tool.replayed,tool.dry_run. -
Doctor checks PW016 (retried side-effect tool with deduplication turned off) and PW017 (agent run or tool registry without step, time or repeat limits).
-
python_wrap.llm, wrappers for LLM calls with no provider SDK imported (usage and errors are duck-typed):llm_transientandllm_retry()retry 408/409/429/529/5xx, overloaded, timeout and connection errors, honouringRetry-Afterandretry-after-ms, and never other 4xx or content-policy refusals;presets.llm_client()bundles them with a 60 s timeout, a retry budget and a breaker that counts only transient errors. -
Budget/budget(tokens=, usd=, per=...): token and dollar limits per total, per key, per explicit run or per call chain (context variables), priced withprices={"model": (in_per_mtok, out_per_mtok)}, optionalperiod=windows and a sharedRedisBudgetBackend; raisesBudgetExceeded. New eventllm.budget_exceeded. -
token_rate_limit(tokens_per_minute, estimate=...): a token bucket that reserves an estimate (estimate_tokens) before the call and reconciles it with the real usage. -
fallback_models([...])(or@fallback_models(backups=[...])): a model fallback chain with a circuit breaker per entry and an optional last-good cached answer. New eventllm.fallback_servednaming the model that served. -
stream_timeout(first_token=, chunk_gap=, total=)for sync and async streams, raisingStreamTimeout(aTimeoutExpired) with.limitnaming the limit that tripped. -
llm_cache(): an exact-match response cache keyed on model, messages/prompt and parameters, with TTL, anyCacheStore/AsyncCacheStore, and an optionalsimilarity=embedding hook for semantic matches. -
Doctor checks PW013 (LLM call retried without a spend budget), PW014 (LLM call without a timeout, or a stream timeout without
chunk_gap) and PW015 (generic retry withoutretry_ifaround an LLM call). -
Agent-friendly tooling, generated from
__all__, docstrings, signatures and the docs so it tracks every release:docs/llms.txtanddocs/llms-full.txt(llmstxt.org format, served at the site root), generated byscripts/gen_llms.pyand checked bytests/test_llms_txt.py.python -m python_wrap api [SYMBOL | search WORDS] [--json]: a machine-readable API index with signatures, parameters, raised exceptions and examples (python_wrap.introspect).python -m python_wrap recipe NEED: plain-language needs ("retry http calls", "stop duplicate emails", "limit llm tokens") mapped to the right API, from an extensiblepython_wrap/_data/recipes.json.python -m python_wrap guide: a concise usage guide for coding agents shipped in the wheel, plus ready-to-copyAGENTS.md, project-memory, editor-rule and skill files underdocs/agents/.python -m python_wrap mcp: a dependency-free, read-only Model Context Protocol server over stdio (python_wrap.mcp) withexplain_policy,doctor,migrate_preview,search_api,get_symbol,recipeandguidetools;--allowrestricts which modules it may import. Threat model updated.
-
EffectLedger: exactly-once bookkeeping for agent tool side effects.tool(ledger=...)records each call as started / succeeded / failed, keyed on the provider's tool-call id (with_call_id,tool_call_id) when there is one, else on the run id and argument digest. Replays return the stored result, concurrent duplicates run once, a call id reused with other arguments raisesEffectConflict, and a crash or store failure between the side effect and the record (or a timeout/cancellation) is detected and handed to anon_unknownhook ("retry",EffectResolved(value), orEffectUnknown). Stores:MemoryEffectStore,SQLiteEffectStore,RedisEffectStore(also built from aRedisStore(fail_open=False)).ToolCallgainscall_id; agent-framework context parameters (RunContext,ToolContext,RunContextWrapper) are left out of a tool's argument digest. -
python_wrap.adapters.pydantic_ai.PythonWrapCapability: guarded pydantic-ai tools (tool,wrap(toolset),toolset(...)) with timeout, a retry that never retriesModelRetry, approvals, ledger ontool_call_id, loop and tool-call limits, a usage bridge into a python-wrapBudget, andAuditTaperecords. Optional extrapython-wrap[pydantic-ai]. -
python_wrap.adapters.openai_agents.AgentsGuard: guardedfunction_tools,wrap()for existingFunctionTools (sub-agents viaas_toolincluded, sharing onemax_tool_calls), andRunHooks/AgentHooksfeedingBudget,AuditTapeand repeat detection; run-ending errors are re-raised through the SDK's tool error handling. Optional extrapython-wrap[openai-agents]. -
mcp_guard: per-attempt timeout, retries limited toretry_tools, a shared per-serverCircuitBreaker(mcp_breaker) and cooperative cancellation around an MCPcall_toolfunction or client object (MCPGuard). Doctor checks PW020 (MCP or framework tool call without a timeout) and PW021 (MCP guard retrying every tool).
Findings of a full package review (bandit, ruff S, pip-audit, a secret scan and zizmor,
plus a manual review); each has a regression test in tests/test_security_fixes.py.
IdempotencyMiddleware/WsgiIdempotencyMiddlewareno longer store or replaySet-Cookieand hop-by-hop headers, so a replay can never hand one client's session cookie to another (high).- Without
scope=, idempotency keys are now partitioned by a digest of the request'sAuthorizationandCookieheaders, so two clients that send the same key never receive each other's stored response (high). - The request fingerprint now includes the query string: the same key and body sent to a different query is a 422 mismatch instead of a replay (medium).
- The WSGI middleware reads chunked request bodies (no
Content-Length) up tomax_bodyand fingerprints them, instead of treating them as empty (medium). MemoryResultStoreis bounded (max_entries, default 10,000), so a flood of distinct client-supplied keys cannot exhaust memory (medium).problem_responseno longer copies internal breaker or bulkhead names from exception messages into 503 bodies sent to clients (low).- A
delay_fromhint such asRetry-Afteris capped atHINT_CEILING(600 s) whenmax_delayis not set, and non-finite hints fall back to the backoff, so one header cannot park a worker for days (medium). - Slack webhook alerts escape
&,<and>, so a breaker name or context value cannot mention@channelor inject a link (low). - Workflows: every action is pinned to a commit SHA,
actions/checkoutruns withpersist-credentials: false, the release build no longer uses a cache, and a step output is passed through the environment instead of being expanded into a script. - MCP server (
python -m python_wrap mcp) hardening, reviewed against the threat model before release:import_pathmust bemodule:attributewith identifiers only and no dunder attributes, the module must already be importable (optionally under--allowprefixes), messages andmigrate_previewsources are capped at 1 MiB, output printed by imported modules goes to stderr instead of the protocol stream, and no tool writes files, opens sockets or calls the inspected code (tests intests/test_mcp.py).
- The package description now matches what it is: a typed, zero-dependency resilience
toolkit. The
Betaclassifier stays until the 1.0 stable-core release. - CI: live PostgreSQL and SQL Server jobs for the SQL lease backends and transient-error
predicates, a framework matrix (oldest and newest Flask, FastAPI, Django, Celery,
httpx, requests), a benchmark comparison and soak job, and a coverage floor
(
fail_under = 80). enforce_typesnow checksTypedDictannotations (required keys present, each present key's value checked; extra keys allowed) and parameterisedruntime_checkableprotocols such asSupportsAbs[int](isinstance), which it used to accept unchecked. A dict missing a required key now raisesArgumentTypeError.measure_memoryserialises measured calls process-wide (tracemallochas one peak counter): a measured call that overlaps another in a different thread or task waits for it (coroutines without blocking the loop), so concurrent measurements no longer share one tracker. Nested measured calls and tasks orasyncio.to_threadworkers started inside a measured call join it instead of waiting. Newexclusive=Falserestores the old, unserialised behaviour.profileon anasync deffunction now profiles only that coroutine's own steps: the profiler is switched off at everyawaitand back on when it resumes, so work the event loop does for other tasks is no longer attributed to it. Overlapping profiled calls run unprofiled with a warning logged once (cProfile allows one active profiler per thread, per process on 3.12+); this is now documented.
TokenRateLimiter: a drained bucket could spin forever on sub-nanosecond waits when the clock reading was large (float precision); the admission slack is now 1e-6 tokens.SQLiteBreakerState: concurrent first connections (threads or processes opening the same database at once) could fail withsqlite3.OperationalError: database is lockedwhile switching to WAL. Setup now retries untilbusy_timeouthas elapsed.retry_after_header: an unparseableRetry-Aftervalue (free text, or a Python-only form such as1_0) is now ignored on its own, so thejson_key=body fallback still applies instead of the whole lookup being abandoned.
tests/e2e/holds release-grade happy-path scenarios that use only the public API (resilient HTTP client, cached service, idempotent job worker with journal replay, policy and doctor, LLM client, agent tool run with audit replay, the CLI commands and the MCP server over stdio), markede2eand run in the default suite.scripts/smoke_wheel.pybuilds the wheel, installs it into a fresh venv with no dev dependencies and checks the beta version, zero runtime dependencies,py.typed, packaged data, the CLIs and a retry/timeout/LLM happy path; CI runs it on Python 3.10 and 3.14 (PW_SMOKE_WHEEL=1 pytest tests/test_smoke_wheel.py).- Verified on Python 3.10 to 3.13. Added Prometheus text-format 0.0.4 conformance tests
(strict grammar check, histogram invariants,
prometheus_clientparser round trip),Retry-Afteredge cases, real-Redis tests forRedisSemaphore,RedisCheckpointandRedisSource, and non-main-threadtimeoutfallback behaviour.
docs/project/limitations.md: thetimeoutthread fallback caveats (Windows runs every sync timeout this way, abandoned workers, thread-affine code) are spelled out.
0.3.0 - 2026-10-29
Production integration helpers, optional distributed backends, and fixes from integration testing. The package keeps zero runtime dependencies; applications supply Redis clients, SQLAlchemy engines, frameworks and telemetry providers.
-
Explicit
retry/retrying(delays=[...])schedules, repeating the final wait, andlog_values=Falsefor retry diagnostics that omit exception/result contents and tracebacks, including failing hooks/hints. -
Opt-in
memoize(copy_result=True)isolates mutable cached results on write and delivery, including concurrent callers and explicit cache reads. -
Adoption guide for existing FastAPI services covering tenant-aware cache keys, response adapters, job delay schedules and boundaries with existing durable infrastructure.
-
ContextFilter,bindandunbindfor context on application log records, plus optional Flask, FastAPI/ASGI, Django and Celery lifecycle adapters. -
Deep
redactandis_sensitivehelpers, opt-indeep=Trueargument redaction; result-basedRetry-Afterandhttp_status; composablePredicate,sqlstate,message_containsandin_cause_chainhelpers. -
RedisStore, early-refreshexpiringcredential loaders, namedPolicyRegistry, globalpolicies, and call-timeresilientpolicy resolution. -
Owner-checked local/Redis leases,
single_instance, PostgreSQL advisory and SQL Server application-lock adapters, and retained-resultidempotentexecution. -
Redis sliding windows, run
Quotabudgets, shared breaker state, failure windows, and lease-backed shared bulkhead capacity.CircuitBreaker.force_open()supports maintenance and tests. -
Bounded sync/async
bufferedwriters, per-item batch processing outcomes and explicit memory/Redis checkpoints, and dynamic environment/Redis switches. -
Opt-in OpenTelemetry event spans and bounded-label metrics,
timedslow-call detection, an explicit weak health registry,disabled,assert_retriedandassert_cache_hit. -
Feature guides, public API pages, worker-lifecycle recipes and a 0.3 migration guide.
- Redaction no longer masks harmless author/activity-session names by substring. Deep redaction masks cycles and uninspected containers at its depth limit.
- Retry hints can inspect rejected return values; a failing ordinary
on_retryhook is logged instead of replacing the protected function's outcome. - Registered local locks and in-flight coordination are rebuilt after POSIX fork; inherited periodic loops require explicit child startup.
- External cache deadlines use the live wall clock. The unsafe handwritten Redis recipe is replaced by a namespaced adapter that does not scan for statistics.
- Default log argument redaction matches whole name segments. Use
redact_match="substring"for the old mode, and explicitly list actual credentials namedsession_idin applications where that name is sensitive. CacheInfo.currsizemay be None for an external store with an unknown size.CircuitOpenErroris never retried. Ordinaryon_retryfailures are swallowed after logging; hook cancellation and process-exit exceptions still propagate.- Default coordination remains in-process. Shared backends are explicit, clients need finite timeouts, and leases/idempotency cannot guarantee exactly-once effects across crashes or lease expiry. See the migration and limitation guides.
0.2.1 - 2026-10-29
Publishes the completed 0.2 release under a fresh version, preserving the older
v0.2.0 tag from the failed publishing attempt.
A ground-up rework and a much larger toolkit. Every decorator works on plain functions,
async def functions and methods, keeps the wrapped signature for type checkers, and never
configures logging. Several
v0.1 decorators that did not do what their names promised (transactional, revert_on_failure,
async timing) now work. See the
migration guide for the full upgrade
path.
- Zero dependencies, fully typed.
wraptandtyping-extensionsare gone; signatures are preserved withParamSpec, the package shipspy.typed, andmypy --strictis clean. - Sync and async with one API.
async defwrappers stay coroutine functions and never block the event loop. - A real resilience toolkit.
retrywith backoff, jitter and hooks;CircuitBreaker;fallback;suppress;timeoutthat actually interrupts. - A real concurrency toolkit.
memoizewith TTL and LRU,rate_limitwith a sliding window, a sharedRateLimiter,Bulkhead,throttle,debounceandsingleflight. - Retry that honours the server.
retry(delay_from=retry_after_header)followsRetry-After,max_time=anddeadline()cap the total time, and cancellation is never retried. - An async toolkit.
gather_limit,map_async,amap_iter,raceandrun_sync, plusbatch_calls(the DataLoader pattern) andhedge. - Policies and configuration.
policy(...)applies protections in the recommended order, andconfigure()sets project-wide defaults. - Observable and testable.
count_calls, onepython_wrap.eventshook for every component,log_context, andpython_wrap.testing(fast_mode,FakeClock,spy, pytest fixtures). - Fast. The
memoizehit path is about 9x faster and the validation and logging decorators skip signature binding on plain calls. - Safe by default. Importing the package no longer touches the root logger, and
log_args,auditandtraceredact secrets. - Works on Windows, and is tested on Python 3.10 to 3.14 on Linux, macOS and Windows.
run_in_threadreturns aconcurrent.futures.Futureinstead of aThread. Migrate: replace.join()with.result()(which also returns the value and re-raises errors).benchmarkis a plain function,benchmark(func, *, args=(), kwargs=None, runs=5, warmup=1) -> BenchmarkResult, instead of a decorator that silently ran the function three times per call. Migrate: callbenchmark(func, args=(...)); usebenchmark_asyncfor coroutines.retry_on_exceptionis deprecated and now stops after 3 attempts by default (v0.1 retried forever with no delay). Migrate: useretry(on=...), and passmax_attempts=Noneto keep the old unlimited behaviour.rate_limitraisesRateLimitExceededinstead of a bareException. Migrate: catchRateLimitExceeded(useexc.retry_after), or passblock=Trueto wait instead.log_args,log_returnandtracelog atDEBUGby default (log_argsusedINFO). Migrate: passlevel=logging.INFOto keep the old level.no_debugis a deprecated no-op and will be removed in 0.3. Migrate: delete the decorator.validate_argsandcheck_typeraiseTypeErrorat decoration time for a name that is not a parameter of the function. Migrate: fix the misspelled or stale parameter name.- Python 3.8 and 3.9 are no longer supported. Migrate: upgrade to Python 3.10 or newer, or stay on 0.1.0.
- Importing the package no longer calls
logging.basicConfig. Migrate: configure logging in your application if you relied on python-wrap's root-logger setup.
Resilience:
RetryBudget(withRetryBudgetStats): one Finagle/Envoy-style retry allowance shared across functions, threads and event loops viaretry(budget=...),retrying(budget=...)orconfigure(retry={"budget": ...}). When it is spent, retrying stops at once and emitsretry.budget_exhausted, which prevents retry storms against a failing dependency.retry_if_result=onretry/retryingretries when the function returns a matching value; once retries run out the last value is returned.retryingblocks setattempt.result.- For
async deffunctions,retry_if,retry_if_resultandon_retrymay be async and are awaited;async with attempt:is supported inretrying. timeout(..., cleanup_grace=)bounds async cleanup after the limit: the call is cancelled, given the grace to finish its cleanup, thenTimeoutExpiredis raised.retry:delay_from=(with theretry_after_headerhelper forRetry-After),max_time=,log_level=andlog_exc_info=;retry_stats(func)andRetryStats;retrying(...)/Retryingfor retrying an inline block (for/async forwithwith attempt); retries honourdeadline(). Cancellation,KeyboardInterrupt,SystemExitandGeneratorExitare never retried.CircuitBreaker:success_threshold,exclude=,on_state_changeand.stats(CircuitStats).timeoutis also a context manager (with timeout(5):/async with timeout(5):) and returns aTimeoutobject.python_wrap.deadline(deadline(),remaining(),check()) gives code a shared time budget, andtimeoutclamps to it.hedge(delay, max_extra=, on=): hedged requests for idempotent calls; the first success wins and async losers are cancelled.
Async toolkit and concurrency:
periodic(interval, *, jitter=, initial_delay=, max_runs=, on_error=)runs a sync function in a daemon thread, or an async function as a task, every N seconds without drift (missed ticks are skipped). The function stays callable and gainsstart(),stop(),running,runs,last_errorandrunning_in_background()for clean shutdown. Eventsperiodic.runandperiodic.failed.python_wrap.aio:gather_limit,map_asyncandamap_iter(bounded concurrency, lazy input, ordered results; everything is cancelled and awaited on error, cancellation or early exit),race(first success wins;RaceFailed) andrun_sync(refuses to run inside a running loop).Bulkhead(max_concurrent, max_waiting=, timeout=, name=)for sync and async (decorator,with,async with,.active,.waiting),limit_concurrency(n)andBulkheadFull.RateLimiter: one budget shared across functions (with,async with,acquire,try_acquire), and several windows at once withrate_limit(limits=[(5, 1), (600, 900)]).batch_calls(max_size=, max_wait=, key=): the DataLoader pattern for sync and async code, with de-duplication,.flush()/.aflush()/.pending, andBatchErroron contract violations.
Caching:
memoize(ttl=..., stale_ttl=...): stale-while-revalidate. Afterttla stale value is served at once while one background refresh runs (a task for async functions, a daemon thread for sync ones); a failed refresh keeps the stale value and is logged. Eventscache.staleandcache.refresh_failed.memoize(store=...)and theCacheStoreprotocol: keep entries in any store (a dict, Redis, ...); thecache_*helpers work against it.memoize(per_instance=True): per-instance method caches held through weak references, so instances stay collectable and need not be hashable.cached_property(ttl=)(thread-safe,async defgetters,invalidate()).memoize:cache_exceptions=/exception_ttl=, a per-itemttl=callable, andcache_contains(),cache_get()andcache_parameters().
Observability, configuration and testing:
trace(otel=True, span_name=...)wraps calls in an OpenTelemetry span (sync and async) withcode.function,code.namespaceandpython_wrap.context.*attributes and exception recording.opentelemetry-apiis imported lazily and only when asked for; python-wrap still has no runtime dependencies.count_calls: calls, errors, in-flight, mean, p50, p95 and p99 per function.python_wrap.events:subscribe(),listening(),filter_events()andEVENT_NAMES, one hook for retry, cache, circuit, limiter, bulkhead and timeout events (Prometheus, OpenTelemetry and statsd recipes in the docs).log_context()/current_log_context(): contextvar fields inlog_args,log_return,audit,traceandtimingmessages, onLogRecord.contextand onAuditRecord.context.log_argsandauditacceptredact_extra=.policy(...)/Policy: reusable, immutable decorator bundles placed by role (observe,validate,fallback,cache,limiter,bulkhead,breaker,retry,timeout,guard,outer,inner) in the recommended order, with.with_();wrap_methods(*decorators, include=, exclude=, include_private=)decorates a class.python_wrap.config:configure(),configured(),get_config()andreset_config()for project-wide defaults (logger, retry options, redaction), read at decoration time; explicit arguments win.python_wrap.testing:fast_mode(),disable_retries(),disable_rate_limits(),disable_caching(),overrides()(context managers and decorators),FakeClock/fake_clock(),spy()/spy_on(),eventually()/eventually_sync(), and the pytest fixturespw_fake_clockandpw_fast_mode(pytest_plugins = ["python_wrap.testing"]).- Typing: stacked decorators keep the exact function type (
@retryover@memoizekeeps.cache_info()), andMemoized,Once,CircuitProtected,LimitedandCountedbind correctly under methods and@classmethod. Typing regression tests runmypyin CI. - A cookbook of eight recipes, seven runnable
examples/, a performance page withbenchmarks/run.py, and a thread-safety stress suite (PW_STRESS=1, also run on free-threaded 3.13t and 3.14t).
Core:
- Decorated functions, including
periodicobjects andwrap_methodsclasses, pickle by reference, so they work withmultiprocessingandProcessPoolExecutorunder the "spawn" start method. Cache, limiter and breaker state is per worker process. retry:backoff,max_delay,jitter,on=exception filter,retry_if=predicate,on_retry=hook receiving aRetryState, unlimited attempts (max_attempts=None), and bare@retryusage.fallback(value)/fallback(handler=...)andsuppress(*exceptions)for failing soft.CircuitBreaker(shareable across functions), thecircuit_breakerdecorator (breaker exposed as.breaker) andCircuitState.memoize:maxsize(LRU),ttl,typed,key=,cache_info(),cache_clear(),cache_delete(), and in-flight de-duplication for async functions.throttle(interval),debounce(wait)with.cancel()and.flush(),singleflight(key=), andrate_limit(block=, key=).timing(threshold=, callback=)withTimingRecord,measure_memory(callback=)withMemoryRecord,profile(sort=, limit=, callback=), andbenchmark_async.log_argssecret redaction (redact=,DEFAULT_REDACT) andmax_length=;auditnow yields a structuredAuditRecordwithsink=andinclude_result=;trace(limit=). Every logging decorator acceptslogger=andlevel=.enforce_types: runtime checks from annotations (generics, unions,Literal,Annotated,NewTypeand more) for arguments and return values.Transactionwithon_commit/on_rollback,tx=injection,current_transaction(), and sync and async context-manager support.revert_on_failure(attrs=, deep=, target=).deprecate(since=, removed_in=, alternative=, category=), which also works on classes;mock_data(enabled=bool | callable);compose(*decorators).- Exceptions in
python_wrap.errors, all subclassingPythonWrapError:TimeoutExpired(also aTimeoutError),RateLimitExceeded,CircuitOpenError,ValidationError(also aValueError) andArgumentTypeError(also aTypeError). oncegained.reset()and.called.- A
py.typedmarker, and aNullHandleron thepython_wraplogger.
CircuitBreaker,RateLimiter,Bulkhead,RetryBudget,Transaction,Policyandtesting.FakeClockraise a clearTypeErrorwhen pickled or copied (their state belongs to one process), instead of an error about a thread lock or a copy that silently shares a lock.RetryState.exceptioncan beNone(when a returned value was rejected byretry_if_result), andRetryStatehas a newresultfield. A sync function given an async retry hook raisesTypeErrorwhen decorated.- On free-threaded Python 3.14t new threads inherit the caller's context, so
log_contextfields carry over into them (sys.flags.thread_inherit_context). - The project uses a
src/layout and Hatchling, and requires Python 3.10 or newer. - The runtime dependencies
wraptandtyping-extensionswere unused and have been removed. retrywaits withasyncio.sleepforasync deffunctions, and re-raises the final exception unchanged with its original traceback.timeoutraisesTimeoutExpired. Async functions are cancelled withasyncio.wait_for; sync functions are interrupted withSIGALRMon the Unix main thread. The thread fallback used elsewhere cannot stop the work, and is now documented.memoizeandcachekeys are bound to the function signature with defaults applied, sof(1),f(x=1)andf(1, y=<default>)share one entry; list, dict and set arguments are converted to hashable keys.deprecatepoints its warning at the caller and sets__deprecated__(PEP 702).from python_wrap.decorators import ...still works through a compatibility module.timeout(...)now returns aTimeoutobject, which is both a decorator and a context manager. Decorator use is unchanged.retrynever retries cancellation-type exceptions (asyncio.CancelledError,KeyboardInterrupt,SystemExit,GeneratorExit), even ifon=lists them.- The
redact=default onlog_argsandauditisNone, which means "the configured value, orDEFAULT_REDACT". Passredact=()to turn redaction off. auditwith nosinkand a disabled log level builds no record at all.Limited.bulkheadis a read-only property.- Test overrides apply only to backoff waits.
fast_mode()andfake_clock()no longer shorten limits on how long to wait: asyncBulkhead/limit_concurrencytimeouts,race(timeout=), asynchedgedelays and asyncbatch_calls/debouncewindows run on real time, like their sync versions andtimeout. - Under
fast_mode(), a blocking rate limiter (block=True) that would wait lets the call through at once and still counts it.
-
Final releases now pass through TestPyPI and an installation check before PyPI. Both indexes are verified after upload before creating the GitHub release.
-
Source distributions include the examples and benchmark script used by their tests.
-
Release smoke checks validate metadata, public imports,
py.typed, retry, memoization and async behavior in an isolated installed environment. -
AsyncPeriodic.stop()no longer swallows a cancellation aimed at the task awaiting it, and ends a loop whose run swallows the cancel;stop()called inside a run ends the loop as soon as that run returns. -
timeout(..., cleanup_grace=...)lets an outside cancellation propagate asCancelledError(matchingasyncio.timeout), and waits for and retrieves the child task when the caller is cancelled instead of logging "Task exception was never retrieved". -
periodic(on_error="raise")logs an error thatstop()never collected whenstart()is called again, instead of dropping it silently. -
revert_on_failurenever restored anything because its snapshot was always empty. -
transactionalwas a no-op; it now commits and rolls back through aTransaction. -
memoizeandcachebuilt keys fromstr(args), which collided and ignored keyword equivalence.cache()also shared a single store across all functions it decorated. -
timingmeasured about zero seconds forasync deffunctions, and now usesperf_counter. -
measure_memoryusedru_maxrss, which is Unix-only and reported the wrong units; it now usestracemalloc. -
The package failed to import on Windows because it imported the Unix-only
resourcemodule. -
auditreported the wrapper's own frame as the caller. -
oncewas not thread-safe, and now retries after an exception. -
validate_argsrebuilt the function signature on every call. -
Under
fast_mode()orfake_clock(), async bulkhead andracetimeouts expired at once andhedgelaunched every backup attempt immediately. -
A blocking
RateLimiter/rate_limit(block=True)busy-spun at full CPU underfast_mode(). -
timeout's thread fallback reported a call as late when it advanced the fake clock (for example aretryinside it), and a nested signal-basedtimeoutdid not fire underfake_clock(). -
@transactionalon a function with a positional-only (or*tx/**tx)txparameter crashed at call time; it now raisesTypeErrorwhen decorating. -
singleflight's default key treatedf(1, b=2)andf((1,), (("b", 2),))as the same call, andmemoizeon a callable without an inspectable signature treatedf(1, b=2)andf(1, 2)as the same call.
- Async
memoizeandcachehits are about 30-35% faster (one lock instead of two). - The
memoizehit path is about 9x faster. validate_args,check_type,enforce_types,log_argsandauditskip signature binding on plain positional calls (5x to 40x faster).auditskips building a record when nobody would receive it, andtimingskips formatting when its log level is disabled.- Numbers and a benchmark script are on the performance page.
retry_on_exception: useretry(on=...). Emits aDeprecationWarning.no_debug: a no-op, to be removed in 0.3.cache: soft-deprecated in the docs only (no warning yet); prefermemoize(ttl=...).
- Support for Python 3.8 and 3.9.
- Poetry as the build and dependency tool (replaced by Hatchling and uv).
- The Sphinx documentation (replaced by the new documentation site).
- The token-based PyPI publish workflow (replaced by tag-driven publishing with Trusted Publishing).
- CI runs ruff,
mypy --strict, the test suite on Linux, macOS and Windows across Python 3.10 to 3.14, the test and thread-safety stress suites on free-threaded Python 3.14t, and a wheel check. - Tag-driven releases publish to PyPI through Trusted Publishing, with no stored token.
- The documentation build is checked in CI and hosted on Read the Docs.
- Added Dependabot, issue and pull request templates,
CONTRIBUTING.md,SECURITY.md,CODE_OF_CONDUCT.mdandRELEASING.md.
- The
timeoutthread fallback (Windows, non-main threads) cannot stop the running work. rate_limit,throttleanddebounceshare state across instances when used on methods (rate_limitacceptskey=to split it).memoizeon methods keeps instances alive; usemaxsizeorttl.- Concurrent calls to
measure_memoryshare one tracker, andprofileon an async function includes event-loop work. transactionalinjectstx=by keyword, so declaretxlast or keyword-only.
0.1.0 - 2025-01-21
Initial release.