Documentation / Reference

Consult Python API

06 - Reference · Cross-language contracts · Ownership and concurrency

Import supported SDK names from co2. These signatures and value definitions mirror the public exports. Sequence and Mapping are from collections.abc; PathLike is from os; Self is from typing. Strings identify resources, computations, attempts, artifacts and output slots; artifact payloads are bytes. Generations and serials obey native checked unsigned limits.

Returned dataclasses are frozen snapshots, not live authority state. Handles (Coherence, ScopedContext and runtime-provider handles) retain shared native state and have different lifetime semantics. Reusing a returned snapshot does not check freshness. See publication and planning guarantees.

Call authority

Coherence() defaults to in-memory operation, unlimited history, no collection policy and legacy caller identities. begin defaults to invocation-level dependencies and unknown execution, which blocks planning even when context is valid. Probabilistic recomputation defaults to disabled. Detailed explanations default to 16 MiB. No call executes a recomputation plan.

ScopedContext

Obtain a ScopedContext through Coherence.context(attempt); native-handle construction is an implementation detail.

def resource(self, resource: str) -> Observation: ...

Record and return the captured observation; the host owns its data.

def artifact(self, artifact: str) -> Artifact: ...

Read and record a captured, currently valid artifact.

Coherence

def __init__(self, config: LifecycleConfig | None=None) -> None: ...
@classmethod
def create_durable(cls, path: str | PathLike[str], config: LifecycleConfig | None=None) -> Self: ...

Exclusively create a new local store; never reset an existing path.

@classmethod
def open_durable(cls, path: str | PathLike[str]) -> Self: ...

Recover an existing store; current decisions await explicit reconciliation.

def close(self) -> None: ...

Release ownership and invalidate all contexts/provider references.

def __enter__(self) -> Self: ...
def __exit__(self, *args: object) -> None: ...
def authority_status(self) -> AuthorityStatus: ...
def revoke_provider(self, provider: str) -> None: ...

Explicit owner decision; no runtime installation is restored.

def reconcile_source(self, resource: str, version: str) -> Observation: ...

Confirm matching source bytes/version and conservatively advance its generation.

def historical_artifact(self, artifact: str) -> HistoricalArtifact: ...

Inspect committed retained history, including before recovery readiness.

def historical_attempt(self, attempt: str) -> HistoricalAttempt: ...
def storage_statistics(self) -> StorageStatistics: ...
def compact(self) -> StorageStatistics: ...

Explicit VACUUM, while ready; needs additional disk and memory headroom.

def new_identity(self, kind: IdentityKind) -> str: ...

Allocate an authority-bound, single-use identity; discard unused reservations.

def new_identities(self, kinds: Sequence[IdentityKind]) -> tuple[ReservedIdentity, ...]: ...

Reserve all requested kinds atomically, or none; empty requests are no-ops. Existing per-kind counters, capacity diagnostics and durable acknowledgement apply. Discard each unused reservation through discard_identity.

def discard_identity(self, kind: IdentityKind, identity: str) -> None: ...
def abandon(self, attempt: str) -> None: ...

Fence publication, without cancelling external inference or execution.

def collect(self) -> LifecycleStatistics: ...

Reclaim unreachable history/terminal state under the authority lock.

def lifecycle_statistics(self) -> LifecycleStatistics: ...

Logical payload accounting and measured private-engine state, not process RSS.

def register_resource(self, resource: str, version: str) -> VersionChange: ...

Register the authoritative version supplied by the host.

def begin(self, attempt: str, computation: str, *, resources: Sequence[str]=(), artifacts: Sequence[str]=(), strategy: DependencyStrategy=DependencyStrategy.INVOCATION_LEVEL, execution: ExecutionKind=ExecutionKind.UNKNOWN) -> Invocation: ...

Capture every accessible input; execution is unknown unless supplied.

def context(self, attempt: str) -> ScopedContext: ...

Return scoped access for an active attempt; this is not a sandbox.

def complete(self, attempt: str, artifact: str, value: bytes) -> ComputationRecord: ...

Atomically publish the default output after validating the snapshot.

def complete_outputs(self, attempt: str, outputs: Sequence[OutputSubmission]) -> tuple[ComputationRecord, ...]: ...

Atomically validate and register all outputs of an invocation.

def record(self, artifact: str) -> ComputationRecord: ...

Return an immutable historical record; this is not a validity check.

def artifact_status(self, artifact: str) -> ArtifactStatus: ...

Return the current validity or supersession of a historical artifact.

def plan(self, policy: PlanPolicy=PlanPolicy(), *, budget: ExplanationBudget=ExplanationBudget()) -> Plan: ...

Return a point-in-time plan; the default forbids probabilistic replay.

def plan_actions(self, policy: PlanPolicy=PlanPolicy()) -> ActionPlan: ...

Return dispositions with the same validity/policy checks, without causal path vectors. Use explain_artifact for complete causes of a current output or plan for all detailed paths. No inspection or plan grants execution permission.

def explain_artifact(self, artifact: str, policy: PlanPolicy=PlanPolicy(), *, budget: ExplanationBudget=ExplanationBudget()) -> PlanStep: ...

Inspect complete causes for one current output. Superseded IDs raise StaleDependencyError.

Use Coherence as a context manager or call close() explicitly to invalidate all retained references. Durable methods are present in Python but require a compatible native persistence build; unsupported builds raise PersistenceUnavailableError. Source/provider reconciliation and labelled history are defined in the durable contract. ScopedContext.resource returns an observation; the host owns the matching resource bytes. Scoped reads do not enforce ambient isolation.

Ordinary failed publication leaves its attempt pending. Adapters abandon their captured work on failure; direct SDK consumers own that choice. Once collected, old attempt/artifact lookups may become unknown, but replay fences remain. record may require readiness; historical_artifact and historical_attempt are the labelled durable inspection APIs before reconciliation. Plans never reserve inputs.

persistence_available() -> bool reports the native build flag, not filesystem qualification. Python Coherence has authority_status() for readiness; the Python API does not export Rust's is_closed method. Readiness includes CLOSED.

Select enum values

DependencyStrategy

INVOCATION_LEVEL = 'invocation_level'
EXPLICIT_STRUCTURED = 'explicit_structured'
RUNTIME_ENFORCED = 'runtime_enforced'

ExecutionKind

UNKNOWN = 'unknown'
DETERMINISTIC = 'deterministic'
READ_ONLY_OBSERVATION = 'read_only_observation'
PROBABILISTIC_REASONING = 'probabilistic_reasoning'
SIDE_EFFECTING_OPERATION = 'side_effecting_operation'
IRREVERSIBLE_OPERATION = 'irreversible_operation'
HUMAN_DECISION = 'human_decision'

DeclarationSource

DEVELOPER = 'developer'
LLM = 'llm'

DependencyAssurance

INVOCATION_LEVEL = 'invocation_level'
DEVELOPER_DECLARED = 'developer_declared'
LLM_FALLBACK = 'llm_fallback'
MISSING_DECLARATION_FALLBACK = 'missing_declaration_fallback'
OBSERVED_OMISSION_FALLBACK = 'observed_omission_fallback'
RUNTIME_OBSERVED_FALLBACK = 'runtime_observed_fallback'
SCOPED_RUNTIME_ENFORCED = 'scoped_runtime_enforced'

VersionChange

REGISTERED = 'registered'
UNCHANGED = 'unchanged'
CHANGED = 'changed'

ContextValidity

VALID = 'valid'
STALE = 'stale'

PlanAction

REUSE = 'reuse'
REFRESH = 'refresh'
RECOMPUTE = 'recompute'
REVALIDATE = 'revalidate'
BLOCK = 'block'
ESCALATE = 'escalate'

PlanReasonKind

CONTEXT_VALID = 'context_valid'
CONTEXT_STALE = 'context_stale'
UNKNOWN_EXECUTION_SEMANTICS = 'unknown_execution_semantics'
DETERMINISTIC_RECOMPUTATION = 'deterministic_recomputation'
OBSERVATION_REFRESH = 'observation_refresh'
PROBABILISTIC_RECOMPUTATION_PERMITTED = 'probabilistic_recomputation_permitted'
PROBABILISTIC_RECOMPUTATION_NOT_PERMITTED = 'probabilistic_recomputation_not_permitted'
SIDE_EFFECT_REPLAY_BLOCKED = 'side_effect_replay_blocked'
IRREVERSIBLE_ESCALATION_REQUIRED = 'irreversible_escalation_required'
HUMAN_REVALIDATION_REQUIRED = 'human_revalidation_required'
PREREQUISITE_NOT_READY = 'prerequisite_not_ready'

IdentityKind

ATTEMPT = 'attempt'
ARTIFACT = 'artifact'
EXECUTION = 'execution'

AuthorityReadiness

READY = 'ready'
RECOVERY_REQUIRED = 'recovery_required'
FAULTED = 'faulted'
CLOSED = 'closed'

HistoricalAttemptState

PENDING = 'pending'
COMPLETED = 'completed'
FAILED = 'failed'
ABANDONED = 'abandoned'
UNKNOWN_OR_COLLECTED = 'unknown_or_collected'

Assurance is assigned by the authority. Constructing a DependencyProvenance or selecting RUNTIME_ENFORCED cannot mint verified evidence. Developer declarations require honest completeness assertions; fallback variants retain full captured context. Consult the execution decision table for disposition semantics and prerequisite blocking.

