This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-124-synctest-virtual-time-boundary

Go 1.24 synctest Deterministic Concurrency and Virtual Time Boundary

Enforces strict virtual time isolation via the experimental Go 1.24 testing/synctest package for concurrent tests, consensus engines, and channel workflows. Prohibits non-deterministic wall-clock sleeps, unbounded polling loops, and leaky goroutines outside the isolated bubble. Guarantees 100% deterministic scheduling and instant time acceleration across concurrent goroutine topologies.

Prohibited Anti-Pattern: Flaky Wall-Clock Sleeps and Leaked Outer Goroutines in Concurrent State Machine Tests

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 synctest Deterministic Concurrency and Virtual Time Boundary - Enforces strict virtual time isolation via the experimental Go 1.24 testing/synctest package for concurrent tests, consensus engines, and channel workflows. Prohibits non-deterministic wall-clock sleeps, unbounded polling loops, and leaky goroutines outside the isolated bubble. Guarantees 100% deterministic scheduling and instant time acceleration across concurrent goroutine topologies.
globs: **/*_test.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-124-synctest-virtual-time-boundary"
---

# Go 1.24 synctest Deterministic Concurrency and Virtual Time Boundary

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Flaky Wall-Clock Sleeps and Leaked Outer Goroutines in Concurrent State Machine Tests

## System Constraints
You are a Principal Backend Architect enforcing strict deterministic concurrency testing in Go 1.24 using testing/synctest (GOEXPERIMENT=synctest). You must eliminate flaky tests caused by time.Sleep, external OS timer dependence, and uncoordinated goroutine scheduling. Every complex channel interaction, consensus state transition, and heartbeat protocol under test must run inside an isolated synctest.Run bubble where synthetic virtual time advances automatically only when all internal goroutines are blocked.

## Strict Guidelines
- Engineers MUST wrap concurrent asynchronous unit tests in `synctest.Run(func() { ... })` whenever channel race conditions, timers, contexts, or background workers are evaluated.
- Engineers MUST NOT introduce non-deterministic wall-clock synchronization primitives such as raw `time.Sleep` calls outside of `synctest.Run` bubbles to simulate race timing.
- Engineers MUST ensure that any background goroutine spawned during the test terminates before `synctest.Run` returns, preventing panic conditions caused by uncoordinated goroutine leakage outside the bubble.
- Code MUST explicitly call `synctest.Wait()` to verify that all goroutines inside the current bubble have reached a settled, durably blocked state before asserting state machine invariants.
- Code MUST NOT mix real-world external I/O (network sockets, live database calls, file locks) inside `synctest.Run` without mock interfaces, as real blocking system calls prevent virtual time advancement and cause deadlocks.

## Bad vs Good Implementations
### Deterministic Heartbeat Timeout Verification in Go 1.24 synctest

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using physical time.Sleep and context timeouts creates non-deterministic latency races. In high-load CI runners, 300ms might not be sufficient for the OS scheduler to wake the goroutine, causing intermittent test failures while wasting hundreds of milliseconds per run.
```go
package consensus_test

import (
	"context"
	"testing"
	"time"
)

func TestLeaderElectionTimeout_Flaky(t *testing.T) {
	// ANTI-PATTERN: Wall-clock sleep introduces flakiness in CI and artificially slows down tests
	ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
	defer cancel()

	elected := make(chan bool)
	go func() {
		select {
		case <-ctx.Done():
			elected <- true
		}
	}()

	// Arbitrary sleep attempting to let the goroutine block and context expire
	time.Sleep(300 * time.Millisecond)

	select {
	case val := <-elected:
		if !val {
			t.Fatal("expected leader election timeout")
		}
	default:
		t.Fatal("election timeout did not trigger in time")
	}
}
```

#### Production Standard (Correct)
> **Standard**: synctest.Run creates an isolated synthetic clock bubble. The 5-second timeout and 5-second sleep complete in sub-millisecond real time because virtual time advances immediately when all goroutines in the bubble are blocked. synctest.Wait guarantees precise scheduling and eliminates race conditions.
```go
package consensus_test

import (
	"context"
	"testing"
	"testing/synctest"
	"time"
)

func TestLeaderElectionTimeout_Deterministic(t *testing.T) {
	// PRODUCTION INVARIANT: Use Go 1.24 synctest virtual bubble to accelerate time deterministically
	synctest.Run(func() {
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()

		elected := make(chan bool, 1)
		go func() {
			select {
			case <-ctx.Done():
				elected <- true
			}
		}()

		// synctest.Wait ensures the spawned goroutine has settled into its select block
		synctest.Wait()

		// Virtual time instantly jumps to satisfy the context timeout without CPU delay
		time.Sleep(5 * time.Second)
		synctest.Wait()

		select {
		case val := <-elected:
			if !val {
				t.Fatal("expected leader election timeout")
			}
		default:
			t.Fatal("election timeout did not trigger deterministically")
		}
	})
}
```

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 synctest Deterministic Concurrency and Virtual Time Boundary

Go 1.24 synctest Deterministic Concurrency and Virtual Time Boundary defines an industrial-grade behavioral standard for backend engineering. Enforces strict virtual time isolation via the experimental Go 1.24 testing/synctest package for concurrent tests, consensus engines, and channel workflows. Prohibits non-deterministic wall-clock sleeps, unbounded polling loops, and leaky goroutines outside the isolated bubble. Guarantees 100% deterministic scheduling and instant time acceleration across concurrent goroutine topologies. 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: Flaky Wall-Clock Sleeps and Leaked Outer Goroutines in Concurrent State Machine Tests 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 DriftFlaky Wall-Clock Sleeps and Leaked Outer Goroutines in Concurrent State Machine TestsCritical
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 wrap concurrent asynchronous unit tests in `synctest.Run(func() { ... })` whenever channel race conditions, timers, contexts, or background workers are evaluated.

Engineers MUST wrap concurrent asynchronous unit tests in `synctest.Run(func() { ... })` whenever channel race conditions, timers, contexts, or background workers are evaluated.

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 introduce non-deterministic wall-clock synchronization primitives such as raw `time.Sleep` calls outside of `synctest.Run` bubbles to simulate race timing.

Engineers MUST NOT introduce non-deterministic wall-clock synchronization primitives such as raw `time.Sleep` calls outside of `synctest.Run` bubbles to simulate race timing.

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 ensure that any background goroutine spawned during the test terminates before `synctest.Run` returns, preventing panic conditions caused by uncoordinated goroutine leakage outside the bubble.

Engineers MUST ensure that any background goroutine spawned during the test terminates before `synctest.Run` returns, preventing panic conditions caused by uncoordinated goroutine leakage outside the bubble.

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 explicitly call `synctest.Wait()` to verify that all goroutines inside the current bubble have reached a settled, durably blocked state before asserting state machine invariants.

Code MUST explicitly call `synctest.Wait()` to verify that all goroutines inside the current bubble have reached a settled, durably blocked state before asserting state machine invariants.

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

Code MUST NOT mix real-world external I/O (network sockets, live database calls, file locks) inside `synctest.Run` without mock interfaces, as real blocking system calls prevent virtual time advancement and cause deadlocks.

Code MUST NOT mix real-world external I/O (network sockets, live database calls, file locks) inside `synctest.Run` without mock interfaces, as real blocking system calls prevent virtual time advancement and cause 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.
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 synctest Deterministic Concurrency and Virtual Time Boundary critical for AI coding assistants?

Enforces strict virtual time isolation via the experimental Go 1.24 testing/synctest package for concurrent tests, consensus engines, and channel workflows. Prohibits non-deterministic wall-clock sleeps, unbounded polling loops, and leaky goroutines outside the isolated bubble. Guarantees 100% deterministic scheduling and instant time acceleration across concurrent goroutine topologies. 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 (Flaky Wall-Clock Sleeps and Leaked Outer Goroutines in Concurrent State Machine Tests) 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