Module contents
Lesson 21 of 23Advanced 105 min

Beyond state-space search: planning as SAT, GraphPlan, partial-order and HTN planning

Planning includes approaches beyond heuristic search. Study GraphPlan and mutual exclusions, planning as satisfiability with horizons and incremental SAT, partial-order planning with causal links, and hierarchical task networks, the dominant industry approach, ending with a map beyond classical planning.

After this lesson you can

  • Build a planning graph with mutual exclusions and extract plans with GraphPlan.
  • Encode planning as SAT with explanatory frame axioms and solve using incremental horizons.
  • Build partial-order plans by resolving threats through promotion and demotion.
  • Design HTN domains with alternative methods and assess their risks.
  • Place temporal, numeric and nondeterministic extensions relative to the classical model.

Before you start

Motivation: a plan as an object, not a path

In the previous lesson a plan was a path through state space: start at the initial state, apply a STRIPS action, reach another state, and heuristic search guided by delete relaxation decides what to expand. This dominates classical planning competitions, but is not the only approach, and each alternative answers a question state search handles poorly.

  • What can happen simultaneously? Two trucks delivering in different cities do not interfere. A state-space path serializes them and pays depth equal to all actions. GraphPlan and SAT encodings reason in steps containing multiple independent actions.
  • What is impossible without search? Polynomial propagation can prove two facts cannot both hold at time 3 without enumerating one state. GraphPlan mutexes do this.
  • Why commit early? If backup and patch download are independent, arbitrarily ordering them hides useful information from the executor. Partial-order plans order only what must be ordered.
  • What if I already know how? A security operations center does not search from scratch for incident response: procedures say “contain, eradicate, recover” and how to do each. Hierarchical task networks (HTN) plan by refining that knowledge, dominating many real applications.

The lesson treats all four rigorously: definitions, the theorem justifying each, an executable from-scratch implementation and an interactive demonstration. It ends with a map beyond the classical model: time, numeric resources, nondeterminism and uncertainty.

GraphPlan: the planning graph

Blum and Furst introduced GraphPlan at IJCAI 1995 (journal version: Fast planning through planning graph analysis, 1997), with immediate impact: it solved in seconds problems contemporary planners did not finish. The idea builds forward, in polynomial time, a layered structure overapproximating what is reachable in ii steps and recording incompatible pairs. It then searches backward within that structure for a plan.

We use literals: an atom pp or its negation ¬p\neg p, allowing negative preconditions and goals as in Russell and Norvig. The initial state is closed-world (absent means false). Each literal ℓ\ell has a persistence action (no-op) with precondition ℓ\ell and effect ℓ\ell, expressing that it remains unchanged.

Mutexes propagate: literal mutexes in SiS_i create competing needs in AiA_i, which in turn leave Si+1S_{i+1} literals without consistent support. None requires search: each level checks pairs in polynomial time in literals and actions.

Russell and Norvig’s classic example is “having your cake and eating it”. The initial state is {tengo}\{\mathit{tengo}\} (and, closed-world, ¬comida\neg\mathit{comida}), goal tengo∧comida\mathit{tengo} \wedge \mathit{comida}, with two actions: Eat, precondition tengo\mathit{tengo} and effects comida,¬tengo\mathit{comida}, \neg\mathit{tengo}; Bake, precondition ¬tengo\neg\mathit{tengo} and effect tengo\mathit{tengo}. Weld’s second “surprise dinner” example has garbage, clean hands and quiet at home; goals are dinner, wrapped present and no garbage. Cooking needs clean hands; wrapping needs quiet; taking out garbage dirties hands and the cart makes noise.

InteractiveGraphPlan mutexes
S0A0S1A1S2Eathave¬eatenhave¬haveeaten¬eaten
  • positive effect
  • negative effect
  • keep (no-op)
  • mutual exclusion
  • chosen during extraction
Problem
1 / 6
Goalhave ∧ eaten
Literals in S1S_14
Mutex pairs in S1S_14
Actions in A0A_01 (+2 noop)
Mutex pairs in A0A_02
Level 1: all goals are present, but have and eaten are mutually exclusive. Expand another level.
The planning graph level by level, using data calculated by the lesson's first cell. Dashed lines are persistence; red lines are goal mutexes. With cake, both goals are in S1S_1 but mutex: eating and preserving cake have inconsistent effects. At S2S_2 they are no longer mutex and backward extraction finds the plan. Touch comida\mathit{comida} at S1S_1 and S2S_2 to compare mutexes. In surprise dinner, S1S_1 has no goal mutexes but extraction still fails: the graph is an approximation.

Notice two things. With cake at S1S_1, tengo\mathit{tengo} and comida\mathit{comida} are mutex: comida\mathit{comida} is achieved only by Eat and tengo\mathit{tengo} only by persistence of tengo\mathit{tengo}, inconsistent with Eat. At A1A_1 Bake appears because ¬tengo\neg\mathit{tengo} is already in S1S_1, and at S2S_2 pair (tengo,comida)(\mathit{tengo}, \mathit{comida}) has consistent support: preserve comida\mathit{comida} and Bake. In dinner at S1S_1, no goal pair is mutex: cena\mathit{cena} and ¬basura\neg\mathit{basura} can be achieved by cook and cart; regalo\mathit{regalo} and ¬basura\neg\mathit{basura} by wrap and take out. But not all three: take out interferes with cook and cart with wrap. Mutexes are pairwise, and pairwise nonmutex goals may be impossible together.

Graph properties

Persistence puts every literal of SiS_i in Si+1S_{i+1} and every action of AiA_i in Ai+1A_{i+1}. Mutexes move the opposite way: Blum and Furst prove that if two literals (or actions) are nonmutex at one level, they remain so next level. With finitely many literals and pairs, eventually nothing changes: the graph levels off. Each level is linear in grounded literals and actions, mutex computation quadratic, so constructing kk levels takes polynomial time in kk and problem size.

You will prove this by induction on ii in the guided exercise. Two consequences. First, the level where goals appear without mutexes lower-bounds any plan’s parallel steps. Haslum and Geffner (Admissible heuristics for optimal planning, AIPS 2000) related it to admissible heuristic family hmh^m: for parallel steps, the graph and mutexes compute essentially h2h^2, which is to atom pairs what the previous lesson’s hmax⁡h_{\max} is to individual atoms. Second, the converse is false, as dinner showed. GraphPlan therefore needs a second phase.

Backward extraction and nogoods

When every goal is in SkS_k without pairwise mutexes, GraphPlan attempts to extract a plan: choose for each goal an Ak−1A_{k-1} action achieving it (preferring persistence), with chosen actions pairwise nonmutex; their preconditions become goals of level k−1k - 1, and repeat to S0S_0. This is backtracking like logic programming’s backward chaining, bounded by levels. On failure record the goal set as a nogood at that level and do not retry; then add a level and repeat.

When can we conclude no plan exists? Blum and Furst proved that if the graph has leveled off at nn and the level nn nogood set does not change between consecutive extraction attempts, no plan of any length exists. Without that test GraphPlan would add levels forever on an unsolvable problem.

The cell implements everything from scratch: the graph with three action-mutex and two literal-mutex rules, extraction with nogoods and the termination test. The figure’s data comes from the same class.

[ ]GraphPlan from scratch: cake and surprise dinnerBrowser
from collections import namedtuple
from itertools import combinations

# ---------------- STRIPS mínimo (el de la lección anterior) ----------------
Accion = namedtuple("Accion", "nombre pre add dele")
Tarea = namedtuple("Tarea", "atomos init meta acciones")

def accion(nombre, pre=(), add=(), dele=()):
    return Accion(nombre, frozenset(pre), frozenset(add), frozenset(dele) - frozenset(add))

# ---------------- GraphPlan con literales (átomo, polaridad) ----------------
def neg(l):
    return (l[0], not l[1])

def lit(s):
    return (s[1:], False) if s.startswith("¬") else (s, True)

def nombre_lit(l):
    return ("" if l[1] else "¬") + l[0]

class Op:
    def __init__(self, nombre, pre=(), add=(), dele=(), noop=False):
        self.nombre, self.noop = nombre, noop
        self.pre = frozenset(pre)                                   # literales
        self.efe = frozenset([(p, True) for p in add] + [(p, False) for p in dele])

def op(nombre, pre=(), add=(), dele=()):
    return Op(nombre, [lit(p) for p in pre], add, dele)

def noop(l):
    return Op(f"mantener {nombre_lit(l)}", [l], [l[0]] if l[1] else [], [] if l[1] else [l[0]], noop=True)

class GrafoPlan:
    def __init__(self, atomos, init, ops):
        self.ops = ops
        self.S = [frozenset((p, p in init) for p in atomos)]       # S_0: mundo cerrado
        self.muS = [set()]                                          # exclusiones entre literales
        self.A, self.muA = [], []                                   # niveles de acciones y sus exclusiones
        self.nogood = {}
        self.traza = []                                             # pasos de la extracción (para la figura)

    def mutex_lit(self, i, l1, l2):
        return frozenset((l1, l2)) in self.muS[i]

    def expandir(self):
        i, S = len(self.A), self.S[-1]
        acts = [noop(l) for l in sorted(S)] + [o for o in self.ops
                if o.pre <= S and not any(self.mutex_lit(i, p, q) for p, q in combinations(o.pre, 2))]
        mu = set()
        for a, b in combinations(acts, 2):
            if (any(neg(e) in b.efe for e in a.efe)                                  # efectos inconsistentes
                    or any(neg(e) in b.pre for e in a.efe) or any(neg(e) in a.pre for e in b.efe)   # interferencia
                    or any(self.mutex_lit(i, p, q) for p in a.pre for q in b.pre)):  # necesidades en competencia
                mu.add(frozenset((a, b)))
        S2 = frozenset(e for a in acts for e in a.efe)
        logra = {l: [a for a in acts if l in a.efe] for l in S2}
        muS = set()
        for l1, l2 in combinations(sorted(S2), 2):
            if l1 == neg(l2) or all(a is not b and frozenset((a, b)) in mu for a in logra[l1] for b in logra[l2]):
                muS.add(frozenset((l1, l2)))                        # negación o apoyo inconsistente
        self.A.append(acts); self.muA.append(mu); self.S.append(S2); self.muS.append(muS)

    def extraer(self, metas, i):
        """Búsqueda hacia atrás desde el nivel i con memoria de conjuntos imposibles (nogoods)."""
        if i == 0:
            self.traza.append(("inicial", 0, metas))
            return [] if metas <= self.S[0] else None
        if metas in self.nogood.get(i, set()):
            self.traza.append(("memo", i, metas))
            return None
        plan = self._elegir(sorted(metas), 0, [], i)
        if plan is None:
            self.nogood.setdefault(i, set()).add(metas)
            self.traza.append(("falla", i, metas))
        return plan

    def _elegir(self, metas, k, elegidas, i):
        if k == len(metas):
            self.traza.append(("elige", i, [a.nombre for a in elegidas]))
            sub = frozenset(p for a in elegidas for p in a.pre)
            antes = self.extraer(sub, i - 1)
            return None if antes is None else antes + [[a.nombre for a in elegidas if not a.noop]]
        g = metas[k]
        if any(g in a.efe for a in elegidas):                       # ya la logra una acción elegida
            return self._elegir(metas, k + 1, elegidas, i)
        cand = sorted((a for a in self.A[i - 1] if g in a.efe), key=lambda a: not a.noop)
        for a in cand:                                              # primero los mantenimientos
            if all(frozenset((a, b)) not in self.muA[i - 1] for b in elegidas):
                r = self._elegir(metas, k + 1, elegidas + [a], i)
                if r is not None:
                    return r
        return None

    def resolver(self, metas, max_niveles=60, traza=True):
        metas = frozenset(lit(m) for m in metas)
        nivelado, nogoods_antes = None, -1
        while len(self.A) < max_niveles:
            i = len(self.S) - 1
            if metas <= self.S[i] and not any(self.mutex_lit(i, p, q) for p, q in combinations(metas, 2)):
                self.traza.append(("intento", i, metas))
                plan = self.extraer(metas, i)
                if traza:
                    print(f"  nivel {i}: metas presentes y sin exclusiones -> extracción {'con éxito' if plan is not None else 'fallida'}")
                if plan is not None:
                    return plan
                if nivelado is not None:                            # prueba de terminación de Blum y Furst
                    n = len(self.nogood.get(nivelado, ()))
                    if n == nogoods_antes:
                        return None
                    nogoods_antes = n
            else:
                if traza:
                    print(f"  nivel {i}: {'faltan metas' if not metas <= self.S[i] else 'hay metas en exclusión mutua'}")
                if nivelado is not None:
                    return None                                     # estabilizado sin las metas: no hay plan
            self.expandir()
            if nivelado is None and self.S[-1] == self.S[-2] and self.muS[-1] == self.muS[-2]:
                nivelado = len(self.S) - 2
        return None

def ver_nivel(G, i):
    lits = sorted(nombre_lit(l) for l in G.S[i])
    mu = sorted(" / ".join(sorted(nombre_lit(l) for l in m)) for m in G.muS[i])
    print(f"  S{i}: {lits}")
    print(f"      exclusiones: {mu}")

print("La tarta:")
tarta = GrafoPlan(["tengo", "comida"], {"tengo"},
                  [op("Comer", ["tengo"], ["comida"], ["tengo"]), op("Hornear", ["¬tengo"], ["tengo"])])
plan = tarta.resolver(["tengo", "comida"])
for i in range(len(tarta.S)):
    ver_nivel(tarta, i)
print("  plan:", plan)

print("\nLa cena sorpresa:")
cena = GrafoPlan(["basura", "manos", "silencio", "cena", "regalo"], {"basura", "manos", "silencio"},
                 [op("cocinar", ["manos"], ["cena"]), op("envolver", ["silencio"], ["regalo"]),
                  op("sacar", [], [], ["basura", "manos"]), op("carretilla", [], [], ["basura", "silencio"])])
plan = cena.resolver(["cena", "regalo", "¬basura"])
ver_nivel(cena, 1)
print("  nogoods anotados en el nivel 1:", [sorted(nombre_lit(l) for l in s) for s in cena.nogood.get(1, ())])
print("  plan:", plan)

print("\nEl triángulo: tres metas compatibles dos a dos, nunca las tres a la vez")
tri = GrafoPlan(["p", "q", "r"], set(), [op("pq", [], ["p", "q"], ["r"]), op("qr", [], ["q", "r"], ["p"]), op("rp", [], ["r", "p"], ["q"])])
plan = tri.resolver(["p", "q", "r"])
print("  plan:", plan, "  niveles de literales construidos:", len(tri.S),
      "  nogoods por nivel:", {i: len(v) for i, v in sorted(tri.nogood.items())})

Output reproduces the figure. For cake, S1S_1 has four mutexes (the two negations, tengo/comida\mathit{tengo}/\mathit{comida} and ¬tengo/¬comida\neg\mathit{tengo}/\neg\mathit{comida}) and at S2S_2 the tengo/comida\mathit{tengo}/\mathit{comida} mutex disappears; the plan is Eat then Bake. In dinner, level-1 extraction fails, records {cena,regalo,¬basura}\{\mathit{cena}, \mathit{regalo}, \neg\mathit{basura}\} as a nogood, and level-2 extraction finds the parallel plan: cook and wrap together, then take out garbage. The triangle tests termination. Each action achieves two of three atoms and deletes the third, so goals appear pairwise nonmutex (rp achieves rr and pp together, for example) but never all three. The graph quickly levels off, each extraction fails and records nogoods, and when an attempt adds none at the stabilized level, Blum and Furst’s test declares no plan.

Planning as satisfiability

Kautz and Selman proposed a direct reduction in 1992 (Planning as Satisfiability, ECAI): “is there an TT-step plan?” is a propositional formula, and a model is a plan. Four years later, Pushing the Envelope (AAAI 1996) showed careful encodings and stochastic local search solving larger logistics and blocks-world problems than GraphPlan. The idea is the usual reduction to SAT: one variable for each thing that can be true at each time.

Frame axioms are delicate, sharing the history of the frame problem seen in action representation. Effect clauses say what changes when an action executes, not what does not change: without more clauses the solver may set any atom true at any time. Classical one-axiom-per-action-and-unaffected-atom needs O(∣A∣∣F∣)\bigO(\abs{A}\abs{F}) clauses per step. Explanatory axioms (Haas, 1987; Schubert, 1990) reverse this: rather than saying what each action preserves, any atom change must be explained by some action. There are two clauses per atom and step, total length proportional to effect count.

Proof

(⇒\Rightarrow) Take a model, let st={f:xf,t}s_t = \{f : x_{f,t}\} and Et={a:at}E_t = \{a : a_t\}. By (3), every EtE_t action’s preconditions are in sts_t. By (4), if qq is added by some action in EtE_t then q∈st+1q \in s_{t+1}, and if some deletes it q∉st+1q \notin s_{t+1}; since the model exists no atom is both added and deleted in one step. If ff is neither added nor deleted by any action in EtE_t, the frame axioms force xf,t+1=xf,tx_{f,t+1} = x_{f,t}. Therefore st+1=(st∖Dt)∪Rts_{t+1} = (s_t \setminus D_t) \cup R_t, with DtD_t and RtR_t the unions of deletes and adds of EtE_t. Execute EtE_t in any order. No action deletes another’s precondition (by (6)), so each finds preconditions that were in sts_t and no one deleted. Since no atom is added and deleted in one step, the sequence yields (st∖Dt)∪Rt=st+1(s_t \setminus D_t) \cup R_t = s_{t+1} in any order. By (1) and (2), s0=Is_0 = I and G⊆sTG \subseteq s_T.

(⇐\Leftarrow) Given the sequence, assign ata_t true if and only if a∈Eta \in E_t and xf,tx_{f,t} according to state sts_t. Clauses (1)–(4) hold by construction (all orders giving the same state requires no atom be both added and deleted in a step, and reached state be (st∖Dt)∪Rt(s_t \setminus D_t) \cup R_t). If ff changes true to false, some action in EtE_t deletes it, and if false to true, some action adds it: frame axioms hold. Finally, if a,b∈Eta, b \in E_t and aa deletes an bb precondition, ordering “aa before bb” would not be executable, contradicting the assumption: mutexes hold.

∎

Parallelism: ∀-steps and ∃-steps

Clause (6) decides what a step is, and how many are needed. Three common semantics were formalized by Rintanen, Heljanko and Niemelä (Planning as satisfiability: parallel plans and algorithms for plan search, Artificial Intelligence, 2006):

  • Sequential: at most one action per step. Exclude all pairs, (∣A∣2)\binom{\abs{A}}{2} clauses per step (or an “at most one” cardinality encoding needing O(∣A∣)\bigO(\abs{A})). Minimum horizon equals optimal plan length.
  • ∀-steps: an action set is a step if every ordering is executable and yields the same result. Exclude pairs interfering either way: GraphPlan’s and the preceding theorem’s semantics.
  • ∃-steps: it suffices that some executable ordering yields the same result as applying all effects simultaneously. Fix a total action order in advance and exclude only pairs where an earlier action deletes a later precondition. With “unload before drive”, a truck may unload and leave for another city in one step.

Contradictory effects need no clauses: effect clauses already make them unsatisfiable. Fewer mutexes allow more actions per step, shorter horizon and smaller formula. Rintanen et al. also provide an ∃-step encoding linear in effects, using auxiliaries propagating “some earlier action deleted pp” along the fixed order; we use the clearer quadratic version. Madagascar, Rintanen’s SAT planner, uses the linear encoding.

InteractiveSearching the horizon
T0UNSAT1UNSAT2UNSAT3UNSAT4UNSAT5SAT6SAT7SAT8SAT9SAT10SAT012345c1D→Cconducir(c1,D,C)↑p3cargar(p3,c1,C)C→Bconducir(c1,C,B)↓p3descargar(p3,c1,B)c2↑p2cargar(p2,c2,D)D→Aconducir(c2,D,A)↑p1cargar(p1,c2,A)A→Bconducir(c2,A,B)↓p1descargar(p1,c2,B)↓p2descargar(p2,c2,B)c1DCCCBBc2DDAABBp1AAAc2c2Bp2Dc2c2c2c2Bp3CCc1c1c1B
  • ↑p load, ↓p unload, X→Y drive
  • p1
  • p2
  • p3
  • inconsistent or unexplained
