Skip to content

Data visualization streamer (internals)

How StartNodeDataVisualization turns a node's outputs into LiveKit video tracks and data-channel messages: the DataVisualizationStreamer lifecycle, the publish bridge the controller injects into NodeBase, the cached last-value republisher with its CACHED marker, the idle watchdog, and the per-RPC LiveKit credentials. The node-author view is Data visualization; this page is for the platform team debugging a viewer that shows nothing, a duplicated track after a reconfigure, or a LiveKit room that never closes.

Components and flow

sequenceDiagram
    participant UI as Cloud UI
    participant NES as Node Engine (via proxy)
    participant RPC as NodeRouter (gRPC)
    participant Ctl as NodeController
    participant Node as NodeBase instance
    participant S as DataVisualizationStreamer
    participant LK as LiveKit room

    UI->>NES: open visualization panel
    NES->>RPC: GetDataVisualizationTopics
    RPC->>Ctl: get_data_visualization_topics()
    Ctl->>Node: get_data_visualizations_topics()
    NES->>RPC: StartNodeDataVisualization(roomName, publisherToken, livekitUrl, topicNames, iceServers)
    RPC->>Ctl: start_data_visualization(...)
    Ctl->>S: start(room, token, url, topic_configs, ros_node, initial_messages, ice_servers)
    S->>LK: connect, publish_track per image/audio topic
    Ctl->>Node: inject _viz_publish_hook and _viz_*_push
    loop every publish()
        Node->>S: hook(port, msg) -> _handle_*_message
        S->>LK: capture_frame / publish_data
    end
    NES->>RPC: StopNodeDataVisualization
    RPC->>Ctl: stop_data_visualization(...)
    Ctl->>S: stop()
    Ctl->>Node: clear hooks, on_stop_data_visualization()

Source files: src/neuraverse_sdk/streaming/data_visualization_streamer.py (streamer), src/neuraverse_sdk/controllers/node_controller.py (session logic), src/neuraverse_sdk/node_base.py (publish bridge and cache), src/neuraverse_sdk/api/grpc/router/node_router.py (RPC handlers).

The three RPCs

RPC on NodeServiceApi Controller call Notes
GetDataVisualizationTopics get_data_visualization_topics() Read-only enumeration; any exception becomes gRPC INTERNAL. Takes no node id.
StartNodeDataVisualization start_data_visualization(node_id, room_name, publisher_token, topic_names, livekit_url, ice_servers) Wrapped in a tenacity retry (two attempts) for retryable exceptions. iceServers are converted to {urls, username, credential} dicts.
StopNodeDataVisualization stop_data_visualization(node_id, room_name) Same retry wrapper.

Start looks the node up with nodes_registry.get_node_object(), so an unknown node id raises NodeNotFoundError, which the router's _handle_rpc wrapper turns into a NeuraPublicRuntimeError. Stop with an unknown key only logs No active streamer found for ... and returns.

Topic enumeration and the list-typed topics trap

NodeController.get_data_visualization_topics() walks every instantiated node, keeps only the ids that still have an active status queue (stopped nodes and stale configure cycles never reach the picker), and calls node.get_data_visualizations_topics() on each. The call is wrapped per node: any exception is logged as Error while collecting visualization topics and that node is skipped; the other nodes still appear.

NodeBase.get_data_visualizations_topics() builds the map from two sources, in this order:

  1. on_get_data_visualization_topics(), the author override, iterated with .topics.items().
  2. get_output_topics(), every output port whose ros_type is not in NodeBase._NON_VISUALIZABLE_TYPES. For a Zenoh-routed output the topic is <uuid>/<node id>/<port> since 2.50.2 (it was built from the display name before).

Outputs are copied last with CopyFrom on the same key, so an output port wins a name collision. Each entry carries topicName = livekit_safe_viz_name(real_topic) and visualizationType = visualization_stream_type(ros_type). Any exception is re-raised as NodeStateError("Failed to get data visualizations topics").

A list instead of a dict removes the whole node

NodeVisualizationsTopics(topics=[...]) makes .topics.items() raise AttributeError; get_data_visualizations_topics() converts it to NodeStateError; the controller's per-node swallow turns that into one warning line and a node that is silently absent from the picker, output ports included. When a node is "not visualizable" in the UI, grep the node service log for Error while collecting visualization topics first.

Not visualized (no stream is created for these output types)
sensor_msgs/msg/CameraInfo
sensor_msgs/msg/Imu
sensor_msgs/msg/LaserScan
sensor_msgs/msg/MagneticField
sensor_msgs/msg/NavSatFix
sensor_msgs/msg/PointCloud2
tf2_msgs/msg/TFMessage

Public names: livekit_safe_viz_name and visualization_stream_type

The engine mints a fresh wire id {uuid}:{node_id} on every configure cycle, so topics reach the SDK in three shapes: {uuid}/{node_id}/{port}, {uuid}:{node_id}/{port}, or the ROS-sanitised {uuid}_{node_id}/{port} (with an n_ prefix when the UUID starts with a digit). livekit_safe_viz_name(topic) strips the leading runtime token in all three shapes (regex _VIZ_RUNTIME_TOKEN_RE), keeps a stable node_id/port, and prefixes any segment that still starts with a digit with n_. Two rules follow:

  • The public name must come from this one function wherever it appears: the reported topicName, the LiveKit track name in _setup_video_track(), and the data-channel topic in _handle_data_message() and _republish_data(). The UI subscribes by topicName verbatim.
  • Because the name is keyed on the node id and not on the per-configure UUID, a reconfigure publishes the same track name again. That is why the stale-sibling retirement below exists.

visualization_stream_type(ros_type) returns sensor_msgs/msg/Image for every type the streamer publishes as a video track (images, image-convertible types, audio) and the input unchanged for everything else, which travels as JSON on the data channel:

Output rosType Streamed to the UI as
sensor_msgs/msg/CompressedImage video track (frames as published)
sensor_msgs/msg/Image video track (frames as published)
instance_segmentation_ros_msgs/msg/SegmentationResult video track (rendered image: greyscale map, masks/boxes over the source image)
instance_segmentation_ros_msgs/msg/SegmentedInstanceArray video track (rendered image: greyscale map, masks/boxes over the source image)
nav_msgs/msg/OccupancyGrid video track (rendered image: greyscale map, masks/boxes over the source image)
audio_common_msgs/msg/AudioData video track (live waveform)
audio_msgs/msg/AudioData video track (live waveform)
any other message type JSON on the data channel (throttled)

_is_ros_subscribable(topic) is the third helper: it rejects names rcl would refuse (a token starting with a digit, or - and : inside a token). Such topics get no ROS subscription and are fed by the publish hook only (CHANGELOG v2.36.1).

Start path in the controller

start_data_visualization() keys sessions by streamer_key = f"{node_id}:{room_name}" and keeps three registries under _streamers_lock: _active_streamers, _active_streamer_topics (the frozenset of picker names each streamer serves) and _pending_stops.

  1. Retire stale siblings. _retire_stale_sibling_streamers() removes, and stops on a viz-retire-<key> thread, every streamer in the same room whose wire id differs but whose _logical_node_id() (wire id minus the {uuid}: prefix) is the same. Without this the previous cycle's passive streamer keeps republishing stale cached frames under the same public track name and the UI binds to the dead track.
  2. Cancel a deferred Stop for the key, if one is pending.
  3. Identical topic set: log, re-run on_start_data_visualization(topic_names), return. Different set: take the union, record it, and extend the existing streamer in place with add_topics(). A stop-and-recreate would rotate the LiveKit participant SID and break UI clients bound to the old tracks.
  4. Resolve topic configs. Picker names are matched against get_data_visualizations_topics(); the real ROS topic and the raw (un-normalised) type come from on_get_data_visualization_topics() and get_output_topics(), output ports winning. Unknown names are warned about and skipped; no configs at all ends the call with a warning and no streamer.
  5. Segmentation backgrounds. For each segmentation-typed config, every input port of type sensor_msgs/msg/Image or sensor_msgs/msg/CompressedImage is appended as {"role": "background", "background_for": <seg topic>}.
  6. ROS node and cache seed. get_ros_node() supplies an existing rclpy node, or None so the streamer creates its own. initial_messages is filled from get_cached_output(port) for every configured topic, mapping ROS topic back to port name through get_output_topics().
  7. Create or extend. A new DataVisualizationStreamer(node_id, logger) gets _on_idle_stop = _make_idle_stop_callback(streamer_key) and start(room_name, publisher_token, livekit_url or node_service_config.livekit_url, topic_configs, ros_node, initial_messages, ice_servers). The registries are updated under the lock.
  8. Inject the node-side hooks (next section).
  9. Wait for sources. On the create path only, streamer.wait_for_sources_ready(timeout=viz_sources_ready_timeout_s); on timeout a WARNING Data visualization video sources not ready after ... is logged and the call continues.
  10. Wire the publish bridge _viz_publish_hook = _make_viz_publish_hook(node, streamer, topic_configs) and call on_start_data_visualization(topic_names).

