Documentation / Core concepts

Python SDK

06 - Reference · Complete signatures, models and errors

Use the SDK to publish results safely against changing input versions. Start with installation and the lending quickstart; this page describes ownership, threads and native interoperability.

The co2 Python package wraps the Rust co2-core authority through PyO3. Python translates values to immutable dataclasses and enums; it does not implement tracking, invalidation, dependency selection or planning. There is no public package publication.

Requirements & Local Installation

From the repository root:

python3 -m venv .venv
. .venv/bin/activate
python -m pip install maturin==1.10.2
maturin develop --locked
python -m unittest discover -s python_tests -v
python examples/lending.py

maturin develop installs into the active environment. Alternatively, python tools/build_release.py --variant base --interpreter python --out wheels/base produces a local wheel; install the exact compatible file printed by the builder. A source distribution can be built with maturin sdist. Native dependencies are exactly locked; the binding uses pinned PyO3 0.29.0; bindings/python/Cargo.lock independently locks the native bridge. The public distribution is installed with python -m pip install context-coherence; use import co2.

Capture and publish result

from co2 import Coherence, ExecutionKind, PlanAction

core = Coherence()
core.register_resource("customer-status", "v1")
core.begin("attempt-1", "eligibility", resources=["customer-status"],
           execution=ExecutionKind.DETERMINISTIC)
core.complete("attempt-1", "eligibility-1", b"eligible")
core.register_resource("customer-status", "v2")
step = core.plan().steps[0]
assert step.action is PlanAction.RECOMPUTE
print(step.validity, step.reasons, step.causes)

The host must supply all accessible inputs, source versions in authoritative order, and an accurate execution classification. Resource data is host-owned and must match the version it registered. Co2 cannot detect invisible changes or validate a trusted developer's declaration. Plans are point-in-time results, not authorization or execution.

begin defaults to DependencyStrategy.INVOCATION_LEVEL and ExecutionKind.UNKNOWN; unknown execution blocks even when current. begin(..., strategy=..., execution=...) supports all Rust strategy and execution kinds. For structured output, pass OutputSubmission values to complete_outputs with Declaration(DeclarationSource.DEVELOPER, ...) only when trusted host code can assert completeness; LLM declarations and missing or contradicted declarations retain conservative fallback.

context(attempt) provides scoped resource observations and artifact reads, but cannot isolate ambient host access. Ordinary runtime tracking reports RUNTIME_OBSERVED_FALLBACK and retains the full captured set.

record returns immutable historical ComputationRecord values, including the invocation, artifact bytes and provenance. artifact_status reports CurrentArtifactStatus or SupersededArtifactStatus; it is separate from plan eligibility. plan(PlanPolicy(allow_probabilistic_recomputation=True)) may classify stale probabilistic work as RECOMPUTE; the default is False. Side-effect replay is blocked, stale irreversible operations escalate, and stale human decisions require revalidation. Each PlanStep carries execution, validity, action, assurance, ordered reasons, and causes with artifact and computation paths. See architecture.

The public module exports typed dataclasses, enum values and the ResourceRef/ArtifactRef and ResourceDependency/ArtifactDependency unions. Artifact contents are bytes; observations carry string identity and version plus the Rust authority's generation. Data returned by the SDK is a snapshot and is not linked to future state changes. py.typed marks the package as typed. Detailed method annotations and docstrings are in the Python API and models.

Errors, Ownership & Threads

Every Rust domain error maps to a distinct subclass of Co2Error, including StaleDependencyError, DuplicateAttemptError, CycleError and DependencyNotAccessibleError. The error message retains the Rust domain details; invalid Python argument types instead raise TypeError or ValueError. A rejected ordinary registration leaves the attempt reserved, as in Rust. The separate evidence-required path groups admission reasons in EvidenceAdmissionError and closes a correctly bound failed admission; it cannot downgrade to ordinary registration.

