Debugging and visualization

How to find out why a behavior tree did what it did: draw the tree, read a trace from the root's result down to the leaf that decided it, explain why a node never ran, and log the same story from inside a game.

An archer keeps running for cover in the middle of a fight, at full health, with an enemy in range and a full quiver. Nothing crashes. The tree validates. The question a person asks is “why did run_to_cover run?”, and its twin, “why did shoot not run?”. A behavior tree can answer both, because every decision it makes is a node returning a status to its parent. Debugging a tree means making those answers visible and reading them in the right order.

This page does that in four steps: draw the tree so you know its shape, reproduce the moment in a simulation, read the trace from the root down to the node that decided, and then log the same thing from inside a running game.

See the shape first

Most surprises in a behavior tree come from its shape: a child in the wrong order, a branch under the wrong parent, a condition that guards less than you thought. Before you read any run, look at the tree as a tree. beetree render draws it:

beetree render archer.beetree.yaml
[SEL] archer_root
├── [SEQ] take_cover_when_hurt
│   ├── [CND] health_low
│   └── [ACT] run_to_cover
├── [SEQ] shoot_enemy
│   ├── [CND] enemy_in_range
│   ├── [CND] has_arrows
│   └── [ACT] shoot
└── [ACT] wander

Read it the way the tree runs it. The root is a selector (a Fallback, from Building blocks): it tries its children from top to bottom and stops at the first that does not fail. So the order of its children is a priority list, and taking cover outranks shooting. Each sequence is a chain of steps that stops at the first step that does not succeed, so run_to_cover only runs when health_low succeeds.

The same command draws for other tools. --format mermaid prints a Mermaid flowchart that GitHub and most wikis show as a picture, and --format dot prints Graphviz, so beetree render archer.beetree.yaml --format dot | dot -Tsvg > archer.svg makes an image for a design document. --format compact prints one node per line with indentation only, which is the form to compare two versions of a tree in:

diff <(beetree render archer-old.beetree.yaml --format compact) <(beetree render archer.beetree.yaml --format compact)

A changed line in that diff is a changed decision, including two children that swapped places.

A tree to debug

version: "1.0"
metadata:
  name: archer
  description: "Takes cover when hurt, shoots an enemy in range while it has arrows, and wanders otherwise"
  tags: [debugging, visualization]
tree:
  type: selector
  name: archer_root
  children:
    - type: sequence
      name: take_cover_when_hurt
      children:
        - {type: condition, name: health_low, node: HealthLow}
        - {type: action, name: run_to_cover, node: RunToCover}
    - type: sequence
      name: shoot_enemy
      children:
        - {type: condition, name: enemy_in_range, node: EnemyInRange}
        - {type: condition, name: has_arrows, node: HasArrows}
        - {type: action, name: shoot, node: Shoot}
    - {type: action, name: wander, node: Wander}

Save it as archer.beetree.yaml. To reproduce the bug, describe the moment to the simulator. A simulation runs the tree without the game, and each leaf returns a status you choose instead of doing its work (Testing and simulation covers this in full). beetree simulate lets every leaf succeed unless --override says otherwise, which here describes exactly the moment the player reported: hurt or not, the enemy is in range and there are arrows.

beetree simulate archer.beetree.yaml
Simulation: archer_root → SUCCESS
──────────────────────────────────────────────────
▶ ? archer_root
  ▶ → take_cover_when_hurt
    ● ¿ health_low → SUCCESS
    ● ! run_to_cover → SUCCESS
  ◀ → take_cover_when_hurt → SUCCESS
◀ ? archer_root → SUCCESS

Read a trace from the result down

The printout above is a trace: every node the tree ticked, in order. ▶ marks a composite starting, ◀ marks it finishing with its status, and ● marks a leaf and what it returned. Indentation is depth in the tree, and the sigils say the node type (? a selector, → a sequence, ¿ a condition, ! an action).

Read it backwards, from the answer to its cause:

  1. Start at the root’s result. archer_root → SUCCESS. A selector succeeds as soon as one child succeeds, so find the last child it ticked: take_cover_when_hurt, which succeeded.
  2. Go down into that child. A sequence succeeds only when every step succeeds, so look for what let it through: health_low → SUCCESS.
  3. Stop at the leaf. The leaf that decided is a condition, and the tree did exactly what it was told. The bug is in the question health_low asks, not in the tree.

The rule behind those steps: for a sequence or a selector, the last child it ticked decided its result. A sequence stops at the first child that fails or is running; a selector stops at the first that succeeds or is running; if neither stops early, the last child decided anyway. A decorator’s result comes from its one child, changed by its policy. So from any line of a trace you can walk down to one leaf, and that leaf is where to look next in the game: its threshold, its sensor, the value it reads.

Why a node never ran

