harness.py 61 KB

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