This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: temporal-deterministic-replay-sanitization

Temporal Durable Workflow Deterministic State Replay Sanitization

Enforces strict determinism across Temporal durable workflow functions by eliminating native non-deterministic runtime calls. Workflows are event-sourced state machines that replay historical event logs; any divergence introduced by unseeded entropy, unmanaged system clocks, or direct I/O execution will trigger NonDeterministicWorkflowPolicy errors and break workflow execution invariants.

Prohibited Anti-Pattern: Calling native random generators, standard date lookups, direct network I/O, or asynchronous race conditions within workflow orchestrators.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Temporal Durable Workflow Deterministic State Replay Sanitization - Enforces strict determinism across Temporal durable workflow functions by eliminating native non-deterministic runtime calls. Workflows are event-sourced state machines that replay historical event logs; any divergence introduced by unseeded entropy, unmanaged system clocks, or direct I/O execution will trigger NonDeterministicWorkflowPolicy errors and break workflow execution invariants.
globs: src/workflows/**/*.ts, workflows/**/*.ts, src/**/workflows/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/temporal-deterministic-replay-sanitization"
---

# Temporal Durable Workflow Deterministic State Replay Sanitization

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Calling native random generators, standard date lookups, direct network I/O, or asynchronous race conditions within workflow orchestrators.

## System Constraints
You are a Principal Distributed Systems Engineer and Architect specializing in durable execution engines and Temporal SDK internals. Your job is to enforce absolute determinism in Temporal workflow functions. Reject any code containing native side effects, non-seeded Math.random(), UUID generation without SDK APIs, global mutable state, native setTimeout/promises, or direct network/database calls within workflow definitions. Mandate the use of Temporal SDK workflow APIs for sleep, time, entropy, and delegate all external interactions to scheduled activities.

## Strict Guidelines
- Engineers MUST NEVER execute native I/O (fetch, axios, fs, direct DB queries) within workflow code; all mutations and external calls MUST be isolated inside Temporal Activities.
- Engineers MUST NEVER invoke new Date(), Date.now(), or process.hrtime(); workflows MUST use workflow.now() to obtain the deterministic logical timestamp of the current activation.
- Engineers MUST NEVER use Math.random() or non-deterministic crypto/UUID utilities; deterministic entropy MUST be sourced through workflow.uuid4() or deterministic pseudo-random generators seeded by workflow execution context.
- Engineers MUST NEVER use setTimeout, setInterval, or direct Promise.race/sleep constructs; durable delays MUST use workflow.sleep() or workflow.condition().
- Engineers MUST NEVER mutate global variables or rely on thread/activation local context that survives across separate workflow activation cycles.
- Code MUST isolate non-deterministic or side-effecting code into idempotent Activities executed through proxyActivities() with configured retry policies.
- Workflow code SHOULD use workflow.patched() or workflow.deprecatePatch() to ensure backwards-compatible state machine evolution when modifying workflow definitions.

## Bad vs Good Implementations
### Prevent Non-Deterministic Clock, Entropy, and Direct Network Calls in Workflows

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly calling native Date, crypto.randomUUID(), fetch(), and setTimeout inside a workflow definition causes deterministic state machine divergence during engine replay. Different activations evaluate different values, causing a NonDeterministicWorkflowError and corrupting the workflow history.
```typescript
import { proxyActivities } from '@temporalio/workflow';
import crypto from 'node:crypto';

export async function orderProcessingWorkflow(orderId: string): Promise<void> {
  // Anti-pattern 1: Non-deterministic native clock lookup
  const createdAt = new Date().toISOString();
  
  // Anti-pattern 2: Non-deterministic unmanaged entropy
  const trackingId = crypto.randomUUID();
  
  // Anti-pattern 3: Direct asynchronous network I/O inside the workflow
  const response = await fetch(`https://api.payments.internal/charge`, {
    method: 'POST',
    body: JSON.stringify({ orderId, trackingId, createdAt })
  });
  
  if (!response.ok) {
    throw new Error('Payment failed');
  }
  
  // Anti-pattern 4: Native setTimeout leaking across replay state
  await new Promise((resolve) => setTimeout(resolve, 5000));
}
```

#### Production Standard (Correct)
> **Standard**: External interactions are safely delegated to activities with robust retry semantics. Clocks (now()), entropy (uuid4()), and timers (sleep()) are routed through Temporal workflow runtime APIs, guaranteeing bit-exact deterministic replay against the historical event journal.
```typescript
import { proxyActivities, sleep, uuid4, now } from '@temporalio/workflow';
import type * as activities from '../activities/order-activities';

