Skip to content

Latest commit

 

History

History
934 lines (846 loc) · 62.7 KB

CHANGELOG.md

File metadata and controls

934 lines (846 loc) · 62.7 KB

Changelog

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.

Security

  • 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.

Fixed

  • 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

Breaking changes

  • observability.enable() now adds python_wrap events as span events on the current span instead of opening a zero-length pw.<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 across register()/load_from_mapping() (also with new thresholds), and an unchanged mapping keeps its generation. Call the breaker's reset() to close it.
  • Retry events carry a new attempt_seconds field; listeners that compare the whole fields dict 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_tags kept 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.
  • SqlResultStore only 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 RedisSource key 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_llm and 86 more) leave the top-level python_wrap namespace: import them from python_wrap.llm, python_wrap.agents, python_wrap.genai, python_wrap.adapters.... The old names still work with a DeprecationWarning and go in 0.6.0. mcp_guard stays, since it shares its name with its module. import python_wrap now loads 45 modules instead of 57.

Changed

  • concurrency is split into timeouts, ratelimit, debounce (throttle and debounce) and singleflight; python_wrap.concurrency re-exports every name, so imports keep working. Code that patched a module global (concurrency._HAS_SETITIMER) must patch the new module.
  • docs/project/stability.md publishes graduation criteria and target releases for the provisional modules and a support window; tests/test_stability.py pins the storage formats of the shared backends. benchmarks/run.py --redis-url measures shared layers on a real Redis, and benchmarks/soak.py --processes N --redis-url soaks several processes sharing one breaker and limiter.

