Skip to main content

CodePact

CodePact catches conflicting resource declarations and supported lifecycle bugs such as use-after-close and missed cleanup in Python. Its analyzer reads source without importing or running application code.

PyPI CLI on PyPI Python Quality Documentation License: MIT

Declare how resources close and how APIs intend to access them alongside ordinary Python types. CodePact 0.3.0 is a candidate that checks cleanup obligations across supported exits, in addition to use-after-close. It is not published yet. The previously published 0.1.0 and 0.2.0 releases used the TypePact name and package names. APIs, diagnostics, and the JSON schema remain provisional during 0.x.

Task Command Availability
Inspect lifecycle and access declarations codepact inspect-contracts FILE... CodePact 0.3.0 candidate
Check use-after-close and cleanup obligations codepact check --root DIR CodePact 0.3.0 candidate

Build the candidate from source using installation, then follow contract inspection or lifecycle checking. See the availability guide for release status and the platform matrix.

Install

CodePact 0.3.0 has passed its pre-tag qualification; the renamed Python packages and Rust crate have not been published yet. To try this candidate from a checkout:

git clone https://github.com/eddiethedean/codepact.git
cd codepact
uv sync --locked
uv run --locked codepact --version

After the maintainer qualifies and publishes 0.3.0, install the helper and its matching CLI dependency with uv add codepact==0.3.0 or python -m pip install 'codepact==0.3.0'.

This installs two matching distributions:

Distribution Contents
codepact Pure Python declaration helpers, typing metadata, and py.typed
codepact-cli The native Rust codepact executable

codepact pins codepact-cli to the same version. Importing the Python helpers does not start the analyzer or download an executable. Prebuilt CLI wheels require no Rust compiler; building the CLI from source requires Rust 1.96 or newer and a linker.

For the command alone after publication:

uv tool install codepact-cli==0.3.0
codepact --version

Inspect your first contract

Save this as connection.py:

from codepact import resource
from codepact.rust import Borrowed, Owned


@resource(closed_by="close")
class Connection:
    def close(self) -> None:
        pass


def read(conn: Borrowed[Connection]) -> str:
    return "ready"


def consume(conn: Owned[Connection]) -> None:
    conn.close()

Inspect its declarations:

uv run codepact inspect-contracts connection.py

CodePact emits JSON containing these contract views:

Declaration Base type Lifecycle Access intent
Connection connection.Connection Closed by close Unspecified
read.conn connection.Connection Closed by close Shared
consume.conn connection.Connection Closed by close Owned

The resource decorator preserves the class identity and records lifecycle metadata. The inspector reads the file as text without importing it, evaluating annotations, or invoking decorators. In the historical TypePact 0.1.0 release, method bodies were not checked: declaring closed_by="close" did not establish that close releases anything.

The inspector also rejects conflicting declarations. The TP4002 example shows a resource alias that declares a different close method, the reported locations, and a valid repair. Use the check command below for lifecycle findings.

See the complete paired example and its JSON snapshot.

Try lifecycle checking from source

The TypePact 0.2.0 checker remains available from its historical tag. For the CodePact 0.3.0 candidate, use Rust 1.96+ and build the current checkout:

git clone https://github.com/eddiethedean/codepact.git
cd codepact
uv sync --locked
uv run --locked codepact check --root examples

Record git rev-parse HEAD with candidate results.

The lifecycle example constructs a connection, passes it to a Borrowed helper, closes it, then calls the helper again. The final call produces a definite TP1001, includes the close location, and exits with status 1. This example intentionally contains an error.

The checker follows supported normal synchronous flow, local aliases, direct calls, and if/else joins. It also reports closing a Borrowed parameter as TP2001. Possible findings and incomplete coverage are visible warnings that can accompany exit 0; read the report even when the command succeeds.

Follow the lifecycle tutorial for an isolated example, expected output, and a valid counterpart. The checker does not establish leak freedom, cleanup on every exit, general ownership safety, or that the declared close method releases a runtime resource. Release status and supported behavior are summarized in the availability guide.

Annotation forms

The access aliases use typing.Annotated, so ordinary Python type checkers retain the underlying type:

Alias from codepact.rust Metadata from codepact.contracts Intent
Borrowed[T] Annotated[T, SharedBorrow()] Shared access
Owned[T] Annotated[T, OwnedAccess()] Owned access
BorrowedMut[T] Annotated[T, ExclusiveBorrow()] Exclusive access

For example, Borrowed[Connection] and Annotated[Connection, SharedBorrow()] produce the same shared-access facts. The aliases are also exported from codepact.contracts.

You can attach lifecycle and access metadata to an alias of an existing class:

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 on an alias describes that view; it does not change every use of the underlying class. CodePact combines compatible lifecycle and access declarations and reports conflicting values with their source locations. These annotations express intent; they do not enforce ownership or borrowing at runtime.

Inspecting a project

Choose a source target explicitly when needed. The default is Python 3.11:

uv run codepact inspect-contracts --python-version 3.13 connection.py

For imports between files, pass every module that should participate in resolution. For a project with a src directory:

uv run codepact inspect-contracts --root src src/models.py src/client.py

For inspect-contracts, --root determines logical paths and package-qualified module names without discovering files. Without it, each input file's stem supplies its module name. Absolute from module import Class imports and direct imports of supported assignment aliases resolve across supplied files. The check command instead scans .py files below its root; explicit filenames add inputs and do not restrict that scan.

