This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-chi-arena-request-context-lifecycle

Go Chi Arena-Backed Request Context Lifecycle Invariant

Enforces strict scope-bound memory arena reclamation within Go Chi HTTP middleware pipelines. Forbids arena-allocated pointers from escaping synchronous request boundaries into asynchronous goroutines, eradicating use-after-free memory corruption in zero-allocation services.

Prohibited Anti-Pattern: Capturing Arena-Allocated Pointers in Asynchronous Goroutines After Deferred Middleware Arena Reclamation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Arena-Backed Request Context Lifecycle Invariant - Enforces strict scope-bound memory arena reclamation within Go Chi HTTP middleware pipelines. Forbids arena-allocated pointers from escaping synchronous request boundaries into asynchronous goroutines, eradicating use-after-free memory corruption in zero-allocation services.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-arena-request-context-lifecycle"
---

# Go Chi Arena-Backed Request Context Lifecycle Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Capturing Arena-Allocated Pointers in Asynchronous Goroutines After Deferred Middleware Arena Reclamation

## System Constraints
You are a Principal Systems Architect enforcing strict memory safety and arena allocation lifecycles in Go Chi microservices. Your directive is to guarantee that no pointer allocated within a request-scoped arena escapes into asynchronous goroutines or outlives the synchronous execution lifecycle of the Chi middleware stack.

## Strict Guidelines
- Engineers MUST ALWAYS free request-scoped arenas exclusively within the originating Chi middleware via a deferred call after the synchronous handler chain returns.
- Engineers MUST NOT pass pointers allocated within an arena into un-joined goroutines, fire-and-forget channel sends, or background task queues.
- Code MUST deep-copy (promote) any arena-allocated struct to standard Go runtime heap memory prior to dispatching background operations or asynchronous processing.
- Middleware injecting an arena into http.Request.Context MUST provide a type-safe accessor that enforces heap-promotion semantics when crossing goroutine boundaries.
- Services MUST compile and test with '-race' and memory sanitizer flags enabled to surface cross-goroutine use-after-free and data races during arena reuse.
- Components NEVER store long-lived pointers (e.g., package-level caches, global sync.Pool elements) referencing memory backed by an arena marked for impending reclamation.

## Bad vs Good Implementations
### Arena Scope Leakage in Chi Middleware vs Heap-Promoted Async Dispatch

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The arena is allocated per-request in the Chi middleware and deferred to Free() when ServeHTTP finishes. Spawning an un-joined goroutine in AsyncHandler captures the arena-allocated *UserSession pointer. When the HTTP request completes, Free() marks arena memory as invalid/reusable, leading to non-deterministic silent memory corruption or panic (use-after-free) in the background worker.
```go
package middleware

import (
	"arena"
	"net/http"

	"github.com/go-chi/chi/v5"
)

type UserSession struct {
	UserID string
	Roles  []string
}

func ArenaMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		memArena := arena.NewArena()
		// VIOLATION: Arena is freed immediately after handler returns,
		// triggering a use-after-free in any asynchronous goroutine capturing arena ptrs.
		defer memArena.Free()

		sess := arena.New[UserSession](memArena)
		sess.UserID = r.Header.Get("X-User-ID")

		ctx := WithSession(r.Context(), sess)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

func AsyncHandler(w http.ResponseWriter, r *http.Request) {
	sess := GetSession(r.Context())
	// VIOLATION: Passing sess (arena-backed pointer) to a background goroutine.
	// memArena.Free() will invalidate this memory while the goroutine runs.
	go func() {
		logAuditTrail(sess.UserID)
	}()
	w.WriteHeader(http.StatusOK)
}
```

