This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: wasi-02-component-memory-fence-production-standard

WASI 0.2 Canonical ABI Sandboxed Memory Boundary and Resource Fencing

Enforces strict memory isolation, resource pooling, and typed WIT (WebAssembly Interface Type) boundaries between host microservices and untrusted multi-tenant WASI 0.2 components. Prohibits direct linear memory pointer passing, unbounded host store growth, and out-of-band memory mutation across tenant contexts. Mandates deterministic memory caps, reentrancy guards, and epoch-based engine preemption.

Prohibited Anti-Pattern: Bypassing WIT Canonical ABI via Raw Pointer Offsets and Shared Unbounded Stores

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WASI 0.2 Canonical ABI Sandboxed Memory Boundary and Resource Fencing - Enforces strict memory isolation, resource pooling, and typed WIT (WebAssembly Interface Type) boundaries between host microservices and untrusted multi-tenant WASI 0.2 components. Prohibits direct linear memory pointer passing, unbounded host store growth, and out-of-band memory mutation across tenant contexts. Mandates deterministic memory caps, reentrancy guards, and epoch-based engine preemption.
globs: src/**/*.{rs,ts,go,cpp}, wit/**/*.wit, deploy/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/wasi-02-component-memory-fence-production-standard"
---

# WASI 0.2 Canonical ABI Sandboxed Memory Boundary and Resource Fencing

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Bypassing WIT Canonical ABI via Raw Pointer Offsets and Shared Unbounded Stores

## System Constraints
You are a Principal Systems and Security Architect enforcing WASI 0.2 Component Model Sandboxed Linear Memory Fences. Mandate strict adherence to the Canonical ABI, deterministic memory pooling, instance isolation, and typed resource lifecycles. Forbid manual pointer arithmetic into guest linear memory, shared state across multi-tenant component instantiations, and unmonitored host-allocated buffers.

## Strict Guidelines
- Engineers MUST ALWAYS exchange data across host and guest runtimes strictly using typed WIT interfaces lowered through the WASI 0.2 Canonical ABI.
- Engineers MUST NOT bypass the Canonical ABI by passing raw guest linear memory pointer offsets or raw buffer addresses into host FFI functions.
- Services MUST instantiate isolated Wasmtime/WASI Stores per tenant invocation, configuring deterministic StoreLimits (max memory allocation, table elements) to prevent cross-tenant exhaustion attacks.
- Engineers MUST ALWAYS configure Epoch Interruption or gas metering on the host engine to preemptively abort infinite loops and rogue memory allocations inside guest components.
- Components NEVER retain or access raw host memory; all transfers of binary data MUST rely on Canonical ABI copy semantics or explicit host-brokered resource handles with deterministic destructors.
- Code SHOULD leverage zero-copy string and list transfer semantics strictly as codified by Canonical ABI lifting/lowering specifications and avoid custom serializations over raw WASM linear memory.
- Hosts MUST enforce explicit pool-allocator backing for linear memory, reclaiming or zeroing pages immediately upon guest instance teardown.

## Bad vs Good Implementations
### Unsafe Raw Guest Pointer Dereference vs Canonical ABI WIT Binding with StoreLimits

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Bypasses the WASI 0.2 Component Model by accessing raw linear memory offsets (`guest_ptr`, `len`). Lacks boundary validation, resource limits, and epoch interruption, enabling out-of-bounds reads and host memory exhaustion.
```rust
use wasmtime::*;

// ANTI-PATTERN: Direct linear memory slicing bypassing Canonical ABI, unbounded store
fn execute_untrusted_plugin(engine: &Engine, wasm_bytes: &[u8], guest_ptr: u32, len: u32) -> Result<String, anyhow::Error> {
    let module = Module::new(engine, wasm_bytes)?;
    let mut store = Store::new(engine, ()); // No limits: guest can allocate host OOM
    let instance = Instance::new(&mut store, &module, &[])?;
    let memory = instance.get_memory(&mut store, "memory")
        .ok_or_else(|| anyhow::anyhow!("missing memory"))?;

    // CRITICAL: Unchecked pointer dereference, susceptible to OOB read, data-race, or stale pointers
    let data = memory.data(&store);
    let slice = &data[guest_ptr as usize..(guest_ptr + len) as usize];
    Ok(String::from_utf8(slice.to_vec())?)
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes the WASI 0.2 Component Model bindgen! macro to enforce Canonical ABI boundaries. Sets hard linear memory caps (64MB) via StoreLimits, attaches epoch preemption, and guarantees isolated address space instantiation.
```rust
use wasmtime::component::*;
use wasmtime::{Engine, Store, StoreLimits, StoreLimitsBuilder};

struct HostState {
    limits: StoreLimits,
}