Immutable value fields

Fields without defaults are required. Definitions below list exact public field names, annotations and constructor defaults. Tuples preserve ordering; capacity mappings are returned read-only. LifecycleConfig.bounded() obtains the native preset; its numerical limits appear in the lifecycle reference. Default None limits are unbounded. RetentionPolicy() retains no extra non-root historical candidates, but required roots always survive collection.

ResourceRef

id: str

ArtifactRef

id: str

Observation

resource: str
version: str
generation: int

ResourceDependency

observation: Observation

ArtifactDependency

id: str

Declaration

source: DeclarationSource
dependencies: tuple[DependencyRef, ...]

Developer source asserts completeness; LLM source always falls back.

OutputSubmission

output: str
artifact: str
value: bytes
declaration: Declaration | None = None

Invocation

execution: ExecutionKind
strategy: DependencyStrategy
attempt: str
computation: str
dependencies: tuple[Dependency, ...]

Artifact

output: str
id: str
computation: str
attempt: str
value: bytes

BrokerAccess

phase: str
dependency: DependencyRef

ExecutionEvidenceProvenance

provider: str
enrollment_generation: int
profile: str
profile_version: str
execution: str
scope: str
mandatory: tuple[DependencyRef, ...]
accesses: tuple[BrokerAccess, ...]

DependencyProvenance

strategy: DependencyStrategy
assurance: DependencyAssurance
declaration: Declaration | None
observed: tuple[DependencyRef, ...]
effective: tuple[Dependency, ...]
evidence: ExecutionEvidenceProvenance | None = None

ComputationRecord

invocation: Invocation
artifact: Artifact
provenance: DependencyProvenance

CurrentArtifactStatus

validity: ContextValidity

SupersededArtifactStatus

current: str

PlanPolicy

allow_probabilistic_recomputation: bool = False

Prerequisite

computation: str
output: str
artifact: str
action: PlanAction

PlanReason

kind: PlanReasonKind
prerequisite: Prerequisite | None = None

ResourceChanged

observed: Observation
current: Observation

ArtifactSuperseded

artifact: str
current: str

InvalidationCause

path: tuple[str, ...]
artifact_path: tuple[str, ...]
reason: InvalidationReason

PlanStep

execution: ExecutionKind
validity: ContextValidity
reasons: tuple[PlanReason, ...]
output: str
assurance: DependencyAssurance
computation: str
artifact: str
action: PlanAction
causes: tuple[InvalidationCause, ...]

ExplanationBudget

max_bytes: int = 16 * 1024 * 1024

Conservative causal-output accounting; not a whole-process memory quota.

ActionPlanStep

execution: ExecutionKind
validity: ContextValidity
reasons: tuple[PlanReason, ...]
output: str
assurance: DependencyAssurance
computation: str
artifact: str
action: PlanAction

ActionPlan

steps: tuple[ActionPlanStep, ...]

Plan

steps: tuple[PlanStep, ...]

ReservedIdentity

kind: IdentityKind
value: str

RetentionPolicy

historical_artifacts: int = 0
terminal_attempts: int = 0

LifecycleConfig

managed_identities: bool = False
retention: RetentionPolicy | None = None
max_resources: int | None = None
max_computations: int | None = None
max_outputs: int | None = None
max_attempts: int | None = None
max_records: int | None = None
max_provider_runs: int | None = None
max_providers: int | None = None
max_legacy_identities: int | None = None
max_outstanding_identities: int | None = None
max_identifier_bytes: int | None = None
max_value_bytes: int | None = None
max_dependencies: int | None = None
max_outputs_per_registration: int | None = None
max_provider_accesses: int | None = None
max_profiles: int | None = None
max_workload_bytes: int | None = None

EngineStatistics

resource_inputs: int
node_inputs: int
edges: int
measured_struct_slots: int
measured_memos: int
measured_fields_and_metadata_bytes: int
measured_pages: int

CapacityUsage

retained: int
limit: int | None

LifecycleStatistics

active_attempts: int
completed_attempts: int
failed_attempts: int
abandoned_attempts: int
current_artifacts: int
historical_artifacts: int
retained_snapshots: int
retained_evidence: int
provider_runs: int
active_provider_runs: int
terminal_provider_runs: int
active_providers: int
revoked_providers: int
workload_bindings: int
legacy_replay_identities: int
outstanding_identities: int
issued_identities: int
effective_edges: int
logical_payload_bytes: int
reclaimed_artifacts: int
reclaimed_attempts: int
reclaimed_runs: int
collections: int
engine_rebuilds: int
capacity_rejections: int
engine: EngineStatistics
capacities: Mapping[str, CapacityUsage]

