|
Última actualización: 2026-12-02
DAY 030 OF 1600 · 2026-11-04 Day 030 — The heuristic never lied, and the route was still worseA student's private learning log · one concept at a time. Date: 2026-11-04 · Day: 30 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #30 — Admissibility buys optimality only if nothing is written offMA08, Intelligent Search, week 1. The lecture opens with the distinction everybody nods at and nobody uses: a state is a configuration of the world, a node is a bookkeeping object in the search tree — state plus parent, action, depth, accumulated cost g . Two nodes can hold the same state reached by different routes. Because of that, graph search keeps an explored set and refuses to expand a state twice, while tree search does not and can loop forever on a cycle. That was the week-1 exam trap, word for word: *the search tree is not the state space*. Then the heuristic. The textbook line is f(n) = g(n) + h(n) , admissibility is h(n) ≤ h (n) — never overestimate — and A with an admissible heuristic is optimal. I had accepted that sentence for a year. It is incomplete, and the missing half is exactly the thing the explored set does. Admissibility is a statement about one node at a time : my guess about the remaining cost is not a lie. Consistency is a statement about **two nodes and the edge between them**: h(u) ≤ c(u,v) + h(v) — the guess cannot drop faster than the cost of actually walking there. If the second holds, f never decreases along a path, nodes are popped in non-decreasing f , and the first time a state enters the explored set it enters with its optimal g . Written off, and correctly so. If only the first holds, a state can be closed with a g that is not yet optimal, and the cheaper route arrives later to a door that is already shut. So I stopped reading and measured it. Random directed graphs, 6 to 9 nodes, integer edge costs 1 to 5, h*(n) computed exactly with Dijkstra on the reversed graph, and then a heuristic drawn uniformly from [0, h*(n)] . Every one of those heuristics is admissible by construction — it is a number between zero and the truth, it cannot overestimate. Then two A* implementations, identical except for one line: whether a state that already sits in the explored set can be expanded again. What I tried today: one file, stdlib only. Random graph generator, exact h* , a consistency checker, A* with and without re-opening closed states, and a 40×40 grid with walls where the same search runs under three heuristics while counting expansions. #!/usr/bin/env python3 """MA08 Intelligent Search, week 1. One idea: an admissible heuristic only buys optimality if the search is allowed to revisit a state it already closed. Consistency is what makes the closed set safe. stdlib only. No network. """ import heapq import random # ---------------------------------------------------------------- graph search def hstar(adj, rev, goal): """True remaining cost to goal, via Dijkstra on the reversed graph.""" dist = {goal: 0} pq = [(0, goal)] while pq: d, u = heapq.heappop(pq) if d > dist.get(u, float("inf")): continue for p, c in rev.get(u, []): nd = d + c if nd < dist.get(p, float("inf")): dist[p] = nd heapq.heappush(pq, (nd, p)) return dist def astar(adj, start, goal, h, reopen): """A* graph search. reopen=False is the textbook version: once a state enters the closed set it is never expanded again.""" gbest = {start: 0} parent = {start: None} pq = [(h.get(start, 0), 0, start, 0)] closed, expanded, tie = set(), 0, 1 while pq: f, _, u, g = heapq.heappop(pq) if g > gbest.get(u, float("inf")): continue # stale entry, a cheaper route exists if u in closed and not reopen: continue # the explored set, no second chance if u == goal: path = [] while u is not None: path.append(u) u = parent[u] return g, expanded, path[::-1] closed.add(u) expanded += 1 for v, c in adj.get(u, []): if v in closed and not reopen: continue ng = g + c if ng < gbest.get(v, float("inf")): gbest[v] = ng parent[v] = u heapq.heappush(pq, (ng + h.get(v, 0), tie, v, ng)) tie += 1 return None, expanded, None def is_consistent(adj, h): for u, edges in adj.items(): for v, c in edges: if h.get(u, 0) > c + h.get(v, 0): return False return True # -------------------------------------------------------------------- witness def random_instance(rng, n): nodes = list(range(n)) adj = {u: [] for u in nodes} for u in nodes: for v in nodes: if u != v and rng.random() < 0.45: adj[u].append((v, rng.randint(1, 5))) rev = {u: [] for u in nodes} for u in nodes: for v, c in adj[u]: rev[v].append((u, c)) goal = n - 1 d = hstar(adj, rev, goal) if len(d) != n: # keep only instances where every node reaches goal return None # admissible by construction: every estimate sits somewhere in [0, h*] h = {u: rng.randint(0, d[u]) for u in nodes} h[goal] = 0 return adj, h, d, goal def main(): rng = random.Random(20261104) tried = inconsistent = witnesses = 0 first = None for _ in range(20000): inst = random_instance(rng, rng.randint(6, 9)) if inst is None: continue adj, h, d, goal = inst tried += 1 cons = is_consistent(adj, h) if not cons: inconsistent += 1 best, _, _ = astar(adj, 0, goal, h, reopen=True) bad, _, bad_path = astar(adj, 0, goal, h, reopen=False) if best != d[0]: raise SystemExit("reopen A* is not optimal -- implementation bug") if bad != best: if cons: raise SystemExit("consistency is supposed to protect the closed set") witnesses += 1 if first is None: first = (adj, h, d, goal, bad, best, bad_path) adj, h, d, goal, bad, best, bad_path = first print("== 1. admissible heuristic + closed set, 20000 random graphs") print(f" instances checked : {tried}") print(f" heuristics inconsistent : {inconsistent} " f"({inconsistent/tried:.1%}) -- all of them still admissible") print(f" reopen A* optimal : {tried}/{tried} (asserted)") print(f" closed-set A* SUBOPTIMAL : {witnesses} " f"({witnesses/tried:.2%} of all, {witnesses/inconsistent:.2%} of the inconsistent ones)") print(f" closed-set A* wrong on a consistent heuristic: 0 (asserted)") print() print(" first witness (start=0, goal=%d), reached path %s for %d, optimal %d:" % (goal, bad_path, bad, d[0])) for u in sorted(adj): for v, c in adj[u]: note = "CONSISTENCY BREAKS HERE" if h[u] > c + h[v] else "" print(f" {u} -> {v} cost {c} h({u})={h[u]} h({v})={h[v]} {note}") print(f" closed-set A* returned {bad}, optimal is {d[0]}\n") # ---------------------------------------------------------- grid, counted print("== 2. same search, a 40x40 grid with walls, three heuristics") size, walls = 40, 0.22 g_rng = random.Random(7) blocked = {(x, y) for x in range(size) for y in range(size) if g_rng.random() < walls and (x, y) not in ((0, 0), (size-1, size-1))} start, target = (0, 0), (size - 1, size - 1) def moves(p): x, y = p for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)): q = (x + dx, y + dy) if 0 <= q[0] < size and 0 <= q[1] < size and q not in blocked: yield q, 1 def manhattan(p): return abs(p[0] - target[0]) + abs(p[1] - target[1]) adj_g = {} for x in range(size): for y in range(size): if (x, y) not in blocked: adj_g[(x, y)] = list(moves((x, y))) rows = [] for name, fn, scale in (("UCS (h=0)", None, 0), ("A* manhattan", manhattan, 1), ("A* 3x manhattan", manhattan, 3)): h = {p: 0 for p in adj_g} if fn is None else {p: scale * fn(p) for p in adj_g} cost, exp, _ = astar(adj_g, start, target, h, reopen=False) rows.append((name, cost, exp, is_consistent(adj_g, h))) base = rows[0] for name, cost, exp, cons in rows: tag = "" if cost == base[1] else " <-- NOT the cheapest path" print(f" {name:16s} cost {cost:4d} expanded {exp:5d} consistent {str(cons):5s}{tag}") print(f" cheapest path cost : {base[1]} (UCS is the baseline)") print(f" A* manhattan expands : {rows[1][2]} nodes, " f"{100*(1-rows[1][2]/base[2]):.1f}% fewer than UCS, same cost") print(f" A* 3x manhattan expands : {rows[2][2]} nodes, " f"{(1-rows[2][2]/rows[1][2])*100:.1f}% fewer than manhattan A*, " f"cost {rows[2][1]} vs {base[1]}") if __name__ == "__main__": main() Real output: == 1. admissible heuristic + closed set, 20000 random graphs instances checked : 16703 heuristics inconsistent : 12979 (77.7%) -- all of them still admissible reopen A* optimal : 16703/16703 (asserted) closed-set A* SUBOPTIMAL : 82 (0.49% of all, 0.63% of the inconsistent ones) closed-set A* wrong on a consistent heuristic: 0 (asserted) first witness (start=0, goal=5), reached path [0, 4, 2, 5] for 12, optimal 11: 0 -> 3 cost 3 h(0)=7 h(3)=8 0 -> 4 cost 5 h(0)=7 h(4)=0 CONSISTENCY BREAKS HERE 1 -> 5 cost 1 h(1)=1 h(5)=0 2 -> 0 cost 4 h(2)=2 h(0)=7 2 -> 3 cost 2 h(2)=2 h(3)=8 2 -> 4 cost 2 h(2)=2 h(4)=0 2 -> 5 cost 3 h(2)=2 h(5)=0 3 -> 0 cost 1 h(3)=8 h(0)=7 3 -> 4 cost 1 h(3)=8 h(4)=0 CONSISTENCY BREAKS HERE 4 -> 2 cost 4 h(4)=0 h(2)=2 4 -> 3 cost 4 h(4)=0 h(3)=8 5 -> 1 cost 4 h(5)=0 h(1)=1 5 -> 2 cost 5 h(5)=0 h(2)=2 5 -> 3 cost 4 h(5)=0 h(3)=8 closed-set A* returned 12, optimal is 11 == 2. same search, a 40x40 grid with walls, three heuristics UCS (h=0) cost 78 expanded 1228 consistent True A* manhattan cost 78 expanded 514 consistent True A* 3x manhattan cost 82 expanded 101 consistent False <-- NOT the cheapest path cheapest path cost : 78 (UCS is the baseline) A* manhattan expands : 514 nodes, 58.1% fewer than UCS, same cost A* 3x manhattan expands : 101 nodes, 80.4% fewer than manhattan A*, cost 82 vs 78 What I understood from it: three numbers, and none of them is the one I expected. First: 77.7% of the admissible heuristics were inconsistent. Admissible is not rare, and it is also not enough — nearly four out of five honest heuristics break the property that makes a closed set safe. That is not a technicality about pathological examples; it is the common case. Second: the closed-set version returned a worse route on 82 of 16,703 instances (0.49%), and on 0.63% of the inconsistent ones. Small, and permanent. The witness is five nodes: it walked 0 → 4 → 2 → 5 for 12 when 11 was available, because the edge 0 → 4 costs 5 while h(0) = 7 and h(4) = 0 , so the estimate fell by 7 across an edge that costs 5. Node 4 was closed at g = 5 ; the better prefix 0 → 3 → 4 (cost 4) arrived afterwards and found node 4 already in the explored set. The same search with re-opening was optimal on all 16,703 , and on the consistent heuristics the closed set never once cost me a single unit. So consistency is not a stronger form of admissibility to be proved "if you have time": it is the exact condition under which forgetting is free. Third, the grid, because expansions are the currency I actually spend. Cheapest path 78 steps. Uniform-cost search expanded 1228 states. A* with Manhattan distance expanded 514 — 58.1% fewer, same 78. A* with 3× Manhattan, which is inadmissible, expanded 101 — another 80.4% fewer, and the path costs 82 . So the trade is real and it is priced: 80% of the work saved for 5% of the route. That is a good trade for a robot delivering samples and a bad trade for a router billing by the metre, and the difference between the two is a line of code nobody thinks to check. The sentence I will keep from today: **a heuristic is a claim about the future, and a closed set is a decision to stop listening.** Admissibility constrains the claim. Consistency is what makes the decision safe. If you cannot prove consistency, do not delete the re-open branch — it costs a heap operation, not a rewrite. --- Security #30 — The greeting was a program, because the template was built from it (CWE-1336)Different bug class today, and a modern one: server-side template injection. The story is always the same shape. Somebody wants a personalised message, and the code that starts as render("Hello, " + request.args["name"] + "!") is not a string formatting call. render parses its argument as a program . The attacker's text stops being data the moment it is concatenated into the source, exactly like SQL string building — except the language here is Turing-complete, has access to Python introspection, and every object in the process is reachable through __class__ , __mro__ , __subclasses__ and __globals__ . {{7*7}} is the fingerprint; the chain that follows is not clever, it is just cycler.__init__.__globals__.os.popen(...) and the process runs what you typed. The pattern I studied: # the bug, in one line and in the shape it really ships def render_concat(text): return jinja2.Environment().from_string("Hello, " + text + "!").render() render_concat("{{cycler.__init__.__globals__.os.popen('echo RAN').read()}}") What I understood about preventing it: # the fix: the template is a constant, the user's text is a value TEMPLATE = jinja2.Environment(undefined=jinja2.StrictUndefined) \ .from_string("Hello, {{ name }}!") TEMPLATE.render(name=user_text) # {{7*7}} stays a literal, evaluated never # the second fence, for when a template really must come from outside: from jinja2.sandbox import SandboxedEnvironment SandboxedEnvironment().from_string(user_text).render() Sandbox check (local only): == 1. one string, three renderers A concat (bug) arithmetic EVALUATED Hello, 49! config leak EVALUATED Hello, <class '_sitebuiltins._Helper'>! rce EVALUATED Hello, RAN ! shadow read EVALUATED Hello, LEAK-OK ! B variable (fix) arithmetic inert (rendered as text) Hello, {{7*7}}! config leak inert (rendered as text) Hello, {{self.__init__.__globals__['__builtins__']['help']._ rce inert (rendered as text) Hello, {{cycler.__init__.__globals__.os.popen('echo RAN').re shadow read inert (rendered as text) Hello, {{lipsum.__globals__['os'].popen('echo LEAK-OK').read C sandbox arithmetic EVALUATED Hello, 49! config leak blocked: SecurityError access to attribute '__init__' of 'TemplateReference' object rce blocked: SecurityError access to attribute '__init__' of 'type' object is unsafe. shadow read blocked: SecurityError access to attribute '__globals__' of 'function' object is un == 2. what actually happened in A input : {{cycler.__init__.__globals__.os.popen('echo RAN').read()}} output: Hello, RAN ! len : 12 chars -- the renderer returned the shell's stdout, newline and all == 3. the same payload where the value is data, not source input : {{7*7}} B out : Hello, {{7*7}}! B out : Hello, {{cycler.__init__.__globals__.os.... == 4. sandbox verdict SecurityError: access to attribute '__init__' of 'type' object is unsafe. What I understood: the fix and the fence are not the same thing, and the numbers show it. Concatenation evaluated 4 of 4 payloads, including a real popen that returned the shell's stdout into the page — that is not a theoretical RCE, that is the renderer handing me the process. Passing the same text as a variable evaluated 0 of 4 : the braces come back as braces, because the parser only ever saw the constant template. The SandboxedEnvironment blocked 3 of 4 with SecurityError on __init__ , __globals__ , __subclasses__ — but it still evaluated {{7*7}} to 49 , and that is the whole lesson: a sandbox is a fence around a language, not a substitute for keeping the user's text out of the source. Every template engine has a "user-supplied template" feature and every one of them is a code-execution endpoint with a nicer name. The defensible rule is narrower than "sanitise the input": **the template string is source, and source does not come from the request.** --- Day 30 notesConcept #30: MA08 week 1, admissibility vs consistency, measured. 16,703 random graphs, heuristics admissible by construction, 77.7% inconsistent. Re-open A*: optimal 16,703/16,703. Closed-set A*: suboptimal on 82 (0.49%), worst witness 12 vs 11 on a five-node graph, and 0 failures on consistent heuristics. Grid 40×40, cheapest 78: UCS 1228 expansions, Manhattan A* 514 (−58.1%), 3× Manhattan 101 (−80.4%) at cost 82. ✔ Security #30: SSTI. Concatenated template 4/4 payloads evaluated including a real shell call; variable-in-static-template 0/4; sandbox 3/4 blocked and still evaluated the arithmetic. Template is source, request is data. ✔ 1570 days left. One at a time. Written by my own daily machine, checked by me. · Day 030 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |