Skip to main content

telltale_vm/
lib.rs

1//! Bytecode VM for choreographic session type protocols.
2//!
3//! This crate provides a standalone, embeddable virtual machine that executes
4//! choreographic protocols projected to local session types. The VM validates
5//! every instruction against its session type monitor, ensuring protocol
6//! conformance at runtime.
7//!
8//! # Architecture
9//!
10//! The VM follows the Lean specification in `lean/Runtime/VM/`:
11//! - **Instructions** ([`instr::Instr`]): bytecode ops for send/recv/choice/session lifecycle
12//! - **Coroutines** ([`coroutine::Coroutine`]): lightweight execution units, one per role
13//! - **Sessions** ([`session::SessionStore`]): manage session lifecycle and namespaces
14//! - **Buffers** ([`buffer::BoundedBuffer`]): bounded message channels with backpressure
15//! - **Scheduler** ([`scheduler::Scheduler`]): policy-based coroutine scheduling
16//! - **Loader** ([`loader`]): dynamic choreography loading with validation
17//! - **Compiler** ([`compiler`]): compile `LocalTypeR` to bytecode
18//!
19//! The VM is the **single execution engine** for simulation and runtime
20//! orchestration. Higher-level systems (e.g. `telltale-simulator`) wrap the
21//! VM with deterministic middleware for network latency, faults, property
22//! monitoring, and checkpointing.
23//!
24//! **Nested simulation** is supported via [`nested::NestedVMHandler`], which
25//! allows a VM coroutine to host an inner VM for distributed or hierarchical
26//! simulations.
27//!
28//! # Effect Handler Contract
29//!
30//! The VM's [`effect::EffectHandler`] is synchronous, deterministic, and
31//! **session-local**. It must not depend on global time or shared mutable
32//! state across sessions. This is distinct from the async, typed
33//! `telltale_choreography::ChoreoHandler` used by generated choreography code.
34//!
35//! # Usage
36//!
37//! ```ignore
38//! use telltale_vm::{OwnedSession, VM, VMConfig, compiler, loader::CodeImage};
39//!
40//! let config = VMConfig::default();
41//! let mut vm = VM::new(config);
42//! let image = CodeImage::from_local_types(&local_types, &global_type);
43//! let _session: OwnedSession =
44//!     vm.load_choreography_owned(&image, "runtime/owner")?;
45//! while vm.step(&handler)? {}
46//! ```
47
48use cfg_if::cfg_if;
49
50pub mod architecture;
51pub mod bridge;
52pub mod buffer;
53pub mod clock;
54pub mod commit_common;
55/// Communication replay modes and consumption state for deterministic and speculatively
56/// replayed session histories.
57pub mod communication_replay;
58pub mod compiler;
59pub mod composition;
60pub mod coroutine;
61pub mod determinism;
62pub mod driver;
63pub mod effect;
64pub mod envelope_diff;
65pub mod exec;
66pub mod exec_api;
67pub mod faults;
68pub mod guard;
69pub mod identity;
70pub mod instr;
71pub mod instruction_semantics;
72pub mod integration;
73pub mod intern;
74pub mod kernel;
75pub mod loader;
76pub mod nested;
77pub mod output_condition;
78pub mod owned;
79pub mod persistence;
80pub mod runtime_contracts;
81pub mod scheduler;
82pub mod serialization;
83/// Session store and role/session bookkeeping used by protocol execution.
84pub mod session;
85pub mod trace;
86pub mod transfer_semantics;
87pub mod verification;
88pub mod vm;
89
90cfg_if! {
91    if #[cfg(feature = "multi-thread")] {
92        pub mod threaded;
93    }
94}
95
96cfg_if! {
97    if #[cfg(target_arch = "wasm32")] {
98        pub mod wasm;
99    }
100}
101
102pub use architecture::{
103    EngineOwnership, EngineRole, CANONICAL_ENGINE, CROSS_TARGET_CONTRACT, ENGINE_OWNERSHIP,
104    EQUIVALENCE_SURFACES,
105};
106pub use bridge::{
107    EffectGuardBridge, IdentityGuardBridge, IdentityPersistenceBridge, IdentityVerificationBridge,
108    PersistenceEffectBridge,
109};
110pub use clock::SimClock;
111pub use communication_replay::{
112    CommunicationConsumeResult, CommunicationConsumption, CommunicationConsumptionArtifact,
113    CommunicationIdentity, CommunicationReplayError, CommunicationReplayMode,
114    CommunicationReplayState, CommunicationStepKind, DefaultCommunicationConsumption,
115    COMM_IDENTITY_DOMAIN_TAG, COMM_REPLAY_DUPLICATE_TAG, COMM_REPLAY_SEQUENCE_MISMATCH_TAG,
116};
117pub use composition::{
118    ComposedRuntime, CompositionCertificate, CompositionError, DeterminismCapability, MemoryBudget,
119    MemoryUsage, ProtocolBundle, SchedulerCapability, TheoremPackCapabilities,
120};
121pub use coroutine::{CoroStatus, Coroutine, CoroutineState, KnowledgeSet, Value};
122pub use determinism::{DeterminismMode, EffectDeterminismTier};
123pub use driver::NativeSingleThreadDriver;
124pub use effect::{
125    send_fast_path_key, CorruptionType, EffectFailure, EffectFailureKind, EffectResult,
126    EffectTraceEntry, EffectTraceTape, RecordingEffectHandler, ReplayEffectHandler,
127    SendDecisionFastPathInput, SendPayloadKind, TopologyPerturbation,
128};
129pub use envelope_diff::{
130    EffectOrderingClass, EnvelopeDiff, EnvelopeDiffArtifactV1, FailureVisibleDiffClass,
131    SchedulerPermutationClass, WaveWidthBound,
132};
133pub use exec_api::{ExecResult, ExecStatus, StepEvent, StepPack};
134pub use faults::{classify_fault, fault_code, fault_code_of, FaultClass};
135pub use guard::{GuardLayer, InMemoryGuardLayer, LayerId};
136pub use identity::{IdentityModel, ParticipantId, SiteId as IdentitySiteId, StaticIdentityModel};
137pub use instr::Instr;
138pub use integration::{run_loaded_vm_record_replay_conformance, LoadedVmReplayConformance};
139pub use intern::{EdgeId, EdgeSymbol, EdgeSymbolTable, StringId, SymbolTable};
140pub use kernel::VMKernel;
141pub use nested::NestedVMHandler;
142pub use output_condition::{
143    verify_output_condition, OutputConditionCheck, OutputConditionHint, OutputConditionMeta,
144    OutputConditionPolicy,
145};
146pub use owned::OwnedSession;
147pub use persistence::{NoopPersistence, PersistenceModel};
148pub use runtime_contracts::{
149    admit_vm_runtime, determinism_profile_supported, enforce_vm_runtime_gates,
150    request_determinism_profile, requires_vm_runtime_contracts, runtime_capability_snapshot,
151    DeterminismArtifacts, RuntimeAdmissionResult, RuntimeContracts, RuntimeGateResult,
152};
153pub use scheduler::{
154    CrossLaneHandoff, LaneId as SchedulerLaneId, PriorityPolicy, SchedPolicy, SchedState,
155    Scheduler, StepUpdate,
156};
157pub use serialization::{
158    canonical_effect_trace, canonical_replay_fragment_v1, canonical_semantic_audit_log,
159    canonical_trace_v1, semantic_audit_log_v1, CanonicalReplayFragmentV1, CanonicalTraceV1,
160    SemanticAuditRecord,
161};
162pub use session::{
163    decode_edge_json, AuthorityArtifact, AuthorityAuditEvent, AuthorityAuditRecord,
164    AuthorityWitnessId, CancellationWitness, ClosedSessionSummary, Edge, FragmentOwnerId,
165    HandlerId, OwnershipCapability, OwnershipClaimId, OwnershipEpoch, OwnershipError,
166    OwnershipReceipt, OwnershipScope, OwnershipTerminalReason, ReadinessWitness,
167    SessionHostMutation, SessionId, SessionStore, SessionStoreMemoryUsage,
168    SessionStoreRetainedBytes, TimeoutWitness,
169};
170pub use trace::{
171    normalize_trace, normalize_trace_v1, obs_session, strict_trace, with_tick, NormalizedTraceV1,
172    TRACE_NORMALIZATION_SCHEMA_VERSION,
173};
174pub use transfer_semantics::{
175    decode_transfer_request, delegation_receipt, delegation_scope_for_endpoint,
176    move_endpoint_bundle, validate_delegation_coherence, DelegationAuditRecord, DelegationReceipt,
177    DelegationStatus, TransferRequest,
178};
179pub use verification::{
180    signValue, sign_value, verifySignedValue, verify_signed_value, AuthProof, AuthTree, Commitment,
181    DefaultVerificationModel, Hash, HashTag, Nullifier, Signature, SigningKey, VerificationModel,
182    VerifyingKey,
183};
184pub use vm::{
185    EffectTraceCaptureMode, MonitorMode, ObservabilityRetentionConfig, ObservabilityRetentionMode,
186    PayloadValidationMode, Program, ProgramStore, RuntimeTuningProfile, SchedExecStatus,
187    SchedStepDebug, ThreadedRoundSemantics, VMConfig, VMState, VmMemoryUsage, VmRetainedBytes, VM,
188};
189
190cfg_if! {
191    if #[cfg(feature = "multi-thread")] {
192        pub use driver::NativeThreadedDriver;
193        pub use threaded::{
194            ContentionMetrics, LaneHandoff, LaneId, LaneSchedulerState, LaneSelection, ThreadedVM,
195        };
196    }
197}
198
199cfg_if! {
200    if #[cfg(target_arch = "wasm32")] {
201        pub use wasm::WasmVM;
202    }
203}