Skip to content

Comments

Add Conditional Execution Support with IfNode#19

Merged
miguelgarcia merged 20 commits intomainfrom
if-behavior-node
Dec 4, 2025
Merged

Add Conditional Execution Support with IfNode#19
miguelgarcia merged 20 commits intomainfrom
if-behavior-node

Conversation

@miguelgarcia
Copy link
Member

@miguelgarcia miguelgarcia commented Dec 3, 2025

Add Conditional Execution Support with IfNode

Summary

This PR introduces conditional execution to the behavior tree system by implementing an IfNode that evaluates expressions and conditionally executes either a "then" or "else" branch based on the result. This enables mission definitions to include conditional logic based on robot state, sensor values, or other runtime conditions.

Implementing the new step required various changes related to the introduction of support for nested steps (Previously, no mission step had child steps). This presented some challenges since, for example, when translating a mission definition into a behavior tree, all steps in the then and else branches needed to be wrapped with timeout handling, task completion reporting, etc.

Demo

screenrecording-2025-12-03_13-36-26.mp4

Changes

Core Implementation

  • IfNode class (behavior_tree.py): New behavior tree node that:

    • Evaluates expressions via REST API (with retry logic: 5 attempts, configurable wait time)
    • Executes then_branch when expression evaluates to True
    • Executes else_branch when expression evaluates to False (optional)
    • Supports target robot evaluation (evaluates expression on a different robot if specified)
    • Propagates state and errors from executed branches
    • Implements full serialization/deserialization support
    • Properly handles node collection and execution reset for nested trees
  • MissionStepIf datatype (datatypes.py): New mission step type that:

    • Accepts an expression string for evaluation
    • Contains then and optional else branches (lists of mission steps)
    • Supports target robot specification
    • Implements visitor pattern for tree building
  • Visitor pattern integration (behavior_tree.py):

    • Added visit_if method to NodeFromStepBuilder to convert MissionStepIf to IfNode
    • Builds nested behavior trees for both then and else branches

Supporting Changes

  • MissionTasksExtractor class (mission.py): New helper class that:

    • Recursively extracts tasks from nested mission steps
    • Properly handles tasks within if step branches
    • Replaces the previous flat task extraction logic
  • Base class improvements (datatypes.py):

    • Added abstract accept method to MissionStep base class to enforce visitor pattern implementation

Testing

  • Comprehensive test suite (tests/test_if_node.py): 393 lines of tests covering:

    • True/false branch execution
    • Missing else branch handling (no-op when false)
    • Target robot evaluation
    • Error propagation from expression evaluation
    • Error propagation from executed branches
    • Serialization/deserialization (with and without else branch)
    • Node collection and execution reset
    • All edge cases and error scenarios
  • Integration tests (tests/test_behavior_tree.py): Updated to verify if step parsing and tree building

Examples

  • Updated example (example.py): Added demonstration of if step usage with then/else branches containing waypoint steps

Technical Details

Expression Evaluation

  • Expressions are evaluated via REST API calls to the robot's expression evaluation endpoint
  • Retry logic: 5 attempts with configurable wait time (default 3 seconds)
  • Errors during expression evaluation are propagated and cause the node to enter error state

Branch Execution

  • Only one branch (then or else) is executed based on expression result
  • The node's state and error are set from the executed branch
  • If expression is False and no else branch exists, the node succeeds (no-op)

Serialization

  • Full support for serialization/deserialization of IfNode and nested branches
  • Else branch is optional in serialized format (omitted if None)

Usage Example

MissionStepIf.model_validate({
    "label": "check battery",
    "if": {
        "expression": "getValue('battery') > 50",
        "then": [
            {"label": "go to waypoint A", "waypoint": {...}},
        ],
        "else": [
            {"label": "go to charging station", "waypoint": {...}},
        ],
    },
})

Breaking Changes

None. This is a purely additive feature that maintains backward compatibility.
Anyway I think we need to bump the major version since this introduces a new step that connector implementors should at least be aware of.

Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR is being reviewed by Cursor Bugbot

Details

Your team is on the Bugbot Free tier. On this plan, Bugbot will review limited PRs each billing cycle for each member of your team.

To receive Bugbot reviews on all of your PRs, visit the Cursor dashboard to activate Pro and start your 14-day free trial.

current_task_id = self._find_current_task_id()
if current_task_id:
req["currentTaskId"] = current_task_id
print(f"Reporting tasks: {req}")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Debugging print statement left in production code

A print(f"Reporting tasks: {req}") statement was accidentally left in the report_tasks method. This will output task information to stdout during production execution, which is unintended debug output. The proper logging mechanism (logger) is already used elsewhere in this class and file.

Fix in Cursor Fix in Web

@miguelgarcia miguelgarcia changed the title Draft: If behavior node Add Conditional Execution Support with IfNode Dec 3, 2025
@miguelgarcia miguelgarcia requested a review from b-Tomas December 3, 2025 16:37
@miguelgarcia miguelgarcia self-assigned this Dec 3, 2025
@miguelgarcia miguelgarcia added the enhancement New feature or request label Dec 3, 2025
@miguelgarcia
Copy link
Member Author

Hey @b-Tomas can you review? I extended the executor to support the new If step

Copy link
Member

@b-Tomas b-Tomas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One comment

LGTM otherwise

@miguelgarcia miguelgarcia merged commit e193759 into main Dec 4, 2025
7 checks passed
@miguelgarcia miguelgarcia deleted the if-behavior-node branch December 4, 2025 12:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants