Skip to content

Add AsyncioRuleBasedStateMachine for async stateful tests - #4953

Open
gjreddy wants to merge 3 commits into
HypothesisWorks:masterfrom
gjreddy:feat-4107-asyncio-stateful
Open

gjreddy wants to merge 3 commits into
HypothesisWorks:masterfrom
gjreddy:feat-4107-asyncio-stateful

Conversation

@gjreddy

@gjreddy gjreddy commented Oct 28, 2026

Copy link
Copy Markdown

Part of #4107. This is the asyncio-first step suggested in the review of #4147. It runs each async method to completion, so rules never run concurrently, and it doesn't import trio or anyio.

The problem today

An async def rule on a RuleBasedStateMachine returns a coroutine that is never awaited. Its body never runs, and the test can pass:

class Machine(RuleBasedStateMachine):
    things = Bundle("things")

    @rule(target=things)
    async def make(self):
        ...  # never runs

    @rule(t=things)
    def use(self, t):
        ...  # receives coroutine objects

On master, run_state_machine_as_test(Machine) passes. make runs 0 times, and use gets coroutines. The only symptom is a RuntimeWarning about the coroutine never being awaited. Without a target bundle, the coroutine instead trips the return_value health check, whose message doesn't mention async.

What this adds

class Machine(AsyncioRuleBasedStateMachine):
    @initialize()
    async def connect(self):
        self.client = await open_client()

    @rule(key=st.text(), value=st.integers())
    async def put(self, key, value):
        await self.client.put(key, value)

    @invariant()
    async def consistent(self):
        assert await self.client.check()

    async def teardown(self):
        await self.client.close()
  • One event loop per test case. The machine creates an asyncio.Runner, which is the stdlib way to run several coroutines on one loop. Hypothesis requires Python 3.11+, so it is always available. Each async rule, initialize rule, invariant and teardown runs with runner.run(...) and finishes before the next step starts. Objects bound to the loop survive from one rule to the next: connections, asyncio.Queues, and context variables (the runner keeps one context for the whole test case). Covered in test_runs_async_and_sync_methods_on_one_loop_per_test_case.
  • Clean-up. runner.close() runs after teardown, even when a rule failed. It cancels tasks still pending and closes the loop, so nothing carries over into the next test case. Covered in test_closes_the_loop_and_cancels_leftover_tasks_when_a_rule_fails.
  • Sync methods are still called directly, so they can be mixed in.
  • Shrinking and reporting are unchanged. The failing steps print as before (test_reports_the_failing_async_steps).
  • RuleBasedStateMachine now rejects async methods with an InvalidDefinition that names the method and points to the new class. The check runs once per class, in setup_state(). Covered for rules, initialize rules, invariants and teardown.

Design notes and open questions

  • Hook. Rules, invariants and teardown now go through a private _call(function, *args, **kwargs) method, and _close() runs after teardown. These are the only extension points, and both are private. A trio or anyio machine later needs only those two methods. I kept them private until we agree on the shape. Support async methods in stateful testing #4107 mentions an __execute_fn hook, and I'm happy to rename it or make it public.
  • Not in this PR: trio and anyio machines; holding context managers open with @initialize(), the ⭐ idea in Support async methods in stateful testing #4107; and printing await state.rule() in the reported steps. I would rather do each in a follow-up, once this shape is agreed.
  • Already inside an event loop. Calling run_state_machine_as_test inside a running loop, for example from an async def pytest test, raises asyncio's own error (Runner.run() cannot be called from a running event loop). That seems right to me, since the machine owns its loop.

Tests

The new tests are in tests/cover/test_asyncio_stateful.py, as suggested on #4147. tests/cover/test_stateful.py and every other test file that defines a state machine pass unchanged (307 tests). shed, ruff and mypy are clean on the changed files.

AI assistance

Per CONTRIBUTING.rst, I'm marking this as AI-assisted. I wrote the code, tests and this description with an AI coding assistant (Claude). I've read all of it, run the tests, and take responsibility for the change.

Rules, initialize rules, invariants and teardown of the new class may be
async def functions. Each test case runs them on its own asyncio.Runner,
one method at a time, so loop-bound objects created in one rule can be used
in later rules; the runner is closed after teardown, which cancels leftover
tasks.

RuleBasedStateMachine now rejects async methods with InvalidDefinition:
they used to return an unawaited coroutine, so the body never ran and the
test could pass without checking anything.
Pyodide always has a running event loop, so asyncio.Runner cannot start
one there, matching the existing asyncio.run tests that are skipped on
emscripten. InvalidDefinition is not in the API reference, so the
release note no longer links to it.
@gjreddy

gjreddy commented Nov 9, 2026

Copy link
Copy Markdown
Author

Friendly ping: this is ready for review and CI is green. I am happy to change the API shape, or to split the PR up, if that would make it easier to review.

@gjreddy

gjreddy commented Nov 16, 2026

Copy link
Copy Markdown
Author

Gentle ping: this still merges cleanly and CI is green. I'm happy to adjust the API or split the PR up if that would make review easier.

@Zac-HD

Zac-HD commented Nov 17, 2026

Copy link
Copy Markdown
Member

Apologies for the delay here, but the combination of stateful testing and async code is hideously complicated, so it may well be a while before I have the time and headspace to review it carefully enough to merge.

(see e.g. PEP-789 for an example of how complicated this can get; finishing that is also higher priority for me!)

@gjreddy

gjreddy commented Nov 17, 2026

Copy link
Copy Markdown
Author

Thanks for letting me know, @Zac-HD, and no worries: that makes sense. I'll stop pinging and leave it with you. When you do get to it, I'm happy to change the design or split it up if that makes it easier to review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants