This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-1-24-runtime-addcleanup-finalizer-replacement

Go 1.24 runtime.AddCleanup Finalizer Replacement Standard

Mandates replacing legacy runtime.SetFinalizer with Go 1.24's runtime.AddCleanup across unmanaged OS descriptors and Cgo lifecycles. Eliminates multi-cycle GC retention, resurrection vulnerabilities, and serialized finalizer goroutine deadlocks by decoupling deallocation state from parent object references.

Prohibited Anti-Pattern: Using runtime.SetFinalizer Induces Object Resurrection, Multi-Cycle GC Leaks, and Serialized Goroutine Head-of-Line Blocking

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 runtime.AddCleanup Finalizer Replacement Standard - Mandates replacing legacy runtime.SetFinalizer with Go 1.24's runtime.AddCleanup across unmanaged OS descriptors and Cgo lifecycles. Eliminates multi-cycle GC retention, resurrection vulnerabilities, and serialized finalizer goroutine deadlocks by decoupling deallocation state from parent object references.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-1-24-runtime-addcleanup-finalizer-replacement"
---

# Go 1.24 runtime.AddCleanup Finalizer Replacement Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Using runtime.SetFinalizer Induces Object Resurrection, Multi-Cycle GC Leaks, and Serialized Goroutine Head-of-Line Blocking

## System Constraints
You are a Principal Systems Architect enforcing the Go 1.24 runtime.AddCleanup standard. Prohibit runtime.SetFinalizer. Enforce value-type state passing to prevent closure-based object resurrection and stop redundant cleanup runs on manual resource exhaustion.

## Strict Guidelines
- Engineers MUST ALWAYS use runtime.AddCleanup instead of runtime.SetFinalizer for Go 1.24+ targets.
- Engineers MUST NOT capture the source pointer, parent struct, or circular references within the cleanup closure or its argument value.
- Engineers MUST pass only disconnected primitive values or isolated handles (e.g., uintptr, int, C.int) as the argument to the cleanup function.
- Code MUST store the returned runtime.Cleanup handle and invoke cleanup.Stop() inside deterministic Close()/Release() methods to prevent duplicate teardown.
- Components NEVER attach cleanups to interior heap pointers or transient stack allocations where reference escape analysis cannot be verified.

## Bad vs Good Implementations
### Reclaiming Cgo Memory and File Descriptors via runtime.AddCleanup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: runtime.SetFinalizer requires the target object to be reachable by the finalizer function, resurrecting the object and preventing immediate reclamation. It forces a minimum of two full GC cycles to collect, does not run on reference cycles, and executes sequentially on a single goroutine, causing unbounded head-of-line blocking under high descriptor churn.
```go
package resource

import (
	"os"
	"runtime"
)

type SafeDescriptor struct {
	file *os.File
}

func NewSafeDescriptor(f *os.File) *SafeDescriptor {
	sd := &SafeDescriptor{file: f}
	// ANTI-PATTERN: SetFinalizer passes sd back, resurrecting it for at least
	// one additional GC cycle. If SafeDescriptor is part of a cycle, the finalizer
	// may never execute. Cleanups run on a single shared finalizer goroutine.
	runtime.SetFinalizer(sd, func(d *SafeDescriptor) {
		if d.file != nil {
			_ = d.file.Close()
		}
	})
	return sd
}

func (sd *SafeDescriptor) Close() error {
	runtime.SetFinalizer(sd, nil) // High runtime lock contention
	return sd.file.Close()
}
```

#### Production Standard (Correct)
> **Standard**: runtime.AddCleanup takes a distinct argument value (the raw file descriptor integer) rather than a pointer to the parent struct. The target struct is freed immediately in the current GC cycle without resurrection. Storing and calling cleanup.Stop() in Close() avoids redundant syscalls and eliminates runtime registry overhead.
```go
package resource

import (
	"errors"
	"runtime"
	"sync/atomic"
	"syscall"
)

type SafeDescriptor struct {
	fd      int
	cleanup runtime.Cleanup
	closed  atomic.Bool
}

func finalizeFD(fd int) {
	if fd >= 0 {
		_ = syscall.Close(fd)
	}
}

func NewSafeDescriptor(fd int) *SafeDescriptor {
	sd := &SafeDescriptor{fd: fd}
	// PRODUCTION INVARIANT: Pass only disconnected value types (int).
	// The target object (sd) is freed IMMEDIATELY in the current GC cycle.
	// No closure captures sd, eliminating object resurrection entirely.
	sd.cleanup = runtime.AddCleanup(sd, finalizeFD, fd)
	return sd
}

func (sd *SafeDescriptor) Close() error {
	if sd.closed.CompareAndSwap(false, true) {
		// Stop cleanup to prevent redundant execution and deregister from runtime table
		sd.cleanup.Stop()
		return syscall.Close(sd.fd)
	}
	return errors.New("resource already closed")
}
```

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 runtime.AddCleanup Finalizer Replacement Standard

Go 1.24 runtime.AddCleanup Finalizer Replacement Standard defines an industrial-grade behavioral standard for backend engineering. Mandates replacing legacy runtime.SetFinalizer with Go 1.24's runtime.AddCleanup across unmanaged OS descriptors and Cgo lifecycles. Eliminates multi-cycle GC retention, resurrection vulnerabilities, and serialized finalizer goroutine deadlocks by decoupling deallocation state from parent object 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: Using runtime.SetFinalizer Induces Object Resurrection, Multi-Cycle GC Leaks, and Serialized Goroutine Head-of-Line Blocking 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 DriftUsing runtime.SetFinalizer Induces Object Resurrection, Multi-Cycle GC Leaks, and Serialized Goroutine Head-of-Line BlockingCritical
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 runtime.AddCleanup instead of runtime.SetFinalizer for Go 1.24+ targets.

Engineers MUST ALWAYS use runtime.AddCleanup instead of runtime.SetFinalizer for Go 1.24+ targets.

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 capture the source pointer, parent struct, or circular references within the cleanup closure or its argument value.

Engineers MUST NOT capture the source pointer, parent struct, or circular references within the cleanup closure or its argument 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.
3

Engineers MUST pass only disconnected primitive values or isolated handles (e.g., uintptr, int, C.int) as the argument to the cleanup function.

Engineers MUST pass only disconnected primitive values or isolated handles (e.g., uintptr, int, C.int) as the argument to the cleanup function.

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 store the returned runtime.Cleanup handle and invoke cleanup.Stop() inside deterministic Close()/Release() methods to prevent duplicate teardown.

Code MUST store the returned runtime.Cleanup handle and invoke cleanup.Stop() inside deterministic Close()/Release() methods to prevent duplicate teardown.

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 attach cleanups to interior heap pointers or transient stack allocations where reference escape analysis cannot be verified.

Components NEVER attach cleanups to interior heap pointers or transient stack allocations where reference escape analysis cannot be verified.

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 runtime.AddCleanup Finalizer Replacement Standard critical for AI coding assistants?

Mandates replacing legacy runtime.SetFinalizer with Go 1.24's runtime.AddCleanup across unmanaged OS descriptors and Cgo lifecycles. Eliminates multi-cycle GC retention, resurrection vulnerabilities, and serialized finalizer goroutine deadlocks by decoupling deallocation state from parent object 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 (Using runtime.SetFinalizer Induces Object Resurrection, Multi-Cycle GC Leaks, and Serialized Goroutine Head-of-Line Blocking) 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