Skip to content

Architecture

How the Python Node SDK (2.43.0) turns a NodeBase subclass into a node service that the Node Engine can initialize, configure, run, pause and stop over gRPC. This page is for the nodegraph platform team: it maps the components, lists the platform-facing NodeBase surface with its real signatures, gives the complete state-transition table, the threads and queues, the bootstrap sequence, the exception hierarchy, and where the C++ SDK matches or deviates. Node authors start at Node anatomy and Lifecycle and states instead; nothing on this page is needed to write a node.

Component map

SDK 2.45.0 extends external input dispatch with separate tracked workers for custom callbacks and Stop. Custom callbacks can interrupt or unblock ordinary execution; they do not wait in its queue. Stop closes admission immediately, and its asynchronous hook retains the normal once-per-lifecycle guard. Configure advances the generation and waits for a pending Stop before replacing node state. Native Stop uses the same tracked worker; Configure also serializes with direct teardown. Completion from an old execution cannot change a replacement run’s status or emit automatic Start, Stop or Error triggers. Stop retains the 2.x teardown order and cancels pending input callbacks. The C++ controller drains owned nodes before derived object destruction. Reconfiguration restores input admission; no ArmNodeForRun or CleanupNode API is introduced.

flowchart TB
    subgraph API["API layer"]
        GRPC["NodeServiceApi (gRPC servicer)<br/>api/grpc/router/node_router.py"]
        HTTP["FastAPI app<br/>GET / pong, nodeRouter, admin router /admin/*"]
    end
    subgraph CTRL["Controller layer (controllers/node_controller.py)"]
        NC["NodeController<br/>status and health queues, fan-out, heartbeat, viz streamers"]
        NR["NodesRegistry<br/>{class: [[instance, wire_id], ...]}"]
    end
    subgraph CORE["Core: one NodeBase instance per bound wire id"]
        NB["NodeBase subclass"]
        SM["StateMachine<br/>state_machine.py"]
        CDF["CompositeDataFlow"]
        ROS["ROSDataFlowAdapter"]
        MQ["MQTTDataFlowAdapter"]
        ZDF["ZenohDataFlowAdapter"]
        TRG["ITrigger: MQTTTriggerAdapter<br/>(ZenohTriggerAdapter exists, not selected)"]
        SRR["ServiceRegistryRepository"]
        SBC["SceneBuilderClient"]
        PSC["ProjectSceneClient<br/>(when project_service_v2_endpoint is set)"]
        DRC["DataRepositoryClient"]
    end
    DVS["DataVisualizationStreamer<br/>streaming/data_visualization_streamer.py"]
    SRC["ServiceRegistryClient<br/>one per (endpoint, token) per process"]
    MH["MQTTHandler singleton<br/>utils/mqtt_singleton.py"]
    ZH["ZenohHandler<br/>one session per adapter"]
    GRPC --> NC
    HTTP --> NC
    NC --> NR --> NB
    NC --> DVS --> LK[(LiveKit)]
    NB --> SM
    NB --> CDF
    CDF --> ROS --> DDS[(ROS 2 / DDS)]
    CDF --> MQ --> MH
    CDF --> ZDF --> ZH --> ZR[(Zenoh router)]
    NB --> TRG --> MH --> Broker[(MQTT broker)]
    NB --> SRR --> SRC --> Consul[(Consul agent)]
    NB --> SBC --> SB[(scene-builder-backend)]
    NB --> PSC --> PV2[(project-v2 SceneApi)]
    NB --> DRC --> NE[(node engine key/value store)]
