Skip to main content

ControlForge Hot Standby Redundancy

Status (October 23, 2026). Heartbeat/state replication now requires a shared key file and pinned peer identity, verifies HMAC before decoding, and rejects replay across boot sessions. Every primary transition requires ownership authorization. Automatic takeover on silence requires shared_lock; priority and TCP-witness modes refuse uncertain promotion. Shared-lock exclusion and UDP partition/recovery have local regression coverage; cross-host filesystem fencing and physical output behavior still require target qualification. SR/RS, edge history, PID/PIDE internals and virtual-axis state now replicate. Dedicated resource-init BOOLs can opt into failover_reinit; existing programs need migration. Hardware-bound axes and coordinated groups refuse automatic resumption. Target qualification and unused configuration controls remain open. See docs/audits/2026-10-23-failover-security-ownership-remediation.md.

James M. Belcher Founder, JMB Technical Services LLC June 2026 | ControlForge v1.0.1064


ControlForge hot standby coordinates an active/standby pair and synchronizes variables plus supported native state. A standby holds its scans and runtime output writes until ownership is established. A heartbeat timeout detects loss of communication; it does not prove the other controller has stopped. Automatic takeover therefore requires an exclusive shared lock whose backing filesystem enforces locking across both controllers. Unsupported native state and protocol initialization patterns must be assessed before relying on a bumpless transfer.

1. Architecture​

Three services run on each node:

  1. HeartbeatService — Publishes a heartbeat envelope every heartbeat.interval_ms (default 100 ms) and listens for the peer's heartbeats. On transitions (peer disappears, peer appears) it emits cluster.node_lost / cluster.node_join on the events bus. Also tracks role change history for audit.
  2. SyncService — On the primary, publishes incremental state updates over UDP every sync.interval_ms (default 10 ms). The payload is a diff against the last send — only changed variables are serialized. On connect or force-sync, it sends a full state payload (gzip-compressed if sync.compress: true). On the standby, it receives UDP packets and applies them to the shadow interpreter.
  3. Manager — Runs the role machine on every heartbeat tick, from the peer's current level rather than from bus events (which can be dropped under an event flood): a standby that has seen its primary and now sees it gone requests promotion, retrying ownership authorization every tick while the loss persists; a primary that sees the peer become standby sends it a full sync; a primary that sees the peer also primary resolves the split-brain once per episode. Manual Promote / Demote come from REST or ST; manual demotion holds automatic promotion until the peer becomes primary or another manual promotion is accepted. The bus events above are still emitted for the spine and the IDE.

The scan loop lives in the task scheduler and is gated by role. A RolePrimary instance runs its tasks; a RoleStandby instance stops them and lets the SyncService mutate the interpreter state directly. A RoleStandalone instance (failover disabled) runs tasks like a normal non-redundant ControlForge. Misconfigured enabled failover remains inhibited.

2. Roles and initial election​

Three role constants:

RoleMeaningTask execution
primaryThis node owns the scan and writes to physical I/O.tasks running
standbyThis node is a hot shadow of the primary. Tasks stopped; state is driven by sync packets.tasks stopped
standaloneFailover disabled. Behaves like a regular non-redundant ControlForge.tasks running

role is a requested startup role, not permission to drive outputs. Every manager starts inhibited, before task and I/O startup. Missing authentication, listener failures, a protocol mode other than explicit cold, unknown ownership strategies, or unavailable ownership leave it standby.

  • shared_lock: every promotion, including API/ST and startup, must acquire the same exclusive lock. The incumbent retains it through output drain, task shutdown, and cold protocol teardown. A previously paired standby can acquire it after heartbeat loss only when the old owner has released it. A heartbeat-only partition leaves the incumbent as the sole owner.
  • priority: promotion requires a live peer that advertises completed standby teardown and a winning priority/instance-ID comparison. An incumbent may continue on peer loss, but a standby cannot promote on silence, including by manual API request.
  • witness: adds a TCP reachability requirement to priority mode. Losing witness reachability demotes the incumbent. Reachability is not an exclusive lease and never authorizes takeover on silence.

A manual demotion holds the node in standby until the peer becomes primary or another manual promotion is accepted. A standby that has never paired does not automatically take over. auto probes with the authenticated listener running, then applies the same ownership checks. In shared-lock mode acquisition decides ownership; priority is not a guarantee about which simultaneous starter obtains the lock.

3. Configuration​

One top-level failover: block configures the pair. Both nodes require distinct identities, the same secret key bytes, explicit protocols.mode: cold, and a compatible ownership strategy. Upgrade both peers together; there is no unsigned fallback.

3.1 Two nodes with authenticated replication and shared ownership​

Node A (10.0.0.10):

failover:
enabled: true
role: auto
priority: 1
instance_id: node-a
authentication:
key_file: /etc/controlforge/failover.key
protocols:
mode: cold
split_brain:
strategy: shared_lock
lock_path: /mnt/qualified-shared-storage/controlforge.lock
peer:
instance_id: node-b
address: 10.0.0.11
port: 8082

Node B (10.0.0.11):

failover:
enabled: true
role: auto
priority: 2
instance_id: node-b
authentication:
key_file: /etc/controlforge/failover.key
protocols:
mode: cold
split_brain:
strategy: shared_lock
lock_path: /mnt/qualified-shared-storage/controlforge.lock
peer:
instance_id: node-a
address: 10.0.0.10
port: 8082

Create a key file containing at least 32 cryptographically random bytes (maximum 4096) and securely provision identical bytes to both nodes. Restrict file permissions to the runtime account; do not commit the key. The lock paths must refer to the same protected file on a filesystem that enforces cross-host exclusive locks through failures. A local /tmp lock works only for same-host tests. Never delete or replace a live ownership file.

3.2 Full reference with all knobs​

failover:
enabled: true
role: auto # "primary", "standby", "auto" (default: auto)
priority: 1 # lower = preferred primary (default: 1)
instance_id: node-a # distinct node identity
authentication:
key_file: /etc/controlforge/failover.key # required shared random secret

peer:
instance_id: node-b # required pinned peer identity
address: 10.0.0.11 # peer IP or hostname — required
port: 8082 # peer API port (heartbeat → port + 10000, state sync → port + 10001)

heartbeat:
interval_ms: 100 # heartbeat period (default: 100)
timeout_multiplier: 10 # failover after N missed beats (default: 10 → 1 s)
transport: datalayer # accepted, NOT consumed: heartbeats are unicast UDP (section 4)

sync:
interval_ms: 10 # incremental sync period (default: 10)
full_sync_on_connect: true # full transfer when standby connects (default: true)
compress: true # gzip full-sync payloads (default: true)
verify_hash_interval: 100 # verify state hash every N sync cycles (default: 100)

protocols:
mode: cold # required; warm promotion is refused

split_brain:
strategy: shared_lock # required for takeover on heartbeat loss
witness_address: "" # for witness strategy
lock_path: /mnt/qualified-shared-storage/controlforge.lock

Four subsections matter in practice:

heartbeat.timeout_multiplier controls failover aggressiveness. The effective failover timeout is interval_ms × multiplier. The default 100 × 10 = 1000 ms means the standby promotes ~1 second after the primary disappears. Tight links can go lower (100 × 5 = 500 ms works on gigabit LAN); flaky Wi-Fi or congested backhaul links should go higher to avoid false positives during network hiccups. Never set the multiplier below 3 — one dropped packet should not cause failover.

sync.interval_ms trades CPU and bandwidth against state freshness. At 10 ms (default), the standby is at most 10 ms of scan progress behind the primary — bumpless for any non-cycle-accurate process. Raise it to 50 or 100 for slow processes where state freshness doesn't matter; lower it to 5 if you're on a LAN with CPU headroom and need sub-scan granularity.

sync.full_sync_on_connect — Currently unused: a full baseline is sent when the peer becomes standby regardless of this value (open audit F6).

protocols.mode — Explicit cold mode is required. Configured drivers are registered without starting, then started only during an authorized promotion. Demotion stops them before yielding ownership; stop failures retain ownership. Warm mode and an omitted mode refuse promotion because background/cyclic output writers are not universally passive. Reconnection time depends on the driver and target. Protocol configuration changes require a process restart while failover is enabled. Direct GPIO initialization is disabled in failover; use lifecycle-managed HAL configuration and qualify it on the target.

