Lifecycle and states¶
This page shows which states a node passes through, which of your hooks the SDK calls on each engine command, in what order teardown happens, and on which thread each hook runs. After reading it you can place setup, work, run-ending and release code in the right hook, make a node pause cooperatively, and predict what happens when a hook raises.
The four moments of a node¶
Every node has the same four moments, and each has one hook:
| Moment | Hook | What belongs there |
|---|---|---|
| Set up | on_configure(config, dynamic_config) |
Acquire what the node needs for as long as it is configured: device handles, clients, threads, model weights. |
| Work | on_execute(trigger_context) |
Do the run. Reset per-run state at the top, because the same configured node can run again. |
| End the run | on_stop_execution(trigger_context) |
Make a blocking on_execute return and stop per-run work. Do not release anything acquired in on_configure. |
| Release | on_cleanup() |
Release everything on_configure acquired. The last thing that runs. |
on_stop_execution is new and on_stop is deprecated. Before 2.43.0 the engine had one Stop command that ended the run and released the node in one go, and on_stop was where nodes released their resources. Now the engine can end a run and keep the node configured (StopExecutionNodeGraph), so the graph runs again without Initialize or Configure, and release only happens on the hard stop (StopAndCleanupNodeGraph). on_stop is still called by the hard stop and still works; move its body to on_stop_execution (ending the run) and on_cleanup (release). See Migrating to stop execution.
States at a glance¶
The engine drives every node through the same state machine. Your code never changes the state directly; the SDK does it around your hooks.
stateDiagram-v2
[*] --> IDLE : Initialize
IDLE --> CONFIGURED : configure
CONFIGURED --> RUNNING : execute
RUNNING --> CONFIGURED : on_execute returns (also after stop_execution)
CONFIGURED --> PAUSED : pause
RUNNING --> PAUSED : pause
PAUSED --> CONFIGURED : resume (paused from CONFIGURED)
PAUSED --> RUNNING : resume (paused from RUNNING)
CONFIGURED --> STOPPED : hard stop
RUNNING --> STOPPED : hard stop
PAUSED --> STOPPED : hard stop
ERROR --> STOPPED : hard stop
STOPPED --> CONFIGURED : configure
STOPPED --> IDLE : Initialize
ERROR --> CONFIGURED : configure (recovery)
ERROR --> IDLE : Initialize
CONFIGURED --> ERROR : hook raised
RUNNING --> ERROR : hook raised
note right of ERROR
Every state moves to ERROR when
a hook raises or a teardown step fails.
end note
The state names are the ExecutionState values the UI shows (IDLE, CONFIGURED, RUNNING, PAUSED, STOPPED, ERROR). Stop execution is not a state: it closes the node's run latch and calls your hook, and the node reads CONFIGURED as soon as on_execute returns. A few transitions are worth knowing because they are not obvious from the picture:
| Situation | What happens |
|---|---|
execute while IDLE or ERROR |
The state machine raises NodeStateError; execute() reports it to the engine as NodeExecutionError and fires the Error output when one is declared. The engine has to configure the node first. |
execute while STOPPED, or a Start that belongs to a run that was ended |
Dropped without error. After a hard stop the next Configure re-arms the node; after a stop execution the engine's next Run re-arms it (ArmNodeForRun). |
stop execution while CONFIGURED |
Allowed; on_stop_execution() is still called, so write it to tolerate having nothing to stop. |
stop execution while PAUSED |
The node is resumed first so a blocked on_execute can leave, then on_stop_execution() runs. |
hard stop while IDLE |
The state does not change and nothing is raised, but the teardown chain and your on_cleanup() still run (see below). |
hard stop while STOPPED |
Returns immediately; the hooks do not run a second time. |
pause while IDLE, STOPPED, ERROR or already PAUSED |
No-op, no error, on_pause() is not called. |
resume in any state but PAUSED |
No-op, no error, on_resume() is not called. |
configure or execute while PAUSED |
The node stays PAUSED; only the state that resume returns to is updated (see Pause and resume). |
STOPPED |
Not terminal. configure re-arms the node, Initialize returns it to IDLE. |
ERROR |
configure is the recovery path and lands in CONFIGURED; no separate reset is needed. |
What the engine calls and what runs in your node¶
| Engine command | What the SDK does | Your hooks |
|---|---|---|
| Initialize | Hard-stops the previous lifecycle of this instance (see Hard stop), resets the guards, creates the single-worker execute thread, the trigger adapter and the dataflow, then asks for the typed defaults. Ends in IDLE: a fresh instance is already there, a stopped or errored one returns to it. |
on_stop_execution(), on_stop() and on_cleanup() of the previous lifecycle, then on_get_configuration() |
| Configure | Wires the declared ports to the graph, calls your hook with the static and typed configuration, opens the run latch, moves to CONFIGURED, pushes one health snapshot and starts the periodic health monitor. An exception moves the node to ERROR and is re-raised to the engine. |
on_configure(config, dynamic_config) |
| Arm for run (sent by the engine before every Run, since SDK 2.43.0) | Opens the run latch so the next Start token runs, and drops any work still queued from the previous run. Refused after a hard stop. |
none |
Execute (incoming Start trigger or a manual run) |
Queues the run on the node's own single-worker thread, moves to RUNNING, calls your hook, moves back to CONFIGURED, then fires every declared Start output (and a legacy Stop output, if declared). An exception fires the Error output when one is declared, moves the node to ERROR and raises NodeExecutionError. A Start that arrives after the run was ended or the node was stopped is dropped. |
on_execute(trigger_context) |
| Pause / Resume | Marks the node PAUSED or returns it to the state it was paused from. Nothing is suspended for you. |
on_pause() / on_resume(), only on a real transition |
| Stop execution (soft stop, since SDK 2.43.0) | Closes the run latch (in-flight Start fan-out and stale tokens are dropped), resumes a paused node, calls your hook once for this run. Keeps the node configured, registered and wired; nothing is torn down. Does not wait for on_execute to return. |
on_stop_execution(trigger_context) |
| Stop and cleanup (hard stop) | Stop execution, then waits up to stop_execution_join_timeout_s (default 5 s) for on_execute to return (as every hard stop does), then runs the teardown chain below and moves to STOPPED. |
on_stop_execution(trigger_context), then on_stop(trigger_context) (deprecated), then on_cleanup() |
| Stop (deprecated engine command, kept for older engines) | Same as Stop and cleanup, including the wait since SDK 2.46.2. | Same hooks, same order |
| Health poll | Runs once after Configure and then every health_stream_check_interval_s seconds. |
on_health_check() (see Health reporting) |
Because the execute thread has exactly one worker, triggers that arrive while on_execute is still running are queued, not run in parallel. A long-running on_execute therefore delays the next run of the same node; it does not overlap with it.
Your hooks may run before any configuration exists
The first Initialize of an instance already runs the hard-stop chain, so on_stop_execution(), on_stop() and on_cleanup() are called on a node whose on_configure() never ran. Write all three so that they tolerate resources that were never opened (check for None before closing).
Stop execution and the run latch¶
stop_execution() is what makes "run it again" possible without Initialize and Configure. It does three things, in this order:
- Closes the node's run latch and advances its execution generation. From here on a
Start(or custom) trigger that was already in flight for this run is dropped, anon_executethat returns after the stop does not fire itsStartoutputs, andfire_trigger()is a logged no-op. - Resumes the node if it was paused, so an
on_executethat blocks onis_paused()can leave. - Calls
on_stop_execution(trigger_context)exactly once for this run. A second stop execution in the same run is a no-op.
It does not join your execute thread and does not touch the state machine: when your on_execute returns, the execute wrapper reports CONFIGURED as always. The engine's StopExecutionNodeGraph waits for that before it reports the graph as ready to run again, so make on_execute return promptly after on_stop_execution.
What on_stop_execution should do: set the flag or notify the condition variable that your on_execute loop waits on, cancel a timer, ask the robot to stop the current motion. What it must not do: close the device, drop the connection, destroy the client. Those survive until on_cleanup, and the next run expects them. Reset per-run state at the top of on_execute, not in on_stop_execution, because the engine ends the run on every armed node whether or not it was executing. is_run_active() tells you whether the current run is still live.
def on_stop_execution(self, trigger_context: Optional[TriggerContext] = None) -> None:
"""End the current run only. The device stays open for the next run.
This node's on_execute returns on its own, so there is nothing to
unblock; a node with a loop would set the flag the loop reads here.
Called at most once per run, also when the node is idle.
"""
self.log_info("SmartLightNode run ended")
A node that ends the run¶
Since SDK 2.50.0
Both stops above are engine commands, normally sent because someone pressed Stop
in the UI. A node in the graph can ask for one instead, which is how a graph ends
its own run when the work is finished. You get this by placing node-misc's
EndRunNode in the graph and triggering it; its Stop mode picks which of the two
stops the engine performs.
- Hard, the node's default, is stop and cleanup: every node in the graph is stopped, the teardown chain below runs and the graph is removed. The graph has to be configured again before it can run.
- Soft is stop execution: every node returns to
CONFIGUREDand the graph stays loaded, so it runs again without Configure.
Nothing in your node code changes and no hook is involved in making the request.
Your node sees only the stop it would have seen from the UI, so a node that
handles on_stop_execution and on_cleanup correctly already handles this. The
request needs a node engine that understands it; on an older engine the node logs
a warning and the run keeps going.
Hard stop teardown order¶
The hard stop (StopAndCleanupNode, the deprecated StopNode, and the re-Initialize of an instance) runs one chain. Each step runs on its own: a failing step is logged and recorded, and the remaining steps still run, so one broken resource cannot leak the others.
on_stop_execution(trigger_context), unless it already ran for this run.- Wait up to
stop_execution_join_timeout_sfor a runningon_executeto return. Every hard stop waits, and a stop called from insideon_executedoes not wait on itself. - Auto-triggering is switched off, so an
on_executethat is still running cannot fireStartto downstream nodes when it returns. - Platform data client is closed.
- State machine moves to
STOPPEDand the status stream ends. - Health monitor stops (its thread is joined) and the health stream ends.
- Dataflow is destroyed (subscriptions gone, no more input data).
- Trigger adapter is destroyed (no more incoming triggers).
- The execute thread is shut down without waiting for a running
on_executeto finish. - Scene client is closed.
on_stop(trigger_context)runs (deprecated), from afinallyblock, exactly once per lifecycle. An exception inside it is logged and never propagated.on_cleanup()runs last, from the samefinallyblock, exactly once per lifecycle.
Before 2.46.2 only stop and cleanup waited. The deprecated Stop, a re-Initialize or Configure of a running node and service shutdown now wait too.
- No overlap.
on_stopandon_cleanupnever run whileon_executeis still returning, unless the timeout expires. The SDK then logs a warning and tears down anyway. - Status sequence. A hard stop drops the late completion of the run. The node goes straight to
STOPPED, withoutRUNNINGtoCONFIGUREDfirst, and anon_executethat raises on its way out sets noERRORstate and fires noErrortrigger. - Cost. A legacy node whose blocking
on_executeis only released byon_stopwaits the full timeout, with a warning, on every hard stop. Service shutdown waits up to the timeout for each node that is still running. Reconfiguring a node whoseon_executeignores the stop takes up to the timeout longer; the engine deadlines (Initialize and Configure 30 s, stop and cleanup 20 s) leave room.
If any step failed, the node moves to ERROR and NodeStopError is raised to the engine after both hooks have run. A second hard stop on an already stopped node returns immediately without calling either hook again. The next Configure (or Initialize) re-arms the hooks for the next lifecycle.
Before 2.43.0 on_cleanup() ran before the dataflow and trigger adapters were destroyed. It now runs last, after them, so publishing or firing a trigger from on_cleanup() fails. Nodes that used on_cleanup() to break their on_execute loop or to publish a final message move that code to on_stop_execution() or to the end of on_execute().
What this means for your code:
- Release in
on_cleanup()what you acquired inon_configure(): device handles, sockets, threads, model weights. Nothing in the SDK is available to you any more at that point. - End the run in
on_stop_execution(). If youron_executeloops, make it check a flag thaton_stop_execution()sets. - Leave
on_stop()empty, or do not override it. Overriding it logs a deprecation warning when the service starts. It is removed in a later major.
def on_cleanup(self) -> None:
"""Final step of the hard stop: release what on_configure() opened."""
self._release_device()
def on_stop(self, trigger_context: Optional[TriggerContext] = None) -> None:
"""Deprecated since SDK 2.43.0 and only kept so this class still
instantiates on older SDKs, where on_stop was abstract. Leave it empty."""
def _release_device(self) -> None:
if self._device is not None:
self._device.close()
self._device = None
Pause and resume (cooperative)¶
Pausing marks the node PAUSED and calls on_pause(). That is all the SDK does: triggers keep arriving, on_execute keeps being called, dataflow keeps flowing. Suspending real work is your job, either by stopping it in on_pause() and restarting it in on_resume(), or by polling is_paused() inside a loop and skipping the work while it returns True.
is_paused()exists onNodeBaseand reads the state machine.pause()fromCONFIGUREDis legal. Before 2.39.0 it raisedNodeStateErrorand put the node inERROR, which hit every idle node when a whole graph was paused.pause()andresume()never move a node toERROR. An exception insideon_pause()oron_resume()still raisesNodePauseErrororNodeResumeErrorto the engine, but the state is unchanged.resume()returns to the state the node was paused from. A node paused whileCONFIGUREDresumes toCONFIGURED, notRUNNING.on_pause()andon_resume()fire only on the call that actually changes the state, so a repeated pause or resume does not re-run them.
Projects still pinned below SDK 2.39.0 have no is_paused(), and pausing from CONFIGURED raises. Code supporting those older projects keeps its own flag in on_pause() / on_resume() and falls back to it, as the example below does.
While paused, an incoming Start still runs on_execute, and a returning on_execute still fires the outgoing Start. The node stays PAUSED throughout and emits no RUNNING or CONFIGURED status, so the UI keeps showing PAUSED until the engine resumes or stops the node. A stop execution resumes the node first, so a loop that waits on is_paused() sees the pause end and can then see the run end.
def on_pause(self) -> None:
self._paused_flag = True
self.log_info("Light control paused")
def on_resume(self) -> None:
self._paused_flag = False
self.log_info("Light control resumed")
def _is_paused(self) -> bool:
# Pause is cooperative: the SDK keeps calling on_execute() while paused, so the node
# has to skip work itself. SDK 2.39.0 added is_paused(), which reads the state machine.
# SDK 2.37.0 has no such method, so fall back to the flag on_pause()/on_resume() keep.
return self.is_paused() if hasattr(self, "is_paused") else self._paused_flag
See the smart home tutorial for the complete node.
The trigger context¶
on_execute, on_stop_execution and on_stop receive an optional trigger_context describing the trigger that caused the call:
| Field | Type | Meaning |
|---|---|---|
source_node |
str |
Class name of the node that fired the trigger. |
timestamp |
datetime |
When the context was created. |
err_info |
ErrorInformation or None |
Set only when the upstream node failed: err_type, err_msg, transaction_id. |
trigger_context.is_triggered_by_error() returns True when err_info is set. Which incoming trigger types reach which hook:
| Incoming trigger type | Calls |
|---|---|
Start, IfTrue, IfFalse, InLoop, BreakLoop, Error |
on_execute(trigger_context) |
Stop |
stop_execution(), and therefore on_stop_execution(trigger_context), when your node overrides on_stop_execution. A node that still relies on on_stop gets the hard stop instead, as before 2.43.0. |
| A custom type name | The method you bound with @trigger_handler("Name"), see Triggers |
Always guard against None. The Mock Runner calls on_execute(trigger_context=None), a manual run from the UI carries no context, and a malformed payload is delivered without one. Error is a valid input trigger: wire an upstream error output to your start input and branch on is_triggered_by_error():
def on_execute(self, trigger_context: Optional[TriggerContext] = None) -> None:
# Start and Error both land here. Only the Error path carries err_info.
if trigger_context is not None and trigger_context.is_triggered_by_error():
err_info = trigger_context.err_info
self.log_error(
f"Upstream node {trigger_context.source_node!r} failed: "
f"{err_info.err_type}: {err_info.err_msg} "
f"(transaction {err_info.transaction_id})"
)
self.errors_seen.append(err_info.err_msg)
return
source = trigger_context.source_node if trigger_context else "unknown"
self.log_info(f"ErrorHandlerNode started normally by {source!r}; nothing to handle")
Import the type with from neuraverse_sdk.trigger.i_trigger import TriggerContext.
Errors and exceptions¶
Any exception that escapes on_execute has the same effect on the state machine: the Error output fires (when declared in the schema) with err_type and err_msg filled from the exception, and the node moves to ERROR. The exception text is what the status message and the Error trigger carry. An exception in on_configure moves the node to ERROR too and is re-raised as is. A node in ERROR recovers on the next Configure; execute is refused until then (a NodeStateError inside the SDK).
Which exception you raise decides what the rest of the graph learns. From on_configure and the other hooks the engine calls directly, a typed error from the error vocabulary gives that call an accurate gRPC status and a safe message, while anything else collapses to a generic INTERNAL. From on_execute there is no response to shape, because a run is queued rather than awaited; what a typed error buys you there is an accurate err_type on the Error trigger and the right class for a downstream handler or your own except to match on.
Before 2.42.0 execute() wrapped every exception from on_execute in NodeExecutionError, so err_type always read NodeExecutionError whatever you raised. It now re-raises a NodeError unchanged and wraps only everything else. Note that err_msg is the exception's own text on both sides of that change, so it reaches downstream nodes verbatim; see Errors.
The older exceptions still exist, the SDK still raises them, and nothing is being removed. They live in neuraverse_sdk.utils.exceptions, derive from NodeSDKError and carry message and error_code:
| Exception | Base | error_code | Raised when |
|---|---|---|---|
DataFlowException |
NodeSDKError |
DATA_FLOW_ERROR |
Raised when dataflow is not valid |
InvalidEndpointError |
NodeSDKError |
ENDPOINT_NOT_FOUND |
Raised when an endpoint is not found |
NodeConfigurationError |
NodeSDKError |
CONFIG_ERROR |
Raised when there's an error in node configuration |
NodeExecutionError |
NodeSDKError |
EXECUTION_ERROR |
Raised when there's an error during node execution |
NodeHealthCheckError |
NodeSDKError |
HEALTH_CHECK_ERROR |
Raised when there's an error performing a health check |
NodeNotFoundError |
NodeSDKError |
NODE_NOT_FOUND |
Raised when a node is not found |
NodePauseError |
NodeSDKError |
PAUSE_ERROR |
Raised when there's an error during node pause |
NodeRegisteryError |
NodeSDKError |
NODE_REGISTRATION_ERROR |
Raised when a node is not able to register |
NodeResumeError |
NodeSDKError |
RESUME_ERROR |
Raised when there's an error during node resume |
NodeSDKError |
Exception |
Base exception for all Neuraverse SDK errors | |
NodeSimulationModeError |
NodeSDKError |
SIMULATION_MODE_ERROR |
Raised when there's an error toggling simulation mode |
NodeStateError |
NodeSDKError |
INVALID_STATE |
Raised when a node is in an invalid state for the requested operation |
NodeStopError |
NodeSDKError |
STOP_ERROR |
Raised when there's an error during node stop |
RobotException |
NodeSDKError |
ROBOT_ERROR |
Raised when robot is in error |
TriggerFlowException |
NodeSDKError |
TRIGGER_FLOW_ERROR |
Raised when trigger flow is not valid |
Threads¶
External custom events and Stop run on tracked workers independent of ordinary execution. Stop closes input admission before its hook finishes. Reconfiguration waits for pending Stop and discards queued events from the previous configuration. Stop uses the existing 2.x teardown order and cancels pending input callbacks.
The SDK calls your hooks from several threads. Anything two hooks share needs a lock or a thread-safe structure.
| Code | Runs on |
|---|---|
on_configure, on_get_configuration, on_pause, on_resume, on_toggle_simulation_mode |
The engine request thread. |
on_execute |
The node's own single-worker execute thread, named <ClassName>-execute. One run at a time per node. |
@trigger_handler methods |
The transport callback thread for native events, or a separate worker for external inputs. Both are concurrent with on_execute. Keep them short and non-blocking. |
Callbacks passed to register_handler(callback, port) |
The transport callback thread for native messages, or the request thread for typed JSON input, after storing the value. |
on_health_check |
Once on the Configure request thread, then on the health-monitor-<node_id> thread. |
on_stop_execution |
The engine request thread (or the transport thread for an incoming Stop trigger), while on_execute is still running. Do not join your execute thread here. |
on_stop, on_cleanup |
The engine request thread (or the transport thread for an incoming Stop trigger on a node without on_stop_execution), after the SDK waited for on_execute to return, or, when it did not return in time, while it is still running. |
Custom trigger handlers are bound at class level with @trigger_handler, so they exist before Configure validates them. Dataflow callbacks go into on_configure(): the port routing that register_handler needs exists only after the SDK configured the dataflow, which happens right before your hook. A call before that silently registers nothing. Never register inside on_execute.
Typed JSON input serializes its commit and message handler with node lifecycle operations. Keep the handler short: a blocking handler delays the input acknowledgement and subsequent Stop or Configure requests.
In the Mock Runner
Init creates your class and attaches an in-memory dataflow; it does not run the SDK's initialize(), so no trigger adapter or health stream exists. Configure runs the real configure(), so on_configure is called and the node reaches CONFIGURED. Execute calls execute(trigger_context=None) synchronously on the request thread. There are no Stop or Pause actions, so on_stop_execution, on_cleanup, on_stop, on_pause and on_resume never run there. Cover them with unit tests instead, see Testing.
Where to next¶
- Errors for which error to raise from a hook and what the caller receives.
- Node anatomy for the exact hook signatures.
- Migrating to stop execution if your node still overrides
on_stop. - Dataflow for reading inputs and publishing outputs inside
on_execute. - Triggers for custom trigger ports and
fire_trigger. - Health reporting for
on_health_checkandsend_health_update.