Fixed

  • Shared cache keys (RedisStore, AsyncRedisStore) and idempotent/single_instance call 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 raise TypeError naming the argument (pass key=). Redis cache keys gain a k2: 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, FileSource or RedisSource validates and applies changed mappings, emits config.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_backend registries; nothing is imported by dotted path. Health reports include policy generations.

  • guard_openai guards embeddings.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 with max_retries=0 and runs invoke/ainvoke through the budget, retry loop, policy and token limiter; stream/astream are resume-safe. PythonWrapCallback observes calls and emits genai.llm_call. read_usage understands LangChain usage_metadata. New langchain extra.

  • 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 carry attempt_seconds. Shared breakers report their state in every process.

  • memoize and amemoize gain lock= (with lock_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= with invalidate_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), with ddl() 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_rate with minimum_calls over window, and slow_call_duration with slow_call_rate (a slow half-open trial re-opens). A non-default failure_threshold with failure_rate raises ValueError. Calls are counted in ten time slots per window, locally and in the Redis and SQLite backends. CircuitStats and the circuit.state_changed event add failure_rate and slow_rate.

  • RedisBreakerState and AsyncRedisBreakerState cache a closed state for state_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 to state_ttl after another process opened the breaker; state_ttl=0 restores one round trip per call. The script runs with EVALSHA and reloads on NOSCRIPT.

  • Async-native shared backends: AsyncRedisBreakerState, AsyncRedisLock and AsyncRedisSemaphore reuse 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 raise TypeError when used from sync code; CircuitBreaker.areset() and aforce_open() cover the admin calls. SharedBackends (and shared=) builds the async classes for a redis.asyncio client. idempotent(store=...) accepts an AsyncCacheStore (an AsyncRedisStore gets a matching AsyncRedisLock). amemoize gains stale_ttl, cache_exceptions, exception_ttl and logger, matching memoize. 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 project cache_codec default and a version= namespace. Bad signatures produce cache.rejected misses; 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 with install(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's retry_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) and install(hard_margin=5.0): a task with only a hard time limit now gets a cooperative deadline of hard limit minus the margin.

  • HttpPolicy with PolicyTransport, AsyncPolicyTransport and mount_policy: retries plus a circuit breaker, rate limiter and bulkhead (optionally one set per host), default connect/read timeouts shortened to the surrounding deadline, 429 Retry-After pauses and propagate=True request-id / X-Request-Deadline headers. RetryTransport, AsyncRetryTransport and mount_retries are 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 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.

  • shared= on every preset (http_client, db_call, third_party_api, llm_client) and configure(shared=...), also read by PolicyRegistry: breaker state, rate window, bulkhead 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 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.

Added

  • 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 (event rate_limit.store_error) unless fail_open=False. SQLiteBudgetBackend shares a Budget the same way.

  • observe_headers(headers) on TokenRateLimiter and the windows (plus parse_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 (pydantic model_validate_json or any callable), re-asks with only the error text, caps calls at 1 + max_repairs (plus max_tokens= and budget=), and raises ValidationRepairExhausted with every attempt and its token cost. Sync and async; events llm.validation_failed and llm.repair_exhausted.

  • Cassette records and replays LLM HTTP traffic at the transport level (RecordingTransport / ReplayTransport, duck-typed against httpx): request-hash matching with ignore_body_keys / ignore_query, secrets never stored (headers, JSON keys, query parameters, literal secrets= and key shapes), chunked streaming bodies, strict replay (CassetteMiss) and loud failure on a damaged file (CassetteError). Opt-in pytest fixtures llm_cassette and chaos_llm_http via pytest_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 the LLMFaults rules.

  • python_wrap.adapters: guard_openai / guard_anthropic wrap 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, a Budget, a TokenRateLimiter lowered to x-ratelimit-remaining-tokens / anthropic-ratelimit-tokens-remaining (read via with_raw_response; a 429's retry-after drains it) and optional traced_llm. No SDK is imported; optional openai / anthropic extras pin tested versions.

  • Retry coordination: no_sdk_retries(client) (with_options(max_retries=0)), sdk_max_retries, and llm_retry(owns_retries=True, client=...): nested llm_retry layers 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 raises StreamInterrupted with the partial text, completed and pending tool calls (never replayed). Understands OpenAI chat chunks, Responses events and Anthropic message events; stall limits via stream_timeout. stream_transient classifies 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 marked sdk run against the real SDKs over a mock HTTP transport and skip when they are absent.

  • agent_run(budget=...) / RunGuard accept a real python_wrap.llm.Budget: entering the run opens the budget's per-run scope, so decorated LLM calls draw on it, and the next step raises RunBudgetExceeded once it is spent (direct calls still raise BudgetExceeded).

  • python -m python_wrap migrate (and the MCP migrate_preview tool) detects hand-rolled retry loops around LLM client calls and rewrites the safe for ... in range(N) shape to an @llm_retry function; every other loop is reported with line numbers and a suggestion. Change gains a kind field.

  • 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 with fake_clock-driven delays, call recording, Anthropic- and OpenAI-style usage, token and call assertions) and chaos.llm fault rules (rate_limit, overloaded, server_error, timeout, malformed_json, slow_first_token, stalled_stream, invalid_tool_call, refusal), also loadable from PW_CHAOS via an "llm" key. Look-alike errors live in python_wrap.llm_testing.

  • python_wrap.genai: AI observability and compliance. traced_llm / traced_tool publish genai.llm_call / genai.tool_call events 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. Redactor scrubs secrets, emails, card numbers and custom patterns and truncates text; content capture is opt-in. AuditTape records calls to memory, JSONL or SQLite; replay() returns a ReplayProvider serving recorded results with ReplayMismatch detection. New observability.enable_genai and genai_span_attributes.

  • Cooperative cancellation for sync timeout: CancelToken, cancel_requested(), checkpoint() and current_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: timeout warns when it takes over a SIGALRM that already has a non-default handler or an armed ITIMER_REAL timer (both are still restored).

  • Doctor checks PW009 (sync timeout that cannot be enforced preemptively: side effects may continue) and PW010 (existing SIGALRM handler or timer that timeout would take over).

  • Policy.explain(), python_wrap.doctor.doctor(func) and python -m python_wrap doctor describe 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 (and python_wrap.migrate.migrate_source): a stdlib-only codemod rewriting tenacity and backoff retry decorators to retry, with dry-run, --diff and --write modes, 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-wide chaos injector add latency, exceptions or canned results at named points (glob patterns, rate, times, seeded randomness), chaos.open_circuit(breaker), and rules loaded from PW_CHAOS only when that variable is set. New event chaos.injected.

  • python_wrap.presets: http_client(), db_call() and third_party_api() policies with documented timeouts, attempts, backoff, retry budgets and breaker thresholds; idempotent=False leaves the retry layer out.

  • attempt_history(exc): the exception retry re-raises carries an AttemptRecord per failed attempt (duration, exception type name, following wait). observability.annotate_span copies it onto an OpenTelemetry span and observability.sentry_breadcrumbs() records python-wrap events as Sentry breadcrumbs, with exceptions reduced to type names.

  • HealthRegistry.summary(critical=...) rolls component health up into ok/degraded/ down with a matching HTTP status, served as JSON by health.wsgi_app() and health.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 as RedisBreakerState; 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, RunLocks and configure_locks, a low-diff replacement for hand-rolled SET NX/DEL lock 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 with LoadShed; PerKeyLimiter and per_key give each tenant its own limiter or bulkhead with LRU eviction. New events adaptive.limit_changed and adaptive.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 and atexit installation and a per-item ShutdownReport. New lifecycle.* events.

  • benchmarks/soak.py (policy soak test against a simulated flaky dependency, checking retry amplification, breaker recovery and memory) and benchmarks/compare.py (overhead next to tenacity, backoff, cachetools and functools.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_countdown and retry_task schedule Celery task retries from request.retries with explicit delays or capped backoff, honouring a dependency's retry_after/Retry-After; shared_breaker builds 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 union db_transient (also SQLAlchemy connection_invalidated) and error_code(...) for driver error numbers. No driver is imported.

  • amemoize, an async-native cache for async def functions whose store is awaited, so Redis I/O no longer blocks the event loop: AsyncCacheStore protocol, AsyncMemoryStore (LRU + TTL) and AsyncRedisStore for redis.asyncio clients, with singleflight for concurrent misses and json_codec() for caches that must not unpickle.

  • python_wrap.http: method-safe HTTP retries. HttpRetryPolicy retries idempotent methods (or any request carrying an Idempotency-Key) on transport errors and 408/425/ 429/5xx, honouring Retry-After, deadlines and RetryBudget. RetryTransport and AsyncRetryTransport plug into httpx, mount_retries into a requests.Session, and http_retry wraps aiohttp-style or hand-written clients. No HTTP library is imported.

  • python_wrap.exporters: PrometheusExporter turns 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 /metrics endpoints, a prometheus_client bridge and a cap on label cardinality; StatsDExporter sends 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 local serve(), plus a sample Grafana dashboard in docs/assets/grafana-dashboard.json.

  • python_wrap.web: IdempotencyMiddleware (ASGI) and WsgiIdempotencyMiddleware dedupe requests carrying an Idempotency-Key, replaying stored responses, answering 409 for a concurrent duplicate and 422 for a reused key with a different body.

  • ratelimit_headers, too_many_requests and problem_response build IETF RateLimit-* 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=) and debounce(..., key=, per_instance=), and rate_limit(..., per_instance=): split the state of decorated methods that every instance used to share. key= mirrors rate_limit/singleflight (a function of the call's arguments, one window or countdown per key; idle keys are dropped); per_instance=True keeps one window, pending call or limiter per instance, held through a weak reference so instances stay collectable and need not be hashable. With either option debounce'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 def functions already shared one in-flight task per key and loop. cache_parameters() gains singleflight and key.

  • Doctor code PW011: a memoized method keyed on self with no maxsize, ttl or store pins every instance it sees. The fix is the existing memoize(per_instance=True), which keeps instances collectable through weak references. No default changed.

  • Doctor check PW012: explain(..., multiprocess=True), doctor(..., multiprocess=True) and python -m python_wrap doctor --multiprocess warn 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 report shared for bulkheads and rate limiters and recognise AdaptiveLimiter layers.

  • Async-friendly Redis backends. AsyncRedisWindow is RedisWindow for redis.asyncio clients (same Lua script and keys): shared_rate_limit and RateLimiter(backend=...) await it on the event loop instead of spending a worker thread per round trip, and reject it on synchronous functions with TypeError. ThreadedStore(store, executor=None) turns any synchronous CacheStore (such as RedisStore with a plain redis.Redis client) into an AsyncCacheStore for amemoize, running each call in a worker thread so it never blocks the loop.

  • Durable buffered writers: buffered(journal=...), Buffered(journal=...) and AsyncBuffered(journal=...) persist each accepted record before submit returns 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 first submit or an explicit replay(). Journals: SQLiteJournal (stdlib, local file), RedisStreamJournal (Redis stream), or any BufferJournal implementation. Opt-in; without a journal nothing changes.

  • enforce_types(strict=True) raises UnsupportedAnnotationError (a TypeError, in python_wrap.validation) for annotations it cannot check (protocols that are not runtime_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 raising StepLimitExceeded, LoopDetected (identical repeated calls) and RunTimeout; current_run() exposes the run id, step count and history, run_id_var the run id for tracing, and the run's CancelToken makes checkpoint() stop long tools cooperatively. record_step() counts LLM calls.

  • ToolPolicy (allow/deny globs, allow_write=False, dry_run=True returning a declared dry_result or a DryRun marker) raising ToolNotAllowed; sync/async human approvers with a timeout that deny by default (ApprovalDenied, ApprovalTimeout); ToolRegistry dispatches 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_transient and llm_retry() retry 408/409/429/529/5xx, overloaded, timeout and connection errors, honouring Retry-After and retry-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 with prices={"model": (in_per_mtok, out_per_mtok)}, optional period= windows and a shared RedisBudgetBackend; raises BudgetExceeded. New event llm.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 event llm.fallback_served naming the model that served.

  • stream_timeout(first_token=, chunk_gap=, total=) for sync and async streams, raising StreamTimeout (a TimeoutExpired) with .limit naming the limit that tripped.

  • llm_cache(): an exact-match response cache keyed on model, messages/prompt and parameters, with TTL, any CacheStore/AsyncCacheStore, and an optional similarity= 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 without retry_if around an LLM call).

  • Agent-friendly tooling, generated from __all__, docstrings, signatures and the docs so it tracks every release:

    • docs/llms.txt and docs/llms-full.txt (llmstxt.org format, served at the site root), generated by scripts/gen_llms.py and checked by tests/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 extensible python_wrap/_data/recipes.json.
    • python -m python_wrap guide: a concise usage guide for coding agents shipped in the wheel, plus ready-to-copy AGENTS.md, project-memory, editor-rule and skill files under docs/agents/.
    • python -m python_wrap mcp: a dependency-free, read-only Model Context Protocol server over stdio (python_wrap.mcp) with explain_policy, doctor, migrate_preview, search_api, get_symbol, recipe and guide tools; --allow restricts 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 raises EffectConflict, and a crash or store failure between the side effect and the record (or a timeout/cancellation) is detected and handed to an on_unknown hook ("retry", EffectResolved(value), or EffectUnknown). Stores: MemoryEffectStore, SQLiteEffectStore, RedisEffectStore (also built from a RedisStore(fail_open=False)). ToolCall gains call_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 retries ModelRetry, approvals, ledger on tool_call_id, loop and tool-call limits, a usage bridge into a python-wrap Budget, and AuditTape records. Optional extra python-wrap[pydantic-ai].

  • python_wrap.adapters.openai_agents.AgentsGuard: guarded function_tools, wrap() for existing FunctionTools (sub-agents via as_tool included, sharing one max_tool_calls), and RunHooks / AgentHooks feeding Budget, AuditTape and repeat detection; run-ending errors are re-raised through the SDK's tool error handling. Optional extra python-wrap[openai-agents].

  • mcp_guard: per-attempt timeout, retries limited to retry_tools, a shared per-server CircuitBreaker (mcp_breaker) and cooperative cancellation around an MCP call_tool function or client object (MCPGuard). Doctor checks PW020 (MCP or framework tool call without a timeout) and PW021 (MCP guard retrying every tool).

Security

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/WsgiIdempotencyMiddleware no longer store or replay Set-Cookie and 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's Authorization and Cookie headers, 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 to max_body and fingerprints them, instead of treating them as empty (medium).
  • MemoryResultStore is bounded (max_entries, default 10,000), so a flood of distinct client-supplied keys cannot exhaust memory (medium).
  • problem_response no longer copies internal breaker or bulkhead names from exception messages into 503 bodies sent to clients (low).
  • A delay_from hint such as Retry-After is capped at HINT_CEILING (600 s) when max_delay is 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 @channel or inject a link (low).
  • Workflows: every action is pinned to a commit SHA, actions/checkout runs with persist-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_path must be module:attribute with identifiers only and no dunder attributes, the module must already be importable (optionally under --allow prefixes), messages and migrate_preview sources 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 in tests/test_mcp.py).

Changed

  • The package description now matches what it is: a typed, zero-dependency resilience toolkit. The Beta classifier 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_types now checks TypedDict annotations (required keys present, each present key's value checked; extra keys allowed) and parameterised runtime_checkable protocols such as SupportsAbs[int] (isinstance), which it used to accept unchecked. A dict missing a required key now raises ArgumentTypeError.
  • measure_memory serialises measured calls process-wide (tracemalloc has 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 or asyncio.to_thread workers started inside a measured call join it instead of waiting. New exclusive=False restores the old, unserialised behaviour.
  • profile on an async def function now profiles only that coroutine's own steps: the profiler is switched off at every await and 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.

Fixed

  • 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 with sqlite3.OperationalError: database is locked while switching to WAL. Setup now retries until busy_timeout has elapsed.
  • retry_after_header: an unparseable Retry-After value (free text, or a Python-only form such as 1_0) is now ignored on its own, so the json_key= body fallback still applies instead of the whole lookup being abandoned.

Tests

  • 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), marked e2e and run in the default suite. scripts/smoke_wheel.py builds 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_client parser round trip), Retry-After edge cases, real-Redis tests for RedisSemaphore, RedisCheckpoint and RedisSource, and non-main-thread timeout fallback behaviour.

Documentation

  • docs/project/limitations.md: the timeout thread 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.

Added

  • Explicit retry/retrying(delays=[...]) schedules, repeating the final wait, and log_values=False for 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, bind and unbind for context on application log records, plus optional Flask, FastAPI/ASGI, Django and Celery lifecycle adapters.

  • Deep redact and is_sensitive helpers, opt-in deep=True argument redaction; result-based Retry-After and http_status; composable Predicate, sqlstate, message_contains and in_cause_chain helpers.

  • RedisStore, early-refresh expiring credential loaders, named PolicyRegistry, global policies, and call-time resilient policy resolution.

  • Owner-checked local/Redis leases, single_instance, PostgreSQL advisory and SQL Server application-lock adapters, and retained-result idempotent execution.

  • Redis sliding windows, run Quota budgets, shared breaker state, failure windows, and lease-backed shared bulkhead capacity. CircuitBreaker.force_open() supports maintenance and tests.

  • Bounded sync/async buffered writers, per-item batch processing outcomes and explicit memory/Redis checkpoints, and dynamic environment/Redis switches.

  • Opt-in OpenTelemetry event spans and bounded-label metrics, timed slow-call detection, an explicit weak health registry, disabled, assert_retried and assert_cache_hit.

  • Feature guides, public API pages, worker-lifecycle recipes and a 0.3 migration guide.

Fixed

  • 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_retry hook 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.

Behavior changes

  • Default log argument redaction matches whole name segments. Use redact_match="substring" for the old mode, and explicitly list actual credentials named session_id in applications where that name is sensitive.
  • CacheInfo.currsize may be None for an external store with an unknown size.
  • CircuitOpenError is never retried. Ordinary on_retry failures 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.

Highlights

  • Zero dependencies, fully typed. wrapt and typing-extensions are gone; signatures are preserved with ParamSpec, the package ships py.typed, and mypy --strict is clean.
  • Sync and async with one API. async def wrappers stay coroutine functions and never block the event loop.
  • A real resilience toolkit. retry with backoff, jitter and hooks; CircuitBreaker; fallback; suppress; timeout that actually interrupts.
  • A real concurrency toolkit. memoize with TTL and LRU, rate_limit with a sliding window, a shared RateLimiter, Bulkhead, throttle, debounce and singleflight.
  • Retry that honours the server. retry(delay_from=retry_after_header) follows Retry-After, max_time= and deadline() cap the total time, and cancellation is never retried.
  • An async toolkit. gather_limit, map_async, amap_iter, race and run_sync, plus batch_calls (the DataLoader pattern) and hedge.
  • Policies and configuration. policy(...) applies protections in the recommended order, and configure() sets project-wide defaults.
  • Observable and testable. count_calls, one python_wrap.events hook for every component, log_context, and python_wrap.testing (fast_mode, FakeClock, spy, pytest fixtures).
  • Fast. The memoize hit 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, audit and trace redact secrets.
  • Works on Windows, and is tested on Python 3.10 to 3.14 on Linux, macOS and Windows.

Breaking changes

  • run_in_thread returns a concurrent.futures.Future instead of a Thread. Migrate: replace .join() with .result() (which also returns the value and re-raises errors).
  • benchmark is 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: call benchmark(func, args=(...)); use benchmark_async for coroutines.
  • retry_on_exception is deprecated and now stops after 3 attempts by default (v0.1 retried forever with no delay). Migrate: use retry(on=...), and pass max_attempts=None to keep the old unlimited behaviour.
  • rate_limit raises RateLimitExceeded instead of a bare Exception. Migrate: catch RateLimitExceeded (use exc.retry_after), or pass block=True to wait instead.
  • log_args, log_return and trace log at DEBUG by default (log_args used INFO). Migrate: pass level=logging.INFO to keep the old level.
  • no_debug is a deprecated no-op and will be removed in 0.3. Migrate: delete the decorator.
  • validate_args and check_type raise TypeError at 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.

Added

Resilience:

  • RetryBudget (with RetryBudgetStats): one Finagle/Envoy-style retry allowance shared across functions, threads and event loops via retry(budget=...), retrying(budget=...) or configure(retry={"budget": ...}). When it is spent, retrying stops at once and emits retry.budget_exhausted, which prevents retry storms against a failing dependency.
  • retry_if_result= on retry/retrying retries when the function returns a matching value; once retries run out the last value is returned. retrying blocks set attempt.result.
  • For async def functions, retry_if, retry_if_result and on_retry may be async and are awaited; async with attempt: is supported in retrying.
  • timeout(..., cleanup_grace=) bounds async cleanup after the limit: the call is cancelled, given the grace to finish its cleanup, then TimeoutExpired is raised.
  • retry: delay_from= (with the retry_after_header helper for Retry-After), max_time=, log_level= and log_exc_info=; retry_stats(func) and RetryStats; retrying(...) / Retrying for retrying an inline block (for / async for with with attempt); retries honour deadline(). Cancellation, KeyboardInterrupt, SystemExit and GeneratorExit are never retried.
  • CircuitBreaker: success_threshold, exclude=, on_state_change and .stats (CircuitStats).
  • timeout is also a context manager (with timeout(5): / async with timeout(5):) and returns a Timeout object. python_wrap.deadline (deadline(), remaining(), check()) gives code a shared time budget, and timeout clamps 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 gains start(), stop(), running, runs, last_error and running_in_background() for clean shutdown. Events periodic.run and periodic.failed.
  • python_wrap.aio: gather_limit, map_async and amap_iter (bounded concurrency, lazy input, ordered results; everything is cancelled and awaited on error, cancellation or early exit), race (first success wins; RaceFailed) and run_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) and BulkheadFull.
  • RateLimiter: one budget shared across functions (with, async with, acquire, try_acquire), and several windows at once with rate_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, and BatchError on contract violations.

Caching:

  • memoize(ttl=..., stale_ttl=...): stale-while-revalidate. After ttl a 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. Events cache.stale and cache.refresh_failed.
  • memoize(store=...) and the CacheStore protocol: keep entries in any store (a dict, Redis, ...); the cache_* 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 def getters, invalidate()).
  • memoize: cache_exceptions= / exception_ttl=, a per-item ttl= callable, and cache_contains(), cache_get() and cache_parameters().

