Última actualización: 2026-12-02

DAY 033 OF 1600 · 2026-11-09

Day 033 — The model is the search: 105x apart, and a heuristic that bought nothing

A student's private learning log · one concept at a time. Date: 2026-11-09 · Day: 33 of 1600 Log: a student's private learning log · one concept at a time. ---

Concept #33 — Model first: the assignment space is a decision

MA08, Intelligent Search, week 4. Weeks 1 to 3 all searched for a sequence: a path, a better configuration, a policy. Week 4 stops looking for a sequence at all. A constraint satisfaction problem is a triple (X, D, C) — variables, their domains, the combinations that are allowed — and the answer is a complete, consistent assignment . Assignment is commutative: writing AI = T1 then ML = T2 lands in exactly the same place as the other order. So there is no path to return, and that is what makes plain depth-first backtracking correct here without revisiting states: every solution appears once, at depth n. The standard formulation is three lines. Initial state: the empty assignment. Successor: assign a value to one unassigned variable if the result stays consistent. Goal test: the assignment is complete. Everything else is a lever, and there are three of them:

order — which variable next, which value first; inference — maintain the domains, prune before trying; formulation — what the variables are, before any search starts.

The week's claim is that the third one dominates. I measured all three on two problems I could solve by hand, with one generic solver so the comparison is not an artefact of two different programs. value attempts counts values actually tried; pruned counts partial assignments abandoned the moment a domain went empty. What I tried today: one file, stdlib only, no network. 8–11 queens with three strategies, a 5-session campus timetable with a unary and four binary constraints, and one allocation problem written twice — 24 boolean variables versus 6 variables with a school domain. """Day 33 concept: a CSP is an assignment problem, and the model decides the search. One file, stdlib only. Output must be byte-identical on every run.""" def solve(variables, domains, ok, select=None, forward_check=False, limit=None): """Generic backtracking over partial assignments. nodes = value attempts; wipes = partial assignments abandoned by propagation.""" stats = {"nodes": 0, "wipes": 0} dom = {v: set(domains[v]) for v in variables} order = list(variables) def pick(assign, d): if select == "mrv": best = None for v in order: if v in assign: continue if best is None or len(d[v]) < len(d[best]): best = v return best for v in order: if v not in assign: return v return None def rec(assign, d): if len(assign) == len(order): return [dict(assign)] v = pick(assign, d) out = [] for val in sorted(d[v]): stats["nodes"] += 1 if not ok(assign, v, val): continue nd = d if forward_check: nd = {u: set(x) for u, x in d.items()} nd[v] = {val} dead = False for u in order: if u == v or u in assign: continue nd[u] = {x for x in nd[u] if ok({**assign, v: val}, u, x)} if not nd[u]: dead = True break if dead: stats["wipes"] += 1 continue assign[v] = val out += rec(assign, nd) del assign[v] if limit and len(out) >= limit: break return out sols = rec({}, dom) return sols, stats # ---------- 1. n-queens: one CSP, three ways to search it ---------- def queens(n, select=None, fc=False): variables = [f"q{c}" for c in range(n)] domains = {v: set(range(n)) for v in variables} col = {v: c for c, v in enumerate(variables)} def ok(assign, v, row): c = col[v] for u, r in assign.items(): if u == v: continue if r == row or abs(r - row) == abs(col[u] - c): return False return True sols, st = solve(variables, domains, ok, select=select, forward_check=fc) return len(sols), st # ---------- 2. Smart-campus timetable ---------- SESSIONS = ["AI", "DS", "ML", "SE", "MATH"] SLOTS = ["T1", "T2", "T3"] ROOMS = ["R1", "R2"] VALUES = [(t, r) for t in SLOTS for r in ROOMS] CANNOT_OVERLAP = [("AI", "ML"), ("DS", "ML"), ("AI", "DS")] def timetable(select=None, fc=False): domains = {s: set(VALUES) for s in SESSIONS} domains["SE"] = {v for v in VALUES if v[1] == "R2"} # unary: SE in R2 def ok(assign, v, val): for u, other in assign.items(): if u == v: continue if other == val: # one session per (slot, room) return False pair = tuple(sorted((u, v))) if pair in CANNOT_OVERLAP and other[0] == val[0]: return False return True sols, st = solve(SESSIONS, domains, ok, select=select, forward_check=fc) return sols, st # ---------- 3. two formulations of one allocation problem ---------- CHILDREN = ["kid1", "kid2", "kid3", "kid4", "kid5", "kid6"] SCHOOLS = ["S1", "S2", "S3", "S4"] CAPACITY = {"S1": 2, "S2": 2, "S3": 1, "S4": 1} WALK_OK = {"kid1": {"S1", "S2"}, "kid2": {"S1", "S3"}, "kid3": {"S2", "S3"}, "kid4": {"S2", "S4"}, "kid5": {"S3", "S4"}, "kid6": {"S1", "S4"}} def model_one_var_per_child(): variables = list(CHILDREN) domains = {c: set(WALK_OK[c]) for c in CHILDREN} def ok(assign, v, s): used = sum(1 for u, x in assign.items() if u != v and x == s) + 1 return used <= CAPACITY[s] return solve(variables, domains, ok, select="mrv", forward_check=True) def model_boolean_naive(limit=1): """24 boolean variables, no completeness rule. Only 'at most one school'.""" variables = [f"{c}|{s}" for c in CHILDREN for s in SCHOOLS] domains = {v: {0, 1} for v in variables} def ok(assign, v, val): c, s = v.split("|") if val == 1 and s not in WALK_OK[c]: return False for u, x in assign.items(): if u == v or x != 1: continue if u.split("|")[0] == c: return False # two schools for one child if u.split("|")[1] == s: used = sum(1 for w, y in assign.items() if y == 1 and w.split("|")[1] == s) + 1 if used > CAPACITY[s]: return False return True return solve(variables, domains, ok, select=None, forward_check=False, limit=limit) def model_boolean_propagated(): """Same 24 variables, but assigning 1 forces the siblings to 0 immediately.""" pairs = [(c, s) for c in CHILDREN for s in SCHOOLS] stats = {"nodes": 0} out = [] def rec(assign): if len(assign) == len(pairs): per_child = {c: 0 for c in CHILDREN} per_school = {s: 0 for s in SCHOOLS} for (c, s), val in assign.items(): if val: per_child[c] += 1 per_school[s] += 1 if all(per_child[c] == 1 for c in CHILDREN) and \ all(per_school[s] <= CAPACITY[s] for s in SCHOOLS): out.append(dict(assign)) return c, s = pairs[len(assign)] for val in (1, 0): stats["nodes"] += 1 if val == 1: if s not in WALK_OK[c]: continue used = sum(1 for (cc, ss), vv in assign.items() if vv == 1 and ss == s) if used + 1 > CAPACITY[s]: continue if any(vv == 1 and cc == c for (cc, ss), vv in assign.items()): continue forced = {p: 0 for p in pairs[len(assign) + 1:] if p[0] == c} for p in forced: stats["nodes"] += 1 assign.update(forced) assign[(c, s)] = 1 rec(assign) for p in forced: del assign[p] del assign[(c, s)] else: assign[(c, s)] = 0 rec(assign) del assign[(c, s)] rec({}) return out, stats def main(): print("== 1. n-queens: one CSP, three ways to search it ==") print(f"{'n':>2} {'strategy':<24} {'solutions':>9} {'value attempts':>14} {'pruned':>7}") for n in (8, 9, 10, 11): for label, sel, fc in (("static order", None, False), ("MRV", "mrv", False), ("MRV + forward checking", "mrv", True)): sols, st = queens(n, select=sel, fc=fc) print(f"{n:>2} {label:<24} {sols:>9} {st['nodes']:>14} {st['wipes']:>7}") print() print("== 2. timetable: 5 sessions, unary + binary constraints ==") print(f"{'model':<24} {'solutions':>9} {'value attempts':>14} {'pruned':>7}") for label, sel, fc in (("static order", None, False), ("MRV", "mrv", False), ("MRV + forward checking", "mrv", True)): sols, st = timetable(select=sel, fc=fc) print(f"{label:<24} {len(sols):>9} {st['nodes']:>14} {st['wipes']:>7}") print() print("== 3. same allocation problem, two formulations ==") raw_bool = 2 ** (len(CHILDREN) * len(SCHOOLS)) raw_kid = 1 for c in CHILDREN: raw_kid *= len(WALK_OK[c]) print(f"boolean: {len(CHILDREN) * len(SCHOOLS)} vars, raw space 2^{len(CHILDREN) * len(SCHOOLS)} = {raw_bool}") print(f"per-child: {len(CHILDREN)} vars, raw space " + " * ".join(str(len(WALK_OK[c])) for c in CHILDREN) + f" = {raw_kid}") naive, _ = model_boolean_naive(limit=1) first = naive[0] assigned = sum(1 for key, v in first.items() if v == 1 and "|" in key) print(f"naive boolean, first accepted assignment: {assigned} of {len(CHILDREN)} children have a school") print(f" -> it calls 'nobody goes to school' a solution: {assigned == 0}") bp, stp = model_boolean_propagated() op, sto = model_one_var_per_child() print(f"propagated boolean -> {len(bp):>4} solutions, {stp['nodes']:>6} value attempts") print(f"one-per-child -> {len(op):>4} solutions, {sto['nodes']:>6} value attempts") set_bool = sorted(tuple(sorted((c, s) for (c, s), v in sol.items() if v == 1)) for sol in bp) set_kid = sorted(tuple(sorted(sol.items())) for sol in op) print(f"identical solution set: {set_bool == set_kid}") print() print("== 4. where the saving actually came from ==") _, q_static = queens(11, select=None, fc=False) _, q_fc = queens(11, select="mrv", fc=True) print(f"11-queens static order : {q_static['nodes']:>8} attempts") print(f"11-queens MRV + forward chk : {q_fc['nodes']:>8} attempts") print(f" forward checking alone {q_static['nodes'] / q_fc['nodes']:.2f}x fewer attempts") _, t_static = timetable(select=None, fc=False) _, t_mrv = timetable(select="mrv", fc=False) print(f"timetable MRV, domains never maintained: {t_mrv['nodes']} vs {t_static['nodes']} attempts") print(f" MRV made it worse: {t_mrv['nodes'] > t_static['nodes']}") print(f"formulation change (boolean -> per-child): " f"{stp['nodes'] / sto['nodes']:.2f}x more attempts to say the same thing") if __name__ == "__main__": main() Real output: == 1. n-queens: one CSP, three ways to search it == n strategy solutions value attempts pruned 8 static order 92 15720 0 8 MRV 92 15720 0 8 MRV + forward checking 92 1360 292 9 static order 352 72378 0 9 MRV 352 72378 0 9 MRV + forward checking 352 5399 1126 10 static order 724 348150 0 10 MRV 724 348150 0 10 MRV + forward checking 724 19744 4992 11 static order 2680 1806706 0 11 MRV 2680 1806706 0 11 MRV + forward checking 2680 85939 21796 == 2. timetable: 5 sessions, unary + binary constraints == model solutions value attempts pruned static order 144 762 0 MRV 144 831 0 MRV + forward checking 144 282 0 == 3. same allocation problem, two formulations == boolean: 24 vars, raw space 2^24 = 16777216 per-child: 6 vars, raw space 2 * 2 * 2 * 2 * 2 * 2 = 64 naive boolean, first accepted assignment: 0 of 6 children have a school -> it calls 'nobody goes to school' a solution: True propagated boolean -> 4 solutions, 2530 value attempts one-per-child -> 4 solutions, 24 value attempts identical solution set: True == 4. where the saving actually came from == 11-queens static order : 1806706 attempts 11-queens MRV + forward chk : 85939 attempts forward checking alone 21.02x fewer attempts timetable MRV, domains never maintained: 831 vs 762 attempts MRV made it worse: True formulation change (boolean -> per-child): 105.42x more attempts to say the same thing What I understood from it: Three things I did not expect. First, MRV alone changed nothing at all . 8 queens with static order: 15,720 attempts. 8 queens with MRV: 15,720. Same for n=9, 10, 11 — the numbers are identical to the digit, because if you never shrink the domains then every unassigned variable has the same size and "minimum remaining values" has no minimum to find; it silently degrades to declaration order. A heuristic that reads domain sizes is only a heuristic if something maintains the domains. Forward checking is what maintains them: 85,939 attempts at n=11 against 1,806,706, 21.02x, with 21,796 branches killed the moment a domain emptied. Second, MRV made the timetable worse — 831 attempts against 762 — and the reason is honest: the only narrow domain was the one the unary constraint created at formulation time, `SE must be in R2 , three values. MRV grabbed exactly that variable, and SE` touches none of the three binary constraints, so taking it first pruned nothing and pushed every real conflict one level deeper. MRV minimises domain size, not constraint impact. With forward checking the same model drops to 282 attempts, 2.7x better than static order, because then the ordering and the propagation finally work on the same information. Third, and this is the one that cost me a rewrite: my first timetable allowed two sessions in the same room at the same time. I had written the three "cannot overlap" pairs and forgotten that a real timetable needs one session per (slot, room). The solver happily returned 864 consistent assignments. Adding that single constraint dropped it to 144 and moved every number in the table below. Nothing about the search changed; the model did. The formulation section is the sharpest version of the same lesson. The boolean encoding — one variable per child–school pair, 24 variables — is the one the slides warn about. With only "at most one school per child" written down, its first accepted assignment put **zero of six children in a school** and called it a solution: absence of a value was never forbidden. Add the missing half of the constraint, force the siblings to zero as soon as one pair is true, and it finds the same 4 solutions as the 6-variable model — for 2,530 value attempts instead of 24. 105.42x to say the same thing, and the difference is entirely in how the variables were cut. ---

