Introducing a new way to review your PRs.

Read the announcement

hatchet-dev / hatchet

🪓 An orchestration engine for background tasks, AI agents, and durable workflows

View on GitHub

31 documents · Updated Nov 23, 2026

docs / operator-execution-platform

Operator execution platform

The operator execution platform hosts long-running processes that perform work for Hatchet and keeps their state connected to workflow execution. It gives each operator a scheduler-visible worker, routes assigned actions to the process, carries task results and durable events back to the engine, and shuts the process down without losing control of in-flight work.

System purpose

An operator is a long-running process that accepts assigned actions and reports their state. The platform makes an operator look like a worker to the scheduler while giving it a wider role: it can publish task results, use durable task events, observe workflow runs, and, for engine-owned operators, advance workflow state.

The platform keeps these concerns together:

  • Placement: the dispatcher decides where an operator-backed worker can receive work.
  • Execution: the operator handles assigned actions and reports started, completed, failed, or cancelled results.
  • Durability: a durable invocation can wait for workflow events and resume from the event log.
  • Observation: a session can open workflow, durable-event, or durable-stream subscriptions for its tenant.
  • Liveness: heartbeats and session state tell the scheduler whether the operator can receive work.
  • Ownership: tenant, operator, and worker checks keep one operator from acting for another.

The main boundary is pkg/operator, which defines the host, session, action handler, durable channel, and run-stream contracts used by both in-process and remote operators. pkg/…/host.go describes this shared boundary. The platform is one execution layer within workflow orchestration.

Hosting model

The platform supports two ways to run an operator. Both use the same engine-side session service, so the scheduler and workflow engine see the same worker state regardless of process placement.

In-process hosting

In-process hosting runs an operator inside the engine process. The dispatcher calls the operator's action handler directly, and the host maintains worker heartbeats for its open sessions. This mode is used for engine-owned operators such as the DAG operator, which needs direct access to workflow data and engine-only workflow actions.

The host opens a session for a registered operator and links its worker to the dispatcher. A claimed operator is opened by its existing record, so hosting does not create a second operator record. A name-based open creates or reuses a self-leased contract operator. In both cases, the worker is treated as infrastructure managed by the engine rather than as a normal tenant worker. internal/…/host.go defines the role of this host.

References: internal/…/host.go• L118-190 internal/…/session.go• L16-29 internal/…/host_test.go• L114-191

Remote hosting

Remote hosting runs an operator outside the engine process and connects it through OperatorService. The operator registers itself, opens a bidirectional listen stream, receives assigned actions, sends heartbeats and action changes, and opens durable task streams when needed.

The client-side session keeps the action set it advertised so it can restore that set after a stream failure. It retries recoverable connection failures, adopts a new worker when the engine cannot resume the old one, and routes later task reports under the current worker. This lets a token rotation or stream loss recover the operator without silently losing its scheduler identity.

Each remote connection has its own worker identity. Several connections for one operator can therefore receive work as separate scheduler targets. A lost stream deactivates its worker, while a reconnect can resume that worker and its action set.

The remote API is defined by api-contracts/…/operator.proto, while internal/…/service.go adapts that protocol to the shared operator service. The client session behavior is represented by pkg/…/session.go.

References: api-contracts/…/operator.proto• L13-28 api-contracts/…/operator.proto• L33-88 internal/…/listen.go• L26-37 pkg/…/session.go• L293-383 pkg/…/runstream_test.go• L17-60

Shared session service

The operator service is the common engine-side layer for registration, worker activation, action links, task events, authorization, durable invocations, and run observation streams. It presents the same state model to both hosts; only action delivery and caller authentication differ.

This shared model matters during placement changes. An operator can move between process boundaries without changing how the dispatcher assigns actions or how workflow state receives results, provided the new host opens a valid session for the same operator and worker.

References: internal/…/service.go• L1-14 internal/…/session.go• L42-83 internal/…/session.go• L136-167

Run observation streams

Run observation streams let an operator session receive tenant-scoped workflow and durable data without turning that observation into a scheduler action. A session opens one stream through its current host credentials, then the engine owns the stream until it ends or the session closes.

The platform exposes these stream purposes:

StreamDirectionRole
Workflow runsBidirectionalSubscribe to named runs and receive their terminal results
Workflow eventsServer-to-clientReceive events for a run or matching metadata
Durable eventsBidirectionalWait for a durable event that completes a task signal
Durable streamsServer-to-clientRead messages from a tenant topic, with optional cursor resume

