veko
ORO Homoiconic Language • Custom VM • Wasm 3.0 (vvm) • Native x86_64 & arm64

Durable Objects & Durable Workflows Guide

Veko 1.0 includes a zero-dependency Durable Objects (lib/durable/object.vk) and Durable Workflows (lib/durable/workflow.vk) library layered directly over lib/db/kv.vk's CRC-32-verified Write-Ahead Log (WAL). Every state transition, alarm, inbox message, step checkpoint, signal, and saga compensation is committed atomically in db/kv batches and survives process restarts and crashes cleanly.


1. Architecture Over lib/db/kv.vk

DURABLE STATE & WORKFLOWS

Crash-Safe Durable Objects & Replay-Safe Workflows over db/kv

Single-writer transactional actors, memoized step checkpoints, external signals, and LIFO saga compensations.

Interactive SVG • Click any node (5 components)
LIB/DURABLE/OBJECT.VK Transactional Keyed Actors LIB/DURABLE/WORKFLOW.VK Deterministic Checkpoint Replay LIB/DB/KV.VK STORAGE LAYER CRC-32 Append-Only WAL do:<ns>:<id> alarm / inbox keys wf:<run>:step evt / comp keys step-done? + mutate Stateful Actor Durable Object Turn open-object + atomic mutate Actor Timers & Mail Alarms & FIFO Inbox set-alarm + enqueue / drain Replay Engine Memoized Workflow Steps start + step + step-with-retry Coordination & Rollback Signals, Timers & LIFO Sagas wait-event + run-compensations Durable Storage CRC-32 Log-Structured KV pwrite + fsync + compact
Components:
Stateful Actor
Durable Object Turn
lib/durable/object.vk
Component 1 of 5
Architectural Role & Purpose

Encapsulates strongly consistent per-entity state keyed by namespace and object ID.

Contextual Description & System Interaction

Models wallets, tenant quotas, device twins, and shopping carts safely.

Core Functionality & Mechanics
  • dobj/mutate snapshots fields and commits atomically on success
  • Automatically rolls back all in-flight mutations if closure returns err
  • Monotonic version counter tracks every committed state transition
Actor Timers & Mail
Alarms & FIFO Inbox
lib/durable/object.vk
Component 2 of 5
Architectural Role & Purpose

Persists scheduled wakeups and ordered actor messages inside the same WAL store.

Contextual Description & System Interaction

Eliminates external Redis/RabbitMQ dependencies for stateful edge services.

Core Functionality & Mechanics
  • poll-due-alarms discovers objects whose deadline <= now_ms
  • enqueue appends durable messages that survive process restarts
  • drain-inbox processes and acknowledges queued work atomically
Replay Engine
Memoized Workflow Steps
lib/durable/workflow.vk
Component 3 of 5
Architectural Role & Purpose

Executes multi-step business processes that resume from their exact last checkpoint after a crash.

Contextual Description & System Interaction

Turns fragile distributed orchestrations into straight-line Veko code.

Core Functionality & Mechanics
  • Completed steps return cached JSON/VBIN results without re-running side effects
  • step-with-retry records attempt counts and exponential backoff
  • Appends an immutable audit trail retrievable via wf/history
Coordination & Rollback
Signals, Timers & LIFO Sagas
lib/durable/workflow.vk
Component 4 of 5
Architectural Role & Purpose

Suspends workflows cleanly on external webhooks/timers and unwinds failures in reverse order.

Contextual Description & System Interaction

Guarantees clean financial and provisioning rollbacks when downstream steps fail.

Core Functionality & Mechanics
  • wait-event returns .waiting until send-event persists the signal
  • sleep-until suspends execution across restarts without holding threads
  • record-compensation & run-compensations execute LIFO saga undo steps
Durable Storage
CRC-32 Log-Structured KV
lib/db/kv.vk
Component 5 of 5
Architectural Role & Purpose

Persists object fields, alarms, workflow steps, signals, and sagas in one crash-safe file.

Contextual Description & System Interaction

Works identically on VM, Wasm (--allow-fs), and all 4 Native OS/CPU targets.

Core Functionality & Mechanics
  • Every record carries a CRC-32 checksum over key + value bytes
  • Recovery truncates partial tail frames automatically on open
  • put-sealed encrypts sensitive credentials with AES-256-GCM

Both abstractions share one single embedded db/kv file (or separate stores per service) using clean, lexicographically sorted key prefixes:

Key Prefix Owner Stored Payload (codec/vbin)
do/<ns>/<id>/meta durable/object Version counter, timestamps, inbox sequence counter, active alarm deadline
do/<ns>/<id>/kv/<field> durable/object Individual durable state fields
do/<ns>/<id>/inbox/<seq> durable/object Monotonic FIFO mailbox messages (with attempt counters & visibility deadlines)
do_alarm/<ns>/<id> durable/object Indexed durable alarm schedule for O(k) poll-due-alarms
do_dlq/<ns>/<id>/<seq> durable/object Poison-message Dead-Letter Queue (list-dead-letters)
wf/<id>/meta durable/workflow Run status (.running, .waiting, .completed, .failed, .compensated), wake deadlines, worker lease
wf/<id>/step/<name> durable/workflow Memoized step result, retry attempt count, backoff deadline, or durable timer
wf/<id>/event/<name> durable/workflow External signal payload delivered via send-event
wf/<id>/comp/<seq> durable/workflow LIFO saga compensation journal entries
wf/<id>/log/<seq> durable/workflow Chronological execution audit trail
wf_dlq/<id> durable/workflow Dead-Letter Queue entry for exhausted workflows (requeue-dead-letter)

2. Durable Objects (lib/durable/object.vk)

A Durable Object is a named, single-writer, versioned stateful actor ((namespace, id)). All mutations commit atomically alongside the object's version counter.