The publish bridge in NodeBase

NodeBase.publish(topic_name, message) does three things, in order: forwards to the data flow, stores (message, time.monotonic()) in _last_output_cache[topic_name], and calls self._viz_publish_hook(topic_name, message) when a hook is set, swallowing every exception so visualization can never break the publish path. The cache is read back through get_cached_output(port) and get_cached_output_topics(). It outlives the streamer and is never cleared by the SDK, which is what lets a viewer that opens after the last publish still see a frame.

Attribute on the node instance Set by the controller when Target
_viz_publish_hook every session, after the sources wait closure from _make_viz_publish_hook()
_viz_bg_push, _viz_bg_mqtt_to_seg a background mapping exists (segmentation output plus image input) streamer.push_background_frame
_viz_seg_push, _viz_seg_topics same condition streamer.push_segmentation_result
_viz_image_push, _viz_image_push_map a non-background image-typed output is in the session streamer.push_image_frame
_viz_bg_input_cache reset to None on every Start placeholder-to-topic cache used by get_data()

NodeBase itself calls only two of these. publish() calls _viz_publish_hook. get_data() calls _try_push_viz_background(), which decodes a CompressedImage, or a raw rgb8, bgr8 or 8UC3 Image, read from an input port and hands the RGBA frame to _viz_bg_push(seg_topic, frame) when that port's topic is in _viz_bg_mqtt_to_seg. _viz_image_push and _viz_seg_push are injected for nodes that call them by hand (legacy MQTT-only nodes); nothing in NodeBase invokes them, and the guide documents them as unsupported.

The hook built by _make_viz_publish_hook() maps the port to its ROS topic via get_output_topics(), drops ports that are not in the session's non-background configs (logged once per port as viz publish hook: skipping port=...), and dispatches on the normalised type to _handle_image_message, _handle_image_convertible_message, _handle_audio_message or _handle_data_message. It logs viz publish hook constructed: port_to_ros_topic=... cfg_topics=... once at session start, the first dispatch per port, and a heartbeat every 250 dispatches. Messages through the hook are not throttled. Only the streamer's own ROS subscriptions are: 10 Hz for _SCALAR_TYPES, 5 Hz for other data types, none for image and audio.

Streamer lifecycle

