harness.py 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  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(6):
  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 >= 5:
  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 kind, payload from events"
  379. " where session_id = ? order by id", (session,)).fetchall()
  380. finally:
  381. conn.close()
  382. def event_rows(task_id, kinds=None):
  383. """The task's ledger rows (kind, payload JSON), oldest first."""
  384. conn = db()
  385. try:
  386. if kinds:
  387. marks = ",".join("?" for _ in kinds)
  388. return conn.execute(
  389. "select kind, payload from events"
  390. " where scope_type = 'task' and scope_id = ? and kind in (%s)"
  391. " order by id" % marks, (task_id,) + tuple(kinds)).fetchall()
  392. return conn.execute(
  393. "select kind, payload from events"
  394. " where scope_type = 'task' and scope_id = ? order by id",
  395. (task_id,)).fetchall()
  396. finally:
  397. conn.close()
  398. class FakeSaddle:
  399. """In-process saddle daemon implementing the wire contract.
  400. Phase-2 push behaviour: the daemon asks POST /api/saddle/next-task
  401. whenever idle-awake (at registration, on POST /wake, after its task
  402. reaches a terminal state, and when a /status probe observes it
  403. parked idle — throttled), accepts assignments like POST /start used
  404. to, then PUSHES its telemetry home: raw PTY chunks via POST
  405. /api/saddle/chunks and round results with state transitions via
  406. POST /api/saddle/results (working at round start, terminal states
  407. when the scripted lifecycle ends them). /output, /log and /start
  408. are gone (404) like a post-phase-2 daemon; /task-update serves the
  409. cancel/comment/subtask-status kinds; POST /answer receives a
  410. delivered verdict when the round is parked in a block's answer
  411. wait (409 when nothing waits — the real daemon's contract; the
  412. resumed round continues after the response). Every trigger can be
  413. disabled per test for determinism; ask_now() performs a
  414. synchronous manual ask.
  415. """
  416. PROMPT = "bbarrow@fedora:/workspace/task-1$ "
  417. def __init__(self):
  418. self.lock = threading.Lock()
  419. self.start_payloads = [] # captured assignment payloads (/start + next-task 200s)
  420. self.state = "idle"
  421. self.summary = ""
  422. self.state_entered = time.monotonic()
  423. self.fail_next = False # next task drives the task to failed
  424. self.start_counts = {} # task id -> assignment count
  425. self.resumed_pending = False # crash-resume flag on the next /status
  426. self.suspend_on_title = None # this task (by title) parks as suspended
  427. self.output_seq = 100 # daemon-global entry ids for pushed results
  428. self.last_activity_epoch = int(time.time())
  429. self.hang_next = {} # path suffix -> hang count (never responds)
  430. self.abort_failures = 0 # cancel task-updates failing (500) while > 0
  431. self.abort_log = [] # task ids aborted via task-update cancel
  432. self.running_task = 0 # task id the daemon believes it runs
  433. self.running_title = "" # its title (suspend targeting)
  434. self.session_id = None # the web-side run row of the running task
  435. self.hold_state = False # freeze lifecycle + heartbeat pushes
  436. self.ssh_public_key = "" # reported on /status + /register
  437. self.started_mono = time.monotonic()
  438. self.freeze_activity = False # hold last_activity_epoch still
  439. self.silent = False # suppress pushes (staleness tests)
  440. self.dead = False # kill(): no serving AND no calls home
  441. self.status_hits = 0 # GET /status arrivals (probe accounting)
  442. self.comment_log = [] # recorded /task-update comment payloads
  443. self.scripted_corpus = None # chunk batch pushed when a task starts
  444. # --- plan 10 phase 1: ask/wake/register ---
  445. self.token = None # per-saddle token from POST /register
  446. self.register_log = [] # recorded /register bodies
  447. self.wake_log = [] # recorded POST /wake arrivals
  448. self.asks = [] # [{"status": int, "payload": dict|None}]
  449. self.ask_on_register = True
  450. self.ask_on_wake = True
  451. self.ask_on_terminal = True
  452. self.ask_on_idle_status = True
  453. self.ask_delay = 0.0 # seconds; a slow daemon delays its wake-triggered ask
  454. self.serve_register = True # False: 404 /register (pre-flip daemon)
  455. self.last_ask_trigger = 0.0
  456. self.port = None
  457. self.ask_threads = [] # scheduled ask-trigger threads (settle_asks joins them)
  458. # --- answer delivery (the parked-session resume) ---
  459. self.pending_block = None # the block payload this daemon waits on (state blocked)
  460. self.answer_log = [] # recorded POST /answer bodies
  461. self.answer_push_delay = 0.2 # the resumed round's first push, after the response
  462. # --- plan 12: goal-agent scripting ---
  463. self.goal_script = [] # behaviours consumed per goal-run assignment
  464. self.goal_behaviour = None # the current round's popped behaviour
  465. self.goal_assignments = [] # captured goal-run assignment payloads
  466. def set_state(self, state, summary=None):
  467. """Advances the scripted lifecycle."""
  468. self.state = state
  469. if summary is not None:
  470. self.summary = summary
  471. self.state_entered = time.monotonic()
  472. def touch_activity(self):
  473. if not self.freeze_activity:
  474. self.last_activity_epoch = int(time.time())
  475. def queue_output(self, entry_type, command, output):
  476. """Pushes one command_output event home (the daemon's entry log
  477. now rides the events channel; the old results-entries path is
  478. gone)."""
  479. self.push_events([{"kind": "command_output",
  480. "payload": {"command": command, "text": output}}])
  481. # --- plan 10 phase 2: the push channels ---
  482. def push_events(self, events):
  483. """Pushes a batch of ledger events home (plan 17 §7.2): each
  484. element a {seq?, kind, actor?, ts?, payload?} dict; a missing
  485. seq is assigned from the per-session monotonic counter.
  486. Pushes are suppressed while silent/hold_state (the staleness
  487. tests' silent runner)."""
  488. if self.dead or self.silent or self.token is None or self.session_id is None:
  489. return
  490. batch = []
  491. with self.lock:
  492. for event in events:
  493. item = dict(event)
  494. item["seq"] = int(item.pop("seq", 0) or self.next_push_seq())
  495. item.setdefault("kind", "progress")
  496. item.setdefault("actor", "model")
  497. item.setdefault("payload", {})
  498. batch.append(item)
  499. try:
  500. saddle_api("POST", "/api/saddle/chunks", self.token,
  501. {"task_id": self.running_task,
  502. "session_id": self.session_id, "events": batch})
  503. except (OSError, ValueError):
  504. pass # app restarting / shutting down mid-test
  505. def push_chunks(self, chunks):
  506. """Legacy-shaped helper: raw texts (or {seq, text} dicts, a
  507. redelivery) push as progress events carrying the text."""
  508. batch = []
  509. for chunk in chunks:
  510. if isinstance(chunk, dict):
  511. batch.append({"seq": chunk.get("seq"),
  512. "kind": chunk.get("kind", "progress"),
  513. "payload": chunk.get("payload",
  514. {"text": chunk.get("text", "")})})
  515. else:
  516. batch.append({"kind": "progress", "payload": {"text": chunk}})
  517. self.push_events(batch)
  518. def next_push_seq(self):
  519. # The daemon-side per-session event counter for ad-hoc pushes.
  520. self._push_seq = getattr(self, "_push_seq", 0) + 1
  521. return self._push_seq
  522. def push_results(self, state, entries=None, block=None, summary=None, session_id=None):
  523. """Pushes one round-results payload home (state transition plus
  524. its entries). Returns the HTTP status when it went out, None
  525. when suppressed."""
  526. if self.dead or self.silent:
  527. return None
  528. if self.token is None:
  529. return None
  530. target = session_id if session_id is not None else self.session_id
  531. if target is None:
  532. return None
  533. payload = {"session_id": target, "state": state}
  534. if block is not None:
  535. payload["block"] = block
  536. if state == "blocked":
  537. # The daemon parks its round on this block's answer wait
  538. # (the real daemon's wait_for_answer).
  539. self.pending_block = dict(block)
  540. if summary is not None:
  541. payload["summary"] = summary
  542. try:
  543. status, _ = saddle_api("POST", "/api/saddle/results", self.token, payload)
  544. if status != 200:
  545. print(" [fake %s] push %s -> HTTP %s (task=%s)"
  546. % (self.port, state, status, self.running_task))
  547. return status
  548. except (OSError, ValueError) as error:
  549. print(" [fake %s] push %s failed: %r (task=%s)"
  550. % (self.port, state, error, self.running_task))
  551. return None
  552. # --- plan 10 phase 1: the ask path ---
  553. def ask_now(self):
  554. """Synchronously asks the web for work (a phase-1 daemon's idle
  555. ask). A 200 assignment is accepted exactly like POST /start;
  556. returns (status, payload|None)."""
  557. token = self.token
  558. if token is None:
  559. raise SystemExit("fake daemon asked before receiving its token")
  560. status, payload = saddle_api("POST", "/api/saddle/next-task", token)
  561. with self.lock:
  562. self.asks.append({"status": status, "payload": payload})
  563. if status == 200:
  564. self.accept_assignment(payload)
  565. return status, payload
  566. def _trigger_ask(self, reason):
  567. """Schedules a delayed ask (the daemon woke / went idle-awake).
  568. ask_delay models a SLOW asker — a daemon still winding down its
  569. round when the wake lands: it honours the wake, but its ask
  570. arrives late (still inside the web's lost-wake guard window)."""
  571. def run():
  572. if self.state in ("working", "failing"):
  573. return # a running daemon does not ask
  574. if self.ask_delay > 0:
  575. time.sleep(self.ask_delay)
  576. for attempt in range(3):
  577. try:
  578. status, _ = self.ask_now()
  579. if status in (200, 204):
  580. return
  581. print(" (ask %s -> HTTP %s, attempt %d)" % (reason, status, attempt + 1))
  582. except Exception as error: # app restarting / blips: retry
  583. print(" (ask %s failed: %r, attempt %d)" % (reason, error, attempt + 1))
  584. time.sleep(1.0)
  585. def starter():
  586. time.sleep(FAKE_TRIGGER_S)
  587. run()
  588. thread = threading.Thread(target=starter, daemon=True)
  589. with self.lock:
  590. self.ask_threads.append(thread)
  591. thread.start()
  592. def settle_asks(self, timeout=15):
  593. """Joins every ask-trigger thread scheduled so far — the
  594. event-driven replacement for the fixed sleeps that waited for
  595. in-flight asks to land after triggers were frozen."""
  596. with self.lock:
  597. threads = [t for t in self.ask_threads if t.is_alive()]
  598. deadline = time.monotonic() + timeout
  599. for thread in threads:
  600. thread.join(timeout=max(0.1, deadline - time.monotonic()))
  601. with self.lock:
  602. self.ask_threads = [t for t in self.ask_threads if t.is_alive()]
  603. return all(not thread.is_alive() for thread in threads)
  604. def maybe_trigger_ask(self, reason, throttle=False):
  605. """Schedules an idle-awake ask. Protocol events (wake, abort,
  606. round end, park) ask singularly and immediately; only the
  607. /status-observation path throttles (a burst of probes must not
  608. hammer the ask endpoint)."""
  609. now = time.monotonic()
  610. if throttle and now - self.last_ask_trigger < 1.0:
  611. return
  612. self.last_ask_trigger = now
  613. self._trigger_ask(reason)
  614. def accept_assignment(self, payload):
  615. """A 200 next-task assignment: adopted exactly like POST /start."""
  616. self.start_payloads.append(payload)
  617. task = payload.get("task") or {}
  618. task_id = task.get("id")
  619. self.running_task = int(task_id or 0)
  620. self.running_title = task.get("title") or ""
  621. self.session_id = payload.get("session_id")
  622. # The assignment's answers resolve any block this daemon was
  623. # parked on (resume-carries-answer).
  624. self.pending_block = None
  625. count = self.start_counts.get(task_id, 0) + 1
  626. self.start_counts[task_id] = count
  627. if count > 1:
  628. # Crash-resume contract: re-pushing a task whose
  629. # workspace still exists restores it; the first
  630. # /status after the restore reports "resumed": true.
  631. self.resumed_pending = True
  632. # Plan 12: a goal-run assignment plays its scripted behaviour
  633. # instead of the plain done push (plan submission, parking,
  634. # question, completion, failure — consumed one per round).
  635. self.goal_behaviour = None
  636. if payload.get("kind") == "goal_run":
  637. self.goal_assignments.append(payload)
  638. self.goal_behaviour = self.goal_script.pop(0) if self.goal_script else ("suspend",)
  639. self.set_state("failing" if self.fail_next else "working")
  640. self.fail_next = False
  641. # The round's opening telemetry: the §7.2 event batch (turn 1:
  642. # lifecycle, turn text, tool call + result, usage) plus the
  643. # working state push. A new session restarts the per-session
  644. # seq counter; a scripted corpus supplements the batch.
  645. self._push_seq = 0
  646. opening = [
  647. {"kind": "lifecycle",
  648. "actor": "harness",
  649. "payload": {"action": "start", "text": "round started"}},
  650. {"kind": "turn_text",
  651. "payload": {"turn": 1, "text": "Starting the assigned task."}},
  652. {"kind": "tool_call",
  653. "payload": {"turn": 1, "tool": "run_command",
  654. "args": {"command": "echo hello"}}},
  655. {"kind": "tool_result",
  656. "actor": "harness",
  657. "payload": {"turn": 1, "stdout": "hello\n", "exit_code": 0}},
  658. {"kind": "usage",
  659. "actor": "harness",
  660. "payload": {"turn": 1, "input_tokens": 120, "output_tokens": 30}},
  661. ]
  662. if self.scripted_corpus is not None:
  663. opening = [dict(chunk) for chunk in self.scripted_corpus]
  664. self.push_events(opening)
  665. self.push_results("working")
  666. class Handler(BaseHTTPRequestHandler):
  667. daemon = None # set on the class before serving
  668. protocol_version = "HTTP/1.1"
  669. def log_message(self, fmt, *args):
  670. pass
  671. def maybe_hang(self, path):
  672. """True when this request should hang forever (never respond),
  673. consuming one unit of the path's hang budget."""
  674. for suffix, count in list(self.daemon.hang_next.items()):
  675. if count > 0 and path.startswith(suffix):
  676. self.daemon.hang_next[suffix] = count - 1
  677. return True
  678. return False
  679. def _send(self, status, obj):
  680. body = json.dumps(obj).encode()
  681. self.send_response(status)
  682. self.send_header("Content-Type", "application/json")
  683. self.send_header("Content-Length", str(len(body)))
  684. self.end_headers()
  685. self.wfile.write(body)
  686. def do_POST(self):
  687. if self.maybe_hang(self.path):
  688. time.sleep(600)
  689. return
  690. self.daemon.touch_activity()
  691. length = int(self.headers.get("Content-Length") or 0)
  692. raw = self.rfile.read(length).decode() if length else "{}"
  693. if self.path == "/register":
  694. # Plan 10: the web delivers the per-saddle token + its
  695. # own base URL; the daemon persists the token for its
  696. # calls home and reports its ssh key + version.
  697. if not self.daemon.serve_register:
  698. self._send(404, {"error": "no such route"})
  699. return
  700. try:
  701. payload = json.loads(raw)
  702. except ValueError:
  703. payload = {"raw": raw}
  704. self.daemon.register_log.append(payload)
  705. if payload.get("saddle_token"):
  706. self.daemon.token = payload["saddle_token"]
  707. self._send(200, {"ok": True,
  708. "ssh_public_key": self.daemon.ssh_public_key,
  709. "version": "0.1-fake"})
  710. if self.daemon.ask_on_register:
  711. self.daemon.maybe_trigger_ask("register")
  712. return
  713. if self.path == "/wake":
  714. # Plan 10: a capable task is ready; a sleeping daemon
  715. # asks for work (immediately — a wake is a direct
  716. # command, never throttled).
  717. self.daemon.wake_log.append(time.monotonic())
  718. self._send(200, {"ok": True})
  719. if self.daemon.ask_on_wake:
  720. self.daemon.maybe_trigger_ask("wake")
  721. return
  722. if self.path == "/answer":
  723. # Plan 11 (daemon Task A): parks FREE the daemon, so no
  724. # block ever waits in-process — the verdict travels in
  725. # the resuming allocation's resume_notice. Always 409,
  726. # exactly like the real daemon's contract.
  727. try:
  728. payload = json.loads(raw)
  729. except ValueError:
  730. self._send(400, {"error": "bad json"})
  731. return
  732. self.daemon.answer_log.append({
  733. "refused": True,
  734. "answer": payload.get("answer", "")})
  735. self._send(409, {"error": "no block is waiting for an answer — parks resume via allocation"})
  736. return
  737. if self.path == "/task-update":
  738. # Plan 10: cancel (abort machinery) and comment
  739. # (injected turn) — delivered directly to a RUNNING
  740. # daemon, no auth.
  741. try:
  742. payload = json.loads(raw)
  743. except ValueError:
  744. self._send(400, {"error": "bad json"})
  745. return
  746. kind = payload.get("kind")
  747. if kind == "cancel":
  748. if self.daemon.abort_failures > 0:
  749. self.daemon.abort_failures -= 1
  750. self._send(500, {"error": "cancel failed (simulated)"})
  751. return
  752. aborted = self.daemon.running_task
  753. self.daemon.set_state("idle")
  754. self.daemon.summary = ""
  755. self.daemon.running_task = 0
  756. self.daemon.session_id = None
  757. self.daemon.abort_log.append(aborted)
  758. self._send(200, {"ok": True, "aborted_task_id": aborted})
  759. # An aborted daemon returns to its idle loop: it asks.
  760. self.daemon.maybe_trigger_ask("aborted")
  761. elif kind == "comment":
  762. self.daemon.comment_log.append(payload)
  763. self._send(200, {"ok": True})
  764. else:
  765. self._send(400, {"error": "unknown task-update kind"})
  766. return
  767. self._send(404, {"error": "no such route"})
  768. self.close_connection = True
  769. def do_GET(self):
  770. if self.maybe_hang(self.path):
  771. time.sleep(600)
  772. return
  773. if self.path != "/status":
  774. # /status itself is not daemon activity: the liveness
  775. # signal must reflect loop rounds / command completions.
  776. self.daemon.touch_activity()
  777. if self.path == "/status":
  778. self.daemon.status_hits += 1
  779. response = {"state": self.daemon.state, "summary": self.daemon.summary,
  780. "uptime_seconds": int(time.monotonic() - self.daemon.started_mono),
  781. "last_activity_epoch": self.daemon.last_activity_epoch,
  782. "ssh_public_key": self.daemon.ssh_public_key}
  783. if getattr(self.daemon, "status_extra", None):
  784. response.update(self.daemon.status_extra)
  785. if self.daemon.resumed_pending:
  786. response["resumed"] = True
  787. self.daemon.resumed_pending = False
  788. # A parked/terminal daemon is idle-awake: a phase-1
  789. # daemon asks (and sleeps on 204). Throttled so status
  790. # poll bursts do not hammer the ask endpoint.
  791. if self.daemon.ask_on_idle_status and self.daemon.state in (
  792. "idle", "done", "failed", "suspended"):
  793. self.daemon.maybe_trigger_ask("idle-status", throttle=True)
  794. self._send(200, response)
  795. else:
  796. self._send(404, {"error": "no such route"})
  797. self.close_connection = True
  798. def run_lifecycle(self):
  799. """Applies the scripted lifecycle on a timer (like a real daemon
  800. whose task ends on its own): working heartbeats chunks (the
  801. flush timer's stand-in, keeping the staleness clock fed), works
  802. for FAKE_WORK_S, then pushes done/suspended; failing pushes
  803. failed after FAKE_FAIL_S — and a task END makes the idle-awake
  804. daemon ask again."""
  805. while True:
  806. time.sleep(0.1)
  807. if self.hold_state or self.silent:
  808. # hold_state freezes the script; silent models a daemon
  809. # mid-round with nothing to flush — its round has not
  810. # ended, so no terminal push fires while quiet.
  811. continue
  812. if self.state == "failing":
  813. if time.monotonic() - self.state_entered >= FAKE_FAIL_S:
  814. self.set_state("failed", "bash -n rejected the script (simulated)")
  815. self.push_results("failed",
  816. summary="bash -n rejected the script (simulated)")
  817. if self.ask_on_terminal:
  818. self.maybe_trigger_ask("terminal")
  819. elif self.state == "working":
  820. if time.monotonic() - self.state_entered >= FAKE_WORK_S:
  821. if self.goal_behaviour is not None:
  822. # A goal-agent round: play the scripted
  823. # behaviour (the results channel carries the
  824. # goal-context verbs).
  825. behaviour, self.goal_behaviour = self.goal_behaviour, None
  826. kind = behaviour[0]
  827. if kind == "plan":
  828. self.set_state("blocked")
  829. self.push_results("blocked", block={
  830. "type": "plan",
  831. "question": "Plan submitted for review",
  832. "body": behaviour[1]})
  833. if self.ask_on_idle_status:
  834. self.maybe_trigger_ask("parked")
  835. elif kind == "question":
  836. self.set_state("blocked")
  837. self.push_results("blocked", block={
  838. "type": "question",
  839. "question": behaviour[1],
  840. "options": list(behaviour[2])
  841. if len(behaviour) > 2 else None})
  842. if self.ask_on_idle_status:
  843. self.maybe_trigger_ask("parked")
  844. elif kind == "suspend":
  845. self.set_state("suspended")
  846. self.push_results("suspended")
  847. if self.ask_on_idle_status:
  848. self.maybe_trigger_ask("parked")
  849. elif kind == "fail":
  850. self.set_state("failed", behaviour[1])
  851. self.push_results("failed", summary=behaviour[1])
  852. if self.ask_on_terminal:
  853. self.maybe_trigger_ask("terminal")
  854. else: # "done": the completion report
  855. self.set_state("done", behaviour[1])
  856. self.push_results("done", summary=behaviour[1])
  857. if self.ask_on_terminal:
  858. self.maybe_trigger_ask("terminal")
  859. elif self.suspend_on_title and self.suspend_on_title == self.running_title:
  860. # `saddle suspend`: park until a fresh assignment
  861. # resumes the workspace (title-targeted one-shot,
  862. # so an interleaved dispatch cannot eat the flag).
  863. self.set_state("suspended")
  864. self.suspend_on_title = None
  865. self.push_results("suspended")
  866. # A parked daemon is idle-awake: it asks (and
  867. # sleeps on 204) so a later wake can reach it.
  868. if self.ask_on_idle_status:
  869. self.maybe_trigger_ask("parked")
  870. else:
  871. self.set_state("done", "fake daemon finished")
  872. self.push_results("done", summary="fake daemon finished")
  873. if self.ask_on_terminal:
  874. self.maybe_trigger_ask("terminal")
  875. elif time.monotonic() - getattr(self, "last_heartbeat", 0) >= FAKE_HEARTBEAT_S:
  876. # The flush timer: output keeps flowing, so chunks
  877. # keep arriving (the staleness window never opens on
  878. # a healthy runner).
  879. self.last_heartbeat = time.monotonic()
  880. self.push_chunks(["working-heartbeat\r\n"])
  881. def serve(self, port=None):
  882. """Binds the daemon's HTTP server. A requested port that is
  883. already taken (free_port() hands out recyclable ports — two
  884. calls can collide) falls back to an OS-assigned one instead of
  885. silently dying and impersonating whatever owns that port."""
  886. if port is None:
  887. port = DAEMON_PORT
  888. handler = type("BoundHandler", (FakeSaddle.Handler,), {"daemon": self})
  889. self.server = None
  890. try:
  891. self.server = ThreadingHTTPServer(("127.0.0.1", port), handler)
  892. except OSError:
  893. print("(fake daemon: port %d taken, falling back)" % port)
  894. self.server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
  895. self.port = self.server.server_address[1]
  896. threading.Thread(target=self.server.serve_forever, daemon=True).start()
  897. threading.Thread(target=self.run_lifecycle, daemon=True).start()
  898. return self.server
  899. def kill(self):
  900. """The daemon dies: it stops listening (connections refused) AND
  901. stops calling home — no pushes, no asks (a dead process has no
  902. outbound anything; in-flight handler threads may linger but the
  903. wire contract's traffic is one-directional now)."""
  904. self.dead = True
  905. if getattr(self, "server", None) is not None:
  906. self.server.shutdown()
  907. self.server.server_close()
  908. self.server = None
  909. def start_app():
  910. config = json.load(open(os.path.join(REPO, "web-config.json")))
  911. config["saddle_callback_base_url"] = WEB
  912. with open(os.path.join(WORK, "web-config.json"), "w") as handle:
  913. json.dump(config, handle)
  914. env = dict(os.environ)
  915. env.update({
  916. "SPRY_DB_PATH": DB_PATH,
  917. "SPRY_SEED_ADMIN_USERNAME": "admin",
  918. "SPRY_SEED_ADMIN_PASSWORD": "adminpass123",
  919. "SADDLE_LLM_BASE_URL": "http://127.0.0.1:%d" % DAEMON_PORT,
  920. "SADDLE_PROJECTS_ROOT": os.path.join(WORK, "workspace"),
  921. "SADDLE_HTTP_TIMEOUT_S": "2",
  922. "SADDLE_LOST_WAKE_S": "2",
  923. "SADDLE_STALE_S": "3",
  924. "SADDLE_DISPATCH_TICK_S": "1",
  925. # Plan 12: the goal-agent resume coalescing window shrinks to
  926. # one second so the event-driven resume tests settle quickly.
  927. "SADDLE_GOAL_RESUME_S": os.environ.get("SADDLE_GOAL_RESUME_S", "1"),
  928. # Never inherit a caller-poisoned LD_LIBRARY_PATH (e.g. one that
  929. # resolves the ancient /lib64 copies): empty makes the loader use
  930. # the binary's RUNPATH, which is the dev stack it was built
  931. # against.
  932. "LD_LIBRARY_PATH": "",
  933. })
  934. log_previous = os.path.join(WORK, "app.log.1")
  935. if os.path.exists(os.path.join(WORK, "app.log")):
  936. shutil.move(os.path.join(WORK, "app.log"), log_previous)
  937. log = open(os.path.join(WORK, "app.log"), "w")
  938. command = [APP, str(APP_PORT)]
  939. if os.environ.get("WEBSTACK_GDB"):
  940. # Debugging aid: run the app under gdb; a crash backtrace lands in
  941. # app.log. WEBSTACK_GDB=1 meson test ... to enable.
  942. command = ["gdb", "-batch", "-quiet",
  943. "-ex", "handle SIGPIPE nostop noprint pass",
  944. "-ex", "run", "-ex", "bt", "--args", APP, str(APP_PORT)]
  945. process = subprocess.Popen(command, cwd=WORK, env=env,
  946. stdout=log, stderr=subprocess.STDOUT)
  947. # The ready probe must require OUR process alive: a free_port()
  948. # TOCTOU can hand this port to another shard's app — ours then dies
  949. # at bind (MHD error()) while the probe happily answers from the
  950. # intruder (same admin seed), and every check would silently drive
  951. # the WRONG app. poll() != None with a serving port is exactly that
  952. # shape: take the exit branch, the start_bundle retry re-ports.
  953. outcome = wait_for(lambda: (app_ready() and process.poll() is None and "ready")
  954. or (process.poll() is not None and "app-exited-%d" % process.poll())
  955. or False, timeout=30, what="app ready")
  956. if outcome is None:
  957. raise SystemExit("app did not come up; see %s/app.log" % WORK)
  958. if str(outcome).startswith("app-exited-"):
  959. raise SystemExit("app exited during startup (%s); see %s/app.log"
  960. % outcome, WORK)
  961. return process
  962. def app_ready():
  963. try:
  964. status, _ = http("GET", "/login", timeout=3)
  965. return status == 200
  966. except (urllib.error.URLError, OSError):
  967. return False
  968. def dump_app_stacks(pid):
  969. """Best-effort thread backtrace of the (possibly wedged) app."""
  970. try:
  971. fds = os.listdir("/proc/%d/fd" % pid)
  972. print("(app open fds at dump: %d)" % len(fds))
  973. kinds = {}
  974. for fd in fds[:1200]:
  975. try:
  976. target = os.readlink("/proc/%d/fd/%s" % (pid, fd))
  977. except OSError:
  978. continue
  979. key = target.split(":", 1)[0] if ":" in target else target
  980. kinds[key] = kinds.get(key, 0) + 1
  981. print("(fd kinds: %s)" % sorted(kinds.items(), key=lambda kv: -kv[1])[:6])
  982. except OSError:
  983. pass
  984. for command in (["eu-stack", "-p", str(pid)],
  985. ["gdb", "-batch", "-quiet", "-p", str(pid),
  986. "-ex", "thread apply all bt"]):
  987. try:
  988. out = subprocess.run(command, capture_output=True, timeout=60)
  989. text = out.stdout.decode(errors="replace") + out.stderr.decode(errors="replace")
  990. if text.strip():
  991. print("(app stacks via %s)\n%s" % (command[0], text[:12000]))
  992. return
  993. except (OSError, subprocess.SubprocessError):
  994. continue
  995. # =============================================================================
  996. # Fake push service + Web Push protocol helpers (plan 11 task E)
  997. # =============================================================================
  998. def b64url(raw):
  999. return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
  1000. def b64url_dec(text):
  1001. return base64.urlsafe_b64decode(text + "=" * ((4 - len(text) % 4) % 4))
  1002. class FakePushService:
  1003. """In-process Web Push endpoint server: every subscription the tests
  1004. register points at a path here (a distinct "browser endpoint").
  1005. Responses are scriptable per path — a fixed status (the 410-prune
  1006. fixture) or N transient 500s (the retry-next-tick fixture)."""
  1007. def __init__(self):
  1008. self.requests = [] # [{"path", "headers", "body", "at"}]
  1009. self.fail_next = {} # path -> remaining 500s
  1010. self.status_for = {} # path -> fixed status
  1011. self.lock = threading.Lock()
  1012. self.port = None
  1013. self.server = None
  1014. def serve(self):
  1015. service = self
  1016. class Handler(BaseHTTPRequestHandler):
  1017. protocol_version = "HTTP/1.1"
  1018. def log_message(self, fmt, *args):
  1019. pass
  1020. def do_POST(self):
  1021. length = int(self.headers.get("Content-Length") or 0)
  1022. body = self.rfile.read(length)
  1023. status = 201
  1024. if self.path in service.status_for:
  1025. status = service.status_for[self.path]
  1026. elif service.fail_next.get(self.path, 0) > 0:
  1027. service.fail_next[self.path] -= 1
  1028. status = 500
  1029. with service.lock:
  1030. service.requests.append({
  1031. "path": self.path,
  1032. "headers": {key.lower(): value
  1033. for key, value in self.headers.items()},
  1034. "body": body,
  1035. "at": time.monotonic(),
  1036. })
  1037. payload = b"{}"
  1038. self.send_response(status)
  1039. self.send_header("Content-Type", "application/json")
  1040. self.send_header("Content-Length", str(len(payload)))
  1041. self.end_headers()
  1042. self.wfile.write(payload)
  1043. self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
  1044. self.port = self.server.server_address[1]
  1045. threading.Thread(target=self.server.serve_forever, daemon=True).start()
  1046. return self.server
  1047. def url(self, path):
  1048. return "http://127.0.0.1:%d%s" % (self.port, path)
  1049. def hits(self, prefix):
  1050. with self.lock:
  1051. return [request for request in self.requests
  1052. if request["path"].startswith(prefix)]
  1053. def decrypt_webpush(request, client_private_key, client_public, auth_secret):
  1054. """RFC 8291 decryption of one captured push: returns
  1055. (record_size, payload dict) — the payload builder's exact output."""
  1056. body = request["body"]
  1057. salt = body[:16]
  1058. record_size = int.from_bytes(body[16:20], "big")
  1059. key_id_len = body[20]
  1060. eph_public = body[21:21 + key_id_len]
  1061. ciphertext = body[21 + key_id_len:]
  1062. eph_point = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(),
  1063. eph_public)
  1064. shared = client_private_key.exchange(ec.ECDH(), eph_point)
  1065. info = b"WebPush: info\x00" + eph_public + client_public
  1066. cek = HKDF(algorithm=hashes.SHA256(), length=16, salt=salt,
  1067. info=info).derive(shared + auth_secret)
  1068. nonce = HKDF(algorithm=hashes.SHA256(), length=12, salt=salt,
  1069. info=info).derive(shared + auth_secret)
  1070. plaintext = AESGCM(cek).decrypt(nonce, ciphertext, None)
  1071. return record_size, json.loads(plaintext[:-1]) # strip the 0x02 delimiter
  1072. def verify_vapid(request, vapid_public, vapid_private):
  1073. """Verifies the ES256 VAPID JWT on one captured push; returns its
  1074. claims dict (aud/exp/sub) — raises on a bad signature."""
  1075. header = request["headers"].get("authorization", "")
  1076. assert header.startswith("vapid t="), "no vapid authorization header"
  1077. token_part = header[len("vapid t="):].split(",")[0]
  1078. sent_key = header.split("k=")[1]
  1079. head_b64, claims_b64, sig_b64 = token_part.split(".")
  1080. signature = b64url_dec(sig_b64)
  1081. key = ec.derive_private_key(
  1082. int.from_bytes(b64url_dec(vapid_private), "big"), ec.SECP256R1())
  1083. key.public_key().verify(
  1084. encode_dss_signature(int.from_bytes(signature[:32], "big"),
  1085. int.from_bytes(signature[32:], "big")),
  1086. (head_b64 + "." + claims_b64).encode(),
  1087. ec.ECDSA(hashes.SHA256()))
  1088. claims = json.loads(b64url_dec(claims_b64))
  1089. assert sent_key == vapid_public, "the k= key is not the app's VAPID key"
  1090. return claims
  1091. def action_notify(result):
  1092. """The message of the first notify directive an action returned."""
  1093. for directive in result:
  1094. if directive.get("type") == "notify":
  1095. return directive.get("message", "")
  1096. return None
  1097. # =============================================================================
  1098. # Shard orchestration
  1099. # =============================================================================
  1100. class Ctx:
  1101. """Per-bundle shared fixtures: the app process, the admin auth slot
  1102. and the primary fake saddle (registered + token delivered)."""
  1103. def start_bundle(name):
  1104. """Boots one shard's environment: scratch dir, database, ports, the
  1105. primary fake daemon and the app, then the shared fixtures every
  1106. bundle builds on (the demo project + the registered fake saddle).
  1107. Scenario groups inside the bundle share this app+daemon instance
  1108. and sequence their state as DB rows, never process restarts."""
  1109. global APP_PORT, WEB, DAEMON_PORT
  1110. bundle_env(name)
  1111. fake = FakeSaddle()
  1112. fake.serve()
  1113. DAEMON_PORT = fake.port # the actually-bound port (fallback-safe)
  1114. # A rare framework-level crash (stack corruption in Statum slot
  1115. # signing during the FIRST login — shared-library codegen bug, moved
  1116. # twice already) kills the app before any test runs; a clean restart
  1117. # (with fresh ports) sidesteps it. Only tolerated while nothing has
  1118. # been checked yet.
  1119. auth = None
  1120. app = None
  1121. for attempt in range(3):
  1122. APP_PORT = free_port()
  1123. WEB = "http://127.0.0.1:%d" % APP_PORT
  1124. if os.path.exists(WORK):
  1125. shutil.rmtree(WORK)
  1126. os.makedirs(os.path.join(WORK, "workspace"))
  1127. try:
  1128. app = start_app()
  1129. auth = login("admin", "adminpass123")
  1130. break
  1131. except (SystemExit, OSError, urllib.error.URLError):
  1132. if passes > 0:
  1133. raise
  1134. if app is not None and app.poll() is None:
  1135. app.terminate()
  1136. try:
  1137. app.wait(timeout=5)
  1138. except subprocess.TimeoutExpired:
  1139. app.kill()
  1140. app = None
  1141. print("(app died before login; restarting cleanly, attempt %d)" % (attempt + 1))
  1142. if app is None or auth is None:
  1143. raise SystemExit("app never came up; see %s/app.log" % WORK)
  1144. state = slot_public(auth, "/projects", "projects")
  1145. act(auth, state["create"], {
  1146. "name": "demo",
  1147. "git_url": "https://example.com/demo.git",
  1148. "default_branch": "main",
  1149. })
  1150. saddles_state = slot_public(auth, "/saddles", "saddles")
  1151. act(auth, saddles_state["register"], {"name": "fake-saddle",
  1152. "host": "127.0.0.1:%d" % fake.port})
  1153. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1154. if s["name"] == "fake-saddle"]
  1155. if wait_for(lambda: len(fake.register_log) > 0 or False,
  1156. timeout=15, what="/register delivery") is None:
  1157. raise SystemExit("fake saddle never received /register")
  1158. ctx = Ctx()
  1159. ctx.name = name
  1160. ctx.app = app
  1161. ctx.auth = auth
  1162. ctx.fake = fake
  1163. ctx.fake_id = int(registered[0]["id"])
  1164. ctx.fake_token = registered[0]["token"]
  1165. return ctx
  1166. BUNDLES_ORDER = ("pages", "dispatch", "subtasks", "lineage",
  1167. "allocation", "lifecycle", "answers", "push", "goals",
  1168. "replay", "goalui", "forcewake", "users")
  1169. def run_bundle(name):
  1170. """Runs one shard to completion; returns a failure count."""
  1171. global CTX
  1172. started = time.monotonic()
  1173. ctx = start_bundle(name)
  1174. CTX = ctx
  1175. import importlib
  1176. bundle = importlib.import_module("bundles." + name)
  1177. # Runtime globals the star-import captured at module load can be
  1178. # stale (the sequential debug path reuses modules across shards) —
  1179. # re-point them at this shard's environment. The shared helpers
  1180. # read them from harness globals already.
  1181. for runtime_name in ("WORK", "DB_PATH", "APP_PORT", "DAEMON_PORT", "WEB"):
  1182. setattr(bundle, runtime_name, globals()[runtime_name])
  1183. runner = bundle.run
  1184. try:
  1185. runner(ctx)
  1186. finally:
  1187. # Exit-code diagnostic: distinguishes a crashed app (negative
  1188. # returncode, e.g. -11 SIGSEGV) from a clean shutdown. When
  1189. # tearing down mid-exception, also capture the still-alive
  1190. # app's stacks before killing it (a wedged-but-alive server
  1191. # otherwise leaves no evidence).
  1192. print("(app returncode at teardown: %s)" % ctx.app.poll())
  1193. if ctx.app.poll() is None and sys.exc_info()[0] is not None:
  1194. dump_app_stacks(ctx.app.pid)
  1195. ctx.fake.kill()
  1196. try:
  1197. ctx.app.terminate()
  1198. try:
  1199. ctx.app.wait(timeout=5)
  1200. except subprocess.TimeoutExpired:
  1201. ctx.app.kill()
  1202. check(ctx.app.poll() in (0, -15),
  1203. "bundle %s app shut down cleanly (exit %s)"
  1204. % (name, ctx.app.poll()))
  1205. except OSError:
  1206. pass
  1207. print("%d passed, %d failed" % (passes, failures))
  1208. print("[bundle %s] %.1fs" % (name, time.monotonic() - started))
  1209. return failures
  1210. def run_all_parallel():
  1211. """The default meson entry: one subprocess per bundle (each with its
  1212. own app, daemons and database), verdicts aggregated into one exit
  1213. code and one combined check-count summary."""
  1214. base = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  1215. log_dir = os.path.join(os.path.dirname(base) or "/tmp/kilo",
  1216. "webstack-shards")
  1217. os.makedirs(log_dir, exist_ok=True)
  1218. procs = {}
  1219. started = time.monotonic()
  1220. for name in BUNDLES_ORDER:
  1221. out_path = os.path.join(log_dir, "bundle-%s.log" % name)
  1222. handle = open(out_path, "w")
  1223. procs[name] = (subprocess.Popen(
  1224. [sys.executable, "-u",
  1225. os.path.join(os.path.dirname(os.path.abspath(__file__)),
  1226. "web_stack_test.py"), APP, "--bundle", name],
  1227. stdout=handle, stderr=subprocess.STDOUT), handle, out_path)
  1228. total_pass = total_fail = 0
  1229. broken = []
  1230. for name, (proc, handle, out_path) in procs.items():
  1231. try:
  1232. proc.wait(timeout=SHARD_TIMEOUT_S)
  1233. except subprocess.TimeoutExpired:
  1234. proc.kill()
  1235. proc.wait()
  1236. handle.close()
  1237. text = open(out_path).read()
  1238. match = re.search(r"(\d+) passed, (\d+) failed", text)
  1239. took = re.search(r"\[bundle %s\] ([0-9.]+)s" % name, text)
  1240. bundle_pass = int(match.group(1)) if match else 0
  1241. bundle_fail = int(match.group(2)) if match else -1
  1242. total_pass += max(bundle_pass, 0)
  1243. total_fail += max(bundle_fail, 0)
  1244. status = "ok"
  1245. if proc.returncode != 0 or bundle_fail != 0 or match is None:
  1246. status = "BROKEN (exit %s)" % proc.returncode
  1247. broken.append(name)
  1248. print("[shard %-10s] %6ss %3d passed %3d failed %s"
  1249. % (name, took.group(1) if took else "?",
  1250. bundle_pass, bundle_fail, status))
  1251. if status != "ok":
  1252. tail = "\n".join(text.rstrip().split("\n")[-60:])
  1253. print("--- web-stack/%s tail (full log: %s) ---" % (name, out_path))
  1254. print(tail)
  1255. print("--- end web-stack/%s tail ---" % name)
  1256. print("shards wall: %.1fs (logs under %s)" % (time.monotonic() - started, log_dir))
  1257. print("ALL SHARDS: %d passed, %d failed%s"
  1258. % (total_pass, total_fail,
  1259. "" if not broken else " BROKEN: " + ", ".join(broken)))
  1260. return 1 if broken or total_fail else 0
  1261. def main():
  1262. if not os.path.exists(APP):
  1263. raise SystemExit("app binary not found at %s (build first)" % APP)
  1264. argv = sys.argv[2:]
  1265. if "--bundle" in argv:
  1266. sys.exit(1 if run_bundle(argv[argv.index("--bundle") + 1]) else 0)
  1267. if os.environ.get("WEBSTACK_SEQUENTIAL"):
  1268. # Debug path: every bundle in-process, one after another.
  1269. for name in BUNDLES_ORDER:
  1270. if run_bundle(name):
  1271. return 1
  1272. return 0
  1273. return run_all_parallel()
  1274. if __name__ == "__main__":
  1275. sys.exit(main())