Top: solver answer for each horizon. Middle: each truck’s actions at each step. Bottom: location of each object at each instant (cX: inside truck X).
5
Semantics
Variables516
Clauses2689
Resultsatisfiable
CDCL conflicts106
Actions in plan10 (sequential optimum: 9)
Minimum horizon: T=5T = 5. The plan has 10 actions, and at this horizon no plan has fewer than 10, more than the 9 of the sequential optimum.
The REPARTO instance: two trucks at depot D and three packages to reach B from A, D and C (26 atoms and 72 actions). Top: solver answer for each horizon TT; middle: each truck's actions per step; bottom: each object's location at each instant. Data came from lesson lab 1 functions (encoding, custom CDCL and validator) for T=0,…,10T = 0, \dots, 10. Start at the minimum ∀-step horizon and count actions; switch to ∃ and sequential. Then disable mutexes (a truck in two places) and frame axioms (teleporting packages).

Lab 1: SATPlan with your CDCL

The solver is a compact version of the SAT lesson’s CDCL with 1-UIP analysis: two watched literals, 1-UIP learning with nonchronological backjumping, VSIDS with a lazy heap, saved phase (false by default, MiniSat’s choice, favoring few-action plans here), and Luby restarts. It lacks clause minimization and deletion, irrelevant at this size, and adds something needed: assumptions, literals fixed as each call’s first decisions, like Z3’s incremental solving.

[ ]Compact CDCL with assumptionsBrowser
import heapq

def luby(i):
    k = 1
    while (1 << k) - 1 < i:
        k += 1
    while True:
        if i == (1 << k) - 1:
            return 1 << (k - 1)
        if i >= (1 << (k - 1)):
            i -= (1 << (k - 1)) - 1; k -= 1
        else:
            k -= 1

class CDCL:
    """Dos literales vigilados, 1-UIP, salto no cronológico, VSIDS con montículo perezoso, fase guardada
    (falso por defecto), reinicios de Luby y suposiciones a la MiniSat. Sin borrado ni minimización."""

    def __init__(self, n=0):
        self.n = 0
        self.clauses, self.watches = [], {}
        self.val, self.level, self.reason, self.act, self.phase = [0], [0], [-1], [0.0], [-1]
        self.trail, self.lim, self.qhead = [], [], 0
        self.heap, self.inc = [], 1.0
        self.ok = True
        self.conflicts = self.decisions = self.props = 0
        self.nuevas_variables(n)

    def nuevas_variables(self, k):
        for _ in range(k):
            self.n += 1
            self.val.append(0); self.level.append(0); self.reason.append(-1)
            self.act.append(0.0); self.phase.append(-1)
            heapq.heappush(self.heap, (0.0, self.n))
        return self.n

    def value(self, l):
        v = self.val[abs(l)]
        return v if l > 0 else -v

    def assign(self, l, r):
        v = abs(l)
        self.val[v] = 1 if l > 0 else -1
        self.level[v] = len(self.lim)
        self.reason[v] = r
        self.trail.append(l)

    def add_clause(self, c):
        """Cláusula permanente; se puede llamar entre dos solve (uso incremental)."""
        self.backtrack(0)
        c = list(dict.fromkeys(c))
        if any(-l in c for l in c) or any(self.value(l) == 1 for l in c):
            return
        c = [l for l in c if self.value(l) == 0]
        if not c:
            self.ok = False
        elif len(c) == 1:
            self.assign(c[0], -1)
            if self.propagate() is not None:
                self.ok = False
        else:
            ci = len(self.clauses)
            self.clauses.append(c)
            self.watches.setdefault(c[0], []).append(ci)
            self.watches.setdefault(c[1], []).append(ci)

    def propagate(self):
        while self.qhead < len(self.trail):
            p = -self.trail[self.qhead]
            self.qhead += 1
            lista, nueva = self.watches.get(p, []), []
            i, m = 0, len(lista)
            while i < m:
                ci = lista[i]; i += 1
                c = self.clauses[ci]
                if c[0] == p:
                    c[0], c[1] = c[1], c[0]
                if self.value(c[0]) == 1:
                    nueva.append(ci); continue
                for k in range(2, len(c)):
                    if self.value(c[k]) != -1:
                        c[1], c[k] = c[k], c[1]
                        self.watches.setdefault(c[1], []).append(ci)
                        break
                else:
                    nueva.append(ci)
                    if self.value(c[0]) == -1:
                        nueva.extend(lista[i:])
                        self.watches[p] = nueva
                        return ci
                    self.assign(c[0], ci)
                    self.props += 1
            self.watches[p] = nueva
        return None

    def backtrack(self, lvl):
        if len(self.lim) <= lvl:
            return
        for l in self.trail[self.lim[lvl]:]:
            v = abs(l)
            self.phase[v] = self.val[v]
            self.val[v] = 0
            self.reason[v] = -1
            heapq.heappush(self.heap, (-self.act[v], v))
        del self.trail[self.lim[lvl]:]
        del self.lim[lvl:]
        self.qhead = len(self.trail)

    def analyze(self, confl):
        seen, dl = set(), len(self.lim)
        learnt, counter, p, idx = [0], 0, 0, len(self.trail) - 1
        while True:
            c = self.clauses[confl]
            for q in (c if p == 0 else c[1:]):
                v = abs(q)
                if v not in seen and self.level[v] > 0:
                    seen.add(v)
                    self.act[v] += self.inc
                    if self.level[v] >= dl:
                        counter += 1
                    else:
                        learnt.append(q)
            while abs(self.trail[idx]) not in seen:
                idx -= 1
            p = self.trail[idx]; idx -= 1
            seen.discard(abs(p))
            counter -= 1
            if counter == 0:
                break
            confl = self.reason[abs(p)]
        learnt[0] = -p
        self.inc /= 0.95
        if self.inc > 1e100:
            self.act = [a * 1e-100 for a in self.act]; self.inc *= 1e-100
        if len(learnt) == 1:
            return learnt, 0
        k = max(range(1, len(learnt)), key=lambda j: self.level[abs(learnt[j])])
        learnt[1], learnt[k] = learnt[k], learnt[1]
        return learnt, self.level[abs(learnt[1])]

    def pick(self):
        while self.heap:
            _, v = heapq.heappop(self.heap)
            if self.val[v] == 0:
                return v if self.phase[v] == 1 else -v
        return 0

    def solve(self, assumptions=()):
        if not self.ok:
            return False
        self.backtrack(0)
        if self.propagate() is not None:
            self.ok = False
            return False
        for v in range(1, self.n + 1):
            if self.val[v] == 0:
                heapq.heappush(self.heap, (-self.act[v], v))
        run, budget, since = 1, 100, 0
        while True:
            confl = self.propagate()
            if confl is not None:
                self.conflicts += 1; since += 1
                if not self.lim:
                    self.ok = False
                    return False
                learnt, bj = self.analyze(confl)
                self.backtrack(bj)
                if len(learnt) == 1:
                    self.assign(learnt[0], -1)
                else:
                    ci = len(self.clauses)
                    self.clauses.append(learnt)
                    self.watches.setdefault(learnt[0], []).append(ci)
                    self.watches.setdefault(learnt[1], []).append(ci)
                    self.assign(learnt[0], ci)
                for q in learnt:
                    heapq.heappush(self.heap, (-self.act[abs(q)], abs(q)))
                continue
            if since >= budget:                                   # reinicio de Luby
                run += 1; since = 0; budget = 100 * luby(run)
                self.backtrack(0)
                continue
            lit_ = 0
            while len(self.lim) < len(assumptions):               # las suposiciones, como primeras decisiones
                a = assumptions[len(self.lim)]
                if self.value(a) == 1:
                    self.lim.append(len(self.trail))              # nivel vacío: ya se cumple
                elif self.value(a) == -1:
                    return False                                  # insatisfacible bajo las suposiciones
                else:
                    lit_ = a
                    break
            if lit_ == 0:
                lit_ = self.pick()
                if lit_ == 0:
                    return True
            self.decisions += 1
            self.lim.append(len(self.trail))
            self.assign(lit_, -1)

    def modelo(self):
        return [self.val[v] == 1 for v in range(self.n + 1)]

# comprobación rápida: el palomar de 4 palomas y 3 huecos es insatisfacible; con 3 huecos y 3 palomas, no
def palomar(p, h):
    v = lambda i, j: i * h + j + 1
    C = [[v(i, j) for j in range(h)] for i in range(p)]
    C += [[-v(i, j), -v(k, j)] for j in range(h) for i in range(p) for k in range(i + 1, p)]
    return p * h, C
for p, h in [(4, 3), (3, 3)]:
    n, C = palomar(p, h)
    S = CDCL(n)
    for c in C:
        S.add_clause(c)
    print(f"palomar({p}, {h}): {'SAT' if S.solve() else 'UNSAT'} con {S.conflicts} conflictos")

Now encoding. Class Codificacion numbers variables fixed by instant (xf,tx_{f,t} and ata_t always occupy the same position in instant tt‘s block), so step clauses do not depend on total horizon. Lab 3 can add steps one by one. Function valida executes a step plan and checks validity under the corresponding semantics: do not simply trust the solver.

[ ]Lab 1: SATPlan encoding and REPARTO instanceBrowser
def interfiere(a, b):
    """a deshabilita b: a borra una precondición de b."""
    return bool(a.dele & b.pre)

def pares_excluidos(tarea, semantica):
    A, n = tarea.acciones, len(tarea.acciones)
    if semantica == "secuencial":
        return [(i, j) for i in range(n) for j in range(i + 1, n)]
    if semantica == "todos":        # pasos ∀: ninguna deshabilita a otra, en ningún sentido
        return [(i, j) for i in range(n) for j in range(i + 1, n) if interfiere(A[i], A[j]) or interfiere(A[j], A[i])]
    if semantica == "existe":       # pasos ∃ con el orden de la lista: ninguna deshabilita a una posterior
        return [(i, j) for i in range(n) for j in range(i + 1, n) if interfiere(A[i], A[j])]
    if semantica == "ninguna":
        return []
    raise ValueError(semantica)