AuthorityStatus

readiness: AuthorityReadiness
durable: bool
namespace: str | None
boot: int | None
pending_sources: tuple[str, ...]
pending_providers: tuple[str, ...]

HistoricalArtifact

record: ComputationRecord | None
identity_fenced: bool

Absence is no retained record, never proof of nonpublication.

HistoricalAttempt

state: HistoricalAttemptState
retained_artifacts: tuple[str, ...]

StorageStatistics

sqlite_version: str
logical_image_bytes: int
database_bytes: int
journal_bytes: int
owner_file_bytes: int
observed_store_bytes: int
page_size: int
pages: int
free_pages: int
available_bytes: int
compaction_headroom_bytes: int

Tagged unions

DependencyRef: TypeAlias = ResourceRef | ArtifactRef
Dependency: TypeAlias = ResourceDependency | ArtifactDependency
ArtifactStatus: TypeAlias = CurrentArtifactStatus | SupersededArtifactStatus
InvalidationReason: TypeAlias = ResourceChanged | ArtifactSuperseded

logical_payload_bytes, engine measurements, storage sizes and compaction headroom are diagnostics, not exact heap/RSS/disk quotas. HistoricalArtifact.record is None means no retained record, not proof of nonpublication. identity_fenced means consumed/burned, not proof of successful publication.

Handle exceptions

All native domain exceptions below are exported from co2. Their base is Co2Error, except the storage-specific subclasses listed with StorageError below. Python argument conversion may also raise TypeError, ValueError or OverflowError. Adapter-specific errors are documented beside their integration; do not parse exception text as a stable protocol.

ExceptionsResponse
EmptyIdentifierError, InvalidIdentityErrorCorrect identifiers/kinds; reserve issued IDs where required. Never recycle consumed/burned identities.
UnknownResourceError, UnknownArtifactError, UnknownAttemptErrorCheck registration, authority/session mapping and collection. Unknown does not prove nonexecution.
DuplicateAttemptError, DuplicateArtifactError, DuplicateDependencyError, DuplicateOutputError, NoOutputsErrorCorrect the submission; a new execution needs new identities.
UnexpectedDeclarationError, DependencyNotAccessibleErrorCorrect strategy/declaration references against the full captured accessible inputs.
StaleDependencyError, SupersededAttemptError, AbandonedAttemptErrorDo not publish the old result; capture current context and a new attempt if execution remains eligible.
ExecutionClassificationMismatchError, CycleErrorCorrect computation semantics or prospective dependency structure. Accepted computation classifications do not change in place.
CapacityExceededError, GenerationExhaustedErrorCollect/adjust supported capacities with headroom; counters never wrap.
ExplanationBudgetExceededErrorUse lightweight actions or targeted detail; raise the budget deliberately. No partial detailed result is returned.
AuthorityClosedError, ForkedAuthorityError, LockPoisonedError, EngineInvariantErrorStop using that invalid instance; investigate invariant failures.
EvidenceAdmissionErrorInspect the admission reason; unsupported/mismatched/replayed/revoked evidence cannot downgrade to ordinary completion.
PersistenceUnavailableError, RecoveryRequiredError, InvalidReconciliationErrorChoose a compatible native build or complete valid source/provider decisions.
StorageError, StoreInUseError, UnsupportedStorageErrorRespect exclusive ownership and qualified storage; do not bypass checks or open active stores with another SQLite connection.
StorageCapacityError, StorageRolledBackErrorConfirmed rollback retains prior usable state; handle storage pressure before eligible retry.
AuthorityFaultedErrorOutcome may be uncertain. Close, reopen a new instance and reconcile; do not blindly repeat publication or effects.

StoreInUseError, UnsupportedStorageError, StorageCapacityError and StorageRolledBackError subclass StorageError, which subclasses Co2Error. Other domain exceptions subclass Co2Error directly. EvidenceAdmissionError groups native AdmissionFailure reasons; see the binding/failure table.

Use optional modules

Framework adapters remain in co2.integrations.langgraph, .openai_agents, .google_adk and .claude_agents; the Build index links their parameters, examples and failure contracts. These modules import their optional frameworks explicitly. They are not loaded by base SDK imports.

co2.runtime exports SPI_VERSION, ResourceSnapshot, ProviderAuthority, EnrolledProvider, ProviderInstallation, PreparedExecution, ExecutionEvidence and available_provider_implementations(). See provider contracts and the annotated runtime facade. Installation and evidence handles are opaque native objects, not public constructors for arbitrary manifests or Python providers.

The private co2._native bridge, _api and _models import paths are implementation details. Use co2 for ordinary SDK imports. The Rust source contract and SPI have independent native trust and feature boundaries.