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

Go 1.24 Weak Pointer Ephemeral Cache Eviction and Epoch Boundary Contract

Isolates Go 1.24 `weak.Pointer` dereferences behind deterministic epoch boundaries to prevent silent memory resurrection, finalizer deadlocks, and stale slot retention. Mandates synchronized read promotion and epoch-gated cleanup loops to guarantee GC reclamation in high-throughput microservices.

Prohibited Anti-Pattern: Unsynchronized weak.Pointer dereference with inline map mutation and lock acquisition inside GC cleanup callbacks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer Ephemeral Cache Eviction and Epoch Boundary Contract - Isolates Go 1.24 `weak.Pointer` dereferences behind deterministic epoch boundaries to prevent silent memory resurrection, finalizer deadlocks, and stale slot retention. Mandates synchronized read promotion and epoch-gated cleanup loops to guarantee GC reclamation in high-throughput microservices.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-weak-pointer-ephemeral-cache-contract"
---

# Go 1.24 Weak Pointer Ephemeral Cache Eviction and Epoch Boundary Contract

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized weak.Pointer dereference with inline map mutation and lock acquisition inside GC cleanup callbacks

## System Constraints
You are a Principal Software Architect enforcing the Go 1.24 Weak Reference Ephemeral Cache Eviction Contract. Go 1.24 introduces standard weak pointers (`weak.Pointer[T]`). You must enforce strict architectural boundaries: weak pointer dereferences must never trigger synchronous cache mutations under lock, cleanup operations via `runtime.AddCleanup` must never acquire application-level mutexes or invoke blocking operations, and ephemeral cache entries must be evicted across isolated generational epoch boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS isolate `weak.Pointer.Value()` dereferencing from cache write-locks to prevent lock contention during GC phase transitions.
- Engineers MUST NOT acquire cache locks or trigger synchronous map deletes inside `runtime.AddCleanup` or finalizer callbacks.
- Services MUST route cleanup notifications through non-blocking, buffered channels or lock-free epoch queues for batched asynchronous eviction.
- Code SHOULD verify `weak.Pointer.Value()` against `nil` immediately upon dereferencing and promote to a strong reference only within local caller scope.
- Components NEVER store resurrected strong pointers back into weak cache slots within the same call stack without verifying epoch advancement.

## Bad vs Good Implementations
### Unsynchronized Weak Pointer Map with Deadlocking GC Cleanup vs Epoch-Buffered Eviction

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Attaching runtime.AddCleanup with an inline lock acquisition causes fatal deadlocks if the GC sweeps while a reader holds c.mu. Mutating the map directly on nil dereference creates write contention on cache reads and permits memory churn without epoch control.
```go
package cache

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

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

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

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

	// ANTI-PATTERN: runtime.AddCleanup captures lock and executes
	// unpredictably during GC mark/sweep, inducing runtime deadlocks
	runtime.AddCleanup(val, func(k K) {
		c.mu.Lock() // DEADLOCK HAZARD: Lock re-entrancy or GC thread stalls
		delete(c.items, k)
		c.mu.Unlock()
	}, key)
}

func (c *BadCache[K, V]) Get(key K) *V {
	c.mu.Lock()
	defer c.mu.Unlock()

	wp, ok := c.items[key]
	if !ok {
		return nil
	}
	v := wp.Value()
	if v == nil {
		// ANTI-PATTERN: Inline mutation under read contention
		delete(c.items, key)
	}
	return v
}
```

#### Production Standard (Correct)
> **Standard**: Separates weak pointer resolution from cache eviction. Dereferencing is performed outside write locks, stale keys are dispatched non-blockingly to a dedicated epoch-isolated eviction worker, and runtime cleanup callbacks are completely decoupled from cache synchronization primitives.
```go
package cache

import (
	"sync"
	"sync/atomic"
	"weak"
)

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

func New[K comparable, V any](bufferSize int) *Cache[K, V] {
	c := &Cache[K, V]{
		items:   make(map[K]weak.Pointer[V]),
		evictCh: make(chan K, bufferSize),
	}
	go c.evictionLoop()
	return c
}

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
	}

	// Safe promotion to strong pointer within local scope
	val := wp.Value()
	if val == nil {
		// Non-blocking notification to epoch eviction loop
		select {
		case c.evictCh <- key:
		default:
			c.dirty.Store(true)
		}
		return nil, false
	}
	return val, true
}

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

func (c *Cache[K, V]) evictionLoop() {
	for key := range c.evictCh {
		c.mu.Lock()
		if wp, ok := c.items[key]; ok && wp.Value() == nil {
			delete(c.items, key)
		}
		c.mu.Unlock()
	}
}
```

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 Ephemeral Cache Eviction and Epoch Boundary Contract

Go 1.24 Weak Pointer Ephemeral Cache Eviction and Epoch Boundary Contract defines an industrial-grade behavioral standard for backend engineering. Isolates Go 1.24 `weak.Pointer` dereferences behind deterministic epoch boundaries to prevent silent memory resurrection, finalizer deadlocks, and stale slot retention. Mandates synchronized read promotion and epoch-gated cleanup loops to guarantee GC reclamation in high-throughput microservices. 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 dereference with inline map mutation and lock acquisition inside GC cleanup callbacks 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 dereference with inline map mutation and lock acquisition inside GC cleanup callbacksCritical
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 isolate `weak.Pointer.Value()` dereferencing from cache write-locks to prevent lock contention during GC phase transitions.

Engineers MUST ALWAYS isolate `weak.Pointer.Value()` dereferencing from cache write-locks to prevent lock contention during GC phase transitions.

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 acquire cache locks or trigger synchronous map deletes inside `runtime.AddCleanup` or finalizer callbacks.

Engineers MUST NOT acquire cache locks or trigger synchronous map deletes inside `runtime.AddCleanup` or finalizer callbacks.

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 route cleanup notifications through non-blocking, buffered channels or lock-free epoch queues for batched asynchronous eviction.

Services MUST route cleanup notifications through non-blocking, buffered channels or lock-free epoch queues for batched asynchronous eviction.

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 SHOULD verify `weak.Pointer.Value()` against `nil` immediately upon dereferencing and promote to a strong reference only within local caller scope.

Code SHOULD verify `weak.Pointer.Value()` against `nil` immediately upon dereferencing and promote to a strong reference only within local caller scope.

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 resurrected strong pointers back into weak cache slots within the same call stack without verifying epoch advancement.

Components NEVER store resurrected strong pointers back into weak cache slots within the same call stack without verifying epoch advancement.

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 Ephemeral Cache Eviction and Epoch Boundary Contract critical for AI coding assistants?

Isolates Go 1.24 `weak.Pointer` dereferences behind deterministic epoch boundaries to prevent silent memory resurrection, finalizer deadlocks, and stale slot retention. Mandates synchronized read promotion and epoch-gated cleanup loops to guarantee GC reclamation in high-throughput microservices. 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 dereference with inline map mutation and lock acquisition inside GC cleanup callbacks) 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