The stream kind maps each purpose to its request and response types. A server stream receives its opening request when it opens and does not accept later sends. Durable streams also require the tenant entitlement, so the engine can refuse an unauthorized subscription before messages flow.

References: pkg/…/runstream.go• L14-53 pkg/…/runstream.go• L55-129 pkg/…/session.go• L687-695 pkg/…/runstream_test.go• L17-60

Operator lifecycle

An operator lifecycle connects a stored operator record to a live worker session. The lifecycle has a clear order because the scheduler must stop assigning work before the operator drains, and the session must remain alive until all required events are reported.

The lifecycle follows this path:

flowchart LR
    A[Operator identity] --> B[Register or claim]
    B --> C[Create or resume worker]
    C --> D[Open session]
    D --> E[Advertise actions]
    E --> F[Receive assigned actions]
    F --> G[Report task state]
    G --> F
    D --> H[Pause assignments]
    H --> I[Drain in-flight work]
    I --> J[Close and deactivate session]

Registration and worker identity

Registration establishes the operator record and the worker that represents one live connection or hosted instance. A named remote registration upserts a self-leased gRPC operator. An in-process claimer instead opens an existing operator row that the dispatcher owns.

The worker carries the action set, slot limits, labels, runtime information, and live listener state used by scheduling. A reconnect may name a previous worker. If that worker still belongs to the operator, the platform resumes it; otherwise, it creates a new worker. A claimed row that is returned as newly taken can mean that another dispatcher released its worker, so the current host tears down its session and waits for a later claim result before reopening it.

Registration does not make actions live by itself. The session links the action set after the worker exists, so registration and action advertisement remain separate parts of the lifecycle.

References: internal/…/register.go• L21-62 internal/…/register.go• L82-147 api-contracts/…/operator.proto• L91-125 internal/…/claimer.go• L267-320 internal/…/host_test.go• L114-191

Session activation

Session activation makes the worker eligible for dispatch on the local dispatcher. It binds the worker to a session fence, installs either direct handler delivery or stream delivery, and notifies the scheduler that the worker is available.

The session fence prevents an old connection from deactivating or changing the state of a newer connection that reused the same worker. This lets reconnects and engine placement changes converge on one live worker without allowing stale sessions to control it.

References: internal/…/session.go• L78-167 internal/…/session.go• L180-208 internal/…/operator_sessions.go• L37-70

Pause, drain, and close

Shutdown uses three stages. The session first pauses assignment and stops delivery. The operator then drains work that it already accepted. The session closes last and deactivates the worker.

This order gives the operator a stable boundary: after the pause is confirmed, no new start action should arrive, while cancellation messages can still be handled. If a process exits unexpectedly, the remote session closes without forcing a pause so that a reconnect can resume an assignable worker.

References: internal/…/session.go• L319-348 internal/…/claimer.go• L386-403 internal/…/listen.go• L123-132

Operator placement and coordination

The dispatcher claimer keeps dispatcher-leased operators aligned with the operator records assigned to that dispatcher. It asks only for operator kinds and named contract operators that this engine can build. It polls that claim view, opens missing sessions, and tears down sessions that are no longer held.

The engine wires this claimer beside the dispatcher. The claimer stops before the dispatcher drains, so an operator can still report final task events while it is shutting down. A missing factory leaves a claimed row unhosted rather than silently running the wrong operator. A failed claim query does not change the current hosted set because the failure does not prove that any claim was lost.

sequenceDiagram
    participant DB as Operator records
    participant C as Dispatcher claimer
    participant H as Operator host
    participant D as Dispatcher
    participant O as Operator process

    C->>DB: Find rows claimed by this dispatcher
    C->>H: Build and open operator session
    H->>D: Register worker routing
    D-->>O: Deliver assigned action
    O-->>D: Report task event
    C->>H: Pause, drain, and close on claim loss

The main wiring is in cmd/…/operators.go, and the reconciliation rules are in internal/…/claimer.go.

References: cmd/…/operators.go• L20-25 cmd/…/operators.go• L43-97 internal/…/claimer.go• L1-16 internal/…/claimer.go• L203-271 internal/…/claimer.go• L322-383 internal/…/claimer_test.go• L358-464

Workflow execution integration

Operators affect workflow execution through the same dispatcher event path used by workers. An assigned action identifies the task run and action. The operator reports a state event, and the dispatcher uses that event to move the workflow task forward.

The shared operator state provides the common result actions:

  • Started: the operator began the task.
  • Completed: the operator returned a JSON result.
  • Failed: the operator returned an error and may mark it as non-retryable.
  • Cancelled: the operator stopped the task and may provide a cancellation reason when it runs in the engine.