class Codificacion:
    """x(t, f): el átomo f es cierto en el instante t; a(t, i): la acción i se ejecuta en el paso t.
    La numeración DIMACS es fija por instante, independiente del horizonte."""
    def __init__(self, tarea, semantica="todos", marco=True):
        self.tarea, self.marco = tarea, marco
        self.F, self.A = list(tarea.atomos), tarea.acciones
        self.fi = {f: j for j, f in enumerate(self.F)}
        self.ancho = len(self.F) + len(self.A)
        self.excl = pares_excluidos(tarea, semantica)
        self.borran = {f: [i for i, a in enumerate(self.A) if f in a.dele] for f in self.F}
        self.anaden = {f: [i for i, a in enumerate(self.A) if f in a.add] for f in self.F}

    def x(self, t, f):
        return t * self.ancho + self.fi[f] + 1

    def a(self, t, i):
        return t * self.ancho + len(self.F) + i + 1

    def variables(self, T):
        return T * self.ancho + len(self.F)

    def inicial(self):
        return [[self.x(0, f)] if f in self.tarea.init else [-self.x(0, f)] for f in self.F]

    def metas(self, T):
        return [self.x(T, g) for g in sorted(self.tarea.meta)]

    def paso(self, t):
        C, x, a = [], self.x, self.a
        for i, ac in enumerate(self.A):
            C += [[-a(t, i), x(t, p)] for p in sorted(ac.pre)]             # precondiciones
            C += [[-a(t, i), x(t + 1, q)] for q in sorted(ac.add)]         # efectos positivos
            C += [[-a(t, i), -x(t + 1, q)] for q in sorted(ac.dele)]       # efectos negativos
        if self.marco:                                                    # axiomas de marco explicativos
            for f in self.F:
                C.append([-x(t, f), x(t + 1, f)] + [a(t, i) for i in self.borran[f]])
                C.append([x(t, f), -x(t + 1, f)] + [a(t, i) for i in self.anaden[f]])
        C += [[-a(t, i), -a(t, j)] for i, j in self.excl]                 # exclusiones
        return C

    def formula(self, T):
        C = self.inicial()
        for t in range(T):
            C += self.paso(t)
        return C + [[g] for g in self.metas(T)]

    def plan(self, modelo, T):
        return [[ac.nombre for i, ac in enumerate(self.A) if modelo[self.a(t, i)]] for t in range(T)]

    def estados(self, modelo, T):
        return [sorted(f for f in self.F if modelo[self.x(t, f)]) for t in range(T + 1)]

def valida(tarea, pasos, semantica="todos"):
    """Ejecuta un plan por pasos: precondiciones ciertas al empezar cada paso y, según la semántica,
    ninguna acción deshabilita a otra (∀) o a una posterior en el orden fijo (∃)."""
    idx = {a.nombre: a for a in tarea.acciones}
    orden = {a.nombre: k for k, a in enumerate(tarea.acciones)}
    s = set(tarea.init)
    for k, paso in enumerate(pasos):
        acc = sorted((idx[n] for n in paso), key=lambda b: orden[b.nombre])
        for b in acc:
            if not b.pre <= s:
                return False, f"paso {k}: {b.nombre} sin su precondición"
        for i, b in enumerate(acc):
            for c in acc[i + 1:]:
                if b.add & c.dele or c.add & b.dele:
                    return False, f"paso {k}: {b.nombre} y {c.nombre} tienen efectos contradictorios"
                if (semantica != "existe" and interfiere(c, b)) or interfiere(b, c):
                    return False, f"paso {k}: {b.nombre} y {c.nombre} interfieren"
        for b in acc:
            s = (s - b.dele) | b.add
    return (True, "válido") if tarea.meta <= s else (False, "no alcanza la meta")

def satplan(tarea, semantica="todos", Tmax=30, marco=True, verbose=True):
    """Horizontes T = 0, 1, 2... con un resolvedor nuevo para cada uno (la estrategia de Kautz y Selman)."""
    cod = Codificacion(tarea, semantica, marco)
    for T in range(Tmax + 1):
        F = cod.formula(T)
        S = CDCL(cod.variables(T))
        for c in F:
            S.add_clause(c)
        r = S.solve()
        if verbose:
            print(f"  T = {T:2d}: {cod.variables(T):4d} variables, {len(F):5d} cláusulas -> {'SAT  ' if r else 'UNSAT'} ({S.conflicts} conflictos)")
        if r:
            return T, cod.plan(S.modelo(), T), S.modelo()
    return None, None, None

def logistica(camiones, paquetes, lugares):
    """camiones: {c: lugar}; paquetes: {p: (origen, destino)}. Orden de la lista: cargar, descargar, conducir
    (es el orden fijo de los pasos ∃: cargar y descargar pueden preceder a conducir en el mismo paso)."""
    A = [accion(f"cargar({p},{c},{x})", [f"en({p},{x})", f"en({c},{x})"], [f"dentro({p},{c})"], [f"en({p},{x})"])
         for p in paquetes for c in camiones for x in lugares]
    A += [accion(f"descargar({p},{c},{x})", [f"dentro({p},{c})", f"en({c},{x})"], [f"en({p},{x})"], [f"dentro({p},{c})"])
          for p in paquetes for c in camiones for x in lugares]
    A += [accion(f"conducir({c},{x},{y})", [f"en({c},{x})"], [f"en({c},{y})"], [f"en({c},{x})"])
          for c in camiones for x in lugares for y in lugares if x != y]
    atomos = sorted({f for a in A for f in a.pre | a.add | a.dele})
    init = frozenset([f"en({c},{x})" for c, x in camiones.items()] + [f"en({p},{o})" for p, (o, d) in paquetes.items()])
    meta = frozenset(f"en({p},{d})" for p, (o, d) in paquetes.items())
    return Tarea(atomos, init, meta, A)

REPARTO = logistica({"c1": "D", "c2": "D"}, {"p1": ("A", "B"), "p2": ("D", "B"), "p3": ("C", "B")}, ["A", "B", "C", "D"])
print(f"REPARTO: {len(REPARTO.atomos)} átomos, {len(REPARTO.acciones)} acciones")
for sem in ["todos", "existe"]:
    print(f"\nPasos {'∀' if sem == 'todos' else '∃'}:")
    T, plan, _ = satplan(REPARTO, sem)
    print(f"  horizonte mínimo {T}, {sum(map(len, plan))} acciones, validación: {valida(REPARTO, plan, sem)}")
    for t, paso in enumerate(plan):
        print(f"    paso {t}: {', '.join(paso)}")

Output has three readings. First: minimum horizon is 5 for ∀-steps and 3 for ∃-steps versus sequential optimum 9 actions (A* calculates it below). In ∃ plan step 1, truck c1 loads p1 at A and drives to B in the same step, and c2 does likewise with p3 at C: driving deletes en(c1,A)\mathit{en}(c1, A), a loading precondition, so the step is valid only in fixed order (load before drive), admitted by ∃ but not ∀ semantics. Second: unsatisfiable horizons are almost free (34 conflicts at most with ∀-steps) because precondition, effect and frame clauses propagate strongly. Third: size. With T=5T = 5 there are 26⋅6+72⋅5=51626 \cdot 6 + 72 \cdot 5 = 516 variables, and the formula grows linearly with TT.

[ ]What breaks without frame axioms or mutexesBrowser
for marco, sem, que in [(False, "todos", "sin axiomas de marco"), (True, "ninguna", "sin exclusiones")]:
    T, plan, modelo = satplan(REPARTO, sem, marco=marco, verbose=False)
    cod = Codificacion(REPARTO, sem, marco)
    print(f"{que}: SAT ya con T = {T}, {sum(map(len, plan))} acciones; validación: {valida(REPARTO, plan, 'todos')}")
    if not marco:
        print("   estado del instante 1 según el modelo:", [f for f in cod.estados(modelo, T)[1] if f.startswith("en(p")])

Minimum horizon does not give the shortest plan

Rintanen states in his 2012 paper that guaranteeing minimum horizon is not important, because for common notions of parallel plan horizon length corresponds to no relevant quality measure, and parallelism represents reorderability rather than actual concurrency. It reduces the search space, not an objective.

Compare heuristic search and GraphPlan

The next cell closes the loop. Solve REPARTO with the previous lesson’s A* and admissible heuristic hmax⁡h_{\max}, yielding the sequential optimum; greedy search and haddh_{\text{add}}, fast but not optimal; and GraphPlan, which should find a plan with the ∀ encoding’s parallel step count because their semantics match.

[ ]REPARTO with A*, greedy search and GraphPlanBrowser
import time

def h_relajada(tarea, s, agregar):
    """h_max (agregar=max) o h_add (agregar=sum) por punto fijo, como en la lección anterior."""
    INF = float("inf")
    c = {f: 0 for f in s}
    cambio = True
    while cambio:
        cambio = False
        for a in tarea.acciones:
            if all(p in c for p in a.pre):
                k = 1 + (agregar(c[p] for p in a.pre) if a.pre else 0)
                for q in a.add:
                    if c.get(q, INF) > k:
                        c[q] = k; cambio = True
    if not all(g in c for g in tarea.meta):
        return INF
    return agregar(c[g] for g in tarea.meta) if tarea.meta else 0

h_max = lambda T, s: h_relajada(T, s, max)
h_add = lambda T, s: h_relajada(T, s, sum)

def mejor_primero(tarea, h, w_g=1, limite=200000):
    """A* (w_g = 1) o búsqueda voraz (w_g = 0). Devuelve (plan, nodos expandidos)."""
    s0 = frozenset(tarea.init)
    abiertos, n = [(h(tarea, s0), 0, s0)], 1
    g, padre, cerrados = {s0: 0}, {s0: None}, set()
    while abiertos and len(cerrados) < limite:
        _, _, s = heapq.heappop(abiertos)
        if s in cerrados:
            continue
        if tarea.meta <= s:
            plan = []
            while padre[s] is not None:
                s, nombre = padre[s]; plan.append(nombre)
            return plan[::-1], len(cerrados)
        cerrados.add(s)
        for a in tarea.acciones:
            if a.pre <= s:
                t = (s - a.dele) | a.add
                if t not in g or g[s] + 1 < g[t]:
                    g[t] = g[s] + 1; padre[t] = (s, a.nombre)
                    ht = h(tarea, t)
                    if ht < float("inf"):
                        heapq.heappush(abiertos, (w_g * g[t] + ht, n, t)); n += 1
    return None, len(cerrados)

