Schema file reference¶
Every node class ships a JSON schema file next to its module. The SDK reads it at service startup and registers it so the node shows up in the graph editor's palette with its ports, description and default settings. After this page you can write a schema that parses, matches your code, follows the platform's port-naming convention and is checked by a test.
Custom gRPC services use author-owned proto definitions and need no graph-node schema. This page describes graph nodes; mixed hosts keep the same schema rules for their node classes.
Where the file lives and how it is loaded¶
| Rule | Detail |
|---|---|
| File name | <module>_schema.json, where <module>.py is the file that defines the class. src/uppercase_node/uppercase_node.py pairs with src/uppercase_node/uppercase_node_schema.json. |
| One class per module | The SDK derives the schema path from the module file of the class, so two node classes in one module would share one file. Keep one node class per module. |
| Loader | The file is parsed into the platform's Node message with unknown fields ignored. Keys the message does not know are silently dropped, not reported. |
| Missing or misnamed file | A warning No static schema file found for <Class> is logged and the node registers with an empty schema: the class name as name, the class docstring as description, no ports, no category. |
| Unparsable file | A warning Failed to parse static schema <path> is logged and the node registers with the same empty schema. Registration never raises, so a broken schema does not stop the service. Watch the startup log. |
executionContext.className |
Overwritten with the real Python class name at registration. Still write the exact class name: the engine looks your class up by it, and the schema test below checks it. |
name and description |
Filled from the class name and docstring only when the file leaves them empty. |
A minimal schema, annotated¶
This is the schema of the quickstart node. It declares one data input, one data output and the standard trigger ports.
{
"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"
}
}
| Key | What it does |
|---|---|
id |
Palette category. Nodes with the same id are grouped under one heading in the editor. You choose it. |
name |
Display name in the palette and the identity the platform registers the node under. Human readable, stable. |
type |
Node kind. Use 1 or NODE_TYPE_ASSET_SOURCE for your own nodes; every example and template node does. |
description |
Shown in the palette. |
tags |
Free-form strings for search and grouping. |
inputs, outputs |
Port maps, see Ports. |
executionContext |
How the engine reaches the node, see executionContext. |
configuration |
Optional static string defaults, see configuration. Not present in this schema because the node has no settings. |
For a schema with a configuration block see the
math node tutorial and the
image node tutorial.
type values¶
| Value | Name | Use |
|---|---|---|
1 |
NODE_TYPE_ASSET_SOURCE |
Ordinary node that processes or produces data. Use this. |
2 |
NODE_TYPE_FLOW_CONTROL |
Platform flow-control nodes. |
3 |
NODE_TYPE_COMPOSITE |
Platform composite nodes. |
4 |
NODE_TYPE_ASSET_DYNAMIC |
Platform use. |
Enum fields accept the numeric value or the enum name, in any field of the file. Pick one style per repository.
Ports¶
inputs and outputs are maps from a port key to a port description. Each port description
has these fields:
| Field | Required | Meaning |
|---|---|---|
rosType |
yes | The type of the port. For data ports the ROS 2 message type, pkg/msg/Type (for example std_msgs/msg/String). For trigger ports the trigger type name (for example Start). |
edgeType |
yes | 1 for data ports, 2 for trigger ports. This is the only thing that separates the two kinds. |
type |
no | Operation type. Legacy schemas carry 1 (OPERATION_TYPE_ROS). The SDK does not read it. Omit. |
requestTarget |
no | Legacy. The SDK does not read it. Omit. |
defaultValue |
no | Legacy. The SDK does not read it. Omit. |
isVisible |
no | Boolean wrapper. The SDK does not read it. Omit unless the platform team asks for it. |
The SDK also accepts pkg/Type for data ports and tolerates a leading slash. Use the
three-segment form: it is what every example and template node writes.
The port-key convention¶
One rule for every port
All port keys, inputs and outputs, data and trigger, built-in and custom, are lowercase
snake_case. rosType carries the type name verbatim: Start, Stop, Error, IfTrue,
IfFalse, InLoop, BreakLoop, a custom name such as TaskInterrupt, or a message type
such as std_msgs/msg/Float32.
Trigger inputs: start, stop. Trigger outputs: start, error. There is no stop
output.
Port keys match [A-Za-z][A-Za-z0-9_]*. That is valid on every transport; a key with spaces or
a / is rewritten for ROS topics, can collide with another key there, and a trailing / fails
configure. MQTT rejects # and + in a port key and Zenoh rejects *, $, ? and #
(since SDK 2.50.2), because they are wildcards in a topic.
fire_trigger("task_interrupt") addresses the port key;
@trigger_handler("TaskInterrupt") binds the type written in rosType.
Why no stop output: after every successful on_execute the SDK fires every declared Start
output and every declared Stop output. A Stop output therefore stops the downstream node on
every run of yours. Nodes keep their stop input so the graph can stop them.
Legacy schemas with capitalised keys or a Stop output keep working. Do not add a Stop output
to a new node, and use lowercase keys when you touch an old schema.
Trigger ports¶
The built-in trigger types and what an incoming trigger of that type runs:
Built-in trigger type (rosType) |
Routes to |
|---|---|
Start |
on_execute() |
Stop |
stop_execution() → on_stop_execution() when the node overrides it; otherwise the hard stop() → on_stop(), on_cleanup() |
Error |
on_execute() with trigger_context.is_triggered_by_error() == True |
IfTrue |
on_execute() |
IfFalse |
on_execute() |
InLoop |
on_execute() |
BreakLoop |
on_execute() |
Error is also a valid input trigger: an error-handler node declares an input with
rosType: "Error" and checks trigger_context.is_triggered_by_error() in on_execute.
Any other name in rosType declares a custom trigger. A custom output port is fired from your
code with self.fire_trigger("<port key>"). A custom input port needs a method decorated with
@trigger_handler("<rosType>"); if none is bound, configuring the node fails even while the port
is not connected. See Triggers.
Data ports and your code¶
Port keys are the names your code uses:
| In the schema | In the code |
|---|---|
outputs.<key> with edgeType 1 |
self.publish("<key>", msg) |
inputs.<key> with edgeType 1 |
self.get_data("<key>") |
Publishing to a key that is not a declared output raises
DataFlowException: Unknown output target: <key> at run time. Reading an undeclared input returns
None. Grep your publish( and get_data( calls and compare them with the schema, or let the
schema test do it.
executionContext¶
"executionContext": { "type": 3, "target": "", "className": "UppercaseNode" }
| Field | Value |
|---|---|
type |
3 or EXECUTION_TARGET_TYPE_GRPC. Python nodes are always driven over gRPC. |
target |
Always "". The engine fills the address per deployment when it configures the node. A hard-coded host leaks into every graph that uses the node. |
className |
The exact Python class name. |
configuration (static defaults)¶
configuration is an optional map of string keys to string values:
"configuration": { "offset": "0.0" }
- The whole map is handed to
on_configure(config, dynamic_config)as the first argument, so whatever parsing you do there (float(),int(),json.loads()) must succeed on the default you wrote. A default that does not parse breaks every freshly dropped node. - Typed settings (toggles, sliders, dropdowns) do not go in this file. They are produced at
run time by
on_get_configuration()and arrive asdynamic_config. See Configuration. - Never add deployment keys such as
node_deployment_host,is_remoteornode_namespace. The platform injects them.
Mock Runner
The Mock Runner builds its own Node from your schema's name, inputs and outputs only.
config arrives empty there, and category, description and executionContext are not
checked. A schema can be wrong and still run in the mock.
Fields that must not appear¶
The Node message also carries run-time document fields. The loader accepts them, so nothing
warns you, but they belong to the engine and the graph document, never to a schema file.
| Field | Why not |
|---|---|
executionStatus, history, resourceVersion, assetInstanceId, nodeBaseUrl |
Run-time state of a node instance in a graph. |
dataFlowEntry, triggerFlowEntry |
Wiring the engine computes from graph edges. Some example schemas carry them as {}; an empty object is harmless, anything else is not. |
errorOutputs |
Unused by the SDK. Error routing uses the error trigger output. |
dynamicConfiguration |
Typed settings are run-time only via on_get_configuration(). The node is not configured at registration, so nothing here would be correct. |
Any key that is not a Node field |
Silently dropped. Legacy template schemas carried a node-level communication-type key; do not copy it. |
After you change a schema¶
- The schema is read when the node service registers the node, normally at service startup. Restart the node service to make sure the changed file is what gets registered.
- A node already placed on a canvas is a snapshot of the schema it was dropped with. To pick up a changed port list, delete the node from the graph and drop it again. Existing graphs keep their old behaviour on purpose.
- Optionally set
node_version = "1.2.0"as a class attribute on the node. It is shown with the registration; without it the SDK reports the version of the node service.
Checking a schema in tests¶
The examples ship a reusable test that discovers every <module>_schema.json with a sibling
<module>.py and checks, for each pair, that the JSON parses into Node, that className names
a NodeBase subclass defined in that module, that port keys are lowercase snake_case, that no
output has rosType: "Stop", and that every literal passed to self.publish() and
self.get_data() is a declared port.
"""Schema-consistency checks for every example node under ``examples/``.
For each ``<module>_schema.json`` with a sibling ``<module>.py`` this verifies that:
* the JSON parses into the business ``Node`` proto (unknown fields ignored),
* ``executionContext.className`` names a ``NodeBase`` subclass defined in the module,
* every input/output key is lowercase snake_case,
* no output port carries ``rosType: "Stop"`` (the SDK fires every declared Stop output after
each successful ``on_execute``, which would stop downstream nodes on every run),
* every string literal passed to ``self.publish(...)`` / ``self.get_data(...)`` in the module
is a declared output / input key.
Run from the repository root::
PYTHONPATH="$(pwd):$(pwd)/src" poetry run pytest examples/tests -q -p no:cacheprovider
"""
from __future__ import annotations
import ast
import importlib.util
import json
import pathlib
import re
import sys
from types import ModuleType
import pytest
ROOT = pathlib.Path(__file__).resolve().parents[2]
for _p in (ROOT, ROOT / "src"):
if str(_p) not in sys.path:
sys.path.insert(0, str(_p))
from examples._testing.stubs import install_stubs # noqa: E402
install_stubs()
from google.protobuf.json_format import ParseDict # noqa: E402
from neuraverse.models.v1.gen.business.node_graph_pb2 import Node # noqa: E402
from neuraverse_sdk.node_base import NodeBase # noqa: E402
EXAMPLES = ROOT / "examples"
SKIP_DIRS = {"_testing", "tests", "__pycache__"}
SNAKE_CASE = re.compile(r"^[a-z][a-z0-9_]*$")
def _discover_schemas() -> list[pathlib.Path]:
found = []
for schema in sorted(EXAMPLES.rglob("*_schema.json")):
rel_parts = schema.relative_to(EXAMPLES).parts
if SKIP_DIRS.intersection(rel_parts[:-1]):
continue
if schema.with_name(schema.name[: -len("_schema.json")] + ".py").exists():
found.append(schema)
return found
SCHEMAS = _discover_schemas()
SCHEMA_IDS = [str(p.relative_to(EXAMPLES)) for p in SCHEMAS]
_MODULE_CACHE: dict[pathlib.Path, ModuleType] = {}
def _module_path(schema: pathlib.Path) -> pathlib.Path:
return schema.with_name(schema.name[: -len("_schema.json")] + ".py")
def _load_module(path: pathlib.Path) -> ModuleType:
"""Import a node module by file path (like the runtime does), once per session."""
if path in _MODULE_CACHE:
return _MODULE_CACHE[path]
name = "example_" + "_".join(path.relative_to(EXAMPLES).with_suffix("").parts)
spec = importlib.util.spec_from_file_location(name, path)
assert spec is not None and spec.loader is not None, path
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
module_dir = str(path.parent)
added = module_dir not in sys.path
if added:
sys.path.insert(0, module_dir)
try:
spec.loader.exec_module(module)
finally:
if added:
sys.path.remove(module_dir)
_MODULE_CACHE[path] = module
return module
def _load_schema(schema: pathlib.Path) -> dict:
return json.loads(schema.read_text(encoding="utf-8"))
def _node_classes(module: ModuleType) -> dict[str, type]:
return {
name: obj
for name, obj in vars(module).items()
if isinstance(obj, type)
and issubclass(obj, NodeBase)
and obj is not NodeBase
and obj.__module__ == module.__name__
}
def _call_literals(path: pathlib.Path, method: str) -> list[str]:
"""String literals passed as first argument to ``self.<method>(...)`` in the module."""
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
literals = []
for node in ast.walk(tree):
if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
continue
func = node.func
if func.attr != method or not isinstance(func.value, ast.Name) or func.value.id != "self":
continue
if node.args and isinstance(node.args[0], ast.Constant):
if isinstance(node.args[0].value, str):
literals.append(node.args[0].value)
return literals
@pytest.mark.parametrize("schema", SCHEMAS, ids=SCHEMA_IDS)
def test_schema_parses_into_node(schema: pathlib.Path) -> None:
node = ParseDict(_load_schema(schema), Node(), ignore_unknown_fields=True)
assert node.name, f"{schema}: 'name' must be set"
assert node.executionContext.className, f"{schema}: executionContext.className must be set"
@pytest.mark.parametrize("schema", SCHEMAS, ids=SCHEMA_IDS)
def test_class_name_matches_module_class(schema: pathlib.Path) -> None:
class_name = _load_schema(schema)["executionContext"]["className"]
classes = _node_classes(_load_module(_module_path(schema)))
assert class_name in classes, (
f"{schema}: executionContext.className {class_name!r} is not a NodeBase subclass "
f"defined in {_module_path(schema).name} (found: {sorted(classes)})"
)
@pytest.mark.parametrize("schema", SCHEMAS, ids=SCHEMA_IDS)
def test_port_keys_are_lowercase_snake_case(schema: pathlib.Path) -> None:
data = _load_schema(schema)
keys = list(data.get("inputs", {})) + list(data.get("outputs", {}))
bad = [k for k in keys if not SNAKE_CASE.match(k)]
assert not bad, f"{schema}: port keys must be lowercase snake_case: {bad}"
@pytest.mark.parametrize("schema", SCHEMAS, ids=SCHEMA_IDS)
def test_no_stop_output(schema: pathlib.Path) -> None:
outputs = _load_schema(schema).get("outputs", {})
stop_outputs = [k for k, v in outputs.items() if v.get("rosType") == "Stop"]
assert not stop_outputs, (
f"{schema}: a Stop output fires after every successful on_execute and stops "
f"downstream nodes; remove {stop_outputs}"
)
@pytest.mark.parametrize("schema", SCHEMAS, ids=SCHEMA_IDS)
def test_publish_and_get_data_literals_are_declared_ports(schema: pathlib.Path) -> None:
data = _load_schema(schema)
module_path = _module_path(schema)
outputs = set(data.get("outputs", {}))
inputs = set(data.get("inputs", {}))
unknown_outputs = [p for p in _call_literals(module_path, "publish") if p not in outputs]
unknown_inputs = [p for p in _call_literals(module_path, "get_data") if p not in inputs]
assert not unknown_outputs, f"{module_path}: publish() to undeclared outputs {unknown_outputs}"
assert not unknown_inputs, f"{module_path}: get_data() from undeclared inputs {unknown_inputs}"
To use it in your own repository, copy the file into tests/, point EXAMPLES at your src/
directory and drop the install_stubs() import if your test environment has ROS 2 installed. Run
it with poetry run pytest tests/ -q. See Testing for the
rest of the test setup.