This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-124-weak-pointer-ephemeral-cache-guardrail

Go 1.24 Weak Pointer Ephemeral Cache and GC Finalizer Guardrail

Enforces deterministic, non-blocking memory reclamation in Go 1.24+ using the standard 'weak' package for ephemeral caches. Prohibits legacy runtime.SetFinalizer patterns that induce object resurrection, GC sweep latency spikes, and concurrent lock inversion deadlocks.

Prohibited Anti-Pattern: Resurrecting Evicted Cache Entries via runtime.SetFinalizer Under Inverted Mutex Locks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer Ephemeral Cache and GC Finalizer Guardrail - Enforces deterministic, non-blocking memory reclamation in Go 1.24+ using the standard 'weak' package for ephemeral caches. Prohibits legacy runtime.SetFinalizer patterns that induce object resurrection, GC sweep latency spikes, and concurrent lock inversion deadlocks.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-124-weak-pointer-ephemeral-cache-guardrail"
---

# Go 1.24 Weak Pointer Ephemeral Cache and GC Finalizer Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Resurrecting Evicted Cache Entries via runtime.SetFinalizer Under Inverted Mutex Locks

## System Constraints
You are a Principal Go Systems Architect enforcing strict memory model invariants for Go 1.24+. Mandate the use of Go 1.24's standard library `weak` package (`weak.Pointer[T]`, `weak.Make`) for ephemeral canonicalization caches and memoization. Prohibit `runtime.SetFinalizer` for cache lifecycle management to prevent GC deadlocks, object resurrection, and heap fragmentation. Enforce lock isolation and lock-free weak pointer resolution with atomic sweep pruning.

## Strict Guidelines
- Engineers MUST ALWAYS use standard library `weak.Pointer[T]` and `weak.Make` (Go 1.24+) for ephemeral, weak-reference, or canonicalizing caches.
- Engineers MUST NOT use `runtime.SetFinalizer` to manage cache eviction, resource pooling, or lifecycle notifications.
- Engineers MUST NEVER capture the referenced object pointer inside `runtime.AddCleanup` closures; cleanups MUST only receive isolated handles or primitives to avoid cyclic resurrection.
- Code MUST dereference `weak.Pointer.Value()` into a local variable and check for `nil` before using or asserting identity.
- Services MUST implement opportunistic or amortized tombstone sweeping using double-checked locking when removing stale `nil` weak pointers from cache maps.
- Components NEVER hold cache mutexes while performing dereferences, allocations, or invoking external callbacks.

## Bad vs Good Implementations
### Ephemeral In-Memory Cache Implementation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using runtime.SetFinalizer captures the pointer, resurrects the object for at least one additional GC cycle, and attempts to acquire a Mutex inside the finalizer goroutine. If another goroutine holds the lock while blocked on GC or allocation, this produces fatal application deadlocks.
```go
package cache

import (
	"runtime"
	"sync"
)

// ANTI-PATTERN: runtime.SetFinalizer causes resurrection, GC stalls, and deadlock.
type BadCache struct {
	mu    sync.Mutex
	items map[string]*Session
}

type Session struct {
	ID   string
	Data []byte
}

func (c *BadCache) Put(s *Session) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.items[s.ID] = s

	// DEADLOCK RISK: If GC sweep triggers this finalizer while another
	// goroutine holds c.mu and allocates, the GC runtime thread hangs.
	// RESURRECTION BUG: Keeps s reachable in the finalizer queue across sweeps.
	runtime.SetFinalizer(s, func(deadSession *Session) {
		c.mu.Lock()
		delete(c.items, deadSession.ID)
		c.mu.Unlock()
	})
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes Go 1.24's native weak.Pointer. Objects are reclaimed in the very same GC cycle when external strong references disappear, eliminating GC latency spikes. Tombstone pruning uses double-checked locking without holding locks during dereference operations.
```go
package cache

