Expressions and Control Flow
LatticeFlow v2 executes data interpolation, conditional routing, bounded iteration, and human-in-the-loop (HITL) suspension without eval() or new Function(). Every template path is statically checked by nodes/triggers.js and validator.js, while branch state, nested loop cursors, and approval checkpoints persist in PostgreSQL so runs survive server restarts and resume atomically.
Template Expression Syntax ({{path}})
Before any rule is saved or run, scanTemplateString (validator.js) inspects all strings and objects in the graph. A valid expression must match TEMPLATE_EXPR_RE = /^[a-zA-Z0-9_.\-$]+$/ (supporting dot-separated keys and zero-based array indices such as steps.q_1.items.0.code).
Runtime Interpolation Rules (interpolateTemplate)
When a configuration string consists solely of a single expression (such as "{{steps.q_1.items}}"), resolveExpr returns the resolved value in its native JavaScript type (array, object, number, or boolean) rather than coercing it to text; unresolved paths return "". When expressions are embedded inside surrounding text (such as "Lot {{data.lotCode}} at {{data.mktCelsius}}C"), null and undefined render as "" while objects and arrays serialize via JSON.stringify.
resolveExpr checks getSafePath(ctx, expr) against the root execution context first and falls back to getSafePath(ctx.data, expr). Both {{lotCode}} and {{data.lotCode}} therefore resolve whenever lotCode is present on data.
Rejected Syntax (UNSAFE_TEMPLATE_EXPRESSION)
| Rejected Pattern | Reason |
|---|---|
${data.id} | JavaScript or shell-style ${...} interpolation is blocked. |
{{a.{{b}}}} or unmatched {{ / }} | Nested or unbalanced braces fail static validation. |
{{}} or {{data.a + 1}} | Empty expressions and inline arithmetic/code expressions are forbidden. |
__proto__, constructor, prototype | Blocked both as JSON object keys and as segments inside {{path}}. |
Runtime Context Root Variables
buildExecState (executor.js) and buildEvalContext (triggers.js) expose the following root keys to all {{path}} expressions and filter evaluators during a run:
| Parameter | Type | Default | Description |
|---|---|---|---|
event | object | — | Normalized CloudEvent envelope: id, type, source, subject, time, organizationId, correlationid, causationid, depth, data. |
data | object | — | Event payload object (derived from event.data or input.data). |
input | any | — | Output payload forwarded directly by the upstream predecessor (or { branches } on control.merge). |
record | object | null | — | Sanitized ORM record for trigger.record runs, or null otherwise. |
dmn | object | — | Flattened output columns from the most recent logic.dmn node (for example {{dmn.approvalTier}}). |
dmnResult | object | null | — | Metadata from the latest DMN evaluation: { tableKey, matched, hitPolicy, outputs }. |
steps | object | — | Keyed by nodeId (steps.<nodeId>) and stepIndex (steps.<stepIndex>), merging output fields alongside output, status, and error. |
nodes | object | — | Full node state records keyed by nodeId: { output, status, error? }. |
loop | object | null | — | Active iteration context inside control.loop: { item, index, count }. |
actor | object | null | — | User or service actor that triggered or resumed the run (id, username, role). |
organizationId | string | — | Tenant identifier enforced for the run. |
resumeDecision | string | null | — | Branch port selected during resumeRun (approved, rejected, or main). |
resumePayload | object | null | — | Optional JSON payload supplied to POST /api/dxosAutomations:resumeRun. |
{
"incidentId": "{{steps.create_incident.id}}",
"lotCode": "{{data.lotCode}}",
"approvalTier": "{{dmn.approvalTier}}",
"currentItemSku": "{{loop.item.sku}}",
"itemPosition": "{{loop.index}}",
"reviewerNote": "{{resumePayload.note}}"
}Structured Filters, Branching, and Merging
Filter Syntax in control.if and filterJson
matchesFilter (nodes/control.js) evaluates structured JSON predicates validated statically by validateFilterStructure:
| Form | Example Syntax | Scope |
|---|---|---|
| Explicit object | {"field": "data.amount", "op": "gt", "value": 50000000} | Single target path and explicit operator |
Operator map ($op) | {"dmn.approvalTier": {"$in": ["quality_hold_director", "vp_ops"]}} | Direct path-keyed constraints |
| Nested combinators | {"$and": [{"data.mktCelsius": {"$gte": 8}}, {"$not": {"data.lotStatus": "expired"}}]} | $and/and/all/rules, $or/or/any, $not |
Supported comparison operators in matchOperatorObject are eq (==, ===), ne (neq, !=), gt, gte, lt, lte, in, nin, exists, and contains (substring check on strings, element membership on arrays).
control.switch and control.merge Modes
control.switch resolves expression and evaluates cases sequentially. The first matching case (via case.condition or operator/equals) routes execution to case.port (case_0, case_1, ...); otherwise execution follows default.
When combining control.parallel fan-out branches at a control.merge node, mode governs both initial traversal and suspended-run recovery:
| Behavior | wait_all (default) | first_completed |
|---|---|---|
| Activation rule | Waits until every non-skipped predecessor pushes into activeInputs. | Runs as soon as the first incoming branch arrives (activeInputs.length > 0). |
| Missing branch handling | Marks the merge node skipped (MERGE_WAIT_ALL_INCOMPLETE) if any active predecessor fails to deliver input. | Ignores slower or skipped branches after firing. |
| Merged output shape | Merges branch objects with Object.assign. | Returns the output of the first completed branch. |
| Resume semantics | Continues waiting for incomplete branches after resumeRun. | collectPreSettledNodes marks an already-completed first_completed merge and its completed descendants as preSettled, preventing duplicate downstream execution when a slower branch later resumes. |
Durable Iteration and loopCursor / loopCursors Stack
control.loop iterates over up to MAX_LOOP_CAP = 100 items resolved from itemsPath (setting strictLimit: true throws FLOW_LOOP_LIMIT_EXCEEDED instead of truncating arrays longer than maxIterations). In loop-resume.js, executeLoopBody extracts the loop body subgraph from the item port (collectSubgraph) and marks those nodes as loopOwned so outer traverseDag does not run them prematurely.
When any node inside a loop body suspends (control.approval, control.delay, or ai.agent awaiting HITL), the engine checkpoints the full loop stack:
- Checkpoint on suspension (
persistSuspendedLoop): Serializes the current frame{ loopNodeId, items, currentIndex, loopResults, loopOutput, iterTraceStart, bodyNodeIds }. For nested loops,[...childStack, cursor, ...rawRest]forms an innermost-to-outermost stack stored in bothnodeStatesJson.loopCursor = loopStack[0]andnodeStatesJson.loopCursors = loopStack. - Stack unwinding on resume (
resumeLoopStack): WhenresumeRunruns, the engine iteratesk = 0 .. rawStack.length - 1:- Restores
execState.loop = { item: items[curIdx], index: curIdx, count: items.length }. - Computes the remaining body subgraph (
remTopo) usingdoneInIter(nodes already completed sinceiterTraceStart) and finishes the interrupted iterationcurIdx. - Continues through
curIdx + 1 .. items.length - 1. If another suspension occurs inside any iteration,loopCursorsupdates in place while preserving accumulatedloopResults. - Once all stacked loops complete, deletes
nodeStatesJson.loopCursorandnodeStatesJson.loopCursors, markscontrol.loopcompleted, and forwardsresultsout thedoneport.
- Restores
Delays, HITL Approvals, and Atomic Resume
/api/dxosAutomations:resumeRunAtomic Claim and Approval Authority (durable-store.js)
When finalizeDagRun handles a suspend signal (control.delay, control.approval, or mutating ai.agent tool), generateResumeToken creates a 24-byte random hex token and stores only its SHA-256 digest (resumeTokenHash) on latticeAutomationRuns alongside status: 'suspended', suspendedNodeId, approvalId, and resumeAt.
Calling resumeRun executes four ordered checks in claimSuspendedRun:
| Step | Control Stage | Enforcement Behavior |
|---|---|---|
1 | In-flight guard and tenant check | Rejects concurrent resume calls on the same organizationId:runUid (409 RUN_RESUME_CONFLICT), returns 403 NATIVE_ORGANIZATION_MISMATCH on tenant mismatch, and returns 409 RUN_ALREADY_RESUMED if status is no longer suspended. |
2 | Token and authority verification | When resumeToken is supplied, validates timingSafeEqualHex(sha256Hex(resumeToken), run.resumeTokenHash). For HITL approvals, verifyApprovalResumeAuthority verifies direct roles (root, admin, ldx_admin, or the node's approverRole) or resolves an active delegation via delegation-engine (scope: 'latticeAutomationRuns'), logging flow.approval_resumed to the PKI audit ledger when delegated. |
3 | Atomic PostgreSQL state transition | Executes UPDATE "latticeAutomationRuns" SET status = 'resuming', "updatedAt" = NOW() WHERE "organizationId" = :organizationId AND "runUid" = :runUid AND status = 'suspended' RETURNING * so only one caller can claim the run. |
4 | Port routing on wake-up | On control.approval, decision (approved or rejected) routes to the matching port and updates latticeAiApprovalQueue. On ai.agent, rejected routes to error and approved routes to main. On control.delay, execution resumes on main. |
Background Scheduler (tickFlowScheduler in cron.js)
Every DX_FLOW_DELAY_TICK_MS (15000 ms by default), tickFlowScheduler acquires pg_try_advisory_xact_lock(hashtext('dxos_flow_scheduler_tick')) and runs three sweeps:
tickScheduledRules: Evaluates activetrigger.schedulerules and launches runs whennextRunAt <= now.tickDueDelayedRuns: Findssuspendeddelay runs (approvalId == null) withresumeAt <= nowand callsresumeFlowRunassystem:delay-ticker.tickExpiredApprovals: Transitions overdue HITL approval runs (resumeAt <= now) tostatus: 'expired'(errorMessage: 'APPROVAL_EXPIRED') and marks matchinglatticeAiApprovalQueueentriesexpired.
curl -sS -X POST "https://localhost:8443/api/dxosAutomations:resumeRun" \
-H "Authorization: Bearer $LDX_MANAGER_JWT" \
-H "Content-Type: application/json" \
-d '{
"runUid": "run_7c2e19a0-4f18-4b7f-a8c1-1234567890ab",
"decision": "approved",
"payload": {
"note": "Emergency compressor budget approved"
}
}'Error Routing, Timeouts, and Replay
LatticeFlow v2 handles node failures deterministically rather than retrying failed nodes silently in place:
| Mechanism | Runtime Behavior | Outcome |
|---|---|---|
Per-node timeout (timeoutMs) | runSingleNode races execution against node.timeoutMs or node.config.timeoutMs. | Fails the node with FLOW_NODE_TIMEOUT (504). |
error port & errorPolicy | Routes { error, output } along outgoing error edges when present; otherwise halts unless continueOnFail or errorPolicy === 'continue'. | Marks the node failed and either routes or halts. |
Final status (computeRunStatus) | Summarizes stepTracesJson: zero failures yields completed, mixed success and failure yields partial, total failure yields failed. | Persisted onto latticeAutomationRuns. |
Run replay (replayRun) | Reconstructs triggerPayloadJson (or falls back to latticeEventBus), increments depth by 1, and runs with ignoreCooldown: true. | Creates a fresh run record. (Exponential backoff retries apply separately to dxosEvents.) |
