Takt: Durable, Typed Workflows

Read with Rechain and Reactor, or use the combined reference.

Contents

Takt's role and persisted state

Takt runs business processes whose steps span messages, canisters and time. A purchase might reserve an NFT, collect payment, deliver the NFT and pay its seller. Each step needs a recorded place in the process, a result, and a clear next action if it cannot finish immediately.

You write typed Motoko functions and a workflow graph. Takt saves the execution's progress, schedules eligible work and applies the graph's decisions, waits and recovery policies. The same definition supplies the inspector's graph. The browser displays the machine that executes the workflow; it does not execute a second JavaScript version.

The three libraries have separate ownership:

Machinery Owns Example
Rechain Business state, validated dispatch and recorded business history when enabled A balance, reservation or listing claim
Reactor Shared scheduling and durable batched communication Delivering a payment request and its reply
Takt Workflow execution, saved stage data, attempts, waits and recovery This purchase has paid and is waiting for NFT delivery

One canister shares one Flow.Runtime across its workflows. Each workflow retains its own typed memory. The runtime uses Reactor's scheduler for turns, budgets, timers and physical callback permits. Applications using Rechain attach it to the same scheduler. Takt can also run without Rechain; its local operations then need explicitly owned application state.

An ordinary synchronous update can dispatch directly. A workflow becomes useful when the process must remember where it reached, handle remote outcomes, wait, branch or recover. It does not make a sequence across canisters globally atomic. Each participant still controls its own local state.

This reference follows the current development checkout, reviewed at b7d429108847. Its README describes an unpublished development library; use the checkout's compiler and dependency instructions rather than assuming a released package works with any Motoko toolchain. Sources: project status, execution model.

Execution, visit, attempt and operation identity

These names answer different questions:

Term Meaning
Definition A versioned graph, such as the purchase workflow
Execution One admitted run, with its own execution ID
Node A named graph position, such as CollectPayment
Visit One invocation of that node; returning through a loop creates another visit
Attempt One try at a task during that visit; retries add attempts
Operation identity The identity of an effect that must remain stable across its attempts
Response address Reactor's durable destination for a particular reply; not the participant's transaction identity
Block ID Index of a recorded action within one canister's chain; not the execution ID
Stage Typed saved data, such as Reserved, Paid or Delivered
Progress The complete typed carrier containing the workflow's saved stages

Suppose purchase 232 reaches CollectPayment, gets no conclusive response, then retries. It remains the same execution and visit, using the same payment identity. A new attempt is not permission to make another payment. By contrast, a loop that processes the next distribution recipient enters a new visit and may prepare a distinct effect.

Identities have scope: execution 232 in one canister and workflow namespace is unrelated to execution 232 elsewhere. Takt's key includes namespace, execution, node, visit and definition version. Participant transaction identity additionally follows its own caller/request contract; retries or migration must not silently replace it with a new identity.

Several parallel branches can be active at once. An execution therefore cannot be represented correctly by one global “current node.” Takt saves the individual nodes, their visits, phases and any pending effect identities. Workflow data describes progress; it must not become another writable copy of balances or listing ownership. Read business state through selectors and change it through Rechain dispatch. Sources: accepted terminology, context and operation types.

Authoring a workflow

The graph owns the meaningful business sequence: checks, effects, choices, parallel work, waits, compensation and child scheduling. An actor method authenticates the caller, normalizes and bounds its arguments, then admits immutable input. Put mutable business eligibility checks in graph nodes so their failures have real visits and visible outcomes.

For example, buy admits a request. PrepareOrder then reads the listing through selectors and checks price and availability. An observation before a remote call can become stale; the later reducer dispatch revalidates the conditions it owns.

A typical workflow has these files:

workflows/purchase/
  purchase.takt.json       nodes, links, policies and inspection bindings
  memory/v1.mo            complete saved types, Progress and constructor
  memory/lib.mo           reexports the selected memory version
  PurchaseRules.mo        pure decisions, mappings and display projections
  PurchaseOperations.mo   reads, local effects and remote operations
  .takt/purchase/         generated ports, runner, inspection and source maps