Transactional Actor Turns (mutate) with Automatic Rollback

VEKO
use [d = durable, dobj = durable/object]

mut db = d/open-store 'state.vkkv'
mut acct = d/object mut db 'account' 'acct-001'
_ = dobj/put-fields mut db mut acct { owner = 'Alice', balance = 500 }

// Atomic turn: succeeds and increments acct.version in one WAL batch
bal = dobj/mutate mut db mut acct fn [st] [
    cur = as-i64 (map/get/or st 'balance' [ 0 ])
    if cur < 120 [ return (err 'insufficient funds') ]
    mut next = st
    map/set mut next 'balance' (cur - 120)
    { state = next, result = (cur - 120) }
]

If the handler returns err, zero keys are written and acct.version stays untouched.

Durable Alarms, Batch Enqueue & Transactional process-inbox with DLQ

Alarms and inbox messages are persisted in the WAL so they survive restarts. Use enqueue-batch for single-fsync multi-message writes, mutate-cas for optimistic compare-and-swap version checks across concurrent handles, and process-inbox (InboxOpts) to commit handler state updates and message deletion in one atomic WAL batch—automatically backing off failed messages and routing poison messages exceeding max_attempts into do_dlq/<ns>/<id>/<seq>:

VEKO
use [d = durable, dobj = durable/object]

_ = dobj/set-alarm mut db mut acct 30s 'billing-reconcile'
_ = dobj/enqueue-batch mut db mut acct [
    { kind = 'credit', payload = 250 }
    { kind = 'debit',  payload = 75 }
]

stats = dobj/process-inbox mut db mut acct (dobj/InboxOpts {
    max_messages = 32
    max_attempts = 3
    base_backoff = 100ms
}) fn [st msg] [
    bal0 = as-i64 (map/get/or st 'balance' [ 0 ])
    delta = if msg.kind == 'credit' [ as-i64 msg.payload ] else [ 0 - (as-i64 msg.payload) ]
    if (bal0 + delta) < 0 [ return (err 'overdraft') ]
    mut next = st
    map/set mut next 'balance' (bal0 + delta)
    next
]

due  = dobj/poll-due-alarms mut db 'account'
dlqs = dobj/list-dead-letters db acct

3. Durable Workflows (lib/durable/workflow.vk)

A Durable Workflow executes multi-step business logic with exact-once step memoization: if the process crashes halfway through a workflow and replays from the top, already-completed steps return their persisted checkpoints from db/kv without re-executing side effects.

Memoized Steps, Retries, Signals, Timers & LIFO Sagas

VEKO
use [d = durable, wf = durable/workflow]

mut db = d/open-store 'workflows.vkkv'
mut run = d/workflow mut db 'ord-77' 'fulfill-order' { sku = 'VEKO-PRO', qty = 2 }

// 1. Memoized step: runs once, replays from db/kv on restart
res_id = wf/step mut db mut run 'reserve-inventory' fn [] [
    'res-901'
]

// 2. Durable retry with backoff & persisted attempt count
quote = wf/step-with-retry mut db mut run 'fetch-quote' 3 100ms fn [attempt] [
    if attempt < 2 [ return (err 'transient carrier timeout') ]
    { carrier = 'fastpost', cents = 1299 }
]

// 3. Suspend waiting for an external webhook signal
sig = wf/wait-event mut db mut run 'payment-confirmed'
if not sig.ready [
    // Workflow is durably parked in .waiting until `wf/send-event` arrives
    return .ok
]

// 4. Durable timer that survives restarts
if not (wf/sleep-until mut db mut run 'cooling-window' 5s) [
    return .ok
]

_ = wf/complete mut db mut run { reservation = res_id, receipt = sig.payload.receipt }

LIFO Saga Compensations, Batch Steps, Worker Leases & Workflow DLQ

Register compensating actions as forward steps succeed. If a downstream step fails permanently, call wf/run-compensations to unwind in strict reverse (LIFO) order:

VEKO
_ = wf/record-compensation mut db mut run 'release-inventory' res_id
_ = wf/record-compensation mut db mut run 'void-payment' auth_id

// On unrecoverable failure:
n = wf/run-compensations mut db mut run fn [comp_name data] [
    println (str/join ['undo ' comp_name ': ' (mold data)] '')
    .ok
]

For high-throughput distributed workers:

  • wf/step-policy & Dead-Letter Queue (wf_dlq/*): Configure wf/RetryPolicy { max_attempts, base_backoff, max_backoff, backoff_factor, dead_letter = true } so non-parked steps persist exponential backoff deadlines (status = .waiting, zero thread blocking!) and move exhausted runs to wf_dlq/<id>. Inspect via wf/list-dead-letters db and replay after fixing an upstream outage via wf/requeue-dead-letter mut db 'ord-77'.
  • wf/step-batch: Executes and checkpoints multiple deterministic sub-steps in a single WAL fsync commit (wf/step-batch mut db mut run [['validate' fn [] [...]] ['enrich' fn [] [...]]]).
  • wf/wait-event-timeout: Parks a workflow awaiting an external webhook signal up to a durable deadline (wf/wait-event-timeout mut db mut run 'approval' 24h), returning { ready = false, timed_out = true } if the deadline elapses first.
  • Distributed Worker Leases (poll-runnable & claim-run): Multiple worker processes poll ready workflows whose sleep/retry timers or signals have matured (wf/poll-runnable db 16) and acquire time-bounded leases (wf/claim-run mut db run_id 'worker-01' 30s) before resuming execution.

Run the end-to-end crash-and-replay demonstration in examples/32_durable_objects_and_workflows.vk:

POWERSHELL
veko run examples/32_durable_objects_and_workflows.vk
veko run --native examples/32_durable_objects_and_workflows.vk