This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-coroutine-range-over-func-leak-prevention

Go 1.24 Coroutine Pull-Iterator Resource Leak and Panic Unwinding Standard

Enforces strict lifecycle management and deterministic cleanup for Go 1.24 range-over-func push-to-pull iterator conversions (`iter.Pull` and `iter.Pull2`). Guarantees that pull-iterator coroutines terminate predictably upon early consumer termination, panic propagation, or context cancellation without leaking coroutine goroutines or underlying OS/database resources.

Prohibited Anti-Pattern: Orphaned Coroutine Goroutines and Leaked File/Connection Handles via Discarded iter.Pull Stop Functions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Coroutine Pull-Iterator Resource Leak and Panic Unwinding Standard - Enforces strict lifecycle management and deterministic cleanup for Go 1.24 range-over-func push-to-pull iterator conversions (`iter.Pull` and `iter.Pull2`). Guarantees that pull-iterator coroutines terminate predictably upon early consumer termination, panic propagation, or context cancellation without leaking coroutine goroutines or underlying OS/database resources.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-coroutine-range-over-func-leak-prevention"
---

# Go 1.24 Coroutine Pull-Iterator Resource Leak and Panic Unwinding Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Orphaned Coroutine Goroutines and Leaked File/Connection Handles via Discarded iter.Pull Stop Functions

## System Constraints
You are a Principal Backend Engineer enforcing memory and concurrency safety standards for Go 1.23+ and Go 1.24 range-over-func iterators. You must mandate that every `iter.Pull` and `iter.Pull2` call is immediately paired with a guaranteed `defer stop()` execution. You must ensure that push iterators (`iter.Seq`, `iter.Seq2`) correctly observe yield boolean returns, respect context cancellation, and execute deferred cleanup blocks even when consumers exit early or experience runtime panics.

## Strict Guidelines
- Engineers MUST ALWAYS immediately invoke `defer stop()` in the exact same scope where `next, stop := iter.Pull(seq)` (or `iter.Pull2`) is initialized.
- Engineers MUST NOT discard or conditionally invoke the `stop()` closure returned by `iter.Pull` under any execution path or early return condition.
- Push iterator implementations (`iter.Seq[V]`, `iter.Seq2[K, V]`) MUST IMMEDIATELY break iteration and return once the `yield` callback returns `false`.
- Push iterators wrapping I/O handles, database cursors, or network sockets MUST place resource releases in `defer` statements prior to any loop execution to guarantee unwinding during panics or consumer aborts.
- Long-running or blocking pull-iterator consumers MUST incorporate context cancellation checks within the consumer loop to avoid hanging against stalled iterator generators.
- Custom iterator adapters MUST NEVER swallow panics originating from inside consumer iteration or upstream `yield` callbacks.

## Bad vs Good Implementations
### Proper cleanup and deferral of iter.Pull iterator coroutines

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When the matching target is found, the function returns early without calling 'stop()'. Because iter.Pull synthesizes a coroutine goroutine to convert push iteration into pull iteration, failing to call stop() permanently leaks that background goroutine and all associated resources.
```go
package iterator

import (
	"context"
	"iter"
)

func ProcessFirstMatching(ctx context.Context, seq iter.Seq[string], target string) (string, bool) {
	// ANTI-PATTERN: stop() is not deferred; early return leaks the coroutine goroutine
	next, stop := iter.Pull(seq)
	for {
		val, ok := next()
		if !ok {
			stop()
			return "", false
		}
		if val == target {
			// LEAK: returning here leaves the hidden iter.Pull goroutine running
			return val, true
		}
	}
}
```

#### Production Standard (Correct)
> **Standard**: Invoking 'defer stop()' immediately guarantees that the coroutine goroutine is safely unwound and terminated whenever the consumer exits, whether through a successful match, exhaustion, context cancellation, or an unhandled panic.
```go
package iterator

import (
	"context"
	"iter"
)

func ProcessFirstMatching(ctx context.Context, seq iter.Seq[string], target string) (string, bool) {
	// PRODUCTION INVARIANT: defer stop() immediately to guarantee coroutine unwinding
	next, stop := iter.Pull(seq)
	defer stop()

	for {
		select {
		case <-ctx.Done():
			return "", false
		default:
		}

		val, ok := next()
		if !ok {
			return "", false
		}
		if val == target {
			return val, true
		}
	}
}
```

