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::{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 sid = vm.load_choreography(image, &handler)?;
44//! while vm.step(&handler)? {}
45//! ```
46
47use cfg_if::cfg_if;
48
49pub mod architecture;
50pub mod backend;
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 persistence;
79pub mod runtime_contracts;
80pub mod scheduler;
81pub mod serialization;
82/// Session store and role/session bookkeeping used by protocol execution.
83pub mod session;
84pub mod trace;
85pub mod transfer_semantics;
86pub mod verification;
87pub mod vm;
88
89cfg_if! {
90    if #[cfg(feature = "multi-thread")] {
91        pub mod threaded;
92    }
93}
94
95cfg_if! {
96    if #[cfg(target_arch = "wasm32")] {
97        pub mod wasm;
98    }
99}
100
101pub use architecture::{
102    EngineOwnership, EngineRole, CANONICAL_ENGINE, CROSS_TARGET_CONTRACT, ENGINE_OWNERSHIP,
103    EQUIVALENCE_SURFACES,
104};
105pub use backend::VMBackend;
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    classify_effect_error, classify_effect_error_owned, send_fast_path_key, CorruptionType,
126    EffectError, EffectErrorCategory, EffectTraceEntry, EffectTraceTape, RecordingEffectHandler,
127    ReplayEffectHandler, 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 persistence::{NoopPersistence, PersistenceModel};
147pub use runtime_contracts::{
148    admit_vm_runtime, determinism_profile_supported, enforce_vm_runtime_gates,
149    request_determinism_profile, requires_vm_runtime_contracts, runtime_capability_snapshot,
150    DeterminismArtifacts, RuntimeAdmissionResult, RuntimeContracts, RuntimeGateResult,
151};
152pub use scheduler::{
153    CrossLaneHandoff, LaneId as SchedulerLaneId, PriorityPolicy, SchedPolicy, SchedState,
154    Scheduler, StepUpdate,
155};
156pub use serialization::{
157    canonical_effect_trace, canonical_replay_fragment_v1, canonical_trace_v1,
158    CanonicalReplayFragmentV1, CanonicalTraceV1,
159};
160pub use session::{
161    decode_edge_json, ClosedSessionSummary, Edge, HandlerId, SessionId, SessionStore,
162    SessionStoreMemoryUsage, SessionStoreRetainedBytes,
163};
164pub use trace::{
165    normalize_trace, normalize_trace_v1, obs_session, strict_trace, with_tick, NormalizedTraceV1,
166    TRACE_NORMALIZATION_SCHEMA_VERSION,
167};
168pub use transfer_semantics::{decode_transfer_request, move_endpoint_bundle, TransferRequest};
169pub use verification::{
170    signValue, sign_value, verifySignedValue, verify_signed_value, AuthProof, AuthTree, Commitment,
171    DefaultVerificationModel, Hash, HashTag, Nullifier, Signature, SigningKey, VerificationModel,
172    VerifyingKey,
173};
174pub use vm::{
175    EffectTraceCaptureMode, MonitorMode, ObservabilityRetentionConfig, ObservabilityRetentionMode,
176    PayloadValidationMode, Program, ProgramStore, RuntimeTuningProfile, SchedExecStatus,
177    SchedStepDebug, ThreadedRoundSemantics, VMConfig, VMState, VmMemoryUsage, VmRetainedBytes, VM,
178};
179
180cfg_if! {
181    if #[cfg(feature = "multi-thread")] {
182        pub use driver::NativeThreadedDriver;
183        pub use threaded::{
184            ContentionMetrics, LaneHandoff, LaneId, LaneSchedulerState, LaneSelection, ThreadedVM,
185        };
186    }
187}
188
189cfg_if! {
190    if #[cfg(target_arch = "wasm32")] {
191        pub use wasm::WasmVM;
192    }
193}