for nombre, h, w in [("A* con h_max", h_max, 1), ("voraz con h_add", h_add, 0)]:
    t0 = time.perf_counter()
    plan, exp = mejor_primero(REPARTO, h, w)
    print(f"{nombre:16s}: {len(plan)} acciones, {exp} nodos expandidos, {time.perf_counter() - t0:.2f} s")

G = GrafoPlan(REPARTO.atomos, REPARTO.init, [Op(a.nombre, [(p, True) for p in a.pre], a.add, a.dele) for a in REPARTO.acciones])
plan = G.resolver(sorted(REPARTO.meta), traza=False)
print(f"GraphPlan       : {len(plan)} pasos paralelos, {sum(map(len, plan))} acciones; validación ∀: {valida(REPARTO, plan, 'todos')}")

A* confirms sequential optimum 9 actions after expanding just over a thousand states; greedy search expands very few nodes but gives 12 actions, three extra; GraphPlan reaches level 5, the ∀ encoding’s horizon, with a valid plan. All agree with what we proved: a sequential plan of kk actions is a ∀ plan of kk steps (one per action), so minimum ∀ horizon lower-bounds every sequential plan’s length; step count is not action count.

Horizons, assumptions and why SAT competes

The satplan loop is Kautz and Selman’s original strategy: try T=0,1,2,…T = 0, 1, 2, \dots with a fresh solver each time. Two costs arise. First, repeated work: formula T+1T + 1 contains TT (except goal clauses), and all the solver learned about early steps is thrown away. Second, worse: proving ΦT\Phi_T unsatisfiable for TT just below optimum is often costliest, because a refutation must cover all plans of that length. The interactive’s sequential row, computed by your CDCL (reproduce with satplan(REPARTO, "secuencial"), a few seconds in the browser), shows refuting T=8T = 8 costs 3013 conflicts, more than finding a plan at T=9T = 9 (2642), while the last unsatisfiable ∀ horizon costs 34.

Two complementary remedies:

  • Incremental SAT with assumptions. Step clauses are permanent and goals are requested as assumptions: to test TT, add clauses for step T−1T - 1 and call solve(assumptions = metas en T). Since assumptions are decisions, never reasons, all learned clauses follow from permanent clauses and remain useful for later horizons (the Z3 lesson’s theorem). Lab 3 measures it.
  • Parallel horizons. Rintanen avoids completing unsatisfiability proofs: algorithm B shares CPU among many horizons, giving t+1t + 1 a fraction γ\gamma (0.9 in Madagascar) of the time for tt. A satisfiable horizon slightly above minimum often solves before refuting the one immediately below: in that sequential row, T=10T = 10 solves with 673 conflicts versus 3013 to refute T=8T = 8.

Why can this compete with A* and greedy search? For years it did not: Rintanen notes early encodings were huge and quadratic, and SAT work did not even compare to planners like LAMA because of the performance gap. Three changes closed it: linear ∃-step encodings shortening horizon; parallel horizon evaluation; and a planning-specific decision heuristic. In Planning as satisfiability: Heuristics (2012), Rintanen replaces VSIDS with a rule searching backward in time for the latest action achieving each unexplained goal or subgoal and deciding it true. On 1646 competition instances from 1998–2011 with 30 minutes each, his Mp planner solved 1416 versus 1414 for LAMA 2011, 1332 LAMA 2008, 1238 FF and 1304 the same setup with VSIDS (paper table 5). The SAT solver is not magic: unit propagation over the encoding deduces invariants like “a truck is in one place”, and clause learning reuses them at all instants.

In competitions, SATPLAN04 won IPC-4’s optimal planning category (2004) and SATPLAN06 shared first place with MaxPlan at IPC-5 (2006).

Lab 3: incremental SAT with an industrial solver

PySAT exposes Armin Biere’s CaDiCaL to Python, including in the browser. The cell compares both approaches under three semantics: a fresh solver per horizon (goals also as assumptions, so only reuse differs) versus one solver with added steps. It then uses a cardinality encoding (Sinz sequential counter) to calculate minimum actions at each minimum horizon. Times depend on your machine; conflicts do not.

[ ]Lab 3: incremental horizons with CaDiCaLBrowser
import random
from pysat.solvers import Solver
from pysat.card import CardEnc, EncType

def desde_cero(cod, Tmax=40):
    conflictos, t0 = 0, time.perf_counter()
    for T in range(Tmax + 1):
        with Solver(name="cadical153", bootstrap_with=cod.inicial() + [c for t in range(T) for c in cod.paso(t)]) as s:
            r = s.solve(assumptions=cod.metas(T))
            conflictos += s.accum_stats()["conflicts"]
        if r:
            return T, conflictos, time.perf_counter() - t0

def incremental(cod, Tmax=40):
    t0 = time.perf_counter()
    s = Solver(name="cadical153", bootstrap_with=cod.inicial())
    for T in range(Tmax + 1):
        if T > 0:
            s.append_formula(cod.paso(T - 1))          # solo las cláusulas del paso nuevo
        if s.solve(assumptions=cod.metas(T)):
            break
    conflictos = s.accum_stats()["conflicts"]
    s.delete()
    return T, conflictos, time.perf_counter() - t0

def logistica_aleatoria(n_cam, n_lug, n_paq, semilla):
    R = random.Random(semilla)
    L = [f"L{i}" for i in range(n_lug)]
    return logistica({f"c{i}": R.choice(L) for i in range(n_cam)},
                     {f"p{i}": tuple(R.sample(L, 2)) for i in range(n_paq)}, L)

GRANDE = logistica_aleatoria(3, 6, 8, 1)
print(f"GRANDE: {len(GRANDE.atomos)} átomos, {len(GRANDE.acciones)} acciones")
for nombre, tarea, sems in [("REPARTO", REPARTO, ["secuencial", "todos", "existe"]), ("GRANDE", GRANDE, ["todos", "existe"])]:
    for sem in sems:
        cod = Codificacion(tarea, sem)
        T1, c1, t1 = desde_cero(cod)
        T2, c2, t2 = incremental(cod)
        assert T1 == T2
        print(f"{nombre:8s} {sem:10s} T* = {T1:2d}   desde cero: {c1:6d} conflictos, {t1:.2f} s   incremental: {c2:6d} conflictos, {t2:.2f} s")

The lab’s second part answers the warning: minimum actions at minimum horizon. Search top-down: solve without limit, count model actions kk, ask for at most k−1k - 1, repeat until unsatisfiable. Each model improves the prior, and the final unsatisfiable answer proves the minimum is the last kk found.

[ ]Lab 3 continued: minimum actions at each horizonBrowser
def min_acciones(tarea, sem, T):
    """Menor número de acciones de un plan de T pasos: búsqueda descendente con «como mucho k» (Sinz)."""
    cod = Codificacion(tarea, sem)
    acts = [cod.a(t, i) for t in range(T) for i in range(len(tarea.acciones))]
    F, mejor, cota = cod.formula(T), None, None
    while True:
        extra = [] if cota is None else CardEnc.atmost(lits=acts, bound=cota, top_id=cod.variables(T), encoding=EncType.seqcounter).clauses
        with Solver(name="cadical153", bootstrap_with=F + extra) as s:
            if not s.solve():
                return mejor
            modelo = set(l for l in s.get_model() if l > 0)
        mejor = sum(1 for v in acts if v in modelo)
        cota = mejor - 1

for sem, T in [("todos", 5), ("existe", 3), ("secuencial", 9)]:
    print(f"REPARTO, pasos {sem}, T = {T}: ningún plan tiene menos de {min_acciones(REPARTO, sem, T)} acciones")

Read carefully: savings vary. On GRANDE (3 trucks, 6 locations, 8 packages) with ∀-steps, incremental needs 2781 conflicts versus 9284 and about one-third the time: unsatisfiable horizons use prior learning, and early-step clauses are neither rebuilt nor repropagated, a fresh-run cost growing with TT squared. On sequential REPARTO, conflicts only drop from 5259 to 4468 and time is unchanged: work lies in refuting T=8T = 8 and shorter-horizon learning barely helps. With ∃-steps little can be saved because horizons are few and cheap. Incremental solving is a reliable improvement of variable size; shorter-horizon semantics and parallel evaluation avoiding refutations change the order of magnitude.

The second cell confirms the warning with an independent solver: at least 10 actions with 5 ∀-steps or 3 ∃-steps, and 9 with sequential horizon 9.

Partial-order planning

Both approaches return step sequences. But a plan is fundamentally an action set with dependencies, and committing early to a total order has two drawbacks: search explores irrelevant orderings and the plan loses executor information. Partial-order, or least-commitment, planning searches partial plans and orders only what is necessary. Its line runs from NOAH (Sacerdoti, 1975) and NONLIN (Tate, 1977) to TWEAK (Chapman, 1987), SNLP (McAllester and Rosenblitt, 1991) and UCPOP (Penberthy and Weld, 1992); Weld’s An Introduction to Least Commitment Planning (AI Magazine, 1994) is the reference tutorial.

The partial order is a directed acyclic graph over steps, and a linearization is any topological ordering. The result justifying the method: once complete, every linearization works.

Proof

Fix linearization π\pi and step cc with precondition qq (including Fin\mathit{Fin}, whose preconditions are goals). No open conditions means link s→qcs \xrightarrow{q} c exists, and s≺cs \prec c, so ss precedes cc in π\pi. Immediately after ss, qq is true because ss adds it (if s=Inicios = \mathit{Inicio}, because qq is initially true). Suppose qq is false at cc. Some step tt between ss and cc in π\pi deletes qq. That tt satisfies neither t≺st \prec s nor c≺tc \prec t in the partial order, because in π\pi it follows ss and precedes cc and π\pi respects ≺\prec. Thus tt threatens the link, contradiction. Every step’s preconditions therefore hold when it executes, especially goals at Fin\mathit{Fin}.

∎

