PYTHON CONCURRENCY SECURITY / v3.2.0

Find the race.
Prove the impact.
Patch it precisely.

cguard is a deterministic, offline semantic SAST for Python. It traces concurrency hazards across FastAPI, Django ORM, SQLAlchemy 2.0, SQLModel, Tortoise ORM, Celery, Redis / Memcached, asyncio.TaskGroup, anyio, and threading—stresses the invariant, and offers source-preserving repairs.

Explore on GitHub
21 semantic rules0 external APIsPython 3.10+ runtime (analyzes 3.9–3.13)
LIVE INVARIANT TRACEONLINE
ILLUSTRATIVE SIMULATION / CG-016× RACE PATH
wallet.balance100starting balance
Request Athr-17
get() → 100
Request Bthr-18
get() → 100
01 / 03

Both requests read the same balance.

DETECTsemantic call paths
PROVEbarrier-synchronized workers
PATCHLibCST-preserved source
AUTOMATECI, SARIF, pre-commit
01 / DETECT

The bug, line by line.

cguard follows the read, the check, and the write — even when they are separated by application code.

CONFIDENCE SCORING--confidence highFilters low-noise deterministic hazards
INLINE PRAGMA# cguard: ignore[CG-001]Rule-scoped pragma suppression
CG-016 / VULNERABLE
race window
01def deduct(user_id, amount):02    wallet = Wallet.objects.get(id=user_id)03    if wallet.balance < amount:04        raise InsufficientFunds()05    wallet.balance -= amount06    wallet.save()
02 / TRACE

One path from finding to fix.

Every stage leaves deterministic evidence and verified artifacts you can inspect locally.

02.1

Inter-procedural call graph & summaries

Cycle-safe module-level FunctionSummary analysis (up to 3 hops) propagates query taint, parameter mutations, commit delegation, and row-lock sanitizers across helper functions.

routes.py→services/wallet.py→FunctionSummary (3 hops)
02.2

Forward taint & lexical scope isolation

Strict def-use taint verification with walrus operator (:=) and starred unpacking support. Exact span-bounded lock sanitization is isolated within lexical scope boundaries (_walk_local_nodes).

target := query()↘ walrus ↘ starred unpackspan-bounded lock
02.3

Deterministic async interleaving & chaos suites

cguard simulate extracts AST timeline steps (READ/CHECK → YIELD await → MUTATE → COMMIT) to simulate multi-coroutine races (--workers), and exports standalone runnable pytest suites via --export-test using asyncio.Barrier (no flaky sleep).

worker 01worker 02worker 03asyncio.Barriercguard simulate --export-test
02.4

Lossless LibCST auto-patcher & CI gates

Syntax-gated source repairs with --diff ANSI unified preview, --check non-destructive CI gates, selective -r patching, and JSON payloads verified against in-memory AST scanner gates.

# comments & layout preserved- wallet = session.exec(select(Wallet)).first()+ wallet = session.exec(select(Wallet).with_for_update()).first()
CACHE & PARALLELISM TELEMETRY / v2.9.0–v3.2.0

Content-Addressable SHA-256 Cache (.cguard_cache/) + ProcessPoolExecutor

--jobs autozero re-scans
Small Service10 files
0.18s cold0.008s warm
22x faster
Medium Backend100 files
1.42s cold0.024s warm
59x faster
Enterprise Monorepo1,000+ files
12.80s cold0.110s warm
116x faster
03 / COVERAGE

Built for the code paths tools usually miss.

Coverage is specific by design: modern Python concurrency primitives, framework semantics, and the evidence to act on a finding.

Multi-ORM support (v3.0.0)

First-class static analysis for SQLAlchemy 2.0, Django ORM, SQLModel, and Tortoise ORM with row-lock and F() expression verification.

Chaos reproducer (v3.2.0)

cguard simulate --export-test generates standalone pytest suites using asyncio.Barrier to deterministically reproduce races without flaky sleep().

Baselines & ratcheting (v3.1.0)

Line-shift-resilient .cguard-baseline.json snapshots with CI ratcheting (--baseline, --update-baseline, --fail-on-stale-baseline) for tech debt management.

Unified config engine (v2.13.0)

Hierarchical discovery for .cguard.toml > cguard.toml > pyproject.toml ([tool.cguard]) supporting select, ignore, per_file_ignores, and baseline.

Structured concurrency & deadlocks

Inter-procedural self-deadlocks, sync locks in coroutines, asyncio.TaskGroup, anyio task groups, and BackgroundTasks session leaks.

Lossless LibCST auto-repair

Syntax-gated source transforms with --diff preview, --check CI gates, selective -r patching, and 100% offline local analysis.

05 / RULE CATALOG

Every rule is inspectable.

Twenty-one named checks across ORM, runtime, filesystem, cache, and lock behavior. Filter the catalog or open a rule for its detection rationale.

RuleSurfacePatternSeverityRepair
CG-001FastAPI / SQLAlchemy / SQLModel / TortoiseUnlocked read-modify-writeCriticalAuto-fix
CG-002FastAPIMissing idempotency guardHighAuto-fix
CG-003asyncio / SQLAlchemyQuery inside async loopMediumGuidance
CG-004SQLAlchemy / SQLModelCheck-then-act uniquenessHighAuto-fix
CG-005CeleryNon-idempotent retryHighGuidance
CG-006asyncioShared-state mutationHighAuto-fix
CG-007threadingThreaded collection mutationHighAuto-fix
CG-008PythonIn-memory RMWHighGuidance
CG-009FilesystemConcurrent file writeMediumAuto-fix
CG-010FilesystemPredictable tempfileMediumGuidance
CG-011Redis / cacheCache check-then-actHighGuidance
CG-012CacheNon-atomic invalidationHighGuidance
CG-013LocksLock-order inversionCriticalGuidance
CG-014PythonCross-file call-chain raceHighGuidance
CG-015PythonTainted shared-state mutationHighGuidance
CG-016DjangoUnlocked ORM mutationCriticalAuto-fix
CG-017Django / TortoiseIn-memory arithmetic vs F()HighAuto-fix
CG-018Redis / cacheUnsafe lock deletionCriticalGuidance
CG-019FastAPIBackgroundTasks session leakHighGuidance
CG-020Locks / HTTPUnbounded lock across network I/OCriticalGuidance
CG-021asyncio / threadingGenerator lock leak (yield)HighGuidance
06 / AUTOMATE

Keep the guardrail in the delivery path.

Run deterministic checks in pull requests, export OASIS SARIF v2.1.0 findings for GitHub Security, or stop regressions before the commit leaves a laptop.

01 — CI / SARIF v2.1.0

Make concurrency visible in review.

Scan code in pull requests, upload SARIF v2.1.0 to GitHub CodeQL / Security, and gate merges with line-level findings and suggested patches.

02 — PRE-COMMIT

Catch regressions before CI.

Use maintained pre-commit hooks to scan staged Python files, verify baselines, and preview safe diffs without touching formatting.

- run: pip install --upgrade concurrency-guard
- run: cguard scan . --format sarif -o cguard.sarif || true
- uses: github/codeql-action/upload-sarif@v3
  if: always()
  with:
    sarif_file: cguard.sarif
    category: concurrency-guard
07 / GITHUB APP

Make every pull request race-aware.

Join early access for the GitHub App: deterministic findings, line-level evidence, and suggested source-preserving patches before code merges.

Early access only. Your source stays in your repository.