Durable execution
Execution keys, settle from any process, accounting for unsettled work, and what every operation does when a durable runtime runs it twice.
Code blocks on this page are excerpts of tested programs; each block's title names its file in examples/, where the complete program runs.
Durable runtimes (DBOS, Temporal, LangGraph with a checkpointer) run each step at least once and may recover a step in another process. The gate never assumes one run is one process: everything a step needs to finish lives in the store, reachable by a key.
The example below runs three "processes" (three gates on one SQLite file, sharing one clock) through one invoice.
# At most two invoices a day. The limit is counted when an invoice actually goes out, so a step that runs twice
# (a crash and a retry) must not count twice.
rules:
invoices: { allow: send_invoice }
daily-invoices:
deny: send_invoice
limit: { max: 2, per: 24h }
reason: At most two invoices a day
def process_start() -> hitl.Gate:
"""One process: a fresh gate on the shared SQLite file, with receipts in the same file."""
# redact_key="store" keeps a development redaction key in the store; production sets VIEWPORT_REDACT_KEY.
return hitl.Gate(POLICY, store=hitl.sqlite(DB), receipts=True, clock=clock, redact_key="store")
invoice = {"tool": "send_invoice", "args": {"invoice_id": "INV-7"}, "call_id": "call_1"}
key = "workflow-42:step-3" # your runtime's stable step identity/** One process: a fresh gate on the shared SQLite file, with receipts in the same file. */
// redactKey "store" keeps a development redaction key in the store; production sets VIEWPORT_REDACT_KEY.
const processStart = () => new Gate(POLICY, { store: sqlite(DB), receipts: true, clock, redactKey: "store" });
const invoice = { tool: "send_invoice", args: { invoice_id: "INV-7" }, call_id: "call_1" };
const key = "workflow-42:step-3"; // your runtime's stable step identityExecution keys
authorize(action, execution_key=k) / authorize(action, { executionKey: k }) (also on redeem) records an
execution under k when it consumes: the action digest, the limit reservations it made, and whether it has been
settled. Use your runtime's stable step identity (workflow_id:step_id) as the key.
first = await process_start().authorize(invoice, execution_key=key)
print(f"first process: {first.status} under {first.execution_key}")
# first process: allowed under workflow-42:step-3
# ...the process dies here, before the invoice goes out.const first = await processStart().authorize(invoice, { executionKey: key });
console.log(`first process: ${first.status} under ${first.executionKey}`); // first process: allowed under workflow-42:step-3
// ...the process dies here, before the invoice goes out.The step runs again in another process. The same key and the same action return the same granted Authorization
(consumed: true): nothing is reserved twice and the single-use check does not refuse it.
second = await process_start().authorize(invoice, execution_key=key) # the step runs again
print(f"second process: {second.status}, re-entered: {second.consumed}")
# second process: allowed, re-entered: True
sent.append("INV-7") # the effect happens
# ...and this process dies before it can settle.const second = await processStart().authorize(invoice, { executionKey: key }); // the step runs again
console.log(`second process: ${second.status}, re-entered: ${second.consumed}`); // second process: allowed, re-entered: true
sent.push("INV-7"); // the effect happens
// ...and this process dies before it can settle.The same key with a different action is refused, so a key always names exactly one action:
# The same key with different args is refused: a key names exactly one action.
other = await process_start().authorize({**invoice, "args": {"invoice_id": "INV-8"}}, execution_key=key)
print(f"same key, other args: {other.status} ({other.code})")
# same key, other args: denied (hitl.execution_key_mismatch)// The same key with different args is refused: a key names exactly one action.
const other = await processStart().authorize({ ...invoice, args: { invoice_id: "INV-8" } }, { executionKey: key });
console.log(`same key, other args: ${other.status} (${other.code})`); // same key, other args: denied (hitl.execution_key_mismatch)Only a key you pass is re-entrant. Without one, the gate generates a key, and adapters derive
<adapter>:<scope>:<call_id>:<action_digest> from ids the client controls, so a derived key is leased: while
its holder runs (executionLease, default 5 minutes on the gate's clock) another consume of the same call is refused
with hitl.execution_in_progress (retryable), and after the lease the next consume takes it over exactly once. A
replay after it settled is refused (hitl.already_used). Durable hosts pass an explicit execution key; adapters'
derived keys are crash-safe only after the lease. Execution keys are tenant-scoped: two tenants may use the same
key without colliding, and settle, consume and execution take the plain key with the tenant.
While a granted effect runs, its holder renews the lease every third of executionLease (gate.wrap and every
adapter wrapper do this; host code calls authorization.keepAlive() or renew()), so a long effect is never taken
over. Settling a derived key is bound to its holder: after a takeover, the old holder's settle is refused with
hitl.execution_lost and the new holder's outcome stands. So for a derived key, settle through the Authorization
the gate returned (succeeded() / failed(), which carry its owner); gate.settle(key) alone is refused. Keys you
pass yourself are settled by key, from any process. sweep() re-checks the lease when it writes, so a takeover
between its scan and its write is never recorded unsettled. Authorization.execution_key / executionKey is the key in use: effects that can
run twice across a crash should key their own idempotency on it.
Consume by approval id
A gateway that verifies and runs the action later, in another request or process, has the approval id, not the
original call. gate.consume(approval_id, execution_key="msg-1", tenant="t1") /
gate.consume(approvalId, { executionKey: "msg-1", tenant: "t1" }) loads the approval (another tenant's id is
hitl.not_found), requires it to be approved, re-evaluates the current policy with fresh facts on the approved args
(the edited ones, if edited), reserves limits and records the execution under the key. It is re-entrant like any
consume: the same key and approval return the same grant, another key on a consumed approval is hitl.already_used.
When the stored args were redacted, pass args (they must digest to the approved ones; otherwise
hitl.args_required).
Bound keys. To allow exactly one execution key, bind it when the request is created:
authorize(..., bind_execution_key="th:c1") / bindExecutionKey, or execution_key="call_id" / executionKey: "call_id" to derive the key from the action's call id and bind the approval to it. The derived key is
callid:<tenant>:<adapter>:<scope>:<call_id> (- for an absent part); call ids come from the client, so like other
derived keys it is leased (a second consume while the first holds it is hitl.execution_in_progress), not
re-entrant. A consume with any other key, or
without one, is refused with hitl.execution_key_mismatch.
Reading an execution. A settled key is never granted again (hitl.already_used). To answer a retry or a
reconcile the same way after settle, read the record: gate.execution(key, tenant=) / gate.execution(key, { tenant }) returns it (with approval_id, settled_at and the outcome), or none for an unknown key or another
tenant's.
Settle
gate.settle(k, ok=True) / gate.settle(k, { ok: true }) commits the reservations (or releases them when
ok=False), appends invariant history and writes the executed receipt, exactly once, from any process that
shares the store. It returns the execution and changed, false when it was already settled. An unknown key raises
hitl.unknown_execution. Authorization.succeeded() and failed() call it for you.
third = process_start()
settled = await third.settle(key, ok=True) # from any process that shares the store
again = await third.settle(key, ok=True) # a retried settle is a no-op
print(f"settled: {settled.changed}, settled again: {again.changed}") # settled: True, settled again: Falseconst third = processStart();
const settled = await third.settle(key, { ok: true }); // from any process that shares the store
const again = await third.settle(key, { ok: true }); // a retried settle is a no-op
console.log(`settled: ${settled.changed}, settled again: ${again.changed}`); // settled: true, settled again: falseUnsettled work
An execution nobody settles may still have run, so its limit usage never expires while it is unsettled. After
reservation_ttl (15 minutes by default), and once its lease has lapsed too (a holder that keeps renewing is still
running), sweep() commits its reservations (fail closed: the usage counts) and
records executed with ok: false, error_type: "hitl.unsettled". A late settle(ok) is a no-op after that.
# A second invoice is consumed and its process vanishes for good: nobody ever settles it.
orphan = await process_start().authorize(
{"tool": "send_invoice", "args": {"invoice_id": "INV-9"}, "call_id": "call_2"},
execution_key="workflow-43:step-1",
)
clock.advance(16 * 60_000) # past the 15 minute reservation TTL
swept = await process_start().sweep() # counts it (it may have run) and records executed with hitl.unsettled// A second invoice is consumed and its process vanishes for good: nobody ever settles it.
const orphan = await processStart().authorize(
{ tool: "send_invoice", args: { invoice_id: "INV-9" }, call_id: "call_2" },
{ executionKey: "workflow-43:step-1" },
);
clock.advance(16 * 60_000); // past the 15 minute reservation TTL
const swept = await processStart().sweep(); // counts it (it may have run) and records executed with hitl.unsettledThe example then checks the accounting: the invoice that ran twice counted once against the daily limit, the orphan
still counts (it may have run), and there is exactly one executed receipt per execution.
What a repeat does
| Operation | Runs twice | Made safe by |
|---|---|---|
authorize (evaluate, create the approval, deliver) | Same approval; deliveries recorded and not repeated | Idempotency key: caller key or adapter:scope:call_id, plus the action digest |
authorize(consume=True) / redeem | With your execution_key: the same granted Authorization, no second reservation. With a derived key: hitl.execution_in_progress until the lease ends, then one takeover | execution_key (host) or the lease (derived) |
settle | No-op after the first | execution_key |
respond | duplicate, never a second transition | Review id (Slack action id, webhook-id, link token id) |
cancel | Returns the terminal approval | Approval id and compare-and-set on version |
sweep | Changes nothing twice | Compare-and-set on approvals and executions |
| Channel delivery | Skipped when already recorded for that channel | Approval id and channel name |
on_decided hooks | Retried with backoff on the gate's clock (hook_retry / hookRetry, default 5 attempts); then hitl.hook_failed | Approval id: hooks must be idempotent, and the shipped resumers are |
| Receipt append | A retry after a lost acknowledgement finds the landed entry | Receipt id |
| Approval events | Deduplicated per adapter, scope, tool, call id and status in one process | Event id |
Hook retries live in the process: a crash between a decision and its hook loses the retry in this release. Hosts that
need more call sweep() and resume from pending() or get(). Wait for in-flight retries before shutting down with
await gate.idle() (both languages; gate.sync.idle(timeout) from sync Python code).
Deterministic ids
ids= takes core's IdGenerator. Seed it from your execution identity so approvals, receipts and events created on
a retried step get the same ids.
Testing your setup
durable_contract(make_gate, make_store=...) in viewportai.hitl.testing and
durableContract(name, makeGate, { makeStore }) in @viewportai/hitl/vitest inject crashes before, between and
after consume, effect and settle (a fresh gate on the same store models a new process) and assert: the effect is
granted on recovery, reservations are committed exactly once, exactly one executed receipt, nothing leaks after
sweep(). Run it against your store and your gate factory.