MCTS decisively beats A* on a stochastic gridworld#

Classical GOAP collapses to A* over the state space. A* is optimal under deterministic dynamics, but its plans can be reckless under noise: it treats expected(state, action) as truth, so a short path that grazes a terminal hazard looks identical to a longer path that stays clear of it.

LangGOAP’s MCTSStrategy switches to a Decision → Chance → Decision tree expansion whenever the supplied TransitionModel is non-deterministic. Each chance node aggregates values from multiple model.sample() outcomes, so the search sees the risk of a slip on the tree itself rather than only in the rollout tail.

This notebook reproduces the pre-registered result captured by tests/integration/test_mcts_beats_astar_stochastic.py on FrozenLake-4x4. The same fixture, rollout, and scoring code drives the test and the notebook, so the numbers here match the CI assertion.

The FrozenLake-4x4 domain#

Gymnasium’s default 4x4 map:

S F F F
F H F H
F F F H
H F F G

Holes (H) are terminal: stepping onto one ends the episode with reward 0. Goal (G) ends with reward +1. Slip dynamics follow the Gymnasium convention — with probability slip_prob the agent moves perpendicular to its intended direction (left or right, uniformly). The declared effects A* consults are the unperturbed grid, so A* plans as if the world were deterministic.

import sys, pathlib
sys.path.insert(0, str(pathlib.Path.cwd().parent.parent))  # LangGOAP/langgoap

from tests.benchmarks.stochastic_gridworld_bench import run_cell
from tests.fixtures.stochastic_gridworld import frozen_lake_4x4

SEEDS = list(range(42, 72))  # 30 paired seeds
SLIP_PROB = 0.2
topology = frozen_lake_4x4()
print(f"topology: {topology.rows}x{topology.cols}, start={topology.start}, goal={topology.goal}")
print(f"holes: {sorted(topology.holes)}")
topology: 4x4, start=(0, 0), goal=(3, 3)
holes: [(1, 1), (1, 3), (2, 3), (3, 0)]

Two strategies, identical environment draws#

run_cell seeds environment and strategy RNGs separately, so every seed produces the same noise sequence for both A* and MCTS. The comparison is paired, not independent.

astar_eps = run_cell(topology=topology, strategy_name="astar", seeds=SEEDS, slip_prob=SLIP_PROB)
mcts_eps  = run_cell(topology=topology, strategy_name="mcts",  seeds=SEEDS, slip_prob=SLIP_PROB)
print(f"finished {len(astar_eps) + len(mcts_eps)} episodes")
finished 60 episodes
import statistics
from statistics import NormalDist

def summarise(name, eps):
    rets = [e.total_return for e in eps]
    goal = sum(1 for e in eps if e.reached_goal) / len(eps)
    hole = sum(1 for e in eps if e.terminated and not e.reached_goal) / len(eps)
    return dict(name=name, n=len(eps), goal=goal, hole=hole,
                mean=statistics.mean(rets),
                std=statistics.stdev(rets) if len(rets) > 1 else 0.0)

def welch_p_one_sided(t, b):
    mt, mb = statistics.mean(t), statistics.mean(b)
    vt, vb = statistics.variance(t), statistics.variance(b)
    nt, nb = len(t), len(b)
    se = (vt/nt + vb/nb) ** 0.5
    return 1.0 - NormalDist().cdf((mt - mb) / se) if se > 0 else 0.5

summaries = [summarise("astar", astar_eps), summarise("mcts", mcts_eps)]
p = welch_p_one_sided([e.total_return for e in mcts_eps],
                      [e.total_return for e in astar_eps])

print(f"{'strategy':10s}  {'n':>3s}  {'goal%':>6s}  {'hole%':>6s}  {'mean±std':>15s}")
for s in summaries:
    print(f"{s['name']:10s}  {s['n']:3d}  {100*s['goal']:5.1f}%  {100*s['hole']:5.1f}%  {s['mean']:.3f}±{s['std']:.3f}")
print(f"\none-sided Welch p(mcts > astar mean return) = {p:.4f}")
strategy      n   goal%   hole%         mean±std
astar        30    3.3%   96.7%  0.033±0.183
mcts         30   26.7%   73.3%  0.267±0.450

one-sided Welch p(mcts > astar mean return) = 0.0042

Why MCTS wins here and A* cannot#

A* picks a shortest path like south, south, east, east, east, south that skirts two holes. At slip_p=0.2 the first south slips west into the wall (harmless), or slips east into hole (1,1). The A* plan is replayed on the post-slip state, finds the next-shortest path, and repeats — but A*’s world model never assigns negative value to being adjacent to a hole, so it cannot find the longer, safer corridor.

MCTS with chance-node expansion builds a tree where each action edge points to a chance node whose value is the empirical mean of sampled successors. Under a 20% slip, the chance node below south @ (0,0) averages (0.8 * V(move succeeded)) + (0.1 * V(slipped into hole)) + (0.1 * V(slipped west into wall)). The hole outcome carries total return 0 forever after; the chance node’s mean drops; UCB1 at the root prefers a different opening move. The library never had to be told hazards existed — the tree inferred their value from samples.

What’s under the hood#

  • SlipperyTransitionModel.expected(state, action) returns the action’s declared effect — A*’s deterministic world model.

  • SlipperyTransitionModel.sample(state, action, rng) draws from the slip distribution — MCTS’s chance nodes consult this.

  • MCTSStrategy._select_stochastic descends decision → chance → decision, collapsing repeated samples of the same successor onto a single decision-node child via ChanceNode.children_by_key.

  • Backpropagation walks the union-typed parent chain transparently; ChanceNode exposes the same visits/value surface as MCTSNode.

On a DeterministicTransitionModel the whole chance layer is bypassed (_expand is used instead of _expand_stochastic), so classical GOAP users pay zero overhead for this feature.