Skip to content

Triggers

Triggers tell a node when to act; data ports tell it what to act on. After this page you can read the built-in trigger table, predict which of your hooks runs for an incoming trigger, know exactly what the SDK fires downstream after on_execute, declare trigger ports in the schema, and add your own trigger types with fire_trigger and @trigger_handler.

Two kinds of edges

A node graph has two kinds of edges. A data edge carries a ROS 2 message between an output port and an input port (see Dataflow). A trigger edge carries no payload of its own; it wakes the target node and, optionally, hands it a small TriggerContext saying who fired and why.

Under the hood a trigger is one small message on the node's transport; you never deal with topics or payloads yourself.

Python MQTT trigger configuration waits for the broker to confirm its input subscriptions. A trigger sent after successful configuration can no longer overtake subscription setup. Reconfiguration after teardown also waits for the previous MQTT network loop to stop before reconnecting.

Every trigger port has a type, written in the schema's rosType field. The type decides which of your hooks the SDK calls. Seven types are built in; any other string is a custom type that you handle yourself.

Built-in trigger types

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()

What the table means for your code:

  • Start, IfTrue, IfFalse, InLoop and BreakLoop all run on_execute. The SDK does not distinguish between them; the names only describe which upstream branch fires them (the true or false branch of a condition, the body or the exit of a loop), so a graph author can wire the matching output.
  • Error as an input also runs on_execute, but the context arrives with err_info set, so trigger_context.is_triggered_by_error() returns True. This is how you build an error-handler node (see below).
  • Stop ends the node's run: stop_execution() and your on_stop_execution() when the node overrides it, so the node stays configured. A node that still relies on the deprecated on_stop is torn down instead, as before SDK 2.43.0. See Lifecycle and states for the teardown order.

Incoming execute-type triggers are queued on a single worker thread per node, so two Start triggers arriving back to back run on_execute twice in sequence, never concurrently. A trigger that arrives after the node has been stopped is ignored and logged.

What the SDK fires after on_execute

You never fire the built-in outputs yourself. When on_execute returns, the SDK does this:

flowchart TD
    A[on_execute returns] -->|no exception| B[fire every declared Start output]
    B --> C[fire every declared Stop output]
    A -->|exception| D[fire every declared Error output<br/>context carries err_info]
    D --> E[node enters ERROR state<br/>NodeExecutionError is raised]
  • Success: every output port whose type is Start fires, with a TriggerContext whose source_node is your class name. Then every output whose type is Stop fires too.
  • Exception: every output whose type is Error fires, with err_info filled from the exception (err_type is the exception class, err_msg its text). The node moves to the ERROR state and the SDK raises NodeExecutionError. If no Error output is declared, nothing fires downstream.
  • Once stop() has begun, the implicit fan-out is switched off, so an in-flight on_execute that returns during shutdown wakes nobody.

Do not declare a Stop output

Because every declared Stop output fires after every successful run, a node with a stop output would stop its downstream nodes each time it executes. New nodes declare only start and error as trigger outputs.

Declaring trigger ports in the schema

Trigger ports live in the inputs and outputs maps of the schema file next to your module, with edgeType set to 2. The port key is lowercase snake_case; rosType carries the trigger type verbatim. The full port convention is on the schema file reference.

"inputs": {
  "start": { "rosType": "Start", "edgeType": 2 },
  "stop":  { "rosType": "Stop",  "edgeType": 2 }
},
"outputs": {
  "start":          { "rosType": "Start",         "edgeType": 2 },
  "error":          { "rosType": "Error",         "edgeType": 2 },
  "task_interrupt": { "rosType": "TaskInterrupt", "edgeType": 2 }
}

The first two inputs and the first two outputs are the standard set that almost every node declares. task_interrupt is a custom output of type TaskInterrupt. The key and the type are two different strings, and each SDK call takes one of them:

Call Takes Example
self.fire_trigger(...) the port key fire_trigger("task_interrupt")
@trigger_handler(...) the trigger type (rosType) @trigger_handler("SpecialStart")

On the SDK side nothing outside the schema and your node code is needed for a custom type; the port is declared, routed and validated from these two places alone.

