CodePact
Find lifecycle mistakes in Python before running your code.
CodePact is a static analyzer for resource contracts. Declare how a resource closes and which functions own or borrow it; CodePact checks supported paths for use after close, missed cleanup, and invalid ownership handoffs. It reads source without importing or executing your application.
Quick start · Try 0.4 · Documentation · Rule catalog · Roadmap
Release scope: This checkout describes the 0.4.0 synthetic preview, including configuration, baselines, suppressions, and must-use results. Real-world usefulness remains unqualified. See availability and verified release evidence for publication and artifact status. The separately qualified 0.3.0 release is available on PyPI and crates.io. APIs and report schemas remain provisional during 0.x.
What it checks
| Contract | Finding | Available in |
|---|---|---|
| A resource is closed by a declared method | Use after close (TP1001) |
Published 0.3 |
| A function owns a resource | Outstanding cleanup duty on a modeled exit (TP1002) |
Published 0.3 |
A function returns Owned[T] |
Invalid ownership handoff (TP1003) |
Published 0.3 |
| A function borrows a resource | Close through a borrowed view (TP2001) |
Published 0.3 |
| A synchronous result must be handled | Discarded must-use result (TP3001) |
0.4 candidate |
| Resource declarations must agree | Conflicting lifecycle/access metadata (TP4002) |
Published 0.3 |
The checker covers bounded local flow, aliases, supported calls, branches,
loops, exceptional exits, finally, context managers, and supported async
cleanup/cancellation paths. Reports expose certainty, related locations, and
coverage boundaries. A clean report describes the supported subset; it does
not establish general Python resource safety.
Quick start
In an existing uv project, install the published helper and matching CLI:
uv add codepact==0.3.0
uv run --locked codepact --version
mkdir -p demo
Save this as demo/connection.py:
from codepact import resource
from codepact.rust import Borrowed
@resource(closed_by="close")
class Connection:
def status(self) -> str:
return "ready"
def close(self) -> None:
pass
def read(conn: Borrowed[Connection]) -> str:
return conn.status()
conn = Connection()
conn.close()
read(conn) # TP1001: the connection has already been closed.
Run the checker on that directory:
uv run --locked codepact check --root demo
CodePact reports a definite TP1001 at read(conn), relates the earlier close,
and exits with status 1. Move read(conn) before conn.close() and recheck
to clear the finding. These methods are small stubs: CodePact trusts the
lifecycle declaration and does not verify what close() releases at runtime.
To inspect the declarations as JSON:
uv run --locked codepact inspect-contracts demo/connection.py
This records the resource lifecycle and the shared access intent of read.conn.
The lifecycle tutorial explains the analysis, and the
cleanup tutorial covers exit duties.
Other installation options
# Python helpers and matching CLI
python -m pip install 'codepact==0.3.0'
# Standalone CLI
uv tool install codepact-cli==0.3.0
# Rust library
cargo add codepact@0.3.0
The codepact distribution pins codepact-cli to the same version. Helpers
are pure Python and include py.typed; importing them does not start the
analyzer. Prebuilt CLI wheels include a native executable and require no Rust
compiler. Source builds require Rust 1.96+ and a linker.
Declare intent with ordinary Python types
The helpers use typing.Annotated, preserving the underlying type for mypy
and Pyright:
| Declaration | Meaning |
|---|---|
@resource(closed_by="close") |
Declare the method that closes a resource |
Owned[T] |
Declare owned access or an ownership handoff |
Borrowed[T] |
Declare shared borrowed access |
BorrowedMut[T] |
Declare exclusive borrowed access |
MustUse[T] or @must_use |
Declare a result that requires immediate handling; 0.4 candidate |
Access aliases come from codepact.rust or codepact.contracts. You can also
write metadata explicitly:
from typing import Annotated
from codepact.contracts import Resource, SharedBorrow
ConnectionView = Annotated[
Connection,
Resource(closed_by="close"),
SharedBorrow(),
]
Here, Connection is the class from the quick start. Metadata describes the
alias's view. Compatible declarations combine; conflicts report both source
locations. The helpers record intent without enforcing borrowing at runtime.
See contracts and annotation forms.
Try the 0.4 source candidate
Build the current checkout with Python 3.11+, uv, and Rust 1.96+:
git clone https://github.com/eddiethedean/codepact.git
cd codepact
uv sync --locked
uv run --locked codepact --version
uv run --locked codepact capabilities --json
Record git rev-parse HEAD when sharing candidate results. The following
features require this checkout's CLI and helpers.
Handle must-use results
from codepact import discard, must_use
@must_use
def fetch() -> int:
return 42
fetch() # TP3001: result discarded
value = fetch() # Immediate handling by assignment
discard(fetch()) # Explicit intentional abandonment
MustUse[int] and Annotated[int, MustUseResult()] return annotations express
the same contract. The rule checks immediate handling of resolved synchronous
calls. It does not track later use of an assigned value, infer ownership, or
prove async result consumption. discard() preserves evaluation effects and
does not close a resource. TP3001 defaults to warning severity; use
--fail-on warning to make it fail the check.
Add a project policy
For a project with a src/ directory, add this to pyproject.toml:
[tool.codepact]
config-version = 1
root = "src"
python-version = "3.12"
exclude = ["generated/**"]
mode = "strict"
fail-on = "warning"
With the candidate CLI, inspect the effective settings and run a check:
codepact check --show-settings --json
codepact check --json > codepact-report.json
codepact explain TP3001 --json
Strict mode also fails on unsuppressed possible violations and incomplete coverage. JSON reports retain certainty, coverage, policy, suppression data, and snapshot identity. See CLI options and report formats and schemas.
Adopt checks gradually
Review current findings, then explicitly create a baseline:
codepact baseline update --output codepact-baseline.json \
--reason "reviewed findings before adoption"
codepact check --baseline codepact-baseline.json
Commit the reviewed baseline with the project. Replacing it requires
--replace; ordinary checks never rewrite it. For a local exception, name the
rule and explain why:
fetch() # codepact: ignore[TP3001] -- queried intentionally for side effects
Eligible suppressed findings remain in the JSON audit output. Baselines and inline suppressions preserve mandatory errors and incomplete coverage. Follow the adoption guide for matching rules, stale entries, policy configuration, and qualification status.
Choose the right command
| Command | Purpose |
|---|---|
codepact check --root src |
Discover Python files and check supported flow |
codepact inspect-contracts --root src src/models.py src/client.py |
Inspect declarations in explicit files and resolve their supported imports |
codepact check --json |
Emit a machine-readable report; schema 2 in the 0.4 CLI |
codepact check --show-settings --json |
Inspect configuration and its origins; 0.4 candidate |
codepact capabilities --json |
List rules, schemas, targets, and limits; 0.4 candidate |
check scans its root; explicit file operands add inputs rather than narrowing
the scan. inspect-contracts reads only the files supplied. The default source
target is Python 3.11; select another with --python-version.
| Check status | Meaning |
|---|---|
0 |
The completed report passes the selected policy |
1 |
The completed report contains a finding or coverage condition that fails policy |
2 |
Invocation, configuration, input, or execution failed |
Advisory mode can return 0 with incomplete coverage. Read the coverage and
certainty fields alongside the exit code. Inspection has its own preserved
exit policy, documented in the CLI reference.
Compatibility and limits
| Surface | Support |
|---|---|
| Python helper runtime | Python 3.11+; CI covers CPython 3.11–3.14 |
| Analyzed Python source | Python 3.11, 3.12, and 3.13 |
| Python typing | Inline types, py.typed, mypy and Pyright fixtures |
| Rust source builds | Rust 1.96+ |
| Published CLI wheels | Linux glibc/musl, macOS, and Windows; x86-64 and ARM64 |
Platform versions and published artifact evidence are in the availability guide. Running the helpers on Python 3.14 does not enable analysis of Python 3.14 grammar.
Analysis is bounded and reports unsupported constructs. String annotations,
from __future__ import annotations, dynamic dispatch, and resource aliases
through arbitrary fields or containers remain important limitations. The
checker does not prove that a declared close method releases an operating
system resource. See supported syntax and
limitations before relying on a result.
How it works
Python helpers provide declarations. The Rust engine uses Ruff's parser and AST for syntax and source ranges, then performs bounded semantic and flow analysis. Salsa caches reusable queries across edits in an analysis session.
The Rust crate exposes inspect, check, check_report, and
AnalysisSession for repeated updates and cancellation. Existing Rust APIs
keep their released result contracts; the 0.4 CLI's adoption policy wraps the
canonical findings. See the Rust API guide and
architecture.
Contributing
From a checkout, install the pinned auditors and run the full gate:
uv sync --locked
cargo install cargo-audit --version 0.22.2 --locked
cargo install cargo-deny --version 0.20.2 --locked
uv run --locked make check
The gate covers Rust and Python quality, tests, MSRV, dependency audits, package builds and isolated installation, schema fixtures, documentation, and checks that analyzed source is never executed. GitHub Actions runs the Python matrix on 3.11–3.14. See CONTRIBUTING.md for focused targets.
- Documentation — guides and API references.
- Rule catalog — findings, certainty, and repair guidance.
- Roadmap — release progression and pending work.
- Planning index — design decisions and qualification plans.
The 0.1 and 0.2 releases used the former TypePact name. The documentation site
retains its typepact.readthedocs.io address; the project and current packages
are named CodePact.
License
MIT.
Metadata
Release files for codepact 0.4.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 |
|---|---|---|---|---|
| codepact-0.4.0.tar.gz | 7.9 kB | Without provenance | Details for codepact-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| codepact-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for codepact-0.4.0-py3-none-any.whl |
Total release size: 16.6 kB
Release files / codepact-0.4.0.tar.gz
| Download URL | codepact-0.4.0.tar.gz |
|---|---|
| Size | 7.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
571e4f8326c69011724bb062f358409f9b713e46b3ebac0327ef7b83e8fed816
|
|
BLAKE2b-256 checksum How to use checksums |
9b1a96899a5f81cd38077115624c0d6bc9947af26c00ffabb833614c6738a389
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / codepact-0.4.0-py3-none-any.whl
| Download URL | codepact-0.4.0-py3-none-any.whl |
|---|---|
| Size | 8.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
92be59edfe92a8136913af5c89caa84935d889d9a43f8a8c746d44ac13fc979c
|
|
BLAKE2b-256 checksum How to use checksums |
31c51c4dfbc576ccfcca55cfd20d6731a6e9c6cb53ccd109b0c8d81c64e4dc9d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Security for codepact 0.4.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.
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.