This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-iter-pull-goroutine-leak-boundary

Go 1.24 iter.Pull2 Mandatory Teardown and Goroutine Lifecycle Boundary

Enforces strict deferred invocation of the teardown closure returned by Go 1.24 iter.Pull and iter.Pull2 conversions. Converting push-based sequence iterators into pull consumers instantiates an underlying coroutine pair; failure to execute the stop closure on early breaks, errors, or panics permanently leaks producer goroutines.

Prohibited Anti-Pattern: Omitting Immediate defer stop() on iter.Pull/iter.Pull2 Producer Coroutines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 iter.Pull2 Mandatory Teardown and Goroutine Lifecycle Boundary - Enforces strict deferred invocation of the teardown closure returned by Go 1.24 iter.Pull and iter.Pull2 conversions. Converting push-based sequence iterators into pull consumers instantiates an underlying coroutine pair; failure to execute the stop closure on early breaks, errors, or panics permanently leaks producer goroutines.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-iter-pull-goroutine-leak-boundary"
---

# Go 1.24 iter.Pull2 Mandatory Teardown and Goroutine Lifecycle Boundary

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Omitting Immediate defer stop() on iter.Pull/iter.Pull2 Producer Coroutines

## System Constraints
You are a Principal Software Architect enforcing Go 1.24 Pull Iterator (iter.Seq / iter.Seq2) Goroutine Leak Boundary standards. Mandate immediate deferred cleanup on pull iterator pairs, forbid the blank identifier discard of stop closures, and prioritize idiomatic push-based range loops.

## Strict Guidelines
- Engineers MUST ALWAYS pair calls to iter.Pull or iter.Pull2 immediately with an unconditional 'defer stop()' statement on the subsequent line.
- Engineers MUST NOT discard the stop closure using the blank identifier (e.g., 'next, _ := iter.Pull(seq)'), which permanently orphans producer goroutines on early break or panic.
- Code SHOULD prefer standard push-based 'for k, v := range seq' loops unless interleaved traversal, parallel zip operations, or manual stepping is strictly required.
- Services MUST ensure that the stop closure is invoked before function exit even if the pull loop encounters early break, return, or context cancellation.
- Components NEVER share the resulting 'next' and 'stop' closures across concurrent goroutines without external mutual exclusion, as pull iterators are strictly thread-unsafe.

## Bad vs Good Implementations
### Pull Iterator Goroutine Leakage vs Guaranteed Teardown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: iter.Pull2 converts push iteration to pull by spawning an internal coroutine runtime thread. Exiting via context cancellation or predicate match without calling stop() leaves the hidden producer goroutine suspended in memory forever.
```go
package stream

import (
	"context"
	"errors"
	"iter"
)

func FindFirstMatch[K comparable, V any](
	ctx context.Context,
	seq iter.Seq2[K, V],
	predicate func(K, V) bool,
) (K, V, error) {
	// ANTI-PATTERN: Discarding or neglecting stop() leaks the underlying
	// coroutine created by iter.Pull2 if an early return triggers.
	next, stop := iter.Pull2(seq)
	// Missing defer stop()!

	for {
		if err := ctx.Err(); err != nil {
			// Producer goroutine blocked indefinitely on yield synchronization channel
			var zeroK K
			var zeroV V
			return zeroK, zeroV, err
		}

		k, v, ok := next()
		if !ok {
			break
		}
		if predicate(k, v) {
			// Leaks goroutine: loop terminated without notifying iterator producer
			return k, v, nil
		}
	}

	stop() // Only runs on full exhaustion; missed on early return!
	var zeroK K
	var zeroV V
	return zeroK, zeroV, errors.New("not found")
}
```

#### Production Standard (Correct)
> **Standard**: Placing 'defer stop()' directly after iter.Pull2 guarantees that the internal runtime coroutine receives the termination signal immediately when FindFirstMatch exits, safely releasing all resources.
```go
package stream

import (
	"context"
	"errors"
	"iter"
)

func FindFirstMatch[K comparable, V any](
	ctx context.Context,
	seq iter.Seq2[K, V],
	predicate func(K, V) bool,
) (K, V, error) {
	next, stop := iter.Pull2(seq)
	// INVARIANT: stop() MUST be deferred immediately to ensure the coroutine
	// is terminated regardless of return path, early break, or panic.
	defer stop()

	for {
		if err := ctx.Err(); err != nil {
			var zeroK K
			var zeroV V
			return zeroK, zeroV, err
		}

		k, v, ok := next()
		if !ok {
			break
		}
		if predicate(k, v) {
			return k, v, nil
		}
	}

	var zeroK K
	var zeroV V
	return zeroK, zeroV, errors.New("not found")
}
```

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 iter.Pull2 Mandatory Teardown and Goroutine Lifecycle Boundary

Go 1.24 iter.Pull2 Mandatory Teardown and Goroutine Lifecycle Boundary defines an industrial-grade behavioral standard for backend engineering. Enforces strict deferred invocation of the teardown closure returned by Go 1.24 iter.Pull and iter.Pull2 conversions. Converting push-based sequence iterators into pull consumers instantiates an underlying coroutine pair; failure to execute the stop closure on early breaks, errors, or panics permanently leaks 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: Omitting Immediate defer stop() on iter.Pull/iter.Pull2 Producer Coroutines 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 DriftOmitting Immediate defer stop() on iter.Pull/iter.Pull2 Producer CoroutinesCritical
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 pair calls to iter.Pull or iter.Pull2 immediately with an unconditional 'defer stop()' statement on the subsequent line.

Engineers MUST ALWAYS pair calls to iter.Pull or iter.Pull2 immediately with an unconditional 'defer stop()' statement on the subsequent line.

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 the stop closure using the blank identifier (e.g., 'next, _

Engineers MUST NOT discard the stop closure using the blank identifier (e.g., 'next, _ := iter.Pull(seq)'), which permanently orphans producer goroutines on early break or panic.

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

Code SHOULD prefer standard push-based 'for k, v

Code SHOULD prefer standard push-based 'for k, v := range seq' loops unless interleaved traversal, parallel zip operations, or manual stepping is strictly required.

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

Services MUST ensure that the stop closure is invoked before function exit even if the pull loop encounters early break, return, or context cancellation.

Services MUST ensure that the stop closure is invoked before function exit even if the pull loop encounters early break, return, or context cancellation.

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 share the resulting 'next' and 'stop' closures across concurrent goroutines without external mutual exclusion, as pull iterators are strictly thread-unsafe.

Components NEVER share the resulting 'next' and 'stop' closures across concurrent goroutines without external mutual exclusion, as pull iterators are strictly thread-unsafe.

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 iter.Pull2 Mandatory Teardown and Goroutine Lifecycle Boundary critical for AI coding assistants?

Enforces strict deferred invocation of the teardown closure returned by Go 1.24 iter.Pull and iter.Pull2 conversions. Converting push-based sequence iterators into pull consumers instantiates an underlying coroutine pair; failure to execute the stop closure on early breaks, errors, or panics permanently leaks 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 (Omitting Immediate defer stop() on iter.Pull/iter.Pull2 Producer Coroutines) 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