The converse is false: a plan with threats can have valid linearizations, just not all. The interactive shows this. The first problem is security maintenance: download a patch, requiring a temporarily open port; hardening closes it and applies policy; also back up, and end with the port closed. The second is Sussman’s anomaly, the three-block problem used in 1975 to show planning goals one after another fails: stack A on B first and it must be undone to put B on C, and vice versa.

InteractiveThreats in a partial-order plan
patchbackuppolicyport closedport openStartStartFinishFinishDownloadDownload patchBackupMake backupHardenHardenOpenOpen port
  • causal link (atom)
  • chosen ordering constraint
  • threat
Open deletes «port closed» and threatens the link Harden → Finish.
Harden deletes «port open» and threatens the link Open → Download.
Compatible total orderings, executed from the start
✗ Backup → Harden → Open → Download (at the end missing port closed)
✓ Backup → Open → Download → Harden
✗ Backup → Open → Harden → Download (Download: missing port open)
✗ Harden → Backup → Open → Download (at the end missing port closed)
✗ Harden → Open → Download → Backup (at the end missing port closed)
✗ Harden → Open → Backup → Download (at the end missing port closed)
✓ Open → Download → Backup → Harden
✓ Open → Download → Harden → Backup
✓ Open → Backup → Download → Harden
✗ Open → Backup → Harden → Download (Download: missing port open)
✗ Open → Harden → Download → Backup (Download: missing port open)
✗ Open → Harden → Backup → Download (Download: missing port open)
Problem
Steps4
Open conditionsnone
Chosen constraintsnone
Valid compatible orderings4 of 12
There are 2 threats: resolve them before refining further.
The plan is built with causal links and two red threats. Below are all total orderings compatible with the partial order, executed from the start: only 4 of 12 in the patch problem are valid. Resolve threats and watch the list change. Demoting ‘Harden’ before ‘Open’ leaves the second threat no solution: the order cycles and must be undone. Arrows replay construction from an empty plan. In Sussman's anomaly no threat can be demoted because nothing may precede start.

In the patch problem backup is unordered relative to everything and occupies all four possible positions in final linearizations: least commitment. Promotion versus demotion matters. “Harden” threatens link Abrir→abiertoDescargar\mathit{Abrir} \xrightarrow{\text{abierto}} \mathit{Descargar}; demoting it (Endurecer≺Abrir\mathit{Endurecer} \prec \mathit{Abrir}) seems reasonable, but “Open” then threatens Endurecer→cerradoFin\mathit{Endurecer} \xrightarrow{\text{cerrado}} \mathit{Fin} and its only resolution Abrir≺Endurecer\mathit{Abrir} \prec \mathit{Endurecer} closes a cycle. A planner discovers this when checking order consistency and backtracks, as the cell does.

[ ]A partial-order planner from scratchBrowser
def alcanzables(ordenes, pasos):
    """Cierre transitivo de las restricciones de orden; None si hay un ciclo."""
    suc = {s: set() for s in pasos}
    for a, b in ordenes:
        suc[a].add(b)
    alc = {}
    for s in pasos:
        vistos, pila = set(), list(suc[s])
        while pila:
            u = pila.pop()
            if u not in vistos:
                vistos.add(u); pila.extend(suc[u])
        if s in vistos:
            return None
        alc[s] = vistos
    return alc

class POP:
    """Búsqueda en el espacio de planes parciales (POP, Weld 1994) con profundización iterativa en el
    número de pasos. Cuenta los planes parciales visitados."""

    def __init__(self, operadores, init, metas):
        self.ops, self.init, self.metas = operadores, frozenset(init), frozenset(metas)
        self.nodos = 0

    def amenaza(self, pasos, enlaces, alc):
        for (p, q, c) in enlaces:
            for s, a in pasos.items():
                if s not in (p, c) and q in a.dele and p not in alc[s] and s not in alc[c]:
                    return s, (p, q, c)                          # s puede caer entre p y c
        return None

    def refinar(self, pasos, ordenes, enlaces, agenda, max_pasos):
        self.nodos += 1
        alc = alcanzables(ordenes, pasos)
        if alc is None:
            return None                                          # orden con un ciclo: inconsistente
        am = self.amenaza(pasos, enlaces, alc)
        if am:
            s, (p, q, c) = am
            for nuevo in ((s, p), (c, s)):                       # degradación, promoción
                r = self.refinar(pasos, ordenes | {nuevo}, enlaces, agenda, max_pasos)
                if r:
                    return r
            return None
        if not agenda:
            return pasos, ordenes, enlaces                       # sin condiciones abiertas ni amenazas
        (q, c), resto = agenda[0], agenda[1:]
        for s, a in pasos.items():                               # 1) un paso existente que produzca q
            if q in a.add and s != c and s not in alc[c]:
                r = self.refinar(pasos, ordenes | {(s, c)}, enlaces + [(s, q, c)], resto, max_pasos)
                if r:
                    return r
        if len(pasos) - 2 < max_pasos:                           # 2) un paso nuevo
            for op in self.ops:
                if q in op.add:
                    s = f"{op.nombre}#{len(pasos) - 1}"
                    p2 = dict(pasos); p2[s] = op
                    o2 = ordenes | {("inicio", s), (s, "fin"), (s, c)}
                    r = self.refinar(p2, o2, enlaces + [(s, q, c)], resto + [(pre, s) for pre in sorted(op.pre)], max_pasos)
                    if r:
                        return r
        return None

    def planificar(self, max_pasos=8):
        pasos = {"inicio": accion("inicio", add=self.init), "fin": accion("fin", pre=self.metas)}
        for k in range(max_pasos + 1):
            r = self.refinar(pasos, frozenset({("inicio", "fin")}), [], [(g, "fin") for g in sorted(self.metas)], k)
            if r:
                return r
        return None

def linealizaciones(pasos, ordenes):
    alc = alcanzables(ordenes, pasos)
    medio = [s for s in pasos if s not in ("inicio", "fin")]
    out = []
    def rec(pref, resto):
        if not resto:
            out.append(pref); return
        for s in resto:
            if not any(u != s and s in alc[u] for u in resto):
                rec(pref + [s], [u for u in resto if u != s])
    rec([], medio)
    return out

def ejecuta(pasos, orden, init, metas):
    s = set(init)
    for x in orden:
        if not pasos[x].pre <= s:
            return False
        s = (s - pasos[x].dele) | pasos[x].add
    return metas <= s

def bloques(nombres):
    ops, lugares = [], nombres + ["mesa"]
    for b in nombres:
        for x in lugares:
            for y in lugares:
                if len({b, x, y}) == 3:
                    ops.append(accion(f"mover({b},{x},{y})",
                                      [f"sobre({b},{x})", f"libre({b})"] + ([f"libre({y})"] if y != "mesa" else []),
                                      [f"sobre({b},{y})"] + ([f"libre({x})"] if x != "mesa" else []),
                                      [f"sobre({b},{x})"] + ([f"libre({y})"] if y != "mesa" else [])))
    return ops

def informe(nombre, ops, init, metas):
    P = POP(ops, init, metas)
    pasos, ordenes, enlaces = P.planificar()
    lin = linealizaciones(pasos, ordenes)
    elegidas = sorted((a, b) for a, b in ordenes if "inicio" not in (a, b) and "fin" not in (a, b))
    print(f"{nombre}: {P.nodos} planes parciales visitados, {len(pasos) - 2} pasos")
    print("   orden:", [f"{a} < {b}" for a, b in elegidas])
    print(f"   linealizaciones: {len(lin)}, todas válidas: {all(ejecuta(pasos, l, init, metas) for l in lin)}")
    for l in lin:
        print("     ", " -> ".join(l))

informe("Anomalía de Sussman", bloques(["A", "B", "C"]),
        {"sobre(A,mesa)", "sobre(B,mesa)", "sobre(C,A)", "libre(B)", "libre(C)"}, {"sobre(A,B)", "sobre(B,C)"})
informe("Parche con puerto temporal",
        [accion("abrir_puerto", [], ["puerto_abierto"], ["puerto_cerrado"]),
         accion("descargar_parche", ["puerto_abierto"], ["parche"]),
         accion("endurecer", [], ["politica", "puerto_cerrado"], ["puerto_abierto"]),
         accion("hacer_copia", [], ["copia"])],
        {"puerto_cerrado"}, {"parche", "politica", "puerto_cerrado", "copia"})

On Sussman’s anomaly, POP finds the three-move plan with a total order forced by two promotions: C to table, B on C, A on B. In patching it leaves four linearizations, one per backup position, all valid as the theorem guarantees. POP also first tries obtaining “port closed” from start: opening threatens that link without any possible resolution (neither before start nor after finish), so search backtracks and obtains closure from “Harden”.

Hierarchical task networks

Earlier approaches receive actions and search for combinations without further knowledge. In real domains that knowledge exists and is valuable: an incident-response manual specifies what to do, order, and acceptable methods. HTN planning writes methods refining abstract tasks into concrete tasks until executable actions.

The difference from classical planning is fundamental: an HTN goal is a task to do, not a fact set, and only decomposition-derived plans count. If methods omit a way to do something, the planner will not find it even if primitive actions permit it. This deliberate restriction lets the domain specify how things are done and the planner choose among ways and check fit.

SHOP: decompose in execution order

SHOP and SHOP2 (Nau et al.; SHOP2: An HTN Planning System, 2003) use ordered decomposition: decompose tasks in execution order. Thus when choosing a method they know the full world state at that point, and preconditions may be arbitrary queries (axioms, arithmetic or external functions), not just atom conjunctions. SHOP2 adds partially ordered subtask networks, allowing subtasks of different tasks to interleave, and received a distinguished performance award at the 2002 International Planning Competition; the 2003 paper explains enabling features, especially in temporal and numeric domains.

The algorithm searches depth-first. Take the first pending task. If primitive and applicable, apply it and continue; if inapplicable, fail. If compound, try methods in order: for each whose precondition holds now, replace the task with subtasks and continue; if later work fails, backtrack to the next method.

