This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-chi-wazero-wasm-isolation-boundary

Strict In-Process Wazero WASM Isolation for Multi-Tenant Chi Middleware

Enforces strict memory page ceilings, lifecycle sandboxing, and secure host function boundaries for dynamic request enrichment plugins executed via Wazero in Go 1.24 Chi HTTP pipelines. Prohibits global mutable runtime modules and unbound host function exports to eliminate cross-tenant data bleed and noisy-neighbor OOM panics while preserving zero-IPC performance.

Prohibited Anti-Pattern: Executing Multi-Tenant Plugins on Shared Wazero Module Instances with Unbounded Memory and Raw Pointer Host Exports

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict In-Process Wazero WASM Isolation for Multi-Tenant Chi Middleware - Enforces strict memory page ceilings, lifecycle sandboxing, and secure host function boundaries for dynamic request enrichment plugins executed via Wazero in Go 1.24 Chi HTTP pipelines. Prohibits global mutable runtime modules and unbound host function exports to eliminate cross-tenant data bleed and noisy-neighbor OOM panics while preserving zero-IPC performance.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-wazero-wasm-isolation-boundary"
---

# Strict In-Process Wazero WASM Isolation for Multi-Tenant Chi Middleware

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing Multi-Tenant Plugins on Shared Wazero Module Instances with Unbounded Memory and Raw Pointer Host Exports

## System Constraints
You are a Principal Software Architect enforcing Go 1.24 Chi & Wazero In-Process WASM Isolation Boundaries. Mandate that all multi-tenant plugin invocations use pre-compiled WASM modules instantiated on per-request Chi lifecycles with rigid memory ceilings (MemoryPages min/max). Prohibit sharing runtime instances across goroutines, enforce strict bounds checks when reading/writing to guest memory, and require host functions to validate request-scoped tenant identity prior to performing any context enrichments.

## Strict Guidelines
- Engineers MUST ALWAYS pre-compile WASM modules once using `wazero.Runtime.CompileModule(ctx, wasmCode)` during application boot, never per request.
- Engineers MUST ALWAYS instantiate a distinct `api.Module` per incoming HTTP request using `r.InstantiateModule(ctx, compiled, moduleConfig)` and ensure cleanup via `defer mod.Close(ctx)`.
- Engineers MUST configure hard limits on plugin memory pages using `wazero.NewModuleConfig().WithMemoryPages(min, max)` to guarantee that plugins cannot trigger host OOM panics.
- Engineers MUST NOT expose unrestricted host primitives, file descriptors, or raw system calls to WASM guests; only register dedicated, tenant-scoped Host Modules.
- Host functions reading guest memory MUST ALWAYS validate buffer boundaries using `mod.Memory().Read(offset, byteCount)` and guard against integer overflows.
- Chi middleware MUST propagate `context.WithTimeout` into `InstantiateModule` and plugin function executions to enforce deterministic execution deadlines.
- Components NEVER share mutable state or non-thread-safe Wazero `api.Module` references across concurrent Chi request goroutines.

## Bad vs Good Implementations
### Unsafe Wazero Plugin Execution vs. Sandboxed Chi Middleware Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reusing a single instantiated `api.Module` across concurrent HTTP requests causes race conditions and tenant cross-contamination. Memory is not bounded, meaning a rogue tenant script can allocate unbounded pages and crash the host Go process. No execution timeouts are enforced on guest execution.
```go
package middleware

import (
	"context"
	"net/http"
	"github.com/tetratelabs/wazero"
	"github.com/tetratelabs/wazero/api"
)

// ANTI-PATTERN: Shared global module instance causes concurrent race conditions,
// has unbounded memory growth, and exports unsanitized host memory mutations.
type InsecurePluginRunner struct {
	mod api.Module
}

func (p *InsecurePluginRunner) Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Concurrent invocations mutate shared module state across tenants
		enrichFn := p.mod.ExportedFunction("enrich_request")
		_, err := enrichFn.Call(r.Context(), 0)
		if err != nil {
			http.Error(w, "Plugin execution failed", http.StatusInternalServerError)
			return
		}
		next.ServeHTTP(w, r)
	})
}
```

