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

Go Chi Zero-Allocation Context Pool Sanitization and Memory Scrubbing Guardrail

Mandates deterministic memory zeroing, pointer detachment, and deep field sanitization for pooled request contexts and custom state structs within Go Chi middleware pipelines. Prevents cross-tenant data bleeding, dangling reference retention, and silent authorization bypasses caused by dirty object reuse in high-throughput sync.Pool implementations.

Prohibited Anti-Pattern: Recycling Unsanitized Request State and Chi Route Contexts via sync.Pool Across Tenant Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Zero-Allocation Context Pool Sanitization and Memory Scrubbing Guardrail - Mandates deterministic memory zeroing, pointer detachment, and deep field sanitization for pooled request contexts and custom state structs within Go Chi middleware pipelines. Prevents cross-tenant data bleeding, dangling reference retention, and silent authorization bypasses caused by dirty object reuse in high-throughput sync.Pool implementations.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-pool-sanitization-guardrail"
---

# Go Chi Zero-Allocation Context Pool Sanitization and Memory Scrubbing Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Recycling Unsanitized Request State and Chi Route Contexts via sync.Pool Across Tenant Boundaries

## System Constraints
You are a Principal Go Security and Performance Architect enforcing strict memory hygiene and zero-allocation safety patterns in Go Chi HTTP services. You MUST reject any code that reuses pooled structs or attaches pooled context references without deterministic pointer detachment, slice truncation, and comprehensive field zeroing prior to sync.Pool recycling.

## Strict Guidelines
- Engineers MUST ALWAYS implement a dedicated, non-pointer-leaking `Reset()` method on any struct managed via `sync.Pool` that explicitly clears all pointer references, slices, maps, and tenant-identifying fields to zero values.
- Engineers MUST ALWAYS zero out slice elements containing pointers before truncating length (`s[i] = nil`) to prevent underlying backing arrays from holding garbage-collection roots or leaking sensitive references across requests.
- Engineers MUST ALWAYS invoke pool restoration (`pool.Put(v)`) strictly inside a guarded `defer` block directly adjacent to context acquisition to guarantee sanitization even during panics or aborted handler chains.
- Engineers MUST NOT pass pooled structs or their pointers across asynchronous goroutine boundaries unless the payload is deeply cloned into an independently heap-allocated struct prior to dispatch.
- Services MUST NEVER rely on downstream handlers to overwrite context fields; state initialization MUST strictly enforce that missing headers or absent claims result in clean zero states rather than fallback to previous pool contents.
- Components MUST detachedly reset Chi's internal `chi.Context` (`chi.RouteContext(r.Context()).Reset()`) if managing custom route sub-dispatchers or custom allocation-free router wrappers.

## Bad vs Good Implementations
### Unsanitized sync.Pool Reuse in Multi-Tenant Chi Middleware vs Deterministic Pointer Detachment

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The pool object is recycled without clearing residual state. If an incoming request lacks an 'X-Tenant-ID' header or role definitions, it retains the prior request's tenant identity and role slice. Furthermore, not executing `Put` within a `defer` leaks objects on panics, and un-cleared slice/map references cause memory leaks and cross-tenant data exfiltration.
```go
package middleware

import (
	"context"
	"net/http"
	"sync"
)

type TenantState struct {
	TenantID string
	UserID   string
	Roles    []string
	Metadata map[string]any
}

var tenantStatePool = sync.Pool{
	New: func() any { return &TenantState{} },
}

func TenantContextMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		state := tenantStatePool.Get().(*TenantState)
		// Anti-Pattern: Partial assignment without resetting prior fields.
		// If Tenant-ID is missing or Roles are unpopulated in this request,
		// previous tenant's data bleeds into the current execution frame.
		if tid := r.Header.Get("X-Tenant-ID"); tid != "" {
			state.TenantID = tid
		}
		
		ctx := context.WithValue(r.Context(), "tenant_state", state)
		next.ServeHTTP(w, r.WithContext(ctx))
		
		// Anti-Pattern: Pool return without scrub; lingering slice headers
		// and maps retain tenant references in the global pool.
		tenantStatePool.Put(state)
	})
}
```

