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

Go 1.24 Weak Pointer Cache Resurrection and Reclamation Guardrail

Enforces strict access patterns when dereferencing Go 1.24+ `weak.Pointer` instances within low-latency in-memory caches. Eliminates memory leaks, silent data corruption, and race conditions by preventing unsynchronized resurrection of dereferenced nil targets across GC sweep cycles and mandating atomic validation before re-anchoring cached objects.

Prohibited Anti-Pattern: Unsynchronized Weak Pointer Dereferencing and Dead Object Resurrection Across GC Sweeps

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer Cache Resurrection and Reclamation Guardrail - Enforces strict access patterns when dereferencing Go 1.24+ `weak.Pointer` instances within low-latency in-memory caches. Eliminates memory leaks, silent data corruption, and race conditions by preventing unsynchronized resurrection of dereferenced nil targets across GC sweep cycles and mandating atomic validation before re-anchoring cached objects.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-124-weak-pointer-cache-resurrection-guardrail"
---

# Go 1.24 Weak Pointer Cache Resurrection and Reclamation Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Weak Pointer Dereferencing and Dead Object Resurrection Across GC Sweeps

## System Constraints
You are a Principal Go Systems Architect enforcing strict memory safety invariants under Go 1.24's `weak` package. You must ensure all interactions with `weak.Pointer[T]` validate pointer nullability immediately upon `Value()` invocation, prevent race conditions where a collecting object is resurrected into an active store without synchronization, and guarantee dead weak pointers are deterministically swept from cache lookup maps to avoid retention of tombstone references.

## Strict Guidelines
- Engineers MUST ALWAYS capture the result of `weak.Pointer[T].Value()` into a local strong pointer variable exactly once and immediately check for `nil` before any field access or re-caching.
- Engineers MUST NOT assume consecutive calls to `Value()` on the same `weak.Pointer` will yield the same value; GC collection cycles between invocations can turn a non-nil return into `nil`.
- Code MUST synchronize cache mutation locks before resurrecting or renewing an expiring weak entry into an alternate persistent storage or strong-reference lookup structure.
- Services MUST implement explicit tombstone cleanup or use cleanup hooks (such as `runtime.AddCleanup`) to purge stale `weak.Pointer` entries from lookup maps, preventing unbounded table growth.
- Components NEVER store naked, unvalidated `weak.Pointer[T].Value()` invocations directly into return values or external data structures without nil-assertion handling.

## Bad vs Good Implementations
### Unsafe Weak Pointer Double-Dereference vs. Atomic Single-Dereference and Cleanup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling `wp.Value()` multiple times creates a Time-of-Check to Time-of-Use (TOCTOU) race condition with the Go runtime garbage collector. If the GC triggers after the nil-check, the second `wp.Value()` call returns `nil`, leading to nil-pointer dereferences downstream. Furthermore, cleared weak pointers remain retained inside `c.items`, leaking map keys.
```go
package cache

import (
	"sync"
	"weak"
)

type Cache[K comparable, V any] struct {
	mu    sync.RWMutex
	items map[K]weak.Pointer[V]
}

// BAD: Calls Value() multiple times; GC can sweep between check and return.
// Also allows resurrecting a nil or near-collected pointer without synchronizing map eviction.
func (c *Cache[K, V]) Get(key K) *V {
	c.mu.RLock()
	wp, exists := c.items[key]
	c.mu.RUnlock()
	if !exists {
		return nil
	}

	// Data race with GC: wp.Value() could be non-nil here...
	if wp.Value() != nil {
		// ...but nil by the time Value() is invoked a second time!
		return wp.Value()
	}

	return nil
}
```

