Última actualización: 2026-12-02

DAY 031 OF 1600 · 2026-11-06

Day 031 — Hill climbing was right twice in thirty, and the temperature was never a knob

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

Concept #31 — In local search the landscape is something you design, not something you find

MA08, Intelligent Search, week 2. Week 1 was path search: a frontier, a goal test, a path. Week 2 removes the path entirely. There is no goal state to reach, there is a **candidate solution and an objective**, and the question becomes "can I make this number bigger". The pseudocode is four fields — State , Objective(s) , Neighbors(s) , InitialState() — and the lecture is blunt about which two matter: the objective and the neighbourhood are modelling choices , not algorithm settings. Two teams can run the same hill climber on the same floor and get different answers because one of them defined "neighbour" differently. That sentence sounds like philosophy until you run it. So I built the week-2 scaffold properly: a weighted floor plan (8×10, seven wall cells, 73 free cells), four Wi-Fi routers placed on free cells, coverage by Manhattan distance ≤ 2. Objective = total weighted demand covered, minus half of the demand that gets covered twice . That second term is the whole design decision. Without it the objective is a plain maximum-coverage problem and my first run had hill climbing hit the exact optimum 16 times out of 20 — a flat, easy landscape that teaches nothing. Adding the waste penalty makes routers compete for the same cells, and the landscape gets ridges. Then the reference. I brute-forced all 1,088,430 placements of four routers over 73 free cells with the exact objective, so every gap I report below is measured against the true optimum, not against "the best I happened to find". That is the part people skip, and it is the only reason the rest of the numbers mean anything. What I tried today: one file, stdlib only. Bitmask objective (so 1.09M placements run in about eight seconds), steepest-ascent hill climbing over the complete one-router neighbourhood, random restarts, simulated annealing with a geometric schedule, and a sweep of the starting temperature across eight orders of magnitude with ten seeds per row. #!/usr/bin/env python3 """MA08 Intelligent Search, week 2. Local search and optimisation. One idea: the objective and the neighbourhood are modelling choices, and the temperature is a number in the units of the objective -- not a magic knob. Router placement on a weighted floor plan. stdlib only. No network. """ import itertools import math import random H, W = 8, 10 RADIUS = 2 K = 4 WASTE = 0.5 # a cell covered twice is paid once, not twice WALLS = frozenset({(1, 4), (2, 4), (3, 4), (4, 7), (5, 7), (6, 2), (6, 3)}) def build_floor(): weights = {} for r in range(H): for c in range(W): if (r, c) in WALLS: continue w = 1.0 if 2 <= r <= 4 and 1 <= c <= 3: w = 2.5 if 1 <= r <= 2 and 7 <= c <= 8: w = 2.0 if r == 6 and c >= 6: w = 1.8 weights[(r, c)] = w return weights WEIGHTS = build_floor() FREE = sorted(WEIGHTS) INDEX = {p: i for i, p in enumerate(FREE)} MASK = {p: sum(1 << INDEX[q] for q in FREE if abs(p[0] - q[0]) + abs(p[1] - q[1]) <= RADIUS) for p in FREE} SELF = {p: WEIGHTS[p] for p in FREE} _WCACHE = {0: 0.0} def weight_of(mask): """Weighted demand covered by a bitmask of cells, memoised.""" v = _WCACHE.get(mask) if v is None: v = 0.0 m = mask while m: b = m & -m v += WEIGHTS[FREE[b.bit_length() - 1]] m ^= b _WCACHE[mask] = v return v def score(routers): """Coverage minus the waste of covering the same cell twice. sum over cells: w*(covered) - WASTE*w*(layers-1) = sum_r weight(mask_r) - WASTE*(sum_r weight(mask_r) - weight(union)) """ union = 0 own = 0.0 for rt in routers: union |= MASK[rt] own += weight_of(MASK[rt]) return weight_of(union) - WASTE * (own - weight_of(union)) def all_moves(routers): occupied = set(routers) out = [] for i in range(len(routers)): rest = occupied - {routers[i]} for c in FREE: if c in rest: continue cand = list(routers) cand[i] = c out.append(tuple(cand)) return out def random_move(routers, rng): occupied = set(routers) while True: i = rng.randrange(len(routers)) rest = occupied - {routers[i]} c = FREE[rng.randrange(len(FREE))] if c not in rest: cand = list(routers) cand[i] = c return tuple(cand) def steepest_ascent(start, cnt): cur = start f = cnt.score(cur) while True: best, best_f = None, f for nb in all_moves(cur): v = cnt.score(nb) if v > best_f: best, best_f = nb, v if best is None: return cur, f cur, f = best, best_f def anneal(start, t0, proposals, rng, cnt, alpha=0.9995): cur = start f = cnt.score(cur) best, best_f = cur, f t = t0 worse_offered = worse_taken = 0 for _ in range(proposals): nb = random_move(cur, rng) v = cnt.score(nb) d = v - f if d >= 0: cur, f = nb, v if f > best_f: best, best_f = nb, f else: worse_offered += 1 if t > 0 and rng.random() < math.exp(d / t): cur, f = nb, v worse_taken += 1 t *= alpha return best, best_f, worse_offered, worse_taken class Counter: def __init__(self): self.n = 0 def score(self, routers): self.n += 1 return score(routers) def main(): print("== 0. the instance") print(f" floor {H}x{W}, {len(WALLS)} walls, {len(FREE)} free cells, " f"{K} routers, radius {RADIUS} (manhattan)") print(f" objective: weighted demand covered, minus {WASTE} x the demand " f"covered twice") print(f" total weighted demand: {sum(WEIGHTS.values()):.1f}") opt_f, opt_p, n_combos = -1.0, None, 0 for p in itertools.combinations(FREE, K): n_combos += 1 v = score(p) if v > opt_f: opt_f, opt_p = v, p print(f" exact optimum over all {n_combos} placements: {opt_f:.2f} " f"at {[list(x) for x in opt_p]}") print() rng = random.Random(20261106) starts = [tuple(rng.sample(FREE, K)) for _ in range(30)] hc_vals, hc_evals = [], [] for s in starts: cnt = Counter() _, v = steepest_ascent(s, cnt) hc_vals.append(v) hc_evals.append(cnt.n) at_opt = sum(1 for v in hc_vals if abs(v - opt_f) < 1e-9) gaps = sorted(opt_f - v for v in hc_vals) print("== 1. steepest-ascent hill climbing, 30 fixed starts") print(f" reached the exact optimum : {at_opt}/30") print(f" mean value : {sum(hc_vals)/len(hc_vals):.2f}") print(f" worst run : {min(hc_vals):.2f} " f"({opt_f - min(hc_vals):.2f} short of the optimum)") print(f" median gap to optimum : {gaps[len(gaps)//2]:.2f}") print(f" evaluations per run : mean {sum(hc_evals)/len(hc_evals):.0f}, " f"max {max(hc_evals)}") print() rr_best, rr_total, rr_opt = -1.0, 0, 0 for s in starts: cnt = Counter() _, v = steepest_ascent(s, cnt) rr_total += cnt.n rr_best = max(rr_best, v) print("== 2. the same hill climbing, 30 restarts, keep the best") print(f" best over 30 restarts : {rr_best:.2f} (optimum {opt_f:.2f})") print(f" restarts that found it : {at_opt}/30") print(f" total evaluations spent : {rr_total}") print() print("== 3. simulated annealing, 4000 random proposals, 10 seeds per row") print(f" {'T0':>6} {'best':>6} {'mean':>6} {'at optimum':>10} " f"{'worse moves accepted':>20}") seed_rng = random.Random(11) rows = [] for t0 in (0.0, 0.05, 0.2, 0.5, 1.0, 2.0, 5.0, 20.0): vals, off, taken = [], 0, 0 for _ in range(10): s = tuple(seed_rng.sample(FREE, K)) cnt = Counter() _, v, wo, wt = anneal(s, t0, 4000, random.Random(seed_rng.randrange(10 ** 9)), cnt) vals.append(v) off += wo taken += wt hits = sum(1 for v in vals if abs(v - opt_f) < 1e-9) rate = (taken / off) if off else 0.0 rows.append((t0, max(vals), sum(vals) / len(vals), hits, rate)) print(f" {t0:6.2f} {max(vals):6.2f} {sum(vals)/len(vals):6.2f} " f"{hits:6d}/10 {rate:17.1%}") best_row = max(rows, key=lambda r: (r[2], r[3])) print(f" best T0 on mean value : {best_row[0]:.2f} " f"(mean {best_row[2]:.2f}, {best_row[3]}/10 runs hit the optimum)") print() drng = random.Random(5) deltas = [] for _ in range(20000): p = tuple(drng.sample(FREE, K)) q = random_move(p, drng) deltas.append(abs(score(q) - score(p))) mean_d = sum(deltas) / len(deltas) print("== 4. what a temperature is measured in") print(f" mean |delta| of a random move : {mean_d:.3f} points") print(f" max |delta| of a random move : {max(deltas):.1f} points") print(f" T that accepts a move 1 mean-step worse: {mean_d:.3f} " f"(that is where e^-1 = {math.exp(-1):.3f} lives)") print(f" best measured T0 / mean |delta| : {best_row[0]/mean_d:.2f}") if __name__ == "__main__": main() Real output: == 0. the instance floor 8x10, 7 walls, 73 free cells, 4 routers, radius 2 (manhattan) objective: weighted demand covered, minus 0.5 x the demand covered twice total weighted demand: 93.7 exact optimum over all 1088430 placements: 65.70 at [[1, 7], [2, 1], [4, 4], [6, 7]] == 1. steepest-ascent hill climbing, 30 fixed starts reached the exact optimum : 2/30 mean value : 63.94 worst run : 61.40 (4.30 short of the optimum) median gap to optimum : 1.50 evaluations per run : mean 1214, max 1681 == 2. the same hill climbing, 30 restarts, keep the best best over 30 restarts : 65.70 (optimum 65.70) restarts that found it : 2/30 total evaluations spent : 36430 == 3. simulated annealing, 4000 random proposals, 10 seeds per row T0 best mean at optimum worse moves accepted 0.00 65.70 64.24 2/10 0.0% 0.05 65.70 64.64 2/10 0.0% 0.20 65.20 64.41 0/10 0.0% 0.50 65.70 64.60 1/10 0.1% 1.00 65.70 64.56 1/10 0.5% 2.00 65.70 64.96 3/10 1.5% 5.00 65.70 65.35 6/10 8.0% 20.00 65.70 64.30 1/10 38.7% best T0 on mean value : 5.00 (mean 65.35, 6/10 runs hit the optimum) == 4. what a temperature is measured in mean |delta| of a random move : 6.798 points max |delta| of a random move : 33.0 points T that accepts a move 1 mean-step worse: 6.798 (that is where e^-1 = 0.368 lives) best measured T0 / mean |delta| : 0.74 What I understood from it: two numbers do all the talking. 2 out of 30. Steepest ascent over the complete neighbourhood — the expensive, thorough version, mean 1,214 objective evaluations per run — found the exact optimum twice. The worst start stopped at 61.40 , which is 4.30 below a 65.70 optimum, and it stopped there because every single one of the 276 neighbours was worse . That is what a local optimum is: not a bug, not a bad implementation, a correct answer to the wrong question. The median run was only 1.50 short, so most of the damage is small and easy to call "fine". This is the number I will quote in the report of every project that reports "our optimiser converged". Restarts are the dumbest fix that works , and the measurement says how dumb: 30 restarts, 36,430 evaluations, best 65.70. It worked. It also means the basin of attraction of the optimum caught roughly 7% of random starts, so anything resembling a guarantee would need dozens of starts, and 36k evaluations for a four-router floor is not free. Then the temperature, which is where I was wrong. I assumed T was a knob you tune by feel, and the sweep shows it is a scale : the mean absolute change of one random move on this objective is 6.798 points , and the useful band sat at T0 = 2…5 , i.e. **0.29 to 0.74 mean |Δ|**. Pick T0 = 0.20 (3% of one step) and the run behaves like hill climbing — the acceptance of worse moves is 0.0%, mean 64.41. Pick T0 = 20 (three mean steps) and 38.7% of worse moves get taken, the walk is nearly random, and the mean comes back to 64.30 — statistically the same as T0 = 0 at 64.24, so all that heat bought nothing at all. At T0 = 5 it accepted 8.0% of worse moves and hit the optimum in 6 of 10 runs, a mean of 65.35 against hill climbing's 63.94 — without any restart, on 4,000 proposals. The honest caveats, since I would rather write them than have them found: 4,000 proposals is more than the ~1,214 evaluations a hill climb spends, so this is not an equal-budget comparison; and ten seeds per row is a small sample, which is why the 0.20 row looks out of place (0/10 at the optimum, mean 64.41 — sampling noise, not a mechanism). The sentence I keep from today: **the landscape is not a property of the problem, it is a property of the objective and the neighbourhood you chose** — the first version of my objective had no waste penalty and hill climbing solved it 16 times out of 20. I did not change the algorithm between those two runs. I changed one term in the objective and moved the difficulty of the problem from "trivial" to "hill climbing is right 7% of the time". ---

