Status: first draft. This document is the authoritative design record for the
taskpackage. Update this file (not scattered notes) when decisions change.
tasking is a library — an async task engine (and, soon, a workflow engine) embedded by
other applications. The task package is its core: it lets an embedding app submit a unit
of background work and have it reliably run, retried on failure, timed out on a deadline, or
cancelled, across process restarts and worker crashes, without the app writing any of that
orchestration itself.
The design follows the same library posture as the sibling notify
package. Two consequences run through every decision:
- It cannot dictate cardinality of task creators or impose multi-tenancy — those
belong to the embedding application.
Creatoris an opaque string (the notification routing key; seenotify);taskingnever interprets it. - The engine's components are wired and lifecycle-owned by the app, not by the package. There is no god-object; components are constructed separately and communicate only through Redis IPC queues and a shared database. This keeps each component independently deployable and testable.
The engine is built on one durable invariant: the database is the source of truth. Every IPC message is a best-effort poke that merely lets a component act sooner than the periodic maintenance scan would. Losing a poke delays work; it never loses it.
The single most important distinction in the package — everything else follows from it:
Task— the unit of work the app submits (models.Task). One-shot, either immediate or scheduled for a future time. It is the thing that "completes", "fails", "times out", or is "cancelled".TaskExecution— one attempt at running a task (models.TaskExecution). A task has 1..N executions: the first attempt plus one per retry. Workers process executions, not tasks. After each execution ends, the scheduler decides the task's next step (done? retry? give up?).
Task (COMPLETE/FAILED/TIMED_OUT/CANCELLED)
│
├── TaskExecution #1 (attempt 1 → FAILED)
├── TaskExecution #2 (retry → FAILED)
└── TaskExecution #3 (retry → PROCESSED) ⇒ Task COMPLETE
Because every ended execution is moved to a single FINALIZED state, ExecutionState alone
can no longer report the outcome — so TerminalState (Processed / Failed / Cancelled) is
captured when the instance ends and preserved through finalization. The retry-counting logic
depends on this (it counts executions whose TerminalState == FAILED).
Four components, each an interface with an impl, wired by the app. They never call one
another directly — they exchange typed messages over Redis reliable IPC queues (§7) and
read/write shared state through the db persistence layer.
┌──────────┐ NEW_TASK / CANCEL_TASK
│ Client │ ──────────────────────────────┐
└──────────┘ (writes Task row first) │
defines Task (PENDING) in DB ▼
┌───────────────────┐
│ [scheduler queue]│
└───────────────────┘
│ dequeue
▼
maintenance timer ─(periodic backstop)─▶ ┌────────────┐
│ Scheduler │ the state machine:
EXECUTE_SUCCEEDED / EXECUTE_FAILED / │ │ owns every Task &
EXECUTE_CANCELLED / ENGINE_FAILED ─────▶│ (single │ TaskExecution transition
│ active) │──────┐
└────────────┘ │
│ │ cancel signal
PENDING_INSTANCE │ (pub/sub, §13.5)
▼ │
┌────────────────────────┐│
│ [task-name→exec queue] ││
└────────────────────────┘│
│ dequeue │
▼ │
┌────────────┐ │
│ Receiver │◀─────┘
│ │ per worker host: claim, hand to
└────────────┘ Executor, report outcome, and
hold the cancel registry
│ submit
▼
┌────────────┐ worker pool for one queue:
│ Executor │ runs the app's
│ │ TaskExecutionProcessor
└────────────┘
Every arrow above but one is a durable reliable queue (§7). The exception is the cancel signal, which is fire-and-forget pub/sub because the state it refers to is already committed — §13.5 says why that is the right primitive and why it must not ride either of the queues.
| Component | Role | Lifecycle |
|---|---|---|
Client |
Task API: define Task rows, poke the scheduler, and serve creator-scoped reads/deletes |
constructed & called |
Scheduler |
The brain / state machine; owns all state transitions; single-active | Start / Stop |
Receiver |
Per-worker-host consumer: claim executions, run them, report back | Initialize/Start/Stop |
Executor |
Worker pool for one task queue; runs the user processor | Stop (started at construction) |
Supporting layers:
models— theTask/TaskExecutionstate machines, IPC message types, and audit events (the seam intonotify).db— persistence. State-change methods (MarkTask*) write aSystemEventAuditrow in the same transaction as the state change, so an event and its state commit atomically. Every timestamp in the schema is UTC, including the GORM-managedcreated_at/updated_at(the connection overrides GORM's local-timeNowFunc), so a query may compare a UTC bound against any timestamp column.common— the Redis reliable-queue IPC send/receive clients (§7).
The Client is the only component an application calls directly, so it is also where the
library's one piece of tenancy policy lives. Beyond the submission API it serves the
task-facing reads and deletes — ListTasks, GetTask, DeleteTask, ListTaskExecutions,
GetTaskExecution — so an embedding application never needs db.Database in its normal
vocabulary.
Every one of those, plus CancelTask, is scoped to the client's DefaultCreator:
- Listing injects the creator into
db.TaskQueryFilter.Creatorswhen the caller leaves it unset. An explicit value overrides it, which is the cross-tenant escape hatch. - Single-entry operations report another creator's task as a
NotFoundError, never a permission error. A distinguishable "forbidden" would confirm the task exists, which is exactly what the scope is meant to withhold.
Creator remains opaque to the engine (§9) — tasking compares it, never interprets it, and
the embedding application still owns what identity goes in there. The scope is a default that
keeps one application's tasks (and the workflow engine's internal step-runner tasks, which
carry the reserved models.WorkflowExecutionTaskCreator) out of another's view; it is not a
security boundary. db.Database is deliberately left unscoped — it is the privileged
layer the engine's own components run on, and the escape hatch for an application that needs
a genuine cross-creator view.
Each component is constructed with factory callbacks rather than concrete dependencies:
ExecutorFactoryCB, IPCMsgSenderFactoryCB, IPCMsgReceiverFactoryCB. The app passes the
real Redis-backed factories (common.NewRedisIPCMessage*, NewExecutor); tests pass mocks.
This is how the components stay decoupled and independently testable despite the tight
choreography between them.
Processors are supplied at construction, not registered at runtime. The app declares each
processor on its task, inside the queue that runs it — TaskQueueConfig.SupportedTasks[].Processor
(§10). The constructor derives each queue's taskName → processor map from
Config.TaskQueues and passes it to that queue's NewExecutor, which rejects a nil processor up
front rather than discovering it at dispatch time. The mapping is then immutable for the
component's lifetime — there is no RegisterTaskProcessor, so no lock guarding it and no window
where a PENDING_INSTANCE can arrive before its processor is registered. A task name that still
has no processor at dispatch time is treated as an engine failure (§8).
Because a processor lives inside its queue's config, binding one to a queue the receiver does not serve is unrepresentable — there is no separate mapping to fall out of step with the queue list.
State machine (models.Task.ValidNextState):
┌─────────────────────────────────────────────┐
│ ▼
submit ─▶ PENDING ─▶ ACTIVE ─▶ COMPLETE CANCELLED
│ │ │ ├──▶ FAILED ▲
│ │ │ └──▶ TIMED_OUT │
│ └────────┴──────────────────────▶ CANCELLING ────┘
└───────────────────────────────────────▲
(PENDING or ACTIVE may go to CANCELLING on a cancel request)
| Transition | Driven by | Trigger |
|---|---|---|
| (none) → PENDING | Client (DefineAndRun…) |
app submits a task |
| PENDING → ACTIVE | Scheduler.processNewPendingTask |
NEW_TASK poke (or maintenance sweep) |
| ACTIVE → COMPLETE | Scheduler.processTaskExecutionComplete |
an execution reached PROCESSED |
| ACTIVE → FAILED | processTaskExecutionFailed / …EngineFailed |
retries exhausted, or an engine failure |
| ACTIVE → TIMED_OUT | processTaskTimeout / …ExecutionTimedOut |
task/execution deadline passed |
| PENDING/ACTIVE → CANCELLING | Scheduler.processCancelTask |
CANCEL_TASK poke (or maintenance) |
| CANCELLING → CANCELLED | Scheduler.processTaskExecutionCancelled / …CancelTask / maintenance |
the task's last live execution instance drained |
Notes:
- CANCELLING is where a task waits for its work to stop. A cancel request can arrive while the
task is still PENDING or ACTIVE — nothing naturally drives it through CANCELLING first — so
processCancelTaskmarks it CANCELLING and settles any execution instance no worker holds. A task with an instance a worker is running stays CANCELLING until that instance drains, so the state has real (bounded) duration rather than being a staging step passed through inside one transaction. The full mechanism, and why the wait is bounded, is §13. - Entering ACTIVE / CANCELLING / COMPLETE / FAILED / CANCELLED / TIMED_OUT writes a matching
SystemEventAuditrow in the same transaction (db.updateTaskState). These are the eventsnotifybroadcasts.CANCELLING_TASKis the one that reports a cancel accepted rather than completed, which is what lets a subscriber distinguish "draining" from "stopped". - Terminal states are COMPLETE / FAILED / TIMED_OUT / CANCELLED — the states with no
outgoing transition. Ask
task.HasReachedTerminalState()(orstate.IsTerminal()) rather than restating the set; both are derived from the transition graph above, so they cannot drift from it. Seemodels/state.go. - Deletion is terminal-only.
db.DeleteTaskrefuses a task in PENDING / ACTIVE / CANCELLING: the scheduler may still be acting on it, and the delete cascades away thetask_executionshistory underneath it. Cancel it first — and because a cancel drains (§13), a task whose work is still running stays undeletable until it settles CANCELLED. A task linked to a workflow step is refused outright regardless of state — it is that workflow's execution history, andDeleteWorkflowis the privileged teardown path that reaps it (bypassing both guards).
State machine (models.taskExecutionStateTransitions):
DEFINED ────┐ ┌─▶ PROCESSED ─┐
(immediate) ├─▶ ENQUEUED ─▶ ACQUIRED ─▶ PROCESSING┤ ├─▶ FINALIZED
SCHEDULED ──┘ │ │ │ └─▶ FAILED ────┘
(future/retry) │ └───┬────┘
│ ▼
│ CANCELLING (a worker holds it — it drains)
│ │
└──▶ CANCELLED ◀─┘
(nobody holds it — cancelled outright)
CANCELLED is reachable from every live state, but by two different routes, and the
difference is the whole of §13. An instance no worker has claimed (DEFINED, SCHEDULED, ENQUEUED) is
cancelled outright, because there is nothing running to wait for. One a worker holds (ACQUIRED,
PROCESSING) passes through CANCELLING while the work drains, and reaches CANCELLED when it
actually stops.
All three outcomes — PROCESSED, FAILED, CANCELLED — are separate branches; that is why
models.HasEnded() is the union of "at or past" any of them, distinct from IsStateAtOrPast
which walks a single downstream chain.
Ended is not terminal here. The only states an instance can never leave are CANCELLED and
FINALIZED, so HasReachedTerminalState() admits just those two — a PROCESSED or FAILED
instance has ended, but the scheduler still moves it to FINALIZED. Use HasEnded() to ask
whether the outcome is known, HasReachedTerminalState() to ask whether the instance is done
moving.
CANCELLING is neither, and that is the case to keep in mind when writing a guard. It has not
ended — no worker has reported, so the outcome genuinely is not known yet — and it is not
terminal, because CANCELLED is still ahead of it. So HasEnded() is false for a CANCELLING
instance, and a handler that must not act on an instance being cancelled has to say so explicitly
rather than relying on the usual predicate (§13.4).
| Transition | Owner | Method |
|---|---|---|
| create → DEFINED/SCHEDULED | Scheduler | db.DefineNewTaskExecInstance (immediate ⇒ DEFINED, scheduled/retry ⇒ SCHEDULED) |
| → ENQUEUED | Scheduler | MarkTaskExecQueued + send PENDING_INSTANCE |
| → ACQUIRED | Receiver | MarkTaskExecAcquired (records worker_name) |
| → PROCESSING | Executor | MarkTaskExecProcessing (pre-processing) |
| → PROCESSED / FAILED | Executor | post-processing defer (captures TerminalState; on FAILED, also FailureDisposition — see §8.1) |
| → FINALIZED | Scheduler | MarkTaskExecFinalized (after deciding task's next step) |
| → CANCELLING | Scheduler | MarkTaskExecCancelling (a claimed instance, on a cancel request — §13.2) |
| → CANCELLED | Executor or Scheduler | MarkTaskExecCancelled — see the rule below |
Ownership handoff — no two components touch the same transition:
- Scheduler owns creation, DEFINED/SCHEDULED → ENQUEUED, → CANCELLING, and the finalization tail.
- Receiver owns ENQUEUED → ACQUIRED and the failure/engine-failure reporting paths.
- Executor owns ACQUIRED → PROCESSING → PROCESSED/FAILED.
CANCELLED is the one transition with two possible writers, and the rule that keeps them from colliding is the component that holds the instance settles it: the Scheduler cancels an instance nobody has claimed (and force-settles one whose worker never answered, §13.6), while the Executor settles one it is running. Neither can act on the other's, because "holds it" is exactly what the ACQUIRED claim records.
The deadline is honored at execution time: the executor derives a context.WithDeadline from the
instance's Deadline. It derives it from the per-instance context the receiver hands it (§13.5),
so the deadline and a cancel signal reach the processor through the same context — the deadline as
that context's own expiry, the cancel as an early cancellation of its parent. Both depend on the
processor honoring the context it was given: a deadline is not an enforcement, and a processor that
ignores its context is not cut off by one. §13.1 is precise about why nothing stronger is available.
The scheduler is the only component that mutates state. It is a single serial consumer: one
support goroutine (processQueue) dequeues an event off its dedicated reliable IPC queue, parses
it, and runs the associated process* handler inline on that goroutine. There is no separate
worker — every event, including maintenance, is processed one at a time on this single path, so
request buffering lives in the IPC queue rather than a second in-process channel.
- The IPC path (
processQueue→processOneIPCRequest): reads the scheduler queue, parses each message, and calls the matchingprocess*handler directly. A handler that returns nil means the message is done and is deleted from the buffer; a fatal error leaves it buffered for startup replay; a poison message is audited and dropped. - The maintenance path (
performMaintenance): re-scans the DB and calls the sameprocess*handlers directly. It does not run on a separate thread — the maintenance interval timer self-enqueues anIPC_TASK_ENG_MAINTENANCEmessage onto the scheduler's own queue, so the sweep is dequeued and run byprocessQueuein the exact same serial path as every other event.
Because everything runs on the one processQueue goroutine, no two handlers ever execute
concurrently and there is no in-process ordering to reconcile.
Every handler guards against duplicate and racing deliveries (an IPC poke racing the
maintenance sweep, or a redundant re-delivery from buffer recovery) using
IsStateAtOrPast / HasEnded / explicit TaskState checks. If the work is already done,
the delivery is a safe no-op; a genuinely out-of-order delivery is not masked and still
surfaces as a consistency error via the subsequent ValidNextState check.
One refinement, where a handler both writes a state and then draws a conclusion from the wider row set: guard the write, not the handler. Returning early because this handler's own write is already done also skips the conclusion, which a different writer may have left owed. §13.7 is the case that makes this concrete — a cancellation report whose instance a force-settle already wrote must still go on to ask whether its task can now settle.
The receiver applies the same rule to the one message it consumes. processOneIPCRequest
reads the execution instance before claiming it: an instance already at or past ACQUIRED
(which includes every ended state) means somebody already owns it, so the request is dropped
from the buffer as a benign duplicate — not reported as an engine failure, which would fail a
parent task that is running perfectly well elsewhere. A state upstream of ACQUIRED is
deliberately left unmasked and still surfaces through MarkTaskExecAcquired's ValidNextState
check. Duplicates are expected here by construction: §6.3's stale-ENQUEUED sweep re-sends a
dispatch whose original looked lost, and buffer replay can re-deliver one.
Every handler follows one ordering rule: it commits the driving state change to the DB first, and only then emits the follow-on IPC message. The message is a poke — it lets the next component act sooner than the maintenance sweep would; it is never the sole record that work exists.
This is load-bearing, not stylistic. The scheduler and the task worker are separate processes against a shared Redis queue: a message enqueued inside the transaction is visible to a worker immediately, well before the transaction commits. A worker that dequeues it then reads an execution instance that does not exist yet, or reads it in its pre-transaction state. The inverse — commit first — is safe because a worker can only ever observe state that is already durable.
Concretely:
- New Pending Task marks the task
ACTIVEand its immediate execution instanceENQUEUED(committed), then emits the dispatch request onto the task queue. - Execution Starting marks the instance
ENQUEUED(committed), then emits the dispatch.
Because of this ordering, a failed emit — the enqueue errors, or the process dies between the commit and the send — loses only the poke, never the work, so it is logged rather than returned. What the emit must never do is fail the handler: the state is already committed, and returning an error would only re-run a handler whose idempotency guard now no-ops.
Two things the rule requires of the surrounding code. The sender lookup stays inside the
transaction — it is an in-memory map read, not IPC, and a task with no route to a worker must
roll the whole thing back rather than commit an ENQUEUED instance nothing can ever claim.
And every lost poke needs a sweep step that re-derives it (§6.3); ENQUEUED is the one state
with no state change left to make, which is why it gets a re-send rather than a re-drive.
The maintenance interval timer does not invoke maintenance directly — it enqueues an
IPC_TASK_ENG_MAINTENANCE message onto the scheduler queue, so the sweep rides the same serial
processQueue path as every other event. performMaintenance re-scans the DB for every state a
lost poke could strand:
- PENDING / CANCELLING tasks — schedule them, or re-drive the cancel.
- ACTIVE tasks past their deadline — time them out.
- PROCESSED / FAILED executions awaiting finalization — finalize them.
- SCHEDULED executions due to start — enqueue them. (This is also the only path that fires scheduled and retry executions — there is no poke for a future time.)
- ENQUEUED executions past the re-poke grace period — re-send their dispatch request.
- Live executions past their deadline — time them out.
This is why the engine is self-healing: a dropped IPC message only delays work; the next maintenance pass catches it. It is also structurally required for scheduled/retry executions, which have no triggering message.
Step 1 carries the whole of cancellation's recovery, which is why cancellation adds no step of
its own. Re-running processCancelTask for a task already CANCELLING re-publishes the cancel signal
(recovering the one message class that is not sent over a reliable queue — §13.5), force-settles
any instance past the cancellation grace (§13.6), and re-evaluates whether the task can now settle
(§13.7). All three follow from the state the DB already holds, so the one existing scan is enough.
Two steps deliberately cannot see a cancellation in progress, and both are correct to be blind to it. Step 2 lists only ACTIVE tasks, and a CANCELLING task is not one; step 6 enumerates the live execution states explicitly, and CANCELLING is not among them. A cancel that is already draining must not also be timed out — §13.4 gives it precedence, and §13.6 is what bounds it instead.
Step 5 is the odd one out and exists because of §6.2.1. Every other step re-derives a state
change the DB says is still owed. ENQUEUED has no such change left — it is the state an
instance is committed in immediately before its dispatch is sent, so a lost send leaves nothing
for the DB to reveal except an instance sitting there. repokeEnqueuedExecution therefore
re-sends the message and mutates nothing. The grace period is one full maintenance interval
(floored at 10s): an instance a worker is about to claim leaves ENQUEUED within milliseconds,
so anything still there after a whole sweep cycle has lost its poke rather than merely queued
behind a busy worker pool. Re-sends that race a claim are absorbed by the receiver's guard
(§6.2).
On an execution FAILED (and the task still ACTIVE), processTaskExecutionFailed counts prior
FAILED executions, asks RetryParams.NextDelay(count-1) for the backoff, and either defines a
new SCHEDULED retry execution (at now + delay) or, if retries are exhausted
(delay <= 0), marks the task FAILED. Backoff is exponential, clamped to a hard
MaxRetryDelay ceiling.
common implements a reliable queue on Redis (IPCMessageReceive/IPCMessageSend):
DequeueMessageatomically moves a message from the shared main queue into a per-reader buffer queue (PopLeftAndMove). The message lives in the buffer until the reader is done with it (DeleteBufferedMessage) — so a crash mid-processing leaves the message safely staged, not lost.- Each reader owns an exclusive buffer queue, so multiple readers can share one main queue.
A crash after dequeue-but-before-delete strands messages in the buffer. Both consumers recover at startup, before normal consumption begins:
- Scheduler —
recoverBufferedMessagesdrains the buffer and re-enqueues valid messages onto the main queue (single processing path); poison messages are audited and dropped. - Receiver —
Initializedrains its buffers and reconciles against the DB: ENQUEUED instances are re-queued for retry; instances this worker was processing are marked FAILED; already-terminal or other-worker instances are ignored. It also fails any instance the DB still shows this worker as processing (it must have crashed mid-run).
A CANCELLING instance is the one case reconciliation must not treat as a failure. A worker that
crashes mid-drain leaves an instance whose cancel this process was the party responsible for
answering, so Initialize settles it CANCELLED and reports EXECUTE_CANCELLED rather than FAILED.
Recording FAILED instead would be wrong twice over: it contradicts §13.4's precedence rule, and it
reports an outcome that drives the failure handler, leaving nothing to ask whether the parent task
can now settle (§13.7). The restarted worker is the fastest party to notice; the scheduler's grace
(§13.6) is what covers a worker that never comes back at all.
Unreadable, unparsable, or unsupported-type messages are recorded as an
INVALID_TASK_IPC_MESSAGE audit event (best-effort — logged if the write fails) and dropped
from the buffer. A message that can never be processed must not become an infinite
crash/replay loop.
Only a models.SQLError (the database or its connection is broken) is fatal — no per-request
recovery is meaningful when the DB is down and every message would fail identically (so this is not a
per-message loop). The scheduler consumer, the workflow-scheduler consumer, and each receiver
per-queue consumer all use the same isFatalDBError (errors.As for SQLError, found through the
wrapped error chain) to make this call.
Handing a fatal fault to the parent — OnFatal. tasking is a library with a fire-and-forget
Start, so a worker goroutine must not decide the host process's lifetime by calling os.Exit
directly. Each of the three worker types accepts an optional OnFatal(reporter, err, timestamp)
callback on its constructor params (NewSchedulerParams, NewWorkflowSchedulerParams,
NewReceiverParams). When a consumer goroutine hits a fatal SQLError it invokes the callback and
then exits that goroutine (it does not loop re-firing on a permanently-broken DB), leaving the
decision of what to do — typically a graceful shutdown — to the parent application. The callback is
guarded by a per-component sync.Once (reportFatal), so even when several receiver queue threads
trip the same outage at once the parent is notified exactly once. When no callback is supplied, the
default preserves the prior behavior: log the fault and log.Fatal.
For the scheduler (and the workflow scheduler, which mirrors it) the split is expressed as
two independent decisions in processOneIPCRequest and processQueue:
- Delete keys off completion, not success. The reliable-queue buffer guards against exactly
one thing — an application crash/panic mid-handling, where the handler never returns. So once a
handler returns (nil or error), the message is deleted from the buffer. Only a crash leaves
a message for
recoverBufferedMessagesto replay. A returned error never strands a message, so a deterministically-failing handler cannot become a replay crash-loop. - The error class decides only stop-vs-continue. After the delete,
processOneIPCRequestreturns the handler error andprocessQueueclassifies it: amodels.SQLErrorreports viaOnFataland stops the consumer; anything else is logged and processing continues. The maintenance sweep re-drives the stranded work from the DB (the source of truth), so a single failing message never wedges the scheduler.
The receiver shares the same SQLError-only fatal split. Most handler failures never surface as
a returned error at all — a bad request is dropped, the failure is reported to the scheduler, and the
queue thread continues. Only an error that propagates out of processOneIPCRequest reaches the
fatal-vs-continue decision in processOneQueue: a models.SQLError reports via OnFatal and stops
that queue thread, anything else is logged and the thread continues.
The cancel signal (§13.5) is the single piece of engine IPC that does not use the reliable queue above. It is published on Redis pub/sub, at most once, retained nowhere.
The reason is that the reliable queue buys exactly two properties, and a cancel signal needs neither. It survives a consumer crash mid-handling — but the signal refers to state that is already committed, so losing it costs latency and never work. And it holds a message until some consumer takes it — but the signal is addressed at a particular process, and a durable per-receiver queue would therefore accumulate undeliverable signals forever for every worker host that never comes back.
What the signal does share with every queued message is §6.2.1's ordering: it is published after the transaction that marked its instances CANCELLING commits, never inside it. §6.3's step 1 re-publishes it, which is what makes a lost signal cost a sweep interval rather than the rest of the work.
Two distinct failure kinds with different semantics:
- Execution failure (
EXECUTE_FAILED,SystemEventTypeFailedTask) — the task's own processor returned an error. Retryable per the task's retry policy — unless the failure carries a non-retryable disposition (see below), in which case the task is failed outright with no retry, but it is still an execution failure (same message type, sameFailedTaskaudit event). - Engine failure (
ENGINE_FAILED,SystemEventTypeEngineFailedTask) — the framework itself couldn't operate: the receiver couldn't claim the instance, couldn't submit it to the executor, or the executor's queue has no registered processor for the task name (a misroutedPENDING_INSTANCE). Not retried —processTaskExecutionEngineFailedfinalizes the instance, fails the task, and writes an audit event atomically. The parent app is expected to review these.
Cancellation is a third outcome and is neither of these (§13). It is not an execution failure —
nothing went wrong, and the retry machinery is not consulted at all — and it is not an engine failure,
because the engine did exactly what it was asked. It carries its own report
(IPC_TASK_ENG_EXECUTE_CANCELLED), its own audit event (SystemEventTypeCancelledTask), and its own
instance state.
An execution failure carries a FailureDisposition (RETRYABLE / NON_RETRYABLE; nil is
treated as retryable). A TaskExecutionProcessor opts a failure out of retry by wrapping its
returned error in a models.NonRecoverableError (e.g. malformed input, a resource that will never
exist). The executor detects it with errors.As and, when marking the instance FAILED, persists
NON_RETRYABLE on the TaskExecution row and stamps it on the EXECUTE_FAILED IPC message.
The persisted column is the source of truth: processTaskExecutionFailed reads it (not the
message) via the shared decideExecutionRetry helper, so the maintenance backstop — which has no
message — reaches the same decision. A lost EXECUTE_FAILED poke therefore cannot resurrect a
non-retryable failure as a retry. decideExecutionRetry is the single point both the IPC handler
and the maintenance sweep call, so the "skip retry on NON_RETRYABLE" rule cannot drift between
them (see §6.2/§6.3).
The classification "which outcome → which report" lives in receiver.onTaskComplete. The cancelled
branch is decided first and without inspecting any error, because the executor reports it as an
explicit terminal state rather than as an error class (§13.5): a CANCELLED outcome → EXECUTE_CANCELLED.
Otherwise the error decides — a TaskExecutorError (the executor's marker for a missing processor) →
ENGINE_FAILED; anything else → EXECUTE_FAILED, with NON_RETRYABLE iff a NonRecoverableError is
in the chain.
A processor performs work that must not be re-executed when its task is retried: LLM calls are non-deterministic, tool calls mutate the world. The journal records the results of those operations so a re-entered processor reuses them instead of re-performing them.
This is a Task Engine feature rather than any one engine's, and deliberately so. Every engine in
tasking runs its work as a task — a workflow step runs under one, a BSP vertex's superstep runs
under one — so anything built on §4's retry inherits journaling by construction. The engines that
need it say what an effect means in their vocabulary; what an effect is is specified here.
Effect marks the boundary between code that is safe to re-run and code that is not:
Everything outside an
Effectmust be deterministic and side-effect-free, because re-entry will execute it again. Everything non-deterministic or externally-visible must be inside one.
This is obligatory, not opportunistic. The question is not "do I want to cache this?" but "if this ran twice, would it produce a different value, or change the world twice?"
Three categories, and only the first is journalable:
- Journal it — I/O, wall clock, randomness, UUID generation. Anything reading the outside world.
- Eliminate it — Go map iteration order, goroutine scheduling,
selectover multiple ready channels. These cannot be recorded away; they are fixed by sorting keys or by explicit effect keys. - Leave it alone — pure computation over data already in hand. Parsing, formatting, deciding
what to do next. Wrapping pure work in an
Effectis legal but stores its result forever; journaling is a correctness tool that happens to memoize, not the reverse.
A retry does not resume a paused invocation. It re-enters the processor from the top and the journal makes already-completed effects return instantly. Everything between the effects — parsing, branching, prompt assembly — is genuinely recomputed. That is why the surrounding code must be deterministic, and why "resume where it left off" is a misleading mental model.
Inputs are explicit parameters, not closure captures. The engine must fingerprint what the handler was given, and it cannot see through a closure.
func Effect[In, Out any](
ctx context.Context,
j *Journal,
key string,
input In,
fn func(context.Context, In) (Out, error),
) (Out, error)It is a package-level function rather than a method on the journal because Go does not permit
type parameters on methods — j.Effect[T](…) is illegal — so the handle is passed in.
Generics carry the decode target: Out is known at each call site, so the engine needs no type
registry and no type tag in the journal. Out must be instantiated with a concrete type —
Effect[Req, io.Reader] compiles and then fails at decode, since the decoder has nothing to
allocate. Go cannot express "must be concrete" as a constraint, so this is a documented rule
with a runtime error behind it.
The split between parameter and capture is the load-bearing convention:
Data goes in
input; infrastructure goes in the closure. The explicit input is the semantically load-bearing data, and is fingerprinted. Captured values — clients, pools, loggers — are scaffolding and must not affect the result. A capture that does affect the result creates exactly the silent divergence the fingerprint exists to catch, and will not be caught.
// llmClient is captured: infrastructure, never serialized
resp, err := Effect(ctx, j, "llm:turn-3",
LLMRequest{Model: model, Messages: history, Temperature: 0},
func(ctx context.Context, req LLMRequest) (LLMResponse, error) {
return llmClient.Complete(ctx, req)
})ctx is a parameter rather than part of In for the same reason — request scaffolding, not
data.
How a processor obtains its *Journal is deliberately left open here; it is settled with the
implementation.
(taskID, effectKey)
│ └── which effect inside this invocation
└── which unit of work
The task is the right grain, and not merely a convenient one. The journal needs exactly one
property from its key — automatic retry hits, user-initiated retry misses — and in every engine
the Task is precisely the identity that satisfies both halves:
| Engine | Automatic retry | User retry |
|---|---|---|
| Task | a new TaskExecution, the same Task |
a new task |
| Workflow | the task engine's retry, within the step's task | a revive links a new task |
| BSP | attempts at the vertex's one task | a fork dispatches a new task |
So crash recovery, an exhausted attempt, and a per-attempt timeout all re-enter against a journal that is already populated, while every deliberate do-over lands on a task with no rows. Nothing has to be deleted to make that true, which demotes journal deletion to pure garbage collection: optional, deferrable, and incapable of corrupting anything.
effectKey disambiguates multiple effects in one invocation. An implicit ordinal (a
counter that resets per invocation) is the simple form, but it is stable only if effects are
issued in a deterministic order — spawning concurrent effects and recording them as they
complete assigns ordinals differently on re-entry, silently returning one effect's result to
another. Explicit user-supplied keys remove that ordering dependency and are the safer
default where a processor fans out effects concurrently.
JournalEntry
ID ulid -- minted by the persistence layer
TaskID -- unique with EffectKey; ON DELETE CASCADE
EffectKey string
InputDigest []byte -- over the deterministic CBOR encoding of the input
Output []byte -- CBOR-encoded result
CodecID string -- which codec wrote Output
CreatedAt, UpdatedAt
Three notes:
InputDigestsits outside the unique key deliberately. It is a guard, not part of the lookup — see §9.6.- There is no
Creator, alone among the tables in this package.Creatoris carried elsewhere so audit events route without a join, and the journal records no audit event; nor does an application ever query it, since the journal is reached only throughEffect. A column whose only justification has no consumer does not earn its place. Tenant-scoped reaping is still available one join away, throughTask.Creator. - Rows CASCADE with their task, where a workflow step's or a BSP vertex's records are guarded against deletion instead. The difference is what the row is: a journal entry is memoization, and deleting the whole table leaves execution correct for pure effects, losing only the at-most-once guarantee for impure ones. It has no claim to outlive what produced it.
Each entry records a digest of the encoded input alongside the result. On a key hit with a mismatched fingerprint the engine fails loudly with a non-determinism error rather than returning a result computed from different inputs.
The fingerprint is a guard, not part of the lookup key. A mismatch is an error, not a cache miss. The alternative — content-addressing, where changed input silently becomes a miss and re-executes — hides a real bug, and would make two legitimately identical calls in one invocation collide.
It is the safety net for the one path that can otherwise diverge silently: a processor that swallows an effect error and branches on it may take a different route on re-entry, reaching the same effect key with different arguments. The general contract it enforces:
A processor must take the same path on every attempt at a task, given the same journal.
CBOR (RFC 8949, STD 94) is the encoding for both
input and output, via github.com/fxamacker/cbor/v2.
The two sides have asymmetric requirements, and only one of them is demanding:
| Input | Output | |
|---|---|---|
| Purpose | Detect divergence | Reconstruct a Go value |
| Direction | One-way — hashed, never read back | Round-trip — encode then decode |
| Deterministic encoding required | Yes | No |
| Decodable required | No | Yes |
| Persisted as | fixed-width digest | encoded bytes |
The canonical encoding of the input is ephemeral — encode, hash, discard. Only the digest is stored, so the input's byte form is never read back by anything.
Plain CBOR is not deterministic. The base format permits indefinite-length containers,
non-shortest integer widths, and arbitrary map key order, so encoding the same value twice may
legitimately produce different bytes. Determinism requires the RFC 8949 §4.2 Core
Deterministic profile, which must be opted into: cbor.CoreDetEncOptions() —
SortCoreDeterministic, IndefLengthForbidden, shortest-float, NaN/Inf normalization.
Use
CoreDetEncOptions(), notCanonicalEncOptions(). The latter implements the older RFC 7049 "Canonical CBOR", which orders map keys length-first rather than bytewise. Both are internally stable, so the wrong choice will not break a single deployment — it will only break agreement with a second implementation.
CBOR was chosen over JSON canonicalization (RFC 8785,
JCS) for a decisive reason: JCS cannot represent int64. It serializes numbers per
ECMAScript, whose data model has only IEEE-754 doubles, so integers above 2⁵³ lose precision and
two distinct int64 values can produce the same digest. For a divergence guard, a false "these
match" is precisely the failure being guarded against — and this is not hypothetical in Go,
where Unix nanosecond timestamps (~1.7×10¹⁸) and Snowflake-style IDs exceed the bound routinely.
CBOR also has a native byte-string type, where JSON turns []byte into base64 that is
indistinguishable from a string.
The constraint comes from durability, not from CBOR. The journal must reconstruct Out in a
different process, on a possibly different worker, possibly days later; nothing depending on
process-local state survives that trip. Any codec would impose the same rule — CBOR only makes
it explicit and enforceable.
No interface implementation is required. Encoding is reflection-based like encoding/json,
with cbor:"..." struct tags for naming; types needing special handling may implement
cbor.Marshaler / cbor.Unmarshaler.
What does not survive:
| Behavior | ||
|---|---|---|
func, chan |
Encode error | loud |
| Cyclic structures | Error or non-termination | loud |
| Unexported fields | Silently dropped | dangerous |
interface as Out |
Decode cannot allocate a concrete type | loud |
*sql.DB, *http.Client, io.Reader |
Encodes to nothing meaningful | silent |
sync.Mutex, sync.WaitGroup |
Unexported fields → empty struct | silent |
| Pointer identity, shared state | Serialized by value; identity lost | silent |
Unexported fields are the hazard to watch. They fail in both directions: a reconstructed
Out silently loses them, and on the input side two genuinely different values fingerprint
identically — defeating the guard exactly when it is needed.
time.Time needs normalizing regardless of codec. It carries a monotonic reading and a
*Location pointer, so two values that compare equal can encode differently depending on how
they were constructed. Normalize before the value reaches the encoder — .UTC() plus an
explicit truncation, or a Unix integer. This is a rule about the type, not the codec; no
canonicalization scheme will do it for you.
Errors never enter the journal. A failed effect is not recorded (see
§9.10), so Out only ever holds a success value.
An LLM streaming response is an io.Reader or a channel and therefore cannot be an Out. The
effect boundary sits after stream assembly: the handler consumes the stream internally and
returns the assembled message.
The application-visible consequence is that on re-entry there is no stream. A UI that rendered tokens live during the first attempt receives the finished message on replay, not a replayed token sequence. This is inherent to a stream being a live-only artifact, and is stated here so that no application is designed assuming otherwise.
Most of the silent failures above collapse into a single check — after encoding, decode and compare:
if devMode && !reflect.DeepEqual(input, roundTrip(input)) {
return fmt.Errorf("effect %q: input does not survive serialization", key)
}That one assertion catches unexported fields, unserializable members, pointer-identity
assumptions, and the time.Time monotonic-clock problem — each of which is otherwise silent and
surfaces much later as unexplained replay divergence. It converts the worst bug class in this
design into a startup-time error.
The precise fingerprint derivation is open.
State it precisely — "at-most-once" would be an overclaim:
An effect that completes and is journaled executes exactly once across all attempts at a task. An effect interrupted between execution and journaling may execute again.
A process that dies after the HTTP POST is sent but before the response is recorded journals nothing, and the retry re-POSTs. That boundary is irreducible without compensation, which is a non-goal.
This puts one requirement on the implementation: the journal write must commit before
Effect returns, not be buffered. Every effect completion costs a durable write. At LLM
latencies that is free, and it must not later be optimized into a batch.
There is no retry inside Effect. The per-attempt retry of §4 and §6.4 is the only retry, and
the journal makes it incremental:
- An effect that completed is journaled; re-entry fast-forwards past it.
- An effect that failed is not journaled; re-entry re-executes it.
Which yields the property that justifies the journal's complexity:
The journal converts the engine's coarse "retry the whole task" into "retry only the part that did not finish."
A processor making three LLM calls and failing on the third normally redoes all three per attempt. Here attempt 2 fast-forwards the first two for free. The same applies to per-attempt timeouts: a task that times out mid-invocation retries with a fresh budget without re-paying for completed work.
The trap this creates, and its resolution. A failure in deterministic code downstream of a journaled effect is reproduced exactly by re-entry — the journal's whole purpose — so automatic retry burns every configured attempt on an identical failure:
1. Effect("llm", …) → response R, journaled
2. parse(R) → error: malformed tool call
3. the engine retries
4. Effect("llm", …) → journal HIT, returns R
5. parse(R) → identical error
Task-level retry helps only when the failure is at or before the last un-journaled point: worker crash, OOM, task timeout, a transient error in an effect that never recorded. Semantic failures need a new effect, which means a new task.
Resolution: the processor returns models.NonRecoverableError for a failure retry cannot fix,
exactly as §8.1 prescribes for any other execution failure. Attempts stop immediately and the task
fails outright, surfacing to whoever owns the work — whose recovery is to run it again under a new
task. This needs no journal-specific machinery in the retry path.
Because compensation is a non-goal, one sentence must land prominently for implementers:
Retrying a task re-executes its unjournaled effects. Effects that are not idempotent will occur more than once. Ensuring idempotency is the responsibility of the processor.
Cancellation (§13) is governed by the same sentence and needs no rule of its own. A cancelled task keeps its journal rows — they are keyed to the task, and nothing deletes them — but the way an application re-runs cancelled work is a new task, which under §9.4 means an empty journal. So its effects run again, exactly as any other deliberate do-over's would.
Every state change writes a SystemEventAudit row in the same transaction, carrying the
task's opaque Creator. The notify package's producer polls those rows and broadcasts them
over Redis pub/sub. task is responsible only for producing durable, creator-tagged audit
events; routing, channels, and delivery are notify's concern. See
notify/DESIGN.md.
Two events are not state changes and are broadcast all the same, because each reports something a
subscriber cannot infer from the states it sees. ENGINE_FAILED_TASK names an instance the engine
could not operate on (§8), and FORCE_CANCELLED_TASK_EXECUTION names a drain the engine stopped
waiting for (§13.6) — a cancel whose task then settles exactly as a clean one does. Both are routed on
their parent task, like every task-bearing event.
The forthcoming workflow engine is a first-class consumer of these notifications (fast path) with a DB-reconciliation backstop, mirroring the task engine's own poke-plus-maintenance reliability model.
All three components describe task queues with the same []TaskQueueConfig. A queue entry
carries its name, worker count, buffer length, and SupportedTasks — the tasks that queue runs,
each with its retry parameters and its TaskExecutionProcessor.
TaskClientConfig— scheduler queue name; task queues (optional, and read only for the per-task-name retry overrides).TaskSchedulerConfig— maintenance interval (≥ 10s); cancellation grace (≥ 10s); scheduler queue name; task queues (read only for queue names and the task names each serves, so the scheduler knows which queue to poke).TaskReceiverConfig— receiver name; scheduler queue name (to report outcomes); task queues, the only component that reads them in full.
The cancellation grace is the scheduler's alone, and it is configured rather than derived because it measures something only the application knows: how long its slowest processor legitimately takes to shut down once asked (§13.6). Deriving it from the maintenance interval would make a short sweep cycle force-settle healthy drains, which is the opposite of what a short sweep cycle should mean.
Nothing new is needed to address the cancel signal. Its pub/sub topic derives from SchedulerQueue
(§13.5), which every component already agrees on, so the channel introduces no field for an embedding
application to keep in step across three configs.
Task-name → queue mapping is the routing fabric: the scheduler sends PENDING_INSTANCE to the
queue configured for that task's name, and the receiver serving that queue picks it up. Expressing
it by nesting — a task declared inside the queue that runs it — means the fabric is described
exactly once. The alternative, a routing map maintained separately from the queue list and the
processor set, gave three descriptions of the same fact for an application to keep in step.
The tradeoff is deliberate. Sharing one shape means the scheduler and the client carry fields
they never read (Workers, BufferRequests, Processor), and those fields are required, so a
scheduler-only deployment must construct processors it will never invoke. Accepted: one
authoritative task list in the embedding application is worth more than trimming each component's
config to exactly what it consumes. Processor is excluded from serialization
(mapstructure:"-" json:"-") and injected in Go after the config is loaded, so config files stay
free of interface values even though the struct is not.
Nesting makes one class of error possible that a flat map did not: a repeated name overwrites
rather than merges, silently dropping a queue's wiring or re-pointing a task at the wrong queue.
Queue names must therefore be unique within a config, and task names unique across the whole
config — enforced as a struct-level validation in models.RegisterWithValidator, so it fires
wherever these configs are validated, including nested inside an application's own config struct.
- Periodic / recurring tasks — the models hint at them (
TaskExecutiondoc comment,RETRY_EXECUTIONclass), but onlyIMMEDIATE_ONE_SHOTandSCHEDULED_ONE_SHOTschedule classes are implemented. Recurring scheduling is future work. - Multi-tenancy / creator isolation — the embedding app's responsibility;
Creatoris an opaque, uninterpreted string. - Scheduler leader election — the scheduler is single-active by contract. Running more than one against the same DB is unsafe (they would both mutate state); electing a single active scheduler is the app's job. (Receivers, by contrast, scale out freely — they coordinate through the reliable queue and DB claim.)
- Migrations — schema is stated by the models; schema evolution is handled near release.
- Workflow orchestration — a separate engine and design
(
workflow/DESIGN.md). - Effect key derivation (§9.4) — serialization and fingerprinting are settled (deterministic
CBOR, digest-as-guard), along with the precise fingerprint derivation. What remains is whether
effectKeysupports implicit ordinals in addition to explicit strings. Ordinals are ergonomic but unsafe under concurrent effects; supporting both means supporting the unsafe one. - Journaled type versioning (§9.7) — journal
Outputbytes are a serialization contract across deployments: work spanning a redeploy decodes bytes written by the old binary into the new binary's types. An added struct field decodes as a zero value, a removed one drops data — both silently. Compile-time knowledge ofOutdoes not help, because the bytes predate the current binary. Either carry a schema version alongsideCodecIDand reject a mismatch, or document that work in flight across an incompatible type change must be restarted rather than resumed. The version tag is the safer default wherever a task can idle for days awaiting something external. - True preemption of a running processor (§13.1) — impossible in-process, and out-of-process workers are the only construction that would deliver it. Rejected because it dictates the embedding application's deployment shape and requires serializing everything a processor closes over. An application that needs a hard kill puts its own work behind a process boundary, where cancellation is already fully effective.
- A worker lease in place of the cancellation grace (§13.6) — a worker renewing a timestamp on the instances it holds would let the scheduler tell "the processor is ignoring its context" from "the worker host is gone", which are worth different log lines and different operator responses. The fixed grace conflates them. Costs a column and a heartbeat; deferred until the distinction is actually wanted.
- Addressed cancellation signalling (§13.5) — the signal is broadcast and filtered locally.
TaskExecutionQueryFilter.ExecutionWorkerNameand theworker_namecolumn would support addressing it per receiver instead, which becomes worth doing only at a receiver count where the wasted wakeups matter. - Naming the wedged processor (§13.6) —
runtime.Stack(buf, true)at the moment of a force-settle is the one diagnosis Go permits from outside a goroutine, and would tell whoever owns the processor which one failed to return. It would have to be opt-in: the all-goroutines dump briefly stops the world.
Every other section of this document describes work the engine drives. This one describes work the engine is asked to stop, and it is the one place where the engine's authority runs out:
A cancel is a request, not an instruction. The engine stops outright anything it has not yet handed to a worker, and it asks work already running to stop. It cannot make it stop.
Three properties follow, and the rest of the section is their consequences.
- What has not started is stopped in the database, with no cooperation from anyone (§13.2).
- What is running drains. The execution instance reaches its terminal state when the work actually stops, not when the request arrives — which is what makes a cancelled task's terminal state mean something (§13.3).
- Because a drain cannot be relied on to finish, it is bounded: after a configured grace the scheduler settles the instance regardless (§13.6).
Cancellation is requested at the task level and applied at the execution instance level.
CANCEL_TASK names a task; the drain is per-instance; the task settles once every instance has.
The engine signals a running processor by cancelling the context.Context it was handed. That is
the whole mechanism, and it is worth being precise about why there is no stronger one available —
because the rest of this section's design exists to be correct in spite of that weakness rather than
to paper over it.
Go offers no preemption, on all three counts a reader might hope for.
- No kill primitive. There is no way to stop another goroutine, and there deliberately never
will be: a goroutine halted at an arbitrary instruction leaves mutexes locked, buffers half
written, and
defers unrun, so nothing downstream could trust shared state again. Every runtime that shipped the feature retracted it — Java deprecatedThread.stop(), .NET Core madeThread.Abort()throw, and POSIXpthread_cancelacts only at cancellation points and is unsafe with anything holding a resource.runtime.Goexitterminates the calling goroutine, and there is no way to invoke it, or a panic, on somebody else's. - No addressable thread. Go runs real kernel threads — more than
GOMAXPROCSwhen goroutines block in syscalls or cgo — but goroutines are multiplexed onto them and migrate freely, so a goroutine has no TID and no stable thread affinity.runtime.LockOSThreadpins one, which looks like a foothold and is not: the runtime owns and tracks its threads, so killing one out from under it corrupts scheduler state. - No per-goroutine signal.
SIGKILLdisposition is process-wide, so a targeted kill takes the process with it; every other signal is claimed by the runtime's own handlers and delivered toos/signalchannels. Signals are a process-level input in Go, never a per-goroutine one.
The one exception proves the rule. The runtime does signal goroutines — it sends SIGURG to
force asynchronous preemption of a goroutine spinning without function calls. Note what for: making
it yield so the collector and scheduler can run. The runtime granted itself exactly the capability
that is safe and stopped precisely where this section would need to go further.
And to be exact about the mechanism this engine does use: cancelling a context closes a channel. Nothing in the runtime makes anyone look at it.
Four tiers, and the engine only owns the first:
- The context — a processor that selects on
ctx.Done(), or passesctxinto the calls it makes, stops promptly. This is what the engine provides. - Closing the resource the goroutine is blocked on. The tier that is easiest to forget and
where most real stalls live: a goroutine parked in
Readon a connection returns the moment something closes it, andhttp.Client,database/sqlandnet.Dialerall do exactly that on cancellation. An LLM call with no client timeout is the canonical hang, and it is fully fixed here — by passingctxdown, not by anything the engine can do from outside. - A process boundary. Where a processor's work is external — a container, a subprocess, a remote job — cancellation kills it, and that is genuine preemption. It is why cancellation is completely effective for external work and only cooperative for in-process computation.
- Process exit. The last resort for a worker slot that will never come back. It is not the
library's decision to make:
OnFatal(§7.3) already establishes that the library detects and the application decides whether the host process lives. A receiver restart reconciles throughInitialize(§7.1).
A processor inside a cgo call is the case no tier below the fourth reaches: it blocks its thread outright, cannot be preempted, and the runtime simply starts another thread and carries on.
Because tiers 1 and 2 are the application's to honor, they are stated as a contract rather than a hope:
A
TaskExecutionProcessormust return promptly once its context is done, and must propagate that context into every blocking call it makes. Nevercontext.Background()for I/O.
Cancellation is exactly as good as the processor's own cancellation story. A processor that honors its context is cancelled within milliseconds of the signal; one that ignores it runs to completion and holds its worker slot until it does. The engine detects the second case (§13.6) and records it; it cannot reclaim the slot.
A cancel divides an execution instance's live states by one question — could a worker be running this right now?
| Instance state | On cancel | Why |
|---|---|---|
| DEFINED / SCHEDULED / ENQUEUED | → CANCELLED, at once | No worker holds it, so there is nothing to drain and nobody to ask |
| ACQUIRED / PROCESSING | → CANCELLING, signalled | A worker holds it; only that worker can stop the work |
The upstream states need no drain and must not get one. An instance nobody has claimed has
produced no side effects, and the worker-side handling of a cancel signal is by definition a no-op
for work that has not begun — so marking such an instance CANCELLING would leave it waiting on a
report that no component is ever going to send, with the parent task waiting behind it forever. The
ENQUEUED case is the one that looks ambiguous, because its dispatch message is already on the task
queue: settling it CANCELLED is nonetheless correct and needs no clean-up, since a receiver that
dequeues that message finds the instance at or past ACQUIRED and drops the delivery as the duplicate
it now is (§6.2).
Restricting CANCELLING to instances downstream of a claim is also what keeps that guard honest.
IsStateAtOrPast walks the transition graph forward, so a state reachable from many places is
"past" all of them; with edges into CANCELLING only from ACQUIRED and PROCESSING, a CANCELLING
instance is by construction one somebody already claimed, and the receiver's guard means what it
says rather than reaching the right answer by accident.
Client.CancelTask ──▶ [scheduler queue] ──▶ Scheduler.processCancelTask
│
┌─────────────────────────────────┴─────────────────────────┐
│ ONE transaction │
│ task → CANCELLING (+ event) │
│ DEFINED / SCHEDULED / ENQUEUED → CANCELLED │
│ ACQUIRED / PROCESSING → CANCELLING │
│ nothing left live? → task CANCELLED, done │
└─────────────────────────────────┬─────────────────────────┘
│ commit, THEN publish
▼
ipc:cancel:<scheduler-queue> (pub/sub)
{ instance IDs }
┌────────────────────────┴─────────────────────────┐
▼ ▼
Receiver A: registry hit Receiver B: no hit
→ cancel that instance's context → drop it
│
▼
the processor returns (or never started)
│
▼
Executor pre/post-processing: instance → CANCELLED
│ EXECUTE_CANCELLED
▼
[scheduler queue] ──▶ processTaskExecutionCancelled
│
any instance still live?
no ──▶ task CANCELLED (+ event)
Read as steps:
- The Client pokes.
CancelTaskconfirms the task exists and belongs to this client's creator (§3.0), then enqueuesCANCEL_TASK. - The scheduler commits the intent. One transaction marks the task CANCELLING, splits its live instances per §13.2, and — if nothing is left draining — settles the task CANCELLED immediately.
- The scheduler publishes, after the commit and never inside it (§6.2.1). The published set is the instances it just marked CANCELLING.
- The receiver holding one cancels the context it created for it (§13.5). That context is the one the processor is running under, so the cancel reaches it directly. A receiver holding none drops the message.
- The worker settles the instance. Whether the processor returned early, ran to completion, or
had not started, the executor's pre- and post-processing write CANCELLED and report
EXECUTE_CANCELLED. - The scheduler re-evaluates the task and settles it CANCELLED once no instance is live (§13.7).
Every step after the second is a poke or a report, and none of them is load-bearing: the state is already durable, and §6.3's sweep re-derives whatever was lost.
The instance state machine gives CANCELLING exactly one outgoing transition. That single edge is what expresses the engine's cancellation precedence rule:
A cancel outranks any outcome that arrives after it. Once an instance is CANCELLING, CANCELLED is the only state it can reach.
Stating it in the graph rather than in a guard is deliberate: a rule that lives in
ValidNextState cannot be forgotten at a call site, whereas a rule spelled out in five handlers
eventually is. Two consequences that must not be discovered by surprise:
- A run that succeeded is still recorded CANCELLED. A processor that completes between the signal and its own post-processing has done real work — and its instance settles CANCELLED, its task CANCELLED rather than COMPLETE. The alternative, letting a completion win the race, makes the outcome of a cancel depend on scheduling, and the engines that build on this one rely on a cancel being absorbing.
- Its journal survives (§9). The effect rows are keyed to the task, so nothing is lost; but a deliberate do-over is a new task with an empty journal (§9.4), so its unjournaled effects run again. §9.11 governs, unchanged.
CANCELLING is neither ended nor terminal, which is the trap this state sets for a guard that
reaches for the usual predicate. It is not ended, because the outcome genuinely is not yet known —
no worker has reported. It is not terminal, because CANCELLED is still ahead of it. So HasEnded()
is false for a CANCELLING instance and no idempotency guard phrased as HasEnded() covers one; a
handler that must not act on an instance being cancelled has to say so explicitly. §5 states the same
point from the state machine's side, and §6.3 names the two sweep steps that depend on it.
The signal travels over Redis pub/sub, not over a reliable IPC queue (§7), and both halves of that choice are deliberate.
Why not a queue. A cancel signal is a poke in the §6.2.1 sense: the state it refers to is already committed, so losing it costs latency and never correctness. Durability would buy nothing and cost something real — a per-receiver queue accumulates undeliverable signals forever for every receiver that never comes back.
Why not the existing queues. Two paths look convenient and are both wrong. Submitting the signal into the executor's own worker pool queues it behind the very tasks it exists to cancel, so it is never handled precisely when all workers are busy. Sending it down the task queue is worse: that queue is competitively consumed by every receiver serving it, so the signal can be delivered to a process that does not hold the instance while the one that does never hears.
Topic. Derived from the scheduler queue name, alongside common.BuildIPCMessageQueueName:
ipc:cancel:<scheduler-queue>. Two independent deployments sharing one Redis therefore cannot
cross-signal, and no new configuration field is needed to say so — every component already agrees on
SchedulerQueue (§11).
One topic, filtered locally. The payload carries the set of instance IDs; every receiver sees
every message and acts on the ones it holds. Addressing each receiver individually is possible —
worker_name is on the instance row from ACQUIRED onward — and buys little: the registry lookup is
the real filter either way, receivers restart, and a cancel is rare. See §12.
The receiver creates the per-instance execution context, and the executor is handed one. This is the piece of the design most worth stating deliberately, because the obvious alternative — the executor creating its own context and handing the cancel func back — works and is worse.
The receiver already knows the moment an instance becomes cancellable: it is the component that
claims the instance and submits it. So immediately before Executor.ProcessExecutionInstance, and
for the same reason it records the dispatch message there, it derives a cancellable context from its
own workerCtx, registers the cancel func under the instance ID, and passes the context down. The
executor uses it in place of a context of its own; the deadline it applies (§5) becomes a child of
it, so both the instance's deadline and a cancel signal reach the processor through one context.
What that buys is an ownership boundary with nothing crossing it:
The registry is created, read, and emptied entirely inside the receiver. The executor never learns that cancellation exists — it runs an instance under the context it was given.
The alternative needs a callback pair passed into the executor purely so it can register and deregister in a map it does not own, which puts cancellation machinery into the component whose job is to run work, and puts the executor's internals on the receiver's critical path.
One context, not two. ProcessExecutionInstance keeps a single context.Context parameter, and
it is the instance's: it governs the submit into the worker pool and, carried on the work request,
the processor invocation on the far side. A second parameter to separate the two roles would be the
obvious way to dodge the consequence below, and it is not worth a signature that takes two contexts.
Three rules keep the registry correct:
- Register before submitting, not inside the worker. The registration then precedes the work by construction, so there is no window in which a processor is running that the registry does not know about. It also covers the interval a request spends waiting in the worker pool's buffer, which is precisely the interval that gets long when every worker is busy — the case where a cancel is most valuable. A signal that still arrives before registration is not lost work: nothing has started, and the executor's pre-processing read finds the instance CANCELLING and settles it without ever calling the processor.
- Deregister — and cancel — in the completion callback. The callback already exists and already
performs this exact kind of clean-up for the buffered dispatch message (§7), so the registry entry
is removed beside it, on the same signal, under the same lock discipline. Calling the cancel func
on the way out is not optional even when the instance ended on its own: an uncancelled
context.WithCancelleaks until its parent dies. - Clean up the one path the callback does not cover. When
ProcessExecutionInstancefails to submit, the executor never took the request and will never report completion, so the receiver removes the registry entry itself — exactly as it already removes the recorded dispatch message on that path.
A submit aborted by cancellation is a cancellation, not an engine failure. Because the context governing the submit is the instance's own, a cancel arriving while the request is queued for a busy worker pool aborts the submit. That must not take the existing engine-failure branch: the instance is being cancelled, not failing to be dispatched. The receiver settles a cancelled one CANCELLED (§13.2 — this receiver is the party holding it) rather than marking it FAILED.
The context being done is the gate; the instance's state is the answer. Asking only whether the
context is done is not enough, because Receiver.Stop cancels those same contexts (below) — so a
submit aborted by a shutdown looks identical, and it is a worker dying mid-dispatch, which must stay a
retryable failure. Nor would the mistake announce itself: ACQUIRED → CANCELLED is a legal transition
retained for the timeout path (§13.8), so the write would silently succeed and settle an instance
nobody cancelled. The receiver therefore reads the instance inside the transaction that path already
opens, and only CANCELLING or CANCELLED takes the cancelled branch. The context check stays as the
cheap gate, so the ordinary submit failure costs no extra read.
Shutdown needs one ordering rule of its own. The per-instance context descends from the
receiver's worker context, which makes it a sibling of the executor's rather than a descendant — so
Executor.Stop, which cancels its own worker context and then waits for its workers, does not by
itself signal a running processor. Receiver.Stop therefore cancels every entry in the registry
before stopping its executors, and that cancellation is what tells in-flight processors to wind
up. Order them the other way and every graceful shutdown holding a long-running processor waits out
the executor's stop timeout and reports that it did not stop in time.
The subscriber starts in Start, after Initialize has reconciled (§7.1); a signal published in
that window is recovered by the sweep's re-publish (§6.3). A worker that crashes mid-drain loses its
registry with its process, which is why the reconciliation §7.1 describes settles a CANCELLING
instance on restart rather than waiting for a signal that has nowhere left to land.
Reporting the outcome. Cancellation is a third terminal outcome rather than a kind of failure,
so the executor's completion callback carries it as one — an explicit terminal state alongside the
error, not an error class the receiver has to unwrap. The receiver maps it to
IPC_TASK_ENG_EXECUTE_CANCELLED, and that report is also what releases the original dispatch
message from the queue buffer, so the callback fires on the cancelled path exactly as it does on the
other two.
A drain waits on a worker, and a worker can fail to answer for two reasons that look identical from the scheduler: its processor is ignoring the context, or its process is gone. Neither produces a report. So an unbounded drain is an unbounded CANCELLING task — never terminal, so it cannot be deleted, and every consumer waiting on it waits forever. The workflow engine's reconciliation waits on the task; a BSP branch's drain waits on its vertex tasks. Neither has a bound of its own, which makes this the layer that must supply one.
TaskSchedulerConfig.CancellationGraceIntSecs is that bound. An instance that has sat CANCELLING
longer than the grace is marked CANCELLED by the scheduler, and the task settles behind it. The clock
is the instance's own updated_at, which MarkTaskExecCancelling advances when the drain begins, so
no new column records it — and because processCancelTask has already listed the task's live
instances to partition them (§13.2), the grace is tested on the rows in hand rather than through a
second UpdatedBefore query.
A forced settle is recorded as its own audit event. The task behind it settles with the ordinary
CANCELLED_TASK, so without FORCE_CANCELLED_TASK_EXECUTION a notification subscriber could not tell
a cancel that drained from one the engine stopped waiting for — and the difference matters, per What
it costs below. The event names the task, the instance, and which worker never answered; the same
account is written to the instance's cancellation message, so the row and the broadcast agree.
Setting it. The grace has to exceed the slowest legitimate cooperative shutdown, which is
per-application knowledge and is why it is configured rather than derived from the maintenance
interval: a grace shorter than the work would force-settle healthy drains as a matter of course. An
instance carrying a Deadline shorter than the grace normally settles well before it, on the
deadline path.
What it costs. A force-settled instance may still have a goroutine running behind it, which is precisely the §13.1 limit showing through. That is what makes the "already terminal is benign" rule (§13.7) load-bearing rather than defensive: the late-returning worker will find its instance settled.
Why this is not a workaround. The force-settle invites being read as compensation for §13.1 — a patch over Go's lack of preemption that a better language, or a future runtime, would let us delete.
It is not. Even given a safe primitive for killing a running goroutine, the force-settle would remain, because the scheduler cannot distinguish a hung processor from a dead worker, and a kill primitive only helps in the first case — and only where a process is still alive to receive the instruction.
Preemption would reduce how often the grace expires. It would never remove the need for a bound. The bound is owed to the distance between the scheduler and the worker, not to the language on either end of it: this is the same bounded wait that every cancel crossing a process boundary needs, and it would be in this design if processors ran in Rust.
The cancellation handlers obey §6.2 like every other handler, with one refinement that is easy to get wrong. Guard the write, not the handler.
processTaskExecutionCancelled does two things, and only the first is conditional:
- If the instance is still CANCELLING, mark it CANCELLED.
- Unconditionally, re-read the task's instances and settle the task CANCELLED if none is live.
Guarding the whole handler on "the instance is already CANCELLED, nothing to do" would strand a task whenever a report arrives after a force-settle has already written the instance — the report finds its work done, returns early, and the task's own settle never runs. The second step is therefore idempotent by construction rather than by guard: it asks a question about the task and acts on the answer, which is safe to do any number of times.
That makes step 2 a single helper with three callers, which is what keeps the drain's completion condition from being stated three ways:
| Caller | When |
|---|---|
processTaskExecutionCancelled |
a worker reported a drained instance |
processCancelTask |
a cancel request, including a repeat |
| the maintenance sweep | the report was lost, or a force-settle just landed |
The worker side needs the mirror-image rule: an already-terminal instance is benign. A worker can
reach either of its two write points — pre-processing, or the post-processing defer — and find its
instance already CANCELLED rather than CANCELLING. That is not an error and must not be reported as
one. It is the ordinary result of a force-settle (§13.6), of a duplicate signal, or of a sweep that
reached the instance first, and the correct handling is to write nothing, report nothing new, and
exit.
The one thing it must still do is fire the completion callback, because that callback is also what releases the dispatch message from the receiver's queue buffer (§7). Returning early without it leaks the buffered message and the receiver's record of it — so "do nothing" means write nothing, never finish silently. This is the rule that makes the force-settle safe to have: it guarantees the late-returning worker, which §13.6 says will certainly appear, has a correct path to take.
The sweep needs no new step. §6.3's first step already lists CANCELLING tasks and re-runs
processCancelTask, so making that handler re-mark, re-publish, and re-evaluate gives automatic
redelivery of the signal, force-settle triggering, and drain reconciliation from the step that
already exists. That redelivery is not a nicety: pub/sub drops messages exactly when a receiver is
restarting, which is exactly when nobody was listening.
A repeated cancel request is meaningful, not merely tolerated. A CANCEL_TASK for a task
already CANCELLING writes nothing and re-publishes the signal, so an application that wants to prod
a slow drain may simply ask again. A task already in a terminal state ignores the request entirely.
A timeout settles immediately: processTaskTimeout marks the task TIMED_OUT — terminal — and its
live instances CANCELLED rather than CANCELLING, publishing the signal best-effort on the way out to
stop wasted compute. Instances marked CANCELLING under a task that is already terminal could never
settle anything, so the two paths share the intent and not the mechanism.
The asymmetry is the point rather than an inconsistency:
A cancel is a request to stop, and its requester wants to know when it stopped. A timeout is a declaration that we have stopped waiting.
A drain has nothing to offer the second: the deadline it enforces has already passed, so waiting longer to record what everyone already knows would only make the timeout late. The worker's late report lands on the benign already-terminal path (§13.7) exactly as a force-settled instance's does.