Skip to content

LatticeFlow v2 Overview ​

LatticeFlow v2 is the directed acyclic graph (DAG) workflow orchestration engine built into @latticedx/plugin-dxos-studio (src/server/flow/*). It pairs the visual @xyflow/react editor in Control Studio with durable PostgreSQL 16 execution under FORCE ROW LEVEL SECURITY, connecting domain CloudEvents, ORM record hooks, cron schedules, signed webhooks, DMN decision tables, AI agents, and Digital Twin commands in one tenant-isolated runtime.

LatticeFlow v2 DAG Engine (24 Node Types & Durable Checkpoints)
TRIGGER INGRESSDAG V2 RUNTIME & PG16 CHECKPOINTSSIDE EFFECTS & EVENTSruntopoparkexecdirect path (no suspend)Trigger Ingress(5)event · record · cronwebhook · manualDAG TopologicalRunner{{steps.*}} depth<=8maxNodes 50 · policyLogic & Control(10 Node Types)logic.dmn · transformif · switch · loopparallel · mergePG16 Suspend &Resumecontrol.delay · HITLloopCursors · :replaySide Effects &Events (9)data.* RLS · ai.agenthttp · twin · notifyevent.emit (Outbox)
InspectorDAG Topological RunnerClick any component to inspect bindings & boundaries
Role
Topological graph traversal, template scope & error policy
Package / Port
@latticedx/plugin-dxos-studio · flow/executor.js
Protocol
Kahn Topo Sort · runNodeInRlsSavepoint
Payload / Schema
errorPolicy: 'stop' | 'continue' · MAX_HARD_DEPTH = 8
Responsibilities
Runs up to 50 nodes inside tenant FORCE RLS savepoints, resolves {{steps.*}} safely without eval, routes error edges per errorPolicy, and records traces for :replayRun.
Left-to-right topological DAG execution across 24 node types; errorPolicy (stop | continue), step traces, and dxosAutomations:replayRun are enforced by the runner and PG16 checkpoint store.

DAG Execution Architecture ​

Each LatticeFlow v2 workflow stores a versioned graph (schemaVersion: 2) that separates editable drafts (draftGraphJson) from the live published definition (graphJson, publishedVersion). Before a graph is saved or executed, schema.js, validator.js, and executor.js enforce structural and security invariants.

Graph Normalization and Static Validation ​

normalizeGraph coerces incoming definitions into FLOW_SCHEMA_VERSION = 2 with bounded defaults, and validateFlowGraph enforces four static checks before persistence or execution:

CheckEnforcement MechanismRejection Code
Topological sort and cyclesKahn's algorithm builds topoOrder and rejects self-loops or cycles.FLOW_CYCLE_DETECTED
Port compatibilityValidates STANDARD_PORTS plus dynamic case_* ports on control.switch; trigger.* nodes accept no incoming edges.FLOW_INVALID_PORT
Template and table safetyRejects ${...}, nested braces, and prototype keys in {{path}}; restricts data nodes to allowlisted collections.UNSAFE_TEMPLATE_EXPRESSION, TARGET_COLLECTION_FORBIDDEN
Static SSRF filteringValidates URL fields on integration.http, ai.llm, and iot.twin_command against loopback and metadata ranges.CONNECTOR_URL_UNSAFE
Engine Limits and Graph Settings (graph.settings)
ParameterTypeDefaultDescription
versionrequired
integer2DAG schema version (FLOW_SCHEMA_VERSION = 2).
MAX_FLOW_NODES
constant50Maximum number of nodes permitted in a single workflow graph.
MAX_HARD_DEPTH
constant8Hard recursion depth cap across ORM hooks, subflows, and event.emit.
MAX_LOOP_ITERATIONS
constant100Maximum items processed per control.loop execution.
settings.errorPolicy
stringstopGraph-level failure handling policy: stop or continue.
settings.cooldownSec
number0Minimum cooldown window in seconds between runs of the same ruleKey.
settings.maxDepth
integer8Per-rule recursion ceiling, clamped to MAX_HARD_DEPTH (8).
settings.timeoutMs
integer30000Default graph execution timeout metadata in milliseconds.

Runtime Traversal Lifecycle ​

When executeFlowGraph receives a trigger event, it builds execState, checks recursion depth (event.depth >= maxDepth), evaluates cooldownSec, and tests filterJson. Once matched, traverseDag drives execution under four runtime invariants:

Runtime InvariantExecution Behavior in traverseDag
Per-node savepoint isolationEach node runs inside runNodeInRlsSavepoint under the tenant RLS context (runAutomationWithRls when DX_PG_RLS_SESSION=true), preventing a single node failure from aborting the surrounding PostgreSQL session.
RLS-aware parallel batchingConcurrent ready nodes run through runRlsAwareBatch, which executes branches concurrently via Promise.all when no shared active RLS transaction is open, or sequentially inside a shared transaction to preserve savepoint ordering.
Port routing and branch skippingCompleted nodes forward their output payload along edges matching nextPort (or nextPorts). Unreachable downstream nodes on untaken branches are marked skipped with reason BRANCH_NOT_TAKEN.
Trace capping and secret scrubbingsanitizeTraceData caps stored step inputs and outputs at 16384 bytes and masks sensitive fields (token, secret, password, apiKey, Bearer, sk-*) before writing to latticeAutomationRuns.

Six Categories and 24 Node Types ​

All node definitions are validated by validateNodeDefinition in registry.js and exposed at runtime via dxosAutomations:nodeRegistry. The 24 built-in nodes are grouped into 6 categories:

CategoryCountInputsStandard OutputsRole in the DAGReference
trigger5[]mainStarts a run from CloudEvents, ORM record hooks, cron, signed webhooks, or API callsNode Reference
control8inmain, true/false, case_*, item/done, approved/rejected, errorConditional branching, fan-out, merge, bounded loops, delays, HITL approvals, and subflowsNode Reference
data3inmain, errorQueries, creates, and updates tenant-scoped records in allowlisted business tablesNode Reference
logic2inmain, errorEvaluates tenant DMN decision tables and runs declarative data transforms without eval()Node Reference
ai2inmain, errorCalls OpenAI-compatible llmServices with PII redaction or runs ReAct agents with HITL toolsNode Reference
integration4inmain, errorInvokes Vault HTTP connectors, sends Digital Twin setpoints, dispatches alerts, and emits CloudEventsNode Reference

See the complete configuration schemas and output payloads in LatticeFlow v2 Node Reference.

Execution States and the Run Ledger ​

Every live execution (dryRun = false) creates a record in latticeAutomationRuns, capturing an immutable graphSnapshotJson and triggerPayloadJson so suspended or failed runs can resume or replay deterministically even after a rule is edited.

StatusMeaningFollow-up Behavior
runningTraversal is actively executing ready nodes.Transitions to a terminal or suspended state in finalizeDagRun.
completedAll visited nodes succeeded without unhandled errors or active suspension.Can be re-executed from original trigger data via replayRun.
partialAt least one non-trigger action completed and at least one failed (via error edge or errorPolicy: 'continue').Inspect stepTracesJson and replay via replayRun.
failedA node failed without an error edge and halted execution, or graph validation failed.Fix graph configuration and re-run via replayRun.
suspendedPaused at control.delay, control.approval, or a mutating ai.agent tool awaiting HITL approval.Resumed via resumeRun or tickFlowScheduler.
resumingAtomic PostgreSQL claim lock acquired while resuming a suspended run.Transient guard preventing duplicate concurrent resumes.
expiredAn HITL approval passed resumeAt without a decision.Closed with errorMessage: 'APPROVAL_EXPIRED'.
skippedStopped early due to RULE_UNPUBLISHED, FILTER_NOT_MATCHED, COOLDOWN_ACTIVE, or RECURSION_DEPTH_LIMIT_EXCEEDED.No downstream actions execute; reason is logged in errorMessage.
Core Fields of latticeAutomationRuns
ParameterTypeDefaultDescription
runUidrequired
string—Unique run identifier formatted as run_<uuid>.
ruleKeyrequired
string—Workflow key matching ^[a-z0-9][a-z0-9_-]{1,62}$.
statusrequired
string—Current lifecycle status of the workflow run.
depth
integer0ORM and subflow recursion depth at run start.
graphVersion
integer2DAG engine version used for execution.
nodeStatesJson
jsonb{}Per-node status, outputs, ports, and loopCursor/loopCursors stack when suspended.
stepTracesJson
jsonb[]Chronological execution trace containing sanitized input, output, error, and durationMs.
suspendedNodeId
string—Node ID currently paused for delay or HITL approval.
approvalId
integer—Foreign reference to latticeAiApprovalQueue when waiting on HITL decision.
resumeAt
datetime—Wake-up timestamp for control.delay or expiration deadline for approvals.
resumeTokenHash
string—SHA-256 digest of the 24-byte random hex token checked during resumeRun.

Versioning, DSL Formats, and Dry-Run Testing ​

LatticeFlow v2 separates draft editing from live traffic and supports symmetric JSON and YAML DSL serialization (serializeFlowDsl and parseFlowDsl in schema.js). Changes persist to draftGraphJson via saveDraft without affecting published traffic and can be simulated through testRule (useDraft: true, dryRun: true, bypassing cooldownSec). Calling publishRule increments publishedVersion, updates graphJson and triggerIndexJson, and writes an immutable snapshot into latticeAutomationRuleVersions. When restoring a prior revision, rollbackRuleVersion publishes a new monotonically increasing version copied from the target snapshot rather than rewriting history.

bash
# 1. Save a v2 draft graph
curl -sS -X POST "https://localhost:8443/api/dxosAutomations:saveDraft" \
  -H "Authorization: Bearer $LDX_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"ruleKey":"order_alert_v2","name":"Order Alert","draftGraphJson":{"version":2,"nodes":[{"id":"trig_1","type":"trigger.record","config":{"collection":"latticeOrders","operation":"create"}}],"edges":[]}}'

# 2. Simulate the draft in dryRun mode
curl -sS -X POST "https://localhost:8443/api/dxosAutomations:testRule" \
  -H "Authorization: Bearer $LDX_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"ruleKey":"order_alert_v2","useDraft":true,"sampleEvent":{"data":{"id":101,"totalAmount":12000000}}}'

# 3. Publish to live execution
curl -sS -X POST "https://localhost:8443/api/dxosAutomations:publishRule" \
  -H "Authorization: Bearer $LDX_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"ruleKey":"order_alert_v2","changeSummary":"Initial release"}'

dxosAutomations API Surface ​

All 19 actions under dxosAutomations enforce organization scoping and ldx_pat_* API key scopes. Direct REST CRUD against latticeAutomationRules, latticeAutomationRuleVersions, and latticeAutomationRuns is blocked by createAutomationDirectGuardMiddleware so every mutation passes graph validation and RLS binding.

POST/api/dxosAutomations:publishRule
Bearer JWT | ldx_pat_*write | ai | iot
Validates the graph, increments publishedVersion, rebuilds triggerIndexJson, and writes an immutable version snapshot.
POST/api/dxosAutomations:runNow
Bearer JWT | ldx_pat_*write | ai | iot
Executes the published rule (or draft when useDraft=true) immediately using the supplied event payload.
GET/api/dxosAutomations:getRunTrace
Bearer JWT | ldx_pat_*read | write | ai | iot
Fetches a single latticeAutomationRuns record by runUid or id, including nodeStatesJson and sanitized stepTracesJson.
POST/api/dxosAutomations:resumeRun
Bearer JWT | ldx_pat_*write | ai | iot
Atomically claims a suspended run, validates resumeToken or approver role/delegation, and resumes DAG traversal.
POST/api/dxosAutomations:webhookIngress
Public (HMAC-SHA256 | Bearer | Standard Webhooks)
Public webhook ingress endpoint dispatching into trigger.webhook rules by organizationId and ruleKey.
ActionTypical MethodAuth & PAT ScopePurpose
listRules, builderCatalog, nodeRegistryGETManager/Admin · readLists rules, Studio builder catalog, and all 24 node schemas
saveRule, saveDraft, publishRule, rollbackRuleVersionPOSTAdmin · write, ai, iotSaves rules, edits drafts, publishes snapshots, and rolls back versions
listRuleVersions, listRuns, getRunTraceGETManager/Admin · readReads version history, run summaries, and step-level traces
toggleRule, deleteRule, runNow, replayRun, resumeRunPOSTManager/Admin · write, ai, iotEnables/disables rules, deletes rules, triggers manual runs, replays, and resumes
testRule, testNodePOSTManager/Admin · read (live testNode needs write)Dry-runs an entire graph or tests one node with pinnedInputs
aiAssistPOSTManager/Admin · write, ai, iotInvokes runFlowArchitect to draft, patch, or diagnose failed traces
webhookIngressPOSTPublic (HMAC / Bearer)Triggers workflows from external HTTP callers

Security Boundaries and Operations ​

data.* and ai.agent nodes strictly reject access to SYSTEM_PROTECTED_COLLECTIONS and FORBIDDEN_SYSTEM_COLLECTIONS (latticePkiKeys, latticeCryptoLedger, latticeConnectors, latticeApiKeys, latticeDelegations, latticeAutomationRules, latticeAutomationRuns).

To prevent infinite trigger loops, AsyncLocalStorage (ormDepthStore) propagates depth across ORM record hooks, control.subflow, and event.emit. Reaching depth >= maxDepth (capped at 8) skips execution with RECURSION_DEPTH_LIMIT_EXCEEDED.

In background scheduling (tickFlowScheduler), every DX_FLOW_DELAY_TICK_MS (15000 ms by default) the engine acquires pg_try_advisory_xact_lock(hashtext('dxos_flow_scheduler_tick')) to run cron triggers, wake control.delay runs, and expire overdue HITL approvals without duplicate execution across replicas.

Apache-2.0 · LatticeDX v0.4.2 · Powered by NocoBase · v2.2.50 · Apache-2.0 (Clause 5.2)