Every Coherence() owns an independent Rust authority. Assignment and copy.copy() share it; copy.deepcopy() is unsupported. Contexts/provider handles retain the same authority.

Explicit close() invalidates all such references and releases durable ownership even while they remain alive. Without close, lifetime follows the last reference. Instances are process-affine; inherited calls reject before authority locks.

Default instances remain in-memory; optional durable create/open, reconciliation, labelled history and typed storage/fault exceptions use the same Rust core. See the durable guide for supported builds/platforms and storage ownership. External execution/cancellation and framework restoration remain host-owned.

For ordinary GIL-enabled CPython, PyO3 converts Python arguments under the GIL, releases it with Python::detach during each Rust authority operation, and reacquires it to construct Python values. Calls sharing an instance are still serialized by the Rust authority's mutex; separate instances can progress independently. Python object conversion and caller code still run under the GIL.

The extension does not opt into free-threaded CPython; forced GIL-disabled mode is unsupported and untested. No Python callback runs within a detached core operation. Thread tests exercise shared update/commit and duplicate-commit races but do not establish distributed, external-resource or scheduling guarantees.

Verify development installation

cargo test --locked
cargo build --locked --example python_sdk_parity
CO2_PARITY_BIN="$PWD/target/debug/examples/python_sdk_parity" python -m unittest discover -s python_tests -v
# Type-checking the optional adapter fixture in python_tests requires the LangGraph extra.
python -m pip install langgraph==1.2.24
python -m mypy --strict python/co2/__init__.py python/co2/_api.py python/co2/_models.py python/co2/integrations/wasmtime.py python_tests examples/lending.py  # mypy==1.19.1

Without CO2_PARITY_BIN, the cross-language fixture is reported as skipped; other Python tests still run. CI builds the fixture and sets the variable. A local CI-equivalent check also runs cargo fmt --check, cargo clippy --locked --all-targets -- -D warnings, and the corresponding commands with --manifest-path bindings/python/Cargo.toml.

Use local provider

The Wasmtime admission guide describes co2.integrations.wasmtime, installed with the separate wasmtime-reference extra. Successful native-broker evidence can produce SCOPED_RUNTIME_ENFORCED and immutable provenance.evidence; ordinary runtime observation remains unchanged. This narrow locally trusted profile is not arbitrary Python/agent isolation. The optional evidence metadata field defaults to None for records without admitted scoped evidence. Rebuild the native extension after updating source.

Provider SPI 1.0

The provider development guide documents co2.runtime, opaque native installation/evidence handles and SPI 1.0. Runtime providers require explicit native build features; the base SDK includes none. Wasmtime's existing consumer facade is retained through the SPI, while a separate expression provider works without Wasmtime. The wasmtime-reference extra installs the Python runtime only; use the guide's Maturin feature commands when rebuilding. Existing framework adapter behavior and ordinary runtime fallback are unchanged.

Lifecycle Configuration

Coherence(config: LifecycleConfig | None = None), new_identity(kind), discard_identity(kind, id), abandon(attempt), collect() and lifecycle_statistics() are typed native-authority operations. See the complete lifecycle guide for identity requirements, capacity fields, state ownership and statistics. Default construction remains unlimited with collection disabled. A caller-held record/handle is an independent retained object; dropping Core history does not release it. Capacity/identity/abandonment errors include CapacityExceededError, InvalidIdentityError and AbandonedAttemptError.

Reserve Bundles and Inspect Actions

Use new_identities(kinds) for atomic typed reservations, plan_actions(policy) for dispositions without eagerly expanded causal paths, and explain_artifact(id, policy) for a complete current-output explanation. Existing individual identities remain available. Detailed planning uses an explicit default explanation budget; oversized calls raise a typed error without returning partial causes. See contracts and examples.

See public contracts, supported configurations and executable examples.

For distributable native-feature builds, use distinct local-version variants; editable development flags do not define release wheel identity.