The current shop calls its rules and operations modules PurchaseDomain.mo and PurchaseProtocol.mo. New workflows use the clearer Rules and Operations naming convention. Generated files are checked in for review; edit their inputs rather than generated wiring.

The memory owner defines concrete stages that express prerequisites. A Paid payload carries payment evidence required for delivery; it is stronger than a large record whose payment fields might be absent. JSON names those types and Motoko functions. It contains no embedded business code. This is a partial excerpt of the current purchase's binding pattern:

"Modules": {
  "M": "./memory/lib",
  "D": "./PurchaseDomain",
  "P": "./PurchaseProtocol"
},
"Types": {
  "Data": "M.Mem.Progress",
  "Error": "M.Mem.Error",
  "Memory": "M.Mem.Memory",
  "Operations": "P.Participants"
},
"Progress": {
  "Order": "M.Mem.Order",
  "Reserved": "M.Mem.Reserved",
  "Paid": "M.Mem.Paid"
}

The full workflow includes its other stages and saved-request carrier. The generator checks the JSON schema, graph structure and concrete Motoko connections. A delivery input requiring Paid cannot be connected to an incompatible unpaid output. Generated ports wrap and project typed stages; they do not introduce a second stored schema or runtime string dispatch.

Operations receive explicit dependencies: participant principals, read-only selectors, dispatch functions and the shared Reactor instance. For a Remote task, a typed Call recipe names its endpoint, request builder, reply interpreter and send-error mapping. Reactor recipes save encoded arguments before sending. Native actor-call recipes remain available; arbitrary native calls are not automatically Reactor traffic.

For a Local task, a Dispatch recipe describes one synchronous action submission:

Plan result Meaning
#Dispatch {action; onSuccess} The library dispatches once and maps the successful block ID
#Done(output) An explicit no-op or already completed operation
#Reject(error) A known precondition failure

The plan itself must not dispatch. The action and its result mapping execute synchronously together; the callback is not persisted. Several successive local nodes can yield between nodes, so put a required atomic change in one bounded operation.

Register documents and hosts in generator/projects.json. Follow the current development prerequisites: install its matching experimental compiler, runtime and plugin bundle, and make the sibling Rechain, Reactor and fast dependencies available. helpers/moc.sh selects moc from PATH, with TAKT_MOC and MOTOKO_PLUGINS overrides; the stock Mops-pinned compiler does not supply the required intrinsics. From that prepared Takt checkout:

npm ci
mops install
npm run generate

Generation rebuilds registered workflows; node generator/index.mjs <workflow.takt.json> --host <main.mo> checks one integration. Capabilities describe dependencies, but do not prove arbitrary handler purity or grant authorization. Sources: authoring guide, generator, compiler wrapper, Rechain dispatch adapter.

Node reference

The current JSON language has eleven node kinds. There is no separate Map node in this schema; bounded repeated work can use explicit graph loops.

Kind Purpose and boundary
Local Synchronous host operation. May dispatch business state changes; no awaited call.
Read Nonmutating host or clock observation. Unlike a pure transform, it can observe outside its input.
Remote Interaction with a participant, through a declared transport and explicit safety contract.
Transform Pure transformation of its input into the next stage.
Choice Evaluate ordered typed projections; take the first matching route.
Wait Save a timed deadline and continue when due. Retains its concrete input.
Parallel Start isolated branch paths, collect their outcomes and join typed results.
ScheduleWorkflow Durably schedule a child and bind the directly following event wait.
AwaitEvent Suspend until a correctly addressed, authenticated, typed event arrives. No timed deadline of its own.
Succeed Finish successfully with its input. Tasks can also terminate using End.
Fail Finish with an application error produced from its input.

Read and Transform are distinct typed bindings even though both use the pass interpreter. Local and Remote handlers are also different types. Expected failures return typed values; trapping is not a business rejection mechanism.

Timing configuration is in milliseconds. Absolute Motoko timestamps and transaction metadata use their declared nanosecond units. A Wait persists its absolute deadline: upgrading after five days of a twenty-day wait leaves fifteen days, rather than starting another twenty-day delay. Sources: authoring schema, node contracts, event waits.

Worked Choice and Parallel