TriggerContext and ErrorInformation

Both classes live in neuraverse_sdk.trigger.i_trigger and are Pydantic models. The same module holds the TriggerType enum with the seven built-in type names, should you need to compare against them in code.

TriggerContext field Type Meaning
source_node str Class name of the node that fired (for SDK-fired triggers) or whatever the caller passed
timestamp datetime Creation time, defaults to now
err_info ErrorInformation \| None Set only when the trigger was fired because of an exception
is_triggered_by_error() method, bool True when err_info is set
ErrorInformation field Type Meaning
err_type str Exception class of the failing node, as a string
err_msg str Exception message
transaction_id str Random UUID, generated per error

on_execute(self, trigger_context=None) receives the context of the trigger that woke the node, or None when the trigger carried none. An error-handler node reads it like this:

    def on_execute(self, trigger_context: Optional[TriggerContext] = None) -> None:
        # Start and Error both land here. Only the Error path carries err_info.
        if trigger_context is not None and trigger_context.is_triggered_by_error():
            err_info = trigger_context.err_info
            self.log_error(
                f"Upstream node {trigger_context.source_node!r} failed: "
                f"{err_info.err_type}: {err_info.err_msg} "
                f"(transaction {err_info.transaction_id})"
            )
            self.errors_seen.append(err_info.err_msg)
            return

        source = trigger_context.source_node if trigger_context else "unknown"
        self.log_info(f"ErrorHandlerNode started normally by {source!r}; nothing to handle")

The full worked example, including the upstream node that raises, is the cloud upload tutorial. Wire the upstream node's error output to the handler's start input; the handler then executes on the upstream failure and sees err_info.

To pass provenance further downstream, hand the context you received to your own fire_trigger call. The implicit Start/Error fan-out always builds a fresh context naming your node.

Custom output triggers

Call self.fire_trigger(port_key, trigger_context=None) from any code your node runs, inside on_execute or on a thread you own. The wired downstream nodes wake immediately; you do not have to return from on_execute first.

            # Fire the custom output port by its schema port KEY (not the
            # rosType). Every node wired to WatchdogNode.task_interrupt
            # wakes up NOW, while this on_execute is still running.
            self.fire_trigger("task_interrupt")

Rules:

  • The argument is the port key from your schema's outputs map. Firing a key you did not declare raises TriggerFlowException, and the message lists the declared trigger output keys.
  • Calling fire_trigger before the node has been initialised (no trigger transport yet) also raises TriggerFlowException.
  • If you pass no context, the SDK creates TriggerContext(source_node=<your class name>).
  • Custom outputs are additive. After on_execute returns, the built-in start (and error on failure) fan-out still happens as described above.
  • You may declare several ports of the same custom type; each is fired individually by key.

Custom input triggers

A custom input trigger runs a handler method of yours instead of on_execute. Bind the method to the trigger type with the decorator:

    # Bind the trigger TYPE (the schema's rosType), not the port key.
    @trigger_handler("SpecialStart")
    def on_special_start(self, trigger_context: Optional[TriggerContext] = None) -> None:
        source = trigger_context.source_node if trigger_context else "unknown"
        self.interrupts_received.append(source)
        self.log_info(f"SpecialStart received from {source}, switching to priority handling")

The decorator is imported with from neuraverse_sdk.trigger.i_trigger import TriggerContext, trigger_handler. If the handler is only known at runtime, register it imperatively in the constructor instead; this must happen before the node is configured:

def __init__(self) -> None:
    super().__init__()
    self.register_trigger_handler("SpecialStart", self._handle_special_start)

