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

Go 1.24 Weak Pointer Cache Invalidation and Memory Safety Invariant

Governs the use of Go 1.24 weak pointers (weak.Pointer) within high-throughput in-memory cache indexing layers to eliminate memory retention cycles and GC pinning. Mandates atomic dereferencing through Pointer.Strong() and safe cleanup synchronizers to prevent use-after-free logic and dangling pointer race conditions under heavy concurrent GC pressure.

Prohibited Anti-Pattern: Retaining Strong References in Secondary Indexes or Accessing Weak Pointers Without Immediate Strong Nil-Checks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer Cache Invalidation and Memory Safety Invariant - Governs the use of Go 1.24 weak pointers (weak.Pointer) within high-throughput in-memory cache indexing layers to eliminate memory retention cycles and GC pinning. Mandates atomic dereferencing through Pointer.Strong() and safe cleanup synchronizers to prevent use-after-free logic and dangling pointer race conditions under heavy concurrent GC pressure.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-1-24-weak-pointer-cache-invalidation"
---

# Go 1.24 Weak Pointer Cache Invalidation and Memory Safety Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining Strong References in Secondary Indexes or Accessing Weak Pointers Without Immediate Strong Nil-Checks

## System Constraints
You are a Principal Go Systems Architect enforcing strict memory safety and zero-allocation invariants using Go 1.24 weak pointers (`weak.Pointer`). Mandate that all secondary cache indexes and lookup structures store weak references to avoid keeping eviction targets pinned in memory. Enforce strict single-point atomic dereference validation (`wp.Strong()`) and prohibit storing intermediate strong references across yield points or goroutine boundaries without proper synchronization.

## Strict Guidelines
- Engineers MUST ALWAYS dereference a `weak.Pointer[T]` using `.Strong()` into a local stack variable and immediately check for `nil` before accessing fields.
- Engineers MUST NOT cache, store, or pass around the `weak.Pointer[T]` under the assumption that a prior `.Strong()` call guarantees non-nil status in subsequent operations.
- Services MUST implement tombstone eviction or cleanup mechanisms in secondary indexing tables when `.Strong()` returns `nil` during lookup.
- Code MUST NEVER use finalizers (`runtime.SetFinalizer`) alongside `weak.Pointer`; use `runtime.AddCleanup` introduced in Go 1.24 to handle associative cleanup without resurrecting objects.
- Secondary indexes and topological lookup maps MUST store `weak.Pointer[T]` instead of direct `*T` pointers whenever the primary cache or lifecycle owner holds the canonical strong reference.

## Bad vs Good Implementations
### Unsafe Weak Pointer Resolution and GC Pinning vs Atomic Strong Validation with Go 1.24 Cleanup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling wp.Strong() multiple times is a severe concurrency bug: the garbage collector can collect the value between the nil check and the subsequent dereference, resulting in a nil pointer dereference panic. It also fails to purge dead weak pointers from the map.
```go
package cache

import (
	"sync"
	"weak" // Go 1.24 weak pointer package
)

type CacheItem struct {
	Key   string
	Value []byte
}

type SecondaryIndex struct {
	mu    sync.RWMutex
	items map[string]weak.Pointer[CacheItem]
}

// BAD: Race condition and memory safety violation.
// Assumes item remains non-nil across distinct accesses without single-point binding.
func (idx *SecondaryIndex) GetValue(key string) ([]byte, bool) {
	idx.mu.RLock()
	wp, exists := idx.items[key]
	idx.mu.RUnlock()
	if !exists {
		return nil, false
	}

	// Race: item may be collected between .Strong() call and dereference
	if wp.Strong() != nil {
		// BUG: Second call to Strong() can return nil if GC swept concurrently!
		return wp.Strong().Value, true
	}
	return nil, false
}
```