import (
	"sync"
	"weak"
)

// PRODUCTION INVARIANT: Go 1.24 weak.Pointer allows automatic GC sweep
// without finalizer cycles, object resurrection, or lock inversion.
type EphemeralCache[K comparable, V any] struct {
	mu    sync.RWMutex
	items map[K]weak.Pointer[V]
}

func NewEphemeralCache[K comparable, V any]() *EphemeralCache[K, V] {
	return &EphemeralCache[K, V]{
		items: make(map[K]weak.Pointer[V]),
	}
}

func (c *EphemeralCache[K, V]) Get(key K) (*V, bool) {
	c.mu.RLock()
	wp, ok := c.items[key]
	c.mu.RUnlock()
	if !ok {
		return nil, false
	}

	// Atomically dereference the weak reference
	val := wp.Value()
	if val == nil {
		// Opportunistic tombstone cleanup with double-checked write lock
		c.mu.Lock()
		if cur, present := c.items[key]; present && cur.Value() == nil {
			delete(c.items, key)
		}
		c.mu.Unlock()
		return nil, false
	}
	return val, true
}

func (c *EphemeralCache[K, V]) Put(key K, val *V) {
	if val == nil {
		return
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	c.items[key] = weak.Make(val)
}
```

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 1.24 Weak Pointer Ephemeral Cache and GC Finalizer Guardrail

Go 1.24 Weak Pointer Ephemeral Cache and GC Finalizer Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic, non-blocking memory reclamation in Go 1.24+ using the standard 'weak' package for ephemeral caches. Prohibits legacy runtime.SetFinalizer patterns that induce object resurrection, GC sweep latency spikes, and concurrent lock inversion deadlocks. 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: Resurrecting Evicted Cache Entries via runtime.SetFinalizer Under Inverted Mutex Locks 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 DriftResurrecting Evicted Cache Entries via runtime.SetFinalizer Under Inverted Mutex LocksCritical
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 use standard library `weak.Pointer[T]` and `weak.Make` (Go 1.24+) for ephemeral, weak-reference, or canonicalizing caches.

Engineers MUST ALWAYS use standard library `weak.Pointer[T]` and `weak.Make` (Go 1.24+) for ephemeral, weak-reference, or canonicalizing caches.

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 use `runtime.SetFinalizer` to manage cache eviction, resource pooling, or lifecycle notifications.

Engineers MUST NOT use `runtime.SetFinalizer` to manage cache eviction, resource pooling, or lifecycle notifications.

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 capture the referenced object pointer inside `runtime.AddCleanup` closures

Engineers MUST NEVER capture the referenced object pointer inside `runtime.AddCleanup` closures; cleanups MUST only receive isolated handles or primitives to avoid cyclic resurrection.

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

Code MUST dereference `weak.Pointer.Value()` into a local variable and check for `nil` before using or asserting identity.

Code MUST dereference `weak.Pointer.Value()` into a local variable and check for `nil` before using or asserting identity.

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 implement opportunistic or amortized tombstone sweeping using double-checked locking when removing stale `nil` weak pointers from cache maps.

Services MUST implement opportunistic or amortized tombstone sweeping using double-checked locking when removing stale `nil` weak pointers from cache maps.

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 hold cache mutexes while performing dereferences, allocations, or invoking external callbacks.

Components NEVER hold cache mutexes while performing dereferences, allocations, or invoking external callbacks.

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 1.24 Weak Pointer Ephemeral Cache and GC Finalizer Guardrail critical for AI coding assistants?

Enforces deterministic, non-blocking memory reclamation in Go 1.24+ using the standard 'weak' package for ephemeral caches. Prohibits legacy runtime.SetFinalizer patterns that induce object resurrection, GC sweep latency spikes, and concurrent lock inversion deadlocks. 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 (Resurrecting Evicted Cache Entries via runtime.SetFinalizer Under Inverted Mutex Locks) 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