#### Production Standard (Correct)
> **Standard**: Compiles the WASM binary once at startup and instantiates an ephemeral, strictly isolated `api.Module` per incoming request. Memory is clamped using `WithMemoryPages(1, 10)` to prevent host OOM attacks. Execution is guarded with `context.WithTimeout(..., 15*time.Millisecond)` to prevent rogue infinite loops, and `defer mod.Close(ctx)` guarantees garbage collection.
```go
package middleware

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"time"

	"github.com/tetratelabs/wazero"
	"github.com/tetratelabs/wazero/api"
)

type TenantPluginEngine struct {
	runtime  wazero.Runtime
	compiled wazero.CompiledModule
}

func NewTenantPluginEngine(ctx context.Context, wasmBytes []byte) (*TenantPluginEngine, error) {
	r := wazero.NewRuntime(ctx)
	compiled, err := r.CompileModule(ctx, wasmBytes)
	if err != nil {
		return nil, fmt.Errorf("failed to compile wasm module: %w", err)
	}
	return &TenantPluginEngine{runtime: r, compiled: compiled}, nil
}

func (e *TenantPluginEngine) Middleware(tenantID string) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx, cancel := context.WithTimeout(r.Context(), 15*time.Millisecond)
			defer cancel()

			// Bound memory: 1 page = 64KB. Min: 1 page, Max: 10 pages (640KB limit)
			modConfig := wazero.NewModuleConfig().
				WithName(fmt.Sprintf("tenant-%s-%d", tenantID, time.Now().UnixNano())).
				WithMemoryPages(1, 10).
				WithSysWalltime().
				WithStdout(wazero.Discard).WithStderr(wazero.Discard)

			mod, err := e.runtime.InstantiateModule(ctx, e.compiled, modConfig)
			if err != nil {
				http.Error(w, "Plugin instantiation denied", http.StatusForbidden)
				return
			}
			defer mod.Close(ctx)

			enrichFn := mod.ExportedFunction("enrich_request")
			if enrichFn == nil {
				http.Error(w, "Plugin missing export", http.StatusBadGateway)
				return
			}

			_, err = enrichFn.Call(ctx)
			if err != nil {
				http.Error(w, "Plugin execution timeout or trap", http.StatusGatewayTimeout)
				return
			}

			next.ServeHTTP(w, r)
		})
	}
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Strict In-Process Wazero WASM Isolation for Multi-Tenant Chi Middleware

Strict In-Process Wazero WASM Isolation for Multi-Tenant Chi Middleware defines an industrial-grade behavioral standard for backend engineering. Enforces strict memory page ceilings, lifecycle sandboxing, and secure host function boundaries for dynamic request enrichment plugins executed via Wazero in Go 1.24 Chi HTTP pipelines. Prohibits global mutable runtime modules and unbound host function exports to eliminate cross-tenant data bleed and noisy-neighbor OOM panics while preserving zero-IPC performance. 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: Executing Multi-Tenant Plugins on Shared Wazero Module Instances with Unbounded Memory and Raw Pointer Host Exports 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 DriftExecuting Multi-Tenant Plugins on Shared Wazero Module Instances with Unbounded Memory and Raw Pointer Host ExportsCritical
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 pre-compile WASM modules once using `wazero.Runtime.CompileModule(ctx, wasmCode)` during application boot, never per request.

Engineers MUST ALWAYS pre-compile WASM modules once using `wazero.Runtime.CompileModule(ctx, wasmCode)` during application boot, never per request.

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 ALWAYS instantiate a distinct `api.Module` per incoming HTTP request using `r.InstantiateModule(ctx, compiled, moduleConfig)` and ensure cleanup via `defer mod.Close(ctx)`.

Engineers MUST ALWAYS instantiate a distinct `api.Module` per incoming HTTP request using `r.InstantiateModule(ctx, compiled, moduleConfig)` and ensure cleanup via `defer mod.Close(ctx)`.

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 configure hard limits on plugin memory pages using `wazero.NewModuleConfig().WithMemoryPages(min, max)` to guarantee that plugins cannot trigger host OOM panics.

Engineers MUST configure hard limits on plugin memory pages using `wazero.NewModuleConfig().WithMemoryPages(min, max)` to guarantee that plugins cannot trigger host OOM panics.

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 NOT expose unrestricted host primitives, file descriptors, or raw system calls to WASM guests

Engineers MUST NOT expose unrestricted host primitives, file descriptors, or raw system calls to WASM guests; only register dedicated, tenant-scoped Host Modules.

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 functions reading guest memory MUST ALWAYS validate buffer boundaries using `mod.Memory().Read(offset, byteCount)` and guard against integer overflows.

Host functions reading guest memory MUST ALWAYS validate buffer boundaries using `mod.Memory().Read(offset, byteCount)` and guard against integer overflows.

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

Chi middleware MUST propagate `context.WithTimeout` into `InstantiateModule` and plugin function executions to enforce deterministic execution deadlines.

Chi middleware MUST propagate `context.WithTimeout` into `InstantiateModule` and plugin function executions to enforce deterministic execution deadlines.

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

Components NEVER share mutable state or non-thread-safe Wazero `api.Module` references across concurrent Chi request goroutines.

Components NEVER share mutable state or non-thread-safe Wazero `api.Module` references across concurrent Chi request goroutines.

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 Strict In-Process Wazero WASM Isolation for Multi-Tenant Chi Middleware critical for AI coding assistants?

Enforces strict memory page ceilings, lifecycle sandboxing, and secure host function boundaries for dynamic request enrichment plugins executed via Wazero in Go 1.24 Chi HTTP pipelines. Prohibits global mutable runtime modules and unbound host function exports to eliminate cross-tenant data bleed and noisy-neighbor OOM panics while preserving zero-IPC performance. 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 (Executing Multi-Tenant Plugins on Shared Wazero Module Instances with Unbounded Memory and Raw Pointer Host Exports) 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

Strict