InteractiveHTN decomposition
✓respond(srv)
✓contain ← «shut down» apagar
✓eradicate: preserve and clean
✓preserve evidence ← «disk» copiar_disco
✓clean ← «reinstall» reinstalar
✓recover
✓credentials ← «rotate» rotar_credenciales
✓restore data ← «from backup» restaurar_copia
✓power on ← «already on»
✓reconnect
✓monitor
Failed methods, in the order SHOP tried them
✗ contain «via firewall»: then “preserve evidence” fails (method “memory via EDR”: missing edr; method “disk”: missing apagado)
Primitive plan
1. apagar2. copiar_disco3. reinstalar4. rotar_credenciales5. restaurar_copia6. reconectar7. vigilar
Initial state: comprometido, encendido, fw, no_critico, firma, imagen_limpia, copia, cred_expuestas. Tasks are decomposed from top to bottom, in execution order: each method sees the state left by earlier actions.
Situation
What the domain does not model
Plan7 actions
Backtracks1
Plan found after 1 backtrack.
Respond to an incident on host srv: contain, eradicate (preserve evidence and clean), and recover (credentials, data, power, reconnection and monitoring), with alternative methods for each task. The initial state matches the HTN lab cell: no EDR, managed firewall. SHOP first tries firewall containment, but evidence cannot then be preserved (no EDR to dump memory and the host is not off to copy disk); it backtracks and contains by shutdown. Force incompatible methods and see where they fail; remove the clean image; then mark the backup compromised.

Expressiveness and complexity

Hierarchy does more than conveniently express knowledge: it increases expressiveness. Erol, Hendler and Nau (HTN Planning: Complexity and Expressivity, AAAI 1994) proved HTN plan existence undecidable in general, even without variables, once a network may contain two unordered compound tasks: their subtasks can interleave, enabling a decision whether two context-free grammars generate a common string, an undecidable problem. Restricting either restores decidability: with totally ordered networks the problem is EXPSPACE-hard and in 2-EXPTIME, and if also propositional, PSPACE-hard and in EXPTIME; without method recursion (acyclic), decomposition depth is bounded.

The intuition for greater HTN expressiveness than STRIPS is the Chomsky hierarchy. A STRIPS problem’s solutions as a language over actions are regular: recognized by a finite automaton whose states are problem states. If aa and bb are actions without relevant preconditions or effects, compound task XX with methods X→a X bX \to a\,X\,b and X→εX \to \varepsilon generates exactly plans anbna^n b^n, a context-free nonregular language; no STRIPS problem over those actions has that solution set.

Lab 2: a SHOP-style HTN planner

The domain has the interactive’s primitive actions for any number of hosts, plus two no method uses (manually disconnect cable and dump memory locally, requiring physical access). Initial task responder(e1, ..., en) has a recursive method handling hosts one at a time. Solve the same task classically with goal “all hosts monitored”, using earlier A* and greedy search.

[ ]Lab 2: SHOP for incident responseBrowser
def primitivas(h):
    """Acciones primitivas para el equipo h (STRIPS con precondiciones positivas)."""
    return [
        accion(f"aislar_edr({h})", [f"comprometido({h})", f"edr({h})", f"encendido({h})"], [f"aislado({h})"]),
        accion(f"bloquear_fw({h})", [f"comprometido({h})", f"fw({h})"], [f"aislado({h})"]),
        accion(f"apagar({h})", [f"encendido({h})", f"no_critico({h})"], [f"aislado({h})", f"apagado({h})"], [f"encendido({h})"]),
        accion(f"desconectar_cable({h})", [f"comprometido({h})", f"acceso_fisico({h})"], [f"aislado({h})"]),
        accion(f"volcar_memoria({h})", [f"aislado({h})", f"encendido({h})", f"edr({h})"], [f"evidencia({h})"]),
        accion(f"volcar_memoria_local({h})", [f"aislado({h})", f"encendido({h})", f"acceso_fisico({h})"], [f"evidencia({h})"]),
        accion(f"copiar_disco({h})", [f"aislado({h})", f"apagado({h})"], [f"evidencia({h})"]),
        accion(f"eliminar_malware({h})", [f"aislado({h})", f"evidencia({h})", f"firma({h})", f"encendido({h})"], [f"limpio({h})"], [f"comprometido({h})"]),
        accion(f"reinstalar({h})", [f"aislado({h})", f"evidencia({h})", "imagen_limpia"], [f"limpio({h})", f"encendido({h})"], [f"comprometido({h})", f"apagado({h})"]),
        accion(f"arrancar({h})", [f"apagado({h})"], [f"encendido({h})"], [f"apagado({h})"]),
        accion(f"restaurar_copia({h})", [f"limpio({h})", f"copia({h})"], [f"datos({h})"]),
        accion(f"reconectar({h})", [f"limpio({h})", f"datos({h})", f"encendido({h})", f"aislado({h})", "cred_seguras"], [f"servicio({h})"], [f"aislado({h})"]),
        accion(f"vigilar({h})", [f"servicio({h})"], [f"vigilado({h})"]),
    ]

def tarea_incidente(equipos, hechos):
    A = [accion("rotar_credenciales", ["cred_expuestas"], ["cred_seguras"], ["cred_expuestas"])]
    A += [a for h in equipos for a in primitivas(h)]
    atomos = sorted({f for a in A for f in a.pre | a.add | a.dele})
    init = frozenset(hechos) | {f"comprometido({h})" for h in equipos} | {f"encendido({h})" for h in equipos}
    return Tarea(atomos, init, frozenset(f"vigilado({h})" for h in equipos), A)

def metodos(tarea, s):
    """Métodos de una tarea compuesta: lista de (nombre, ¿precondición cierta en s?, subtareas).
    None si la tarea es primitiva."""
    nombre, args = tarea
    h = args[0] if args else None
    if nombre == "responder":                                     # recursión sobre la lista de equipos
        return [("uno a uno", True, [("atender", (args[0],)), ("responder", args[1:])])] if args else [("nada", True, [])]
    if nombre == "atender":
        return [("contener, erradicar, recuperar", True, [("contener", (h,)), ("erradicar", (h,)), ("recuperar", (h,))])]
    if nombre == "contener":
        return [("por firewall", f"fw({h})" in s, [("bloquear_fw", (h,))]),
                ("por EDR", f"edr({h})" in s and f"encendido({h})" in s, [("aislar_edr", (h,))]),
                ("apagando", f"no_critico({h})" in s and f"encendido({h})" in s, [("apagar", (h,))])]
    if nombre == "erradicar":
        return [("preservar y limpiar", True, [("preservar", (h,)), ("limpiar", (h,))])]
    if nombre == "preservar":
        return [("memoria por EDR", f"encendido({h})" in s and f"edr({h})" in s, [("volcar_memoria", (h,))]),
                ("disco", f"apagado({h})" in s, [("copiar_disco", (h,))])]
    if nombre == "limpiar":
        return [("con firma", f"firma({h})" in s and f"encendido({h})" in s, [("eliminar_malware", (h,))]),
                ("reinstalando", "imagen_limpia" in s, [("reinstalar", (h,))])]
    if nombre == "recuperar":
        return [("credenciales, datos, servicio", True, [("credenciales", ()), ("restaurar", (h,)), ("encender", (h,)),
                                                          ("reconectar", (h,)), ("vigilar", (h,))])]
    if nombre == "credenciales":
        return [("rotar", "cred_expuestas" in s, [("rotar_credenciales", ())]), ("ya seguras", "cred_seguras" in s, [])]
    if nombre == "restaurar":
        return [("desde la copia", f"copia({h})" in s, [("restaurar_copia", (h,))])]
    if nombre == "encender":
        return [("ya encendido", f"encendido({h})" in s, []), ("arrancar", f"apagado({h})" in s, [("arrancar", (h,))])]
    return None

def shop(acciones, s, tareas, stats):
    """Descomposición ordenada total con retroceso. Devuelve la lista de acciones o None."""
    stats["nodos"] += 1
    if not tareas:
        return []
    t, resto = tareas[0], tareas[1:]
    ms = metodos(t, s)
    if ms is None:                                                # primitiva: se ejecuta sobre el estado actual
        nombre = f"{t[0]}({','.join(t[1])})" if t[1] else t[0]
        a = acciones[nombre]
        if not a.pre <= s:
            return None
        r = shop(acciones, (s - a.dele) | a.add, resto, stats)
        return None if r is None else [nombre] + r
    for _, pre, sub in ms:
        if pre:
            r = shop(acciones, s, sub + resto, stats)
            if r is not None:
                return r
            if len(ms) > 1:
                stats["retrocesos"] += 1                          # se abandona un método en un punto de elección
    return None

def planificar_htn(tarea, equipos):
    stats = {"nodos": 0, "retrocesos": 0}
    acc = {a.nombre: a for a in tarea.acciones}
    return shop(acc, frozenset(tarea.init), [("responder", tuple(equipos))], stats), stats

def hechos(equipos, extra=(), sin=()):
    H = {"imagen_limpia", "cred_expuestas"}
    for h in equipos:
        H |= {f"fw({h})", f"no_critico({h})", f"firma({h})", f"copia({h})"}
    return (H | set(extra)) - set(sin)

T1 = tarea_incidente(["srv"], hechos(["srv"]))
plan, st = planificar_htn(T1, ["srv"])
print("Un equipo:", plan)
print("   ", st)
print("\n n | HTN: nodos, retrocesos | voraz h_add: expandidos, acciones | A* h_max: expandidos, acciones")
for n in range(1, 7):
    eqs = [f"e{i}" for i in range(1, n + 1)]
    T = tarea_incidente(eqs, hechos(eqs))
    p, st = planificar_htn(T, eqs)
    pv, ev = mejor_primero(T, h_add, 0)
    fila = f"{n:2d} | {st['nodos']:4d} {st['retrocesos']:3d} ({len(p)} acciones) | {ev:5d} {len(pv):3d}"
    if n <= 3:
        pa, ea = mejor_primero(T, h_max, 1)
        fila += f" | {ea:6d} {len(pa):3d}"
    print(fila)

With one host, SHOP visits a few nodes and backtracks once: “via firewall” applies but leaves the host on without EDR, and no “preserve” method applies next; SHOP undoes it and contains by shutdown. The plan has 7 actions, as do optimal A* and greedy plans. The table shows scaling: SHOP grows linearly because procedure fixes order and there is nothing to explore. Optimal A* grows exponentially because hosts are independent and all action interleavings must be considered: an optimal plan has many orderings A* does not know are equivalent. Greedy search with haddh_{\text{add}} goes straight to a plan in this delete-relaxation-friendly domain. The honest comparison is not “HTN is faster than heuristic search”: HTN is predictable and follows procedure, while heuristic search finds what the goal permits.