The report uses a detached, time-bounded context so a task delivery that was cancelled does not prevent the operator from reporting its final outcome. pkg/…/operator.go defines these result paths.

References: pkg/…/operator.go• L27-43 pkg/…/operator.go• L299-386 internal/…/service.go• L337-352

DAG orchestration

The DAG operator is the built-in operator that turns one workflow action into coordination for the workflow's graph. It builds the selected workflow version into a dependency graph, starts ready child steps, waits for child results or durable conditions, and collects their results into the parent output.

Its action set is derived from the tenant's DAG workflows rather than from a static process configuration. The operator refreshes this set when it starts and on a regular poll, so new or changed workflows become scheduler actions without restarting the operator. A workflow version on an assigned action pins the graph and child orchestration to the version that created the run.

The DAG operator handles start and cancel actions as separate paths. A start action runs asynchronously so the dispatch path can continue. A cancel action targets every active invocation for the task, while an invocation that has already finished is no longer targeted. If no invocation remains, the operator reports the cancellation itself. Unsupported action types are acknowledged without entering DAG execution.

The operator also handles graph outcomes as workflow outcomes. Parent output can control skip or cancel conditions, a failed child cancels dependent children, and an on-failure step runs after failure or is skipped when the graph completes without failure. Ready children are sent to the engine as one ordered batch, so the engine can append and start related steps together while returning one result for each request. When a parent reaches a terminal state, its task-run identity remains available when the operator triggers later children. The engine resolves that identity to the latest completed or failed event, so replayed parent output remains available to children and failed parents remain visible to on-failure processing. A cancelled run cancels already-triggered unfinished children, while a shutdown leaves the task available for reassignment. A stale invocation that loses its place to a newer invocation stands down without reporting a second outcome. Missing or empty parent output is treated as an empty object for condition checks, and a condition that cannot be evaluated is treated as not matched.

Durable condition registrations are sent one at a time until the engine acknowledges each one. If a completion arrives before its matching acknowledgement, the operator holds it and applies it after the reference is known. This preserves the event order needed for replay while allowing already-finished children and conditions to be handled normally. After an invocation is evicted and restored, the same ordering keeps shared event waits aligned with their original log positions instead of letting an early completion trigger the wrong step.

References: pkg/…/operator.go• L34-40 pkg/…/operator.go• L118-194 pkg/…/operator.go• L199-302 pkg/…/operator.go• L304-476 pkg/…/operator.go• L529-574 pkg/…/operator.go• L593-617 pkg/…/operator.go• L632-724 pkg/…/dag.go• L222-303 pkg/…/dag.go• L307-375 pkg/…/dag.go• L431-628 pkg/…/dag.go• L651-687 pkg/…/dag.go• L789-849 pkg/…/dag.go• L929-1004

Workflow state boundaries

The operator platform does not replace the workflow engine's state model. The operator asks the dispatcher to publish task events and asks the engine to trigger or cancel DAG children. The workflow engine remains the authority for task state, retries, durable event history, and final run results.

This boundary lets an operator focus on coordination or task work while the engine preserves the state needed for replay and reassignment. A process restart therefore does not require the operator to own the full workflow history.

References: pkg/…/operator.go• L89-108 pkg/…/operator.go• L262-275 pkg/…/operator.go• L366-446 pkg/…/operator.go• L540-573

Durable invocation flow

A durable invocation is a task execution that exchanges events with the engine and can wait for durable results. The operator opens one channel for an invocation. The host performs the worker registration handshake, then the operator reads invocation events and sends durable requests through that channel.

The channel keeps engine responses in the order required by the durable protocol. In particular, an entry completion is not exposed until the operator has received the acknowledgement or expectation that names that entry. The DAG operator buffers a completion that races ahead of its acknowledgement and applies it after the matching registration is known. This protects replay and makes already-satisfied entries behave like newly received entries.

While a DAG run waits for child work or durable conditions, it reports the event entries that block progress. The dispatcher can use that status to evict an idle invocation and free its slot. An eviction ends that run without a terminal task result because the task remains available for restore or reassignment.

sequenceDiagram
    participant O as Operator
    participant S as Operator session
    participant D as Durable dispatcher path
    participant W as Workflow state

    O->>S: Open durable invocation
    S->>D: Register worker for task and invocation
    D-->>S: Registration acknowledgement
    O->>S: Wait, trigger, memo, or eviction request
    S->>D: Forward durable request
    D->>W: Update durable state
    W-->>D: Ack or entry completion
    D-->>S: Ordered durable response
    S-->>O: Deliver invocation event

