durabletask-js
Copilot instructions14 starsChanged 7 months agoMITView on GitHub
This document provides architectural context for AI assistants working with this codebase. Focus is on stable patterns, invariants, and pitfalls — not file paths or function signatures. The Durable Task SDK for JavaScript/TypeScript enables writing long-running, stateful workflows as code. It is the JavaScript implementation of Microsoft's cross-language Durable Task Framework (sibling SDKs exist in .NET, Python, Java, Go). This is NOT Azure Durable Functions. It's a lower-level SDK for the Azure Durable Task Scheduler service (or its emulator). The…
In this repository2 other files it gives its agents.
- js-fact-checkingSkill
- simulationSkill
The file
We split this copilot-instructions.md into the rules it gives an agent
5 rules. About 0 are common, 2 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 44
Orchestrator code MUST be deterministic: Every replay must produce the exact same sequence of actions.
- Very specific: line 121
Parent notification chain: When a child task completes, it calls parent.onChildCompleted().
- Distinctive: line 206
If not available, tracing is silently disabled.
- Very specific: line 273
When done is true but the loop keeps checking?
- Distinctive: line 318
Every source file starts with the Microsoft copyright header + MIT license reference.
≈ “Common” is an estimate: at least 1 in 5 of the 1,644 Copilot instructions files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Copilot Instructions — DurableTask JavaScript SDK
This document provides architectural context for AI assistants working with this codebase. Focus is on stable patterns, invariants, and pitfalls — not file paths or function signatures.
What This Project Is
The Durable Task SDK for JavaScript/TypeScript enables writing long-running, stateful workflows as code. It is the JavaScript implementation of Microsoft's cross-language Durable Task Framework (sibling SDKs exist in .NET, Python, Java, Go).
This is NOT Azure Durable Functions. It's a lower-level SDK for the Azure Durable Task Scheduler service (or its emulator). The two are related but have different APIs, deployment models, and npm packages.
Core Execution Model — Generator-Based Replay
This is the single most important thing to understand. Everything else follows from it.
How Orchestrations Work
Orchestrations are async generator functions (async function*) that yield Task<T>
objects. The runtime replays completed history events to rebuild state, then advances the
generator for new work.
Orchestrator yields Task → Runtime checks history → Already done? Send result back
→ Not done? Suspend generator, create action for sidecarOn every re-invocation:
- The executor receives
(instanceId, oldEvents[], newEvents[]). - With
isReplaying = true: feedsoldEventsthrough event processing. Completed tasks resolve instantly viagenerator.next(result). - With
isReplaying = false: processesnewEvents. Incomplete tasks suspend the generator. - The resulting
OrchestratorAction[]are sent back to the sidecar.
The Determinism Rule (Critical)
Orchestrator code MUST be deterministic. Every replay must produce the exact same
sequence of actions. This is enforced at runtime — mismatches throw NonDeterminismError.
What this means in practice:
- No
Date.now()— usecontext.currentUtcDateTime - No
Math.random()orcrypto.randomUUID()— usecontext.newGuid()(deterministic UUID v5) - No direct I/O (HTTP calls, file reads, database queries) — use activities
- No non-deterministic control flow — no data-dependent branching on external state
Adding, removing, or reordering yield statements between code versions breaks replay
for in-flight orchestrations. The validator catches type/name mismatches but not all
ordering issues.
Activities vs Orchestrations
Activities are the leaf nodes — they execute side effects exactly once (modulo retries) and persist results as history events. They can do anything: HTTP calls, DB writes, etc.
Key mental model: Orchestrations = coordination logic (deterministic). Activities = real work (non-deterministic allowed).
Architecture — How Pieces Connect
Communication Model
The SDK never touches storage directly. All communication happens over gRPC to a sidecar (Azure Durable Task Scheduler, emulator, or Dapr):
Client → gRPC → Sidecar (owns storage & scheduling)
↕
Worker ← gRPC (streaming) ← Sidecar pushes work itemsThe worker opens a server-streaming RPC (getWorkItems) and dispatches incoming work:
orchestration replays, activity executions, and entity operations.
Package Structure
This is an npm workspaces monorepo with three published packages:
| Package | Role | Changelog |
| Core SDK | Orchestration engine, client, worker, entities, testing, tracing | CHANGELOG.md |
| Azure Managed Backend | Connection string / Entra ID auth, credential factory, builder pattern | packages/durabletask-js-azuremanaged/CHANGELOG.md |
| Azure Functions Durable Provider | Azure Functions v4 compatibility provider | packages/azure-functions-durable/CHANGELOG.md |
The Azure package peers on the core package — it adds authentication and connection management but delegates all domain logic to core.
Protocol Layer
Protobuf definitions live in internal/protocol/. Generated JavaScript stubs (not
TypeScript) provide the gRPC message types. A helper layer converts between protobuf
messages and SDK types (history events, orchestrator actions).
Generated proto files should never be manually edited. They're rebuilt from the proto
definitions using grpc_tools_node_protoc.
Task System — The Heart of the SDK
Task Hierarchy
Task<T> — Base: result, exception, isComplete, isFailed, parent ref
├── CompletableTask — Can be completed or failed; notifies parent on completion
│ ├── RetryableTask — Policy-driven retries (exponential backoff)
│ └── RetryHandlerTask — Custom retry handler function
└── CompositeTask — Holds children with parent backlinks
├── WhenAllTask — Completes when ALL children are terminal (waits for every child)
└── WhenAnyTask — Completes when ANY child doneParent notification chain: When a child task completes, it calls
parent.onChildCompleted(). This chain drives composite task completion.
Important: CompositeTask checks already-complete children in its constructor.
A composite task can be immediately complete upon construction — callers must handle this.
WhenAll Wait-All Behavior
WhenAllTask completes only when every child is terminal (_completedTasks == _tasks.length) —
a failing child does not complete it early. This prevents a later failing sibling's TaskFailed
from being dropped against an already-terminal instance (issue #301). _exception is set only at
completion, so isFailed and isComplete flip together — otherwise resume() (which checks
isFailed before isComplete) would throw into the generator before the other siblings finish,
re-introducing fail-fast. On failure, all child exceptions are aggregated into an AggregateError
whose message inlines each child message.
Entity System
Identity Model
Entities are addressed as @name@key. Names are always lowercased (cross-SDK
consistency with .NET). Keys preserve case.
Execution Model
Entities process operations in single-threaded batches with per-operation transactional semantics:
- Checkpoint state + accumulated actions before each operation
- Execute the operation
- On success: commit. On failure: rollback to checkpoint.
State uses lazy JSON deserialization — deserialize only on first read. If state is written but never read, the original JSON is discarded (intentional optimization).
Method Dispatch
TaskEntity<TState> does automatic method dispatch: it walks the prototype chain, finds
a method matching the operation name (case-insensitive), and calls it. The implicit
delete operation sets state to null.
Entity Lock Ordering
lockEntities() sorts entity IDs before acquiring locks to prevent deadlocks.
This is enforced in the orchestration context — never bypass it or implement custom locking.
Error Handling Patterns
Exception Hierarchy
| Error | When |
TaskFailedError | Activity or sub-orchestration fails (carries FailureDetails) |
NonDeterminismError | Replayed action mismatches history (not recoverable) |
OrchestrationStateError | Invalid state transition attempted |
EntityOperationFailedException | Entity operation throws |
TimeoutError | Wait timeout exceeded |
Error Propagation Flow
- Activity throws → sidecar records failure event → executor calls
task.fail()→ generator receives thrownTaskFailedError→ orchestrator can catch or propagate. - Uncaught orchestrator error → executor catches → creates complete action with failure details → sidecar records failed status.
- Non-determinism → immediately throws, aborts replay. Not recoverable by user code.
Retry System
Two flavors, both using durable timers for backoff (survives process restarts):
- Policy-driven:
RetryPolicywith max attempts, backoff coefficient, intervals. Delay formula:firstRetryInterval × backoffCoefficient^(attempt - 1), capped. - Custom handler: User function receives
RetryContext, returnsRetryAction.
Critical invariant: Retry tasks create timers whose taskId differs from the original
task's ID. The executor maintains maps to link timer IDs back to retry tasks. If this
linkage breaks (e.g., during continue-as-new), retries silently fail.
Tracing (OpenTelemetry)
OpenTelemetry is an optional peer dependency, loaded via require() with fallback.
If not available, tracing is silently disabled.
Cross-SDK conventions (shared with .NET, Python, Java, Go):
- Tracer name:
"Microsoft.DurableTask" - Span naming:
"{type}:{name}"(e.g.,"orchestration:MyWorkflow") - W3C
traceparentpropagated via protobufTraceContextfields - Replay spans carry forward original span ID for cross-replay correlation
Logging Conventions
Logger Interface
The SDK supports two logging modes, detected at runtime via type guard:
- Plain
Logger:error(),warn(),info(),debug()— string messages StructuredLogger: AddslogEvent(level, event, message)with event IDs and categories matching the .NET SDK for cross-SDK log correlation
Replay-Safe Logging
ReplaySafeLogger wraps any logger and suppresses all output when isReplaying = true.
This prevents duplicate log entries during history replay. Always use it in orchestrator
context.
Testing Approach
In-Memory Backend
The SDK provides a full in-memory testing stack that mirrors the gRPC path:
TestOrchestrationClient → InMemoryOrchestrationBackend ← TestOrchestrationWorkerThis enables testing orchestrations with the real executor logic but no sidecar, no gRPC, no network. The backend manages instance state, work queues, timers, and state waiters.
Key test utilities:
backend.waitForState(predicate, timeout)— polling with timeout for async assertionsbackend.reset()— clear all state between tests- Direct timer control for deterministic time-dependent tests
Test Conventions
- Framework: Jest 29 with
ts-jest - File naming:
.spec.tssuffix - Protobuf test helpers: factory functions create
HistoryEventinstances without a sidecar - Three tiers: unit tests (no sidecar), e2e with sidecar, e2e with Azure
Where Bugs Tend to Hide
These are stable architectural areas where complexity concentrates:
- Replay event matching — The executor's large switch statement processes 27+ event types. Unmatched events are logged but silently dropped in several places. The TODOs in the code explicitly question whether these should be errors.
- Timer-to-retry linkage — Retry tasks create timers with different IDs. The maps connecting them are critical. Any break in linkage = silent retry failure.
- Generator lifecycle edge cases — What happens when the generator yields
null? Whendoneis true but the loop keeps checking? The initialnext()return value? Several TODOs mark these as not fully hardened. - Composite task constructor side effects — Already-complete children trigger
onChildCompleted()during construction, potentially completing the composite before the caller inspects it. - Continue-as-new state reset — Resetting history while preserving carryover events (buffered external events) is a subtle operation. Incorrect carryover handling leaks state between iterations.
- Suspend/resume event buffering — Suspended orchestrations buffer "suspendable" events. On resume, all buffered events are replayed in order. If events arrive at the boundary of suspend/resume transitions, ordering may be surprising.
- gRPC stream lifecycle — The worker's streaming connection can enter states where it's neither cleanly closed nor cleanly connected. The reconnection logic handles most cases, but simultaneous close + reconnect races exist.
- Entity V1 vs V2 code paths — The worker supports both entity execution paths. V2 is current; V1 is legacy. Incorrect version detection or mixed-version scenarios could cause issues.
Code Conventions
Naming
- Files:
kebab-case.ts - Classes:
PascalCase - Private fields:
_underscorePrefixed - Type aliases:
T-prefixed (TOrchestrator,TActivity) - Constants:
UPPER_SNAKE_CASEorPascalCaseobjects withUPPER_SNAKE_CASEproperties - Enums:
PascalCasenames withPascalCasemembers
Module System
- CommonJS output, ES2022 target
- OpenTelemetry loaded via synchronous
require()with catch (future ESM migration noted)
Cross-SDK Consistency
Many decisions mirror the .NET SDK intentionally: entity name lowercasing, structured log event IDs, tracing attribute names, span naming conventions. When in doubt about "why is it done this way?", the answer is often ".NET SDK compatibility."
License
Every source file starts with the Microsoft copyright header + MIT license reference.
Builder Pattern
Both packages use the builder pattern for constructing clients and workers.
Fluent API with .host(), .port(), .connectionString(), .endpoint(), .build().
Registration Lock
addOrchestrator(), addActivity(), addEntity() all throw if called after start().
The registry is frozen once the worker begins processing.
What Not to Touch
- Generated proto files (
*_pb.js,*_pb.d.ts,*_grpc_pb.js) — regenerated from proto definitions, never manually edited version.ts— auto-generated by prebuild script- Proto definitions in
internal/protocol/— shared across language SDKs, changes must be coordinated
Key Design Constraints to Respect
- No new dependencies without careful consideration — this is a core SDK
- Node.js >= 22 required — the engines field enforces this
- Single-threaded execution — no locking primitives; correctness depends on not yielding to the event loop during replay processing
- Pre-1.0 API — public API surface is still evolving but changes should be deliberate
- Cross-SDK alignment — behavior should match .NET/Python/Java/Go SDKs where applicable
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

