Operator protocol and sessions
An operator is a process that runs workflow actions for a tenant. This protocol gives the engine a trusted operator identity, a live worker session, a stream for assigned work, and paths for progress and durable task events. The shared host and session contract lets the same operator behavior run over gRPC or inside the dispatcher process. It also lets the dispatcher treat an external operator like any other worker while the session keeps work safe across pauses, reconnects, and shutdowns. For the wider execution model, see Operator execution platform. For dispatcher handoff, see Dispatcher and worker coordination. For serverless operator behavior, see Serverless endpoints and operator runtime. For the tenant boundary and public service contracts, see Authorization and tenancy and Public API contracts.
Operator identity
Registration
Registration has two entry paths. A network session names an operator so the engine can create or update its self-leased identity. A dispatcher-hosted session opens an existing operator row after the dispatcher has claimed it. Both paths then create a worker or resume the named worker from an earlier registration. Each connection can therefore act as its own worker while several connections use the same operator name.
The registration also carries the worker's scheduling shape. Slot limits control how much work it can hold, labels guide affinity-based assignment, and runtime information describes the process for the dashboard. Registration does not publish workflows or actions; those use the session after the identity is established.
| Registration result | Meaning |
|---|---|
operator_id | Stable identity for later OperatorService calls |
worker_id | Worker activated by the current connection |
resumed | Whether the requested worker still belonged to this operator and was reused |
References: api-contracts/…/operator.proto• L13-33 api-contracts/…/operator.proto• L91-126 internal/…/register.go• L82-147 pkg/…/host.go• L48-71
Authorization
Authorization binds every post-registration call to both a tenant and an operator. The client sends the bearer token on every call and sends the returned operator ID in the hatchet-operator-id metadata field. The engine accepts only a self-leased gRPC operator owned by the authenticated tenant. Calls that name a worker also require that the worker belongs to that operator.
This boundary keeps an operator from using a valid tenant token to control another operator's worker. Missing or malformed identity data is an invalid request. A valid-looking identity that does not belong to the tenant is a permission failure.
References: api-contracts/…/operator.proto• L23-29 pkg/…/session.go• L399-405 internal/…/authz.go• L16-69 pkg/…/host_test.go• L885-913
Transport channels
Listen stream
The Listen stream is the live control channel for one worker. The client starts it by naming the registered worker. The engine then sends assigned actions, while the client sends heartbeats, action-set changes, and pause requests on the same stream.
The stream has one message direction for work and another for control results. This keeps liveness and worker state tied to the connection that delivers work. If the stream ends, the engine deactivates that worker session and the client must register and listen again.
The protocol accepts these client messages after the start message:
- A heartbeat keeps the worker eligible for scheduling.
- An actions delta adds or removes actions from the worker's set.
- A pause changes whether the scheduler may assign new work.
The client sends heartbeats every four seconds. The engine treats a stale heartbeat as inactive. A stream-backed session is also subject to a per-operator stream limit on each engine replica.
References: api-contracts/…/operator.proto• L35-76 internal/…/service.go• L38-70 pkg/…/session.go• L437-466 pkg/…/host_test.go• L1221-1351
gRPC calls
The stream is part of a wider gRPC contract. Registration starts the identity handshake. Progress events report started, completed, failed, or cancelled work. The durable task stream carries long-lived task state for an invocation. Workflow publication uses the AdminService on the same connection rather than the operator registration call.
The client attaches the tenant bearer token to all calls. It adds the operator ID only to calls on OperatorService after registration. Durable task registration uses the current worker ID, so a durable listener can survive a worker identity change after reconnect.
References: api-contracts/…/operator.proto• L29-89 pkg/…/client.go• L70-137 pkg/…/session.go• L762-805
Run observation streams
Run observation streams let an operator session subscribe to tenant-scoped run results, workflow events, durable events, or durable stream messages. The session opens each stream through the current authenticated client, so the stream uses the session's tenant credentials and ends when that client session ends.
The stream kind selects the gRPC procedure and its request and response types. A server stream accepts its opening request and then only receives engine messages. A bidirectional stream can receive more requests after it opens. The caller must reopen a stream after session recovery because the old transport is no longer tied to the current client session.
| Stream | Direction | Purpose |
|---|---|---|
| Workflow runs | Bidirectional | Subscribe to terminal results for named workflow runs |
| Workflow events | Server stream | Receive workflow events for a run or metadata match |
| Durable events | Bidirectional | Subscribe to durable events for a task and signal key |
| Durable streams | Server stream | Read messages from a tenant durable-stream topic, with optional resume position |
References: pkg/…/runstream.go• L14-129 pkg/…/host.go• L152-157 pkg/…/session.go• L687-695 pkg/…/runstream_test.go• L17-60 pkg/…/runstream_test.go• L15-47
Session lifecycle
Session activation
Opening a session makes the worker visible to the scheduler and connects it to the local dispatcher. The engine pins the worker to the dispatcher that owns the delivery path, activates the worker under a fresh session fence, and registers the stream as a dispatcher delivery target. The session then notifies scheduling so the worker can receive matching actions.
The session fence links the database worker state to the live dispatcher entry. When a newer connection takes over the same worker, an older session cannot deactivate or pause the newer session by mistake.
When an external session opens, the client performs this sequence:
- Register the operator and worker.
- Open Listen and send the worker start message.
- Replay the required pause state and action state.
- Start receiving actions and sending heartbeats.
The host publishes the initial action set before it returns the session to its caller. If that first flush fails, it closes the session instead of exposing a worker with an unknown action set.
References: internal/…/session.go• L42-167 pkg/…/session.go• L248-310 internal/…/operator_sessions.go• L14-70 pkg/…/session.go• L145-174 pkg/…/host_test.go• L695-717
Session pause
Pause is a handoff barrier between the scheduler and the operator. The engine first stops dispatcher delivery, then records the worker as paused, and only then acknowledges the pause. An action assigned just before the scheduler sees the pause returns to the queue instead of arriving after the acknowledgement.
Resume reverses that order. The worker becomes assignable only after the dispatcher can deliver again. The pause belongs to the current stream, so a reconnect restores it before it restores action membership.
The barrier gives a caller a clear point at which it holds the last actions it will receive. A caller can use that point to drain its in-flight work without accepting new work.
References: api-contracts/…/operator.proto• L66-73 internal/…/session.go• L319-380 pkg/…/session.go• L677-749
Session shutdown
Normal shutdown closes open durable channels, pauses the worker, waits for work already handed to the operator, flushes pending action changes, and ends the stream. Ending the stream releases the dispatcher delivery entry and deactivates the worker. The host then stops delivery and supervision before it releases its client reference.
An immediate close skips the drain when the process cannot wait. The engine then relies on task timeout and retry behavior for work that was handed out but not completed. Closing a session is idempotent, so one owner can safely perform cleanup after another shutdown path has started.
References: pkg/…/client.go• L120-159 pkg/…/session.go• L826-871 internal/…/session.go• L396-475 pkg/…/session.go• L653-692
Action membership and acknowledgements
Action set changes
The action set is the worker's claim about which action IDs it can run. Clients change it with incremental add and remove messages. The engine applies each delta as one committed change, then notifies the scheduler to reload the worker. Repeating an add or remove is safe because the operation is a set change rather than a replacement.
The engine limits one delta to 1,000 IDs and limits total action links across an operator's workers. A large desired set is split into several ordered deltas. The scheduler notification is coalesced during a short burst so it reloads the committed set without turning every small change into a separate scheduling event.
References: api-contracts/…/operator.proto• L157-170 internal/…/session.go• L285-299 internal/…/service.go• L44-56
Delta acknowledgements
Each sent delta has a positive, increasing sequence number. The engine acknowledges a sequence only after the action change is committed. An acknowledgement for sequence N also confirms all lower sequences, which lets the client remove a prefix of its pending changes.
The client keeps unacknowledged deltas until it receives their acknowledgement. If the stream fails, it replays them in order. If registration creates a new worker instead of resuming the old one, the client sends the complete desired action set because the new worker starts empty. This makes a lost acknowledgement safe to replay.
A sequence of zero requests no acknowledgement. A delta that cannot be applied or whose acknowledgement cannot be sent ends the stream instead of claiming success.
References: api-contracts/…/operator.proto• L51-65 pkg/…/actions.go• L55-68 pkg/…/actions.go• L216-308
Durable work
Durable task stream
Durable work is long-lived task state that an operator reads and updates while an invocation runs. The operator opens one durable channel for a task and invocation through the session. The engine registers the current worker before it releases invocation messages to the operator.
The channel carries task requests and responses such as memo results, child-run triggers, waits, completion entries, and invocation eviction. It keeps the registration acknowledgement ahead of invocation traffic. This ordering lets a resumed operator build its local state before it consumes restored entries.
The session owns the worker registration on the durable stream. The operator owns invocation traffic. A single session listener can serve several invocation channels, which keeps durable transport tied to the session while preserving one logical channel per invocation.
References: api-contracts/…/operator.proto• L84-88 internal/…/durable.go• L48-73 internal/…/durable.go• L122-203 pkg/…/durable.go• L38-84
Durable acknowledgements
Only one acknowledgement-bearing durable request may be in flight for one task invocation. The channel releases that slot when the engine returns the acknowledgement or its error. Wait and child-run acknowledgements also establish which event entries the operator expects next.
The channel bounds retained responses. If the operator does not consume them and the bound is exceeded, the channel fails rather than growing without limit. Closing the channel cancels the invocation and waits briefly for the engine to release its side.
References: internal/…/durable.go• L67-73 internal/…/durable.go• L245-338 internal/…/durable.go• L380-538
In-process DAG execution
The engine's DAG operator uses the same durable task model without a network hop. It registers the tenant's DAG workflows as worker actions before the worker becomes assignable, then refreshes that action set on a schedule so workflow changes do not require an operator restart.
When the dispatcher assigns a run, the operator builds the workflow's task graph and keeps the run alive on a context that outlasts the dispatcher's short action context. Each ready child step or wait condition becomes durable work. The operator sends wait registrations one at a time and waits for their acknowledgements before it emits dependent child work. If a completion arrives before its registration acknowledgement, the run holds it until the matching reference is known.
The run reports the durable entries that block it while it waits. The engine can then evict an idle run and release its slot for reassignment. Parent output collection includes every terminal parent task, including failed tasks, so later steps and replayed runs retain the available result or error state.
Child failure, cancellation, condition errors, and durable nondeterminism are stable workflow outcomes. Shutdown and other operational errors are delivery failures, so unfinished orchestration remains available for retry.
References: pkg/…/operator.go• L25-61 pkg/…/operator.go• L118-195 pkg/…/operator.go• L276-440 pkg/…/dag.go• L287-390 pkg/…/dag.go• L413-596 pkg/…/dag.go• L599-768 pkg/…/dag.go• L830-912
Dispatcher coordination
Delivery session
The dispatcher represents an external operator as a stream delivery session. It serializes dispatcher assignments with protocol responses on one sender, so an action cannot race an acknowledgement or pause response on the gRPC stream. It can also mark the session as paused and return new assignments to the queue.
The operator service registers this delivery entry with the same session ID stored as the worker's listener fence. Releasing the entry stops future delivery. A dispatcher shutdown can signal the stream to end through the session's finish channel.
In-process operators use the same coordination model without gRPC encoding. The dispatcher calls their handler directly, while the session service keeps the worker activation, pause, action set, and scheduler notifications consistent with external operators.
References: internal/…/operator_sessions.go• L14-103 internal/…/operator_sessions.go• L106-145 internal/…/service.go• L101-128
Claimed operator hosting
The dispatcher claimer keeps dispatcher-leased operator rows hosted in the process. It asks for only the operator kinds and named contract operators that this process can build, opens each claimed row by its existing ID, and starts the resulting handler on a session. This separates placement from session ownership: the claimer decides which rows belong here, while the host owns workers, heartbeats, and dispatcher delivery.
Each poll is a desired-state check. A row that is still held remains hosted. A row that is no longer held is torn down, and a row that loses its worker is reopened on a later poll. A failed claim query does not change the current set because it cannot prove that any row was released. Rows without a matching factory stay unhosted rather than being opened with the wrong implementation.
When a row leaves the claim set, teardown pauses the worker, drains the operator, and closes the session within a bounded time. The claimer stops before dispatcher drain so work events from operator teardown still have a delivery path.
References: internal/…/claimer.go• L1-17 internal/…/claimer.go• L224-271 internal/…/claimer.go• L322-403 internal/…/claimer_test.go• L228-356 internal/…/claimer_test.go• L358-464
Work event reporting
An operator reports progress through SendStepActionEvent. The session fills an omitted worker ID with its own worker and rejects an event that names a different worker. Terminal events mark the delivered task run as no longer in flight, which allows normal shutdown to finish its drain.
If an external session reconnects and receives a new worker identity, the host keeps track of workers used by the session and reports under the worker the engine currently knows. This prevents a late result from being tied to an obsolete worker while preserving the task run's delivery history.
References: internal/…/session.go• L302-317 pkg/…/session.go• L578-605 pkg/…/session.go• L481-603 pkg/…/host_test.go• L1117-1150
In-process dispatcher handoff
The in-process DAG operator starts each run from a dispatcher assignment but keeps the run alive on its own context. A targeted cancellation stops one run and can cancel its unfinished children. Operator shutdown instead stops polling and interrupts active runs so unfinished work remains available for reassignment.
This distinction protects durable work during handoff. A normal task cancellation is a terminal workflow outcome. A process shutdown is a delivery failure, so it must not report the run as completed or cancelled merely because the local operator stopped.
References: pkg/…/operator.go• L134-143 pkg/…/operator.go• L197-271 pkg/…/operator.go• L312-348 pkg/…/operator.go• L523-567
Reconnection behavior
Stream recovery
The client treats the Listen stream as recoverable transport. A failed receive loop ends the old stream and causes registration to run again. By default the client asks to resume the last worker. The engine clears a pause when it resumes a worker, so the client restores a desired pause before it replays actions.
The client restores the desired action set after registration. A resumed worker receives only unacknowledged deltas. A new worker receives a full snapshot. Heartbeats then continue on the replacement stream, and assigned actions return through the same session consumer.
The host can supervise this client session and ask its token source for a new token. It retries failures that may recover, but it stops serving the tenant for permanent failures such as a missing token or a tenant mismatch. A rotated token replaces the cached gRPC client without closing an older client that still has open sessions.
References: pkg/…/session.go• L119-205 pkg/…/session.go• L313-333 pkg/…/session.go• L293-382 pkg/…/host_test.go• L966-1115 pkg/…/host_test.go• L1438-1475
Work continuity
The session tracks actions after it hands them to the operator and removes them when it reports a terminal result. During a graceful close, the pause acknowledgement prevents new delivery and the drain gives these actions time to finish. If delivery ends before results arrive, the session abandons its local tracking so the engine can retry work that remains unfinished.
The host reads the action stream eagerly. Cancels go directly to the handler, while starts use a bounded queue behind a serial start worker. When that queue is full or the handler refuses a start, the host reports a retryable failure instead of blocking delivery. This keeps cancellation prompt and leaves retry decisions to the engine.
Durable listeners and run observation streams close with the client session during recovery. Open durable channels and run streams then fail or retry through the host's supervision path rather than continuing on a transport that no longer owns the worker.
References: pkg/…/session.go• L526-575 pkg/…/session.go• L607-675 pkg/…/session.go• L222-290 pkg/…/session.go• L293-306 pkg/…/session.go• L687-695 pkg/…/host_test.go• L1173-1219
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to
Host,Identity, orSessioncapability rules must stay aligned between in-process hosting and gRPC hosting. - Changes to
OperatorServiceidentity metadata must stay aligned between the protobuf contract, client metadata, and server authorization. - Changes to registration resume rules must preserve the
resumedmeaning used by action replay and durable worker registration. - Changes to Listen message ordering must preserve the first-message start rule and the pause acknowledgement barrier.
- Changes to action delta limits or sequence handling must preserve chunking, replay, and cumulative acknowledgement behavior.
- Changes to worker activation or session fencing must preserve the link between the database worker and the dispatcher delivery entry.
- Changes to claimer filters or factory lookup must preserve the split between kind-based operators and named GRPC contract operators.
- Changes to claim reconciliation must keep query errors from tearing down valid hosts and must reopen rows that lose their worker.
- Changes to durable request or response ordering must preserve registration acknowledgement before invocation entries and the one-request acknowledgement slot.
- Changes to run observation stream kinds or procedure mappings must keep direction and request or response types aligned with the gRPC services.
- Changes to stream ownership or reconnect handling must ensure observation streams end with the old client and are reopened on the replacement session.
- Changes to shutdown order must keep durable channel close, pause, drain, delta flush, stream close, and worker deactivation in a safe order.
- Changes to host delivery queues must preserve prompt cancel handling and retryable refusal when the start queue is full.
- Changes to in-process DAG run cancellation or eviction must keep ordinary cancellation distinct from shutdown so unfinished work remains retryable.
- Changes to DAG workflow polling or slot selection must keep the worker's advertised actions and durable capacity aligned with the tenant's current workflows.
- Changes to DAG parent-result collection must preserve terminal parent outputs and errors for later steps and replayed task runs.
- Changes to DAG wait registration or completion matching must preserve acknowledgement order and buffering for completions that arrive early.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
A post-registration RPC omits or changes hatchet-operator-id | The engine rejects the call or prevents access to the worker | Attach the registered operator ID to every later OperatorService call |
| The first Listen message is not the registered worker's start message | The stream is rejected before it becomes a live session | Send exactly one start message first |
| Heartbeats stop while the stream remains open | The scheduler treats the worker as inactive | Send heartbeats at the protocol cadence and reconnect on stream failure |
| A delta exceeds the per-message or operator-wide action limit | The delta is rejected and the worker action view does not commit | Chunk changes and wait for Flush acknowledgement |
| A delta is committed but its acknowledgement is lost | The client may otherwise lose part of its action set | Retain unacknowledged deltas and replay them after registration |
| A pause is recorded without stopping dispatcher delivery first | An already assigned action may arrive after the caller believes the worker is drained | Use the session pause barrier and wait for its acknowledgement |
| A run observation stream is opened with the wrong kind or message direction | The open fails or the caller cannot exchange the expected messages | Use the procedure-to-kind mapping and respect server-stream versus bidirectional behavior |
| A session reconnects without reopening its run observation streams | The caller stops receiving run, durable event, or stream messages | Treat streams as session-owned and open them again on the replacement session |
| Durable responses are not consumed | The durable channel reaches its retention bound and fails | Read responses and close channels when the invocation ends |
| A session closes before terminal work events are reported | Held work is retried after the engine's task timeout | Pause, drain, and report terminal events before normal close |
| A host start queue fills while a handler is blocked | The newest start is refused and the engine must retry it through task policy | Keep the queue bounded and treat the refusal as retryable |
| A claim query fails during reconciliation | The claimer cannot prove that a row was released and may leave current hosts running | Keep the prior hosted set until a successful claim result arrives |
| A claimed row has no matching factory | The row stays unhosted and cannot receive work from this process | Register a factory for each buildable kind or named contract operator |
| A dispatcher loses a claimed worker but the claimer keeps the stale host | Work remains attached to an obsolete worker until the next reconciliation | Treat a newly taken row as lost and reopen it on a later poll |
| A claimer tears down without pausing first | New work can arrive while the operator is draining | Use the pause, drain, close order |
| A DAG run reports shutdown as workflow cancellation | The engine records a terminal result instead of retrying unfinished orchestration | Let shutdown interrupt the run without sending a terminal workflow event |
| A durable completion arrives before its wait registration acknowledgement | The operator cannot match the event reference and may lose progress or report a false wait | Hold the completion until the registration acknowledgement supplies its reference |
| A DAG run emits a child trigger before a wait registration is acknowledged | Durable log order can change and replay can report nondeterminism | Hold new triggers until pending wait acknowledgements are consumed |
| A DAG run omits a failed terminal parent from a later trigger | Downstream steps lose the parent's available output or error detail | Pass all terminal parent task IDs to the dispatcher when triggering the next step |
| A DAG run stays idle while waiting for durable events | The run keeps a slot even though it cannot make progress | Report the entries that block the run so the engine can evict it |
Key files
| File | Why to read it |
|---|---|
| api-contracts/…/operator.proto | Defines registration, authorization metadata, Listen messages, acknowledgements, pause rules, and durable RPCs |
| pkg/…/host.go | Defines the host, identity, session, durable channel, and transport-neutral lifecycle contract |
| internal/…/register.go | Explains how operator and worker identities are created or resumed |
| internal/…/authz.go | Shows the tenant, operator, and worker authorization boundary |
| internal/…/session.go | Describes activation, action updates, pause, event reporting, and close behavior |
| internal/…/durable.go | Describes engine-side durable invocation ordering and response bounds |
| pkg/…/session.go | Shows the external client's handshake, receive loop, heartbeat, replay, drain, and close lifecycle |
| pkg/…/actions.go | Shows action set coalescing, chunking, sequence acknowledgements, and replay |
| internal/…/operator_sessions.go | Shows how the dispatcher delivers assigned work and coordinates pause and release |
| internal/…/claimer.go | Shows how a dispatcher claims, builds, hosts, and tears down in-process operators |
| pkg/…/session.go | Shows host-level supervision, bounded action delivery, worker continuity, reconnect behavior, and run stream ownership |
| pkg/…/runstream.go | Defines the supported run observation stream kinds, directions, and message contracts |
| internal/…/claimer_test.go | Verifies claim filtering, factory selection, reconciliation, retry, and teardown behavior |
| pkg/…/host_test.go | Verifies tenant checks, token rotation, reconnect recovery, action restoration, and bounded delivery behavior |
| internal/…/host_test.go | Verifies in-process identity, worker activation, action updates, durable channels, run streams, and session fencing |
| pkg/…/runstream_test.go | Verifies that sessions open supported run observation streams and refuse them after close |
| pkg/…/runstream_test.go | Verifies the procedure mapping and direction and message types for each run stream |
| pkg/…/durable.go | Shows how one external durable listener serves invocation channels |
| pkg/…/operator.go | Shows how the in-process DAG operator refreshes workflow actions, runs durable orchestration, and separates cancellation from shutdown |
| pkg/…/dag.go | Shows how DAG steps, waits, completions, parent results, blocked status, and eviction move through the durable channel |
| pkg/…/dag_test.go | Verifies durable ordering, event races, blocked-run reporting, eviction, and DAG completion outcomes |