Overview
The execution environment implementation is located inrs/execution_environment/ and provides:
- Canister Execution: WebAssembly-based smart contract execution
- Message Routing: Routing messages to and from canisters
- Scheduler: Fair, deterministic scheduling across canisters
- Hypervisor: Sandboxed Wasm runtime with system API
- Cycles Management: Resource accounting and payment
- Ingress Filtering: Input validation for user messages
Architecture
Source Code Structure
Execution Services
Fromrs/execution_environment/src/lib.rs:86, the execution environment exports public services:
Message Routing
Message Routing coordinates message flow between consensus and execution:Message Flow
Responsibilities
Fromrs/messaging/src/message_routing.rs:8:
- Receive finalized batches from consensus
- Load replicated state at batch height
- Induct XNet messages from other subnets
- Route ingress messages to canisters
- Trigger scheduler execution
- Commit updated state
- Generate execution summaries
rs/messaging/
Scheduler
The scheduler manages fair execution across canisters within a round.Scheduler Implementation
Fromrs/execution_environment/src/scheduler.rs:139:
Round Limits
Fromrs/execution_environment/src/scheduler.rs:75:
- Bounded execution time per round
- Fair resource distribution
- Memory availability
- Callback quota management
Scheduling Algorithm
Subnet Messages
Execute subnet messages first (limited by
SUBNET_MESSAGES_LIMIT_FRACTION from line 71)Fair Scheduling
The scheduler ensures fairness through:- Compute Allocation: Reserved execution time per canister
- Round-Robin: Equal opportunity for all canisters
- Priority Levels: Higher priority for critical operations
- Backpressure: Queue limits prevent resource exhaustion
Hypervisor
The Hypervisor provides the WebAssembly runtime environment.Hypervisor Structure
Fromrs/execution_environment/src/hypervisor.rs:115:
WebAssembly Execution
Wasm Execution Flow
Wasm Execution Flow
- Module Loading: Load canister Wasm module
- Compilation: JIT compile to native code (cached)
- Instrumentation: Inject metering and safety checks
- Instantiation: Create Wasm instance with memory
- Execution: Run method with instruction limits
- Metering: Track instruction and memory usage
- Result: Return output or trap
Compilation and Caching
Fromrs/execution_environment/src/hypervisor.rs:5:
- Compilation Cache: Reuse compiled code across executions
- Lazy Compilation: Compile on first use
- Compilation Costs: Charged to canisters (line 149)
- Validation: Ensure Wasm safety before compilation
rs/embedders/
System API
The System API provides canisters access to IC capabilities:Messaging
Send/receive inter-canister messages
State
Access stable memory and heap
Crypto
Cryptographic operations (hash, sign)
Management
Canister lifecycle operations
Time
Access current timestamp
Random
Get deterministic randomness
Cycles
Query and transfer cycles
HTTP
Make HTTPS outcalls
rs/embedders/src/wasmtime_embedder/system_api/
Sandboxing
For security, canister execution is sandboxed:- Process Isolation: Separate OS process per canister
- Resource Limits: CPU, memory, and instruction bounds
- System Call Filtering: Only allowed syscalls permitted
- Capability-based: Explicit permissions required
rs/canister_sandbox/
Canister Lifecycle
The Canister Manager handles canister lifecycle operations.Lifecycle States
Management Canister API
Fromrs/execution_environment/Contributing.md:1, the Management Canister provides:
install_code: Install Wasm module in canisterinstall_chunked_code: Install large modules in chunksuninstall_code: Remove code from canisterstart_canister: Resume canister executionstop_canister: Pause canister executioncanister_status: Query canister statusdelete_canister: Permanently delete canisterupdate_settings: Change canister settingscreate_canister: Allocate new canister ID
Installation Process
Location:
rs/execution_environment/src/execution/install_code.rs
Query Execution
Queries are read-only operations that don’t go through consensus.Query Types
Fromrs/execution_environment/src/lib.rs:60:
Query Handler
Queries are processed by the Query Handler:- No consensus: Executed locally without consensus
- Read-only: Cannot modify state
- Fast: Millisecond response times
- Eventually consistent: May return stale state
rs/execution_environment/src/query_handler.rs
Cycles and Resource Management
The Internet Computer uses a cycles model for resource accounting.Cycles Account Manager
Fromrs/execution_environment/src/lib.rs:88:
rs/cycles_account_manager/
Resource Costs
Canisters pay cycles for:- Execution: Per instruction executed
- Storage: Per byte of memory over time
- Network: Per byte of messages sent
- Compilation: One-time cost for Wasm compilation
See
rs/execution_environment/EXECUTION_COST.md for detailed cost model.Cycles Operations
- Charging: Deduct cycles before operations
- Refunds: Return unused cycles
- Transfers: Send cycles with inter-canister calls
- Minting: Controllers can add cycles
- Burning: Unused cycles are burned
Memory Limits
Memory allocation is tracked and limited:- Wasm Memory: Canister heap
- Stable Memory: Persistent storage
- Message Memory: Queues and messages
- Subnet Memory: Total available across subnet
Ingress Filtering
Ingress messages are filtered before execution:Filter Checks
Ingress Filter Validations
Ingress Filter Validations
- Signature Verification: Validate sender signature
- Expiry Check: Ensure message not expired
- Canister Status: Verify canister is running
- Method Permissions: Check method accessibility
- Rate Limiting: Prevent spam
- Cycles Balance: Ensure sufficient cycles
rs/execution_environment/src/ingress_filter.rs
Ingress History
Ingress history tracks message execution status:Received: Message acceptedProcessing: Under executionCompleted: Successfully executedFailed: Execution failedDone: Final state (pruned after TTL)
rs/execution_environment/src/history.rs
Determinism
Determinism mechanisms:Deterministic Randomness
Randomness comes from consensus Random Tape:- Generated via threshold signatures
- Identical across all replicas
- Unpredictable before generation
Instruction Metering
Precise instruction counting ensures:- Identical execution limits
- Fair resource allocation
- Reproducible execution
Controlled Time
Timestamps come from consensus:- Fixed per batch
- No wall-clock dependency
- Monotonically increasing
Floating Point
WebAssembly floating-point is deterministic:- IEEE 754 compliance
- Consistent rounding modes
- No NaN payload variation
Performance Optimizations
Parallel Execution
Fromrs/execution_environment/src/scheduler.rs:149:
- No message dependencies
- Sufficient resources
- Multiple cores available
Copy-on-Write Memory
Query execution uses CoW memory:- Queries don’t copy full memory
- Writes create private copies
- Reduces memory overhead
rs/execution_environment/src/lib.rs:57:
Compilation Caching
Compiled Wasm is cached:- In-memory cache (LRU)
- Persistent disk cache
- Shared across executions
- Bounded size (
MAX_COMPILATION_CACHE_SIZE)
Testing
Test Frameworks
Fromrs/execution_environment/Contributing.md:41:
ExecutionTest: Default framework for unit tests
- Fast, lightweight
- Mocked dependencies
- Direct component testing
- Full consensus simulation
- Inter-canister calls
- State manager integration
- Checkpointing
rs/execution_environment/tests/
Benchmarks
Performance benchmarks measure:- System API call overhead
- Wasm execution speed
- Compilation time
- Scheduler throughput
rs/execution_environment/benches/
Integration Points
Consensus
Receives finalized batches for execution:State Manager
Loads and commits replicated state:Registry
Reads execution settings:Crypto
Threshold signatures and randomness:Best Practices
Use feature flags for experimental APIs and roll out gradually via feature releases (Contributing.md:39)
Further Reading
Replica
Understand replica structure
Consensus
Learn about batch finalization
Networking
Explore message transport
Overview
Return to architecture overview