#### Production Standard (Correct)
> **Standard**: The handler decouples background concurrency from the request arena lifecycle by explicitly promoting arena-allocated data to the Go runtime heap via PromoteToHeap() before spawning the goroutine. The deferred memArena.Free() cleans up synchronously without corrupting background readers.
```go
package middleware

import (
	"arena"
	"net/http"

	"github.com/go-chi/chi/v5"
)

type UserSession struct {
	UserID string
	Roles  []string
}

// PromoteToHeap creates a deep, standard Go heap-allocated copy of the session.
func (s *UserSession) PromoteToHeap() UserSession {
	rolesCopy := make([]string, len(s.Roles))
	copy(rolesCopy, s.Roles)
	return UserSession{
		UserID: s.UserID,
		Roles:  rolesCopy,
	}
}

func ArenaMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		memArena := arena.NewArena()
		defer memArena.Free()

		sess := arena.New[UserSession](memArena)
		sess.UserID = r.Header.Get("X-User-ID")

		ctx := WithSession(r.Context(), sess)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

func AsyncHandler(w http.ResponseWriter, r *http.Request) {
	sess := GetSession(r.Context())
	// INVARIANT: Deep-copy arena-allocated values to the standard heap before spawning.
	heapSafeSession := sess.PromoteToHeap()

	go func(s UserSession) {
		logAuditTrail(s.UserID)
	}(heapSafeSession)

	w.WriteHeader(http.StatusOK)
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go Chi Arena-Backed Request Context Lifecycle Invariant

Go Chi Arena-Backed Request Context Lifecycle Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict scope-bound memory arena reclamation within Go Chi HTTP middleware pipelines. Forbids arena-allocated pointers from escaping synchronous request boundaries into asynchronous goroutines, eradicating use-after-free memory corruption in zero-allocation services. 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: Capturing Arena-Allocated Pointers in Asynchronous Goroutines After Deferred Middleware Arena Reclamation 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 DriftCapturing Arena-Allocated Pointers in Asynchronous Goroutines After Deferred Middleware Arena ReclamationCritical
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 free request-scoped arenas exclusively within the originating Chi middleware via a deferred call after the synchronous handler chain returns.

Engineers MUST ALWAYS free request-scoped arenas exclusively within the originating Chi middleware via a deferred call after the synchronous handler chain returns.

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 pass pointers allocated within an arena into un-joined goroutines, fire-and-forget channel sends, or background task queues.

Engineers MUST NOT pass pointers allocated within an arena into un-joined goroutines, fire-and-forget channel sends, or background task queues.

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

Code MUST deep-copy (promote) any arena-allocated struct to standard Go runtime heap memory prior to dispatching background operations or asynchronous processing.

Code MUST deep-copy (promote) any arena-allocated struct to standard Go runtime heap memory prior to dispatching background operations or asynchronous processing.

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

Middleware injecting an arena into http.Request.Context MUST provide a type-safe accessor that enforces heap-promotion semantics when crossing goroutine boundaries.

Middleware injecting an arena into http.Request.Context MUST provide a type-safe accessor that enforces heap-promotion semantics when crossing goroutine boundaries.

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

Services MUST compile and test with '-race' and memory sanitizer flags enabled to surface cross-goroutine use-after-free and data races during arena reuse.

Services MUST compile and test with '-race' and memory sanitizer flags enabled to surface cross-goroutine use-after-free and data races during arena reuse.

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

Components NEVER store long-lived pointers (e.g., package-level caches, global sync.Pool elements) referencing memory backed by an arena marked for impending reclamation.

Components NEVER store long-lived pointers (e.g., package-level caches, global sync.Pool elements) referencing memory backed by an arena marked for impending reclamation.

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 Go Chi Arena-Backed Request Context Lifecycle Invariant critical for AI coding assistants?

Enforces strict scope-bound memory arena reclamation within Go Chi HTTP middleware pipelines. Forbids arena-allocated pointers from escaping synchronous request boundaries into asynchronous goroutines, eradicating use-after-free memory corruption in zero-allocation services. 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 (Capturing Arena-Allocated Pointers in Asynchronous Goroutines After Deferred Middleware Arena Reclamation) 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

Go