Node anatomy¶
This page names the parts every Neuraverse node is made of and the rules that tie them together. After reading it you can recognise a complete node project at a glance, write a class that the SDK accepts, put its schema file where the SDK finds it, and register it so the node service starts it. Everything here is Python; the deeper behaviour of each part has its own page, linked from the tables.
The five parts of every node¶
| Part | What it is | Where to read more |
|---|---|---|
| A node class | A Python class that extends NodeBase |
This page |
| Three required hooks | on_configure, on_execute, on_get_configuration (plus the optional on_stop_execution and on_cleanup for nodes that hold resources or run loops) |
Lifecycle and states, Configuration |
| A schema file | <module>_schema.json next to <module>.py, declaring name, ports and static configuration |
Schema file reference |
| Registration | set_node_classes([...]) followed by run() in run_nodes.py |
Project layout and build |
| A service config | config/service_config.yaml, the endpoints and ports of the node service |
Project layout and build |
A node service (one container, one process) can host several node classes. Each class brings its own schema file; all classes share one run_nodes.py and one service config.
Imports that work¶
The package neuraverse_sdk has an empty __init__.py, so nothing can be imported from the package root. Import every symbol from its submodule:
| You need | Import |
|---|---|
| The base class | from neuraverse_sdk.node_base import NodeBase |
| Registration and startup | from neuraverse_sdk.node_manager_service import run, set_node_classes, set_node_service_class |
| Trigger context and custom trigger handlers | from neuraverse_sdk.trigger.i_trigger import TriggerContext, trigger_handler |
| Reading one config key from both config maps | from neuraverse_sdk.utils.config import get_config_value |
| Errors to raise from hooks | from neuraverse_sdk.models.errors import NodeDataError, NodeDependencyError, NodeError (since SDK 2.42.0; before that from neuraverse_sdk.utils.exceptions import NodeExecutionError, NodeConfigurationError) |
| Typed configuration entries | from neuraverse.models.v1.gen.business.node_graph_pb2 import NodeConfigEntry, NodeConfigValue, ToggleValue, RangeValue, SingleSelectListValue, MultiSelectListValue |
| Message types for ports | from std_msgs.msg import String, Float32 (any ROS 2 message package) |
The imports of the quickstart node show the usual set:
from typing import Optional
from google.protobuf.internal.containers import MessageMap, ScalarMap
from neuraverse.models.v1.gen.business.node_graph_pb2 import NodeConfigEntry
from std_msgs.msg import String
from neuraverse_sdk.node_base import NodeBase
from neuraverse_sdk.trigger.i_trigger import TriggerContext
A minimal node¶
The smallest complete node reads one data port, publishes one data port and does nothing else. It implements exactly the four required hooks:
class UppercaseNode(NodeBase):
"""Reads ``text_input`` and publishes the upper-cased text on ``text_output``."""
def on_configure(
self,
config: ScalarMap[str, str],
dynamic_config: MessageMap[str, NodeConfigEntry] | None = None,
) -> None:
"""Receives the static schema config and the typed UI config. Nothing to set up here."""
self.log_info("UppercaseNode configured")
def on_execute(self, trigger_context: Optional[TriggerContext] = None) -> None:
"""Runs every time the node is triggered."""
msg = self.get_data("text_input")
if msg is None:
self.log_warning("No message on text_input yet, nothing to publish")
return
result = String(data=msg.data.upper())
self.publish("text_output", result)
self.log_info(f"Published: {result.data}")
def on_stop(self, trigger_context: Optional[TriggerContext] = None) -> None:
"""Runs once when the node is stopped."""
self.log_info("UppercaseNode stopped")
def on_get_configuration(self) -> dict[str, NodeConfigEntry]:
"""This node has no settings to show in the UI."""
return {}
Three things to notice:
- Messages on ports are ROS 2 message objects. Read the payload through
msg.dataand publish a message object, never a barestr. See Dataflow. self.get_data(port)returnsNonewhile nothing has arrived on that port yet, so everyon_executeguards for it.- Logging goes through
self.log_info(),self.log_warning()andself.log_error().
The hooks¶
NodeBase is an abstract base class. The four required hooks are declared abstract, so a class that misses one cannot be instantiated: the service fails at startup with a TypeError naming the missing method. The optional hooks have safe default bodies and are overridden only when needed.
Required — your class must implement all four:
| Hook | Purpose | Called on |
|---|---|---|
on_configure(config: ScalarMap[str, str], dynamic_config: MessageMap[str, NodeConfigEntry] \| None = None) -> None |
Called when the node configuration is updated | ConfigureNode — on every (re)configuration, before any execution. |
on_execute(trigger_context: Optional[TriggerContext] = None) -> None |
Execute the main node logic. This is called when execution is requested | Each incoming Start/IfTrue/IfFalse/InLoop/BreakLoop/Error trigger (or an explicit Run). |
on_get_configuration() -> MessageMap[str, NodeConfigEntry] |
Get node configuration to be displayed in the UI | InitializeNode, before any configure — returns the typed defaults the UI renders. |
Optional — override when you need them (defaults are safe no-ops):
| Hook | Purpose | Called on |
|---|---|---|
on_stop_execution(trigger_context: Optional[TriggerContext] = None) -> None |
End the current run (soft stop); configured resources stay for on_cleanup. |
StopExecutionNode (soft stop) and as the first step of every hard stop — at most once per run, also on an idle node (since SDK 2.43.0). |
on_stop(trigger_context: Optional[TriggerContext] = None) -> None |
Deprecated since SDK 2.43.0; use on_stop_execution and on_cleanup. |
Deprecated since SDK 2.43.0. Hard stop (StopNode, StopAndCleanupNode, re-Initialize) after the SDK teardown and before on_cleanup() — once per lifecycle. Move the body to on_stop_execution() / on_cleanup(). |
on_pause() -> None |
Called when the node is paused. Suspending real work is up to the node; the SDK keeps delivering | PauseNode, only when the state actually transitions to PAUSED (since SDK 2.39.0). |
on_resume() -> None |
Called when the node is resumed. Restart whatever on_pause() stopped. | ResumeNode, only when the node was paused. |
on_toggle_simulation_mode(is_simulation: bool) -> None |
Called when simulation mode is toggled. Override to react to simulation/read mode change. | ToggleSimulationMode — the graph switched between real and simulation mode. |
on_health_check() -> bool |
Called when NES polls health. Override to report custom health status. returns True by defualt. | Once after ConfigureNode, then every health_stream_check_interval_s seconds. |
on_cleanup() -> None |
Release everything the node acquired: the counterpart of Initialize/Configure. | Final step of the hard stop (StopNode, StopAndCleanupNode, re-Initialize), after the SDK transports are gone — once per lifecycle. The counterpart of Initialize/Configure. |
on_get_data_visualization_topics() -> NodeVisualizationsTopics |
Get remaining visualizations other than outputs, to be displayed on UI | GetDataVisualizationTopics / StartNodeDataVisualization — extra topics besides your output ports. |
on_start_data_visualization(topic_names: list[str]) -> None |
Called when live data visualization streaming starts for this node. | StartNodeDataVisualization — a viewer started streaming this node. |
on_stop_data_visualization() -> None |
Called when live data visualization streaming stops for this node. | StopNodeDataVisualization — the last viewer left. |
What the required hooks receive and return¶
| Hook | Argument or return value | Notes |
|---|---|---|
on_configure(config, dynamic_config=None) |
config is the static string map from the schema's configuration block (ScalarMap[str, str]); dynamic_config holds the typed values the user set in the UI (MessageMap[str, NodeConfigEntry]) or None |
Runs on every Configure, before any execution. Parse strings here and store the results on self. |
on_execute(trigger_context=None) |
TriggerContext with source_node, timestamp and optional err_info, or None when the node was run without a trigger |
Runs once per incoming trigger on the node's own executor thread. Wrap the body in try/except and raise NodeExecutionError. |
on_stop_execution(trigger_context=None) |
Same TriggerContext shape, or None |
Optional. Ends the current run: make a blocking on_execute return, stop per-run work. Called at most once per run, also when the node is idle. |
on_cleanup() |
none | Optional. Releases what on_configure acquired. Final step of the hard stop, exactly once per lifecycle, after the SDK transports are gone. |
on_stop(trigger_context=None) |
Same TriggerContext shape, or None |
Deprecated since SDK 2.43.0, no longer required. Still runs once per lifecycle on the hard stop, before on_cleanup(); a failure inside it is logged, never propagated. Move its body to on_stop_execution() / on_cleanup(). |
on_get_configuration() |
Returns {key: NodeConfigEntry}, typed entries the UI renders as form fields |
Called on Initialize, before any Configure. Return {} when the node has no user-facing settings. Never return plain strings. |
trigger_context can be None in every hook that takes it. Always check before reading it.
The number-one copy-paste crash¶
The SDK always calls on_configure with two positional arguments: the static map and the typed map. An override with only one parameter raises TypeError on the first Configure and puts the node into the error state.
| You wrote | What happens on Configure |
|---|---|
on_configure(self, config) |
TypeError, node goes to ERROR |
on_configure(self, config, dynamic_config=None) |
Works, both maps arrive |
on_execute, on_stop_execution and on_stop are more forgiving. The SDK inspects the override and calls it with trigger_context only when it declares a parameter, so an old zero-argument on_execute(self) still runs. Write the full signature anyway; the context is the only way to tell a normal run from an error-triggered one. See Triggers.
Which optional hook for which job¶
is_run_active() reports whether the configured target still accepts work.
It becomes false when Stop is accepted and true after successful Configure.
A cooperative execution loop can use it to exit when its target stops.
It does not initialize or re-arm the node.
| You want to | Override | Read |
|---|---|---|
| Stop motors, close sockets or pause a publisher while the graph is paused | on_pause() and on_resume(), or poll self.is_paused() |
Lifecycle and states |
| Switch between real hardware and a simulated device | on_toggle_simulation_mode(is_simulation) |
Simulation mode |
| Report a device or connection problem to the UI | on_health_check() -> bool, optionally set self._health_check_message |
Health reporting |
End a running on_execute when the graph is stopped, keeping the node ready for the next run |
on_stop_execution(trigger_context) |
Lifecycle and states |
Release what on_configure() acquired when the node is torn down |
on_cleanup() |
Lifecycle and states |
| Offer extra live views besides your output ports | on_get_data_visualization_topics(), on_start_data_visualization(topic_names), on_stop_data_visualization() |
Data visualization |
| Download models or warm caches once per service, before any node exists | NodeServiceBase.on_prepare_node_dependencies() registered with set_node_service_class |
Service-level hooks |
Pause is cooperative. The SDK keeps delivering triggers and data while the node is paused and calls on_pause() only on the call that actually transitions the node. Suspending real work is your job; self.is_paused() is the polling API. Older SDKs have no is_paused().
The schema file next to the module¶
Each node class ships a JSON schema file that the SDK loads at startup and registers, so the graph editor can show the node with its ports before any instance is configured. The lookup rule is fixed:
- The file is named
<module>_schema.jsonand sits in the same directory as<module>.py. Foruppercase_node.pythat isuppercase_node_schema.json. - The SDK locates it through the class's module file. A missing or unparsable file produces a warning and an empty schema, so the node registers without ports.
executionContext.classNamemust equal the Python class name. The engine sends this value back on Configure to pick the class inside your service. The SDK overwrites the field with the real class name when it registers the schema, so the registered value is always right; a wrong value in the file is not caught by any tool, it only misleads whoever reads the file.- The class name appears nowhere else in the schema.
nameis the display name in the palette (it defaults to the class name when empty),idis the palette category you choose, anddescriptiondefaults to the class docstring.
The quickstart node's schema, with the port keys the schema convention prescribes:
{
"id": "Examples",
"name": "Uppercase Node",
"type": 1,
"description": "Reads a text message and publishes it in upper case",
"tags": ["example", "quickstart"],
"inputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"stop": { "rosType": "Stop", "edgeType": 2 },
"text_input": { "rosType": "std_msgs/msg/String", "edgeType": 1 }
},
"outputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"error": { "rosType": "Error", "edgeType": 2 },
"text_output": { "rosType": "std_msgs/msg/String", "edgeType": 1 }
},
"executionContext": {
"type": 3,
"target": "",
"className": "UppercaseNode"
}
}
Trigger ports carry the trigger type name in rosType (Start, Stop, Error), data ports carry the ROS 2 type (std_msgs/msg/String). Inputs declare start and stop; outputs declare start and error and no stop output.
Registering and starting: run_nodes.py¶
The node service does not scan your source tree. You tell it which classes to host, then hand over control:
from neuraverse_sdk.node_manager_service import run, set_node_classes
from uppercase_node.uppercase_node import UppercaseNode
def main() -> None:
set_node_classes([UppercaseNode])
run()
if __name__ == "__main__":
main()
set_node_classes([...])must be called beforerun(). Starting without classes raisesRuntimeError.run()starts the gRPC and HTTP servers, blocks until the service terminates, then ends the process. Put nothing after it.set_node_service_class(MyService)is optional. It registers aNodeServiceBasesubclass with service-level hooks; without it the SDK uses a no-op default. See Service-level hooks.- The SDK also installs a console script,
neuraverse-node-sdk, that runs the samerun()function. It is only useful when a wrapper module has already calledset_node_classes; the template'srun_nodes.pyis the simpler entry point and its Docker image runspoetry run python src/run_nodes.py.
Template helpers are not SDK API
The node template ships src/node_utils.py with set_env_defaults() (fills service-name and config-path environment variables from pyproject.toml) and discover_node_classes(src_dir) (imports every module under src/ and collects NodeBase subclasses). Both are plain helper functions in the template, not part of neuraverse_sdk. Explicit set_node_classes([...]) is the documented way to register nodes.
Every class you register also needs a packages entry in pyproject.toml so it is installed into the image. See Project layout and build.
Rules every node follows¶
| Rule | Why |
|---|---|
Call super().__init__() and keep __init__ free of side effects (no sockets, no hardware, no threads) |
The SDK instantiates every registered class once at service startup to build its schema (that instance also serves the first graph node of the class) and once more for every further graph node. All real setup belongs in on_configure(), which receives the configuration. |
Log with self.log_info(), self.log_warning(), self.log_error(message, exception=None) or self.log_debug(), never print() |
The SDK methods write to the service logger the platform configures for the node process. print() output bypasses that logger. |
Wrap the body of on_execute in try/except and raise a typed error from Errors |
Any exception escaping on_execute fires the error trigger and moves the node to ERROR. Raising a typed error yourself also gives the caller an accurate status, a safe message and retry advice; anything else arrives as a bare NodeExecutionError. |
| Add type hints to every hook | The SDK counts the parameters of on_execute, on_stop_execution, on_stop and trigger handlers to decide how to call them; an explicit, typed signature makes that decision visible. |
Set node_version = "1.2.0" as a class attribute when your node needs its own version |
Without it the registered version falls back to the service descriptor version, and to 1.0.0 when that is empty too. get_node_version() returns the value that was registered. |
Keep on_execute bounded |
It runs on a single-worker executor per node. While one run is in progress, further triggers queue behind it. |
Where to next¶
- Lifecycle and states: what the engine calls, in which order, and what runs on which thread.
- Dataflow: ports, messages and the exact behaviour of
get_dataandpublish. - Triggers: built-in and custom triggers, and
trigger_context. - Configuration: static strings versus typed UI entries.
- Errors: which error to raise from a hook and what the caller receives.
- Testing: drive a node with a fake dataflow, without ROS.