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

Go 1.24 Weak Pointer & Canonical Cache Memory Retention Standard

Enforces Go 1.24 native weak pointer runtime primitives (weak.Pointer, weak.Make) across long-lived canonicalizing caches, deduplication tables, and cyclic structures. Eliminates unbounded heap growth, memory leaks from stale cache keys, and finalizer-induced retention cascades caused by cyclic strong references.

Prohibited Anti-Pattern: Unbounded Strong Reference Retention and Finalizer Deadlocks in Long-Lived Interning Structures

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer & Canonical Cache Memory Retention Standard - Enforces Go 1.24 native weak pointer runtime primitives (weak.Pointer, weak.Make) across long-lived canonicalizing caches, deduplication tables, and cyclic structures. Eliminates unbounded heap growth, memory leaks from stale cache keys, and finalizer-induced retention cascades caused by cyclic strong references.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go124-weak-pointer-cyclic-memory-guardrail"
---

# Go 1.24 Weak Pointer & Canonical Cache Memory Retention Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Strong Reference Retention and Finalizer Deadlocks in Long-Lived Interning Structures

## System Constraints
You are a Principal Systems Architect enforcing memory safety and GC invariants in Go 1.24+. Mandate the strict use of the native `weak` package for canonical interning caches, observer registrations, and parent-child cyclic references. Prohibit legacy finalizer-based resurrection patterns (`runtime.SetFinalizer`), prevent unbounded map key growth, and require explicit nil-checks on every weak pointer dereference.

## Strict Guidelines
- Engineers MUST ALWAYS use Go 1.24 `weak.Make` and `weak.Pointer[T]` when implementing intern tables, canonicalizing caches, or parent back-references across long-lived objects.
- Engineers MUST NEVER use `runtime.SetFinalizer` or `runtime.AddCleanup` to artificially break circular graph references or manage cache lifecycle, as cycles prevent finalization and delay GC reclamation.
- Code MUST ALWAYS evaluate whether `wp.Value()` returns `nil` before using the referenced object, as the garbage collector can reclaim weakly-held targets concurrently during any GC cycle.
- Services MUST implement periodic or tombstone-based key eviction strategies for maps holding `weak.Pointer` values to prevent map bucket and key memory exhaustion from dead entries.
- Components NEVER store direct strong pointers (*T) in global or singleton deduplication indices when the lifecycle of the deduplicated resource is intended to be governed by active consumer usage.

## Bad vs Good Implementations
### Canonicalizing Cache Implementation: Strong References vs Go 1.24 Weak Pointers

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The registry retains strong references to every Session created. Because the cache map outlives the operational scope of individual sessions, memory usage grows monotonically. Using runtime.SetFinalizer on Session would fail to trigger because the strong pointer in the map prevents the runtime from marking the session as unreachable.
```go
package cache

import (
	"sync"
)

type Session struct {
	ID   string
	Data []byte
}

// Bad: Canonicalizing cache holds strong pointers.
// Values are never reclaimed by GC even when all callers release them.
type SessionRegistry struct {
	mu       sync.RWMutex
	sessions map[string]*Session
}

func NewSessionRegistry() *SessionRegistry {
	return &SessionRegistry{
		sessions: make(map[string]*Session),
	}
}

func (r *SessionRegistry) Intern(id string, data []byte) *Session {
	r.mu.Lock()
	defer r.mu.Unlock()

	if s, exists := r.sessions[id]; exists {
		return s
	}

	s := &Session{ID: id, Data: data}
	r.sessions[id] = s // Strong reference causes indefinite retention leak
	return s
}
```