Module Role
node_manager_service.py run(), set_node_classes(), set_node_service_class(), the NodeManagerService bootstrap (DI wiring, gRPC and HTTP servers, forced exit).
node_base.py NodeBase: author hooks, the platform-facing lifecycle methods, dataflow and trigger passthroughs, health monitor, schema loading, Consul registration, scene-builder and data-repository helpers, visualization caches.
node_service_base.py NodeServiceBase.on_prepare_node_dependencies() (class method, service level).
state_machine.py, state_machine_mock.py State pattern with six State classes; the mock emits random states when NEURAVERSE_SDK_MOCK_STATUS is set.
dataflow/ IDataFlow, CompositeDataFlow, ROS, MQTT and Zenoh adapters, DataFlowFactory, _import_msg_type. See Transports.
trigger/ ITrigger, TriggerType, TriggerContext, trigger_handler, MQTT and Zenoh trigger adapters, TriggerFactory.
controllers/ NodeController, NodesRegistry, ServiceRegistryRepository (shared-client cache).
api/grpc/router/node_router.py NodeServiceApi, the gRPC servicer. api/grpc/clients/ holds the scene-builder, project-v2 scene (ProjectSceneClient) and data-repository clients.
api/http/ FastAPI app, empty nodeRouter, admin router (/admin/*) with allowlist and audit log.
api/consul/clients/service_registry_api.py ServiceRegistryClient: Consul registration, KV writes, registration monitor. See Registration and discovery.
streaming/data_visualization_streamer.py LiveKit publisher used by the controller for data visualization.
models/config/ NodeServiceConfig, MQTTConfig, ZenohConfig, RegistryConfig (pydantic settings).
utils/ exceptions, MQTTHandler, ZenohHandler, get_config_value, robot pose helpers, connection pool, proto helper.

The platform-facing NodeBase surface

The engine never calls author hooks directly. It calls the gRPC servicer, which calls NodeController, which calls one of these NodeBase methods. All of them live in node_base.py; the author hooks they wrap are documented in the guide.

Method Called by What it does
register_node(node_service_config) NodesRegistry.add_node_class() at bootstrap and whenever a fresh instance is minted Stores the service config and registers the class with Consul (service capability-<ClassName>, schema envelope in KV). Skips silently when registry_config.registry_endpoint is empty.
initialize(status_queue, node_id, health_queue=None) NodeController._initialize_node_locked() Resets the stop flags, stores both queues and the wire id, replaces the single-worker execute executor, calls state_machine.initialize(), creates the MQTT trigger adapter (connects, blocking 10 s) and wires its callbacks, creates the CompositeDataFlow, initializes the scene client (ProjectSceneClient when project_service_v2_endpoint is set, else the scene-builder client) and, only when node_engine_endpoint is set, the data-repository client. Any exception moves the node to ERROR and is re-raised. Returns True.
configure(node_info) NodeController.configure_node() Re-arms _auto_trigger and the stop flags, recreates the executor if it was shut down, configures the dataflow entry and the trigger entry, stores the port maps, calls on_configure(node_info.configuration, node_info.dynamicConfiguration or None), transitions to CONFIGURED, pushes the first health snapshot and starts the health monitor. Exception: ERROR, re-raise.
execute(trigger_context=None) The execute executor (via _submit_execute), execute_background(), and execute_node() One run. Drops the call when _stop_completed is set (stale Start). Transitions to RUNNING, calls on_execute(trigger_context=...) when supports_argument(on_execute) is true and on_execute() otherwise, transitions back with state_machine.configure(), then fires every declared Start output and every declared Stop output with a fresh TriggerContext(source_node=<ClassName>). On exception: fills err_info, fires the Error outputs if declared, moves to ERROR, raises NodeExecutionError.
execute_background() NodeController.execute_node_background() (the RunNode RPC) Starts a daemon threading.Thread(target=self.execute) and returns True immediately. This thread is separate from the execute executor that trigger callbacks use.
stop_execution(trigger_context=None) NodeController.stop_execution_node() (StopExecutionNode), the first step of stop(), and _submit_stop for an incoming Stop trigger on a node that overrides on_stop_execution Soft stop. Under _hook_lock: closes the run latch (_run_active=False), bumps _execution_generation, and, once per run (_stop_execution_called_for_run), calls resume() and then on_stop_execution(trigger_context=...). No teardown, no join, no state-machine transition. An author exception becomes NodeStopError. Since 2.43.0.
stop_and_cleanup(trigger_context=None) NodeController.stop_and_cleanup_node() (StopAndCleanupNode), stale-generation release stop_execution(), then stop(), whose _stop_lifecycle does the bounded wait for on_execute (C++: stopForGeneration). Since 2.43.0.
arm_for_run(supports_graph_stop_request=False) NodeController.arm_node_for_run() (ArmNodeForRun) and configure() Reopens the run latch, bumps the generation and resets the per-run hook guard, and records the engine's graph-stop-request advertisement for the run. Raises NodeStopError when _stop_completed is set. Since 2.43.0; the keyword since 2.50.0.
stop(trigger_context=None) NodeController.stop_node() (deprecated StopNode), the tail of stop_and_cleanup(), _initialize_node_locked() before re-init, and _submit_stop for an incoming Stop trigger on a node that still relies on on_stop The hard-stop chain, idempotent through _stop_completed. Runs stop_execution() first (guarded once per run), then _wait_for_on_execute_to_leave(stop_execution_join_timeout_s) (default 5 s; waits on the in-flight tracker of threads inside on_execute, excludes the calling thread, warns and continues on timeout; since 2.46.2), clears _auto_trigger, then under _hook_lock runs each teardown step in isolation (failures collected): data-repository close, state_machine.stop(), end_status_stream(), _end_health_stream() (joins the monitor thread), data_flow.destroy(), trigger.destroy(), executor.shutdown(wait=False, cancel_futures=True), scene-builder close. From a finally: on_stop() exactly once through _invoke_on_stop_once() (deprecated), then on_cleanup() as the final step. Collected failures move the node to ERROR and raise NodeStopError. Consul monitoring is deliberately untouched. Since 2.43.0 on_cleanup() runs last instead of before the transport destroy.
pause() -> bool NodeController.pause_node() if state_machine.pause(): on_pause(); always returns True. A raising on_pause() becomes NodePauseError without changing the state.
resume() -> bool NodeController.resume_node() Same shape with state_machine.resume() and on_resume(); raises NodeResumeError.
toggle_simulation_mode(is_simulation) NodeController.toggle_simulation_mode() (SetToggleSimulationMode) Logs and calls on_toggle_simulation_mode(is_simulation); raises NodeSimulationModeError.
get_health_check() -> tuple[bool, str] GetHealthCheck, the health monitor thread, _push_current_health() Clears _health_check_message, calls on_health_check(), returns (is_healthy, message) where the message is the author's _health_check_message or "Healthy" / "Unhealthy". Never raises: an exception returns (False, "Health check failed: ...").
get_configuration() InitializeNode (through _initialize_node_locked) and GetNodeConfiguration Returns on_get_configuration(); wraps failures in NodeConfigurationError.
get_schema() Registration (_build_schema_envelope) Loads the sibling <module>_schema.json (located with inspect.getfile), fills name and description when empty and always overwrites executionContext.className with the class name. Never raises; a missing or unparsable file yields an empty Node.
get_data_visualizations_topics() NodeController.get_data_visualization_topics() (GetDataVisualizationTopics) Merges on_get_data_visualization_topics() with every output port whose ROS type is not in _NON_VISUALIZABLE_TYPES; topicName is livekit_safe_viz_name(topic). Failures raise NodeStateError.
supports_argument(func) (static) execute(), stop_execution(), _invoke_on_stop_once(), _normalize_trigger_handler() inspect.signature: true when the callable takes any parameter besides self. This is what keeps zero-argument on_execute() / on_stop_execution() / on_stop() overrides working.
is_run_active() Authors The run latch: True from arm/configure until stop_execution(). Independent of the state-machine value.
trigger_handlers (property) Tests and tooling A copy of the {trigger type name: normalized callback} map collected from @trigger_handler methods and register_trigger_handler() calls. initialize() and configure() hand the live map to the trigger adapter with set_named_trigger_callbacks().
send_health_update(is_healthy, message) Health monitor, authors Puts {"nodeId", "isHealthy", "resultMessage"} on health_queue when the snapshot changed. See Status and health streams.
is_paused() Authors state_machine.get_state() == EXECUTION_STATE_PAUSED.

Two callbacks deserve a note. The trigger adapter's execute callback is _submit_execute, not execute: it captures the current _execution_generation and submits _execute_if_current(generation, trigger_context) to the single-worker executor so the MQTT network thread is never blocked; the trigger is dropped when the run latch is closed, the node is stopped, has no executor, or the executor is shut down, and the queued work is dropped again at the executor boundary when a stop or re-arm happened in between. Custom @trigger_handler callbacks are wrapped the same way (_gated_trigger_handlers). The stop callback is _submit_stop: for a node that overrides on_stop_execution it calls stop_execution() (dropped when the run is already inactive); for a node that still relies on the deprecated on_stop it calls the hard stop(), so such a node keeps its pre-2.43 behaviour. _uses_legacy_stop_hook() is the predicate, and register_node() logs a deprecation warning for it.

State machine

StateMachine (state_machine.py) holds the current State object and guards every call with an RLock. Concrete states decide what each call does; transition_to() swaps the object, logs, and pushes a status dict onto the status queue. Since 2.39.0 pause() and resume() return whether this call transitioned, and PausedState carries the state to return to.

Every cell below is read from the State subclasses in state_machine.py. "stay" means no transition and no error; "raise" means NodeStateError.

State \ call initialize() configure() execute() pause() -> bool resume() -> bool stop() error() reset()
IDLE stay (logs) -> CONFIGURED raise stay, False stay, False stay (logs, stream not ended) -> ERROR raise
CONFIGURED stay stay -> RUNNING -> PAUSED (resume target CONFIGURED), True stay, False -> STOPPED, ends status stream -> ERROR raise
RUNNING raise -> CONFIGURED stay -> PAUSED (resume target RUNNING), True stay, False -> STOPPED, ends status stream -> ERROR raise
PAUSED raise stay PAUSED, resume target becomes CONFIGURED stay PAUSED, resume target becomes RUNNING stay, False -> remembered state, True -> STOPPED, ends status stream -> ERROR raise
STOPPED -> IDLE -> CONFIGURED -> RUNNING stay, False stay, False stay -> ERROR raise
ERROR -> IDLE -> CONFIGURED (logs) raise stay, False stay, False -> STOPPED, ends status stream stay (logs the additional error) -> IDLE

What follows from the table:

  • STOPPED is not terminal. configure() re-arms the node and initialize() takes it back to IDLE; the controller relies on both for the stop, re-init and re-configure cycles.
  • execute() from IDLE or ERROR raises NodeStateError. NodeBase.execute() turns that into NodeExecutionError, fires the Error output when one is declared, and parks the node in ERROR; configure() is the recovery path.
  • PAUSED remembers where to resume. A blocking on_execute() that returns while paused calls configure() and only changes the target to CONFIGURED; an incoming trigger that calls execute() only changes it to RUNNING. The node stays PAUSED, so is_paused() keeps returning True for the author's own guard.
  • pause() and resume() never raise from any state; the return value is what NodeBase uses to decide whether on_pause() / on_resume() fire.
  • reset() has no caller outside state_machine.py; nothing in the gRPC surface reaches it.
  • initialize() from RUNNING or PAUSED raises. The controller avoids it by calling stop() on the instance before initialize().

Pause is cooperative and never errors a node: CONFIGURED and RUNNING pause, IDLE, STOPPED and ERROR are silent no-ops, and resume returns to the state the node paused from. Before 2.39.0 pause() outside RUNNING raised NodeStateError and resume always landed in RUNNING.

Every transition produces one status dict (StateMachine.send_status_message), put on the status queue without blocking; a full queue drops the item with a warning:

{
  "nodeId": "<wire id>",
  "state": "<ExecutionState enum value>",
  "resultCode": 0,
  "resultMessage": "State of node with ID <id> changed from EXECUTION_STATE_X to EXECUTION_STATE_Y | Message: <optional>"
}

resultCode is 1 only when the target state is ERROR. The stop transitions call end_status_stream(), which puts the None sentinel and drops the queue reference. How these items reach gRPC subscribers is on Status and health streams.

NEURAVERSE_SDK_MOCK_STATUS=1 (also TRUE / YES) makes _create_state_machine() return MockRandomStateMachine from state_machine_mock.py, which emits random states for UI triangulation. It is evaluated once per NodeBase construction.

Threads and queues

Thread Created by Runs
gRPC worker pool, grpc_server_max_workers threads (default 50) NodeManagerService.start_grpc_service() Every RPC handler. Each open status or health stream pins one worker for its whole lifetime; the engine opens both per initialized node, so this setting bounds the node count one service can serve.
asyncio main thread (uvicorn) bootstrap_service() under asyncio.run The HTTP and admin API.
<ClassName>-execute (a ThreadPoolExecutor with one worker) initialize(), recreated by configure() when shut down execute() for trigger-driven runs, one at a time per node. stop_execution() leaves it running; stop() shuts it down without waiting and cancels queued futures; stop() first waits bounded for the in-flight tracker to empty, so no on_execute is inside the hook when it shuts down.
unnamed daemon thread execute_background() One execute() per RunNode RPC.
paho network thread (one per process) MQTTHandler.connect() via loop_start() Every MQTT delivery: trigger callbacks (_submit_execute, _submit_stop, gated custom @trigger_handler methods), MQTT dataflow _save_data, register_handler callbacks for MQTT ports.
ros-dataflow-spin (daemon), one per ROS adapter ROSDataFlowAdapter._init() SingleThreadedExecutor.spin(); ROS subscription callbacks and the register_handler callbacks for ROS ports run inline.
health-monitor-<node_id> (daemon) configure() through _start_health_monitor() get_health_check() every health_stream_check_interval_s (default 10 s) and send_health_update().
Two fan-out threads per node (daemon) NodeController.__get_status_queue() and __get_health_queue() Copy each main-queue item to every subscriber queue and record the replay snapshot.
status-heartbeat-<node_id> (daemon) NodeController._start_heartbeat() Re-emits the last status after status_stream_heartbeat_interval_s (default 1 s) of silence.
ConsulHealthCheck (daemon), one per shared registry client ServiceRegistryClient._start_health_check_monitoring() Validates all registrations every 30 s.
LiveKit streamer threads DataVisualizationStreamer Data visualization; out of scope for this page.

Queues: one status_queue and one health_queue per bound wire id (created by the controller, handed to initialize()), plus one queue.Queue per open gRPC stream subscriber. None is the end-of-stream sentinel everywhere. The controller serializes InitializeNode, ConfigureNode, StopNode, StopExecutionNode, StopAndCleanupNode and ArmNodeForRun per wire id with _lock_for_node(); NodeBase has _lifecycle_lock (flags) and _hook_lock (hook ordering); StateMachine has its own RLock. Which thread calls which author hook is tabulated in Lifecycle and states.

Controller layer

NodeController is built during DI wiring with the node classes, the NodeServiceConfig and the NodeServiceBase subclass (kept as a class, never instantiated). Its constructor calls NodesRegistry.add_node_class() for every class, which instantiates the class once and calls register_node(); that is the moment Consul registration happens, before any server exists.

NodesRegistry keeps {node_class: [[instance, wire_id], ...]}. bind_node_instance_with_id() returns early when the wire id is already bound (engine retry), reuses the seeded [instance, None] row for the first init, and otherwise mints a fresh instance and registers it again (an idempotent Consul overwrite). get_node_object() returns the first row with a matching wire id or raises NodeNotFoundError; remove_node_by_id() drops the row on a successful stop and keeps the class key.

The engine mints a fresh wire id {uuid}:{node_id} per configure cycle and never sends StopNode for the previous one. initialize_node() therefore first calls _release_stale_generations(): every row whose _logical_node_id() matches but whose wire id differs is hard-stopped (stop_and_cleanup()), its streams are ended with the sentinel, its queues, heartbeat and replay snapshots are dropped and its rows removed. Then, under the per-node lock, _initialize_node_locked() binds the class, calls stop() on the instance, creates a fresh status queue (fan-out plus heartbeat) and a fresh health queue (fan-out), calls initialize(status_queue, node_id, health_queue=health_queue), sets the project id and returns get_configuration() as the InitializeNode response payload.

configure_node() self-heals a ConfigureNode that arrives without a paired InitializeNode by auto-initializing with node_info.executionContext.className, recreates missing queues, and on failure drops queues, heartbeat and replay snapshots before re-raising. stop_node() (deprecated StopNode) and stop_and_cleanup_node() share _release_node_locked(): move any visualization streamer to passive mode, call stop() or stop_and_cleanup(), drop the same bookkeeping and remove the registry row; a retry after the row is gone is treated as success. stop_execution_node() only calls stop_execution() and leaves the row, queues and heartbeat in place, so the node stays addressable for the next Run. arm_node_for_run() calls arm_for_run(), passing on whether the engine advertised that it acts on graph stop requests. prepare_node_dependencies() calls NodeServiceBase.on_prepare_node_dependencies(configuration) as a class method.

API layer

gRPC: NodeServiceApi

Every method is decorated with @authenticated() and BaseApiServicerV2.grpc_api_method, which builds the ExecutionContext. Unary handlers run through a tenacity @retry (two attempts, only for exceptions flagged is_retryable) and _handle_rpc, which calls to_neura_grpc_error (see The gRPC error boundary). The server is created with GrpcUnhandledExceptionInterceptor, ExceptionToStatusInterceptor and JWTAuthInterceptor(unauth_methods), enables reflection and listens on an insecure port at grpc.address:grpc.port.

RPC Controller call
InitializeNode initialize_node(project_id, node_id, class_name); validates that projectId, nodeId and className are present. The response carries lifecycleProtocolVersion = 1 (LIFECYCLE_PROTOCOL_VERSION): this SDK implements ArmNodeForRun, StopExecutionNode and StopAndCleanupNode. The engine uses it to pick a compatible verb, never to reject a node.
ConfigureNode configure_node(node_info)
RunNode execute_node_background(node_id)
StopNode (deprecated) stop_node(node_id)
StopExecutionNode stop_execution_node(node_id)
StopAndCleanupNode stop_and_cleanup_node(node_id)
ArmNodeForRun arm_node_for_run(node_id)
PauseNode / ResumeNode pause_node() / resume_node()
SetToggleSimulationMode toggle_simulation_mode(node_id, is_simulation)
GetHealthCheck get_health_check(node_id)
GetNodeConfiguration get_node_configuration(node_id)
SubscribeNodeStatusStream / SubscribeNodeHealthStream subscribe_node_status_stream() / subscribe_node_health_stream() generators, see Status and health streams
GetDataVisualizationTopics get_data_visualization_topics()
StartNodeDataVisualization / StopNodeDataVisualization start_data_visualization() / stop_data_visualization()
PrepareNodeDependencies prepare_node_dependencies(cntx, configuration) with the request map decoded to plain values
GetNodeMetrics, GetNodeLogs Raise NotImplementedError.
GetNodeStatus Declared in the proto, not overridden by the SDK servicer (gRPC answers UNIMPLEMENTED).

HTTP: FastAPI

api/http/http_api.py builds one app with docs_url=None and openapi_url=None. GET / answers a small "pong" page, nodeRouter declares no routes, and BaseNeuraFastAPIMiddleware answers unknown paths with 400. The admin router (api/http/admin/router.py, prefix /admin) exposes whoami, node/status, nodes, nodes/{node_id}/state and nodes/{node_id}/diag, all read-only and guarded by RequireAdmin("read"): the Auth0 JWT proves identity, AdminAllowlist (YAML at NEURAVERSE_ADMIN_ALLOWLIST_PATH, reloaded on SIGHUP) grants scopes, and every call emits one nodectl.audit log event. Every node container inherits this surface.

Bootstrap

sequenceDiagram
    participant S as run_nodes.py
    participant R as node_manager_service.run
    participant B as BaseNeuraverseService
    participant I as inject binder
    participant C as NodeController / NodesRegistry
    participant K as Consul
    S->>R: set_node_classes([...]), set_node_service_class(...) optional, run()
    R->>B: asyncio.run(bootstrap_service()): register_service_type(), create_instance()
    R->>B: service.configure(NodeServiceConfig())
    B->>B: _on_configure_logging, _on_configure_metrics (Prometheus endpoint)
    B->>I: inject.configure(_on_configure_injection)
    I->>I: bind NodeServiceConfig, GrpcConfig, HttpConfig, JwtConfig, LogConfig, MetricsConfig, ServiceInfo, JwtValidator, AdminAllowlist, NodeBase classes
    I->>C: NodeController(node_classes, config, node_service_class)
    C->>C: add_node_class per class: instantiate, register_node()
    C->>K: register capability-<Class> (bootstrap retry budget), KV writes, start monitor
    R->>B: service.start(): _serve_grpc() then await serve_http()
    R->>B: service.wait_for_termination()
    R->>R: _force_exit(0 or 1)

Order matters: registration runs inside DI wiring, before service.start() opens the gRPC and HTTP ports. _on_configure_injection raises RuntimeError when set_node_classes() was not called, and NodeController construction is where every node class is instantiated once (author __init__ must therefore stay side-effect free).

Two bootstrap guarantees. First, the process's first Consul registration retries transport errors with exponential backoff (initial registry_config.registration_retry_delay_s, default 2 s, doubling to a 60 s cap) for up to registry_config.registration_timeout_s (default 120 s); a registration that never succeeded is not recorded and starts no monitor. Second, run() catches everything around asyncio.run(bootstrap_service()), logs, and calls _force_exit(): logging.shutdown(), flush, then os._exit(1) on failure and os._exit(0) on a clean return or KeyboardInterrupt. Non-daemon threads (logging, transports, node workers) can no longer keep a bootstrap-failed process alive, so Kubernetes restarts the container instead of leaving a zombie. Details on Registration and discovery.

NodeServiceConfig (models/config/node_service_config.py) extends the common BaseServiceConfig with mqtt, zenoh, registry_config, service_descriptor, container_name, scene_builder_endpoint, project_service_v2_endpoint, project_service_v2_use_tls, node_engine_endpoint, node_engine_use_tls, livekit_url, status_stream_heartbeat_interval_s, health_stream_check_interval_s, escalate_unhealthy_to_error, unhealthy_escalate_after_s, grpc_server_max_workers and viz_sources_ready_timeout_s. The author-facing view of the YAML is service_config.yaml reference.

Exception hierarchy

Node-author errors live in models/errors/ (NodeError, SDKError, factories). The gRPC conversion is The gRPC error boundary. The SDK's own internals still raise the older NodeSDKError(message, error_code) family in utils/exceptions.py. That table is generated from the source:

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

Where each one comes from in 2.40.0:

Exception Raised by
NodeConfigurationError get_configuration() wrapping a failing on_get_configuration(), NodeController.configure_node() when configure() returns False, and @trigger_handler misuse (built-in name, duplicate) at node instantiation.
NodeExecutionError execute() for any failure inside a run; NodeController.execute_node*() when the call returns False.
NodeStopError, NodePauseError, NodeResumeError, NodeSimulationModeError The corresponding NodeBase methods when a teardown step or an author hook raised.
NodeHealthCheckError Declared for NodeController.get_health_check(); get_health_check() itself never raises, so it is effectively unused.
NodeStateError StateMachine on invalid transitions; NodeBase getters used before configure (get_node_id, get_connected_ports, ...); get_frames / get_robots / get_paths and get_data_visualizations_topics() on failure.
NodeNotFoundError NodesRegistry lookups (_get_class_instance, get_node_object) and the stream subscriptions for an unknown wire id.
NodeRegisteryError ServiceRegistryRepository.register_node() for an invalid endpoint or any Consul failure.
InvalidEndpointError Declared and imported by the registry repository but not raised anywhere in 2.40.0; invalid endpoints surface as NodeRegisteryError.
DataFlowException Unknown output target, invalid ROS type string in _import_msg_type, MQTT subscribe failure, ROS node not initialized.
TriggerFlowException Unknown trigger port or type, a custom input type without a handler, subscribe failure, and MQTTHandler misuse (not configured, refusing a second broker).
RobotException utils/robot_utils.py pose conversion helpers.

At the gRPC boundary _handle_rpc converts both families through to_neura_grpc_error; the interceptors turn that into a gRPC status. The factory tables for the new families:

SDKLifecycleError: A lifecycle transition or mode change could not be completed.

Factory Error code gRPC status Raise it when Caller sees by default
SDKLifecycleError.invalid_state(msg) err.sdk.lifecycle.invalid_state FAILED_PRECONDITION The node's current state does not allow the requested operation. The node is in an invalid state for this operation.
SDKLifecycleError.initialize(msg) err.sdk.lifecycle.initialize INTERNAL Initialization failed - the node class could not be brought into existence. Node initialization failed.
SDKLifecycleError.configure(msg) err.sdk.lifecycle.configure INTERNAL Configuration failed - on_configure raised, or the SDK could not apply it. Node configuration failed.
SDKLifecycleError.execute(msg) err.sdk.lifecycle.execute INTERNAL Execution failed - the run path raised before or inside on_execute. Node execution failed.
SDKLifecycleError.stop(msg) err.sdk.lifecycle.stop INTERNAL Stopping failed - the node may be left holding resources. Node stop failed.
SDKLifecycleError.pause(msg) err.sdk.lifecycle.pause INTERNAL Pausing failed - on_pause raised. Node pause failed.
SDKLifecycleError.resume(msg) err.sdk.lifecycle.resume INTERNAL Resuming failed - on_resume raised. Node resume failed.
SDKLifecycleError.mode(msg) err.sdk.lifecycle.mode INTERNAL A mode change failed - for example toggling simulation mode. Failed to change node's mode.

SDKTransportError: Moving messages in or out of the node failed.

Factory Error code gRPC status Raise it when Caller sees by default
SDKTransportError.data_connection(msg) err.sdk.transport.data.connection UNAVAILABLE Could not establish or keep a data-plane connection. Failed to connect to the data plane.
SDKTransportError.data_pubsub(msg) err.sdk.transport.data.pubsub UNAVAILABLE Connected to the data plane, but a publish or subscribe failed. Failed to publish/subscribe on the data plane.
SDKTransportError.data_codec(msg) err.sdk.transport.data.codec INTERNAL A data-plane message could not be encoded or decoded. Failed to encode/decode a data-plane message.
SDKTransportError.data_not_configured(msg) err.sdk.transport.data.not_configured FAILED_PRECONDITION The data plane was used before it was set up. Data plane is not configured.
SDKTransportError.control_connection(msg) err.sdk.transport.control.connection UNAVAILABLE Could not establish or keep a control-plane connection. Failed to connect to the control plane.
SDKTransportError.control_pubsub(msg) err.sdk.transport.control.pubsub UNAVAILABLE Connected to the control plane, but a publish or subscribe failed. Failed to publish/subscribe on the control plane.
SDKTransportError.control_codec(msg) err.sdk.transport.control.codec INTERNAL A control-plane message could not be encoded or decoded. Failed to encode/decode a control-plane message.
SDKTransportError.control_not_configured(msg) err.sdk.transport.control.not_configured FAILED_PRECONDITION The control plane was used before it was set up. Control plane is not configured.

SDKServiceError: A service the SDK depends on failed the request.

Factory Error code gRPC status Raise it when Caller sees by default
SDKServiceError.registration(msg) err.sdk.service.registration UNAVAILABLE Registering the node with the Consul discovery service failed. Failed to register the node with Consul discovery service.
SDKServiceError.twin(msg) err.sdk.service.twin UNAVAILABLE A request to the digital twin service failed. Request to digital twin failed.
SDKServiceError.data_repository(msg) err.sdk.service.data_repository UNAVAILABLE A request to the data repository failed. Request to data repository failed.
SDKServiceError.streaming(msg) err.sdk.service.streaming UNAVAILABLE A streaming request failed - for example the LiveKit visualization path. Streaming request failed.

SDKOperationError: An SDK-internal operation failed.

Factory Error code gRPC status Raise it when Caller sees by default
SDKOperationError.bootstrap(msg) err.sdk.operation.bootstrap INTERNAL The node bootstrap service could not be started. Failed to start the node bootstrap service.
SDKOperationError.status_check(msg) err.sdk.operation.status_check INTERNAL Sending or receiving a node status update failed. Failed to send/receive node status.
SDKOperationError.health_check(msg) err.sdk.operation.health_check INTERNAL A health check could not be completed. Node health check failed.
SDKOperationError.node_not_found(msg) err.sdk.operation.node_not_found NOT_FOUND The requested node is not in the registry, or is not running. Requested node is not running or not found.

SDKConfigError: Configuration handed to the SDK is unusable.

Factory Error code gRPC status Raise it when Caller sees by default
SDKConfigError.missing(msg) err.sdk.config.missing INVALID_ARGUMENT A required configuration key was not supplied. Required configuration missing.
SDKConfigError.invalid(msg) err.sdk.config.invalid INVALID_ARGUMENT Configuration parsed, but a value is not acceptable. Configuration is invalid.
SDKConfigError.parse(msg) err.sdk.config.parse INVALID_ARGUMENT Configuration could not be parsed at all - malformed YAML, JSON or env value. Configuration could not be parsed.

SDKError: Base class for errors raised by the SDK itself.

Factory Error code gRPC status Raise it when Caller sees by default
SDKError.unknown(msg) err.sdk.unknown INTERNAL An SDK failure that fits none of the specific categories. An unexpected SDK error occurred.

Python and C++ parity

The C++ SDK (neuraverse-node-sdk-cpp, same repository) is a port of this tree: Python leads API and contract changes, C++ follows. Both ship from one base image. The wire contracts they must agree on are pinned by the fixtures in neuraverse-node-sdk-cpp/tests/fixtures/contract/ and asserted by both test suites; see Transports. The author-facing mapping of hooks and helpers is C++ SDK mapping; this table covers the internals.

Area Python (this tree) C++
Layers NodeServiceApi + FastAPI, NodeController + NodesRegistry, NodeBase, StateMachine, IDataFlow, ITrigger Same layers and class names (NodeServiceApi, HttpApi, NodeController, NodesRegistry, NodeBase, StateMachine).
State machine RLock in StateMachine; pause() / resume() return bool; PausedState(resume_state) Same since 2.39.0, with StateMachine taking a lock, PausedState(resume_state_), and transitionTo() / sendStatusMessage() private.
NodeBase access boundary No compile-time boundary; every platform-facing method in the table above is a normal public method authors could in principle call directly. Since 2.46.0, NodeBase splits public (the methods authors call), protected (the hooks authors override, plus getNodeVersion()/setHealthCheckMessage()/registerTriggerHandler()/setProjectId() for use from inside a hook) and private (every method in the platform-facing surface above, and every data member); NodeController and NodesRegistry are the only friends. C++ tests that must drive the private surface without a controller use NodeBaseTestPeer (neuraverse-node-sdk-cpp/tests/NodeBaseTestPeer.hpp), a friend class exposing it through an internals(node) factory function; it ships with the test suite, not with the installed package. Deliberately not ported to Python: Python has no equivalent access-control mechanism.
Trigger transport TriggerFactory supports MQTT and Zenoh; initialize() hardcodes TRIGGER_COMMUNICATION_TYPE_MQTT NodeBase.cpp hardcodes the same MQTT type; ZenohTriggerAdapter builds only when Zenoh is enabled.
MQTT trigger topic {entry.id}/{port}, QoS 1, payload TriggerContext JSON or triggered Identical (MqttTriggerAdapter.cpp).
Zenoh trigger topic {entry.name}/{port} (a known inconsistency, commented in zenoh_trigger_adapter.py) {entry.id}/{port} (ZenohTriggerAdapter.cpp). Mixed Python and C++ graphs over Zenoh triggers would not meet; MQTT is the active path in both.
Shared MQTT client MQTTHandler process singleton, refcounted connect, handle-based subscriptions MqttHandler::shared, refcounted across dataflow and trigger adapters.
Zenoh Always importable (eclipse-zenoh is a hard dependency); ZenohHandler per adapter Optional at build time (ENABLE_ZENOH AUTO / ON / OFF).
Message types _import_msg_type() imports pkg.msg.Type dynamically at configure time TypeRegistry::registerType<T>("pkg/msg/Type") at startup; unregistered types cannot be routed.
wait_for_message Raises NotImplementedError in the ROS, MQTT and Zenoh adapters The ROS adapter implements waitForMessage(); MQTT and Zenoh throw DataFlowException.
Schema discovery Sibling <module>_schema.json found through inspect.getfile SchemaProvider scans NodeServiceConfig.schema_dir and indexes by the executionContext.className inside each file.
Service configuration service_config.yaml through pydantic settings No YAML loader; main.cpp sets NodeServiceConfig fields and reads NODE_NAMESPACE, CONTAINER_NAME, SERVICE_VERSION, NODE_SCHEMA_DIR from the environment.
Consul client One shared ServiceRegistryClient per (endpoint, token), monitor lives for the process Per-request libcurl connections, monitor threads joined on instance stop; deregisters the stale legacy capability-<Class> id at startup, which Python does not.
Admin API In-process JWT validation plus YAML allowlist, always mounted Same bearer JWT validation (since 2.47.0, jwt__* config) plus YAML allowlist; disabled by default (admin.enabled), registered on any bind address.
gRPC authentication JWTAuthInterceptor(unauth_methods) on the server Since 2.47.0 every NodeServiceApi handler calls an internal::JwtValidator (vendored jwt-cpp, JWKS over libcurl), configured by NodeServiceConfig.jwt and jwt__* env vars; custom services opt in per service through Authentication (NodeServiceApi takes the validator as constructor argument).
Feature timeline Health stream 2.23.0, error trigger 2.25.0, schema registration 2.27.0, custom triggers 2.37.0 Health stream 2.29.0, error trigger 2.28.0, schema registration 2.34.0, custom triggers 2.37.0, zero-code data visualization 2.40.0.
Node-local process safety An exception in on_execute() is caught by execute() Same since 2.40.0; before, a throwing onExecute() escaped the detached thread and terminated the process.

Scope decisions for what the C++ tree deliberately does not port are kept in neuraverse-node-sdk-cpp/developer_reference/CPP_SCOPE_DECISIONS.md.