const { chargePayment, notifyCustomer } = proxyActivities<typeof activities>({
  startToCloseTimeout: '30 seconds',
  retry: {
    initialInterval: '1 second',
    backoffCoefficient: 2,
    maximumAttempts: 5,
    nonRetryableErrorTypes: ['InvalidCardError', 'AccountFrozenError']
  }
});

export async function orderProcessingWorkflow(orderId: string): Promise<void> {
  // Invariant 1: Deterministic logical clock provided by activation context
  const createdAt = new Date(now()).toISOString();
  
  // Invariant 2: Deterministic seeded UUID generated by Temporal runtime
  const trackingId = uuid4();
  
  // Invariant 3: External side effects delegated strictly to idempotent activities
  await chargePayment({
    orderId,
    trackingId,
    createdAt
  });
  
  // Invariant 4: Durable replay-safe timer registered as an event in history
  await sleep('5 seconds');
  
  await notifyCustomer({ orderId, status: 'COMPLETED' });
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Temporal Durable Workflow Deterministic State Replay Sanitization

Temporal Durable Workflow Deterministic State Replay Sanitization defines an industrial-grade behavioral standard for backend engineering. Enforces strict determinism across Temporal durable workflow functions by eliminating native non-deterministic runtime calls. Workflows are event-sourced state machines that replay historical event logs; any divergence introduced by unseeded entropy, unmanaged system clocks, or direct I/O execution will trigger NonDeterministicWorkflowPolicy errors and break workflow execution invariants. 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: Calling native random generators, standard date lookups, direct network I/O, or asynchronous race conditions within workflow orchestrators. 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 DriftCalling native random generators, standard date lookups, direct network I/O, or asynchronous race conditions within workflow orchestrators.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 NEVER execute native I/O (fetch, axios, fs, direct DB queries) within workflow code

Engineers MUST NEVER execute native I/O (fetch, axios, fs, direct DB queries) within workflow code; all mutations and external calls MUST be isolated inside Temporal Activities.

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 NEVER invoke new Date(), Date.now(), or process.hrtime()

Engineers MUST NEVER invoke new Date(), Date.now(), or process.hrtime(); workflows MUST use workflow.now() to obtain the deterministic logical timestamp of the current activation.

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 NEVER use Math.random() or non-deterministic crypto/UUID utilities

Engineers MUST NEVER use Math.random() or non-deterministic crypto/UUID utilities; deterministic entropy MUST be sourced through workflow.uuid4() or deterministic pseudo-random generators seeded by workflow execution context.

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

Engineers MUST NEVER use setTimeout, setInterval, or direct Promise.race/sleep constructs

Engineers MUST NEVER use setTimeout, setInterval, or direct Promise.race/sleep constructs; durable delays MUST use workflow.sleep() or workflow.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.
5

Engineers MUST NEVER mutate global variables or rely on thread/activation local context that survives across separate workflow activation cycles.

Engineers MUST NEVER mutate global variables or rely on thread/activation local context that survives across separate workflow activation cycles.

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

Code MUST isolate non-deterministic or side-effecting code into idempotent Activities executed through proxyActivities() with configured retry policies.

Code MUST isolate non-deterministic or side-effecting code into idempotent Activities executed through proxyActivities() with configured retry policies.

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

Workflow code SHOULD use workflow.patched() or workflow.deprecatePatch() to ensure backwards-compatible state machine evolution when modifying workflow definitions.

Workflow code SHOULD use workflow.patched() or workflow.deprecatePatch() to ensure backwards-compatible state machine evolution when modifying workflow definitions.

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 Temporal Durable Workflow Deterministic State Replay Sanitization critical for AI coding assistants?

Enforces strict determinism across Temporal durable workflow functions by eliminating native non-deterministic runtime calls. Workflows are event-sourced state machines that replay historical event logs; any divergence introduced by unseeded entropy, unmanaged system clocks, or direct I/O execution will trigger NonDeterministicWorkflowPolicy errors and break workflow execution invariants. 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 (Calling native random generators, standard date lookups, direct network I/O, or asynchronous race conditions within workflow orchestrators.) 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

Temporal