This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: wasi-02-linear-memory-hard-cap-invariant

WASI 0.2 Component Model Linear Memory Hard-Cap and Resource Limiter Invariant

Enforces strict per-instance linear memory allocation ceilings and deterministic trap semantics for multi-tenant WASI 0.2 components. Prevents untrusted guest code from exhausting host memory by mandating explicit Store-level ResourceLimiter configurations and bounded canonical ABI reallocations.

Prohibited Anti-Pattern: Unbounded Wasm Instance Growth via Default Store Allocation and Missing ResourceLimiter Traps

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WASI 0.2 Component Model Linear Memory Hard-Cap and Resource Limiter Invariant - Enforces strict per-instance linear memory allocation ceilings and deterministic trap semantics for multi-tenant WASI 0.2 components. Prevents untrusted guest code from exhausting host memory by mandating explicit Store-level ResourceLimiter configurations and bounded canonical ABI reallocations.
globs: src/**/*.rs, crates/**/*.rs, src/wasm/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/wasi-02-linear-memory-hard-cap-invariant"
---

# WASI 0.2 Component Model Linear Memory Hard-Cap and Resource Limiter Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Wasm Instance Growth via Default Store Allocation and Missing ResourceLimiter Traps

## System Constraints
You are a Principal Systems Architect enforcing WASI 0.2 Component Model memory isolation standards. You must mandate that every WebAssembly component instantiation explicitly attaches a hard memory ceiling via StoreLimits or ResourceLimiter. Never permit instantiation of untrusted components against default, unconstrained host stores. Ensure canonical ABI allocations trap deterministically upon exceeding memory limits.

## Strict Guidelines
- Engineers MUST ALWAYS attach an explicit `ResourceLimiter` or `StoreLimits` implementation to every `wasmtime::Store<T>` hosting untrusted guest components.
- Engineers MUST NOT initialize WASI 0.2 components using default unbounded memory configurations (`Store::default()` or unconstrained `Config::new()`).
- Engines MUST configure `StoreLimitsBuilder::new().memory_size(...)` to an absolute, non-negotiable byte quota per tenant instance.
- Host bindings MUST handle memory growth exhaustion deterministically by capturing memory-exhaustion traps without terminating the parent host daemon.
- Components NEVER share linear memories across tenant boundaries; each guest execution MUST run within an isolated component instance with dedicated linear memory tables.
- Engineers SHOULD set pooling allocator slot limits (`InstanceLimits::total_memories`) matching maximum tenant concurrency to prevent OS page fragmentation.

## Bad vs Good Implementations
### WASI 0.2 Host Component Instantiation Memory Protection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Wasm store lacks a ResourceLimiter or StoreLimits attachment. When an untrusted WASI 0.2 component allocates dynamically or invokes canonical ABI reallocations, it can expand linear memory until the host OS runs out of physical memory and kills the process.
```rust
use wasmtime::component::{Component, Linker};
use wasmtime::{Config, Engine, Store};
use wasmtime_wasi::WasiCtxBuilder;

pub struct HostState {
    pub wasi_ctx: wasmtime_wasi::WasiCtx,
}

pub fn instantiate_untrusted(engine: &Engine, component: &Component) -> anyhow::Result<()> {
    let wasi = WasiCtxBuilder::new().inherit_stdout().build();
    let state = HostState { wasi_ctx: wasi };

    // ANTI-PATTERN: Store is created without a ResourceLimiter.
    // The untrusted component can execute `memory.grow` up to 4GB,
    // risking host OOM-kill and noisy-neighbor exhaustion.
    let mut store = Store::new(engine, state);
    let linker = Linker::new(engine);
    
    let _instance = linker.instantiate(&mut store, component)?;
    Ok(())
}
```

#### Production Standard (Correct)
> **Standard**: Implements `wasmtime::ResourceLimiter` on the host store context, backed by `StoreLimitsBuilder`. Calls to `memory.grow` beyond `max_memory_bytes` immediately fail or trap deterministically within the sandbox, insulating host resources.
```rust
use wasmtime::component::{Component, Linker};
use wasmtime::{Config, Engine, ResourceLimiter, Store, StoreLimits, StoreLimitsBuilder};
use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiView};

pub struct TenantHostState {
    pub wasi_ctx: WasiCtx,
    pub limits: StoreLimits,
}

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

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

pub fn instantiate_sandboxed(engine: &Engine, component: &Component, max_memory_bytes: usize) -> anyhow::Result<()> {
    let wasi = WasiCtxBuilder::new().inherit_stdout().build();
    
    // PRODUCTION INVARIANT: Hard ceiling on linear memory and tables.
    let limits = StoreLimitsBuilder::new()
        .memory_size(max_memory_bytes)
        .instances(1)
        .tables(10)
        .build();

    let state = TenantHostState { wasi_ctx: wasi, limits };
    let mut store = Store::new(engine, state);
    store.limiter(|s| s);

    let linker = Linker::new(engine);
    let _instance = linker.instantiate(&mut store, component)?;
    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 Linear Memory Hard-Cap and Resource Limiter Invariant

WASI 0.2 Component Model Linear Memory Hard-Cap and Resource Limiter Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict per-instance linear memory allocation ceilings and deterministic trap semantics for multi-tenant WASI 0.2 components. Prevents untrusted guest code from exhausting host memory by mandating explicit Store-level ResourceLimiter configurations and bounded canonical ABI reallocations. 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: Unbounded Wasm Instance Growth via Default Store Allocation and Missing ResourceLimiter Traps 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 DriftUnbounded Wasm Instance Growth via Default Store Allocation and Missing ResourceLimiter TrapsCritical
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 attach an explicit `ResourceLimiter` or `StoreLimits` implementation to every `wasmtime

Engineers MUST ALWAYS attach an explicit `ResourceLimiter` or `StoreLimits` implementation to every `wasmtime::Store<T>` hosting untrusted 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.
2

Engineers MUST NOT initialize WASI 0.2 components using default unbounded memory configurations (`Store

Engineers MUST NOT initialize WASI 0.2 components using default unbounded memory configurations (`Store::default()` or unconstrained `Config::new()`).

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

Engines MUST configure `StoreLimitsBuilder

Engines MUST configure `StoreLimitsBuilder::new().memory_size(...)` to an absolute, non-negotiable byte quota per tenant instance.

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

Host bindings MUST handle memory growth exhaustion deterministically by capturing memory-exhaustion traps without terminating the parent host daemon.

Host bindings MUST handle memory growth exhaustion deterministically by capturing memory-exhaustion traps without terminating the parent host daemon.

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 share linear memories across tenant boundaries

Components NEVER share linear memories across tenant boundaries; each guest execution MUST run within an isolated component instance with dedicated linear memory tables.

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

Engineers SHOULD set pooling allocator slot limits (`InstanceLimits

Engineers SHOULD set pooling allocator slot limits (`InstanceLimits::total_memories`) matching maximum tenant concurrency to prevent OS page fragmentation.

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 Linear Memory Hard-Cap and Resource Limiter Invariant critical for AI coding assistants?

Enforces strict per-instance linear memory allocation ceilings and deterministic trap semantics for multi-tenant WASI 0.2 components. Prevents untrusted guest code from exhausting host memory by mandating explicit Store-level ResourceLimiter configurations and bounded canonical ABI reallocations. 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 (Unbounded Wasm Instance Growth via Default Store Allocation and Missing ResourceLimiter Traps) 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