Observability, configuration and testing:

  • trace(otel=True, span_name=...) wraps calls in an OpenTelemetry span (sync and async) with code.function, code.namespace and python_wrap.context.* attributes and exception recording. opentelemetry-api is 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() and EVENT_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 in log_args, log_return, audit, trace and timing messages, on LogRecord.context and on AuditRecord.context. log_args and audit accept redact_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() and reset_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 fixtures pw_fake_clock and pw_fast_mode (pytest_plugins = ["python_wrap.testing"]).
  • Typing: stacked decorators keep the exact function type (@retry over @memoize keeps .cache_info()), and Memoized, Once, CircuitProtected, Limited and Counted bind correctly under methods and @classmethod. Typing regression tests run mypy in CI.
  • A cookbook of eight recipes, seven runnable examples/, a performance page with benchmarks/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 periodic objects and wrap_methods classes, pickle by reference, so they work with multiprocessing and ProcessPoolExecutor under 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 a RetryState, unlimited attempts (max_attempts=None), and bare @retry usage.
  • fallback(value) / fallback(handler=...) and suppress(*exceptions) for failing soft.
  • CircuitBreaker (shareable across functions), the circuit_breaker decorator (breaker exposed as .breaker) and CircuitState.
  • 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=), and rate_limit(block=, key=).
  • timing(threshold=, callback=) with TimingRecord, measure_memory(callback=) with MemoryRecord, profile(sort=, limit=, callback=), and benchmark_async.
  • log_args secret redaction (redact=, DEFAULT_REDACT) and max_length=; audit now yields a structured AuditRecord with sink= and include_result=; trace(limit=). Every logging decorator accepts logger= and level=.
  • enforce_types: runtime checks from annotations (generics, unions, Literal, Annotated, NewType and more) for arguments and return values.
  • Transaction with on_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 subclassing PythonWrapError: TimeoutExpired (also a TimeoutError), RateLimitExceeded, CircuitOpenError, ValidationError (also a ValueError) and ArgumentTypeError (also a TypeError).
  • once gained .reset() and .called.
  • A py.typed marker, and a NullHandler on the python_wrap logger.

Changed

  • CircuitBreaker, RateLimiter, Bulkhead, RetryBudget, Transaction, Policy and testing.FakeClock raise a clear TypeError when 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.exception can be None (when a returned value was rejected by retry_if_result), and RetryState has a new result field. A sync function given an async retry hook raises TypeError when decorated.
  • On free-threaded Python 3.14t new threads inherit the caller's context, so log_context fields 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 wrapt and typing-extensions were unused and have been removed.
  • retry waits with asyncio.sleep for async def functions, and re-raises the final exception unchanged with its original traceback.
  • timeout raises TimeoutExpired. Async functions are cancelled with asyncio.wait_for; sync functions are interrupted with SIGALRM on the Unix main thread. The thread fallback used elsewhere cannot stop the work, and is now documented.
  • memoize and cache keys are bound to the function signature with defaults applied, so f(1), f(x=1) and f(1, y=<default>) share one entry; list, dict and set arguments are converted to hashable keys.
  • deprecate points its warning at the caller and sets __deprecated__ (PEP 702).
  • from python_wrap.decorators import ... still works through a compatibility module.
  • timeout(...) now returns a Timeout object, which is both a decorator and a context manager. Decorator use is unchanged.
  • retry never retries cancellation-type exceptions (asyncio.CancelledError, KeyboardInterrupt, SystemExit, GeneratorExit), even if on= lists them.
  • The redact= default on log_args and audit is None, which means "the configured value, or DEFAULT_REDACT". Pass redact=() to turn redaction off.
  • audit with no sink and a disabled log level builds no record at all.
  • Limited.bulkhead is a read-only property.
  • Test overrides apply only to backoff waits. fast_mode() and fake_clock() no longer shorten limits on how long to wait: async Bulkhead/limit_concurrency timeouts, race(timeout=), async hedge delays and async batch_calls/debounce windows run on real time, like their sync versions and timeout.
  • Under fast_mode(), a blocking rate limiter (block=True) that would wait lets the call through at once and still counts it.

