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-pinning-standard

Go 1.24 Weak Pointer Cache Eviction and Memory Pinning Standard

Enforces deterministic memory reclamation patterns in high-throughput caching tiers using Go 1.24+ 'weak' references and 'runtime.KeepAlive' pin semantics. Prevents finalizer race conditions, memory retention leaks, and use-after-collection panics caused by naive strong pointer caching or premature GC sweeps during heavy concurrent allocation cycles.

Prohibited Anti-Pattern: Retaining Strong References in Canonicalizer Caches or Accessing Dereferenced Weak Pointers Without Immediate Strong Binding and Pinning

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer Cache Eviction and Memory Pinning Standard - Enforces deterministic memory reclamation patterns in high-throughput caching tiers using Go 1.24+ 'weak' references and 'runtime.KeepAlive' pin semantics. Prevents finalizer race conditions, memory retention leaks, and use-after-collection panics caused by naive strong pointer caching or premature GC sweeps during heavy concurrent allocation cycles.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-124-weak-pointer-cache-pinning-standard"
---

# Go 1.24 Weak Pointer Cache Eviction and Memory Pinning Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining Strong References in Canonicalizer Caches or Accessing Dereferenced Weak Pointers Without Immediate Strong Binding and Pinning

## System Constraints
You are a Principal Go Systems Architect enforcing strict Go 1.24 weak pointer semantics, lock-free canonicalization, and memory lifecycle hygiene across distributed cache implementations. You must reject any usage of runtime.SetFinalizer for cleanup, naive strong-pointer cache maps that evade GC pressure, and unsafe weak pointer dereferencing that lacks atomic promotion and caller-level lifetime pinning.

## Strict Guidelines
- Engineers MUST ALWAYS promote a weak.Pointer[T] to a strong pointer *T and explicitly verify non-nil status before invoking any methods or accessing fields.
- Engineers MUST NEVER access an object through a weak.Pointer without capturing it into a local strong pointer variable within the active stack frame.
- Engineers MUST use sync.Map or partitioned mutexes storing weak.Pointer[T] handles to build deduplicating/canonicalizing caches, allowing the Go 1.24 GC to evict unreferenced entries automatically.
- Engineers MUST invoke runtime.KeepAlive(val) at the end of critical operation boundaries whenever raw memory addresses or intermediate unsafe buffers depend on the lifetime of the promoted strong pointer.
- Engineers MUST NOT rely on runtime.SetFinalizer for memory eviction or cleanup in weak-pointer architectures; use runtime.AddCleanup (introduced in Go 1.24) with independent handle values to avoid cyclic reference memory leaks and resurrection bugs.

## Bad vs Good Implementations
### Weak Pointer Promotion and Safe Cache Canonicalization in Go 1.24

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: wp.Value() returns *T, which may be nil if the GC executed between the map lookup and the call to Value(). Accessing .Payload directly causes an unhandled nil pointer dereference under high memory pressure.
```go
package cache

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

type Item struct {
	Payload []byte
}

type Cache struct {
	items sync.Map // stores map[string]weak.Pointer[Item]
}

// GetPayload demonstrates incorrect handling: dereferences without validation,
// and assumes weak pointer survives between lookups and dereference.
func (c *Cache) GetPayload(key string) []byte {
	v, ok := c.items.Load(key)
	if !ok {
		return nil
	}
	wp := v.(weak.Pointer[Item])
	// BAD: Dereferencing without nil checking; if GC collects Item between Load
	// and Value(), this causes a panic or nil dereference.
	return wp.Value().Payload
}
```

#### Production Standard (Correct)
> **Standard**: Promotes the weak.Pointer to a strong stack reference and safely handles the reclaimed nil state with CompareAndDelete. Uses Go 1.24 runtime.AddCleanup to detach finalizer cycles and guarantees object longevity via explicit runtime.KeepAlive.
```go
package cache

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

type Item struct {
	Payload []byte
}

type SafeCache struct {
	items sync.Map // string -> weak.Pointer[Item]
}

func (c *SafeCache) Get(key string) (*Item, bool) {
	v, ok := c.items.Load(key)
	if !ok {
		return nil, false
	}

	wp := v.(weak.Pointer[Item])
	// Promote weak pointer to strong pointer in the current stack frame
	strong := wp.Value()
	if strong == nil {
		// GC has already reclaimed the target; eagerly scrub dead cache key
		c.items.CompareAndDelete(key, wp)
		return nil, false
	}

	// Pin strong reference across return boundary
	runtime.KeepAlive(strong)
	return strong, true
}

func (c *SafeCache) Put(key string, item *Item) {
	wp := weak.Make(item)
	c.items.Store(key, wp)

	// Register Go 1.24 cleanup without passing 'item' directly to avoid resurrection
	runtime.AddCleanup(item, func(k string) {
		c.items.CompareAndDelete(k, wp)
	}, key)
}
```

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 Eviction and Memory Pinning Standard

Go 1.24 Weak Pointer Cache Eviction and Memory Pinning Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic memory reclamation patterns in high-throughput caching tiers using Go 1.24+ 'weak' references and 'runtime.KeepAlive' pin semantics. Prevents finalizer race conditions, memory retention leaks, and use-after-collection panics caused by naive strong pointer caching or premature GC sweeps during heavy concurrent allocation cycles. 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 Canonicalizer Caches or Accessing Dereferenced Weak Pointers Without Immediate Strong Binding and Pinning 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 Canonicalizer Caches or Accessing Dereferenced Weak Pointers Without Immediate Strong Binding and PinningCritical
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 promote a weak.Pointer[T] to a strong pointer *T and explicitly verify non-nil status before invoking any methods or accessing fields.

Engineers MUST ALWAYS promote a weak.Pointer[T] to a strong pointer *T and explicitly verify non-nil status before invoking any methods or 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 NEVER access an object through a weak.Pointer without capturing it into a local strong pointer variable within the active stack frame.

Engineers MUST NEVER access an object through a weak.Pointer without capturing it into a local strong pointer variable within the active stack frame.

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 use sync.Map or partitioned mutexes storing weak.Pointer[T] handles to build deduplicating/canonicalizing caches, allowing the Go 1.24 GC to evict unreferenced entries automatically.

Engineers MUST use sync.Map or partitioned mutexes storing weak.Pointer[T] handles to build deduplicating/canonicalizing caches, allowing the Go 1.24 GC to evict unreferenced entries automatically.

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 invoke runtime.KeepAlive(val) at the end of critical operation boundaries whenever raw memory addresses or intermediate unsafe buffers depend on the lifetime of the promoted strong pointer.

Engineers MUST invoke runtime.KeepAlive(val) at the end of critical operation boundaries whenever raw memory addresses or intermediate unsafe buffers depend on the lifetime of the promoted strong pointer.

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

Engineers MUST NOT rely on runtime.SetFinalizer for memory eviction or cleanup in weak-pointer architectures

Engineers MUST NOT rely on runtime.SetFinalizer for memory eviction or cleanup in weak-pointer architectures; use runtime.AddCleanup (introduced in Go 1.24) with independent handle values to avoid cyclic reference memory leaks and resurrection bugs.

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 Eviction and Memory Pinning Standard critical for AI coding assistants?

Enforces deterministic memory reclamation patterns in high-throughput caching tiers using Go 1.24+ 'weak' references and 'runtime.KeepAlive' pin semantics. Prevents finalizer race conditions, memory retention leaks, and use-after-collection panics caused by naive strong pointer caching or premature GC sweeps during heavy concurrent allocation cycles. 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 Canonicalizer Caches or Accessing Dereferenced Weak Pointers Without Immediate Strong Binding and Pinning) 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