Two situations outside the domain show the other side:

[ ]What HTN misses and assumesBrowser
# 1) Equipo crítico, sin EDR ni firewall, pero con acceso físico: ningún método de «contener» encaja
sin_metodo = hechos(["srv"], extra={"acceso_fisico(srv)"}, sin={"fw(srv)", "no_critico(srv)"})
T2 = tarea_incidente(["srv"], sin_metodo)
p, st = planificar_htn(T2, ["srv"])
pc, ec = mejor_primero(T2, h_add, 0)
print("HTN:", p, st)
print("Clásico:", pc)

# 2) La copia está comprometida, un hecho que el método «desde la copia» no comprueba
def ejecutar_en_el_mundo(plan, init, comprometida):
    """El mundo real: restaurar una copia comprometida reinfecta el equipo."""
    s = set(init)
    acc = {a.nombre: a for a in T1.acciones}
    for n in plan:
        s = (s - acc[n].dele) | acc[n].add
        if n.startswith("restaurar_copia") and comprometida:
            s |= {"comprometido(srv)"}; s.discard("limpio(srv)")
    return s

plan, _ = planificar_htn(T1, ["srv"])
final = ejecutar_en_el_mundo(plan, T1.init, comprometida=True)
print("\nPlan del modelo:", plan)
print("En el mundo real, al final: vigilado =", "vigilado(srv)" in final, "  comprometido =", "comprometido(srv)" in final)

In the first, the classical planner finds a plan (disconnect cable, dump memory locally, remove malware…) and SHOP finds none: a critical host cannot be shut down, and there is neither firewall nor EDR. No containment method applies. The procedure did not anticipate this. That may be correct (perhaps the manual forbids improvising with the cable) or a domain gap; either way “no plan” should mean “escalate to a person”, not “nothing can be done”.

HTN in practice

Erol, Hendler and Nau already observed in 1994 that most practical work of the preceding fifteen years used HTN decomposition, such as NOAH, NONLIN, SIPE and DEVISER. Later documented cases: Bridge Baron 8 used HTN for declarer play and won the 1997 world computer bridge championship (Smith, Nau and Throop, Computer Bridge: A Big Win for AI Planning, AI Magazine, 1998); and Killzone 2 multiplayer bots (Guerrilla Games, 2009) used an HTN planner with 360 methods according to Champandard, Verweij and Straatman’s Paris Game AI Conference presentation that year. The reason is consistent: designers control possible behaviors and the plan is explainable by construction, each action under a named task. Language-model agents’ task decomposition has HTN as a formal ancestor, with “methods” in natural language rather than logic, sharing both risks: undescribed things are not attempted, and unwritten assumptions are not checked.

Beyond the classical model

The classical model assumes instantaneous actions, a finite fully observable state, deterministic effects and binary goals. Relaxing each gives a family of problems with languages and complexity. This map is planning beyond the classical model.

ExtensionWhat changesUsual representationPlan existence
Classical (STRIPS)nothingPDDLPSPACE-complete (Bylander, 1994)
Numeric and temporalnumeric variables, durations, real concurrencyPDDL 2.1undecidable with unbounded numbers (Helmert, 2002)
Fully observable nondeterministic (FOND)an action may have multiple outcomesPDDL with oneofEXPTIME-complete (Littman, 1997; Rintanen, 2004)
Conformantuncertain initial state, no observationsbelief statesEXPSPACE-complete (Haslum and Jonsson, 2000)
Conditional with partial observabilitysome state observedbelief trees or policies2-EXPTIME-complete (Rintanen, 2004)
Probabilisticoutcome probabilitiesMDP, POMDPdepends on criterion (horizon, discount)

Time and resources. PDDL 2.1 (Fox and Long, PDDL2.1: An Extension to PDDL for Expressing Temporal Planning Domains, 2003) organizes extensions into levels: level 1 is propositional planning; 2 adds numeric variables (fuel, money, capacity), increment/decrement effects and an optimization metric; 3 adds discretized durative actions, with conditions required at start (at start), end (at end) or throughout (over all), and effects at start or end; 4 adds continuous durative actions. A plan becomes actions with start times, and concurrency is a requirement rather than search reduction: some problems require actions to overlap. Temporal planners combine state search with simple temporal constraints and, like POPF, partial orders.

Nondeterminism. If abrir_puerta can fail, a plan is no longer a sequence but a policy specifying what to do depending on outcomes. Cimatti, Pistore, Roveri and Traverso (Weak, strong, and strong cyclic planning via symbolic model checking, Artificial Intelligence, 2003) distinguish weak solutions (some outcome reaches the goal), strong (all reach it in bounded steps) and strong cyclic (all executions not trapped in a loop reach it, assuming every outcome eventually occurs, as in “retry until success”).

Uncertainty without observation. In conformant planning the initial state is one of several and nothing is observed: the plan must work in all. Search uses belief states, sets of possible states, exponentially larger. Hence the PSPACE-to-EXPSPACE jump.

The jump to probability. With outcome probabilities and rewards replacing goals, the problem is a Markov decision process, and with partial observation a POMDP, which becomes an MDP over belief states. Prior ideas remain useful: factored representations like PDDL compactly describe huge MDPs, classical planning heuristics guide solutions (FF-Replan determinizes, plans with FF and replans after deviations; it won the first probabilistic competition in 2004), and hierarchical decomposition reappears in hierarchical reinforcement learning and robotic task-and-motion planning.

Common mistakes

Exercises

ProofMutexes are sound
Prove: If literals ℓ\ell and ℓ′\ell' are mutex at planning-graph level SiS_i, no ii-step parallel plan (action sets without inconsistent-effect or interfering pairs) executable from the initial state ends with both ℓ\ell and ℓ′\ell' true.
0
Induct on ii. Represent each parallel step as its action set plus persistence for every unchanged literal; call the plan's states s0,…,sis_0, \dots, s_i.

Step 1 of 4. What is the base case?

QuizWhy are they mutex?
At level S1S_1 of surprise dinner, cena\mathit{cena} and ¬manos\neg\mathit{manos} are mutually exclusive. Why?
NumericEncoding size
A STRIPS problem has F=20F = 20 atoms, ∣G∣=4\abs{G} = 4 goals and A=30A = 30 actions, each with p=2p = 2 preconditions and e=3e = 3 effects (adds plus deletes). With horizon T=10T = 10, sequential semantics (all action pairs excluded each step by binary clauses) and explanatory frame axioms, how many clauses does ΦT\Phi_T have?
NumericCommitment saved by a partial order
A complete partial-order plan has six steps: a1≺a2≺a3a_1 \prec a_2 \prec a_3, b1≺b2b_1 \prec b_2 and step cc unordered relative to the rest (except start and finish). How many linearizations does it have?
QuizAn ∃-step that is not a ∀-step
In REPARTO's ∃ plan, step 1 contains cargar(p1,c1,A), cargar(p3,c2,C), conducir(c1,A,B) and conducir(c2,C,B). Why is that set not a valid ∀-step?
QuizHTN or classical planning?
A security team wants to automate ransomware incident response. It has a legal-approved operating manual (notification order, preserving evidence before touching anything, who authorizes shutdown of critical systems) and wants every action auditable. It also worries about incidents the manual omits. What approach and precautions are most suitable?
QuizPromotion or demotion
A partial plan has link s→qcs \xrightarrow{q} c and step tt deleting qq, with no order constraints between tt and ss or between tt and cc. Which statements are true?

More than one answer may be correct.

CodeSATPlan encoding with ∀-steps
Implement codificar(atomos, init, meta, acciones, T), where acciones is a list of tuples (nombre, pre, add, dele) with atom sets. Return (nv, clausulas, x, a): variable count, DIMACS clause list (integer lists), x[t][f] the variable for atom f at instant t (0 to T), and a[t][i] for action i at step t (0 to T - 1). Include the complete initial state, goals, preconditions, effects, explanatory frame axioms and ∀-step mutexes (exclude pairs when one action deletes the other's precondition). Tests solve your formula using a PySAT solver.
def codificar(atomos, init, meta, acciones, T):
  nv = 0
  x, a = [], []
  for t in range(T + 1):
      x.append({})
      for f in atomos:
          nv += 1
          x[t][f] = nv
  for t in range(T):
      a.append([])
      for _ in acciones:
          nv += 1
          a[t].append(nv)
  C = [[x[0][f]] if f in init else [-x[0][f]] for f in atomos]
  C += [[x[T][g]] for g in meta]
  # tu código: precondiciones, efectos, marco y exclusiones
  return nv, C, x, a
Shift+Enter to run

Summary

Key idea
State search is not the only way to plan: a plan can be a path in a layered graph (GraphPlan), a formula model (SAT), a partial order with causal links (POP), or a refined procedure (HTN), each representation simplifying something difficult in others.
  • GraphPlan builds literal and action levels with pairwise mutexes in polynomial time. A mutex at SiS_i proves no ii-step plan; its absence proves nothing, so backward extraction with nogoods and termination test is needed.
  • SAT planning encodes “an TT-step plan exists” with time-indexed variables, effects, explanatory frame axioms and mutexes. Without frames atoms change without cause; without mutexes interfering actions run together.
  • Parallel semantics determine horizon: sequential, ∀-steps (any order works) or ∃-steps (one fixed order works). Minimum horizon does not minimize actions: REPARTO’s 5 ∀-steps require 10 actions versus sequential optimum 9.
  • SAT competes with heuristic search through linear encodings, parallel horizon evaluation, incremental solving with assumptions and planning-specific decision heuristics.
  • Partial order resolves threats by promotion or demotion; a plan without open conditions or threats is valid in all linearizations.
  • HTN plans by refining tasks through methods in execution order (SHOP). More expressive than STRIPS, predictable and auditable, it still misses what methods do not describe and inherits authors’ unwritten assumptions.
  • Beyond classical planning lie time and numbers (PDDL 2.1), nondeterminism (strong and strong cyclic solutions), conformant belief states, and probabilistic MDPs and POMDPs.