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

Go 1.24 weak.Pointer and runtime.AddCleanup Concurrent Cache Standard

Enforces deterministic weak reference caching and resource cleanup introduced in Go 1.24 using weak.Pointer and runtime.AddCleanup. Eliminates memory leaks from unbounded key retention and removes finalizer-induced object resurrection bugs in high-throughput concurrent services.

Prohibited Anti-Pattern: Retaining strong heap references in caches or passing target pointers to legacy SetFinalizer closures.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 weak.Pointer and runtime.AddCleanup Concurrent Cache Standard - Enforces deterministic weak reference caching and resource cleanup introduced in Go 1.24 using weak.Pointer and runtime.AddCleanup. Eliminates memory leaks from unbounded key retention and removes finalizer-induced object resurrection bugs in high-throughput concurrent services.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-weak-pointer-addcleanup-cache-standard"
---

# Go 1.24 weak.Pointer and runtime.AddCleanup Concurrent Cache Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining strong heap references in caches or passing target pointers to legacy SetFinalizer closures.

## System Constraints
You are a Principal Go Architect enforcing memory safety and cache lifecycle standards using Go 1.24 weak.Pointer and runtime.AddCleanup primitives. Mandate weak reference isolation, prohibit SetFinalizer usage, prevent closure-induced pointer leakage in cleanup callbacks, and ensure atomic nil-checks during weak pointer dereferencing.

## Strict Guidelines
- Engineers MUST ALWAYS dereference weak.Pointer[T].Value() into a local variable and verify nil before accessing fields.
- Engineers MUST NOT pass the monitored heap pointer or any closure referencing the heap pointer into runtime.AddCleanup, as doing so retains the object and disables GC.
- Engineers MUST NEVER use runtime.SetFinalizer in Go 1.24+, migrating all object teardown logic to runtime.AddCleanup to prevent object resurrection and delayed GC collection cycles.
- Concurrent caches MUST clean up stale map keys inside runtime.AddCleanup using an independent lookup key argument passed by value.
- Cleanup functions MUST be thread-safe, non-blocking, and NEVER attempt synchronous network I/O or acquire reentrant locks held by active caller goroutines.

## Bad vs Good Implementations
### Concurrent Cache Weak Eviction and Cleanup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using runtime.SetFinalizer delays garbage collection across cycles and introduces resurrection bugs. Passing val to the closure creates a strong pointer reference that prevents garbage collection indefinitely.
```go
package cache

import (
	"runtime"
	"sync"
)

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

func (c *Cache[K, V]) Set(key K, val *V) {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.items[key] = val

	// ANTI-PATTERN: SetFinalizer causes multi-cycle collection delays and object resurrection.
	// Passing 'val' inside the closure keeps the object alive, creating an uncollectable memory leak.
	runtime.SetFinalizer(val, func(v *V) {
		c.mu.Lock()
		delete(c.items, key)
		c.mu.Unlock()
	})
}
```

#### Production Standard (Correct)
> **Standard**: Uses Go 1.24 weak.Pointer[V] to allow immediate GC reclamation without map leaks. Uses runtime.AddCleanup passing key by value, preventing closure pointer capture and object resurrection.
```go
package cache

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

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

func (c *Cache[K, V]) Set(key K, val *V) {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.items[key] = weak.Make(val)

	// INVARIANT: Pass only the primitive key by value to runtime.AddCleanup.
	// Never capture 'val' or the 'weak.Pointer' in the cleanup closure.
	runtime.AddCleanup(val, func(cleanupKey K) {
		c.mu.Lock()
		defer c.mu.Unlock()
		if wp, exists := c.items[cleanupKey]; exists && wp.Value() == nil {
			delete(c.items, cleanupKey)
		}
	}, key)
}

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

	v := wp.Value()
	if v == nil {
		return nil, false
	}
	return v, 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 and runtime.AddCleanup Concurrent Cache Standard

Go 1.24 weak.Pointer and runtime.AddCleanup Concurrent Cache Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic weak reference caching and resource cleanup introduced in Go 1.24 using weak.Pointer and runtime.AddCleanup. Eliminates memory leaks from unbounded key retention and removes finalizer-induced object resurrection bugs in high-throughput concurrent services. 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 heap references in caches or passing target pointers to legacy SetFinalizer closures. 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 heap references in caches or passing target pointers to legacy SetFinalizer closures.Critical
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 weak.Pointer[T].Value() into a local variable and verify nil before accessing fields.

Engineers MUST ALWAYS dereference weak.Pointer[T].Value() into a local variable and verify 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 pass the monitored heap pointer or any closure referencing the heap pointer into runtime.AddCleanup, as doing so retains the object and disables GC.

Engineers MUST NOT pass the monitored heap pointer or any closure referencing the heap pointer into runtime.AddCleanup, as doing so retains the object and disables GC.

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 use runtime.SetFinalizer in Go 1.24+, migrating all object teardown logic to runtime.AddCleanup to prevent object resurrection and delayed GC collection cycles.

Engineers MUST NEVER use runtime.SetFinalizer in Go 1.24+, migrating all object teardown logic to runtime.AddCleanup to prevent object resurrection and delayed GC collection cycles.

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

Concurrent caches MUST clean up stale map keys inside runtime.AddCleanup using an independent lookup key argument passed by value.

Concurrent caches MUST clean up stale map keys inside runtime.AddCleanup using an independent lookup key argument passed by value.

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

Cleanup functions MUST be thread-safe, non-blocking, and NEVER attempt synchronous network I/O or acquire reentrant locks held by active caller goroutines.

Cleanup functions MUST be thread-safe, non-blocking, and NEVER attempt synchronous network I/O or acquire reentrant locks held by active caller goroutines.

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 and runtime.AddCleanup Concurrent Cache Standard critical for AI coding assistants?

Enforces deterministic weak reference caching and resource cleanup introduced in Go 1.24 using weak.Pointer and runtime.AddCleanup. Eliminates memory leaks from unbounded key retention and removes finalizer-induced object resurrection bugs in high-throughput concurrent services. 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 heap references in caches or passing target pointers to legacy SetFinalizer closures.) 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