3.3 Ownership and deployment limits​

The strategy rules in section 2 apply to startup, automatic takeover, REST promotion and asynchronous ST requests. Unknown strategies fail closed. A shared lock is revalidated while primary; missing/replaced lock paths or lock errors revoke output permission and trigger demotion. If cold protocol teardown fails, ownership is retained and the node does not advertise a completed yield. A successful handover waits for already-admitted output writes and task shutdown before releasing the lock.

Cross-host guarantees depend on the actual shared filesystem and device protocols. Local flock tests do not certify NFS/cluster-filesystem behavior during storage partitions, server failover, lock revocation, or a paused process. Protect the lock directory against replacement and qualify the deployment with a two-controller rig. Warm protocol clients and asynchronous device-side writes need device-specific qualification too.

GET /api/failover exposes security_error, authentication_rejected, and ownership_error. These explain why an instance is held standby. Priority/TCP-witness mode deliberately sacrifices automatic takeover during silence rather than inferring that the old primary has stopped.

4. State sync wire protocol​

Both UDP channels use a versioned HMAC-SHA256 envelope binding the channel, sender/recipient identities, sender session, receiver boot challenge, sequence and timestamp. The receiver checks the source against the configured peer's startup-resolved IP addresses before accepting payloads. Hello packets exchange challenges only; they do not establish liveness. State transmission waits for a bilateral authenticated heartbeat handshake. Unsigned, wrong-key, wrong-recipient, tampered, stale and replayed datagrams are rejected before JSON/gzip processing. Both full baselines and increments are protected.

Keep peer clocks synchronized: packets outside a ±30-second window are rejected, and a restarted sender's heartbeat timestamp must exceed the last confirmed session's timestamp. After 64 confirmed peer boots in one receiver lifetime, restart the receiver to reset the bounded retired-session history. Rotate keys by provisioning both peers and restarting them together. HMAC authenticates traffic; it does not encrypt process values.

State sync is a dedicated UDP stream, not part of the HTTP API, and not the same as the UADP multicast DataLayer (documented separately). The publisher dials peer.address:peer.port+10001 and sends newline-delimited JSON payloads. The receiver binds its own api.port+10001 and applies the updates.

Packet typeContents
IncrementalOnly changed variables since the last send, per task. Tiny (usually 50–500 bytes).
FullAll variables, all timers, all counters, all SFC step indices. Compressed with gzip if sync.compress: true. Triggered when this node becomes primary, whenever the primary sees the peer become standby (a standby joining, a standby resolving at boot, the loser of a split-brain), on ForceFullSync REST call, and as the repair for a task whose hash the standby reports mismatched — re-sent with backoff (1 s, 2 s, 4 s … 60 s) while that task's increments keep flowing.

Each packet carries a seq field (monotonic uint64) and a task name. Every verify_hash_interval sync ticks is a hash tick: every task's increment carries a CRC32 of that task's own variables as the primary holds them after the delta (a task that did not change gets a hash-only increment, so a quiet task is verified as often as a busy one; the members of shared GVLs are excluded — they are written by other tasks between exports). The standby applies the increment, hashes its own variables and compares. A match marks the task verified; a mismatch is counted, logged once, and the task is named in the standby's next heartbeats until the primary re-sends its baseline; a task the primary runs and the standby does not is reported as missing (program skew — no baseline can repair it). (Before v1.0.1585 the hash was computed and shipped but never compared, and state_hash_match was hardcoded true.) You can see the current sequence, the last observed lag and the verification state in the status endpoint.

Port math: each node listens on its own api.port + 10000 (heartbeat) and api.port + 10001 (state sync), and sends to peer.port + 10000 and peer.port + 10001. With node A on 8082 and node B on 8083: A listens on UDP 18082/18083 and sends to 18083/18084; B listens on 18083/18084 and sends to 18082/18083. Open each node's two listen ports inbound from the peer. The runtime logs the layout at startup (udp layout: heartbeat listen :… → send …).

Two nodes on one host need API ports at least two apart: with adjacent ports one node's sync listener lands on the other's heartbeat listener and the second to bind loses that channel (the runtime warns). Before v1.0.1580 both listeners derived from peer.port instead of the node's own port, so only pairs with identical API ports ever exchanged a datagram — a pair on different ports stayed peer_status: unknown on both sides, silently.