Security #33 — Web cache deception: the cache and the app disagree about what a path is (CWE-525)

A web cache decides whether to keep a response by looking at the URL. The application decides what to return by looking at the path and at who is asking. When those two disagree about what a path means, one user's page becomes another user's cache entry. That is cache deception (CWE-525), and it needs no bug in either component: each one is behaving as designed. The app half: many frameworks treat a trailing known extension as decoration and route /account/profile/avatar.css to the account page — a real behaviour, in Rails, Spring, Django with APPEND_SLASH , and in nginx configs that fall back to index.php . The cache half: an extension in .css/.js/.png/.jpg means "static asset", static means shared, and the response gets stored without looking at the Cookie header that produced it. The attack is one request from the victim, and HTML gives that away for free: an <img src="/account/profile/avatar.css"> in a comment, a chat message, a forum post. The browser attaches the session cookie, the app answers 200 with the account page, the cache stores it under a key that contains no identity, and the attacker reads it with a plain GET. The attacker never needs to guess anything, which is the part people get wrong: unauthenticated /account/profile is a 302 with zero bytes. The only request that returns the body is the one served from the cache. Two halves of one disagreement: the origin strips a trailing static extension before routing; the cache treats any static-looking path as shared and stores whatever came back. Those are the two lines I built, and the bug lives in the space between them. The pattern I studied: for ext in STATIC_EXT: # the framework ignores a trailing fake extension if routed.endswith(ext): routed = routed[: -len(ext)] break static = self.path.split("?")[0].endswith(STATIC_EXT) Sandbox check (local only, two servers on 127.0.0.1, data invented): """Day 33 security: web cache deception (CWE-525), reproduced end to end on loopback. Three real processes' worth of truth: an origin app, a shared cache in front of it, and two clients (victim with a session cookie, attacker without one). No external network, no real host, PII is invented. Output is deterministic. """ import http.client import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer ORIGIN_PORT = 18099 CACHE_PORT = 18098 SESSION = "sid=victim-session-8f21" PII_MARK = "victima@example.cl" STATIC_EXT = (".css", ".js", ".png", ".jpg") PROFILE_HTML = ( "<html><body><h1>Account</h1>" "<p>email: " + PII_MARK + "</p>" "<p>plan: student / balance: 41.20 EUR</p></body></html>" ).encode() CSS_V1 = b"body{background:#fff;font:14px Arial}" + b"\x00" * 200 CSS_V2 = b"body{background:#fff;font:16px Georgia}" + b"\x00" * 200 # ---------------------------------------------------------------- origin app class Origin(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, *a): pass def do_GET(self): path = self.path.split("?")[0] routed = path for ext in STATIC_EXT: # the framework ignores a trailing fake extension if routed.endswith(ext): routed = routed[: -len(ext)] break cookie = self.headers.get("Cookie", "") if routed.startswith("/account/profile"): if SESSION in cookie: self._send(200, PROFILE_HTML, "text/html") else: self._send(302, b"", "text/html", extra={"Location": "/login"}) elif routed.startswith("/static/"): v2 = "v=2" in self.path self._send(200, CSS_V2 if v2 else CSS_V1, "text/css", extra={"Cache-Control": "public, max-age=60"}) else: self._send(404, b"not found", "text/plain") def _send(self, code, body, ctype, extra=None): self.send_response(code) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) for k, v in (extra or {}).items(): self.send_header(k, v) self.end_headers() self.wfile.write(body) def do_HEAD(self): self.do_GET() # ---------------------------------------------------------------- shared cache class CacheProxy(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" store = {} mode = "vulnerable" hits = 0 misses = 0 def log_message(self, *a): pass def do_GET(self): cls = CacheProxy key = self.path.split("?")[0] if cls.mode == "vulnerable" else self.path static = self.path.split("?")[0].endswith(STATIC_EXT) cookie = self.headers.get("Cookie", "") if static and cls.mode == "vulnerable" and key in cls.store: status, ctype, body = cls.store[key] cls.hits += 1 return self._reply(status, body, ctype, "HIT") if static and cls.mode == "fixed" and key in cls.store: status, ctype, body = cls.store[key] cls.hits += 1 return self._reply(status, body, ctype, "HIT") conn = http.client.HTTPConnection("127.0.0.1", ORIGIN_PORT, timeout=5) conn.request("GET", self.path, headers={"Cookie": cookie} if cookie else {}) resp = conn.getresponse() body = resp.read() ctype = resp.getheader("Content-Type", "") status = resp.status set_cookie = resp.getheader("Set-Cookie") cc = (resp.getheader("Cache-Control") or "").lower() conn.close() store_it = static and status == 200 if cls.mode == "fixed": # a shared cache may only store when the response is explicitly public, # the request carried no credentials, and nothing sets a cookie store_it = store_it and "public" in cc and not cookie and not set_cookie if store_it: cls.store[key] = (status, ctype, body) cls.misses += 1 return self._reply(status, body, ctype, "MISS") def _reply(self, status, body, ctype, label): self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) self.send_header("X-Cache", label) if status == 302: self.send_header("Location", "/login") self.end_headers() self.wfile.write(body) def serve(handler, port): srv = ThreadingHTTPServer(("127.0.0.1", port), handler) threading.Thread(target=srv.serve_forever, daemon=True).start() return srv def get(path, cookie=None): conn = http.client.HTTPConnection("127.0.0.1", CACHE_PORT, timeout=5) h = {"Cookie": cookie} if cookie else {} conn.request("GET", path, headers=h) r = conn.getresponse() body = r.read() conn.close() return r.status, r.getheader("X-Cache", "-"), body def run(mode): CacheProxy.mode = mode CacheProxy.store = {} CacheProxy.hits = 0 CacheProxy.misses = 0 print(f"--- cache mode: {mode} ---") s, tag, b = get("/account/profile") print(f"attacker GET /account/profile -> {s} {len(b):>4}B cache={tag}") s, tag, b = get("/account/profile/avatar.css", SESSION) print(f"victim GET /account/profile/avatar.css -> {s} {len(b):>4}B cache={tag} (cookie sent)") s, tag, b = get("/account/profile/avatar.css") leak = PII_MARK.encode() in b print(f"attacker GET /account/profile/avatar.css -> {s} {len(b):>4}B cache={tag} " f"contains victim email: {leak}") s1, t1, b1 = get("/static/app.css") s2, t2, b2 = get("/static/app.css") s3, t3, b3 = get("/static/app.css?v=2") print(f"attacker GET /static/app.css -> {s1} {len(b1):>4}B cache={t1}") print(f"attacker GET /static/app.css (again) -> {s2} {len(b2):>4}B cache={t2}") print(f"attacker GET /static/app.css?v=2 -> {s3} {len(b3):>4}B cache={t3} " f"served v1 bytes: {b3 == b1}") return leak, CacheProxy.hits, CacheProxy.misses def main(): serve(Origin, ORIGIN_PORT) serve(CacheProxy, CACHE_PORT) print("origin :18099 cache :18098 (loopback only)") print(f"static bytes v1={len(CSS_V1)} v2={len(CSS_V2)} profile bytes={len(PROFILE_HTML)}") print() leak_vuln, hits_v, misses_v = run("vulnerable") print() leak_fix, hits_f, misses_f = run("fixed") print() print(f"deception holds: {leak_vuln} after fix: {leak_fix}") print(f"cache still useful after fix: static hits {hits_f} > 0 -> {hits_f > 0}") print(f"distinct stored objects: vulnerable {misses_v}, fixed {misses_f}") if __name__ == "__main__": main() Real output: origin :18099 cache :18098 (loopback only) static bytes v1=237 v2=239 profile bytes=115 --- cache mode: vulnerable --- attacker GET /account/profile -> 302 0B cache=MISS victim GET /account/profile/avatar.css -> 200 115B cache=MISS (cookie sent) attacker GET /account/profile/avatar.css -> 200 115B cache=HIT contains victim email: True attacker GET /static/app.css -> 200 237B cache=MISS attacker GET /static/app.css (again) -> 200 237B cache=HIT attacker GET /static/app.css?v=2 -> 200 237B cache=HIT served v1 bytes: True --- cache mode: fixed --- attacker GET /account/profile -> 302 0B cache=MISS victim GET /account/profile/avatar.css -> 200 115B cache=MISS (cookie sent) attacker GET /account/profile/avatar.css -> 302 0B cache=MISS contains victim email: False attacker GET /static/app.css -> 200 237B cache=MISS attacker GET /static/app.css (again) -> 200 237B cache=HIT attacker GET /static/app.css?v=2 -> 200 239B cache=MISS served v1 bytes: False deception holds: True after fix: False cache still useful after fix: static hits 1 > 0 -> True distinct stored objects: vulnerable 2, fixed 2 What I understood about preventing it: store_it = static and status == 200 if cls.mode == "fixed": store_it = store_it and "public" in cc and not cookie and not set_cookie What I understood: The fix is not "cache less". It is making the cache store only what the origin explicitly declares public, and only for requests that carried no credentials. Two rules, both from the response and the request, not from the URL string:

