Files
Donald Pinckney 0c8586b4c2 Add Java SDK support (#42)
* Add Java SDK reference files (11 files)

Create complete Java reference documentation covering:
- java.md: Entry point with quick start tutorial, key concepts
- patterns.md: 17 patterns (signals, queries, updates, child workflows,
  saga, cancellation scopes, heartbeating, etc.)
- determinism.md: Safe alternatives table, forbidden operations
- determinism-protection.md: Convention-based enforcement (no sandbox)
- error-handling.md: ApplicationFailure, retry/timeout config
- gotchas.md: Non-deterministic operations, cancellation, heartbeating
- testing.md: TestWorkflowEnvironment, Mockito mocking, replay testing
- versioning.md: Workflow.getVersion(), worker versioning
- data-handling.md: Jackson, PayloadConverter, encryption, search attributes
- observability.md: SLF4J logging, Micrometer metrics
- advanced-features.md: Schedules, async completion, worker tuning

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Fix Java alignment issues from self-review

- Reduce gotchas.md Non-Deterministic Operations from ~94 lines to ~12
  (reference determinism.md instead of duplicating)
- Remove Workflow Failure Exception Types duplication from error-handling.md
  (keep only in advanced-features.md)
- Expand versioning.md Worker Versioning with Key Concepts, PINNED vs
  AUTO_UPGRADE, Deployment Strategies subsections
- Fix section names to match Python reference style:
  Activity Heartbeat Details, Handling Activity Errors,
  Retry Policy Configuration, Workflow Test Environment,
  Mocking Activities, Workflow Replay Testing
- Reduce data-handling.md Payload Encryption verbosity
- Reduce observability.md Logger Customization verbosity
- Reduce testing.md to single approach per section
- Rename determinism.md "Convention-Based Enforcement" to "SDK Protection"
- Fix handler guidance in patterns.md to match Python

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Fix correctness issues in Java reference files

- patterns.md: Fix Queries section — ActivityStub → typed interface
  (Workflow.newActivityStub returns the typed interface, not ActivityStub)
- data-handling.md: Add missing ProtobufPayloadConverter to default
  converter chain (4th of 5 converters)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Add Java to SKILL.md and core/determinism.md

- SKILL.md: Add "Temporal Java" trigger phrase, update Overview to
  list Java, add Java entry to Getting Started references
- core/determinism.md: Add Java entry to SDK Protection Mechanisms
  (no sandbox, convention-based, NonDeterministicException at replay)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Apply manual editorial fixes to Java references

- java.md: Remove "Understanding Replay" section (covered by Overview),
  simplify File Organization note (no sandbox rationale)
- gotchas.md: Move Heartbeating before Cancellation, make Wrong Retry
  Classification brief with reference (not inline examples)
- error-handling.md: Remove editorializing from Workflow Failure note
- determinism-protection.md: Remove cross-language comparison paragraph
  (state Java's approach on its own terms)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Add temporal-workflowcheck static analysis to Java determinism docs

- determinism-protection.md: Add "Static Analysis with temporal-workflowcheck"
  section with Gradle/Maven setup, manual run, and suppression instructions.
  Beta warning included.
- determinism.md: Update overview and SDK Protection to reference workflowcheck
- core/determinism.md: Update Java entry in SDK Protection Mechanisms

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Integrate feedback from Go PR into Java patterns

- Updates: Add validator note — validators must not mutate state or
  block (matches note added to Python, TypeScript, Go, and core)
- Saga Pattern: Use Workflow.newDetachedCancellationScope() for
  compensations so they execute even if the workflow is cancelled
  (mirrors Go's workflow.NewDisconnectedContext pattern)

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>

* docs: add @WorkflowInit description to java.md Key Concepts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* mark java as supported

* Apply suggestions from code review

Co-authored-by: Brian Strauch <brian@brianstrauch.com>

* strongly recommend java 21+

* Softened stance on static checker and replay testing.

* address python/typescript sandboxing comment

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Brian Strauch <brian.strauch@temporal.io>
Co-authored-by: Brian Strauch <brian@brianstrauch.com>
2026-04-02 17:07:33 -04:00

5.6 KiB

Determinism in Temporal Workflows

This document provides a conceptual-level overview to determinism in Temporal. Additional language-specific determinism information is available at references/{your_language}/determinism.md.

Overview

Temporal workflows must be deterministic because of history replay - the mechanism that enables durable execution.

Why Determinism Matters

The Replay Mechanism

When a Worker needs to restore workflow state (after crash, cache eviction, or continuing after a long timer), it re-executes the workflow code from the beginning. But instead of re-running external actions, it uses results stored in the Event History.

Initial Execution:
  Code runs → Generates Commands → Server stores as Events

Replay (Recovery):
  Code runs again → Generates Commands → SDK compares to Events
  If match: Use stored results, continue
  If mismatch: NondeterminismError!

Commands and Events

Every workflow operation generates a Command that becomes an Event, here are some examples:

Workflow Code Command Generated Event Stored
Execute activity ScheduleActivityTask ActivityTaskScheduled
Sleep/timer StartTimer TimerStarted
Child workflow StartChildWorkflowExecution ChildWorkflowExecutionStarted
Complete workflow CompleteWorkflowExecution WorkflowExecutionCompleted

Non-Determinism Example

First Run (11:59 AM):
  if datetime.now().hour < 12:  → True
    execute_activity(morning_task)  → Command: ScheduleActivityTask("morning_task")

Replay (12:01 PM):
  if datetime.now().hour < 12:  → False
    execute_activity(afternoon_task)  → Command: ScheduleActivityTask("afternoon_task")

Result: Commands don't match history → NondeterminismError

Sources of Non-Determinism

Time-Based Operations

  • datetime.now(), time.time(), Date.now()
  • Different value on each execution

Random Values

  • random.random(), Math.random(), uuid.uuid4()
  • Different value on each execution

External State

  • Reading files, environment variables, databases, networking / HTTP calls
  • State may change between executions

Non-Deterministic Iteration

  • Map/dict iteration order (in some languages)
  • Set iteration order

Threading/Concurrency

  • Race conditions produce different outcomes
  • Non-deterministic ordering

Central Concept: Place Non-Determinism within Activities

In Temporal, activities are the primary mechanism for making non-deterministic code durable and persisted in workflow history. Generally speaking, you should place sources of non-determinism in activities, which provides durability and recording of results, as well as automated retries and more. See references/{your_language}/{your_language}.md for the language you are working in for how to do this in practice.

For a few simple cases, like timestamps, random values, UUIDs, etc. the Temporal SDK in your language may provide durable variants that are simple to use. See references/{your_language}/determinism.md for the language you are working in for more info.

SDK Protection Mechanisms

Each Temporal SDK language provides a different level of protection against non-determinism:

  • Python: The Python SDK runs workflows in a sandbox that intercepts and aborts non-deterministic calls early at runtime.
  • TypeScript: The TypeScript SDK runs workflows in an isolated V8 sandbox, intercepting many common sources of non-determinism and replacing them automatically with deterministic variants.
  • Java: The Java SDK has no sandbox. Determinism is enforced by developer conventions — the SDK provides Workflow.* APIs as safe alternatives (e.g., Workflow.sleep() instead of Thread.sleep()), and non-determinism is only detected at replay time via NonDeterministicException. A static analysis tool (temporal-workflowcheck, beta) can catch violations at build time. Cooperative threading under a global lock eliminates the need for synchronization.
  • Go: The Go SDK has no runtime sandbox. Therefore, non-determinism bugs will never be immediately appararent, and are usually only observable during replay. The optional workflowcheck static analysis tool can be used to check for many sources of non-determinism at compile time.

Regardless of which SDK you are using, it is your responsibility to ensure that workflow code does not contain sources of non-determinism. Use SDK-specific tools as well as replay tests for doing so.

Detecting Non-Determinism

During Execution

  • NondeterminismError raised when Commands don't match Events
  • Workflow becomes blocked until code is fixed

Testing with Replay

Replay tests verify that workflows follow identical code paths when re-run, by attempting to replay recorded executions. See the replay testing section of references/{your_language}/testing.md for information on how to write these tests.

Recovery from Non-Determinism

Accidental Change

If you accidentally introduced non-determinism:

  1. Revert code to match what's in history
  2. Restart worker
  3. Workflow auto-recovers

Intentional Change

If you need to change workflow logic:

  1. Use the Patching API to support both old and new code paths
  2. Or terminate old workflows and start new ones with updated code

See versioning.md for patching details.

Best Practices

  1. Use SDK-provided alternatives for time, random, UUID
  2. Move I/O to activities - workflows should only orchestrate
  3. Test with replay before deploying workflow changes
  4. Use patching for intentional changes to running workflows
  5. Keep workflows focused - complex logic increases non-determinism risk