This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: wasi-component-model-fuel-isolation-invariant

WASI 0.2 Component Model Gas-Metered Sandbox Execution Invariant

Mandates strict per-invocation instruction fuel metering, memory bounds enforcement, and capability-scoped host interfaces for untrusted tenant plugins using the WASI 0.2 Component Model. Prevents denial-of-service vectors, infinite execution loops, and guest heap exhaustion in high-throughput backend services by isolating linear memory and binding execution to deterministic gas limits.

Prohibited Anti-Pattern: Unmetered Shared Store Instantiation with Ambient Host Capabilities

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WASI 0.2 Component Model Gas-Metered Sandbox Execution Invariant - Mandates strict per-invocation instruction fuel metering, memory bounds enforcement, and capability-scoped host interfaces for untrusted tenant plugins using the WASI 0.2 Component Model. Prevents denial-of-service vectors, infinite execution loops, and guest heap exhaustion in high-throughput backend services by isolating linear memory and binding execution to deterministic gas limits.
globs: src/sandbox/**/*.rs, src/plugins/**/*.rs, src/runtime/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/wasi-component-model-fuel-isolation-invariant"
---

# WASI 0.2 Component Model Gas-Metered Sandbox Execution Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unmetered Shared Store Instantiation with Ambient Host Capabilities

## System Constraints
You are a Principal Software Architect specializing in WebAssembly security and the WASI 0.2 Component Model. Enforce strict gas metering (fuel/epoch interruption), per-invocation Store allocation, strict linear memory bounds via StoreLimits, and least-privilege WASI context pre-opens for all untrusted third-party tenant plugin workloads. Reject any code that reuses Stores across tenants, executes guest functions without fuel caps, or leaks ambient host filesystem and network handles.

## Strict Guidelines
- Engineers MUST ALWAYS configure `wasmtime::Config::consume_fuel(true)` or `epoch_interruption(true)` on the shared engine.
- Engineers MUST instantiate a unique `wasmtime::Store<T>` per execution context and explicitly set fuel quotas with `store.set_fuel(quota)` prior to invocation.
- Engineers MUST NOT share `Store` instances or guest memory allocations across concurrent or sequential tenant invocations.
- Services MUST enforce strict memory ceilings using `StoreLimitsBuilder` implementing `ResourceLimiter` to clamp guest heap growth to tenant SLA maximums.
- Components NEVER receive ambient root filesystem or outbound network socket privileges; `WasiCtxBuilder` MUST limit I/O to ephemeral in-memory streams or tenant-isolated directories.

## Bad vs Good Implementations
### WASI 0.2 Component Sandbox Execution with Fuel and Memory Quotas

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The runtime config lacks fuel consumption metering, allowing infinite CPU loop attacks. The Store is instantiated without ResourceLimiter bounds, letting untrusted guests exhaust host virtual memory. Ambient WASI context is omitted or unconstrained.
```rust
use wasmtime::component::{Component, Linker};
use wasmtime::{Config, Engine, Store};
use wasmtime_wasi::WasiCtxBuilder;

pub struct TenantPluginRuntime {
    engine: Engine,
    linker: Linker<()>, // Anti-pattern: Untyped context without limits
}

impl TenantPluginRuntime {
    pub fn new() -> wasmtime::Result<Self> {
        // CRITICAL FLAW: Default config lacks fuel metering and epoch interruption
        let config = Config::new();
        let engine = Engine::new(&config)?;
        let linker = Linker::new(&engine);
        Ok(Self { engine, linker })
    }

    pub fn run_plugin(&self, component: &Component) -> wasmtime::Result<()> {
        // CRITICAL FLAW: Store has no fuel limit and unmetered memory allocation
        let mut store = Store::new(&self.engine, ());
        let instance = self.linker.instantiate(&mut store, component)?;
        let func = instance.get_typed_func::<(), ()>(&mut store, "run")?;
        // Guest can execute an infinite loop or exhaust host RAM
        func.call(&mut store, ())?;
        Ok(())
    }
}
```