The actual account audit demonstrates both constructs. It compares an index's local view with authoritative token and NFT observations:

flowchart LR
  W[WaitUntilAudit] --> C[CaptureIndex]
  C --> P{ReadSources}
  P --> T[ReadToken]
  P --> N[ReadNFT]
  T --> J[Join and Compare]
  N --> J
  J --> Q{Consistent}
  Q -->|matched| M[Matches]
  Q -->|mismatched| S[NeedsIndexing]

Here is its Parallel node, with only the display label omitted:

"ReadSources": {
  "Type": "Parallel",
  "Input": "Gathered",
  "Branches": [
    {"StartAt": "ReadToken", "Result": "TokenObservation", "Merge": "R.mergeToken"},
    {"StartAt": "ReadNFT", "Result": "NftObservation", "Merge": "R.mergeNft"}
  ],
  "Next": "Compare"
}

Both remote branches may be outstanding together. Each has its own visits, attempts and typed terminal result. A completed sibling stays completed while another branch retries or waits. Branch paths cannot jump into a sibling or the parent's continuation. The join waits for all branch outcomes; on success it merges results in declaration order. A failed branch cannot cancel or undo another branch's already sent effect. This audit only reads, but the distinction matters when composing mutations.

The next Choice routes the report:

"Consistent": {
  "Type": "Choice",
  "Input": "Report",
  "Routes": [
    {"Select": "R.matched", "Next": "Matches"},
    {"Select": "R.mismatched", "Next": "NeedsIndexing"}
  ]
}

Each projection has the form Input -> ?DestinationInput. Returning null declines a route; returning a value selects it and provides the destination payload. Ordering matters when conditions overlap. Include a route covering remaining inputs: compiler checks prove payload compatibility, not exhaustiveness of arbitrary Motoko predicates.

Both audit endings are successful reports. A mismatch is useful information, not automatically an engine failure. These are independently timed observations, so the audit does not promise a distributed snapshot and does not update the index. Sources: actual audit graph, audit explanation, join implementation.

Remote effects, retries and reconciliation

A missing reply tells us about communication, not necessarily about the participant's state. The participant may have committed payment before its reply became unavailable. Takt therefore keeps outcome certainty separate from retry policy.

Evidence What the workflow can conclude
Confirmed success Continue with the returned evidence
Confirmed rejection Follow the declared failure path
Timeout or interrupted/unavailable response The effect may be unknown; do not infer rejection
Authoritative reconciliation Settle the original uncertainty using authenticated evidence

A Remote operation declares its safety contract:

Contract Application promise Engine consequence
ReadOnly Repeating the operation cannot cause a business mutation An unknown result can retry under policy; exhausted reads can fail without an unresolved mutation obligation
Idempotent The participant safely recognizes the same effect throughout the declared replay window Unknown outcomes may retry the original request within policy and SafeUntil; unresolved mutations block when safe retries end
Reconcile An uncertain mutation needs authoritative evidence before repeating Unknown outcomes cannot retry automatically or through manual retry until reconciled

These are participant promises, not properties conferred by a function signature. A still-pending Reactor response address prevents replacement sends under every contract. For value-changing Rechain participants, prepare and save the exact destination, arguments, caller, memo, creation time and expiry before the first send. Every permitted retry keeps that identity and request unchanged.

Rechain idempotency checks retained success before new business validation. The participant normalizes a duplicate into the original successful block ID without making another change. The token/NFT examples retain their success index for twenty-four hours from the saved creation time. This finite application protocol is not a universal exactly-once guarantee from Takt or Reactor.

Takt's retry rules are ordered. The first matching rule owns its budget; retry is considered before catch, and node-level Retry replaces inherited rules, including an empty list. In generated typed graphs, When predicates classify application errors; unknown outcomes and timeouts match a retry rule without invoking that predicate. Use Retry: [] to disable retries. Catches handle confirmed application failures. A Recovery: true edge labels the graph; it does not prove that an earlier effect failed.