Security #31 — The check was one byte short, and the field behind it paid (CWE-193)

Different class today, and the first one in this log that lives below the application layer: a length check off by exactly one, in the direction that lets a NUL terminator land one byte past its buffer. The shape is always the same. A fixed-size name field. A check written against the content length but not against the terminator : if (n > sizeof(name)) return -1; /* 8 characters pass */ Eight characters fit exactly, so the check says yes — and then the code writes name[n] = '\0' , which is name[8] , one past a char[8] . The byte is written, nothing crashes, no warning at -O0 , and the test suite is happy because the string is still readable. What actually changes is the neighbour: whatever the compiler placed immediately after the array. In C that is not a detail you get to choose at review time. The pattern I studied: static int store_buggy(void *rec, size_t cap, const char *user) { size_t n = strlen(user); char *dst = (char *)rec; if (n > cap) /* should be >= : the terminator needs a slot */ return -1; memcpy(dst, user, n); dst[n] = '\0'; /* one past the array when n == cap */ return (int)n; } What I understood about preventing it: if (n >= cap) /* one slot is reserved for the terminator */ return -1; memcpy(dst, user, n); dst[n] = '\0'; Sandbox check (local only): == layout, measured, not assumed sizeof(acct_perms) 9 offsetof(name) 0 offsetof(perms) 8 sizeof(acct_id) 16 offsetof(name) 0 offsetof(record_id) 8 == 1. same bug, two neighbours, two different consequences name "admin518" (8 chars) -> store returned 8 name bytes: admin518 (no terminator inside the array) perms 0x05 -> 0x00 same call, neighbour is a uint64 id: record_id 0x000000000000002a -> 0x0000000000000000 == 2. the window is exactly one length 9 chars -> store returned -1, perms still 0x05 == 3. the fix is one character 8 chars, fixed check -> store returned -1, perms 0x05 6 chars, fixed check -> store returned 6, name "matias", perms 0x05 == 4. the sanitizer, on a bare buffer (addresses redacted) ERROR: AddressSanitizer: stack-buffer-overflow on address 0x... at pc 0x... bp 0x... sp 0x... WRITE of size 1 at 0x... thread T0 SUMMARY: AddressSanitizer: stack-buffer-overflow asan.c:14 in store_buggy What I understood: the number that matters is not the size of the overflow, it is **which byte it is**. One byte, value 0x00 , position fixed by the ABI — and the measured layout says offsetof(perms) = 8 and offsetof(record_id) = 8 , so in both structs the write lands on the first byte of the next field . In the first struct that is the permission bitmask: 0x05 (read + write) became 0x00 , silently, on an 8-character name. In the second struct the same call zeroed the low byte of a 64-bit record id, 0x2a → 0x00 , which is a different bug entirely — a lookup collision — from the same source line. Same code, same input, blast radius decided by struct layout. That is why "it's only one byte" is not an argument: the attacker does not choose the byte; the compiler does, and the compiler is not on your side. The second measured fact is that the window is exactly one length : nine characters were correctly rejected, eight were accepted, and the fixed check ( >= , literally one character) rejects eight. There is no exploitability spectrum here; it is a boundary that is either on the right side or off by one, and everything else is consequences. The third thing, and the reason I ran the sanitizer: against a bare char buf[8] the byte past the end belongs to nobody, and only then does anything complain — stack-buffer-overflow, WRITE of size 1 . Inside a struct, the identical write is *architecturally legal*, so ASAN stays quiet and -Warray-bounds only fires when the compiler can see the constant at -O2 . Which means: a clean sanitizer run is evidence about objects, not about fields. For this class the only reliable defence is the invariant at the boundary — "capacity counts bytes including the terminator" — plus a struct design that does not put a security-relevant byte next to a character array, because the day it is one byte off, it will be that byte. ---

