CancelLens
CancelLens tests what happens when an asyncio operation is cancelled while suspended.
It observes real suspension points, repeats the operation on fresh state, and sends
real Task.cancel() requests by default. An explicit AnyIO mode sends a real
CancelScope.cancel() request. Your oracle checks resource release, state consistency,
and whether the same pool or resource can serve another operation.
Use it in ordinary pytest tests with native Python coroutines and real I/O. A passing sweep confirms the evaluated schedules and your invariants; it does not prove general cancellation safety or cover every possible task interleaving.
Installation
python -m pip install cancellens
The base installation uses only the standard library. No pytest plugin or pytest-asyncio is required. For AnyIO scope cancellation, install the optional extra:
python -m pip install 'cancellens[anyio]'
The extra accepts AnyIO 4 (>=4,<5); it is not imported by the default asyncio mode.
For a source checkout, see Contributing.
Quick start
Save this test as test_pool.py in a pytest project:
import asyncio
from cancellens import Case, Completion, require, sweep
def test_pool_survives_cancellation():
async def factory():
return asyncio.Semaphore(1)
async def operation(pool):
await pool.acquire()
try:
await asyncio.sleep(0)
finally:
pool.release()
async def oracle(pool, completion: Completion):
require(completion.state in ("returned", "cancelled"), "operation terminated")
require(not pool.locked(), "pool slot returned")
await pool.acquire() # Check reuse of the SAME resource.
pool.release()
async def teardown(pool):
if pool.locked():
pool.release()
asyncio.run(sweep(Case(factory, operation, oracle, teardown))).assert_passed()
Run it with python -m pytest -q test_pool.py.
Moving pool.release() from finally to the happy path makes cancellation lose the
slot. The oracle reports FAIL before teardown repairs it. The pool example
contains both implementations.
Define a case
Each attempt creates fresh state through four async callbacks:
factory()creates and returns state. It must clean up incomplete setup if it fails.operation(state)returns a native Python coroutine and runs in a real Task.oracle(state, completion)checks state before harness cleanup. It can await application-owned cleanup and exercise the same resource again.teardown(state)releases the attempt's resources, including after a failed oracle.
Use require(condition, "invariant name") or raise InvariantViolation to report a
contract failure. Other oracle exceptions, including AssertionError, mean the check
could not be evaluated correctly. Use static, non-sensitive invariant text because
it is included in reports.
Completion.state is returned, cancelled, raised, pending, not_started, or
scope_cancelled. The last state means the operation was interrupted and the
harness-owned AnyIO scope suppressed its cancellation exception; the operation Task
returned normally. A normal Task exit does not establish that no cancellation occurred.
The operation's value and exception are available to the oracle in memory when they
exist. Your oracle judges their meaning, including whether suppression is acceptable.
Explore cancellation schedules
sweep(case) runs two uncancelled baselines and compares their traces. It then cancels
at each baseline suspension point. By default it also tests a second cancellation at
later points discovered on each valid single-cancel path, including cleanup paths
that never ran in the baseline.
Requests are sent only after the required trace prefix matches. A second request requires confirmed delivery of the first. CancelLens adds no awaits to the operation and does not select cancellation targets with random delays.
- PASS: the report's schedules were evaluated and satisfied the oracle.
- FAIL: an attributable schedule violated an explicit invariant.
- UNRESOLVED: a target or delivery could not be confirmed, replay diverged, a budget cut coverage short, or the operation had no suspension points.
- ERROR: setup, instrumentation, oracle code, or infrastructure failed.
Each attempt records its schedule, trace, cancellation acceptance and delivery, operation completion, oracle, and teardown. A confirmed FAIL or ERROR remains visible if cleanup also fails. An oracle violation on an invalid schedule is recorded without being classified as an established cancellation bug.
report.coverage describes planned and valid schedules, baseline points, attempt
count, completeness, and reasons for incomplete coverage. Incomplete coverage cannot
produce PASS. report.assert_passed() raises an assertion with the schedule and coverage.
from cancellens import Limits
limits = Limits(
max_points=100,
max_attempts=100, # Includes both baselines.
max_depth=2, # Use 1 for single cancellation only.
phase_timeout=2.0,
total_timeout=30.0,
cleanup_timeout=0.1,
)
Pass limits with await sweep(case, limits=limits) or await replay(case, schedule, limits=limits).
AnyIO scope cancellation
report = await sweep(case, cancellation_mode="anyio", backend="asyncio")
This mode supports AnyIO 4 on the standard asyncio backend, CPython, and default Task
factory. It runs the same two uncancelled baselines, then one scope cancellation at
each matched baseline point. It does not schedule double cancellations, even with
Limits(max_depth=2). One request can cause repeated cancellation exceptions while
the scope remains effectively cancelled, including at awaits in cleanup. These are
repeated deliveries from AnyIO, not additional requests from CancelLens.
The harness creates, enters, and exits one scope in the operation Task. It adds no
awaits to the operation and keeps its Task identity. Oracle and teardown run outside
that scope in their own Tasks and budgets. An awaited cleanup normally needs a real,
bounded shield, for example with anyio.fail_after(0.1, shield=True): ....
The synthetic examples compare resource reuse and terminal
callback events with and without shielding under both cancellation modes.
Reports distinguish reaching a target, matching its prefix, calling the scope's
cancel(), observing a cancellation exception, scope suppression, and operation
completion. Confirmed delivery requires both an observed cancellation exception and
public scope.cancelled_caught evidence from the owned scope. cancel_called alone
is insufficient. User suppression, child Tasks, or shielding can leave attribution
unknown, so the attempt remains UNRESOLVED with a concrete reason even if its oracle
records a violation. No exception message, address, or private AnyIO state establishes
attribution.
Trio, child-Task sweeps, multiple harness-controlled scopes, AnyIO double-cancel scheduling, and full coverage of AnyIO APIs are outside this mode's scope. Application scopes and shielding may defer or prevent delivery at the requested target; a matched point is not a guarantee of a cancellation exception at that exact await.
Save reports and replay a schedule
Inside an async test, with a case already defined:
import json
from cancellens import Schedule, replay, sweep
report = await sweep(case)
saved = json.loads(report.to_json())
schedule_data = next(a["schedule"] for a in saved["attempts"] if a["schedule"]["cancel_at"])
replayed = await replay(case, Schedule.from_dict(schedule_data))
replayed.assert_passed()
A schedule contains one-based targets, the required trace prefix, cancellation mode,
backend, and AnyIO version when applicable. Replay infers the mode from the schedule;
an explicit cancellation_mode must agree. It checks Python minor and exact AnyIO
version compatibility before running the factory, then checks visible frame locations,
bytecode offsets, code fingerprints, and yielded types before cancellation. Changed
code or scheduling may make replay unresolved. Replay covers only the selected
schedule. An empty schedule is an uncancelled control.
New reports and schedules use schema version 2. A version 2 schedule must explicitly
include cancellation_mode, backend, and anyio_version (null for asyncio mode).
Existing version 1 reports remain ordinary JSON; extracting their schedules with
Schedule.from_dict() preserves Task.cancel() semantics. Legacy schedules are never
reinterpreted as scope cancellation.
Reports omit locals, object reprs, absolute paths, SQL, response bodies, operation values, and exception messages. They retain code metadata, exception types, and explicit invariant text. See the instrumentation and report reference.
Supported environments
CancelLens v0.1 supports CPython 3.10–3.15, the standard asyncio event loop, and the default Task factory. CI tests Linux and Windows across those versions. macOS is also used for local validation. Python 3.16+, PyPy, uvloop, free-threaded builds, custom or eager factories, and Trio are outside this scope. AnyIO scope cancellation is available only through the explicitly selected mode above.
Observation follows nested Python awaits. Child Tasks and shielded work are boundaries: only the caller's wait is visible, and cleanup may outlive the caller. The oracle must check or explicitly await that work. On CPython 3.10, a cancelled child Task can lose the request marker; uncertain delivery is UNRESOLVED. Child suppression or replacement of the marker can also prevent attribution on later versions.
C awaitables can hide deeper source frames. Exact source attribution is not guaranteed
for every extension awaitable. Wrapper frames and Task.get_coro() identity are not
preserved. Lifecycle phases run in separate Tasks, so pass setup configuration through
case state rather than relying on factory changes to ContextVars.
Deadlines and resource ownership
In-process deadlines require a functioning event loop. They cannot stop blocked native code, a cancellation-resistant coroutine, or a running thread. After an operation deadline, the oracle observes state before teardown and emergency cancellation. Reserved oracle, teardown, and drain windows can extend the exploration deadline.
Cases own their application Tasks, threads, and external resources. Caller cancellation
propagates after attempted bounded finalization. In AnyIO mode, the runner shields
its final oracle/teardown wait windows and drain from an external cancelled caller
scope, then checks for deferred caller cancellation before another attempt or return.
These lifecycle shields are not scheduled cancellation targets. Repeated direct
Task.cancel() requests can still interrupt finalization; default asyncio mode retains
its existing behavior. CancelLens cannot roll back arbitrary external side effects.
For potentially hanging tests in a checkout, use the validation watchdog:
uv run --no-sync python validation/watchdog.py --timeout 90 -- uv run --no-sync pytest -q
On POSIX it terminates the owned process group and kills remaining members. Nested validation workers inherit that group, so a whole-run deadline includes them. On Windows it can terminate only the immediate child. See Validation for commands, evidence, and supervision details.
Validated integrations
These cases use real resources and inspect them before final cleanup:
- aiosqlite cancelled opening: a native SQLite connection and worker thread expose a lost connection during opening. The pinned base fails; the selected proposed patch passes the opening contract.
- LangChain terminal callbacks: an unchanged pinned upstream revision uses a local tool and async callback handler. Scope cancellation interrupts the terminal event; a separately labeled local shielded control records it. This validates the callback mechanism related to #41744, not every part of the reported application failure.
- HTTPX/httpcore double cancellation: loopback TCP and a one-slot HTTP/1.1 pool expose interrupted response cleanup. The pinned base loses the slot; the selected proposed patch allows cleanup to retry and the next request to succeed. An additional single-cancel close failure is retained on both snapshots.
Each case publishes immutable commits, schedules, controls, and resource observations. These are bounded integration results, not general safety claims about either library.
Documentation
- Contributing: development setup, checks, CI, and releases.
- Instrumentation and report reference: observation, attribution, lifecycle ownership, and JSON schema.
- Validation: reproducible external cases and evidence.
- Changelog: released changes and unreleased project updates.
Community and support
Use the issue forms for bug reports, feature requests, and usage questions. Include a minimal case and relevant versions when reporting unexpected behavior.
Read Contributing before submitting changes. Participation follows the Code of Conduct. Report vulnerabilities privately using the security policy.
Related work
- SQLAlchemy cancellation testing uses greenlet-aware sweeps and connection/pool accounting for async dialects.
- Pyleak detects task, thread, and loop-blocking leaks.
- Aiotools cancellation utilities provide application cancellation and waiting helpers.
- Simloom explores asyncio programs with a simulated scheduler.
CancelLens uses its own coroutine-protocol instrumentation, the standard loop, real I/O, and user-defined resource oracles. No code from these projects is incorporated.
Metadata
Release files for cancellens 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| cancellens-0.2.0.tar.gz | 232.0 kB | With provenance | Details for cancellens-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| cancellens-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for cancellens-0.2.0-py3-none-any.whl |
Total release size: 254.9 kB
Release files / cancellens-0.2.0.tar.gz
| Download URL | cancellens-0.2.0.tar.gz |
|---|---|
| Size | 232.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
bad6a8410b3c6e641b33458492e9301bf10f5428b8aef1d006859547b66143bc
|
|
BLAKE2b-256 checksum How to use checksums |
d74f24e5da6284ba42ea154cd52ed27ee021eddaffc51948d9cac81a22a50d9d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.
Transparency logRelease files / cancellens-0.2.0-py3-none-any.whl
| Download URL | cancellens-0.2.0-py3-none-any.whl |
|---|---|
| Size | 22.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b155ef7551caeb1a217058da3d5359c3cf2cb421489f62322b97c537d83eedab
|
|
BLAKE2b-256 checksum How to use checksums |
33f1c607782fa7367988cbe67d6cb4239e18511d1cf9e2ffe55efee6da65bbb7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.
Transparency logSecurity for cancellens 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for cancellens-0.2.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.