6 Workflow execution
A checkpoint evaluates replay-safe computation while retaining its workflow worker claim, without holding the SQLite transaction. Its validated result and stage advance commit atomically afterward. Cancellation is checked again inside that transaction; a cancelled task cannot commit the computed checkpoint or start the next stage. Transactional application mutations belong in perform with a transactional adapter, not in checkpoint computation.
#:execution task requires client Tasks capability before work is queued. #:execution task-optional explicitly selects task execution when that capability is present and ordinary MRTR workflow execution otherwise. The default remains #:execution mrtr. Both task modes require a workflow descriptor; unknown execution modes fail construction or language expansion.
Task input updates ignore unrecognized response keys. An update containing only unknown keys acknowledges without advancing or restarting the worker. Recognized elicitation responses are validated before the task changes state, so malformed input does not turn a pending task into a failed task.
(workflow (approve [name String]) #:version "1" (checkpoint [greeting String] (string-append "Hello, " name)) (await-input [answer Any] (hasheq 'mode "form" 'message "Continue?" 'requestedSchema (object-schema (hasheq 'approved Boolean)))) (structured-result (hasheq 'greeting greeting 'answer answer)))
(await-input ([name Any name-request] [color Any color-request]))
Each input round receives its own opaque token. Matching retries retain completed work, while a conflicting response to a completed input is rejected. Tokens are bound through storage to the original identity, arguments, operation, executable version, and expiry. Unknown response fields are ignored. Clients echo tokens without interpreting them.
(perform [receipt Integer] #:adapter writer #:policy manual input-expression)
Checkpoint computation, branch selection, branch joins, input-request construction, completion handlers, and completion change-key callbacks retain this claim while running outside SQLite transactions. Task polling and cancellation can proceed while these callbacks block. Cancellation is checked again before their transitions commit; cancelled completion does not record change-outbox entries. Callbacks can run again after process loss before their transition commits, so persistent mutations belong in declared effects. Checkpoint encoders and external-effect result encoders also run outside SQLite. Cancellation prevents a checkpoint from advancing; an external effect that already returned a committed outcome still records that outcome and its change keys after cancellation, without changing the task’s cancelled result. Transactional effect encoders retain the mutation transaction so encoding failure rolls back both mutation and stage completion. Effect-input preparation and its environment decoding run outside SQLite for all three policies. Cancellation is checked before adapter invocation or recording an external intent. An uncertain manual effect rejects retry before input preparation runs again. Applications must keep mutations inside the declared adapter; input preparation can run again after process loss before its effect begins.
Single and grouped input requests are persisted after construction and before input processing continues. Retries reuse this saved request data; they do not re-enter the constructor. Cancellation during construction prevents the request from being saved. Process loss before that save may rerun construction; after the save, the pending request is available even if its response was never delivered.
Observed-outcome recovery codecs run without a SQLite transaction while retaining the exclusive instance claim. Ownership and the pending effect are checked before encoding. The repaired value, recovery journal, and change outbox commit together; encoding failure or a stale revision commits none of them. Recovery cannot be called inside an existing transaction on the same store, because it must own these transaction boundaries.
#:execution task selects Tasks instead of MRTR. Durable serving requires an explicit state-file configuration. make-runtime scans unexpired working tasks and starts recovery workers. Awaiting-input and terminal tasks stay unchanged. Use #:recover-tasks? #f to defer startup and recover-runtime-tasks! to scan explicitly; the latter returns worker thread events. A missing executable is a startup error. Incompatible executable versions fail through the workflow compatibility check before execution. A startup worker that encounters another owner’s live claim skips that claim. If that owner subsequently dies, call recover-runtime-tasks! again or explicitly resume the task. There is no continuous takeover scheduler. Expiry still prevents public access and resumption; a worker stopping at expiry may record a failed terminal state without extending the TTL.
A workflow’s #:key callback also applies to immediate task execution. It runs once per initial invocation, outside SQLite transactions, using validated effective arguments, with absent entries removed and before persistence converts native numbers and objects to their stored representation. Captured workflows compute it under their sealed executable resolver. Task creation rejects a caller-owned transaction before key evaluation, so a returned task handle cannot depend on a subsequent caller commit or rollback. The key is scoped to the principal and workflow operation; reusing it with changed arguments fails. Expired instances and incompatible executable versions are not silently replaced.
Concurrent initial calls with the same key retrieve one task handle and its saved creation response, even after the task completes or fails. A failed task remains failed; repeating the key does not retry an uncertain effect. Synchronous and task execution of a task-optional workflow share the keyed workflow execution. The task receipt is stored separately so attaching a task cannot disrupt an in-flight synchronous stage. Without a key, initial calls still create independent work. This does not retroactively deduplicate immediate tasks created by older builds that did not record their declared keys.
syntax
(task-boundary stage-id)
A task workflow containing a boundary runs its prefix synchronously as durable MRTR. Its input-required results contain no task handle. Reaching the first boundary on the selected branch atomically persists a task and its handoff receipt, then returns the task result without an MRTR state token. Checkpoints and accepted input carry into the task. A branch that completes before reaching a boundary returns its ordinary result; use this to preserve decline or cancellation outcomes.
Repeating an accepted continuation returns the same recorded task handle, including while the task runs and after it finishes. Conflicting input, changed arguments, foreign principals, expiry and incompatible workflow code remain errors. The task inherits the preparation’s expiry. Process restart recovers working tasks through the ordinary runtime scan. No initial invocation is automatically replayed: without a declared workflow key, another initial request creates another preparation.
Without a boundary, task execution retains its immediate-start behavior. With #:execution task-optional and no client Tasks capability, boundaries are passed synchronously and the entire workflow remains MRTR. Subsequent boundaries inside an already-started task do not create nested tasks. A nested local workflow does not inherit the parent’s handoff factory.
examples/prepared-task.rkt demonstrates a name request followed by background work. The ordinary data API uses a workflow-stage of kind ’task-boundary, with Any, a procedure returning json-null, and #f adapter and policy fields. The boundary does not invoke that procedure or save a value. start-workflow-task accepts #:state and #:responses for the preparation’s MRTR retries. Adding Tasks capability to a continuation preserves its existing workflow and accepted responses. It continues MRTR until an explicit task boundary; without a boundary it completes that execution synchronously.
bind-arguments accepts optional #:defaults containing saved effective bindings. Omitted defaulted arguments reuse that map, including saved absence; fresh calls retain left-to-right default evaluation. Rendering records retain these bindings through render-layout’s optional #:bindings. Older rendering records can resume with recoverable bindings or explicit arguments. An omitted default without retained evidence is a compatibility error and is not reevaluated.
Managed tasks resolve embedded resources and input, expand content groups, and produce JSON presentations before checking completion shape, Boolean isError, and the tool’s output schema. The low-level mcp/tasks start, resume, update, and replacement APIs accept #:output-schema. Start defaults to no output contract; omitted values on later calls retain the stored contract, while explicit #f disables that low-level contract. Runtime managed calls supply the declared tool contract. Polling rejects malformed retained completed results without changing or replaying their records.
Records with missing rendering provenance or unverifiable executable identity require explicit recovery outside these APIs. The runtime does not guess old identity metadata or adopt unsupported storage layouts.
#:restore-principal maps the stored principal key to a current application principal. Its default returns the key itself, suitable for string identities. Applications using verified principals supply their identity/policy lookup. Recovery checks identity, expiry, and operation authorization after acquiring the worker claim; no bearer credentials are persisted. A denied recovery fails the task.
SQLite task workers use OS file locks in a sibling .workers directory, together with process-local thread ownership. Keep that directory alongside the database; do not remove lock files while runtimes are active. Workers use one canonical state-file path on one host. Process termination releases the OS lock, and retries retain the workflow’s recorded effect policy and key. This is not a distributed lease protocol. Native lock/restart verification currently covers Linux only. Clients opt into task status notifications with a taskIds string array in subscriptions/listen. The runtime verifies each task’s ownership and read policy before acknowledging the accepted IDs. Committed transitions emit notifications/tasks with the complete detailed task, tagged with the subscription request ID. Notifications are bounded hints: after reconnecting or overflow, poll tasks/get; there is no notification replay. Terminal no-op cancellation does not emit a new transition. The exhaustive failure-boundary matrix remains open.