Method What it does
start(room_name, publisher_token, livekit_url, topic_configs, ros_node=None, initial_messages=None, ice_servers=None) Refuses a second start while running. Creates a dedicated rclpy node viz_streamer_<id> with its own SingleThreadedExecutor thread when no ros_node is passed. Starts a daemon thread livekit-streamer-<node_id> that runs an asyncio loop with _connect_and_stream().
wait_for_sources_ready(timeout=10.0) Blocks on _sources_ready_event, which is set after the room is connected and every video track is published.
add_topics(new_topic_configs) -> bool Schedules _add_topics_coroutine() on the loop; returns False when not running. The coroutine waits up to _ADD_TOPICS_READY_TIMEOUT_SEC (10 s) for the room to connect, then publishes tracks and subscriptions for topics not yet configured (idempotent for supersets).
transition_to_passive() Idempotent. Destroys ROS subscriptions and the owned executor and rclpy node; keeps the room, the republish loop and the watchdog alive.
stop() Sets _running = False, tears down subscriptions, disconnects the room (5 s), joins the loop thread (5 s), clears video sources and background maps.
is_running (property) Mirrors _running; _run_event_loop() also sets it to False when the loop exits or raises.
clear_cache() Empties the last-value caches. Nothing in the SDK calls it today; the docstring's "controller calls this on graph teardown" describes an intent, not the code.
push_image_frame(topic, rgba), push_segmentation_result(seg_topic, ros_msg), push_background_frame(seg_topic, rgba) Direct entry points that bypass ROS (see the hook table). push_image_frame is a no-op until the track for that topic exists. push_segmentation_result accepts SegmentationResult (.instances) and SegmentedInstanceArray (.segmented_instances) and stores the instances even when the source is not ready yet. push_background_frame re-renders with the last seen instances so the codec keeps receiving frames between sparse segmentation results.

_connect_and_stream() runs, in order: Room.connect() with RoomOptions carrying the ICE servers when any were passed; build the background-to-segmentation map; _setup_video_track() for every non-background image, convertible or audio config (a 640 x 480 RGBA VideoSource, track named with the public name, source keyed by the real topic); set _sources_ready_event; _subscribe_ros_topics() inside a try/except so a subscription failure can no longer abort the session; _replay_initial_messages(); schedule _republish_loop() and _idle_watchdog(); sleep in 0.5 s steps while running; cancel both tasks on exit.

Cached last-value republish (PASSIVE mode and the CACHED marker)

Every live capture records the payload per topic: _remember_image_frame() for RGBA frames, _remember_data() for the unwrapped dict, both stamping _last_capture_times[topic] with time.monotonic(). _republish_loop() ticks every _CACHE_REPUBLISH_INTERVAL (1.0 s) and, for each topic whose last capture is at least _CACHE_STALE_AFTER (1.5 s) old, re-emits the cached value on the same channel:

  • Images: _republish_image() copies the frame, resizes it to 640 x 480 if needed, draws a translucent bar with the amber text CACHED · <n>s ago along the bottom (_draw_cached_overlay()) and captures it to the existing VideoSource.
  • Data: _republish_data() publishes the usual envelope {"nodeId", "topicName", "data", "timestamp"} with data._meta = {"cached": true, "age_seconds": <n>} added by _wrap_cached_payload().

While fresh data flows the loop is a no-op. On a fresh session the loop is seeded by _replay_initial_messages(), which pumps the controller's initial_messages through the normal handlers right after connect, so a late viewer gets a frame at once and the CACHED overlay follows 1.5 s later.

PASSIVE mode is this loop without ingestion. When stop_node() runs, the controller calls _transition_streamers_to_passive(node_id) before node.stop(): every streamer for the node gets transition_to_passive(), and the node's _viz_bg_push, _viz_seg_push, _viz_image_push and _viz_publish_hook are set to None (the map attributes are emptied). The streamer stays in _active_streamers and keeps republishing the last cached frame to viewers still in the room. It is released only by an explicit StopNodeDataVisualization, by the idle watchdog, or by pod teardown. on_stop_data_visualization() is therefore not called when the node stops, only on the explicit Stop.

Idle watchdog

_idle_watchdog() wakes every _IDLE_WATCHDOG_INTERVAL (60 s) and inspects room.remote_participants. Once the set has been empty for _IDLE_NO_SUBSCRIBER_SECONDS (30 min) it logs Idle watchdog firing: no UI subscriber for ..., sets _idle_stop_requested, and runs _self_stop() on a thread named viz-streamer-idle-stop-<node_id>: stop() followed by the _on_idle_stop callback, which the controller wired to _make_idle_stop_callback(streamer_key) to drop the registry entries. The next Start creates a fresh streamer and re-seeds it from the node's _last_output_cache. An exception while reading the room counts as "has subscriber", so the watchdog errs towards staying alive.