Day 31 notes

Concept #31: MA08 week 2, local search. 8×10 floor, 73 free cells, 4 routers, waste penalty

0.5. Exact optimum by brute force over 1,088,430 placements: 65.70. Steepest ascent on 30 starts: 2/30 at the optimum, mean 63.94, worst 61.40 (−4.30), ~1,214 evaluations per run. 30 restarts: optimum found. Simulated annealing best at T0 = 5 → mean 65.35 , 6/10 at the optimum, 8.0% of worse moves accepted; T0 = 20 → 38.7% accepted, mean 64.30; T0 = 0.20 → 0.0% accepted, behaves like hill climbing. Mean |Δ| of a move = 6.798 , so the useful band was 0.29–0.74 × mean |Δ|. ✔

Security #31: off-by-one NUL write (CWE-193). if (n > cap) accepts exactly cap

characters, then dst[n] = '\0' writes one past. Measured offsetof = 8 in both structs: perms 0x05 → 0x00 , record id 0x2a → 0x00 . Nine characters rejected, eight accepted, fix is >= . ASAN only named it on a bare buffer. Sandbox /tmp , no network, no targets. ✔

1569 days left. One at a time.

Written by my own daily machine, checked by me.

← Back to the index

· Day 031 of 1600 · Matías Rathgeb


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


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