do not store if the request had a Cookie (or Authorization ) header — a shared cache cannot

represent "for this user only";

do not store if the response sets a cookie, and require an explicit Cache-Control: public (or

s-maxage ) instead of inferring cacheability from the extension;

key on the full request URI, including the query string, because "the query does not matter" is a

guess that shows up as ?v=2 returning the v=1 bytes. Vary: Cookie is not the fix. A shared cache keyed per cookie has one entry per user, which is a private cache with extra steps and a fresh way to fill the disk. Measured on loopback with invented data: the deception takes 2 requests and 115 bytes, and after the fix the attacker's request is a 302 with 0 bytes while a legitimate static asset still hits the cache. Limits, honestly: my cache is forty lines I wrote in an afternoon; real CDNs normalise, vary on more headers and have their own rules. What I measured is the class of defect — the app and the cache disagreeing about what a path is — not any deployed product, and nothing left 127.0.0.1. ---

Day 33 notes

Concept #33: code ran, output above — 1,806,706 attempts cut to 85,939, and the model worth 105.42x. ✔ Security #33: cache deception reproduced on loopback only, then closed; attacker reads 0 bytes after the fix. ✔ Two corrections during the day: the timetable was missing the room constraint (864 fake solutions), and MRV turned out to be a no-op without domain maintenance. ✔ 1567 days left. One at a time.

Written by my own daily machine, checked by me.

← Back to the index

· Day 033 of 1600 · Matías Rathgeb


[ inicio ]   [ proyectos ]   [ posts ]   [ daylog ]


Página estática. Sin cookies, sin javascript, sin fuentes externas.
Contacto: ver inicio.