#### Production Standard (Correct)
> **Standard**: Evaluates `wp.Value()` precisely once into a local strong pointer `val`, ensuring that GC execution cannot invalidate the nil-check. Cleans up stale tombstone entries immediately and integrates `runtime.AddCleanup` to eliminate unbounded memory growth from dead keys.
```go
package cache

import (
	"runtime"
	"sync"
	"weak"
)

type Cache[K comparable, V any] struct {
	mu    sync.RWMutex
	items map[K]weak.Pointer[V]
}

// GOOD: Single evaluation, immediate nil validation, and deterministic stale key eviction.
func (c *Cache[K, V]) Get(key K) *V {
	c.mu.RLock()
	wp, exists := c.items[key]
	c.mu.RUnlock()
	if !exists {
		return nil
	}

	// Atomic single evaluation to strong reference
	val := wp.Value()
	if val == nil {
		// Evict tombstone to avoid key leakage
		c.mu.Lock()
		// Re-verify under write lock to avoid concurrent resurrection races
		if current, ok := c.items[key]; ok && current.Value() == nil {
			delete(c.items, key)
		}
		c.mu.Unlock()
		return nil
	}

	return val
}

func (c *Cache[K, V]) Set(key K, val *V) {
	c.mu.Lock()
	defer c.mu.Unlock()
	wp := weak.Make(val)
	c.items[key] = wp

	// Ensure dead entries are cleaned up when val is finalized
	runtime.AddCleanup(val, func(k K) {
		c.mu.Lock()
		if current, ok := c.items[k]; ok && current.Value() == nil {
			delete(c.items, k)
		}
		c.mu.Unlock()
	}, key)
}
```

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 Cache Resurrection and Reclamation Guardrail

Go 1.24 Weak Pointer Cache Resurrection and Reclamation Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict access patterns when dereferencing Go 1.24+ `weak.Pointer` instances within low-latency in-memory caches. Eliminates memory leaks, silent data corruption, and race conditions by preventing unsynchronized resurrection of dereferenced nil targets across GC sweep cycles and mandating atomic validation before re-anchoring cached objects. 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: Unsynchronized Weak Pointer Dereferencing and Dead Object Resurrection Across GC Sweeps 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 DriftUnsynchronized Weak Pointer Dereferencing and Dead Object Resurrection Across GC SweepsCritical
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 capture the result of `weak.Pointer[T].Value()` into a local strong pointer variable exactly once and immediately check for `nil` before any field access or re-caching.

Engineers MUST ALWAYS capture the result of `weak.Pointer[T].Value()` into a local strong pointer variable exactly once and immediately check for `nil` before any field access or re-caching.

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 assume consecutive calls to `Value()` on the same `weak.Pointer` will yield the same value

Engineers MUST NOT assume consecutive calls to `Value()` on the same `weak.Pointer` will yield the same value; GC collection cycles between invocations can turn a non-nil return into `nil`.

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 synchronize cache mutation locks before resurrecting or renewing an expiring weak entry into an alternate persistent storage or strong-reference lookup structure.

Code MUST synchronize cache mutation locks before resurrecting or renewing an expiring weak entry into an alternate persistent storage or strong-reference lookup structure.

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

Services MUST implement explicit tombstone cleanup or use cleanup hooks (such as `runtime.AddCleanup`) to purge stale `weak.Pointer` entries from lookup maps, preventing unbounded table growth.

Services MUST implement explicit tombstone cleanup or use cleanup hooks (such as `runtime.AddCleanup`) to purge stale `weak.Pointer` entries from lookup maps, preventing unbounded table growth.

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

Components NEVER store naked, unvalidated `weak.Pointer[T].Value()` invocations directly into return values or external data structures without nil-assertion handling.

Components NEVER store naked, unvalidated `weak.Pointer[T].Value()` invocations directly into return values or external data structures without nil-assertion handling.

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 Cache Resurrection and Reclamation Guardrail critical for AI coding assistants?

Enforces strict access patterns when dereferencing Go 1.24+ `weak.Pointer` instances within low-latency in-memory caches. Eliminates memory leaks, silent data corruption, and race conditions by preventing unsynchronized resurrection of dereferenced nil targets across GC sweep cycles and mandating atomic validation before re-anchoring cached objects. 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 (Unsynchronized Weak Pointer Dereferencing and Dead Object Resurrection Across GC Sweeps) 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