The engine's logical TimeoutMillis differs from transport timing. Native call recipes use CallTimeoutMillis for the actual call timeout, through Calls.seconds(context); the logical deadline does not cancel the physical handler. That handler occupies its physical slot until it exits. Reactor recipes reject per-node CallTimeoutMillis: shared Reactor settings govern batch exchanges. Their saved response address remains unresolved after logical timeout. A late authoritative reply can resume the original visit, while manual retry is refused until the address resolves. See Reactor recovery and the native timeout helper.

The library default task policy has a thirty-second logical timeout and no automatic retries. Applications choose policies appropriate to their participants. The shop chooses eight transient retries with capped backoff, then blocks, and places its saved replay deadline one minute inside the participant's twenty-four-hour window. SafeUntil is checked when work actually runs, including delayed first attempts and authorized manual recovery. Scheduling before expiry does not permit execution after it.

Uncertain mutations remain protected after retry exhaustion or expiry. A TooOld response is not evidence that payment never happened. Do not refresh timestamps, issue a replacement payment or refund on that basis. Reconciliation may use a permanent participant block or another authoritative protocol result. #Resolved(#Ok(...)) and #Resolved(#Err(...)) explicitly assert such evidence; host-side resolve must authenticate it. Accepted resolution fences older callbacks, but cannot cancel transports already in motion.

Different expiry results carry different evidence. Reactor's #Expired means this envelope was refused for execution; the Takt adapter treats it as unknown because an earlier attempt may have succeeded. A participant's #TransactionExpired can establish rejection within its retained-success contract: duplicate-success lookup occurs before the participant checks admission expiry. After the success-index window, #TooOld provides no such proof. The adapter must preserve this distinction.

Compensation is another operation with its own possible failures. A refund that is blocked has not completed. After confirmed NFT delivery, the shop still owes seller payout; it cannot treat the delivered NFT as rolled back. Sources: safety guide, reply and policy types, Reactor recipe, participant evidence adapter.

Events and child workflows

An event wait suspends work without polling another canister's chain. A parent can start a remote child, then resume from a business fact that the child commits.

The graph declares ScheduleWorkflow → AwaitEvent → .... The child declares a Receive binding. Generation produces an interface-only child client and receiver; the host binds them to ReactorCoordination on the shared Reactor.

The sequence is:

  1. The parent's scheduling node durably saves the child request and its exact successor event address.
  2. The generated receiver authenticates the request and installs the subscription before admitting the child, so even an immediate commit can be observed.
  3. The child executes. A successful Rechain commit invokes its synchronous listener, which queues a publication.
  4. Reactor delivers the addressed event. Takt verifies the expected producer and exact workflow version, execution, node and visit, then advances the typed wait synchronously.

Scheduling success means the request was saved. The matching event establishes the topic's specified committed fact; it does not necessarily mean the entire child workflow terminated successfully. A storage acknowledgement proves only storage. An early event whose visit is still Ready remains retained until the wait can consume it. Loops and parallel waits have distinct addresses.

Topics use a chain ID and exact key bytes. One-shot subscriptions receive the next matching publication; a subscription added later cannot consume an earlier publication. Failed child admission removes its subscription: busy admission retries later without executing the effect. Do not implement separate host launch caches, public callback routes or child retry loops around the graph.

Reactor retains committed notifications and retries delivery indefinitely, preserving bytes and sequence. That transport policy does not extend a financial effect's replay deadline. Authenticate trusted peers and distinguish the sending canister from its propagated original caller. Sources: messaging contract, working two-canister example, Reactor events.

Worked marketplace

The real examples/fourcans/shop coordinates a shop, token ledger and NFT ledger. It is separate from the synthetic throughput workload under examples/reactor/fourcans.

To list, the seller approves the shop's default account on the NFT ledger. list returns a temporary request ID. The graph checks offer availability and price, asks the NFT participant for ownership and allowance through Reactor, then dispatches #List. A listing ID is its creation block ID. An active listing is not itself an NFT reservation: ownership or approval can change before purchase.

The buyer approves the shop on the token ledger, then calls buy. The purchase follows this sequence:

Node Work and evidence
PrepareOrder Read the offer and check price/claim; save an execution-owned order
ReserveNFT Reserve the NFT for this shop and buyer
CollectPayment transferFrom buyer funds into a distinct escrow subaccount on the token ledger, controlled by the shop
ClaimOffer Dispatch a local claim, rechecking price and availability after confirmed payment
DeliverNFT transferFrom the NFT to the buyer
PreparePayout Prepare the seller transfer with its own saved identity
PaySeller Transfer from escrow to the seller
RecordSale Dispatch the sale, recording payment, delivery and payout block IDs and clearing its claim

The example reservation lasts one minute. New payment admission stops ten seconds before that deadline. These are shop policies, not universal Takt constants. Before payment confirmation, the seller may still cancel or change the offer. If the claim fails after confirmed payment, the workflow refunds the buyer.

Definite payment failure releases the reservation. Definite claim or delivery failure refunds the buyer before cleanup. InspectOffer → KeepOrDelist decides whether the offer remains usable; missing ownership or unusable approval can lead to delisting. A pending approval revocation preserves an active reservation's rights until it clears or expires. Unknown payment or delivery never authorizes refund. Confirmed delivery creates an ongoing payout obligation.

Inside this sequence the machines keep their distinct roles. Takt saves the next required step. Reactor batches participant requests with other work. Each participant synchronously dispatches through its own Rechain, commits its state and produces a block ID. The response advances the shop's saved stage; the final shop dispatch records the accepted sale. No coordinator writes another canister's reducer memory, and no cross-canister atomic transaction is implied.

sequenceDiagram
  participant W as Shop Takt
  participant S as Shop Reactor
  participant L as Token Reactor + Rechain
  W->>S: Saved CollectPayment request
  S->>L: Batch containing transferFrom
  L-->>S: Storage ACK only
  Note over L: Dispatch, escrow balance change, block ID
  L->>S: Addressed payment result
  S-->>L: Storage ACK only
  S->>W: Original address is ready
  Note over W: Save Paid stage, then ClaimOffer

Multiple shop or asset canisters can use this composition, but this example does not implement arbitrary account sharding or automatic shard routing. A sharded deployment must define participant selection, authority, effect identities and settlement ownership explicitly. The source account-index example also does not automatically receive ledger records yet. Sources: shop behavior, purchase graph, purchase operations, index limitations.

Inspector: graph, timeline and instructions

The host exposes one authorized, read-only takt_inspect query. Its generated router provides the catalog, exact definitions, execution pages, snapshots, typed business status, history and retained migration revisions. It exports selected business fields, not arbitrary persisted payloads. A separate authorized update handles actions such as resuming blocked work.

The graph shows real definition links and current execution state. Select a node to inspect its visits, branch, operation identity, attempts, deadlines, certainty and application details. Loops produce multiple visits; retries produce multiple attempts. A timeout is shown as uncertain or blocked rather than a fabricated rejection.

Tracing is off by default. Saved execution.current remains available for current phases, attempt counts, uncertainty, deadlines and branches. Historical visits and measurements require tracing. Turning it on midway creates a partial session; turning it off releases that history. Session IDs keep pages from different sessions separate. An absent historic node does not prove it never ran.

The two performance views answer different questions:

View What it shows How to read it
Timeline Recorded elapsed spans, attempts, waits, overlaps and engine-entry boundaries Waiting contributes time, not continuous CPU work; explicit breaks shorten long unrecorded gaps
Instructions Cumulative recorded instruction cost across visits and retries Compare work, with caller and optional participant scopes kept distinct; it is not a wall-clock timeline

Local measurements include the synchronous handler and its dispatch. Reactor operation measurements describe the adapter's local work and elapsed request/response span; shared batching and participant work are separate. Native remote samples may have more limited measurement scopes, which the inspector labels. Participant reports are optional, unverified telemetry; they do not establish transaction outcomes.

Node-card summaries show peak retained measurements, whereas the Instructions view accumulates recorded costs. Missing or pruned measurements are not zero, and two peak values need not come from the same attempt. IC time is fixed within a message, so a synchronous handler can report zero elapsed milliseconds while still doing substantial measured work. Sources: inspector behavior and views, inspection contract, tracing controls.

Capacity, retention and upgrades

Persistent does not mean unbounded. Admission checks counts and payload sizes before starting new work. Current development defaults include 64 active executions per typed workflow and 256 across the shared runtime, with ten logical calls and forty physical handlers across that runtime. Hosts must configure and monitor limits appropriate to their participants; these numbers are not a production capacity estimate.