The second question, “why did shoot not run?”, has a trace too: shoot is simply not in it. A node is missing from a trace for one of two reasons, and both can be read from the lines that are there:

  • An earlier sibling ended its parent. In the trace above, take_cover_when_hurt succeeded, so the selector archer_root stopped and never ticked shoot_enemy. The cause of a missing node is the last sibling before it that did run.
  • A sibling before it in a sequence did not succeed. When the enemy is in range but the quiver is empty, the sequence stops at has_arrows:
beetree simulate archer.beetree.yaml --override health_low=FAILURE --override has_arrows=FAILURE
▶ ? archer_root
  ▶ → take_cover_when_hurt
    ● ¿ health_low → FAILURE
  ◀ → take_cover_when_hurt → FAILURE
  ▶ → shoot_enemy
    ● ¿ enemy_in_range → SUCCESS
    ● ¿ has_arrows → FAILURE
  ◀ → shoot_enemy → FAILURE
  ● ! wander → SUCCESS
◀ ? archer_root → SUCCESS

shoot is missing because has_arrows failed, and the archer wanders instead. To explore a moment rather than describe it, run beetree simulate archer.beetree.yaml --step: it pauses at each leaf and asks for its status. In the web builder, paste the tree and open the Debug tab: Step through marks each node in the outline as it is visited and shows the trace beside it, so a node that stays unmarked is one that never ran.

Visualizing a tree while the game runs

A simulation answers “what would the tree do”, but some bugs only appear in the game, where a leaf’s real answer depends on the world. The technique is the same: record what each node returned this tick, in the order it ran, and show it. Commercial tools draw it over the tree: Unreal’s Behavior Tree editor highlights the active branch while you play in the editor, and Groot2 does the same for BehaviorTree.CPP. In your own runtime, a small decorator gives you the same record.

The probe below wraps any node. When the node runs, the probe adds a line to a tick log with the node’s name and its depth, and fills in the status when the node returns, so the log comes out in the same order and shape as the trace above. A short function then prints each line with the child that decided it, using the rule from the previous section. Clear the log at the start of each tick, and print it when the behavior surprises you, or draw it as text over the character’s head. Each sample builds on the Status type and tick() contract from Building blocks.

Agnostic

TickLog: entries = []    // {name, depth, status}, in the order nodes started
         depth = 0

Probe(name, child, log):
    tick():
        index = len(log.entries)
        log.entries.append({name, depth: log.depth, status: none})
        log.depth += 1
        status = child.tick()
        log.depth -= 1
        log.entries[index].status = status
        return status

decidedBy(log, i):       // the last child ticked under entry i, or none for a leaf
    decider = none
    for j in i + 1 .. len(log.entries) - 1 while log.entries[j].depth > log.entries[i].depth:
        if log.entries[j].depth == log.entries[i].depth + 1: decider = log.entries[j].name
    return decider

Unity C#

public class TickLog
{
    public struct Entry
    {
        public string Name;
        public int Depth;
        public Status Status;
    }

    // In the order nodes started; cleared at the start of each tick.
    public readonly System.Collections.Generic.List<Entry> Entries = new System.Collections.Generic.List<Entry>();
    public int Depth;

    public void Clear()
    {
        Entries.Clear();
        Depth = 0;
    }

    // The last child ticked under entry i, or null for a leaf.
    public string DecidedBy(int i)
    {
        string decider = null;
        for (int j = i + 1; j < Entries.Count && Entries[j].Depth > Entries[i].Depth; j++)
            if (Entries[j].Depth == Entries[i].Depth + 1) decider = Entries[j].Name;
        return decider;
    }

    public override string ToString()
    {
        var text = new System.Text.StringBuilder();
        for (int i = 0; i < Entries.Count; i++)
        {
            var decider = DecidedBy(i);
            text.Append(new string(' ', 2 * Entries[i].Depth)).Append(Entries[i].Name).Append(' ').Append(Entries[i].Status);
            if (decider != null) text.Append("  (decided by ").Append(decider).Append(')');
            text.Append('\n');
        }
        return text.ToString();
    }
}

public class Probe : Node
{
    readonly string name;
    readonly Node child;
    readonly TickLog log;

    public Probe(string name, Node child, TickLog log)
    {
        this.name = name;
        this.child = child;
        this.log = log;
    }

    public override Status Tick()
    {
        int index = log.Entries.Count;
        log.Entries.Add(new TickLog.Entry { Name = name, Depth = log.Depth });
        log.Depth++;
        var status = child.Tick();
        log.Depth--;
        var entry = log.Entries[index];
        entry.Status = status;
        log.Entries[index] = entry;
        return status;
    }
}

GDScript

