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

WASI 0.2 Canonical ABI Boundary Memory Governor & Deterministic Resource Lifecycle Enforcement

Enforces strict linear memory quotas, deterministic post-return deallocations, and ResourceTable lifecycle boundaries between polyglot WebAssembly 0.2 component guests. Guarantees that Canonical ABI lowering allocations trigger corresponding post-return hooks and that linear memory growth is strictly bounded to prevent heap exhaustion in high-density serverless execution contexts.

Prohibited Anti-Pattern: Bypassing cabi_post_* Cleanup and Omitting Host StoreLimits in Polyglot WASI 0.2 Guest Invocations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WASI 0.2 Canonical ABI Boundary Memory Governor & Deterministic Resource Lifecycle Enforcement - Enforces strict linear memory quotas, deterministic post-return deallocations, and ResourceTable lifecycle boundaries between polyglot WebAssembly 0.2 component guests. Guarantees that Canonical ABI lowering allocations trigger corresponding post-return hooks and that linear memory growth is strictly bounded to prevent heap exhaustion in high-density serverless execution contexts.
globs: crates/**/*.rs, src/**/*.rs, runtime/**/*.rs, src/**/*.{js,ts}, wit/**/*.wit
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/wasi-02-canonical-abi-memory-governor"
---

# WASI 0.2 Canonical ABI Boundary Memory Governor & Deterministic Resource Lifecycle Enforcement

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Bypassing cabi_post_* Cleanup and Omitting Host StoreLimits in Polyglot WASI 0.2 Guest Invocations

## System Constraints
You are a Principal Systems Architect enforcing WASI 0.2 Component Model Canonical ABI Boundary Memory Governor invariants. Mandate strict linear memory allocation bounds, explicit ResourceTable lifecycle management, deterministic invocation of `post_return` (cabi_post_*) handlers for lowered data structures, and isolation boundaries between guest components to eradicate cross-tenant memory leaks.

## Strict Guidelines
- Host runtimes MUST ALWAYS configure explicit StoreLimits (or engine memory governors) restricting total memory growth and table elements per guest component store.
- Host callers MUST ALWAYS invoke TypedFunc::post_return (or cabi_post_* handlers) immediately after consuming lifted strings, lists, or compound values from component calls.
- Engineers MUST NEVER transfer unmanaged guest linear memory pointers across ABI boundaries; all stateful cross-component references MUST use WIT resource handles backed by a managed ResourceTable.
- Polyglot guest components MUST NOT rely on host garbage collection for linear memory reclamation; WIT interfaces MUST specify explicit borrowing (`borrow<T>`) rather than passing owned buffers whenever read-only semantics suffice.
- Host execution pipelines MUST trap and terminate component instances instantly upon any out-of-bounds Canonical ABI reallocation failure (`realloc` returning null/0 in linear memory).

## Bad vs Good Implementations
### Wasmtime Component Host Invocation with Canonical ABI Post-Return Lifecycle and StoreLimits

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The store is created without StoreLimits, allowing rogue guest allocations to exhaust host linear memory. Furthermore, failing to invoke `func.post_return()` skips the generated Canonical ABI `cabi_post_*` cleanup function, leaking the guest heap allocation for the returned string on every serverless invocation.
```rust
// Anti-Pattern: Unbounded store limits and bypassed post_return lifecycle leaks guest heap
use wasmtime::component::{Component, Linker};
use wasmtime::{Engine, Store};

pub async fn execute_unbounded_guest(engine: &Engine, component: &Component) -> anyhow::Result<String> {
    // Bypasses memory governor: No StoreLimits configured
    let mut store = Store::new(engine, ());
    let linker = Linker::new(engine);
    let instance = linker.instantiate_async(&mut store, component).await?;

    let func = instance.get_typed_func::<(), (String,)>(&mut store, "process-payload")?;
    let (result,) = func.call_async(&mut store, ()).await?;

    // CRITICAL BUG: Omits func.post_return(&mut store). The guest linear memory
    // allocated for `String` is leaked permanently in the guest heap across subsequent calls.
    Ok(result)
}
```