#### Production Standard (Correct)
> **Standard**: Enforces determinism by activating `consume_fuel(true)` at engine initialization and setting an explicit per-execution fuel budget. Clamps linear memory to 32MB via `StoreLimitsBuilder`, provides a sandboxed `WasiCtx` without ambient host filesystem privileges, and intercepts out-of-fuel traps.
```rust
use wasmtime::component::{Component, Linker, ResourceLimiter};
use wasmtime::{Config, Engine, Store, StoreLimits, StoreLimitsBuilder};
use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiView};

struct HostState {
    wasi: WasiCtx,
    limits: StoreLimits,
}

impl WasiView for HostState {
    fn ctx(&mut self) -> &mut WasiCtx { &mut self.wasi }
}

impl ResourceLimiter for HostState {
    fn memory_growing(&mut self, current: usize, desired: usize, _maximum: Option<usize>) -> Result<bool, wasmtime::Error> {
        self.limits.memory_growing(current, desired, _maximum)
    }
    fn table_growing(&mut self, current: usize, desired: usize, _maximum: Option<usize>) -> Result<bool, wasmtime::Error> {
        self.limits.table_growing(current, desired, _maximum)
    }
}

pub struct TenantPluginRuntime {
    engine: Engine,
    linker: Linker<HostState>,
}

impl TenantPluginRuntime {
    const FUEL_BUDGET: u64 = 1_000_000;
    const MAX_MEMORY_BYTES: usize = 32 * 1024 * 1024; // 32MB max guest heap

    pub fn new() -> wasmtime::Result<Self> {
        let mut config = Config::new();
        config.wasm_component_model(true);
        config.consume_fuel(true); // Mandatory: gas metering enabled
        
        let engine = Engine::new(&config)?;
        let mut linker = Linker::new(&engine);
        wasmtime_wasi::add_to_linker_sync(&mut linker)?;
        
        Ok(Self { engine, linker })
    }

    pub fn run_plugin(&self, component: &Component) -> wasmtime::Result<()> {
        let wasi = WasiCtxBuilder::new()
            .build(); // Least privilege: no ambient host FS or network
            
        let limits = StoreLimitsBuilder::new()
            .memory_size(Self::MAX_MEMORY_BYTES)
            .build();

        let state = HostState { wasi, limits };
        let mut store = Store::new(&self.engine, state);
        store.limiter(|s| s);
        store.set_fuel(Self::FUEL_BUDGET)?; // Bounded instruction execution

        let instance = self.linker.instantiate(&mut store, component)?;
        let func = instance.get_typed_func::<(), ()>(&mut store, "run")?;
        
        func.call(&mut store, ())
            .map_err(|e| {
                if store.get_fuel().unwrap_or(0) == 0 {
                    wasmtime::Error::msg("Plugin execution exceeded deterministic gas quota (out of fuel)")
                } else {
                    e
                }
            })?;

        Ok(())
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WASI 0.2 Component Model Gas-Metered Sandbox Execution Invariant

WASI 0.2 Component Model Gas-Metered Sandbox Execution Invariant defines an industrial-grade behavioral standard for security engineering. Mandates strict per-invocation instruction fuel metering, memory bounds enforcement, and capability-scoped host interfaces for untrusted tenant plugins using the WASI 0.2 Component Model. Prevents denial-of-service vectors, infinite execution loops, and guest heap exhaustion in high-throughput backend services by isolating linear memory and binding execution to deterministic gas limits. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unmetered Shared Store Instantiation with Ambient Host Capabilities Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnmetered Shared Store Instantiation with Ambient Host CapabilitiesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS configure `wasmtime

Engineers MUST ALWAYS configure `wasmtime::Config::consume_fuel(true)` or `epoch_interruption(true)` on the shared engine.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST instantiate a unique `wasmtime

Engineers MUST instantiate a unique `wasmtime::Store<T>` per execution context and explicitly set fuel quotas with `store.set_fuel(quota)` prior to invocation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST NOT share `Store` instances or guest memory allocations across concurrent or sequential tenant invocations.

Engineers MUST NOT share `Store` instances or guest memory allocations across concurrent or sequential tenant invocations.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST enforce strict memory ceilings using `StoreLimitsBuilder` implementing `ResourceLimiter` to clamp guest heap growth to tenant SLA maximums.

Services MUST enforce strict memory ceilings using `StoreLimitsBuilder` implementing `ResourceLimiter` to clamp guest heap growth to tenant SLA maximums.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER receive ambient root filesystem or outbound network socket privileges

Components NEVER receive ambient root filesystem or outbound network socket privileges; `WasiCtxBuilder` MUST limit I/O to ephemeral in-memory streams or tenant-isolated directories.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is WASI 0.2 Component Model Gas-Metered Sandbox Execution Invariant critical for AI coding assistants?

Mandates strict per-invocation instruction fuel metering, memory bounds enforcement, and capability-scoped host interfaces for untrusted tenant plugins using the WASI 0.2 Component Model. Prevents denial-of-service vectors, infinite execution loops, and guest heap exhaustion in high-throughput backend services by isolating linear memory and binding execution to deterministic gas limits. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unmetered Shared Store Instantiation with Ambient Host Capabilities) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

WASI