Inspection output and exit codes

JSON is the default output; --json is accepted explicitly. Each result includes:

  • contracts: normalized base symbols, lifecycle and access facts, source spans, and declaration provenance.
  • diagnostics: errors and unsupported-boundary findings, including related locations where applicable.
  • coverage: complete-for-supported-subset or incomplete, with reasons and work counts.
  • schema_version: 0 and assurance: "contract-inspection-only".

Contract provenance is declared-unverified. Line and column numbers are one-based; columns count UTF-8 bytes.

Exit code Meaning
0 Inspection completed with no declaration errors or incomplete coverage
1 Declaration errors, syntax errors, or unsupported/unresolved constructs were reported
2 An invocation, file access, input limit, or fatal execution error prevented inspection

A successful inspection establishes the recorded declarations within the supported subset. It does not prove resource safety.

Scope of the original 0.1 release

The inspector supports module-level classes, literal CodePact resource decorators, simple assignment aliases, parameter and return annotations, and direct absolute imports among explicitly supplied modules. It resolves supported API imports by identity, respects local rebinding, and preserves the class and metadata captured by earlier aliases.

Relevant unsupported constructs produce incomplete coverage. Current boundaries include:

  • String annotations and from __future__ import annotations.
  • Relative imports, star imports, import re-export chains, and supplied-module cycles.
  • Class inheritance and metaclass behavior, other class decorators, and decorated functions.
  • Computed contract expressions, dynamic decorator arguments, and eager named expressions that could rebind module names.
  • Module-level control flow and unsupported nested or generic declarations.

The inspector has explicit source and work limits, including a 1,000,000-byte total source budget per request. See the inspector guide for the detailed limits and Rust session API.

The historical TypePact 0.2.0 release added bounded lifecycle flow checks. The CodePact 0.3.0 candidate adds cleanup obligations across supported exits. General ownership enforcement and precise alias analysis through fields and containers remain future work. The release roadmap describes that progression.

Compatibility

Surface Support
Python helper runtime Python 3.11+; CI covers CPython 3.11–3.14
Analyzed Python source targets 3.11, 3.12, and 3.13
Python typing Inline types and py.typed; compatibility fixtures for mypy and Pyright
Rust source builds Rust 1.96+

The release configuration defines eight native CLI wheel targets. The current candidate's build and install evidence is recorded in the availability guide:

Platform x86-64 ARM64
Linux glibc glibc 2.17+ glibc 2.28+
Linux musl musl 1.2+ musl 1.2+
macOS 10.13+ 11.0+
Windows Supported Supported

The helper wheel is universal pure Python. CLI wheels contain a standalone executable and do not depend on a particular CPython ABI. Identifier validation follows the Unicode rules of the selected source target. See compatibility and distribution details for the complete policy.

Architecture

The Python helpers supply declarations; the Rust engine performs inspection. Pinned Ruff parser and AST components provide structured syntax and source ranges. Salsa tracks parsing and module semantics so reusable sessions can retain unaffected work across edits.

The Rust codepact crate exposes inspect for a single request and AnalysisSession for repeated updates, removal, reset, cancellation, and revision-tagged results. The candidate adds check and versioned check_report methods. CLI and library calls share the analyzer; the host application supplies the Rust API's source snapshot. See the Rust API guide and analyzer design.

Development

Use a source checkout with uv, Rust 1.96+, rustfmt, Clippy, and Make. Install the pinned dependency auditors, then run the full local 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

make check covers Rust formatting, compilation, Clippy, tests, MSRV validation, dependency audits, strict Python typing and linting, identifier-table verification, package builds and clean installation checks, and the inspector's execution guard. GitHub Actions runs the Python checks on 3.11–3.14 alongside the Rust and dependency checks.

Run the repository example from the checkout:

uv run --locked codepact inspect-contracts --root . examples/contracts.py

See CONTRIBUTING.md for focused check targets and contribution guidance.

Documentation

License

CodePact is distributed under the MIT license.

Metadata

Release files for codepact 0.3.0

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

Source distribution (sdist)

Source distribution for codepact 0.3.0
File Size Uploaded Provenance Actions
codepact-0.3.0.tar.gz 8.2 kB Without provenance Details for codepact-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for codepact 0.3.0
File Interpreter ABI Platform Actions
codepact-0.3.0-py3-none-any.whl Python 3 none any Details for codepact-0.3.0-py3-none-any.whl

Total release size: 17.1 kB

Release files / codepact-0.3.0.tar.gz

Download URL codepact-0.3.0.tar.gz
Size 8.2 kB
Tags Source
SHA-256 checksum
How to use checksums
d1f4ebc33f09f89b5ab455d568ce3adc6a39989d424d7a836d6c61125ea50c00
BLAKE2b-256 checksum
How to use checksums
faefac89654dceab5a2ebe567348f018221d888c3236d74fe28d3ed03c0885ac
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.3.0-py3-none-any.whl

Download URL codepact-0.3.0-py3-none-any.whl
Size 8.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6b3cf356914fc6c3773987ffd1d5828f9434774b5e7b7319c873e2cbda4ab73f
BLAKE2b-256 checksum
How to use checksums
f28c29ccf654cf33aa5b131f9bcf8db32fc6bf7c3ebcb4342cc1c6d43f4bd41d
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.3.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.

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