Heartbeats are unicast UDP on the same scheme. The heartbeat.transport key (datalayer / mqtt) is accepted by the parser but not consumed.

5. ST Functions​

Eight builtins let ST code observe and drive the redundancy pair. All return a safe default when failover is disabled or the global manager isn't running, so guard-free usage from ST programs is safe.

5.1 Status queries​

VAR
role : STRING;
is_prim : BOOL;
peer : STRING;
uptime_ms : LINT;
lag_ms : LINT;
END_VAR

role := FAILOVER_ROLE(); (* 'primary', 'standby', 'standalone' *)
is_prim := FAILOVER_IS_PRIMARY(); (* TRUE if role = 'primary' or 'standalone' *)
peer := FAILOVER_PEER_STATUS(); (* 'connected', 'disconnected', 'unknown' *)
uptime_ms := FAILOVER_UPTIME_MS(); (* this instance's failover uptime *)
lag_ms := FAILOVER_SYNC_LAG_MS(); (* how far behind primary this standby is *)

FAILOVER_IS_PRIMARY returns TRUE when the node is either primary or standalone — the common case of "is this instance the one that should be doing work?" A standby returns FALSE; you can use this to gate any side-effecting code that should run only once across the pair:

IF FAILOVER_IS_PRIMARY() THEN
(* Send the start command to the VFD only once, not twice *)
MB_WRITE_REGISTER('plant1', 40001, 1);
END_IF;

FAILOVER_SYNC_LAG_MS is the standby's observed lag behind the primary. On a healthy LAN pair it sits under 10 ms; a persistent lag of hundreds of milliseconds is a symptom of a saturated network path or a CPU-starved standby.

5.2 Role transitions​

(* Manual promotion — typically called from a pushbutton or scheduled test *)
IF manual_switch_button AND NOT was_pressed THEN
FAILOVER_PROMOTE();
END_IF;
was_pressed := manual_switch_button;

(* Manual demotion — less common, usually for planned maintenance *)
FAILOVER_DEMOTE();

(* Force a full state resync from primary to standby *)
FAILOVER_FORCE_SYNC();

FAILOVER_PROMOTE returns TRUE if the node was not already primary and the request was accepted; FAILOVER_DEMOTE is the reverse. Both run on your scan, and a demotion stops the scans, so the transition is queued and lands on its own goroutine a moment after the call returns: read FAILOVER_ROLE() on a later scan for the outcome. A node whose heartbeat listener failed to bind refuses FAILOVER_PROMOTE (it could never hear the arbitration that demotes a second primary). Both log a role-change entry with the reason "manual: ST program" and emit cluster.failover_started on the bus.

FAILOVER_FORCE_SYNC queues an immediate full state sync from primary to standby. Use it after a deploy or a config reload when you know the interpreter state has diverged and you don't want to wait for the next hash verification cycle. Returns TRUE when the request was accepted (this node is primary), FALSE otherwise. The send itself runs off your scan and is rate-limited to one per second whoever asks (REST, ST or the runtime), so calling it every scan costs one export per second, not one per scan. A REAL holding NaN or ±Inf crosses the wire as a tagged value and is restored on the standby (before v1.0.1584 one such variable silently blocked its whole task's sync). A task whose state genuinely cannot be serialised is named in the runtime log and gets no increments until its baseline goes out.

6. REST API​