Fixed

  • 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 as CancelledError (matching asyncio.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 that stop() never collected when start() is called again, instead of dropping it silently.

  • revert_on_failure never restored anything because its snapshot was always empty.

  • transactional was a no-op; it now commits and rolls back through a Transaction.

  • memoize and cache built keys from str(args), which collided and ignored keyword equivalence. cache() also shared a single store across all functions it decorated.

  • timing measured about zero seconds for async def functions, and now uses perf_counter.

  • measure_memory used ru_maxrss, which is Unix-only and reported the wrong units; it now uses tracemalloc.

  • The package failed to import on Windows because it imported the Unix-only resource module.

  • audit reported the wrapper's own frame as the caller.

  • once was not thread-safe, and now retries after an exception.

  • validate_args rebuilt the function signature on every call.

  • Under fast_mode() or fake_clock(), async bulkhead and race timeouts expired at once and hedge launched every backup attempt immediately.

  • A blocking RateLimiter/rate_limit(block=True) busy-spun at full CPU under fast_mode().

  • timeout's thread fallback reported a call as late when it advanced the fake clock (for example a retry inside it), and a nested signal-based timeout did not fire under fake_clock().

  • @transactional on a function with a positional-only (or *tx / **tx) tx parameter crashed at call time; it now raises TypeError when decorating.

  • singleflight's default key treated f(1, b=2) and f((1,), (("b", 2),)) as the same call, and memoize on a callable without an inspectable signature treated f(1, b=2) and f(1, 2) as the same call.

Performance

  • Async memoize and cache hits are about 30-35% faster (one lock instead of two).
  • The memoize hit path is about 9x faster.
  • validate_args, check_type, enforce_types, log_args and audit skip signature binding on plain positional calls (5x to 40x faster).
  • audit skips building a record when nobody would receive it, and timing skips formatting when its log level is disabled.
  • Numbers and a benchmark script are on the performance page.

Deprecated

  • retry_on_exception: use retry(on=...). Emits a DeprecationWarning.
  • no_debug: a no-op, to be removed in 0.3.
  • cache: soft-deprecated in the docs only (no warning yet); prefer memoize(ttl=...).

Removed

  • 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).

Infrastructure

  • 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.md and RELEASING.md.

Known limitations

  • The timeout thread fallback (Windows, non-main threads) cannot stop the running work.
  • rate_limit, throttle and debounce share state across instances when used on methods (rate_limit accepts key= to split it).
  • memoize on methods keeps instances alive; use maxsize or ttl.
  • Concurrent calls to measure_memory share one tracker, and profile on an async function includes event-loop work.
  • transactional injects tx= by keyword, so declare tx last or keyword-only.

0.1.0 - 2025-01-21

Initial release.