Completed results default to one-hour retention, subject to an earlier result-count limit. Trace history has bounded events, completed visits and retained attempts. Active or blocked work remains protected and occupies capacity. Never free room by evicting live escrow, reservations or unresolved effects.

Oversized admission returns PayloadTooLarge. An oversized step output or error blocks with StorageLimit, retaining the original bounded input and operation identity. It cannot turn into permission to compensate or repeat an effect. Manual retry cannot bypass that boundary. Permanent business evidence remains in recorded Rechain history; temporary workflow progress has its own lifecycle. The shop's archives are disabled, so its recorded evidence remains local in this example.

These versions are independent:

Version What changes
Workflow definition Graph, policies and compiled business behavior
Workflow memory Concrete persisted input, stages, errors and carrier
Takt library memory Generic engine and coordination storage
Reactor reader capability Whether installed peer code can understand a retained wire payload

Each memory owner defines its complete schema in memory/vN.mo; memory/lib.mo selects the current version. Public actor schemas and Reactor wire types are separately owned contracts. Changing a memory alias does not migrate data, and changing a transport does not convert unresolved requests.

Upgrades reconstruct transient runners, handlers, watchers and scheduler registrations around saved memory. Bind live engine memory once per actor lifetime. Preserve original requests, identities and absolute deadlines. A workflow-definition migration uses an explicit typed plan, validates the whole batch before installation and cannot extend the saved safe replay window. Live physical handlers must drain first. Unresolved Reactor response addresses and externally addressed event waits keep their original definition until resolved.

Retain an old runner while unresolved work requires it. After a deployed transition is complete, retire obsolete installers and cleared roots rather than reconstructing every historical migration at startup. This checkout is still developing its first layouts; several earlier development layouts require a fresh installation rather than a supported migration. Never equate a fresh install with recovery of existing obligations. Sources: storage policy, migration constraints, fleet message compatibility.

Implementation and testing checklist

  1. Define business state ownership and the invariant each reducer enforces. Pass selectors and dispatch into workflows, never mutable reducer memory.
  2. Draw the full graph, including rejection, uncertain outcomes, waits and compensation. Keep ordinary business sequences out of wrappers and adapters.
  3. Define concrete stages and source-owned memory, actor and wire contracts. Generate and compile actual connections against the host.
  4. Specify participant safety, exact request identity, finite retries, safe deadlines and authoritative reconciliation before enabling remote mutations.
  5. Authorize peer transport, child admission, inspection and recovery independently. A propagated caller field alone grants no authority.
  6. Configure admission, payload, result and history limits. Rebuild deadlines and transient registrations after upgrades.
  7. Test public workflows under duplicate delivery, late replies, unknown outcomes, exhausted retries, full capacity and upgrades. Verify exact request reuse and real parallel overlap.
  8. Inspect the resulting graph and current state, then enable tracing when timeline or instruction history is needed. Keep synthetic UI fixtures distinct from captured executions.

The repository supplies generator/compiler tests, PocketIC integration tests, storage and recovery tests, and inspector tests. Its documented commands include npm run generate, npm run check:conventions, npm test and npm run test:web. Convention checks enforce structural boundaries; they do not prove handler purity or participant idempotency. Test those behaviors directly. Sources: required change procedure, test commands.

Sources

This lesson describes the checked-out development implementation, with example policies identified where used. Read it alongside Rechain for local business commits and permanent evidence, and Reactor for delivery and scheduling guarantees.

Topic Primary source
Terminology, composition and authoring rules guide.md, convention.md
JSON language and generated artifacts schema, generator guide
Execution, joining, retry and resolution Engine.mo, Types.mo
Exact requests and participant evidence Reactor adapter, Rechain adapter
Events and child scheduling messaging.md, events example
Actual listing and purchase shop, purchase graph
Parallel and Choice audit graph
Inspection and measurement scopes web inspector, Inspection.mo
Capacity and persistence storage.md, memory contract
Behavioral evidence resolution races, Reactor recipes, storage bounds, purchase upgrades, event delivery