Skip to main content

ConcurrencyGuard

Find race conditions and deadlocks in Python.

PyPI CI MIT License

Quick start · What it catches · CI and reports · Interactive examples

ConcurrencyGuard terminal demo

ConcurrencyGuard (cguard) scans Python code for concurrency bugs that can be hard to spot in review. It reports the file, line, and rule ID, and suggests what to change. The static scan reads your source without running it.

Quick start

python -m pip install concurrency-guard
cguard scan .

Scan a single file by passing its path instead of .. To see what an available automatic fix would change, run cguard fix . --diff. Apply the changes with cguard fix . --write.

ConcurrencyGuard supports Python 3.9 and newer. Run cguard --version to check which release your terminal is using. Run cguard explain CG-031 to see why sharing one database session across concurrent tasks can fail and how to use a separate session per task.

In 4.2.0, CG-031 shows where the session came from and which two tasks share it. JSON and HTML reports, editor diagnostics, and SARIF exports carry those locations in order. Use cguard scan . --diff-base origin/main in CI to check changed files and their callers with unchanged helpers available for analysis.

Example

Two requests can read the same wallet balance, each subtract an amount, and then overwrite each other’s update:

async def withdraw(session, wallet_id, amount):
    wallet = await session.get(Wallet, wallet_id)
    wallet.balance -= amount
    await session.commit()

cguard scan reports CG-001 at the database read. Depending on the database and transaction, a row lock or an atomic SQL update can protect the operation.

What it catches

Area Example findings
Database writes Missing row locks, incomplete locking across branches, and check-then-insert races
Deadlocks Functions in different files acquire the same locks in opposite orders
Async Python Shared state changes across an await, blocking calls in coroutines, and orphaned tasks
Redis and background jobs Non-atomic check-then-set operations, unsafe lock release, and retry or transaction hazards

The scanner includes checks for SQLAlchemy, SQLModel, Django ORM, Tortoise ORM, asyncio, Redis, and Celery.

New in 3.9.0: CG-028 finds branch paths that can mutate and commit without the lock held on another path. CG-029 traces cross-file lock-order cycles to their acquisition sites. CG-030 detects when a coroutine reads shared module or class state, awaits, and then writes to it without continuous lock protection.

cguard scan . --select CG-028,CG-029,CG-030

CG-031 requires evidence that a shared value is an AsyncSession, such as a type annotation or a recognized session factory. Untyped parameters named db or session alone do not trigger the rule.

Keep tasks inside the session scope

CG-034 flags a task that can keep using an async database session after its context exits. Keep the task group inside the session scope so it joins before the session closes, or open a separate session inside the task.

async with session_factory() as db:
    async with asyncio.TaskGroup() as group:
        group.create_task(load(db))

Run cguard explain CG-034 for a paired example and remediation guidance.

CI and reports

# Export findings for GitHub Code Scanning
cguard scan . --format sarif --output cguard.sarif

# Open an HTML audit report in your browser
cguard report . --format html --output cguard-report.html

The scan exits with status 1 when it reports findings. For a GitHub Actions setup, see the example Code Scanning workflow. To scan only files changed against a Git base branch, use cguard scan . --base-ref origin/main.

Version 3.9.1 improves self-scan accuracy. Deadlock checks resolve local functions and methods by their receiver and class. Redis checks distinguish Redis operations from generic file-cache calls and match the receiver and key.

When scanning this repository, examples/ and tests/ include intentional unsafe code used to demonstrate and verify findings. Run cguard scan src/ to audit the scanner implementation.

Version 3.9.2 recognizes simple repeated database status assignments in retryable tasks and keeps retry warnings when acks_late=True is the only safeguard. Arithmetic writes, inserts, state-dependent transitions, and unknown side-effect calls retain their diagnostics.

More commands

Command When to use it
cguard verify --help Run a concurrency stress test against supported targets
cguard simulate --help Explore a possible execution order behind a finding
cguard baseline --help Track existing findings so CI can focus on new ones
cguard watch --help Rescan while you edit
cguard lsp --help Set up editor diagnostics

Run cguard --help for the full command list.

Contributing

python -m pip install -e ".[dev]"
pytest
ruff check .
mypy --strict .

Browse the example projects, open an issue, or review the release history on PyPI.

Async checks in v4.0.0

Rule What to review CWE
CG-031 Multiple coroutines in asyncio.gather or a TaskGroup use one async database session. Give each task its own session. CWE-362
CG-032 An async lock is acquired again inside its own context, directly or by an awaited helper. CWE-833
CG-033 A bare or BaseException handler can swallow cancellation. Re-raise asyncio.CancelledError before the broad handler. CWE-662

Preview the cancellation fix with cguard fix . --rule CG-033 --diff.

Scan changes and their callers

Run cguard scan . --diff-base origin/main to check committed Python changes since the merge base and the files that transitively import them. Fetch the base ref in CI before scanning. The scanner builds the import graph before running rules on the selected files.

Add a local rule

Declare workspace-relative Python files in pyproject.toml.

[tool.cguard]
plugins = ["rules/my_rule.py"]

Export a PLUGIN instance implementing CGuardRulePlugin from cguard.plugins. Provide a unique uppercase rule_id, a severity of HIGH, MEDIUM, or LOW, a cwe such as CWE-362, and a check(module) method returning ASTFinding values with the same rule ID. The ParsedModule gives the rule the file path, source text, and parsed AST.

Run cguard scan . --allow-plugins for projects whose Python plugins you trust. Plugins run as Python code with the scanner process's permissions.

Metadata

Release files for concurrency-guard 4.3.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for concurrency-guard 4.3.2
File Size Uploaded Provenance Actions
concurrency_guard-4.3.2.tar.gz 219.2 kB Without provenance Details for concurrency_guard-4.3.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for concurrency-guard 4.3.2
File Interpreter ABI Platform Actions
concurrency_guard-4.3.2-py3-none-any.whl Python 3 none any Details for concurrency_guard-4.3.2-py3-none-any.whl

Total release size: 395.1 kB

Release files / concurrency_guard-4.3.2.tar.gz

Download URL concurrency_guard-4.3.2.tar.gz
Size 219.2 kB
Tags Source
SHA-256 checksum
How to use checksums
2503adad28b770a4be37c506d35fb5afe20dd944db1452279d7abd0210c76364
BLAKE2b-256 checksum
How to use checksums
825f7b6f4f126a2afed23fab031b29b2024f36fde15c0575a656c69c17daa4c6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.8

Release files / concurrency_guard-4.3.2-py3-none-any.whl

Download URL concurrency_guard-4.3.2-py3-none-any.whl
Size 175.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
74da93b83ff6a22c33eca3545705a1b6be8e606e3b418d00871b0795b1fce22a
BLAKE2b-256 checksum
How to use checksums
43142ffd5f0a4b213004013d8e9ba1618c8c6a56e5853d67f76249d0d8293290
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.8

Security for concurrency-guard 4.3.2

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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

Release history Release notifications | RSS feed

This release

4.3.2 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page