The in-process channel and the remote DurableTask stream use the same dispatcher routing model. The in-process path is a channel-backed equivalent of the remote stream, so a durable event has the same workflow meaning in either deployment mode.

References: pkg/…/host.go• L145-149 pkg/…/operator.go• L286-297 internal/…/durable.go• L58-73 internal/…/durable.go• L122-203 internal/…/server_v1.go• L704-715 pkg/…/dag.go• L307-375 pkg/…/dag.go• L593-687 pkg/…/dag.go• L690-752

Registration and authorization boundaries

Registration and authorization answer different questions. Registration creates or resumes the operator's worker identity. Authorization checks whether later requests may use the operator and the worker named by those requests.

For remote operators, the tenant comes from the authenticated tenant token and the operator ID comes from the hatchet-operator-id metadata value. The engine accepts only a self-leased gRPC operator owned by that tenant. Calls that name a worker also require that the worker belongs to the operator.

These checks apply before action events and durable streams reach the dispatcher. The dispatcher can therefore treat an accepted operator event as belonging to the worker session that delivered it.

References: internal/…/service.go• L29-31 internal/…/service.go• L176-219 internal/…/authz.go• L16-69 api-contracts/…/operator.proto• L23-28

For the detailed wire rules, see Operator protocol and sessions. The registration, authorization, and session topics have dedicated child pages:

  • Operator registration
  • Operator authorization
  • Operator session handling

Change checklist

When these files or sections are changed, remember to consider these:

  • Changes to pkg/…/host.go must stay compatible with both internal/operator/hostinproc and the remote operator client. A capability that exists only in one host must remain explicit.
  • Changes to operator or worker identity rules must be applied to registration, metadata authorization, worker authorization, and durable stream setup together.
  • Changes to action-set updates must preserve the worker action links, scheduler notification, delta acknowledgement, and reconnect replay contract.
  • Changes to claimer factories or claim filters must keep the set of claimable rows aligned with the operators the engine can build. A claim query error must continue to leave the current hosted set unchanged.
  • Changes to pause or close order must preserve the boundary between “no new work” and “in-flight work is drained.”
  • Changes to durable response routing must preserve registration acknowledgement ordering and the mapping between task, invocation, and durable event entries.
  • Changes to run observation streams must keep procedure names, stream direction, opening messages, response types, and tenant entitlement checks aligned.
  • Changes to DAG condition watches must preserve one-at-a-time registration, acknowledgement ordering, and buffering for completions that arrive before their watch reference.
  • Changes to DAG child triggering must preserve batch request order, one result per ready step, and the shared parent-run context for every step in the batch.
  • Changes to blocked-run eviction must preserve the worker status entries that identify the task and invocation that can be restored or reassigned.
  • Changes to DAG operator actions must keep workflow-derived action names aligned with the action names stored for workflow steps.
  • Changes to DAG run tracking or cancellation must preserve cancellation of every active invocation for the targeted task without cancelling other tasks.
  • Changes to DAG run contexts must keep operator shutdown separate from targeted run cancellation, so one cancelled run does not stop other runs and shutdown still leaves work available for reassignment.
  • Changes to start-event reporting must preserve its ordering with completion and failure events.
  • Changes to stale invocation handling must keep superseded runs from reporting a terminal result for a newer invocation.
  • Changes to DAG slot configuration must preserve the stored-slot override and the server default when the stored value is absent.

Important failure modes