#### Production Standard (Correct)
> **Standard**: Production invariant compliant implementation ensuring memory safety, deterministic execution, and zero runtime hallucination.
```go
package middleware

import (
	"context"
	"net/http"
	"sync"
)

type contextKey struct{}
var tenantContextKey = contextKey{}

type TenantState struct {
	TenantID string
	UserID   string
	Roles    []string
	Metadata map[string]any
}

// Reset clears all scalar values, detaches pointers, and zeros slices to prevent cross-tenant retention.
func (s *TenantState) Reset() {
	s.TenantID = ""
	s.UserID = ""
	// Clear slice elements before resetting length to detach GC roots
	for i := range s.Roles {
		s.Roles[i] = ""
	}
	s.Roles = s.Roles[:0]
	// Clear map references
	clear(s.Metadata)
}

var tenantStatePool = sync.Pool{
	New: func() any {
		return &TenantState{
			Roles:    make([]string, 0, 8),
			Metadata: make(map[string]any),
		}
	},
}

func TenantContextMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		state := tenantStatePool.Get().(*TenantState)
		
		// Invariant: Pool recycling MUST be deferred immediately to ensure cleanup
		// under panics or abortive writes, with deterministic Reset().
		defer func() {
			state.Reset()
			tenantStatePool.Put(state)
		}()
		
		// Enforce clean state initialization
		state.TenantID = r.Header.Get("X-Tenant-ID")
		state.UserID = r.Header.Get("X-User-ID")
		
		ctx := context.WithValue(r.Context(), tenantContextKey, state)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
```

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: Go Chi Zero-Allocation Context Pool Sanitization and Memory Scrubbing Guardrail

Go Chi Zero-Allocation Context Pool Sanitization and Memory Scrubbing Guardrail defines an industrial-grade behavioral standard for backend engineering. Mandates deterministic memory zeroing, pointer detachment, and deep field sanitization for pooled request contexts and custom state structs within Go Chi middleware pipelines. Prevents cross-tenant data bleeding, dangling reference retention, and silent authorization bypasses caused by dirty object reuse in high-throughput sync.Pool implementations. 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: Recycling Unsanitized Request State and Chi Route Contexts via sync.Pool Across Tenant Boundaries 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 DriftRecycling Unsanitized Request State and Chi Route Contexts via sync.Pool Across Tenant BoundariesCritical
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 implement a dedicated, non-pointer-leaking `Reset()` method on any struct managed via `sync.Pool` that explicitly clears all pointer references, slices, maps, and tenant-identifying fields to zero values.

Engineers MUST ALWAYS implement a dedicated, non-pointer-leaking `Reset()` method on any struct managed via `sync.Pool` that explicitly clears all pointer references, slices, maps, and tenant-identifying fields to zero values.

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 zero out slice elements containing pointers before truncating length (`s[i] = nil`) to prevent underlying backing arrays from holding garbage-collection roots or leaking sensitive references across requests.

Engineers MUST ALWAYS zero out slice elements containing pointers before truncating length (`s[i] = nil`) to prevent underlying backing arrays from holding garbage-collection roots or leaking sensitive references across requests.

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 ALWAYS invoke pool restoration (`pool.Put(v)`) strictly inside a guarded `defer` block directly adjacent to context acquisition to guarantee sanitization even during panics or aborted handler chains.

Engineers MUST ALWAYS invoke pool restoration (`pool.Put(v)`) strictly inside a guarded `defer` block directly adjacent to context acquisition to guarantee sanitization even during panics or aborted handler chains.

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 pass pooled structs or their pointers across asynchronous goroutine boundaries unless the payload is deeply cloned into an independently heap-allocated struct prior to dispatch.

Engineers MUST NOT pass pooled structs or their pointers across asynchronous goroutine boundaries unless the payload is deeply cloned into an independently heap-allocated struct prior to dispatch.

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 NEVER rely on downstream handlers to overwrite context fields

Services MUST NEVER rely on downstream handlers to overwrite context fields; state initialization MUST strictly enforce that missing headers or absent claims result in clean zero states rather than fallback to previous pool contents.

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 MUST detachedly reset Chi's internal `chi.Context` (`chi.RouteContext(r.Context()).Reset()`) if managing custom route sub-dispatchers or custom allocation-free router wrappers.

Components MUST detachedly reset Chi's internal `chi.Context` (`chi.RouteContext(r.Context()).Reset()`) if managing custom route sub-dispatchers or custom allocation-free router wrappers.

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 Zero-Allocation Context Pool Sanitization and Memory Scrubbing Guardrail critical for AI coding assistants?

Mandates deterministic memory zeroing, pointer detachment, and deep field sanitization for pooled request contexts and custom state structs within Go Chi middleware pipelines. Prevents cross-tenant data bleeding, dangling reference retention, and silent authorization bypasses caused by dirty object reuse in high-throughput sync.Pool implementations. 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 (Recycling Unsanitized Request State and Chi Route Contexts via sync.Pool Across Tenant Boundaries) 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