### Yield return checking with deferred I/O release in push iterators

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Ignoring the boolean returned by 'yield(id, name)' forces the database iterator to continue scanning rows even after the caller breaks from the loop. Furthermore, rows.Close() is not deferred, leaving connections open if yield panics or if the loop exits prematurely.
```go
package iterator

import (
	"database/sql"
	"iter"
)

func QueryUsers(db *sql.DB) iter.Seq2[int64, string] {
	return func(yield func(int64, string) bool) {
		rows, err := db.Query("SELECT id, name FROM users")
		if err != nil {
			return
		}
		// ANTI-PATTERN: rows.Close is manually placed at bottom, ignored if yield() breaks
		for rows.Next() {
			var id int64
			var name string
			_ = rows.Scan(&id, &name)
			yield(id, name) // Return value ignored; iteration continues even if consumer aborts
		}
		rows.Close()
	}
}
```

#### Production Standard (Correct)
> **Standard**: The database cursor cleanup is deferred before iteration begins, guaranteeing cleanup on panics. The return value of 'yield(id, name)' is checked, immediately halting upstream row fetching as soon as the downstream consumer signals completion.
```go
package iterator

import (
	"database/sql"
	"iter"
)

func QueryUsers(db *sql.DB) iter.Seq2[int64, string] {
	return func(yield func(int64, string) bool) {
		rows, err := db.Query("SELECT id, name FROM users")
		if err != nil {
			return
		}
		// PRODUCTION INVARIANT: Defer connection closure to unwind on consumer break or panic
		defer rows.Close()

		for rows.Next() {
			var id int64
			var name string
			if err := rows.Scan(&id, &name); err != nil {
				return
			}
			if !yield(id, name) {
				// Early consumer termination explicitly halts query processing
				return
			}
		}
	}
}
```

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 Coroutine Pull-Iterator Resource Leak and Panic Unwinding Standard

Go 1.24 Coroutine Pull-Iterator Resource Leak and Panic Unwinding Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict lifecycle management and deterministic cleanup for Go 1.24 range-over-func push-to-pull iterator conversions (`iter.Pull` and `iter.Pull2`). Guarantees that pull-iterator coroutines terminate predictably upon early consumer termination, panic propagation, or context cancellation without leaking coroutine goroutines or underlying OS/database resources. 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: Orphaned Coroutine Goroutines and Leaked File/Connection Handles via Discarded iter.Pull Stop Functions 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 DriftOrphaned Coroutine Goroutines and Leaked File/Connection Handles via Discarded iter.Pull Stop FunctionsCritical
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 immediately invoke `defer stop()` in the exact same scope where `next, stop

Engineers MUST ALWAYS immediately invoke `defer stop()` in the exact same scope where `next, stop := iter.Pull(seq)` (or `iter.Pull2`) is initialized.

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 discard or conditionally invoke the `stop()` closure returned by `iter.Pull` under any execution path or early return condition.

Engineers MUST NOT discard or conditionally invoke the `stop()` closure returned by `iter.Pull` under any execution path or early return condition.

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

Push iterator implementations (`iter.Seq[V]`, `iter.Seq2[K, V]`) MUST IMMEDIATELY break iteration and return once the `yield` callback returns `false`.

Push iterator implementations (`iter.Seq[V]`, `iter.Seq2[K, V]`) MUST IMMEDIATELY break iteration and return once the `yield` callback returns `false`.

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

Push iterators wrapping I/O handles, database cursors, or network sockets MUST place resource releases in `defer` statements prior to any loop execution to guarantee unwinding during panics or consumer aborts.

Push iterators wrapping I/O handles, database cursors, or network sockets MUST place resource releases in `defer` statements prior to any loop execution to guarantee unwinding during panics or consumer aborts.

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

Long-running or blocking pull-iterator consumers MUST incorporate context cancellation checks within the consumer loop to avoid hanging against stalled iterator generators.

Long-running or blocking pull-iterator consumers MUST incorporate context cancellation checks within the consumer loop to avoid hanging against stalled iterator generators.

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.
6

Custom iterator adapters MUST NEVER swallow panics originating from inside consumer iteration or upstream `yield` callbacks.

Custom iterator adapters MUST NEVER swallow panics originating from inside consumer iteration or upstream `yield` 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.
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 Coroutine Pull-Iterator Resource Leak and Panic Unwinding Standard critical for AI coding assistants?

Enforces strict lifecycle management and deterministic cleanup for Go 1.24 range-over-func push-to-pull iterator conversions (`iter.Pull` and `iter.Pull2`). Guarantees that pull-iterator coroutines terminate predictably upon early consumer termination, panic propagation, or context cancellation without leaking coroutine goroutines or underlying OS/database resources. 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 (Orphaned Coroutine Goroutines and Leaked File/Connection Handles via Discarded iter.Pull Stop Functions) 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