// PRODUCTION FIX: Explicit Component Model with WIT-bound interface and memory sandbox fencing
bindgen!({
    world: "tenant-processor",
    inline: "package tenant:processor; world tenant-processor { import process-payload: func(payload: list<u8>) -> result<string, string>; }"
});

fn execute_sandboxed_component(engine: &Engine, component_bytes: &[u8], input: &[u8]) -> Result<String, anyhow::Error> {
    let component = Component::from_binary(engine, component_bytes)?;
    let mut linker = Linker::new(engine);
    wasmtime_wasi::add_to_linker_sync(&mut linker)?;

    let state = HostState {
        limits: StoreLimitsBuilder::new()
            .memory_size(64 * 1024 * 1024) // 64 MB maximum linear memory fence
            .instances(1)
            .tables(5)
            .build(),
    };

    let mut store = Store::new(engine, state);
    store.limiter(|s| &mut s.limits);
    store.set_epoch_deadline(5); // Preempts runaway CPU/allocation cycles

    let (processor, _) = TenantProcessor::instantiate(&mut store, &component, &linker)?;
    let result = processor.call_process_payload(&mut store, input)?
        .map_err(|e| anyhow::anyhow!("Component failed: {e}"))?;

    Ok(result)
}
```

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 Canonical ABI Sandboxed Memory Boundary and Resource Fencing

WASI 0.2 Canonical ABI Sandboxed Memory Boundary and Resource Fencing defines an industrial-grade behavioral standard for devops engineering. Enforces strict memory isolation, resource pooling, and typed WIT (WebAssembly Interface Type) boundaries between host microservices and untrusted multi-tenant WASI 0.2 components. Prohibits direct linear memory pointer passing, unbounded host store growth, and out-of-band memory mutation across tenant contexts. Mandates deterministic memory caps, reentrancy guards, and epoch-based engine preemption. 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: Bypassing WIT Canonical ABI via Raw Pointer Offsets and Shared Unbounded Stores 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 DriftBypassing WIT Canonical ABI via Raw Pointer Offsets and Shared Unbounded StoresCritical
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 exchange data across host and guest runtimes strictly using typed WIT interfaces lowered through the WASI 0.2 Canonical ABI.

Engineers MUST ALWAYS exchange data across host and guest runtimes strictly using typed WIT interfaces lowered through the WASI 0.2 Canonical ABI.

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 NOT bypass the Canonical ABI by passing raw guest linear memory pointer offsets or raw buffer addresses into host FFI functions.

Engineers MUST NOT bypass the Canonical ABI by passing raw guest linear memory pointer offsets or raw buffer addresses into host FFI functions.

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

Services MUST instantiate isolated Wasmtime/WASI Stores per tenant invocation, configuring deterministic StoreLimits (max memory allocation, table elements) to prevent cross-tenant exhaustion attacks.

Services MUST instantiate isolated Wasmtime/WASI Stores per tenant invocation, configuring deterministic StoreLimits (max memory allocation, table elements) to prevent cross-tenant exhaustion attacks.

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

Engineers MUST ALWAYS configure Epoch Interruption or gas metering on the host engine to preemptively abort infinite loops and rogue memory allocations inside guest components.

Engineers MUST ALWAYS configure Epoch Interruption or gas metering on the host engine to preemptively abort infinite loops and rogue memory allocations inside guest components.

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 retain or access raw host memory

Components NEVER retain or access raw host memory; all transfers of binary data MUST rely on Canonical ABI copy semantics or explicit host-brokered resource handles with deterministic destructors.

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.
6

Code SHOULD leverage zero-copy string and list transfer semantics strictly as codified by Canonical ABI lifting/lowering specifications and avoid custom serializations over raw WASM linear memory.

Code SHOULD leverage zero-copy string and list transfer semantics strictly as codified by Canonical ABI lifting/lowering specifications and avoid custom serializations over raw WASM linear memory.

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.
7

Hosts MUST enforce explicit pool-allocator backing for linear memory, reclaiming or zeroing pages immediately upon guest instance teardown.

Hosts MUST enforce explicit pool-allocator backing for linear memory, reclaiming or zeroing pages immediately upon guest instance teardown.

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 Canonical ABI Sandboxed Memory Boundary and Resource Fencing critical for AI coding assistants?

Enforces strict memory isolation, resource pooling, and typed WIT (WebAssembly Interface Type) boundaries between host microservices and untrusted multi-tenant WASI 0.2 components. Prohibits direct linear memory pointer passing, unbounded host store growth, and out-of-band memory mutation across tenant contexts. Mandates deterministic memory caps, reentrancy guards, and epoch-based engine preemption. 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 (Bypassing WIT Canonical ABI via Raw Pointer Offsets and Shared Unbounded Stores) 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