Stop path in the controller

stop_data_visualization(node_id, room_name):

  • No streamer for the key: WARNING No active streamer found for ..., return.
  • Sources ready: remove the registry entries and run _teardown_streamer(): streamer.stop(), reset every _viz_* attribute on the node, call on_stop_data_visualization().
  • Sources not ready (a Stop raced a Start): register a cancel event in _pending_stops and hand off to _deferred_stop_runner(), which polls _sources_ready_event every 100 ms for up to _STOP_SETUP_GRACE_SECONDS (5.0 s), aborts if a follow-up Start cancelled it or replaced the streamer, and otherwise tears down. A duplicate Stop during the deferral is ignored.

_stop_all_streamers_for_node() exists but has no caller.

Per-RPC LiveKit credentials

Nothing about the media transport comes from environment variables. Every StartNodeDataVisualizationRequest carries roomName, publisherToken, livekitUrl, topicNames and iceServers, and the router passes them straight to the controller. Two service-config keys are the only local inputs:

NodeServiceConfig field Default Role
livekit_url "" Used only when the request's livekitUrl is empty.
viz_sources_ready_timeout_s 10.0 Upper bound for wait_for_sources_ready() on the create path.

iceServers are RTCIceServer-shaped (urls, username, credential) per-identity ephemeral TURN credentials relayed by the proxy (NRV-7971, CHANGELOG v2.35.0). _build_room_options() maps credential to LiveKit's IceServer.password (CHANGELOG v2.35.1) and returns None when the list is empty, in which case Room.connect() runs with the SDK's default ICE configuration.

Specifications, tests and history

  • Behaviour briefs: 200-data-viz-topics.md (enumeration) and 210-data-visualization.md (Start, Stop, extend, PASSIVE, sources-ready timeout).
  • Executable specs: specifications/specs/data-visualization/ (start and stop, extend, passive on node stop, sources-ready timeout, streamer internals, segmentation background, idle and stop-all, deferred stop, publish-hook dispatch, stale-streamer retirement), specifications/specs/data-viz-topics/, specifications/specs/grpc-routing/050-viz-topics.feature and specifications/specs/dataflow-routing/070-viz-background-push.feature. LiveKit is patched at the streamer module level, so nothing here talks to a real room.
  • Unit tests: tests/test_data_visualization_ice.py, tests/test_data_visualization_json.py. The tests/test_data_visualization_streamer.py that prompt 210 links to no longer exists.
  • Coverage: pyproject.toml lowers fail_under to 70 explicitly because the streamer needs a real LiveKit plus ROS harness to be covered; see Specifications.
  • CHANGELOG v2.36.1: wire-id topics no longer kill the session (_is_ros_subscribable, per-topic subscription guard, guarded start-path subscribe).

The C++ SDK streams the same way with no node-author code: visualizable outputs, ROS-subscribed extra topics and the per-port last-value cache (CHANGELOG v2.40.0).

Log lines worth grepping

Line Meaning
Error while collecting visualization topics A node's get_data_visualizations_topics() raised; the node is missing from the picker.
Viz topic resolved: viz_name=... ros_topic=... public_name=... Per requested topic at Start; lookup_hit=False means the type fell back to the normalised one.
viz publish hook constructed: port_to_ros_topic=... The bridge is wired; compare the port map with the schema.
viz: first frame captured to LiveKit for topic ... Publish, render, encode and capture succeeded at least once for that topic.
Data visualization video sources not ready after ... viz_sources_ready_timeout_s elapsed; the first frames may drop.
Transitioning streamer to passive cache-only mode The node stopped; viewers now see CACHED frames.
Retiring stale viz streamer ... A reconfigure superseded a previous cycle's streamer.
Idle watchdog firing 30 min without a viewer; the room is being released.