#### Production Standard (Correct)
> **Standard**: Implements `StoreLimits` via `store.limiter()` to strictly bound linear memory to 16MB. Immediately triggers `post_return_async()`, executing the guest's Canonical ABI deallocator for the returned string and maintaining absolute memory hygiene.
```rust
// Production Standard: Enforced StoreLimits governor and deterministic post_return cleanup
use wasmtime::component::{Component, Linker, ResourceTable};
use wasmtime::{Engine, Store, StoreLimits, StoreLimitsBuilder};

struct HostState {
    limits: StoreLimits,
    table: ResourceTable,
}

impl wasmtime::AsContext for HostState {
    type Data = HostState;
    fn as_context(&self) -> wasmtime::StoreContext<'_, Self::Data> { unimplemented!() }
}

pub async fn execute_governed_guest(engine: &Engine, component: &Component) -> anyhow::Result<String> {
    // 1. Enforce strict linear memory governor: 16MB max linear memory, 10,000 table elements
    let limits = StoreLimitsBuilder::new()
        .memory_size(16 * 1024 * 1024)
        .instances(10)
        .tables(10_000)
        .build();

    let state = HostState { limits, table: ResourceTable::new() };
    let mut store = Store::new(engine, state);
    store.limiter(|s| &mut s.limits);

    let linker = Linker::new(engine);
    let instance = linker.instantiate_async(&mut store, component).await?;
    let func = instance.get_typed_func::<(), (String,)>(&mut store, "process-payload")?;

    // 2. Invoke component function
    let (result,) = func.call_async(&mut store, ()).await?;

    // 3. Deterministically trigger Canonical ABI cabi_post_* cleanup in guest linear memory
    func.post_return_async(&mut store).await?;

    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 Boundary Memory Governor & Deterministic Resource Lifecycle Enforcement

WASI 0.2 Canonical ABI Boundary Memory Governor & Deterministic Resource Lifecycle Enforcement defines an industrial-grade behavioral standard for devops engineering. Enforces strict linear memory quotas, deterministic post-return deallocations, and ResourceTable lifecycle boundaries between polyglot WebAssembly 0.2 component guests. Guarantees that Canonical ABI lowering allocations trigger corresponding post-return hooks and that linear memory growth is strictly bounded to prevent heap exhaustion in high-density serverless execution contexts. 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 cabi_post_* Cleanup and Omitting Host StoreLimits in Polyglot WASI 0.2 Guest Invocations 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 cabi_post_* Cleanup and Omitting Host StoreLimits in Polyglot WASI 0.2 Guest InvocationsCritical
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

Host runtimes MUST ALWAYS configure explicit StoreLimits (or engine memory governors) restricting total memory growth and table elements per guest component store.

Host runtimes MUST ALWAYS configure explicit StoreLimits (or engine memory governors) restricting total memory growth and table elements per guest component store.

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

Host callers MUST ALWAYS invoke TypedFunc

Host callers MUST ALWAYS invoke TypedFunc::post_return (or cabi_post_* handlers) immediately after consuming lifted strings, lists, or compound values from component calls.

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 NEVER transfer unmanaged guest linear memory pointers across ABI boundaries

Engineers MUST NEVER transfer unmanaged guest linear memory pointers across ABI boundaries; all stateful cross-component references MUST use WIT resource handles backed by a managed ResourceTable.

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

Polyglot guest components MUST NOT rely on host garbage collection for linear memory reclamation

Polyglot guest components MUST NOT rely on host garbage collection for linear memory reclamation; WIT interfaces MUST specify explicit borrowing (`borrow<T>`) rather than passing owned buffers whenever read-only semantics suffice.

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

Host execution pipelines MUST trap and terminate component instances instantly upon any out-of-bounds Canonical ABI reallocation failure (`realloc` returning null/0 in linear memory).

Host execution pipelines MUST trap and terminate component instances instantly upon any out-of-bounds Canonical ABI reallocation failure (`realloc` returning null/0 in 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.
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 Boundary Memory Governor & Deterministic Resource Lifecycle Enforcement critical for AI coding assistants?

Enforces strict linear memory quotas, deterministic post-return deallocations, and ResourceTable lifecycle boundaries between polyglot WebAssembly 0.2 component guests. Guarantees that Canonical ABI lowering allocations trigger corresponding post-return hooks and that linear memory growth is strictly bounded to prevent heap exhaustion in high-density serverless execution contexts. 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 cabi_post_* Cleanup and Omitting Host StoreLimits in Polyglot WASI 0.2 Guest Invocations) 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