[{"content":"# Encyclopedia > Event-history > Event History walkthrough with the Go SDK\n## Example of a non-deterministic Workflow Definition\n\nNow that Replay has been covered, this section will explain why a Workflow Definition needs to be\n[deterministic](https://docs.temporal.io/workflow-definition#deterministic-constraints) in order for Replay to work.\n\nA Workflow Definition is deterministic if every execution of it produces the same Commands in the same\nsequence given the same input.\n\nAs mentioned in the [`How History Replay Provides Durable Execution`](https://docs.temporal.io/encyclopedia/event-history/event-history-go#How-History-Replay-Provides-Durable-Execution)\nwalkthrough, in the case of a failure, a Worker requests the Event History to replay it. During Replay, the Worker runs\nthe Workflow code again to produce a set of Commands which is compared against the sequence of Commands in the Event\nHistory. When there’s a mismatch between the expected sequence of Commands the Worker expects based on the Event History\nand the actual sequence produced during Replay (due to non-determinism), Replay will be unable to continue.\n\nTo better understand why a Workflow Definition needs to be deterministic, it's helpful to look at one that violates\nit. In this case, this code will walk through a Workflow Definition that breaks the determinism constraint with a random\nnumber generator.\n```\n1func GenerateDailyReport(ctx workflow.Context) error {2\n3    options := workflow.ActivityOptions{4        StartToCloseTimeout: 45 * time.Minute,5    }6    ctx = workflow.WithActivityOptions(ctx, options)7\n8    // this Activity is always executed9    err := workflow.ExecuteActivity(ctx, ImportSalesData).Get(ctx, nil)10    if err != nil {11        return err12    }13\n14    if rand.Intn(100) >= 50 {15        workflow.Sleep(ctx, 4 * time.Hour)16    }17\n18    workflow.GetLogger(ctx).Info(\"Preparing to run daily report\")19    err = workflow.ExecuteActivity(ctx, RunDailyReport).Get(ctx, nil)20    if err != nil {21        return err22    }23\n24    return nil25}\n```\n\nStep 1/9Sends a CommandFirst execution#### The ImportSalesData Activity runs\n\nAs this Workflow executes step by step, the first line that results in a Command is the call to the ImportSalesData Activity. The Activity Execution succeeds, so the Temporal Service logs three Events to the Event History.\n\nCommands created1. ScheduleActivityTask(ImportSalesData)\nRelevant History Events1. ActivityTaskScheduled(ImportSalesData)- ActivityTaskStarted- ActivityTaskCompleted\n← Previous123456789Next →\nDuring the first execution, the random number is 84, so the Workflow starts a Timer and the Event History records\n`TimerStarted` and `TimerFired`. During Replay, the random number is 14, so the Workflow skips the Timer and produces a\n`ScheduleActivityTask` Command where the Event History expects `StartTimer`. That mismatch is what makes Replay fail.\n\nNote that non-deterministic failures do not fail the Workflow Execution by default. A non-deterministic failure is\nconsidered a [Workflow Task Failure](https://docs.temporal.io/references/failures#workflow-task-failures) which is considered a transient\nfailure, meaning it retries over and over. Users can also fix the source of non-determinism, perhaps by removing the\nActivity, and then restart the Workers. This means that this type of failure can recover by itself. You can also use a\nstrategy called versioning to address this non-determinism error. See [versioning](https://docs.temporal.io/develop/go/workflows/versioning) to\nlearn more.\n\nFor more information on how Temporal handles Durable Execution or to see these walkthroughs in video format with more\nexplanation, check out our free, self-paced courses: [Temporal 102](https://learn.temporal.io/courses/temporal_102/) and\n[Versioning Workflows](https://learn.temporal.io/courses/versioning/).","source_url":"https://docs.temporal.io/encyclopedia/event-history/event-history-go.md","page_url":"https://docs.temporal.io/encyclopedia/event-history/event-history-go#Example-of-Non-Deterministic-Workflow"},{"content":"# Encyclopedia > Event-history > Event History walkthrough with the TypeScript SDK\n## Example of a non-deterministic Workflow Definition\n\nNow that Replay has been covered, this section will explain why a Workflow Definition needs to be\n[deterministic](https://docs.temporal.io/workflow-definition#deterministic-constraints) in order for Replay to work.\n\nA Workflow Definition is deterministic if every execution of it produces the same Commands in the same\nsequence given the same input.\n\nAs mentioned in the [`How History Replay Provides Durable Execution`](https://docs.temporal.io/encyclopedia/event-history/event-history-typescript#How-History-Replay-Provides-Durable-Execution)\nwalkthrough, in the case of a failure, a Worker requests the Event History to replay it. During Replay, the Worker runs\nthe Workflow code again to produce a set of Commands which is compared against the sequence of Commands in the Event\nHistory. When there’s a mismatch between the expected sequence of Commands the Worker expects based on the Event History\nand the actual sequence produced during Replay (due to non-determinism), Replay will be unable to continue.\n\nTo better understand why a Workflow Definition needs to be deterministic, it's helpful to look at one that violates\nit. In this case, this code will walk through a Workflow Definition that breaks the determinism constraint with a random\nnumber generator.\n```\n1const { importSalesData, runDailyReport } = proxyActivities<typeof activities>({2  startToCloseTimeout: '45 minutes',3});4\n5export async function generateDailyReport(): Promise<void> {6  await importSalesData();7\n8  if (getRandomNumber(1, 100) >= 50) {9    await sleep('4 hours');10  }11\n12  log.info('Preparing to run daily report', {});13\n14  await runDailyReport();15}\n```\n\nStep 1/9Sends a CommandFirst execution#### The importSalesData Activity runs\n\nAs this Workflow executes step by step, the first line that results in a Command is the call to the importSalesData Activity. The Activity Execution succeeds, so the Temporal Service logs three Events to the Event History.\n\nCommands created1. ScheduleActivityTask(importSalesData)\nRelevant History Events1. ActivityTaskScheduled(importSalesData)- ActivityTaskStarted- ActivityTaskCompleted\n← Previous123456789Next →\nDuring the first execution, the random number is 84, so the Workflow starts a Timer and the Event History records\n`TimerStarted` and `TimerFired`. During Replay, the random number is 14, so the Workflow skips the Timer and produces a\n`ScheduleActivityTask` Command where the Event History expects `StartTimer`. That mismatch is what makes Replay fail.\n\nNote that non-deterministic failures do not fail the Workflow Execution by default. A non-deterministic failure is\nconsidered a [Workflow Task Failure](https://docs.temporal.io/references/failures#workflow-task-failures) which is considered a transient\nfailure, meaning it retries over and over. Users can also fix the source of non-determinism, perhaps by removing the\nActivity, and then restart the Workers. This means that this type of failure can recover by itself. You can also use a\nstrategy called versioning to address this non-determinism error. See\n[versioning](https://docs.temporal.io/develop/typescript/workflows/versioning) to learn more.\n\nFor more information on how Temporal handles Durable Execution or to see these walkthroughs in video format with more\nexplanation, check out our free, self-paced courses: [Temporal 102](https://learn.temporal.io/courses/temporal_102/) and\n[Versioning Workflows](https://learn.temporal.io/courses/versioning/).","source_url":"https://docs.temporal.io/encyclopedia/event-history/event-history-typescript.md","page_url":"https://docs.temporal.io/encyclopedia/event-history/event-history-typescript#Example-of-Non-Deterministic-Workflow"},{"content":"# Encyclopedia > Event-history > Event History walkthrough with the .NET SDK\n## Example of a non-deterministic Workflow Definition\n\nNow that Replay has been covered, this section will explain why a Workflow Definition needs to be\n[deterministic](https://docs.temporal.io/workflow-definition#deterministic-constraints) in order for Replay to work.\n\nA Workflow Definition is deterministic if every execution of it produces the same Commands in the same\nsequence given the same input.\n\nAs mentioned in the [`How History Replay Provides Durable Execution`](https://docs.temporal.io/encyclopedia/event-history/event-history-dotnet#How-History-Replay-Provides-Durable-Execution)\nwalkthrough, in the case of a failure, a Worker requests the Event History to replay it. During Replay, the Worker runs\nthe Workflow code again to produce a set of Commands which is compared against the sequence of Commands in the Event\nHistory. When there’s a mismatch between the expected sequence of Commands the Worker expects based on the Event History\nand the actual sequence produced during Replay (due to non-determinism), Replay will be unable to continue.\n\nTo better understand why a Workflow Definition needs to be deterministic, it's helpful to look at one that violates\nit. In this case, this code will walk through a Workflow Definition that breaks the determinism constraint with a random\nnumber generator.\n```\n1[Workflow]2public class GenerateDailyReport3{4    private static readonly Random random = new Random();5\n6    [WorkflowRun]7    public async Task<string> RunAsync()8    {9        // Activity Options and logger declaration omitted for brevity10        var salesData = await Workflow.ExecuteActivityAsync(11            (Activities act) => act.ImportSalesDataAsync(),12            options);13\n14        if (random.Next(100) >= 50)15        {16            await Workflow.DelayAsync(TimeSpan.FromHours(4));17        }18\n19        Logger.LogInformation(\"Preparing to run daily report\");20\n21        return await Workflow.ExecuteActivityAsync(22            (Activities act) => act.RunDailyReportAsync(),23            options);24    }25}\n```\n\nStep 1/9Sends a CommandFirst execution#### The ImportSalesData Activity runs\n\nAs this Workflow executes step by step, the first line that results in a Command is the call to the ImportSalesData Activity. The Activity Execution succeeds, so the Temporal Service logs three Events to the Event History.\n\nCommands created1. ScheduleActivityTask(ImportSalesData)\nRelevant History Events1. ActivityTaskScheduled(ImportSalesData)- ActivityTaskStarted- ActivityTaskCompleted\n← Previous123456789Next →\nDuring the first execution, the random number is 84, so the Workflow starts a Timer and the Event History records\n`TimerStarted` and `TimerFired`. During Replay, the random number is 14, so the Workflow skips the Timer and produces a\n`ScheduleActivityTask` Command where the Event History expects `StartTimer`. That mismatch is what makes Replay fail.\n\nNote that non-deterministic failures do not fail the Workflow Execution by default. A non-deterministic failure is\nconsidered a [Workflow Task Failure](https://docs.temporal.io/references/failures#workflow-task-failures) which is considered a transient\nfailure, meaning it retries over and over. Users can also fix the source of non-determinism, perhaps by removing the\nActivity, and then restart the Workers. This means that this type of failure can recover by itself. You can also use a\nstrategy called versioning to address this non-determinism error. See [versioning](https://docs.temporal.io/develop/dotnet/workflows/versioning)\nto learn more.\n\nFor more information on how Temporal handles Durable Execution or to see these walkthroughs in video format with more\nexplanation, check out our free, self-paced courses: [Temporal 102](https://learn.temporal.io/courses/temporal_102/) and\n[Versioning Workflows](https://learn.temporal.io/courses/versioning/).","source_url":"https://docs.temporal.io/encyclopedia/event-history/event-history-dotnet.md","page_url":"https://docs.temporal.io/encyclopedia/event-history/event-history-dotnet#Example-of-Non-Deterministic-Workflow"},{"content":"# Encyclopedia > Event-history > Event History walkthrough with the Python SDK\n## Example of a non-deterministic Workflow Definition\n\nNow that Replay has been covered, this section will explain why a Workflow Definition needs to be\n[deterministic](https://docs.temporal.io/workflow-definition#deterministic-constraints) in order for Replay to work.\n\nA Workflow Definition is deterministic if every execution of it produces the same Commands in the same\nsequence given the same input.\n\nAs mentioned in the [`How History Replay Provides Durable Execution`](https://docs.temporal.io/encyclopedia/event-history/event-history-python#How-History-Replay-Provides-Durable-Execution)\nwalkthrough, in the case of a failure, a Worker requests the Event History to replay it. During Replay, the Worker runs\nthe Workflow code again to produce a set of Commands which is compared against the sequence of Commands in the Event\nHistory. When there’s a mismatch between the expected sequence of Commands the Worker expects based on the Event History\nand the actual sequence produced during Replay (due to non-determinism), Replay will be unable to continue.\n\nTo better understand why a Workflow Definition needs to be deterministic, it's helpful to look at one that violates\nit. In this case, this code will walk through a Workflow Definition that breaks the determinism constraint with a random\nnumber generator.\n```\n1@workflow.defn2class GenerateDailyReport:3    @workflow.run4    async def run(self) -> str:5        sales_data = await workflow.execute_activity_method(6            ReportActivities.import_sales_data,7            start_to_close_timeout=timedelta(minutes=45),8        )9\n10        if non_deterministic_number_generator(100) >= 50:11            # sleep for 4 hours12            await asyncio.sleep(timedelta(hours=4).total_seconds())13\n14        workflow.logger.info(\"Preparing to run daily report\")15\n16        return await workflow.execute_activity_method(17            ReportActivities.run_daily_report,18            sales_data,19            start_to_close_timeout=timedelta(minutes=45),20        )\n```\n\nStep 1/9Sends a CommandFirst execution#### The import_sales_data Activity runs\n\nAs this Workflow executes step by step, the first line that results in a Command is the call to the `import_sales_data` Activity. The Activity Execution succeeds, so the Temporal Service logs three Events to the Event History.\n\nCommands created1. ScheduleActivityTask(import_sales_data)\nRelevant History Events1. ActivityTaskScheduled(import_sales_data)- ActivityTaskStarted- ActivityTaskCompleted\n← Previous123456789Next →\nDuring the first execution, the random number is 84, so the Workflow starts a Timer and the Event History records\n`TimerStarted` and `TimerFired`. During Replay, the random number is 14, so the Workflow skips the Timer and produces a\n`ScheduleActivityTask` Command where the Event History expects `StartTimer`. That mismatch is what makes Replay fail.\n\nNote that non-deterministic failures do not fail the Workflow Execution by default. A non-deterministic failure is\nconsidered a [Workflow Task Failure](https://docs.temporal.io/references/failures#workflow-task-failures) which is considered a transient\nfailure, meaning it retries over and over. Users can also fix the source of non-determinism, perhaps by removing the\nActivity, and then restart the Workers. This means that this type of failure can recover by itself. You can also use a\nstrategy called versioning to address this non-determinism error. See [versioning](https://docs.temporal.io/develop/python/workflows/versioning)\nto learn more.\n\nFor more information on how Temporal handles Durable Execution or to see these walkthroughs in video format with more\nexplanation, check out our free, self-paced courses: [Temporal 102](https://learn.temporal.io/courses/temporal_102/) and\n[Versioning Workflows](https://learn.temporal.io/courses/versioning/).","source_url":"https://docs.temporal.io/encyclopedia/event-history/event-history-python.md","page_url":"https://docs.temporal.io/encyclopedia/event-history/event-history-python#Example-of-Non-Deterministic-Workflow"},{"content":"# Temporal Workflow Definition > What is a Workflow Definition?\n## Deterministic constraints\n\nA critical aspect of developing Workflow Definitions is ensuring that they are deterministic.\nGenerally speaking, this means you must take care to ensure that any time your Workflow code is executed it makes the same Workflow API calls in the same sequence, given the same input.\nSome changes to those API calls are safe to make.\n\nA Workflow Definition must be deterministic to support replay. To handle non-deterministic operations like API calls, LLM/AI invocations, database queries, and other external interactions, put them in Activities. Activities execute outside the replay path and are automatically retried so they don't cause non-determinism errors.\n\nFor example, you can change:\n\n- The input parameters, return values, and execution timeouts of Child Workflows and Activities, and the Retry Policy\n  of an Activity. See [Changing Activity arguments and options](https://docs.temporal.io/workflow-definition#activity-arguments-and-options).\n  - However, it is not safe to change the types or IDs of Child Workflows or Activities\n- The input parameters used to Signal an external Workflow\n- The duration of Timers (although changing them to 0 is not safe in all SDKs)\n- Add or remove calls to Workflow APIs that don't produce [Commands](https://docs.temporal.io/workflow-execution#command) (For example - `workflow.GetInfo` in the Go SDK or its equivalent in other SDKs)\n\nThe following Workflow API calls all can produce Commands, and thus must not be reordered, added, or removed without proper [Versioning techniques](https://docs.temporal.io/workflow-definition#workflow-versioning):\n\n- Starting or cancelling a Timer\n- Scheduling or cancelling Activity Executions (including local Activities)\n- Starting or cancelling Child Workflow executions\n- Signalling or cancelling signals to external Workflow Executions\n- Scheduling or cancelling Nexus operations\n- Ending the Workflow Execution in any way (completing, failing, cancelling, or continuing-as-new)\n- `Patched` or `GetVersion` calls for Versioning (although they may be added or removed according to the [patching](https://docs.temporal.io/workflow-definition#workflow-patching) rules)\n- Upserting Workflow Search Attributes\n- Upserting Workflow Memos\n- Running a `SideEffect` or `MutableSideEffect`\n\nFor a complete reference, see the [Command reference](https://docs.temporal.io/references/commands).\n\nMore formally, the use of certain Workflow APIs in the function is what generates Commands.\nCommands tell the Temporal Service which Events to create and add to the Workflow Execution's [Event History](https://docs.temporal.io/workflow-execution/event#event-history).\nWhen the Workflow's code [replays](https://docs.temporal.io/workflow-execution#replay), the Commands that are emitted are compared with the existing Event History.\nIf a corresponding Event already exists within the Event History that matches that command, then the Execution progresses.\nSee [Event History](https://docs.temporal.io/encyclopedia/event-history) for a detailed walkthrough of the process.\n\nFor example, using an SDK's \"Execute Activity\" API generates the [ScheduleActivityTask](https://docs.temporal.io/references/commands#scheduleactivitytask) Command.\nWhen this API is called upon re-execution, that Command is compared with the Event that is in the same location within the sequence.\nThe Event in the sequence must be an [ActivityTaskScheduled](https://docs.temporal.io/references/events#activitytaskscheduled) Event, where the Activity name is the same as what is in the Command.\n\nIf a generated Command doesn't match what it needs to in the existing Event History, then the Workflow Execution returns a *non-deterministic* error.\n\nThe following are the two reasons why a Command might be generated out of sequence or the wrong Command might be generated altogether:","source_url":"https://docs.temporal.io/workflow-definition.md","page_url":"https://docs.temporal.io/workflow-definition#deterministic-constraints"},{"content":"# Troubleshooting > Troubleshoot Workflow and Activity execution failures\n## Non-determinism error\n\n**Recommended alert:** `temporal_workflow_task_execution_failed` with `failure_reason=NonDeterminismError`\nFires on any occurrence, held for 1m. Routed Critical by default. [Tune the threshold](https://docs.temporal.io/best-practices/worker-alerting#execution-failures).\n\nReplay produced a different sequence of commands than the one recorded in Event History.\nThe Worker noticed that the Workflow code it is running no longer matches what the Execution has already done.\n\n**Why it matters.**\nAffected Executions stop making progress.\nThe Temporal Service retries the Workflow Task over and over, loading up your Workflow Workers, and by default those Executions sit in Running status the whole time.\nThis will not clear up on its own.\n\n**Triage.**\n\n1. **Identify the affected Workflow Executions.** This metric does not carry a Workflow Id. Worker logs record the error with the Workflow Id and Run Id. In the Temporal UI you can also find affected Executions by querying the `TemporalReportedProblems` Search Attribute, which the Temporal Service sets on Executions experiencing repeated Workflow Task failures.\n1. **Read the error.** The `WorkflowTaskFailed` event in an affected Execution's Event History contains the message identifying exactly where replay diverged and which command was expected versus produced. This is the most direct signal for root cause.\n1. **Determine whether this is a code change or a deploy artifact.** Common causes:\n   - A code change added, removed, or reordered commands such as Activity scheduling, Timers, Signals, or Child Workflows, without a versioning guard. Executions that built their History under the old code fail on the new code.\n   - A rolling restart with old and new Worker versions briefly running together. Some Executions fail transiently and recover once the rollout completes. If your deploys routinely trigger this alert, lengthen its `for` duration past how long a rollout takes.\n   - Changed Activity or Timer parameters in existing Workflow code without versioning.\n1. **Roll back if it isn't clearing.** If the errors started after a deploy and aren't going away, roll the Worker back. Affected Executions pick up again on their next Workflow Task retry once compatible code is running. Then add a proper versioning guard before you redeploy. See [Versioning Workflows](https://docs.temporal.io/workflow-definition#workflow-versioning) and [Worker Versioning](https://docs.temporal.io/production-deployment/worker-deployments/worker-versioning).\n1. **Watch Worker pressure.** All those retries add up. Cross-check [Worker Task slots exhausted](https://docs.temporal.io/troubleshooting/worker-capacity#worker-task-slots-exhausted) for `worker_type=WorkflowWorker` and [Workflow Task execution latency high](https://docs.temporal.io/troubleshooting/execution-failures#workflow-task-execution-latency-high). Enough retry volume will saturate your capacity and start hurting healthy Executions on the same Task Queue.","source_url":"https://docs.temporal.io/troubleshooting/execution-failures.md","page_url":"https://docs.temporal.io/troubleshooting/execution-failures#non-determinism-error"},{"content":"# Encyclopedia > Event-history > Event History walkthrough with the Java SDK\n## Example of a non-deterministic Workflow Definition\n\nNow that Replay has been covered, this section will explain why a Workflow Definition needs to be\n[deterministic](https://docs.temporal.io/workflow-definition#deterministic-constraints) in order for Replay to work.\n\nA Workflow Definition is deterministic if every execution of it produces the same Commands in the same\nsequence given the same input.\n\nAs mentioned in the [`How History Replay Provides Durable Execution`](https://docs.temporal.io/encyclopedia/event-history/event-history-java#How-History-Replay-Provides-Durable-Execution)\nwalkthrough, in the case of a failure, a Worker requests the Event History to replay it. During Replay, the Worker runs\nthe Workflow code again to produce a set of Commands which is compared against the sequence of Commands in the Event\nHistory. When there’s a mismatch between the expected sequence of Commands the Worker expects based on the Event History\nand the actual sequence produced during Replay (due to non-determinism), Replay will be unable to continue.\n\nTo better understand why a Workflow Definition needs to be deterministic, it's helpful to look at one that violates\nit. In this case, this code will walk through a Workflow Definition that breaks the determinism constraint with a random\nnumber generator.\n```\n1public class GenerateDailyReportImpl implements GenerateDailyReport {2\n3    ActivityOptions options = ActivityOptions.newBuilder()4        .setStartToCloseTimeout(Duration.ofMinutes(45))5        .build();6\n7    private final ReportActivities activities =8        Workflow.newActivityStub(ReportActivities.class, options);9\n10    @Override11    public void generateDailyReport() {12\n13        String salesData = activities.importSalesData();14\n15        Random random = new Random();16        if (random.nextInt(101) >= 50) {17            // Sleep for 4 hours18            Workflow.sleep(Duration.ofHours(4));19        }20\n21        Workflow.getLogger(this.getClass()).info(\"Preparing to run daily report\");22        DailyReport report = activities.runDailyReport(salesData);23    }24}\n```","source_url":"https://docs.temporal.io/encyclopedia/event-history/event-history-java.md","page_url":"https://docs.temporal.io/encyclopedia/event-history/event-history-java#Example-of-Non-Deterministic-Workflow"},{"content":"# Guides > Build a customer loyalty program with Entity Workflows\n## Step 7: Ensure Workflow Definition determinism\n\nTemporal replays Event History to resume a Workflow after a crash. The code must produce the same sequence of Commands on every replay.\n\nThe Python SDK sandbox blocks most non-deterministic operations, but in a few cases, you should use Temporal's Workflow-safe operations instead of standard ones:\n|Do not use Use instead Reason| `datetime.now()` `workflow.now()` Returns the same value during replay| `random.random()` `workflow.random().random()` Seeded deterministically by the SDK| `uuid.uuid4()` `workflow.uuid4()` Produces the same value during replay| `time.sleep()` `asyncio.sleep()` or `workflow.sleep()` Converts to a Durable Timer| `print()` `workflow.logger.info()` Replay-safe; only logs on initial execution| Direct I/O (HTTP, file reads) Activities All I/O must happen in Activities | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | ||\n|---|\n\nIf you update your code, and you're not sure whether it's safe for determinism, use the `Replayer` to verify code changes against a saved Event History:\n\n```\n# test_determinism.py  \nimport asyncio  \n  \nfrom temporalio.client import WorkflowHistory  \nfrom temporalio.worker import Replayer  \n  \nfrom workflows import LoyaltyEntityWorkflow  \n  \n  \nasync def test_replay_compatibility() -> None:  \n    \"\"\"Replay a saved Event History against the current code.  \n  \n    Export history first:  \n        temporal workflow show --workflow-id loyalty-cust-42 --output json > history.json  \n    \"\"\"  \n    replayer = Replayer(workflows=[LoyaltyEntityWorkflow])  \n  \n    with open(\"history.json\") as f:  \n        history = WorkflowHistory.from_json(\"loyalty-cust-42\", f.read())  \n  \n    # This raises NondeterminismError if the code is incompatible  \n    await replayer.replay_workflow(history)  \n    print(\"Replay succeeded: code is compatible with saved history\")  \n  \n  \nif __name__ == \"__main__\":  \n    asyncio.run(test_replay_compatibility())\n```\n\nRun this test as part of your continuous integration pipeline before deploying Workflow code changes. If the replay fails with a `NondeterminismError`, the code change is not backward-compatible. Use Worker Versioning (see Step 8) to deploy the change safely.","source_url":"https://docs.temporal.io/guides/entity-pattern-loyalty-points.md","page_url":"https://docs.temporal.io/guides/entity-pattern-loyalty-points#step-7-ensure-workflow-definition-determinism"},{"content":"# Encyclopedia > Event-history > Event History walkthrough with the Java SDK\n## Example of a non-deterministic Workflow Definition\n\nStep 1/9Sends a CommandFirst execution#### The importSalesData Activity runs\n\nAs this Workflow executes step by step, the first line that results in a Command is the call to the importSalesData Activity. The Activity Execution succeeds, so the Temporal Service logs three Events to the Event History.\n\nCommands created1. ScheduleActivityTask(importSalesData)\nRelevant History Events1. ActivityTaskScheduled(importSalesData)- ActivityTaskStarted- ActivityTaskCompleted\n← Previous123456789Next →\nDuring the first execution, the random number is 84, so the Workflow starts a Timer and the Event History records\n`TimerStarted` and `TimerFired`. During Replay, the random number is 14, so the Workflow skips the Timer and produces a\n`ScheduleActivityTask` Command where the Event History expects `StartTimer`. That mismatch is what makes Replay fail.\n\nNote that non-deterministic failures do not fail the Workflow Execution by default. A non-deterministic failure is\nconsidered a [Workflow Task Failure](https://docs.temporal.io/references/failures#workflow-task-failures) which is considered a transient\nfailure, meaning it retries over and over. Users can also fix the source of non-determinism, perhaps by removing the\nActivity, and then restart the Workers. This means that this type of failure can recover by itself. You can also use a\nstrategy called versioning to address this non-determinism error. See [versioning](https://docs.temporal.io/develop/java/workflows/versioning)\nto learn more.\n\nFor more information on how Temporal handles Durable Execution or to see these walkthroughs in video format with more\nexplanation, check out our free, self-paced courses: [Temporal 102](https://learn.temporal.io/courses/temporal_102/) and\n[Versioning Workflows](https://learn.temporal.io/courses/versioning/).","source_url":"https://docs.temporal.io/encyclopedia/event-history/event-history-java.md","page_url":"https://docs.temporal.io/encyclopedia/event-history/event-history-java#Example-of-Non-Deterministic-Workflow"},{"content":"# Guides > Build durable multiplayer game sessions with the actor model > Background and best practices\n## Workflow Definition determinism\n\nIn Temporal, your Activities can include non-deterministic code, but the Workflow Definition must remain deterministic. This is because Temporal restores Workflow state through *replay*. When a Worker restarts, it re-executes the Workflow code from the beginning, matching Commands against Events stored in the history. If the code produces different Commands than what the history contains, the Worker raises a `NondeterminismError`.\n\nIn practice, this means:\n\n- Use `workflow.now()` instead of `datetime.now()`.\n- Use `workflow.uuid4()` instead of `uuid.uuid4()`.\n- Use `workflow.random()` instead of the `random` module.\n- Do not perform I/O, network calls, or file system access inside Workflow code. Delegate all side effects to Activities.\n- Use `workflow.logger` instead of `print()` for replay-safe logging.\n\nThe Python SDK's Workflow sandbox provides automatic protection against many of these violations, but understanding the underlying mechanism helps you write correct code.","source_url":"https://docs.temporal.io/guides/durable-gaming-sessions.md","page_url":"https://docs.temporal.io/guides/durable-gaming-sessions#workflow-definition-determinism"}]