#### Production Standard (Correct)
> **Standard**: Assigning wp.Strong() once to a stack-local strong pointer ensures that GC cannot collect the underlying struct while it is being read. The pattern incorporates runtime.AddCleanup to automatically purge the dead map key when the object is finalized without object resurrection issues.
```go
package cache

import (
	"runtime"
	"sync"
	"weak" // Go 1.24 weak pointer package
)

type CacheItem struct {
	Key   string
	Value []byte
}

type SafeSecondaryIndex struct {
	mu    sync.RWMutex
	items map[string]weak.Pointer[CacheItem]
}

func (idx *SafeSecondaryIndex) Register(item *CacheItem) {
	idx.mu.Lock()
	defer idx.mu.Unlock()

	wp := weak.Make(item)
	idx.items[item.Key] = wp

	// Use Go 1.24 runtime.AddCleanup instead of runtime.SetFinalizer
	runtime.AddCleanup(item, func(k string) {
		idx.mu.Lock()
		defer idx.mu.Unlock()
		delete(idx.items, k)
	}, item.Key)
}

// GOOD: Atomic dereference to local variable with immediate nil-check and lazy eviction.
func (idx *SafeSecondaryIndex) GetValue(key string) ([]byte, bool) {
	idx.mu.RLock()
	wp, exists := idx.items[key]
	idx.mu.RUnlock()
	if !exists {
		return nil, false
	}

	// Capture exactly once into a strong reference on the current stack
	strongItem := wp.Strong()
	if strongItem == nil {
		// Target was collected; clean up lazily if not already handled by cleanup hook
		idx.mu.Lock()
		delete(idx.items, key)
		idx.mu.Unlock()
		return nil, false
	}

	return strongItem.Value, true
}
```

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 Cache Invalidation and Memory Safety Invariant

Go 1.24 Weak Pointer Cache Invalidation and Memory Safety Invariant defines an industrial-grade behavioral standard for backend engineering. Governs the use of Go 1.24 weak pointers (weak.Pointer) within high-throughput in-memory cache indexing layers to eliminate memory retention cycles and GC pinning. Mandates atomic dereferencing through Pointer.Strong() and safe cleanup synchronizers to prevent use-after-free logic and dangling pointer race conditions under heavy concurrent GC pressure. 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: Retaining Strong References in Secondary Indexes or Accessing Weak Pointers Without Immediate Strong Nil-Checks 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 DriftRetaining Strong References in Secondary Indexes or Accessing Weak Pointers Without Immediate Strong Nil-ChecksCritical
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 dereference a `weak.Pointer[T]` using `.Strong()` into a local stack variable and immediately check for `nil` before accessing fields.

Engineers MUST ALWAYS dereference a `weak.Pointer[T]` using `.Strong()` into a local stack variable and immediately check for `nil` before accessing fields.

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 cache, store, or pass around the `weak.Pointer[T]` under the assumption that a prior `.Strong()` call guarantees non-nil status in subsequent operations.

Engineers MUST NOT cache, store, or pass around the `weak.Pointer[T]` under the assumption that a prior `.Strong()` call guarantees non-nil status in subsequent operations.

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

Services MUST implement tombstone eviction or cleanup mechanisms in secondary indexing tables when `.Strong()` returns `nil` during lookup.

Services MUST implement tombstone eviction or cleanup mechanisms in secondary indexing tables when `.Strong()` returns `nil` during lookup.

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 NEVER use finalizers (`runtime.SetFinalizer`) alongside `weak.Pointer`

Code MUST NEVER use finalizers (`runtime.SetFinalizer`) alongside `weak.Pointer`; use `runtime.AddCleanup` introduced in Go 1.24 to handle associative cleanup without resurrecting objects.

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

Secondary indexes and topological lookup maps MUST store `weak.Pointer[T]` instead of direct `*T` pointers whenever the primary cache or lifecycle owner holds the canonical strong reference.

Secondary indexes and topological lookup maps MUST store `weak.Pointer[T]` instead of direct `*T` pointers whenever the primary cache or lifecycle owner holds the canonical strong reference.

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 Invalidation and Memory Safety Invariant critical for AI coding assistants?

Governs the use of Go 1.24 weak pointers (weak.Pointer) within high-throughput in-memory cache indexing layers to eliminate memory retention cycles and GC pinning. Mandates atomic dereferencing through Pointer.Strong() and safe cleanup synchronizers to prevent use-after-free logic and dangling pointer race conditions under heavy concurrent GC pressure. 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 (Retaining Strong References in Secondary Indexes or Accessing Weak Pointers Without Immediate Strong Nil-Checks) 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