pytest-state-guard
A pytest plugin auditing ThreadPoolExecutor task lifetimes against fixture and test owner boundaries.
Installation & Quickstart
Install State Guard into your pytest test environment from PyPI:
pip install pytest-state-guard
Automatic Discovery
Once installed, State Guard is automatically discovered by pytest via its standard pytest11 entry point (state_guard = "pytest_state_guard.plugin"). No conftest.py edits, fixtures, or command-line flags are required.
Run your test suite normally:
pytest
Deactivating State Guard
To temporarily deactivate State Guard for a specific test run without uninstalling it:
pytest -p no:state_guard
The test passed. The work didn't stop.
Pytest evaluates assertions, executes fixture teardowns, and moves smoothly to the next test in the suite. But if a test function or fixture submitted a callable to a concurrent.futures.ThreadPoolExecutor and did not explicitly wait on Future.result() or shut down the executor with wait=True, the submitted work may remain queued or actively executing past the owner's boundary.
Depending on operating system scheduling, the submitted callable may have completed unnoticed, may still be queued waiting for a worker, or may be actively mutating process-level state while a subsequent test assumes a clean environment.
Consider an illustrative scenario: a test submits background work and exits cleanly in mere milliseconds. Several tests later, an intermittent flake occurs because an orphaned thread from that earlier test was still executing and wrote into shared memory.
pytest-state-guard identifies this lifecycle mismatch. It instruments ThreadPoolExecutor.submit to capture task provenance, records observed lifecycle transitions into an append-only event ledger with monotonic sequence numbers, and evaluates task lifetimes against owner finalization boundaries using a formal policy engine.
Usage Example
A Leaky Test
The following test submits work to a ThreadPoolExecutor and synchronizes on callable startup to confirm the worker has begun executing before the test call completes:
import threading
from concurrent.futures import ThreadPoolExecutor
started = threading.Event()
stop_event = threading.Event()
def background_work():
started.set()
stop_event.wait(timeout=2.0)
def test_background_worker():
executor = ThreadPoolExecutor(max_workers=1)
executor.submit(background_work)
# Synchronize: confirm the worker callable has started execution
assert started.wait(timeout=1.0)
# Test assertions pass, but the worker is still running across teardown:
assert True
(Note: The synchronization event confirms callable startup. The bounded wait keeps the callable active long enough to demonstrate the intended lifecycle violation under the observed execution; arbitrary operating system scheduling can still affect the outcome. This example deliberately demonstrates an unjoined background worker to illustrate State Guard's detection; unjoined background execution is an anti-pattern for production test suites.)
Representative Terminal Output
Running pytest against this test demonstrates how State Guard surfaces the boundary violation during test teardown without masking call-phase assertions:
============================= test session starts =============================
platform ... -- Python 3.x, pytest-9.x, pluggy-1.x
plugins: state-guard-0.1.1
collected 1 item
test_demo.py::test_background_worker PASSED [100%]
test_demo.py::test_background_worker ERROR [100%]
=================================== ERRORS ====================================
_________________ ERROR at teardown of test_background_worker _________________
- State Guard Teardown Violation: TEST_CALL [test_demo.py::test_background_worker] -
Owner ID: owner:test:test_demo.py::test_background_worker:<owner_uuid>
Owner Finalized Sequence: 7 (created at seq 2)
* Finding: finding:owner:test:test_demo.py::test_background_worker:<owner_uuid>:task:<task_uuid>
Classification: CALLABLE_NOT_EXITED
Task ID: task:<task_uuid>
Evidence: Task 'task:<task_uuid>' callable began execution at seq 4 before finalization, but has not committed an exit event.
Sequences: 3, 4, 7
=================== State Guard Audit: VIOLATIONS DETECTED ====================
Owner: TEST_CALL [test_demo.py::test_background_worker]
- [CALLABLE_NOT_EXITED] Task 'task:<task_uuid>': Task 'task:<task_uuid>' callable began execution at seq 4 before finalization, but has not committed an exit event.
Sequences: 3, 4, 7
=========================== short test summary info ===========================
ERROR test_demo.py::test_background_worker
========================= 1 passed, 1 error in 0.80s ==========================
The Fix
To ensure clean teardown, wrap executor usage in a context manager or explicitly wait for submitted futures within the owner scope:
def test_background_worker_fixed():
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(lambda: 42)
assert future.result() == 42
# The context manager exit automatically invokes executor.shutdown(wait=True),
# waiting for submitted callables to finish executing before the test owner finalization boundary.
# (Note: shutdown(wait=True) waits for work to complete; it does not forcibly cancel or terminate running threads.)
What It Does — and What It Does Not Do
What State Guard Does
- Instruments Task Submission: Intercepts
ThreadPoolExecutor.submitdynamically during the pytest session to bind task provenance to the active owner context. - Enforces Monotonic Ordering: Commits every observed, tracked submission, start, exit, and finalization event to a thread-safe, append-only in-memory ledger.
- Classifies Against Boundaries: Evaluates whether submitted callables completed before their submitter was finalized, remained outstanding, or started execution after owner teardown.
- Surfaces Failures Without Masking: Reports violations in test teardowns (
=== ERRORS ===) and the session summary without overwriting original call assertions (=== FAILURES ===) or swallowing upstream exceptions.
What State Guard Deliberately Does Not Do
- It does not terminate threads: State Guard is an auditor, not an execution sandbox. It will not forcibly kill threads, cancel running callables, or shut down executors.
- It does not isolate memory or prevent races: It does not intercept memory writes or prevent data races in shared state. It does not detect every concurrency defect.
- It does not instrument other concurrency primitives: Raw
threading.Thread,multiprocessing,asyncioloops, and third-party thread pools are out of scope. - Physical scheduling is non-deterministic; auditing is not: State Guard does not claim that physical thread scheduling is deterministic. It guarantees that ledger event commitment, boundary snapshots, and policy classifications are strictly deterministic for any observed event sequence.
Task Provenance: The Submitter Owns the Task
In concurrent systems, an executor is merely an execution mechanism—often a shared, long-lived resource configured across multiple tests or fixtures. The entity responsible for the existence and lifetime of a task is the submitter.
State Guard establishes ownership through two primary scopes:
- Test Call Owners: Bound to the test item during its
pytest_runtest_callphase and finalized by thepytest_runtest_teardownhookwrapper after teardown processing (including fixture teardown finalizers). - Fixture Owners: Bound to fixture invocations during
pytest_fixture_setupacross all fixture scopes (function,class,module,package, andsession), and finalized throughpytest_fixture_post_finalizerafter that fixture's teardown logic has completed. State Guard does not track arbitrary teardown code beyond this hook-defined boundary.
Ownership is propagated via context-local storage (contextvars.ContextVar). When a test or fixture calls executor.submit(fn, *args, **kwargs), State Guard captures the active owner ID, issues a UUID for the task, and commits a submission reservation event before delegating to the real executor.
The Event Ledger & Committed Ordering
Physical time is unreliable for concurrent auditing. State Guard relies on monotonic event sequence IDs assigned under an atomic lock. All sequence identifiers ($S_*$) represent committed ledger sequence numbers, not physical timestamps or hardware clock readings. State Guard establishes the deterministic order in which observations were committed, not the exact physical instants a thread started or completed.
The ledger records the lifecycle evidence State Guard observes:
- Owner Finalization Boundary ($S_F$): The sequence ID committed at the owner's teardown boundary (in
pytest_runtest_teardownfor test items, orpytest_fixture_post_finalizerfor fixtures). - Submission Window ($S_{inv} \to S_{ret}$ / $S_{raise}$): $S_{inv}$ is the submission-reservation sequence ID committed before delegating to the real executor; $S_{ret}$ or $S_{raise}$ is committed when
submit()returns aFutureor raises an exception. - Callable Lifecycle ($S_{start} \to S_{exit}$): Committed when the wrapper begins executing the user callable and when it exits (by return or exception).
- Future Observations ($S_{done}$ / $S_{cancel}$): Committed when done-callbacks or cancellation were observed (noting that callback observation is not the exact physical settlement instant).
Policy evaluation compares observed evidence against the committed finalization boundary $S_F$.
Policy Classifications & Severity
Every task tracked by State Guard is classified according to its committed sequence history:
| Classification | Severity | Semantic Description |
|---|---|---|
NO_OUTSTANDING_TASKS |
CLEAN |
No task remains outstanding at the owner finalization boundary (tasks may have completed or been cancelled prior to finalization). |
COMPLETED_BEFORE_FINALIZATION |
CLEAN |
Callable started and exited before owner finalization ($S_{exit} < S_F$). |
CANCELLED_BEFORE_START |
CLEAN |
Future cancellation committed before finalization and before callable started. |
OUTSTANDING_TASK |
VIOLATION |
Submission returned before finalization, but callable never started ($S_{ret} < S_F$). |
CALLABLE_NOT_EXITED |
VIOLATION |
Callable started before finalization but did not exit before finalization. |
EXECUTION_AFTER_OWNER_FINALIZATION |
VIOLATION |
Callable began execution after owner finalization ($S_{start} > S_F$). |
EXIT_COMMITTED_AFTER_FINALIZATION |
VIOLATION |
Callable started before finalization but exited after finalization ($S_{exit} > S_F$). |
POST_LIFETIME_SUBMISSION |
VIOLATION |
Task submitted after owner was already finalized ($S_{inv} > S_F$). |
SUBMISSION_UNRESOLVED |
UNCERTAIN |
submit() did not return or raise before finalization. |
SUBMISSION_FAILED_UNVERIFIED |
UNCERTAIN |
submit() raised before finalization; work item enqueue state unverified. |
Preserving Boundary Evidence
- Uncertainty is Advisory: Submissions that were in flight when an owner finalized remain
SUBMISSION_UNRESOLVEDeven ifsubmit()subsequently returns. Uncertain findings are advisory: they are rendered in an advisory section of the terminal summary and do not automatically cause test failures. - Finding Identity Stability: If an unresolved task subsequently begins execution after finalization, its classification evolves to
EXECUTION_AFTER_OWNER_FINALIZATIONwhile retaining its stable finding identifier.
Reporting Architecture
1. Per-Test Teardown Errors
Findings originating from test functions or function-scoped fixtures are attributed directly to that test item:
- Test Passed: Marked failed in teardown, appearing under
=== ERRORS ===asERROR at teardown of <nodeid>. - Test Failed: If the test call itself failed (for example, an assertion failure), the call failure remains visible under
=== FAILURES ===with its complete traceback, while concurrency violations appear under=== ERRORS ===. - Teardown Already Failed: If the test teardown already failed (for example, an exception in a fixture finalizer), State Guard preserves the original teardown error representation and chains its violation details using a chained terminal representation (
ChainedTerminalRepr) without overwriting the fixture error.
2. Session Audit Summary
Class, module, package, and session-scoped fixtures cannot be attributed to an arbitrary single test. Their findings are audited at session finish and rendered in the terminal summary by pytest_terminal_summary.
3. Exit Code Promotion
If all test assertions passed but State Guard detected concurrency violations, the session exit code is promoted to pytest.ExitCode.TESTS_FAILED (1). Pre-existing nonzero exit codes (such as assertion failures or interrupts) are preserved.
Compatibility & Verification
- Python Requirements:
>= 3.11- Verified Matrix Environments: Python 3.11, Python 3.12, Python 3.13, and Python 3.14 across Ubuntu (Linux), Windows, and macOS (verified in CI Run 44079270152)
- Pytest Requirements:
>= 9.1.1(direct runtime dependency)- Verified Environments: pytest 9.1.1, pytest 9.2.0
- Pluggy Requirements:
>= 1.5.0(transitive dependency via pytest)- Verified Environments: pluggy 1.5.0, pluggy 1.6.0, pluggy 1.7.0
Scope & Limitations
- ThreadPoolExecutor Exclusivity: Only
concurrent.futures.ThreadPoolExecutoris instrumented. Custom worker implementations relying onthreading.Threaddirectly are uninstrumented. - Process Boundaries: Each pytest process maintains its own independent in-memory ledger. Cross-process ledger aggregation and distributed ownership correlation (such as across
pytest-xdistworker processes) are not provided. - Audit, Not Intervention: State Guard reports concurrency boundary violations; it does not alter thread execution, terminate running threads, or enforce shutdown.
Development & Test Suite
To run the complete test suite across adversarial, unit, and lifecycle integration tests from a local checkout:
PowerShell:
$env:PYTHONPATH = "src"
pytest
Command Prompt:
set PYTHONPATH=src
pytest
To build a standalone distribution wheel:
python -m build
License
This project is licensed under the MIT License.
Copyright (c) 2026 bitbyrizbit
Metadata
Release files for pytest-state-guard 0.1.1
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 |
|---|---|---|---|---|
| pytest_state_guard-0.1.1.tar.gz | 31.1 kB | With provenance | Details for pytest_state_guard-0.1.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pytest_state_guard-0.1.1-py3-none-any.whl | Python 3 | none | any | Details for pytest_state_guard-0.1.1-py3-none-any.whl |
Total release size: 60.3 kB
Release files / pytest_state_guard-0.1.1.tar.gz
| Download URL | pytest_state_guard-0.1.1.tar.gz |
|---|---|
| Size | 31.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
73a88d71069c949145b941e0d3365d95852c51d0e2b9165e5b4e77881b8221cd
|
|
BLAKE2b-256 checksum How to use checksums |
1d0ffd6fde6ab92af183601b0bf5047f71b54d2a829693d1383941330012a073
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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 18, 2026.
Transparency logRelease files / pytest_state_guard-0.1.1-py3-none-any.whl
| Download URL | pytest_state_guard-0.1.1-py3-none-any.whl |
|---|---|
| Size | 29.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e442cd098008a41aa8253e74a98f42289628a7b9e39204c0b6c20a5bd5e03f40
|
|
BLAKE2b-256 checksum How to use checksums |
254dbe807e84fb176d5ff9b62d294a21a45fbe828a273d382360afad547c6103
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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 18, 2026.
Transparency logSecurity for pytest-state-guard 0.1.1
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 pytest_state_guard-0.1.1.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 18, 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.