harness.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  1. #!/usr/bin/env python3
  2. """The web-stack test harness (plan 16 R5, arch 18): everything the
  3. scenario bundles share, plus the parallel runner.
  4. Layout: test/harness.py (this file — the FakeSaddle daemon, the
  5. http/act/login/slot_public wire helpers, wait_for/quiet_window/db/check,
  6. the per-shard fixtures via start_bundle/Ctx, and run_bundle +
  7. run_all_parallel); test/bundles/<name>.py (one module per bundle, its
  8. run(ctx) driving that shard's scenarios); test/web_stack_test.py (the
  9. thin entry shim meson invokes; it also stays directly runnable for the
  10. per-bundle shard processes the parallel runner spawns).
  11. Unlike integration_test.py (which needs a real saddle daemon and a mock
  12. LLM), this suite spawns everything it needs:
  13. - the clanker-saddle app binary (path from argv[1], or builddir default)
  14. in a scratch directory with its own web-config.json (statum keys copied
  15. from the repo, plus `saddle_callback_base_url`) and SQLite database
  16. - in-process fake saddle daemons speaking the wire contract: POST
  17. /register (plan 10: receives {saddle_token, web_base_url}, answers
  18. {ok, ssh_public_key, version}), POST /wake (records the wake; the
  19. daemon then asks POST /api/saddle/next-task), POST /task-update
  20. (cancel/comment/subtask-status), GET /status (scripted reflection —
  21. exceptional use only), and the phase-2 push channels home:
  22. POST /api/saddle/chunks (raw PTY batches) and POST /api/saddle/results
  23. (round entries + state transitions). The retired /start, /output and
  24. /log routes 404 like a post-phase-2 daemon.
  25. It then drives the app the way statum.js does (entrypoint loads + action
  26. POSTs) and asserts the Workstream B features against the wire contract:
  27. 3. plan-review blocks hide their duplicate body preview
  28. 5. rules CRUD/attach + the effective `rules` array in assignments
  29. 6. project notes, POST /api/saddle/note, `project_notes` + `callback`
  30. in assignments
  31. plus the raw-log side: pushed chunks -> session_raw_log + terminal
  32. raw view
  33. Plan 10 phase 1 (work acquisition flip):
  34. - per-saddle tokens: registration mints + /register-delivers them,
  35. the row is the single credential store (the api_tokens fallback
  36. died with arch 24), removal revokes
  37. - token auth on every /api/saddle/* endpoint
  38. - next-task allocation: concurrent asks race exactly one winner,
  39. affinity pinning for parked tasks, resume_notice on suspended resumes
  40. - dispatcher: wake -> ask -> allocate roundtrip, the lost-wake guard
  41. (no ask after a wake -> offline, re-wake the next capable), and the
  42. pre-flip /answer + /start resume paths kept as the rollback route
  43. Plan 10 phase 2 (telemetry flip):
  44. - pushed chunks: idempotent on (session_id, seq), ordered, landing in
  45. session_raw_log so the SSE terminal keeps working
  46. - pushed results: entries store like the /output path did (redelivery
  47. idempotent on the daemon entry ids), blocked raises the block row +
  48. parks + bumps the pulse (sealed refresh shows it), done/failed
  49. complete/fail the task, suspended parks for the affinity resume
  50. - answer resumes, both daemon shapes: a SLEEPING affine saddle (its
  51. post-park ask returned 204) is woken, its ask allocating the resume
  52. with the verdict riding the assignment; a daemon parked MID-ROUND
  53. (its round holds the block's answer wait open, so it can never ask)
  54. gets the verdict delivered into that wait via POST /answer — same
  55. session, no wake. A daemon dying with a parked-with-answered task
  56. never requeues it: the verdict and session survive for the resume
  57. - staleness: a silent runner gets ONE exceptional GET /status probe —
  58. alive keeps it running, dead requeues the task with an agent comment and
  59. marks the saddle offline; a recovered daemon's ask flips offline rows
  60. back to idle
  61. - the deleted layers are gone: /output, /log and /start 404 on the
  62. daemon side, and nothing on the web side calls them
  63. Plan 10 phase 3 (capability awareness + UI):
  64. - assignment capability context: {saddle_tags, fleet_tags} on every
  65. payload, GET /api/saddle/capabilities (per-saddle token) feeding
  66. the daemon's `saddle capabilities` CLI
  67. - subtask callback capabilities: explicit-only attachment validated
  68. against the operator tag set, unknown tags rejected with the valid
  69. list in the error
  70. - task page: status block pinned to the top, blocking sections
  71. newest-first (sealed GET state)
  72. - home dashboard: pinned OPEN blocks as newest-first link-through
  73. cards (no inline answer forms) above the cross-task activity
  74. timeline (last ~50 events newest-first)
  75. - lost-wake-guard regression: a saddle that asks SLOWLY after its
  76. wake (busy winding down) still claims the task — the wake is never
  77. silently dropped, no re-wake storm fires, and the never-asks guard
  78. path (offline + re-wake of the next capable) stays green
  79. Prints PASS/FAIL lines Statum-style; exits non-zero on any failure.
  80. Plan 11 task D+E (UI + notifications), the `push` shard:
  81. - task page: progress feed above the status card, status + description
  82. in a 50/50 grid, edit expander under the history expander, plan
  83. behind an expander, answered blocks behind an expander; queue screen:
  84. New Task expander above the filters; dashboard waiting-on-drafts
  85. block with links to where Enqueue lives (pages shard)
  86. - real Web Push over VAPID: keypair generated at startup into
  87. web-config.json, GET /sw.js service worker with click-through,
  88. subscribe/unsubscribe + per-task Notify me actions, block events and
  89. waiting-on-drafts pushed globally, first start/failure/completion to
  90. opted-in users, best-effort queue with dispatcher-tick retry, 410/404
  91. endpoint pruning — payloads verified protocol-level (RFC 8291
  92. decryption + ES256 JWT signature) because the harness owns the
  93. browser-side keys
  94. Heredoc completion reports (pages shard):
  95. - terminal tasks render tasks.summary (set by done/fail) as a
  96. markdown completion-report card below the status/description grid —
  97. "Completion report" when done, "Failure summary" when failed, no
  98. card when empty; the summary renders through the shipped
  99. stm-markdown renderer (headings/code, no syntax leaks, HTML
  100. escaped) and the dashboard timeline snippets its first line
  101. Speed pass (plan 11, task 0):
  102. - SHARDING: the scenario groups are partitioned into seven independent
  103. bundles (pages, dispatch, subtasks, lineage, allocation, lifecycle,
  104. answers), each running in its own process against its own app
  105. instance, fake daemons and SQLite database. The default invocation
  106. runs all bundles in parallel and aggregates the verdicts and check
  107. counts into one exit code — meson sees a single green/red test.
  108. `--bundle NAME` runs one shard for debugging; WEBSTACK_SEQUENTIAL=1
  109. runs them in-process, one after another.
  110. - Within a bundle, scenario groups SHARE the app+daemon instance and
  111. carry per-group state as database rows (task/session/block
  112. fixtures), never process restarts; the one deliberate restart (the
  113. startup token migration) lives in the answers bundle.
  114. - EVENT-DRIVEN WAITS: wait_for polls at 50ms; the fixed sleeps were
  115. converted either to observable-condition waits (daemon-side
  116. counters, e.g. failed-delivery hits) or to quiet_window() — a
  117. bounded negative-assertion poll that FAILS LOUDLY the moment the
  118. event it guards against happens (a sleep could silently pass).
  119. - ENV KNOBS: SADDLE_DISPATCH_TICK_S=1 (dispatcher cadence; default 5
  120. in production), SADDLE_HTTP_TIMEOUT_S=2, SADDLE_LOST_WAKE_S=2,
  121. SADDLE_STALE_S=3, plus the fake daemon's scripted timings — the
  122. wire-traffic shapes stay realistic, just faster.
  123. """
  124. import json
  125. import os
  126. import re
  127. import shutil
  128. import socket
  129. import sqlite3
  130. import subprocess
  131. import sys
  132. import threading
  133. import time
  134. import urllib.error
  135. import urllib.parse
  136. import urllib.request
  137. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  138. # Web Push protocol verification (plan 11 task E): the test harness
  139. # owns the browser-side keys, so it can do everything the push service
  140. # does — decrypt the RFC 8291 body and verify the ES256 VAPID JWT.
  141. import base64
  142. from cryptography.hazmat.primitives import hashes
  143. from cryptography.hazmat.primitives.asymmetric import ec
  144. from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
  145. from cryptography.hazmat.primitives.ciphers.aead import AESGCM
  146. from cryptography.hazmat.primitives.kdf.hkdf import HKDF
  147. from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
  148. REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  149. APP = os.path.abspath(sys.argv[1]) if len(sys.argv) > 1 else os.path.join(REPO, "builddir", "clanker-saddle")
  150. # --- speed-pass tuning -----------------------------------------------------
  151. # The fake daemon's scripted timings and the dispatch-tick cadence the
  152. # quiet windows are sized against. All overridable for debugging.
  153. TICK_S = float(os.environ.get("SADDLE_DISPATCH_TICK_S", "1") or 1)
  154. FAKE_WORK_S = float(os.environ.get("WEBSTACK_FAKE_WORK_S", "1.2") or 1.2)
  155. FAKE_FAIL_S = float(os.environ.get("WEBSTACK_FAKE_FAIL_S", "0.5") or 0.5)
  156. FAKE_HEARTBEAT_S = float(os.environ.get("WEBSTACK_FAKE_HEARTBEAT_S", "0.4") or 0.4)
  157. FAKE_TRIGGER_S = float(os.environ.get("WEBSTACK_FAKE_TRIGGER_S", "0.05") or 0.05)
  158. SHARD_TIMEOUT_S = float(os.environ.get("WEBSTACK_SHARD_TIMEOUT_S", "600") or 600)
  159. def quiet_seconds():
  160. """A negative-assertion window spanning several dispatch ticks (the
  161. converted fixed sleeps were 3-7s at the old 5s tick; the bound never
  162. exceeds the old timeout)."""
  163. return min(2 * TICK_S + 0.8, 7.0)
  164. WORK = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  165. DB_PATH = os.path.join(WORK, "web.sqlite")
  166. passes = 0
  167. failures = 0
  168. # The current shard's fixture context (goal_state reads its auth — the
  169. # restart scenarios re-login and re-point ctx.auth mid-run)
  170. CTX = None
  171. def check(condition, label):
  172. global passes, failures
  173. if condition:
  174. passes += 1
  175. print("PASS %s" % label)
  176. else:
  177. failures += 1
  178. print("FAIL %s" % label)
  179. def free_port():
  180. with socket.socket() as sock:
  181. sock.bind(("127.0.0.1", 0))
  182. return sock.getsockname()[1]
  183. APP_PORT = free_port()
  184. DAEMON_PORT = free_port()
  185. WEB = "http://127.0.0.1:%d" % APP_PORT
  186. def bundle_env(name):
  187. """Point the module's runtime globals at one shard's scratch dir,
  188. database and ports (each bundle is a process with its own app,
  189. daemons and SQLite file)."""
  190. global WORK, DB_PATH, APP_PORT, DAEMON_PORT, WEB
  191. base = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  192. WORK = "%s-%s" % (base, name)
  193. DB_PATH = os.path.join(WORK, "web.sqlite")
  194. APP_PORT = free_port()
  195. DAEMON_PORT = free_port()
  196. WEB = "http://127.0.0.1:%d" % APP_PORT
  197. def http(method, url, data=None, headers=None, timeout=30):
  198. body = None
  199. if data is not None:
  200. pairs = []
  201. for k, v in data.items():
  202. for item in (v if isinstance(v, (list, tuple)) else [v]):
  203. pairs.append((k, item))
  204. body = "&".join("%s=%s" % (k, urllib.parse.quote(str(item))) for k, item in pairs).encode()
  205. request = urllib.request.Request(WEB + url if url.startswith("/") else url,
  206. data=body, method=method)
  207. if data is not None:
  208. request.add_header("Content-Type", "application/x-www-form-urlencoded")
  209. for key, value in (headers or {}).items():
  210. request.add_header(key, value)
  211. # Retry dropped/refused connections: the freshly started app can
  212. # close a very early keep-alive connection once while warming up,
  213. # and its first seconds can wobble under load.
  214. for attempt in range(3):
  215. try:
  216. with urllib.request.urlopen(request, timeout=timeout) as response:
  217. return response.status, response.read().decode()
  218. except urllib.error.HTTPError as error:
  219. return error.code, error.read().decode()
  220. except (urllib.error.URLError, OSError):
  221. if attempt >= 2:
  222. raise
  223. time.sleep(0.75)
  224. def directives(uri, auth=None):
  225. headers = {}
  226. if auth:
  227. headers["X-Statum-Slot"] = "key=%s; as_at=%s" % (auth["key"], auth["as_at"])
  228. status, body = http("GET", "/_statum/entrypoint?uri=" + urllib.parse.quote(uri.split("?")[0]),
  229. headers=headers)
  230. if status != 200:
  231. raise SystemExit("entrypoint %s -> HTTP %d: %s" % (uri, status, body[:300]))
  232. return json.loads(body)
  233. def slot_public(auth, uri, type_name):
  234. for directive in directives(uri, auth):
  235. if directive["type"] == "set":
  236. content = directive["snapshot_frame"].get("content")
  237. if not content:
  238. continue
  239. content = json.loads(content)
  240. if content["slot"]["type"] == type_name:
  241. return content["public"]
  242. raise SystemExit("no %s slot in entrypoint state for %s" % (type_name, uri))
  243. def act(auth, action, fields):
  244. headers = {"X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])}
  245. if action.get("private"):
  246. headers["X-Statum-Private"] = action["private"]
  247. status, body = http(action.get("method", "POST"), action["uri"], fields, headers)
  248. if status != 200:
  249. raise SystemExit("action %s -> HTTP %d: %s" % (action["uri"], status, body[:300]))
  250. return json.loads(body)
  251. def login(username, password):
  252. frames = directives("/login")
  253. content = json.loads(frames[0]["snapshot_frame"]["content"])
  254. action = content["public"]["login"]
  255. status, body = http(action.get("method", "POST"), action["uri"],
  256. {"username": username, "password": password})
  257. if status != 200:
  258. raise SystemExit("login -> HTTP %d: %s" % (status, body[:300]))
  259. for directive in json.loads(body):
  260. if directive["type"] == "set":
  261. frame = json.loads(directive["snapshot_frame"]["content"])
  262. if frame["slot"]["type"] == "auth":
  263. return {"key": frame["slot"]["key"], "as_at": frame["as_at"]}
  264. raise SystemExit("login response carried no auth slot: " + body[:300])
  265. def wait_for(predicate, timeout=60, what="condition", interval=0.05):
  266. deadline = time.monotonic() + timeout
  267. last = None
  268. while time.monotonic() < deadline:
  269. last = predicate()
  270. if last is not False and last is not None:
  271. return last
  272. time.sleep(interval)
  273. print(" (timeout waiting for %s; last: %s)" % (what, last))
  274. dump_threads()
  275. return None
  276. def quiet_window(seconds, predicate, what):
  277. """A converted fixed sleep: asserts a NEGATIVE condition (nothing may
  278. happen) across a window spanning several dispatch ticks, polling at
  279. 50ms. The moment the condition breaks the window fails loudly
  280. (diagnostics + thread dump) instead of silently passing a sleep."""
  281. deadline = time.monotonic() + seconds
  282. while time.monotonic() < deadline:
  283. value = predicate()
  284. if value is False or value is None:
  285. remaining = deadline - time.monotonic()
  286. print(" (quiet window '%s' broken after %.2fs of %.2fs — the"
  287. " guarded event DID happen)" % (what, seconds - remaining, seconds))
  288. dump_threads()
  289. return False
  290. time.sleep(0.05)
  291. return True
  292. def dump_threads():
  293. """Stacks of suite threads not parked in sleep — pinpoints a wedged
  294. fake lifecycle when a wait times out."""
  295. import traceback
  296. shown = 0
  297. for thread_id, frame in sys._current_frames().items():
  298. stack = "".join(traceback.format_stack(frame)[-4:])
  299. if (("harness.py" in stack or "bundles" in stack
  300. or "web_stack_test.py" in stack) and ("sleep" not in stack)
  301. and shown < 6):
  302. shown += 1
  303. print(" --- thread %s ---\n%s" % (thread_id, stack))
  304. def task_state(auth, task_id):
  305. return slot_public(auth, "/tasks/%d" % task_id, "task")
  306. def wait_task_done(auth, task_id, timeout=90):
  307. return wait_for(lambda: task_state(auth, task_id).get("status") == "done" or False,
  308. timeout=timeout, what="task %d -> done" % task_id)
  309. def task_id_of(title):
  310. conn = db()
  311. try:
  312. return conn.execute("select id from tasks where title = ?", (title,)).fetchone()[0]
  313. finally:
  314. conn.close()
  315. def enqueue_task(auth, task_id):
  316. """The human-only Enqueue action (plan 11): draft -> queued."""
  317. detail = task_state(auth, task_id)
  318. assert detail["status"] == "draft", "task %d not in draft (%s)" % (task_id, detail["status"])
  319. act(auth, detail["enqueue"], {})
  320. return task_state(auth, task_id)["status"]
  321. def create_queued(auth, fields):
  322. """Create via the queue form (lands in draft) and enqueue it — the
  323. standard 'this task should dispatch' fixture of the plan-11 world."""
  324. act(auth, slot_public(auth, "/tasks", "tasks")["create"], fields)
  325. task_id = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  326. if t["title"] == fields["title"]][0])
  327. enqueue_task(auth, task_id)
  328. return task_id
  329. def saddle_api(method, path, token, payload=None):
  330. """Raw call against the saddle ingest API; returns (status, json)."""
  331. request = urllib.request.Request(WEB + path,
  332. data=json.dumps(payload or {}).encode(), method=method)
  333. request.add_header("Content-Type", "application/json")
  334. if token is not None:
  335. request.add_header("Authorization", "Bearer " + token)
  336. try:
  337. with urllib.request.urlopen(request, timeout=15) as response:
  338. return response.status, json.loads(response.read().decode() or "{}")
  339. except urllib.error.HTTPError as error:
  340. body = error.read().decode()
  341. try:
  342. return error.code, json.loads(body)
  343. except ValueError:
  344. return error.code, {"raw": body}
  345. def db():
  346. return sqlite3.connect(DB_PATH)
  347. def http_get_page(auth, uri):
  348. """The compiled page HTML for a statum route (auth via the slot
  349. header), for asserting page-level embeds the slot state cannot
  350. see."""
  351. status, body = http("GET", uri, headers={
  352. "X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])})
  353. if status != 200:
  354. raise SystemExit("GET %s -> HTTP %d" % (uri, status))
  355. return body
  356. def goal_state(goal_id):
  357. """The goal slot for the CURRENT shard's admin login (the x7
  358. per-bundle duplicates collapsed here, plan 16 R5). Reads the
  359. runner's fixture context — the restart scenarios re-login and
  360. re-point ctx.auth mid-run, and late binding follows."""
  361. return slot_public(CTX.auth, "/goals/%d" % goal_id, "goal")
  362. def saddle_card(auth, name):
  363. rows = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  364. if s["name"] == name]
  365. return rows[0]
  366. def queued_count():
  367. conn = db()
  368. try:
  369. return conn.execute(
  370. "select count(*) from tasks where status = 'queued'").fetchone()[0]
  371. finally:
  372. conn.close()
  373. def command_rows(session):
  374. conn = db()
  375. try:
  376. return conn.execute(
  377. "select command_text, type from session_commands"
  378. " where session_id = ? order by id", (session,)).fetchall()
  379. finally:
  380. conn.close()
  381. class FakeSaddle:
  382. """In-process saddle daemon implementing the wire contract.
  383. Phase-2 push behaviour: the daemon asks POST /api/saddle/next-task
  384. whenever idle-awake (at registration, on POST /wake, after its task
  385. reaches a terminal state, and when a /status probe observes it
  386. parked idle — throttled), accepts assignments like POST /start used
  387. to, then PUSHES its telemetry home: raw PTY chunks via POST
  388. /api/saddle/chunks and round results with state transitions via
  389. POST /api/saddle/results (working at round start, terminal states
  390. when the scripted lifecycle ends them). /output, /log and /start
  391. are gone (404) like a post-phase-2 daemon; /task-update serves the
  392. cancel/comment/subtask-status kinds; POST /answer receives a
  393. delivered verdict when the round is parked in a block's answer
  394. wait (409 when nothing waits — the real daemon's contract; the
  395. resumed round continues after the response). Every trigger can be
  396. disabled per test for determinism; ask_now() performs a
  397. synchronous manual ask.
  398. """
  399. PROMPT = "bbarrow@fedora:/workspace/task-1$ "
  400. def __init__(self):
  401. self.lock = threading.Lock()
  402. self.start_payloads = [] # captured assignment payloads (/start + next-task 200s)
  403. self.state = "idle"
  404. self.summary = ""
  405. self.state_entered = time.monotonic()
  406. self.fail_next = False # next task drives the task to failed
  407. self.start_counts = {} # task id -> assignment count
  408. self.resumed_pending = False # crash-resume flag on the next /status
  409. self.suspend_on_title = None # this task (by title) parks as suspended
  410. self.output_seq = 100 # daemon-global entry ids for pushed results
  411. self.last_activity_epoch = int(time.time())
  412. self.hang_next = {} # path suffix -> hang count (never responds)
  413. self.abort_failures = 0 # cancel task-updates failing (500) while > 0
  414. self.abort_log = [] # task ids aborted via task-update cancel
  415. self.running_task = 0 # task id the daemon believes it runs
  416. self.running_title = "" # its title (suspend targeting)
  417. self.session_id = None # the web-side run row of the running task
  418. self.hold_state = False # freeze lifecycle + heartbeat pushes
  419. self.ssh_public_key = "" # reported on /status + /register
  420. self.started_mono = time.monotonic()
  421. self.freeze_activity = False # hold last_activity_epoch still
  422. self.silent = False # suppress pushes (staleness tests)
  423. self.dead = False # kill(): no serving AND no calls home
  424. self.status_hits = 0 # GET /status arrivals (probe accounting)
  425. self.comment_log = [] # recorded /task-update comment payloads
  426. self.scripted_corpus = None # chunk batch pushed when a task starts
  427. # --- plan 10 phase 1: ask/wake/register ---
  428. self.token = None # per-saddle token from POST /register
  429. self.register_log = [] # recorded /register bodies
  430. self.wake_log = [] # recorded POST /wake arrivals
  431. self.asks = [] # [{"status": int, "payload": dict|None}]
  432. self.ask_on_register = True
  433. self.ask_on_wake = True
  434. self.ask_on_terminal = True
  435. self.ask_on_idle_status = True
  436. self.ask_delay = 0.0 # seconds; a slow daemon delays its wake-triggered ask
  437. self.serve_register = True # False: 404 /register (pre-flip daemon)
  438. self.last_ask_trigger = 0.0
  439. self.port = None
  440. self.ask_threads = [] # scheduled ask-trigger threads (settle_asks joins them)
  441. # --- answer delivery (the parked-session resume) ---
  442. self.pending_block = None # the block payload this daemon waits on (state blocked)
  443. self.answer_log = [] # recorded POST /answer bodies
  444. self.answer_push_delay = 0.2 # the resumed round's first push, after the response
  445. # --- plan 12: goal-agent scripting ---
  446. self.goal_script = [] # behaviours consumed per goal-run assignment
  447. self.goal_behaviour = None # the current round's popped behaviour
  448. self.goal_assignments = [] # captured goal-run assignment payloads
  449. def set_state(self, state, summary=None):
  450. """Advances the scripted lifecycle."""
  451. self.state = state
  452. if summary is not None:
  453. self.summary = summary
  454. self.state_entered = time.monotonic()
  455. def touch_activity(self):
  456. if not self.freeze_activity:
  457. self.last_activity_epoch = int(time.time())
  458. def queue_output(self, entry_type, command, output):
  459. """Pushes a typed entry as a round-results push (the daemon's
  460. entry log riding the results channel)."""
  461. with self.lock:
  462. entry = {
  463. "id": self.output_seq,
  464. "command": command,
  465. "output": output,
  466. "exit_code": 1,
  467. "type": entry_type,
  468. "timestamp": "2026-09-06T00:00:00Z",
  469. }
  470. self.output_seq += 1
  471. self.push_results(self.state if self.state in ("working",) else "working",
  472. entries=[entry])
  473. # --- plan 10 phase 2: the push channels ---
  474. def push_chunks(self, chunks):
  475. """Pushes raw PTY chunks home: elements are texts (assigned
  476. fresh seqs) or {seq, text} dicts (a redelivery or explicit
  477. corpus). Pushes are suppressed while silent/hold_state (the
  478. staleness tests' silent runner)."""
  479. if self.dead or self.silent or self.token is None or self.session_id is None:
  480. return
  481. batch = []
  482. with self.lock:
  483. for chunk in chunks:
  484. if isinstance(chunk, dict):
  485. batch.append({"seq": int(chunk["seq"]), "text": chunk["text"]})
  486. else:
  487. batch.append({"seq": self.next_push_seq(), "text": chunk})
  488. try:
  489. saddle_api("POST", "/api/saddle/chunks", self.token,
  490. {"session_id": self.session_id, "chunks": batch})
  491. except (OSError, ValueError):
  492. pass # app restarting / shutting down mid-test
  493. def next_push_seq(self):
  494. # The daemon-side chunk counter for ad-hoc pushes.
  495. self._push_seq = getattr(self, "_push_seq", 0) + 1
  496. return self._push_seq
  497. def push_results(self, state, entries=None, block=None, summary=None, session_id=None):
  498. """Pushes one round-results payload home (state transition plus
  499. its entries). Returns the HTTP status when it went out, None
  500. when suppressed."""
  501. if self.dead or self.silent:
  502. return None
  503. if self.token is None:
  504. return None
  505. target = session_id if session_id is not None else self.session_id
  506. if target is None:
  507. return None
  508. payload = {"session_id": target, "state": state}
  509. if entries is not None:
  510. payload["entries"] = entries
  511. if block is not None:
  512. payload["block"] = block
  513. if state == "blocked":
  514. # The daemon parks its round on this block's answer wait
  515. # (the real daemon's wait_for_answer).
  516. self.pending_block = dict(block)
  517. if summary is not None:
  518. payload["summary"] = summary
  519. try:
  520. status, _ = saddle_api("POST", "/api/saddle/results", self.token, payload)
  521. if status != 200:
  522. print(" [fake %s] push %s -> HTTP %s (task=%s)"
  523. % (self.port, state, status, self.running_task))
  524. return status
  525. except (OSError, ValueError) as error:
  526. print(" [fake %s] push %s failed: %r (task=%s)"
  527. % (self.port, state, error, self.running_task))
  528. return None
  529. # --- plan 10 phase 1: the ask path ---
  530. def ask_now(self):
  531. """Synchronously asks the web for work (a phase-1 daemon's idle
  532. ask). A 200 assignment is accepted exactly like POST /start;
  533. returns (status, payload|None)."""
  534. token = self.token
  535. if token is None:
  536. raise SystemExit("fake daemon asked before receiving its token")
  537. status, payload = saddle_api("POST", "/api/saddle/next-task", token)
  538. with self.lock:
  539. self.asks.append({"status": status, "payload": payload})
  540. if status == 200:
  541. self.accept_assignment(payload)
  542. return status, payload
  543. def _trigger_ask(self, reason):
  544. """Schedules a delayed ask (the daemon woke / went idle-awake).
  545. ask_delay models a SLOW asker — a daemon still winding down its
  546. round when the wake lands: it honours the wake, but its ask
  547. arrives late (still inside the web's lost-wake guard window)."""
  548. def run():
  549. if self.state in ("working", "failing"):
  550. return # a running daemon does not ask
  551. if self.ask_delay > 0:
  552. time.sleep(self.ask_delay)
  553. for attempt in range(3):
  554. try:
  555. status, _ = self.ask_now()
  556. if status in (200, 204):
  557. return
  558. print(" (ask %s -> HTTP %s, attempt %d)" % (reason, status, attempt + 1))
  559. except Exception as error: # app restarting / blips: retry
  560. print(" (ask %s failed: %r, attempt %d)" % (reason, error, attempt + 1))
  561. time.sleep(1.0)
  562. def starter():
  563. time.sleep(FAKE_TRIGGER_S)
  564. run()
  565. thread = threading.Thread(target=starter, daemon=True)
  566. with self.lock:
  567. self.ask_threads.append(thread)
  568. thread.start()
  569. def settle_asks(self, timeout=15):
  570. """Joins every ask-trigger thread scheduled so far — the
  571. event-driven replacement for the fixed sleeps that waited for
  572. in-flight asks to land after triggers were frozen."""
  573. with self.lock:
  574. threads = [t for t in self.ask_threads if t.is_alive()]
  575. deadline = time.monotonic() + timeout
  576. for thread in threads:
  577. thread.join(timeout=max(0.1, deadline - time.monotonic()))
  578. with self.lock:
  579. self.ask_threads = [t for t in self.ask_threads if t.is_alive()]
  580. return all(not thread.is_alive() for thread in threads)
  581. def maybe_trigger_ask(self, reason, throttle=False):
  582. """Schedules an idle-awake ask. Protocol events (wake, abort,
  583. round end, park) ask singularly and immediately; only the
  584. /status-observation path throttles (a burst of probes must not
  585. hammer the ask endpoint)."""
  586. now = time.monotonic()
  587. if throttle and now - self.last_ask_trigger < 1.0:
  588. return
  589. self.last_ask_trigger = now
  590. self._trigger_ask(reason)
  591. def accept_assignment(self, payload):
  592. """A 200 next-task assignment: adopted exactly like POST /start."""
  593. self.start_payloads.append(payload)
  594. task = payload.get("task") or {}
  595. task_id = task.get("id")
  596. self.running_task = int(task_id or 0)
  597. self.running_title = task.get("title") or ""
  598. self.session_id = payload.get("session_id")
  599. # The assignment's answers resolve any block this daemon was
  600. # parked on (resume-carries-answer).
  601. self.pending_block = None
  602. count = self.start_counts.get(task_id, 0) + 1
  603. self.start_counts[task_id] = count
  604. if count > 1:
  605. # Crash-resume contract: re-pushing a task whose
  606. # workspace still exists restores it; the first
  607. # /status after the restore reports "resumed": true.
  608. self.resumed_pending = True
  609. # Plan 12: a goal-run assignment plays its scripted behaviour
  610. # instead of the plain done push (plan submission, parking,
  611. # question, completion, failure — consumed one per round).
  612. self.goal_behaviour = None
  613. if payload.get("kind") == "goal_run":
  614. self.goal_assignments.append(payload)
  615. self.goal_behaviour = self.goal_script.pop(0) if self.goal_script else ("suspend",)
  616. self.set_state("failing" if self.fail_next else "working")
  617. self.fail_next = False
  618. # The round's opening telemetry: the flushed-so-far raw PTY
  619. # batch plus the working state push (>= 2 flushes per round
  620. # and the 10s timer are the real daemon's contract; the fake
  621. # pushes its batch up front and heartbeats while working).
  622. if self.scripted_corpus is not None:
  623. self.push_chunks([dict(chunk) for chunk in self.scripted_corpus])
  624. else:
  625. self.push_chunks([self.PROMPT, "echo hello\r\n", "hello\r\n"])
  626. self.push_results("working")
  627. class Handler(BaseHTTPRequestHandler):
  628. daemon = None # set on the class before serving
  629. protocol_version = "HTTP/1.1"
  630. def log_message(self, fmt, *args):
  631. pass
  632. def maybe_hang(self, path):
  633. """True when this request should hang forever (never respond),
  634. consuming one unit of the path's hang budget."""
  635. for suffix, count in list(self.daemon.hang_next.items()):
  636. if count > 0 and path.startswith(suffix):
  637. self.daemon.hang_next[suffix] = count - 1
  638. return True
  639. return False
  640. def _send(self, status, obj):
  641. body = json.dumps(obj).encode()
  642. self.send_response(status)
  643. self.send_header("Content-Type", "application/json")
  644. self.send_header("Content-Length", str(len(body)))
  645. self.end_headers()
  646. self.wfile.write(body)
  647. def do_POST(self):
  648. if self.maybe_hang(self.path):
  649. time.sleep(600)
  650. return
  651. self.daemon.touch_activity()
  652. length = int(self.headers.get("Content-Length") or 0)
  653. raw = self.rfile.read(length).decode() if length else "{}"
  654. if self.path == "/register":
  655. # Plan 10: the web delivers the per-saddle token + its
  656. # own base URL; the daemon persists the token for its
  657. # calls home and reports its ssh key + version.
  658. if not self.daemon.serve_register:
  659. self._send(404, {"error": "no such route"})
  660. return
  661. try:
  662. payload = json.loads(raw)
  663. except ValueError:
  664. payload = {"raw": raw}
  665. self.daemon.register_log.append(payload)
  666. if payload.get("saddle_token"):
  667. self.daemon.token = payload["saddle_token"]
  668. self._send(200, {"ok": True,
  669. "ssh_public_key": self.daemon.ssh_public_key,
  670. "version": "0.1-fake"})
  671. if self.daemon.ask_on_register:
  672. self.daemon.maybe_trigger_ask("register")
  673. return
  674. if self.path == "/wake":
  675. # Plan 10: a capable task is ready; a sleeping daemon
  676. # asks for work (immediately — a wake is a direct
  677. # command, never throttled).
  678. self.daemon.wake_log.append(time.monotonic())
  679. self._send(200, {"ok": True})
  680. if self.daemon.ask_on_wake:
  681. self.daemon.maybe_trigger_ask("wake")
  682. return
  683. if self.path == "/answer":
  684. # Plan 11 (daemon Task A): parks FREE the daemon, so no
  685. # block ever waits in-process — the verdict travels in
  686. # the resuming allocation's resume_notice. Always 409,
  687. # exactly like the real daemon's contract.
  688. try:
  689. payload = json.loads(raw)
  690. except ValueError:
  691. self._send(400, {"error": "bad json"})
  692. return
  693. self.daemon.answer_log.append({
  694. "refused": True,
  695. "answer": payload.get("answer", "")})
  696. self._send(409, {"error": "no block is waiting for an answer — parks resume via allocation"})
  697. return
  698. if self.path == "/task-update":
  699. # Plan 10: cancel (abort machinery) and comment
  700. # (injected turn) — delivered directly to a RUNNING
  701. # daemon, no auth.
  702. try:
  703. payload = json.loads(raw)
  704. except ValueError:
  705. self._send(400, {"error": "bad json"})
  706. return
  707. kind = payload.get("kind")
  708. if kind == "cancel":
  709. if self.daemon.abort_failures > 0:
  710. self.daemon.abort_failures -= 1
  711. self._send(500, {"error": "cancel failed (simulated)"})
  712. return
  713. aborted = self.daemon.running_task
  714. self.daemon.set_state("idle")
  715. self.daemon.summary = ""
  716. self.daemon.running_task = 0
  717. self.daemon.session_id = None
  718. self.daemon.abort_log.append(aborted)
  719. self._send(200, {"ok": True, "aborted_task_id": aborted})
  720. # An aborted daemon returns to its idle loop: it asks.
  721. self.daemon.maybe_trigger_ask("aborted")
  722. elif kind == "comment":
  723. self.daemon.comment_log.append(payload)
  724. self._send(200, {"ok": True})
  725. else:
  726. self._send(400, {"error": "unknown task-update kind"})
  727. return
  728. self._send(404, {"error": "no such route"})
  729. self.close_connection = True
  730. def do_GET(self):
  731. if self.maybe_hang(self.path):
  732. time.sleep(600)
  733. return
  734. if self.path != "/status":
  735. # /status itself is not daemon activity: the liveness
  736. # signal must reflect loop rounds / command completions.
  737. self.daemon.touch_activity()
  738. if self.path == "/status":
  739. self.daemon.status_hits += 1
  740. response = {"state": self.daemon.state, "summary": self.daemon.summary,
  741. "uptime_seconds": int(time.monotonic() - self.daemon.started_mono),
  742. "last_activity_epoch": self.daemon.last_activity_epoch,
  743. "ssh_public_key": self.daemon.ssh_public_key}
  744. if getattr(self.daemon, "status_extra", None):
  745. response.update(self.daemon.status_extra)
  746. if self.daemon.resumed_pending:
  747. response["resumed"] = True
  748. self.daemon.resumed_pending = False
  749. # A parked/terminal daemon is idle-awake: a phase-1
  750. # daemon asks (and sleeps on 204). Throttled so status
  751. # poll bursts do not hammer the ask endpoint.
  752. if self.daemon.ask_on_idle_status and self.daemon.state in (
  753. "idle", "done", "failed", "suspended"):
  754. self.daemon.maybe_trigger_ask("idle-status", throttle=True)
  755. self._send(200, response)
  756. else:
  757. self._send(404, {"error": "no such route"})
  758. self.close_connection = True
  759. def run_lifecycle(self):
  760. """Applies the scripted lifecycle on a timer (like a real daemon
  761. whose task ends on its own): working heartbeats chunks (the
  762. flush timer's stand-in, keeping the staleness clock fed), works
  763. for FAKE_WORK_S, then pushes done/suspended; failing pushes
  764. failed after FAKE_FAIL_S — and a task END makes the idle-awake
  765. daemon ask again."""
  766. while True:
  767. time.sleep(0.1)
  768. if self.hold_state or self.silent:
  769. # hold_state freezes the script; silent models a daemon
  770. # mid-round with nothing to flush — its round has not
  771. # ended, so no terminal push fires while quiet.
  772. continue
  773. if self.state == "failing":
  774. if time.monotonic() - self.state_entered >= FAKE_FAIL_S:
  775. self.set_state("failed", "bash -n rejected the script (simulated)")
  776. self.push_results("failed",
  777. summary="bash -n rejected the script (simulated)")
  778. if self.ask_on_terminal:
  779. self.maybe_trigger_ask("terminal")
  780. elif self.state == "working":
  781. if time.monotonic() - self.state_entered >= FAKE_WORK_S:
  782. if self.goal_behaviour is not None:
  783. # A goal-agent round: play the scripted
  784. # behaviour (the results channel carries the
  785. # goal-context verbs).
  786. behaviour, self.goal_behaviour = self.goal_behaviour, None
  787. kind = behaviour[0]
  788. if kind == "plan":
  789. self.set_state("blocked")
  790. self.push_results("blocked", block={
  791. "type": "plan",
  792. "question": "Plan submitted for review",
  793. "body": behaviour[1]})
  794. if self.ask_on_idle_status:
  795. self.maybe_trigger_ask("parked")
  796. elif kind == "question":
  797. self.set_state("blocked")
  798. self.push_results("blocked", block={
  799. "type": "question",
  800. "question": behaviour[1],
  801. "options": list(behaviour[2])
  802. if len(behaviour) > 2 else None})
  803. if self.ask_on_idle_status:
  804. self.maybe_trigger_ask("parked")
  805. elif kind == "suspend":
  806. self.set_state("suspended")
  807. self.push_results("suspended")
  808. if self.ask_on_idle_status:
  809. self.maybe_trigger_ask("parked")
  810. elif kind == "fail":
  811. self.set_state("failed", behaviour[1])
  812. self.push_results("failed", summary=behaviour[1])
  813. if self.ask_on_terminal:
  814. self.maybe_trigger_ask("terminal")
  815. else: # "done": the completion report
  816. self.set_state("done", behaviour[1])
  817. self.push_results("done", summary=behaviour[1])
  818. if self.ask_on_terminal:
  819. self.maybe_trigger_ask("terminal")
  820. elif self.suspend_on_title and self.suspend_on_title == self.running_title:
  821. # `saddle suspend`: park until a fresh assignment
  822. # resumes the workspace (title-targeted one-shot,
  823. # so an interleaved dispatch cannot eat the flag).
  824. self.set_state("suspended")
  825. self.suspend_on_title = None
  826. self.push_results("suspended")
  827. # A parked daemon is idle-awake: it asks (and
  828. # sleeps on 204) so a later wake can reach it.
  829. if self.ask_on_idle_status:
  830. self.maybe_trigger_ask("parked")
  831. else:
  832. self.set_state("done", "fake daemon finished")
  833. self.push_results("done", summary="fake daemon finished")
  834. if self.ask_on_terminal:
  835. self.maybe_trigger_ask("terminal")
  836. elif time.monotonic() - getattr(self, "last_heartbeat", 0) >= FAKE_HEARTBEAT_S:
  837. # The flush timer: output keeps flowing, so chunks
  838. # keep arriving (the staleness window never opens on
  839. # a healthy runner).
  840. self.last_heartbeat = time.monotonic()
  841. self.push_chunks(["working-heartbeat\r\n"])
  842. def serve(self, port=None):
  843. """Binds the daemon's HTTP server. A requested port that is
  844. already taken (free_port() hands out recyclable ports — two
  845. calls can collide) falls back to an OS-assigned one instead of
  846. silently dying and impersonating whatever owns that port."""
  847. if port is None:
  848. port = DAEMON_PORT
  849. handler = type("BoundHandler", (FakeSaddle.Handler,), {"daemon": self})
  850. self.server = None
  851. try:
  852. self.server = ThreadingHTTPServer(("127.0.0.1", port), handler)
  853. except OSError:
  854. print("(fake daemon: port %d taken, falling back)" % port)
  855. self.server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
  856. self.port = self.server.server_address[1]
  857. threading.Thread(target=self.server.serve_forever, daemon=True).start()
  858. threading.Thread(target=self.run_lifecycle, daemon=True).start()
  859. return self.server
  860. def kill(self):
  861. """The daemon dies: it stops listening (connections refused) AND
  862. stops calling home — no pushes, no asks (a dead process has no
  863. outbound anything; in-flight handler threads may linger but the
  864. wire contract's traffic is one-directional now)."""
  865. self.dead = True
  866. if getattr(self, "server", None) is not None:
  867. self.server.shutdown()
  868. self.server.server_close()
  869. self.server = None
  870. def start_app():
  871. config = json.load(open(os.path.join(REPO, "web-config.json")))
  872. config["saddle_callback_base_url"] = WEB
  873. with open(os.path.join(WORK, "web-config.json"), "w") as handle:
  874. json.dump(config, handle)
  875. env = dict(os.environ)
  876. env.update({
  877. "SPRY_DB_PATH": DB_PATH,
  878. "SPRY_SEED_ADMIN_USERNAME": "admin",
  879. "SPRY_SEED_ADMIN_PASSWORD": "adminpass123",
  880. "SADDLE_LLM_BASE_URL": "http://127.0.0.1:%d" % DAEMON_PORT,
  881. "SADDLE_PROJECTS_ROOT": os.path.join(WORK, "workspace"),
  882. "SADDLE_HTTP_TIMEOUT_S": "2",
  883. "SADDLE_LOST_WAKE_S": "2",
  884. "SADDLE_STALE_S": "3",
  885. "SADDLE_DISPATCH_TICK_S": "1",
  886. # Plan 12: the goal-agent resume coalescing window shrinks to
  887. # one second so the event-driven resume tests settle quickly.
  888. "SADDLE_GOAL_RESUME_S": os.environ.get("SADDLE_GOAL_RESUME_S", "1"),
  889. # Never inherit a caller-poisoned LD_LIBRARY_PATH (e.g. one that
  890. # resolves the ancient /lib64 copies): empty makes the loader use
  891. # the binary's RUNPATH, which is the dev stack it was built
  892. # against.
  893. "LD_LIBRARY_PATH": "",
  894. })
  895. log_previous = os.path.join(WORK, "app.log.1")
  896. if os.path.exists(os.path.join(WORK, "app.log")):
  897. shutil.move(os.path.join(WORK, "app.log"), log_previous)
  898. log = open(os.path.join(WORK, "app.log"), "w")
  899. command = [APP, str(APP_PORT)]
  900. if os.environ.get("WEBSTACK_GDB"):
  901. # Debugging aid: run the app under gdb; a crash backtrace lands in
  902. # app.log. WEBSTACK_GDB=1 meson test ... to enable.
  903. command = ["gdb", "-batch", "-quiet",
  904. "-ex", "handle SIGPIPE nostop noprint pass",
  905. "-ex", "run", "-ex", "bt", "--args", APP, str(APP_PORT)]
  906. process = subprocess.Popen(command, cwd=WORK, env=env,
  907. stdout=log, stderr=subprocess.STDOUT)
  908. # The ready probe must require OUR process alive: a free_port()
  909. # TOCTOU can hand this port to another shard's app — ours then dies
  910. # at bind (MHD error()) while the probe happily answers from the
  911. # intruder (same admin seed), and every check would silently drive
  912. # the WRONG app. poll() != None with a serving port is exactly that
  913. # shape: take the exit branch, the start_bundle retry re-ports.
  914. outcome = wait_for(lambda: (app_ready() and process.poll() is None and "ready")
  915. or (process.poll() is not None and "app-exited-%d" % process.poll())
  916. or False, timeout=30, what="app ready")
  917. if outcome is None:
  918. raise SystemExit("app did not come up; see %s/app.log" % WORK)
  919. if str(outcome).startswith("app-exited-"):
  920. raise SystemExit("app exited during startup (%s); see %s/app.log"
  921. % outcome, WORK)
  922. return process
  923. def app_ready():
  924. try:
  925. status, _ = http("GET", "/login", timeout=3)
  926. return status == 200
  927. except (urllib.error.URLError, OSError):
  928. return False
  929. def dump_app_stacks(pid):
  930. """Best-effort thread backtrace of the (possibly wedged) app."""
  931. try:
  932. fds = os.listdir("/proc/%d/fd" % pid)
  933. print("(app open fds at dump: %d)" % len(fds))
  934. kinds = {}
  935. for fd in fds[:1200]:
  936. try:
  937. target = os.readlink("/proc/%d/fd/%s" % (pid, fd))
  938. except OSError:
  939. continue
  940. key = target.split(":", 1)[0] if ":" in target else target
  941. kinds[key] = kinds.get(key, 0) + 1
  942. print("(fd kinds: %s)" % sorted(kinds.items(), key=lambda kv: -kv[1])[:6])
  943. except OSError:
  944. pass
  945. for command in (["eu-stack", "-p", str(pid)],
  946. ["gdb", "-batch", "-quiet", "-p", str(pid),
  947. "-ex", "thread apply all bt"]):
  948. try:
  949. out = subprocess.run(command, capture_output=True, timeout=60)
  950. text = out.stdout.decode(errors="replace") + out.stderr.decode(errors="replace")
  951. if text.strip():
  952. print("(app stacks via %s)\n%s" % (command[0], text[:12000]))
  953. return
  954. except (OSError, subprocess.SubprocessError):
  955. continue
  956. # =============================================================================
  957. # Fake push service + Web Push protocol helpers (plan 11 task E)
  958. # =============================================================================
  959. def b64url(raw):
  960. return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
  961. def b64url_dec(text):
  962. return base64.urlsafe_b64decode(text + "=" * ((4 - len(text) % 4) % 4))
  963. class FakePushService:
  964. """In-process Web Push endpoint server: every subscription the tests
  965. register points at a path here (a distinct "browser endpoint").
  966. Responses are scriptable per path — a fixed status (the 410-prune
  967. fixture) or N transient 500s (the retry-next-tick fixture)."""
  968. def __init__(self):
  969. self.requests = [] # [{"path", "headers", "body", "at"}]
  970. self.fail_next = {} # path -> remaining 500s
  971. self.status_for = {} # path -> fixed status
  972. self.lock = threading.Lock()
  973. self.port = None
  974. self.server = None
  975. def serve(self):
  976. service = self
  977. class Handler(BaseHTTPRequestHandler):
  978. protocol_version = "HTTP/1.1"
  979. def log_message(self, fmt, *args):
  980. pass
  981. def do_POST(self):
  982. length = int(self.headers.get("Content-Length") or 0)
  983. body = self.rfile.read(length)
  984. status = 201
  985. if self.path in service.status_for:
  986. status = service.status_for[self.path]
  987. elif service.fail_next.get(self.path, 0) > 0:
  988. service.fail_next[self.path] -= 1
  989. status = 500
  990. with service.lock:
  991. service.requests.append({
  992. "path": self.path,
  993. "headers": {key.lower(): value
  994. for key, value in self.headers.items()},
  995. "body": body,
  996. "at": time.monotonic(),
  997. })
  998. payload = b"{}"
  999. self.send_response(status)
  1000. self.send_header("Content-Type", "application/json")
  1001. self.send_header("Content-Length", str(len(payload)))
  1002. self.end_headers()
  1003. self.wfile.write(payload)
  1004. self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
  1005. self.port = self.server.server_address[1]
  1006. threading.Thread(target=self.server.serve_forever, daemon=True).start()
  1007. return self.server
  1008. def url(self, path):
  1009. return "http://127.0.0.1:%d%s" % (self.port, path)
  1010. def hits(self, prefix):
  1011. with self.lock:
  1012. return [request for request in self.requests
  1013. if request["path"].startswith(prefix)]
  1014. def decrypt_webpush(request, client_private_key, client_public, auth_secret):
  1015. """RFC 8291 decryption of one captured push: returns
  1016. (record_size, payload dict) — the payload builder's exact output."""
  1017. body = request["body"]
  1018. salt = body[:16]
  1019. record_size = int.from_bytes(body[16:20], "big")
  1020. key_id_len = body[20]
  1021. eph_public = body[21:21 + key_id_len]
  1022. ciphertext = body[21 + key_id_len:]
  1023. eph_point = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(),
  1024. eph_public)
  1025. shared = client_private_key.exchange(ec.ECDH(), eph_point)
  1026. info = b"WebPush: info\x00" + eph_public + client_public
  1027. cek = HKDF(algorithm=hashes.SHA256(), length=16, salt=salt,
  1028. info=info).derive(shared + auth_secret)
  1029. nonce = HKDF(algorithm=hashes.SHA256(), length=12, salt=salt,
  1030. info=info).derive(shared + auth_secret)
  1031. plaintext = AESGCM(cek).decrypt(nonce, ciphertext, None)
  1032. return record_size, json.loads(plaintext[:-1]) # strip the 0x02 delimiter
  1033. def verify_vapid(request, vapid_public, vapid_private):
  1034. """Verifies the ES256 VAPID JWT on one captured push; returns its
  1035. claims dict (aud/exp/sub) — raises on a bad signature."""
  1036. header = request["headers"].get("authorization", "")
  1037. assert header.startswith("vapid t="), "no vapid authorization header"
  1038. token_part = header[len("vapid t="):].split(",")[0]
  1039. sent_key = header.split("k=")[1]
  1040. head_b64, claims_b64, sig_b64 = token_part.split(".")
  1041. signature = b64url_dec(sig_b64)
  1042. key = ec.derive_private_key(
  1043. int.from_bytes(b64url_dec(vapid_private), "big"), ec.SECP256R1())
  1044. key.public_key().verify(
  1045. encode_dss_signature(int.from_bytes(signature[:32], "big"),
  1046. int.from_bytes(signature[32:], "big")),
  1047. (head_b64 + "." + claims_b64).encode(),
  1048. ec.ECDSA(hashes.SHA256()))
  1049. claims = json.loads(b64url_dec(claims_b64))
  1050. assert sent_key == vapid_public, "the k= key is not the app's VAPID key"
  1051. return claims
  1052. def action_notify(result):
  1053. """The message of the first notify directive an action returned."""
  1054. for directive in result:
  1055. if directive.get("type") == "notify":
  1056. return directive.get("message", "")
  1057. return None
  1058. # =============================================================================
  1059. # Shard orchestration
  1060. # =============================================================================
  1061. class Ctx:
  1062. """Per-bundle shared fixtures: the app process, the admin auth slot
  1063. and the primary fake saddle (registered + token delivered)."""
  1064. def start_bundle(name):
  1065. """Boots one shard's environment: scratch dir, database, ports, the
  1066. primary fake daemon and the app, then the shared fixtures every
  1067. bundle builds on (the demo project + the registered fake saddle).
  1068. Scenario groups inside the bundle share this app+daemon instance
  1069. and sequence their state as DB rows, never process restarts."""
  1070. global APP_PORT, WEB, DAEMON_PORT
  1071. bundle_env(name)
  1072. fake = FakeSaddle()
  1073. fake.serve()
  1074. DAEMON_PORT = fake.port # the actually-bound port (fallback-safe)
  1075. # A rare framework-level crash (stack corruption in Statum slot
  1076. # signing during the FIRST login — shared-library codegen bug, moved
  1077. # twice already) kills the app before any test runs; a clean restart
  1078. # (with fresh ports) sidesteps it. Only tolerated while nothing has
  1079. # been checked yet.
  1080. auth = None
  1081. app = None
  1082. for attempt in range(3):
  1083. APP_PORT = free_port()
  1084. WEB = "http://127.0.0.1:%d" % APP_PORT
  1085. if os.path.exists(WORK):
  1086. shutil.rmtree(WORK)
  1087. os.makedirs(os.path.join(WORK, "workspace"))
  1088. try:
  1089. app = start_app()
  1090. auth = login("admin", "adminpass123")
  1091. break
  1092. except (SystemExit, OSError, urllib.error.URLError):
  1093. if passes > 0:
  1094. raise
  1095. if app is not None and app.poll() is None:
  1096. app.terminate()
  1097. try:
  1098. app.wait(timeout=5)
  1099. except subprocess.TimeoutExpired:
  1100. app.kill()
  1101. app = None
  1102. print("(app died before login; restarting cleanly, attempt %d)" % (attempt + 1))
  1103. if app is None or auth is None:
  1104. raise SystemExit("app never came up; see %s/app.log" % WORK)
  1105. state = slot_public(auth, "/projects", "projects")
  1106. act(auth, state["create"], {
  1107. "name": "demo",
  1108. "git_url": "https://example.com/demo.git",
  1109. "default_branch": "main",
  1110. })
  1111. saddles_state = slot_public(auth, "/saddles", "saddles")
  1112. act(auth, saddles_state["register"], {"name": "fake-saddle",
  1113. "host": "127.0.0.1:%d" % fake.port})
  1114. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1115. if s["name"] == "fake-saddle"]
  1116. if wait_for(lambda: len(fake.register_log) > 0 or False,
  1117. timeout=15, what="/register delivery") is None:
  1118. raise SystemExit("fake saddle never received /register")
  1119. ctx = Ctx()
  1120. ctx.name = name
  1121. ctx.app = app
  1122. ctx.auth = auth
  1123. ctx.fake = fake
  1124. ctx.fake_id = int(registered[0]["id"])
  1125. ctx.fake_token = registered[0]["token"]
  1126. return ctx
  1127. BUNDLES_ORDER = ("pages", "dispatch", "subtasks", "lineage",
  1128. "allocation", "lifecycle", "answers", "push", "goals",
  1129. "replay", "goalui")
  1130. def run_bundle(name):
  1131. """Runs one shard to completion; returns a failure count."""
  1132. global CTX
  1133. started = time.monotonic()
  1134. ctx = start_bundle(name)
  1135. CTX = ctx
  1136. import importlib
  1137. bundle = importlib.import_module("bundles." + name)
  1138. # Runtime globals the star-import captured at module load can be
  1139. # stale (the sequential debug path reuses modules across shards) —
  1140. # re-point them at this shard's environment. The shared helpers
  1141. # read them from harness globals already.
  1142. for runtime_name in ("WORK", "DB_PATH", "APP_PORT", "DAEMON_PORT", "WEB"):
  1143. setattr(bundle, runtime_name, globals()[runtime_name])
  1144. runner = bundle.run
  1145. try:
  1146. runner(ctx)
  1147. finally:
  1148. # Exit-code diagnostic: distinguishes a crashed app (negative
  1149. # returncode, e.g. -11 SIGSEGV) from a clean shutdown. When
  1150. # tearing down mid-exception, also capture the still-alive
  1151. # app's stacks before killing it (a wedged-but-alive server
  1152. # otherwise leaves no evidence).
  1153. print("(app returncode at teardown: %s)" % ctx.app.poll())
  1154. if ctx.app.poll() is None and sys.exc_info()[0] is not None:
  1155. dump_app_stacks(ctx.app.pid)
  1156. ctx.fake.kill()
  1157. try:
  1158. ctx.app.terminate()
  1159. try:
  1160. ctx.app.wait(timeout=5)
  1161. except subprocess.TimeoutExpired:
  1162. ctx.app.kill()
  1163. check(ctx.app.poll() in (0, -15),
  1164. "bundle %s app shut down cleanly (exit %s)"
  1165. % (name, ctx.app.poll()))
  1166. except OSError:
  1167. pass
  1168. print("%d passed, %d failed" % (passes, failures))
  1169. print("[bundle %s] %.1fs" % (name, time.monotonic() - started))
  1170. return failures
  1171. def run_all_parallel():
  1172. """The default meson entry: one subprocess per bundle (each with its
  1173. own app, daemons and database), verdicts aggregated into one exit
  1174. code and one combined check-count summary."""
  1175. base = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  1176. log_dir = os.path.join(os.path.dirname(base) or "/tmp/kilo",
  1177. "webstack-shards")
  1178. os.makedirs(log_dir, exist_ok=True)
  1179. procs = {}
  1180. started = time.monotonic()
  1181. for name in BUNDLES_ORDER:
  1182. out_path = os.path.join(log_dir, "bundle-%s.log" % name)
  1183. handle = open(out_path, "w")
  1184. procs[name] = (subprocess.Popen(
  1185. [sys.executable, "-u",
  1186. os.path.join(os.path.dirname(os.path.abspath(__file__)),
  1187. "web_stack_test.py"), APP, "--bundle", name],
  1188. stdout=handle, stderr=subprocess.STDOUT), handle, out_path)
  1189. total_pass = total_fail = 0
  1190. broken = []
  1191. for name, (proc, handle, out_path) in procs.items():
  1192. try:
  1193. proc.wait(timeout=SHARD_TIMEOUT_S)
  1194. except subprocess.TimeoutExpired:
  1195. proc.kill()
  1196. proc.wait()
  1197. handle.close()
  1198. text = open(out_path).read()
  1199. match = re.search(r"(\d+) passed, (\d+) failed", text)
  1200. took = re.search(r"\[bundle %s\] ([0-9.]+)s" % name, text)
  1201. bundle_pass = int(match.group(1)) if match else 0
  1202. bundle_fail = int(match.group(2)) if match else -1
  1203. total_pass += max(bundle_pass, 0)
  1204. total_fail += max(bundle_fail, 0)
  1205. status = "ok"
  1206. if proc.returncode != 0 or bundle_fail != 0 or match is None:
  1207. status = "BROKEN (exit %s)" % proc.returncode
  1208. broken.append(name)
  1209. print("[shard %-10s] %6ss %3d passed %3d failed %s"
  1210. % (name, took.group(1) if took else "?",
  1211. bundle_pass, bundle_fail, status))
  1212. if status != "ok":
  1213. tail = "\n".join(text.rstrip().split("\n")[-60:])
  1214. print("--- web-stack/%s tail (full log: %s) ---" % (name, out_path))
  1215. print(tail)
  1216. print("--- end web-stack/%s tail ---" % name)
  1217. print("shards wall: %.1fs (logs under %s)" % (time.monotonic() - started, log_dir))
  1218. print("ALL SHARDS: %d passed, %d failed%s"
  1219. % (total_pass, total_fail,
  1220. "" if not broken else " BROKEN: " + ", ".join(broken)))
  1221. return 1 if broken or total_fail else 0
  1222. def main():
  1223. if not os.path.exists(APP):
  1224. raise SystemExit("app binary not found at %s (build first)" % APP)
  1225. argv = sys.argv[2:]
  1226. if "--bundle" in argv:
  1227. sys.exit(1 if run_bundle(argv[argv.index("--bundle") + 1]) else 0)
  1228. if os.environ.get("WEBSTACK_SEQUENTIAL"):
  1229. # Debug path: every bundle in-process, one after another.
  1230. for name in BUNDLES_ORDER:
  1231. if run_bundle(name):
  1232. return 1
  1233. return 0
  1234. return run_all_parallel()
  1235. if __name__ == "__main__":
  1236. sys.exit(main())