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

Go 1.24 Push Iterator Early-Exit and Goroutine Leak Prevention

Enforces strict termination and resource cleanup invariants in Go 1.24 range-over-func push iterators (iter.Seq and iter.Seq2). Yield calls returning false indicate downstream consumer breaks, requiring immediate cessation of traversal, deterministic lock releases, and active cancellation of associated producer goroutines.

Prohibited Anti-Pattern: Ignoring yield() return values or failing to propagate cancellation to concurrent worker goroutines during iterator breaks.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Push Iterator Early-Exit and Goroutine Leak Prevention - Enforces strict termination and resource cleanup invariants in Go 1.24 range-over-func push iterators (iter.Seq and iter.Seq2). Yield calls returning false indicate downstream consumer breaks, requiring immediate cessation of traversal, deterministic lock releases, and active cancellation of associated producer goroutines.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-range-over-func-early-exit-cleanup"
---

# Go 1.24 Push Iterator Early-Exit and Goroutine Leak Prevention

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Ignoring yield() return values or failing to propagate cancellation to concurrent worker goroutines during iterator breaks.

## System Constraints
You are a Principal Go Architect enforcing Go 1.24 range-over-func iterator invariants. You must ensure all custom iter.Seq and iter.Seq2 push implementations strictly respect yield() false return signals, guarantee deterministic cleanup via defers, and prevent concurrent goroutine leaks.

## Strict Guidelines
- Engineers MUST ALWAYS inspect the boolean return value of yield() and immediately exit the iterator function when yield() returns false.
- Engineers MUST NOT spawn unbounded concurrent worker goroutines inside or for an iterator without binding them to a context.Context or a deterministic done channel that is cancelled on early exit.
- Iterators acquiring synchronization primitives (sync.Mutex, sync.RWMutex) MUST release or unlock them via defer or before calling yield() to eliminate re-entrancy deadlocks.
- Iterators consuming from producer channels MUST ensure worker goroutines are not blocked indefinitely on unbuffered channel sends when consumer loops break early.
- Services MUST verify iterator tear-down paths using goleak or runtime.NumGoroutine checks in unit tests.

## Bad vs Good Implementations
### Concurrent Push Iterator Early-Exit Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Ignoring the boolean result from yield(val) means the range loop continues even after the caller breaks. Worse, the concurrent producer goroutine leaks permanently, blocked indefinitely on unbuffered channel sends.
```go
package streaming

import "iter"

// BadIterator launches a producer goroutine but leaks it if the consumer breaks early.
func StreamBatches(items []string) iter.Seq[string] {
	return func(yield func(string) bool) {
	ch := make(chan string)
	go func() {
		for _, item := range items {
			// If consumer breaks early, this send blocks forever -> goroutine leak
			ch <- item
		}
		close(ch)
	}()

	for val := range ch {
		// BUG: Return value of yield is ignored, and channel remains unconsumed
		yield(val)
	}
	}
}
```

#### Production Standard (Correct)
> **Standard**: The iterator immediately returns when yield() evaluates to false, which runs the deferred cancel() call. The concurrent worker terminates safely via ctx.Done(), preventing any goroutine leakage.
```go
package streaming

import (
	"context"
	"iter"
)

// StreamBatches safely manages producer cancellation and terminates immediately on yield break.
func StreamBatches(items []string) iter.Seq[string] {
	return func(yield func(string) bool) {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()

		ch := make(chan string)
		go func() {
			defer close(ch)
			for _, item := range items {
				select {
				case <-ctx.Done():
					return
				case ch <- item:
				}
			}
		}()

		for val := range ch {
			if !yield(val) {
				// Consumer broke out of loop: return triggers defer cancel(), killing the worker
				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 Push Iterator Early-Exit and Goroutine Leak Prevention

Go 1.24 Push Iterator Early-Exit and Goroutine Leak Prevention defines an industrial-grade behavioral standard for backend engineering. Enforces strict termination and resource cleanup invariants in Go 1.24 range-over-func push iterators (iter.Seq and iter.Seq2). Yield calls returning false indicate downstream consumer breaks, requiring immediate cessation of traversal, deterministic lock releases, and active cancellation of associated producer goroutines. 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: Ignoring yield() return values or failing to propagate cancellation to concurrent worker goroutines during iterator breaks. 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 DriftIgnoring yield() return values or failing to propagate cancellation to concurrent worker goroutines during iterator breaks.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 inspect the boolean return value of yield() and immediately exit the iterator function when yield() returns false.

Engineers MUST ALWAYS inspect the boolean return value of yield() and immediately exit the iterator function when yield() 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.
2

Engineers MUST NOT spawn unbounded concurrent worker goroutines inside or for an iterator without binding them to a context.Context or a deterministic done channel that is cancelled on early exit.

Engineers MUST NOT spawn unbounded concurrent worker goroutines inside or for an iterator without binding them to a context.Context or a deterministic done channel that is cancelled on early exit.

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

Iterators acquiring synchronization primitives (sync.Mutex, sync.RWMutex) MUST release or unlock them via defer or before calling yield() to eliminate re-entrancy deadlocks.

Iterators acquiring synchronization primitives (sync.Mutex, sync.RWMutex) MUST release or unlock them via defer or before calling yield() to eliminate re-entrancy deadlocks.

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

Iterators consuming from producer channels MUST ensure worker goroutines are not blocked indefinitely on unbuffered channel sends when consumer loops break early.

Iterators consuming from producer channels MUST ensure worker goroutines are not blocked indefinitely on unbuffered channel sends when consumer loops break early.

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

Services MUST verify iterator tear-down paths using goleak or runtime.NumGoroutine checks in unit tests.

Services MUST verify iterator tear-down paths using goleak or runtime.NumGoroutine checks in unit tests.

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 Push Iterator Early-Exit and Goroutine Leak Prevention critical for AI coding assistants?

Enforces strict termination and resource cleanup invariants in Go 1.24 range-over-func push iterators (iter.Seq and iter.Seq2). Yield calls returning false indicate downstream consumer breaks, requiring immediate cessation of traversal, deterministic lock releases, and active cancellation of associated producer goroutines. 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 (Ignoring yield() return values or failing to propagate cancellation to concurrent worker goroutines during iterator breaks.) 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