Handler rules

  • A declared custom input trigger requires a handler, even when the port is not connected. Configuring a node whose schema declares special_start of type SpecialStart without a bound handler fails with TriggerFlowException ("declares custom trigger type 'SpecialStart' but no handler is registered"). Typos fail at configure time instead of dropping events silently.
  • Built-in type names cannot be rebound. @trigger_handler("Start") or register_trigger_handler("Stop", ...) raises NodeConfigurationError. The decorator case is checked when the node object is created, so in a multi-node service the whole service fails at startup, which is what you want from CI.
  • Handlers are inherited. The SDK collects decorated methods across the class hierarchy; a subclass that decorates a method with the same type name overrides the base handler. Two methods in one class claiming the same type raise NodeConfigurationError.
  • A handler may take one optional trigger_context parameter or none. Both shapes are accepted and normalised; the return value is ignored.
  • Handlers run concurrently with an in-flight on_execute. Native events use the transport callback thread; external inputs use a separate worker. A TaskInterrupt must not queue behind the execution it interrupts. Keep handlers fast and non-blocking (set a flag, push to a queue) and protect anything they share with on_execute the same way you would for on_stop_execution.
  • The normal start input keeps driving on_execute; a handler only takes over the port(s) of its type.

Pause is cooperative. A paused node still receives triggers: execute-type triggers still run on_execute, and custom handlers still dispatch. Poll self.is_paused() in your own code if paused should mean idle.

Testing triggers

The Mock Runner creates your node object when you click Init, so a built-in type name or a duplicate handler raises there. It replaces the trigger transport with a stub, however: a declared custom input without a handler is not detected, nothing is fired and nothing is received. Unit tests can call on_execute and handler methods directly. For an end-to-end run over a real broker without an engine, see the testing page and the custom triggers tutorial, which walks through the two nodes in examples/custom_triggers/.

Common errors

Symptom Cause Fix
TriggerFlowException: Unknown output trigger port 'TaskInterrupt' fire_trigger was given the type instead of the key Pass the schema key, e.g. "task_interrupt"
TriggerFlowException: ... declares custom trigger type 'X' but no handler is registered at configure Schema declares a custom input type with no @trigger_handler("X") Add the handler, or remove the port
NodeConfigurationError: Cannot register a custom handler for built-in trigger type at startup @trigger_handler used with Start, Stop, Error, IfTrue, IfFalse, InLoop or BreakLoop Use a custom type name; built-ins keep their routing
NodeConfigurationError: Duplicate @trigger_handler(...) at startup Two methods in one class bound to the same type Keep one handler per type per class
Downstream nodes stop after every run A Stop output is declared Remove it; declare only start and error outputs
Downstream nodes never wake The transport was not connected when fire_trigger ran (a warning is logged) Fire only after the node is configured and running

External Start input

The platform can send Start to a declared input on a configured Python or C++ node.

Each input is addressed by its schema key. A disconnected Start input is valid, and two keys using Start remain separately addressable. Accepted input uses the same execution queue and on_execute / onExecute hook as an ordinary incoming Start trigger. Normal outgoing triggers still execute the wired downstream nodes; unrelated nodes keep working.

Acknowledgement means accepted for dispatch, not completed work. A timeout can leave the outcome unknown, and an explicit retry can repeat effects. Sending Start does not re-arm a stopped run or reset an errored node. After external input Stop, reconfigure the target through the normal lifecycle workflow before sending more input; use cleanup and reconfigure after an error. Unknown inputs, output keys and unregistered trigger types are rejected.

Provided trigger context and error information reach the hook unchanged. When a graph caller omits context, the platform supplies its authenticated identity and current UTC timestamp. Context describes execution; it is not an identity proof. Pause remains cooperative: the SDK still delivers input while paused. Guard work with is_paused() / isPaused() or suspend it in the pause hook, as described in lifecycle.

External input also supports Stop, Error, IfTrue, IfFalse, InLoop, BreakLoop and registered custom trigger types in Python and C++.

Stop runs the existing 2.x teardown on its target, including cleanup followed by on_stop / onStop with the supplied context. Unrelated branches continue. Further input to the stopped target fails with node_run_inactive until the normal lifecycle workflow reconfigures it. Python is_run_active() becomes false as soon as Stop is accepted. C++ hooks cooperate by setting a cancellation flag in onStopExecution(), allowing in-flight work to exit before teardown joins it. An input event does not initialize, re-arm or reset a node.

Custom keys resolve the declared handler type. Two keys sharing that type each invoke the same registered handler; neither needs an incoming connection. The other built-ins follow their ordinary wired execution path. Handlers remain responsible for cooperative pause. Acknowledgement promises dispatch acceptance; it does not promise completed work, and explicit retries may repeat effects.