Six endpoints under /api/failover/*.

6.1 GET /api/failover​

curl http://host:port/api/failover

Returns the current status:

{
"role": "primary",
"instance_id": "plant1-a",
"peer_status": "connected",
"peer_id": "plant1-b",
"peer_address": "10.0.0.11:8082",
"sync_lag_ms": 8,
"last_heartbeat": "2026-04-13T14:22:18Z",
"uptime_ms": 3621540,
"sync_sequence": 41256,
"state_hash_match": true,
"state_hash_verified_at": "2026-04-13T14:22:17Z",
"state_hash_verified_tasks": 12,
"state_hash_mismatches": 0,
"sync_decode_failed": 0,
"heartbeat_listen": "ok :18082",
"sync_listen": "ok :18083"
}
  • role — primary / standby / standalone.
  • peer_status — connected / disconnected / unknown.
  • sync_lag_ms — how far behind the standby is (from the primary's perspective, or 0 on the primary itself).
  • sync_sequence — monotonic counter of sync packets sent/received.
  • state_hash_match — true only once the standby has verified at least one task's variables against the primary's hash and no task is waiting for a repair or missing; false until the first verification, and reset on every role change. On the primary it is the standby's report from its heartbeat, and false whenever that peer is not a live standby.
  • state_hash_verified_at, state_hash_verified_tasks, state_hash_mismatches, state_hash_pending, state_hash_missing — the standby's last match, how many tasks have matched this tenure, its mismatch count, the tasks awaiting a repair baseline, and the tasks the primary syncs that this node does not run.
  • sync_decode_failed — datagrams the sync receiver refused (a full state whose PID field the decoder rejects, a datagram from another build); a climbing count is a task the standby is not receiving.
  • heartbeat_listen, sync_listen — ok :<port> or the bind error (a listener that lost its port is why a peer stays unknown).

6.2 GET /api/failover/history​

curl http://host:port/api/failover/history

Returns up to the last N role-change entries:

[
{
"timestamp": "2026-04-13T14:22:18Z",
"from_role": "standby",
"to_role": "primary",
"reason": "peer lost"
},
{
"timestamp": "2026-04-13T09:14:02Z",
"from_role": "standalone",
"to_role": "standby",
"reason": "startup"
}
]

Every setRole call adds an entry. The history is in-memory — surviving a restart requires pulling it off the bus audit trail.

6.3 Promote / demote / force sync​

# Promote the standby (or standalone) to primary
curl -X POST http://host:port/api/failover/promote

# Demote the primary to standby (for planned maintenance)
curl -X POST http://host:port/api/failover/demote

# Force an immediate full state resync from primary to standby
curl -X POST http://host:port/api/failover/sync

# Snapshot-style sync status
curl http://host:port/api/failover/sync/status

All three mutating endpoints emit a bus event (cluster.failover_started with a reason field). They are subject to the standard auth/RBAC middleware — promote, demote, and force-sync require engineer role if RBAC is enabled.

7. Event bus integration​

Failover state transitions fire bus events that can be routed to Slack, PagerDuty, MQTT, or the WebSocket stream for live HMI banners. Subscribe from the events guide patterns.

Event typeSeverityEmitted whenSource
cluster.node_joininfoHeartbeat service first hears a heartbeat from a new peerfailover
cluster.node_lostwarningPeer heartbeat missed for interval_ms × timeout_multiplierfailover
cluster.failover_startedwarningRole transition (auto promotion, manual promote, split-brain demotion)failover
cluster.split_brain_detectedcriticalBoth nodes claim primary at reconnectionfailover

A typical ops setup routes all four to Slack at info and the split_brain_detected to PagerDuty at critical:

events:
enabled: true
webhooks:
- name: "ops-slack"
url: "https://hooks.slack.com/services/..."
format: "slack"
event_types:
- "cluster.node_join"
- "cluster.node_lost"
- "cluster.failover_started"
- "cluster.split_brain_detected"
min_severity: "info"

- name: "pagerduty-critical"
url: "https://events.pagerduty.com/v2/enqueue"
format: "pagerduty"
routing_key: "R0UTINGKEY..."
event_types: ["cluster.split_brain_detected"]
min_severity: "critical"

The dedup window (default 1 s) collapses a flapping link into one notification per real transition.

8. What gets synced (and what doesn't)​

StateExporter — the interface the task scheduler satisfies for the SyncService — exports and imports:

Synced:

  • Interpreter variables across tasks, except explicitly local failover_reinit latches.
  • Timer state: running flag, elapsed, preset, Q output (from TimerState). Lets TON/TOF/TP instances resume mid-timer with no visible glitch on promotion.
  • Counter values (CTU / CTD / CTUD accumulators).
  • SR/RS latch memory and R_TRIG/F_TRIG edge history.
  • PID/PIDE control internals, including manual mode, fault recovery and PIDE autotune history.
  • SFC active steps and stored actions.
  • Virtual motion axes, including identity, homing and trajectory progress, routed once for the shared controller. Hardware-bound axes and coordinated groups refuse promotion pending local reconciliation.
  • A CRC32 of owned variables and native FB state every verify_hash_interval task-ticks. Shared motion is excluded from per-task hashes; state_hash_match does not verify it.

Not synced:

  • Protocol driver connection state. Open TCP sockets, MQTT subscriptions, ENIP explicit-message sessions — none of these live on the shadow side. The standby opens its own connections on promotion in the required cold mode. One-shot ST resources need the explicit init-latch migration below or an every-scan idempotent-create pattern.
  • File descriptors from FileIO operations. Any file the primary has open is not visible to the standby.
  • HTTP client state from HTTP_GET etc. — these are in-flight requests, not persistent state.
  • In-memory caches that aren't in the interpreter variable map (e.g., JIT regex caches). Not usually a problem — they rebuild on first use.
  • The GlobalEngine state for alarms and events. Alarms are reconstructed from config on the new primary; event history lives in the SQLite bus store, which is per-node.

Replication preserves supported execution state as of the last received snapshot. Driver connections must be re-established, and the transfer delay and device-side behavior require target measurement.

Resource initialization after promotion​

Declare a dedicated program-local latch with {failover_reinit := TRUE}:

VAR
linkInitialized : BOOL := FALSE {failover_reinit := TRUE};
END_VAR
IF NOT linkInitialized THEN
linkInitialized := MB_CLIENT_CREATE('drive', '192.0.2.10', 502);
END_IF;

The latch stays local and is reset before each authorized primary tenure. Ordinary scans do not reset it. Use this only for resource creation/configuration, keeping process initialization and actuator commands separate. Do not use it for replicated virtual-axis creation. RETAIN, CONSTANT, AT-mapped, non-BOOL and initially-TRUE declarations refuse promotion. Unmarked one-shot init latches retain their previous behavior and must be migrated explicitly. Resource allocation and remote-device readiness are separate checks.

See the native-state remediation record, docs/audits/2026-10-23-failover-native-state-remediation.md, for tests and unsupported motion/lifecycle cases.

9. Recipes​

9.1 Run once across the pair​

The most common pattern: a side-effecting action that must run exactly once even if both nodes are up. Gate on FAILOVER_IS_PRIMARY:

PROGRAM AlertPump
VAR
pump_fault_bit : BOOL;
prev_fault : BOOL;
END_VAR

IF pump_fault_bit AND NOT prev_fault THEN
IF FAILOVER_IS_PRIMARY() THEN
NOTIFY_CRITICAL('Pump fault — manual reset required');
END_IF;
END_IF;
prev_fault := pump_fault_bit;
END_PROGRAM

Standby instances evaluate the same ST code (because state sync mirrors variables, including prev_fault), but skip the notification. The primary sends exactly one Slack/PagerDuty message per fault rising edge.

9.2 Alarm on sync lag drift​

FAILOVER_SYNC_LAG_MS is a scalar you can alarm on. Create a HI alarm with a setpoint of 100 ms and a priority of 2 — if the standby starts lagging, operations gets notified before the lag is bad enough to cause a problem:

alarms:
enabled: true
definitions:
- name: "standby_sync_lag"
tag: "failover_watchdog.lag_ms"
type: HI
setpoint: 100.0
deadband: 20.0
priority: 2
delay_ms: 5000
PROGRAM FailoverWatchdog
VAR
lag_ms : LINT;
END_VAR

lag_ms := FAILOVER_SYNC_LAG_MS();
END_PROGRAM

One ST variable, one alarm definition, one recipe — the operator gets warned before the redundancy pair drifts far enough to matter.

9.3 Planned-maintenance demotion​

PROGRAM MaintDemote
VAR
maint_switch : BOOL; (* HMI toggle *)
prev_switch : BOOL;
END_VAR

IF maint_switch AND NOT prev_switch THEN
(* Flip to standby; peer will promote within the heartbeat timeout *)
FAILOVER_DEMOTE();
END_IF;
IF NOT maint_switch AND prev_switch THEN
(* Done with maintenance — take primary back *)
FAILOVER_PROMOTE();
END_IF;
prev_switch := maint_switch;
END_PROGRAM

The cluster.failover_started event on both nodes carries the reason "manual: ST program", so you can prove from the audit trail that the demotion was intentional.

9.4 Partition and handover drill​

On an isolated rig, establish authenticated replication and verify one owner. Drop heartbeat traffic in both directions while both controllers can still reach shared storage. The standby must remain inhibited while the incumbent owns the lock. Restore traffic and verify replication recovery. Then stop the incumbent and verify that scans and outputs drain before the standby acquires ownership. Separately test storage loss, driver teardown failures, process restart, and delayed/replayed packets. Priority and TCP-witness modes must refuse promotion on silence. Observe role history and ownership_error alongside actual output measurements.

10. Performance and scaling​

  • Heartbeat transport: periodic challenge, probe, and heartbeat messages include authenticated headers; measure overhead at your configured rate.
  • Incremental sync cost is variable: 10 ms tick × size of diff. For a 100-variable program with maybe 5 variables changing per scan, expect ~2 kB/s. For a 1,000-variable program with significant churn, expect ~50 kB/s.
  • Full sync cost is one-shot: at connect, it's the compressed total state. For a typical 1,000-variable project, that's 10–50 kB on the wire.
  • Failover detection latency is heartbeat.interval_ms × timeout_multiplier (default 1 s). Reduce the multiplier to 5 for 500 ms on a gigabit LAN; never go below 3.
  • Promotion latency includes ownership authorization, driver reconnection and task startup. Measure it with the configured drivers and target devices; the last received shadow state can lag the failed primary.
  • State sync CPU cost on the standby is the cost of deserializing the JSON diff and writing back into the interpreter map. Small — expect well under 1% of one core at 10 ms tick rate.
  • Bandwidth is the limiting factor on high-variable-churn programs. If you're seeing sync_lag_ms climb, check the link bandwidth first, then raise sync.interval_ms.

11. Troubleshooting​

SymptomLikely causeFix
Both nodes stay standaloneenabled: false on one or both, or peer.address emptyCheck both configs, ensure enabled: true and the peer addresses cross-reference.
Heartbeat loss is reported on every small network bliptimeout_multiplier too aggressiveRaise to 10 (default) or higher on flaky Wi-Fi. Never lower than 3.
sync_lag_ms climbs without boundBandwidth saturation or CPU-starved standbyCheck iftop/nload on the link, raise sync.interval_ms if link is the bottleneck, or move to a faster interconnect.
Standby never catches up after reconnectAuthentication/clock mismatch, missing task, or baseline transport failureCheck authentication rejection counts, clocks, task names and sync logs. full_sync_on_connect is currently not consumed.
state_hash_match: false persists with state_hash_pending non-emptyThe re-sent baselines keep failing to match: one side has a variable the other doesn't (program version skew), or a task's state cannot be encodedCompare state_hash_mismatches over a minute; redeploy the same project to both nodes. Failover can't reconcile different ST program sets.
state_hash_match: false with nothing pending and no state_hash_verified_atNo verification has happened yet: no increment has carried a hash (the primary's variables are not changing, or verify_hash_interval is long)Expected on an idle plant; write a variable on the primary, or lower verify_hash_interval.
Split-brain happens on every cold bootRuntime older than v1.0.1581: both nodes auto-elected primary before the first heartbeat exchange (the probe ran before the listener)Upgrade; on current builds the probe hears the peer. If it persists, the two nodes are not hearing each other during the probe window — check the UDP layout the runtime logs at startup (section 4).
Protocol drivers stall for several seconds on failoverprotocols.mode: coldDesign ST logic to tolerate the reconnect window and qualify its duration. Warm mode is refused.
FAILOVER_PROMOTE returns FALSE from STAlready primary, failover manager not initialized, or this node's heartbeat listener is downCheck FAILOVER_ROLE() first; if it returns standalone, failover is disabled entirely. Then heartbeat_listen in GET /api/failover — a deaf node is never allowed to become primary.
peer_status: unknown on both nodes, no cluster.node_join everOne of the UDP listeners never bound (adjacent API ports on one host, another process on the port) or a firewall drops UDP api.port + 10000/10001Read heartbeat_listen / sync_listen in GET /api/failover — ok :<port> or the bind error — and the udp layout: line the runtime logs at startup. heartbeat.transport is not a factor (the key is not consumed).