TriggerConsequenceGuard
A claim query fails and its empty result is treated as authoritativeHealthy operators are torn down during a temporary store or network faultKeep the current hosted set unchanged until a successful claim result arrives
The claim filter includes an operator with no matching factoryThe dispatcher holds an operator that this engine cannot hostClaim only registered kinds and named contract operators, and leave unknown rows unhosted
A running row changes from held to newly takenThe current worker may already have been released by another dispatcherTear down the current session and reopen only after a later claim result
A remote call omits or sends a malformed hatchet-operator-id valueThe request is rejected before it can access operator stateParse and require the operator metadata on every RPC after registration
A worker ID belongs to another operator or tenantThe operator could report events for another execution identityAuthorize the operator first, then authorize each worker ID against that operator
A server stream is treated as bidirectional or opened without its required first requestThe subscription cannot receive the intended tenant dataUse the stream kind's direction and opening message contract
An action delta is applied without a committed scheduler notificationThe database has the new action set, but assignment can remain staleApply the delta and refresh or notify the scheduler before treating the set as live
The client session loses its stream and does not restore its desired action setThe replacement worker is connected but cannot receive the operator's workReconnect through the token source, restore the desired actions, and wait for acknowledgement before delivery resumes
A session reports a task under a stale worker after reconnectThe engine rejects the event or leaves the task tied to the wrong workerRewrite reports from this session to its current worker while passing foreign workers through for engine rejection
A start queue fills while the handler is blockedThe action is refused and relies on retry rather than waiting without boundKeep the queue bounded and report a retryable failure when it is full
The session closes before the operator drainsAccepted work can stop without a final task event, and the worker can be reassigned too earlyPause delivery, drain in-flight work, then close and deactivate
A durable entry completion arrives before its acknowledgement is knownReplay can expose an entry before the operator has established that it is waiting for itHold the completion until the matching acknowledgement or explicit expectation
A cancel action targets only one of several active invocations for the same taskAnother invocation can continue and report a result after cancellationTrack each invocation separately and cancel every matching active run
An unsupported action enters the DAG execution pathThe operator can perform work for an action it does not own or fail before reporting a valid stateHandle supported action types explicitly and acknowledge unsupported types without DAG execution
A batch trigger returns results out of request order or without one result per ready stepChild identities can attach to the wrong DAG step or leave the invocation unable to resume safelyKeep the batch ordered and validate that the result count matches the request count
A DAG run stays blocked without reporting its awaited entriesThe dispatcher cannot identify an idle invocation to evict, so a worker slot can remain occupiedReport the task's outstanding durable entries while the run waits
The dispatcher evicts a blocked DAG invocationThe run ends without a terminal task event and must be restored or reassignedTreat eviction as a non-terminal release of the durable slot
A stale DAG invocation triggers a child after a newer invocation is assignedThe old invocation could report a result for superseded stateTreat the stale invocation as evicted and stand down without reporting
Operator shutdown interrupts an in-flight DAG runShutdown could turn into a task failure instead of allowing reassignmentLeave the task available for reassignment and log the shutdown
A child task fails or durable replay reports nondeterminismRetrying the orchestrator cannot change the recorded graph outcomeMark deterministic child and engine-reported outcomes as non-retryable
A parent condition cannot be evaluated against its outputThe dependent step may run instead of being skipped or cancelledTreat the condition as not matched and record the evaluation error
A dispatcher loses an operator claimThe old process may keep receiving work or hold a stale worker leaseReconcile claims and tear down operators that are no longer claimed
A DAG run is cancelled while child runs already existChild workflow runs can continue after the parent has stoppedCancel triggered, unfinished DAG children during run cancellation
A fast DAG reports completion before its started event is recordedAnalytics can show completion before startCapture the start time and wait for the started report before final run completion
A DAG operator has invalid stored configurationThe operator cannot start with a valid worker slot modelReject invalid configuration and use the server default only when the stored slot value is absent

Key files

FileWhy to read it
pkg/…/host.goDefines the host, session, durable channel, run-stream, and lifecycle contracts shared by both deployment modes
pkg/…/runstream.goMaps workflow and durable observation streams to their procedures, directions, and message types
pkg/…/operator.goShows how an operator reports task state, advertises actions, tracks overlapping in-flight work, drains, and batches engine-internal DAG triggers
internal/…/service.goExplains the shared engine-side service used by in-process and remote operators
internal/…/session.goShows how a worker becomes live, receives action changes, pauses, and closes
internal/…/register.goDefines operator registration, worker creation, and worker resumption
internal/…/durable.goExplains the in-process durable invocation channel and response ordering
internal/…/host.goShows how the engine hosts operators directly and keeps their workers alive
internal/…/claimer.goShows how buildable claim filters control operator placement, retry, and teardown
internal/…/listen.goShows how a remote operator stream becomes a live worker session
pkg/…/session.goShows how a remote client session delivers actions, recovers streams, preserves worker identity, and opens run observations
api-contracts/…/operator.protoDefines the remote operator registration, listen, event, and durable task interfaces
pkg/…/operator.goIllustrates workflow-derived actions, separate start and cancel handling, DAG run ownership, batched child triggering, cancellation, result reporting, and stale-invocation handling
pkg/…/operator_test.goCaptures the action-routing, overlapping-cancellation, and slot-default contracts for the DAG operator
pkg/…/dag.goExplains dependency readiness, batched child starts, durable waits, replay ordering, blocked-run status, and graph outcomes
cmd/…/operators.goShows how the engine assembles the operator service, host, and claimer