class TickLog:
    var entries: Array[Dictionary] = []   # {name, depth, status}, in the order nodes started
    var depth := 0

    func clear() -> void:
        entries.clear()
        depth = 0

    # The last child ticked under entry i, or "" for a leaf.
    func decided_by(i: int) -> String:
        var decider := ""
        var j := i + 1
        while j < entries.size() and int(entries[j]["depth"]) > int(entries[i]["depth"]):
            if int(entries[j]["depth"]) == int(entries[i]["depth"]) + 1:
                decider = str(entries[j]["name"])
            j += 1
        return decider

    func describe() -> String:
        var text := ""
        for i in entries.size():
            var entry: Dictionary = entries[i]
            text += "  ".repeat(int(entry["depth"])) + "%s %s" % [entry["name"], BTNode.Status.keys()[int(entry["status"])]]
            var decider := decided_by(i)
            if decider != "":
                text += "  (decided by %s)" % decider
            text += "\n"
        return text

class Probe extends BTNode:
    var node_name: String
    var child: BTNode
    var tick_log: TickLog

    func _init(n: String, c: BTNode, l: TickLog):
        node_name = n
        child = c
        tick_log = l

    func tick() -> Status:
        var index := tick_log.entries.size()
        tick_log.entries.append({"name": node_name, "depth": tick_log.depth, "status": Status.FAILURE})
        tick_log.depth += 1
        var status := child.tick()
        tick_log.depth -= 1
        tick_log.entries[index]["status"] = status
        return status

Unreal C++

struct FTickEntry
{
    FString Name;
    int32 Depth = 0;
    EStatus Status = EStatus::Failure;
};

struct FTickLog
{
    TArray<FTickEntry> Entries; // in the order nodes started; emptied at the start of each tick
    int32 Depth = 0;

    // The index of the last child ticked under entry I, or -1 for a leaf.
    int32 DecidedBy(int32 I) const
    {
        int32 Decider = -1;
        for (int32 J = I + 1; J < Entries.Num() && Entries[J].Depth > Entries[I].Depth; ++J)
        {
            if (Entries[J].Depth == Entries[I].Depth + 1) Decider = J;
        }
        return Decider;
    }

    void Print() const
    {
        for (int32 I = 0; I < Entries.Num(); ++I)
        {
            const int32 Decider = DecidedBy(I);
            UE_LOG(LogTemp, Display, TEXT("%*s%s %d%s%s"), Entries[I].Depth * 2, TEXT(""), *Entries[I].Name,
                static_cast<int32>(Entries[I].Status), Decider >= 0 ? TEXT("  decided by ") : TEXT(""),
                Decider >= 0 ? *Entries[Decider].Name : TEXT(""));
        }
    }
};

class FProbe : public FNode
{
public:
    FString Name;
    TSharedPtr<FNode> Child;
    FTickLog* Log = nullptr;

    EStatus Tick() override
    {
        const int32 Index = Log->Entries.Num();
        Log->Entries.Add(FTickEntry{Name, Log->Depth});
        ++Log->Depth;
        const EStatus Status = Child->Tick();
        --Log->Depth;
        Log->Entries[Index].Status = Status;
        return Status;
    }
};

Wrap the nodes you care about, or all of them, when you build the tree. For the archer at the moment of the bug, the log prints archer_root Success (decided by take_cover_when_hurt), then take_cover_when_hurt Success (decided by run_to_cover) and the two leaves, indented under it. The “decided by” rule holds for sequences, selectors and decorators. A parallel node ticks every child and decides by counting, so for a parallel read all of its children’s lines instead (Concurrency explains its policies). Keep the probes in development builds only: a log line per node per tick is cheap for one character and noisy for a hundred.

What BeeTreeCraft shows today

  • A trace shows what each node returned, not why. You follow “decided by” yourself with the rule above; a trace that names the deciding child on each line is planned.
  • beetree simulate runs one tick, so a bug that needs several ticks is played as one command per tick, as on the Reactive versus memory nodes page.
  • A trace does not show the values a condition read (health, distance, ammunition). The simulator does not run your conditions, so the values belong to the game: log them next to the probe’s line for the leaf that decided.

Where it comes from

Champandard and Dunstan’s The Behavior Tree Starter Kit (Game AI Pro, 2013) builds the node, status and composite contract these probes rely on. Unreal’s Behavior Tree debugger highlights the active branch while the game runs, and Groot2 shows a BehaviorTree.CPP tree’s live statuses and replays recorded logs. Colledanchise and Ögren’s Behavior Trees in Robotics and AI (2018) explains why a tree’s structure makes its decisions easier to trace than a state machine’s transitions. More reading is on the Resources page.

Next, open the Build hub, paste the archer into the builder, and use Step through in the Debug tab to find the leaf that sends it running for cover; then fix health_low, and read about the tree format to change the tree itself.