#### Production Standard (Correct)
> **Standard**: Go 1.24 `weak.Pointer[Session]` holds a non-owning reference to `*Session`. When callers discard their strong `*Session` handles, the Go GC reclaims the underlying session memory during the next mark-sweep phase. `wp.Value()` returns `nil` safely, and stale keys are purged during cache hits or during periodic sweeps.
```go
package cache

import (
	"sync"
	"weak"
)

type Session struct {
	ID   string
	Data []byte
}

// Good: Registry stores Go 1.24 native weak.Pointer[T].
// Objects are eligible for GC once all external strong references are released.
type SessionRegistry struct {
	mu       sync.RWMutex
	sessions map[string]weak.Pointer[Session]
}

func NewSessionRegistry() *SessionRegistry {
	return &SessionRegistry{
		sessions: make(map[string]weak.Pointer[Session]),
	}
}

func (r *SessionRegistry) Intern(id string, data []byte) *Session {
	r.mu.Lock()
	defer r.mu.Unlock()

	if wp, exists := r.sessions[id]; exists {
		if s := wp.Value(); s != nil {
			return s
		}
		// Evict tombstone if target was reclaimed by GC
		delete(r.sessions, id)
	}

	s := &Session{ID: id, Data: data}
	r.sessions[id] = weak.Make(s)
	return s
}

func (r *SessionRegistry) PruneStale() {
	r.mu.Lock()
	defer r.mu.Unlock()
	for k, wp := range r.sessions {
		if wp.Value() == nil {
			delete(r.sessions, k)
		}
	}
}
```

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 & Canonical Cache Memory Retention Standard

Go 1.24 Weak Pointer & Canonical Cache Memory Retention Standard defines an industrial-grade behavioral standard for backend engineering. Enforces Go 1.24 native weak pointer runtime primitives (weak.Pointer, weak.Make) across long-lived canonicalizing caches, deduplication tables, and cyclic structures. Eliminates unbounded heap growth, memory leaks from stale cache keys, and finalizer-induced retention cascades caused by cyclic strong references. 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: Unbounded Strong Reference Retention and Finalizer Deadlocks in Long-Lived Interning Structures 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 DriftUnbounded Strong Reference Retention and Finalizer Deadlocks in Long-Lived Interning StructuresCritical
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 Go 1.24 `weak.Make` and `weak.Pointer[T]` when implementing intern tables, canonicalizing caches, or parent back-references across long-lived objects.

Engineers MUST ALWAYS use Go 1.24 `weak.Make` and `weak.Pointer[T]` when implementing intern tables, canonicalizing caches, or parent back-references across long-lived 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.
2

Engineers MUST NEVER use `runtime.SetFinalizer` or `runtime.AddCleanup` to artificially break circular graph references or manage cache lifecycle, as cycles prevent finalization and delay GC reclamation.

Engineers MUST NEVER use `runtime.SetFinalizer` or `runtime.AddCleanup` to artificially break circular graph references or manage cache lifecycle, as cycles prevent finalization and delay GC reclamation.

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 ALWAYS evaluate whether `wp.Value()` returns `nil` before using the referenced object, as the garbage collector can reclaim weakly-held targets concurrently during any GC cycle.

Code MUST ALWAYS evaluate whether `wp.Value()` returns `nil` before using the referenced object, as the garbage collector can reclaim weakly-held targets concurrently during any GC cycle.

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 periodic or tombstone-based key eviction strategies for maps holding `weak.Pointer` values to prevent map bucket and key memory exhaustion from dead entries.

Services MUST implement periodic or tombstone-based key eviction strategies for maps holding `weak.Pointer` values to prevent map bucket and key memory exhaustion from dead entries.

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 direct strong pointers (*T) in global or singleton deduplication indices when the lifecycle of the deduplicated resource is intended to be governed by active consumer usage.

Components NEVER store direct strong pointers (*T) in global or singleton deduplication indices when the lifecycle of the deduplicated resource is intended to be governed by active consumer usage.

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 & Canonical Cache Memory Retention Standard critical for AI coding assistants?

Enforces Go 1.24 native weak pointer runtime primitives (weak.Pointer, weak.Make) across long-lived canonicalizing caches, deduplication tables, and cyclic structures. Eliminates unbounded heap growth, memory leaks from stale cache keys, and finalizer-induced retention cascades caused by cyclic strong references. 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 (Unbounded Strong Reference Retention and Finalizer Deadlocks in Long-Lived Interning Structures) 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